[Pkg-cmake-commits] [cmake] 01/07: New upstream version 3.8.0

Felix Geyer fgeyer at moszumanska.debian.org
Sat Apr 15 11:20:38 UTC 2017


This is an automated email from the git hooks/post-receive script.

fgeyer pushed a commit to branch experimental
in repository cmake.

commit b4903bcd04384cbe059c2800801218ec807e096b
Author: Felix Geyer <fgeyer at debian.org>
Date:   Fri Apr 14 19:02:05 2017 +0200

    New upstream version 3.8.0
---
 .gitattributes                                     |   24 +-
 .hooks-config                                      |   10 +
 .hooks-config.bash                                 |    9 -
 Auxiliary/CMakeLists.txt                           |    2 +-
 Auxiliary/vim/syntax/cmake.vim                     |    6 +-
 CMakeCPack.cmake                                   |  392 +-
 CMakeCPackOptions.cmake.in                         |   60 +-
 CMakeLists.txt                                     |  115 +-
 CTestCustom.cmake.in                               |    6 +-
 Copyright.txt                                      |    4 +-
 Help/command/add_custom_command.rst                |   11 +-
 Help/command/add_custom_target.rst                 |    9 +
 Help/command/add_library.rst                       |    2 +-
 Help/command/ctest_memcheck.rst                    |    8 +-
 Help/command/ctest_submit.rst                      |    8 +-
 Help/command/execute_process.rst                   |   27 +-
 Help/command/file.rst                              |   18 +-
 Help/command/if.rst                                |    6 +-
 Help/command/install.rst                           |    6 +-
 Help/command/source_group.rst                      |   18 +-
 Help/command/string.rst                            |   34 +-
 Help/command/target_link_libraries.rst             |    5 +
 Help/command/try_compile.rst                       |   36 +-
 Help/generator/CodeBlocks.rst                      |    3 +
 Help/generator/VS_TOOLSET_HOST_ARCH.txt            |   10 +
 Help/generator/Visual Studio 10 2010.rst           |    7 +
 Help/generator/Visual Studio 11 2012.rst           |    7 +
 Help/generator/Visual Studio 12 2013.rst           |    9 +
 Help/generator/Visual Studio 14 2015.rst           |    9 +
 Help/generator/Visual Studio 15 2017.rst           |    9 +
 Help/generator/Xcode.rst                           |    7 +
 Help/manual/OPTIONS_BUILD.txt                      |   11 +-
 Help/manual/cmake-buildsystem.7.rst                |    2 +
 Help/manual/cmake-compile-features.7.rst           |   45 +-
 Help/manual/cmake-developer.7.rst                  |    6 +-
 Help/manual/cmake-generator-expressions.7.rst      |    2 +
 Help/manual/cmake-language.7.rst                   |   10 +-
 Help/manual/cmake-modules.7.rst                    |    2 +
 Help/manual/cmake-packages.7.rst                   |    4 +-
 Help/manual/cmake-policies.7.rst                   |    8 +
 Help/manual/cmake-properties.7.rst                 |   24 +
 Help/manual/cmake-qt.7.rst                         |   32 +-
 Help/manual/cmake-variables.7.rst                  |   10 +
 Help/manual/cmake.1.rst                            |    6 +-
 Help/module/CPackIFWConfigureFile.rst              |    1 +
 Help/module/CSharpUtilities.rst                    |    1 +
 Help/policy/CMP0067.rst                            |   37 +
 Help/prop_gbl/AUTOGEN_TARGETS_FOLDER.rst           |    2 +-
 Help/prop_gbl/AUTOMOC_TARGETS_FOLDER.rst           |    2 +-
 Help/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.rst         |   12 +
 Help/prop_gbl/CMAKE_C_KNOWN_FEATURES.rst           |    9 +
 .../XCODE_EMIT_EFFECTIVE_PLATFORM_NAME.rst         |   24 +
 Help/prop_sf/COMPILE_FLAGS.rst                     |    7 +
 Help/prop_sf/SKIP_AUTOGEN.rst                      |    8 +
 Help/prop_sf/SKIP_AUTOMOC.rst                      |    6 +
 Help/prop_sf/SKIP_AUTORCC.rst                      |    6 +
 Help/prop_sf/SKIP_AUTOUIC.rst                      |    6 +
 Help/prop_sf/VS_COPY_TO_OUT_DIR.rst                |    6 +
 Help/prop_sf/VS_CSHARP_tagname.rst                 |   19 +
 Help/prop_sf/VS_INCLUDE_IN_VSIX.rst                |    6 +
 Help/prop_sf/VS_RESOURCE_GENERATOR.rst             |    8 +
 Help/prop_test/TIMEOUT_AFTER_MATCH.rst             |    4 +-
 Help/prop_tgt/AUTOGEN_TARGET_DEPENDS.rst           |    8 +-
 Help/prop_tgt/AUTOMOC.rst                          |   16 +-
 Help/prop_tgt/AUTORCC.rst                          |    3 +
 Help/prop_tgt/AUTOUIC.rst                          |    3 +
 Help/prop_tgt/BUILD_RPATH.rst                      |   10 +
 Help/prop_tgt/CROSSCOMPILING_EMULATOR.rst          |    4 +
 Help/prop_tgt/CUDA_EXTENSIONS.rst                  |   17 +
 Help/prop_tgt/CUDA_SEPARABLE_COMPILATION.rst       |   13 +
 Help/prop_tgt/CUDA_STANDARD.rst                    |   32 +
 Help/prop_tgt/CUDA_STANDARD_REQUIRED.rst           |   18 +
 Help/prop_tgt/CXX_STANDARD.rst                     |    2 +-
 Help/prop_tgt/FRAMEWORK.rst                        |    4 +-
 Help/prop_tgt/IMPORTED_LIBNAME.rst                 |   23 +
 Help/prop_tgt/IMPORTED_LIBNAME_CONFIG.rst          |    7 +
 Help/prop_tgt/LANG_CPPLINT.rst                     |   13 +
 Help/prop_tgt/MANUALLY_ADDED_DEPENDENCIES.rst      |    8 +
 Help/prop_tgt/MAP_IMPORTED_CONFIG_CONFIG.rst       |   22 +-
 Help/prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY.rst    |    6 +
 Help/prop_tgt/VS_DOTNET_REFERENCES_COPY_LOCAL.rst  |    7 +
 Help/prop_tgt/VS_DOTNET_REFERENCE_refname.rst      |   12 +
 Help/prop_tgt/VS_USER_PROPS.rst                    |   12 +
 Help/prop_tgt/XCODE_EXPLICIT_FILE_TYPE.rst         |    8 +
 Help/prop_tgt/XCODE_PRODUCT_TYPE.rst               |    8 +
 Help/release/3.8.rst                               |  417 ++
 Help/release/index.rst                             |    1 +
 Help/variable/CMAKE_BUILD_RPATH.rst                |   10 +
 Help/variable/CMAKE_CL_64.rst                      |    5 +-
 Help/variable/CMAKE_CUDA_EXTENSIONS.rst            |   11 +
 Help/variable/CMAKE_CUDA_STANDARD.rst              |   11 +
 Help/variable/CMAKE_CUDA_STANDARD_REQUIRED.rst     |   11 +
 .../CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES.rst     |    7 +
 Help/variable/CMAKE_DL_LIBS.rst                    |    2 +-
 Help/variable/CMAKE_LANG_COMPILER_ID.rst           |    1 +
 Help/variable/CMAKE_LANG_CPPLINT.rst               |    6 +
 Help/variable/CMAKE_POLICY_WARNING_CMPNNNN.rst     |    2 +
 .../variable/CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS.rst |   25 +
 .../CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE.rst    |    7 +
 .../CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD.rst  |    8 +
 ...CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE.rst |   10 +
 Help/variable/CTEST_MEMORYCHECK_TYPE.rst           |    2 +-
 Help/variable/MSVC.rst                             |    2 +
 Help/variable/MSVC10.rst                           |    2 +
 Help/variable/MSVC11.rst                           |    2 +
 Help/variable/MSVC12.rst                           |    2 +
 Help/variable/MSVC14.rst                           |    6 +-
 Help/variable/MSVC60.rst                           |    2 +
 Help/variable/MSVC70.rst                           |    2 +
 Help/variable/MSVC71.rst                           |    2 +
 Help/variable/MSVC80.rst                           |    2 +
 Help/variable/MSVC90.rst                           |    2 +
 Help/variable/MSVC_VERSION.rst                     |    3 +-
 Modules/AndroidTestUtilities.cmake                 |   17 +-
 .../AndroidTestUtilities/PushToAndroidDevice.cmake |    6 +-
 Modules/AutogenInfo.cmake.in                       |   18 +-
 Modules/BundleUtilities.cmake                      |   58 +-
 Modules/CMakeAddFortranSubdirectory.cmake          |    1 -
 Modules/CMakeCSharpCompiler.cmake.in               |    9 +
 Modules/CMakeCSharpCompilerId.cs.in                |   63 +
 Modules/CMakeCSharpInformation.cmake               |  119 +
 Modules/CMakeCUDACompiler.cmake.in                 |   27 +
 Modules/CMakeCUDACompilerABI.cu                    |   16 +
 Modules/CMakeCUDACompilerId.cu.in                  |   50 +
 Modules/CMakeCUDAInformation.cmake                 |  206 +
 Modules/CMakeCXXCompiler.cmake.in                  |    1 +
 Modules/CMakeCXXCompilerId.cpp.in                  |    4 +-
 Modules/CMakeCompilerIdDetection.cmake             |    9 +-
 Modules/CMakeDetermineASMCompiler.cmake            |    8 +-
 Modules/CMakeDetermineCSharpCompiler.cmake         |   43 +
 Modules/CMakeDetermineCUDACompiler.cmake           |  188 +
 Modules/CMakeDetermineCompileFeatures.cmake        |    6 +
 Modules/CMakeDetermineCompilerId.cmake             |   30 +-
 Modules/CMakeExpandImportedTargets.cmake           |    3 -
 Modules/CMakeFindBinUtils.cmake                    |    1 +
 Modules/CMakeGraphVizOptions.cmake                 |   13 +-
 Modules/CMakePackageConfigHelpers.cmake            |    9 +-
 Modules/CMakeParseImplicitLinkInfo.cmake           |   25 +-
 Modules/CMakePrintHelpers.cmake                    |    2 -
 Modules/CMakeRCInformation.cmake                   |   21 +-
 Modules/CMakeTestCSharpCompiler.cmake              |   64 +
 Modules/CMakeTestCUDACompiler.cmake                |   76 +
 Modules/CPack.STGZ_Header.sh.in                    |    5 +-
 Modules/CPack.cmake                                |    4 +-
 Modules/CPackDeb.cmake                             |   15 +-
 Modules/CPackIFW.cmake                             |  179 +-
 Modules/CPackIFWConfigureFile.cmake                |   65 +
 Modules/CPackProductBuild.cmake                    |   20 +
 Modules/CPackRPM.cmake                             |  379 +-
 Modules/CSharpUtilities.cmake                      |  306 ++
 Modules/CTestCoverageCollectGCOV.cmake             |    1 -
 Modules/CTestUseLaunchers.cmake                    |    4 +-
 Modules/CheckFunctionExists.c                      |    2 +-
 Modules/CheckFunctionExists.cmake                  |   30 +-
 Modules/Compiler/AppleClang-C.cmake                |   12 +-
 Modules/Compiler/AppleClang-CXX.cmake              |   21 +-
 Modules/Compiler/Clang-C.cmake                     |   12 +-
 Modules/Compiler/Clang-CXX-FeatureTests.cmake      |    3 +-
 Modules/Compiler/Clang-CXX.cmake                   |   26 +-
 ...ompiler.cmake => GNU-C-DetermineCompiler.cmake} |    0
 Modules/Compiler/GNU-C-FeatureTests.cmake          |   10 +-
 Modules/Compiler/GNU-C.cmake                       |   23 +-
 Modules/Compiler/GNU-CXX-DetermineCompiler.cmake   |   15 +
 Modules/Compiler/GNU-CXX.cmake                     |   24 +-
 Modules/Compiler/Intel-C-FeatureTests.cmake        |    9 +-
 Modules/Compiler/Intel-C.cmake                     |   28 +-
 Modules/Compiler/Intel-CXX-FeatureTests.cmake      |   71 +-
 Modules/Compiler/Intel-CXX.cmake                   |   51 +-
 Modules/Compiler/MSVC-CXX.cmake                    |   10 +-
 Modules/Compiler/NVIDIA-CUDA.cmake                 |   27 +
 Modules/Compiler/NVIDIA-DetermineCompiler.cmake    |   17 +
 Modules/Compiler/PGI-Fortran.cmake                 |    3 +
 Modules/Compiler/SDCC-C-DetermineCompiler.cmake    |   10 +-
 Modules/Compiler/SunPro-CXX.cmake                  |   12 +-
 Modules/CompilerId/VS-10.csproj.in                 |   55 +
 Modules/CompilerId/VS-10.vcxproj.in                |    3 +
 Modules/ExternalData.cmake                         |  119 +-
 Modules/ExternalProject.cmake                      |  229 +-
 Modules/FeatureSummary.cmake                       |  345 +-
 Modules/FindALSA.cmake                             |    2 -
 Modules/FindASPELL.cmake                           |    2 -
 Modules/FindAVIFile.cmake                          |    2 -
 Modules/FindArmadillo.cmake                        |    7 -
 Modules/FindBISON.cmake                            |    4 -
 Modules/FindBLAS.cmake                             |   33 +-
 Modules/FindBZip2.cmake                            |    2 -
 Modules/FindBoost.cmake                            |   57 +-
 Modules/FindBullet.cmake                           |    2 -
 Modules/FindCUDA/select_compute_arch.cmake         |   21 +-
 Modules/FindCURL.cmake                             |    2 -
 Modules/FindCoin3D.cmake                           |    4 -
 Modules/FindCurses.cmake                           |    2 -
 Modules/FindDart.cmake                             |    2 -
 Modules/FindDevIL.cmake                            |    4 +-
 Modules/FindEXPAT.cmake                            |    2 -
 Modules/FindFLEX.cmake                             |    4 -
 Modules/FindFreetype.cmake                         |    3 -
 Modules/FindGIF.cmake                              |    2 -
 Modules/FindGSL.cmake                              |    3 +-
 Modules/FindGTK2.cmake                             |   99 +-
 Modules/FindGTest.cmake                            |   14 +-
 Modules/FindGettext.cmake                          |    2 -
 Modules/FindGit.cmake                              |   21 +-
 Modules/FindGnuTLS.cmake                           |    3 -
 Modules/FindGnuplot.cmake                          |    3 -
 Modules/FindHDF5.cmake                             |  205 +-
 Modules/FindHSPELL.cmake                           |    3 -
 Modules/FindHg.cmake                               |    2 -
 Modules/FindICU.cmake                              |    1 +
 Modules/FindIcotool.cmake                          |    2 -
 Modules/FindJNI.cmake                              |    5 +
 Modules/FindJPEG.cmake                             |    2 -
 Modules/FindJasper.cmake                           |    2 -
 Modules/FindJava.cmake                             |    9 +-
 Modules/FindLAPACK.cmake                           |   11 +-
 Modules/FindLATEX.cmake                            |    1 -
 Modules/FindLTTngUST.cmake                         |    2 -
 Modules/FindLibArchive.cmake                       |    8 +-
 Modules/FindLibXml2.cmake                          |    2 -
 Modules/FindLua.cmake                              |   23 +-
 Modules/FindMPEG.cmake                             |    2 -
 Modules/FindMPEG2.cmake                            |    3 -
 Modules/FindMPI.cmake                              |   18 +-
 Modules/FindMotif.cmake                            |    3 -
 Modules/FindOpenAL.cmake                           |    2 -
 Modules/FindOpenGL.cmake                           |   61 +-
 Modules/FindOpenSSL.cmake                          |   13 +-
 Modules/FindOpenSceneGraph.cmake                   |    1 -
 Modules/FindPNG.cmake                              |    4 +-
 Modules/FindPackageHandleStandardArgs.cmake        |    1 -
 Modules/FindPerl.cmake                             |    2 -
 Modules/FindPerlLibs.cmake                         |    2 -
 Modules/FindPhysFS.cmake                           |    3 -
 Modules/FindPkgConfig.cmake                        |    8 +-
 Modules/FindProtobuf.cmake                         |    2 +-
 Modules/FindPythonInterp.cmake                     |    2 -
 Modules/FindPythonLibs.cmake                       |   27 +-
 Modules/FindQuickTime.cmake                        |    2 -
 Modules/FindRuby.cmake                             |   10 +-
 Modules/FindSDL.cmake                              |   14 +-
 Modules/FindSDL_sound.cmake                        |    7 +-
 Modules/FindSquish.cmake                           |    3 -
 Modules/FindTCL.cmake                              |    2 -
 Modules/FindTIFF.cmake                             |    2 -
 Modules/FindTclsh.cmake                            |    2 -
 Modules/FindVulkan.cmake                           |    9 +-
 Modules/FindWget.cmake                             |    4 +-
 Modules/FindZLIB.cmake                             |    2 -
 Modules/FindwxWidgets.cmake                        |   14 +-
 Modules/FortranCInterface.cmake                    |    3 +-
 Modules/FortranCInterface/CMakeLists.txt           |    3 +
 Modules/FortranCInterface/Detect.cmake             |    3 +-
 Modules/GNUInstallDirs.cmake                       |  130 +-
 Modules/GenerateExportHeader.cmake                 |    1 -
 Modules/GetPrerequisites.cmake                     |   20 +-
 Modules/InstallRequiredSystemLibraries.cmake       |  453 +-
 Modules/Internal/FeatureTesting.cmake              |   12 +-
 Modules/Platform/Android-Clang-ASM.cmake           |    2 +
 Modules/Platform/Android-Clang.cmake               |    4 +-
 Modules/Platform/Android-Common.cmake              |    9 +
 Modules/Platform/Android/ndk-stl-c++.cmake         |    5 +-
 Modules/Platform/Darwin-PGI-C.cmake                |    2 +
 Modules/Platform/Darwin-PGI-CXX.cmake              |    2 +
 Modules/Platform/Darwin-PGI-Fortran.cmake          |    2 +
 Modules/Platform/Darwin-PGI.cmake                  |   14 +
 Modules/Platform/Darwin.cmake                      |    2 -
 Modules/Platform/Fuchsia.cmake                     |   25 +
 Modules/Platform/Windows-MSVC.cmake                |   13 +-
 Modules/Platform/Windows-NVIDIA-CUDA.cmake         |   46 +
 Modules/Platform/Windows.cmake                     |    1 +
 Modules/Qt4Macros.cmake                            |    2 +-
 Modules/UseJava.cmake                              |    2 -
 Modules/UseSWIG.cmake                              |   81 +-
 Modules/WriteBasicConfigVersionFile.cmake          |    2 -
 Modules/WriteCompilerDetectionHeader.cmake         |  130 +-
 Packaging/QtSDK/ToolsCMakeXX.cmake                 |   45 +
 Packaging/QtSDK/qt.tools.cmake.xx.qs.in            |   46 +
 Source/.gitattributes                              |   26 +-
 Source/CMakeInstallDestinations.cmake              |    8 +-
 Source/CMakeLists.txt                              |  317 +-
 Source/CMakeVersion.cmake                          |    4 +-
 Source/CPack/IFW/cmCPackIFWGenerator.h             |    1 -
 Source/CPack/IFW/cmCPackIFWInstaller.cxx           |  137 +-
 Source/CPack/IFW/cmCPackIFWInstaller.h             |   25 +
 Source/CPack/IFW/cmCPackIFWPackage.cxx             |  256 +-
 Source/CPack/IFW/cmCPackIFWPackage.h               |   14 +
 Source/CPack/IFW/cmCPackIFWRepository.cxx          |    2 +-
 Source/CPack/OSXScriptLauncher.cxx                 |    4 +-
 Source/CPack/WiX/cmCPackWIXGenerator.cxx           |    8 +-
 Source/CPack/WiX/cmWIXRichTextFormatWriter.h       |    3 +-
 Source/CPack/WiX/cmWIXSourceWriter.cxx             |   41 +-
 Source/CPack/WiX/cmWIXSourceWriter.h               |    2 -
 Source/CPack/cmCPack7zGenerator.h                  |    1 -
 Source/CPack/cmCPackArchiveGenerator.h             |    3 +-
 Source/CPack/cmCPackBundleGenerator.cxx            |    5 +-
 Source/CPack/cmCPackBundleGenerator.h              |    4 +
 Source/CPack/cmCPackDebGenerator.cxx               |    6 +-
 Source/CPack/cmCPackDebGenerator.h                 |    1 -
 Source/CPack/cmCPackDragNDropGenerator.cxx         |    4 +-
 Source/CPack/cmCPackDragNDropGenerator.h           |    6 +
 Source/CPack/cmCPackGenerator.cxx                  |   34 +-
 Source/CPack/cmCPackGenerator.h                    |   32 +-
 Source/CPack/cmCPackGeneratorFactory.cxx           |   12 +-
 Source/CPack/cmCPackGeneratorFactory.h             |   11 +-
 Source/CPack/cmCPackLog.cxx                        |    7 +-
 Source/CPack/cmCPackLog.h                          |   23 +-
 Source/CPack/cmCPackNSISGenerator.cxx              |   12 +-
 Source/CPack/cmCPackNSISGenerator.h                |    1 -
 Source/CPack/cmCPackOSXX11Generator.cxx            |   11 +-
 Source/CPack/cmCPackOSXX11Generator.h              |    3 +
 Source/CPack/cmCPackPKGGenerator.cxx               |   11 +-
 Source/CPack/cmCPackPKGGenerator.h                 |    7 +-
 Source/CPack/cmCPackPackageMakerGenerator.cxx      |   18 +-
 Source/CPack/cmCPackPackageMakerGenerator.h        |    3 +
 Source/CPack/cmCPackProductBuildGenerator.cxx      |   33 +-
 Source/CPack/cmCPackProductBuildGenerator.h        |    4 +
 Source/CPack/cmCPackRPMGenerator.cxx               |  256 +-
 Source/CPack/cmCPackRPMGenerator.h                 |    1 -
 Source/CPack/cmCPackSTGZGenerator.cxx              |    8 +-
 Source/CPack/cmCPackSTGZGenerator.h                |    1 -
 Source/CPack/cmCPackTGZGenerator.h                 |    1 -
 Source/CPack/cmCPackTXZGenerator.h                 |    1 -
 Source/CPack/cmCPackTarBZip2Generator.h            |    1 -
 Source/CPack/cmCPackTarCompressGenerator.h         |    1 -
 Source/CPack/cmCPackZIPGenerator.h                 |    1 -
 Source/CPack/cpack.cxx                             |   35 +-
 Source/CTest/cmCTestBuildAndTestHandler.h          |    3 +-
 Source/CTest/cmCTestBuildCommand.h                 |    3 -
 Source/CTest/cmCTestBuildHandler.cxx               |   27 +-
 Source/CTest/cmCTestBuildHandler.h                 |   10 +-
 Source/CTest/cmCTestCommand.h                      |    2 -
 Source/CTest/cmCTestConfigureCommand.cxx           |    4 +
 Source/CTest/cmCTestConfigureCommand.h             |    3 -
 Source/CTest/cmCTestConfigureHandler.h             |    3 +-
 Source/CTest/cmCTestCoverageCommand.h              |    3 +-
 Source/CTest/cmCTestCoverageHandler.cxx            |   12 +-
 Source/CTest/cmCTestCoverageHandler.h              |    3 +-
 Source/CTest/cmCTestCurl.cxx                       |   46 +-
 Source/CTest/cmCTestCurl.h                         |    2 +
 Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h  |    3 -
 Source/CTest/cmCTestGIT.cxx                        |   30 +-
 Source/CTest/cmCTestGenericHandler.cxx             |    7 +-
 Source/CTest/cmCTestGenericHandler.h               |   13 +-
 Source/CTest/cmCTestHandlerCommand.cxx             |    5 +
 Source/CTest/cmCTestHandlerCommand.h               |    5 +-
 Source/CTest/cmCTestLaunch.cxx                     |   56 +-
 Source/CTest/cmCTestMemCheckCommand.cxx            |   23 +
 Source/CTest/cmCTestMemCheckCommand.h              |   13 +-
 Source/CTest/cmCTestMemCheckHandler.cxx            |   90 +-
 Source/CTest/cmCTestMemCheckHandler.h              |    7 +-
 Source/CTest/cmCTestMultiProcessHandler.cxx        |    2 +-
 Source/CTest/cmCTestReadCustomFilesCommand.h       |    3 -
 Source/CTest/cmCTestRunScriptCommand.h             |    3 -
 Source/CTest/cmCTestRunTest.cxx                    |    9 +-
 Source/CTest/cmCTestRunTest.h                      |    4 +-
 Source/CTest/cmCTestSVN.cxx                        |    5 +-
 Source/CTest/cmCTestScriptHandler.cxx              |   22 +-
 Source/CTest/cmCTestScriptHandler.h                |    3 +-
 Source/CTest/cmCTestSleepCommand.h                 |    3 -
 Source/CTest/cmCTestStartCommand.h                 |    3 -
 Source/CTest/cmCTestSubmitCommand.cxx              |   29 +-
 Source/CTest/cmCTestSubmitCommand.h                |    3 +-
 Source/CTest/cmCTestSubmitHandler.cxx              |  181 +-
 Source/CTest/cmCTestSubmitHandler.h                |    3 +-
 Source/CTest/cmCTestTestCommand.h                  |    3 -
 Source/CTest/cmCTestTestHandler.cxx                |  170 +-
 Source/CTest/cmCTestTestHandler.h                  |    3 +-
 Source/CTest/cmCTestUpdateCommand.h                |    3 -
 Source/CTest/cmCTestUpdateHandler.h                |    3 +-
 Source/CTest/cmCTestUploadCommand.cxx              |    5 +-
 Source/CTest/cmCTestUploadCommand.h                |    3 +-
 Source/CTest/cmCTestUploadHandler.h                |    3 +-
 Source/CTest/cmCTestVC.cxx                         |    9 +-
 Source/CTest/cmCTestVC.h                           |   11 +-
 Source/CTest/cmParseCoberturaCoverage.cxx          |    2 +-
 Source/CTest/cmProcess.cxx                         |   11 +-
 Source/CursesDialog/ccmake.cxx                     |    6 +-
 Source/CursesDialog/cmCursesBoolWidget.cxx         |    4 +-
 .../CursesDialog/cmCursesCacheEntryComposite.cxx   |   11 +-
 Source/CursesDialog/cmCursesDummyWidget.cxx        |    4 +-
 Source/CursesDialog/cmCursesFilePathWidget.cxx     |    4 +-
 Source/CursesDialog/cmCursesMainForm.cxx           |  129 +-
 Source/CursesDialog/cmCursesMainForm.h             |    4 +-
 Source/CursesDialog/cmCursesOptionsWidget.cxx      |    4 +-
 Source/CursesDialog/cmCursesPathWidget.cxx         |    6 +-
 Source/CursesDialog/cmCursesStringWidget.cxx       |    8 +-
 Source/CursesDialog/cmCursesWidget.cxx             |    4 +-
 Source/CursesDialog/cmCursesWidget.h               |    6 +-
 Source/CursesDialog/form/.gitattributes            |    1 +
 Source/Modules/FindLibRHash.cmake                  |   73 +
 Source/QtDialog/AddCacheEntry.cxx                  |    2 +-
 Source/QtDialog/CMakeSetup.cxx                     |    4 +-
 Source/QtDialog/FirstConfigure.cxx                 |    2 +-
 Source/QtDialog/QCMake.cxx                         |   26 +-
 Source/QtDialog/RegexExplorer.cxx                  |   34 +-
 Source/QtDialog/RegexExplorer.h                    |    1 +
 Source/QtDialog/RegexExplorer.ui                   |   37 +-
 Source/QtIFW/CMake.DeveloperReference.HTML.qs.in   |    4 +-
 Source/QtIFW/CMake.Dialogs.QtGUI.qs                |   21 -
 Source/QtIFW/CMake.Dialogs.QtGUI.qs.in             |   21 +
 Source/QtIFW/CMake.Documentation.SphinxHTML.qs.in  |    4 +-
 Source/QtIFW/CMake.qs.in                           |   10 +-
 Source/QtIFW/installscript.qs.in                   |   12 +-
 Source/bindexplib.cxx                              |    3 +-
 Source/bindexplib.h                                |    5 +-
 Source/cmAddCompileOptionsCommand.cxx              |    4 +
 Source/cmAddCompileOptionsCommand.h                |    8 +-
 Source/cmAddCustomCommandCommand.cxx               |   21 +-
 Source/cmAddCustomCommandCommand.h                 |    8 +-
 Source/cmAddCustomTargetCommand.cxx                |   25 +-
 Source/cmAddCustomTargetCommand.h                  |    8 +-
 Source/cmAddDefinitionsCommand.cxx                 |    4 +
 Source/cmAddDefinitionsCommand.h                   |    8 +-
 Source/cmAddDependenciesCommand.cxx                |    8 +-
 Source/cmAddDependenciesCommand.h                  |    8 +-
 Source/cmAddExecutableCommand.cxx                  |   20 +-
 Source/cmAddExecutableCommand.h                    |    8 +-
 Source/cmAddLibraryCommand.cxx                     |   80 +-
 Source/cmAddLibraryCommand.h                       |    8 +-
 Source/cmAddSubDirectoryCommand.cxx                |    8 +
 Source/cmAddSubDirectoryCommand.h                  |    8 +-
 Source/cmAddTestCommand.cxx                        |    6 +-
 Source/cmAddTestCommand.h                          |    8 +-
 Source/cmAlgorithms.h                              |   22 +-
 Source/cmAuxSourceDirectoryCommand.cxx             |   14 +-
 Source/cmAuxSourceDirectoryCommand.h               |    8 +-
 Source/cmBootstrapCommands1.cxx                    |   87 -
 Source/cmBootstrapCommands2.cxx                    |   94 -
 Source/cmBreakCommand.cxx                          |    5 +
 Source/cmBreakCommand.h                            |    8 +-
 Source/cmBuildCommand.cxx                          |   13 +-
 Source/cmBuildCommand.h                            |    8 +-
 Source/cmBuildNameCommand.cxx                      |   12 +-
 Source/cmBuildNameCommand.h                        |    7 +-
 Source/cmCMakeHostSystemInformationCommand.cxx     |   20 +
 Source/cmCMakeHostSystemInformationCommand.h       |   12 +-
 Source/cmCMakeMinimumRequired.cxx                  |    8 +
 Source/cmCMakeMinimumRequired.h                    |    8 +-
 Source/cmCMakePolicyCommand.cxx                    |   12 +-
 Source/cmCMakePolicyCommand.h                      |    8 +-
 Source/cmCPluginAPI.cxx                            |   75 +-
 Source/cmCTest.cxx                                 |  171 +-
 Source/cmCTest.h                                   |   26 +-
 Source/cmCacheManager.cxx                          |   45 +-
 Source/cmCacheManager.h                            |   25 +-
 Source/cmCallVisualStudioMacro.cxx                 |    2 +
 Source/cmCallVisualStudioMacro.h                   |    2 +-
 Source/cmCommand.cxx                               |   54 +
 Source/cmCommand.h                                 |   95 +-
 Source/cmCommandArgumentLexer.cxx                  | 1783 ++++----
 Source/cmCommandArgumentLexer.h                    |  144 +-
 Source/cmCommandArgumentLexer.in.l                 |   36 +-
 Source/cmCommandArgumentsHelper.h                  |    6 +-
 Source/cmCommands.cxx                              |  241 ++
 Source/cmCommands.cxx.in                           |   10 -
 Source/cmCommands.h                                |   10 +-
 Source/cmCommandsForBootstrap.cxx                  |    7 -
 Source/cmCommonTargetGenerator.cxx                 |   45 +-
 Source/cmCommonTargetGenerator.h                   |    8 +-
 Source/cmComputeLinkDepends.cxx                    |    6 +-
 Source/cmComputeLinkInformation.cxx                |   58 +-
 Source/cmComputeLinkInformation.h                  |    1 +
 Source/cmComputeTargetDepends.cxx                  |   21 +-
 Source/cmConditionEvaluator.cxx                    |   26 +-
 Source/cmConditionEvaluator.h                      |   12 +-
 Source/cmConfigure.cmake.h.in                      |    1 -
 Source/cmConfigureFileCommand.cxx                  |    8 +-
 Source/cmConfigureFileCommand.h                    |    9 +-
 Source/cmContinueCommand.cxx                       |    5 +
 Source/cmContinueCommand.h                         |    8 +-
 Source/cmConvertMSBuildXMLToJSON.py                |  453 ++
 Source/cmCoreTryCompile.cxx                        |  367 +-
 Source/cmCoreTryCompile.h                          |   14 +-
 Source/cmCreateTestSourceList.cxx                  |    6 +
 Source/cmCreateTestSourceList.h                    |    9 +-
 Source/cmCryptoHash.cxx                            |  113 +-
 Source/cmCryptoHash.h                              |   74 +-
 Source/cmCustomCommand.cxx                         |   12 +
 Source/cmCustomCommand.h                           |    5 +
 Source/cmCustomCommandGenerator.cxx                |   77 +-
 Source/cmCustomCommandGenerator.h                  |    6 +-
 Source/cmDefinePropertyCommand.cxx                 |    7 +-
 Source/cmDefinePropertyCommand.h                   |    8 +-
 Source/cmDefinitions.cxx                           |    1 +
 Source/cmDefinitions.h                             |   25 +-
 Source/cmDependsC.cxx                              |   11 +-
 Source/cmDependsFortran.cxx                        |   61 +-
 Source/cmDependsFortran.h                          |    3 +
 Source/cmDependsJavaLexer.cxx                      | 2255 +++++-----
 Source/cmDependsJavaLexer.h                        |  201 +-
 Source/cmDependsJavaLexer.in.l                     |   30 +-
 Source/cmDependsJavaParserHelper.cxx               |    4 +-
 Source/cmDependsJavaParserHelper.h                 |    2 +
 Source/cmDocumentationFormatter.cxx                |    2 +-
 Source/cmELF.cxx                                   |  224 +-
 Source/cmELF.h                                     |   23 +-
 Source/cmElseCommand.cxx                           |   12 -
 Source/cmElseCommand.h                             |   41 -
 Source/cmElseIfCommand.cxx                         |   11 -
 Source/cmElseIfCommand.h                           |   41 -
 Source/cmEnableLanguageCommand.cxx                 |    4 +
 Source/cmEnableLanguageCommand.h                   |    8 +-
 Source/cmEnableTestingCommand.cxx                  |    4 +
 Source/cmEnableTestingCommand.h                    |    8 +-
 Source/cmEndForEachCommand.cxx                     |   12 -
 Source/cmEndForEachCommand.h                       |   51 -
 Source/cmEndFunctionCommand.cxx                    |   12 -
 Source/cmEndFunctionCommand.h                      |   51 -
 Source/cmEndIfCommand.cxx                          |   19 -
 Source/cmEndIfCommand.h                            |   41 -
 Source/cmEndMacroCommand.cxx                       |   12 -
 Source/cmEndMacroCommand.h                         |   51 -
 Source/cmEndWhileCommand.cxx                       |   18 -
 Source/cmEndWhileCommand.h                         |   51 -
 Source/cmExecProgramCommand.cxx                    |   22 +-
 Source/cmExecProgramCommand.h                      |   13 +-
 Source/cmExecuteProcessCommand.cxx                 |   42 +-
 Source/cmExecuteProcessCommand.h                   |    8 +-
 Source/cmExecutionStatus.h                         |    4 -
 Source/cmExpandedCommandArgument.h                 |    4 +-
 Source/cmExportBuildAndroidMKGenerator.cxx         |   44 +-
 Source/cmExportBuildAndroidMKGenerator.h           |   10 +-
 Source/cmExportBuildFileGenerator.cxx              |   10 +-
 Source/cmExportCommand.cxx                         |   22 +-
 Source/cmExportCommand.h                           |    9 +-
 Source/cmExportFileGenerator.cxx                   |   20 +-
 Source/cmExportInstallAndroidMKGenerator.cxx       |   19 +-
 Source/cmExportInstallAndroidMKGenerator.h         |   10 +-
 Source/cmExportInstallFileGenerator.cxx            |    8 +-
 Source/cmExportLibraryDependenciesCommand.cxx      |   20 +-
 Source/cmExportLibraryDependenciesCommand.h        |    7 +-
 Source/cmExportTryCompileFileGenerator.cxx         |    4 +-
 Source/cmExprLexer.cxx                             | 1976 ++++-----
 Source/cmExprLexer.h                               |  193 +-
 Source/cmExprLexer.in.l                            |   24 +-
 Source/cmExprParser.cxx                            | 1768 ++++----
 Source/cmExprParser.y                              |  157 +-
 Source/cmExprParserTokens.h                        |   94 +-
 Source/cmExtraCodeBlocksGenerator.cxx              |   59 +-
 Source/cmExtraCodeLiteGenerator.cxx                |  103 +-
 Source/cmExtraCodeLiteGenerator.h                  |   12 +-
 Source/cmExtraEclipseCDT4Generator.cxx             |   61 +-
 Source/cmExtraKateGenerator.cxx                    |   16 +-
 Source/cmExtraSublimeTextGenerator.cxx             |   99 +-
 Source/cmExtraSublimeTextGenerator.h               |    3 +
 Source/cmFLTKWrapUICommand.cxx                     |   14 +-
 Source/cmFLTKWrapUICommand.h                       |    9 +-
 Source/cmFileCommand.cxx                           |  142 +-
 Source/cmFileCommand.h                             |    8 +-
 Source/cmFileMonitor.cxx                           |   11 +-
 Source/cmFileMonitor.h                             |    2 +-
 Source/cmFilePathChecksum.cxx                      |   88 +
 Source/cmFilePathChecksum.h                        |   65 +
 Source/cmFilePathUuid.cxx                          |  118 -
 Source/cmFilePathUuid.h                            |   69 -
 Source/cmFileTimeComparison.cxx                    |   35 +-
 Source/cmFindBase.cxx                              |   13 +-
 Source/cmFindBase.h                                |    6 +-
 Source/cmFindCommon.cxx                            |    6 +-
 Source/cmFindCommon.h                              |   10 +-
 Source/cmFindFileCommand.cxx                       |    2 -
 Source/cmFindFileCommand.h                         |    7 +-
 Source/cmFindLibraryCommand.cxx                    |   84 +-
 Source/cmFindLibraryCommand.h                      |    9 +-
 Source/cmFindPackageCommand.cxx                    |   51 +-
 Source/cmFindPackageCommand.h                      |   13 +-
 Source/cmFindPathCommand.cxx                       |   17 +-
 Source/cmFindPathCommand.h                         |    8 +-
 Source/cmFindProgramCommand.cxx                    |   16 +-
 Source/cmFindProgramCommand.h                      |    9 +-
 Source/cmForEachCommand.cxx                        |   10 +-
 Source/cmForEachCommand.h                          |   10 +-
 Source/cmFortranLexer.cxx                          |  183 +-
 Source/cmFortranLexer.h                            |   13 +-
 Source/cmFortranLexer.in.l                         |   10 +-
 Source/cmFortranParserImpl.cxx                     |   10 +-
 Source/cmFunctionBlocker.h                         |    7 +-
 Source/cmFunctionCommand.cxx                       |   18 +-
 Source/cmFunctionCommand.h                         |   11 +-
 Source/cmGeneratedFileStream.cxx                   |   24 +-
 Source/cmGeneratedFileStream.h                     |    7 +-
 Source/cmGeneratorExpression.cxx                   |   10 +-
 Source/cmGeneratorExpressionDAGChecker.cxx         |    5 +-
 Source/cmGeneratorExpressionEvaluationFile.cxx     |   11 +-
 Source/cmGeneratorExpressionEvaluationFile.h       |   13 +-
 Source/cmGeneratorExpressionEvaluator.h            |    6 +-
 Source/cmGeneratorExpressionNode.cxx               |   50 +-
 Source/cmGeneratorExpressionParser.cxx             |    4 +-
 Source/cmGeneratorTarget.cxx                       |  386 +-
 Source/cmGeneratorTarget.h                         |   23 +-
 Source/cmGetCMakePropertyCommand.cxx               |    6 +-
 Source/cmGetCMakePropertyCommand.h                 |    8 +-
 Source/cmGetDirectoryPropertyCommand.cxx           |    6 +
 Source/cmGetDirectoryPropertyCommand.h             |    8 +-
 Source/cmGetFilenameComponentCommand.cxx           |   16 +-
 Source/cmGetFilenameComponentCommand.h             |    8 +-
 Source/cmGetPropertyCommand.cxx                    |   27 +-
 Source/cmGetPropertyCommand.h                      |    8 +-
 Source/cmGetSourceFilePropertyCommand.cxx          |    3 +
 Source/cmGetSourceFilePropertyCommand.h            |    8 +-
 Source/cmGetTargetPropertyCommand.cxx              |   23 +-
 Source/cmGetTargetPropertyCommand.h                |    8 +-
 Source/cmGetTestPropertyCommand.cxx                |    4 +-
 Source/cmGetTestPropertyCommand.h                  |    8 +-
 Source/cmGhsMultiGpj.h                             |    2 -
 Source/cmGhsMultiTargetGenerator.cxx               |   25 +-
 Source/cmGlobalBorlandMakefileGenerator.cxx        |    2 +
 Source/cmGlobalGenerator.cxx                       |  135 +-
 Source/cmGlobalGenerator.h                         |   70 +-
 Source/cmGlobalGeneratorFactory.h                  |    7 +-
 Source/cmGlobalGhsMultiGenerator.cxx               |   15 +-
 Source/cmGlobalGhsMultiGenerator.h                 |    2 +-
 Source/cmGlobalJOMMakefileGenerator.cxx            |    2 +
 Source/cmGlobalKdevelopGenerator.cxx               |    4 +-
 Source/cmGlobalMSYSMakefileGenerator.cxx           |    5 +-
 Source/cmGlobalMinGWMakefileGenerator.cxx          |    2 +
 Source/cmGlobalNMakeMakefileGenerator.cxx          |    2 +
 Source/cmGlobalNMakeMakefileGenerator.h            |    6 +
 Source/cmGlobalNinjaGenerator.cxx                  |  125 +-
 Source/cmGlobalNinjaGenerator.h                    |   38 +-
 Source/cmGlobalUnixMakefileGenerator3.cxx          |  102 +-
 Source/cmGlobalUnixMakefileGenerator3.h            |   14 +-
 Source/cmGlobalVisualStudio10Generator.cxx         |  139 +-
 Source/cmGlobalVisualStudio10Generator.h           |   23 +-
 Source/cmGlobalVisualStudio11Generator.cxx         |   18 +-
 Source/cmGlobalVisualStudio11Generator.h           |   13 +-
 Source/cmGlobalVisualStudio12Generator.cxx         |   28 +
 Source/cmGlobalVisualStudio12Generator.h           |   12 +
 Source/cmGlobalVisualStudio14Generator.cxx         |   13 +
 Source/cmGlobalVisualStudio14Generator.h           |    9 +
 Source/cmGlobalVisualStudio15Generator.cxx         |   95 +-
 Source/cmGlobalVisualStudio15Generator.h           |   17 +
 Source/cmGlobalVisualStudio71Generator.cxx         |    9 +-
 Source/cmGlobalVisualStudio71Generator.h           |    2 +-
 Source/cmGlobalVisualStudio7Generator.cxx          |   69 +-
 Source/cmGlobalVisualStudio7Generator.h            |    4 +-
 Source/cmGlobalVisualStudio8Generator.cxx          |   26 +-
 Source/cmGlobalVisualStudio8Generator.h            |    7 +-
 Source/cmGlobalVisualStudio9Generator.cxx          |    3 +-
 Source/cmGlobalVisualStudioGenerator.cxx           |   62 +-
 Source/cmGlobalVisualStudioGenerator.h             |   20 +-
 Source/cmGlobalXCodeGenerator.cxx                  |  278 +-
 Source/cmGlobalXCodeGenerator.h                    |   74 +-
 Source/cmGraphAdjacencyList.h                      |    4 +-
 Source/cmGraphVizWriter.cxx                        |   29 +-
 Source/cmGraphVizWriter.h                          |    4 +-
 Source/cmHexFileConverter.cxx                      |    5 +-
 Source/cmHexFileConverter.h                        |    4 -
 Source/cmIDEOptions.cxx                            |   12 +-
 Source/cmIDEOptions.h                              |    8 +-
 Source/cmIfCommand.cxx                             |   14 +-
 Source/cmIfCommand.h                               |   12 +-
 Source/cmIncludeCommand.cxx                        |   14 +-
 Source/cmIncludeCommand.h                          |    8 +-
 Source/cmIncludeDirectoryCommand.cxx               |    8 +
 Source/cmIncludeDirectoryCommand.h                 |    8 +-
 Source/cmIncludeExternalMSProjectCommand.cxx       |   15 +-
 Source/cmIncludeExternalMSProjectCommand.h         |    8 +-
 Source/cmIncludeRegularExpressionCommand.cxx       |    4 +
 Source/cmIncludeRegularExpressionCommand.h         |    8 +-
 Source/cmInstallCommand.cxx                        |   88 +-
 Source/cmInstallCommand.h                          |    8 +-
 Source/cmInstallCommandArguments.cxx               |    2 +
 Source/cmInstallCommandArguments.h                 |    5 +-
 Source/cmInstallFilesCommand.cxx                   |    7 +
 Source/cmInstallFilesCommand.h                     |    8 +-
 Source/cmInstallProgramsCommand.cxx                |    8 +
 Source/cmInstallProgramsCommand.h                  |    8 +-
 Source/cmInstallTargetGenerator.cxx                |   62 +-
 Source/cmInstallTargetsCommand.cxx                 |    9 +
 Source/cmInstallTargetsCommand.h                   |    8 +-
 Source/cmLinkDirectoriesCommand.cxx                |    9 +
 Source/cmLinkDirectoriesCommand.h                  |    8 +-
 Source/cmLinkItem.h                                |    8 +
 Source/cmLinkLibrariesCommand.cxx                  |   11 +-
 Source/cmLinkLibrariesCommand.h                    |    8 +-
 Source/cmLinkLineComputer.cxx                      |  192 +
 Source/cmLinkLineComputer.h                        |   58 +
 Source/cmLinkLineDeviceComputer.cxx                |   80 +
 Source/cmLinkLineDeviceComputer.h                  |   39 +
 Source/cmLinkedTree.h                              |    4 +-
 Source/cmListCommand.cxx                           |   18 +-
 Source/cmListCommand.h                             |    8 +-
 Source/cmListFileCache.cxx                         |    7 +-
 Source/cmListFileCache.h                           |   12 +-
 Source/cmListFileLexer.c                           |  203 +-
 Source/cmListFileLexer.h                           |    2 +-
 Source/cmListFileLexer.in.l                        |   15 +-
 Source/cmLoadCacheCommand.cxx                      |   10 +-
 Source/cmLoadCacheCommand.h                        |    9 +-
 Source/cmLoadCommandCommand.cxx                    |   23 +-
 Source/cmLoadCommandCommand.h                      |    7 +-
 Source/cmLocalCommonGenerator.cxx                  |    5 +-
 Source/cmLocalCommonGenerator.h                    |    5 +-
 Source/cmLocalGenerator.cxx                        |  722 +---
 Source/cmLocalGenerator.h                          |  104 +-
 Source/cmLocalGhsMultiGenerator.cxx                |    2 +-
 Source/cmLocalNinjaGenerator.cxx                   |   70 +-
 Source/cmLocalNinjaGenerator.h                     |   22 +-
 Source/cmLocalUnixMakefileGenerator3.cxx           |  120 +-
 Source/cmLocalUnixMakefileGenerator3.h             |    3 +
 Source/cmLocalVisualStudio10Generator.cxx          |    4 +-
 Source/cmLocalVisualStudio10Generator.h            |    7 +
 Source/cmLocalVisualStudio7Generator.cxx           |   89 +-
 Source/cmLocalVisualStudio7Generator.h             |   17 +-
 Source/cmLocalVisualStudioGenerator.cxx            |    4 +-
 Source/cmLocalVisualStudioGenerator.h              |   16 +-
 Source/cmLocalXCodeGenerator.cxx                   |    5 +-
 Source/cmLocalXCodeGenerator.h                     |    9 +
 Source/cmLocale.h                                  |    7 +-
 Source/cmMSVC60LinkLineComputer.cxx                |   42 +
 Source/cmMSVC60LinkLineComputer.h                  |   26 +
 Source/cmMachO.cxx                                 |    6 +-
 Source/cmMachO.h                                   |    5 +
 Source/cmMacroCommand.cxx                          |   18 +-
 Source/cmMacroCommand.h                            |   11 +-
 Source/cmMakeDirectoryCommand.cxx                  |    5 +
 Source/cmMakeDirectoryCommand.h                    |    8 +-
 Source/cmMakefile.cxx                              |  335 +-
 Source/cmMakefile.h                                |  105 +-
 Source/cmMakefileExecutableTargetGenerator.cxx     |  314 +-
 Source/cmMakefileExecutableTargetGenerator.h       |    4 +
 Source/cmMakefileLibraryTargetGenerator.cxx        |  422 +-
 Source/cmMakefileLibraryTargetGenerator.h          |    6 +
 Source/cmMakefileTargetGenerator.cxx               |  302 +-
 Source/cmMakefileTargetGenerator.h                 |   23 +-
 Source/cmMakefileUtilityTargetGenerator.cxx        |   12 +-
 Source/cmMarkAsAdvancedCommand.cxx                 |   10 +-
 Source/cmMarkAsAdvancedCommand.h                   |    8 +-
 Source/cmMathCommand.cxx                           |    5 +
 Source/cmMathCommand.h                             |    8 +-
 Source/cmMessageCommand.cxx                        |    6 +
 Source/cmMessageCommand.h                          |    8 +-
 Source/cmNinjaLinkLineComputer.cxx                 |   23 +
 Source/cmNinjaLinkLineComputer.h                   |   31 +
 Source/cmNinjaNormalTargetGenerator.cxx            |  498 ++-
 Source/cmNinjaNormalTargetGenerator.h              |   10 +
 Source/cmNinjaTargetGenerator.cxx                  |  166 +-
 Source/cmNinjaTypes.h                              |    6 +-
 Source/cmNinjaUtilityTargetGenerator.cxx           |    4 +-
 Source/cmObject.h                                  |   41 -
 Source/cmOptionCommand.cxx                         |   12 +-
 Source/cmOptionCommand.h                           |    8 +-
 Source/cmOrderDirectories.cxx                      |   22 +-
 Source/cmOrderDirectories.h                        |    2 +
 Source/cmOutputConverter.cxx                       |  111 +-
 Source/cmOutputConverter.h                         |   48 +-
 Source/cmOutputRequiredFilesCommand.cxx            |   34 +-
 Source/cmOutputRequiredFilesCommand.h              |    8 +-
 Source/cmParseArgumentsCommand.cxx                 |   11 +
 Source/cmParseArgumentsCommand.h                   |    8 +-
 Source/cmPathLabel.cxx                             |    2 +
 Source/cmPathLabel.h                               |    4 +-
 Source/cmPolicies.cxx                              |    3 +-
 Source/cmPolicies.h                                |    5 +-
 Source/cmProcessOutput.cxx                         |  173 +
 Source/cmProcessOutput.h                           |   88 +
 Source/cmProcessTools.cxx                          |   23 +-
 Source/cmProcessTools.h                            |    5 +-
 Source/cmProjectCommand.cxx                        |   18 +-
 Source/cmProjectCommand.h                          |    8 +-
 Source/cmQTWrapCPPCommand.cxx                      |    9 +-
 Source/cmQTWrapCPPCommand.h                        |    8 +-
 Source/cmQTWrapUICommand.cxx                       |    9 +-
 Source/cmQTWrapUICommand.h                         |    7 +-
 Source/cmQtAutoGeneratorInitializer.cxx            |  528 +--
 Source/cmQtAutoGenerators.cxx                      | 1700 ++++----
 Source/cmQtAutoGenerators.h                        |  152 +-
 Source/cmRemoveCommand.cxx                         |    5 +
 Source/cmRemoveCommand.h                           |    8 +-
 Source/cmRemoveDefinitionsCommand.cxx              |    4 +
 Source/cmRemoveDefinitionsCommand.h                |    8 +-
 Source/cmReturnCommand.cxx                         |    2 +
 Source/cmReturnCommand.h                           |    8 +-
 Source/cmRulePlaceholderExpander.cxx               |  308 ++
 Source/cmRulePlaceholderExpander.h                 |   81 +
 Source/cmSearchPath.cxx                            |    6 +
 Source/cmSearchPath.h                              |    4 +-
 Source/cmSeparateArgumentsCommand.cxx              |    8 +
 Source/cmSeparateArgumentsCommand.h                |    8 +-
 Source/cmServer.cxx                                |    1 +
 Source/cmServerConnection.cxx                      |    1 +
 Source/cmServerProtocol.cxx                        |   91 +-
 Source/cmSetCommand.cxx                            |   19 +-
 Source/cmSetCommand.h                              |    8 +-
 Source/cmSetDirectoryPropertiesCommand.cxx         |    4 +-
 Source/cmSetDirectoryPropertiesCommand.h           |    9 +-
 Source/cmSetPropertyCommand.cxx                    |   19 +-
 Source/cmSetPropertyCommand.h                      |   13 +-
 Source/cmSetSourceFilesPropertiesCommand.cxx       |    4 +
 Source/cmSetSourceFilesPropertiesCommand.h         |    9 +-
 Source/cmSetTargetPropertiesCommand.cxx            |    7 +-
 Source/cmSetTargetPropertiesCommand.h              |    9 +-
 Source/cmSetTestsPropertiesCommand.cxx             |    6 +-
 Source/cmSetTestsPropertiesCommand.h               |    9 +-
 Source/cmSiteNameCommand.cxx                       |    9 +-
 Source/cmSiteNameCommand.h                         |    8 +-
 Source/cmSourceFile.cxx                            |    4 +-
 Source/cmSourceFile.h                              |    1 +
 Source/cmSourceGroupCommand.cxx                    |  175 +-
 Source/cmSourceGroupCommand.h                      |   12 +-
 Source/cmStandardIncludes.h                        |    1 -
 Source/cmStandardLexer.h                           |   26 +-
 Source/cmState.cxx                                 | 1147 +-----
 Source/cmState.h                                   |  245 +-
 Source/cmStateDirectory.cxx                        |  528 +++
 Source/cmStateDirectory.h                          |   83 +
 Source/cmStatePrivate.h                            |  101 +
 Source/cmStateSnapshot.cxx                         |  427 ++
 Source/cmStateSnapshot.h                           |   88 +
 Source/cmStateTypes.h                              |   55 +
 Source/cmStringCommand.cxx                         |   29 +-
 Source/cmStringCommand.h                           |   11 +-
 Source/cmSubdirCommand.cxx                         |   11 +-
 Source/cmSubdirCommand.h                           |    8 +-
 Source/cmSubdirDependsCommand.cxx                  |    4 +
 Source/cmSubdirDependsCommand.h                    |    7 +-
 Source/cmSystemTools.cxx                           |  129 +-
 Source/cmSystemTools.h                             |   11 +-
 Source/cmTarget.cxx                                |  741 ++--
 Source/cmTarget.h                                  |   70 +-
 Source/cmTargetCompileDefinitionsCommand.cxx       |    7 +
 Source/cmTargetCompileDefinitionsCommand.h         |   10 +-
 Source/cmTargetCompileFeaturesCommand.cxx          |    7 +
 Source/cmTargetCompileFeaturesCommand.h            |   10 +-
 Source/cmTargetCompileOptionsCommand.cxx           |    8 +
 Source/cmTargetCompileOptionsCommand.h             |   10 +-
 Source/cmTargetDepend.h                            |    4 +-
 Source/cmTargetExport.h                            |    6 +-
 Source/cmTargetIncludeDirectoriesCommand.cxx       |   10 +
 Source/cmTargetIncludeDirectoriesCommand.h         |   10 +-
 Source/cmTargetLinkLibrariesCommand.cxx            |   53 +-
 Source/cmTargetLinkLibrariesCommand.h              |   10 +-
 Source/cmTargetPropCommandBase.cxx                 |   18 +-
 Source/cmTargetPropCommandBase.h                   |    7 +-
 Source/cmTargetPropertyComputer.cxx                |   92 +
 Source/cmTargetPropertyComputer.h                  |  110 +
 Source/cmTargetSourcesCommand.cxx                  |    9 +-
 Source/cmTargetSourcesCommand.h                    |   10 +-
 Source/cmTestGenerator.cxx                         |   13 +-
 Source/cmTimestamp.cxx                             |   20 +-
 Source/cmTimestamp.h                               |    4 +-
 Source/cmTryCompileCommand.cxx                     |    5 +
 Source/cmTryCompileCommand.h                       |    9 +-
 Source/cmTryRunCommand.cxx                         |   27 +-
 Source/cmTryRunCommand.h                           |    9 +-
 Source/cmTypeMacro.h                               |   31 -
 Source/cmUnexpectedCommand.cxx                     |   22 +
 Source/cmUnexpectedCommand.h                       |   40 +
 Source/cmUnsetCommand.cxx                          |    8 +
 Source/cmUnsetCommand.h                            |    8 +-
 Source/cmUseMangledMesaCommand.cxx                 |    9 +-
 Source/cmUseMangledMesaCommand.h                   |    7 +-
 Source/cmUtilitySourceCommand.cxx                  |   14 +-
 Source/cmUtilitySourceCommand.h                    |    7 +-
 Source/cmUuid.cxx                                  |   31 +-
 Source/cmVS10CSharpFlagTable.h                     |  120 +
 Source/cmVS11CSharpFlagTable.h                     |  120 +
 Source/cmVS12CSharpFlagTable.h                     |  120 +
 Source/cmVS140CSharpFlagTable.h                    |  120 +
 Source/cmVS141CSharpFlagTable.h                    |  120 +
 Source/cmVSSetupHelper.cxx                         |  366 ++
 Source/cmVSSetupHelper.h                           |  154 +
 Source/cmVariableRequiresCommand.cxx               |    5 +
 Source/cmVariableRequiresCommand.h                 |    7 +-
 Source/cmVariableWatchCommand.cxx                  |    7 +
 Source/cmVariableWatchCommand.h                    |    9 +-
 Source/cmVisualStudio10TargetGenerator.cxx         | 1160 ++++--
 Source/cmVisualStudio10TargetGenerator.h           |   52 +-
 Source/cmVisualStudio10ToolsetOptions.cxx          |  159 +
 Source/cmVisualStudio10ToolsetOptions.h            |   37 +
 Source/cmVisualStudioGeneratorOptions.cxx          |   28 +-
 Source/cmVisualStudioGeneratorOptions.h            |   14 +-
 Source/cmVisualStudioSlnData.h                     |    4 +-
 Source/cmVisualStudioSlnParser.h                   |    6 +-
 Source/cmVisualStudioWCEPlatformParser.h           |    5 +-
 Source/cmWhileCommand.cxx                          |    6 +
 Source/cmWhileCommand.h                            |   10 +-
 Source/cmWriteFileCommand.cxx                      |    7 +-
 Source/cmWriteFileCommand.h                        |    8 +-
 Source/cmXCode21Object.cxx                         |    3 +
 Source/cmXCode21Object.h                           |    5 +
 Source/cmXCodeObject.cxx                           |    5 +-
 Source/cmXCodeObject.h                             |    9 +-
 Source/cm_codecvt.cxx                              |  215 +
 Source/cm_codecvt.hxx                              |   58 +
 Source/cm_sha2.c                                   | 1613 --------
 Source/cm_sha2.h                                   |  140 -
 Source/cm_sha2_mangle.h                            |   42 -
 Source/cm_unordered_map.hxx                        |   25 +
 Source/cm_unordered_set.hxx                        |   25 +
 Source/cmake.cxx                                   |  260 +-
 Source/cmake.h                                     |   32 +-
 Source/cmakemain.cxx                               |   19 +-
 Source/cmakexbuild.cxx                             |    9 +-
 Source/cmcldeps.cxx                                |   11 +-
 Source/cmcmd.cxx                                   |  179 +-
 Source/ctest.cxx                                   |   14 +-
 Source/kwsys/.gitattributes                        |    4 +-
 Source/kwsys/Base64.c                              |  218 +-
 Source/kwsys/Base64.h.in                           |   82 +-
 Source/kwsys/CMakeLists.txt                        |   44 +-
 Source/kwsys/CONTRIBUTING.rst                      |   38 +-
 Source/kwsys/CTestConfig.cmake                     |   14 +-
 Source/kwsys/CommandLineArguments.cxx              |  786 ++--
 Source/kwsys/CommandLineArguments.hxx.in           |  133 +-
 Source/kwsys/Configure.h.in                        |  167 +-
 Source/kwsys/Configure.hxx.in                      |   29 +-
 Source/kwsys/ConsoleBuf.hxx.in                     |  650 +--
 Source/kwsys/Copyright.txt                         |   17 +-
 Source/kwsys/Directory.cxx                         |  140 +-
 Source/kwsys/Directory.hxx.in                      |   23 +-
 Source/kwsys/DynamicLoader.cxx                     |  363 +-
 Source/kwsys/DynamicLoader.hxx.in                  |   43 +-
 Source/kwsys/Encoding.h.in                         |   58 +-
 Source/kwsys/Encoding.hxx.in                       |   72 +-
 Source/kwsys/EncodingC.c                           |   53 +-
 Source/kwsys/EncodingCXX.cxx                       |  170 +-
 Source/kwsys/FStream.cxx                           |   67 +-
 Source/kwsys/FStream.hxx.in                        |  428 +-
 Source/kwsys/Glob.cxx                              |  416 +-
 Source/kwsys/Glob.hxx.in                           |   64 +-
 Source/kwsys/IOStream.cxx                          |  245 +-
 Source/kwsys/IOStream.hxx.in                       |  136 +-
 Source/kwsys/MD5.c                                 |  523 ++-
 Source/kwsys/MD5.h.in                              |   64 +-
 Source/kwsys/Process.h.in                          |  260 +-
 Source/kwsys/ProcessUNIX.c                         | 2078 +++++-----
 Source/kwsys/ProcessWin32.c                        | 1837 ++++-----
 Source/kwsys/README.rst                            |   37 +
 Source/kwsys/README.txt                            |   12 -
 Source/kwsys/RegularExpression.cxx                 | 1666 ++++----
 Source/kwsys/RegularExpression.hxx.in              |  148 +-
 Source/kwsys/SharedForward.h.in                    |  604 ++-
 Source/kwsys/String.c                              |   97 +-
 Source/kwsys/String.h.in                           |   36 +-
 Source/kwsys/String.hxx.in                         |   62 +-
 Source/kwsys/System.c                              |  221 +-
 Source/kwsys/System.h.in                           |   32 +-
 Source/kwsys/SystemInformation.cxx                 | 4308 ++++++++++----------
 Source/kwsys/SystemInformation.hxx.in              |   61 +-
 Source/kwsys/SystemTools.cxx                       | 3908 ++++++++----------
 Source/kwsys/SystemTools.hxx.in                    |  294 +-
 Source/kwsys/Terminal.c                            |  317 +-
 Source/kwsys/Terminal.h.in                         |  191 +-
 Source/kwsys/hash_fun.hxx.in                       |   89 +-
 Source/kwsys/hash_map.hxx.in                       |  246 +-
 Source/kwsys/hash_set.hxx.in                       |  217 +-
 Source/kwsys/hashtable.hxx.in                      |  486 ++-
 Source/kwsys/kwsysHeaderDump.pl                    |   13 +-
 Source/kwsys/kwsysPlatformTests.cmake              |   14 +-
 Source/kwsys/kwsysPlatformTestsC.c                 |   52 +-
 Source/kwsys/kwsysPlatformTestsCXX.cxx             |  147 +-
 Source/kwsys/kwsysPrivate.h                        |   19 +-
 Source/kwsys/testCommandLineArguments.cxx          |  201 +-
 Source/kwsys/testCommandLineArguments1.cxx         |   83 +-
 Source/kwsys/testConsoleBuf.cxx                    |  443 +-
 Source/kwsys/testConsoleBuf.hxx                    |   20 +-
 Source/kwsys/testConsoleBufChild.cxx               |   21 +-
 Source/kwsys/testDynamicLoader.cxx                 |   89 +-
 Source/kwsys/testDynload.c                         |   15 +-
 Source/kwsys/testEncode.c                          |   31 +-
 Source/kwsys/testEncoding.cxx                      |  161 +-
 Source/kwsys/testFStream.cxx                       |  114 +-
 Source/kwsys/testFail.c                            |   31 +-
 Source/kwsys/testHashSTL.cxx                       |   37 +-
 Source/kwsys/testIOS.cxx                           |  153 +-
 Source/kwsys/testProcess.c                         |  454 +--
 Source/kwsys/testSharedForward.c.in                |   27 +-
 Source/kwsys/testSystemInformation.cxx             |   67 +-
 Source/kwsys/testSystemTools.cxx                   | 1181 +++---
 Source/kwsys/testSystemTools.h.in                  |   13 +-
 Source/kwsys/testTerminal.c                        |   19 +-
 Templates/TestDriver.cxx.in                        |  146 +-
 Tests/BootstrapTest.cmake                          |    9 +-
 .../target_compile_features/CMakeLists.txt         |    2 +-
 Tests/CMakeLib/CMakeLists.txt                      |    3 +
 Tests/CMakeLib/run_compile_commands.cxx            |    4 +-
 Tests/CMakeLib/testEncoding.cxx                    |   49 +
 Tests/CMakeLib/testFindPackageCommand.cxx          |    6 +-
 Tests/CMakeLib/testSystemTools.cxx                 |    7 +-
 Tests/CMakeLib/testXMLSafe.cxx                     |    5 +-
 Tests/CMakeLists.txt                               |   38 +-
 Tests/CMakeOnly/CMakeLists.txt                     |    3 +
 Tests/CMakeOnly/CompilerIdCSharp/CMakeLists.txt    |   21 +
 Tests/CMakeTests/File-SHA3_224-Works.cmake         |    2 +
 Tests/CMakeTests/File-SHA3_256-Works.cmake         |    2 +
 Tests/CMakeTests/File-SHA3_384-Works.cmake         |    2 +
 Tests/CMakeTests/File-SHA3_512-Works.cmake         |    2 +
 Tests/CMakeTests/File-TIMESTAMP-NotBogus.cmake     |    1 +
 Tests/CMakeTests/FileTest.cmake.in                 |   12 +
 Tests/CMakeTests/ImplicitLinkInfoTest.cmake.in     |   13 +
 Tests/CMakeTests/String-SHA3_224-Works.cmake       |    2 +
 Tests/CMakeTests/String-SHA3_256-Works.cmake       |    2 +
 Tests/CMakeTests/String-SHA3_384-Works.cmake       |    2 +
 Tests/CMakeTests/String-SHA3_512-Works.cmake       |    2 +
 Tests/CMakeTests/StringTest.cmake.in               |   12 +
 .../RunCPackVerifyResult.cmake                     |    8 +-
 Tests/CSharpOnly/CMakeLists.txt                    |   10 +
 Tests/CSharpOnly/csharponly.cs                     |   15 +
 Tests/CSharpOnly/lib1.cs                           |   10 +
 Tests/CSharpOnly/lib2.cs                           |   10 +
 Tests/CTestTestChecksum/test.cmake.in              |    4 +-
 .../launcher_compiler_test_project/CMakeLists.txt  |    7 +
 .../CTestConfig.cmake                              |    0
 .../launcher_compiler_test_project/build_error.cxx |    5 +
 .../CMakeLists.txt                                 |   19 +
 .../CTestConfig.cmake                              |    0
 .../command.cmake                                  |    0
 .../launcher_linker_test_project/CMakeLists.txt    |    7 +
 .../CTestConfig.cmake                              |    0
 .../launcher_linker_test_project/link_error.cxx    |    6 +
 .../launcher_test_project/CMakeLists.txt           |   19 -
 Tests/CTestTestLaunchers/test.cmake.in             |   80 +-
 Tests/CTestTestStopTime/GetDate.cmake              |    1 +
 Tests/CompileFeatures/.gitattributes               |    2 +
 Tests/CompileFeatures/CMakeLists.txt               |   37 +-
 Tests/CompileFeatures/cxx_right_angle_brackets.cpp |    4 +-
 Tests/CompileFeatures/default_dialect.cpp          |    6 +-
 Tests/Cuda/.clang-format                           |    9 +
 Tests/Cuda/CMakeLists.txt                          |    7 +
 Tests/Cuda/Complex/CMakeLists.txt                  |   40 +
 Tests/Cuda/Complex/dynamic.cpp                     |   11 +
 Tests/Cuda/Complex/dynamic.cu                      |   30 +
 Tests/Cuda/Complex/file1.cu                        |   10 +
 Tests/Cuda/Complex/file1.h                         |    7 +
 Tests/Cuda/Complex/file2.cu                        |   16 +
 Tests/Cuda/Complex/file2.h                         |   10 +
 Tests/Cuda/Complex/file3.cu                        |   26 +
 Tests/Cuda/Complex/main.cpp                        |   20 +
 Tests/Cuda/Complex/mixed.cpp                       |   22 +
 Tests/Cuda/Complex/mixed.cu                        |   33 +
 Tests/Cuda/ConsumeCompileFeatures/CMakeLists.txt   |   17 +
 Tests/Cuda/ConsumeCompileFeatures/main.cu          |   20 +
 Tests/Cuda/ConsumeCompileFeatures/static.cpp       |   10 +
 Tests/Cuda/ConsumeCompileFeatures/static.cu        |    9 +
 Tests/Cuda/ObjectLibrary/CMakeLists.txt            |   12 +
 Tests/Cuda/ObjectLibrary/main.cpp                  |   20 +
 Tests/Cuda/ObjectLibrary/static.cpp                |    6 +
 Tests/Cuda/ObjectLibrary/static.cu                 |   21 +
 Tests/Cuda/ProperLinkFlags/CMakeLists.txt          |   20 +
 Tests/Cuda/ProperLinkFlags/file1.cu                |   11 +
 Tests/Cuda/ProperLinkFlags/file1.h                 |    7 +
 Tests/Cuda/ProperLinkFlags/main.cxx                |    9 +
 Tests/Cuda/ToolkitInclude/CMakeLists.txt           |   11 +
 Tests/Cuda/ToolkitInclude/main.cpp                 |    8 +
 Tests/Cuda/WithC/CMakeLists.txt                    |   12 +
 Tests/Cuda/WithC/cuda.cu                           |   16 +
 Tests/Cuda/WithC/main.c                            |   14 +
 Tests/CudaOnly/.clang-format                       |    9 +
 Tests/CudaOnly/CMakeLists.txt                      |    4 +
 Tests/CudaOnly/EnableStandard/CMakeLists.txt       |   26 +
 Tests/CudaOnly/EnableStandard/main.cu              |   23 +
 Tests/CudaOnly/EnableStandard/shared.cu            |   15 +
 Tests/CudaOnly/EnableStandard/static.cu            |    9 +
 Tests/CudaOnly/SeparateCompilation/CMakeLists.txt  |   33 +
 Tests/CudaOnly/SeparateCompilation/file1.cu        |   10 +
 Tests/CudaOnly/SeparateCompilation/file1.h         |    7 +
 Tests/CudaOnly/SeparateCompilation/file2.cu        |   16 +
 Tests/CudaOnly/SeparateCompilation/file2.h         |   10 +
 Tests/CudaOnly/SeparateCompilation/file3.cu        |   22 +
 Tests/CudaOnly/SeparateCompilation/file4.cu        |   23 +
 Tests/CudaOnly/SeparateCompilation/file5.cu        |   23 +
 Tests/CudaOnly/SeparateCompilation/main.cu         |   15 +
 Tests/CudaOnly/WithDefs/CMakeLists.txt             |   36 +
 Tests/CudaOnly/WithDefs/main.notcu                 |   53 +
 Tests/CustomCommand/CMakeLists.txt                 |   21 +
 Tests/CustomCommand/compare_options.cmake          |   14 +
 Tests/ExternalProject/CMakeLists.txt               |   17 +
 Tests/ExternalProjectLocal/CMakeLists.txt          |    1 +
 Tests/FindLibRHash/CMakeLists.txt                  |   10 +
 Tests/FindLibRHash/Test/CMakeLists.txt             |   17 +
 Tests/FindLibRHash/Test/main.c                     |    7 +
 Tests/FindOpenGL/CMakeLists.txt                    |   10 +
 Tests/FindOpenGL/Test/CMakeLists.txt               |   14 +
 Tests/FindOpenGL/Test/main.c                       |   17 +
 Tests/FindPackageModeMakefileTest/CMakeLists.txt   |   13 +-
 Tests/Framework/CMakeLists.txt                     |   47 +-
 Tests/GeneratorExpression/CMakeLists.txt           |   26 +-
 Tests/GeneratorExpression/check-part3.cmake        |   21 +-
 Tests/GeneratorExpression/check-part4.cmake        |    5 +
 Tests/GeneratorExpression/echo.c                   |    3 +
 Tests/IncludeDirectories/CMakeLists.txt            |    4 +-
 .../SystemIncludeDirectories/CMakeLists.txt        |   15 +-
 Tests/InterfaceLibrary/CMakeLists.txt              |   20 +-
 Tests/InterfaceLibrary/definetestexe.cpp           |    3 +-
 Tests/InterfaceLibrary/item.cpp                    |    4 +
 Tests/InterfaceLibrary/item_fake.cpp               |    5 +
 Tests/MacRuntimePath/A/CMakeLists.txt              |   15 +-
 Tests/MathTest/CMakeLists.txt                      |    3 +
 Tests/Module/ExternalData/CMakeLists.txt           |    2 +
 .../ExternalData/MultipleAlgorithmNoMD5.dat.md5    |    1 +
 .../ExternalData/MultipleAlgorithmNoMD5.dat.sha1   |    1 +
 .../ExternalData/MultipleAlgorithmNoSHA1.dat.md5   |    1 +
 .../ExternalData/MultipleAlgorithmNoSHA1.dat.sha1  |    1 +
 Tests/Module/ExternalData/SHA3_256/.gitattributes  |    1 +
 ...c7b45493750a3612ecc483095eb1366f9f46b179550e231 |    1 +
 .../Module/ExternalData/SeriesMixed.5.dat.sha3-256 |    1 +
 .../WriteCompilerDetectionHeader/CMakeLists.txt    |  154 +-
 Tests/ObjectLibrary/A/CMakeLists.txt               |    1 +
 Tests/PositionIndependentTargets/.gitattributes    |    2 +
 Tests/Preprocess/CMakeLists.txt                    |   14 +-
 Tests/QtAutoUicInterface/CMakeLists.txt            |    7 +-
 Tests/QtAutoUicInterface/libwidget.cpp             |    5 +
 Tests/QtAutoUicInterface/libwidget.h               |    3 +-
 Tests/QtAutoUicInterface/mywidget.cpp              |    5 +
 Tests/QtAutoUicInterface/mywidget.h                |    3 +-
 Tests/QtAutogen/Bdir/CMakeLists.txt                |   10 -
 Tests/QtAutogen/CMakeLists.txt                     |  192 +-
 Tests/QtAutogen/automoc_rerun/CMakeLists.txt       |    2 +-
 Tests/QtAutogen/autorcc_depends/CMakeLists.txt     |    2 +-
 Tests/QtAutogen/{ => complex}/Adir/CMakeLists.txt  |    0
 Tests/QtAutogen/{ => complex}/Adir/libA.cpp        |    0
 Tests/QtAutogen/{ => complex}/Adir/libA.h          |    0
 Tests/QtAutogen/complex/Bdir/CMakeLists.txt        |    9 +
 Tests/QtAutogen/{ => complex}/Bdir/libB.cpp        |    0
 Tests/QtAutogen/{ => complex}/Bdir/libB.h          |    0
 Tests/QtAutogen/complex/CMakeLists.txt             |   82 +
 Tests/QtAutogen/{ => complex}/abc.cpp              |    0
 Tests/QtAutogen/{ => complex}/abc.h                |    0
 Tests/QtAutogen/{ => complex}/abc_p.h              |    0
 Tests/QtAutogen/{ => complex}/bar.cpp              |    0
 Tests/QtAutogen/{ => complex}/blub.cpp             |    0
 Tests/QtAutogen/{ => complex}/blub.h               |    0
 Tests/QtAutogen/{ => complex}/calwidget.cpp        |    0
 Tests/QtAutogen/{ => complex}/calwidget.h          |    0
 Tests/QtAutogen/{ => complex}/calwidget.ui         |    0
 Tests/QtAutogen/{ => complex}/codeeditor.cpp       |    0
 Tests/QtAutogen/{ => complex}/codeeditor.h         |    0
 Tests/QtAutogen/{ => complex}/debug_class.cpp      |    0
 Tests/QtAutogen/{ => complex}/debug_class.h        |    0
 Tests/QtAutogen/{ => complex}/debug_class.ui       |    0
 Tests/QtAutogen/{ => complex}/debug_resource.qrc   |    0
 Tests/QtAutogen/{ => complex}/foo.cpp              |    0
 Tests/QtAutogen/{ => complex}/foo.h                |    0
 Tests/QtAutogen/{ => complex}/gadget.cpp           |    0
 Tests/QtAutogen/{ => complex}/gadget.h             |    0
 Tests/QtAutogen/{ => complex}/generated.cpp        |    0
 Tests/QtAutogen/{ => complex}/generated.h          |    0
 Tests/QtAutogen/{ => complex}/generated.txt.in     |    0
 .../{ => complex}/generated_resource.qrc.in        |    0
 Tests/QtAutogen/{ => complex}/libC.cpp             |    0
 Tests/QtAutogen/{ => complex}/libC.h               |    0
 Tests/QtAutogen/{ => complex}/main.cpp             |    0
 Tests/QtAutogen/{ => complex}/multiplewidgets.cpp  |    0
 Tests/QtAutogen/{ => complex}/multiplewidgets.h    |    0
 Tests/QtAutogen/{ => complex}/myinterface.h.in     |    0
 .../QtAutogen/{ => complex}/myotherinterface.h.in  |    0
 Tests/QtAutogen/{ => complex}/private_slot.cpp     |    0
 Tests/QtAutogen/{ => complex}/private_slot.h       |    0
 Tests/QtAutogen/{ => complex}/resourcetester.cpp   |    0
 Tests/QtAutogen/{ => complex}/resourcetester.h     |    0
 Tests/QtAutogen/{ => complex}/second_resource.qrc  |    0
 Tests/QtAutogen/{ => complex}/second_widget.cpp    |    0
 Tests/QtAutogen/{ => complex}/second_widget.h      |    0
 Tests/QtAutogen/{ => complex}/second_widget.ui     |    0
 Tests/QtAutogen/{ => complex}/sub/bar.h            |    0
 .../QtAutogen/{ => complex}/targetObjectsTest.cpp  |    0
 Tests/QtAutogen/{ => complex}/test.qrc             |    0
 Tests/QtAutogen/{ => complex}/widget1.ui           |    0
 Tests/QtAutogen/{ => complex}/widget2.ui           |    0
 Tests/QtAutogen/{ => complex}/xyz.cpp              |    0
 Tests/QtAutogen/{ => complex}/xyz.h                |    0
 Tests/QtAutogen/{ => complex}/yaf.cpp              |    0
 Tests/QtAutogen/{ => complex}/yaf.h                |    0
 Tests/QtAutogen/{ => complex}/yaf_p.h              |    0
 Tests/QtAutogen/defines_test/CMakeLists.txt        |    2 -
 Tests/QtAutogen/rccEmpty.cpp                       |    9 +
 .../{rcc_empty_resource.qrc => rccEmptyRes.qrc}    |    0
 Tests/QtAutogen/rccOnly.cpp                        |    9 +
 Tests/QtAutogen/rccOnlyRes.qrc                     |    5 +
 Tests/QtAutogen/rcc_empty.cpp                      |    9 -
 Tests/QtAutogen/rcconly.cpp                        |    9 -
 Tests/QtAutogen/sameName/CMakeLists.txt            |    3 +-
 Tests/QtAutogen/skipMoc.cpp                        |   14 +
 Tests/QtAutogen/skipRcc.cpp                        |    9 +
 Tests/QtAutogen/skipSource/qItemA.cpp              |    5 +
 Tests/QtAutogen/skipSource/qItemA.hpp              |   13 +
 Tests/QtAutogen/skipSource/qItemB.cpp              |    5 +
 Tests/QtAutogen/skipSource/qItemB.hpp              |   13 +
 Tests/QtAutogen/skipSource/qItemC.cpp              |    5 +
 Tests/QtAutogen/skipSource/qItemC.hpp              |   13 +
 Tests/QtAutogen/skipSource/skipRccBad1.qrc         |    5 +
 Tests/QtAutogen/skipSource/skipRccBad2.qrc         |    5 +
 Tests/QtAutogen/skipSource/skipRccGood.qrc         |    6 +
 Tests/QtAutogen/skipSource/skipUicGen.cpp          |    7 +
 Tests/QtAutogen/skipSource/skipUicGen.hpp          |    8 +
 Tests/QtAutogen/skipSource/skipUicNoGen1.cpp       |    7 +
 Tests/QtAutogen/skipSource/skipUicNoGen1.hpp       |    8 +
 Tests/QtAutogen/skipSource/skipUicNoGen2.cpp       |    7 +
 Tests/QtAutogen/skipSource/skipUicNoGen2.hpp       |    8 +
 Tests/QtAutogen/skipSource/ui_nogen1.h             |    6 +
 Tests/QtAutogen/skipSource/ui_nogen2.h             |    6 +
 Tests/QtAutogen/skipSource/uigen1.ui               |   24 +
 Tests/QtAutogen/skipSource/uigen2.ui               |   24 +
 Tests/QtAutogen/skipUic.cpp                        |   22 +
 Tests/QtAutogen/sub/uiconly.cpp                    |   13 -
 Tests/QtAutogen/sub/uiconly.h                      |   20 -
 Tests/QtAutogen/uicOnlySource/uiconly.cpp          |   18 +
 Tests/QtAutogen/uicOnlySource/uiconly.h            |   20 +
 Tests/QtAutogen/{sub => uicOnlySource}/uiconly.ui  |    0
 .../AndroidTestUtilities/RunCMakeTest.cmake        |    1 +
 .../RunCMake/AndroidTestUtilities/SetupTest4.cmake |   13 +
 .../SetupTest4Build-check.cmake                    |    5 +
 Tests/RunCMake/CMakeLists.txt                      |   31 +-
 Tests/RunCMake/CPack/7Z/Helpers.cmake              |    3 +
 Tests/RunCMake/CPack/7Z/Prerequirements.cmake      |    4 +
 .../packaging_COMPONENT_default.cmake}             |    0
 .../CPack/ArchiveCommon/common_helpers.cmake       |   62 +
 Tests/RunCMake/CPack/CMakeLists.txt                |   13 +-
 Tests/RunCMake/CPack/COMPONENTS_EMPTY_DIR.cmake    |    5 -
 Tests/RunCMake/CPack/CPackTestHelpers.cmake        |   51 +-
 Tests/RunCMake/CPack/CUSTOM_NAMES.cmake            |    7 -
 .../DEB/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake   |    5 -
 .../CPack/DEB/COMPONENTS_EMPTY_DIR-specifics.cmake |    3 -
 .../CPack/DEB/CUSTOM_NAMES-ExpectedFiles.cmake     |    9 -
 .../CPack/DEB/CUSTOM_NAMES-specifics.cmake         |    6 -
 .../CPack/DEB/DEB_EXTRA-ExpectedFiles.cmake        |    9 -
 .../DEB/DEB_GENERATE_SHLIBS-ExpectedFiles.cmake    |    6 -
 .../DEB/DEB_GENERATE_SHLIBS-Prerequirements.cmake  |    7 -
 ...EB_GENERATE_SHLIBS_LDCONFIG-ExpectedFiles.cmake |    6 -
 ..._GENERATE_SHLIBS_LDCONFIG-Prerequirements.cmake |    7 -
 .../CPack/DEB/DEPENDENCIES-ExpectedFiles.cmake     |   14 -
 .../CPack/DEB/DEPENDENCIES-VerifyResult.cmake      |   34 -
 .../CPack/DEB/DEPENDENCIES-specifics.cmake         |   23 -
 .../CPack/DEB/EMPTY_DIR-ExpectedFiles.cmake        |    5 -
 Tests/RunCMake/CPack/DEB/EMPTY_DIR-specifics.cmake |    2 -
 Tests/RunCMake/CPack/DEB/Helpers.cmake             |   43 +-
 .../CPack/DEB/LONG_FILENAMES-ExpectedFiles.cmake   |    5 -
 .../CPack/DEB/LONG_FILENAMES-Prerequirements.cmake |    7 -
 .../CPack/DEB/LONG_FILENAMES-specifics.cmake       |    3 -
 .../RunCMake/CPack/DEB/MINIMAL-ExpectedFiles.cmake |    5 -
 Tests/RunCMake/CPack/DEB/MINIMAL-specifics.cmake   |    2 -
 .../DEB/PER_COMPONENT_FIELDS-ExpectedFiles.cmake   |    9 -
 .../DEB/PER_COMPONENT_FIELDS-VerifyResult.cmake    |   18 -
 .../CPack/DEB/PER_COMPONENT_FIELDS-specifics.cmake |    7 -
 Tests/RunCMake/CPack/DEB/Prerequirements.cmake     |    7 +
 .../CPack/DEB/packaging_COMPONENT_default.cmake    |    2 +
 .../CPack/DEB/packaging_MONOLITHIC_default.cmake   |    1 +
 Tests/RunCMake/CPack/DEBUGINFO.cmake               |   34 -
 Tests/RunCMake/CPack/DEB_EXTRA.cmake               |   39 -
 Tests/RunCMake/CPack/DEB_GENERATE_SHLIBS.cmake     |   18 -
 .../CPack/DEB_GENERATE_SHLIBS_LDCONFIG.cmake       |   19 -
 Tests/RunCMake/CPack/DEPENDENCIES.cmake            |   20 -
 Tests/RunCMake/CPack/EMPTY_DIR.cmake               |    4 -
 Tests/RunCMake/CPack/INSTALL_SCRIPTS.cmake         |   26 -
 Tests/RunCMake/CPack/LONG_FILENAMES.cmake          |   10 -
 Tests/RunCMake/CPack/MINIMAL.cmake                 |    3 -
 Tests/RunCMake/CPack/PACKAGE_CHECKSUM.cmake        |    4 -
 .../CPack/PARTIALLY_RELOCATABLE_WARNING.cmake      |    6 -
 Tests/RunCMake/CPack/PER_COMPONENT_FIELDS.cmake    |    5 -
 Tests/RunCMake/CPack/README.txt                    |  179 +-
 .../RPM/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake   |    5 -
 .../CPack/RPM/COMPONENTS_EMPTY_DIR-stderr.txt      |    1 -
 .../CPack/RPM/CUSTOM_NAMES-ExpectedFiles.cmake     |    9 -
 .../CPack/RPM/CUSTOM_NAMES-specifics.cmake         |    5 -
 Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-stderr.txt   |    3 -
 .../CPack/RPM/DEBUGINFO-ExpectedFiles.cmake        |   14 -
 Tests/RunCMake/CPack/RPM/DEBUGINFO-stderr.txt      |    3 -
 .../CPack/RPM/DEPENDENCIES-ExpectedFiles.cmake     |   13 -
 .../CPack/RPM/DEPENDENCIES-VerifyResult.cmake      |   45 -
 .../CPack/RPM/DEPENDENCIES-specifics.cmake         |   22 -
 .../CPack/RPM/EMPTY_DIR-ExpectedFiles.cmake        |    5 -
 Tests/RunCMake/CPack/RPM/EMPTY_DIR-stderr.txt      |    1 -
 Tests/RunCMake/CPack/RPM/Helpers.cmake             |   57 +
 .../CPack/RPM/INSTALL_SCRIPTS-ExpectedFiles.cmake  |    7 -
 .../CPack/RPM/INSTALL_SCRIPTS-specifics.cmake      |   19 -
 .../RunCMake/CPack/RPM/MINIMAL-ExpectedFiles.cmake |    5 -
 Tests/RunCMake/CPack/RPM/MINIMAL-stderr.txt        |    1 -
 ...RTIALLY_RELOCATABLE_WARNING-ExpectedFiles.cmake |    5 -
 .../RPM/PER_COMPONENT_FIELDS-ExpectedFiles.cmake   |    9 -
 .../RPM/PER_COMPONENT_FIELDS-VerifyResult.cmake    |   18 -
 .../CPack/RPM/PER_COMPONENT_FIELDS-specifics.cmake |    5 -
 .../CPack/RPM/RPM_DIST-ExpectedFiles.cmake         |    5 -
 .../CPack/RPM/SOURCE_PACKAGE-ExpectedFiles.cmake   |    5 -
 .../CPack/RPM/SOURCE_PACKAGE-VerifyResult.cmake    |   63 -
 .../RunCMake/CPack/RPM/default_expected_stderr.txt |    1 +
 .../CPack/RPM/packaging_COMPONENT_default.cmake    |    1 +
 Tests/RunCMake/CPack/RPM_DIST.cmake                |    4 -
 Tests/RunCMake/CPack/RunCMakeTest.cmake            |   39 +-
 Tests/RunCMake/CPack/SOURCE_PACKAGE.cmake          |    9 -
 Tests/RunCMake/CPack/STGZ/Helpers.cmake            |   64 +
 Tests/RunCMake/CPack/STGZ/Prerequirements.cmake    |   11 +
 .../packaging_COMPONENT_default.cmake}             |    0
 Tests/RunCMake/CPack/TBZ2/Helpers.cmake            |    3 +
 Tests/RunCMake/CPack/TBZ2/Prerequirements.cmake    |    4 +
 .../packaging_COMPONENT_default.cmake}             |    0
 .../TGZ/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake   |    3 -
 .../CPack/TGZ/EMPTY_DIR-ExpectedFiles.cmake        |    3 -
 Tests/RunCMake/CPack/TGZ/Helpers.cmake             |   11 +-
 .../RunCMake/CPack/TGZ/MINIMAL-ExpectedFiles.cmake |    5 -
 .../CPack/TGZ/PACKAGE_CHECKSUM-ExpectedFiles.cmake |    9 -
 .../CPack/TGZ/PACKAGE_CHECKSUM-VerifyResult.cmake  |   14 -
 ...ics.cmake => packaging_COMPONENT_default.cmake} |    0
 Tests/RunCMake/CPack/TXZ/Helpers.cmake             |    3 +
 Tests/RunCMake/CPack/TXZ/Prerequirements.cmake     |    4 +
 .../packaging_COMPONENT_default.cmake}             |    0
 Tests/RunCMake/CPack/TZ/Helpers.cmake              |    3 +
 Tests/RunCMake/CPack/TZ/Prerequirements.cmake      |    4 +
 .../packaging_COMPONENT_default.cmake}             |    0
 Tests/RunCMake/CPack/VerifyResult.cmake            |   71 +-
 Tests/RunCMake/CPack/ZIP/Helpers.cmake             |    3 +
 Tests/RunCMake/CPack/ZIP/Prerequirements.cmake     |    4 +
 .../packaging_COMPONENT_default.cmake}             |    0
 .../CUSTOM_BINARY_SPEC_FILE/ExpectedFiles.cmake    |    9 +
 .../RPM-COMPONENT-stderr.txt                       |    2 +
 .../RPM-MONOLITHIC-stderr.txt                      |    1 +
 .../tests/CUSTOM_BINARY_SPEC_FILE/custom.spec.in   |   80 +
 .../CPack/tests/CUSTOM_BINARY_SPEC_FILE/test.cmake |    9 +
 .../CPack/tests/CUSTOM_NAMES/ExpectedFiles.cmake   |   12 +
 Tests/RunCMake/CPack/tests/CUSTOM_NAMES/test.cmake |   14 +
 .../CPack/tests/DEBUGINFO/ExpectedFiles.cmake      |   16 +
 Tests/RunCMake/CPack/tests/DEBUGINFO/test.cmake    |   30 +
 .../CPack/tests/DEPENDENCIES/DEB-stderr.txt        |    1 +
 .../CPack/tests/DEPENDENCIES/ExpectedFiles.cmake   |   18 +
 .../CPack/tests/DEPENDENCIES/VerifyResult.cmake    |   82 +
 Tests/RunCMake/CPack/tests/DEPENDENCIES/test.cmake |   60 +
 .../RunCMake/CPack/tests/DIST/ExpectedFiles.cmake  |    2 +
 .../DIST/VerifyResult.cmake}                       |    0
 Tests/RunCMake/CPack/tests/DIST/test.cmake         |    3 +
 .../CPack/tests/EMPTY_DIR/ExpectedFiles.cmake      |    7 +
 Tests/RunCMake/CPack/tests/EMPTY_DIR/test.cmake    |   14 +
 .../RunCMake/CPack/tests/EXTRA/ExpectedFiles.cmake |    8 +
 .../EXTRA/VerifyResult.cmake}                      |    0
 Tests/RunCMake/CPack/tests/EXTRA/test.cmake        |   35 +
 .../GENERATE_SHLIBS/DEB-Prerequirements.cmake      |    7 +
 .../tests/GENERATE_SHLIBS/ExpectedFiles.cmake      |    6 +
 .../GENERATE_SHLIBS/VerifyResult.cmake}            |    0
 .../CPack/tests/GENERATE_SHLIBS/test.cmake         |   14 +
 .../DEB-Prerequirements.cmake                      |    7 +
 .../GENERATE_SHLIBS_LDCONFIG/ExpectedFiles.cmake   |    6 +
 .../GENERATE_SHLIBS_LDCONFIG/VerifyResult.cmake}   |    0
 .../tests/GENERATE_SHLIBS_LDCONFIG/test.cmake      |   15 +
 .../tests/INSTALL_SCRIPTS/ExpectedFiles.cmake      |    5 +
 .../INSTALL_SCRIPTS/VerifyResult.cmake}            |    0
 .../CPack/tests/INSTALL_SCRIPTS/test.cmake         |   44 +
 .../tests/LONG_FILENAMES/DEB-Prerequirements.cmake |    7 +
 .../CPack/tests/LONG_FILENAMES/ExpectedFiles.cmake |    3 +
 .../LONG_FILENAMES/VerifyResult.cmake}             |    0
 .../RunCMake/CPack/tests/LONG_FILENAMES/test.cmake |   13 +
 .../CPack/tests/MAIN_COMPONENT/ExpectedFiles.cmake |   11 +
 .../tests/MAIN_COMPONENT/RPM-invalid-stderr.txt    |    1 +
 .../RunCMake/CPack/tests/MAIN_COMPONENT/test.cmake |   10 +
 .../CPack/tests/MD5SUMS/ExpectedFiles.cmake        |    2 +
 .../CPack/tests/MD5SUMS/VerifyResult.cmake         |    3 +
 Tests/RunCMake/CPack/tests/MD5SUMS/test.cmake      |    5 +
 .../CPack/tests/MINIMAL/ExpectedFiles.cmake        |    2 +
 Tests/RunCMake/CPack/tests/MINIMAL/test.cmake      |    5 +
 .../tests/PACKAGE_CHECKSUM/ExpectedFiles.cmake     |    6 +
 .../PACKAGE_CHECKSUM/TGZ-invalid-stderr.txt}       |    0
 .../tests/PACKAGE_CHECKSUM/VerifyResult.cmake      |   12 +
 .../CPack/tests/PACKAGE_CHECKSUM/test.cmake        |    3 +
 .../ExpectedFiles.cmake                            |    2 +
 .../PARTIALLY_RELOCATABLE_WARNING/RPM-stderr.txt}  |    0
 .../tests/PARTIALLY_RELOCATABLE_WARNING/test.cmake |    4 +
 .../tests/PER_COMPONENT_FIELDS/ExpectedFiles.cmake |    8 +
 .../tests/PER_COMPONENT_FIELDS/VerifyResult.cmake  |   26 +
 .../CPack/tests/PER_COMPONENT_FIELDS/test.cmake    |   18 +
 .../tests/SINGLE_DEBUGINFO/ExpectedFiles.cmake     |   30 +
 .../RPM-no_main_component-stderr.txt               |    1 +
 .../CPack/tests/SINGLE_DEBUGINFO/test.cmake        |   54 +
 .../CPack/tests/SOURCE_PACKAGE/ExpectedFiles.cmake |    2 +
 .../CPack/tests/SOURCE_PACKAGE/VerifyResult.cmake  |   67 +
 .../RunCMake/CPack/tests/SOURCE_PACKAGE/test.cmake |    7 +
 .../CPack/tests/SUGGESTS/ExpectedFiles.cmake       |    2 +
 Tests/RunCMake/CPack/tests/SUGGESTS/RPM-stderr.txt |    1 +
 .../CPack/tests/SUGGESTS/VerifyResult.cmake        |   31 +
 Tests/RunCMake/CPack/tests/SUGGESTS/test.cmake     |    3 +
 .../CPack/tests/USER_FILELIST/ExpectedFiles.cmake  |    2 +
 .../CPack/tests/USER_FILELIST/VerifyResult.cmake   |   12 +
 .../RunCMake/CPack/tests/USER_FILELIST/test.cmake  |   13 +
 Tests/RunCMake/CTestCommandLine/RunCMakeTest.cmake |    1 +
 .../CTestCommandLine/repeat-until-fail-cmake.cmake |    2 +
 Tests/RunCMake/ClangTidy/C-bad-Build-result.txt    |    1 +
 Tests/RunCMake/ClangTidy/C-bad-Build-stdout.txt    |    2 +
 Tests/RunCMake/ClangTidy/C-bad.cmake               |    3 +
 Tests/RunCMake/ClangTidy/RunCMakeTest.cmake        |    1 +
 .../CommandLine/E___run_iwyu-no-iwyu-stderr.txt    |    2 +-
 .../CommandLine/cmake_depends/.gitattributes       |    2 +
 .../LinkImplementationFeatureCycle.cmake           |    4 +-
 .../LinkImplementationFeatureCycleSolved.cmake     |    2 +-
 Tests/RunCMake/Configure/RemoveCache-stdout.txt    |    1 +
 Tests/RunCMake/Configure/RemoveCache.cmake         |   17 +
 Tests/RunCMake/Configure/RunCMakeTest.cmake        |    9 +
 Tests/RunCMake/Cpplint/C-Build-stdout.txt          |    1 +
 Tests/RunCMake/Cpplint/C-error-Build-result.txt    |    1 +
 Tests/RunCMake/Cpplint/C-error-Build-stdout.txt    |    1 +
 .../Cpplint/C-error-launch-Build-result.txt        |    1 +
 .../Cpplint/C-error-launch-Build-stdout.txt        |    1 +
 Tests/RunCMake/Cpplint/C-error-launch.cmake        |    3 +
 Tests/RunCMake/Cpplint/C-error.cmake               |    3 +
 Tests/RunCMake/Cpplint/C-launch-Build-stdout.txt   |    1 +
 Tests/RunCMake/Cpplint/C-launch.cmake              |    3 +
 Tests/RunCMake/Cpplint/C.cmake                     |    3 +
 Tests/RunCMake/Cpplint/CMakeLists.txt              |    3 +
 Tests/RunCMake/Cpplint/CXX-Build-stdout.txt        |    1 +
 Tests/RunCMake/Cpplint/CXX-error-Build-result.txt  |    1 +
 Tests/RunCMake/Cpplint/CXX-error-Build-stdout.txt  |    1 +
 .../Cpplint/CXX-error-launch-Build-result.txt      |    1 +
 .../Cpplint/CXX-error-launch-Build-stdout.txt      |    1 +
 Tests/RunCMake/Cpplint/CXX-error-launch.cmake      |    3 +
 Tests/RunCMake/Cpplint/CXX-error.cmake             |    3 +
 Tests/RunCMake/Cpplint/CXX-launch-Build-stdout.txt |    1 +
 Tests/RunCMake/Cpplint/CXX-launch.cmake            |    3 +
 Tests/RunCMake/Cpplint/CXX.cmake                   |    3 +
 Tests/RunCMake/Cpplint/RunCMakeTest.cmake          |   26 +
 Tests/RunCMake/Cpplint/main.c                      |    4 +
 Tests/RunCMake/Cpplint/main.cxx                    |    4 +
 .../CrosscompilingEmulator/AddCustomCommand.cmake  |   17 +-
 .../CrosscompilingEmulator/AddCustomTarget.cmake   |   16 +-
 .../generated_exe_emulator_unexpected.cxx          |    9 +
 .../simple_src_exitsuccess.cxx                     |    4 -
 .../FeatureSummaryCustomBadDefault-result.txt      |    1 +
 .../FeatureSummaryCustomBadDefault-stderr.txt      |    9 +
 .../FeatureSummaryCustomBadDefault.cmake           |    8 +
 .../FeatureSummaryCustomRequired-result.txt        |    1 +
 .../FeatureSummaryCustomRequired-stderr.txt        |    6 +
 .../FeatureSummaryCustomRequired-stdout.txt        |   17 +
 .../FeatureSummaryCustomRequired.cmake             |   16 +
 .../FeatureSummaryCustomRequiredListA-result.txt   |    1 +
 .../FeatureSummaryCustomRequiredListA-stderr.txt   |    6 +
 .../FeatureSummaryCustomRequiredListA-stdout.txt   |   17 +
 .../FeatureSummaryCustomRequiredListA.cmake        |   16 +
 .../FeatureSummaryCustomRequiredListB-result.txt   |    1 +
 .../FeatureSummaryCustomRequiredListB-stderr.txt   |    6 +
 .../FeatureSummaryCustomRequiredListB-stdout.txt   |   17 +
 .../FeatureSummaryCustomRequiredListB.cmake        |   16 +
 .../FeatureSummaryCustomTypes-stdout.txt           |   29 +
 .../FeatureSummary/FeatureSummaryCustomTypes.cmake |   36 +
 ...ummaryFatalOnMissingRequiredPackages-result.txt |    1 +
 ...ummaryFatalOnMissingRequiredPackages-stderr.txt |    6 +
 ...ummaryFatalOnMissingRequiredPackages-stdout.txt |   17 +
 ...tureSummaryFatalOnMissingRequiredPackages.cmake |   12 +
 .../FeatureSummaryIncludeQuietPackages-stdout.txt  |   14 +
 .../FeatureSummaryIncludeQuietPackages.cmake       |   11 +
 .../FeatureSummaryMultipleDepends-stdout.txt       |   10 +
 .../FeatureSummaryMultipleDepends.cmake            |   12 +
 .../FeatureSummaryPurpose-stdout.txt               |   16 +
 .../FeatureSummary/FeatureSummaryPurpose.cmake     |   16 +
 .../FeatureSummaryQuietOnEmpty-stdout.txt          |    5 +
 .../FeatureSummaryQuietOnEmpty.cmake               |   14 +
 .../FeatureSummary/FeatureSummaryTypes-stdout.txt  |   45 +
 .../FeatureSummary/FeatureSummaryTypes.cmake       |   48 +
 .../FeatureSummaryURLDescription-stdout.txt        |   32 +
 .../FeatureSummaryURLDescription.cmake             |   28 +
 .../FeatureSummaryWhatAll-stdout.txt               |    4 +-
 .../FeatureSummaryWhatList-stdout.txt              |    4 +-
 .../FeatureSummaryWhatOnce-stdout.txt              |    2 +-
 .../FeatureSummary/FeatureSummaryWhatOnce.cmake    |    4 +-
 .../FeatureSummaryWhatSingle-stdout.txt            |    2 +-
 Tests/RunCMake/FeatureSummary/FindBar.cmake        |    2 +
 Tests/RunCMake/FeatureSummary/FindBaz.cmake        |    2 +
 Tests/RunCMake/FeatureSummary/FindFoo.cmake        |    4 +
 Tests/RunCMake/FeatureSummary/RunCMakeTest.cmake   |   12 +
 Tests/RunCMake/FindGTK2/CMakeLists.txt             |    3 +
 Tests/RunCMake/FindGTK2/FindGTK2RunTwice.cmake     |   21 +
 Tests/RunCMake/FindGTK2/RunCMakeTest.cmake         |    3 +
 Tests/RunCMake/Framework/FrameworkLayout.cmake     |    5 +-
 .../Framework/FrameworkTypeSHARED-build-stdout.txt |    1 +
 .../Framework/FrameworkTypeSTATIC-build-stdout.txt |    1 +
 Tests/RunCMake/Framework/RunCMakeTest.cmake        |   69 +-
 .../GenerateExportHeader/reference/.gitattributes  |    2 +
 .../RunCMake/GeneratorExpression/BadIF-result.txt  |    1 +
 .../RunCMake/GeneratorExpression/BadIF-stderr.txt  |   15 +
 Tests/RunCMake/GeneratorExpression/BadIF.cmake     |    5 +
 .../GeneratorExpression/RunCMakeTest.cmake         |    1 +
 .../TARGET_PROPERTY-LOCATION-stderr.txt            |    4 +-
 .../GeneratorToolset/BadToolsetHostArch-result.txt |    1 +
 .../GeneratorToolset/BadToolsetHostArch-stderr.txt |   10 +
 .../GeneratorToolset/BadToolsetHostArch.cmake      |    1 +
 Tests/RunCMake/GeneratorToolset/RunCMakeTest.cmake |   15 +
 .../TestToolsetHostArchBoth-stdout.txt             |    2 +
 .../GeneratorToolset/TestToolsetHostArchBoth.cmake |    2 +
 .../TestToolsetHostArchNone-stdout.txt             |    2 +
 .../GeneratorToolset/TestToolsetHostArchNone.cmake |    2 +
 .../TestToolsetHostArchOnly-stdout.txt             |    2 +
 .../GeneratorToolset/TestToolsetHostArchOnly.cmake |    2 +
 Tests/RunCMake/Ninja/NinjaToolMissing-result.txt   |    1 +
 Tests/RunCMake/Ninja/NinjaToolMissing-stderr.txt   |    6 +
 .../RunCMake/Ninja/NinjaToolMissing.cmake          |    0
 Tests/RunCMake/Ninja/RunCMakeTest.cmake            |    6 +
 Tests/RunCMake/RunCMake.cmake                      |    4 +-
 Tests/RunCMake/RunCTest.cmake                      |    1 +
 Tests/RunCMake/RuntimePath/A.c                     |    4 +
 Tests/RunCMake/RuntimePath/CMakeLists.txt          |    3 +
 Tests/RunCMake/RuntimePath/RunCMakeTest.cmake      |   18 +
 Tests/RunCMake/RuntimePath/SymlinkImplicit.cmake   |   17 +
 .../RuntimePath/SymlinkImplicitCheck-result.txt    |    1 +
 .../RuntimePath/SymlinkImplicitCheck-stderr.txt    |   22 +
 .../RuntimePath/SymlinkImplicitCheck.cmake         |    2 +
 Tests/RunCMake/RuntimePath/main.c                  |    4 +
 Tests/RunCMake/VS10Project/RunCMakeTest.cmake      |    4 +
 .../VS10Project/VsCSharpCustomTags-check.cmake     |   23 +
 .../RunCMake/VS10Project/VsCSharpCustomTags.cmake  |   11 +
 .../RunCMake/VS10Project/VsCustomProps-check.cmake |   25 +
 Tests/RunCMake/VS10Project/VsCustomProps.cmake     |    7 +
 .../VS10Project/VsDebuggerWorkingDir-check.cmake   |   22 +
 .../VS10Project/VsDebuggerWorkingDir.cmake         |    5 +
 .../VsTargetsFileReferences-check.cmake            |   45 +
 .../VS10Project/VsTargetsFileReferences.cmake      |    9 +
 Tests/RunCMake/VS10Project/bar.cpp                 |    3 +
 Tests/RunCMake/VS10Project/baz.cpp                 |    3 +
 Tests/RunCMake/VS10Project/foo.cs                  |    3 +
 Tests/RunCMake/VS10Project/my.props                |    5 +
 .../VSSolution/AddPackageToDefault-check.cmake     |   29 +
 .../RunCMake/VSSolution/AddPackageToDefault.cmake  |    2 +
 Tests/RunCMake/VSSolution/RunCMakeTest.cmake       |    1 +
 .../PerConfigPerSourceFlags-result.txt             |    1 +
 .../PerConfigPerSourceFlags-stderr.txt             |    8 +
 .../XcodeProject/PerConfigPerSourceFlags.cmake     |    3 +
 Tests/RunCMake/XcodeProject/RunCMakeTest.cmake     |   23 +
 Tests/RunCMake/XcodeProject/XcodeBundles.cmake     |   52 +-
 .../RunCMake/XcodeProject/XcodeMultiplatform.cmake |   14 +
 .../add_dependencies/ReadOnlyProperty-result.txt   |    1 +
 .../add_dependencies/ReadOnlyProperty-stderr.txt   |    1 +
 .../add_dependencies/ReadOnlyProperty.cmake        |    6 +
 .../add_dependencies/RetrieveDependencies.cmake    |   16 +
 Tests/RunCMake/add_dependencies/RunCMakeTest.cmake |    2 +
 Tests/RunCMake/add_dependencies/a.c                |    3 +
 Tests/RunCMake/add_dependencies/b.c                |    3 +
 Tests/RunCMake/add_dependencies/c.c                |    3 +
 Tests/RunCMake/ctest_build/CMakeLists.txt.in       |    1 +
 Tests/RunCMake/ctest_build/RunCMakeTest.cmake      |    5 +
 Tests/RunCMake/ctest_build/test.cmake.in           |    1 +
 Tests/RunCMake/ctest_fixtures/CMakeLists.txt.in    |    6 +
 Tests/RunCMake/ctest_fixtures/RunCMakeTest.cmake   |    1 +
 Tests/RunCMake/ctest_fixtures/unused-stdout.txt    |    9 +
 .../DummyAddressLeakSanitizer-result.txt}          |    0
 .../DummyAddressLeakSanitizer-stderr.txt           |    1 +
 .../DummyAddressLeakSanitizer-stdout.txt           |    3 +
 .../DummyLeakSanitizerPrintDefects-result.txt}     |    0
 .../DummyLeakSanitizerPrintDefects-stderr.txt      |    1 +
 .../DummyLeakSanitizerPrintDefects-stdout.txt      |    3 +
 .../RunCMake/ctest_memcheck/DummyPurify-stdout.txt |    4 +-
 .../ctest_memcheck/DummyValgrind-stdout.txt        |    4 +-
 .../DummyValgrindCustomOptions-stdout.txt          |    4 +-
 .../DummyValgrindFailPost-stdout.txt               |    4 +-
 .../DummyValgrindIgnoreMemcheck-stdout.txt         |    4 +-
 .../DummyValgrindNoDefects-result.txt              |    1 +
 .../DummyValgrindNoDefects-stderr.txt              |    1 +
 .../DummyValgrindNoDefects-stdout.txt              |    8 +
 .../ctest_memcheck/DummyValgrindPrePost-stdout.txt |    4 +-
 Tests/RunCMake/ctest_memcheck/RunCMakeTest.cmake   |   56 +-
 Tests/RunCMake/ctest_memcheck/test.cmake.in        |    4 +-
 .../ctest_memcheck/testAddressLeakSanitizer.cmake  |   47 +
 .../ctest_memcheck/testAddressSanitizer.cmake      |    2 +-
 .../ctest_memcheck/testLeakSanitizer.cmake         |   20 +-
 .../ctest_memcheck/testMemorySanitizer.cmake       |    4 +-
 .../ctest_memcheck/testThreadSanitizer.cmake       |    4 +-
 .../testUndefinedBehaviorSanitizer.cmake           |    6 +-
 ...esult.txt => CDashUploadMissingFile-result.txt} |    0
 .../ctest_submit/CDashUploadMissingFile-stderr.txt |    1 +
 .../ctest_submit/CDashUploadRETRY_COUNT-stderr.txt |    2 -
 .../ctest_submit/CDashUploadRETRY_DELAY-stderr.txt |    2 -
 ...OUNT-result.txt => CDashUploadRetry-result.txt} |    0
 .../ctest_submit/CDashUploadRetry-stderr.txt       |    1 +
 .../ctest_submit/CDashUploadRetry-stdout.txt       |    4 +
 Tests/RunCMake/ctest_submit/RunCMakeTest.cmake     |    4 +-
 Tests/RunCMake/execute_process/CMakeLists.txt      |    3 +
 Tests/RunCMake/execute_process/Encoding.cmake      |    6 +
 .../execute_process/EncodingMissing-result.txt     |    1 +
 .../execute_process/EncodingMissing-stderr.txt     |    4 +
 .../RunCMake/execute_process/EncodingMissing.cmake |    1 +
 .../execute_process/EncodingUTF8-stderr.txt        |    1 +
 Tests/RunCMake/execute_process/RunCMakeTest.cmake  |    5 +
 .../file/GLOB-noexp-LIST_DIRECTORIES.cmake         |    1 +
 Tests/RunCMake/file/RunCMakeTest.cmake             |    1 +
 Tests/RunCMake/find_library/LibArchLink-stderr.txt |    2 +
 Tests/RunCMake/find_library/LibArchLink.cmake      |   24 +
 Tests/RunCMake/find_library/RunCMakeTest.cmake     |    3 +
 .../IMPORTED_LIBNAME-bad-value-result.txt          |    1 +
 .../IMPORTED_LIBNAME-bad-value-stderr.txt          |   44 +
 .../IMPORTED_LIBNAME-bad-value.cmake               |    6 +
 .../IMPORTED_LIBNAME-non-iface-result.txt          |    1 +
 .../IMPORTED_LIBNAME-non-iface-stderr.txt          |   45 +
 .../IMPORTED_LIBNAME-non-iface.cmake               |   17 +
 .../IMPORTED_LIBNAME-non-imported-result.txt       |    1 +
 .../IMPORTED_LIBNAME-non-imported-stderr.txt       |   21 +
 .../IMPORTED_LIBNAME-non-imported.cmake            |    5 +
 .../RunCMake/interface_library/RunCMakeTest.cmake  |    3 +
 Tests/RunCMake/pseudo_cpplint.c                    |   21 +
 Tests/RunCMake/pseudo_emulator_custom_command.c    |    3 +-
 Tests/RunCMake/pseudo_iwyu.c                       |    3 +-
 Tests/RunCMake/pseudo_tidy.c                       |    6 +
 Tests/RunCMake/set_property/RunCMakeTest.cmake     |    1 +
 Tests/RunCMake/set_property/TYPE-result.txt        |    1 +
 Tests/RunCMake/set_property/TYPE-stderr.txt        |    1 +
 Tests/RunCMake/set_property/TYPE.cmake             |    2 +
 Tests/RunCMake/string/RunCMakeTest.cmake           |    5 +
 Tests/RunCMake/string/Timestamp-result.txt         |    1 +
 Tests/RunCMake/string/Timestamp-stderr.txt         |    1 +
 Tests/RunCMake/string/Timestamp.cmake              |    3 +
 Tests/RunCMake/string/TimestampEmpty-result.txt    |    1 +
 Tests/RunCMake/string/TimestampEmpty-stderr.txt    |    1 +
 Tests/RunCMake/string/TimestampEmpty.cmake         |    3 +
 Tests/RunCMake/string/TimestampInvalid-result.txt  |    1 +
 Tests/RunCMake/string/TimestampInvalid-stderr.txt  |    1 +
 Tests/RunCMake/string/TimestampInvalid.cmake       |    3 +
 Tests/RunCMake/string/TimestampInvalid2-result.txt |    1 +
 Tests/RunCMake/string/TimestampInvalid2-stderr.txt |    1 +
 Tests/RunCMake/string/TimestampInvalid2.cmake      |    3 +
 Tests/RunCMake/try_compile/CMP0067-stderr.txt      |   25 +
 Tests/RunCMake/try_compile/CMP0067.cmake           |   40 +
 Tests/RunCMake/try_compile/CStandard-result.txt    |    1 +
 Tests/RunCMake/try_compile/CStandard-stderr.txt    |    7 +
 Tests/RunCMake/try_compile/CStandard.cmake         |    7 +
 Tests/RunCMake/try_compile/CStandardGNU.c          |   10 +
 Tests/RunCMake/try_compile/CStandardGNU.cmake      |   23 +
 .../RunCMake/try_compile/CStandardNoDefault.cmake  |    9 +
 Tests/RunCMake/try_compile/CudaStandard-result.txt |    1 +
 Tests/RunCMake/try_compile/CudaStandard-stderr.txt |    7 +
 Tests/RunCMake/try_compile/CudaStandard.cmake      |    7 +
 .../try_compile/CudaStandardNoDefault.cmake        |    9 +
 Tests/RunCMake/try_compile/CxxStandard-result.txt  |    1 +
 Tests/RunCMake/try_compile/CxxStandard-stderr.txt  |    7 +
 Tests/RunCMake/try_compile/CxxStandard.cmake       |    7 +
 Tests/RunCMake/try_compile/CxxStandardGNU.cmake    |   23 +
 Tests/RunCMake/try_compile/CxxStandardGNU.cxx      |   11 +
 .../try_compile/CxxStandardNoDefault.cmake         |    9 +
 Tests/RunCMake/try_compile/RunCMakeTest.cmake      |   26 +
 Tests/RunCMake/try_compile/WarnDeprecated.cmake    |   19 +
 Tests/RunCMake/try_compile/src.cu                  |    4 +
 Tests/RunCMake/try_compile/src.cxx                 |    4 +
 Tests/RunCMake/while/EndAlone-stderr.txt           |    2 +-
 Tests/Server/CMakeLists.txt                        |    1 +
 Tests/Server/cmakelib.pyc                          |  Bin 7552 -> 0 bytes
 Tests/SourceGroups/CMakeLists.txt                  |   13 +-
 Tests/SourceGroups/main.c                          |    7 +
 Tests/SourceGroups/sub1/tree_bar.c                 |    4 +
 Tests/SourceGroups/sub1/tree_baz.c                 |    4 +
 Tests/SourceGroups/sub1/tree_subdir/tree_foobar.c  |    4 +
 Tests/SourceGroups/tree_foo.c                      |    4 +
 Tests/SwiftMix/ObjCMain.m                          |    2 +-
 Tests/SwiftMix/SwiftMain.swift                     |    8 +-
 Tests/SwigTest/CMakeLists.txt                      |   13 +-
 Utilities/.gitattributes                           |    5 +
 Utilities/CMakeLists.txt                           |    2 +-
 Utilities/Git/pre-commit                           |   15 +-
 Utilities/GitSetup/.gitattributes                  |    5 +-
 Utilities/GitSetup/README                          |    7 +
 Utilities/GitSetup/config                          |    2 +-
 Utilities/GitSetup/config.sample                   |   10 +
 Utilities/GitSetup/git-gerrit-push                 |   74 +
 Utilities/GitSetup/git-gitlab-push                 |  177 +
 Utilities/GitSetup/setup-gerrit                    |   15 +-
 Utilities/GitSetup/setup-gitlab                    |  140 +
 Utilities/GitSetup/setup-hooks                     |    1 +
 Utilities/GitSetup/setup-stage                     |    9 +-
 Utilities/GitSetup/setup-upstream                  |  104 +
 Utilities/KWIML/test/CMakeLists.txt                |    2 +-
 Utilities/KWStyle/CMake.kws.xml.in                 |   11 -
 Utilities/KWStyle/CMakeFiles.txt.in                |   15 -
 Utilities/KWStyle/CMakeLists.txt                   |   69 -
 Utilities/KWStyle/CMakeMoreChecks.kws.xml.in       |   30 -
 Utilities/Release/README                           |    2 +-
 Utilities/Release/WiX/WIX.template.in              |   13 +-
 Utilities/Release/linux64_release.cmake            |    7 +-
 Utilities/Release/osx_release.cmake                |    2 +-
 Utilities/Release/upload_release.cmake             |    2 +-
 Utilities/Scripts/clang-format.bash                |   35 +-
 Utilities/Scripts/update-curl.bash                 |    2 +-
 Utilities/Scripts/update-gitsetup.bash             |   20 +
 Utilities/Scripts/update-kwsys.bash                |    2 +-
 Utilities/Scripts/update-librhash.bash             |   45 +
 Utilities/SetupForDevelopment.sh                   |    4 +
 Utilities/Sphinx/apply_qthelp_css_workaround.cmake |   14 +-
 Utilities/Sphinx/cmake.py                          |    8 +-
 Utilities/cmThirdParty.h.in                        |    1 +
 Utilities/cm_rhash.h                               |   14 +
 Utilities/cmcurl/CMake/CurlSymbolHiding.cmake      |   61 +
 Utilities/cmcurl/CMake/FindNGHTTP2.cmake           |   18 +
 Utilities/cmcurl/CMakeLists.txt                    |  100 +-
 Utilities/cmcurl/include/curl/curl.h               |   11 +-
 Utilities/cmcurl/include/curl/curlver.h            |    8 +-
 Utilities/cmcurl/lib/CMakeLists.txt                |    5 +
 Utilities/cmcurl/lib/Makefile.inc                  |    8 +-
 Utilities/cmcurl/lib/amigaos.c                     |    2 +-
 Utilities/cmcurl/lib/base64.c                      |    5 +
 Utilities/cmcurl/lib/conncache.c                   |    1 -
 Utilities/cmcurl/lib/connect.c                     |   33 +-
 Utilities/cmcurl/lib/connect.h                     |   40 +-
 Utilities/cmcurl/lib/cookie.c                      |  128 +-
 Utilities/cmcurl/lib/cookie.h                      |    4 +-
 Utilities/cmcurl/lib/curl_config.h.cmake           |    8 +-
 Utilities/cmcurl/lib/curl_ntlm_core.c              |   37 +-
 Utilities/cmcurl/lib/curl_sasl.c                   |   12 +-
 Utilities/cmcurl/lib/curl_setup.h                  |   24 +-
 Utilities/cmcurl/lib/curl_sspi.c                   |   20 +-
 Utilities/cmcurl/lib/curlx.h                       |   13 +-
 Utilities/cmcurl/lib/dict.c                        |   25 +-
 Utilities/cmcurl/lib/easy.c                        |   40 +-
 Utilities/cmcurl/lib/escape.c                      |   34 +-
 Utilities/cmcurl/lib/file.c                        |   11 +-
 Utilities/cmcurl/lib/formdata.c                    |   62 +-
 Utilities/cmcurl/lib/formdata.h                    |    1 +
 Utilities/cmcurl/lib/ftp.c                         |  107 +-
 Utilities/cmcurl/lib/ftp.h                         |    4 +-
 Utilities/cmcurl/lib/ftplistparser.c               |    3 +-
 Utilities/cmcurl/lib/getenv.c                      |    3 +-
 Utilities/cmcurl/lib/getinfo.c                     |   19 +-
 Utilities/cmcurl/lib/gopher.c                      |   37 +-
 Utilities/cmcurl/lib/hostcheck.c                   |   14 +-
 Utilities/cmcurl/lib/hostip.c                      |    7 +-
 Utilities/cmcurl/lib/http.c                        |  282 +-
 Utilities/cmcurl/lib/http.h                        |    1 +
 Utilities/cmcurl/lib/http2.c                       |  172 +-
 Utilities/cmcurl/lib/http2.h                       |    6 +-
 Utilities/cmcurl/lib/http_digest.c                 |    2 +-
 Utilities/cmcurl/lib/http_negotiate.c              |    1 -
 Utilities/cmcurl/lib/http_ntlm.c                   |    2 +-
 Utilities/cmcurl/lib/http_proxy.c                  |   18 +-
 Utilities/cmcurl/lib/if2ip.c                       |    8 +-
 Utilities/cmcurl/lib/imap.c                        |   25 +-
 Utilities/cmcurl/lib/krb5.c                        |   12 +-
 Utilities/cmcurl/lib/ldap.c                        |   59 +-
 Utilities/cmcurl/lib/libcurl.rc                    |    6 +-
 Utilities/cmcurl/lib/md5.c                         |    2 +-
 Utilities/cmcurl/lib/mprintf.c                     |   26 +-
 Utilities/cmcurl/lib/multi.c                       |  281 +-
 Utilities/cmcurl/lib/multiif.h                     |    1 +
 Utilities/cmcurl/lib/netrc.c                       |   18 +-
 Utilities/cmcurl/lib/parsedate.c                   |   20 +-
 Utilities/cmcurl/lib/pingpong.c                    |    3 +-
 Utilities/cmcurl/lib/pipeline.c                    |   12 +-
 Utilities/cmcurl/lib/pop3.c                        |   10 +-
 Utilities/cmcurl/lib/progress.c                    |   75 +
 Utilities/cmcurl/lib/progress.h                    |    6 +-
 Utilities/cmcurl/lib/rawstr.c                      |  148 -
 Utilities/cmcurl/lib/rawstr.h                      |   47 -
 Utilities/cmcurl/lib/rtsp.c                        |   22 +-
 Utilities/cmcurl/lib/security.c                    |   13 +-
 Utilities/cmcurl/lib/select.c                      |   35 +-
 Utilities/cmcurl/lib/select.h                      |    9 +-
 Utilities/cmcurl/lib/smb.c                         |   10 +-
 Utilities/cmcurl/lib/smtp.c                        |    8 +-
 Utilities/cmcurl/lib/socks.c                       |  132 +-
 Utilities/cmcurl/lib/ssh.c                         |   55 +-
 Utilities/cmcurl/lib/strcase.c                     |  166 +
 Utilities/cmcurl/lib/strcase.h                     |   50 +
 Utilities/cmcurl/lib/strdup.c                      |    4 +-
 Utilities/cmcurl/lib/strdup.h                      |    4 +-
 Utilities/cmcurl/lib/strequal.c                    |   79 -
 Utilities/cmcurl/lib/strequal.h                    |   31 -
 Utilities/cmcurl/lib/strerror.c                    |   87 +-
 Utilities/cmcurl/lib/strerror.h                    |    4 +-
 Utilities/cmcurl/lib/system_win32.c                |   39 +-
 Utilities/cmcurl/lib/telnet.c                      |   13 +-
 Utilities/cmcurl/lib/tftp.c                        |   31 +-
 Utilities/cmcurl/lib/transfer.c                    |  103 +-
 Utilities/cmcurl/lib/transfer.h                    |    8 +-
 Utilities/cmcurl/lib/url.c                         |  243 +-
 Utilities/cmcurl/lib/urldata.h                     |   15 +-
 Utilities/cmcurl/lib/vauth/cleartext.c             |    2 -
 Utilities/cmcurl/lib/vauth/digest.c                |   48 +-
 Utilities/cmcurl/lib/vauth/digest_sspi.c           |   25 +-
 Utilities/cmcurl/lib/vauth/krb5_gssapi.c           |   14 +
 Utilities/cmcurl/lib/vauth/krb5_sspi.c             |   22 +
 Utilities/cmcurl/lib/vauth/ntlm.c                  |   14 +
 Utilities/cmcurl/lib/vauth/ntlm_sspi.c             |   21 +
 Utilities/cmcurl/lib/vauth/spnego_gssapi.c         |   14 +
 Utilities/cmcurl/lib/vauth/spnego_sspi.c           |   26 +-
 Utilities/cmcurl/lib/vauth/vauth.c                 |   41 +
 Utilities/cmcurl/lib/vauth/vauth.h                 |   15 +
 Utilities/cmcurl/lib/version.c                     |   14 +-
 Utilities/cmcurl/lib/vtls/axtls.c                  |    3 +-
 Utilities/cmcurl/lib/vtls/cyassl.c                 |    9 +-
 Utilities/cmcurl/lib/vtls/darwinssl.c              |   24 +-
 Utilities/cmcurl/lib/vtls/gskit.c                  |   10 +-
 Utilities/cmcurl/lib/vtls/gtls.c                   |   12 +-
 Utilities/cmcurl/lib/vtls/mbedtls.c                |   14 +-
 Utilities/cmcurl/lib/vtls/nss.c                    |   68 +-
 Utilities/cmcurl/lib/vtls/openssl.c                |  108 +-
 Utilities/cmcurl/lib/vtls/polarssl.c               |   80 +-
 Utilities/cmcurl/lib/vtls/polarssl_threadlock.c    |    4 +-
 Utilities/cmcurl/lib/vtls/schannel.c               |   40 +-
 Utilities/cmcurl/lib/vtls/vtls.c                   |   18 +-
 Utilities/cmcurl/lib/x509asn1.c                    |   12 +-
 Utilities/cmlibarchive/libarchive/archive_random.c |    2 +-
 .../libarchive/archive_read_support_format_zip.c   |   36 +-
 Utilities/cmlibrhash/.gitattributes                |    1 +
 Utilities/cmlibrhash/CMakeLists.txt                |   40 +
 Utilities/cmlibrhash/COPYING                       |   15 +
 Utilities/cmlibrhash/README                        |    7 +
 Utilities/cmlibrhash/librhash/algorithms.c         |  220 +
 Utilities/cmlibrhash/librhash/algorithms.h         |  120 +
 Utilities/cmlibrhash/librhash/byte_order.c         |  150 +
 Utilities/cmlibrhash/librhash/byte_order.h         |  156 +
 Utilities/cmlibrhash/librhash/hex.c                |  188 +
 Utilities/cmlibrhash/librhash/hex.h                |   25 +
 Utilities/cmlibrhash/librhash/md5.c                |  236 ++
 Utilities/cmlibrhash/librhash/md5.h                |   31 +
 Utilities/cmlibrhash/librhash/rhash.c              |  872 ++++
 Utilities/cmlibrhash/librhash/rhash.h              |  288 ++
 Utilities/cmlibrhash/librhash/sha1.c               |  196 +
 Utilities/cmlibrhash/librhash/sha1.h               |   31 +
 Utilities/cmlibrhash/librhash/sha256.c             |  241 ++
 Utilities/cmlibrhash/librhash/sha256.h             |   32 +
 Utilities/cmlibrhash/librhash/sha3.c               |  356 ++
 Utilities/cmlibrhash/librhash/sha3.h               |   54 +
 Utilities/cmlibrhash/librhash/sha512.c             |  255 ++
 Utilities/cmlibrhash/librhash/sha512.h             |   32 +
 Utilities/cmlibrhash/librhash/ustd.h               |   39 +
 Utilities/cmlibrhash/librhash/util.h               |   31 +
 Utilities/cmlibuv/CMakeLists.txt                   |   10 +-
 Utilities/cmvssetup/.gitattributes                 |    1 +
 Utilities/cmvssetup/Setup.Configuration.h          |  991 +++++
 bootstrap                                          |  196 +-
 1807 files changed, 52993 insertions(+), 33513 deletions(-)

diff --git a/.gitattributes b/.gitattributes
index d959918..3829160 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,6 +1,13 @@
 .gitattributes   export-ignore
 .hooks*          export-ignore
 
+# Custom attribute to mark sources as using our C code style.
+[attr]our-c-style  whitespace=tab-in-indent  format.clang-format
+
+# Custom attribute to mark sources as generated.
+# Do not perform whitespace checks.  Do not format.
+[attr]generated  whitespace=-tab-in-indent,-indent-with-non-tab -format.clang-format
+
 bootstrap        crlf=input
 configure        crlf=input
 *.[1-9]          crlf=input
@@ -16,10 +23,17 @@ configure        crlf=input
 *.sln           -crlf
 *.vcproj        -crlf
 
-*.c              whitespace=tab-in-indent
-*.h              whitespace=tab-in-indent
-*.cxx            whitespace=tab-in-indent
-*.txt            whitespace=tab-in-indent
-*.cmake          whitespace=tab-in-indent
+*.c              our-c-style
+*.cc             our-c-style
+*.cpp            our-c-style
+*.cu             our-c-style
+*.cxx            our-c-style
+*.h              our-c-style
+*.hh             our-c-style
+*.hpp            our-c-style
+*.hxx            our-c-style
+*.notcu          our-c-style
 
+*.cmake          whitespace=tab-in-indent
 *.rst            whitespace=tab-in-indent conflict-marker-size=79
+*.txt            whitespace=tab-in-indent
diff --git a/.hooks-config b/.hooks-config
new file mode 100644
index 0000000..064371c
--- /dev/null
+++ b/.hooks-config
@@ -0,0 +1,10 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# Loaded by .git/hooks/(pre-commit|commit-msg|prepare-commit-msg)
+# during git commit after local hooks have been installed.
+
+[hooks "chain"]
+	pre-commit = Utilities/Git/pre-commit
+	commit-msg = Utilities/Git/commit-msg
+	prepare-commit-msg = Utilities/Git/prepare-commit-msg
diff --git a/.hooks-config.bash b/.hooks-config.bash
deleted file mode 100644
index ea9342a..0000000
--- a/.hooks-config.bash
+++ /dev/null
@@ -1,9 +0,0 @@
-# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-# file Copyright.txt or https://cmake.org/licensing for details.
-
-# Loaded by .git/hooks/(pre-commit|commit-msg|prepare-commit-msg)
-# during git commit after local hooks have been installed.
-
-hooks_chain_pre_commit="Utilities/Git/pre-commit"
-hooks_chain_commit_msg="Utilities/Git/commit-msg"
-hooks_chain_prepare_commit_msg="Utilities/Git/prepare-commit-msg"
diff --git a/Auxiliary/CMakeLists.txt b/Auxiliary/CMakeLists.txt
index 8eb74b7..53cf2c5 100644
--- a/Auxiliary/CMakeLists.txt
+++ b/Auxiliary/CMakeLists.txt
@@ -1,4 +1,4 @@
 install(DIRECTORY vim/indent vim/syntax DESTINATION ${CMAKE_DATA_DIR}/editors/vim)
 install(FILES cmake-mode.el DESTINATION ${CMAKE_DATA_DIR}/editors/emacs)
-install(FILES cmake.m4 DESTINATION share/aclocal)
+install(FILES cmake.m4 DESTINATION ${CMAKE_XDGDATA_DIR}/aclocal)
 add_subdirectory (bash-completion)
diff --git a/Auxiliary/vim/syntax/cmake.vim b/Auxiliary/vim/syntax/cmake.vim
index 11b0fcb..1f19cb7 100644
--- a/Auxiliary/vim/syntax/cmake.vim
+++ b/Auxiliary/vim/syntax/cmake.vim
@@ -32,11 +32,11 @@ syn region cmakeArguments start=/(/ end=/)/
 
 syn case match
 syn keyword cmakeProperty
-            \ ABSTRACT ADDITIONAL_MAKE_CLEAN_FILES ADVANCED ALIASED_TARGET ALLOW_DUPLICATE_CUSTOM_TARGETS ANDROID_ANT_ADDITIONAL_OPTIONS ANDROID_API ANDROID_API_MIN ANDROID_ARCH ANDROID_ASSETS_DIRECTORIES ANDROID_GUI ANDROID_JAR_DEPENDENCIES ANDROID_JAR_DIRECTORIES ANDROID_JAVA_SOURCE_DIR ANDROID_NATIVE_LIB_DEPENDENCIES ANDROID_NATIVE_LIB_DIRECTORIES ANDROID_PROCESS_MAX ANDROID_PROGUARD ANDROID_PROGUARD_CONFIG_PATH ANDROID_SECURE_PROPS_PATH ANDROID_SKIP_ANT_STEP ANDROID_STL_TYPE ARCHIVE_ [...]
+            \ ABSTRACT ADDITIONAL_MAKE_CLEAN_FILES ADVANCED ALIASED_TARGET ALLOW_DUPLICATE_CUSTOM_TARGETS ANDROID_ANT_ADDITIONAL_OPTIONS ANDROID_API ANDROID_API_MIN ANDROID_ARCH ANDROID_ASSETS_DIRECTORIES ANDROID_GUI ANDROID_JAR_DEPENDENCIES ANDROID_JAR_DIRECTORIES ANDROID_JAVA_SOURCE_DIR ANDROID_NATIVE_LIB_DEPENDENCIES ANDROID_NATIVE_LIB_DIRECTORIES ANDROID_PROCESS_MAX ANDROID_PROGUARD ANDROID_PROGUARD_CONFIG_PATH ANDROID_SECURE_PROPS_PATH ANDROID_SKIP_ANT_STEP ANDROID_STL_TYPE ARCHIVE_ [...]
             \ contained
 
 syn keyword cmakeVariable
-            \ <PROJECT-NAME>_BINARY_DIR <PROJECT-NAME>_SOURCE_DIR <PROJECT-NAME>_VERSION <PROJECT-NAME>_VERSION_MAJOR <PROJECT-NAME>_VERSION_MINOR <PROJECT-NAME>_VERSION_PATCH <PROJECT-NAME>_VERSION_TWEAK APPLE BORLAND BUILD_SHARED_LIBS CMAKE_<CONFIG>_POSTFIX CMAKE_<LANG>_ARCHIVE_APPEND CMAKE_<LANG>_ARCHIVE_CREATE CMAKE_<LANG>_ARCHIVE_FINISH CMAKE_<LANG>_COMPILER CMAKE_<LANG>_COMPILER_ABI CMAKE_<LANG>_COMPILER_EXTERNAL_TOOLCHAIN CMAKE_<LANG>_COMPILER_ID CMAKE_<LANG>_COMPILER_LAUNCHER CMA [...]
+            \ <PROJECT-NAME>_BINARY_DIR <PROJECT-NAME>_SOURCE_DIR <PROJECT-NAME>_VERSION <PROJECT-NAME>_VERSION_MAJOR <PROJECT-NAME>_VERSION_MINOR <PROJECT-NAME>_VERSION_PATCH <PROJECT-NAME>_VERSION_TWEAK APPLE BORLAND BUILD_SHARED_LIBS CMAKE_<CONFIG>_POSTFIX CMAKE_<LANG>_ARCHIVE_APPEND CMAKE_<LANG>_ARCHIVE_CREATE CMAKE_<LANG>_ARCHIVE_FINISH CMAKE_<LANG>_COMPILER CMAKE_<LANG>_COMPILER_ABI CMAKE_<LANG>_COMPILER_EXTERNAL_TOOLCHAIN CMAKE_<LANG>_COMPILER_ID CMAKE_<LANG>_COMPILER_LAUNCHER CMA [...]
             \ contained
 
 syn keyword cmakeModule
@@ -128,7 +128,7 @@ syn keyword cmakeKWctest_coverage
             \ contained
 
 syn keyword cmakeKWctest_memcheck
-            \ APPEND BUILD END EXCLUDE EXCLUDE_LABEL INCLUDE INCLUDE_LABEL OFF ON PARALLEL_LEVEL QUIET RETURN_VALUE SCHEDULE_RANDOM START STOP_TIME STRIDE TEST_LOAD
+            \ APPEND BUILD DEFECT_COUNT END EXCLUDE EXCLUDE_LABEL INCLUDE INCLUDE_LABEL OFF ON PARALLEL_LEVEL QUIET RETURN_VALUE SCHEDULE_RANDOM START STOP_TIME STRIDE TEST_LOAD
             \ contained
 
 syn keyword cmakeKWctest_run_script
diff --git a/CMakeCPack.cmake b/CMakeCPack.cmake
index 1889be2..a0aacb4 100644
--- a/CMakeCPack.cmake
+++ b/CMakeCPack.cmake
@@ -1,205 +1,249 @@
 # Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
 # file Copyright.txt or https://cmake.org/licensing for details.
 
-# If the cmake version includes cpack, use it
-if(EXISTS "${CMAKE_ROOT}/Modules/CPack.cmake")
-  if(EXISTS "${CMAKE_ROOT}/Modules/InstallRequiredSystemLibraries.cmake")
-    option(CMAKE_INSTALL_DEBUG_LIBRARIES
-      "Install Microsoft runtime debug libraries with CMake." FALSE)
-    mark_as_advanced(CMAKE_INSTALL_DEBUG_LIBRARIES)
-
-    # By default, do not warn when built on machines using only VS Express:
-    if(NOT DEFINED CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS)
-      set(CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS ON)
-    endif()
+option(CMAKE_INSTALL_DEBUG_LIBRARIES
+  "Install Microsoft runtime debug libraries with CMake." FALSE)
+mark_as_advanced(CMAKE_INSTALL_DEBUG_LIBRARIES)
 
-    if(CMake_INSTALL_DEPENDENCIES)
-      include(${CMake_SOURCE_DIR}/Modules/InstallRequiredSystemLibraries.cmake)
-    endif()
-  endif()
+# By default, do not warn when built on machines using only VS Express:
+if(NOT DEFINED CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS)
+  set(CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS ON)
+endif()
 
-  set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "CMake is a build tool")
-  set(CPACK_PACKAGE_VENDOR "Kitware")
-  set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/Copyright.txt")
-  set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/Copyright.txt")
-  set(CPACK_PACKAGE_NAME "${CMAKE_PROJECT_NAME}")
-  set(CPACK_PACKAGE_VERSION "${CMake_VERSION}")
-  set(CPACK_PACKAGE_INSTALL_DIRECTORY "${CPACK_PACKAGE_NAME}")
-  set(CPACK_SOURCE_PACKAGE_FILE_NAME "cmake-${CMake_VERSION}")
+if(CMake_INSTALL_DEPENDENCIES)
+  include(${CMake_SOURCE_DIR}/Modules/InstallRequiredSystemLibraries.cmake)
+endif()
 
-  # Installers for 32- vs. 64-bit CMake:
-  #  - Root install directory (displayed to end user at installer-run time)
-  #  - "NSIS package/display name" (text used in the installer GUI)
-  #  - Registry key used to store info about the installation
-  if(CMAKE_CL_64)
-    set(CPACK_NSIS_INSTALL_ROOT "$PROGRAMFILES64")
-    set(CPACK_NSIS_PACKAGE_NAME "${CPACK_PACKAGE_NAME} ${CPACK_PACKAGE_VERSION} (Win64)")
+set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "CMake is a build tool")
+set(CPACK_PACKAGE_VENDOR "Kitware")
+set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/Copyright.txt")
+set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/Copyright.txt")
+set(CPACK_PACKAGE_NAME "${CMAKE_PROJECT_NAME}")
+set(CPACK_PACKAGE_VERSION "${CMake_VERSION}")
+set(CPACK_PACKAGE_INSTALL_DIRECTORY "${CPACK_PACKAGE_NAME}")
+set(CPACK_SOURCE_PACKAGE_FILE_NAME "cmake-${CMake_VERSION}")
+
+# Installers for 32- vs. 64-bit CMake:
+#  - Root install directory (displayed to end user at installer-run time)
+#  - "NSIS package/display name" (text used in the installer GUI)
+#  - Registry key used to store info about the installation
+if(CMAKE_CL_64)
+  set(CPACK_NSIS_INSTALL_ROOT "$PROGRAMFILES64")
+  set(CPACK_NSIS_PACKAGE_NAME "${CPACK_PACKAGE_NAME} ${CPACK_PACKAGE_VERSION} (Win64)")
+else()
+  set(CPACK_NSIS_INSTALL_ROOT "$PROGRAMFILES")
+  set(CPACK_NSIS_PACKAGE_NAME "${CPACK_PACKAGE_NAME} ${CPACK_PACKAGE_VERSION}")
+endif()
+set(CPACK_PACKAGE_INSTALL_REGISTRY_KEY "${CPACK_NSIS_PACKAGE_NAME}")
+
+if(NOT DEFINED CPACK_SYSTEM_NAME)
+  # make sure package is not Cygwin-unknown, for Cygwin just
+  # cygwin is good for the system name
+  if("x${CMAKE_SYSTEM_NAME}" STREQUAL "xCYGWIN")
+    set(CPACK_SYSTEM_NAME Cygwin)
   else()
-    set(CPACK_NSIS_INSTALL_ROOT "$PROGRAMFILES")
-    set(CPACK_NSIS_PACKAGE_NAME "${CPACK_PACKAGE_NAME} ${CPACK_PACKAGE_VERSION}")
-  endif()
-  set(CPACK_PACKAGE_INSTALL_REGISTRY_KEY "${CPACK_NSIS_PACKAGE_NAME}")
-
-  if(NOT DEFINED CPACK_SYSTEM_NAME)
-    # make sure package is not Cygwin-unknown, for Cygwin just
-    # cygwin is good for the system name
-    if("x${CMAKE_SYSTEM_NAME}" STREQUAL "xCYGWIN")
-      set(CPACK_SYSTEM_NAME Cygwin)
-    else()
-      set(CPACK_SYSTEM_NAME ${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR})
-    endif()
+    set(CPACK_SYSTEM_NAME ${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR})
   endif()
-  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(${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()
 
-  # Components
-  if(CMake_INSTALL_COMPONENTS)
-    set(_CPACK_IFW_COMPONENTS_ALL cmake ctest cpack)
-    if(WIN32 AND NOT CYGWIN)
-        list(APPEND _CPACK_IFW_COMPONENTS_ALL cmcldeps)
-    endif()
-    if(APPLE)
-      list(APPEND _CPACK_IFW_COMPONENTS_ALL cmakexbuild)
-    endif()
-    if(CMAKE_INSTALL_DEFAULT_COMPONENT_NAME)
-      set(_CPACK_IFW_COMPONENT_UNSPECIFIED_NAME
-        ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME})
-    else()
-      set(_CPACK_IFW_COMPONENT_UNSPECIFIED_NAME Unspecified)
-    endif()
-    list(APPEND _CPACK_IFW_COMPONENTS_ALL ${_CPACK_IFW_COMPONENT_UNSPECIFIED_NAME})
-    string(TOUPPER "${_CPACK_IFW_COMPONENT_UNSPECIFIED_NAME}"
-      _CPACK_IFW_COMPONENT_UNSPECIFIED_UNAME)
-    if(BUILD_CursesDialog)
-      list(APPEND _CPACK_IFW_COMPONENTS_ALL ccmake)
-    endif()
-    if(BUILD_QtDialog)
-      list(APPEND _CPACK_IFW_COMPONENTS_ALL cmake-gui)
-      if(USE_LGPL)
-        set(_CPACK_IFW_COMPONENT_CMAKE-GUI_LICENSES "set(CPACK_IFW_COMPONENT_CMAKE-GUI_LICENSES
-    \"LGPLv${USE_LGPL}\" \"${CMake_SOURCE_DIR}/Licenses/LGPLv${USE_LGPL}.txt\")")
-      endif()
-    endif()
-    if(SPHINX_MAN)
-      list(APPEND _CPACK_IFW_COMPONENTS_ALL sphinx-man)
-    endif()
-    if(SPHINX_HTML)
-      list(APPEND _CPACK_IFW_COMPONENTS_ALL sphinx-html)
-    endif()
-    if(SPHINX_SINGLEHTML)
-      list(APPEND _CPACK_IFW_COMPONENTS_ALL sphinx-singlehtml)
+# Command for configure IFW script templates
+include(${CMake_SOURCE_DIR}/Modules/CPackIFWConfigureFile.cmake)
+
+# Advanced IFW configuration
+set(_cpifwrc CPACK_IFW_COMPONENT_GROUP_CMAKE_)
+set(_cpifwrcconf _CPACK_IFW_COMPONENT_GROUP_CMAKE)
+set(${_cpifwrcconf} "# CMake IFW configuration\n")
+macro(_cmifwarg DESCRIPTION TYPE NAME DEFAULT)
+  set(_var CMake_IFW_ROOT_COMPONENT_${NAME})
+  if(DEFINED ${_var})
+    set(${_var} ${${_var}} CACHE ${TYPE} ${DESCRIPTION})
+    mark_as_advanced(${_var})
+  elseif(NOT "${DEFAULT}" STREQUAL "")
+    set(${_var} ${DEFAULT})
+  endif()
+  if(DEFINED ${_var})
+    set(${_cpifwrcconf}
+      "${${_cpifwrcconf}}  set(${_cpifwrc}${NAME}\n    \"${${_var}}\")\n")
+  endif()
+endmacro()
+
+_cmifwarg("Package <Name> tag (domen-like)"
+  STRING NAME "")
+_cmifwarg("Package <DisplayName> tag"
+  STRING DISPLAY_NAME "")
+_cmifwarg("Package <Description> tag"
+  STRING DESCRIPTION "")
+_cmifwarg("Package <ReleaseDate> tag (keep empty to auto generate)"
+  STRING RELEASE_DATE "")
+_cmifwarg("Package <Default> tag (values: TRUE, FALSE, SCRIPT)"
+  STRING DEFAULT "")
+_cmifwarg("Package <Version> tag"
+  STRING VERSION
+  "${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}.${CMake_VERSION_PATCH}")
+_cmifwarg("Package <SortingPriority> tag"
+  STRING PRIORITY "100")
+_cmifwarg("Package <ForsedInstallation> tag"
+  STRING FORCED_INSTALLATION "")
+
+set(${_cpifwrc}LICENSES_DEFAULT
+  "${CPACK_PACKAGE_NAME} Copyright;${CPACK_RESOURCE_FILE_LICENSE}")
+
+# Components
+if(CMake_INSTALL_COMPONENTS)
+  set(_CPACK_IFW_COMPONENTS_ALL cmake ctest cpack)
+  if(WIN32 AND NOT CYGWIN)
+      list(APPEND _CPACK_IFW_COMPONENTS_ALL cmcldeps)
+  endif()
+  if(APPLE)
+    list(APPEND _CPACK_IFW_COMPONENTS_ALL cmakexbuild)
+  endif()
+  if(CMAKE_INSTALL_DEFAULT_COMPONENT_NAME)
+    set(_CPACK_IFW_COMPONENT_UNSPECIFIED_NAME
+      ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME})
+  else()
+    set(_CPACK_IFW_COMPONENT_UNSPECIFIED_NAME Unspecified)
+  endif()
+  list(APPEND _CPACK_IFW_COMPONENTS_ALL ${_CPACK_IFW_COMPONENT_UNSPECIFIED_NAME})
+  string(TOUPPER "${_CPACK_IFW_COMPONENT_UNSPECIFIED_NAME}"
+    _CPACK_IFW_COMPONENT_UNSPECIFIED_UNAME)
+  if(BUILD_CursesDialog)
+    list(APPEND _CPACK_IFW_COMPONENTS_ALL ccmake)
+  endif()
+  if(BUILD_QtDialog)
+    list(APPEND _CPACK_IFW_COMPONENTS_ALL cmake-gui)
+    if(USE_LGPL)
+      set(_CPACK_IFW_COMPONENT_CMAKE-GUI_LICENSES "set(CPACK_IFW_COMPONENT_CMAKE-GUI_LICENSES
+  \"LGPLv${USE_LGPL}\" \"${CMake_SOURCE_DIR}/Licenses/LGPLv${USE_LGPL}.txt\")")
     endif()
-    if(SPHINX_QTHELP)
-      list(APPEND _CPACK_IFW_COMPONENTS_ALL sphinx-qthelp)
+  endif()
+  if(SPHINX_MAN)
+    list(APPEND _CPACK_IFW_COMPONENTS_ALL sphinx-man)
+  endif()
+  if(SPHINX_HTML)
+    list(APPEND _CPACK_IFW_COMPONENTS_ALL sphinx-html)
+  endif()
+  if(SPHINX_SINGLEHTML)
+    list(APPEND _CPACK_IFW_COMPONENTS_ALL sphinx-singlehtml)
+  endif()
+  if(SPHINX_QTHELP)
+    list(APPEND _CPACK_IFW_COMPONENTS_ALL sphinx-qthelp)
+  endif()
+  if(CMake_BUILD_DEVELOPER_REFERENCE)
+    if(CMake_BUILD_DEVELOPER_REFERENCE_HTML)
+      list(APPEND _CPACK_IFW_COMPONENTS_ALL cmake-developer-reference-html)
     endif()
-    if(CMake_BUILD_DEVELOPER_REFERENCE)
-      if(CMake_BUILD_DEVELOPER_REFERENCE_HTML)
-        list(APPEND _CPACK_IFW_COMPONENTS_ALL cmake-developer-reference-html)
-      endif()
-      if(CMake_BUILD_DEVELOPER_REFERENCE_QTHELP)
-        list(APPEND _CPACK_IFW_COMPONENTS_ALL cmake-developer-reference-qthelp)
-      endif()
+    if(CMake_BUILD_DEVELOPER_REFERENCE_QTHELP)
+      list(APPEND _CPACK_IFW_COMPONENTS_ALL cmake-developer-reference-qthelp)
     endif()
-    set(_CPACK_IFW_COMPONENTS_CONFIGURATION "
+  endif()
+  set(_CPACK_IFW_COMPONENTS_CONFIGURATION "
   # Components
   set(CPACK_COMPONENTS_ALL \"${_CPACK_IFW_COMPONENTS_ALL}\")
   set(CPACK_COMPONENTS_GROUPING IGNORE)
-")
-  else()
-    if(BUILD_QtDialog AND USE_LGPL)
-      set(_CPACK_IFW_ADDITIONAL_LICENSES
-        "\"LGPLv${USE_LGPL}\" \"${CMake_SOURCE_DIR}/Licenses/LGPLv${USE_LGPL}.txt\"")
-    endif()
+  ")
+  _cmifwarg("Package <Script> template"
+    FILEPATH SCRIPT_TEMPLATE "${CMake_SOURCE_DIR}/Source/QtIFW/CMake.qs.in")
+else()
+  if(BUILD_QtDialog AND USE_LGPL)
+    set(${_cpifwrc}LICENSES_DEFAULT
+      "${${_cpifwrc}LICENSES_DEFAULT};LGPLv${USE_LGPL};${CMake_SOURCE_DIR}/Licenses/LGPLv${USE_LGPL}.txt")
   endif()
+  _cmifwarg("Package <Script> template"
+    FILEPATH SCRIPT_TEMPLATE "${CMake_SOURCE_DIR}/Source/QtIFW/installscript.qs.in")
+endif()
+_cmifwarg("Package <Script> generated"
+  FILEPATH SCRIPT_GENERATED "${CMake_BINARY_DIR}/CMake.qs")
 
-  # Components scripts configuration
-  foreach(_script
-    CMake
-    CMake.Documentation.SphinxHTML
-    CMake.DeveloperReference.HTML)
-    configure_file("${CMake_SOURCE_DIR}/Source/QtIFW/${_script}.qs.in"
-      "${CMake_BINARY_DIR}/${_script}.qs" @ONLY)
-  endforeach()
-
-  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()
-    if(CMake_BUILD_DEVELOPER_REFERENCE)
-      if(CMake_BUILD_DEVELOPER_REFERENCE_HTML)
-      set(_CPACK_IFW_SHORTCUT_OPTIONAL "${_CPACK_IFW_SHORTCUT_OPTIONAL}component.addOperation(\"CreateShortcut\", \"@TargetDir@/doc/cmake-${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}/developer-reference/html/index.html\", \"@StartMenuDir@/CMake Developer Reference.lnk\");\n")
-      endif()
-    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 "${CMAKE_DOC_DIR}"
-    )
-    if(CMake_INSTALL_COMPONENTS)
-      set(_CPACK_IFW_PACKAGE_SCRIPT "${CMake_BINARY_DIR}/CMake.qs")
-    else()
-      set(_CPACK_IFW_PACKAGE_SCRIPT "${CMake_BINARY_DIR}/installscript.qs")
-    endif()
-  endif()
+_cmifwarg("Package <Licenses> tag (pairs of <display_name> <file_path>)"
+  STRING LICENSES "${${_cpifwrc}LICENSES_DEFAULT}")
 
-  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}")
+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()
-
-  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
-    # needed
-    if(CYGWIN)
-      set(CPACK_PACKAGE_FILE_NAME "${CPACK_SOURCE_PACKAGE_FILE_NAME}")
-    else()
-      set(CPACK_PACKAGE_FILE_NAME
-        "${CPACK_SOURCE_PACKAGE_FILE_NAME}-${CPACK_SYSTEM_NAME}")
+  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()
+  if(CMake_BUILD_DEVELOPER_REFERENCE)
+    if(CMake_BUILD_DEVELOPER_REFERENCE_HTML)
+    set(_CPACK_IFW_SHORTCUT_OPTIONAL "${_CPACK_IFW_SHORTCUT_OPTIONAL}component.addOperation(\"CreateShortcut\", \"@TargetDir@/doc/cmake-${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}/developer-reference/html/index.html\", \"@StartMenuDir@/CMake Developer Reference.lnk\");\n")
     endif()
   endif()
+  install(FILES "${CMake_SOURCE_DIR}/Source/QtIFW/cmake.org.html"
+    DESTINATION "${CMAKE_DOC_DIR}"
+  )
+endif()
 
-  set(CPACK_PACKAGE_CONTACT "cmake at cmake.org")
+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()
 
-  if(UNIX)
-    set(CPACK_STRIP_FILES "${CMAKE_BIN_DIR}/ccmake;${CMAKE_BIN_DIR}/cmake;${CMAKE_BIN_DIR}/cpack;${CMAKE_BIN_DIR}/ctest")
-    set(CPACK_SOURCE_STRIP_FILES "")
-    set(CPACK_PACKAGE_EXECUTABLES "ccmake" "CMake")
+# Components scripts configuration
+if((EXISTS "${CMake_IFW_ROOT_COMPONENT_SCRIPT_TEMPLATE}")
+  AND (NOT "${CMake_IFW_ROOT_COMPONENT_SCRIPT_GENERATED}" STREQUAL "")
+  AND (NOT "${CMake_IFW_ROOT_COMPONENT_SCRIPT}"))
+  cpack_ifw_configure_file("${CMake_IFW_ROOT_COMPONENT_SCRIPT_TEMPLATE}"
+    "${CMake_IFW_ROOT_COMPONENT_SCRIPT_GENERATED}")
+  _cmifwarg("Package <Script> tag"
+    FILEPATH SCRIPT "${CMake_IFW_ROOT_COMPONENT_SCRIPT_GENERATED}")
+endif()
+foreach(_script
+  CMake.Dialogs.QtGUI
+  CMake.Documentation.SphinxHTML
+  CMake.DeveloperReference.HTML)
+  cpack_ifw_configure_file("${CMake_SOURCE_DIR}/Source/QtIFW/${_script}.qs.in"
+    "${CMake_BINARY_DIR}/${_script}.qs")
+endforeach()
+
+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
+  # needed
+  if(CYGWIN)
+    set(CPACK_PACKAGE_FILE_NAME "${CPACK_SOURCE_PACKAGE_FILE_NAME}")
+  else()
+    set(CPACK_PACKAGE_FILE_NAME
+      "${CPACK_SOURCE_PACKAGE_FILE_NAME}-${CPACK_SYSTEM_NAME}")
   endif()
+endif()
 
-  set(CPACK_WIX_UPGRADE_GUID "8ffd1d72-b7f1-11e2-8ee5-00238bca4991")
+set(CPACK_PACKAGE_CONTACT "cmake at cmake.org")
 
-  if(MSVC AND NOT "$ENV{WIX}" STREQUAL "")
-    set(WIX_CUSTOM_ACTION_ENABLED TRUE)
-    if(CMAKE_CONFIGURATION_TYPES)
-      set(WIX_CUSTOM_ACTION_MULTI_CONFIG TRUE)
-    else()
-      set(WIX_CUSTOM_ACTION_MULTI_CONFIG FALSE)
-    endif()
+if(UNIX)
+  set(CPACK_STRIP_FILES "${CMAKE_BIN_DIR}/ccmake;${CMAKE_BIN_DIR}/cmake;${CMAKE_BIN_DIR}/cpack;${CMAKE_BIN_DIR}/ctest")
+  set(CPACK_SOURCE_STRIP_FILES "")
+  set(CPACK_PACKAGE_EXECUTABLES "ccmake" "CMake")
+endif()
+
+set(CPACK_WIX_UPGRADE_GUID "8ffd1d72-b7f1-11e2-8ee5-00238bca4991")
+
+if(MSVC AND NOT "$ENV{WIX}" STREQUAL "")
+  set(WIX_CUSTOM_ACTION_ENABLED TRUE)
+  if(CMAKE_CONFIGURATION_TYPES)
+    set(WIX_CUSTOM_ACTION_MULTI_CONFIG TRUE)
   else()
-    set(WIX_CUSTOM_ACTION_ENABLED FALSE)
+    set(WIX_CUSTOM_ACTION_MULTI_CONFIG FALSE)
   endif()
+else()
+  set(WIX_CUSTOM_ACTION_ENABLED FALSE)
+endif()
 
-  # Set the options file that needs to be included inside CMakeCPackOptions.cmake
-  set(QT_DIALOG_CPACK_OPTIONS_FILE ${CMake_BINARY_DIR}/Source/QtDialog/QtDialogCPack.cmake)
-  configure_file("${CMake_SOURCE_DIR}/CMakeCPackOptions.cmake.in"
-    "${CMake_BINARY_DIR}/CMakeCPackOptions.cmake" @ONLY)
-  set(CPACK_PROJECT_CONFIG_FILE "${CMake_BINARY_DIR}/CMakeCPackOptions.cmake")
+# Set the options file that needs to be included inside CMakeCPackOptions.cmake
+set(QT_DIALOG_CPACK_OPTIONS_FILE ${CMake_BINARY_DIR}/Source/QtDialog/QtDialogCPack.cmake)
+configure_file("${CMake_SOURCE_DIR}/CMakeCPackOptions.cmake.in"
+  "${CMake_BINARY_DIR}/CMakeCPackOptions.cmake" @ONLY)
+set(CPACK_PROJECT_CONFIG_FILE "${CMake_BINARY_DIR}/CMakeCPackOptions.cmake")
 
-  # include CPack model once all variables are set
-  include(CPack)
-endif()
+# include CPack model once all variables are set
+include(CPack)
diff --git a/CMakeCPackOptions.cmake.in b/CMakeCPackOptions.cmake.in
index d7a33bc..ad0c245 100644
--- a/CMakeCPackOptions.cmake.in
+++ b/CMakeCPackOptions.cmake.in
@@ -47,7 +47,7 @@ if(CPACK_GENERATOR MATCHES "IFW")
   @_CPACK_IFW_COMPONENTS_CONFIGURATION@
   # Unspecified
   set(CPACK_IFW_COMPONENT_ at _CPACK_IFW_COMPONENT_UNSPECIFIED_UNAME@_VERSION
-    "@_CPACK_IFW_PACKAGE_VERSION@")
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   # Package configuration group
   set(CPACK_IFW_PACKAGE_GROUP CMake)
@@ -59,13 +59,7 @@ if(CPACK_GENERATOR MATCHES "IFW")
     "@CPACK_PACKAGE_NAME@")
   set(CPACK_COMPONENT_GROUP_CMAKE_DESCRIPTION
     "@CPACK_PACKAGE_DESCRIPTION_SUMMARY@")
-  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_ADDITIONAL_LICENSES@)
-  set(CPACK_IFW_COMPONENT_GROUP_CMAKE_SCRIPT "@_CPACK_IFW_PACKAGE_SCRIPT@")
-  set(CPACK_IFW_COMPONENT_GROUP_CMAKE_PRIORITY 100)
+  @_CPACK_IFW_COMPONENT_GROUP_CMAKE@
 
   # Tools
   set(CPACK_COMPONENT_GROUP_TOOLS_DISPLAY_NAME "Command-Line Tools")
@@ -73,7 +67,8 @@ if(CPACK_GENERATOR MATCHES "IFW")
     "Command-Line Tools: cmake, ctest and cpack")
   set(CPACK_COMPONENT_GROUP_TOOLS_PARENT_GROUP CMake)
   set(CPACK_IFW_COMPONENT_GROUP_TOOLS_PRIORITY 90)
-  set(CPACK_IFW_COMPONENT_GROUP_TOOLS_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+  set(CPACK_IFW_COMPONENT_GROUP_TOOLS_VERSION
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   set(CPACK_COMPONENT_CMAKE_DISPLAY_NAME "cmake")
   set(CPACK_COMPONENT_CMAKE_DESCRIPTION
@@ -82,7 +77,8 @@ if(CPACK_GENERATOR MATCHES "IFW")
   set(CPACK_COMPONENT_CMAKE_GROUP Tools)
   set(CPACK_IFW_COMPONENT_CMAKE_NAME "CMake")
   set(CPACK_IFW_COMPONENT_CMAKE_PRIORITY 89)
-  set(CPACK_IFW_COMPONENT_CMAKE_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+  set(CPACK_IFW_COMPONENT_CMAKE_VERSION
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   set(CPACK_COMPONENT_CTEST_DISPLAY_NAME "ctest")
   set(CPACK_COMPONENT_CTEST_DESCRIPTION
@@ -91,7 +87,8 @@ if(CPACK_GENERATOR MATCHES "IFW")
   set(CPACK_COMPONENT_CTEST_GROUP Tools)
   set(CPACK_IFW_COMPONENT_CTEST_NAME "CTest")
   set(CPACK_IFW_COMPONENT_CTEST_PRIORITY 88)
-  set(CPACK_IFW_COMPONENT_CTEST_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+  set(CPACK_IFW_COMPONENT_CTEST_VERSION
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   set(CPACK_COMPONENT_CPACK_DISPLAY_NAME "cpack")
   set(CPACK_COMPONENT_CPACK_DESCRIPTION
@@ -100,7 +97,8 @@ if(CPACK_GENERATOR MATCHES "IFW")
   set(CPACK_COMPONENT_CPACK_GROUP Tools)
   set(CPACK_IFW_COMPONENT_CPACK_NAME "CPack")
   set(CPACK_IFW_COMPONENT_CPACK_PRIORITY 87)
-  set(CPACK_IFW_COMPONENT_CPACK_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+  set(CPACK_IFW_COMPONENT_CPACK_VERSION
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   set(CPACK_COMPONENT_CMCLDEPS_DISPLAY_NAME "cmcldeps")
   set(CPACK_COMPONENT_CMCLDEPS_DESCRIPTION
@@ -108,7 +106,8 @@ if(CPACK_GENERATOR MATCHES "IFW")
   set(CPACK_COMPONENT_CMCLDEPS_GROUP Tools)
   set(CPACK_IFW_COMPONENT_CMCLDEPS_NAME "CMClDeps")
   set(CPACK_IFW_COMPONENT_CMCLDEPS_PRIORITY 86)
-  set(CPACK_IFW_COMPONENT_CMCLDEPS_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+  set(CPACK_IFW_COMPONENT_CMCLDEPS_VERSION
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   set(CPACK_COMPONENT_CMAKEXBUILD_DISPLAY_NAME "cmakexbuild")
   set(CPACK_COMPONENT_CMAKEXBUILD_DESCRIPTION
@@ -117,7 +116,8 @@ if(CPACK_GENERATOR MATCHES "IFW")
   set(CPACK_COMPONENT_CMAKEXBUILD_GROUP Tools)
   set(CPACK_IFW_COMPONENT_CMAKEXBUILD_NAME "CMakeXBuild")
   set(CPACK_IFW_COMPONENT_CMAKEXBUILD_PRIORITY 85)
-  set(CPACK_IFW_COMPONENT_CMAKEXBUILD_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+  set(CPACK_IFW_COMPONENT_CMAKEXBUILD_VERSION
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   # Dialogs
   set(CPACK_COMPONENT_GROUP_DIALOGS_DISPLAY_NAME "Interactive Dialogs")
@@ -125,20 +125,23 @@ if(CPACK_GENERATOR MATCHES "IFW")
     "Interactive Dialogs with Console and GUI interfaces")
   set(CPACK_COMPONENT_GROUP_DIALOGS_PARENT_GROUP CMake)
   set(CPACK_IFW_COMPONENT_GROUP_DIALOGS_PRIORITY 80)
-  set(CPACK_IFW_COMPONENT_GROUP_DIALOGS_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+  set(CPACK_IFW_COMPONENT_GROUP_DIALOGS_VERSION
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   set(CPACK_COMPONENT_CMAKE-GUI_DISPLAY_NAME "cmake-gui")
   set(CPACK_COMPONENT_CMAKE-GUI_GROUP Dialogs)
   set(CPACK_IFW_COMPONENT_CMAKE-GUI_NAME "QtGUI")
   set(CPACK_IFW_COMPONENT_CMAKE-GUI_SCRIPT
-    "@CMake_SOURCE_DIR@/Source/QtIFW/CMake.Dialogs.QtGUI.qs")
-  set(CPACK_IFW_COMPONENT_CMAKE-GUI_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+    "@CMake_BINARY_DIR@/CMake.Dialogs.QtGUI.qs")
+  set(CPACK_IFW_COMPONENT_CMAKE-GUI_VERSION
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
   @_CPACK_IFW_COMPONENT_CMAKE-GUI_LICENSES@
 
   set(CPACK_COMPONENT_CCMAKE_DISPLAY_NAME "ccmake")
   set(CPACK_COMPONENT_CCMAKE_GROUP Dialogs)
   set(CPACK_IFW_COMPONENT_CCMAKE_NAME "CursesGUI")
-  set(CPACK_IFW_COMPONENT_CCMAKE_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+  set(CPACK_IFW_COMPONENT_CCMAKE_VERSION
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   # Documentation
   set(CPACK_COMPONENT_GROUP_DOCUMENTATION_DISPLAY_NAME "Documentation")
@@ -147,33 +150,36 @@ if(CPACK_GENERATOR MATCHES "IFW")
   set(CPACK_COMPONENT_GROUP_DOCUMENTATION_PARENT_GROUP CMake)
   set(CPACK_IFW_COMPONENT_GROUP_DOCUMENTATION_PRIORITY 60)
   set(CPACK_IFW_COMPONENT_GROUP_DOCUMENTATION_VERSION
-    "@_CPACK_IFW_PACKAGE_VERSION@")
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   set(CPACK_COMPONENT_SPHINX-MAN_DISPLAY_NAME "man")
   set(CPACK_COMPONENT_SPHINX-MAN_GROUP Documentation)
   set(CPACK_COMPONENT_SPHINX-MAN_DISABLED TRUE)
   set(CPACK_IFW_COMPONENT_SPHINX-MAN_NAME "SphinxMan")
-  set(CPACK_IFW_COMPONENT_SPHINX-MAN_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+  set(CPACK_IFW_COMPONENT_SPHINX-MAN_VERSION
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   set(CPACK_COMPONENT_SPHINX-HTML_DISPLAY_NAME "HTML")
   set(CPACK_COMPONENT_SPHINX-HTML_GROUP Documentation)
   set(CPACK_IFW_COMPONENT_SPHINX-HTML_NAME "SphinxHTML")
   set(CPACK_IFW_COMPONENT_SPHINX-HTML_SCRIPT
     "@CMake_BINARY_DIR@/CMake.Documentation.SphinxHTML.qs")
-  set(CPACK_IFW_COMPONENT_SPHINX-HTML_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+  set(CPACK_IFW_COMPONENT_SPHINX-HTML_VERSION
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   set(CPACK_COMPONENT_SPHINX-SINGLEHTML_DISPLAY_NAME "Single HTML")
   set(CPACK_COMPONENT_SPHINX-SINGLEHTML_GROUP Documentation)
   set(CPACK_COMPONENT_SPHINX-SINGLEHTML_DISABLED TRUE)
   set(CPACK_IFW_COMPONENT_SPHINX-SINGLEHTML_NAME "SphinxSingleHTML")
   set(CPACK_IFW_COMPONENT_SPHINX-SINGLEHTML_VERSION
-    "@_CPACK_IFW_PACKAGE_VERSION@")
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   set(CPACK_COMPONENT_SPHINX-QTHELP_DISPLAY_NAME "Qt Compressed Help")
   set(CPACK_COMPONENT_SPHINX-QTHELP_GROUP Documentation)
   set(CPACK_COMPONENT_SPHINX-QTHELP_DISABLED TRUE)
   set(CPACK_IFW_COMPONENT_SPHINX-QTHELP_NAME "SphinxQtHelp")
-  set(CPACK_IFW_COMPONENT_SPHINX-QTHELP_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+  set(CPACK_IFW_COMPONENT_SPHINX-QTHELP_VERSION
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   # Developer Reference
   set(CPACK_COMPONENT_GROUP_DEVELOPERREFERENCE_DISPLAY_NAME "Developer Reference")
@@ -182,7 +188,7 @@ if(CPACK_GENERATOR MATCHES "IFW")
   set(CPACK_COMPONENT_GROUP_DEVELOPERREFERENCE_PARENT_GROUP CMake)
   set(CPACK_IFW_COMPONENT_GROUP_DEVELOPERREFERENCE_PRIORITY 50)
   set(CPACK_IFW_COMPONENT_GROUP_DEVELOPERREFERENCE_VERSION
-    "@_CPACK_IFW_PACKAGE_VERSION@")
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_DISPLAY_NAME "HTML")
   set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_GROUP DeveloperReference)
@@ -190,13 +196,15 @@ if(CPACK_GENERATOR MATCHES "IFW")
   set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_NAME "HTML")
   set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_SCRIPT
     "@CMake_BINARY_DIR@/CMake.DeveloperReference.HTML.qs")
-  set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+  set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-HTML_VERSION
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
   set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_DISPLAY_NAME "Qt Compressed Help")
   set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_GROUP DeveloperReference)
   set(CPACK_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_DISABLED TRUE)
   set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_NAME "QtHelp")
-  set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_VERSION "@_CPACK_IFW_PACKAGE_VERSION@")
+  set(CPACK_IFW_COMPONENT_CMAKE-DEVELOPER-REFERENCE-QTHELP_VERSION
+    "@CMake_IFW_ROOT_COMPONENT_VERSION@")
 
 endif()
 
diff --git a/CMakeLists.txt b/CMakeLists.txt
index b4a577c..bec81a3 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -66,12 +66,8 @@ if(NOT CMake_TEST_EXTERNAL_CMAKE)
   include(${CMake_SOURCE_DIR}/Source/Checks/cm_cxx_features.cmake)
 endif()
 
-# option to set the internal encoding of CMake to UTF-8
-option(CMAKE_ENCODING_UTF8 "Use UTF-8 encoding internally." ON)
-mark_as_advanced(CMAKE_ENCODING_UTF8)
-if(CMAKE_ENCODING_UTF8)
-  set(KWSYS_ENCODING_DEFAULT_CODEPAGE CP_UTF8)
-endif()
+# set the internal encoding of CMake to UTF-8
+set(KWSYS_ENCODING_DEFAULT_CODEPAGE CP_UTF8)
 
 # option to use COMPONENT with install command
 option(CMake_INSTALL_COMPONENTS "Using components when installing" OFF)
@@ -108,7 +104,7 @@ macro(CMAKE_HANDLE_SYSTEM_LIBRARIES)
 
   # 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 FORM JSONCPP LIBARCHIVE LIBLZMA LIBUV ZLIB)
+  set(UTILITIES BZIP2 CURL EXPAT FORM JSONCPP LIBARCHIVE LIBLZMA LIBRHASH LIBUV ZLIB)
   foreach(util ${UTILITIES})
     if(NOT DEFINED CMAKE_USE_SYSTEM_LIBRARY_${util}
         AND DEFINED CMAKE_USE_SYSTEM_LIBRARIES)
@@ -148,6 +144,7 @@ macro(CMAKE_HANDLE_SYSTEM_LIBRARIES)
     "${CMAKE_USE_SYSTEM_LIBRARY_LIBLZMA}" "NOT CMAKE_USE_SYSTEM_LIBARCHIVE" ON)
   option(CMAKE_USE_SYSTEM_FORM "Use system-installed libform" "${CMAKE_USE_SYSTEM_LIBRARY_FORM}")
   option(CMAKE_USE_SYSTEM_JSONCPP "Use system-installed jsoncpp" "${CMAKE_USE_SYSTEM_LIBRARY_JSONCPP}")
+  option(CMAKE_USE_SYSTEM_LIBRHASH "Use system-installed librhash" "${CMAKE_USE_SYSTEM_LIBRARY_LIBRHASH}")
   option(CMAKE_USE_SYSTEM_LIBUV "Use system-installed libuv" "${CMAKE_USE_SYSTEM_LIBRARY_LIBUV}")
 
   # For now use system KWIML only if explicitly requested rather
@@ -260,6 +257,7 @@ macro (CMAKE_BUILD_UTILITIES)
   set(KWSYS_USE_MD5 1)
   set(KWSYS_USE_Process 1)
   set(KWSYS_USE_CommandLineArguments 1)
+  set(KWSYS_USE_ConsoleBuf 1)
   set(KWSYS_HEADER_ROOT ${CMake_BINARY_DIR}/Source)
   set(KWSYS_INSTALL_DOC_DIR "${CMAKE_DOC_DIR}")
   add_subdirectory(Source/kwsys)
@@ -301,6 +299,23 @@ macro (CMAKE_BUILD_UTILITIES)
     add_subdirectory(Utilities/KWIML)
   endif()
 
+  if(CMAKE_USE_SYSTEM_LIBRHASH)
+    if(NOT CMAKE_VERSION VERSION_LESS 3.0)
+      find_package(LibRHash)
+    else()
+      message(FATAL_ERROR "CMAKE_USE_SYSTEM_LIBRHASH requires CMake >= 3.0")
+    endif()
+    if(NOT LibRHash_FOUND)
+      message(FATAL_ERROR
+        "CMAKE_USE_SYSTEM_LIBRHASH is ON but LibRHash is not found!")
+    endif()
+    set(CMAKE_LIBRHASH_LIBRARIES LibRHash::LibRHash)
+  else()
+    set(CMAKE_LIBRHASH_LIBRARIES cmlibrhash)
+    add_subdirectory(Utilities/cmlibrhash)
+    CMAKE_SET_TARGET_FOLDER(cmlibrhash "Utilities/3rdParty")
+  endif()
+
   #---------------------------------------------------------------------
   # Build zlib library for Curl, CMake, and CTest.
   set(CMAKE_ZLIB_HEADER "cm_zlib.h")
@@ -366,31 +381,55 @@ macro (CMAKE_BUILD_UTILITIES)
   set(CMAKE_COMPRESS_LIBRARIES "cmcompress")
   add_subdirectory(Utilities/cmcompress)
   CMAKE_SET_TARGET_FOLDER(cmcompress "Utilities/3rdParty")
-  if(CMAKE_USE_SYSTEM_BZIP2)
-    find_package(BZip2)
+
+  #---------------------------------------------------------------------
+  # Build expat library for CMake, CTest, and libarchive.
+  if(CMAKE_USE_SYSTEM_EXPAT)
+    find_package(EXPAT)
+    if(NOT EXPAT_FOUND)
+      message(FATAL_ERROR
+        "CMAKE_USE_SYSTEM_EXPAT is ON but a expat is not found!")
+    endif()
+    set(CMAKE_EXPAT_INCLUDES ${EXPAT_INCLUDE_DIRS})
+    set(CMAKE_EXPAT_LIBRARIES ${EXPAT_LIBRARIES})
   else()
-    set(BZIP2_INCLUDE_DIR
-      "${CMAKE_CURRENT_SOURCE_DIR}/Utilities/cmbzip2")
-    set(BZIP2_LIBRARIES cmbzip2)
-    add_subdirectory(Utilities/cmbzip2)
-    CMAKE_SET_TARGET_FOLDER(cmbzip2 "Utilities/3rdParty")
+    set(CMAKE_EXPAT_INCLUDES)
+    set(CMAKE_EXPAT_LIBRARIES cmexpat)
+    add_subdirectory(Utilities/cmexpat)
+    CMAKE_SET_TARGET_FOLDER(cmexpat "Utilities/3rdParty")
+  endif()
+
+  #---------------------------------------------------------------------
+  # Build or use system libbz2 for libarchive.
+  if(NOT CMAKE_USE_SYSTEM_LIBARCHIVE)
+    if(CMAKE_USE_SYSTEM_BZIP2)
+      find_package(BZip2)
+    else()
+      set(BZIP2_INCLUDE_DIR
+        "${CMAKE_CURRENT_SOURCE_DIR}/Utilities/cmbzip2")
+      set(BZIP2_LIBRARIES cmbzip2)
+      add_subdirectory(Utilities/cmbzip2)
+      CMAKE_SET_TARGET_FOLDER(cmbzip2 "Utilities/3rdParty")
+    endif()
   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!")
+  if(NOT CMAKE_USE_SYSTEM_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()
-    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()
 
   #---------------------------------------------------------------------
@@ -403,6 +442,8 @@ macro (CMAKE_BUILD_UTILITIES)
     set(CMAKE_TAR_INCLUDES ${LibArchive_INCLUDE_DIRS})
     set(CMAKE_TAR_LIBRARIES ${LibArchive_LIBRARIES})
   else()
+    set(EXPAT_INCLUDE_DIR ${CMAKE_EXPAT_INCLUDES})
+    set(EXPAT_LIBRARY ${CMAKE_EXPAT_LIBRARIES})
     set(ZLIB_INCLUDE_DIR ${CMAKE_ZLIB_INCLUDES})
     set(ZLIB_LIBRARY ${CMAKE_ZLIB_LIBRARIES})
     add_definitions(-DLIBARCHIVE_STATIC)
@@ -412,7 +453,7 @@ macro (CMAKE_BUILD_UTILITIES)
     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_LIBXML2 OFF CACHE INTERNAL "Enable the use of the system found libxml2 library if found")
-    set(ENABLE_EXPAT OFF CACHE INTERNAL "Enable the use of the system found EXPAT library if found")
+    set(ENABLE_EXPAT ON CACHE INTERNAL "Enable the use of the system found EXPAT library if found")
     set(ENABLE_PCREPOSIX OFF CACHE INTERNAL "Enable the use of the system found PCREPOSIX library if found")
     set(ENABLE_LibGCC OFF CACHE INTERNAL "Enable the use of the system found LibGCC library if found")
     set(ENABLE_XATTR OFF CACHE INTERNAL "Enable extended attribute support")
@@ -425,23 +466,6 @@ macro (CMAKE_BUILD_UTILITIES)
   endif()
 
   #---------------------------------------------------------------------
-  # Build expat library for CMake and CTest.
-  if(CMAKE_USE_SYSTEM_EXPAT)
-    find_package(EXPAT)
-    if(NOT EXPAT_FOUND)
-      message(FATAL_ERROR
-        "CMAKE_USE_SYSTEM_EXPAT is ON but a expat is not found!")
-    endif()
-    set(CMAKE_EXPAT_INCLUDES ${EXPAT_INCLUDE_DIRS})
-    set(CMAKE_EXPAT_LIBRARIES ${EXPAT_LIBRARIES})
-  else()
-    set(CMAKE_EXPAT_INCLUDES)
-    set(CMAKE_EXPAT_LIBRARIES cmexpat)
-    add_subdirectory(Utilities/cmexpat)
-    CMAKE_SET_TARGET_FOLDER(cmexpat "Utilities/3rdParty")
-  endif()
-
-  #---------------------------------------------------------------------
   # Build jsoncpp library.
   if(CMAKE_USE_SYSTEM_JSONCPP)
     if(NOT CMAKE_VERSION VERSION_LESS 3.0)
@@ -486,6 +510,9 @@ int main(void) { return 0; }
     elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "sparc")
       # Disable until it can be ported.
       set(CMAKE_USE_LIBUV 0)
+    elseif(CMAKE_SYSTEM STREQUAL "SunOS-5.10")
+      # Disable until it can be ported.
+      set(CMAKE_USE_LIBUV 0)
     endif()
   endif()
   if(CMAKE_USE_LIBUV)
diff --git a/CTestCustom.cmake.in b/CTestCustom.cmake.in
index 48dd3de..fa2fbe3 100644
--- a/CTestCustom.cmake.in
+++ b/CTestCustom.cmake.in
@@ -17,7 +17,6 @@ list(APPEND CTEST_CUSTOM_WARNING_EXCEPTION
   "Utilities.cmbzip2."
   "Source.CTest.Curl"
   "Source.CursesDialog.form"
-  "Source.cm_sha2.*warning.*cast increases required alignment of target type"
   "Utilities.cmcurl"
   "Utilities.cmexpat."
   "Utilities.cmlibarchive"
@@ -84,7 +83,10 @@ list(APPEND CTEST_CUSTOM_WARNING_EXCEPTION
   "warning: Value stored to 'yytoken' is never read"
   "index_encoder.c.241.2. warning: Value stored to .out_start. is never read"
   "index.c.*warning: Access to field.*results in a dereference of a null pointer.*loaded from variable.*"
-  "cm_sha2.*warning: Value stored to.*is never read"
+  "cmCommandArgumentLexer.cxx:[0-9]+:[0-9]+: warning: Call to 'realloc' has an allocation size of 0 bytes"
+  "cmDependsJavaLexer.cxx:[0-9]+:[0-9]+: warning: Call to 'realloc' has an allocation size of 0 bytes"
+  "cmExprLexer.cxx:[0-9]+:[0-9]+: warning: Call to 'realloc' has an allocation size of 0 bytes"
+  "cmListFileLexer.c:[0-9]+:[0-9]+: warning: Call to 'realloc' has an allocation size of 0 bytes"
   "cmFortranLexer.cxx:[0-9]+:[0-9]+: warning: Call to 'realloc' has an allocation size of 0 bytes"
   "testProcess.*warning: Dereference of null pointer .loaded from variable .invalidAddress.."
   "liblzma/simple/x86.c:[0-9]+:[0-9]+: warning: The result of the '<<' expression is undefined"
diff --git a/Copyright.txt b/Copyright.txt
index 63d7bb8..daaa1d1 100644
--- a/Copyright.txt
+++ b/Copyright.txt
@@ -1,5 +1,5 @@
 CMake - Cross Platform Makefile Generator
-Copyright 2000-2016 Kitware, Inc. and Contributors
+Copyright 2000-2017 Kitware, Inc. and Contributors
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
@@ -37,6 +37,7 @@ The following individuals and institutions are among the Contributors:
 * Aleksey Avdeev <solo at altlinux.ru>
 * Alexander Neundorf <neundorf at kde.org>
 * Alexander Smorkalov <alexander.smorkalov at itseez.com>
+* Alexey Sokolov <sokolov at google.com>
 * Alex Turbov <i.zaufi at gmail.com>
 * Andreas Pakulat <apaku at gmx.de>
 * Andreas Schneider <asn at cryptomilk.org>
@@ -54,6 +55,7 @@ The following individuals and institutions are among the Contributors:
 * Eran Ifrah <eran.ifrah at gmail.com>
 * Esben Mose Hansen, Ange Optimization ApS
 * Geoffrey Viola <geoffrey.viola at asirobots.com>
+* Google Inc
 * Gregor Jasny
 * Helio Chissini de Castro <helio at kde.org>
 * Ilya Lavrenov <ilya.lavrenov at itseez.com>
diff --git a/Help/command/add_custom_command.rst b/Help/command/add_custom_command.rst
index 4ab4298..80e7edf 100644
--- a/Help/command/add_custom_command.rst
+++ b/Help/command/add_custom_command.rst
@@ -21,7 +21,8 @@ The first signature is for adding a custom command to produce an output::
                      [WORKING_DIRECTORY dir]
                      [COMMENT comment]
                      [DEPFILE depfile]
-                     [VERBATIM] [APPEND] [USES_TERMINAL])
+                     [VERBATIM] [APPEND] [USES_TERMINAL]
+                     [COMMAND_EXPAND_LISTS])
 
 This defines a command to generate specified ``OUTPUT`` file(s).
 A target created in the same directory (``CMakeLists.txt`` file)
@@ -122,6 +123,14 @@ The options are:
   Arguments to ``DEPENDS`` may use
   :manual:`generator expressions <cmake-generator-expressions(7)>`.
 
+``COMMAND_EXPAND_LISTS``
+  Lists in ``COMMAND`` arguments will be expanded, including those
+  created with
+  :manual:`generator expressions <cmake-generator-expressions(7)>`,
+  allowing ``COMMAND`` arguments such as
+  ``${CC} "-I$<JOIN:$<TARGET_PROPERTY:foo,INCLUDE_DIRECTORIES>,;-I>" foo.cc``
+  to be properly expanded.
+
 ``IMPLICIT_DEPENDS``
   Request scanning of implicit dependencies of an input file.
   The language given specifies the programming language whose
diff --git a/Help/command/add_custom_target.rst b/Help/command/add_custom_target.rst
index 6980d61..bd61c8b 100644
--- a/Help/command/add_custom_target.rst
+++ b/Help/command/add_custom_target.rst
@@ -12,6 +12,7 @@ Add a target with no output so it will always be built.
                     [WORKING_DIRECTORY dir]
                     [COMMENT comment]
                     [VERBATIM] [USES_TERMINAL]
+                    [COMMAND_EXPAND_LISTS]
                     [SOURCES src1 [src2...]])
 
 Adds a target with the given name that executes the given commands.
@@ -88,6 +89,14 @@ The options are:
   Use the :command:`add_dependencies` command to add dependencies
   on other targets.
 
+``COMMAND_EXPAND_LISTS``
+  Lists in ``COMMAND`` arguments will be expanded, including those
+  created with
+  :manual:`generator expressions <cmake-generator-expressions(7)>`,
+  allowing ``COMMAND`` arguments such as
+  ``${CC} "-I$<JOIN:$<TARGET_PROPERTY:foo,INCLUDE_DIRECTORIES>,;-I>" foo.cc``
+  to be properly expanded.
+
 ``SOURCES``
   Specify additional source files to be included in the custom target.
   Specified source files will be added to IDE project files for
diff --git a/Help/command/add_library.rst b/Help/command/add_library.rst
index 36adcbe..af75a39 100644
--- a/Help/command/add_library.rst
+++ b/Help/command/add_library.rst
@@ -33,7 +33,7 @@ type is ``STATIC`` or ``SHARED`` based on whether the current value of the
 variable :variable:`BUILD_SHARED_LIBS` is ``ON``.  For ``SHARED`` and
 ``MODULE`` libraries the :prop_tgt:`POSITION_INDEPENDENT_CODE` target
 property is set to ``ON`` automatically.
-A ``SHARED`` library may be marked with the :prop_tgt:`FRAMEWORK`
+A ``SHARED`` or ``STATIC`` library may be marked with the :prop_tgt:`FRAMEWORK`
 target property to create an OS X Framework.
 
 If a library does not export any symbols, it must not be declared as a
diff --git a/Help/command/ctest_memcheck.rst b/Help/command/ctest_memcheck.rst
index 29bdf7d..a983d68 100644
--- a/Help/command/ctest_memcheck.rst
+++ b/Help/command/ctest_memcheck.rst
@@ -18,6 +18,7 @@ Perform the :ref:`CTest MemCheck Step` as a :ref:`Dashboard Client`.
                  [SCHEDULE_RANDOM <ON|OFF>]
                  [STOP_TIME <time-of-day>]
                  [RETURN_VALUE <result-var>]
+                 [DEFECT_COUNT <defect-count-var>]
                  [QUIET]
                  )
 
@@ -26,4 +27,9 @@ Run tests with a dynamic analysis tool and store results in
 ``MemCheck.xml`` for submission with the :command:`ctest_submit`
 command.
 
-The options are the same as those for the :command:`ctest_test` command.
+Most options are the same as those for the :command:`ctest_test` command.
+
+The options unique to this command are:
+
+``DEFECT_COUNT <defect-count-var>``
+  Store in the ``<defect-count-var>`` the number of defects found.
diff --git a/Help/command/ctest_submit.rst b/Help/command/ctest_submit.rst
index 6830b59..a7d9708 100644
--- a/Help/command/ctest_submit.rst
+++ b/Help/command/ctest_submit.rst
@@ -56,10 +56,16 @@ Submit to CDash Upload API
 
 ::
 
-  ctest_submit(CDASH_UPLOAD <file> [CDASH_UPLOAD_TYPE <type>])
+  ctest_submit(CDASH_UPLOAD <file> [CDASH_UPLOAD_TYPE <type>]
+               [RETRY_COUNT <count>]
+               [RETRY_DELAY <delay>]
+               [QUIET])
 
 This second signature is used to upload files to CDash via the CDash
 file upload API. The api first sends a request to upload to CDash along
 with a content hash of the file. If CDash does not already have the file,
 then it is uploaded. Along with the file, a CDash type string is specified
 to tell CDash which handler to use to process the data.
+
+This signature accepts the ``RETRY_COUNT``, ``RETRY_DELAY``, and ``QUIET``
+options as described above.
diff --git a/Help/command/execute_process.rst b/Help/command/execute_process.rst
index ca44b53..d617243 100644
--- a/Help/command/execute_process.rst
+++ b/Help/command/execute_process.rst
@@ -18,9 +18,10 @@ Execute one or more child processes.
                   [OUTPUT_QUIET]
                   [ERROR_QUIET]
                   [OUTPUT_STRIP_TRAILING_WHITESPACE]
-                  [ERROR_STRIP_TRAILING_WHITESPACE])
+                  [ERROR_STRIP_TRAILING_WHITESPACE]
+                  [ENCODING <name>])
 
-Runs the given sequence of one or more commands with the standard
+Runs the given sequence of one or more commands in parallel with the standard
 output of each process piped to the standard input of the next.
 A single standard error pipe is used for all processes.
 
@@ -36,6 +37,9 @@ Options:
  (Use the ``INPUT_*``, ``OUTPUT_*``, and ``ERROR_*`` options to
  redirect stdin, stdout, and stderr.)
 
+ If a sequential execution of multiple commands is required, use multiple
+ :command:`execute_process` calls with a single ``COMMAND`` argument.
+
 ``WORKING_DIRECTORY``
  The named directory will be set as the current working directory of
  the child processes.
@@ -63,6 +67,25 @@ Options:
 ``OUTPUT_QUIET``, ``ERROR_QUIET``
  The standard output or standard error results will be quietly ignored.
 
+``ENCODING <name>``
+ On Windows, the encoding that is used to decode output from the process.
+ Ignored on other platforms.
+ Valid encoding names are:
+
+ ``NONE``
+   Perform no decoding.  This assumes that the process output is encoded
+   in the same way as CMake's internal encoding (UTF-8).
+   This is the default.
+ ``AUTO``
+   Use the current active console's codepage or if that isn't
+   available then use ANSI.
+ ``ANSI``
+   Use the ANSI codepage.
+ ``OEM``
+   Use the original equipment manufacturer (OEM) code page.
+ ``UTF8``
+   Use the UTF-8 codepage.
+
 If more than one ``OUTPUT_*`` or ``ERROR_*`` option is given for the
 same pipe the precedence is not specified.
 If no ``OUTPUT_*`` or ``ERROR_*`` options are given the output will
diff --git a/Help/command/file.rst b/Help/command/file.rst
index 77e9f62..b2e4eea 100644
--- a/Help/command/file.rst
+++ b/Help/command/file.rst
@@ -83,10 +83,12 @@ from the input file.
 
 ::
 
-  file(<MD5|SHA1|SHA224|SHA256|SHA384|SHA512> <filename> <variable>)
+  file(<HASH> <filename> <variable>)
 
 Compute a cryptographic hash of the content of ``<filename>`` and
-store it in a ``<variable>``.
+store it in a ``<variable>``.  The supported ``<HASH>`` algorithm names
+are those listed by the :ref:`string(\<HASH\>) <Supported Hash Algorithms>`
+command.
 
 ------------------------------------------------------------------------------
 
@@ -153,7 +155,8 @@ Move a file or directory within a filesystem from ``<oldname>`` to
   file(REMOVE_RECURSE [<files>...])
 
 Remove the given files.  The ``REMOVE_RECURSE`` mode will remove the given
-files and directories, also non-empty directories
+files and directories, also non-empty directories. No error is emitted if a
+given file does not exist.
 
 ------------------------------------------------------------------------------
 
@@ -233,8 +236,8 @@ Additional options to ``DOWNLOAD`` are:
 ``EXPECTED_HASH ALGO=<value>``
 
   Verify that the downloaded content hash matches the expected value, where
-  ``ALGO`` is one of ``MD5``, ``SHA1``, ``SHA224``, ``SHA256``, ``SHA384``, or
-  ``SHA512``.  If it does not match, the operation fails with an error.
+  ``ALGO`` is one of the algorithms supported by ``file(<HASH>)``.
+  If it does not match, the operation fails with an error.
 
 ``EXPECTED_MD5 <value>``
   Historical short-hand for ``EXPECTED_HASH MD5=<value>``.
@@ -301,6 +304,11 @@ Exactly one ``CONTENT`` or ``INPUT`` option must be given.  A specific
 Generated files are modified on subsequent cmake runs only if their content
 is changed.
 
+Note also that ``file(GENERATE)`` does not create the output file until the
+generation phase. The output file will not yet have been written when the
+``file(GENERATE)`` command returns, it is written only after processing all
+of a project's ``CMakeLists.txt`` files.
+
 ------------------------------------------------------------------------------
 
 ::
diff --git a/Help/command/if.rst b/Help/command/if.rst
index 0941029..2a087d0 100644
--- a/Help/command/if.rst
+++ b/Help/command/if.rst
@@ -9,17 +9,17 @@ Conditionally execute a group of commands.
    # then section.
    COMMAND1(ARGS ...)
    COMMAND2(ARGS ...)
-   ...
+   #...
  elseif(expression2)
    # elseif section.
    COMMAND1(ARGS ...)
    COMMAND2(ARGS ...)
-   ...
+   #...
  else(expression)
    # else section.
    COMMAND1(ARGS ...)
    COMMAND2(ARGS ...)
-   ...
+   #...
  endif(expression)
 
 Evaluates the given expression.  If the result is true, the commands
diff --git a/Help/command/install.rst b/Help/command/install.rst
index d57dd75..70087a4 100644
--- a/Help/command/install.rst
+++ b/Help/command/install.rst
@@ -90,8 +90,10 @@ project.  There are five kinds of target files that may be installed:
 ``ARCHIVE``, ``LIBRARY``, ``RUNTIME``, ``FRAMEWORK``, and ``BUNDLE``.
 Executables are treated as ``RUNTIME`` targets, except that those
 marked with the ``MACOSX_BUNDLE`` property are treated as ``BUNDLE``
-targets on OS X.  Static libraries are always treated as ``ARCHIVE``
-targets.  Module libraries are always treated as ``LIBRARY`` targets.
+targets on OS X.  Static libraries are treated as ``ARCHIVE`` targets,
+except that those marked with the ``FRAMEWORK`` property are treated
+as ``FRAMEWORK`` targets on OS X.
+Module libraries are always treated as ``LIBRARY`` targets.
 For non-DLL platforms shared libraries are treated as ``LIBRARY``
 targets, except that those marked with the ``FRAMEWORK`` property are
 treated as ``FRAMEWORK`` targets on OS X.  For DLL platforms the DLL
diff --git a/Help/command/source_group.rst b/Help/command/source_group.rst
index 6e3829c..938ca40 100644
--- a/Help/command/source_group.rst
+++ b/Help/command/source_group.rst
@@ -2,15 +2,27 @@ source_group
 ------------
 
 Define a grouping for source files in IDE project generation.
+There are two different signatures to create source groups.
 
-.. code-block:: cmake
+::
 
   source_group(<name> [FILES <src>...] [REGULAR_EXPRESSION <regex>])
+  source_group(TREE <root> [PREFIX <prefix>] [FILES <src>...])
 
 Defines a group into which sources will be placed in project files.
 This is intended to set up file tabs in Visual Studio.
 The options are:
 
+``TREE``
+ CMake will automatically detect, from ``<src>`` files paths, source groups
+ it needs to create, to keep structure of source groups analogically to the
+ actual files and directories structure in the project. Paths of ``<src>``
+ files will be cut to be relative to ``<root>``.
+
+``PREFIX``
+ Source group and files located directly in ``<root>`` path, will be placed
+ in ``<prefix>`` source groups.
+
 ``FILES``
  Any source file specified explicitly will be placed in group
  ``<name>``.  Relative paths are interpreted with respect to the
@@ -25,11 +37,13 @@ explicitly lists the file with ``FILES`` will be favored, if any.
 If no group explicitly lists the file, the *last* group whose
 regular expression matches the file will be favored.
 
-The ``<name>`` of the group may contain backslashes to specify subgroups:
+The ``<name>`` of the group and ``<prefix>`` argument may contain backslashes
+to specify subgroups:
 
 .. code-block:: cmake
 
   source_group(outer\\inner ...)
+  source_group(TREE <root> PREFIX sources\\inc ...)
 
 For backwards compatibility, the short-hand signature
 
diff --git a/Help/command/string.rst b/Help/command/string.rst
index 8028333..698a91d 100644
--- a/Help/command/string.rst
+++ b/Help/command/string.rst
@@ -206,15 +206,38 @@ Comparison
 
 Compare the strings and store true or false in the output variable.
 
+.. _`Supported Hash Algorithms`:
+
 Hashing
 ^^^^^^^
 
 ::
 
-  string(<MD5|SHA1|SHA224|SHA256|SHA384|SHA512>
-         <output variable> <input>)
+  string(<HASH> <output variable> <input>)
 
 Compute a cryptographic hash of the input string.
+The supported ``<HASH>`` algorithm names are:
+
+``MD5``
+  Message-Digest Algorithm 5, RFC 1321.
+``SHA1``
+  US Secure Hash Algorithm 1, RFC 3174.
+``SHA224``
+  US Secure Hash Algorithms, RFC 4634.
+``SHA256``
+  US Secure Hash Algorithms, RFC 4634.
+``SHA384``
+  US Secure Hash Algorithms, RFC 4634.
+``SHA512``
+  US Secure Hash Algorithms, RFC 4634.
+``SHA3_224``
+  Keccak SHA-3.
+``SHA3_256``
+  Keccak SHA-3.
+``SHA3_384``
+  Keccak SHA-3.
+``SHA3_512``
+  Keccak SHA-3.
 
 Generation
 ^^^^^^^^^^
@@ -273,6 +296,7 @@ specifiers:
 
 ::
 
+   %%        A literal percent sign (%).
    %d        The day of the current month (01-31).
    %H        The hour on a 24-hour clock (00-23).
    %I        The hour on a 12-hour clock (01-12).
@@ -306,6 +330,12 @@ If no explicit ``<format string>`` is given it will default to:
 
 Write a string which can be used as an identifier in C.
 
+.. note::
+
+  If the ``SOURCE_DATE_EPOCH`` environment variable is set,
+  its value will be used instead of the current time.
+  See https://reproducible-builds.org/specs/source-date-epoch/ for details.
+
 UUID
 """"
 
diff --git a/Help/command/target_link_libraries.rst b/Help/command/target_link_libraries.rst
index 90b6575..30d69f2 100644
--- a/Help/command/target_link_libraries.rst
+++ b/Help/command/target_link_libraries.rst
@@ -53,6 +53,11 @@ Each ``<item>`` may be:
   :ref:`usage requirement <Target Usage Requirements>`.  This has the same
   effect as passing the framework directory as an include directory.
 
+  On :ref:`Visual Studio Generators` for VS 2010 and above, library files
+  ending in ``.targets`` will be treated as MSBuild targets files and
+  imported into generated project files.  This is not supported by other
+  generators.
+
 * **A plain library name**: The generated link line will ask the linker
   to search for the library (e.g. ``foo`` becomes ``-lfoo`` or ``foo.lib``).
 
diff --git a/Help/command/try_compile.rst b/Help/command/try_compile.rst
index 7830deb..66ea3d7 100644
--- a/Help/command/try_compile.rst
+++ b/Help/command/try_compile.rst
@@ -35,7 +35,11 @@ Try Compiling Source Files
               [COMPILE_DEFINITIONS <defs>...]
               [LINK_LIBRARIES <libs>...]
               [OUTPUT_VARIABLE <var>]
-              [COPY_FILE <fileName> [COPY_FILE_ERROR <var>]])
+              [COPY_FILE <fileName> [COPY_FILE_ERROR <var>]]
+              [<LANG>_STANDARD <std>]
+              [<LANG>_STANDARD_REQUIRED <bool>]
+              [<LANG>_EXTENSIONS <bool>]
+              )
 
 Try building an executable from one or more source files.  The success or
 failure of the ``try_compile``, i.e. ``TRUE`` or ``FALSE`` respectively, is
@@ -82,6 +86,19 @@ The options are:
 ``OUTPUT_VARIABLE <var>``
   Store the output from the build process the given variable.
 
+``<LANG>_STANDARD <std>``
+  Specify the :prop_tgt:`C_STANDARD`, :prop_tgt:`CXX_STANDARD`,
+  or :prop_tgt:`CUDA_STANDARD` target property of the generated project.
+
+``<LANG>_STANDARD_REQUIRED <bool>``
+  Specify the :prop_tgt:`C_STANDARD_REQUIRED`,
+  :prop_tgt:`CXX_STANDARD_REQUIRED`, or :prop_tgt:`CUDA_STANDARD_REQUIRED`
+  target property of the generated project.
+
+``<LANG>_EXTENSIONS <bool>``
+  Specify the :prop_tgt:`C_EXTENSIONS`, :prop_tgt:`CXX_EXTENSIONS`,
+  or :prop_tgt:`CUDA_EXTENSIONS` target property of the generated project.
+
 In this version all files in ``<bindir>/CMakeFiles/CMakeTmp`` will be
 cleaned automatically.  For debugging, ``--debug-trycompile`` can be
 passed to ``cmake`` to avoid this clean.  However, multiple sequential
@@ -119,3 +136,20 @@ the type of target used for the source file signature.
 Set the :variable:`CMAKE_TRY_COMPILE_PLATFORM_VARIABLES` variable to specify
 variables that must be propagated into the test project.  This variable is
 meant for use only in toolchain files.
+
+If :policy:`CMP0067` is set to ``NEW``, or any of the ``<LANG>_STANDARD``,
+``<LANG>_STANDARD_REQUIRED``, or ``<LANG>_EXTENSIONS`` options are used,
+then the language standard variables are honored:
+
+* :variable:`CMAKE_C_STANDARD`
+* :variable:`CMAKE_C_STANDARD_REQUIRED`
+* :variable:`CMAKE_C_EXTENSIONS`
+* :variable:`CMAKE_CXX_STANDARD`
+* :variable:`CMAKE_CXX_STANDARD_REQUIRED`
+* :variable:`CMAKE_CXX_EXTENSIONS`
+* :variable:`CMAKE_CUDA_STANDARD`
+* :variable:`CMAKE_CUDA_STANDARD_REQUIRED`
+* :variable:`CMAKE_CUDA_EXTENSIONS`
+
+Their values are used to set the corresponding target properties in
+the generated project (unless overridden by an explicit option).
diff --git a/Help/generator/CodeBlocks.rst b/Help/generator/CodeBlocks.rst
index 01798c7..d03cb0c 100644
--- a/Help/generator/CodeBlocks.rst
+++ b/Help/generator/CodeBlocks.rst
@@ -18,6 +18,9 @@ This "extra" generator may be specified as:
 ``CodeBlocks - NMake Makefiles``
  Generate with :generator:`NMake Makefiles`.
 
+``CodeBlocks - NMake Makefiles JOM``
+ Generate with :generator:`NMake Makefiles JOM`.
+
 ``CodeBlocks - Ninja``
  Generate with :generator:`Ninja`.
 
diff --git a/Help/generator/VS_TOOLSET_HOST_ARCH.txt b/Help/generator/VS_TOOLSET_HOST_ARCH.txt
new file mode 100644
index 0000000..58e9223
--- /dev/null
+++ b/Help/generator/VS_TOOLSET_HOST_ARCH.txt
@@ -0,0 +1,10 @@
+For each toolset that comes with this version of Visual Studio, there are
+variants that are themselves compiled for 32-bit (x86) and 64-bit (x64) hosts
+(independent of the architecture they target).  By default Visual Studio
+chooses the 32-bit variant even on a 64-bit host.  One may request use of the
+64-bit host tools by adding ``host=x64`` to the toolset specification:
+
+``host=x64``
+  Select the 64-bit variant of the default toolset.
+``<toolset>,host=x64``
+  Select the 64-bit variant of the ``<toolset>`` toolset.
diff --git a/Help/generator/Visual Studio 10 2010.rst b/Help/generator/Visual Studio 10 2010.rst
index c694443..04eef10 100644
--- a/Help/generator/Visual Studio 10 2010.rst	
+++ b/Help/generator/Visual Studio 10 2010.rst	
@@ -17,3 +17,10 @@ a target platform name optionally at the end of this generator name:
 
 For compatibility with CMake versions prior to 3.0, one may specify this
 generator using the name ``Visual Studio 10`` without the year component.
+
+Toolset Selection
+^^^^^^^^^^^^^^^^^
+
+The ``v100`` toolset that comes with Visual Studio 10 2010 is selected by
+default.  The :variable:`CMAKE_GENERATOR_TOOLSET` option may be set, perhaps
+via the :manual:`cmake(1)` ``-T`` option, to specify another toolset.
diff --git a/Help/generator/Visual Studio 11 2012.rst b/Help/generator/Visual Studio 11 2012.rst
index 2f1e729..347a153 100644
--- a/Help/generator/Visual Studio 11 2012.rst	
+++ b/Help/generator/Visual Studio 11 2012.rst	
@@ -20,3 +20,10 @@ a target platform name optionally at the end of this generator 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.
+
+Toolset Selection
+^^^^^^^^^^^^^^^^^
+
+The ``v110`` toolset that comes with Visual Studio 11 2012 is selected by
+default.  The :variable:`CMAKE_GENERATOR_TOOLSET` option may be set, perhaps
+via the :manual:`cmake(1)` ``-T`` option, to specify another toolset.
diff --git a/Help/generator/Visual Studio 12 2013.rst b/Help/generator/Visual Studio 12 2013.rst
index 6e8545b..5071b20 100644
--- a/Help/generator/Visual Studio 12 2013.rst	
+++ b/Help/generator/Visual Studio 12 2013.rst	
@@ -17,3 +17,12 @@ a target platform name optionally at the end of this generator name:
 
 For compatibility with CMake versions prior to 3.0, one may specify this
 generator using the name "Visual Studio 12" without the year component.
+
+Toolset Selection
+^^^^^^^^^^^^^^^^^
+
+The ``v120`` toolset that comes with Visual Studio 12 2013 is selected by
+default.  The :variable:`CMAKE_GENERATOR_TOOLSET` option may be set, perhaps
+via the :manual:`cmake(1)` ``-T`` option, to specify another toolset.
+
+.. include:: VS_TOOLSET_HOST_ARCH.txt
diff --git a/Help/generator/Visual Studio 14 2015.rst b/Help/generator/Visual Studio 14 2015.rst
index 707caf9..64254b5 100644
--- a/Help/generator/Visual Studio 14 2015.rst	
+++ b/Help/generator/Visual Studio 14 2015.rst	
@@ -14,3 +14,12 @@ a target platform name optionally at the end of this generator name:
 
 ``Visual Studio 14 2015 ARM``
   Specify target platform ``ARM``.
+
+Toolset Selection
+^^^^^^^^^^^^^^^^^
+
+The ``v140`` toolset that comes with Visual Studio 14 2015 is selected by
+default.  The :variable:`CMAKE_GENERATOR_TOOLSET` option may be set, perhaps
+via the :manual:`cmake(1)` ``-T`` option, to specify another toolset.
+
+.. include:: VS_TOOLSET_HOST_ARCH.txt
diff --git a/Help/generator/Visual Studio 15 2017.rst b/Help/generator/Visual Studio 15 2017.rst
index 18b0131..a88f8bc 100644
--- a/Help/generator/Visual Studio 15 2017.rst	
+++ b/Help/generator/Visual Studio 15 2017.rst	
@@ -14,3 +14,12 @@ a target platform name optionally at the end of this generator name:
 
 ``Visual Studio 15 2017 ARM``
   Specify target platform ``ARM``.
+
+Toolset Selection
+^^^^^^^^^^^^^^^^^
+
+The ``v141`` toolset that comes with Visual Studio 15 2017 is selected by
+default.  The :variable:`CMAKE_GENERATOR_TOOLSET` option may be set, perhaps
+via the :manual:`cmake(1)` ``-T`` option, to specify another toolset.
+
+.. include:: VS_TOOLSET_HOST_ARCH.txt
diff --git a/Help/generator/Xcode.rst b/Help/generator/Xcode.rst
index d8a6790..25ff4c7 100644
--- a/Help/generator/Xcode.rst
+++ b/Help/generator/Xcode.rst
@@ -2,3 +2,10 @@ Xcode
 -----
 
 Generate Xcode project files.
+
+Toolset Selection
+^^^^^^^^^^^^^^^^^
+
+By default Xcode is allowed to select its own default toolchain.
+The :variable:`CMAKE_GENERATOR_TOOLSET` option may be set, perhaps
+via the :manual:`cmake(1)` ``-T`` option, to specify another toolset.
diff --git a/Help/manual/OPTIONS_BUILD.txt b/Help/manual/OPTIONS_BUILD.txt
index fa0e4c1..9b3f717 100644
--- a/Help/manual/OPTIONS_BUILD.txt
+++ b/Help/manual/OPTIONS_BUILD.txt
@@ -52,13 +52,12 @@
  Specify toolset name if supported by generator.
 
  Some CMake generators support a toolset name to be given to the
- native build system to choose a compiler.  This is supported only on
- specific generators:
-
- ::
+ native build system to choose a compiler.
+ See the :variable:`CMAKE_GENERATOR_TOOLSET` variable.
+ This is supported only on specific generators:
 
-   Visual Studio >= 10
-   Xcode >= 3.0
+ * :ref:`Visual Studio Generators` for VS 2010 and above
+ * The :generator:`Xcode` generator for Xcode 3.0 and above
 
  See native build system documentation for allowed toolset names.
 
diff --git a/Help/manual/cmake-buildsystem.7.rst b/Help/manual/cmake-buildsystem.7.rst
index 4950fee..2e6a803 100644
--- a/Help/manual/cmake-buildsystem.7.rst
+++ b/Help/manual/cmake-buildsystem.7.rst
@@ -964,6 +964,8 @@ are:
 * ``EXPORT_NAME``
 * ``IMPORTED``
 * ``NAME``
+* ``NO_SYSTEM_FROM_IMPORTED``
+* Properties matching ``IMPORTED_LIBNAME_*``
 * Properties matching ``MAP_IMPORTED_CONFIG_*``
 
 ``INTERFACE`` libraries may be installed and exported.  Any content they refer
diff --git a/Help/manual/cmake-compile-features.7.rst b/Help/manual/cmake-compile-features.7.rst
index 7289e61..448fe9a 100644
--- a/Help/manual/cmake-compile-features.7.rst
+++ b/Help/manual/cmake-compile-features.7.rst
@@ -84,6 +84,33 @@ Feature requirements are evaluated transitively by consuming the link
 implementation.  See :manual:`cmake-buildsystem(7)` for more on
 transitive behavior of build properties and usage requirements.
 
+Requiring Language Standards
+----------------------------
+
+In projects that use a large number of commonly available features from
+a particular language standard (e.g. C++ 11) one may specify a
+meta-feature (e.g. ``cxx_std_11``) that requires use of a compiler mode
+aware of that standard.  This is simpler than specifying all the
+features individually, but does not guarantee the existence of any
+particular feature.  Diagnosis of use of unsupported features will be
+delayed until compile time.
+
+For example, if C++ 11 features are used extensively in a project's
+header files, then clients must use a compiler mode aware of C++ 11
+or above.  This can be requested with the code:
+
+.. code-block:: cmake
+
+  target_compile_features(mylib PUBLIC cxx_std_11)
+
+In this example, CMake will ensure the compiler is invoked in a mode
+that is aware of C++ 11 (or above), adding flags such as
+``-std=gnu++11`` if necessary.  This applies to sources within ``mylib``
+as well as any dependents (that may include headers from ``mylib``).
+
+Availability of Compiler Extensions
+-----------------------------------
+
 Because the :prop_tgt:`CXX_EXTENSIONS` target property is ``ON`` by default,
 CMake uses extended variants of language dialects by default, such as
 ``-std=gnu++11`` instead of ``-std=c++11``.  That target property may be
@@ -299,7 +326,7 @@ the feature-appropriate include directory
 Supported Compilers
 ===================
 
-CMake is currently aware of the :prop_tgt:`language standards <CXX_STANDARD>`
+CMake is currently aware of the :prop_tgt:`C++ standards <CXX_STANDARD>`
 and :prop_gbl:`compile features <CMAKE_CXX_KNOWN_FEATURES>` available from
 the following :variable:`compiler ids <CMAKE_<LANG>_COMPILER_ID>` as of the
 versions specified for each:
@@ -309,4 +336,18 @@ versions specified for each:
 * ``GNU``: GNU compiler versions 4.4 through 5.0.
 * ``MSVC``: Microsoft Visual Studio versions 2010 through 2015.
 * ``SunPro``: Oracle SolarisStudio version 12.4.
-* ``Intel``: Intel compiler versions 12.1 through 16.0 on UNIX platforms.
+* ``Intel``: Intel compiler versions 12.1 through 17.0.
+
+CMake is currently aware of the :prop_tgt:`C standards <C_STANDARD>`
+and :prop_gbl:`compile features <CMAKE_C_KNOWN_FEATURES>` available from
+the following :variable:`compiler ids <CMAKE_<LANG>_COMPILER_ID>` as of the
+versions specified for each:
+
+* all compilers and versions listed above for C++
+* ``GNU``: GNU compiler versions 3.4 through 5.0.
+
+CMake is currently aware of the :prop_tgt:`CUDA standards <CUDA_STANDARD>`
+from the following :variable:`compiler ids <CMAKE_<LANG>_COMPILER_ID>` as of the
+versions specified for each:
+
+* ``NVIDIA``: NVIDIA nvcc compiler 7.5 though 8.0.
diff --git a/Help/manual/cmake-developer.7.rst b/Help/manual/cmake-developer.7.rst
index 6557686..f77d8c0 100644
--- a/Help/manual/cmake-developer.7.rst
+++ b/Help/manual/cmake-developer.7.rst
@@ -11,7 +11,7 @@ Introduction
 ============
 
 This manual is intended for reference by developers modifying the CMake
-source tree itself.
+source tree itself, and by those authoring externally-maintained modules.
 
 
 Permitted C++ Subset
@@ -540,7 +540,7 @@ a :ref:`Line Comment` block of the form:
 
 or a :ref:`Bracket Comment` of the form:
 
-.. code-block:: cmake
+::
 
  #[[.rst:
  <module-name>
@@ -558,7 +558,7 @@ All such comments must start with ``#`` in the first column.
 
 For example, a ``Modules/Findxxx.cmake`` module may contain:
 
-.. code-block:: cmake
+::
 
  # Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
  # file Copyright.txt or https://cmake.org/licensing for details.
diff --git a/Help/manual/cmake-generator-expressions.7.rst b/Help/manual/cmake-generator-expressions.7.rst
index 64d15a9..3a225ad 100644
--- a/Help/manual/cmake-generator-expressions.7.rst
+++ b/Help/manual/cmake-generator-expressions.7.rst
@@ -51,6 +51,8 @@ Available logical expressions are:
   ``0`` if all ``?`` are ``0``, else ``1``
 ``$<NOT:?>``
   ``0`` if ``?`` is ``1``, else ``1``
+``$<IF:?,true-value...,false-value...>```
+  ``true-value...`` if ``?`` is ``1``, ``false-value...`` if ``?`` is ``0``
 ``$<STREQUAL:a,b>``
   ``1`` if ``a`` is STREQUAL ``b``, else ``0``
 ``$<EQUAL:a,b>``
diff --git a/Help/manual/cmake-language.7.rst b/Help/manual/cmake-language.7.rst
index 41542c9..27b5d30 100644
--- a/Help/manual/cmake-language.7.rst
+++ b/Help/manual/cmake-language.7.rst
@@ -255,7 +255,7 @@ invocation as exactly one argument.
 
 For example:
 
-.. code-block:: cmake
+::
 
  message("This is a quoted argument containing multiple lines.
  This is always one argument even though it contains a ; character.
@@ -329,11 +329,17 @@ For example:
  To support legacy CMake code, unquoted arguments may also contain
  double-quoted strings (``"..."``, possibly enclosing horizontal
  whitespace), and make-style variable references (``$(MAKEVAR)``).
+
  Unescaped double-quotes must balance, may not appear at the
  beginning of an unquoted argument, and are treated as part of the
  content.  For example, the unquoted arguments ``-Da="b c"``,
  ``-Da=$(v)``, and ``a" "b"c"d`` are each interpreted literally.
 
+ Make-style references are treated literally as part of the content
+ and do not undergo variable expansion.  They are treated as part
+ of a single argument (rather than as separate ``$``, ``(``,
+ ``MAKEVAR``, and ``)`` arguments).
+
  The above "unquoted_legacy" production represents such arguments.
  We do not recommend using legacy unquoted arguments in new code.
  Instead use a `Quoted Argument`_ or a `Bracket Argument`_ to
@@ -421,7 +427,7 @@ A ``#`` immediately followed by a `Bracket Argument`_ forms a
 
 For example:
 
-.. code-block:: cmake
+::
 
  #[[This is a bracket comment.
  It runs until the close bracket.]]
diff --git a/Help/manual/cmake-modules.7.rst b/Help/manual/cmake-modules.7.rst
index 015e36e..c478a1b 100644
--- a/Help/manual/cmake-modules.7.rst
+++ b/Help/manual/cmake-modules.7.rst
@@ -59,12 +59,14 @@ All Modules
    /module/CPackDeb
    /module/CPackDMG
    /module/CPackIFW
+   /module/CPackIFWConfigureFile
    /module/CPackNSIS
    /module/CPackPackageMaker
    /module/CPackProductBuild
    /module/CPackRPM
    /module/CPack
    /module/CPackWIX
+   /module/CSharpUtilities
    /module/CTest
    /module/CTestCoverageCollectGCOV
    /module/CTestScriptMode
diff --git a/Help/manual/cmake-packages.7.rst b/Help/manual/cmake-packages.7.rst
index c27c612..c9442bc 100644
--- a/Help/manual/cmake-packages.7.rst
+++ b/Help/manual/cmake-packages.7.rst
@@ -449,12 +449,12 @@ be true. This can be tested with logic in the package configuration file:
   foreach(_comp ${ClimbingStats_FIND_COMPONENTS})
     if (NOT ";${_supported_components};" MATCHES _comp)
       set(ClimbingStats_FOUND False)
-      set(ClimbingStats_NOTFOUND_MESSAGE "Unsupported component: ${_comp}")
+      set(ClimbingStats_NOT_FOUND_MESSAGE "Unsupported component: ${_comp}")
     endif()
     include("${CMAKE_CURRENT_LIST_DIR}/ClimbingStats${_comp}Targets.cmake")
   endforeach()
 
-Here, the ``ClimbingStats_NOTFOUND_MESSAGE`` is set to a diagnosis that the package
+Here, the ``ClimbingStats_NOT_FOUND_MESSAGE`` is set to a diagnosis that the package
 could not be found because an invalid component was specified.  This message
 variable can be set for any case where the ``_FOUND`` variable is set to ``False``,
 and will be displayed to the user.
diff --git a/Help/manual/cmake-policies.7.rst b/Help/manual/cmake-policies.7.rst
index 0cfe983..3266958 100644
--- a/Help/manual/cmake-policies.7.rst
+++ b/Help/manual/cmake-policies.7.rst
@@ -51,6 +51,14 @@ The :variable:`CMAKE_MINIMUM_REQUIRED_VERSION` variable may also be used
 to determine whether to report an error on use of deprecated macros or
 functions.
 
+Policies Introduced by CMake 3.8
+================================
+
+.. toctree::
+   :maxdepth: 1
+
+   CMP0067: Honor language standard in try_compile() source-file signature. </policy/CMP0067>
+
 Policies Introduced by CMake 3.7
 ================================
 
diff --git a/Help/manual/cmake-properties.7.rst b/Help/manual/cmake-properties.7.rst
index 271f497..0e3eb86 100644
--- a/Help/manual/cmake-properties.7.rst
+++ b/Help/manual/cmake-properties.7.rst
@@ -44,6 +44,7 @@ Properties of Global Scope
    /prop_gbl/TARGET_MESSAGES
    /prop_gbl/TARGET_SUPPORTS_SHARED_LIBS
    /prop_gbl/USE_FOLDERS
+   /prop_gbl/XCODE_EMIT_EFFECTIVE_PLATFORM_NAME
 
 .. _`Directory Properties`:
 
@@ -121,6 +122,7 @@ Properties on Targets
    /prop_tgt/AUTORCC
    /prop_tgt/AUTORCC_OPTIONS
    /prop_tgt/BINARY_DIR
+   /prop_tgt/BUILD_RPATH
    /prop_tgt/BUILD_WITH_INSTALL_RPATH
    /prop_tgt/BUNDLE_EXTENSION
    /prop_tgt/BUNDLE
@@ -142,6 +144,10 @@ Properties on Targets
    /prop_tgt/CONFIG_OUTPUT_NAME
    /prop_tgt/CONFIG_POSTFIX
    /prop_tgt/CROSSCOMPILING_EMULATOR
+   /prop_tgt/CUDA_SEPARABLE_COMPILATION
+   /prop_tgt/CUDA_EXTENSIONS
+   /prop_tgt/CUDA_STANDARD
+   /prop_tgt/CUDA_STANDARD_REQUIRED
    /prop_tgt/CXX_EXTENSIONS
    /prop_tgt/CXX_STANDARD
    /prop_tgt/CXX_STANDARD_REQUIRED
@@ -166,6 +172,8 @@ Properties on Targets
    /prop_tgt/IMPORTED_CONFIGURATIONS
    /prop_tgt/IMPORTED_IMPLIB_CONFIG
    /prop_tgt/IMPORTED_IMPLIB
+   /prop_tgt/IMPORTED_LIBNAME_CONFIG
+   /prop_tgt/IMPORTED_LIBNAME
    /prop_tgt/IMPORTED_LINK_DEPENDENT_LIBRARIES_CONFIG
    /prop_tgt/IMPORTED_LINK_DEPENDENT_LIBRARIES
    /prop_tgt/IMPORTED_LINK_INTERFACE_LANGUAGES_CONFIG
@@ -204,6 +212,7 @@ Properties on Targets
    /prop_tgt/LABELS
    /prop_tgt/LANG_CLANG_TIDY
    /prop_tgt/LANG_COMPILER_LAUNCHER
+   /prop_tgt/LANG_CPPLINT
    /prop_tgt/LANG_INCLUDE_WHAT_YOU_USE
    /prop_tgt/LANG_VISIBILITY_PRESET
    /prop_tgt/LIBRARY_OUTPUT_DIRECTORY_CONFIG
@@ -229,6 +238,7 @@ Properties on Targets
    /prop_tgt/MACOSX_BUNDLE
    /prop_tgt/MACOSX_FRAMEWORK_INFO_PLIST
    /prop_tgt/MACOSX_RPATH
+   /prop_tgt/MANUALLY_ADDED_DEPENDENCIES
    /prop_tgt/MAP_IMPORTED_CONFIG_CONFIG
    /prop_tgt/NAME
    /prop_tgt/NO_SONAME
@@ -265,8 +275,11 @@ Properties on Targets
    /prop_tgt/VERSION
    /prop_tgt/VISIBILITY_INLINES_HIDDEN
    /prop_tgt/VS_CONFIGURATION_TYPE
+   /prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY
    /prop_tgt/VS_DESKTOP_EXTENSIONS_VERSION
+   /prop_tgt/VS_DOTNET_REFERENCE_refname
    /prop_tgt/VS_DOTNET_REFERENCES
+   /prop_tgt/VS_DOTNET_REFERENCES_COPY_LOCAL
    /prop_tgt/VS_DOTNET_TARGET_FRAMEWORK_VERSION
    /prop_tgt/VS_GLOBAL_KEYWORD
    /prop_tgt/VS_GLOBAL_PROJECT_TYPES
@@ -281,6 +294,7 @@ Properties on Targets
    /prop_tgt/VS_SCC_PROJECTNAME
    /prop_tgt/VS_SCC_PROVIDER
    /prop_tgt/VS_SDK_REFERENCES
+   /prop_tgt/VS_USER_PROPS
    /prop_tgt/VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION
    /prop_tgt/VS_WINRT_COMPONENT
    /prop_tgt/VS_WINRT_EXTENSIONS
@@ -288,6 +302,8 @@ Properties on Targets
    /prop_tgt/WIN32_EXECUTABLE
    /prop_tgt/WINDOWS_EXPORT_ALL_SYMBOLS
    /prop_tgt/XCODE_ATTRIBUTE_an-attribute
+   /prop_tgt/XCODE_EXPLICIT_FILE_TYPE
+   /prop_tgt/XCODE_PRODUCT_TYPE
    /prop_tgt/XCTEST
 
 .. _`Test Properties`:
@@ -344,9 +360,17 @@ Properties on Source Files
    /prop_sf/MACOSX_PACKAGE_LOCATION
    /prop_sf/OBJECT_DEPENDS
    /prop_sf/OBJECT_OUTPUTS
+   /prop_sf/SKIP_AUTOGEN
+   /prop_sf/SKIP_AUTOMOC
+   /prop_sf/SKIP_AUTORCC
+   /prop_sf/SKIP_AUTOUIC
    /prop_sf/SYMBOLIC
+   /prop_sf/VS_COPY_TO_OUT_DIR
+   /prop_sf/VS_CSHARP_tagname
    /prop_sf/VS_DEPLOYMENT_CONTENT
    /prop_sf/VS_DEPLOYMENT_LOCATION
+   /prop_sf/VS_INCLUDE_IN_VSIX
+   /prop_sf/VS_RESOURCE_GENERATOR
    /prop_sf/VS_SHADER_ENTRYPOINT
    /prop_sf/VS_SHADER_FLAGS
    /prop_sf/VS_SHADER_MODEL
diff --git a/Help/manual/cmake-qt.7.rst b/Help/manual/cmake-qt.7.rst
index 7827065..56d4ca7 100644
--- a/Help/manual/cmake-qt.7.rst
+++ b/Help/manual/cmake-qt.7.rst
@@ -22,12 +22,11 @@ Qt 4 and Qt 5 may be used together in the same
 
 .. code-block:: cmake
 
-  cmake_minimum_required(VERSION 3.0.0 FATAL_ERROR)
+  cmake_minimum_required(VERSION 3.8.0 FATAL_ERROR)
 
   project(Qt4And5)
 
   set(CMAKE_AUTOMOC ON)
-  set(CMAKE_INCLUDE_CURRENT_DIR ON)
 
   find_package(Qt5 COMPONENTS Widgets DBus REQUIRED)
   add_executable(publisher publisher.cpp)
@@ -73,14 +72,20 @@ The ``moc`` command line will consume the :prop_tgt:`COMPILE_DEFINITIONS` and
 :prop_tgt:`INCLUDE_DIRECTORIES` target properties from the target it is being
 invoked for, and for the appropriate build configuration.
 
-Generated ``moc_*.cpp`` and ``*.moc`` files are placed in the build directory
-so it is convenient to set the :variable:`CMAKE_INCLUDE_CURRENT_DIR`
-variable.  The :prop_tgt:`AUTOMOC` target property may be pre-set for all
+The generated ``moc_*.cpp`` and ``*.moc`` files are placed in the
+``<CMAKE_CURRENT_BINARY_DIR>/<TARGETNAME>_autogen/include`` directory which is
+automatically added to the target's :prop_tgt:`INCLUDE_DIRECTORIES`.
+(This differs from CMake 3.7 and below; see their documentation for details.)
+
+The :prop_tgt:`AUTOMOC` target property may be pre-set for all
 following targets by setting the :variable:`CMAKE_AUTOMOC` variable.  The
 :prop_tgt:`AUTOMOC_MOC_OPTIONS` target property may be populated to set
 options to pass to ``moc``. The :variable:`CMAKE_AUTOMOC_MOC_OPTIONS`
 variable may be populated to pre-set the options for all following targets.
 
+Source C++ files can be excluded from :prop_tgt:`AUTOMOC` processing by
+enabling :prop_sf:`SKIP_AUTOMOC` or the broader :prop_sf:`SKIP_AUTOGEN`.
+
 .. _`Qt AUTOUIC`:
 
 AUTOUIC
@@ -94,10 +99,13 @@ If a preprocessor ``#include`` directive is found which matches
 ``ui_<basename>.h``, and a ``<basename>.ui`` file exists, then ``uic`` will
 be executed to generate the appropriate file.
 
-Generated ``ui_*.h`` files are placed in the build directory so it is
-convenient to set the :variable:`CMAKE_INCLUDE_CURRENT_DIR` variable.  The
-:prop_tgt:`AUTOUIC` target property may be pre-set for all following targets
-by setting the :variable:`CMAKE_AUTOUIC` variable.  The
+The generated generated ``ui_*.h`` files are placed in the
+``<CMAKE_CURRENT_BINARY_DIR>/<TARGETNAME>_autogen/include`` directory which is
+automatically added to the target's :prop_tgt:`INCLUDE_DIRECTORIES`.
+(This differs from CMake 3.7 and below; see their documentation for details.)
+
+The :prop_tgt:`AUTOUIC` target property may be pre-set for all following
+targets by setting the :variable:`CMAKE_AUTOUIC` variable.  The
 :prop_tgt:`AUTOUIC_OPTIONS` target property may be populated to set options
 to pass to ``uic``.  The :variable:`CMAKE_AUTOUIC_OPTIONS` variable may be
 populated to pre-set the options for all following targets.  The
@@ -144,6 +152,9 @@ result of linking with the :prop_tgt:`IMPORTED` target:
     Qt5::Widgets
   )
 
+Source files can be excluded from :prop_tgt:`AUTOUIC` processing by
+enabling :prop_sf:`SKIP_AUTOUIC` or the broader :prop_sf:`SKIP_AUTOGEN`.
+
 .. _`Qt AUTORCC`:
 
 AUTORCC
@@ -166,6 +177,9 @@ populated to pre-set the options for all following targets.  The
 ``<name>.qrc`` file to set particular options for the file.  This
 overrides options from the :prop_tgt:`AUTORCC_OPTIONS` target property.
 
+Source files can be excluded from :prop_tgt:`AUTORCC` processing by
+enabling :prop_sf:`SKIP_AUTORCC` or the broader :prop_sf:`SKIP_AUTOGEN`.
+
 qtmain.lib on Windows
 =====================
 
diff --git a/Help/manual/cmake-variables.7.rst b/Help/manual/cmake-variables.7.rst
index 31c0a84..38444d1 100644
--- a/Help/manual/cmake-variables.7.rst
+++ b/Help/manual/cmake-variables.7.rst
@@ -82,6 +82,7 @@ Variables that Provide Information
    /variable/CMAKE_VS_NsightTegra_VERSION
    /variable/CMAKE_VS_PLATFORM_NAME
    /variable/CMAKE_VS_PLATFORM_TOOLSET
+   /variable/CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE
    /variable/CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION
    /variable/CMAKE_XCODE_PLATFORM_TOOLSET
    /variable/PROJECT_BINARY_DIR
@@ -160,6 +161,8 @@ Variables that Change Behavior
    /variable/CMAKE_PROJECT_PROJECT-NAME_INCLUDE
    /variable/CMAKE_SKIP_INSTALL_ALL_DEPENDENCY
    /variable/CMAKE_STAGING_PREFIX
+   /variable/CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS
+   /variable/CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE
    /variable/CMAKE_SYSTEM_APPBUNDLE_PATH
    /variable/CMAKE_SYSTEM_FRAMEWORK_PATH
    /variable/CMAKE_SYSTEM_IGNORE_PATH
@@ -259,6 +262,7 @@ Variables that Control the Build
    /variable/CMAKE_AUTORCC_OPTIONS
    /variable/CMAKE_AUTOUIC
    /variable/CMAKE_AUTOUIC_OPTIONS
+   /variable/CMAKE_BUILD_RPATH
    /variable/CMAKE_BUILD_WITH_INSTALL_RPATH
    /variable/CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY
    /variable/CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY_CONFIG
@@ -280,6 +284,7 @@ Variables that Control the Build
    /variable/CMAKE_IOS_INSTALL_COMBINED
    /variable/CMAKE_LANG_CLANG_TIDY
    /variable/CMAKE_LANG_COMPILER_LAUNCHER
+   /variable/CMAKE_LANG_CPPLINT
    /variable/CMAKE_LANG_INCLUDE_WHAT_YOU_USE
    /variable/CMAKE_LANG_VISIBILITY_PRESET
    /variable/CMAKE_LIBRARY_OUTPUT_DIRECTORY
@@ -325,6 +330,7 @@ Variables that Control the Build
    /variable/CMAKE_USE_RELATIVE_PATHS
    /variable/CMAKE_VISIBILITY_INLINES_HIDDEN
    /variable/CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD
+   /variable/CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD
    /variable/CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS
    /variable/CMAKE_WIN32_EXECUTABLE
    /variable/CMAKE_XCODE_ATTRIBUTE_an-attribute
@@ -344,6 +350,10 @@ Variables for Languages
    /variable/CMAKE_C_EXTENSIONS
    /variable/CMAKE_C_STANDARD
    /variable/CMAKE_C_STANDARD_REQUIRED
+   /variable/CMAKE_CUDA_EXTENSIONS
+   /variable/CMAKE_CUDA_STANDARD
+   /variable/CMAKE_CUDA_STANDARD_REQUIRED
+   /variable/CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES
    /variable/CMAKE_CXX_COMPILE_FEATURES
    /variable/CMAKE_CXX_EXTENSIONS
    /variable/CMAKE_CXX_STANDARD
diff --git a/Help/manual/cmake.1.rst b/Help/manual/cmake.1.rst
index 063aea1..37e50d2 100644
--- a/Help/manual/cmake.1.rst
+++ b/Help/manual/cmake.1.rst
@@ -263,8 +263,10 @@ Available commands are:
      052f86c15bbde68af55c7f7b340ab639  file2.txt
 
 ``remove [-f] <file>...``
-  Remove the file(s), use ``-f`` to force it.  If a file does
-  not exist it will be silently ignored.
+  Remove the file(s). If any of the listed files already do not
+  exist, the command returns a non-zero exit code, but no message
+  is logged. The ``-f`` option changes the behavior to return a
+  zero exit code (i.e. success) in such situations instead.
 
 ``remove_directory <dir>``
   Remove a directory and its contents.  If a directory does
diff --git a/Help/module/CPackIFWConfigureFile.rst b/Help/module/CPackIFWConfigureFile.rst
new file mode 100644
index 0000000..e88517c
--- /dev/null
+++ b/Help/module/CPackIFWConfigureFile.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/CPackIFWConfigureFile.cmake
diff --git a/Help/module/CSharpUtilities.rst b/Help/module/CSharpUtilities.rst
new file mode 100644
index 0000000..3621bbc
--- /dev/null
+++ b/Help/module/CSharpUtilities.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/CSharpUtilities.cmake
diff --git a/Help/policy/CMP0067.rst b/Help/policy/CMP0067.rst
new file mode 100644
index 0000000..e6dda80
--- /dev/null
+++ b/Help/policy/CMP0067.rst
@@ -0,0 +1,37 @@
+CMP0067
+-------
+
+Honor language standard in :command:`try_compile` source-file signature.
+
+The :command:`try_compile` source file signature is intended to allow
+callers to check whether they will be able to compile a given source file
+with the current toolchain.  In order to match compiler behavior, any
+language standard mode should match.  However, CMake 3.7 and below did not
+do this.  CMake 3.8 and above prefer to honor the language standard settings
+for ``C``, ``CXX`` (C++), and ``CUDA`` using the values of the variables:
+
+* :variable:`CMAKE_C_STANDARD`
+* :variable:`CMAKE_C_STANDARD_REQUIRED`
+* :variable:`CMAKE_C_EXTENSIONS`
+* :variable:`CMAKE_CXX_STANDARD`
+* :variable:`CMAKE_CXX_STANDARD_REQUIRED`
+* :variable:`CMAKE_CXX_EXTENSIONS`
+* :variable:`CMAKE_CUDA_STANDARD`
+* :variable:`CMAKE_CUDA_STANDARD_REQUIRED`
+* :variable:`CMAKE_CUDA_EXTENSIONS`
+
+This policy provides compatibility for projects that do not expect
+the language standard settings to be used automatically.
+
+The ``OLD`` behavior of this policy is to ignore language standard
+setting variables when generating the ``try_compile`` test project.
+The ``NEW`` behavior of this policy is to honor language standard
+setting variables.
+
+This policy was introduced in CMake version 3.8.  Unlike most policies,
+CMake version |release| does *not* warn by default when this policy
+is not set and simply uses OLD behavior.  See documentation of the
+:variable:`CMAKE_POLICY_WARNING_CMP0067 <CMAKE_POLICY_WARNING_CMP<NNNN>>`
+variable to control the warning.
+
+.. include:: DEPRECATED.txt
diff --git a/Help/prop_gbl/AUTOGEN_TARGETS_FOLDER.rst b/Help/prop_gbl/AUTOGEN_TARGETS_FOLDER.rst
index 5a69ef3..fae5626 100644
--- a/Help/prop_gbl/AUTOGEN_TARGETS_FOLDER.rst
+++ b/Help/prop_gbl/AUTOGEN_TARGETS_FOLDER.rst
@@ -1,7 +1,7 @@
 AUTOGEN_TARGETS_FOLDER
 ----------------------
 
-Name of :prop_tgt:`FOLDER` for ``*_automoc`` targets that are added automatically by
+Name of :prop_tgt:`FOLDER` for ``*_autogen`` targets that are added automatically by
 CMake for targets for which :prop_tgt:`AUTOMOC` is enabled.
 
 If not set, CMake uses the :prop_tgt:`FOLDER` property of the parent target as a
diff --git a/Help/prop_gbl/AUTOMOC_TARGETS_FOLDER.rst b/Help/prop_gbl/AUTOMOC_TARGETS_FOLDER.rst
index 671f86a..17666e4 100644
--- a/Help/prop_gbl/AUTOMOC_TARGETS_FOLDER.rst
+++ b/Help/prop_gbl/AUTOMOC_TARGETS_FOLDER.rst
@@ -1,7 +1,7 @@
 AUTOMOC_TARGETS_FOLDER
 ----------------------
 
-Name of :prop_tgt:`FOLDER` for ``*_automoc`` targets that are added automatically by
+Name of :prop_tgt:`FOLDER` for ``*_autogen`` targets that are added automatically by
 CMake for targets for which :prop_tgt:`AUTOMOC` is enabled.
 
 This property is obsolete.  Use :prop_gbl:`AUTOGEN_TARGETS_FOLDER` instead.
diff --git a/Help/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.rst b/Help/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.rst
index e8f4d2a..2ad8157 100644
--- a/Help/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.rst
+++ b/Help/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.rst
@@ -14,6 +14,18 @@ compile features and a list of supported compilers.
 
 The features known to this version of CMake are:
 
+``cxx_std_98``
+  Compiler mode is aware of C++ 98.
+
+``cxx_std_11``
+  Compiler mode is aware of C++ 11.
+
+``cxx_std_14``
+  Compiler mode is aware of C++ 14.
+
+``cxx_std_17``
+  Compiler mode is aware of C++ 17.
+
 ``cxx_aggregate_default_initializers``
   Aggregate default initializers, as defined in N3605_.
 
diff --git a/Help/prop_gbl/CMAKE_C_KNOWN_FEATURES.rst b/Help/prop_gbl/CMAKE_C_KNOWN_FEATURES.rst
index a08af00..3707fef 100644
--- a/Help/prop_gbl/CMAKE_C_KNOWN_FEATURES.rst
+++ b/Help/prop_gbl/CMAKE_C_KNOWN_FEATURES.rst
@@ -13,6 +13,15 @@ compile features and a list of supported compilers.
 
 The features known to this version of CMake are:
 
+``c_std_90``
+  Compiler mode is aware of C 90.
+
+``c_std_99``
+  Compiler mode is aware of C 99.
+
+``c_std_11``
+  Compiler mode is aware of C 11.
+
 ``c_function_prototypes``
   Function prototypes, as defined in ``ISO/IEC 9899:1990``.
 
diff --git a/Help/prop_gbl/XCODE_EMIT_EFFECTIVE_PLATFORM_NAME.rst b/Help/prop_gbl/XCODE_EMIT_EFFECTIVE_PLATFORM_NAME.rst
new file mode 100644
index 0000000..9a6086e
--- /dev/null
+++ b/Help/prop_gbl/XCODE_EMIT_EFFECTIVE_PLATFORM_NAME.rst
@@ -0,0 +1,24 @@
+XCODE_EMIT_EFFECTIVE_PLATFORM_NAME
+----------------------------------
+
+Control emission of ``EFFECTIVE_PLATFORM_NAME`` by the Xcode generator.
+
+It is required for building the same target with multiple SDKs. A
+common use case is the parallel use of ``iphoneos`` and
+``iphonesimulator`` SDKs.
+
+Three different states possible that control when the Xcode generator
+emits the ``EFFECTIVE_PLATFORM_NAME`` variable:
+
+- If set to ``ON`` it will always be emitted
+- If set to ``OFF`` it will never be emitted
+- If unset (the default) it will only be emitted when the project was
+  configured for an embedded Xcode SDK like iOS, tvOS, watchOS or any
+  of the simulators.
+
+.. note::
+
+  When this behavior is enable for generated Xcode projects, the
+  ``EFFECTIVE_PLATFORM_NAME`` variable will leak into
+  :manual:`Generator expressions <cmake-generator-expressions(7)>`
+  like ``TARGET_FILE`` and will render those mostly unusable.
diff --git a/Help/prop_sf/COMPILE_FLAGS.rst b/Help/prop_sf/COMPILE_FLAGS.rst
index 086a063..1012164 100644
--- a/Help/prop_sf/COMPILE_FLAGS.rst
+++ b/Help/prop_sf/COMPILE_FLAGS.rst
@@ -6,3 +6,10 @@ Additional flags to be added when compiling this source file.
 These flags will be added to the list of compile flags when this
 source file builds.  Use :prop_sf:`COMPILE_DEFINITIONS` to pass
 additional preprocessor definitions.
+
+Contents of ``COMPILE_FLAGS`` may use "generator expressions"
+with the syntax ``$<...>``.  See the :manual:`cmake-generator-expressions(7)`
+manual for available expressions.  However, :generator:`Xcode`
+does not support per-config per-source settings, so expressions
+that depend on the build configuration are not allowed with that
+generator.
diff --git a/Help/prop_sf/SKIP_AUTOGEN.rst b/Help/prop_sf/SKIP_AUTOGEN.rst
new file mode 100644
index 0000000..6bf2409
--- /dev/null
+++ b/Help/prop_sf/SKIP_AUTOGEN.rst
@@ -0,0 +1,8 @@
+SKIP_AUTOGEN
+------------
+
+Exclude the source file from :prop_tgt:`AUTOMOC`, :prop_tgt:`AUTOUIC` and
+:prop_tgt:`AUTORCC` processing (for Qt projects).
+
+For finer control see :prop_sf:`SKIP_AUTOMOC`, :prop_sf:`SKIP_AUTOUIC` and
+:prop_sf:`SKIP_AUTORCC`.
diff --git a/Help/prop_sf/SKIP_AUTOMOC.rst b/Help/prop_sf/SKIP_AUTOMOC.rst
new file mode 100644
index 0000000..2245ca6
--- /dev/null
+++ b/Help/prop_sf/SKIP_AUTOMOC.rst
@@ -0,0 +1,6 @@
+SKIP_AUTOMOC
+------------
+
+Exclude the source file from :prop_tgt:`AUTOMOC` processing (for Qt projects).
+
+For broader control see :prop_sf:`SKIP_AUTOGEN`
diff --git a/Help/prop_sf/SKIP_AUTORCC.rst b/Help/prop_sf/SKIP_AUTORCC.rst
new file mode 100644
index 0000000..394d8f8
--- /dev/null
+++ b/Help/prop_sf/SKIP_AUTORCC.rst
@@ -0,0 +1,6 @@
+SKIP_AUTORCC
+------------
+
+Exclude the source file from :prop_tgt:`AUTORCC` processing (for Qt projects).
+
+For broader control see :prop_sf:`SKIP_AUTOGEN`
diff --git a/Help/prop_sf/SKIP_AUTOUIC.rst b/Help/prop_sf/SKIP_AUTOUIC.rst
new file mode 100644
index 0000000..50f78ef
--- /dev/null
+++ b/Help/prop_sf/SKIP_AUTOUIC.rst
@@ -0,0 +1,6 @@
+SKIP_AUTOUIC
+------------
+
+Exclude the source file from :prop_tgt:`AUTOUIC` processing (for Qt projects).
+
+For broader control see :prop_sf:`SKIP_AUTOGEN`
diff --git a/Help/prop_sf/VS_COPY_TO_OUT_DIR.rst b/Help/prop_sf/VS_COPY_TO_OUT_DIR.rst
new file mode 100644
index 0000000..16c8d83
--- /dev/null
+++ b/Help/prop_sf/VS_COPY_TO_OUT_DIR.rst
@@ -0,0 +1,6 @@
+VS_COPY_TO_OUT_DIR
+------------------
+
+Sets the ``<CopyToOutputDirectory>`` tag for a source file in a
+Visual Studio project file. Valid values are ``Never``, ``Always``
+and ``PreserveNewest``.
diff --git a/Help/prop_sf/VS_CSHARP_tagname.rst b/Help/prop_sf/VS_CSHARP_tagname.rst
new file mode 100644
index 0000000..d42159f
--- /dev/null
+++ b/Help/prop_sf/VS_CSHARP_tagname.rst
@@ -0,0 +1,19 @@
+VS_CSHARP_<tagname>
+-------------------
+
+Visual Studio and CSharp source-file-specific configuration.
+
+Tell the Visual Studio generator to set the source file tag
+``<tagname>`` to a given value in the generated Visual Studio CSharp
+project. Ignored on other generators and languages. This property
+can be used to define dependencies between source files or set any
+other Visual Studio specific parameters.
+
+Example usage:
+
+.. code-block:: cmake
+
+  set_source_files_property(<filename>
+           PROPERTIES
+           VS_CSHARP_DependentUpon <other file>
+           VS_CSHARP_SubType "Form")
diff --git a/Help/prop_sf/VS_INCLUDE_IN_VSIX.rst b/Help/prop_sf/VS_INCLUDE_IN_VSIX.rst
new file mode 100644
index 0000000..30f471d
--- /dev/null
+++ b/Help/prop_sf/VS_INCLUDE_IN_VSIX.rst
@@ -0,0 +1,6 @@
+VS_INCLUDE_IN_VSIX
+------------------
+
+Boolean property to specify if the file should be included within a VSIX
+extension package. This is needed for development of Visual Studio
+extensions.
diff --git a/Help/prop_sf/VS_RESOURCE_GENERATOR.rst b/Help/prop_sf/VS_RESOURCE_GENERATOR.rst
new file mode 100644
index 0000000..97e5aac
--- /dev/null
+++ b/Help/prop_sf/VS_RESOURCE_GENERATOR.rst
@@ -0,0 +1,8 @@
+VS_RESOURCE_GENERATOR
+---------------------
+
+This property allows to specify the resource generator to be used
+on this file. It defaults to ``PublicResXFileCodeGenerator`` if
+not set.
+
+This property only applies to C# projects.
diff --git a/Help/prop_test/TIMEOUT_AFTER_MATCH.rst b/Help/prop_test/TIMEOUT_AFTER_MATCH.rst
index a191a9c..d607992 100644
--- a/Help/prop_test/TIMEOUT_AFTER_MATCH.rst
+++ b/Help/prop_test/TIMEOUT_AFTER_MATCH.rst
@@ -22,7 +22,9 @@ When the test outputs a line that matches ``regex`` its start time is
 reset to the current time and its timeout duration is changed to
 ``seconds``.  Prior to this, the timeout duration is determined by the
 :prop_test:`TIMEOUT` property or the :variable:`CTEST_TEST_TIMEOUT`
-variable if either of these are set.
+variable if either of these are set.  Because the test's start time is
+reset, its execution time will not include any time that was spent
+waiting for the matching output.
 
 :prop_test:`TIMEOUT_AFTER_MATCH` is useful for avoiding spurious
 timeouts when your test must wait for some system resource to become
diff --git a/Help/prop_tgt/AUTOGEN_TARGET_DEPENDS.rst b/Help/prop_tgt/AUTOGEN_TARGET_DEPENDS.rst
index 5063244..f522c6b 100644
--- a/Help/prop_tgt/AUTOGEN_TARGET_DEPENDS.rst
+++ b/Help/prop_tgt/AUTOGEN_TARGET_DEPENDS.rst
@@ -1,16 +1,16 @@
 AUTOGEN_TARGET_DEPENDS
 ----------------------
 
-Target dependencies of the corresponding ``_automoc`` target.
+Target dependencies of the corresponding ``_autogen`` target.
 
 Targets which have their :prop_tgt:`AUTOMOC` target ``ON`` have a
-corresponding ``_automoc`` target which is used to autogenerate generate moc
-files.  As this ``_automoc`` target is created at generate-time, it is not
+corresponding ``_autogen`` target which is used to autogenerate generate moc
+files.  As this ``_autogen`` target is created at generate-time, it is not
 possible to define dependencies of it, such as to create inputs for the ``moc``
 executable.
 
 The ``AUTOGEN_TARGET_DEPENDS`` target property can be set instead to a list of
-dependencies for the ``_automoc`` target.  The buildsystem will be generated to
+dependencies for the ``_autogen`` target.  The buildsystem will be generated to
 depend on its contents.
 
 See the :manual:`cmake-qt(7)` manual for more information on using CMake
diff --git a/Help/prop_tgt/AUTOMOC.rst b/Help/prop_tgt/AUTOMOC.rst
index 8143ba9..b42643f 100644
--- a/Help/prop_tgt/AUTOMOC.rst
+++ b/Help/prop_tgt/AUTOMOC.rst
@@ -15,11 +15,12 @@ source files at build time and invoke moc accordingly.
   the ``Q_OBJECT`` class declaration is expected in the header, and
   ``moc`` is run on the header file.  A ``moc_foo.cpp`` file will be
   generated from the source's header into the
-  :variable:`CMAKE_CURRENT_BINARY_DIR` directory.  This allows the
-  compiler to find the included ``moc_foo.cpp`` file regardless of the
-  location the original source.  However, if multiple source files
-  in different directories do this then their generated moc files would
-  collide.  In this case a diagnostic will be issued.
+  ``<CMAKE_CURRENT_BINARY_DIR>/<TARGETNAME>_autogen/include``
+  directory which is automatically added to the target's
+  :prop_tgt:`INCLUDE_DIRECTORIES`.  This allows the compiler to find the
+  included ``moc_foo.cpp`` file regardless of the location the original source.
+  However, if multiple source files in different directories do this then their
+  generated moc files would collide.  In this case a diagnostic will be issued.
 
 * If an ``#include`` statement like ``#include "foo.moc"`` is found,
   then a ``Q_OBJECT`` is expected in the current source file and ``moc``
@@ -30,7 +31,7 @@ source files at build time and invoke moc accordingly.
   alternative extensions, such as ``hpp``, ``hxx`` etc when searching
   for headers.  The resulting moc files, which are not included as shown
   above in any of the source files are included in a generated
-  ``<targetname>_automoc.cpp`` file, which is compiled as part of the
+  ``moc_compilation.cpp`` file, which is compiled as part of the
   target.
 
 This property is initialized by the value of the :variable:`CMAKE_AUTOMOC`
@@ -46,5 +47,8 @@ See the documentation for this variable for more details.
 The global property :prop_gbl:`AUTOGEN_TARGETS_FOLDER` can be used to group the
 automoc targets together in an IDE, e.g.  in MSVS.
 
+Source C++ files can be excluded from :prop_tgt:`AUTOMOC` processing by
+enabling :prop_sf:`SKIP_AUTOMOC` or the broader :prop_sf:`SKIP_AUTOGEN`.
+
 See the :manual:`cmake-qt(7)` manual for more information on using CMake
 with Qt.
diff --git a/Help/prop_tgt/AUTORCC.rst b/Help/prop_tgt/AUTORCC.rst
index 158fdf8..1ad0895 100644
--- a/Help/prop_tgt/AUTORCC.rst
+++ b/Help/prop_tgt/AUTORCC.rst
@@ -24,5 +24,8 @@ generate unspecified unique names for ``rcc``.  Therefore if
 ``Q_INIT_RESOURCE()`` or ``Q_CLEANUP_RESOURCE()`` need to be used the
 ``.qrc`` file name must be unique.
 
+Source files can be excluded from :prop_tgt:`AUTORCC` processing by
+enabling :prop_sf:`SKIP_AUTORCC` or the broader :prop_sf:`SKIP_AUTOGEN`.
+
 See the :manual:`cmake-qt(7)` manual for more information on using CMake
 with Qt.
diff --git a/Help/prop_tgt/AUTOUIC.rst b/Help/prop_tgt/AUTOUIC.rst
index 4e60ec3..fbf24c3 100644
--- a/Help/prop_tgt/AUTOUIC.rst
+++ b/Help/prop_tgt/AUTOUIC.rst
@@ -20,5 +20,8 @@ Additional command line options for ``uic`` can be set via the
 The global property :prop_gbl:`AUTOGEN_TARGETS_FOLDER` can be used to group the
 autouic targets together in an IDE, e.g. in MSVS.
 
+Source files can be excluded from :prop_tgt:`AUTOUIC` processing by
+enabling :prop_sf:`SKIP_AUTOUIC` or the broader :prop_sf:`SKIP_AUTOGEN`.
+
 See the :manual:`cmake-qt(7)` manual for more information on using CMake
 with Qt.
diff --git a/Help/prop_tgt/BUILD_RPATH.rst b/Help/prop_tgt/BUILD_RPATH.rst
new file mode 100644
index 0000000..27393f5
--- /dev/null
+++ b/Help/prop_tgt/BUILD_RPATH.rst
@@ -0,0 +1,10 @@
+BUILD_RPATH
+-----------
+
+A :ref:`;-list <CMake Language Lists>` specifying runtime path (``RPATH``)
+entries to add to binaries linked in the build tree (for platforms that
+support it).  The entries will *not* be used for binaries in the install
+tree.  See also the :prop_tgt:`INSTALL_RPATH` target property.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_BUILD_RPATH` if it is set when a target is created.
diff --git a/Help/prop_tgt/CROSSCOMPILING_EMULATOR.rst b/Help/prop_tgt/CROSSCOMPILING_EMULATOR.rst
index d30a2f2..a0811bc 100644
--- a/Help/prop_tgt/CROSSCOMPILING_EMULATOR.rst
+++ b/Help/prop_tgt/CROSSCOMPILING_EMULATOR.rst
@@ -5,3 +5,7 @@ Use the given emulator to run executables created when crosscompiling.
 This command will be added as a prefix to :command:`add_test`,
 :command:`add_custom_command`, and :command:`add_custom_target` commands
 for built target system executables.
+
+This property is initialized by the value of the
+:variable:`CMAKE_CROSSCOMPILING_EMULATOR` variable if it is set when a target
+is created.
diff --git a/Help/prop_tgt/CUDA_EXTENSIONS.rst b/Help/prop_tgt/CUDA_EXTENSIONS.rst
new file mode 100644
index 0000000..098ca3c
--- /dev/null
+++ b/Help/prop_tgt/CUDA_EXTENSIONS.rst
@@ -0,0 +1,17 @@
+CUDA_EXTENSIONS
+---------------
+
+Boolean specifying whether compiler specific extensions are requested.
+
+This property specifies whether compiler specific extensions should be
+used.  For some compilers, this results in adding a flag such
+as ``-std=gnu++11`` instead of ``-std=c++11`` to the compile line.  This
+property is ``ON`` by default. The basic CUDA/C++ standard level is
+controlled by the :prop_tgt:`CUDA_STANDARD` target property.
+
+See the :manual:`cmake-compile-features(7)` manual for information on
+compile features and a list of supported compilers.
+
+This property is initialized by the value of
+the :variable:`CMAKE_CUDA_EXTENSIONS` variable if it is set when a target
+is created.
diff --git a/Help/prop_tgt/CUDA_SEPARABLE_COMPILATION.rst b/Help/prop_tgt/CUDA_SEPARABLE_COMPILATION.rst
new file mode 100644
index 0000000..1c7dd80
--- /dev/null
+++ b/Help/prop_tgt/CUDA_SEPARABLE_COMPILATION.rst
@@ -0,0 +1,13 @@
+CUDA_SEPARABLE_COMPILATION
+--------------------------
+
+CUDA only: Enables separate compilation of device code
+
+If set this will enable separable compilation for all CUDA files for
+the given target.
+
+For instance:
+
+.. code-block:: cmake
+
+  set_property(TARGET myexe PROPERTY CUDA_SEPARABLE_COMPILATION ON)
diff --git a/Help/prop_tgt/CUDA_STANDARD.rst b/Help/prop_tgt/CUDA_STANDARD.rst
new file mode 100644
index 0000000..b262814
--- /dev/null
+++ b/Help/prop_tgt/CUDA_STANDARD.rst
@@ -0,0 +1,32 @@
+CUDA_STANDARD
+-------------
+
+The CUDA/C++ standard whose features are requested to build this target.
+
+This property specifies the CUDA/C++ standard whose features are requested
+to build this target.  For some compilers, this results in adding a
+flag such as ``-std=gnu++11`` to the compile line.
+
+Supported values are ``98``, ``11``.
+
+If the value requested does not result in a compile flag being added for
+the compiler in use, a previous standard flag will be added instead.  This
+means that using:
+
+.. code-block:: cmake
+
+  set_property(TARGET tgt PROPERTY CUDA_STANDARD 11)
+
+with a compiler which does not support ``-std=gnu++11`` or an equivalent
+flag will not result in an error or warning, but will instead add the
+``-std=gnu++98`` flag if supported.  This "decay" behavior may be controlled
+with the :prop_tgt:`CUDA_STANDARD_REQUIRED` target property.
+Additionally, the :prop_tgt:`CUDA_EXTENSIONS` target property may be used to
+control whether compiler-specific extensions are enabled on a per-target basis.
+
+See the :manual:`cmake-compile-features(7)` manual for information on
+compile features and a list of supported compilers.
+
+This property is initialized by the value of
+the :variable:`CMAKE_CUDA_STANDARD` variable if it is set when a target
+is created.
diff --git a/Help/prop_tgt/CUDA_STANDARD_REQUIRED.rst b/Help/prop_tgt/CUDA_STANDARD_REQUIRED.rst
new file mode 100644
index 0000000..b2d5b28
--- /dev/null
+++ b/Help/prop_tgt/CUDA_STANDARD_REQUIRED.rst
@@ -0,0 +1,18 @@
+CUDA_STANDARD_REQUIRED
+----------------------
+
+Boolean describing whether the value of :prop_tgt:`CUDA_STANDARD` is a requirement.
+
+If this property is set to ``ON``, then the value of the
+:prop_tgt:`CUDA_STANDARD` target property is treated as a requirement.  If this
+property is ``OFF`` or unset, the :prop_tgt:`CUDA_STANDARD` target property is
+treated as optional and may "decay" to a previous standard if the requested is
+not available.  For compilers that have no notion of a standard level, such as
+MSVC, this has no effect.
+
+See the :manual:`cmake-compile-features(7)` manual for information on
+compile features and a list of supported compilers.
+
+This property is initialized by the value of
+the :variable:`CMAKE_CUDA_STANDARD_REQUIRED` variable if it is set when a
+target is created.
diff --git a/Help/prop_tgt/CXX_STANDARD.rst b/Help/prop_tgt/CXX_STANDARD.rst
index 5b186c1..30a612d 100644
--- a/Help/prop_tgt/CXX_STANDARD.rst
+++ b/Help/prop_tgt/CXX_STANDARD.rst
@@ -8,7 +8,7 @@ to build this target.  For some compilers, this results in adding a
 flag such as ``-std=gnu++11`` to the compile line.  For compilers that
 have no notion of a standard level, such as MSVC, this has no effect.
 
-Supported values are ``98``, ``11`` and ``14``.
+Supported values are ``98``, ``11``, ``14``, and ``17``.
 
 If the value requested does not result in a compile flag being added for
 the compiler in use, a previous standard flag will be added instead.  This
diff --git a/Help/prop_tgt/FRAMEWORK.rst b/Help/prop_tgt/FRAMEWORK.rst
index 8120c36..495d30e 100644
--- a/Help/prop_tgt/FRAMEWORK.rst
+++ b/Help/prop_tgt/FRAMEWORK.rst
@@ -1,9 +1,9 @@
 FRAMEWORK
 ---------
 
-Build ``SHARED`` library as Framework Bundle on the OS X and iOS.
+Build ``SHARED`` or ``STATIC`` library as Framework Bundle on the OS X and iOS.
 
-If a ``SHARED`` library target has this property set to ``TRUE`` it will be
+If such a library target has this property set to ``TRUE`` it will be
 built as a framework when built on the OS X and iOS.  It will have the
 directory structure required for a framework and will be suitable to
 be used with the ``-framework`` option
diff --git a/Help/prop_tgt/IMPORTED_LIBNAME.rst b/Help/prop_tgt/IMPORTED_LIBNAME.rst
new file mode 100644
index 0000000..1943dba
--- /dev/null
+++ b/Help/prop_tgt/IMPORTED_LIBNAME.rst
@@ -0,0 +1,23 @@
+IMPORTED_LIBNAME
+----------------
+
+Specify the link library name for an :ref:`imported <Imported Targets>`
+:ref:`Interface Library <Interface Libraries>`.
+
+An interface library builds no library file itself but does specify
+usage requirements for its consumers.  The ``IMPORTED_LIBNAME``
+property may be set to specify a single library name to be placed
+on the link line in place of the interface library target name as
+a requirement for using the interface.
+
+This property is intended for use in naming libraries provided by
+a platform SDK for which the full path to a library file may not
+be known.  The value may be a plain library name such as ``foo``
+but may *not* be a path (e.g. ``/usr/lib/libfoo.so``) or a flag
+(e.g. ``-Wl,...``).  The name is never treated as a library target
+name even if it happens to name one.
+
+The ``IMPORTED_LIBNAME`` property is allowed only on
+:ref:`imported <Imported Targets>` :ref:`Interface Libraries`
+and is rejected on targets of other types (for which
+the :prop_tgt:`IMPORTED_LOCATION` target property may be used).
diff --git a/Help/prop_tgt/IMPORTED_LIBNAME_CONFIG.rst b/Help/prop_tgt/IMPORTED_LIBNAME_CONFIG.rst
new file mode 100644
index 0000000..a28b838
--- /dev/null
+++ b/Help/prop_tgt/IMPORTED_LIBNAME_CONFIG.rst
@@ -0,0 +1,7 @@
+IMPORTED_LIBNAME_<CONFIG>
+-------------------------
+
+<CONFIG>-specific version of :prop_tgt:`IMPORTED_LIBNAME` property.
+
+Configuration names correspond to those provided by the project from
+which the target is imported.
diff --git a/Help/prop_tgt/LANG_CPPLINT.rst b/Help/prop_tgt/LANG_CPPLINT.rst
new file mode 100644
index 0000000..14f47d4
--- /dev/null
+++ b/Help/prop_tgt/LANG_CPPLINT.rst
@@ -0,0 +1,13 @@
+<LANG>_CPPLINT
+--------------
+
+This property is supported only when ``<LANG>`` is ``C`` or ``CXX``.
+
+Specify a :ref:`;-list <CMake Language Lists>` containing a command line
+for the ``cpplint`` style checker.  The :ref:`Makefile Generators` and the
+:generator:`Ninja` generator will run ``cpplint`` along with the compiler
+and report any problems.
+
+This property is initialized by the value of the
+:variable:`CMAKE_<LANG>_CPPLINT` variable if it is set when a target is
+created.
diff --git a/Help/prop_tgt/MANUALLY_ADDED_DEPENDENCIES.rst b/Help/prop_tgt/MANUALLY_ADDED_DEPENDENCIES.rst
new file mode 100644
index 0000000..c12ea14
--- /dev/null
+++ b/Help/prop_tgt/MANUALLY_ADDED_DEPENDENCIES.rst
@@ -0,0 +1,8 @@
+MANUALLY_ADDED_DEPENDENCIES
+---------------------------
+
+Get manually added dependencies to other top-level targets.
+
+This read-only property can be used to query all dependencies that
+were added for this target with the :command:`add_dependencies`
+command.
diff --git a/Help/prop_tgt/MAP_IMPORTED_CONFIG_CONFIG.rst b/Help/prop_tgt/MAP_IMPORTED_CONFIG_CONFIG.rst
index 09ff0ce..4da855b 100644
--- a/Help/prop_tgt/MAP_IMPORTED_CONFIG_CONFIG.rst
+++ b/Help/prop_tgt/MAP_IMPORTED_CONFIG_CONFIG.rst
@@ -1,19 +1,25 @@
 MAP_IMPORTED_CONFIG_<CONFIG>
 ----------------------------
 
-Map from project configuration to IMPORTED target's configuration.
+Map from project configuration to
+:ref:`imported target <IMPORTED targets>`'s configuration.
 
 Set this to the list of configurations of an imported target that may
-be used for the current project's <CONFIG> configuration.  Targets
+be used for the current project's ``<CONFIG>`` configuration.  Targets
 imported from another project may not provide the same set of
 configuration names available in the current project.  Setting this
 property tells CMake what imported configurations are suitable for use
-when building the <CONFIG> configuration.  The first configuration in
-the list found to be provided by the imported target is selected.  If
-this property is set and no matching configurations are available,
+when building the ``<CONFIG>`` configuration.  The first configuration in
+the list found to be provided by the imported target (i.e. via
+:prop_tgt:`IMPORTED_LOCATION_<CONFIG>` for the mapped-to ``<CONFIG>``)
+is selected.  As a special case, an empty list element refers to the
+configuration-less imported target location
+(i.e. :prop_tgt:`IMPORTED_LOCATION`).
+
+If this property is set and no matching configurations are available,
 then the imported target is considered to be not found.  This property
 is ignored for non-imported targets.
 
-This property is initialized by the value of the variable
-CMAKE_MAP_IMPORTED_CONFIG_<CONFIG> if it is set when a target is
-created.
+This property is initialized by the value of the
+:variable:`CMAKE_MAP_IMPORTED_CONFIG_<CONFIG>` variable if it is set when a
+target is created.
diff --git a/Help/prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY.rst b/Help/prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY.rst
new file mode 100644
index 0000000..0af85cb
--- /dev/null
+++ b/Help/prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY.rst
@@ -0,0 +1,6 @@
+VS_DEBUGGER_WORKING_DIRECTORY
+-----------------------------
+
+Sets the local debugger working directory for Visual Studio C++ targets.
+This is defined in ``<LocalDebuggerWorkingDirectory>`` in the Visual Studio
+project file.
diff --git a/Help/prop_tgt/VS_DOTNET_REFERENCES_COPY_LOCAL.rst b/Help/prop_tgt/VS_DOTNET_REFERENCES_COPY_LOCAL.rst
new file mode 100644
index 0000000..7641ba5
--- /dev/null
+++ b/Help/prop_tgt/VS_DOTNET_REFERENCES_COPY_LOCAL.rst
@@ -0,0 +1,7 @@
+VS_DOTNET_REFERENCES_COPY_LOCAL
+-------------------------------
+
+Sets the **Copy Local** property for all .NET hint references in the target
+
+Boolean property to enable/disable copying of .NET hint references to
+output directory. The default is ``ON``.
diff --git a/Help/prop_tgt/VS_DOTNET_REFERENCE_refname.rst b/Help/prop_tgt/VS_DOTNET_REFERENCE_refname.rst
new file mode 100644
index 0000000..5814005
--- /dev/null
+++ b/Help/prop_tgt/VS_DOTNET_REFERENCE_refname.rst
@@ -0,0 +1,12 @@
+VS_DOTNET_REFERENCE_<refname>
+-----------------------------
+
+Visual Studio managed project .NET reference with name ``<refname>``
+and hint path.
+
+Adds one .NET reference to generated Visual Studio project. The
+reference will have the name ``<refname>`` and will point to the
+assembly given as value of the property.
+
+See also :prop_tgt:`VS_DOTNET_REFERENCES` and
+:prop_tgt:`VS_DOTNET_REFERENCES_COPY_LOCAL`
diff --git a/Help/prop_tgt/VS_USER_PROPS.rst b/Help/prop_tgt/VS_USER_PROPS.rst
new file mode 100644
index 0000000..1be222b
--- /dev/null
+++ b/Help/prop_tgt/VS_USER_PROPS.rst
@@ -0,0 +1,12 @@
+VS_USER_PROPS
+-------------
+
+Sets the user props file to be included in the visual studio
+C++ project file. The standard path is
+``$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props``, which is
+in most cases the same as
+``%LOCALAPPDATA%\\Microsoft\\MSBuild\\v4.0\\Microsoft.Cpp.Win32.user.props``
+or ``%LOCALAPPDATA%\\Microsoft\\MSBuild\\v4.0\\Microsoft.Cpp.x64.user.props``.
+
+The ``*.user.props`` files can be used for Visual Studio wide
+configuration which is independent from cmake.
diff --git a/Help/prop_tgt/XCODE_EXPLICIT_FILE_TYPE.rst b/Help/prop_tgt/XCODE_EXPLICIT_FILE_TYPE.rst
new file mode 100644
index 0000000..dc92902
--- /dev/null
+++ b/Help/prop_tgt/XCODE_EXPLICIT_FILE_TYPE.rst
@@ -0,0 +1,8 @@
+XCODE_EXPLICIT_FILE_TYPE
+------------------------
+
+Set the Xcode ``explicitFileType`` attribute on its reference to a
+target.  CMake computes a default based on target type but
+can be told explicitly with this property.
+
+See also :prop_tgt:`XCODE_PRODUCT_TYPE`.
diff --git a/Help/prop_tgt/XCODE_PRODUCT_TYPE.rst b/Help/prop_tgt/XCODE_PRODUCT_TYPE.rst
new file mode 100644
index 0000000..f4ef5c0
--- /dev/null
+++ b/Help/prop_tgt/XCODE_PRODUCT_TYPE.rst
@@ -0,0 +1,8 @@
+XCODE_PRODUCT_TYPE
+------------------
+
+Set the Xcode ``productType`` attribute on its reference to a
+target.  CMake computes a default based on target type but
+can be told explicitly with this property.
+
+See also :prop_tgt:`XCODE_EXPLICIT_FILE_TYPE`.
diff --git a/Help/release/3.8.rst b/Help/release/3.8.rst
new file mode 100644
index 0000000..efb2aa5
--- /dev/null
+++ b/Help/release/3.8.rst
@@ -0,0 +1,417 @@
+CMake 3.8 Release Notes
+***********************
+
+.. only:: html
+
+  .. contents::
+
+Changes made since CMake 3.7 include the following.
+
+New Features
+============
+
+Languages
+---------
+
+C#
+^^
+
+* CMake learned to support ``CSharp`` (C#) as a first-class language that
+  can be enabled via the :command:`project` and :command:`enable_language`
+  commands.  It is currently supported by the :ref:`Visual Studio Generators`
+  for VS 2010 and above.
+
+  C# assemblies and programs can be added just like common C++ targets using
+  the :command:`add_library` and :command:`add_executable` commands.
+  References between C# targets in the same source tree may be specified by
+  :command:`target_link_libraries` like for C++.  References to system or
+  3rd-party assemblies may be specified by the target properties
+  :prop_tgt:`VS_DOTNET_REFERENCE_<refname>` and
+  :prop_tgt:`VS_DOTNET_REFERENCES`.
+
+* More fine tuning of C# targets may be done using target and source
+  file properties.  Specifically the target properties related to
+  Visual Studio (``VS_*``) are worth a look (for setting toolset
+  versions, root namespaces, assembly icons, ...).
+
+CUDA
+^^^^
+
+* CMake learned to support ``CUDA`` as a first-class language that can be
+  enabled via the :command:`project` and :command:`enable_language` commands.
+
+* ``CUDA`` is currently supported by the :ref:`Makefile Generators`
+  and the :generator:`Ninja` generator on Linux, macOS, and Windows.
+  Support for the Visual Studio IDE is under development but not
+  included in this release.
+
+* The NVIDIA CUDA Toolkit compiler (``nvcc``) is supported.
+
+C & C++
+^^^^^^^
+
+* The :manual:`Compile Features <cmake-compile-features(7)>` functionality
+  now offers meta-features that request compiler modes for specific language
+  standard levels (e.g. ``cxx_std_11``).  See
+  :prop_gbl:`CMAKE_C_KNOWN_FEATURES` and :prop_gbl:`CMAKE_CXX_KNOWN_FEATURES`.
+
+* The :manual:`Compile Features <cmake-compile-features(7)>` functionality
+  is now aware of C++ 17.  No specific features are yet enumerated besides
+  the ``cxx_std_17`` meta-feature.
+
+* The :manual:`Compile Features <cmake-compile-features(7)>` functionality
+  is now aware of the availability of C99 in gcc since version 3.4.
+
+Platforms
+---------
+
+* A new minimal platform file for ``Fuchsia`` was added.
+
+Generators
+----------
+
+* The :generator:`CodeBlocks` extra generator may now be used to
+  generate with :generator:`NMake Makefiles JOM`.
+
+* The :ref:`Visual Studio Generators` for VS 2013 and above learned to
+  support a ``host=x64`` option in the :variable:`CMAKE_GENERATOR_TOOLSET`
+  value (e.g.  via the :manual:`cmake(1)` ``-T`` option) to request use
+  of a VS 64-bit toolchain on 64-bit hosts.
+
+* The :ref:`Visual Studio Generators` learned to treat files passed to
+  :command:`target_link_libraries` whose names end in ``.targets``
+  as MSBuild "targets" files to be imported into generated project files.
+
+Commands
+--------
+
+* The :command:`add_custom_command` and :command:`add_custom_target` commands
+  learned the option ``COMMAND_EXPAND_LISTS`` which causes lists in the
+  ``COMMAND`` argument to be expanded, including lists created by generator
+  expressions.
+
+* The :command:`execute_process` command gained an ``ENCODING`` option to
+  specify on Windows which encoding is used for output from child process.
+
+* The :command:`math(EXPR)` command gained support for unary
+  ``+`` and ``-`` operators.
+
+* The :command:`source_group` command gained ``TREE`` and ``PREFIX``
+  options to add groups following source tree directory structure.
+
+* The :command:`string(TIMESTAMP)` command learned to treat ``%%``
+  as a way to encode plain ``%``.
+
+* The :command:`string(TIMESTAMP)` command will now honor the
+  ``SOURCE_DATE_EPOCH`` environment variable and use its value
+  instead of the current time.
+
+* The :command:`try_compile` command source file signature gained new options
+  to specify the language standard to use in the generated test project.
+
+* The :command:`try_compile` command source file signature now honors
+  language standard variables like :variable:`CMAKE_CXX_STANDARD`.
+  See policy :policy:`CMP0067`.
+
+Variables
+---------
+
+* A :variable:`CMAKE_CODELITE_USE_TARGETS` variable was added to tell the
+  :generator:`CodeLite` extra generator to change the generated project
+  to have target-centric organization.
+  The ``build``, ``rebuild``, and ``clean`` operations within ``CodeLite``
+  then work on a selected target rather than the whole workspace.
+  (Note that the :generator:`Ninja` clean operation on a target
+  includes its dependencies, though.)
+
+* The :variable:`CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS` variable was added to
+  tell the :generator:`Sublime Text 2` extra generator to place specified
+  environment variables in the generated ``.sublime-project``.
+
+* The :variable:`CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE` variable was added
+  to tell the :generator:`Sublime Text 2` extra generator whether to exclude
+  the build tree from the ``.sublime-project`` when it is inside the source
+  tree.
+
+* A :variable:`CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD` variable was
+  added to tell :ref:`Visual Studio Generators` for VS 2010 and above
+  to include the ``PACKAGE`` target in the default build, similar to
+  the existing :variable:`CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD`
+  variable for the ``INSTALL`` target.
+
+Properties
+----------
+
+* A :prop_tgt:`BUILD_RPATH` target property and corresponding
+  :variable:`CMAKE_BUILD_RPATH` variable were added to support custom
+  ``RPATH`` locations to be added to binaries in the build tree.
+
+* The :prop_sf:`COMPILE_FLAGS` source file property learned to support
+  :manual:`generator expressions <cmake-generator-expressions(7)>`.
+
+* The :prop_tgt:`FRAMEWORK` target property may now also be applied to
+  static libraries on Apple targets.  It will result in a proper
+  Framework but with a static library inside.
+
+* :ref:`Imported <Imported Targets>` :ref:`Interface Libraries` learned new
+  :prop_tgt:`IMPORTED_LIBNAME` and :prop_tgt:`IMPORTED_LIBNAME_<CONFIG>`
+  target properties to specify a link library name since interface libraries
+  do not build their own library files.
+
+* A :prop_tgt:`<LANG>_CPPLINT` target property and supporting
+  :variable:`CMAKE_<LANG>_CPPLINT` variable were introduced to tell
+  the :ref:`Makefile Generators` and the :generator:`Ninja` generator to
+  run the ``cpplint`` style checker along with the compiler for ``C`` and
+  ``CXX`` languages.
+
+* A :prop_tgt:`MANUALLY_ADDED_DEPENDENCIES` target property has been added.
+  It provides a read-only list of dependencies that have been added with
+  the :command:`add_dependencies` command.
+
+* The :prop_tgt:`MAP_IMPORTED_CONFIG_<CONFIG>` target property learned
+  to interpret empty list elements as referring to the configuration-less
+  imported location specified by :prop_tgt:`IMPORTED_LOCATION`.
+
+* The :prop_tgt:`NO_SYSTEM_FROM_IMPORTED` target property is now supported
+  on :ref:`Imported <Imported Targets>` :ref:`Interface Libraries`.
+
+* New source file properties :prop_sf:`SKIP_AUTOMOC`, :prop_sf:`SKIP_AUTOUIC`,
+  :prop_sf:`SKIP_AUTORCC`, and :prop_sf:`SKIP_AUTOGEN` were added to allow
+  source files to be excluded from processing by :prop_tgt:`AUTOMOC`,
+  :prop_tgt:`AUTOUIC`, and :prop_tgt:`AUTORCC` target properties.
+
+* A :prop_sf:`VS_COPY_TO_OUT_DIR` source file property was added to
+  tell :ref:`Visual Studio Generators` for VS 2010 and above whether
+  or not a file should e copied to the output directory.
+
+* A :prop_tgt:`VS_DEBUGGER_WORKING_DIRECTORY` target property was added
+  to tell :ref:`Visual Studio Generators` for VS 2010 and above what
+  debugger working directory should be set for the target.
+
+* A :prop_tgt:`VS_DOTNET_REFERENCES_COPY_LOCAL` target property was added
+  to specify whether to copy referenced assemblies to the output directory.
+
+* A :prop_tgt:`VS_DOTNET_REFERENCE_<refname>` target property was added
+  to tell :ref:`Visual Studio Generators` for VS 2010 and above to add
+  a .NET reference with a given hint path.
+
+* A :prop_sf:`VS_INCLUDE_IN_VSIX` source file property was added to
+  tell :ref:`Visual Studio Generators` for VS 2010 and above whether
+  to include the file in a Visual Studio extension package.
+
+* A :prop_sf:`VS_RESOURCE_GENERATOR` source file property was added to
+  give :ref:`Visual Studio Generators` for VS 2010 and above a setting
+  for the resource generator (``C#`` only).
+
+* A :prop_tgt:`VS_USER_PROPS` target property was added to tell
+  :ref:`Visual Studio Generators` for VS 2010 and above to use a
+  custom MSBuild user ``.props`` file.
+
+* A :prop_gbl:`XCODE_EMIT_EFFECTIVE_PLATFORM_NAME` global property was
+  added to tell the :generator:`Xcode` generator whether to emit the
+  ``EFFECTIVE_PLATFORM_NAME`` variable.  This is useful when building
+  with multiple SDKs like ``macosx`` and ``iphoneos`` in parallel.
+
+* New :prop_tgt:`XCODE_PRODUCT_TYPE` and :prop_tgt:`XCODE_EXPLICIT_FILE_TYPE`
+  target properties were created to tell the :generator:`Xcode` generator
+  to use custom values of the corresponding attributes for a target in the
+  generated Xcode project.
+
+Modules
+-------
+
+* A :module:`CSharpUtilities` module was added to aid parameterization of
+  Visual Studio C# targets.  It provides functions to allow automated
+  setting of source file properties to support Windows Forms, WPF/XAML or
+  other technologies as needed.
+
+* The :module:`ExternalData` module learned to support multiple
+  content links for one data file using different hashes, e.g.
+  ``img.png.sha256`` and ``img.png.sha1``.  This allows objects
+  to be fetched from sources indexed by different hash algorithms.
+
+* The :module:`ExternalProject` module gained the ``GIT_PROGRESS`` option to
+  force Git to show progress when cloning repositories.
+
+* The :module:`ExternalProject` module gained a ``GIT_CONFIG`` option
+  to pass ``--config`` options to Git when cloning repositories.
+
+* The :module:`FeatureSummary` module :command:`feature_summary` command now
+  accepts a new ``QUIET_ON_EMPTY`` option that suppresses the output when
+  the list of packages that belong to the selected category is empty.
+
+* The :module:`FeatureSummary` module :command:`add_feature_info` command
+  now accepts lists of dependencies for deciding whether a feature is enabled
+  or not.
+
+* The package types accepted by the :module:`FeatureSummary` module can now
+  be tweaked by changing the :variable:`FeatureSummary_PKG_TYPES`,
+  :variable:`FeatureSummary_REQUIRED_PKG_TYPES` and
+  :variable:`FeatureSummary_DEFAULT_PKG_TYPE` global properties.
+
+* The :module:`FindOpenGL` module now provides imported targets
+  ``OpenGL::GL`` and ``OpenGL::GLU`` when the libraries are found.
+
+* The :module:`UseSWIG` module gained a ``swig_add_library`` command
+  to give more flexibility over the old ``swig_add_module`` command.
+
+* The :module:`UseSWIG` module ``swig_add_source_to_module`` command
+  learned a new ``SWIG_OUTFILE_DIR`` option to control the output
+  file location (``swig -o``).
+
+* The :module:`WriteCompilerDetectionHeader` module gained the
+  ``ALLOW_UNKNOWN_COMPILERS`` and ``ALLOW_UNKNOWN_COMPILER_VERSIONS`` options
+  that allow creation of headers that will work also with unknown or old
+  compilers by simply assuming they do not support any of the requested
+  features.
+
+CTest
+-----
+
+* The :command:`ctest_memcheck` command gained a ``DEFECT_COUNT <var>``
+  option to capture the number of memory defects detected.
+
+* The :command:`ctest_memcheck` command learned to read the location of
+  suppressions files for sanitizers from the
+  :variable:`CTEST_MEMORYCHECK_SUPPRESSIONS_FILE` variable.
+
+* The :command:`ctest_memcheck` command learned to support ``LeakSanitizer``
+  independently from ``AddressSanitizer``.
+
+* The :command:`ctest_update` command ``CDASH_UPLOAD`` signature was taught
+  to honor the ``RETRY_COUNT``, ``RETRY_DELAY``, and ``QUIET`` options.
+
+CPack
+-----
+
+* The :module:`CPackIFWConfigureFile` module was added to define a new
+  :command:`cpack_ifw_configure_file` command to configure file templates
+  prepared in QtIFW/SDK/Creator style.
+
+* The :module:`CPackIFW` module :command:`cpack_ifw_configure_component` and
+  :command:`cpack_ifw_configure_component_group` commands gained a new
+  ``DEFAULT``, ``VIRTUAL``, ``FORCED_INSTALLATION``, ``REQUIRES_ADMIN_RIGHTS``,
+  ``DISPLAY_NAME``, ``UPDATE_TEXT``, ``DESCRIPTION``, ``RELEASE_DATE``,
+  ``AUTO_DEPEND_ON`` and ``TRANSLATIONS`` options to more specific
+  configuration.
+
+* The :module:`CPackIFW` module :command:`cpack_ifw_configure_component`
+  command gained a new ``DEPENDENCIES`` alias for ``DEPENDS`` option.
+
+* The :module:`CPackIFW` module :command:`cpack_ifw_configure_component_group`
+  command gained a new ``DEPENDS`` option. The ``DEPENDENCIES`` alias also
+  added.
+
+* The :module:`CPackIFW` module :command:`cpack_ifw_configure_component` and
+  :command:`cpack_ifw_configure_component_group` commands ``PRIORITY``
+  option now is deprecated and will be removed in a future version of CMake.
+  Please use new ``SORTING_PRIORITY`` option instead.
+
+* The :module:`CPackIFW` module gained new
+  :variable:`CPACK_IFW_PACKAGE_WATERMARK`,
+  :variable:`CPACK_IFW_PACKAGE_BANNER`,
+  :variable:`CPACK_IFW_PACKAGE_BACKGROUND`,
+  :variable:`CPACK_IFW_PACKAGE_WIZARD_STYLE`,
+  :variable:`CPACK_IFW_PACKAGE_WIZARD_DEFAULT_WIDTH`,
+  :variable:`CPACK_IFW_PACKAGE_WIZARD_DEFAULT_HEIGHT`, and
+  :variable:`CPACK_IFW_PACKAGE_TITLE_COLOR`
+  variables to customize a QtIFW installer look.
+
+* The :module:`CPackProductBuild` module gained options to sign packages.
+  See the variables :variable:`CPACK_PRODUCTBUILD_IDENTITY_NAME`,
+  :variable:`CPACK_PRODUCTBUILD_KEYCHAIN_PATH`,
+  :variable:`CPACK_PKGBUILD_IDENTITY_NAME`, and
+  :variable:`CPACK_PKGBUILD_KEYCHAIN_PATH`.
+
+* The :module:`CPackRPM` module learned to omit tags that are not supported by
+  provided ``rpmbuild`` tool. If unsupported tags are set they are ignored
+  and a developer warning is printed out.
+
+* The :module:`CPackRPM` module learned to generate main component package
+  which forces generation of a rpm for defined component without component
+  suffix in filename and package name.
+  See :variable:`CPACK_RPM_MAIN_COMPONENT` variable.
+
+* The :module:`CPackRPM` module learned to generate a single ``debuginfo``
+  package on demand even if components packaging is used.
+  See :variable:`CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE` variable.
+
+* The :module:`CPackRPM` module learned to support
+  multiple directives per file when using
+  :variable:`CPACK_RPM_USER_FILELIST` variable.
+
+Other
+-----
+
+* CMake functionality using cryptographic hashes now supports SHA-3 algorithms.
+
+* A new generator expression ``$<IF:cond,true-value,false-value>`` was added.
+  It resolves to the true-value if the condition is ``1`` and resolves to
+  the false-value if the condition is ``0``.
+
+Deprecated and Removed Features
+===============================
+
+* The :module:`FeatureSummary` module commands :command:`set_package_info`,
+  :command:`set_feature_info`, :command:`print_enabled_features`, and
+  :command:`print_disabled_features` are now deprecated.
+
+* The :module:`UseSWIG` module ``swig_add_module`` command is now
+  deprecated in favor of ``swig_add_library``.
+
+Other Changes
+=============
+
+* If a command specified by the :prop_tgt:`<LANG>_CLANG_TIDY` target property
+  returns non-zero at build time this is now treated as an error instead of
+  silently ignored.
+
+* The :command:`ctest_memcheck` command no longer automatically adds
+  ``leak_check=1`` to the options used by ``AddressSanitizer``. The default
+  behavior of ``AddressSanitizer`` is to run `LeakSanitizer` to check leaks
+  unless ``leak_check=0``.
+
+* The :command:`ctest_memcheck` command was fixed to correctly append extra
+  sanitizer options read from the
+  :variable:`CTEST_MEMORYCHECK_SANITIZER_OPTIONS` variable to the environment
+  variables used internally by the sanitizers.
+
+* The :module:`FeatureSummary` module :command:`set_package_properties`
+  command no longer forces the package type to ``OPTIONAL`` when the type
+  is not explicitly set.
+
+* The :manual:`Compile Features <cmake-compile-features(7)>` functionality
+  is now aware of features supported by Intel C++ compilers versions 12.1
+  through 17.0 on UNIX and Windows platforms.
+
+* Calls to the :module:`FindPkgConfig` module :command:`pkg_check_modules`
+  command following a successful call learned to re-evaluate the cached values
+  for a given prefix after changes to the parameters to the command for that
+  prefix.
+
+* When using :prop_tgt:`AUTOMOC` or :prop_tgt:`AUTOUIC`, generated
+  ``moc_*``, ``*.moc`` and ``ui_*`` are placed in the
+  ``<CMAKE_CURRENT_BINARY_DIR>/<TARGETNAME>_autogen/include`` directory which
+  is automatically added to the target's :prop_tgt:`INCLUDE_DIRECTORIES`.
+  It is therefore not necessary anymore to have
+  :variable:`CMAKE_CURRENT_BINARY_DIR` in the target's
+  :prop_tgt:`INCLUDE_DIRECTORIES`.
+
+* The :generator:`Sublime Text 2` generator no longer runs the native
+  build command (e.g. ``ninja`` or ``make``) with verbose build output
+  enabled.
+
+* The :command:`try_compile` command source file signature now
+  honors the :variable:`CMAKE_WARN_DEPRECATED` variable value
+  in the generated test project.
+
+* The :ref:`Visual Studio Generators` for VS 2010 and above now place
+  per-source file flags after target-wide flags when they are classified
+  as raw flags with no project file setting (``AdditionalOptions``).
+  This behavior is more consistent with the ordering of flags produced
+  by other generators, and allows flags on more-specific properties
+  (per-source) to override those on more general ones (per-target).
+
+* The precompiled Windows binary MSI package provided on ``cmake.org`` now
+  records the installation directory in the Windows Registry under the key
+  ``HKLM\Software\Kitware\CMake`` with a value named ``InstallDir``.
diff --git a/Help/release/index.rst b/Help/release/index.rst
index 25c6c3e..8f0f252 100644
--- a/Help/release/index.rst
+++ b/Help/release/index.rst
@@ -11,6 +11,7 @@ Releases
 .. toctree::
    :maxdepth: 1
 
+   3.8 <3.8>
    3.7 <3.7>
    3.6 <3.6>
    3.5 <3.5>
diff --git a/Help/variable/CMAKE_BUILD_RPATH.rst b/Help/variable/CMAKE_BUILD_RPATH.rst
new file mode 100644
index 0000000..f20eb41
--- /dev/null
+++ b/Help/variable/CMAKE_BUILD_RPATH.rst
@@ -0,0 +1,10 @@
+CMAKE_BUILD_RPATH
+-----------------
+
+A :ref:`;-list <CMake Language Lists>` specifying runtime path (``RPATH``)
+entries to add to binaries linked in the build tree (for platforms that
+support it).  The entries will *not* be used for binaries in the install
+tree.  See also the :variable:`CMAKE_INSTALL_RPATH` variable.
+
+This is used to initialize the :prop_tgt:`BUILD_RPATH` target property
+for all targets.
diff --git a/Help/variable/CMAKE_CL_64.rst b/Help/variable/CMAKE_CL_64.rst
index a1e86a5..4e80d1f 100644
--- a/Help/variable/CMAKE_CL_64.rst
+++ b/Help/variable/CMAKE_CL_64.rst
@@ -1,6 +1,7 @@
 CMAKE_CL_64
 -----------
 
-Using the 64-bit compiler from Microsoft
+Discouraged.  Use :variable:`CMAKE_SIZEOF_VOID_P` instead.
 
-Set to ``true`` when using the 64-bit ``cl`` compiler from Microsoft.
+Set to a true value when using a Microsoft Visual Studio ``cl`` compiler that
+*targets* a 64-bit architecture.
diff --git a/Help/variable/CMAKE_CUDA_EXTENSIONS.rst b/Help/variable/CMAKE_CUDA_EXTENSIONS.rst
new file mode 100644
index 0000000..4fe758e
--- /dev/null
+++ b/Help/variable/CMAKE_CUDA_EXTENSIONS.rst
@@ -0,0 +1,11 @@
+CMAKE_CUDA_EXTENSIONS
+---------------------
+
+Default value for :prop_tgt:`CUDA_EXTENSIONS` property of targets.
+
+This variable is used to initialize the :prop_tgt:`CUDA_EXTENSIONS`
+property on all targets.  See that target property for additional
+information.
+
+See the :manual:`cmake-compile-features(7)` manual for information on
+compile features and a list of supported compilers.
diff --git a/Help/variable/CMAKE_CUDA_STANDARD.rst b/Help/variable/CMAKE_CUDA_STANDARD.rst
new file mode 100644
index 0000000..6c23031
--- /dev/null
+++ b/Help/variable/CMAKE_CUDA_STANDARD.rst
@@ -0,0 +1,11 @@
+CMAKE_CUDA_STANDARD
+-------------------
+
+Default value for :prop_tgt:`CUDA_STANDARD` property of targets.
+
+This variable is used to initialize the :prop_tgt:`CUDA_STANDARD`
+property on all targets.  See that target property for additional
+information.
+
+See the :manual:`cmake-compile-features(7)` manual for information on
+compile features and a list of supported compilers.
diff --git a/Help/variable/CMAKE_CUDA_STANDARD_REQUIRED.rst b/Help/variable/CMAKE_CUDA_STANDARD_REQUIRED.rst
new file mode 100644
index 0000000..935d605
--- /dev/null
+++ b/Help/variable/CMAKE_CUDA_STANDARD_REQUIRED.rst
@@ -0,0 +1,11 @@
+CMAKE_CUDA_STANDARD_REQUIRED
+----------------------------
+
+Default value for :prop_tgt:`CUDA_STANDARD_REQUIRED` property of targets.
+
+This variable is used to initialize the :prop_tgt:`CUDA_STANDARD_REQUIRED`
+property on all targets.  See that target property for additional
+information.
+
+See the :manual:`cmake-compile-features(7)` manual for information on
+compile features and a list of supported compilers.
diff --git a/Help/variable/CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES.rst b/Help/variable/CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES.rst
new file mode 100644
index 0000000..768f571
--- /dev/null
+++ b/Help/variable/CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES.rst
@@ -0,0 +1,7 @@
+CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES
+--------------------------------------
+
+When the ``CUDA`` language has been enabled, this provides a
+:ref:`;-list <CMake Language Lists>` of include directories provided
+by the CUDA Toolkit.  The value may be useful for C++ source files
+to include CUDA headers.
diff --git a/Help/variable/CMAKE_DL_LIBS.rst b/Help/variable/CMAKE_DL_LIBS.rst
index 1fe7641..50d313d 100644
--- a/Help/variable/CMAKE_DL_LIBS.rst
+++ b/Help/variable/CMAKE_DL_LIBS.rst
@@ -1,7 +1,7 @@
 CMAKE_DL_LIBS
 -------------
 
-Name of library containing ``dlopen`` and ``dlcose``.
+Name of library containing ``dlopen`` and ``dlclose``.
 
 The name of the library that has ``dlopen`` and ``dlclose`` in it, usually
 ``-ldl`` on most UNIX machines.
diff --git a/Help/variable/CMAKE_LANG_COMPILER_ID.rst b/Help/variable/CMAKE_LANG_COMPILER_ID.rst
index ebd616e..0fab10c 100644
--- a/Help/variable/CMAKE_LANG_COMPILER_ID.rst
+++ b/Help/variable/CMAKE_LANG_COMPILER_ID.rst
@@ -23,6 +23,7 @@ include:
   Intel = Intel Compiler (intel.com)
   MIPSpro = SGI MIPSpro (sgi.com)
   MSVC = Microsoft Visual Studio (microsoft.com)
+  NVIDIA = NVIDIA CUDA Compiler (nvidia.com)
   OpenWatcom = Open Watcom (openwatcom.org)
   PGI = The Portland Group (pgroup.com)
   PathScale = PathScale (pathscale.com)
diff --git a/Help/variable/CMAKE_LANG_CPPLINT.rst b/Help/variable/CMAKE_LANG_CPPLINT.rst
new file mode 100644
index 0000000..3b6f452
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_CPPLINT.rst
@@ -0,0 +1,6 @@
+CMAKE_<LANG>_CPPLINT
+--------------------
+
+Default value for :prop_tgt:`<LANG>_CPPLINT` target property. This variable
+is used to initialize the property on each target as it is created.  This
+is done only when ``<LANG>`` is ``C`` or ``CXX``.
diff --git a/Help/variable/CMAKE_POLICY_WARNING_CMPNNNN.rst b/Help/variable/CMAKE_POLICY_WARNING_CMPNNNN.rst
index 36cf75f..aa23b65 100644
--- a/Help/variable/CMAKE_POLICY_WARNING_CMPNNNN.rst
+++ b/Help/variable/CMAKE_POLICY_WARNING_CMPNNNN.rst
@@ -17,6 +17,8 @@ warn by default:
   policy :policy:`CMP0065`.
 * ``CMAKE_POLICY_WARNING_CMP0066`` controls the warning for
   policy :policy:`CMP0066`.
+* ``CMAKE_POLICY_WARNING_CMP0067`` controls the warning for
+  policy :policy:`CMP0067`.
 
 This variable should not be set by a project in CMake code.  Project
 developers running CMake may set this variable in their cache to
diff --git a/Help/variable/CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS.rst b/Help/variable/CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS.rst
new file mode 100644
index 0000000..02c8663
--- /dev/null
+++ b/Help/variable/CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS.rst
@@ -0,0 +1,25 @@
+CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS
+---------------------------------
+
+This variable contains a list of env vars as a list of tokens with the
+syntax ``var=value``.
+
+Example:
+
+.. code-block:: cmake
+
+  set(CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS
+     "FOO=FOO1\;FOO2\;FOON"
+     "BAR=BAR1\;BAR2\;BARN"
+     "BAZ=BAZ1\;BAZ2\;BAZN"
+     "FOOBAR=FOOBAR1\;FOOBAR2\;FOOBARN"
+     "VALID="
+     )
+
+In case of malformed variables CMake will fail:
+
+.. code-block:: cmake
+
+  set(CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS
+      "THIS_IS_NOT_VALID"
+      )
diff --git a/Help/variable/CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE.rst b/Help/variable/CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE.rst
new file mode 100644
index 0000000..d654425
--- /dev/null
+++ b/Help/variable/CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE.rst
@@ -0,0 +1,7 @@
+CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE
+---------------------------------------
+
+If this variable evaluates to ``ON`` at the end of the top-level
+``CMakeLists.txt`` file, the :generator:`Sublime Text 2` extra generator
+excludes the build tree from the ``.sublime-project`` if it is inside the
+source tree.
diff --git a/Help/variable/CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD.rst b/Help/variable/CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD.rst
new file mode 100644
index 0000000..693ba45
--- /dev/null
+++ b/Help/variable/CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD.rst
@@ -0,0 +1,8 @@
+CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD
+-----------------------------------------
+
+Include ``PACKAGE`` target to default build.
+
+In Visual Studio solution, by default the ``PACKAGE`` target will not be part
+of the default build. Setting this variable will enable the ``PACKAGE`` target
+to be part of the default build.
diff --git a/Help/variable/CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE.rst b/Help/variable/CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE.rst
new file mode 100644
index 0000000..9b59c52
--- /dev/null
+++ b/Help/variable/CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE.rst
@@ -0,0 +1,10 @@
+CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE
+-------------------------------------------
+
+Visual Studio preferred tool architecture.
+
+The :ref:`Visual Studio Generators` for VS 2013 and above support optional
+selection of a 64-bit toolchain on 64-bit hosts by specifying a ``host=x64``
+value in the :variable:`CMAKE_GENERATOR_TOOLSET` option.  CMake provides
+the selected toolchain architecture preference in this variable (either
+``x64`` or empty).
diff --git a/Help/variable/CTEST_MEMORYCHECK_TYPE.rst b/Help/variable/CTEST_MEMORYCHECK_TYPE.rst
index b963293..b8b4c30 100644
--- a/Help/variable/CTEST_MEMORYCHECK_TYPE.rst
+++ b/Help/variable/CTEST_MEMORYCHECK_TYPE.rst
@@ -4,5 +4,5 @@ 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
+``ThreadSanitizer``, ``AddressSanitizer``, ``LeakSanitizer``, ``MemorySanitizer``, and
 ``UndefinedBehaviorSanitizer``.
diff --git a/Help/variable/MSVC.rst b/Help/variable/MSVC.rst
index 913ed08..22a087a 100644
--- a/Help/variable/MSVC.rst
+++ b/Help/variable/MSVC.rst
@@ -4,3 +4,5 @@ MSVC
 ``True`` when using Microsoft Visual C++.
 
 Set to ``true`` when the compiler is some version of Microsoft Visual C++.
+
+See also the :variable:`MSVC_VERSION` variable.
diff --git a/Help/variable/MSVC10.rst b/Help/variable/MSVC10.rst
index 98e0493..55c6337 100644
--- a/Help/variable/MSVC10.rst
+++ b/Help/variable/MSVC10.rst
@@ -1,5 +1,7 @@
 MSVC10
 ------
 
+Discouraged.  Use the :variable:`MSVC_VERSION` variable instead.
+
 ``True`` when using the Microsoft Visual Studio ``v100`` toolset
 (``cl`` version 16) or another compiler that simulates it.
diff --git a/Help/variable/MSVC11.rst b/Help/variable/MSVC11.rst
index 42b7b86..17943dc 100644
--- a/Help/variable/MSVC11.rst
+++ b/Help/variable/MSVC11.rst
@@ -1,5 +1,7 @@
 MSVC11
 ------
 
+Discouraged.  Use the :variable:`MSVC_VERSION` variable instead.
+
 ``True`` when using the Microsoft Visual Studio ``v110`` toolset
 (``cl`` version 17) or another compiler that simulates it.
diff --git a/Help/variable/MSVC12.rst b/Help/variable/MSVC12.rst
index 0648f35..a524fab 100644
--- a/Help/variable/MSVC12.rst
+++ b/Help/variable/MSVC12.rst
@@ -1,5 +1,7 @@
 MSVC12
 ------
 
+Discouraged.  Use the :variable:`MSVC_VERSION` variable instead.
+
 ``True`` when using the Microsoft Visual Studio ``v120`` toolset
 (``cl`` version 18) or another compiler that simulates it.
diff --git a/Help/variable/MSVC14.rst b/Help/variable/MSVC14.rst
index f67ebc7..79e0c10 100644
--- a/Help/variable/MSVC14.rst
+++ b/Help/variable/MSVC14.rst
@@ -1,5 +1,7 @@
 MSVC14
 ------
 
-``True`` when using the Microsoft Visual Studio ``v140`` toolset
-(``cl`` version 19) or another compiler that simulates it.
+Discouraged.  Use the :variable:`MSVC_VERSION` variable instead.
+
+``True`` when using the Microsoft Visual Studio ``v140`` or ``v141``
+toolset (``cl`` version 19) or another compiler that simulates it.
diff --git a/Help/variable/MSVC60.rst b/Help/variable/MSVC60.rst
index 14f09cf..14164bf 100644
--- a/Help/variable/MSVC60.rst
+++ b/Help/variable/MSVC60.rst
@@ -1,6 +1,8 @@
 MSVC60
 ------
 
+Discouraged.  Use the :variable:`MSVC_VERSION` variable instead.
+
 ``True`` when using Microsoft Visual C++ 6.0.
 
 Set to ``true`` when the compiler is version 6.0 of Microsoft Visual C++.
diff --git a/Help/variable/MSVC70.rst b/Help/variable/MSVC70.rst
index 76fa96f..ed3b0bb 100644
--- a/Help/variable/MSVC70.rst
+++ b/Help/variable/MSVC70.rst
@@ -1,6 +1,8 @@
 MSVC70
 ------
 
+Discouraged.  Use the :variable:`MSVC_VERSION` variable instead.
+
 ``True`` when using Microsoft Visual C++ 7.0.
 
 Set to ``true`` when the compiler is version 7.0 of Microsoft Visual C++.
diff --git a/Help/variable/MSVC71.rst b/Help/variable/MSVC71.rst
index d69d4fc..0237592 100644
--- a/Help/variable/MSVC71.rst
+++ b/Help/variable/MSVC71.rst
@@ -1,6 +1,8 @@
 MSVC71
 ------
 
+Discouraged.  Use the :variable:`MSVC_VERSION` variable instead.
+
 ``True`` when using Microsoft Visual C++ 7.1.
 
 Set to ``true`` when the compiler is version 7.1 of Microsoft Visual C++.
diff --git a/Help/variable/MSVC80.rst b/Help/variable/MSVC80.rst
index 0d33e82..1533218 100644
--- a/Help/variable/MSVC80.rst
+++ b/Help/variable/MSVC80.rst
@@ -1,5 +1,7 @@
 MSVC80
 ------
 
+Discouraged.  Use the :variable:`MSVC_VERSION` variable instead.
+
 ``True`` when using the Microsoft Visual Studio ``v80`` toolset
 (``cl`` version 14) or another compiler that simulates it.
diff --git a/Help/variable/MSVC90.rst b/Help/variable/MSVC90.rst
index 1716e6f..4981ecf 100644
--- a/Help/variable/MSVC90.rst
+++ b/Help/variable/MSVC90.rst
@@ -1,5 +1,7 @@
 MSVC90
 ------
 
+Discouraged.  Use the :variable:`MSVC_VERSION` variable instead.
+
 ``True`` when using the Microsoft Visual Studio ``v90`` toolset
 (``cl`` version 15) or another compiler that simulates it.
diff --git a/Help/variable/MSVC_VERSION.rst b/Help/variable/MSVC_VERSION.rst
index e2aff3c..8932147 100644
--- a/Help/variable/MSVC_VERSION.rst
+++ b/Help/variable/MSVC_VERSION.rst
@@ -13,4 +13,5 @@ Known version numbers are::
   1600 = VS 10.0
   1700 = VS 11.0
   1800 = VS 12.0
-  1900 = VS 14.0, 15.0
+  1900 = VS 14.0
+  1910 = VS 15.0
diff --git a/Modules/AndroidTestUtilities.cmake b/Modules/AndroidTestUtilities.cmake
index a0a74fa..62d04f3 100644
--- a/Modules/AndroidTestUtilities.cmake
+++ b/Modules/AndroidTestUtilities.cmake
@@ -110,11 +110,18 @@ function(android_add_test_data test_name)
   endforeach()
 
   set(DATA_TARGET_NAME "${test_name}")
-  ExternalData_Expand_Arguments(
-    ${DATA_TARGET_NAME}
-    extern_data_output
-    ${AST_FILES})
-  ExternalData_Add_Target(${DATA_TARGET_NAME})
+  string(FIND "${AST_FILES}" "DATA{" data_files_found)
+  if(${data_files_found} GREATER "-1")
+    # Use ExternalData if any DATA{} files were found.
+    ExternalData_Expand_Arguments(
+      ${DATA_TARGET_NAME}
+      extern_data_output
+      ${AST_FILES})
+    ExternalData_Add_Target(${DATA_TARGET_NAME})
+  else()
+    add_custom_target(${DATA_TARGET_NAME} ALL)
+    set(extern_data_output ${AST_FILES})
+  endif()
 
   # For regular files on Linux, just copy them directly.
   foreach(path ${AST_FILES})
diff --git a/Modules/AndroidTestUtilities/PushToAndroidDevice.cmake b/Modules/AndroidTestUtilities/PushToAndroidDevice.cmake
index f5f2564..04529b1 100644
--- a/Modules/AndroidTestUtilities/PushToAndroidDevice.cmake
+++ b/Modules/AndroidTestUtilities/PushToAndroidDevice.cmake
@@ -39,7 +39,9 @@ function(android_push_test_files_to_device)
   # if(file_exists) will return true.
   macro(check_device_file_exists device_file file_exists)
     set(${file_exists} "")
-    execute_adb_command(shell ls ${device_file})
+    execute_process(
+      COMMAND ${adb_executable} shell ls ${device_file}
+      OUTPUT_VARIABLE out_var ERROR_VARIABLE out_var)
     if(NOT out_var) # when a directory exists but is empty the output is empty
       set(${file_exists} "YES")
     else()
@@ -117,7 +119,7 @@ function(android_push_test_files_to_device)
   check_device_file_exists(${_ptd_DEV_TEST_DIR} test_dir_exists)
   if(test_dir_exists)
     # This is protected in the SetupProjectTests module.
-    execute_adb_command(shell echo rm -r ${_ptd_DEV_TEST_DIR} | su)
+    execute_adb_command(shell rm -r ${_ptd_DEV_TEST_DIR})
   endif()
   execute_adb_command(shell mkdir -p ${_ptd_DEV_TEST_DIR})
 
diff --git a/Modules/AutogenInfo.cmake.in b/Modules/AutogenInfo.cmake.in
index 7d89420..3fafaff 100644
--- a/Modules/AutogenInfo.cmake.in
+++ b/Modules/AutogenInfo.cmake.in
@@ -1,12 +1,11 @@
-set(AM_SOURCES @_cpp_files@ )
-set(AM_RCC_SOURCES @_rcc_files@ )
-set(AM_RCC_INPUTS @_qt_rcc_inputs@)
-set(AM_SKIP_MOC @_skip_moc@ )
-set(AM_SKIP_UIC @_skip_uic@ )
-set(AM_HEADERS @_moc_headers@ )
+set(AM_SOURCES @_moc_uic_sources@)
+set(AM_HEADERS @_moc_uic_headers@)
+set(AM_SKIP_MOC @_skip_moc@)
+set(AM_SKIP_UIC @_skip_uic@)
 set(AM_MOC_COMPILE_DEFINITIONS @_moc_compile_defs@)
 set(AM_MOC_INCLUDES @_moc_incs@)
 set(AM_MOC_OPTIONS @_moc_options@)
+set(AM_MOC_RELAXED_MODE "@_moc_relaxed_mode@")
 set(AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE "@CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE@")
 set(AM_CMAKE_BINARY_DIR "@CMAKE_BINARY_DIR@/")
 set(AM_CMAKE_SOURCE_DIR "@CMAKE_SOURCE_DIR@/")
@@ -18,9 +17,10 @@ set(AM_CMAKE_CURRENT_BINARY_DIR "@CMAKE_CURRENT_BINARY_DIR@/")
 set(AM_QT_VERSION_MAJOR "@_target_qt_version@")
 set(AM_TARGET_NAME @_moc_target_name@)
 set(AM_ORIGIN_TARGET_NAME @_origin_target_name@)
-set(AM_RELAXED_MODE "@_moc_relaxed_mode@")
 set(AM_UIC_TARGET_OPTIONS @_uic_target_options@)
 set(AM_UIC_OPTIONS_FILES @_qt_uic_options_files@)
 set(AM_UIC_OPTIONS_OPTIONS @_qt_uic_options_options@)
-set(AM_RCC_OPTIONS_FILES @_qt_rcc_options_files@)
-set(AM_RCC_OPTIONS_OPTIONS @_qt_rcc_options_options@)
+set(AM_RCC_SOURCES @_rcc_files@ )
+set(AM_RCC_INPUTS @_rcc_inputs@)
+set(AM_RCC_OPTIONS_FILES @_rcc_options_files@)
+set(AM_RCC_OPTIONS_OPTIONS @_rcc_options_options@)
diff --git a/Modules/BundleUtilities.cmake b/Modules/BundleUtilities.cmake
index b1610e2..5d6f402 100644
--- a/Modules/BundleUtilities.cmake
+++ b/Modules/BundleUtilities.cmake
@@ -624,6 +624,33 @@ function(get_bundle_keys app libs dirs keys_var)
       endif()
     endforeach()
 
+    # preserve library symlink structure
+    foreach(key ${${keys_var}})
+      if("${${key}_COPYFLAG}" STREQUAL 1)
+        if(IS_SYMLINK "${${key}_RESOLVED_ITEM}")
+          get_filename_component(target "${${key}_RESOLVED_ITEM}" REALPATH)
+          set_bundle_key_values(${keys_var} "${exe}" "${target}" "${exepath}" "${dirs}" 1 "${exe_rpaths}")
+          get_item_key("${target}" targetkey)
+
+          if(WIN32)
+            # ignore case on Windows
+            string(TOLOWER "${${key}_RESOLVED_ITEM}" resolved_item_compare)
+            string(TOLOWER "${${targetkey}_RESOLVED_EMBEDDED_ITEM}" resolved_embedded_item_compare)
+          else()
+            set(resolved_item_compare "${${key}_RESOLVED_ITEM}")
+            set(resolved_embedded_item_compare "${${targetkey}_RESOLVED_EMBEDDED_ITEM}")
+          endif()
+          get_filename_component(resolved_item_compare "${resolved_item_compare}" NAME)
+          get_filename_component(resolved_embedded_item_compare "${resolved_embedded_item_compare}" NAME)
+
+          if(NOT "${resolved_item_compare}" STREQUAL "${resolved_embedded_item_compare}")
+            set(${key}_COPYFLAG "2")
+            set(${key}_RESOLVED_ITEM "${${targetkey}_RESOLVED_EMBEDDED_ITEM}")
+          endif()
+
+        endif()
+      endif()
+    endforeach()
     # Propagate values to caller's scope:
     #
     set(${keys_var} ${${keys_var}} PARENT_SCOPE)
@@ -640,6 +667,24 @@ function(get_bundle_keys app libs dirs keys_var)
   endif()
 endfunction()
 
+function(link_resolved_item_into_bundle resolved_item resolved_embedded_item)
+  if(WIN32)
+    # ignore case on Windows
+    string(TOLOWER "${resolved_item}" resolved_item_compare)
+    string(TOLOWER "${resolved_embedded_item}" resolved_embedded_item_compare)
+  else()
+    set(resolved_item_compare "${resolved_item}")
+    set(resolved_embedded_item_compare "${resolved_embedded_item}")
+  endif()
+
+  if("${resolved_item_compare}" STREQUAL "${resolved_embedded_item_compare}")
+    message(STATUS "warning: resolved_item == resolved_embedded_item - not linking...")
+  else()
+    get_filename_component(target_dir "${resolved_embedded_item}" DIRECTORY)
+    file(RELATIVE_PATH symlink_target "${target_dir}" "${resolved_item}")
+    execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink "${symlink_target}" "${resolved_embedded_item}")
+  endif()
+endfunction()
 
 function(copy_resolved_item_into_bundle resolved_item resolved_embedded_item)
   if(WIN32)
@@ -854,7 +899,9 @@ function(fixup_bundle app libs dirs)
     set(i 0)
     foreach(key ${keys})
       math(EXPR i ${i}+1)
-      if(${${key}_COPYFLAG})
+      if("${${key}_COPYFLAG}" STREQUAL "2")
+        message(STATUS "${i}/${n}: linking '${${key}_RESOLVED_ITEM}' -> '${${key}_RESOLVED_EMBEDDED_ITEM}'")
+      elseif(${${key}_COPYFLAG})
         message(STATUS "${i}/${n}: copying '${${key}_RESOLVED_ITEM}'")
       else()
         message(STATUS "${i}/${n}: *NOT* copying '${${key}_RESOLVED_ITEM}'")
@@ -872,7 +919,10 @@ function(fixup_bundle app libs dirs)
         message(STATUS "")
       endif()
 
-      if(${${key}_COPYFLAG})
+      if("${${key}_COPYFLAG}" STREQUAL "2")
+        link_resolved_item_into_bundle("${${key}_RESOLVED_ITEM}"
+          "${${key}_RESOLVED_EMBEDDED_ITEM}")
+      elseif(${${key}_COPYFLAG})
         set(item "${${key}_ITEM}")
         if(item MATCHES "[^/]+\\.framework/")
           copy_resolved_framework_into_bundle("${${key}_RESOLVED_ITEM}"
@@ -889,7 +939,9 @@ function(fixup_bundle app libs dirs)
       math(EXPR i ${i}+1)
       if(APPLE)
         message(STATUS "${i}/${n}: fixing up '${${key}_RESOLVED_EMBEDDED_ITEM}'")
-        fixup_bundle_item("${${key}_RESOLVED_EMBEDDED_ITEM}" "${exepath}" "${dirs}")
+        if(NOT "${${key}_COPYFLAG}" STREQUAL "2")
+          fixup_bundle_item("${${key}_RESOLVED_EMBEDDED_ITEM}" "${exepath}" "${dirs}")
+        endif()
       else()
         message(STATUS "${i}/${n}: fix-up not required on this platform '${${key}_RESOLVED_EMBEDDED_ITEM}'")
       endif()
diff --git a/Modules/CMakeAddFortranSubdirectory.cmake b/Modules/CMakeAddFortranSubdirectory.cmake
index 3b39bce..4649f35 100644
--- a/Modules/CMakeAddFortranSubdirectory.cmake
+++ b/Modules/CMakeAddFortranSubdirectory.cmake
@@ -45,7 +45,6 @@
 set(_MS_MINGW_SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR})
 include(CheckLanguage)
 include(ExternalProject)
-include(CMakeParseArguments)
 
 function(_setup_mingw_config_and_build source_dir build_dir)
   # Look for a MinGW gfortran.
diff --git a/Modules/CMakeCSharpCompiler.cmake.in b/Modules/CMakeCSharpCompiler.cmake.in
new file mode 100644
index 0000000..5ecc480
--- /dev/null
+++ b/Modules/CMakeCSharpCompiler.cmake.in
@@ -0,0 +1,9 @@
+set(CMAKE_CSharp_COMPILER "@CMAKE_CSharp_COMPILER@")
+set(CMAKE_CSharp_COMPILER_ID "@CMAKE_CSharp_COMPILER_ID@")
+set(CMAKE_CSharp_COMPILER_VERSION "@CMAKE_CSharp_COMPILER_VERSION@")
+
+set(CMAKE_CSharp_COMPILER_WORKS "@CMAKE_CSharp_COMPILER_WORKS@")
+
+set(CMAKE_CSharp_COMPILER_ID_RUN "@CMAKE_CSharp_COMPILER_ID_RUN@")
+set(CMAKE_CSharp_IGNORE_EXTENSIONS "inl;h;hpp;HPP;H;o;O;obj;OBJ;def;DEF;rc;RC")
+set(CMAKE_CSharp_SOURCE_FILE_EXTENSIONS "cs")
diff --git a/Modules/CMakeCSharpCompilerId.cs.in b/Modules/CMakeCSharpCompilerId.cs.in
new file mode 100644
index 0000000..987f63a
--- /dev/null
+++ b/Modules/CMakeCSharpCompilerId.cs.in
@@ -0,0 +1,63 @@
+using System;
+
+namespace CSharp
+{
+    public class CSharpApp
+    {
+        const string InfoCompiler = "INFO:compiler[Microsoft "
+#if PlatformToolsetv100
+        + "Visual Studio"
+#elif PlatformToolsetv110
+        + "Visual Studio"
+#elif PlatformToolsetv120
+        + "Visual Studio"
+#elif PlatformToolsetv140
+        + "Visual Studio"
+#elif PlatformToolsetv141
+        + "Visual Studio"
+#else
+        + "unknown"
+#endif
+        + "]";
+
+        const string InfoPlatform = "INFO:platform[Windows]";
+
+        const string InfoArchitecture = "INFO:arch["
+#if Platformx64
+        + "x64"
+#elif Platformx86
+        + "x86"
+#elif PlatformxWin32
+        + "Win32]"
+#else
+        + "unknown"
+#endif
+        + "]";
+
+        const string InfoCompilerVersion = "INFO:compiler_version["
+#if PlatformToolsetv100
+        + "2010"
+#elif PlatformToolsetv110
+        + "2012"
+#elif PlatformToolsetv120
+        + "2013"
+#elif PlatformToolsetv140
+        + "2015"
+#elif PlatformToolsetv141
+        + "2017"
+#else
+        + "9999"
+#endif
+        + "]";
+
+        static void Main(string[] args)
+        {
+            // we have to print the lines to make sure
+            // the compiler does not optimize them away ...
+            System.Console.WriteLine(InfoCompiler);
+            System.Console.WriteLine(InfoPlatform);
+            System.Console.WriteLine(InfoArchitecture);
+            System.Console.WriteLine(InfoCompilerVersion);
+        }
+    }
+}
diff --git a/Modules/CMakeCSharpInformation.cmake b/Modules/CMakeCSharpInformation.cmake
new file mode 100644
index 0000000..dc775bd
--- /dev/null
+++ b/Modules/CMakeCSharpInformation.cmake
@@ -0,0 +1,119 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# This file sets the basic flags for the C# language in CMake.
+# It also loads the available platform file for the system-compiler
+# if it exists.
+
+set(CMAKE_BASE_NAME)
+get_filename_component(CMAKE_BASE_NAME "${CMAKE_CSharp_COMPILER}" NAME_WE)
+
+set(CMAKE_BUILD_TYPE_INIT Debug)
+
+set(CMAKE_CSharp_FLAGS_INIT "/define:TRACE /langversion:3 /nowin32manifest")
+set(CMAKE_CSharp_FLAGS_DEBUG_INIT "/debug:full /optimize- /warn:3 /errorreport:prompt /define:DEBUG")
+set(CMAKE_CSharp_FLAGS_RELEASE_INIT "/debug:none /optimize  /warn:1  /errorreport:queue")
+set(CMAKE_CSharp_FLAGS_RELWITHDEBINFO_INIT "/debug:full /optimize-")
+set(CMAKE_CSharp_FLAGS_MINSIZEREL_INIT "/debug:none /optimize")
+set(CMAKE_CSharp_LINKER_SUPPORTS_PDB ON)
+
+set(CMAKE_CSharp_STANDARD_LIBRARIES_INIT "System")
+
+if(CMAKE_SIZEOF_VOID_P EQUAL 4)
+  set(CMAKE_CSharp_FLAGS_INIT "/platform:x86 ${CMAKE_CSharp_FLAGS_INIT}")
+else()
+  set(CMAKE_CSharp_FLAGS_INIT "/platform:x64 ${CMAKE_CSharp_FLAGS_INIT}")
+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.
+
+# for most systems a module is the same as a shared library
+# so unless the variable CMAKE_MODULE_EXISTS is set just
+# copy the values from the LIBRARY variables
+if(NOT CMAKE_MODULE_EXISTS)
+  set(CMAKE_SHARED_MODULE_CSharp_FLAGS ${CMAKE_SHARED_LIBRARY_CSharp_FLAGS})
+  set(CMAKE_SHARED_MODULE_CREATE_CSharp_FLAGS ${CMAKE_SHARED_LIBRARY_CREATE_CSharp_FLAGS})
+endif()
+
+# add the flags to the cache based
+# on the initial values computed in the platform/*.cmake files
+# use _INIT variables so that this only happens the first time
+# and you can set these flags in the cmake cache
+set(CMAKE_CSharp_FLAGS_INIT "$ENV{CSharpFLAGS} ${CMAKE_CSharp_FLAGS_INIT}")
+# avoid just having a space as the initial value for the cache
+if(CMAKE_CSharp_FLAGS_INIT STREQUAL " ")
+  set(CMAKE_CSharp_FLAGS_INIT)
+endif()
+set (CMAKE_CSharp_FLAGS "${CMAKE_CSharp_FLAGS_INIT}" CACHE STRING
+     "Flags used by the C# compiler during all build types.")
+
+if(NOT CMAKE_NOT_USING_CONFIG_FLAGS)
+  set (CMAKE_CSharp_FLAGS_DEBUG "${CMAKE_CSharp_FLAGS_DEBUG_INIT}" CACHE STRING
+     "Flags used by the C# compiler during debug builds.")
+  set (CMAKE_CSharp_FLAGS_MINSIZEREL "${CMAKE_CSharp_FLAGS_MINSIZEREL_INIT}" CACHE STRING
+     "Flags used by the C# compiler during release builds for minimum size.")
+  set (CMAKE_CSharp_FLAGS_RELEASE "${CMAKE_CSharp_FLAGS_RELEASE_INIT}" CACHE STRING
+     "Flags used by the C# compiler during release builds.")
+  set (CMAKE_CSharp_FLAGS_RELWITHDEBINFO "${CMAKE_CSharp_FLAGS_RELWITHDEBINFO_INIT}" CACHE STRING
+     "Flags used by the C# compiler during release builds with debug info.")
+endif()
+
+if(CMAKE_CSharp_STANDARD_LIBRARIES_INIT)
+  set(CMAKE_CSharp_STANDARD_LIBRARIES "${CMAKE_CSharp_STANDARD_LIBRARIES_INIT}"
+    CACHE STRING "Libraries linked by default with all C# applications.")
+  mark_as_advanced(CMAKE_CSharp_STANDARD_LIBRARIES)
+endif()
+
+# set missing flags (if they do not exist). This is needed in the
+# unlikely case that you have only C# and no C/C++ targets in your
+# project.
+if(NOT EXISTS CMAKE_SHARED_LINKER_FLAGS)
+    set(CMAKE_SHARED_LINKER_FLAGS "" CACHE STRING "" FORCE)
+endif()
+if(NOT EXISTS CMAKE_SHARED_LINKER_FLAGS_DEBUG)
+    set(CMAKE_SHARED_LINKER_FLAGS_DEBUG "" CACHE STRING "" FORCE)
+endif()
+if(NOT EXISTS CMAKE_SHARED_LINKER_FLAGS_RELEASE)
+    set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "" CACHE STRING "" FORCE)
+endif()
+if(NOT EXISTS CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL)
+    set(CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL "" CACHE STRING "" FORCE)
+endif()
+if(NOT EXISTS CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO)
+    set(CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO "" CACHE STRING "" FORCE)
+endif()
+
+if(NOT EXISTS CMAKE_EXE_LINKER_FLAGS)
+    set(CMAKE_EXE_LINKER_FLAGS "" CACHE STRING "" FORCE)
+endif()
+if(NOT EXISTS CMAKE_EXE_LINKER_FLAGS_DEBUG)
+    set(CMAKE_EXE_LINKER_FLAGS_DEBUG "" CACHE STRING "" FORCE)
+endif()
+if(NOT EXISTS CMAKE_EXE_LINKER_FLAGS_RELEASE)
+    set(CMAKE_EXE_LINKER_FLAGS_RELEASE "" CACHE STRING "" FORCE)
+endif()
+if(NOT EXISTS CMAKE_EXE_LINKER_FLAGS_MINSIZEREL)
+    set(CMAKE_EXE_LINKER_FLAGS_MINSIZEREL "" CACHE STRING "" FORCE)
+endif()
+if(NOT EXISTS CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO)
+    set(CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO "" CACHE STRING "" FORCE)
+endif()
+
+set(CMAKE_CSharp_CREATE_SHARED_LIBRARY "CSharp_NO_CREATE_SHARED_LIBRARY")
+set(CMAKE_CSharp_CREATE_SHARED_MODULE "CSharp_NO_CREATE_SHARED_MODULE")
+set(CMAKE_CSharp_LINK_EXECUTABLE "CSharp_NO_LINK_EXECUTABLE")
+
+mark_as_advanced(
+    CMAKE_CSharp_FLAGS
+    CMAKE_CSharp_FLAGS_RELEASE
+    CMAKE_CSharp_FLAGS_RELWITHDEBINFO
+    CMAKE_CSharp_FLAGS_MINSIZEREL
+    CMAKE_CSharp_FLAGS_DEBUG
+    )
+
+set(CMAKE_CSharp_USE_RESPONSE_FILE_FOR_OBJECTS 1)
+set(CMAKE_CSharp_INFORMATION_LOADED 1)
diff --git a/Modules/CMakeCUDACompiler.cmake.in b/Modules/CMakeCUDACompiler.cmake.in
new file mode 100644
index 0000000..f524e5f
--- /dev/null
+++ b/Modules/CMakeCUDACompiler.cmake.in
@@ -0,0 +1,27 @@
+set(CMAKE_CUDA_COMPILER "@CMAKE_CUDA_COMPILER@")
+set(CMAKE_CUDA_HOST_COMPILER "@CMAKE_CUDA_HOST_COMPILER@")
+set(CMAKE_CUDA_HOST_LINK_LAUNCHER "@CMAKE_CUDA_HOST_LINK_LAUNCHER@")
+set(CMAKE_CUDA_COMPILER_ID "@CMAKE_CUDA_COMPILER_ID@")
+set(CMAKE_CUDA_COMPILER_VERSION "@CMAKE_CUDA_COMPILER_VERSION@")
+set(CMAKE_CUDA_STANDARD_COMPUTED_DEFAULT "@CMAKE_CUDA_STANDARD_COMPUTED_DEFAULT@")
+set(CMAKE_CUDA_SIMULATE_ID "@CMAKE_CUDA_SIMULATE_ID@")
+set(CMAKE_CUDA_SIMULATE_VERSION "@CMAKE_CUDA_SIMULATE_VERSION@")
+ at SET_MSVC_CUDA_ARCHITECTURE_ID@
+
+set(CMAKE_CUDA_COMPILER_ENV_VAR "CUDACXX")
+set(CMAKE_CUDA_HOST_COMPILER_ENV_VAR "CUDAHOSTCXX")
+
+set(CMAKE_CUDA_COMPILER_ID_RUN 1)
+set(CMAKE_CUDA_SOURCE_FILE_EXTENSIONS cu)
+set(CMAKE_CUDA_LINKER_PREFERENCE 15)
+set(CMAKE_CUDA_LINKER_PREFERENCE_PROPAGATES 1)
+
+set(CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES "@CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES@")
+
+set(CMAKE_CUDA_HOST_IMPLICIT_LINK_LIBRARIES "@CMAKE_CUDA_HOST_IMPLICIT_LINK_LIBRARIES@")
+set(CMAKE_CUDA_HOST_IMPLICIT_LINK_DIRECTORIES "@CMAKE_CUDA_HOST_IMPLICIT_LINK_DIRECTORIES@")
+set(CMAKE_CUDA_HOST_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "@CMAKE_CUDA_HOST_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES@")
+
+set(CMAKE_CUDA_IMPLICIT_LINK_LIBRARIES "@CMAKE_CUDA_IMPLICIT_LINK_LIBRARIES@")
+set(CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES "@CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES@")
+set(CMAKE_CUDA_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "@CMAKE_CUDA_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES@")
diff --git a/Modules/CMakeCUDACompilerABI.cu b/Modules/CMakeCUDACompilerABI.cu
new file mode 100644
index 0000000..99bacef
--- /dev/null
+++ b/Modules/CMakeCUDACompilerABI.cu
@@ -0,0 +1,16 @@
+#ifndef __CUDACC__
+#error "A C or C++ compiler has been selected for CUDA"
+#endif
+
+#include "CMakeCompilerABI.h"
+
+int main(int argc, char* argv[])
+{
+  int require = 0;
+  require += info_sizeof_dptr[argc];
+#if defined(ABI_ID)
+  require += info_abi[argc];
+#endif
+  (void)argv;
+  return require;
+}
diff --git a/Modules/CMakeCUDACompilerId.cu.in b/Modules/CMakeCUDACompilerId.cu.in
new file mode 100644
index 0000000..018bab7
--- /dev/null
+++ b/Modules/CMakeCUDACompilerId.cu.in
@@ -0,0 +1,50 @@
+#ifndef __CUDACC__
+# error "A C or C++ compiler has been selected for CUDA"
+#endif
+
+ at CMAKE_CUDA_COMPILER_ID_CONTENT@
+
+/* Construct the string literal in pieces to prevent the source from
+   getting matched.  Store it in a pointer rather than an array
+   because some compilers will just produce instructions to fill the
+   array rather than assigning a pointer to a static array.  */
+char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]";
+#ifdef SIMULATE_ID
+char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]";
+#endif
+
+ at CMAKE_CUDA_COMPILER_ID_PLATFORM_CONTENT@
+ at CMAKE_CUDA_COMPILER_ID_ERROR_FOR_TEST@
+
+const char* info_language_dialect_default = "INFO" ":" "dialect_default["
+#if __cplusplus > 201402L
+  "17"
+#elif __cplusplus >= 201402L
+  "14"
+#elif __cplusplus >= 201103L
+  "11"
+#else
+  "98"
+#endif
+"]";
+
+/*--------------------------------------------------------------------------*/
+
+int main(int argc, char* argv[])
+{
+  int require = 0;
+  require += info_compiler[argc];
+  require += info_platform[argc];
+#ifdef COMPILER_VERSION_MAJOR
+  require += info_version[argc];
+#endif
+#ifdef SIMULATE_ID
+  require += info_simulate[argc];
+#endif
+#ifdef SIMULATE_VERSION_MAJOR
+  require += info_simulate_version[argc];
+#endif
+  require += info_language_dialect_default[argc];
+  (void)argv;
+  return require;
+}
diff --git a/Modules/CMakeCUDAInformation.cmake b/Modules/CMakeCUDAInformation.cmake
new file mode 100644
index 0000000..1c48159
--- /dev/null
+++ b/Modules/CMakeCUDAInformation.cmake
@@ -0,0 +1,206 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+if(UNIX)
+  set(CMAKE_CUDA_OUTPUT_EXTENSION .o)
+else()
+  set(CMAKE_CUDA_OUTPUT_EXTENSION .obj)
+endif()
+set(CMAKE_INCLUDE_FLAG_CUDA "-I")
+
+# Load compiler-specific information.
+if(CMAKE_CUDA_COMPILER_ID)
+  include(Compiler/${CMAKE_CUDA_COMPILER_ID}-CUDA OPTIONAL)
+endif()
+
+# load the system- and compiler specific files
+if(CMAKE_CUDA_COMPILER_ID)
+  # load a hardware specific file, mostly useful for embedded compilers
+  if(CMAKE_SYSTEM_PROCESSOR)
+    include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_CUDA_COMPILER_ID}-CUDA-${CMAKE_SYSTEM_PROCESSOR} OPTIONAL)
+  endif()
+  include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_CUDA_COMPILER_ID}-CUDA OPTIONAL)
+endif()
+
+
+if(NOT CMAKE_SHARED_LIBRARY_RUNTIME_CUDA_FLAG)
+  set(CMAKE_SHARED_LIBRARY_RUNTIME_CUDA_FLAG ${CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG})
+endif()
+
+if(NOT CMAKE_SHARED_LIBRARY_RUNTIME_CUDA_FLAG_SEP)
+  set(CMAKE_SHARED_LIBRARY_RUNTIME_CUDA_FLAG_SEP ${CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG_SEP})
+endif()
+
+if(NOT CMAKE_SHARED_LIBRARY_RPATH_LINK_CUDA_FLAG)
+  set(CMAKE_SHARED_LIBRARY_RPATH_LINK_CUDA_FLAG ${CMAKE_SHARED_LIBRARY_RPATH_LINK_C_FLAG})
+endif()
+
+if(NOT DEFINED CMAKE_EXE_EXPORTS_CUDA_FLAG)
+  set(CMAKE_EXE_EXPORTS_CUDA_FLAG ${CMAKE_EXE_EXPORTS_C_FLAG})
+endif()
+
+if(NOT DEFINED CMAKE_SHARED_LIBRARY_SONAME_CUDA_FLAG)
+  set(CMAKE_SHARED_LIBRARY_SONAME_CUDA_FLAG ${CMAKE_SHARED_LIBRARY_SONAME_C_FLAG})
+endif()
+
+if(NOT CMAKE_EXECUTABLE_RUNTIME_CUDA_FLAG)
+  set(CMAKE_EXECUTABLE_RUNTIME_CUDA_FLAG ${CMAKE_SHARED_LIBRARY_RUNTIME_CUDA_FLAG})
+endif()
+
+if(NOT CMAKE_EXECUTABLE_RUNTIME_CUDA_FLAG_SEP)
+  set(CMAKE_EXECUTABLE_RUNTIME_CUDA_FLAG_SEP ${CMAKE_SHARED_LIBRARY_RUNTIME_CUDA_FLAG_SEP})
+endif()
+
+if(NOT CMAKE_EXECUTABLE_RPATH_LINK_CUDA_FLAG)
+  set(CMAKE_EXECUTABLE_RPATH_LINK_CUDA_FLAG ${CMAKE_SHARED_LIBRARY_RPATH_LINK_CUDA_FLAG})
+endif()
+
+if(NOT DEFINED CMAKE_SHARED_LIBRARY_LINK_CUDA_WITH_RUNTIME_PATH)
+  set(CMAKE_SHARED_LIBRARY_LINK_CUDA_WITH_RUNTIME_PATH ${CMAKE_SHARED_LIBRARY_LINK_C_WITH_RUNTIME_PATH})
+endif()
+
+
+# for most systems a module is the same as a shared library
+# so unless the variable CMAKE_MODULE_EXISTS is set just
+# copy the values from the LIBRARY variables
+if(NOT CMAKE_MODULE_EXISTS)
+  set(CMAKE_SHARED_MODULE_CUDA_FLAGS ${CMAKE_SHARED_LIBRARY_CUDA_FLAGS})
+  set(CMAKE_SHARED_MODULE_CREATE_CUDA_FLAGS ${CMAKE_SHARED_LIBRARY_CREATE_CUDA_FLAGS})
+endif()
+
+# add the flags to the cache based
+# on the initial values computed in the platform/*.cmake files
+# use _INIT variables so that this only happens the first time
+# and you can set these flags in the cmake cache
+set(CMAKE_CUDA_FLAGS_INIT "$ENV{CUDAFLAGS} ${CMAKE_CUDA_FLAGS_INIT}")
+
+foreach(c "" _DEBUG _RELEASE _MINSIZEREL _RELWITHDEBINFO)
+  string(STRIP "${CMAKE_CUDA_FLAGS${c}_INIT}" CMAKE_CUDA_FLAGS${c}_INIT)
+endforeach()
+
+set (CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS_INIT}" CACHE STRING
+     "Flags used by the compiler during all build types.")
+
+if(NOT CMAKE_NOT_USING_CONFIG_FLAGS)
+  set (CMAKE_CUDA_FLAGS_DEBUG "${CMAKE_CUDA_FLAGS_DEBUG_INIT}" CACHE STRING
+     "Flags used by the compiler during debug builds.")
+  set (CMAKE_CUDA_FLAGS_MINSIZEREL "${CMAKE_CUDA_FLAGS_MINSIZEREL_INIT}" CACHE STRING
+     "Flags used by the compiler during release builds for minimum size.")
+  set (CMAKE_CUDA_FLAGS_RELEASE "${CMAKE_CUDA_FLAGS_RELEASE_INIT}" CACHE STRING
+     "Flags used by the compiler during release builds.")
+  set (CMAKE_CUDA_FLAGS_RELWITHDEBINFO "${CMAKE_CUDA_FLAGS_RELWITHDEBINFO_INIT}" CACHE STRING
+     "Flags used by the compiler during release builds with debug info.")
+
+endif()
+
+if(CMAKE_CUDA_STANDARD_LIBRARIES_INIT)
+  set(CMAKE_CUDA_STANDARD_LIBRARIES "${CMAKE_CUDA_STANDARD_LIBRARIES_INIT}"
+    CACHE STRING "Libraries linked by default with all CUDA applications.")
+  mark_as_advanced(CMAKE_CUDA_STANDARD_LIBRARIES)
+endif()
+
+include(CMakeCommonLanguageInclude)
+
+# now define the following rules:
+# CMAKE_CUDA_CREATE_SHARED_LIBRARY
+# CMAKE_CUDA_CREATE_SHARED_MODULE
+# CMAKE_CUDA_COMPILE_OBJECT
+# CMAKE_CUDA_LINK_EXECUTABLE
+
+if(CMAKE_CUDA_HOST_COMPILER)
+  set(CMAKE_CUDA_HOST_FLAGS "-ccbin=<CMAKE_CUDA_HOST_COMPILER>")
+else()
+  set(CMAKE_CUDA_HOST_FLAGS "")
+endif()
+
+set(__IMPLICT_LINKS )
+foreach(dir ${CMAKE_CUDA_HOST_IMPLICIT_LINK_DIRECTORIES})
+  string(APPEND __IMPLICT_LINKS " -L\"${dir}\"")
+endforeach()
+foreach(lib ${CMAKE_CUDA_HOST_IMPLICIT_LINK_LIBRARIES})
+  if(${lib} MATCHES "/")
+    string(APPEND __IMPLICT_LINKS " \"${lib}\"")
+  else()
+    string(APPEND __IMPLICT_LINKS " -l${lib}")
+  endif()
+endforeach()
+
+# create a shared library
+if(NOT CMAKE_CUDA_CREATE_SHARED_LIBRARY)
+  set(CMAKE_CUDA_CREATE_SHARED_LIBRARY
+      "<CMAKE_CUDA_HOST_LINK_LAUNCHER> <CMAKE_SHARED_LIBRARY_CUDA_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CUDA_FLAGS> <SONAME_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>${__IMPLICT_LINKS}")
+endif()
+
+# create a shared module copy the shared library rule by default
+if(NOT CMAKE_CUDA_CREATE_SHARED_MODULE)
+  set(CMAKE_CUDA_CREATE_SHARED_MODULE ${CMAKE_CUDA_CREATE_SHARED_LIBRARY})
+endif()
+
+# Create a static archive incrementally for large object file counts.
+if(NOT DEFINED CMAKE_CUDA_ARCHIVE_CREATE)
+  set(CMAKE_CUDA_ARCHIVE_CREATE "<CMAKE_AR> qc <TARGET> <LINK_FLAGS> <OBJECTS>")
+endif()
+if(NOT DEFINED CMAKE_CUDA_ARCHIVE_APPEND)
+  set(CMAKE_CUDA_ARCHIVE_APPEND "<CMAKE_AR> q  <TARGET> <LINK_FLAGS> <OBJECTS>")
+endif()
+if(NOT DEFINED CMAKE_CUDA_ARCHIVE_FINISH)
+  set(CMAKE_CUDA_ARCHIVE_FINISH "<CMAKE_RANLIB> <TARGET>")
+endif()
+
+#Specify how to compile when ptx has been requested
+if(NOT CMAKE_CUDA_COMPILE_PTX_COMPILATION)
+  set(CMAKE_CUDA_COMPILE_PTX_COMPILATION
+    "<CMAKE_CUDA_COMPILER> ${CMAKE_CUDA_HOST_FLAGS} <DEFINES> <INCLUDES> <FLAGS> -x cu -ptx <SOURCE> -o <OBJECT>")
+endif()
+
+#Specify how to compile when separable compilation has been requested
+if(NOT CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION)
+  set(CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION
+    "<CMAKE_CUDA_COMPILER> ${CMAKE_CUDA_HOST_FLAGS} <DEFINES> <INCLUDES> <FLAGS> -x cu -dc <SOURCE> -o <OBJECT>")
+endif()
+
+#Specify how to compile when whole compilation has been requested
+if(NOT CMAKE_CUDA_COMPILE_WHOLE_COMPILATION)
+  set(CMAKE_CUDA_COMPILE_WHOLE_COMPILATION
+    "<CMAKE_CUDA_COMPILER> ${CMAKE_CUDA_HOST_FLAGS} <DEFINES> <INCLUDES> <FLAGS> -x cu -c <SOURCE> -o <OBJECT>")
+endif()
+
+if(CMAKE_GENERATOR STREQUAL "Ninja")
+  set(CMAKE_CUDA_COMPILE_DEPENDENCY_DETECTION
+    "<CMAKE_CUDA_COMPILER> ${CMAKE_CUDA_HOST_FLAGS} <DEFINES> <INCLUDES> <FLAGS> -x cu -M <SOURCE> -MT <OBJECT> -o $DEP_FILE")
+  #The Ninja generator uses the make file dependency files to determine what
+  #files need to be recompiled. Unfortunately, nvcc doesn't support building
+  #a source file and generating the dependencies of said file in a single
+  #invocation. Instead we have to state that you need to chain two commands.
+  #
+  #The makefile generators uses the custom CMake dependency scanner, and thus
+  #it is exempt from this logic.
+  list(APPEND CMAKE_CUDA_COMPILE_PTX_COMPILATION "${CMAKE_CUDA_COMPILE_DEPENDENCY_DETECTION}")
+  list(APPEND CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION "${CMAKE_CUDA_COMPILE_DEPENDENCY_DETECTION}")
+  list(APPEND CMAKE_CUDA_COMPILE_WHOLE_COMPILATION "${CMAKE_CUDA_COMPILE_DEPENDENCY_DETECTION}")
+endif()
+
+# compile a cu file into an executable
+if(NOT CMAKE_CUDA_LINK_EXECUTABLE)
+  set(CMAKE_CUDA_LINK_EXECUTABLE
+    "<CMAKE_CUDA_HOST_LINK_LAUNCHER> <CMAKE_CUDA_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>${__IMPLICT_LINKS}")
+endif()
+
+#These are used when linking relocatable (dc) cuda code
+if(NOT CMAKE_CUDA_DEVICE_LINK_LIBRARY)
+  set(CMAKE_CUDA_DEVICE_LINK_LIBRARY
+    "<CMAKE_CUDA_COMPILER> <CMAKE_CUDA_LINK_FLAGS> <LANGUAGE_COMPILE_FLAGS> ${CMAKE_CUDA_COMPILE_OPTIONS_PIC} -shared -dlink <OBJECTS> -o <TARGET> <LINK_LIBRARIES>")
+endif()
+if(NOT CMAKE_CUDA_DEVICE_LINK_EXECUTABLE)
+  set(CMAKE_CUDA_DEVICE_LINK_EXECUTABLE
+    "<CMAKE_CUDA_COMPILER> <FLAGS> <CMAKE_CUDA_LINK_FLAGS> ${CMAKE_CUDA_COMPILE_OPTIONS_PIC} -shared -dlink <OBJECTS> -o <TARGET> <LINK_LIBRARIES>")
+endif()
+
+mark_as_advanced(
+CMAKE_CUDA_FLAGS
+CMAKE_CUDA_FLAGS_RELEASE
+CMAKE_CUDA_FLAGS_RELWITHDEBINFO
+CMAKE_CUDA_FLAGS_MINSIZEREL
+CMAKE_CUDA_FLAGS_DEBUG)
+
+set(CMAKE_CUDA_INFORMATION_LOADED 1)
diff --git a/Modules/CMakeCXXCompiler.cmake.in b/Modules/CMakeCXXCompiler.cmake.in
index c295b74..6d56488 100644
--- a/Modules/CMakeCXXCompiler.cmake.in
+++ b/Modules/CMakeCXXCompiler.cmake.in
@@ -8,6 +8,7 @@ set(CMAKE_CXX_COMPILE_FEATURES "@CMAKE_CXX_COMPILE_FEATURES@")
 set(CMAKE_CXX98_COMPILE_FEATURES "@CMAKE_CXX98_COMPILE_FEATURES@")
 set(CMAKE_CXX11_COMPILE_FEATURES "@CMAKE_CXX11_COMPILE_FEATURES@")
 set(CMAKE_CXX14_COMPILE_FEATURES "@CMAKE_CXX14_COMPILE_FEATURES@")
+set(CMAKE_CXX17_COMPILE_FEATURES "@CMAKE_CXX17_COMPILE_FEATURES@")
 
 set(CMAKE_CXX_PLATFORM_ID "@CMAKE_CXX_PLATFORM_ID@")
 set(CMAKE_CXX_SIMULATE_ID "@CMAKE_CXX_SIMULATE_ID@")
diff --git a/Modules/CMakeCXXCompilerId.cpp.in b/Modules/CMakeCXXCompilerId.cpp.in
index 3e5c0fc..9aa096d 100644
--- a/Modules/CMakeCXXCompilerId.cpp.in
+++ b/Modules/CMakeCXXCompilerId.cpp.in
@@ -28,7 +28,9 @@ char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]";
 @CMAKE_CXX_COMPILER_ID_ERROR_FOR_TEST@
 
 const char* info_language_dialect_default = "INFO" ":" "dialect_default["
-#if __cplusplus >= 201402L
+#if __cplusplus > 201402L
+  "17"
+#elif __cplusplus >= 201402L
   "14"
 #elif __cplusplus >= 201103L
   "11"
diff --git a/Modules/CMakeCompilerIdDetection.cmake b/Modules/CMakeCompilerIdDetection.cmake
index 4732250..7ca79bd 100644
--- a/Modules/CMakeCompilerIdDetection.cmake
+++ b/Modules/CMakeCompilerIdDetection.cmake
@@ -11,11 +11,9 @@ function(_readFile file)
   set(_compiler_id_pp_test_${CompilerId} ${_compiler_id_pp_test} PARENT_SCOPE)
 endfunction()
 
-include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake)
-
 function(compiler_id_detection outvar lang)
 
-  if (NOT lang STREQUAL Fortran)
+  if (NOT lang STREQUAL Fortran AND NOT lang STREQUAL CSharp)
     file(GLOB lang_files
       "${CMAKE_ROOT}/Modules/Compiler/*-DetermineCompiler.cmake")
     set(nonlang CXX)
@@ -90,6 +88,11 @@ function(compiler_id_detection outvar lang)
     list(APPEND ordered_compilers
       MIPSpro)
 
+    #Currently the only CUDA compilers are NVIDIA
+    if(lang STREQUAL CUDA)
+      set(ordered_compilers NVIDIA)
+    endif()
+
     if(CID_ID_DEFINE)
       foreach(Id ${ordered_compilers})
         set(CMAKE_${lang}_COMPILER_ID_CONTENT "${CMAKE_${lang}_COMPILER_ID_CONTENT}# define ${CID_PREFIX}COMPILER_IS_${Id} 0\n")
diff --git a/Modules/CMakeDetermineASMCompiler.cmake b/Modules/CMakeDetermineASMCompiler.cmake
index deb10fb..4162726 100644
--- a/Modules/CMakeDetermineASMCompiler.cmake
+++ b/Modules/CMakeDetermineASMCompiler.cmake
@@ -9,7 +9,13 @@ include(${CMAKE_ROOT}/Modules/CMakeDetermineCompiler.cmake)
 if(NOT CMAKE_ASM${ASM_DIALECT}_COMPILER)
   # prefer the environment variable ASM
   if(NOT $ENV{ASM${ASM_DIALECT}} STREQUAL "")
-    set(CMAKE_ASM${ASM_DIALECT}_COMPILER_INIT "$ENV{ASM${ASM_DIALECT}}")
+    get_filename_component(CMAKE_ASM${ASM_DIALECT}_COMPILER_INIT $ENV{ASM${ASM_DIALECT}} PROGRAM PROGRAM_ARGS CMAKE_ASM${ASM_DIALECT}_FLAGS_ENV_INIT)
+    if(CMAKE_ASM${ASM_DIALECT}_FLAGS_ENV_INIT)
+      set(CMAKE_ASM${ASM_DIALECT}_COMPILER_ARG1 "${CMAKE_ASM${ASM_DIALECT}_FLAGS_ENV_INIT}" CACHE STRING "First argument to ASM${ASM_DIALECT} compiler")
+    endif()
+    if(NOT EXISTS ${CMAKE_ASM${ASM_DIALECT}_COMPILER_INIT})
+      message(FATAL_ERROR "Could not find compiler set in environment variable ASM${ASM_DIALECT}:\n$ENV{ASM${ASM_DIALECT}}.")
+    endif()
   endif()
 
   # finally list compilers to try
diff --git a/Modules/CMakeDetermineCSharpCompiler.cmake b/Modules/CMakeDetermineCSharpCompiler.cmake
new file mode 100644
index 0000000..1b8dd02
--- /dev/null
+++ b/Modules/CMakeDetermineCSharpCompiler.cmake
@@ -0,0 +1,43 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+if(NOT ${CMAKE_GENERATOR} MATCHES "Visual Studio ([^789]|[789][0-9])")
+   message(FATAL_ERROR
+    "C# is currently only supported for Microsoft Visual Studio 2010 and later.")
+endif()
+
+include(${CMAKE_ROOT}/Modules/CMakeDetermineCompiler.cmake)
+#include(Platform/${CMAKE_SYSTEM_NAME}-Determine-CSharp OPTIONAL)
+#include(Platform/${CMAKE_SYSTEM_NAME}-CSharp OPTIONAL)
+if(NOT CMAKE_CSharp_COMPILER_NAMES)
+  set(CMAKE_CSharp_COMPILER_NAMES csc)
+endif()
+
+# Build a small source file to identify the compiler.
+if(NOT CMAKE_CSharp_COMPILER_ID_RUN)
+  set(CMAKE_CSharp_COMPILER_ID_RUN 1)
+
+  # Try to identify the compiler.
+  set(CMAKE_CSharp_COMPILER_ID_STRINGS_PARAMETERS ENCODING UTF-16LE)
+  set(CMAKE_CSharp_COMPILER_ID)
+  include(${CMAKE_ROOT}/Modules/CMakeDetermineCompilerId.cmake)
+  CMAKE_DETERMINE_COMPILER_ID(CSharp CSFLAGS CMakeCSharpCompilerId.cs)
+
+  execute_process(COMMAND "${CMAKE_CSharp_COMPILER}" "/help" OUTPUT_VARIABLE output)
+  string(REPLACE "\n" ";" output "${output}")
+  foreach(line ${output})
+    string(TOUPPER ${line} line)
+    string(REGEX REPLACE "^.*COMPILER.*VERSION[^\\.0-9]*([\\.0-9]+).*$" "\\1" version "${line}")
+    if(version AND NOT "x${line}" STREQUAL "x${version}")
+      set(CMAKE_CSharp_COMPILER_VERSION ${version})
+      break()
+    endif()
+  endforeach()
+  message(STATUS "The CSharp compiler version is ${CMAKE_CSharp_COMPILER_VERSION}")
+endif()
+
+# configure variables set in this file for fast reload later on
+configure_file(${CMAKE_ROOT}/Modules/CMakeCSharpCompiler.cmake.in
+  ${CMAKE_PLATFORM_INFO_DIR}/CMakeCSharpCompiler.cmake
+  @ONLY
+  )
diff --git a/Modules/CMakeDetermineCUDACompiler.cmake b/Modules/CMakeDetermineCUDACompiler.cmake
new file mode 100644
index 0000000..7b6d17b
--- /dev/null
+++ b/Modules/CMakeDetermineCUDACompiler.cmake
@@ -0,0 +1,188 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+include(${CMAKE_ROOT}/Modules/CMakeDetermineCompiler.cmake)
+include(${CMAKE_ROOT}/Modules//CMakeParseImplicitLinkInfo.cmake)
+
+if( NOT ( ("${CMAKE_GENERATOR}" MATCHES "Make") OR
+          ("${CMAKE_GENERATOR}" MATCHES "Ninja") ) )
+  message(FATAL_ERROR "CUDA language not currently supported by \"${CMAKE_GENERATOR}\" generator")
+endif()
+
+if(NOT CMAKE_CUDA_COMPILER)
+  set(CMAKE_CUDA_COMPILER_INIT NOTFOUND)
+
+    # prefer the environment variable CUDACXX
+    if(NOT $ENV{CUDACXX} STREQUAL "")
+      get_filename_component(CMAKE_CUDA_COMPILER_INIT $ENV{CUDACXX} PROGRAM PROGRAM_ARGS CMAKE_CUDA_FLAGS_ENV_INIT)
+      if(CMAKE_CUDA_FLAGS_ENV_INIT)
+        set(CMAKE_CUDA_COMPILER_ARG1 "${CMAKE_CUDA_FLAGS_ENV_INIT}" CACHE STRING "First argument to CXX compiler")
+      endif()
+      if(NOT EXISTS ${CMAKE_CUDA_COMPILER_INIT})
+        message(FATAL_ERROR "Could not find compiler set in environment variable CUDACXX:\n$ENV{CUDACXX}.\n${CMAKE_CUDA_COMPILER_INIT}")
+      endif()
+    endif()
+
+  # finally list compilers to try
+  if(NOT CMAKE_CUDA_COMPILER_INIT)
+    set(CMAKE_CUDA_COMPILER_LIST nvcc)
+  endif()
+
+  _cmake_find_compiler(CUDA)
+else()
+  _cmake_find_compiler_path(CUDA)
+endif()
+
+mark_as_advanced(CMAKE_CUDA_COMPILER)
+
+#Allow the user to specify a host compiler
+set(CMAKE_CUDA_HOST_COMPILER "" CACHE FILEPATH "Host compiler to be used by nvcc")
+if(NOT $ENV{CUDAHOSTCXX} STREQUAL "")
+  get_filename_component(CMAKE_CUDA_HOST_COMPILER $ENV{CUDAHOSTCXX} PROGRAM)
+  if(NOT EXISTS ${CMAKE_CUDA_HOST_COMPILER})
+    message(FATAL_ERROR "Could not find compiler set in environment variable CUDAHOSTCXX:\n$ENV{CUDAHOSTCXX}.\n${CMAKE_CUDA_HOST_COMPILER}")
+  endif()
+endif()
+
+# Build a small source file to identify the compiler.
+if(NOT CMAKE_CUDA_COMPILER_ID_RUN)
+  set(CMAKE_CUDA_COMPILER_ID_RUN 1)
+
+  # Try to identify the compiler.
+  set(CMAKE_CUDA_COMPILER_ID)
+  set(CMAKE_CUDA_PLATFORM_ID)
+  file(READ ${CMAKE_ROOT}/Modules/CMakePlatformId.h.in
+    CMAKE_CUDA_COMPILER_ID_PLATFORM_CONTENT)
+
+  list(APPEND CMAKE_CUDA_COMPILER_ID_MATCH_VENDORS NVIDIA)
+  set(CMAKE_CUDA_COMPILER_ID_MATCH_VENDOR_REGEX_NVIDIA "nvcc: NVIDIA \(R\) Cuda compiler driver")
+
+  set(CMAKE_CXX_COMPILER_ID_TOOL_MATCH_REGEX "\nLd[^\n]*(\n[ \t]+[^\n]*)*\n[ \t]+([^ \t\r\n]+)[^\r\n]*-o[^\r\n]*CompilerIdCUDA/(\\./)?(CompilerIdCUDA.xctest/)?CompilerIdCUDA[ \t\n\\\"]")
+  set(CMAKE_CXX_COMPILER_ID_TOOL_MATCH_INDEX 2)
+
+  set(CMAKE_CUDA_COMPILER_ID_FLAGS_ALWAYS -v --keep --keep-dir tmp)
+  if(CMAKE_CUDA_HOST_COMPILER)
+      list(APPEND CMAKE_CUDA_COMPILER_ID_FLAGS_ALWAYS "-ccbin=${CMAKE_CUDA_HOST_COMPILER}")
+  endif()
+
+  include(${CMAKE_ROOT}/Modules/CMakeDetermineCompilerId.cmake)
+  CMAKE_DETERMINE_COMPILER_ID(CUDA CUDAFLAGS CMakeCUDACompilerId.cu)
+endif()
+
+include(CMakeFindBinUtils)
+if(MSVC_CUDA_ARCHITECTURE_ID)
+  set(SET_MSVC_CUDA_ARCHITECTURE_ID
+    "set(MSVC_CUDA_ARCHITECTURE_ID ${MSVC_CUDA_ARCHITECTURE_ID})")
+endif()
+
+#if this compiler vendor is matches NVIDIA we can determine
+#what the host compiler is. This only needs to be done if the CMAKE_CUDA_HOST_COMPILER
+#has NOT been explicitly set
+#
+#Find the line from compiler ID that contains a.out ( or last line )
+#We also need to find the implicit link lines. Which can be done by replacing
+#the compiler with cuda-fake-ld  and pass too CMAKE_PARSE_IMPLICIT_LINK_INFO
+if(CMAKE_CUDA_COMPILER_ID STREQUAL NVIDIA)
+  set(_nvcc_log "")
+  string(REPLACE "\r" "" _nvcc_output_orig "${CMAKE_CUDA_COMPILER_PRODUCED_OUTPUT}")
+  if(_nvcc_output_orig MATCHES "#\\\$ +LIBRARIES= *([^\n]*)\n")
+    set(_nvcc_libraries "${CMAKE_MATCH_1}")
+    string(APPEND _nvcc_log "  found 'LIBRARIES=' string: [${_nvcc_libraries}]\n")
+  else()
+    set(_nvcc_libraries "")
+    string(REPLACE "\n" "\n    " _nvcc_output_log "\n${_nvcc_output_orig}")
+    string(APPEND _nvcc_log "  no 'LIBRARIES=' string found in nvcc output:${_nvcc_output_log}\n")
+  endif()
+
+  set(_nvcc_link_line "")
+  if(_nvcc_libraries)
+    # Remove variable assignments.
+    string(REGEX REPLACE "#\\\$ *[^= ]+=[^\n]*\n" "" _nvcc_output "${_nvcc_output_orig}")
+    # Split lines.
+    string(REGEX REPLACE "\n+(#\\\$ )?" ";" _nvcc_output "${_nvcc_output}")
+    foreach(line IN LISTS _nvcc_output)
+      set(_nvcc_output_line "${line}")
+      string(APPEND _nvcc_log "  considering line: [${_nvcc_output_line}]\n")
+      if("${_nvcc_output_line}" MATCHES "^ *nvlink")
+        string(APPEND _nvcc_log "    ignoring nvlink line\n")
+      elseif(_nvcc_libraries)
+        if("${_nvcc_output_line}" MATCHES "(@\"?tmp/a\\.exe\\.res\"?)")
+          set(_nvcc_link_res_arg "${CMAKE_MATCH_1}")
+          set(_nvcc_link_res "${CMAKE_PLATFORM_INFO_DIR}/CompilerIdCUDA/tmp/a.exe.res")
+          if(EXISTS "${_nvcc_link_res}")
+            file(READ "${_nvcc_link_res}" _nvcc_link_res_content)
+            string(REPLACE "${_nvcc_link_res_arg}" "${_nvcc_link_res_content}" _nvcc_output_line "${_nvcc_output_line}")
+          endif()
+        endif()
+        string(FIND "${_nvcc_output_line}" "${_nvcc_libraries}" _nvcc_libraries_pos)
+        if(NOT _nvcc_libraries_pos EQUAL -1)
+          set(_nvcc_link_line "${_nvcc_output_line}")
+          string(APPEND _nvcc_log "    extracted link line: [${_nvcc_link_line}]\n")
+        endif()
+      endif()
+    endforeach()
+  endif()
+
+  if(_nvcc_link_line)
+    if("x${CMAKE_CUDA_SIMULATE_ID}" STREQUAL "xMSVC")
+      set(CMAKE_CUDA_HOST_LINK_LAUNCHER "${CMAKE_LINKER}")
+    else()
+      #extract the compiler that is being used for linking
+      separate_arguments(_nvcc_link_line_args UNIX_COMMAND "${_nvcc_link_line}")
+      list(GET _nvcc_link_line_args 0 CMAKE_CUDA_HOST_LINK_LAUNCHER)
+    endif()
+
+    #prefix the line with cuda-fake-ld so that implicit link info believes it is
+    #a link line
+    set(_nvcc_link_line "cuda-fake-ld ${_nvcc_link_line}")
+    CMAKE_PARSE_IMPLICIT_LINK_INFO("${_nvcc_link_line}"
+                                   CMAKE_CUDA_HOST_IMPLICIT_LINK_LIBRARIES
+                                   CMAKE_CUDA_HOST_IMPLICIT_LINK_DIRECTORIES
+                                   CMAKE_CUDA_HOST_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES
+                                   log
+                                   "${CMAKE_CUDA_IMPLICIT_OBJECT_REGEX}")
+
+    file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
+      "Parsed CUDA nvcc implicit link information from above output:\n${_nvcc_log}\n${log}\n\n")
+  else()
+    file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+      "Failed to parsed CUDA nvcc implicit link information:\n${_nvcc_log}\n\n")
+    message(FATAL_ERROR "Failed to extract nvcc implicit link line.")
+  endif()
+
+  set(CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES )
+  if(_nvcc_output_orig MATCHES "#\\\$ +INCLUDES= *([^\n]*)\n")
+    set(_nvcc_includes "${CMAKE_MATCH_1}")
+    string(APPEND _nvcc_log "  found 'INCLUDES=' string: [${_nvcc_includes}]\n")
+  else()
+    set(_nvcc_includes "")
+    string(REPLACE "\n" "\n    " _nvcc_output_log "\n${_nvcc_output_orig}")
+    string(APPEND _nvcc_log "  no 'INCLUDES=' string found in nvcc output:${_nvcc_output_log}\n")
+  endif()
+  if(_nvcc_includes)
+    # across all operating system each include directory is prefixed with -I
+    separate_arguments(_nvcc_output UNIX_COMMAND "${_nvcc_includes}")
+    foreach(line IN LISTS _nvcc_output)
+      string(REGEX REPLACE "^-I" "" line "${line}")
+      get_filename_component(line "${line}" ABSOLUTE)
+      list(APPEND CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES "${line}")
+    endforeach()
+
+    file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
+      "Parsed CUDA nvcc include information from above output:\n${_nvcc_log}\n${log}\n\n")
+  else()
+    file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
+      "Failed to detect CUDA nvcc include information:\n${_nvcc_log}\n\n")
+  endif()
+
+
+endif()
+
+# configure all variables set in this file
+configure_file(${CMAKE_ROOT}/Modules/CMakeCUDACompiler.cmake.in
+  ${CMAKE_PLATFORM_INFO_DIR}/CMakeCUDACompiler.cmake
+  @ONLY
+  )
+
+set(CMAKE_CUDA_COMPILER_ENV_VAR "CUDACXX")
+set(CMAKE_CUDA_HOST_COMPILER_ENV_VAR "CUDAHOSTCXX")
diff --git a/Modules/CMakeDetermineCompileFeatures.cmake b/Modules/CMakeDetermineCompileFeatures.cmake
index 5ca72cc..3ed92be 100644
--- a/Modules/CMakeDetermineCompileFeatures.cmake
+++ b/Modules/CMakeDetermineCompileFeatures.cmake
@@ -48,6 +48,7 @@ function(cmake_determine_compile_features lang)
     set(CMAKE_CXX98_COMPILE_FEATURES)
     set(CMAKE_CXX11_COMPILE_FEATURES)
     set(CMAKE_CXX14_COMPILE_FEATURES)
+    set(CMAKE_CXX17_COMPILE_FEATURES)
 
     include("${CMAKE_ROOT}/Modules/Internal/FeatureTesting.cmake")
 
@@ -58,6 +59,9 @@ function(cmake_determine_compile_features lang)
       return()
     endif()
 
+    if (CMAKE_CXX14_COMPILE_FEATURES AND CMAKE_CXX17_COMPILE_FEATURES)
+      list(REMOVE_ITEM CMAKE_CXX17_COMPILE_FEATURES ${CMAKE_CXX14_COMPILE_FEATURES})
+    endif()
     if (CMAKE_CXX11_COMPILE_FEATURES AND CMAKE_CXX14_COMPILE_FEATURES)
       list(REMOVE_ITEM CMAKE_CXX14_COMPILE_FEATURES ${CMAKE_CXX11_COMPILE_FEATURES})
     endif()
@@ -70,6 +74,7 @@ function(cmake_determine_compile_features lang)
         ${CMAKE_CXX98_COMPILE_FEATURES}
         ${CMAKE_CXX11_COMPILE_FEATURES}
         ${CMAKE_CXX14_COMPILE_FEATURES}
+        ${CMAKE_CXX17_COMPILE_FEATURES}
       )
     endif()
 
@@ -77,6 +82,7 @@ function(cmake_determine_compile_features lang)
     set(CMAKE_CXX98_COMPILE_FEATURES ${CMAKE_CXX98_COMPILE_FEATURES} PARENT_SCOPE)
     set(CMAKE_CXX11_COMPILE_FEATURES ${CMAKE_CXX11_COMPILE_FEATURES} PARENT_SCOPE)
     set(CMAKE_CXX14_COMPILE_FEATURES ${CMAKE_CXX14_COMPILE_FEATURES} PARENT_SCOPE)
+    set(CMAKE_CXX17_COMPILE_FEATURES ${CMAKE_CXX17_COMPILE_FEATURES} PARENT_SCOPE)
 
     message(STATUS "Detecting ${lang} compile features - done")
   endif()
diff --git a/Modules/CMakeDetermineCompilerId.cmake b/Modules/CMakeDetermineCompilerId.cmake
index 145efc6..c41a986 100644
--- a/Modules/CMakeDetermineCompilerId.cmake
+++ b/Modules/CMakeDetermineCompilerId.cmake
@@ -101,6 +101,8 @@ function(CMAKE_DETERMINE_COMPILER_ID lang flagvar src)
   set(CMAKE_${lang}_SIMULATE_ID "${CMAKE_${lang}_SIMULATE_ID}" PARENT_SCOPE)
   set(CMAKE_${lang}_SIMULATE_VERSION "${CMAKE_${lang}_SIMULATE_VERSION}" PARENT_SCOPE)
   set(CMAKE_${lang}_STANDARD_COMPUTED_DEFAULT "${CMAKE_${lang}_STANDARD_COMPUTED_DEFAULT}" PARENT_SCOPE)
+  set(CMAKE_${lang}_COMPILER_PRODUCED_OUTPUT "${COMPILER_${lang}_PRODUCED_OUTPUT}" PARENT_SCOPE)
+  set(CMAKE_${lang}_COMPILER_PRODUCED_FILES "${COMPILER_${lang}_PRODUCED_FILES}" PARENT_SCOPE)
 endfunction()
 
 include(CMakeCompilerIdDetection)
@@ -129,13 +131,14 @@ function(CMAKE_DETERMINE_COMPILER_ID_BUILD lang testflags src)
   # Create a clean working directory.
   file(REMOVE_RECURSE ${CMAKE_${lang}_COMPILER_ID_DIR})
   file(MAKE_DIRECTORY ${CMAKE_${lang}_COMPILER_ID_DIR})
+  file(MAKE_DIRECTORY ${CMAKE_${lang}_COMPILER_ID_DIR}/tmp)
   CMAKE_DETERMINE_COMPILER_ID_WRITE("${lang}" "${src}")
 
   # Construct a description of this test case.
   set(COMPILER_DESCRIPTION
     "Compiler: ${CMAKE_${lang}_COMPILER} ${CMAKE_${lang}_COMPILER_ID_ARG1}
 Build flags: ${CMAKE_${lang}_COMPILER_ID_FLAGS_LIST}
-Id flags: ${testflags}
+Id flags: ${testflags} ${CMAKE_${lang}_COMPILER_ID_FLAGS_ALWAYS}
 ")
 
   # Compile the compiler identification source.
@@ -162,6 +165,10 @@ Id flags: ${testflags}
       set(v Intel)
       set(ext vfproj)
       set(id_cl ifort.exe)
+    elseif(lang STREQUAL CSharp)
+      set(v 10)
+      set(ext csproj)
+      set(id_cl csc.exe)
     elseif(NOT "${vs_version}" VERSION_LESS 10)
       set(v 10)
       set(ext vcxproj)
@@ -182,6 +189,11 @@ Id flags: ${testflags}
     else()
       set(id_toolset "")
     endif()
+    if(CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE)
+      set(id_PreferredToolArchitecture "<PreferredToolArchitecture>${CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE}</PreferredToolArchitecture>")
+    else()
+      set(id_PreferredToolArchitecture "")
+    endif()
     if(CMAKE_SYSTEM_NAME STREQUAL "WindowsPhone")
       set(id_system "<ApplicationType>Windows Phone</ApplicationType>")
     elseif(CMAKE_SYSTEM_NAME STREQUAL "WindowsStore")
@@ -257,7 +269,13 @@ Id flags: ${testflags}
       set(id_toolset "")
     endif()
     if("${lang}" STREQUAL "Swift")
-      set(id_lang_version "SWIFT_VERSION = 2.3;")
+      if(CMAKE_Swift_LANGUAGE_VERSION)
+        set(id_lang_version "SWIFT_VERSION = ${CMAKE_Swift_LANGUAGE_VERSION};")
+      elseif(XCODE_VERSION VERSION_GREATER_EQUAL 8.3)
+        set(id_lang_version "SWIFT_VERSION = 3.0;")
+      else()
+        set(id_lang_version "SWIFT_VERSION = 2.3;")
+      endif()
     else()
       set(id_lang_version "")
     endif()
@@ -317,6 +335,7 @@ Id flags: ${testflags}
               ${CMAKE_${lang}_COMPILER_ID_ARG1}
               ${CMAKE_${lang}_COMPILER_ID_FLAGS_LIST}
               ${testflags}
+              ${CMAKE_${lang}_COMPILER_ID_FLAGS_ALWAYS}
               "${src}"
       WORKING_DIRECTORY ${CMAKE_${lang}_COMPILER_ID_DIR}
       OUTPUT_VARIABLE CMAKE_${lang}_COMPILER_ID_OUTPUT
@@ -395,6 +414,7 @@ ${CMAKE_${lang}_COMPILER_ID_OUTPUT}
   # Return the files produced by the compilation.
   set(COMPILER_${lang}_PRODUCED_FILES "${COMPILER_${lang}_PRODUCED_FILES}" PARENT_SCOPE)
   set(COMPILER_${lang}_PRODUCED_OUTPUT "${COMPILER_${lang}_PRODUCED_OUTPUT}" PARENT_SCOPE)
+
 endfunction()
 
 #-----------------------------------------------------------------------------
@@ -438,8 +458,12 @@ function(CMAKE_DETERMINE_COMPILER_ID_CHECK lang file)
     set(SIMULATE_ID)
     set(SIMULATE_VERSION)
     file(STRINGS ${file}
-      CMAKE_${lang}_COMPILER_ID_STRINGS LIMIT_COUNT 38 REGEX "INFO:[A-Za-z0-9_]+\\[[^]]*\\]")
+      CMAKE_${lang}_COMPILER_ID_STRINGS LIMIT_COUNT 38
+      ${CMAKE_${lang}_COMPILER_ID_STRINGS_PARAMETERS}
+      REGEX "INFO:[A-Za-z0-9_]+\\[[^]]*\\]")
     set(COMPILER_ID_TWICE)
+    # In C# binaries, some strings are found more than once.
+    list(REMOVE_DUPLICATES CMAKE_${lang}_COMPILER_ID_STRINGS)
     foreach(info ${CMAKE_${lang}_COMPILER_ID_STRINGS})
       if("${info}" MATCHES "INFO:compiler\\[([^]\"]*)\\]")
         if(COMPILER_ID)
diff --git a/Modules/CMakeExpandImportedTargets.cmake b/Modules/CMakeExpandImportedTargets.cmake
index add0c6d..ad065f0 100644
--- a/Modules/CMakeExpandImportedTargets.cmake
+++ b/Modules/CMakeExpandImportedTargets.cmake
@@ -37,9 +37,6 @@
 #       LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}
 #       CONFIGURATION "${CMAKE_TRY_COMPILE_CONFIGURATION}" )
 
-
-include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake)
-
 function(CMAKE_EXPAND_IMPORTED_TARGETS _RESULT )
 
    set(options )
diff --git a/Modules/CMakeFindBinUtils.cmake b/Modules/CMakeFindBinUtils.cmake
index 75a031e..4c0486e 100644
--- a/Modules/CMakeFindBinUtils.cmake
+++ b/Modules/CMakeFindBinUtils.cmake
@@ -25,6 +25,7 @@ if("x${CMAKE_C_SIMULATE_ID}" STREQUAL "xMSVC"
    OR "x${CMAKE_Fortran_SIMULATE_ID}" STREQUAL "xMSVC"
    OR "x${CMAKE_C_COMPILER_ID}" STREQUAL "xMSVC"
    OR "x${CMAKE_CXX_COMPILER_ID}" STREQUAL "xMSVC"
+   OR "x${CMAKE_CUDA_SIMULATE_ID}" STREQUAL "xMSVC"
    OR (CMAKE_GENERATOR MATCHES "Visual Studio"
        AND NOT CMAKE_VS_PLATFORM_NAME STREQUAL "Tegra-Android"))
 
diff --git a/Modules/CMakeGraphVizOptions.cmake b/Modules/CMakeGraphVizOptions.cmake
index e7c4de6..420e3a9 100644
--- a/Modules/CMakeGraphVizOptions.cmake
+++ b/Modules/CMakeGraphVizOptions.cmake
@@ -13,8 +13,8 @@
 # CMake
 # can generate graphviz files, showing the dependencies between the
 # targets in a project and also external libraries which are linked
-# against.  When CMake is run with the --graphviz=foo option, it will
-# produce
+# against.  When CMake is run with the --graphviz=foo.dot option, it will
+# produce:
 #
 # * a foo.dot file showing all dependencies in the project
 # * a foo.dot.<target> file for each target, file showing on which other targets the respective target depends
@@ -29,11 +29,18 @@
 #
 # .. variable:: GRAPHVIZ_GRAPH_TYPE
 #
-#  The graph type
+#  The graph type.
 #
 #  * Mandatory : NO
 #  * Default   : "digraph"
 #
+#  Valid graph types are:
+#
+#  * "graph" : Nodes are joined with lines
+#  * "digraph" : Nodes are joined with arrows showing direction
+#  * "strict graph" : Like "graph" but max one line between each node
+#  * "strict digraph" : Like "graph" but max one line between each node in each direction
+#
 # .. variable:: GRAPHVIZ_GRAPH_NAME
 #
 #  The graph name.
diff --git a/Modules/CMakePackageConfigHelpers.cmake b/Modules/CMakePackageConfigHelpers.cmake
index 8415641..90c2a57 100644
--- a/Modules/CMakePackageConfigHelpers.cmake
+++ b/Modules/CMakePackageConfigHelpers.cmake
@@ -40,7 +40,7 @@
 #    set(FOO_INCLUDE_DIR   "@CMAKE_INSTALL_FULL_INCLUDEDIR@" )
 #    set(FOO_DATA_DIR   "@CMAKE_INSTALL_PREFIX@/@RELATIVE_DATA_INSTALL_DIR@" )
 #    set(FOO_ICONS_DIR   "@CMAKE_INSTALL_PREFIX@/share/icons" )
-#    ...logic to determine installedPrefix from the own location...
+#    #...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
@@ -174,7 +174,7 @@
 #    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
@@ -190,7 +190,7 @@
 #
 # ``FooConfig.cmake.in``:
 #
-# .. code-block:: cmake
+# ::
 #
 #    set(FOO_VERSION x.y.z)
 #    ...
@@ -201,9 +201,6 @@
 #
 #    check_required_components(Foo)
 
-
-include(CMakeParseArguments)
-
 include(WriteBasicConfigVersionFile)
 
 macro(WRITE_BASIC_PACKAGE_VERSION_FILE)
diff --git a/Modules/CMakeParseImplicitLinkInfo.cmake b/Modules/CMakeParseImplicitLinkInfo.cmake
index 2031ba5..3273443 100644
--- a/Modules/CMakeParseImplicitLinkInfo.cmake
+++ b/Modules/CMakeParseImplicitLinkInfo.cmake
@@ -45,15 +45,35 @@ function(CMAKE_PARSE_IMPLICIT_LINK_INFO text lib_var dir_var fwk_var log_var obj
       endif()
       list(GET args 0 cmd)
     endif()
+    set(is_msvc 0)
     if("${cmd}" MATCHES "${linker_regex}")
       string(APPEND log "  link line: [${line}]\n")
       string(REGEX REPLACE ";-([LYz]);" ";-\\1" args "${args}")
+      set(skip_value_of "")
       foreach(arg IN LISTS args)
-        if("${arg}" MATCHES "^-L(.:)?[/\\]")
+        if(skip_value_of)
+          string(APPEND log "    arg [${arg}] ==> skip value of ${skip_value_of}\n")
+          set(skip_value_of "")
+        elseif("${arg}" MATCHES "^-L(.:)?[/\\]")
           # Unix search path.
           string(REGEX REPLACE "^-L" "" dir "${arg}")
           list(APPEND implicit_dirs_tmp ${dir})
           string(APPEND log "    arg [${arg}] ==> dir [${dir}]\n")
+        elseif("${arg}" MATCHES "^[-/]LIBPATH:(.+)")
+          # MSVC search path.
+          set(dir "${CMAKE_MATCH_1}")
+          list(APPEND implicit_dirs_tmp ${dir})
+          string(APPEND log "    arg [${arg}] ==> dir [${dir}]\n")
+        elseif(is_msvc AND "${arg}" STREQUAL "-link")
+          string(APPEND log "    arg [${arg}] ==> ignore MSVC cl option\n")
+        elseif(is_msvc AND "${arg}" MATCHES "^(.*\\.[Ll][Ii][Bb])$")
+          set(lib "${CMAKE_MATCH_1}")
+          list(APPEND implicit_libs_tmp ${lib})
+          string(APPEND log "    arg [${arg}] ==> lib [${lib}]\n")
+        elseif("${arg}" STREQUAL "-lto_library")
+          # ld argument "-lto_library <path>"
+          set(skip_value_of "${arg}")
+          string(APPEND log "    arg [${arg}] ==> ignore, skip following value\n")
         elseif("${arg}" MATCHES "^-l([^:].*)$")
           # Unix library.
           set(lib "${CMAKE_MATCH_1}")
@@ -82,6 +102,9 @@ function(CMAKE_PARSE_IMPLICIT_LINK_INFO text lib_var dir_var fwk_var log_var obj
           # Link editor option.
           list(APPEND implicit_libs_tmp ${arg})
           string(APPEND log "    arg [${arg}] ==> opt [${arg}]\n")
+        elseif("${arg}" STREQUAL "cl.exe")
+          string(APPEND log "    arg [${arg}] ==> recognize MSVC cl\n")
+          set(is_msvc 1)
         else()
           string(APPEND log "    arg [${arg}] ==> ignore\n")
         endif()
diff --git a/Modules/CMakePrintHelpers.cmake b/Modules/CMakePrintHelpers.cmake
index bf98a42..21c333e 100644
--- a/Modules/CMakePrintHelpers.cmake
+++ b/Modules/CMakePrintHelpers.cmake
@@ -39,8 +39,6 @@
 #
 #   -- CMAKE_C_COMPILER="/usr/bin/gcc" ; CMAKE_MAJOR_VERSION="2" ; DOES_NOT_EXIST=""
 
-include(CMakeParseArguments)
-
 function(CMAKE_PRINT_VARIABLES)
    set(msg "")
    foreach(var ${ARGN})
diff --git a/Modules/CMakeRCInformation.cmake b/Modules/CMakeRCInformation.cmake
index 10f2cfb..a340288 100644
--- a/Modules/CMakeRCInformation.cmake
+++ b/Modules/CMakeRCInformation.cmake
@@ -17,11 +17,26 @@ set(CMAKE_SYSTEM_AND_RC_COMPILER_INFO_FILE
   ${CMAKE_ROOT}/Modules/Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME}.cmake)
 include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME} OPTIONAL)
 
-string(STRIP "$ENV{RCFLAGS} ${CMAKE_RC_FLAGS_INIT}" CMAKE_RC_FLAGS_INIT)
+set(CMAKE_RC_FLAGS_INIT "$ENV{RCFLAGS} ${CMAKE_RC_FLAGS_INIT}")
+
+foreach(c "" _DEBUG _RELEASE _MINSIZEREL _RELWITHDEBINFO)
+  string(STRIP "${CMAKE_RC_FLAGS${c}_INIT}" CMAKE_RC_FLAGS${c}_INIT)
+endforeach()
 
 set (CMAKE_RC_FLAGS "${CMAKE_RC_FLAGS_INIT}" CACHE STRING
      "Flags for Windows Resource Compiler.")
 
+if(NOT CMAKE_NOT_USING_CONFIG_FLAGS)
+  set (CMAKE_RC_FLAGS_DEBUG "${CMAKE_RC_FLAGS_DEBUG_INIT}" CACHE STRING
+    "Flags for Windows Resource Compiler during debug builds.")
+  set (CMAKE_RC_FLAGS_MINSIZEREL "${CMAKE_RC_FLAGS_MINSIZEREL_INIT}" CACHE STRING
+    "Flags for Windows Resource Compiler during release builds for minimum size.")
+  set (CMAKE_RC_FLAGS_RELEASE "${CMAKE_RC_FLAGS_RELEASE_INIT}" CACHE STRING
+    "Flags for Windows Resource Compiler during release builds.")
+  set (CMAKE_RC_FLAGS_RELWITHDEBINFO "${CMAKE_RC_FLAGS_RELWITHDEBINFO_INIT}" CACHE STRING
+    "Flags for Windows Resource Compiler during release builds with debug info.")
+endif()
+
 # These are the only types of flags that should be passed to the rc
 # command, if COMPILE_FLAGS is used on a target this will be used
 # to filter out any other flags
@@ -38,6 +53,10 @@ endif()
 
 mark_as_advanced(
 CMAKE_RC_FLAGS
+CMAKE_RC_FLAGS_DEBUG
+CMAKE_RC_FLAGS_MINSIZEREL
+CMAKE_RC_FLAGS_RELEASE
+CMAKE_RC_FLAGS_RELWITHDEBINFO
 )
 # set this variable so we can avoid loading this more than once.
 set(CMAKE_RC_INFORMATION_LOADED 1)
diff --git a/Modules/CMakeTestCSharpCompiler.cmake b/Modules/CMakeTestCSharpCompiler.cmake
new file mode 100644
index 0000000..1a8bf32
--- /dev/null
+++ b/Modules/CMakeTestCSharpCompiler.cmake
@@ -0,0 +1,64 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+if(CMAKE_CSharp_COMPILER_FORCED)
+  # The compiler configuration was forced by the user.
+  # Assume the user has configured all compiler information.
+  set(CMAKE_CSharp_COMPILER_WORKS TRUE)
+  return()
+endif()
+
+include(CMakeTestCompilerCommon)
+
+unset(CMAKE_CSharp_COMPILER_WORKS CACHE)
+
+set(test_compile_file "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/testCSharpCompiler.cs")
+
+# This file is used by EnableLanguage in cmGlobalGenerator to
+# determine that that selected C# compiler can actually compile
+# and link the most basic of programs. If not, a fatal error
+# is set and cmake stops processing commands and will not generate
+# any makefiles or projects.
+if(NOT CMAKE_CSharp_COMPILER_WORKS)
+  PrintTestCompilerStatus("C#" "${CMAKE_CSharp_COMPILER}")
+  file(WRITE "${test_compile_file}"
+    "namespace Test {"
+    "   public class CSharp {"
+    "       static void Main(string[] args) {}"
+    "   }"
+    "}"
+    )
+  try_compile(CMAKE_CSharp_COMPILER_WORKS ${CMAKE_BINARY_DIR} "${test_compile_file}"
+    OUTPUT_VARIABLE __CMAKE_CSharp_COMPILER_OUTPUT
+    )
+  # Move result from cache to normal variable.
+  set(CMAKE_CSharp_COMPILER_WORKS ${CMAKE_CSharp_COMPILER_WORKS})
+  unset(CMAKE_CSharp_COMPILER_WORKS CACHE)
+  set(CSharp_TEST_WAS_RUN 1)
+endif()
+
+if(NOT CMAKE_CSharp_COMPILER_WORKS)
+  PrintTestCompilerStatus("C#" "${CMAKE_CSharp_COMPILER} -- broken")
+  file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+    "Determining if the C# compiler works failed with "
+    "the following output:\n${__CMAKE_CSharp_COMPILER_OUTPUT}\n\n")
+  message(FATAL_ERROR "The C# compiler \"${CMAKE_CSharp_COMPILER}\" "
+    "is not able to compile a simple test program.\nIt fails "
+    "with the following output:\n ${__CMAKE_CSharp_COMPILER_OUTPUT}\n\n"
+    "CMake will not be able to correctly generate this project.")
+else()
+  if(CSharp_TEST_WAS_RUN)
+    PrintTestCompilerStatus("C#" "${CMAKE_CSharp_COMPILER} -- works")
+    file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
+      "Determining if the C# compiler works passed with "
+      "the following output:\n${__CMAKE_CSharp_COMPILER_OUTPUT}\n\n")
+  endif()
+
+  # Re-configure to save learned information.
+  configure_file(
+    ${CMAKE_ROOT}/Modules/CMakeCSharpCompiler.cmake.in
+    ${CMAKE_PLATFORM_INFO_DIR}/CMakeCSharpCompiler.cmake
+    @ONLY
+    )
+  include(${CMAKE_PLATFORM_INFO_DIR}/CMakeCSharpCompiler.cmake)
+endif()
diff --git a/Modules/CMakeTestCUDACompiler.cmake b/Modules/CMakeTestCUDACompiler.cmake
new file mode 100644
index 0000000..80113cb
--- /dev/null
+++ b/Modules/CMakeTestCUDACompiler.cmake
@@ -0,0 +1,76 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+if(CMAKE_CUDA_COMPILER_FORCED)
+  # The compiler configuration was forced by the user.
+  # Assume the user has configured all compiler information.
+  set(CMAKE_CUDA_COMPILER_WORKS TRUE)
+  return()
+endif()
+
+include(CMakeTestCompilerCommon)
+
+# Remove any cached result from an older CMake version.
+# We now store this in CMakeCUDACompiler.cmake.
+unset(CMAKE_CUDA_COMPILER_WORKS CACHE)
+
+# This file is used by EnableLanguage in cmGlobalGenerator to
+# determine that that selected cuda compiler can actually compile
+# and link the most basic of programs.   If not, a fatal error
+# is set and cmake stops processing commands and will not generate
+# any makefiles or projects.
+if(NOT CMAKE_CUDA_COMPILER_WORKS)
+  PrintTestCompilerStatus("CUDA" "")
+  file(WRITE ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/main.cu
+    "#ifndef __CUDACC__\n"
+    "# error \"The CMAKE_CUDA_COMPILER is set to an invalid CUDA compiler\"\n"
+    "#endif\n"
+    "int main(){return 0;}\n")
+
+  try_compile(CMAKE_CUDA_COMPILER_WORKS ${CMAKE_BINARY_DIR}
+    ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/main.cu
+    OUTPUT_VARIABLE __CMAKE_CUDA_COMPILER_OUTPUT)
+
+  # Move result from cache to normal variable.
+  set(CMAKE_CUDA_COMPILER_WORKS ${CMAKE_CUDA_COMPILER_WORKS})
+  unset(CMAKE_CUDA_COMPILER_WORKS CACHE)
+  set(CUDA_TEST_WAS_RUN 1)
+endif()
+
+if(NOT CMAKE_CUDA_COMPILER_WORKS)
+  PrintTestCompilerStatus("CUDA" " -- broken")
+  file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+    "Determining if the CUDA compiler works failed with "
+    "the following output:\n${__CMAKE_CUDA_COMPILER_OUTPUT}\n\n")
+  message(FATAL_ERROR "The CUDA compiler \"${CMAKE_CUDA_COMPILER}\" "
+    "is not able to compile a simple test program.\nIt fails "
+    "with the following output:\n ${__CMAKE_CUDA_COMPILER_OUTPUT}\n\n"
+    "CMake will not be able to correctly generate this project.")
+else()
+  if(CUDA_TEST_WAS_RUN)
+    PrintTestCompilerStatus("CUDA" " -- works")
+    file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
+      "Determining if the CUDA compiler works passed with "
+      "the following output:\n${__CMAKE_CUDA_COMPILER_OUTPUT}\n\n")
+  endif()
+
+  # Try to identify the ABI and configure it into CMakeCUDACompiler.cmake
+  include(${CMAKE_ROOT}/Modules/CMakeDetermineCompilerABI.cmake)
+  CMAKE_DETERMINE_COMPILER_ABI(CUDA ${CMAKE_ROOT}/Modules/CMakeCUDACompilerABI.cu)
+
+  if("x${CMAKE_CUDA_SIMULATE_ID}" STREQUAL "xMSVC")
+    set(CMAKE_CUDA_IMPLICIT_LINK_LIBRARIES "${CMAKE_CUDA_HOST_IMPLICIT_LINK_LIBRARIES}")
+    set(CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES "${CMAKE_CUDA_HOST_IMPLICIT_LINK_DIRECTORIES}")
+  endif()
+
+  # Re-configure to save learned information.
+  configure_file(
+    ${CMAKE_ROOT}/Modules/CMakeCUDACompiler.cmake.in
+    ${CMAKE_PLATFORM_INFO_DIR}/CMakeCUDACompiler.cmake
+    @ONLY
+    )
+  include(${CMAKE_PLATFORM_INFO_DIR}/CMakeCUDACompiler.cmake)
+endif()
+
+
+unset(__CMAKE_CUDA_COMPILER_OUTPUT)
diff --git a/Modules/CPack.STGZ_Header.sh.in b/Modules/CPack.STGZ_Header.sh.in
index dee576f..c615851 100755
--- a/Modules/CPack.STGZ_Header.sh.in
+++ b/Modules/CPack.STGZ_Header.sh.in
@@ -130,7 +130,10 @@ echo ""
 use_new_tail_syntax="-n"
 tail $use_new_tail_syntax +1 "$0" > /dev/null 2> /dev/null || use_new_tail_syntax=""
 
-tail $use_new_tail_syntax +###CPACK_HEADER_LENGTH### "$0" | gunzip | (cd "${toplevel}" && tar xf -) || cpack_echo_exit "Problem unpacking the @CPACK_PACKAGE_FILE_NAME@"
+extractor="pax -r"
+command -v pax > /dev/null 2> /dev/null || extractor="tar xf -"
+
+tail $use_new_tail_syntax +###CPACK_HEADER_LENGTH### "$0" | gunzip | (cd "${toplevel}" && ${extractor}) || cpack_echo_exit "Problem unpacking the @CPACK_PACKAGE_FILE_NAME@"
 
 echo "Unpacking finished successfully"
 
diff --git a/Modules/CPack.cmake b/Modules/CPack.cmake
index cee1914..4e7546b 100644
--- a/Modules/CPack.cmake
+++ b/Modules/CPack.cmake
@@ -126,7 +126,9 @@
 #
 #     ${CPACK_PACKAGE_FILE_NAME}.${CPACK_PACKAGE_CHECKSUM}
 #
-#  Current supported alogorithms: MD5|SHA1|SHA224|SHA256|SHA384|SHA512.
+#  Supported algorithms are those listed by the
+#  :ref:`string(\<HASH\>) <Supported Hash Algorithms>`
+#  command.
 #
 # .. variable:: CPACK_PROJECT_CONFIG_FILE
 #
diff --git a/Modules/CPackDeb.cmake b/Modules/CPackDeb.cmake
index 909a12b..ddf8b23 100644
--- a/Modules/CPackDeb.cmake
+++ b/Modules/CPackDeb.cmake
@@ -587,12 +587,21 @@ function(cpack_deb_prepare_package_vars)
       file(GLOB_RECURSE FILE_PATHS_ LIST_DIRECTORIES false RELATIVE "${WDIR}" "${WDIR}/*")
     cmake_policy(POP)
 
+    find_program(FILE_EXECUTABLE file)
+    if(NOT FILE_EXECUTABLE)
+      message(FATAL_ERROR "CPackDeb: file utility is not available. CPACK_DEBIAN_PACKAGE_SHLIBDEPS and CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS options are not available.")
+    endif()
+
     # get file info so that we can determine if file is executable or not
     unset(CPACK_DEB_INSTALL_FILES)
     foreach(FILE_ IN LISTS FILE_PATHS_)
-      execute_process(COMMAND file "./${FILE_}"
+      execute_process(COMMAND env LC_ALL=C ${FILE_EXECUTABLE} "./${FILE_}"
         WORKING_DIRECTORY "${WDIR}"
+        RESULT_VARIABLE FILE_RESULT_
         OUTPUT_VARIABLE INSTALL_FILE_)
+      if(NOT FILE_RESULT_ EQUAL 0)
+        message (FATAL_ERROR "CPackDeb: execution of command: '${FILE_EXECUTABLE} ./${FILE_}' failed with exit code: ${FILE_RESULT_}")
+      endif()
       list(APPEND CPACK_DEB_INSTALL_FILES "${INSTALL_FILE_}")
     endforeach()
 
@@ -905,7 +914,7 @@ function(cpack_deb_prepare_package_vars)
         extract_so_info("${_FILE}" libname soversion)
         if(libname AND soversion)
           list(APPEND CPACK_DEBIAN_PACKAGE_SHLIBS_LIST
-               "${libname} ${soversion} ${CPACK_DEBIAN_PACKAGE_NAME} (${CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS_POLICY} ${CPACK_PACKAGE_VERSION})")
+               "${libname} ${soversion} ${CPACK_DEBIAN_PACKAGE_NAME} (${CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS_POLICY} ${CPACK_DEBIAN_PACKAGE_VERSION})")
         else()
           message(AUTHOR_WARNING "Shared library '${_FILE}' is missing soname or soversion. Library will not be added to DEBIAN/shlibs control file.")
         endif()
@@ -958,7 +967,7 @@ function(cpack_deb_prepare_package_vars)
       # Patch package file name to be in corrent debian format:
       # <foo>_<VersionNumber>-<DebianRevisionNumber>_<DebianArchitecture>.deb
       set(CPACK_OUTPUT_FILE_NAME
-        "${CPACK_DEBIAN_PACKAGE_NAME}_${CPACK_PACKAGE_VERSION}-${CPACK_DEBIAN_PACKAGE_RELEASE}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}.deb")
+        "${CPACK_DEBIAN_PACKAGE_NAME}_${CPACK_DEBIAN_PACKAGE_VERSION}-${CPACK_DEBIAN_PACKAGE_RELEASE}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}.deb")
     else()
       cmake_policy(PUSH)
         cmake_policy(SET CMP0010 NEW)
diff --git a/Modules/CPackIFW.cmake b/Modules/CPackIFW.cmake
index 08078cb..deb724c 100644
--- a/Modules/CPackIFW.cmake
+++ b/Modules/CPackIFW.cmake
@@ -76,6 +76,34 @@
 #
 #  Filename for a logo is used as QWizard::LogoPixmap.
 #
+# .. variable:: CPACK_IFW_PACKAGE_WATERMARK
+#
+#  Filename for a watermark is used as QWizard::WatermarkPixmap.
+#
+# .. variable:: CPACK_IFW_PACKAGE_BANNER
+#
+#  Filename for a banner is used as QWizard::BannerPixmap.
+#
+# .. variable:: CPACK_IFW_PACKAGE_BACKGROUND
+#
+#  Filename for an image used as QWizard::BackgroundPixmap (only used by MacStyle).
+#
+# .. variable:: CPACK_IFW_PACKAGE_WIZARD_STYLE
+#
+#  Wizard style to be used ("Modern", "Mac", "Aero" or "Classic").
+#
+# .. variable:: CPACK_IFW_PACKAGE_WIZARD_DEFAULT_WIDTH
+#
+#  Default width of the wizard in pixels. Setting a banner image will override this.
+#
+# .. variable:: CPACK_IFW_PACKAGE_WIZARD_DEFAULT_HEIGHT
+#
+#  Default height of the wizard in pixels. Setting a watermark image will override this.
+#
+# .. variable:: CPACK_IFW_PACKAGE_TITLE_COLOR
+#
+#  Color of the titles and subtitles (takes an HTML color code, such as "#88FF33").
+#
 # .. variable:: CPACK_IFW_PACKAGE_START_MENU_DIRECTORY
 #
 #  Name of the default program group for the product in the Windows Start menu.
@@ -198,14 +226,22 @@
 #
 #   ::
 #
-#     cpack_ifw_configure_component(<compname> [COMMON] [ESSENTIAL]
+#     cpack_ifw_configure_component(<compname> [COMMON] [ESSENTIAL] [VIRTUAL]
+#                         [FORCED_INSTALLATION] [REQUIRES_ADMIN_RIGHTS]
 #                         [NAME <name>]
+#                         [DISPLAY_NAME <display_name>]
+#                         [DESCRIPTION <description>]
+#                         [UPDATE_TEXT <update_text>]
 #                         [VERSION <version>]
+#                         [RELEASE_DATE <release_date>]
 #                         [SCRIPT <script>]
-#                         [PRIORITY <priority>]
-#                         [DEPENDS <com_id> ...]
+#                         [PRIORITY|SORTING_PRIORITY <sorting_priority>] # Note: PRIORITY is deprecated
+#                         [DEPENDS|DEPENDENCIES <com_id> ...]
+#                         [AUTO_DEPEND_ON <comp_id> ...]
 #                         [LICENSES <display_name> <file_path> ...]
-#                         [USER_INTERFACES <file_path> <file_path> ...])
+#                         [DEFAULT <value>]
+#                         [USER_INTERFACES <file_path> <file_path> ...]
+#                         [TRANSLATIONS <file_path> <file_path> ...])
 #
 #   This command should be called after :command:`cpack_add_component` command.
 #
@@ -217,30 +253,74 @@
 #     if set, then the package manager stays disabled until that
 #     component is updated.
 #
+#   ``VIRTUAL``
+#     if set, then the component will be hidden from the installer.
+#     It is a equivalent of the ``HIDDEN`` option from the
+#     :command:`cpack_add_component` command.
+#
+#   ``FORCED_INSTALLATION``
+#     if set, then the component must always be installed.
+#     It is a equivalent of the ``REQUARED`` option from the
+#     :command:`cpack_add_component` command.
+#
+#   ``REQUIRES_ADMIN_RIGHTS``
+#     set it if the component needs to be installed with elevated permissions.
+#
 #   ``NAME``
 #     is used to create domain-like identification for this component.
 #     By default used origin component name.
 #
+#   ``DISPLAY_NAME``
+#     set to rewrite original name configured by
+#     :command:`cpack_add_component` command.
+#
+#   ``DESCRIPTION``
+#     set to rewrite original description configured by
+#     :command:`cpack_add_component` command.
+#
+#   ``UPDATE_TEXT``
+#     will be added to the component description if this is an update to
+#     the component.
+#
 #   ``VERSION``
 #     is version of component.
 #     By default used :variable:`CPACK_PACKAGE_VERSION`.
 #
+#   ``RELEASE_DATE``
+#     keep empty to auto generate.
+#
 #   ``SCRIPT``
 #     is a relative or absolute path to operations script
 #     for this component.
 #
-#   ``PRIORITY``
+#   ``PRIORITY`` | ``SORTING_PRIORITY``
 #     is priority of the component in the tree.
+#     The ``PRIORITY`` option is deprecated and will be removed in a future
+#     version of CMake. Please use ``SORTING_PRIORITY`` option instead.
+#
+#   ``DEPENDS`` | ``DEPENDENCIES``
+#     list of dependency component or component group identifiers in
+#     QtIFW_ style.
 #
-#   ``DEPENDS``
-#     list of dependency component identifiers in QtIFW_ style.
+#   ``AUTO_DEPEND_ON``
+#     list of identifiers of component or component group in QtIFW_ style
+#     that this component has an automatic dependency on.
 #
 #   ``LICENSES``
 #     pair of <display_name> and <file_path> of license text for this
 #     component. You can specify more then one license.
 #
+#   ``DEFAULT``
+#     Possible values are: TRUE, FALSE, and SCRIPT.
+#     Set to FALSE to disable the component in the installer or to SCRIPT
+#     to resolved during runtime (don't forget add the file of the script
+#     as a value of the ``SCRIPT`` option).
+#
 #   ``USER_INTERFACES``
-#     a list of <file_path> representing pages to load
+#     is a list of <file_path> ('.ui' files) representing pages to load.
+#
+#   ``TRANSLATIONS``
+#     is a list of <file_path> ('.qm' files) representing translations to load.
 #
 #
 # .. command:: cpack_ifw_configure_component_group
@@ -249,38 +329,93 @@
 #
 #   ::
 #
-#     cpack_ifw_configure_component_group(<groupname>
+#     cpack_ifw_configure_component_group(<groupname> [VIRTUAL]
+#                         [FORCED_INSTALLATION] [REQUIRES_ADMIN_RIGHTS]
 #                         [NAME <name>]
+#                         [DISPLAY_NAME <display_name>]
+#                         [DESCRIPTION <description>]
+#                         [UPDATE_TEXT <update_text>]
 #                         [VERSION <version>]
+#                         [RELEASE_DATE <release_date>]
 #                         [SCRIPT <script>]
-#                         [PRIORITY <priority>]
+#                         [PRIORITY|SORTING_PRIORITY <sorting_priority>] # Note: PRIORITY is deprecated
+#                         [DEPENDS|DEPENDENCIES <com_id> ...]
+#                         [AUTO_DEPEND_ON <comp_id> ...]
 #                         [LICENSES <display_name> <file_path> ...]
-#                         [USER_INTERFACES <file_path> <file_path> ...])
+#                         [DEFAULT <value>]
+#                         [USER_INTERFACES <file_path> <file_path> ...]
+#                         [TRANSLATIONS <file_path> <file_path> ...])
 #
 #   This command should be called after :command:`cpack_add_component_group`
 #   command.
 #
+#   ``VIRTUAL``
+#     if set, then the group will be hidden from the installer.
+#     Note that setting this on a root component does not work.
+#
+#   ``FORCED_INSTALLATION``
+#     if set, then the group must always be installed.
+#
+#   ``REQUIRES_ADMIN_RIGHTS``
+#     set it if the component group needs to be installed with elevated
+#     permissions.
+#
 #   ``NAME``
 #     is used to create domain-like identification for this component group.
 #     By default used origin component group name.
 #
+#   ``DISPLAY_NAME``
+#     set to rewrite original name configured by
+#     :command:`cpack_add_component_group` command.
+#
+#   ``DESCRIPTION``
+#     set to rewrite original description configured by
+#     :command:`cpack_add_component_group` command.
+#
+#   ``UPDATE_TEXT``
+#     will be added to the component group description if this is an update to
+#     the component group.
+#
 #   ``VERSION``
 #     is version of component group.
 #     By default used :variable:`CPACK_PACKAGE_VERSION`.
 #
+#   ``RELEASE_DATE``
+#     keep empty to auto generate.
+#
 #   ``SCRIPT``
 #     is a relative or absolute path to operations script
 #     for this component group.
 #
-#   ``PRIORITY``
+#   ``PRIORITY`` | ``SORTING_PRIORITY``
 #     is priority of the component group in the tree.
+#     The ``PRIORITY`` option is deprecated and will be removed in a future
+#     version of CMake. Please use ``SORTING_PRIORITY`` option instead.
+#
+#   ``DEPENDS`` | ``DEPENDENCIES``
+#     list of dependency component or component group identifiers in
+#     QtIFW_ style.
+#
+#   ``AUTO_DEPEND_ON``
+#     list of identifiers of component or component group in QtIFW_ style
+#     that this component group has an automatic dependency on.
 #
 #   ``LICENSES``
 #     pair of <display_name> and <file_path> of license text for this
 #     component group. You can specify more then one license.
 #
+#   ``DEFAULT``
+#     Possible values are: TRUE, FALSE, and SCRIPT.
+#     Set to TRUE to preselect the group in the installer
+#     (this takes effect only on groups that have no visible child components)
+#     or to SCRIPT to resolved during runtime (don't forget add the file of
+#     the script as a value of the ``SCRIPT`` option).
+#
 #   ``USER_INTERFACES``
-#     a list of <file_path> representing pages to load
+#     is a list of <file_path> ('.ui' files) representing pages to load.
+#
+#   ``TRANSLATIONS``
+#     is a list of <file_path> ('.qm' files) representing translations to load.
 #
 #
 # .. command:: cpack_ifw_add_repository
@@ -568,10 +703,6 @@ 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})
@@ -625,14 +756,15 @@ macro(cpack_ifw_configure_component compname)
 
   string(TOUPPER ${compname} _CPACK_IFWCOMP_UNAME)
 
-  set(_IFW_OPT COMMON ESSENTIAL)
-  set(_IFW_ARGS NAME VERSION SCRIPT PRIORITY)
-  set(_IFW_MULTI_ARGS DEPENDS LICENSES USER_INTERFACES)
+  set(_IFW_OPT COMMON ESSENTIAL VIRTUAL FORCED_INSTALLATION REQUIRES_ADMIN_RIGHTS)
+  set(_IFW_ARGS NAME DISPLAY_NAME DESCRIPTION VERSION RELEASE_DATE SCRIPT PRIORITY SORTING_PRIORITY UPDATE_TEXT DEFAULT)
+  set(_IFW_MULTI_ARGS DEPENDS DEPENDENCIES AUTO_DEPEND_ON LICENSES USER_INTERFACES TRANSLATIONS)
   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)
   _cpack_ifw_resolve_file_list(CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME}_USER_INTERFACES)
+  _cpack_ifw_resolve_file_list(CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME}_TRANSLATIONS)
 
   set(_CPACK_IFWCOMP_STR "\n# Configuration for IFW component \"${compname}\"\n")
 
@@ -665,14 +797,15 @@ 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 USER_INTERFACES)
+  set(_IFW_OPT VIRTUAL FORCED_INSTALLATION REQUIRES_ADMIN_RIGHTS)
+  set(_IFW_ARGS NAME DISPLAY_NAME DESCRIPTION VERSION RELEASE_DATE SCRIPT PRIORITY SORTING_PRIORITY UPDATE_TEXT DEFAULT)
+  set(_IFW_MULTI_ARGS DEPENDS DEPENDENCIES AUTO_DEPEND_ON LICENSES USER_INTERFACES TRANSLATIONS)
   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)
   _cpack_ifw_resolve_file_list(CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME}_USER_INTERFACES)
+  _cpack_ifw_resolve_file_list(CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME}_TRANSLATIONS)
 
   set(_CPACK_IFWGRP_STR "\n# Configuration for IFW component group \"${grpname}\"\n")
 
diff --git a/Modules/CPackIFWConfigureFile.cmake b/Modules/CPackIFWConfigureFile.cmake
new file mode 100644
index 0000000..790574a
--- /dev/null
+++ b/Modules/CPackIFWConfigureFile.cmake
@@ -0,0 +1,65 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#.rst:
+# CPackIFWConfigureFile
+# ---------------------
+#
+# The module defines :command:`configure_file` similar command to
+# configure file templates prepared in QtIFW/SDK/Creator style.
+#
+#
+# Commands
+# ^^^^^^^^
+#
+# The module defines the following commands:
+#
+# .. command:: cpack_ifw_configure_file
+#
+#   Copy a file to another location and modify its contents.
+#
+#   ::
+#
+#     cpack_ifw_configure_file(<input> <output>)
+#
+#   Copies an ``<input>`` file to an ``<output>`` file and substitutes variable
+#   values referenced as ``%{VAR}`` or ``%VAR%`` in the input file content.
+#   Each variable reference will be replaced with the current value of the
+#   variable, or the empty string if the variable is not defined.
+#
+
+# NOTE: This file used to himself packaging via CPack IFW generator and
+# should be compatible with minimal CMake version defined in
+# ../CMakeLists.txt file.
+
+if(NOT DEFINED CPackIFWConfigureFile_CMake_INCLUDED)
+set(CPackIFWConfigureFile_CMake_INCLUDED 1)
+
+macro(cpack_ifw_configure_file INPUT OUTPUT)
+  file(READ "${INPUT}" _tmp)
+  foreach(_tmp_regex "%{([^%}]+)}" "%([^%]+)%")
+    string(REGEX MATCHALL "${_tmp_regex}" _tmp_vars "${_tmp}")
+    while(_tmp_vars)
+      foreach(_tmp_var ${_tmp_vars})
+        string(REGEX REPLACE "${_tmp_regex}" "\\1"
+          _tmp_var_name "${_tmp_var}")
+        if(DEFINED ${_tmp_var_name})
+          set(_tmp_var_value "${${_tmp_var_name}}")
+        elseif(NOT "$ENV{${_tmp_var_name}}" STREQUAL "")
+          set(_tmp_var_value "$ENV{${_tmp_var_name}}")
+        else()
+          set(_tmp_var_value "")
+        endif()
+        string(REPLACE "${_tmp_var}" "${_tmp_var_value}" _tmp "${_tmp}")
+      endforeach()
+      string(REGEX MATCHALL "${_tmp_regex}" _tmp_vars "${_tmp}")
+    endwhile()
+  endforeach()
+  if(IS_ABSOLUTE "${OUTPUT}")
+    file(WRITE "${OUTPUT}" "${_tmp}")
+  else()
+    file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT}" "${_tmp}")
+  endif()
+endmacro()
+
+endif() # NOT DEFINED CPackIFWConfigureFile_CMake_INCLUDED
diff --git a/Modules/CPackProductBuild.cmake b/Modules/CPackProductBuild.cmake
index ea2fa7c..d545d3e 100644
--- a/Modules/CPackProductBuild.cmake
+++ b/Modules/CPackProductBuild.cmake
@@ -20,9 +20,29 @@
 #  the automatically detected command (or specify its location if the
 #  auto-detection fails to find it.)
 #
+# .. variable:: CPACK_PRODUCTBUILD_IDENTITY_NAME
+#
+#  Adds a digital signature to the resulting package.
+#
+#
+# .. variable:: CPACK_PRODUCTBUILD_KEYCHAIN_PATH
+#
+#  Specify a specific keychain to search for the signing identity.
+#
+#
 # .. variable:: CPACK_COMMAND_PKGBUILD
 #
 #  Path to the pkgbuild(1) command used to generate an OS X component package
 #  on OS X.  This variable can be used to override the automatically detected
 #  command (or specify its location if the auto-detection fails to find it.)
 #
+#
+# .. variable:: CPACK_PKGBUILD_IDENTITY_NAME
+#
+#  Adds a digital signature to the resulting package.
+#
+#
+# .. variable:: CPACK_PKGBUILD_KEYCHAIN_PATH
+#
+#  Specify a specific keychain to search for the signing identity.
+#
diff --git a/Modules/CPackRPM.cmake b/Modules/CPackRPM.cmake
index 0640630..e905bc6 100644
--- a/Modules/CPackRPM.cmake
+++ b/Modules/CPackRPM.cmake
@@ -95,6 +95,17 @@
 #    and it is up to the packager to set the variables in a manner that will
 #    prevent such errors.
 #
+# .. variable:: CPACK_RPM_MAIN_COMPONENT
+#
+#  Main component that is packaged without component suffix.
+#
+#  * Mandatory : NO
+#  * Default   : -
+#
+#  This variable can be set to any component or group name so that component or
+#  group rpm package is generated without component suffix in filename and
+#  package name.
+#
 # .. variable:: CPACK_RPM_PACKAGE_VERSION
 #
 #  The RPM package version.
@@ -496,10 +507,12 @@
 #
 #  May be used to explicitly specify ``%(<directive>)`` file line
 #  in the spec file. Like ``%config(noreplace)`` or any other directive
-#  that be found in the ``%files`` section. Since CPackRPM is generating
-#  the list of files (and directories) the user specified files of
-#  the ``CPACK_RPM_<COMPONENT>_USER_FILELIST`` list will be removed from
-#  the generated list.
+#  that be found in the ``%files`` section. You can have multiple directives
+#  per line, as in ``%attr(600,root,root) %config(noreplace)``. Since
+#  CPackRPM is generating the list of files (and directories) the user
+#  specified files of the ``CPACK_RPM_<COMPONENT>_USER_FILELIST`` list will
+#  be removed from the generated list. If referring to directories do
+#  not add a trailing slash.
 #
 # .. variable:: CPACK_RPM_CHANGELOG_FILE
 #
@@ -708,14 +721,6 @@
 # Debuginfo packages contain debug symbols and sources for debugging packaged
 # binaries.
 #
-# .. note::
-#
-#  Currently multiple debuginfo packages are generated if component based
-#  packaging is used - one debuginfo package per component. This duplicates
-#  sources if multiple binaries are using them. This is a side effect of
-#  how CPackRPM currently generates component packages and will be addressed
-#  in later versions of the generator.
-#
 # Debuginfo RPM packaging has it's own set of variables:
 #
 # .. variable:: CPACK_RPM_DEBUGINFO_PACKAGE
@@ -792,6 +797,26 @@
 #  * Mandatory : NO
 #  * Default   : -
 #
+# .. variable:: CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE
+#
+#  Create a single debuginfo package even if components packaging is set.
+#
+#  * Mandatory : NO
+#  * Default   : OFF
+#
+#  When this variable is enabled it produces a single debuginfo package even if
+#  component packaging is enabled.
+#
+#  When using this feature in combination with components packaging and there is
+#  more than one component this variable requires :variable:`CPACK_RPM_MAIN_COMPONENT`
+#  to be set.
+#
+# .. note::
+#
+#  If none of the :variable:`CPACK_RPM_<component>_DEBUGINFO_PACKAGE` variables
+#  is set then :variable:`CPACK_RPM_DEBUGINFO_PACKAGE` is automatically set to
+#  ``ON`` when :variable:`CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE` is set.
+#
 # Packaging of sources (SRPM)
 # ^^^^^^^^^^^^^^^^^^^^^^^^^^^
 #
@@ -1439,8 +1464,8 @@ function(cpack_rpm_debugsymbol_check INSTALL_FILES WORKING_DIR)
           string(LENGTH "${CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX}/src_${index_}" debuginfo_dir_len)
           if(source_dir_len_ LESS debuginfo_dir_len)
             message(FATAL_ERROR "CPackRPM: source dir path '${source_dir_}' is"
-              " longer than debuginfo sources dir path '${CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX}/src_${index_}'!"
-              " Source dir path must be shorter than debuginfo sources dir path."
+              " shorter than debuginfo sources dir path '${CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX}/src_${index_}'!"
+              " Source dir path must be longer than debuginfo sources dir path."
               " Set CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX variable to a shorter value"
               " or make source dir path longer."
               " Required for debuginfo packaging. See documentation of"
@@ -1649,10 +1674,16 @@ function(cpack_rpm_generate_package)
   endif()
 
   if(CPACK_RPM_PACKAGE_COMPONENT)
-    string(APPEND CPACK_RPM_PACKAGE_NAME "-${CPACK_RPM_PACKAGE_COMPONENT}")
-    cpack_rpm_variable_fallback("CPACK_RPM_PACKAGE_NAME"
-      "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_PACKAGE_NAME"
-      "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_PACKAGE_NAME")
+    string(TOUPPER "${CPACK_RPM_MAIN_COMPONENT}"
+      CPACK_RPM_MAIN_COMPONENT_UPPER)
+
+    if(NOT CPACK_RPM_MAIN_COMPONENT_UPPER STREQUAL CPACK_RPM_PACKAGE_COMPONENT_UPPER)
+      string(APPEND CPACK_RPM_PACKAGE_NAME "-${CPACK_RPM_PACKAGE_COMPONENT}")
+
+      cpack_rpm_variable_fallback("CPACK_RPM_PACKAGE_NAME"
+        "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_PACKAGE_NAME"
+        "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_PACKAGE_NAME")
+    endif()
   endif()
 
   # CPACK_RPM_PACKAGE_VERSION (mandatory)
@@ -1807,6 +1838,12 @@ function(cpack_rpm_generate_package)
     set(CPACK_RPM_PACKAGE_RELOCATABLE FALSE) # disable relocatable option if building source RPM
   endif()
 
+  execute_process(
+    COMMAND "${RPMBUILD_EXECUTABLE}" --querytags
+    OUTPUT_VARIABLE RPMBUILD_TAG_LIST
+    OUTPUT_STRIP_TRAILING_WHITESPACE)
+  string(REPLACE "\n" ";" RPMBUILD_TAG_LIST "${RPMBUILD_TAG_LIST}")
+
   # Check if additional fields for RPM spec header are given
   # There may be some COMPONENT specific variables as well
   # If component specific var is not provided we use the global one
@@ -1815,6 +1852,7 @@ function(cpack_rpm_generate_package)
     if(CPACK_RPM_PACKAGE_DEBUG)
       message("CPackRPM:Debug: processing ${_RPM_SPEC_HEADER}")
     endif()
+
     if(CPACK_RPM_PACKAGE_COMPONENT)
       cpack_rpm_variable_fallback("CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}"
         "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_PACKAGE_${_RPM_SPEC_HEADER}"
@@ -1822,9 +1860,24 @@ function(cpack_rpm_generate_package)
     endif()
 
     if(DEFINED CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER})
+      cmake_policy(PUSH)
+        cmake_policy(SET CMP0057 NEW)
+        # Prefix can be replaced by Prefixes but the old version stil works so we'll ignore it for now
+        # Requires* is a special case because it gets transformed to Requires(pre/post/preun/postun)
+        # Auto* is a special case because the tags can not be queried by querytags rpmbuild flag
+        set(special_case_tags_ PREFIX REQUIRES_PRE REQUIRES_POST REQUIRES_PREUN REQUIRES_POSTUN AUTOPROV AUTOREQ AUTOREQPROV)
+        if(NOT _RPM_SPEC_HEADER IN_LIST RPMBUILD_TAG_LIST AND NOT _RPM_SPEC_HEADER IN_LIST special_case_tags_)
+          cmake_policy(POP)
+          message(AUTHOR_WARNING "CPackRPM:Warning: ${_RPM_SPEC_HEADER} not "
+              "supported in provided rpmbuild. Tag will not be used.")
+          continue()
+        endif()
+      cmake_policy(POP)
+
       if(CPACK_RPM_PACKAGE_DEBUG)
         message("CPackRPM:Debug: using CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}")
       endif()
+
       set(CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}_TMP ${CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}})
     endif()
 
@@ -1996,7 +2049,8 @@ function(cpack_rpm_generate_package)
     set(CPACK_RPM_USER_INSTALL_FILES "")
     foreach(F IN LISTS CPACK_RPM_USER_FILELIST_INTERNAL)
       string(REGEX REPLACE "%[A-Za-z]+(\\([^()]*\\))? " "" F_PATH ${F})
-      string(REGEX MATCH "%[A-Za-z]+(\\([^()]*\\))?" F_PREFIX ${F})
+      string(REGEX MATCH "(%[A-Za-z]+(\\([^()]*\\))? )*" F_PREFIX ${F})
+      string(STRIP ${F_PREFIX} F_PREFIX)
 
       if(CPACK_RPM_PACKAGE_DEBUG)
         message("CPackRPM:Debug: F_PREFIX=<${F_PREFIX}>, F_PATH=<${F_PATH}>")
@@ -2059,7 +2113,7 @@ function(cpack_rpm_generate_package)
     "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_DEBUGINFO_PACKAGE"
     "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_DEBUGINFO_PACKAGE"
     "CPACK_RPM_DEBUGINFO_PACKAGE")
-  if(CPACK_RPM_DEBUGINFO_PACKAGE)
+  if(CPACK_RPM_DEBUGINFO_PACKAGE OR (CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE AND NOT GENERATE_SPEC_PARTS))
     cpack_rpm_variable_fallback("CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX"
       "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_BUILD_SOURCE_DIRS_PREFIX"
       "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_BUILD_SOURCE_DIRS_PREFIX"
@@ -2067,9 +2121,87 @@ function(cpack_rpm_generate_package)
     if(NOT CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX)
       set(CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX "/usr/src/debug/${CPACK_PACKAGE_FILE_NAME}${CPACK_RPM_PACKAGE_COMPONENT_PART_PATH}")
     endif()
-    cpack_rpm_debugsymbol_check("${CPACK_RPM_INSTALL_FILES}" "${WDIR}")
 
-    set(TMP_RPM_DEBUGINFO "
+    if(CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE AND GENERATE_SPEC_PARTS)
+      file(WRITE "${CPACK_RPM_ROOTDIR}/SPECS/${CPACK_RPM_PACKAGE_COMPONENT}.files"
+        "${CPACK_RPM_INSTALL_FILES}")
+    else()
+      if(CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE AND CPACK_RPM_PACKAGE_COMPONENT)
+        # this part is only required by components packaging - with monolithic
+        # packages we can be certain that there are no other components present
+        # so CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE is a noop
+        if(CPACK_RPM_DEBUGINFO_PACKAGE)
+          # only add current package files to debuginfo list if debuginfo
+          # generation is enabled for current package
+          string(STRIP "${CPACK_RPM_INSTALL_FILES}" install_files_)
+          string(REPLACE "\n" ";" install_files_ "${install_files_}")
+          string(REPLACE "\"" "" install_files_ "${install_files_}")
+        else()
+          unset(install_files_)
+        endif()
+
+        file(GLOB files_ "${CPACK_RPM_DIRECTORY}/SPECS/*.files")
+
+        foreach(f_ IN LISTS files_)
+          file(READ "${f_}" tmp_)
+          string(APPEND install_files_ ";${tmp_}")
+        endforeach()
+
+        # if there were other components/groups so we need to move files from them
+        # to current component otherwise those files won't be found
+        file(GLOB components_ LIST_DIRECTORIES true RELATIVE
+          "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}"
+          "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}/*")
+        foreach(component_ IN LISTS components_)
+          string(TOUPPER "${component_}" component_dir_upper_)
+          if(component_dir_upper_ STREQUAL CPACK_RPM_PACKAGE_COMPONENT_UPPER)
+            # skip current component
+            continue()
+          endif()
+
+          cmake_policy(PUSH)
+            cmake_policy(SET CMP0009 NEW)
+            file(GLOB_RECURSE files_for_move_ LIST_DIRECTORIES false RELATIVE
+              "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}/${component_}"
+              "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}/${component_}/*")
+          cmake_policy(POP)
+
+          foreach(f_ IN LISTS files_for_move_)
+            get_filename_component(dir_path_ "${f_}" DIRECTORY)
+            set(src_file_
+              "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}/${component_}/${f_}")
+
+            # check that we are not overriding an existing file that doesn't
+            # match the file that we want to copy
+            if(EXISTS "${src_file_}" AND EXISTS "${WDIR}/${f_}")
+              execute_process(
+                  COMMAND ${CMAKE_COMMAND} -E compare_files "${src_file_}" "${WDIR}/${f_}"
+                  RESULT_VARIABLE res_
+                )
+              if(res_)
+                message(FATAL_ERROR "CPackRPM:Error: File on path '${WDIR}/${f_}'"
+                  " already exists but is a different than the one in component"
+                  " '${component_}'! Packages will not be generated.")
+              endif()
+            endif()
+
+            file(MAKE_DIRECTORY "${WDIR}/${dir_path_}")
+            file(RENAME "${src_file_}"
+              "${WDIR}/${f_}")
+          endforeach()
+        endforeach()
+
+        cpack_rpm_debugsymbol_check("${install_files_}" "${WDIR}")
+      else()
+        string(STRIP "${CPACK_RPM_INSTALL_FILES}" install_files_)
+        string(REPLACE "\n" ";" install_files_ "${install_files_}")
+        string(REPLACE "\"" "" install_files_ "${install_files_}")
+
+        cpack_rpm_debugsymbol_check("${install_files_}" "${WDIR}")
+      endif()
+
+      if(TMP_DEBUGINFO_ADDITIONAL_SOURCES)
+        set(TMP_RPM_DEBUGINFO "
 # Modified version of %%debug_package macro
 # defined in /usr/lib/rpm/macros as that one
 # can't handle injection of extra source files.
@@ -2088,6 +2220,15 @@ package or when debugging this package.
 ${TMP_DEBUGINFO_ADDITIONAL_SOURCES}
 %endif
 ")
+      elseif(CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE)
+        message(AUTHOR_WARNING "CPackRPM:Warning: debuginfo package was requested"
+          " but will not be generated as no source files were found!")
+      else()
+        message(AUTHOR_WARNING "CPackRPM:Warning: debuginfo package was requested"
+          " but will not be generated as no source files were found! Component: '"
+          "${CPACK_RPM_PACKAGE_COMPONENT}'.")
+      endif()
+    endif()
   endif()
 
   # Prepare install files
@@ -2164,12 +2305,25 @@ ${TMP_DEBUGINFO_ADDITIONAL_SOURCES}
       cmake_policy(POP)
     else()
       # old file name format for back compatibility
-      set(CPACK_RPM_FILE_NAME "${CPACK_OUTPUT_FILE_NAME}")
+      string(TOUPPER "${CPACK_RPM_MAIN_COMPONENT}"
+        CPACK_RPM_MAIN_COMPONENT_UPPER)
+
+      if(CPACK_RPM_MAIN_COMPONENT_UPPER STREQUAL CPACK_RPM_PACKAGE_COMPONENT_UPPER)
+        # this is the main component so ignore the component filename part
+        set(CPACK_RPM_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}.rpm")
+      else()
+        set(CPACK_RPM_FILE_NAME "${CPACK_OUTPUT_FILE_NAME}")
+      endif()
     endif()
     # else example:
     #set(CPACK_RPM_FILE_NAME "${CPACK_RPM_PACKAGE_NAME}-${CPACK_RPM_PACKAGE_VERSION}-${CPACK_RPM_PACKAGE_RELEASE}-${CPACK_RPM_PACKAGE_ARCHITECTURE}.rpm")
 
-    if(NOT CPACK_RPM_DEBUGINFO_PACKAGE)
+    if(CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE AND GENERATE_SPEC_PARTS)
+      string(TOLOWER "${CPACK_RPM_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}.*\\.rpm" expected_filename_)
+
+      file(WRITE "${CPACK_RPM_ROOTDIR}/SPECS/${CPACK_RPM_PACKAGE_COMPONENT}.rpm_name"
+        "${expected_filename_};${CPACK_RPM_FILE_NAME}")
+    elseif(NOT CPACK_RPM_DEBUGINFO_PACKAGE)
       set(FILE_NAME_DEFINE "%define _rpmfilename ${CPACK_RPM_FILE_NAME}")
     endif()
   endif()
@@ -2264,13 +2418,61 @@ Vendor:         \@CPACK_RPM_PACKAGE_VENDOR\@
 \@CPACK_RPM_SPEC_CHANGELOG\@
 "
     )
+
+  elseif(GENERATE_SPEC_PARTS) # binary rpm with single debuginfo package
+    file(WRITE ${CPACK_RPM_BINARY_SPECFILE}.in
+        "# -*- rpm-spec -*-
+%package -n \@CPACK_RPM_PACKAGE_NAME\@
+Summary:        \@CPACK_RPM_PACKAGE_SUMMARY\@
+Version:        \@CPACK_RPM_PACKAGE_VERSION\@
+Release:        \@CPACK_RPM_PACKAGE_RELEASE\@
+License:        \@CPACK_RPM_PACKAGE_LICENSE\@
+Group:          \@CPACK_RPM_PACKAGE_GROUP\@
+Vendor:         \@CPACK_RPM_PACKAGE_VENDOR\@
+
+\@TMP_RPM_URL\@
+\@TMP_RPM_REQUIRES\@
+\@TMP_RPM_REQUIRES_PRE\@
+\@TMP_RPM_REQUIRES_POST\@
+\@TMP_RPM_REQUIRES_PREUN\@
+\@TMP_RPM_REQUIRES_POSTUN\@
+\@TMP_RPM_PROVIDES\@
+\@TMP_RPM_OBSOLETES\@
+\@TMP_RPM_CONFLICTS\@
+\@TMP_RPM_SUGGESTS\@
+\@TMP_RPM_AUTOPROV\@
+\@TMP_RPM_AUTOREQ\@
+\@TMP_RPM_AUTOREQPROV\@
+\@TMP_RPM_BUILDARCH\@
+\@TMP_RPM_PREFIXES\@
+
+%description -n \@CPACK_RPM_PACKAGE_NAME\@
+\@CPACK_RPM_PACKAGE_DESCRIPTION\@
+
+%files -n \@CPACK_RPM_PACKAGE_NAME\@
+%defattr(\@TMP_DEFAULT_FILE_PERMISSIONS\@,\@TMP_DEFAULT_USER\@,\@TMP_DEFAULT_GROUP\@,\@TMP_DEFAULT_DIR_PERMISSIONS\@)
+\@CPACK_RPM_INSTALL_FILES\@
+\@CPACK_RPM_ABSOLUTE_INSTALL_FILES\@
+\@CPACK_RPM_USER_INSTALL_FILES\@
+"
+    )
+
   else()  # binary rpm
+    if(CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE)
+      # find generated spec file and take its name
+      file(GLOB spec_files_ "${CPACK_RPM_DIRECTORY}/SPECS/*.spec")
+
+      foreach(f_ IN LISTS spec_files_)
+        file(READ "${f_}" tmp_)
+        string(APPEND TMP_OTHER_COMPONENTS "\n${tmp_}\n")
+      endforeach()
+    endif()
 
     # We should generate a USER spec file template:
     #  - either because the user asked for it : CPACK_RPM_GENERATE_USER_BINARY_SPECFILE_TEMPLATE
     #  - or the user did not provide one : NOT CPACK_RPM_USER_BINARY_SPECFILE
+    set(RPMBUILD_FLAGS "-bb")
     if(CPACK_RPM_GENERATE_USER_BINARY_SPECFILE_TEMPLATE OR NOT CPACK_RPM_USER_BINARY_SPECFILE)
-      set(RPMBUILD_FLAGS "-bb")
 
       file(WRITE ${CPACK_RPM_BINARY_SPECFILE}.in
         "# -*- rpm-spec -*-
@@ -2292,6 +2494,7 @@ Vendor:         \@CPACK_RPM_PACKAGE_VENDOR\@
 \@TMP_RPM_PROVIDES\@
 \@TMP_RPM_OBSOLETES\@
 \@TMP_RPM_CONFLICTS\@
+\@TMP_RPM_SUGGESTS\@
 \@TMP_RPM_AUTOPROV\@
 \@TMP_RPM_AUTOREQ\@
 \@TMP_RPM_AUTOREQPROV\@
@@ -2350,6 +2553,8 @@ mv %_topdir/tmpBBroot $RPM_BUILD_ROOT
 
 %changelog
 \@CPACK_RPM_SPEC_CHANGELOG\@
+
+\@TMP_OTHER_COMPONENTS\@
 "
       )
     endif()
@@ -2376,60 +2581,90 @@ mv %_topdir/tmpBBroot $RPM_BUILD_ROOT
     configure_file(${CPACK_RPM_BINARY_SPECFILE}.in ${CPACK_RPM_BINARY_SPECFILE} @ONLY)
   endif()
 
-  if(RPMBUILD_EXECUTABLE)
-    # Now call rpmbuild using the SPECFILE
-    execute_process(
-      COMMAND "${RPMBUILD_EXECUTABLE}" ${RPMBUILD_FLAGS}
-              --define "_topdir ${CPACK_RPM_DIRECTORY}"
-              --buildroot "%_topdir/${CPACK_PACKAGE_FILE_NAME}${CPACK_RPM_PACKAGE_COMPONENT_PART_PATH}"
-              --target "${CPACK_RPM_PACKAGE_ARCHITECTURE}"
-              "${CPACK_RPM_BINARY_SPECFILE}"
-      WORKING_DIRECTORY "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}${CPACK_RPM_PACKAGE_COMPONENT_PART_PATH}"
-      RESULT_VARIABLE CPACK_RPMBUILD_EXEC_RESULT
-      ERROR_FILE "${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.err"
-      OUTPUT_FILE "${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.out")
-    if(CPACK_RPM_PACKAGE_DEBUG OR CPACK_RPMBUILD_EXEC_RESULT)
-      file(READ ${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.err RPMBUILDERR)
-      file(READ ${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.out RPMBUILDOUT)
-      message("CPackRPM:Debug: You may consult rpmbuild logs in: ")
-      message("CPackRPM:Debug:    - ${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.err")
-      message("CPackRPM:Debug: *** ${RPMBUILDERR} ***")
-      message("CPackRPM:Debug:    - ${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.out")
-      message("CPackRPM:Debug: *** ${RPMBUILDOUT} ***")
+  if(NOT GENERATE_SPEC_PARTS) # generate package
+    if(RPMBUILD_EXECUTABLE)
+      # Now call rpmbuild using the SPECFILE
+      execute_process(
+        COMMAND "${RPMBUILD_EXECUTABLE}" ${RPMBUILD_FLAGS}
+                --define "_topdir ${CPACK_RPM_DIRECTORY}"
+                --buildroot "%_topdir/${CPACK_PACKAGE_FILE_NAME}${CPACK_RPM_PACKAGE_COMPONENT_PART_PATH}"
+                --target "${CPACK_RPM_PACKAGE_ARCHITECTURE}"
+                "${CPACK_RPM_BINARY_SPECFILE}"
+        WORKING_DIRECTORY "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}${CPACK_RPM_PACKAGE_COMPONENT_PART_PATH}"
+        RESULT_VARIABLE CPACK_RPMBUILD_EXEC_RESULT
+        ERROR_FILE "${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.err"
+        OUTPUT_FILE "${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.out")
+      if(CPACK_RPM_PACKAGE_DEBUG OR CPACK_RPMBUILD_EXEC_RESULT)
+        file(READ ${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.err RPMBUILDERR)
+        file(READ ${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.out RPMBUILDOUT)
+        message("CPackRPM:Debug: You may consult rpmbuild logs in: ")
+        message("CPackRPM:Debug:    - ${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.err")
+        message("CPackRPM:Debug: *** ${RPMBUILDERR} ***")
+        message("CPackRPM:Debug:    - ${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.out")
+        message("CPackRPM:Debug: *** ${RPMBUILDOUT} ***")
+      endif()
+    else()
+      if(ALIEN_EXECUTABLE)
+        message(FATAL_ERROR "RPM packaging through alien not done (yet)")
+      endif()
     endif()
-  else()
-    if(ALIEN_EXECUTABLE)
-      message(FATAL_ERROR "RPM packaging through alien not done (yet)")
+
+    # find generated rpm files and take their names
+    cmake_policy(PUSH)
+      # Tell file(GLOB_RECURSE) not to follow directory symlinks
+      # even if the project does not set this policy to NEW.
+      cmake_policy(SET CMP0009 NEW)
+      file(GLOB_RECURSE GENERATED_FILES "${CPACK_RPM_DIRECTORY}/RPMS/*.rpm"
+        "${CPACK_RPM_DIRECTORY}/SRPMS/*.rpm")
+    cmake_policy(POP)
+
+    if(NOT GENERATED_FILES)
+      message(FATAL_ERROR "RPM package was not generated! ${CPACK_RPM_DIRECTORY}")
     endif()
-  endif()
 
-  # find generated rpm files and take their names
-  cmake_policy(PUSH)
-    # Tell file(GLOB_RECURSE) not to follow directory symlinks
-    # even if the project does not set this policy to NEW.
-    cmake_policy(SET CMP0009 NEW)
-    file(GLOB_RECURSE GENERATED_FILES "${CPACK_RPM_DIRECTORY}/RPMS/*.rpm"
-      "${CPACK_RPM_DIRECTORY}/SRPMS/*.rpm")
-  cmake_policy(POP)
+    unset(expected_filenames_)
+    unset(filenames_)
+    if(CPACK_RPM_DEBUGINFO_PACKAGE AND NOT CPACK_RPM_FILE_NAME STREQUAL "RPM-DEFAULT")
+      string(TOLOWER "${CPACK_RPM_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}.*\\.rpm" efn_)
+      list(APPEND expected_filenames_ "${efn_}")
+      list(APPEND filenames_ "${CPACK_RPM_FILE_NAME}")
+    endif()
 
-  if(NOT GENERATED_FILES)
-    message(FATAL_ERROR "RPM package was not generated! ${CPACK_RPM_DIRECTORY}")
-  endif()
+    # check if other files have to be renamed
+    file(GLOB rename_files_ "${CPACK_RPM_DIRECTORY}/SPECS/*.rpm_name")
+    if(rename_files_)
+      foreach(f_ IN LISTS rename_files_)
+        file(READ "${f_}" tmp_)
+        list(GET tmp_ 0 efn_)
+        list(APPEND expected_filenames_ "${efn_}")
+        list(GET tmp_ 1 fn_)
+        list(APPEND filenames_ "${fn_}")
+      endforeach()
+    endif()
 
-  if(CPACK_RPM_DEBUGINFO_PACKAGE AND NOT CPACK_RPM_FILE_NAME STREQUAL "RPM-DEFAULT")
-    string(TOLOWER "${CPACK_RPM_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}.*\\.rpm" EXPECTED_FILENAME)
+    if(expected_filenames_)
+      foreach(F IN LISTS GENERATED_FILES)
+        unset(matched_)
+        foreach(expected_ IN LISTS expected_filenames_)
+          if(F MATCHES ".*/${expected_}")
+            list(FIND expected_filenames_ "${expected_}" idx_)
+            list(GET filenames_ ${idx_} filename_)
+            get_filename_component(FILE_PATH "${F}" DIRECTORY)
+            file(RENAME "${F}" "${FILE_PATH}/${filename_}")
+            list(APPEND new_files_list_ "${FILE_PATH}/${filename_}")
+            set(matched_ "YES")
+
+            break()
+          endif()
+        endforeach()
 
-    foreach(F IN LISTS GENERATED_FILES)
-      if(F MATCHES ".*/${EXPECTED_FILENAME}")
-        get_filename_component(FILE_PATH "${F}" DIRECTORY)
-        file(RENAME "${F}" "${FILE_PATH}/${CPACK_RPM_FILE_NAME}")
-        list(APPEND new_files_list_ "${FILE_PATH}/${CPACK_RPM_FILE_NAME}")
-      else()
-        list(APPEND new_files_list_ "${F}")
-      endif()
-    endforeach()
+        if(NOT matched_)
+          list(APPEND new_files_list_ "${F}")
+        endif()
+      endforeach()
 
-    set(GENERATED_FILES "${new_files_list_}")
+      set(GENERATED_FILES "${new_files_list_}")
+    endif()
   endif()
 
   set(GEN_CPACK_OUTPUT_FILES "${GENERATED_FILES}" PARENT_SCOPE)
diff --git a/Modules/CSharpUtilities.cmake b/Modules/CSharpUtilities.cmake
new file mode 100644
index 0000000..e9e1510
--- /dev/null
+++ b/Modules/CSharpUtilities.cmake
@@ -0,0 +1,306 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+CSharpUtilities
+---------------
+
+Functions to make configuration of CSharp/.NET targets easier.
+
+A collection of CMake utility functions useful for dealing with CSharp
+targets for Visual Studio generators from version 2010 and later.
+
+The following functions are provided by this module:
+
+**Main functions**
+
+- :command:`csharp_set_windows_forms_properties`
+- :command:`csharp_set_designer_cs_properties`
+- :command:`csharp_set_xaml_cs_properties`
+
+**Helper functions**
+
+- :command:`csharp_get_filename_keys`
+- :command:`csharp_get_filename_key_base`
+- :command:`csharp_get_dependentupon_name`
+
+Main functions provided by the module
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. command:: csharp_set_windows_forms_properties
+
+  Sets source file properties for use of Windows Forms. Use this, if your CSharp
+  target uses Windows Forms::
+
+    csharp_set_windows_forms_properties([<file1> [<file2> [...]]])
+
+  ``<fileN>``
+    List of all source files which are relevant for setting the
+    :prop_sf:`VS_CSHARP_<tagname>` properties (including ``.cs``, ``.resx`` and
+    ``.Designer.cs`` extensions).
+
+  In the list of all given files for all files ending with ``.Designer.cs`` and
+  ``.resx`` is searched.  For every *designer* or *resource* file a file with the
+  same base name but only ``.cs`` as extension is searched.  If this is found, the
+  :prop_sf:`VS_CSHARP_<tagname>` properties are set as follows:
+
+  for the **.cs** file:
+   - VS_CSHARP_SubType "Form"
+
+  for the **.Designer.cs** file (if it exists):
+   - VS_CSHARP_DependentUpon <cs-filename>
+   - VS_CSHARP_DesignTime "" (delete tag if previously defined)
+   - VS_CSHARP_AutoGen ""(delete tag if previously defined)
+
+  for the **.resx** file (if it exists):
+   - VS_RESOURCE_GENERATOR "" (delete tag if previously defined)
+   - VS_CSHARP_DependentUpon <cs-filename>
+   - VS_CSHARP_SubType "Designer"
+
+.. command:: csharp_set_designer_cs_properties
+
+  Sets source file properties of ``.Designer.cs`` files depending on
+  sibling filenames. Use this, if your CSharp target does **not**
+  use Windows Forms (for Windows Forms use
+  :command:`csharp_set_designer_cs_properties` instead)::
+
+    csharp_set_designer_cs_properties([<file1> [<file2> [...]]])
+
+  ``<fileN>``
+    List of all source files which are relevant for setting the
+    :prop_sf:`VS_CSHARP_<tagname>` properties (including ``.cs``,
+    ``.resx``, ``.settings`` and ``.Designer.cs`` extensions).
+
+  In the list of all given files for all files ending with
+  ``.Designer.cs`` is searched. For every *designer* file all files
+  with the same base name but different extensions are searched. If
+  a match is found, the source file properties of the *designer* file
+  are set depending on the extension of the matched file:
+
+  if match is **.resx** file:
+   - VS_CSHARP_AutoGen "True"
+   - VS_CSHARP_DesignTime "True"
+   - VS_CSHARP_DependentUpon <resx-filename>
+
+  if match is **.cs** file:
+   - VS_CSHARP_DependentUpon <cs-filename>
+
+  if match is **.settings** file:
+   - VS_CSHARP_AutoGen "True"
+   - VS_CSHARP_DesignTimeSharedInput "True"
+   - VS_CSHARP_DependentUpon <settings-filename>
+
+.. note::
+
+    Because the source file properties of the ``.Designer.cs`` file are set according
+    to the found matches and every match sets the **VS_CSHARP_DependentUpon**
+    property, there should only be one match for each ``Designer.cs`` file.
+
+.. command:: csharp_set_xaml_cs_properties
+
+  Sets source file properties for use of Windows Presentation Foundation (WPF) and
+  XAML. Use this, if your CSharp target uses WPF/XAML::
+
+    csharp_set_xaml_cs_properties([<file1> [<file2> [...]]])
+
+  ``<fileN>``
+    List of all source files which are relevant for setting the
+    :prop_sf:`VS_CSHARP_<tagname>` properties (including ``.cs``,
+    ``.xaml``, and ``.xaml.cs`` extensions).
+
+  In the list of all given files for all files ending with
+  ``.xaml.cs`` is searched. For every *xaml-cs* file, a file
+  with the same base name but extension ``.xaml`` is searched.
+  If a match is found, the source file properties of the ``.xaml.cs``
+  file are set:
+
+   - VS_CSHARP_DependentUpon <xaml-filename>
+
+Helper functions which are used by the above ones
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. command:: csharp_get_filename_keys
+
+  Helper function which computes a list of key values to identify
+  source files independently of relative/absolute paths given in cmake
+  and eliminates case sensitivity::
+
+    csharp_get_filename_keys(OUT [<file1> [<file2> [...]]])
+
+  ``OUT``
+    Name of the variable in which the list of keys is stored
+
+  ``<fileN>``
+    filename(s) as given to to CSharp target using :command:`add_library`
+    or :command:`add_executable`
+
+  In some way the function applies a canonicalization to the source names.
+  This is necessary to find file matches if the files have been added to
+  the target with different directory prefixes:
+
+  .. code-block:: cmake
+
+    add_library(lib
+      myfile.cs
+      ${CMAKE_CURRENT_SOURCE_DIR}/myfile.Designer.cs)
+
+    set_source_files_properties(myfile.Designer.cs PROPERTIES
+      VS_CSHARP_DependentUpon myfile.cs)
+
+    # this will fail, because in cmake
+    #  - ${CMAKE_CURRENT_SOURCE_DIR}/myfile.Designer.cs
+    #  - myfile.Designer.cs
+    # are not the same source file. The source file property is not set.
+
+.. command:: csharp_get_filename_key_base
+
+  Returns the full filepath and name **without** extension of a key.
+  KEY is expected to be a key from csharp_get_filename_keys. In BASE
+  the value of KEY without the file extension is returned::
+
+    csharp_get_filename_key_base(BASE KEY)
+
+  ``BASE``
+    Name of the variable with the computed "base" of ``KEY``.
+
+  ``KEY``
+    The key of which the base will be computed. Expected to be a
+    upper case full filename.
+
+.. command:: csharp_get_dependentupon_name
+
+  Computes a string which can be used as value for the source file property
+  :prop_sf:`VS_CSHARP_<tagname>` with *target* being ``DependentUpon``::
+
+    csharp_get_dependentupon_name(NAME FILE)
+
+  ``NAME``
+    Name of the variable with the result value
+
+  ``FILE``
+    Filename to convert to ``<DependentUpon>`` value
+
+  Actually this is only the filename without any path given at the moment.
+
+#]=======================================================================]
+
+function(csharp_get_filename_keys OUT)
+  set(${OUT} "")
+  foreach(f ${ARGN})
+    get_filename_component(f ${f} REALPATH)
+    string(TOUPPER ${f} f)
+    list(APPEND ${OUT} ${f})
+  endforeach()
+  set(${OUT} "${${OUT}}" PARENT_SCOPE)
+endfunction()
+
+function(csharp_get_filename_key_base base key)
+  get_filename_component(dir ${key} DIRECTORY)
+  get_filename_component(fil ${key} NAME_WE)
+  set(${base} "${dir}/${fil}" PARENT_SCOPE)
+endfunction()
+
+function(csharp_get_dependentupon_name out in)
+  get_filename_component(${out} ${in} NAME)
+  set(${out} ${${out}} PARENT_SCOPE)
+endfunction()
+
+function(csharp_set_windows_forms_properties)
+  csharp_get_filename_keys(fileKeys ${ARGN})
+  foreach(key ${fileKeys})
+    get_filename_component(ext ${key} EXT)
+    if(${ext} STREQUAL ".DESIGNER.CS" OR
+       ${ext} STREQUAL ".RESX")
+      csharp_get_filename_key_base(NAME_BASE ${key})
+      list(FIND fileKeys "${NAME_BASE}.CS" FILE_INDEX)
+      if(NOT ${FILE_INDEX} EQUAL -1)
+        list(GET ARGN ${FILE_INDEX} FILE_NAME)
+        # set properties of main form file
+        set_source_files_properties("${FILE_NAME}"
+          PROPERTIES
+          VS_CSHARP_SubType "Form")
+        csharp_get_dependentupon_name(LINK "${FILE_NAME}")
+        # set properties of designer file (if found)
+        list(FIND fileKeys "${NAME_BASE}.DESIGNER.CS" FILE_INDEX)
+        if(NOT ${FILE_INDEX} EQUAL -1)
+          list(GET ARGN ${FILE_INDEX} FILE_NAME)
+          set_source_files_properties("${FILE_NAME}"
+            PROPERTIES
+            VS_CSHARP_DependentUpon "${LINK}"
+            VS_CSHARP_DesignTime ""
+            VS_CSHARP_AutoGen "")
+        endif()
+        # set properties of corresponding resource file (if found)
+        list(FIND fileKeys "${NAME_BASE}.RESX" FILE_INDEX)
+        if(NOT ${FILE_INDEX} EQUAL -1)
+          list(GET ARGN ${FILE_INDEX} FILE_NAME)
+          set_source_files_properties("${FILE_NAME}"
+            PROPERTIES
+            VS_RESOURCE_GENERATOR ""
+            VS_CSHARP_DependentUpon "${LINK}"
+            VS_CSHARP_SubType "Designer")
+        endif()
+      endif()
+    endif()
+  endforeach()
+endfunction()
+
+function(csharp_set_designer_cs_properties)
+  csharp_get_filename_keys(fileKeys ${ARGN})
+  set(INDEX -1)
+  foreach(key ${fileKeys})
+    math(EXPR INDEX "${INDEX}+1")
+    list(GET ARGN ${INDEX} source)
+    get_filename_component(ext ${key} EXT)
+    if(${ext} STREQUAL ".DESIGNER.CS")
+      csharp_get_filename_key_base(NAME_BASE ${key})
+      if("${NAME_BASE}.RESX" IN_LIST fileKeys)
+        list(FIND fileKeys "${NAME_BASE}.RESX" FILE_INDEX)
+        list(GET ARGN ${FILE_INDEX} FILE_NAME)
+        csharp_get_dependentupon_name(LINK "${FILE_NAME}")
+        set_source_files_properties("${source}"
+          PROPERTIES
+          VS_CSHARP_AutoGen "True"
+          VS_CSHARP_DesignTime "True"
+          VS_CSHARP_DependentUpon "${LINK}")
+      elseif("${NAME_BASE}.CS" IN_LIST fileKeys)
+        list(FIND fileKeys "${NAME_BASE}.CS" FILE_INDEX)
+        list(GET ARGN ${FILE_INDEX} FILE_NAME)
+        csharp_get_dependentupon_name(LINK "${FILE_NAME}")
+        set_source_files_properties("${source}"
+          PROPERTIES
+          VS_CSHARP_DependentUpon "${LINK}")
+      elseif("${NAME_BASE}.SETTINGS" IN_LIST fileKeys)
+        list(FIND fileKeys "${NAME_BASE}.SETTINGS" FILE_INDEX)
+        list(GET ARGN ${FILE_INDEX} FILE_NAME)
+        csharp_get_dependentupon_name(LINK "${FILE_NAME}")
+        set_source_files_properties("${source}"
+          PROPERTIES
+          VS_CSHARP_AutoGen "True"
+          VS_CSHARP_DesignTimeSharedInput "True"
+          VS_CSHARP_DependentUpon "${LINK}")
+      endif()
+    endif()
+  endforeach()
+endfunction()
+
+function(csharp_set_xaml_cs_properties)
+  csharp_get_filename_keys(fileKeys ${ARGN})
+  set(INDEX -1)
+  foreach(key ${fileKeys})
+    math(EXPR INDEX "${INDEX}+1")
+    list(GET ARGN ${INDEX} source)
+    get_filename_component(ext ${key} EXT)
+    if(${ext} STREQUAL ".XAML.CS")
+      csharp_get_filename_key_base(NAME_BASE ${key})
+      if("${NAME_BASE}.XAML" IN_LIST fileKeys)
+        list(FIND fileKeys "${NAME_BASE}.XAML" FILE_INDEX)
+        list(GET ARGN ${FILE_INDEX} FILE_NAME)
+        csharp_get_dependentupon_name(LINK "${FILE_NAME}")
+        set_source_files_properties("${source}"
+          PROPERTIES
+          VS_CSHARP_DependentUpon "${LINK}")
+      endif()
+    endif()
+  endforeach()
+endfunction()
diff --git a/Modules/CTestCoverageCollectGCOV.cmake b/Modules/CTestCoverageCollectGCOV.cmake
index 8451a6a..1203be4 100644
--- a/Modules/CTestCoverageCollectGCOV.cmake
+++ b/Modules/CTestCoverageCollectGCOV.cmake
@@ -65,7 +65,6 @@
 #     Suppress non-error messages that otherwise would have been
 #     printed out by this function.
 
-include(CMakeParseArguments)
 function(ctest_coverage_collect_gcov)
   set(options QUIET GLOB DELETE)
   set(oneValueArgs TARBALL SOURCE BUILD GCOV_COMMAND)
diff --git a/Modules/CTestUseLaunchers.cmake b/Modules/CTestUseLaunchers.cmake
index 1cf20eb..dc90513 100644
--- a/Modules/CTestUseLaunchers.cmake
+++ b/Modules/CTestUseLaunchers.cmake
@@ -24,7 +24,9 @@
 # include(CTestUseLaunchers), it will use the value of the ENV variable
 # to initialize a CTEST_USE_LAUNCHERS cache variable.  This cache
 # variable initialization only occurs if CTEST_USE_LAUNCHERS is not
-# already defined.
+# already defined. If CTEST_USE_LAUNCHERS is on in a ctest -S script
+# the ctest_configure command will add -DCTEST_USE_LAUNCHERS:BOOL=TRUE
+# to the cmake command used to configure the project.
 
 if(NOT DEFINED CTEST_USE_LAUNCHERS AND DEFINED ENV{CTEST_USE_LAUNCHERS_DEFAULT})
   set(CTEST_USE_LAUNCHERS "$ENV{CTEST_USE_LAUNCHERS_DEFAULT}"
diff --git a/Modules/CheckFunctionExists.c b/Modules/CheckFunctionExists.c
index 2304000..224e340 100644
--- a/Modules/CheckFunctionExists.c
+++ b/Modules/CheckFunctionExists.c
@@ -4,7 +4,7 @@
 extern "C"
 #endif
   char
-  CHECK_FUNCTION_EXISTS();
+  CHECK_FUNCTION_EXISTS(void);
 #ifdef __CLASSIC_C__
 int main()
 {
diff --git a/Modules/CheckFunctionExists.cmake b/Modules/CheckFunctionExists.cmake
index 5f049e7..ef08062 100644
--- a/Modules/CheckFunctionExists.cmake
+++ b/Modules/CheckFunctionExists.cmake
@@ -5,18 +5,16 @@
 # CheckFunctionExists
 # -------------------
 #
-# Check if a C function can be linked
+# Check if a C function can be linked::
 #
-# CHECK_FUNCTION_EXISTS(<function> <variable>)
+#   check_function_exists(<function> <variable>)
 #
-# Check that the <function> is provided by libraries on the system and
-# 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.
+# Check that the ``<function>`` is provided by libraries on the system and store
+# the result in a ``<variable>``. ``<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:
+# The following variables may be set before calling this macro to modify the
+# way the check is run:
 #
 # ::
 #
@@ -25,6 +23,20 @@
 #   CMAKE_REQUIRED_INCLUDES = list of include directories
 #   CMAKE_REQUIRED_LIBRARIES = list of libraries to link
 #   CMAKE_REQUIRED_QUIET = execute quietly without messages
+#
+# .. note::
+#
+#   Prefer using :Module:`CheckSymbolExists` instead of this module,
+#   for the following reasons:
+#
+#   * ``check_function_exists()`` can't detect functions that are inlined
+#     in headers or specified as a macro.
+#
+#   * ``check_function_exists()`` can't detect anything in the 32-bit
+#     versions of the Win32 API, because of a mismatch in calling conventions.
+#
+#   * ``check_function_exists()`` only verifies linking, it does not verify
+#     that the function is declared in system headers.
 
 macro(CHECK_FUNCTION_EXISTS FUNCTION VARIABLE)
   if(NOT DEFINED "${VARIABLE}" OR "x${${VARIABLE}}" STREQUAL "x${VARIABLE}")
diff --git a/Modules/Compiler/AppleClang-C.cmake b/Modules/Compiler/AppleClang-C.cmake
index 1cc72c0..f874e74 100644
--- a/Modules/Compiler/AppleClang-C.cmake
+++ b/Modules/Compiler/AppleClang-C.cmake
@@ -25,18 +25,16 @@ if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.0)
 endif()
 
 macro(cmake_record_c_compile_features)
-  macro(_get_appleclang_features std_version list)
-    record_compiler_features(C "${std_version}" ${list})
-  endmacro()
-
   set(_result 0)
   if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.0)
-    _get_appleclang_features(${CMAKE_C11_STANDARD_COMPILE_OPTION} CMAKE_C11_COMPILE_FEATURES)
     if (_result EQUAL 0)
-      _get_appleclang_features(${CMAKE_C99_STANDARD_COMPILE_OPTION} CMAKE_C99_COMPILE_FEATURES)
+      _record_compiler_features_c(11)
+    endif()
+    if (_result EQUAL 0)
+      _record_compiler_features_c(99)
     endif()
     if (_result EQUAL 0)
-      _get_appleclang_features(${CMAKE_C90_STANDARD_COMPILE_OPTION} CMAKE_C90_COMPILE_FEATURES)
+      _record_compiler_features_c(90)
     endif()
   endif()
 endmacro()
diff --git a/Modules/Compiler/AppleClang-CXX.cmake b/Modules/Compiler/AppleClang-CXX.cmake
index 95bc79a..ee900ae 100644
--- a/Modules/Compiler/AppleClang-CXX.cmake
+++ b/Modules/Compiler/AppleClang-CXX.cmake
@@ -22,6 +22,11 @@ elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.1)
   set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++1y")
 endif()
 
+if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 6.1)
+  set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "-std=c++1z")
+  set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "-std=gnu++1z")
+endif()
+
 if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.0)
   if (NOT CMAKE_CXX_COMPILER_FORCED)
     if (NOT CMAKE_CXX_STANDARD_COMPUTED_DEFAULT)
@@ -36,21 +41,19 @@ endif()
 
 
 macro(cmake_record_cxx_compile_features)
-  macro(_get_appleclang_features std_version list)
-    record_compiler_features(CXX "${std_version}" ${list})
-  endmacro()
-
   set(_result 0)
   if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.0)
-    set(_result 0)
-    if(CMAKE_CXX14_STANDARD_COMPILE_OPTION)
-      _get_appleclang_features(${CMAKE_CXX14_STANDARD_COMPILE_OPTION} CMAKE_CXX14_COMPILE_FEATURES)
+    if(_result EQUAL 0 AND CMAKE_CXX17_STANDARD_COMPILE_OPTION)
+      _record_compiler_features_cxx(17)
+    endif()
+    if(_result EQUAL 0 AND CMAKE_CXX14_STANDARD_COMPILE_OPTION)
+      _record_compiler_features_cxx(14)
     endif()
     if (_result EQUAL 0)
-      _get_appleclang_features(${CMAKE_CXX11_STANDARD_COMPILE_OPTION} CMAKE_CXX11_COMPILE_FEATURES)
+      _record_compiler_features_cxx(11)
     endif()
     if (_result EQUAL 0)
-      _get_appleclang_features(${CMAKE_CXX98_STANDARD_COMPILE_OPTION} CMAKE_CXX98_COMPILE_FEATURES)
+      _record_compiler_features_cxx(98)
     endif()
   endif()
 endmacro()
diff --git a/Modules/Compiler/Clang-C.cmake b/Modules/Compiler/Clang-C.cmake
index d8b7743..bcd9218 100644
--- a/Modules/Compiler/Clang-C.cmake
+++ b/Modules/Compiler/Clang-C.cmake
@@ -34,18 +34,16 @@ if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 3.4)
 endif()
 
 macro(cmake_record_c_compile_features)
-  macro(_get_clang_features std_version list)
-    record_compiler_features(C "${std_version}" ${list})
-  endmacro()
-
   set(_result 0)
   if (UNIX AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 3.4)
-    _get_clang_features(${CMAKE_C11_STANDARD_COMPILE_OPTION} CMAKE_C11_COMPILE_FEATURES)
     if (_result EQUAL 0)
-      _get_clang_features(${CMAKE_C99_STANDARD_COMPILE_OPTION} CMAKE_C99_COMPILE_FEATURES)
+      _record_compiler_features_c(11)
+    endif()
+    if (_result EQUAL 0)
+      _record_compiler_features_c(99)
     endif()
     if (_result EQUAL 0)
-      _get_clang_features(${CMAKE_C90_STANDARD_COMPILE_OPTION} CMAKE_C90_COMPILE_FEATURES)
+      _record_compiler_features_c(90)
     endif()
   endif()
 endmacro()
diff --git a/Modules/Compiler/Clang-CXX-FeatureTests.cmake b/Modules/Compiler/Clang-CXX-FeatureTests.cmake
index df2e1a8..cd04190 100644
--- a/Modules/Compiler/Clang-CXX-FeatureTests.cmake
+++ b/Modules/Compiler/Clang-CXX-FeatureTests.cmake
@@ -2,7 +2,7 @@
 # Reference: http://clang.llvm.org/cxx_status.html
 # http://clang.llvm.org/docs/LanguageExtensions.html
 
-set(_cmake_oldestSupported "((__clang_major__ * 100) + __clang_minor__) >= 304")
+set(_cmake_oldestSupported "((__clang_major__ * 100) + __clang_minor__) >= 301")
 
 include("${CMAKE_CURRENT_LIST_DIR}/Clang-CXX-TestableFeatures.cmake")
 
@@ -15,7 +15,6 @@ set(_cmake_feature_test_cxx_digit_separators "${Clang34_CXX14}")
 # http://llvm.org/bugs/show_bug.cgi?id=19674
 set(_cmake_feature_test_cxx_generic_lambdas "${Clang34_CXX14}")
 
-# TODO: Should be supported by Clang 3.1
 set(Clang31_CXX11 "${_cmake_oldestSupported} && __cplusplus >= 201103L")
 set(_cmake_feature_test_cxx_enum_forward_declarations "${Clang31_CXX11}")
 set(_cmake_feature_test_cxx_sizeof_member "${Clang31_CXX11}")
diff --git a/Modules/Compiler/Clang-CXX.cmake b/Modules/Compiler/Clang-CXX.cmake
index dc62711..8ed3695 100644
--- a/Modules/Compiler/Clang-CXX.cmake
+++ b/Modules/Compiler/Clang-CXX.cmake
@@ -31,7 +31,12 @@ elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4)
   set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++1y")
 endif()
 
-if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4)
+if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.5)
+  set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "-std=c++1z")
+  set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "-std=gnu++1z")
+endif()
+
+if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.1)
   if (NOT CMAKE_CXX_COMPILER_FORCED)
     if (NOT CMAKE_CXX_STANDARD_COMPUTED_DEFAULT)
       message(FATAL_ERROR "CMAKE_CXX_STANDARD_COMPUTED_DEFAULT should be set for ${CMAKE_CXX_COMPILER_ID} (${CMAKE_CXX_COMPILER}) version ${CMAKE_CXX_COMPILER_VERSION}")
@@ -44,18 +49,19 @@ if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4)
 endif()
 
 macro(cmake_record_cxx_compile_features)
-  macro(_get_clang_features std_version list)
-    record_compiler_features(CXX "${std_version}" ${list})
-  endmacro()
-
   set(_result 0)
-  if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4)
-    _get_clang_features(${CMAKE_CXX14_STANDARD_COMPILE_OPTION} CMAKE_CXX14_COMPILE_FEATURES)
-    if (_result EQUAL 0)
-      _get_clang_features(${CMAKE_CXX11_STANDARD_COMPILE_OPTION} CMAKE_CXX11_COMPILE_FEATURES)
+  if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.1)
+    if(_result EQUAL 0 AND CMAKE_CXX17_STANDARD_COMPILE_OPTION)
+      _record_compiler_features_cxx(17)
+    endif()
+    if(_result EQUAL 0 AND CMAKE_CXX14_STANDARD_COMPILE_OPTION)
+      _record_compiler_features_cxx(14)
+    endif()
+    if (_result EQUAL 0 AND CMAKE_CXX11_STANDARD_COMPILE_OPTION)
+      _record_compiler_features_cxx(11)
     endif()
     if (_result EQUAL 0)
-      _get_clang_features(${CMAKE_CXX98_STANDARD_COMPILE_OPTION} CMAKE_CXX98_COMPILE_FEATURES)
+      _record_compiler_features_cxx(98)
     endif()
   endif()
 endmacro()
diff --git a/Modules/Compiler/GNU-DetermineCompiler.cmake b/Modules/Compiler/GNU-C-DetermineCompiler.cmake
similarity index 100%
rename from Modules/Compiler/GNU-DetermineCompiler.cmake
rename to Modules/Compiler/GNU-C-DetermineCompiler.cmake
diff --git a/Modules/Compiler/GNU-C-FeatureTests.cmake b/Modules/Compiler/GNU-C-FeatureTests.cmake
index b3fe33f..0ab5265 100644
--- a/Modules/Compiler/GNU-C-FeatureTests.cmake
+++ b/Modules/Compiler/GNU-C-FeatureTests.cmake
@@ -1,5 +1,5 @@
 
-set(_cmake_oldestSupported "(__GNUC__ * 100 + __GNUC_MINOR__) >= 404")
+set(_cmake_oldestSupported "(__GNUC__ * 100 + __GNUC_MINOR__) >= 304")
 
 # GNU 4.7 correctly sets __STDC_VERSION__ to 201112L, but GNU 4.6 sets it
 # to 201000L.  As the former is strictly greater than the latter, test only
@@ -8,10 +8,10 @@ set(_cmake_oldestSupported "(__GNUC__ * 100 + __GNUC_MINOR__) >= 404")
 # to the distinction between __cplusplus and __GXX_EXPERIMENTAL_CXX0X__ tests.
 set(GNU46_C11 "(__GNUC__ * 100 + __GNUC_MINOR__) >= 406 && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201000L")
 set(_cmake_feature_test_c_static_assert "${GNU46_C11}")
-# Since 4.4 at least:
-set(GNU44_C99 "(__GNUC__ * 100 + __GNUC_MINOR__) >= 404 && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L")
-set(_cmake_feature_test_c_restrict "${GNU44_C99}")
-set(_cmake_feature_test_c_variadic_macros "${GNU44_C99}")
+# Since 3.4 at least:
+set(GNU34_C99 "(__GNUC__ * 100 + __GNUC_MINOR__) >= 304 && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L")
+set(_cmake_feature_test_c_restrict "${GNU34_C99}")
+set(_cmake_feature_test_c_variadic_macros "${GNU34_C99}")
 
 set(GNU_C90 "${_cmake_oldestSupported}")
 set(_cmake_feature_test_c_function_prototypes "${GNU_C90}")
diff --git a/Modules/Compiler/GNU-C.cmake b/Modules/Compiler/GNU-C.cmake
index 2c478da..3f02618 100644
--- a/Modules/Compiler/GNU-C.cmake
+++ b/Modules/Compiler/GNU-C.cmake
@@ -4,12 +4,12 @@ __compiler_gnu(C)
 if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.5)
   set(CMAKE_C90_STANDARD_COMPILE_OPTION "-std=c90")
   set(CMAKE_C90_EXTENSION_COMPILE_OPTION "-std=gnu90")
-elseif (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.4)
+elseif (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 3.4)
   set(CMAKE_C90_STANDARD_COMPILE_OPTION "-std=c89")
   set(CMAKE_C90_EXTENSION_COMPILE_OPTION "-std=gnu89")
 endif()
 
-if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.4)
+if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 3.4)
   set(CMAKE_C99_STANDARD_COMPILE_OPTION "-std=c99")
   set(CMAKE_C99_EXTENSION_COMPILE_OPTION "-std=gnu99")
 endif()
@@ -22,7 +22,7 @@ elseif (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.6)
   set(CMAKE_C11_EXTENSION_COMPILE_OPTION "-std=gnu1x")
 endif()
 
-if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.4)
+if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 3.4)
   if (NOT CMAKE_C_COMPILER_FORCED)
     if (NOT CMAKE_C_STANDARD_COMPUTED_DEFAULT)
       message(FATAL_ERROR "CMAKE_C_STANDARD_COMPUTED_DEFAULT should be set for ${CMAKE_C_COMPILER_ID} (${CMAKE_C_COMPILER}) version ${CMAKE_C_COMPILER_VERSION}")
@@ -38,22 +38,17 @@ if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.4)
   endif()
 endif()
 
-
 macro(cmake_record_c_compile_features)
-  macro(_get_gcc_features std_version list)
-    record_compiler_features(C "${std_version}" ${list})
-  endmacro()
-
   set(_result 0)
-  if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.6)
-    _get_gcc_features(${CMAKE_C11_STANDARD_COMPILE_OPTION} CMAKE_C11_COMPILE_FEATURES)
-  endif()
-  if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.4)
+  if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 3.4)
+    if(_result EQUAL 0 AND CMAKE_C11_STANDARD_COMPILE_OPTION)
+      _record_compiler_features_c(11)
+    endif()
     if (_result EQUAL 0)
-      _get_gcc_features(${CMAKE_C99_STANDARD_COMPILE_OPTION} CMAKE_C99_COMPILE_FEATURES)
+      _record_compiler_features_c(99)
     endif()
     if (_result EQUAL 0)
-      _get_gcc_features(${CMAKE_C90_STANDARD_COMPILE_OPTION} CMAKE_C90_COMPILE_FEATURES)
+      _record_compiler_features_c(90)
     endif()
   endif()
 endmacro()
diff --git a/Modules/Compiler/GNU-CXX-DetermineCompiler.cmake b/Modules/Compiler/GNU-CXX-DetermineCompiler.cmake
new file mode 100644
index 0000000..c25b147
--- /dev/null
+++ b/Modules/Compiler/GNU-CXX-DetermineCompiler.cmake
@@ -0,0 +1,15 @@
+
+set(_compiler_id_pp_test "defined(__GNUC__) || defined(__GNUG__)")
+
+set(_compiler_id_version_compute "
+# if defined(__GNUC__)
+#  define @PREFIX at COMPILER_VERSION_MAJOR @MACRO_DEC@(__GNUC__)
+# else
+#  define @PREFIX at COMPILER_VERSION_MAJOR @MACRO_DEC@(__GNUG__)
+# endif
+# if defined(__GNUC_MINOR__)
+#  define @PREFIX at COMPILER_VERSION_MINOR @MACRO_DEC@(__GNUC_MINOR__)
+# endif
+# if defined(__GNUC_PATCHLEVEL__)
+#  define @PREFIX at COMPILER_VERSION_PATCH @MACRO_DEC@(__GNUC_PATCHLEVEL__)
+# endif")
diff --git a/Modules/Compiler/GNU-CXX.cmake b/Modules/Compiler/GNU-CXX.cmake
index e1c555b..c007c98 100644
--- a/Modules/Compiler/GNU-CXX.cmake
+++ b/Modules/Compiler/GNU-CXX.cmake
@@ -6,7 +6,7 @@ if (WIN32)
     set(CMAKE_CXX_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN "-fno-keep-inline-dllexport")
   endif()
 else()
-  if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.2)
+  if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.0)
     set(CMAKE_CXX_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN "-fvisibility-inlines-hidden")
   endif()
 endif()
@@ -34,6 +34,11 @@ elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.8)
   set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++1y")
 endif()
 
+if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.1)
+  set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "-std=c++1z")
+  set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "-std=gnu++1z")
+endif()
+
 if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.4)
   if (NOT CMAKE_CXX_COMPILER_FORCED)
     if (NOT CMAKE_CXX_STANDARD_COMPUTED_DEFAULT)
@@ -47,20 +52,19 @@ if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.4)
 endif()
 
 macro(cmake_record_cxx_compile_features)
-  macro(_get_gcc_features std_version list)
-    record_compiler_features(CXX "${std_version}" ${list})
-  endmacro()
-
   set(_result 0)
-  if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.8)
-    _get_gcc_features(${CMAKE_CXX14_STANDARD_COMPILE_OPTION} CMAKE_CXX14_COMPILE_FEATURES)
-  endif()
   if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.4)
+    if(_result EQUAL 0 AND CMAKE_CXX17_STANDARD_COMPILE_OPTION)
+      _record_compiler_features_cxx(17)
+    endif()
+    if(_result EQUAL 0 AND CMAKE_CXX14_STANDARD_COMPILE_OPTION)
+      _record_compiler_features_cxx(14)
+    endif()
     if (_result EQUAL 0)
-      _get_gcc_features(${CMAKE_CXX11_STANDARD_COMPILE_OPTION} CMAKE_CXX11_COMPILE_FEATURES)
+      _record_compiler_features_cxx(11)
     endif()
     if (_result EQUAL 0)
-      _get_gcc_features(${CMAKE_CXX98_STANDARD_COMPILE_OPTION} CMAKE_CXX98_COMPILE_FEATURES)
+      _record_compiler_features_cxx(98)
     endif()
   endif()
 endmacro()
diff --git a/Modules/Compiler/Intel-C-FeatureTests.cmake b/Modules/Compiler/Intel-C-FeatureTests.cmake
index 34175c8..5d09767 100644
--- a/Modules/Compiler/Intel-C-FeatureTests.cmake
+++ b/Modules/Compiler/Intel-C-FeatureTests.cmake
@@ -3,15 +3,11 @@
 #   - https://software.intel.com/en-us/articles/c99-support-in-intel-c-compiler
 #   - https://software.intel.com/en-us/articles/c11-support-in-intel-c-compiler
 
-# FIXME: Intel C feature detection works only when simulating the GNU compiler.
-if("x${CMAKE_C_SIMULATE_ID}" STREQUAL "xMSVC")
-  return()
-endif()
-
 set(DETECT_C99 "defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L")
+set(DETECT_C11 "defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L")
 
 #static assert is only around in version 1500 update 2 and above
-set(_cmake_feature_test_c_static_assert "(__INTEL_COMPILER > 1500 || (__INTEL_COMPILER == 1500 && __INTEL_COMPILER_UPDATE > 1) ) && ${DETECT_C99}")
+set(_cmake_feature_test_c_static_assert "(__INTEL_COMPILER > 1500 || (__INTEL_COMPILER == 1500 && __INTEL_COMPILER_UPDATE > 1) ) && (${DETECT_C11} || ${DETECT_C99} && !defined(_MSC_VER))")
 
 set(_cmake_oldestSupported "__INTEL_COMPILER >= 1110")
 set(Intel_C99 "${_cmake_oldestSupported} && ${DETECT_C99}")
@@ -21,3 +17,4 @@ set(_cmake_feature_test_c_function_prototypes "${_cmake_oldestSupported}")
 unset(Intel_C99)
 
 unset(DETECT_C99)
+unset(DETECT_C11)
diff --git a/Modules/Compiler/Intel-C.cmake b/Modules/Compiler/Intel-C.cmake
index 61adf40..9c67fbd 100644
--- a/Modules/Compiler/Intel-C.cmake
+++ b/Modules/Compiler/Intel-C.cmake
@@ -10,14 +10,17 @@ set(CMAKE_DEPFILE_FLAGS_C "-MD -MT <OBJECT> -MF <DEPFILE>")
 if("x${CMAKE_C_SIMULATE_ID}" STREQUAL "xMSVC")
   set(_std -Qstd)
   set(_ext c)
+  if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 16.0.0)
+    set(CMAKE_C11_STANDARD_COMPILE_OPTION "-Qstd=c11")
+    set(CMAKE_C11_EXTENSION_COMPILE_OPTION "-Qstd=c11")
+  endif()
 else()
   set(_std -std)
   set(_ext gnu)
-endif()
-
-if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 15.0.0)
-  set(CMAKE_C11_STANDARD_COMPILE_OPTION "${_std}=c11")
-  set(CMAKE_C11_EXTENSION_COMPILE_OPTION "${_std}=${_ext}11")
+  if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 15.0.0)
+    set(CMAKE_C11_STANDARD_COMPILE_OPTION "-std=c11")
+    set(CMAKE_C11_EXTENSION_COMPILE_OPTION "-std=gnu11")
+  endif()
 endif()
 
 if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 12.0)
@@ -47,21 +50,16 @@ unset(_std)
 unset(_ext)
 
 macro(cmake_record_c_compile_features)
-  macro(_get_intel_c_features std_version list)
-    record_compiler_features(C "${std_version}" ${list})
-  endmacro()
-
   set(_result 0)
-  if (NOT "x${CMAKE_C_SIMULATE_ID}" STREQUAL "xMSVC" AND
-      NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 12.1)
-    if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 15.0.0)
-      _get_intel_c_features(${CMAKE_C11_STANDARD_COMPILE_OPTION} CMAKE_C11_COMPILE_FEATURES)
+  if (NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 12.1)
+    if (_result EQUAL 0 AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 15.0.0)
+      _record_compiler_features_C(11)
     endif()
     if (_result EQUAL 0)
-      _get_intel_c_features(${CMAKE_C99_STANDARD_COMPILE_OPTION} CMAKE_C99_COMPILE_FEATURES)
+      _record_compiler_features_C(99)
     endif()
     if (_result EQUAL 0)
-      _get_intel_c_features(${CMAKE_C90_STANDARD_COMPILE_OPTION} CMAKE_C90_COMPILE_FEATURES)
+      _record_compiler_features_C(90)
     endif()
   endif()
 endmacro()
diff --git a/Modules/Compiler/Intel-CXX-FeatureTests.cmake b/Modules/Compiler/Intel-CXX-FeatureTests.cmake
index 57a05c8..929a7c6 100644
--- a/Modules/Compiler/Intel-CXX-FeatureTests.cmake
+++ b/Modules/Compiler/Intel-CXX-FeatureTests.cmake
@@ -3,14 +3,16 @@
 #   - https://software.intel.com/en-us/articles/c14-features-supported-by-intel-c-compiler
 #   - http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0096r3.html
 
-# FIXME: Intel C++ feature detection works only when simulating the GNU compiler.
-# When simulating MSVC, Intel always sets __cplusplus to 199711L.
-if("x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC")
-  return()
-endif()
+# Notes:
+# [1] Some Intel versions define some feature macros under -std=gnu++98
+#     that do not work in that mode (or work with warnings):
+#     - __cpp_attributes 200809
+#     - __cpp_init_captures 201304
+#     - __cpp_lambdas 200907
+#     - __cpp_rvalue_references 200610
+#     - __cpp_variadic_templates 200704
 
 set(_cmake_feature_test_cxx_variable_templates "__cpp_variable_templates >= 201304")
-set(_cmake_feature_test_cxx_relaxed_constexpr "__cpp_constexpr >= 201304")
 
 set(_cmake_oldestSupported "__INTEL_COMPILER >= 1210")
 set(DETECT_CXX11 "((__cplusplus >= 201103L) || defined(__INTEL_CXX11_MODE__) || defined(__GXX_EXPERIMENTAL_CXX0X__))")
@@ -18,44 +20,53 @@ set(DETECT_CXX11 "((__cplusplus >= 201103L) || defined(__INTEL_CXX11_MODE__) ||
 #if you are compiling as 98/11/14. So to properly detect C++14 with this version
 #we look for the existence of __GXX_EXPERIMENTAL_CXX0X__ but not __INTEL_CXX11_MODE__
 set(DETECT_BUGGY_ICC15 "((__INTEL_COMPILER == 1500) && (__INTEL_COMPILER_UPDATE == 1))")
-set(DETECT_CXX14 "((__cplusplus >= 201300L) || ((__cplusplus == 201103L) && !defined(__INTEL_CXX11_MODE__)) || ((${DETECT_BUGGY_ICC15}) && defined(__GXX_EXPERIMENTAL_CXX0X__) && !defined(__INTEL_CXX11_MODE__) ) )")
+set(DETECT_CXX14 "((__cplusplus >= 201300L) || ((__cplusplus == 201103L) && !defined(__INTEL_CXX11_MODE__)) || ((${DETECT_BUGGY_ICC15}) && defined(__GXX_EXPERIMENTAL_CXX0X__) && !defined(__INTEL_CXX11_MODE__) ) || (defined(__INTEL_CXX11_MODE__) && defined(__cpp_aggregate_nsdmi)) )")
+unset(DETECT_BUGGY_ICC15)
+
+set(Intel17_CXX14 "__INTEL_COMPILER >= 1700 && ${DETECT_CXX14}")
+set(_cmake_feature_test_cxx_relaxed_constexpr "__cpp_constexpr >= 201304 || (${Intel17_CXX14} && !defined(_MSC_VER))")
 
 set(Intel16_CXX14 "__INTEL_COMPILER >= 1600 && ${DETECT_CXX14}")
 set(_cmake_feature_test_cxx_aggregate_default_initializers "${Intel16_CXX14}")
 set(_cmake_feature_test_cxx_contextual_conversions "${Intel16_CXX14}")
-set(_cmake_feature_test_cxx_generic_lambdas "${Intel16_CXX14}")
+set(_cmake_feature_test_cxx_generic_lambdas "__cpp_generic_lambdas >= 201304")
 set(_cmake_feature_test_cxx_digit_separators "${Intel16_CXX14}")
 # This test is supposed to work in Intel 14 but the compiler has a bug
 # in versions 14 and 15::
 # https://software.intel.com/en-us/forums/intel-c-compiler/topic/600514
-# It also appears to fail with an internal compiler error on Intel 16.
+# It also appears to fail with an internal compiler error on Intel 16 and 17.
 #set(_cmake_feature_test_cxx_generalized_initializers "${Intel16_CXX14}")
+unset(Intel16_CXX14)
 
-set(Intel15_CXX14 "__INTEL_COMPILER >= 1500 && ${DETECT_CXX14}")
-set(_cmake_feature_test_cxx_decltype_auto "${Intel15_CXX14}")
-set(_cmake_feature_test_cxx_lambda_init_captures "${Intel15_CXX14}")
+set(Intel15 "__INTEL_COMPILER >= 1500")
+set(Intel15_CXX14 "${Intel15} && ${DETECT_CXX14}")
+set(_cmake_feature_test_cxx_decltype_auto "__cpp_decltype_auto >= 201304 || ${Intel15_CXX14}")
+set(_cmake_feature_test_cxx_lambda_init_captures "(__cpp_init_captures >= 201304 || ${Intel15}) && ${DETECT_CXX14}") # [1]
 set(_cmake_feature_test_cxx_attribute_deprecated "${Intel15_CXX14}")
-set(_cmake_feature_test_cxx_return_type_deduction "${Intel15_CXX14}")
+set(_cmake_feature_test_cxx_return_type_deduction "__cpp_return_type_deduction >= 201304 || ${Intel15_CXX14}")
+unset(Intel15_CXX14)
+unset(Intel15)
 
 set(Intel15_CXX11 "__INTEL_COMPILER >= 1500 && ${DETECT_CXX11}")
 set(_cmake_feature_test_cxx_alignas "${Intel15_CXX11}")
 set(_cmake_feature_test_cxx_alignof "${Intel15_CXX11}")
 set(_cmake_feature_test_cxx_inheriting_constructors "${Intel15_CXX11}")
-set(_cmake_feature_test_cxx_user_literals "${Intel15_CXX11}")
+set(_cmake_feature_test_cxx_user_literals "__cpp_user_defined_literals >= 200809 || (${Intel15_CXX11} && (!defined(_MSC_VER) || __INTEL_COMPILER >= 1600))")
 set(_cmake_feature_test_cxx_thread_local "${Intel15_CXX11}")
+unset(Intel15_CXX11)
 
 set(Intel14_CXX11 "${DETECT_CXX11} && (__INTEL_COMPILER > 1400 || (__INTEL_COMPILER == 1400 && __INTEL_COMPILER_UPDATE >= 2))")
 # Documented as 12.0+ but in testing it only works on 14.0.2+
-set(_cmake_feature_test_cxx_decltype_incomplete_return_types "${Intel14_CXX11}")
+set(_cmake_feature_test_cxx_decltype_incomplete_return_types "${Intel14_CXX11} && !defined(_MSC_VER)")
 
 set(Intel14_CXX11 "__INTEL_COMPILER >= 1400 && ${DETECT_CXX11}")
 set(_cmake_feature_test_cxx_delegating_constructors "${Intel14_CXX11}")
-set(_cmake_feature_test_cxx_constexpr "${Intel14_CXX11}")
+set(_cmake_feature_test_cxx_constexpr "__cpp_constexpr >= 200704 || ${Intel14_CXX11}")
 set(_cmake_feature_test_cxx_sizeof_member "${Intel14_CXX11}")
 set(_cmake_feature_test_cxx_strong_enums "${Intel14_CXX11}")
 set(_cmake_feature_test_cxx_reference_qualified_functions "${Intel14_CXX11}")
-set(_cmake_feature_test_cxx_raw_string_literals "${Intel14_CXX11}")
-set(_cmake_feature_test_cxx_unicode_literals "${Intel14_CXX11}")
+set(_cmake_feature_test_cxx_raw_string_literals "__cpp_raw_strings >= 200710 || ${Intel14_CXX11}")
+set(_cmake_feature_test_cxx_unicode_literals "__cpp_unicode_literals >= 200710 || (${Intel14_CXX11} && (!defined(_MSC_VER) || __INTEL_COMPILER >= 1600))")
 set(_cmake_feature_test_cxx_inline_namespaces "${Intel14_CXX11}")
 set(_cmake_feature_test_cxx_unrestricted_unions "${Intel14_CXX11}")
 set(_cmake_feature_test_cxx_nonstatic_member_init "${Intel14_CXX11}")
@@ -64,29 +75,32 @@ set(_cmake_feature_test_cxx_override "${Intel14_CXX11}")
 set(_cmake_feature_test_cxx_final "${Intel14_CXX11}")
 set(_cmake_feature_test_cxx_noexcept "${Intel14_CXX11}")
 set(_cmake_feature_test_cxx_defaulted_move_initializers "${Intel14_CXX11}")
+unset(Intel14_CXX11)
 
 set(Intel13_CXX11 "__INTEL_COMPILER >= 1300 && ${DETECT_CXX11}")
 set(_cmake_feature_test_cxx_explicit_conversions "${Intel13_CXX11}")
 set(_cmake_feature_test_cxx_range_for "${Intel13_CXX11}")
 # Cannot find Intel documentation for N2640: cxx_uniform_initialization
 set(_cmake_feature_test_cxx_uniform_initialization "${Intel13_CXX11}")
+unset(Intel13_CXX11)
 
-set(Intel121_CXX11 "${_cmake_oldestSupported} && ${DETECT_CXX11}")
-set(_cmake_feature_test_cxx_variadic_templates "${Intel121_CXX11}")
+set(Intel121 "${_cmake_oldestSupported}")
+set(Intel121_CXX11 "${Intel121} && ${DETECT_CXX11}")
+set(_cmake_feature_test_cxx_variadic_templates "(__cpp_variadic_templates >= 200704 || ${Intel121}) && ${DETECT_CXX11}") # [1]
 set(_cmake_feature_test_cxx_alias_templates "${Intel121_CXX11}")
 set(_cmake_feature_test_cxx_nullptr "${Intel121_CXX11}")
 set(_cmake_feature_test_cxx_trailing_return_types "${Intel121_CXX11}")
-set(_cmake_feature_test_cxx_attributes "${Intel121_CXX11}")
+set(_cmake_feature_test_cxx_attributes "(__cpp_attributes >= 200809 || ${Intel121}) && ${DETECT_CXX11}") # [1]
 set(_cmake_feature_test_cxx_default_function_template_args "${Intel121_CXX11}")
 set(_cmake_feature_test_cxx_extended_friend_declarations "${Intel121_CXX11}")
-set(_cmake_feature_test_cxx_rvalue_references "${Intel121_CXX11}")
-set(_cmake_feature_test_cxx_decltype "${Intel121_CXX11}")
+set(_cmake_feature_test_cxx_rvalue_references "(__cpp_rvalue_references >= 200610 || ${Intel121}) && ${DETECT_CXX11}") # [1]
+set(_cmake_feature_test_cxx_decltype "__cpp_decltype >= 200707 || ${Intel121_CXX11}")
 set(_cmake_feature_test_cxx_defaulted_functions "${Intel121_CXX11}")
 set(_cmake_feature_test_cxx_deleted_functions "${Intel121_CXX11}")
 set(_cmake_feature_test_cxx_local_type_template_args "${Intel121_CXX11}")
-set(_cmake_feature_test_cxx_lambdas "${Intel121_CXX11}")
-set(_cmake_feature_test_cxx_binary_literals "${Intel121_CXX11}")
-set(_cmake_feature_test_cxx_static_assert "${Intel121_CXX11}")
+set(_cmake_feature_test_cxx_lambdas "(__cpp_lambdas >= 200907 || ${Intel121}) && ${DETECT_CXX11}") # [1]
+set(_cmake_feature_test_cxx_binary_literals "__cpp_binary_literals >= 201304 || ${Intel121}")
+set(_cmake_feature_test_cxx_static_assert "(__cpp_static_assert >= 200410 || ${Intel121}) && ${DETECT_CXX11}")
 set(_cmake_feature_test_cxx_right_angle_brackets "${Intel121_CXX11}")
 set(_cmake_feature_test_cxx_auto_type "${Intel121_CXX11}")
 set(_cmake_feature_test_cxx_extern_templates "${Intel121_CXX11}")
@@ -94,3 +108,8 @@ set(_cmake_feature_test_cxx_variadic_macros "${Intel121_CXX11}")
 set(_cmake_feature_test_cxx_long_long_type "${Intel121_CXX11}")
 set(_cmake_feature_test_cxx_func_identifier "${Intel121_CXX11}")
 set(_cmake_feature_test_cxx_template_template_parameters "${Intel121_CXX11}")
+unset(Intel121_CXX11)
+unset(Intel121)
+
+unset(DETECT_CXX11)
+unset(DETECT_CXX14)
diff --git a/Modules/Compiler/Intel-CXX.cmake b/Modules/Compiler/Intel-CXX.cmake
index 73dd7fa..9c39236 100644
--- a/Modules/Compiler/Intel-CXX.cmake
+++ b/Modules/Compiler/Intel-CXX.cmake
@@ -10,19 +10,23 @@ set(CMAKE_DEPFILE_FLAGS_CXX "-MD -MT <OBJECT> -MF <DEPFILE>")
 if("x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC")
   set(_std -Qstd)
   set(_ext c++)
+  if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16.0)
+    set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-Qstd=c++14")
+    # todo: there is no gnu++14 value supported; figure out what to do
+    set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-Qstd=c++14")
+  endif()
 else()
   set(_std -std)
   set(_ext gnu++)
-endif()
-
-if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15.0.2)
-  set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "${_std}=c++14")
-  # todo: there is no gnu++14 value supported; figure out what to do
-  set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "${_std}=c++14")
-elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15.0.0)
-  set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "${_std}=c++1y")
-  # todo: there is no gnu++14 value supported; figure out what to do
-  set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "${_std}=c++1y")
+  if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15.0.2)
+    set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std=c++14")
+    # todo: there is no gnu++14 value supported; figure out what to do
+    set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=c++14")
+  elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15.0.0)
+    set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std=c++1y")
+    # todo: there is no gnu++14 value supported; figure out what to do
+    set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=c++1y")
+  endif()
 endif()
 
 if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 13.0)
@@ -34,8 +38,13 @@ elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 12.1)
 endif()
 
 if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 12.1)
-  set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "${_std}=c++98")
-  set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "${_std}=${_ext}98")
+  if("x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC")
+    set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "")
+    set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "")
+  else()
+    set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "${_std}=c++98")
+    set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "${_std}=gnu++98")
+  endif()
 endif()
 
 if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 12.1)
@@ -55,21 +64,19 @@ unset(_std)
 unset(_ext)
 
 macro(cmake_record_cxx_compile_features)
-  macro(_get_intel_features std_version list)
-    record_compiler_features(CXX "${std_version}" ${list})
-  endmacro()
-
   set(_result 0)
-  if(NOT "x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC" AND
-      NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 12.1)
-    if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15.0)
-      _get_intel_features(${CMAKE_CXX14_STANDARD_COMPILE_OPTION} CMAKE_CXX14_COMPILE_FEATURES)
+  if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 12.1)
+    if (_result EQUAL 0 AND
+        (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16.0
+         OR (NOT "x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC" AND
+             NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15.0)))
+      _record_compiler_features_cxx(14)
     endif()
     if (_result EQUAL 0)
-      _get_intel_features(${CMAKE_CXX11_STANDARD_COMPILE_OPTION} CMAKE_CXX11_COMPILE_FEATURES)
+      _record_compiler_features_cxx(11)
     endif()
     if (_result EQUAL 0)
-      _get_intel_features(${CMAKE_CXX98_STANDARD_COMPILE_OPTION} CMAKE_CXX98_COMPILE_FEATURES)
+      _record_compiler_features_cxx(98)
     endif()
   endif()
 endmacro()
diff --git a/Modules/Compiler/MSVC-CXX.cmake b/Modules/Compiler/MSVC-CXX.cmake
index 82ce069..8fcfa0f 100644
--- a/Modules/Compiler/MSVC-CXX.cmake
+++ b/Modules/Compiler/MSVC-CXX.cmake
@@ -5,5 +5,13 @@ if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16.0)
 endif()
 
 macro(cmake_record_cxx_compile_features)
-  record_compiler_features(CXX "" CMAKE_CXX_COMPILE_FEATURES)
+  if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16.0)
+    list(APPEND CMAKE_CXX_COMPILE_FEATURES
+      cxx_std_98
+      cxx_std_11
+      cxx_std_14
+      cxx_std_17
+      )
+    _record_compiler_features(CXX "" CMAKE_CXX_COMPILE_FEATURES)
+  endif()
 endmacro()
diff --git a/Modules/Compiler/NVIDIA-CUDA.cmake b/Modules/Compiler/NVIDIA-CUDA.cmake
new file mode 100644
index 0000000..316cab8
--- /dev/null
+++ b/Modules/Compiler/NVIDIA-CUDA.cmake
@@ -0,0 +1,27 @@
+set(CMAKE_CUDA_VERBOSE_FLAG "-v")
+
+if(NOT "x${CMAKE_CUDA_SIMULATE_ID}" STREQUAL "xMSVC")
+  set(CMAKE_CUDA_COMPILE_OPTIONS_PIE -Xcompiler=-fPIE)
+  set(CMAKE_CUDA_COMPILE_OPTIONS_PIC -Xcompiler=-fPIC)
+  set(CMAKE_CUDA_COMPILE_OPTIONS_VISIBILITY -Xcompiler=-fvisibility=)
+  # CMAKE_SHARED_LIBRARY_CUDA_FLAGS is sent to the host linker so we
+  # don't need to forward it through nvcc.
+  set(CMAKE_SHARED_LIBRARY_CUDA_FLAGS -fPIC)
+  string(APPEND CMAKE_CUDA_FLAGS_INIT " ")
+  string(APPEND CMAKE_CUDA_FLAGS_DEBUG_INIT " -g")
+  string(APPEND CMAKE_CUDA_FLAGS_RELEASE_INIT " -O3 -DNDEBUG")
+  string(APPEND CMAKE_CUDA_FLAGS_MINSIZEREL_INIT " -O1 -DNDEBUG")
+  string(APPEND CMAKE_CUDA_FLAGS_RELWITHDEBINFO_INIT " -O2 -g -DNDEBUG")
+endif()
+set(CMAKE_SHARED_LIBRARY_CREATE_CUDA_FLAGS -shared)
+set(CMAKE_INCLUDE_SYSTEM_FLAG_CUDA -isystem=)
+
+if("x${CMAKE_CUDA_SIMULATE_ID}" STREQUAL "xMSVC")
+  set(CMAKE_CUDA_STANDARD_DEFAULT "")
+else()
+  set(CMAKE_CUDA_STANDARD_DEFAULT 98)
+  set(CMAKE_CUDA98_STANDARD_COMPILE_OPTION "")
+  set(CMAKE_CUDA98_EXTENSION_COMPILE_OPTION "")
+  set(CMAKE_CUDA11_STANDARD_COMPILE_OPTION "-std=c++11")
+  set(CMAKE_CUDA11_EXTENSION_COMPILE_OPTION "-std=c++11")
+endif()
diff --git a/Modules/Compiler/NVIDIA-DetermineCompiler.cmake b/Modules/Compiler/NVIDIA-DetermineCompiler.cmake
new file mode 100644
index 0000000..cb0beaf
--- /dev/null
+++ b/Modules/Compiler/NVIDIA-DetermineCompiler.cmake
@@ -0,0 +1,17 @@
+
+set(_compiler_id_pp_test "defined(__NVCC__)")
+
+set(_compiler_id_version_compute "
+# define @PREFIX at COMPILER_VERSION_MAJOR @MACRO_DEC@(__CUDACC_VER_MAJOR__)
+# define @PREFIX at COMPILER_VERSION_MINOR @MACRO_DEC@(__CUDACC_VER_MINOR__)
+# define @PREFIX at COMPILER_VERSION_PATCH @MACRO_DEC@(__CUDACC_VER_BUILD__)
+# if defined(_MSC_VER)
+   /* _MSC_VER = VVRR */
+#  define @PREFIX at SIMULATE_VERSION_MAJOR @MACRO_DEC@(_MSC_VER / 100)
+#  define @PREFIX at SIMULATE_VERSION_MINOR @MACRO_DEC@(_MSC_VER % 100)
+# endif")
+
+set(_compiler_id_simulate "
+# if defined(_MSC_VER)
+#  define @PREFIX at SIMULATE_ID \"MSVC\"
+# endif")
diff --git a/Modules/Compiler/PGI-Fortran.cmake b/Modules/Compiler/PGI-Fortran.cmake
index 3765079..4783424 100644
--- a/Modules/Compiler/PGI-Fortran.cmake
+++ b/Modules/Compiler/PGI-Fortran.cmake
@@ -1,6 +1,9 @@
 include(Compiler/PGI)
 __compiler_pgi(Fortran)
 
+set(CMAKE_Fortran_PREPROCESS_SOURCE
+  "<CMAKE_Fortran_COMPILER> -Mpreprocess <DEFINES> <INCLUDES> <FLAGS> -E <SOURCE> > <PREPROCESSED_SOURCE>")
+
 set(CMAKE_Fortran_FORMAT_FIXED_FLAG "-Mnofreeform")
 set(CMAKE_Fortran_FORMAT_FREE_FLAG "-Mfreeform")
 
diff --git a/Modules/Compiler/SDCC-C-DetermineCompiler.cmake b/Modules/Compiler/SDCC-C-DetermineCompiler.cmake
index 1d7dd78..4c70c5e 100644
--- a/Modules/Compiler/SDCC-C-DetermineCompiler.cmake
+++ b/Modules/Compiler/SDCC-C-DetermineCompiler.cmake
@@ -1,10 +1,16 @@
 
 # sdcc, the small devices C compiler for embedded systems,
 #   http://sdcc.sourceforge.net  */
-set(_compiler_id_pp_test "defined(SDCC)")
+set(_compiler_id_pp_test "defined(__SDCC_VERSION_MAJOR) || defined(SDCC)")
 
 set(_compiler_id_version_compute "
+# if defined(__SDCC_VERSION_MAJOR)
+#  define COMPILER_VERSION_MAJOR @MACRO_DEC@(__SDCC_VERSION_MAJOR)
+#  define COMPILER_VERSION_MINOR @MACRO_DEC@(__SDCC_VERSION_MINOR)
+#  define COMPILER_VERSION_PATCH @MACRO_DEC@(__SDCC_VERSION_PATCH)
+# else
   /* SDCC = VRP */
 #  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)")
+#  define COMPILER_VERSION_PATCH @MACRO_DEC@(SDCC    % 10)
+# endif")
diff --git a/Modules/Compiler/SunPro-CXX.cmake b/Modules/Compiler/SunPro-CXX.cmake
index ce01cdd..f4345b8 100644
--- a/Modules/Compiler/SunPro-CXX.cmake
+++ b/Modules/Compiler/SunPro-CXX.cmake
@@ -32,6 +32,8 @@ set(CMAKE_CXX_CREATE_STATIC_LIBRARY
   "<CMAKE_RANLIB> <TARGET> ")
 
 if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.13)
+  set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "")
+  set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "")
   set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "-std=c++11")
   set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "-std=c++11")
 endif()
@@ -49,15 +51,13 @@ if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.13)
 endif()
 
 macro(cmake_record_cxx_compile_features)
-  macro(_get_solaris_studio_features std_version list)
-    record_compiler_features(CXX "${std_version}" ${list})
-  endmacro()
-
   set(_result 0)
   if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.13)
-    _get_solaris_studio_features(${CMAKE_CXX11_STANDARD_COMPILE_OPTION} CMAKE_CXX11_COMPILE_FEATURES)
     if (_result EQUAL 0)
-      _get_solaris_studio_features("" CMAKE_CXX98_COMPILE_FEATURES)
+      _record_compiler_features_cxx(11)
+    endif()
+    if (_result EQUAL 0)
+      _record_compiler_features_cxx(98)
     endif()
   endif()
 endmacro()
diff --git a/Modules/CompilerId/VS-10.csproj.in b/Modules/CompilerId/VS-10.csproj.in
new file mode 100644
index 0000000..ed5e847
--- /dev/null
+++ b/Modules/CompilerId/VS-10.csproj.in
@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{CAE07175-D007-4FC3-BFE8-47B392814159}</ProjectGuid>
+    <RootNamespace>CompilerId at id_lang@</RootNamespace>
+    <Keyword>Win32Proj</Keyword>
+    @id_system@
+    @id_system_version@
+    @id_WindowsTargetPlatformVersion@
+    @id_WindowsSDKDesktopARMSupport@
+  </PropertyGroup>
+  <PropertyGroup>
+    @id_PreferredToolArchitecture@
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|@id_platform@'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    @id_toolset@
+    <CharacterSet>MultiByte</CharacterSet>
+  </PropertyGroup>
+  <!-- ============================================================ -->
+  <!-- ==                set preprocessor definitions            == -->
+  <!-- ============================================================ -->
+  <PropertyGroup>
+    <DefineConstants></DefineConstants>
+    <UnknownValue>Unknown</UnknownValue>
+  </PropertyGroup>
+  <!-- Platform -->
+  <PropertyGroup Condition="'$(Platform)'!=''">
+    <DefineConstants>$(DefineConstants);Platform$(Platform)</DefineConstants>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Platform)'==''">
+    <DefineConstants>$(DefineConstants);Platform$(UnknownValue)</DefineConstants>
+  </PropertyGroup>
+  <!-- PlatformToolset -->
+  <PropertyGroup Condition="'$(PlatformToolset)'!=''">
+    <DefineConstants>$(DefineConstants);PlatformToolset$(PlatformToolset)</DefineConstants>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(PlatformToolset)'==''">
+    <DefineConstants>$(DefineConstants);PlatformToolset$(UnknownValue)</DefineConstants>
+  </PropertyGroup>
+  <!-- ============================================================ -->
+  <PropertyGroup>
+    <OutputPath Condition="'$(Configuration)|$(Platform)'=='Debug|@id_platform@'">.\</OutputPath>
+  </PropertyGroup>
+  <ItemGroup>
+    <Compile Include="@id_src@" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <PropertyGroup>
+    <PostBuildEvent>if not "$(RoslynTargetsPath)"=="" if exist "$(RoslynTargetsPath)\@id_cl@" set _CSC=$(RoslynTargetsPath)
+if exist "$(MSBuildToolsPath)\@id_cl@" set _CSC=$(MSBuildToolsPath)
+if "%_CSC%"=="" exit -1
+%40echo CMAKE_ at id_lang@_COMPILER=%_CSC%\@id_cl@</PostBuildEvent>
+  </PropertyGroup>
+</Project>
diff --git a/Modules/CompilerId/VS-10.vcxproj.in b/Modules/CompilerId/VS-10.vcxproj.in
index 2870a11..50be9cb 100644
--- a/Modules/CompilerId/VS-10.vcxproj.in
+++ b/Modules/CompilerId/VS-10.vcxproj.in
@@ -16,6 +16,9 @@
     @id_WindowsSDKDesktopARMSupport@
   </PropertyGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup>
+    @id_PreferredToolArchitecture@
+  </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|@id_platform@'" Label="Configuration">
     <ConfigurationType>Application</ConfigurationType>
     @id_toolset@
diff --git a/Modules/ExternalData.cmake b/Modules/ExternalData.cmake
index b00de14..873f88d 100644
--- a/Modules/ExternalData.cmake
+++ b/Modules/ExternalData.cmake
@@ -201,6 +201,11 @@ For example, the argument ``DATA{img.png}`` may be satisfied by either a
 real ``img.png`` file in the current source directory or a ``img.png.md5``
 file containing its MD5 sum.
 
+Multiple content links of the same name with different hash algorithms
+are supported (e.g. ``img.png.sha256`` and ``img.png.sha1``) so long as
+they all correspond to the same real file.  This allows objects to be
+fetched from sources indexed by different hash algorithms.
+
 Referencing File Series
 """""""""""""""""""""""
 
@@ -274,6 +279,10 @@ The following hash algorithms are supported::
  SHA256      .sha256   US Secure Hash Algorithms, RFC 4634
  SHA384      .sha384   US Secure Hash Algorithms, RFC 4634
  SHA512      .sha512   US Secure Hash Algorithms, RFC 4634
+ SHA3_224    .sha3-224 Keccak SHA-3
+ SHA3_256    .sha3-256 Keccak SHA-3
+ SHA3_384    .sha3-384 Keccak SHA-3
+ SHA3_512    .sha3-512 Keccak SHA-3
 
 Note that the hashes are used only for unique data identification and
 download verification.
@@ -429,8 +438,10 @@ function(ExternalData_add_target target)
     string(REPLACE "|" ";" tuple "${entry}")
     list(GET tuple 0 file)
     list(GET tuple 1 name)
-    list(GET tuple 2 ext)
-    set(stamp "${ext}-stamp")
+    list(GET tuple 2 exts)
+    string(REPLACE "+" ";" exts_list "${exts}")
+    list(GET exts_list 0 first_ext)
+    set(stamp "-hash-stamp")
     if(NOT DEFINED "_ExternalData_FILE_${file}")
       set("_ExternalData_FILE_${file}" 1)
       get_property(added DIRECTORY PROPERTY "_ExternalData_FILE_${file}")
@@ -446,12 +457,12 @@ function(ExternalData_add_target target)
           OUTPUT "${file}${stamp}" "${file}"
           # Run the data fetch/update script.
           COMMAND ${CMAKE_COMMAND} -Drelative_top=${CMAKE_BINARY_DIR}
-                                   -Dfile=${file} -Dname=${name} -Dext=${ext}
+                                   -Dfile=${file} -Dname=${name} -Dexts=${exts}
                                    -DExternalData_ACTION=fetch
                                    -DExternalData_CONFIG=${config}
                                    -P ${_ExternalData_SELF}
           # Update whenever the object hash changes.
-          MAIN_DEPENDENCY "${name}${ext}"
+          MAIN_DEPENDENCY "${name}${first_ext}"
           )
       endif()
       list(APPEND files "${file}${stamp}")
@@ -501,8 +512,8 @@ endfunction()
 #-----------------------------------------------------------------------------
 # Private helper interface
 
-set(_ExternalData_REGEX_ALGO "MD5|SHA1|SHA224|SHA256|SHA384|SHA512")
-set(_ExternalData_REGEX_EXT "md5|sha1|sha224|sha256|sha384|sha512")
+set(_ExternalData_REGEX_ALGO "MD5|SHA1|SHA224|SHA256|SHA384|SHA512|SHA3_224|SHA3_256|SHA3_384|SHA3_512")
+set(_ExternalData_REGEX_EXT "md5|sha1|sha224|sha256|sha384|sha512|sha3-224|sha3-256|sha3-384|sha3-512")
 set(_ExternalData_SELF "${CMAKE_CURRENT_LIST_FILE}")
 get_filename_component(_ExternalData_SELF_DIR "${_ExternalData_SELF}" PATH)
 
@@ -798,6 +809,7 @@ function(_ExternalData_arg_find_files glob pattern regex)
   cmake_policy(SET CMP0009 NEW)
   file(${glob} globbed RELATIVE "${top_src}" "${top_src}/${pattern}*")
   cmake_policy(POP)
+  set(externals_count -1)
   foreach(entry IN LISTS globbed)
     if("x${entry}" MATCHES "^x(.*)(\\.(${_ExternalData_REGEX_EXT}))$")
       set(relname "${CMAKE_MATCH_1}")
@@ -817,7 +829,11 @@ function(_ExternalData_arg_find_files glob pattern regex)
         set(name "${top_src}/${relname}")
         set(file "${top_bin}/${relname}")
         if(alg)
-          list(APPEND external "${file}|${name}|${alg}")
+          if(NOT "${external_${externals_count}_file_name}" STREQUAL "${file}|${name}")
+            math(EXPR externals_count "${externals_count} + 1")
+            set(external_${externals_count}_file_name "${file}|${name}")
+          endif()
+          list(APPEND external_${externals_count}_algs "${alg}")
         elseif(ExternalData_LINK_CONTENT)
           _ExternalData_link_content("${name}" alg)
           list(APPEND external "${file}|${name}|${alg}")
@@ -830,6 +846,14 @@ function(_ExternalData_arg_find_files glob pattern regex)
       endif()
     endif()
   endforeach()
+  if(${externals_count} GREATER -1)
+    foreach(ii RANGE ${externals_count})
+      string(REPLACE ";" "+" algs_delim "${external_${ii}_algs}")
+      list(APPEND external "${external_${ii}_file_name}|${algs_delim}")
+      unset(external_${ii}_algs)
+      unset(external_${ii}_file_name)
+    endforeach()
+  endif()
   set(external "${external}" PARENT_SCOPE)
   set(internal "${internal}" PARENT_SCOPE)
   set(have_original "${have_original}" PARENT_SCOPE)
@@ -947,13 +971,28 @@ function(_ExternalData_custom_fetch key loc file err_var msg_var)
   set("${msg_var}" "${msg}" PARENT_SCOPE)
 endfunction()
 
-function(_ExternalData_download_object name hash algo var_obj)
+function(_ExternalData_get_from_object_store hash algo var_obj var_success)
+  # Search all object stores for an existing object.
+  foreach(dir ${ExternalData_OBJECT_STORES})
+    set(obj "${dir}/${algo}/${hash}")
+    if(EXISTS "${obj}")
+      message(STATUS "Found object: \"${obj}\"")
+      set("${var_obj}" "${obj}" PARENT_SCOPE)
+      set("${var_success}" 1 PARENT_SCOPE)
+      return()
+    endif()
+  endforeach()
+endfunction()
+
+function(_ExternalData_download_object name hash algo var_obj var_success var_errorMsg)
   # Search all object stores for an existing object.
+  set(success 1)
   foreach(dir ${ExternalData_OBJECT_STORES})
     set(obj "${dir}/${algo}/${hash}")
     if(EXISTS "${obj}")
       message(STATUS "Found object: \"${obj}\"")
       set("${var_obj}" "${obj}" PARENT_SCOPE)
+      set("${var_success}" "${success}" PARENT_SCOPE)
       return()
     endif()
   endforeach()
@@ -1008,6 +1047,7 @@ function(_ExternalData_download_object name hash algo var_obj)
   get_filename_component(dir "${name}" PATH)
   set(staged "${dir}/.ExternalData_${algo}_${hash}")
 
+  set(success 1)
   if(found)
     file(RENAME "${tmp}" "${obj}")
     message(STATUS "Downloaded object: \"${obj}\"")
@@ -1018,38 +1058,75 @@ function(_ExternalData_download_object name hash algo var_obj)
     if(NOT tried)
       set(tried "\n  (No ExternalData_URL_TEMPLATES given)")
     endif()
-    message(FATAL_ERROR "Object ${algo}=${hash} not found at:${tried}")
+    set(success 0)
+    set("${var_errorMsg}" "Object ${algo}=${hash} not found at:${tried}" PARENT_SCOPE)
   endif()
 
   set("${var_obj}" "${obj}" PARENT_SCOPE)
+  set("${var_success}" "${success}" PARENT_SCOPE)
 endfunction()
 
 if("${ExternalData_ACTION}" STREQUAL "fetch")
-  foreach(v ExternalData_OBJECT_STORES file name ext)
+  foreach(v ExternalData_OBJECT_STORES file name exts)
     if(NOT DEFINED "${v}")
       message(FATAL_ERROR "No \"-D${v}=\" value provided!")
     endif()
   endforeach()
 
-  file(READ "${name}${ext}" hash)
-  string(STRIP "${hash}" hash)
-
-  if("${ext}" MATCHES "^\\.(${_ExternalData_REGEX_EXT})$")
-    string(TOUPPER "${CMAKE_MATCH_1}" algo)
-  else()
-    message(FATAL_ERROR "Unknown hash algorithm extension \"${ext}\"")
-  endif()
+  string(REPLACE "+" ";" exts_list "${exts}")
+  set(succeeded 0)
+  set(errorMsg "")
+  set(hash_list )
+  set(algo_list )
+  set(hash )
+  set(algo )
+  foreach(ext ${exts_list})
+    file(READ "${name}${ext}" hash)
+    string(STRIP "${hash}" hash)
+
+    if("${ext}" MATCHES "^\\.(${_ExternalData_REGEX_EXT})$")
+      string(TOUPPER "${CMAKE_MATCH_1}" algo)
+      string(REPLACE "-" "_" algo "${algo}")
+    else()
+      message(FATAL_ERROR "Unknown hash algorithm extension \"${ext}\"")
+    endif()
 
-  _ExternalData_download_object("${name}" "${hash}" "${algo}" obj)
+    list(APPEND hash_list ${hash})
+    list(APPEND algo_list ${algo})
+  endforeach()
 
+  list(LENGTH exts_list num_extensions)
+  math(EXPR exts_range "${num_extensions} - 1")
+  foreach(ii RANGE 0 ${exts_range})
+    list(GET hash_list ${ii} hash)
+    list(GET algo_list ${ii} algo)
+    _ExternalData_get_from_object_store("${hash}" "${algo}" obj succeeded)
+    if(succeeded)
+      break()
+    endif()
+  endforeach()
+  if(NOT succeeded)
+    foreach(ii RANGE 0 ${exts_range})
+      list(GET hash_list ${ii} hash)
+      list(GET algo_list ${ii} algo)
+      _ExternalData_download_object("${name}" "${hash}" "${algo}"
+        obj succeeded algoErrorMsg)
+      set(errorMsg "${errorMsg}\n${algoErrorMsg}")
+      if(succeeded)
+        break()
+      endif()
+    endforeach()
+  endif()
+  if(NOT succeeded)
+    message(FATAL_ERROR "${errorMsg}")
+  endif()
   # Check if file already corresponds to the object.
-  set(stamp "${ext}-stamp")
+  set(stamp "-hash-stamp")
   set(file_up_to_date 0)
   if(EXISTS "${file}" AND EXISTS "${file}${stamp}")
     file(READ "${file}${stamp}" f_hash)
     string(STRIP "${f_hash}" f_hash)
     if("${f_hash}" STREQUAL "${hash}")
-      #message(STATUS "File already corresponds to object")
       set(file_up_to_date 1)
     endif()
   endif()
diff --git a/Modules/ExternalProject.cmake b/Modules/ExternalProject.cmake
index 4551cc8..b42d2dd 100644
--- a/Modules/ExternalProject.cmake
+++ b/Modules/ExternalProject.cmake
@@ -65,9 +65,18 @@ Create custom targets to build projects in external trees
   ``GIT_SUBMODULES <module>...``
     Git submodules that shall be updated, all if empty
   ``GIT_SHALLOW 1``
-    Tell Git to clone with ``--depth 1``.   Use when ``GIT_TAG`` is not
+    Tell Git to clone with ``--depth 1``.  Use when ``GIT_TAG`` is not
     specified or when it names a branch in order to download only the
     tip of the branch without the rest of its history.
+  ``GIT_PROGRESS 1``
+    Tell Git to clone with ``--progress``.  For large projects, the clone step
+    does not output anything which can make the build appear to have stalled.
+    This option forces Git to output progress information during the clone step
+    so that forward progress is indicated.
+  ``GIT_CONFIG <option>...``
+    Tell Git to clone with ``--config <option>``.  Use additional configuration
+    parameters when cloning the project (``key=value`` as expected by ``git
+    config``).
   ``HG_REPOSITORY <url>``
     URL of mercurial repo
   ``HG_TAG <tag>``
@@ -165,9 +174,16 @@ Create custom targets to build projects in external trees
   Install step options are:
 
   ``INSTALL_DIR <dir>``
-    Installation prefix
+    Installation prefix to be placed in the ``<INSTALL_DIR>`` placeholder.
+    This does not actually configure the external project to install to
+    the given prefix.  That must be done by passing appropriate arguments
+    to the external project configuration step, e.g. using ``<INSTALL_DIR>``.
   ``INSTALL_COMMAND <cmd>...``
-    Command to drive install after build
+    Command to drive installation of the external project after it has been
+    built.  This only happens at the *build* time of the calling project.
+    In order to install files from the external project alongside the
+    locally-built files, a separate local :command:`install` call must be
+    added to pick the files up from one of the external project trees.
 
   Test step options are:
 
@@ -418,7 +434,7 @@ if(_ep_func)
 endif()
 
 # Save regex matching supported hash algorithm names.
-set(_ep_hash_algos "MD5|SHA1|SHA224|SHA256|SHA384|SHA512")
+set(_ep_hash_algos "MD5|SHA1|SHA224|SHA256|SHA384|SHA512|SHA3_224|SHA3_256|SHA3_384|SHA3_512")
 set(_ep_hash_regex "^(${_ep_hash_algos})=([0-9A-Fa-f]+)$")
 
 set(_ExternalProject_SELF "${CMAKE_CURRENT_LIST_FILE}")
@@ -509,7 +525,7 @@ define_property(DIRECTORY PROPERTY "EP_UPDATE_DISCONNECTED" INHERITED
   "ExternalProject module."
   )
 
-function(_ep_write_gitclone_script script_filename source_dir git_EXECUTABLE git_repository git_tag git_remote_name git_submodules git_shallow src_name work_dir gitclone_infofile gitclone_stampfile tls_verify)
+function(_ep_write_gitclone_script script_filename source_dir git_EXECUTABLE git_repository git_tag git_remote_name git_submodules git_shallow git_progress git_config src_name work_dir gitclone_infofile gitclone_stampfile tls_verify)
   if(NOT GIT_VERSION_STRING VERSION_LESS 1.7.10)
     set(git_clone_shallow_options "--depth 1 --no-single-branch")
   else()
@@ -555,6 +571,16 @@ if(git_shallow)
   list(APPEND git_clone_options ${git_clone_shallow_options})
 endif()
 
+set(git_progress \"${git_progress}\")
+if(git_progress)
+  list(APPEND git_clone_options --progress)
+endif()
+
+set(git_config \"${git_config}\")
+foreach(config IN LISTS git_config)
+  list(APPEND git_clone_options --config \${config})
+endforeach()
+
 # try the clone 3 times incase there is an odd git clone issue
 set(error_code 1)
 set(number_of_tries 0)
@@ -574,6 +600,9 @@ if(error_code)
   message(FATAL_ERROR \"Failed to clone repository: '${git_repository}'\")
 endif()
 
+# Use `git checkout <branch>` even though this risks ambiguity with a
+# local path.  Unfortunately we cannot use `git checkout <tree-ish> --`
+# because that will not search for remote branch names, a common use case.
 execute_process(
   COMMAND \"${git_EXECUTABLE}\" \${git_options} checkout ${git_tag}
   WORKING_DIRECTORY \"${work_dir}/${src_name}\"
@@ -870,7 +899,7 @@ function(_ep_write_downloadfile_script script_filename REMOTE LOCAL timeout no_p
 
   if("${hash}" MATCHES "${_ep_hash_regex}")
     set(ALGO "${CMAKE_MATCH_1}")
-    set(EXPECT_VALUE "${CMAKE_MATCH_2}")
+    string(TOLOWER "${CMAKE_MATCH_2}" EXPECT_VALUE)
   else()
     set(ALGO "")
     set(EXPECT_VALUE "")
@@ -1180,6 +1209,7 @@ function(_ep_write_initial_cache target_name script_filename script_initial_cach
   # Write out values into an initial cache, that will be passed to CMake with -C
   # Replace location tags.
   _ep_replace_location_tags(${target_name} script_initial_cache)
+  _ep_replace_location_tags(${target_name} script_filename)
   # Write out the initial cache file to the location specified.
   file(GENERATE OUTPUT "${script_filename}" CONTENT "${script_initial_cache}")
 endfunction()
@@ -1225,87 +1255,84 @@ endfunction()
 
 
 function(_ep_get_build_command name step cmd_var)
-  set(cmd "${${cmd_var}}")
-  if(NOT cmd)
-    set(args)
-    _ep_get_configure_command_id(${name} cfg_cmd_id)
-    if(cfg_cmd_id STREQUAL "cmake")
-      # CMake project.  Select build command based on generator.
-      get_target_property(cmake_generator ${name} _EP_CMAKE_GENERATOR)
-      if("${CMAKE_GENERATOR}" MATCHES "Make" AND
-         ("${cmake_generator}" MATCHES "Make" OR NOT cmake_generator))
-        # The project uses the same Makefile generator.  Use recursive make.
-        set(cmd "$(MAKE)")
-        if(step STREQUAL "INSTALL")
-          set(args install)
-        endif()
-        if("x${step}x" STREQUAL "xTESTx")
-          set(args test)
-        endif()
-      else()
-        # Drive the project with "cmake --build".
-        get_target_property(cmake_command ${name} _EP_CMAKE_COMMAND)
-        if(cmake_command)
-          set(cmd "${cmake_command}")
-        else()
-          set(cmd "${CMAKE_COMMAND}")
-        endif()
-        set(args --build ".")
-        if(CMAKE_CONFIGURATION_TYPES)
-          if (CMAKE_CFG_INTDIR AND
-              NOT CMAKE_CFG_INTDIR STREQUAL "." AND
-              NOT CMAKE_CFG_INTDIR MATCHES "\\$")
-            # CMake 3.4 and below used the CMAKE_CFG_INTDIR placeholder value
-            # provided by multi-configuration generators.  Some projects were
-            # taking advantage of that undocumented implementation detail to
-            # specify a specific configuration here.  They should use
-            # BUILD_COMMAND to change the default command instead, but for
-            # compatibility honor the value.
-            set(config ${CMAKE_CFG_INTDIR})
-            message(AUTHOR_WARNING "CMAKE_CFG_INTDIR should not be set by project code.\n"
-              "To get a non-default build command, use the BUILD_COMMAND option.")
-          else()
-            set(config $<CONFIG>)
-          endif()
-          list(APPEND args --config ${config})
-        endif()
-        if(step STREQUAL "INSTALL")
-          list(APPEND args --target install)
-        endif()
-        # But for "TEST" drive the project with corresponding "ctest".
-        if("x${step}x" STREQUAL "xTESTx")
-          string(REGEX REPLACE "^(.*/)cmake([^/]*)$" "\\1ctest\\2" cmd "${cmd}")
-          set(args "")
-          if(CMAKE_CONFIGURATION_TYPES)
-            list(APPEND args -C ${config})
-          endif()
-        endif()
+  set(cmd "")
+  set(args)
+  _ep_get_configure_command_id(${name} cfg_cmd_id)
+  if(cfg_cmd_id STREQUAL "cmake")
+    # CMake project.  Select build command based on generator.
+    get_target_property(cmake_generator ${name} _EP_CMAKE_GENERATOR)
+    if("${CMAKE_GENERATOR}" MATCHES "Make" AND
+       ("${cmake_generator}" MATCHES "Make" OR NOT cmake_generator))
+      # The project uses the same Makefile generator.  Use recursive make.
+      set(cmd "$(MAKE)")
+      if(step STREQUAL "INSTALL")
+        set(args install)
+      endif()
+      if("x${step}x" STREQUAL "xTESTx")
+        set(args test)
       endif()
     else()
-      # Non-CMake project.  Guess "make" and "make install" and "make test".
-      if("${CMAKE_GENERATOR}" MATCHES "Makefiles")
-        # Try to get the parallel arguments
-        set(cmd "$(MAKE)")
+      # Drive the project with "cmake --build".
+      get_target_property(cmake_command ${name} _EP_CMAKE_COMMAND)
+      if(cmake_command)
+        set(cmd "${cmake_command}")
       else()
-        set(cmd "make")
+        set(cmd "${CMAKE_COMMAND}")
+      endif()
+      set(args --build ".")
+      if(CMAKE_CONFIGURATION_TYPES)
+        if (CMAKE_CFG_INTDIR AND
+            NOT CMAKE_CFG_INTDIR STREQUAL "." AND
+            NOT CMAKE_CFG_INTDIR MATCHES "\\$")
+          # CMake 3.4 and below used the CMAKE_CFG_INTDIR placeholder value
+          # provided by multi-configuration generators.  Some projects were
+          # taking advantage of that undocumented implementation detail to
+          # specify a specific configuration here.  They should use
+          # BUILD_COMMAND to change the default command instead, but for
+          # compatibility honor the value.
+          set(config ${CMAKE_CFG_INTDIR})
+          message(AUTHOR_WARNING "CMAKE_CFG_INTDIR should not be set by project code.\n"
+            "To get a non-default build command, use the BUILD_COMMAND option.")
+        else()
+          set(config $<CONFIG>)
+        endif()
+        list(APPEND args --config ${config})
       endif()
       if(step STREQUAL "INSTALL")
-        set(args install)
+        list(APPEND args --target install)
       endif()
+      # But for "TEST" drive the project with corresponding "ctest".
       if("x${step}x" STREQUAL "xTESTx")
-        set(args test)
+        string(REGEX REPLACE "^(.*/)cmake([^/]*)$" "\\1ctest\\2" cmd "${cmd}")
+        set(args "")
+        if(CMAKE_CONFIGURATION_TYPES)
+          list(APPEND args -C ${config})
+        endif()
       endif()
     endif()
-
-    # Use user-specified arguments instead of default arguments, if any.
-    get_property(have_args TARGET ${name} PROPERTY _EP_${step}_ARGS SET)
-    if(have_args)
-      get_target_property(args ${name} _EP_${step}_ARGS)
+  else()
+    # Non-CMake project.  Guess "make" and "make install" and "make test".
+    if("${CMAKE_GENERATOR}" MATCHES "Makefiles")
+      # Try to get the parallel arguments
+      set(cmd "$(MAKE)")
+    else()
+      set(cmd "make")
     endif()
+    if(step STREQUAL "INSTALL")
+      set(args install)
+    endif()
+    if("x${step}x" STREQUAL "xTESTx")
+      set(args test)
+    endif()
+  endif()
 
-    list(APPEND cmd ${args})
+  # Use user-specified arguments instead of default arguments, if any.
+  get_property(have_args TARGET ${name} PROPERTY _EP_${step}_ARGS SET)
+  if(have_args)
+    get_target_property(args ${name} _EP_${step}_ARGS)
   endif()
 
+  list(APPEND cmd ${args})
   set(${cmd_var} "${cmd}" PARENT_SCOPE)
 endfunction()
 
@@ -1800,6 +1827,8 @@ function(_ep_add_download_command name)
       set(tls_verify "${CMAKE_TLS_VERIFY}")
     endif()
     get_property(git_shallow TARGET ${name} PROPERTY _EP_GIT_SHALLOW)
+    get_property(git_progress TARGET ${name} PROPERTY _EP_GIT_PROGRESS)
+    get_property(git_config TARGET ${name} PROPERTY _EP_GIT_CONFIG)
 
     # For the download step, and the git clone operation, only the repository
     # should be recorded in a configured RepositoryInfo file. If the repo
@@ -1824,7 +1853,7 @@ function(_ep_add_download_command name)
     # The script will delete the source directory and then call git clone.
     #
     _ep_write_gitclone_script(${tmp_dir}/${name}-gitclone.cmake ${source_dir}
-      ${GIT_EXECUTABLE} ${git_repository} ${git_tag} ${git_remote_name} "${git_submodules}" "${git_shallow}" ${src_name} ${work_dir}
+      ${GIT_EXECUTABLE} ${git_repository} ${git_tag} ${git_remote_name} "${git_submodules}" "${git_shallow}" "${git_progress}" "${git_config}" ${src_name} ${work_dir}
       ${stamp_dir}/${name}-gitinfo.txt ${stamp_dir}/${name}-gitclone-lastrun.txt "${tls_verify}"
       )
     set(comment "Performing download step (git clone) for '${name}'")
@@ -2143,12 +2172,12 @@ Update to Mercurial >= 2.1.1.
     ${uses_terminal}
     )
 
-  if(always AND update_disconnected)
+  if(update_disconnected)
     _ep_get_step_stampfile(${name} skip-update skip-update_stamp_file)
     string(REPLACE "Performing" "Skipping" comment "${comment}")
     ExternalProject_Add_Step(${name} skip-update
       COMMENT ${comment}
-      ALWAYS 1
+      ALWAYS ${always}
       EXCLUDE_FROM_MAIN 1
       WORKING_DIRECTORY ${work_dir}
       DEPENDEES download
@@ -2181,24 +2210,7 @@ function(_ep_add_patch_command name)
 endfunction()
 
 
-# TODO: Make sure external projects use the proper compiler
-function(_ep_add_configure_command name)
-  ExternalProject_Get_Property(${name} source_dir source_subdir binary_dir tmp_dir)
-
-  # Depend on other external projects (file-level).
-  set(file_deps)
-  get_property(deps TARGET ${name} PROPERTY _EP_DEPENDS)
-  foreach(dep IN LISTS deps)
-    get_property(dep_type TARGET ${dep} PROPERTY TYPE)
-    if(dep_type STREQUAL "UTILITY")
-      get_property(is_ep TARGET ${dep} PROPERTY _EP_IS_EXTERNAL_PROJECT)
-      if(is_ep)
-        _ep_get_step_stampfile(${dep} "done" done_stamp_file)
-        list(APPEND file_deps ${done_stamp_file})
-      endif()
-    endif()
-  endforeach()
-
+function(_ep_extract_configure_command var name)
   get_property(cmd_set TARGET ${name} PROPERTY _EP_CONFIGURE_COMMAND SET)
   if(cmd_set)
     get_property(cmd TARGET ${name} PROPERTY _EP_CONFIGURE_COMMAND)
@@ -2219,7 +2231,7 @@ function(_ep_add_configure_command name)
     get_property(cmake_cache_default_args TARGET ${name} PROPERTY _EP_CMAKE_CACHE_DEFAULT_ARGS)
 
     if(cmake_cache_args OR cmake_cache_default_args)
-      set(_ep_cache_args_script "${tmp_dir}/${name}-cache-$<CONFIG>.cmake")
+      set(_ep_cache_args_script "<TMP_DIR>/${name}-cache-$<CONFIG>.cmake")
       if(cmake_cache_args)
         _ep_command_line_to_initial_cache(script_initial_cache_force "${cmake_cache_args}" 1)
       endif()
@@ -2261,9 +2273,32 @@ function(_ep_add_configure_command name)
       endif()
     endif()
 
-    list(APPEND cmd "${source_dir}${source_subdir}")
+    list(APPEND cmd "<SOURCE_DIR><SOURCE_SUBDIR>")
   endif()
 
+  set("${var}" "${cmd}" PARENT_SCOPE)
+endfunction()
+
+# TODO: Make sure external projects use the proper compiler
+function(_ep_add_configure_command name)
+  ExternalProject_Get_Property(${name} binary_dir tmp_dir)
+
+  # Depend on other external projects (file-level).
+  set(file_deps)
+  get_property(deps TARGET ${name} PROPERTY _EP_DEPENDS)
+  foreach(dep IN LISTS deps)
+    get_property(dep_type TARGET ${dep} PROPERTY TYPE)
+    if(dep_type STREQUAL "UTILITY")
+      get_property(is_ep TARGET ${dep} PROPERTY _EP_IS_EXTERNAL_PROJECT)
+      if(is_ep)
+        _ep_get_step_stampfile(${dep} "done" done_stamp_file)
+        list(APPEND file_deps ${done_stamp_file})
+      endif()
+    endif()
+  endforeach()
+
+  _ep_extract_configure_command(cmd ${name})
+
   # If anything about the configure command changes, (command itself, cmake
   # used, cmake args or cmake generator) then re-run the configure step.
   # Fixes issue https://gitlab.kitware.com/cmake/cmake/issues/10258
diff --git a/Modules/FeatureSummary.cmake b/Modules/FeatureSummary.cmake
index 88bc1c8..f29a5f0 100644
--- a/Modules/FeatureSummary.cmake
+++ b/Modules/FeatureSummary.cmake
@@ -14,33 +14,93 @@ packages and/or feature for a build tree such as::
     LibXml2 (required version >= 2.4), XML processing lib, <http://xmlsoft.org>
        * Enables HTML-import in MyWordProcessor
        * Enables odt-export in MyWordProcessor
-    PNG , A PNG image library. , <http://www.libpng.org/pub/png/>
+    PNG, A PNG image library., <http://www.libpng.org/pub/png/>
        * Enables saving screenshots
     -- The following OPTIONAL packages have not been found:
-    Lua51 , The Lua scripting language. , <http://www.lua.org>
+    Lua51, The Lua scripting language., <http://www.lua.org>
        * Enables macros in MyWordProcessor
-    Foo , Foo provides cool stuff.
+    Foo, Foo provides cool stuff.
+
+Global Properties
+^^^^^^^^^^^^^^^^^
+
+.. variable:: FeatureSummary_PKG_TYPES
+
+The global property :variable:`FeatureSummary_PKG_TYPES` defines the type of
+packages used by `FeatureSummary`.
+
+The order in this list is important, the first package type in the list is the
+least important, the last is the most important. the of a package can only be
+changed to higher types.
+
+The default package types are , ``RUNTIME``, ``OPTIONAL``, ``RECOMMENDED`` and
+``REQUIRED``, and their importance is
+``RUNTIME < OPTIONAL < RECOMMENDED < REQUIRED``.
+
+
+.. variable:: FeatureSummary_REQUIRED_PKG_TYPES
+
+The global property :variable:`FeatureSummary_REQUIRED_PKG_TYPES` defines which
+package types are required.
+
+If one or more package in this categories has not been found, CMake will abort
+when calling :command:`feature_summary` with the
+'FATAL_ON_MISSING_REQUIRED_PACKAGES' option enabled.
+
+The default value for this global property is ``REQUIRED``.
+
+
+.. variable:: FeatureSummary_DEFAULT_PKG_TYPE
+
+The global property :variable:`FeatureSummary_DEFAULT_PKG_TYPE` defines which
+package type is the default one.
+When calling :command:`feature_summary`, if the user did not set the package type
+explicitly, the package will be assigned to this category.
+
+This value must be one of the types defined in the
+:variable:`FeatureSummary_PKG_TYPES` global property unless the package type
+is set for all the packages.
+
+The default value for this global property is ``OPTIONAL``.
+
+#]=======================================================================]
+
+get_property(_fsPkgTypeIsSet GLOBAL PROPERTY FeatureSummary_PKG_TYPES SET)
+if(NOT _fsPkgTypeIsSet)
+  set_property(GLOBAL PROPERTY FeatureSummary_PKG_TYPES RUNTIME OPTIONAL RECOMMENDED REQUIRED)
+endif()
+
+get_property(_fsReqPkgTypesIsSet GLOBAL PROPERTY FeatureSummary_REQUIRED_PKG_TYPES SET)
+if(NOT _fsReqPkgTypesIsSet)
+  set_property(GLOBAL PROPERTY FeatureSummary_REQUIRED_PKG_TYPES REQUIRED)
+endif()
+
+get_property(_fsDefaultPkgTypeIsSet GLOBAL PROPERTY FeatureSummary_DEFAULT_PKG_TYPE SET)
+if(NOT _fsDefaultPkgTypeIsSet)
+  set_property(GLOBAL PROPERTY FeatureSummary_DEFAULT_PKG_TYPE OPTIONAL)
+endif()
+
+#[=======================================================================[.rst:
 
 Functions
 ^^^^^^^^^
 
 #]=======================================================================]
 
-include("${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake")
-
+include(CMakeParseArguments)
 
 function(_FS_GET_FEATURE_SUMMARY _property _var _includeQuiet)
 
+  get_property(_fsPkgTypes GLOBAL PROPERTY FeatureSummary_PKG_TYPES)
+  get_property(_fsDefaultPkgType GLOBAL PROPERTY FeatureSummary_DEFAULT_PKG_TYPE)
+
   set(_type "ANY")
-  if("${_property}" MATCHES "REQUIRED_")
-    set(_type "REQUIRED")
-  elseif("${_property}" MATCHES "RECOMMENDED_")
-    set(_type "RECOMMENDED")
-  elseif("${_property}" MATCHES "RUNTIME_")
-    set(_type "RUNTIME")
-  elseif("${_property}" MATCHES "OPTIONAL_")
-    set(_type "OPTIONAL")
-  endif()
+  foreach(_fsPkgType ${_fsPkgTypes})
+    if("${_property}" MATCHES "${_fsPkgType}_PACKAGES_(NOT_)?FOUND")
+      set(_type "${_fsPkgType}")
+      break()
+    endif()
+  endforeach()
 
   if("${_property}" MATCHES "PACKAGES_FOUND")
     set(_property "PACKAGES_FOUND")
@@ -60,15 +120,30 @@ function(_FS_GET_FEATURE_SUMMARY _property _var _includeQuiet)
     # does this package belong to the type we currently want to list ?
     get_property(_currentType  GLOBAL PROPERTY _CMAKE_${_currentFeature}_TYPE)
     if(NOT _currentType)
-      set(_currentType OPTIONAL)
+      list(FIND _fsPkgTypes "${_fsDefaultPkgType}" _defaultInPkgTypes)
+      if("${_defaultInPkgTypes}" STREQUAL "-1")
+        string(REGEX REPLACE ";([^;]+)$" " and \\1" _fsPkgTypes_msg "${_fsPkgTypes}")
+        string(REPLACE ";" ", " _fsPkgTypes_msg "${_fsPkgTypes_msg}")
+        message(FATAL_ERROR "Bad package property type ${_fsDefaultPkgType} used in global property FeatureSummary_DEFAULT_PKG_TYPE. "
+                            "Valid types are ${_fsPkgTypes_msg}. "
+                            "Either update FeatureSummary_DEFAULT_PKG_TYPE or add ${_fsDefaultPkgType} to the FeatureSummary_PKG_TYPES global property.")
+      endif()
+      set(_currentType ${_fsDefaultPkgType})
     endif()
 
     if("${_type}" STREQUAL ANY  OR  "${_type}" STREQUAL "${_currentType}")
-
       # check whether the current feature/package should be in the output depending on whether it was QUIET or not
       set(includeThisOne TRUE)
+      set(_required FALSE)
       # skip QUIET packages, except if they are REQUIRED or INCLUDE_QUIET_PACKAGES has been set
-      if((NOT "${_currentType}" STREQUAL "REQUIRED") AND NOT _includeQuiet)
+      get_property(_fsReqPkgTypes GLOBAL PROPERTY FeatureSummary_REQUIRED_PKG_TYPES)
+      foreach(_fsReqPkgType ${_fsReqPkgTypes})
+        if("${_currentType}" STREQUAL "${_fsReqPkgType}")
+          set(_required TRUE)
+          break()
+        endif()
+      endforeach()
+      if(NOT _required AND NOT _includeQuiet)
         get_property(_isQuiet  GLOBAL PROPERTY _CMAKE_${_currentFeature}_QUIET)
         if(_isQuiet)
           set(includeThisOne FALSE)
@@ -90,11 +165,11 @@ function(_FS_GET_FEATURE_SUMMARY _property _var _includeQuiet)
         endif()
         get_property(_info  GLOBAL PROPERTY _CMAKE_${_currentFeature}_DESCRIPTION)
         if(_info)
-          string(APPEND _currentFeatureText " , ${_info}")
+          string(APPEND _currentFeatureText ", ${_info}")
         endif()
         get_property(_info  GLOBAL PROPERTY _CMAKE_${_currentFeature}_URL)
         if(_info)
-          string(APPEND _currentFeatureText " , <${_info}>")
+          string(APPEND _currentFeatureText ", <${_info}>")
         endif()
 
         get_property(_info  GLOBAL PROPERTY _CMAKE_${_currentFeature}_PURPOSE)
@@ -121,8 +196,11 @@ endfunction()
                      [VAR <variable_name>]
                      [INCLUDE_QUIET_PACKAGES]
                      [FATAL_ON_MISSING_REQUIRED_PACKAGES]
-                     [DESCRIPTION "Found packages:"]
-                     WHAT (ALL | PACKAGES_FOUND | PACKAGES_NOT_FOUND
+                     [DESCRIPTION "<description>"]
+                     [QUIET_ON_EMPTY]
+                     WHAT (ALL
+                          | PACKAGES_FOUND | PACKAGES_NOT_FOUND
+                          | <TYPE>_PACKAGES_FOUND | <TYPE>_PACKAGES_NOT_FOUND
                           | ENABLED_FEATURES | DISABLED_FEATURES)
                    )
 
@@ -146,22 +224,15 @@ endfunction()
    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
+
+  For each package type ``<TYPE>`` defined by the
+  :variable:`FeatureSummary_PKG_TYPES` global property, the following
+  information can also be used:
+
+  ``<TYPE>_PACKAGES_FOUND``
+   only those packages which have been found which have the type <TYPE>
+  ``<TYPE>_PACKAGES_NOT_FOUND``
+   only those packages which have not been found which have the type <TYPE>
 
   With the exception of the ``ALL`` value, these values can be combined
   in order to customize the output. For example:
@@ -176,11 +247,24 @@ endfunction()
   information is "printed" into the specified variable.  If ``FILENAME`` is
   not used, the information is printed to the terminal.  Using the
   ``DESCRIPTION`` option a description or headline can be set which will be
-  printed above the actual content.  If ``INCLUDE_QUIET_PACKAGES`` is given,
-  packages which have been searched with ``find_package(... QUIET)`` will
-  also be listed.  By default they are skipped.  If
-  ``FATAL_ON_MISSING_REQUIRED_PACKAGES`` is given, CMake will abort if a
-  package which is marked as ``REQUIRED`` has not been found.
+  printed above the actual content.
+  If ``INCLUDE_QUIET_PACKAGES`` is given, packages which have been searched with
+  ``find_package(... QUIET)`` will also be listed. By default they are skipped.
+  If ``FATAL_ON_MISSING_REQUIRED_PACKAGES`` is given, CMake will abort if a
+  package which is marked as one of the package types listed in the
+  :variable:`FeatureSummary_REQUIRED_PKG_TYPES` global property has not been
+  found.
+  The default value for the :variable:`FeatureSummary_REQUIRED_PKG_TYPES` global
+  property is ``REQUIRED``.
+
+  The :variable:`FeatureSummary_DEFAULT_PKG_TYPE` global property can be
+  modified to change the default package type assigned when not explicitly
+  assigned by the user.
+
+  If the ``QUIET_ON_EMPTY`` option is used, if only one type of package was
+  requested, and no packages belonging to that category were found, then no
+  output (including the ``DESCRIPTION``) is printed or added to the ``VAR``
+  variable.
 
   Example 1, append everything to a file:
 
@@ -201,11 +285,28 @@ endfunction()
                    DESCRIPTION "Enabled Features:"
                    VAR enabledFeaturesText)
    message(STATUS "${enabledFeaturesText}")
+
+  Example 3, change default package types and print only the categories that
+  are not empty:
+
+  .. code-block:: cmake
+
+   include(FeatureSummary)
+   set_property(GLOBAL APPEND PROPERTY FeatureSummary_PKG_TYPES BUILD)
+   find_package(FOO)
+   set_package_properties(FOO PROPERTIES TYPE BUILD)
+   feature_summary(WHAT BUILD_PACKAGES_FOUND
+                   Description "Build tools found:"
+                   QUIET_ON_EMPTY)
+   feature_summary(WHAT BUILD_PACKAGES_NOT_FOUND
+                   Description "Build tools not found:"
+                   QUIET_ON_EMPTY)
+
 #]=======================================================================]
 
 function(FEATURE_SUMMARY)
 # CMAKE_PARSE_ARGUMENTS(<prefix> <options> <one_value_keywords> <multi_value_keywords> args...)
-  set(options APPEND INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES)
+  set(options APPEND INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES QUIET_ON_EMPTY)
   set(oneValueArgs FILENAME VAR DESCRIPTION)
   set(multiValueArgs WHAT)
 
@@ -222,40 +323,42 @@ function(FEATURE_SUMMARY)
   set(validWhatParts "ENABLED_FEATURES"
                      "DISABLED_FEATURES"
                      "PACKAGES_FOUND"
-                     "PACKAGES_NOT_FOUND"
-                     "OPTIONAL_PACKAGES_FOUND"
-                     "OPTIONAL_PACKAGES_NOT_FOUND"
-                     "RECOMMENDED_PACKAGES_FOUND"
-                     "RECOMMENDED_PACKAGES_NOT_FOUND"
-                     "REQUIRED_PACKAGES_FOUND"
-                     "REQUIRED_PACKAGES_NOT_FOUND"
-                     "RUNTIME_PACKAGES_FOUND"
-                     "RUNTIME_PACKAGES_NOT_FOUND")
+                     "PACKAGES_NOT_FOUND")
+
+  get_property(_fsPkgTypes GLOBAL PROPERTY FeatureSummary_PKG_TYPES)
+  get_property(_fsReqPkgTypes GLOBAL PROPERTY FeatureSummary_REQUIRED_PKG_TYPES)
+  foreach(_fsPkgType ${_fsPkgTypes})
+    list(APPEND validWhatParts "${_fsPkgType}_PACKAGES_FOUND"
+                               "${_fsPkgType}_PACKAGES_NOT_FOUND")
+  endforeach()
 
   list(FIND validWhatParts "${_FS_WHAT}" indexInList)
   if(NOT "${indexInList}" STREQUAL "-1")
     _FS_GET_FEATURE_SUMMARY( ${_FS_WHAT} _featureSummary ${_FS_INCLUDE_QUIET_PACKAGES} )
-    set(_fullText "${_FS_DESCRIPTION}${_featureSummary}\n")
-    if (("${_FS_WHAT}" STREQUAL "REQUIRED_PACKAGES_NOT_FOUND") AND _featureSummary)
-      set(requiredPackagesNotFound TRUE)
+    if(_featureSummary OR NOT _FS_QUIET_ON_EMPTY)
+      set(_fullText "${_FS_DESCRIPTION}${_featureSummary}\n")
+    endif()
+
+    if(_featureSummary)
+      foreach(_fsReqPkgType ${_fsReqPkgTypes})
+        if("${_FS_WHAT}" STREQUAL "${_fsReqPkgType}_PACKAGES_NOT_FOUND")
+          set(requiredPackagesNotFound TRUE)
+          break()
+        endif()
+      endforeach()
     endif()
 
   else()
     if("${_FS_WHAT}" STREQUAL "ALL")
 
-      set(allWhatParts "ENABLED_FEATURES"
-                       "RUNTIME_PACKAGES_FOUND"
-                       "OPTIONAL_PACKAGES_FOUND"
-                       "RECOMMENDED_PACKAGES_FOUND"
-                       "REQUIRED_PACKAGES_FOUND"
-
-                       "DISABLED_FEATURES"
-                       "RUNTIME_PACKAGES_NOT_FOUND"
-                       "OPTIONAL_PACKAGES_NOT_FOUND"
-                       "RECOMMENDED_PACKAGES_NOT_FOUND"
-                       "REQUIRED_PACKAGES_NOT_FOUND"
-      )
-
+      set(allWhatParts "ENABLED_FEATURES")
+      foreach(_fsPkgType ${_fsPkgTypes})
+        list(APPEND allWhatParts "${_fsPkgType}_PACKAGES_FOUND")
+      endforeach()
+      list(APPEND allWhatParts "DISABLED_FEATURES")
+      foreach(_fsPkgType ${_fsPkgTypes})
+        list(APPEND allWhatParts "${_fsPkgType}_PACKAGES_NOT_FOUND")
+      endforeach()
     else()
       set(allWhatParts)
       foreach(part ${_FS_WHAT})
@@ -276,45 +379,49 @@ function(FEATURE_SUMMARY)
     set(title_DISABLED_FEATURES              "The following features have been disabled:")
     set(title_PACKAGES_FOUND                 "The following packages have been found:")
     set(title_PACKAGES_NOT_FOUND             "The following packages have not been found:")
-    set(title_OPTIONAL_PACKAGES_FOUND        "The following OPTIONAL packages have been found:")
-    set(title_OPTIONAL_PACKAGES_NOT_FOUND    "The following OPTIONAL packages have not been found:")
-    set(title_RECOMMENDED_PACKAGES_FOUND     "The following RECOMMENDED packages have been found:")
-    set(title_RECOMMENDED_PACKAGES_NOT_FOUND "The following RECOMMENDED packages have not been found:")
-    set(title_REQUIRED_PACKAGES_FOUND        "The following REQUIRED packages have been found:")
-    set(title_REQUIRED_PACKAGES_NOT_FOUND    "The following REQUIRED packages have not been found:")
-    set(title_RUNTIME_PACKAGES_FOUND         "The following RUNTIME packages have been found:")
-    set(title_RUNTIME_PACKAGES_NOT_FOUND     "The following RUNTIME packages have not been found:")
+    foreach(_fsPkgType ${_fsPkgTypes})
+      set(title_${_fsPkgType}_PACKAGES_FOUND     "The following ${_fsPkgType} packages have been found:")
+      set(title_${_fsPkgType}_PACKAGES_NOT_FOUND "The following ${_fsPkgType} packages have not been found:")
+    endforeach()
 
     set(_fullText "${_FS_DESCRIPTION}")
     foreach(part ${allWhatParts})
       set(_tmp)
       _FS_GET_FEATURE_SUMMARY( ${part} _tmp ${_FS_INCLUDE_QUIET_PACKAGES})
       if(_tmp)
-        string(APPEND _fullText "\n-- ${title_${part}}\n${_tmp}\n")
-        if("${part}" STREQUAL "REQUIRED_PACKAGES_NOT_FOUND")
-          set(requiredPackagesNotFound TRUE)
+        if(_fullText)
+          string(APPEND _fullText "\n-- ")
         endif()
+        string(APPEND _fullText "${title_${part}}\n${_tmp}\n")
+        foreach(_fsReqPkgType ${_fsReqPkgTypes})
+          if("${part}" STREQUAL "${_fsReqPkgType}_PACKAGES_NOT_FOUND")
+            set(requiredPackagesNotFound TRUE)
+            break()
+          endif()
+        endforeach()
       endif()
     endforeach()
   endif()
 
-  if(_FS_FILENAME)
-    if(_FS_APPEND)
-      file(APPEND "${_FS_FILENAME}" "${_fullText}")
+  if(_fullText OR NOT _FS_QUIET_ON_EMPTY)
+    if(_FS_FILENAME)
+      if(_FS_APPEND)
+        file(APPEND "${_FS_FILENAME}" "${_fullText}")
+      else()
+        file(WRITE  "${_FS_FILENAME}" "${_fullText}")
+      endif()
+
     else()
-      file(WRITE  "${_FS_FILENAME}" "${_fullText}")
+      if(NOT _FS_VAR)
+        message(STATUS "${_fullText}")
+      endif()
     endif()
 
-  else()
-    if(NOT _FS_VAR)
-      message(STATUS "${_fullText}")
+    if(_FS_VAR)
+      set(${_FS_VAR} "${_fullText}" PARENT_SCOPE)
     endif()
   endif()
 
-  if(_FS_VAR)
-    set(${_FS_VAR} "${_fullText}" PARENT_SCOPE)
-  endif()
-
   if(requiredPackagesNotFound  AND  _FS_FATAL_ON_MISSING_REQUIRED_PACKAGES)
     message(FATAL_ERROR "feature_summary() Error: REQUIRED package(s) are missing, aborting CMake run.")
   endif()
@@ -365,7 +472,8 @@ endfunction()
     TYPEs (``RUNTIME < OPTIONAL < RECOMMENDED < REQUIRED``), lower TYPEs are
     ignored.  The ``TYPE`` property is project-specific, so it cannot be set
     by the Find-module, but must be set in the project.
-
+    Type accepted can be changed by setting the
+    :variable:`FeatureSummary_PKG_TYPES` global property.
 
   ``PURPOSE <purpose>``
     This describes which features this package enables in the
@@ -438,25 +546,28 @@ function(SET_PACKAGE_PROPERTIES _name _props)
     set_property(GLOBAL APPEND PROPERTY _CMAKE_${_name}_PURPOSE "${_SPP_PURPOSE}" )
   endif()
 
-  # handle the TYPE
-  if(NOT _SPP_TYPE)
-    set(_SPP_TYPE OPTIONAL)
-  endif()
+  get_property(_fsPkgTypes GLOBAL PROPERTY FeatureSummary_PKG_TYPES)
+  get_property(_fsDefaultPkgType GLOBAL PROPERTY FeatureSummary_DEFAULT_PKG_TYPE)
 
-  # List the supported types, according to their priority
-  set(validTypes "RUNTIME" "OPTIONAL" "RECOMMENDED" "REQUIRED" )
-  list(FIND validTypes ${_SPP_TYPE} _typeIndexInList)
-  if("${_typeIndexInList}" STREQUAL "-1" )
-    message(FATAL_ERROR "Bad package property type ${_SPP_TYPE} used in SET_PACKAGE_PROPERTIES(). "
-                        "Valid types are OPTIONAL, RECOMMENDED, REQUIRED and RUNTIME." )
-  endif()
+  # handle the TYPE
+  if(DEFINED _SPP_TYPE)
+    # Supported types are listed in FeatureSummary_PKG_TYPES according to their priority
+    get_property(_fsPkgTypes GLOBAL PROPERTY FeatureSummary_PKG_TYPES)
+    list(FIND _fsPkgTypes ${_SPP_TYPE} _typeIndexInList)
+    if("${_typeIndexInList}" STREQUAL "-1" )
+      string(REGEX REPLACE ";([^;]+)$" " and \\1" _fsPkgTypes_msg "${_fsPkgTypes}")
+      string(REPLACE ";" ", " _fsPkgTypes_msg "${_fsPkgTypes_msg}")
+      message(FATAL_ERROR "Bad package property type ${_SPP_TYPE} used in SET_PACKAGE_PROPERTIES(). "
+                          "Valid types are ${_fsPkgTypes_msg}." )
+    endif()
 
-  get_property(_previousType  GLOBAL PROPERTY _CMAKE_${_name}_TYPE)
-  list(FIND validTypes "${_previousType}" _prevTypeIndexInList)
+    get_property(_previousType  GLOBAL PROPERTY _CMAKE_${_name}_TYPE)
+    list(FIND _fsPkgTypes "${_previousType}" _prevTypeIndexInList)
 
-  # make sure a previously set TYPE is not overridden with a lower new TYPE:
-  if("${_typeIndexInList}" GREATER "${_prevTypeIndexInList}")
-    set_property(GLOBAL PROPERTY _CMAKE_${_name}_TYPE "${_SPP_TYPE}" )
+    # make sure a previously set TYPE is not overridden with a lower new TYPE:
+    if("${_typeIndexInList}" GREATER "${_prevTypeIndexInList}")
+      set_property(GLOBAL PROPERTY _CMAKE_${_name}_TYPE "${_SPP_TYPE}" )
+    endif()
   endif()
 
 endfunction()
@@ -469,7 +580,8 @@ endfunction()
     add_feature_info(<name> <enabled> <description>)
 
   Use this macro to add information about a feature with the given ``<name>``.
-  ``<enabled>`` contains whether this feature is enabled or not.
+  ``<enabled>`` contains whether this feature is enabled or not. It can be a
+  variable or a list of conditions.
   ``<description>`` is a text describing the feature.  The information can
   be displayed using ``feature_summary()`` for ``ENABLED_FEATURES`` and
   ``DISABLED_FEATURES`` respectively.
@@ -481,7 +593,16 @@ endfunction()
      option(WITH_FOO "Help for foo" ON)
      add_feature_info(Foo WITH_FOO "The Foo feature provides very cool stuff.")
 #]=======================================================================]
-function(ADD_FEATURE_INFO _name _enabled _desc)
+function(ADD_FEATURE_INFO _name _depends _desc)
+  set(_enabled 1)
+  foreach(_d ${_depends})
+    string(REGEX REPLACE " +" ";" _d "${_d}")
+    if(${_d})
+    else()
+      set(_enabled 0)
+      break()
+    endif()
+  endforeach()
   if (${_enabled})
     set_property(GLOBAL APPEND PROPERTY ENABLED_FEATURES "${_name}")
   else ()
@@ -514,6 +635,7 @@ CMake versions:
   can be set are added automatically by the ``find_package()`` command.
 #]=======================================================================]
 function(SET_PACKAGE_INFO _name _desc)
+  message(DEPRECATION "SET_PACKAGE_INFO is deprecated. Use SET_PACKAGE_PROPERTIES instead.")
   unset(_url)
   unset(_purpose)
   if(ARGC GREATER 2)
@@ -543,6 +665,7 @@ endfunction()
     set_package_info(<name> <description> <url>)
 #]=======================================================================]
 function(SET_FEATURE_INFO)
+  message(DEPRECATION "SET_FEATURE_INFO is deprecated. Use ADD_FEATURE_INFO instead.")
   SET_PACKAGE_INFO(${ARGN})
 endfunction()
 
@@ -560,6 +683,8 @@ endfunction()
     feature_summary(WHAT ENABLED_FEATURES DESCRIPTION "Enabled features:")
 #]=======================================================================]
 function(PRINT_ENABLED_FEATURES)
+  message(DEPRECATION "PRINT_ENABLED_FEATURES is deprecated. Use
+    feature_summary(WHAT ENABLED_FEATURES DESCRIPTION \"Enabled features:\")")
   FEATURE_SUMMARY(WHAT ENABLED_FEATURES  DESCRIPTION "Enabled features:")
 endfunction()
 
@@ -577,5 +702,7 @@ endfunction()
     feature_summary(WHAT DISABLED_FEATURES DESCRIPTION "Disabled features:")
 #]=======================================================================]
 function(PRINT_DISABLED_FEATURES)
+  message(DEPRECATION "PRINT_DISABLED_FEATURES is deprecated. Use
+    feature_summary(WHAT DISABLED_FEATURES DESCRIPTION \"Disabled features:\")")
   FEATURE_SUMMARY(WHAT DISABLED_FEATURES  DESCRIPTION "Disabled features:")
 endfunction()
diff --git a/Modules/FindALSA.cmake b/Modules/FindALSA.cmake
index d0ffa03..fa9a434 100644
--- a/Modules/FindALSA.cmake
+++ b/Modules/FindALSA.cmake
@@ -39,8 +39,6 @@ if(ALSA_INCLUDE_DIR AND EXISTS "${ALSA_INCLUDE_DIR}/alsa/version.h")
   unset(alsa_version_str)
 endif()
 
-# handle the QUIETLY and REQUIRED arguments and set ALSA_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(ALSA
                                   REQUIRED_VARS ALSA_LIBRARY ALSA_INCLUDE_DIR
diff --git a/Modules/FindASPELL.cmake b/Modules/FindASPELL.cmake
index 8f2b007..6944ac1 100644
--- a/Modules/FindASPELL.cmake
+++ b/Modules/FindASPELL.cmake
@@ -25,8 +25,6 @@ find_program(ASPELL_EXECUTABLE
 
 find_library(ASPELL_LIBRARIES NAMES aspell aspell-15 libaspell-15 libaspell)
 
-# handle the QUIETLY and REQUIRED arguments and set ASPELL_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(ASPELL DEFAULT_MSG ASPELL_LIBRARIES ASPELL_INCLUDE_DIR ASPELL_EXECUTABLE)
 
diff --git a/Modules/FindAVIFile.cmake b/Modules/FindAVIFile.cmake
index 38701be..88a2a25 100644
--- a/Modules/FindAVIFile.cmake
+++ b/Modules/FindAVIFile.cmake
@@ -32,8 +32,6 @@ if (UNIX)
 
 endif ()
 
-# handle the QUIETLY and REQUIRED arguments and set AVIFILE_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(AVIFile DEFAULT_MSG AVIFILE_INCLUDE_DIR AVIFILE_AVIPLAY_LIBRARY)
 
diff --git a/Modules/FindArmadillo.cmake b/Modules/FindArmadillo.cmake
index fab04c2..95f0c56 100644
--- a/Modules/FindArmadillo.cmake
+++ b/Modules/FindArmadillo.cmake
@@ -73,10 +73,6 @@ if(ARMADILLO_INCLUDE_DIR)
   set(ARMADILLO_VERSION_STRING "${ARMADILLO_VERSION_MAJOR}.${ARMADILLO_VERSION_MINOR}.${ARMADILLO_VERSION_PATCH}")
 endif ()
 
-#======================
-
-
-# Checks 'REQUIRED', 'QUIET' and versions.
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 find_package_handle_standard_args(Armadillo
   REQUIRED_VARS ARMADILLO_LIBRARY ARMADILLO_INCLUDE_DIR
@@ -88,10 +84,7 @@ if (ARMADILLO_FOUND)
   set(ARMADILLO_LIBRARIES ${ARMADILLO_LIBRARY})
 endif ()
 
-
 # Hide internal variables
 mark_as_advanced(
   ARMADILLO_INCLUDE_DIR
   ARMADILLO_LIBRARY)
-
-#======================
diff --git a/Modules/FindBISON.cmake b/Modules/FindBISON.cmake
index d40b806..d684ccd 100644
--- a/Modules/FindBISON.cmake
+++ b/Modules/FindBISON.cmake
@@ -84,8 +84,6 @@
 find_program(BISON_EXECUTABLE NAMES bison win_bison DOC "path to the bison executable")
 mark_as_advanced(BISON_EXECUTABLE)
 
-include(CMakeParseArguments)
-
 if(BISON_EXECUTABLE)
   # the bison commands should be executed with the C locale, otherwise
   # the message (which are parsed) may be translated
@@ -253,5 +251,3 @@ endif()
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(BISON REQUIRED_VARS  BISON_EXECUTABLE
                                         VERSION_VAR BISON_VERSION)
-
-# FindBISON.cmake ends here
diff --git a/Modules/FindBLAS.cmake b/Modules/FindBLAS.cmake
index 853a6b4..2684617 100644
--- a/Modules/FindBLAS.cmake
+++ b/Modules/FindBLAS.cmake
@@ -32,13 +32,32 @@
 #      all the possibilities
 #   BLA_F95     if set on tries to find the f95 interfaces for BLAS/LAPACK
 #
-# ######### ## List of vendors (BLA_VENDOR) valid in this module #
-# Goto,OpenBLAS,ATLAS PhiPACK,CXML,DXML,SunPerf,SCSL,SGIMATH,IBMESSL,
-# Intel10_32 (intel mkl v10 32 bit),Intel10_64lp (intel mkl v10 64 bit,
-# lp thread model, lp64 model), # Intel10_64lp_seq (intel mkl v10 64
-# bit,sequential code, lp64 model), # Intel( older versions of mkl 32
-# and 64 bit), ACML,ACML_MP,ACML_GPU,Apple, NAS, Generic C/CXX should be
-# enabled to use Intel mkl
+# List of vendors (BLA_VENDOR) valid in this module:
+#
+# * Goto
+# * OpenBLAS
+# * ATLAS PhiPACK
+# * CXML
+# * DXML
+# * SunPerf
+# * SCSL
+# * SGIMATH
+# * IBMESSL
+# * Intel10_32 (intel mkl v10 32 bit)
+# * Intel10_64lp (intel mkl v10 64 bit, lp thread model, lp64 model)
+# * Intel10_64lp_seq (intel mkl v10 64 bit, sequential code, lp64 model)
+# * Intel (older versions of mkl 32 and 64 bit)
+# * ACML
+# * ACML_MP
+# * ACML_GPU
+# * Apple
+# * NAS
+# * Generic
+#
+# .. note::
+#
+#   C/CXX should be enabled to use Intel mkl
+#
 
 include(${CMAKE_CURRENT_LIST_DIR}/CheckFunctionExists.cmake)
 include(${CMAKE_CURRENT_LIST_DIR}/CheckFortranFunctionExists.cmake)
diff --git a/Modules/FindBZip2.cmake b/Modules/FindBZip2.cmake
index 2d93eba..d2307f1 100644
--- a/Modules/FindBZip2.cmake
+++ b/Modules/FindBZip2.cmake
@@ -45,8 +45,6 @@ if (BZIP2_INCLUDE_DIR AND EXISTS "${BZIP2_INCLUDE_DIR}/bzlib.h")
     string(REGEX REPLACE ".* bzip2/libbzip2 version ([0-9]+\\.[^ ]+) of [0-9]+ .*" "\\1" BZIP2_VERSION_STRING "${BZLIB_H}")
 endif ()
 
-# handle the QUIETLY and REQUIRED arguments and set BZip2_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(BZip2
                                   REQUIRED_VARS BZIP2_LIBRARIES BZIP2_INCLUDE_DIR
diff --git a/Modules/FindBoost.cmake b/Modules/FindBoost.cmake
index 6947620..2dd08e1 100644
--- a/Modules/FindBoost.cmake
+++ b/Modules/FindBoost.cmake
@@ -428,7 +428,7 @@ function(_Boost_GUESS_COMPILER_PREFIX _ret)
     set(_boost_COMPILER "-ghs")
   elseif("x${CMAKE_CXX_COMPILER_ID}" STREQUAL "xMSVC")
     if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10)
-      set(_boost_COMPILER "-vc150")
+      set(_boost_COMPILER "-vc141")
     elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19)
       set(_boost_COMPILER "-vc140")
     elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18)
@@ -445,7 +445,7 @@ function(_Boost_GUESS_COMPILER_PREFIX _ret)
       set(_boost_COMPILER "-vc71")
     elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 13) # Good luck!
       set(_boost_COMPILER "-vc7") # yes, this is correct
-    else() # MSVC60 Good luck!
+    else() # VS 6.0 Good luck!
       set(_boost_COMPILER "-vc6") # yes, this is correct
     endif()
   elseif (BORLAND)
@@ -742,10 +742,11 @@ function(_Boost_COMPONENT_DEPENDENCIES component _ret)
     set(_Boost_THREAD_DEPENDENCIES chrono system date_time atomic)
     set(_Boost_WAVE_DEPENDENCIES filesystem system serialization thread chrono date_time atomic)
     set(_Boost_WSERIALIZATION_DEPENDENCIES serialization)
-  elseif(NOT Boost_VERSION VERSION_LESS 106300 AND Boost_VERSION VERSION_LESS 106400)
+  elseif(NOT Boost_VERSION VERSION_LESS 106300 AND Boost_VERSION VERSION_LESS 106500)
     set(_Boost_CHRONO_DEPENDENCIES system)
     set(_Boost_CONTEXT_DEPENDENCIES thread chrono system date_time)
     set(_Boost_COROUTINE_DEPENDENCIES context system)
+    set(_Boost_COROUTINE2_DEPENDENCIES context fiber thread chrono system date_time)
     set(_Boost_FIBER_DEPENDENCIES context thread chrono system date_time)
     set(_Boost_FILESYSTEM_DEPENDENCIES system)
     set(_Boost_IOSTREAMS_DEPENDENCIES regex)
@@ -892,7 +893,7 @@ endfunction()
 # This function would append corresponding directories if MSVC is a current compiler,
 # so having `BOOST_ROOT` would be enough to specify to find everything.
 #
-macro(_Boost_UPDATE_LIBRARY_SEARCH_DIRS_WITH_PREBUILT_PATHS componentlibvar basedir)
+macro(_Boost_UPDATE_WINDOWS_LIBRARY_SEARCH_DIRS_WITH_PREBUILT_PATHS componentlibvar basedir)
   if("x${CMAKE_CXX_COMPILER_ID}" STREQUAL "xMSVC")
     if(CMAKE_SIZEOF_VOID_P EQUAL 8)
       set(_arch_suffix 64)
@@ -900,19 +901,19 @@ macro(_Boost_UPDATE_LIBRARY_SEARCH_DIRS_WITH_PREBUILT_PATHS componentlibvar base
       set(_arch_suffix 32)
     endif()
     if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10)
-      list(APPEND ${componentlibvar} ${${basedir}}/lib${_arch_suffix}-msvc-15.0)
+      list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-15.0)
     elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19)
-      list(APPEND ${componentlibvar} ${${basedir}}/lib${_arch_suffix}-msvc-14.0)
+      list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-14.0)
     elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18)
-      list(APPEND ${componentlibvar} ${${basedir}}/lib${_arch_suffix}-msvc-12.0)
+      list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-12.0)
     elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 17)
-      list(APPEND ${componentlibvar} ${${basedir}}/lib${_arch_suffix}-msvc-11.0)
+      list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-11.0)
     elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16)
-      list(APPEND ${componentlibvar} ${${basedir}}/lib${_arch_suffix}-msvc-10.0)
+      list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-10.0)
     elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15)
-      list(APPEND ${componentlibvar} ${${basedir}}/lib${_arch_suffix}-msvc-9.0)
+      list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-9.0)
     elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 14)
-      list(APPEND ${componentlibvar} ${${basedir}}/lib${_arch_suffix}-msvc-8.0)
+      list(APPEND ${componentlibvar} ${basedir}/lib${_arch_suffix}-msvc-8.0)
     endif()
   endif()
 endmacro()
@@ -963,7 +964,7 @@ else()
   # _Boost_COMPONENT_HEADERS.  See the instructions at the top of
   # _Boost_COMPONENT_DEPENDENCIES.
   set(_Boost_KNOWN_VERSIONS ${Boost_ADDITIONAL_VERSIONS}
-    "1.63.0" "1.63" "1.62.0" "1.62" "1.61.0" "1.61" "1.60.0" "1.60"
+    "1.64.0" "1.64" "1.63.0" "1.63" "1.62.0" "1.62" "1.61.0" "1.61" "1.60.0" "1.60"
     "1.59.0" "1.59" "1.58.0" "1.58" "1.57.0" "1.57" "1.56.0" "1.56" "1.55.0" "1.55"
     "1.54.0" "1.54" "1.53.0" "1.53" "1.52.0" "1.52" "1.51.0" "1.51"
     "1.50.0" "1.50" "1.49.0" "1.49" "1.48.0" "1.48" "1.47.0" "1.47" "1.46.1"
@@ -1332,13 +1333,13 @@ string(APPEND _boost_DEBUG_ABI_TAG "d")
 #  p        using the STLport standard library rather than the
 #           default one supplied with your compiler
 if(Boost_USE_STLPORT)
-  set( _boost_RELEASE_ABI_TAG "${_boost_RELEASE_ABI_TAG}p")
-  set( _boost_DEBUG_ABI_TAG   "${_boost_DEBUG_ABI_TAG}p")
+  string(APPEND _boost_RELEASE_ABI_TAG "p")
+  string(APPEND _boost_DEBUG_ABI_TAG "p")
 endif()
 #  n        using the STLport deprecated "native iostreams" feature
 if(Boost_USE_STLPORT_DEPRECATED_NATIVE_IOSTREAMS)
-  set( _boost_RELEASE_ABI_TAG "${_boost_RELEASE_ABI_TAG}n")
-  set( _boost_DEBUG_ABI_TAG   "${_boost_DEBUG_ABI_TAG}n")
+  string(APPEND _boost_RELEASE_ABI_TAG "n")
+  string(APPEND _boost_DEBUG_ABI_TAG "n")
 endif()
 
 if(Boost_DEBUG)
@@ -1376,10 +1377,10 @@ foreach(c DEBUG RELEASE)
 
     if(BOOST_ROOT)
       list(APPEND _boost_LIBRARY_SEARCH_DIRS_${c} ${BOOST_ROOT}/lib ${BOOST_ROOT}/stage/lib)
-      _Boost_UPDATE_LIBRARY_SEARCH_DIRS_WITH_PREBUILT_PATHS(_boost_LIBRARY_SEARCH_DIRS_${c} BOOST_ROOT)
+      _Boost_UPDATE_WINDOWS_LIBRARY_SEARCH_DIRS_WITH_PREBUILT_PATHS(_boost_LIBRARY_SEARCH_DIRS_${c} "${BOOST_ROOT}")
     elseif(_ENV_BOOST_ROOT)
       list(APPEND _boost_LIBRARY_SEARCH_DIRS_${c} ${_ENV_BOOST_ROOT}/lib ${_ENV_BOOST_ROOT}/stage/lib)
-      _Boost_UPDATE_LIBRARY_SEARCH_DIRS_WITH_PREBUILT_PATHS(_boost_LIBRARY_SEARCH_DIRS_${c} _ENV_BOOST_ROOT)
+      _Boost_UPDATE_WINDOWS_LIBRARY_SEARCH_DIRS_WITH_PREBUILT_PATHS(_boost_LIBRARY_SEARCH_DIRS_${c} "${_ENV_BOOST_ROOT}")
     endif()
 
     list(APPEND _boost_LIBRARY_SEARCH_DIRS_${c}
@@ -1387,6 +1388,7 @@ foreach(c DEBUG RELEASE)
       ${Boost_INCLUDE_DIR}/../lib
       ${Boost_INCLUDE_DIR}/stage/lib
       )
+    _Boost_UPDATE_WINDOWS_LIBRARY_SEARCH_DIRS_WITH_PREBUILT_PATHS(_boost_LIBRARY_SEARCH_DIRS_${c} "${Boost_INCLUDE_DIR}/..")
     if( Boost_NO_SYSTEM_PATHS )
       list(APPEND _boost_LIBRARY_SEARCH_DIRS_${c} NO_CMAKE_SYSTEM_PATH NO_SYSTEM_ENVIRONMENT_PATH)
     else()
@@ -1395,6 +1397,7 @@ foreach(c DEBUG RELEASE)
         C:/boost
         /sw/local/lib
         )
+      _Boost_UPDATE_WINDOWS_LIBRARY_SEARCH_DIRS_WITH_PREBUILT_PATHS(_boost_LIBRARY_SEARCH_DIRS_${c} "C:/boost")
     endif()
   endif()
 endforeach()
@@ -1409,9 +1412,9 @@ endif()
 if( Boost_USE_STATIC_LIBS )
   set( _boost_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
   if(WIN32)
-    set(CMAKE_FIND_LIBRARY_SUFFIXES .lib .a ${CMAKE_FIND_LIBRARY_SUFFIXES})
+    list(INSERT CMAKE_FIND_LIBRARY_SUFFIXES 0 .lib .a)
   else()
-    set(CMAKE_FIND_LIBRARY_SUFFIXES .a )
+    set(CMAKE_FIND_LIBRARY_SUFFIXES .a)
   endif()
 endif()
 
@@ -1437,7 +1440,7 @@ endif()
 set(_boost_STATIC_RUNTIME_WORKAROUND false)
 if(WIN32 AND Boost_USE_STATIC_LIBS)
   if(NOT DEFINED Boost_USE_STATIC_RUNTIME)
-    set(_boost_STATIC_RUNTIME_WORKAROUND true)
+    set(_boost_STATIC_RUNTIME_WORKAROUND TRUE)
   endif()
 endif()
 
@@ -1461,7 +1464,7 @@ if(NOT _Boost_THREAD_DEPENDENCY_LIBS EQUAL -1)
 endif()
 
 # If the user changed any of our control inputs flush previous results.
-if(_Boost_CHANGE_LIBDIR OR _Boost_CHANGE_LIBNAME)
+if(_Boost_CHANGE_LIBDIR_DEBUG OR _Boost_CHANGE_LIBDIR_RELEASE OR _Boost_CHANGE_LIBNAME)
   foreach(COMPONENT ${_Boost_COMPONENTS_SEARCHED})
     string(TOUPPER ${COMPONENT} UPPERCOMPONENT)
     foreach(c DEBUG RELEASE)
@@ -1700,13 +1703,11 @@ if(Boost_FOUND)
     endif()
 
     if(EXISTS "${_boost_LIB_DIR}/lib")
-      set(_boost_LIB_DIR ${_boost_LIB_DIR}/lib)
+      string(APPEND _boost_LIB_DIR /lib)
+    elseif(EXISTS "${_boost_LIB_DIR}/stage/lib")
+      string(APPEND _boost_LIB_DIR "/stage/lib")
     else()
-      if(EXISTS "${_boost_LIB_DIR}/stage/lib")
-        set(_boost_LIB_DIR ${_boost_LIB_DIR}/stage/lib)
-      else()
-        set(_boost_LIB_DIR "")
-      endif()
+      set(_boost_LIB_DIR "")
     endif()
 
     if(_boost_LIB_DIR AND EXISTS "${_boost_LIB_DIR}")
diff --git a/Modules/FindBullet.cmake b/Modules/FindBullet.cmake
index d000f79..fc6695c 100644
--- a/Modules/FindBullet.cmake
+++ b/Modules/FindBullet.cmake
@@ -78,8 +78,6 @@ _FIND_BULLET_LIBRARY(BULLET_SOFTBODY_LIBRARY        BulletSoftBody)
 _FIND_BULLET_LIBRARY(BULLET_SOFTBODY_LIBRARY_DEBUG  BulletSoftBody_Debug BulletSoftBody_d)
 
 
-# handle the QUIETLY and REQUIRED arguments and set BULLET_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(Bullet DEFAULT_MSG
     BULLET_DYNAMICS_LIBRARY BULLET_COLLISION_LIBRARY BULLET_MATH_LIBRARY
diff --git a/Modules/FindCUDA/select_compute_arch.cmake b/Modules/FindCUDA/select_compute_arch.cmake
index 5ce71a9..8fb44d8 100644
--- a/Modules/FindCUDA/select_compute_arch.cmake
+++ b/Modules/FindCUDA/select_compute_arch.cmake
@@ -44,9 +44,10 @@ endif ()
 #
 function(CUDA_DETECT_INSTALLED_GPUS OUT_VARIABLE)
   if(NOT CUDA_GPU_DETECT_OUTPUT)
-    set(cufile ${PROJECT_BINARY_DIR}/detect_cuda_archs.cu)
+    set(file ${PROJECT_BINARY_DIR}/detect_cuda_compute_capabilities.cpp)
 
-    file(WRITE ${cufile} ""
+    file(WRITE ${file} ""
+      "#include <cuda_runtime.h>\n"
       "#include <cstdio>\n"
       "int main()\n"
       "{\n"
@@ -62,14 +63,15 @@ function(CUDA_DETECT_INSTALLED_GPUS OUT_VARIABLE)
       "  return 0;\n"
       "}\n")
 
-    execute_process(COMMAND "${CUDA_NVCC_EXECUTABLE}" "--run" "${cufile}"
-                    WORKING_DIRECTORY "${PROJECT_BINARY_DIR}/CMakeFiles/"
-                    RESULT_VARIABLE nvcc_res OUTPUT_VARIABLE nvcc_out
-                    ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
+    try_run(run_result compile_result ${PROJECT_BINARY_DIR} ${file}
+            CMAKE_FLAGS "-DINCLUDE_DIRECTORIES=${CUDA_INCLUDE_DIRS}"
+            LINK_LIBRARIES ${CUDA_LIBRARIES}
+            RUN_OUTPUT_VARIABLE compute_capabilities)
 
-    if(nvcc_res EQUAL 0)
-      string(REPLACE "2.1" "2.1(2.0)" nvcc_out "${nvcc_out}")
-      set(CUDA_GPU_DETECT_OUTPUT ${nvcc_out} CACHE INTERNAL "Returned GPU architetures from detect_gpus tool" FORCE)
+    if(run_result EQUAL 0)
+      string(REPLACE "2.1" "2.1(2.0)" compute_capabilities "${compute_capabilities}")
+      set(CUDA_GPU_DETECT_OUTPUT ${compute_capabilities}
+        CACHE INTERNAL "Returned GPU architectures from detect_gpus tool" FORCE)
     endif()
   endif()
 
@@ -110,6 +112,7 @@ function(CUDA_SELECT_NVCC_ARCH_FLAGS out_variable)
   list(REMOVE_DUPLICATES CUDA_ARCH_LIST)
   foreach(arch_name ${CUDA_ARCH_LIST})
     set(arch_bin)
+    set(arch_ptx)
     set(add_ptx FALSE)
     # Check to see if we are compiling PTX
     if(arch_name MATCHES "(.*)\\+PTX$")
diff --git a/Modules/FindCURL.cmake b/Modules/FindCURL.cmake
index 200f8c3..f4bcc36 100644
--- a/Modules/FindCURL.cmake
+++ b/Modules/FindCURL.cmake
@@ -44,8 +44,6 @@ if(CURL_INCLUDE_DIR)
   endforeach()
 endif()
 
-# handle the QUIETLY and REQUIRED arguments and set CURL_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(CURL
                                   REQUIRED_VARS CURL_LIBRARY CURL_INCLUDE_DIR
diff --git a/Modules/FindCoin3D.cmake b/Modules/FindCoin3D.cmake
index fea644d..f11903d 100644
--- a/Modules/FindCoin3D.cmake
+++ b/Modules/FindCoin3D.cmake
@@ -70,11 +70,7 @@ else ()
 
 endif ()
 
-# handle the QUIETLY and REQUIRED arguments and set COIN3D_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(Coin3D DEFAULT_MSG COIN3D_LIBRARIES COIN3D_INCLUDE_DIRS)
 
 mark_as_advanced(COIN3D_INCLUDE_DIRS COIN3D_LIBRARIES )
-
-
diff --git a/Modules/FindCurses.cmake b/Modules/FindCurses.cmake
index a0929ce..4365e99 100644
--- a/Modules/FindCurses.cmake
+++ b/Modules/FindCurses.cmake
@@ -190,8 +190,6 @@ endif()
 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
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(Curses DEFAULT_MSG
   CURSES_LIBRARY CURSES_INCLUDE_PATH)
diff --git a/Modules/FindDart.cmake b/Modules/FindDart.cmake
index 37164e6..acd4ef6 100644
--- a/Modules/FindDart.cmake
+++ b/Modules/FindDart.cmake
@@ -26,8 +26,6 @@ find_path(DART_ROOT README.INSTALL
     DOC "If you have Dart installed, where is it located?"
     )
 
-# handle the QUIETLY and REQUIRED arguments and set DART_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(Dart DEFAULT_MSG DART_ROOT)
 
diff --git a/Modules/FindDevIL.cmake b/Modules/FindDevIL.cmake
index dc8e38a..45fab82 100644
--- a/Modules/FindDevIL.cmake
+++ b/Modules/FindDevIL.cmake
@@ -67,6 +67,6 @@ find_library(ILU_LIBRARIES
 
 #message("ILU_LIBRARIES is ${ILU_LIBRARIES}")
 
-FIND_PACKAGE_HANDLE_STANDARD_ARGS(IL DEFAULT_MSG
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(DevIL DEFAULT_MSG
                                   IL_LIBRARIES ILU_LIBRARIES
-                                  ILUT_LIBRARIES IL_INCLUDE_DIR)
+                                  IL_INCLUDE_DIR)
diff --git a/Modules/FindEXPAT.cmake b/Modules/FindEXPAT.cmake
index cc89203..09963fc 100644
--- a/Modules/FindEXPAT.cmake
+++ b/Modules/FindEXPAT.cmake
@@ -44,8 +44,6 @@ if (EXPAT_INCLUDE_DIR AND EXISTS "${EXPAT_INCLUDE_DIR}/expat.h")
     endforeach()
 endif ()
 
-# handle the QUIETLY and REQUIRED arguments and set EXPAT_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(EXPAT
                                   REQUIRED_VARS EXPAT_LIBRARY EXPAT_INCLUDE_DIR
diff --git a/Modules/FindFLEX.cmake b/Modules/FindFLEX.cmake
index 69cf513..fef7fb4 100644
--- a/Modules/FindFLEX.cmake
+++ b/Modules/FindFLEX.cmake
@@ -107,8 +107,6 @@ find_path(FLEX_INCLUDE_DIR FlexLexer.h
 
 mark_as_advanced(FL_LIBRARY FLEX_INCLUDE_DIR)
 
-include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake)
-
 set(FLEX_INCLUDE_DIRS ${FLEX_INCLUDE_DIR})
 set(FLEX_LIBRARIES ${FL_LIBRARY})
 
@@ -218,5 +216,3 @@ endif()
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(FLEX REQUIRED_VARS FLEX_EXECUTABLE
                                        VERSION_VAR FLEX_VERSION)
-
-# FindFLEX.cmake ends here
diff --git a/Modules/FindFreetype.cmake b/Modules/FindFreetype.cmake
index 21a5d89..9ea77df 100644
--- a/Modules/FindFreetype.cmake
+++ b/Modules/FindFreetype.cmake
@@ -135,9 +135,6 @@ if(FREETYPE_INCLUDE_DIR_freetype2 AND FREETYPE_H)
   endforeach()
 endif()
 
-
-# handle the QUIETLY and REQUIRED arguments and set FREETYPE_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 
 find_package_handle_standard_args(
diff --git a/Modules/FindGIF.cmake b/Modules/FindGIF.cmake
index 88c4180..0843d5f 100644
--- a/Modules/FindGIF.cmake
+++ b/Modules/FindGIF.cmake
@@ -91,8 +91,6 @@ if(GIF_INCLUDE_DIR)
   CMAKE_POP_CHECK_STATE()
 endif()
 
-# handle the QUIETLY and REQUIRED arguments and set GIF_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(GIF  REQUIRED_VARS  GIF_LIBRARY  GIF_INCLUDE_DIR
                                        VERSION_VAR GIF_VERSION )
diff --git a/Modules/FindGSL.cmake b/Modules/FindGSL.cmake
index 98377a2..76059b3 100644
--- a/Modules/FindGSL.cmake
+++ b/Modules/FindGSL.cmake
@@ -55,7 +55,6 @@
 #  GSL_LIBRARY_DEBUG       - Location of the debug GSL library (if any).
 #
 
-# Include these modules to handle the QUIETLY and REQUIRED arguments.
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 
 #=============================================================================
@@ -136,7 +135,7 @@ if( NOT GSL_VERSION )
   # 2. If gsl-config is not available, try looking in gsl/gsl_version.h
   if( NOT GSL_VERSION AND EXISTS "${GSL_INCLUDE_DIRS}/gsl/gsl_version.h" )
     file( STRINGS "${GSL_INCLUDE_DIRS}/gsl/gsl_version.h" gsl_version_h_contents REGEX "define GSL_VERSION" )
-    string( REGEX REPLACE ".*([0-9].[0-9][0-9]).*" "\\1" GSL_VERSION ${gsl_version_h_contents} )
+    string( REGEX REPLACE ".*([0-9]\\.[0-9][0-9]?).*" "\\1" GSL_VERSION ${gsl_version_h_contents} )
   endif()
 
   # might also try scraping the directory name for a regex match "gsl-X.X"
diff --git a/Modules/FindGTK2.cmake b/Modules/FindGTK2.cmake
index 78dc6ba..fd179a8 100644
--- a/Modules/FindGTK2.cmake
+++ b/Modules/FindGTK2.cmake
@@ -105,7 +105,7 @@
 #   * 14236: Detect gthread library
 #            Detect pangocairo on windows
 #            Detect pangocairo with gtk module instead of with gtkmm
-#   * 14259: Use vc100 libraries with MSVC11
+#   * 14259: Use vc100 libraries with VS 11
 #   * 14260: Export a GTK2_DEFINITIONS variable to set /vd2 when appropriate
 #            (i.e. MSVC)
 #   * Use the optimized/debug syntax for _LIBRARY and _LIBRARIES variables when
@@ -165,7 +165,6 @@
 #=============================================================
 
 include(${CMAKE_CURRENT_LIST_DIR}/SelectLibraryConfigurations.cmake)
-include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake)
 
 function(_GTK2_GET_VERSION _OUT_major _OUT_minor _OUT_micro _gtkversion_hdr)
     file(STRINGS ${_gtkversion_hdr} _contents REGEX "#define GTK_M[A-Z]+_VERSION[ \t]+")
@@ -224,7 +223,10 @@ function(_GTK2_SIGCXX_GET_VERSION _OUT_major _OUT_minor _OUT_micro _sigcxxversio
         set(${_OUT_minor} ${${_OUT_minor}} PARENT_SCOPE)
         set(${_OUT_micro} ${${_OUT_micro}} PARENT_SCOPE)
     else()
-        message(FATAL_ERROR "Include file ${_gtkversion_hdr} does not exist")
+        # The header does not have the version macros; assume it is ``0.0.0``.
+        set(${_OUT_major} 0)
+        set(${_OUT_minor} 0)
+        set(${_OUT_micro} 0)
     endif()
 endfunction()
 
@@ -350,13 +352,13 @@ function(_GTK2_FIND_LIBRARY _var _lib _expand_vc _append_version)
 
     if(_expand_vc AND MSVC)
         # Add vc80/vc90/vc100 midfixes
-        if(MSVC80)
+        if(MSVC_VERSION EQUAL 1400)
             set(_library   ${_library}-vc80)
-        elseif(MSVC90)
+        elseif(MSVC_VERSION EQUAL 1500)
             set(_library   ${_library}-vc90)
-        elseif(MSVC10)
+        elseif(MSVC_VERSION EQUAL 1600)
             set(_library ${_library}-vc100)
-        elseif(MSVC11)
+        elseif(MSVC_VERSION EQUAL 1700)
             # Up to gtkmm-win 2.22.0-2 there are no vc110 libraries but vc100 can be used
             set(_library ${_library}-vc100)
         endif()
@@ -530,52 +532,54 @@ function(_GTK2_ADD_TARGET _var)
 
     cmake_parse_arguments(_${_var} "" "" "GTK2_DEPENDS;GTK2_OPTIONAL_DEPENDS;OPTIONAL_INCLUDES" ${ARGN})
 
-    if(GTK2_${_var}_FOUND AND NOT TARGET GTK2::${_basename})
-        # Do not create the target if dependencies are missing
-        foreach(_dep ${_${_var}_GTK2_DEPENDS})
-            if(NOT TARGET GTK2::${_dep})
-                return()
-            endif()
-        endforeach()
+    if(GTK2_${_var}_FOUND)
+        if(NOT TARGET GTK2::${_basename})
+            # Do not create the target if dependencies are missing
+            foreach(_dep ${_${_var}_GTK2_DEPENDS})
+                if(NOT TARGET GTK2::${_dep})
+                    return()
+                endif()
+            endforeach()
 
-        add_library(GTK2::${_basename} UNKNOWN IMPORTED)
+            add_library(GTK2::${_basename} UNKNOWN IMPORTED)
 
-        set(GTK2_TARGETS ${GTK2_TARGETS} GTK2::${_basename})
-        set(GTK2_TARGETS ${GTK2_TARGETS} PARENT_SCOPE)
+            if(GTK2_${_var}_LIBRARY_RELEASE)
+                set_property(TARGET GTK2::${_basename} APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
+                set_property(TARGET GTK2::${_basename}        PROPERTY IMPORTED_LOCATION_RELEASE "${GTK2_${_var}_LIBRARY_RELEASE}" )
+            endif()
 
-        if(GTK2_${_var}_LIBRARY_RELEASE)
-            set_property(TARGET GTK2::${_basename} APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
-            set_property(TARGET GTK2::${_basename}        PROPERTY IMPORTED_LOCATION_RELEASE "${GTK2_${_var}_LIBRARY_RELEASE}" )
-        endif()
+            if(GTK2_${_var}_LIBRARY_DEBUG)
+                set_property(TARGET GTK2::${_basename} APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG)
+                set_property(TARGET GTK2::${_basename}        PROPERTY IMPORTED_LOCATION_DEBUG "${GTK2_${_var}_LIBRARY_DEBUG}" )
+            endif()
 
-        if(GTK2_${_var}_LIBRARY_DEBUG)
-            set_property(TARGET GTK2::${_basename} APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG)
-            set_property(TARGET GTK2::${_basename}        PROPERTY IMPORTED_LOCATION_DEBUG "${GTK2_${_var}_LIBRARY_DEBUG}" )
-        endif()
+            if(GTK2_${_var}_INCLUDE_DIR)
+                set_property(TARGET GTK2::${_basename} APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${GTK2_${_var}_INCLUDE_DIR}")
+            endif()
 
-        if(GTK2_${_var}_INCLUDE_DIR)
-            set_property(TARGET GTK2::${_basename} APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${GTK2_${_var}_INCLUDE_DIR}")
-        endif()
+            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()
 
-        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()
+            if(GTK2_DEFINITIONS)
+                set_property(TARGET GTK2::${_basename} PROPERTY INTERFACE_COMPILE_DEFINITIONS "${GTK2_DEFINITIONS}")
+            endif()
 
-        if(GTK2_DEFINITIONS)
-            set_property(TARGET GTK2::${_basename} PROPERTY INTERFACE_COMPILE_DEFINITIONS "${GTK2_DEFINITIONS}")
-        endif()
+            if(_${_var}_GTK2_DEPENDS)
+                _GTK2_ADD_TARGET_DEPENDS(${_var} ${_${_var}_GTK2_DEPENDS} ${_${_var}_GTK2_OPTIONAL_DEPENDS})
+            endif()
 
-        if(_${_var}_GTK2_DEPENDS)
-            _GTK2_ADD_TARGET_DEPENDS(${_var} ${_${_var}_GTK2_DEPENDS} ${_${_var}_GTK2_OPTIONAL_DEPENDS})
+            if(_${_var}_OPTIONAL_INCLUDES)
+                foreach(_D ${_${_var}_OPTIONAL_INCLUDES})
+                    if(_D)
+                        _GTK2_ADD_TARGET_INCLUDE_DIRS(${_var} ${_D})
+                    endif()
+                endforeach()
+            endif()
         endif()
 
-        if(_${_var}_OPTIONAL_INCLUDES)
-            foreach(_D ${_${_var}_OPTIONAL_INCLUDES})
-                if(_D)
-                    _GTK2_ADD_TARGET_INCLUDE_DIRS(${_var} ${_D})
-                endif()
-            endforeach()
-        endif()
+        set(GTK2_TARGETS ${GTK2_TARGETS} GTK2::${_basename})
+        set(GTK2_TARGETS ${GTK2_TARGETS} PARENT_SCOPE)
 
         if(GTK2_USE_IMPORTED_TARGETS)
             set(GTK2_${_var}_LIBRARY GTK2::${_basename} PARENT_SCOPE)
@@ -736,9 +740,7 @@ foreach(_GTK2_component ${GTK2_FIND_COMPONENTS})
             if(APPLE)
                 _GTK2_FIND_LIBRARY    (GDK gdk-quartz false true)
             endif()
-            if(NOT GTK2_GDK_FOUND)
-                _GTK2_FIND_LIBRARY    (GDK gdk-x11 false true)
-            endif()
+            _GTK2_FIND_LIBRARY    (GDK gdk-x11 false true)
         else()
             _GTK2_FIND_LIBRARY    (GDK gdk-win32 false true)
         endif()
@@ -750,9 +752,7 @@ foreach(_GTK2_component ${GTK2_FIND_COMPONENTS})
             if(APPLE)
                 _GTK2_FIND_LIBRARY    (GTK gtk-quartz false true)
             endif()
-            if(NOT GTK2_GTK_FOUND)
-                _GTK2_FIND_LIBRARY    (GTK gtk-x11 false true)
-            endif()
+            _GTK2_FIND_LIBRARY    (GTK gtk-x11 false true)
         else()
             _GTK2_FIND_LIBRARY    (GTK gtk-win32 false true)
         endif()
@@ -957,4 +957,3 @@ endif()
 if(GTK2_INCLUDE_DIRS)
    list(REMOVE_DUPLICATES GTK2_INCLUDE_DIRS)
 endif()
-
diff --git a/Modules/FindGTest.cmake b/Modules/FindGTest.cmake
index 76ab716..6540171 100644
--- a/Modules/FindGTest.cmake
+++ b/Modules/FindGTest.cmake
@@ -49,8 +49,8 @@
 #   The root directory of the Google Test installation (may also be
 #   set as an environment variable)
 # ``GTEST_MSVC_SEARCH``
-#   If compiling with MSVC, this variable can be set to ``MD`` or
-#   ``MT`` (the default) to enable searching a GTest build tree
+#   If compiling with MSVC, this variable can be set to ``MT`` or
+#   ``MD`` (the default) to enable searching a GTest build tree
 #
 #
 # Example usage
@@ -160,11 +160,17 @@ if(MSVC)
     if(GTEST_MSVC_SEARCH STREQUAL "MD")
         list(APPEND _gtest_libpath_suffixes
             msvc/gtest-md/Debug
-            msvc/gtest-md/Release)
+            msvc/gtest-md/Release
+            msvc/x64/Debug
+            msvc/x64/Release
+            )
     elseif(GTEST_MSVC_SEARCH STREQUAL "MT")
         list(APPEND _gtest_libpath_suffixes
             msvc/gtest/Debug
-            msvc/gtest/Release)
+            msvc/gtest/Release
+            msvc/x64/Debug
+            msvc/x64/Release
+            )
     endif()
 endif()
 
diff --git a/Modules/FindGettext.cmake b/Modules/FindGettext.cmake
index 7718468..8035507 100644
--- a/Modules/FindGettext.cmake
+++ b/Modules/FindGettext.cmake
@@ -77,8 +77,6 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(Gettext
                                   REQUIRED_VARS GETTEXT_MSGMERGE_EXECUTABLE GETTEXT_MSGFMT_EXECUTABLE
                                   VERSION_VAR GETTEXT_VERSION_STRING)
 
-include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake)
-
 function(_GETTEXT_GET_UNIQUE_TARGET_NAME _name _unique_name)
    set(propertyName "_GETTEXT_UNIQUE_COUNTER_${_name}")
    get_property(currentCounter GLOBAL PROPERTY "${propertyName}")
diff --git a/Modules/FindGit.cmake b/Modules/FindGit.cmake
index 5d38193..fae31eb 100644
--- a/Modules/FindGit.cmake
+++ b/Modules/FindGit.cmake
@@ -30,7 +30,7 @@ set(git_names git eg)
 # Prefer .cmd variants on Windows unless running in a Makefile
 # in the MSYS shell.
 #
-if(WIN32)
+if(CMAKE_HOST_WIN32)
   if(NOT CMAKE_GENERATOR MATCHES "MSYS")
     set(git_names git.cmd git eg.cmd eg)
     # GitHub search path for Windows
@@ -43,12 +43,26 @@ if(WIN32)
   endif()
 endif()
 
+# First search the PATH and specific locations.
 find_program(GIT_EXECUTABLE
   NAMES ${git_names}
   PATHS ${github_path} ${_git_sourcetree_path}
-  PATH_SUFFIXES Git/cmd Git/bin
   DOC "Git command line client"
   )
+
+if(CMAKE_HOST_WIN32)
+  # Now look for installations in Git/ directories under typical installation
+  # prefixes on Windows.  Exclude PATH from this search because VS 2017's
+  # command prompt happens to have a PATH entry with a Git/ subdirectory
+  # containing a minimal git not meant for general use.
+  find_program(GIT_EXECUTABLE
+    NAMES ${git_names}
+    PATH_SUFFIXES Git/cmd Git/bin
+    NO_SYSTEM_ENVIRONMENT_PATH
+    DOC "Git command line client"
+    )
+endif()
+
 mark_as_advanced(GIT_EXECUTABLE)
 
 unset(git_names)
@@ -65,9 +79,6 @@ if(GIT_EXECUTABLE)
   unset(git_version)
 endif()
 
-# Handle the QUIETLY and REQUIRED arguments and set Git_FOUND to TRUE if
-# all listed variables are TRUE
-
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 find_package_handle_standard_args(Git
                                   REQUIRED_VARS GIT_EXECUTABLE
diff --git a/Modules/FindGnuTLS.cmake b/Modules/FindGnuTLS.cmake
index a6ab092..1a97d99 100644
--- a/Modules/FindGnuTLS.cmake
+++ b/Modules/FindGnuTLS.cmake
@@ -50,8 +50,6 @@ find_library(GNUTLS_LIBRARY NAMES gnutls libgnutls
 
 mark_as_advanced(GNUTLS_INCLUDE_DIR GNUTLS_LIBRARY)
 
-# handle the QUIETLY and REQUIRED arguments and set GNUTLS_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(GnuTLS
                                   REQUIRED_VARS GNUTLS_LIBRARY GNUTLS_INCLUDE_DIR
@@ -61,4 +59,3 @@ if(GNUTLS_FOUND)
     set(GNUTLS_LIBRARIES    ${GNUTLS_LIBRARY})
     set(GNUTLS_INCLUDE_DIRS ${GNUTLS_INCLUDE_DIR})
 endif()
-
diff --git a/Modules/FindGnuplot.cmake b/Modules/FindGnuplot.cmake
index 9ace651..aa4cd6c 100644
--- a/Modules/FindGnuplot.cmake
+++ b/Modules/FindGnuplot.cmake
@@ -46,12 +46,9 @@ endif()
 # for compatibility
 set(GNUPLOT ${GNUPLOT_EXECUTABLE})
 
-# handle the QUIETLY and REQUIRED arguments and set GNUPLOT_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(Gnuplot
                                   REQUIRED_VARS GNUPLOT_EXECUTABLE
                                   VERSION_VAR GNUPLOT_VERSION_STRING)
 
 mark_as_advanced( GNUPLOT_EXECUTABLE )
-
diff --git a/Modules/FindHDF5.cmake b/Modules/FindHDF5.cmake
index 16764e0..2a81da6 100644
--- a/Modules/FindHDF5.cmake
+++ b/Modules/FindHDF5.cmake
@@ -89,7 +89,11 @@
 #
 # The following variable can be set to guide the search for HDF5 libraries and includes:
 #
-# HDF5_ROOT
+# ``HDF5_ROOT``
+#   Specify the path to the HDF5 installation to use.
+#
+# ``HDF5_NO_FIND_PACKAGE_CONFIG_FILE``
+#   Set to a true value to skip trying to find ``hdf5-config.cmake``.
 
 # This module is maintained by Will Dicharry <wdicharry at stellarscience.com>.
 
@@ -340,71 +344,61 @@ macro( _HDF5_parse_compile_line
     libraries
     libraries_hl)
 
-    # Match the include paths
-    set( RE " -I *([^\" ]+|\"[^\"]+\")")
-    string( REGEX MATCHALL "${RE}" include_path_flags "${${compile_line_var}}")
-    foreach( IPATH IN LISTS include_path_flags )
-        string( REGEX REPLACE "${RE}" "\\1" IPATH "${IPATH}" )
-        list( APPEND ${include_paths} ${IPATH} )
-    endforeach()
-
-    # Match the definitions
-    set( RE " -D([^ ]*)")
-    string( REGEX MATCHALL "${RE}" definition_flags "${${compile_line_var}}" )
-    foreach( DEF IN LISTS definition_flags )
-        string( STRIP "${DEF}" DEF )
-        list( APPEND ${definitions} ${DEF} )
-    endforeach()
-
-    # Match the library paths
-    set( RE " -L *([^\" ]+|\"[^\"]+\")")
-    string( REGEX MATCHALL "${RE}" library_path_flags "${${compile_line_var}}")
-    foreach( LPATH IN LISTS library_path_flags )
-        string( REGEX REPLACE "${RE}" "\\1" LPATH "${LPATH}" )
-        list( APPEND ${library_paths} ${LPATH} )
-    endforeach()
-
-    # now search for the lib names specified in the compile line (match -l...)
-    # match only -l's preceded by a space or comma
-    set( RE " -l *([^\" ]+|\"[^\"]+\")")
-    string( REGEX MATCHALL "${RE}" library_name_flags "${${compile_line_var}}")
-    foreach( LNAME IN LISTS library_name_flags )
-        string( REGEX REPLACE "${RE}" "\\1" LNAME "${LNAME}" )
-        if(LNAME MATCHES ".*hl")
-            list(APPEND ${libraries_hl} ${LNAME})
-        else()
-            list(APPEND ${libraries} ${LNAME})
-        endif()
-    endforeach()
+  if(UNIX)
+    separate_arguments(_HDF5_COMPILE_ARGS UNIX_COMMAND "${${compile_line_var}}")
+  else()
+    separate_arguments(_HDF5_COMPILE_ARGS WINDOWS_COMMAND "${${compile_line_var}}")
+  endif()
 
-    # now search for full library paths with no flags
-    set( RE " ([^\" ]+|\"[^\"]+\")")
-    string( REGEX MATCHALL "${RE}" library_name_noflags "${${compile_line_var}}")
-    foreach( LIB IN LISTS library_name_noflags )
-        string( REGEX REPLACE "${RE}" "\\1" LIB "${LIB}" )
-        get_filename_component(LIB "${LIB}" ABSOLUTE)
-        if(NOT EXISTS ${LIB} OR IS_DIRECTORY ${LIB})
-            continue()
-        endif()
-        get_filename_component(LPATH ${LIB} DIRECTORY)
-        get_filename_component(LNAME ${LIB} NAME_WE)
-        string( REGEX REPLACE "^lib" "" LNAME ${LNAME} )
-        list( APPEND ${library_paths} ${LPATH} )
-        if(LNAME MATCHES ".*hl")
-            list(APPEND ${libraries_hl} ${LNAME})
-        else()
-            list(APPEND ${libraries} ${LNAME})
-        endif()
-    endforeach()
+  foreach(arg IN LISTS _HDF5_COMPILE_ARGS)
+    if("${arg}" MATCHES "^-I(.*)$")
+      # include directory
+      list(APPEND ${include_paths} "${CMAKE_MATCH_1}")
+    elseif("${arg}" MATCHES "^-D(.*)$")
+      # compile definition
+      list(APPEND ${definitions} "-D${CMAKE_MATCH_1}")
+    elseif("${arg}" MATCHES "^-L(.*)$")
+      # library search path
+      list(APPEND ${library_paths} "${CMAKE_MATCH_1}")
+    elseif("${arg}" MATCHES "^-l(hdf5.*hl.*)$")
+      # library name (hl)
+      list(APPEND ${libraries_hl} "${CMAKE_MATCH_1}")
+    elseif("${arg}" MATCHES "^-l(.*)$")
+      # library name
+      list(APPEND ${libraries} "${CMAKE_MATCH_1}")
+    elseif("${arg}" MATCHES "^(.:)?[/\\].*\\.(a|so|dylib|sl|lib)$")
+      # library file
+      if(NOT EXISTS "${arg}")
+        continue()
+      endif()
+      get_filename_component(_HDF5_LPATH "${arg}" DIRECTORY)
+      get_filename_component(_HDF5_LNAME "${arg}" NAME_WE)
+      string(REGEX REPLACE "^lib" "" _HDF5_LNAME "${_HDF5_LNAME}")
+      list(APPEND ${library_paths} "${_HDF5_LPATH}")
+      if(_HDF5_LNAME MATCHES "hdf5.*hl")
+        list(APPEND ${libraries_hl} "${_HDF5_LNAME}")
+      else()
+        list(APPEND ${libraries} "${_HDF5_LNAME}")
+      endif()
+    endif()
+  endforeach()
 endmacro()
 
 if(NOT HDF5_ROOT)
     set(HDF5_ROOT $ENV{HDF5_ROOT})
 endif()
+if(HDF5_ROOT)
+    set(_HDF5_SEARCH_OPTS NO_DEFAULT_PATH)
+else()
+    set(_HDF5_SEARCH_OPTS)
+endif()
 
 # Try to find HDF5 using an installed hdf5-config.cmake
-if(NOT HDF5_FOUND AND NOT HDF5_ROOT)
-    find_package(HDF5 QUIET NO_MODULE)
+if(NOT HDF5_FOUND AND NOT HDF5_NO_FIND_PACKAGE_CONFIG_FILE)
+    find_package(HDF5 QUIET NO_MODULE
+      HINTS ${HDF5_ROOT}
+      ${_HDF5_SEARCH_OPTS}
+      )
     if( HDF5_FOUND)
         set(HDF5_IS_PARALLEL ${HDF5_ENABLE_PARALLEL})
         set(HDF5_INCLUDE_DIRS ${HDF5_INCLUDE_DIR})
@@ -439,8 +433,8 @@ if(NOT HDF5_FOUND AND NOT HDF5_ROOT)
                 set(HDF5_${_lang}_LIBRARY ${_lang_location} CACHE PATH
                     "HDF5 ${_lang} library" )
                 mark_as_advanced(HDF5_${_lang}_LIBRARY)
-                list(APPEND HDF5_LIBRARIES ${HDF5_${_lang}_LIBRARY})
-                set(HDF5_${_lang}_LIBRARIES ${HDF5_${_lang}_LIBRARY})
+                list(APPEND HDF5_LIBRARIES ${HDF5_${_lang}_TARGET}${_suffix})
+                set(HDF5_${_lang}_LIBRARIES ${HDF5_${_lang}_TARGET}${_suffix})
                 set(HDF5_${_lang}_FOUND True)
             endif()
             if(FIND_HL)
@@ -449,8 +443,8 @@ if(NOT HDF5_FOUND AND NOT HDF5_ROOT)
                     set(HDF5_${_lang}_HL_LIBRARY ${_lang_hl_location} CACHE PATH
                         "HDF5 ${_lang} HL library" )
                     mark_as_advanced(HDF5_${_lang}_HL_LIBRARY)
-                    list(APPEND HDF5_HL_LIBRARIES ${HDF5_${_lang}_HL_LIBRARY})
-                    set(HDF5_${_lang}_HL_LIBRARIES ${HDF5_${_lang}_HL_LIBRARY})
+                    list(APPEND HDF5_HL_LIBRARIES ${HDF5_${_lang}_TARGET}${_suffix})
+                    set(HDF5_${_lang}_HL_LIBRARIES ${HDF5_${_lang}_TARGET}${_suffix})
                     set(HDF5_HL_FOUND True)
                 endif()
             endif()
@@ -458,7 +452,7 @@ if(NOT HDF5_FOUND AND NOT HDF5_ROOT)
     endif()
 endif()
 
-if(NOT HDF5_FOUND AND NOT HDF5_ROOT)
+if(NOT HDF5_FOUND)
   set(_HDF5_NEED_TO_SEARCH False)
   set(HDF5_COMPILER_NO_INTERROGATE True)
   # Only search for languages we've enabled
@@ -506,8 +500,10 @@ if(NOT HDF5_FOUND AND NOT HDF5_ROOT)
       # search options with the wrapper
       find_program(HDF5_${__lang}_COMPILER_EXECUTABLE
         NAMES ${HDF5_${__lang}_COMPILER_NAMES} NAMES_PER_DIR
+        HINTS ${HDF5_ROOT}
         PATH_SUFFIXES bin Bin
         DOC "HDF5 ${__lang} Wrapper compiler.  Used only to detect HDF5 compile flags."
+        ${_HDF5_SEARCH_OPTS}
       )
       mark_as_advanced( HDF5_${__lang}_COMPILER_EXECUTABLE )
       unset(HDF5_${__lang}_COMPILER_NAMES)
@@ -526,15 +522,26 @@ if(NOT HDF5_FOUND AND NOT HDF5_ROOT)
           )
           set(HDF5_${__lang}_LIBRARIES)
 
-          set(_HDF5_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
-          if(HDF5_USE_STATIC_LIBRARIES)
-            set(CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_STATIC_LIBRARY_SUFFIX})
-          else()
-            set(CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_SHARED_LIBRARY_SUFFIX})
-          endif()
-
           foreach(L IN LISTS HDF5_${__lang}_LIBRARY_NAMES)
-            find_library(HDF5_${__lang}_LIBRARY_${L} ${L} ${HDF5_${__lang}_LIBRARY_DIRS})
+            set(_HDF5_SEARCH_NAMES_LOCAL)
+            if("x${L}" MATCHES "hdf5")
+              # hdf5 library
+              set(_HDF5_SEARCH_OPTS_LOCAL ${_HDF5_SEARCH_OPTS})
+              if(UNIX AND HDF5_USE_STATIC_LIBRARIES)
+                set(_HDF5_SEARCH_NAMES_LOCAL lib${L}.a)
+              endif()
+            else()
+              # external library
+              set(_HDF5_SEARCH_OPTS_LOCAL)
+            endif()
+            find_library(HDF5_${__lang}_LIBRARY_${L}
+              NAMES ${_HDF5_SEARCH_NAMES_LOCAL} ${L} NAMES_PER_DIR
+              HINTS ${HDF5_${__lang}_LIBRARY_DIRS}
+                    ${HDF5_ROOT}
+              ${_HDF5_SEARCH_OPTS_LOCAL}
+              )
+            unset(_HDF5_SEARCH_OPTS_LOCAL)
+            unset(_HDF5_SEARCH_NAMES_LOCAL)
             if(HDF5_${__lang}_LIBRARY_${L})
               list(APPEND HDF5_${__lang}_LIBRARIES ${HDF5_${__lang}_LIBRARY_${L}})
             else()
@@ -544,7 +551,25 @@ if(NOT HDF5_FOUND AND NOT HDF5_ROOT)
           if(FIND_HL)
             set(HDF5_${__lang}_HL_LIBRARIES)
             foreach(L IN LISTS HDF5_${__lang}_HL_LIBRARY_NAMES)
-              find_library(HDF5_${__lang}_LIBRARY_${L} ${L} ${HDF5_${__lang}_LIBRARY_DIRS})
+              set(_HDF5_SEARCH_NAMES_LOCAL)
+              if("x${L}" MATCHES "hdf5")
+                # hdf5 library
+                set(_HDF5_SEARCH_OPTS_LOCAL ${_HDF5_SEARCH_OPTS})
+                if(UNIX AND HDF5_USE_STATIC_LIBRARIES)
+                  set(_HDF5_SEARCH_NAMES_LOCAL lib${L}.a)
+                endif()
+              else()
+                # external library
+                set(_HDF5_SEARCH_OPTS_LOCAL)
+              endif()
+              find_library(HDF5_${__lang}_LIBRARY_${L}
+                NAMES ${_HDF5_SEARCH_NAMES_LOCAL} ${L} NAMES_PER_DIR
+                HINTS ${HDF5_${__lang}_LIBRARY_DIRS}
+                      ${HDF5_ROOT}
+                ${_HDF5_SEARCH_OPTS_LOCAL}
+                )
+              unset(_HDF5_SEARCH_OPTS_LOCAL)
+              unset(_HDF5_SEARCH_NAMES_LOCAL)
               if(HDF5_${__lang}_LIBRARY_${L})
                 list(APPEND HDF5_${__lang}_HL_LIBRARIES ${HDF5_${__lang}_LIBRARY_${L}})
               else()
@@ -554,8 +579,6 @@ if(NOT HDF5_FOUND AND NOT HDF5_ROOT)
             set(HDF5_HL_FOUND True)
           endif()
 
-          set(CMAKE_FIND_LIBRARY_SUFFIXES ${_HDF5_CMAKE_FIND_LIBRARY_SUFFIXES})
-
           set(HDF5_${__lang}_FOUND True)
           mark_as_advanced(HDF5_${__lang}_DEFINITIONS)
           mark_as_advanced(HDF5_${__lang}_INCLUDE_DIRS)
@@ -626,14 +649,11 @@ elseif(NOT HDF5_FOUND AND NOT _HDF5_NEED_TO_SEARCH)
   endif()
 endif()
 
-if(HDF5_ROOT)
-    set(SEARCH_OPTS NO_DEFAULT_PATH)
-endif()
 find_program( HDF5_DIFF_EXECUTABLE
     NAMES h5diff
     HINTS ${HDF5_ROOT}
     PATH_SUFFIXES bin Bin
-    ${SEARCH_OPTS}
+    ${_HDF5_SEARCH_OPTS}
     DOC "HDF5 file differencing tool." )
 mark_as_advanced( HDF5_DIFF_EXECUTABLE )
 
@@ -650,9 +670,9 @@ if( NOT HDF5_FOUND )
 
     foreach(__lang IN LISTS HDF5_LANGUAGE_BINDINGS)
         # find the HDF5 include directories
-        if(LANGUAGE STREQUAL "Fortran")
+        if("${__lang}" STREQUAL "Fortran")
             set(HDF5_INCLUDE_FILENAME hdf5.mod)
-        elseif(LANGUAGE STREQUAL "CXX")
+        elseif("${__lang}" STREQUAL "CXX")
             set(HDF5_INCLUDE_FILENAME H5Cpp.h)
         else()
             set(HDF5_INCLUDE_FILENAME hdf5.h)
@@ -662,9 +682,9 @@ if( NOT HDF5_FOUND )
             HINTS ${HDF5_ROOT}
             PATHS $ENV{HOME}/.local/include
             PATH_SUFFIXES include Include
-            ${SEARCH_OPTS}
+            ${_HDF5_SEARCH_OPTS}
         )
-        mark_as_advanced(HDF5_${LANGUAGE}_INCLUDE_DIR)
+        mark_as_advanced(HDF5_${__lang}_INCLUDE_DIR)
         list(APPEND HDF5_INCLUDE_DIRS ${HDF5_${__lang}_INCLUDE_DIR})
 
         # find the HDF5 libraries
@@ -686,12 +706,12 @@ if( NOT HDF5_FOUND )
             find_library(HDF5_${LIB}_LIBRARY_DEBUG
                 NAMES ${THIS_LIBRARY_SEARCH_DEBUG}
                 HINTS ${HDF5_ROOT} PATH_SUFFIXES lib Lib
-                ${SEARCH_OPTS}
+                ${_HDF5_SEARCH_OPTS}
             )
             find_library( HDF5_${LIB}_LIBRARY_RELEASE
                 NAMES ${THIS_LIBRARY_SEARCH_RELEASE}
                 HINTS ${HDF5_ROOT} PATH_SUFFIXES lib Lib
-                ${SEARCH_OPTS}
+                ${_HDF5_SEARCH_OPTS}
             )
             select_library_configurations( HDF5_${LIB} )
             list(APPEND HDF5_${__lang}_LIBRARIES ${HDF5_${LIB}_LIBRARY})
@@ -723,12 +743,12 @@ if( NOT HDF5_FOUND )
                 find_library(HDF5_${LIB}_LIBRARY_DEBUG
                     NAMES ${THIS_LIBRARY_SEARCH_DEBUG}
                     HINTS ${HDF5_ROOT} PATH_SUFFIXES lib Lib
-                    ${SEARCH_OPTS}
+                    ${_HDF5_SEARCH_OPTS}
                 )
                 find_library( HDF5_${LIB}_LIBRARY_RELEASE
                     NAMES ${THIS_LIBRARY_SEARCH_RELEASE}
                     HINTS ${HDF5_ROOT} PATH_SUFFIXES lib Lib
-                    ${SEARCH_OPTS}
+                    ${_HDF5_SEARCH_OPTS}
                 )
                 select_library_configurations( HDF5_${LIB} )
                 list(APPEND HDF5_${__lang}_HL_LIBRARIES ${HDF5_${LIB}_LIBRARY})
@@ -780,17 +800,18 @@ if( NOT HDF5_FOUND )
         "HDF5 library compiled with parallel IO support" )
     mark_as_advanced( HDF5_IS_PARALLEL )
 
-    # For backwards compatibility we set HDF5_INCLUDE_DIR to the value of
-    # HDF5_INCLUDE_DIRS
-    if( HDF5_INCLUDE_DIRS )
-        set( HDF5_INCLUDE_DIR "${HDF5_INCLUDE_DIRS}" )
-    endif()
     set(HDF5_REQUIRED_VARS HDF5_LIBRARIES HDF5_INCLUDE_DIRS)
     if(FIND_HL)
         list(APPEND HDF5_REQUIRED_VARS HDF5_HL_LIBRARIES)
     endif()
 endif()
 
+# For backwards compatibility we set HDF5_INCLUDE_DIR to the value of
+# HDF5_INCLUDE_DIRS
+if( HDF5_INCLUDE_DIRS )
+  set( HDF5_INCLUDE_DIR "${HDF5_INCLUDE_DIRS}" )
+endif()
+
 # If HDF5_REQUIRED_VARS is empty at this point, then it's likely that
 # something external is trying to explicitly pass already found
 # locations
@@ -803,3 +824,5 @@ find_package_handle_standard_args(HDF5
     VERSION_VAR   HDF5_VERSION
     HANDLE_COMPONENTS
 )
+
+unset(_HDF5_SEARCH_OPTS)
diff --git a/Modules/FindHSPELL.cmake b/Modules/FindHSPELL.cmake
index 72d70ad..bb0e2f0 100644
--- a/Modules/FindHSPELL.cmake
+++ b/Modules/FindHSPELL.cmake
@@ -36,12 +36,9 @@ if (HSPELL_INCLUDE_DIR)
     unset(HSPELL_H)
 endif()
 
-# handle the QUIETLY and REQUIRED arguments and set HSPELL_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(HSPELL
                                   REQUIRED_VARS HSPELL_LIBRARIES HSPELL_INCLUDE_DIR
                                   VERSION_VAR HSPELL_VERSION_STRING)
 
 mark_as_advanced(HSPELL_INCLUDE_DIR HSPELL_LIBRARIES)
-
diff --git a/Modules/FindHg.cmake b/Modules/FindHg.cmake
index ef85abc..8aa553e 100644
--- a/Modules/FindHg.cmake
+++ b/Modules/FindHg.cmake
@@ -90,8 +90,6 @@ if(HG_EXECUTABLE)
   endmacro(HG_WC_INFO)
 endif()
 
-# Handle the QUIETLY and REQUIRED arguments and set HG_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 find_package_handle_standard_args(Hg
                                   REQUIRED_VARS HG_EXECUTABLE
diff --git a/Modules/FindICU.cmake b/Modules/FindICU.cmake
index 36dd67e..5210f08 100644
--- a/Modules/FindICU.cmake
+++ b/Modules/FindICU.cmake
@@ -126,6 +126,7 @@ function(_ICU_FIND)
   # Generic 64-bit and 32-bit directories
   list(APPEND icu_binary_suffixes "${_bin64}" "bin")
   list(APPEND icu_library_suffixes "${_lib64}" "lib")
+  list(APPEND icu_include_suffixes "include")
 
   # Find all ICU programs
   foreach(program ${icu_programs})
diff --git a/Modules/FindIcotool.cmake b/Modules/FindIcotool.cmake
index bd3e327..26e95a0 100644
--- a/Modules/FindIcotool.cmake
+++ b/Modules/FindIcotool.cmake
@@ -39,8 +39,6 @@ if(ICOTOOL_EXECUTABLE)
   unset(_icotool_version)
 endif()
 
-# handle the QUIETLY and REQUIRED arguments and set ICOTOOL_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(
   Icotool
diff --git a/Modules/FindJNI.cmake b/Modules/FindJNI.cmake
index 39e504f..cebba10 100644
--- a/Modules/FindJNI.cmake
+++ b/Modules/FindJNI.cmake
@@ -145,6 +145,9 @@ JAVA_APPEND_LIBRARY_DIRECTORIES(JAVA_AWT_LIBRARY_DIRECTORIES
   /usr/lib/jvm/default-java/jre/lib/{libarch}
   /usr/lib/jvm/default-java/jre/lib
   /usr/lib/jvm/default-java/lib
+  # Arch Linux specific paths for default JVM
+  /usr/lib/jvm/default/jre/lib/{libarch}
+  /usr/lib/jvm/default/lib/{libarch}
   # Ubuntu specific paths for default JVM
   /usr/lib/jvm/java-8-openjdk-{libarch}/jre/lib/{libarch}     # Ubuntu 15.10
   /usr/lib/jvm/java-7-openjdk-{libarch}/jre/lib/{libarch}     # Ubuntu 15.10
@@ -200,6 +203,8 @@ JAVA_APPEND_LIBRARY_DIRECTORIES(JAVA_AWT_INCLUDE_DIRECTORIES
   /opt/sun-jdk-1.5.0.04/include
   # Debian specific path for default JVM
   /usr/lib/jvm/default-java/include
+  # Arch specific path for default JVM
+  /usr/lib/jvm/default/include
   # OpenBSD specific path for default JVM
   /usr/local/jdk-1.7.0/include
   /usr/local/jdk-1.6.0/include
diff --git a/Modules/FindJPEG.cmake b/Modules/FindJPEG.cmake
index b644181..e233714 100644
--- a/Modules/FindJPEG.cmake
+++ b/Modules/FindJPEG.cmake
@@ -26,8 +26,6 @@ find_path(JPEG_INCLUDE_DIR jpeglib.h)
 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
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(JPEG DEFAULT_MSG JPEG_LIBRARY JPEG_INCLUDE_DIR)
 
diff --git a/Modules/FindJasper.cmake b/Modules/FindJasper.cmake
index 748510e..db76657 100644
--- a/Modules/FindJasper.cmake
+++ b/Modules/FindJasper.cmake
@@ -34,8 +34,6 @@ if (JASPER_INCLUDE_DIR AND EXISTS "${JASPER_INCLUDE_DIR}/jasper/jas_config.h")
     string(REGEX REPLACE "^#define[\t ]+JAS_VERSION[\t ]+\"([^\"]+)\".*" "\\1" JASPER_VERSION_STRING "${jasper_version_str}")
 endif ()
 
-# handle the QUIETLY and REQUIRED arguments and set JASPER_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(Jasper
                                   REQUIRED_VARS JASPER_LIBRARIES JASPER_INCLUDE_DIR JPEG_LIBRARIES
diff --git a/Modules/FindJava.cmake b/Modules/FindJava.cmake
index e30917d..4265a97 100644
--- a/Modules/FindJava.cmake
+++ b/Modules/FindJava.cmake
@@ -86,6 +86,14 @@ list(APPEND _JAVA_HINTS
   "[HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Development Kit\\1.5;JavaHome]/bin"
   "[HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Development Kit\\1.4;JavaHome]/bin"
   "[HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Development Kit\\1.3;JavaHome]/bin"
+  "[HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment\\2.0;JavaHome]/bin"
+  "[HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment\\1.9;JavaHome]/bin"
+  "[HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment\\1.8;JavaHome]/bin"
+  "[HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment\\1.7;JavaHome]/bin"
+  "[HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment\\2.6;JavaHome]/bin"
+  "[HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment\\1.5;JavaHome]/bin"
+  "[HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment\\1.4;JavaHome]/bin"
+  "[HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment\\1.3;JavaHome]/bin"
   )
 # Hard-coded guesses should still go in PATHS. This ensures that the user
 # environment can always override hard guesses.
@@ -262,4 +270,3 @@ mark_as_advanced(
 set(JAVA_RUNTIME ${Java_JAVA_EXECUTABLE})
 set(JAVA_ARCHIVE ${Java_JAR_EXECUTABLE})
 set(JAVA_COMPILE ${Java_JAVAC_EXECUTABLE})
-
diff --git a/Modules/FindLAPACK.cmake b/Modules/FindLAPACK.cmake
index fe6af91..a451e6c 100644
--- a/Modules/FindLAPACK.cmake
+++ b/Modules/FindLAPACK.cmake
@@ -33,8 +33,15 @@
 #      all the possibilities
 #   BLA_F95     if set on tries to find the f95 interfaces for BLAS/LAPACK
 #
-# ## List of vendors (BLA_VENDOR) valid in this module # Intel(mkl),
-# OpenBLAS, ACML,Apple, NAS, Generic
+# List of vendors (BLA_VENDOR) valid in this module:
+#
+# * Intel(mkl)
+# * OpenBLAS
+# * ACML
+# * Apple
+# * NAS
+# * Generic
+#
 
 set(_lapack_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
 
diff --git a/Modules/FindLATEX.cmake b/Modules/FindLATEX.cmake
index 1d8f6ce..d1f4fa4 100644
--- a/Modules/FindLATEX.cmake
+++ b/Modules/FindLATEX.cmake
@@ -271,7 +271,6 @@ mark_as_advanced(
   HTLATEX_COMPILER
 )
 
-# handle variables for found Latex and its components
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 find_package_handle_standard_args(LATEX
   REQUIRED_VARS LATEX_COMPILER
diff --git a/Modules/FindLTTngUST.cmake b/Modules/FindLTTngUST.cmake
index 8781bae..00d5e7a 100644
--- a/Modules/FindLTTngUST.cmake
+++ b/Modules/FindLTTngUST.cmake
@@ -90,8 +90,6 @@ if(LTTNGUST_INCLUDE_DIRS AND LTTNGUST_LIBRARIES)
   set(LTTNGUST_LIBRARIES ${LTTNGUST_LIBRARIES} ${CMAKE_DL_LIBS})
 endif()
 
-# handle the QUIETLY and REQUIRED arguments and set LTTNGUST_FOUND to
-# TRUE if all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 find_package_handle_standard_args(LTTngUST FOUND_VAR LTTNGUST_FOUND
                                   REQUIRED_VARS LTTNGUST_LIBRARIES
diff --git a/Modules/FindLibArchive.cmake b/Modules/FindLibArchive.cmake
index 1a26bbb..38e512f 100644
--- a/Modules/FindLibArchive.cmake
+++ b/Modules/FindLibArchive.cmake
@@ -46,17 +46,11 @@ if(LibArchive_INCLUDE_DIR AND EXISTS "${LibArchive_INCLUDE_DIR}/archive.h")
   unset(_LibArchive_VERSION_STRING)
 endif()
 
-# Handle the QUIETLY and REQUIRED arguments and set LIBARCHIVE_FOUND
-# to TRUE if all listed variables are TRUE.
-# (Use ${CMAKE_ROOT}/Modules instead of ${CMAKE_CURRENT_LIST_DIR} because CMake
-#  itself includes this FindLibArchive when built with an older CMake that does
-#  not provide it.  The older CMake also does not have CMAKE_CURRENT_LIST_DIR.)
-include(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake)
+include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 find_package_handle_standard_args(LibArchive
                                   REQUIRED_VARS LibArchive_LIBRARY LibArchive_INCLUDE_DIR
                                   VERSION_VAR LibArchive_VERSION
   )
-set(LibArchive_FOUND ${LIBARCHIVE_FOUND})
 unset(LIBARCHIVE_FOUND)
 
 if(LibArchive_FOUND)
diff --git a/Modules/FindLibXml2.cmake b/Modules/FindLibXml2.cmake
index 9580981..613f927 100644
--- a/Modules/FindLibXml2.cmake
+++ b/Modules/FindLibXml2.cmake
@@ -52,8 +52,6 @@ elseif(LIBXML2_INCLUDE_DIR AND EXISTS "${LIBXML2_INCLUDE_DIR}/libxml/xmlversion.
     unset(libxml2_version_str)
 endif()
 
-# handle the QUIETLY and REQUIRED arguments and set LIBXML2_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibXml2
                                   REQUIRED_VARS LIBXML2_LIBRARIES LIBXML2_INCLUDE_DIR
diff --git a/Modules/FindLua.cmake b/Modules/FindLua.cmake
index 5be0428..b59b9b3 100644
--- a/Modules/FindLua.cmake
+++ b/Modules/FindLua.cmake
@@ -75,16 +75,9 @@ function(_lua_set_version_vars)
              include/lua${CMAKE_MATCH_1}.${CMAKE_MATCH_2}
              include/lua-${CMAKE_MATCH_1}.${CMAKE_MATCH_2}
         )
-        list(APPEND _lua_library_names
-             lua${CMAKE_MATCH_1}${CMAKE_MATCH_2}
-             lua${CMAKE_MATCH_1}.${CMAKE_MATCH_2}
-             lua-${CMAKE_MATCH_1}.${CMAKE_MATCH_2}
-             lua.${CMAKE_MATCH_1}.${CMAKE_MATCH_2}
-        )
     endforeach ()
 
     set(_lua_include_subdirs "${_lua_include_subdirs}" PARENT_SCOPE)
-    set(_lua_library_names "${_lua_library_names}" PARENT_SCOPE)
     set(_lua_append_versions "${_lua_append_versions}" PARENT_SCOPE)
 endfunction(_lua_set_version_vars)
 
@@ -152,6 +145,15 @@ endif ()
 unset(_lua_include_subdirs)
 unset(_lua_append_versions)
 
+if (LUA_VERSION_STRING)
+    set(_lua_library_names
+        lua${LUA_VERSION_MAJOR}${LUA_VERSION_MINOR}
+        lua${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}
+        lua-${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}
+        lua.${LUA_VERSION_MAJOR}.${LUA_VERSION_MINOR}
+    )
+endif ()
+
 find_library(LUA_LIBRARY
   NAMES ${_lua_library_names} lua
   HINTS
@@ -172,6 +174,13 @@ if (LUA_LIBRARY)
     if (UNIX AND NOT APPLE AND NOT BEOS)
         find_library(LUA_MATH_LIBRARY m)
         set(LUA_LIBRARIES "${LUA_LIBRARY};${LUA_MATH_LIBRARY}")
+
+        # include dl library for statically-linked Lua library
+        get_filename_component(LUA_LIB_EXT ${LUA_LIBRARY} EXT)
+        if(LUA_LIB_EXT STREQUAL CMAKE_STATIC_LIBRARY_SUFFIX)
+          list(APPEND LUA_LIBRARIES ${CMAKE_DL_LIBS})
+        endif()
+
     # For Windows and Mac, don't need to explicitly include the math library
     else ()
         set(LUA_LIBRARIES "${LUA_LIBRARY}")
diff --git a/Modules/FindMPEG.cmake b/Modules/FindMPEG.cmake
index aff464e..cd1b021 100644
--- a/Modules/FindMPEG.cmake
+++ b/Modules/FindMPEG.cmake
@@ -34,8 +34,6 @@ find_library( MPEG_vo_LIBRARY vo
   /usr/local/livid/mpeg2dec/libvo/.libs
 )
 
-# handle the QUIETLY and REQUIRED arguments and set MPEG2_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(MPEG DEFAULT_MSG MPEG_INCLUDE_DIR MPEG_mpeg2_LIBRARY MPEG_vo_LIBRARY)
 
diff --git a/Modules/FindMPEG2.cmake b/Modules/FindMPEG2.cmake
index e28054d..2c75d7b 100644
--- a/Modules/FindMPEG2.cmake
+++ b/Modules/FindMPEG2.cmake
@@ -35,9 +35,6 @@ find_library( MPEG2_vo_LIBRARY vo
   /usr/local/livid/mpeg2dec/libvo/.libs
 )
 
-
-# handle the QUIETLY and REQUIRED arguments and set MPEG2_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(MPEG2 DEFAULT_MSG MPEG2_mpeg2_LIBRARY MPEG2_INCLUDE_DIR)
 
diff --git a/Modules/FindMPI.cmake b/Modules/FindMPI.cmake
index 676e1bc..ff2c4de 100644
--- a/Modules/FindMPI.cmake
+++ b/Modules/FindMPI.cmake
@@ -91,7 +91,6 @@
 #
 # In new projects, please use the ``MPI_<lang>_XXX`` equivalents.
 
-# include this to handle the QUIETLY and REQUIRED arguments
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 
 #
@@ -114,9 +113,10 @@ include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 #
 
 # Start out with the generic MPI compiler names, as these are most commonly used.
-set(_MPI_C_COMPILER_NAMES                  mpicc    mpcc      mpicc_r mpcc_r)
+set(_MPI_C_COMPILER_NAMES                  mpicc    mpcc      mpicc_r mpcc_r  mpicc.bat)
 set(_MPI_CXX_COMPILER_NAMES                mpicxx   mpiCC     mpcxx   mpCC    mpic++   mpc++
-                                           mpicxx_r mpiCC_r   mpcxx_r mpCC_r  mpic++_r mpc++_r)
+                                           mpicxx_r mpiCC_r   mpcxx_r mpCC_r  mpic++_r mpc++_r
+                                           mpicxx.bat)
 set(_MPI_Fortran_COMPILER_NAMES            mpif95   mpif95_r  mpf95   mpf95_r
                                            mpif90   mpif90_r  mpf90   mpf90_r
                                            mpif77   mpif77_r  mpf77   mpf77_r)
@@ -128,9 +128,9 @@ set(_MPI_GNU_Fortran_COMPILER_NAMES        mpigfortran mpgfortran mpigfortran_r
                                            mpig77 mpig77_r mpg77 mpg77_r)
 
 # Intel MPI compiler names
-set(_MPI_Intel_C_COMPILER_NAMES            mpiicc)
-set(_MPI_Intel_CXX_COMPILER_NAMES          mpiicpc  mpiicxx mpiic++ mpiiCC)
-set(_MPI_Intel_Fortran_COMPILER_NAMES      mpiifort mpiif95 mpiif90 mpiif77)
+set(_MPI_Intel_C_COMPILER_NAMES            mpiicc   mpiicc.bat)
+set(_MPI_Intel_CXX_COMPILER_NAMES          mpiicpc  mpiicxx mpiic++ mpiiCC  mpiicpc.bat)
+set(_MPI_Intel_Fortran_COMPILER_NAMES      mpiifort mpiif95 mpiif90 mpiif77 mpiifort.bat)
 
 # PGI compiler names
 set(_MPI_PGI_C_COMPILER_NAMES              mpipgcc mppgcc)
@@ -314,6 +314,7 @@ function (interrogate_mpi_compiler lang try_libs)
         set(MPI_COMPILE_FLAGS_WORK)
 
         foreach(FLAG ${MPI_ALL_COMPILE_FLAGS})
+          string(REGEX REPLACE "^ " "" FLAG ${FLAG})
           if (MPI_COMPILE_FLAGS_WORK)
             string(APPEND MPI_COMPILE_FLAGS_WORK " ${FLAG}")
           else()
@@ -323,9 +324,13 @@ function (interrogate_mpi_compiler lang try_libs)
 
         # Extract include paths from compile command line
         string(REGEX MATCHALL "(^| )-I([^\" ]+|\"[^\"]+\")" MPI_ALL_INCLUDE_PATHS "${MPI_COMPILE_CMDLINE}")
+        set(MPI_INCLUDE_PATH_WORK)
+
         foreach(IPATH ${MPI_ALL_INCLUDE_PATHS})
           string(REGEX REPLACE "^ ?-I" "" IPATH ${IPATH})
           string(REPLACE "//" "/" IPATH ${IPATH})
+          string(REPLACE "\"" "" IPATH ${IPATH})
+          file(TO_CMAKE_PATH "${IPATH}" IPATH)
           list(APPEND MPI_INCLUDE_PATH_WORK ${IPATH})
         endforeach()
 
@@ -363,6 +368,7 @@ function (interrogate_mpi_compiler lang try_libs)
         string(REGEX MATCHALL "(^| )(-Wl,|-Xlinker )([^\" ]+|\"[^\"]+\")" MPI_ALL_LINK_FLAGS "${MPI_LINK_CMDLINE}")
         set(MPI_LINK_FLAGS_WORK)
         foreach(FLAG ${MPI_ALL_LINK_FLAGS})
+          string(REGEX REPLACE "^ " "" FLAG ${FLAG})
           if (MPI_LINK_FLAGS_WORK)
             string(APPEND MPI_LINK_FLAGS_WORK " ${FLAG}")
           else()
diff --git a/Modules/FindMotif.cmake b/Modules/FindMotif.cmake
index 3923238..7304d95 100644
--- a/Modules/FindMotif.cmake
+++ b/Modules/FindMotif.cmake
@@ -30,12 +30,9 @@ if(UNIX)
 
 endif()
 
-# handle the QUIETLY and REQUIRED arguments and set MOTIF_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(Motif DEFAULT_MSG MOTIF_LIBRARIES MOTIF_INCLUDE_DIR)
 
-
 mark_as_advanced(
   MOTIF_INCLUDE_DIR
   MOTIF_LIBRARIES
diff --git a/Modules/FindOpenAL.cmake b/Modules/FindOpenAL.cmake
index 1abb0d6..8622b4c 100644
--- a/Modules/FindOpenAL.cmake
+++ b/Modules/FindOpenAL.cmake
@@ -92,8 +92,6 @@ find_library(OPENAL_LIBRARY
 
 unset(_OpenAL_ARCH_DIR)
 
-# handle the QUIETLY and REQUIRED arguments and set OPENAL_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(OpenAL  DEFAULT_MSG  OPENAL_LIBRARY OPENAL_INCLUDE_DIR)
 
diff --git a/Modules/FindOpenGL.cmake b/Modules/FindOpenGL.cmake
index e487726..503d955 100644
--- a/Modules/FindOpenGL.cmake
+++ b/Modules/FindOpenGL.cmake
@@ -7,6 +7,16 @@
 #
 # FindModule for OpenGL and GLU.
 #
+# IMPORTED Targets
+# ^^^^^^^^^^^^^^^^
+#
+# This module defines the :prop_tgt:`IMPORTED` targets:
+#
+# ``OpenGL::GL``
+#  Defined if the system has OpenGL.
+# ``OpenGL::GLU``
+#  Defined if the system has GLU.
+#
 # Result Variables
 # ^^^^^^^^^^^^^^^^
 #
@@ -156,12 +166,59 @@ endif()
 # This deprecated setting is for backward compatibility with CMake1.4
 set(OPENGL_INCLUDE_PATH ${OPENGL_INCLUDE_DIR})
 
-# handle the QUIETLY and REQUIRED arguments and set OPENGL_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(OpenGL REQUIRED_VARS ${_OpenGL_REQUIRED_VARS})
 unset(_OpenGL_REQUIRED_VARS)
 
+# OpenGL:: targets
+if(OPENGL_FOUND)
+  if(NOT TARGET OpenGL::GL)
+    if(IS_ABSOLUTE "${OPENGL_gl_LIBRARY}")
+      add_library(OpenGL::GL UNKNOWN IMPORTED)
+      if(OPENGL_gl_LIBRARY MATCHES "/([^/]+)\\.framework$")
+        set(_gl_fw "${OPENGL_gl_LIBRARY}/${CMAKE_MATCH_1}")
+        if(EXISTS "${_gl_fw}.tbd")
+          set(_gl_fw "${_gl_fw}.tbd")
+        endif()
+        set_target_properties(OpenGL::GL PROPERTIES
+          IMPORTED_LOCATION "${_gl_fw}")
+      else()
+        set_target_properties(OpenGL::GL PROPERTIES
+          IMPORTED_LOCATION "${OPENGL_gl_LIBRARY}")
+      endif()
+    else()
+      add_library(OpenGL::GL INTERFACE IMPORTED)
+      set_target_properties(OpenGL::GL PROPERTIES
+        IMPORTED_LIBNAME "${OPENGL_gl_LIBRARY}")
+    endif()
+    set_target_properties(OpenGL::GL PROPERTIES
+      INTERFACE_INCLUDE_DIRECTORIES "${OPENGL_INCLUDE_DIR}")
+  endif()
+
+  if(OPENGL_GLU_FOUND AND NOT TARGET OpenGL::GLU)
+    if(IS_ABSOLUTE "${OPENGL_glu_LIBRARY}")
+      add_library(OpenGL::GLU UNKNOWN IMPORTED)
+      if(OPENGL_glu_LIBRARY MATCHES "/([^/]+)\\.framework$")
+        set(_glu_fw "${OPENGL_glu_LIBRARY}/${CMAKE_MATCH_1}")
+        if(EXISTS "${_glu_fw}.tbd")
+          set(_glu_fw "${_glu_fw}.tbd")
+        endif()
+        set_target_properties(OpenGL::GLU PROPERTIES
+          IMPORTED_LOCATION "${_glu_fw}")
+      else()
+        set_target_properties(OpenGL::GLU PROPERTIES
+          IMPORTED_LOCATION "${OPENGL_glu_LIBRARY}")
+      endif()
+    else()
+      add_library(OpenGL::GLU INTERFACE IMPORTED)
+      set_target_properties(OpenGL::GLU PROPERTIES
+        IMPORTED_LIBNAME "${OPENGL_glu_LIBRARY}")
+    endif()
+    set_target_properties(OpenGL::GLU PROPERTIES
+      INTERFACE_LINK_LIBRARIES OpenGL::GL)
+  endif()
+endif()
+
 mark_as_advanced(
   OPENGL_INCLUDE_DIR
   OPENGL_xmesa_INCLUDE_DIR
diff --git a/Modules/FindOpenSSL.cmake b/Modules/FindOpenSSL.cmake
index 30fc5c6..6259ce1 100644
--- a/Modules/FindOpenSSL.cmake
+++ b/Modules/FindOpenSSL.cmake
@@ -204,7 +204,6 @@ if(WIN32 AND NOT CYGWIN)
                      SSL_EAY_LIBRARY_DEBUG SSL_EAY_LIBRARY_RELEASE)
     set(OPENSSL_SSL_LIBRARY ${SSL_EAY_LIBRARY} )
     set(OPENSSL_CRYPTO_LIBRARY ${LIB_EAY_LIBRARY} )
-    set(OPENSSL_LIBRARIES ${SSL_EAY_LIBRARY} ${LIB_EAY_LIBRARY} )
   elseif(MINGW)
     # same player, for MinGW
     set(LIB_EAY_NAMES crypto libeay32)
@@ -232,7 +231,6 @@ if(WIN32 AND NOT CYGWIN)
     mark_as_advanced(SSL_EAY LIB_EAY)
     set(OPENSSL_SSL_LIBRARY ${SSL_EAY} )
     set(OPENSSL_CRYPTO_LIBRARY ${LIB_EAY} )
-    set(OPENSSL_LIBRARIES ${SSL_EAY} ${LIB_EAY} )
     unset(LIB_EAY_NAMES)
     unset(SSL_EAY_NAMES)
   else()
@@ -264,7 +262,6 @@ if(WIN32 AND NOT CYGWIN)
     mark_as_advanced(SSL_EAY LIB_EAY)
     set(OPENSSL_SSL_LIBRARY ${SSL_EAY} )
     set(OPENSSL_CRYPTO_LIBRARY ${LIB_EAY} )
-    set(OPENSSL_LIBRARIES ${SSL_EAY} ${LIB_EAY} )
   endif()
 else()
 
@@ -298,8 +295,6 @@ else()
   set(OPENSSL_SSL_LIBRARIES ${OPENSSL_SSL_LIBRARY})
   set(OPENSSL_CRYPTO_LIBRARIES ${OPENSSL_CRYPTO_LIBRARY})
 
-  set(OPENSSL_LIBRARIES ${OPENSSL_SSL_LIBRARY} ${OPENSSL_CRYPTO_LIBRARY})
-
 endif()
 
 function(from_hex HEX DEC)
@@ -371,10 +366,13 @@ endif ()
 
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 
+set(OPENSSL_LIBRARIES ${OPENSSL_SSL_LIBRARY} ${OPENSSL_CRYPTO_LIBRARY} )
+
 if (OPENSSL_VERSION)
   find_package_handle_standard_args(OpenSSL
     REQUIRED_VARS
-      OPENSSL_LIBRARIES
+      OPENSSL_SSL_LIBRARY
+      OPENSSL_CRYPTO_LIBRARY
       OPENSSL_INCLUDE_DIR
     VERSION_VAR
       OPENSSL_VERSION
@@ -383,7 +381,8 @@ if (OPENSSL_VERSION)
   )
 else ()
   find_package_handle_standard_args(OpenSSL "Could NOT find OpenSSL, try to set the path to OpenSSL root folder in the system variable OPENSSL_ROOT_DIR"
-    OPENSSL_LIBRARIES
+    OPENSSL_SSL_LIBRARY
+    OPENSSL_CRYPTO_LIBRARY
     OPENSSL_INCLUDE_DIR
   )
 endif ()
diff --git a/Modules/FindOpenSceneGraph.cmake b/Modules/FindOpenSceneGraph.cmake
index af873fa..425aa45 100644
--- a/Modules/FindOpenSceneGraph.cmake
+++ b/Modules/FindOpenSceneGraph.cmake
@@ -227,4 +227,3 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(OpenSceneGraph
 unset(_osg_component_founds)
 
 set(OPENSCENEGRAPH_INCLUDE_DIRS ${OPENSCENEGRAPH_INCLUDE_DIR})
-
diff --git a/Modules/FindPNG.cmake b/Modules/FindPNG.cmake
index 6f94d50..dceb6bc 100644
--- a/Modules/FindPNG.cmake
+++ b/Modules/FindPNG.cmake
@@ -25,7 +25,7 @@
 # ``PNG_LIBRARIES``
 #   the libraries to link against to use PNG.
 # ``PNG_DEFINITIONS``
-#   You should add_definitons(${PNG_DEFINITIONS}) before compiling code
+#   You should add_definitions(${PNG_DEFINITIONS}) before compiling code
 #   that includes png library files.
 # ``PNG_FOUND``
 #   If false, do not try to use PNG.
@@ -140,8 +140,6 @@ if(ZLIB_FOUND)
   endif ()
 endif()
 
-# handle the QUIETLY and REQUIRED arguments and set PNG_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 find_package_handle_standard_args(PNG
                                   REQUIRED_VARS PNG_LIBRARY PNG_PNG_INCLUDE_DIR
diff --git a/Modules/FindPackageHandleStandardArgs.cmake b/Modules/FindPackageHandleStandardArgs.cmake
index 7b46877..b77925d 100644
--- a/Modules/FindPackageHandleStandardArgs.cmake
+++ b/Modules/FindPackageHandleStandardArgs.cmake
@@ -130,7 +130,6 @@ message.
 #]=======================================================================]
 
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageMessage.cmake)
-include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake)
 
 # internal helper macro
 macro(_FPHSA_FAILURE_MESSAGE _msg)
diff --git a/Modules/FindPerl.cmake b/Modules/FindPerl.cmake
index a0c8a33..423fc69 100644
--- a/Modules/FindPerl.cmake
+++ b/Modules/FindPerl.cmake
@@ -70,8 +70,6 @@ endif()
 # Deprecated settings for compatibility with CMake1.4
 set(PERL ${PERL_EXECUTABLE})
 
-# handle the QUIETLY and REQUIRED arguments and set PERL_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(Perl
                                   REQUIRED_VARS PERL_EXECUTABLE
diff --git a/Modules/FindPerlLibs.cmake b/Modules/FindPerlLibs.cmake
index 42729d7..e01e75e 100644
--- a/Modules/FindPerlLibs.cmake
+++ b/Modules/FindPerlLibs.cmake
@@ -239,8 +239,6 @@ if (PERL_EXECUTABLE)
 
 endif ()
 
-# handle the QUIETLY and REQUIRED arguments and set PERLLIBS_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 find_package_handle_standard_args(PerlLibs REQUIRED_VARS PERL_LIBRARY PERL_INCLUDE_PATH
                                            VERSION_VAR PERL_VERSION_STRING)
diff --git a/Modules/FindPhysFS.cmake b/Modules/FindPhysFS.cmake
index fe5b397..cfe9b0f 100644
--- a/Modules/FindPhysFS.cmake
+++ b/Modules/FindPhysFS.cmake
@@ -43,8 +43,5 @@ find_library(PHYSFS_LIBRARY
   /opt
 )
 
-# handle the QUIETLY and REQUIRED arguments and set PHYSFS_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(PhysFS DEFAULT_MSG PHYSFS_LIBRARY PHYSFS_INCLUDE_DIR)
-
diff --git a/Modules/FindPkgConfig.cmake b/Modules/FindPkgConfig.cmake
index 3f75b19..1958f4b 100644
--- a/Modules/FindPkgConfig.cmake
+++ b/Modules/FindPkgConfig.cmake
@@ -381,8 +381,9 @@ macro(_pkg_check_modules_internal _is_required _is_silent _no_cmake_path _no_cma
       if (_pkg_check_modules_pkg_op)
         list(APPEND _pkg_check_modules_exist_query "${_pkg_check_modules_pkg_ver}")
       else()
-        list(APPEND _pkg_check_modules_exist_query --exists --print-errors --short-errors)
+        list(APPEND _pkg_check_modules_exist_query --exists)
       endif()
+      list(APPEND _pkg_check_modules_exist_query --print-errors --short-errors)
 
       _pkgconfig_unset(${_prefix}_${_pkg_check_modules_pkg_name}_VERSION)
       _pkgconfig_unset(${_prefix}_${_pkg_check_modules_pkg_name}_PREFIX)
@@ -584,10 +585,13 @@ endmacro()
 macro(pkg_check_modules _prefix _module0)
   _pkgconfig_parse_options(_pkg_modules _pkg_is_required _pkg_is_silent _no_cmake_path _no_cmake_environment_path _imp_target "${_module0}" ${ARGN})
   # check cached value
-  if (NOT DEFINED __pkg_config_checked_${_prefix} OR __pkg_config_checked_${_prefix} LESS ${PKG_CONFIG_VERSION} OR NOT ${_prefix}_FOUND)
+  if (NOT DEFINED __pkg_config_checked_${_prefix} OR __pkg_config_checked_${_prefix} LESS ${PKG_CONFIG_VERSION} OR NOT ${_prefix}_FOUND OR NOT "${__pkg_config_arguments_${_prefix}}" STREQUAL "${_module0};${ARGN}")
     _pkg_check_modules_internal("${_pkg_is_required}" "${_pkg_is_silent}" ${_no_cmake_path} ${_no_cmake_environment_path} ${_imp_target} "${_prefix}" ${_pkg_modules})
 
     _pkgconfig_set(__pkg_config_checked_${_prefix} ${PKG_CONFIG_VERSION})
+    if (${_prefix}_FOUND)
+      _pkgconfig_set(__pkg_config_arguments_${_prefix} "${_module0};${ARGN}")
+    endif()
   elseif (${_prefix}_FOUND AND ${_imp_target})
     _pkg_create_imp_target("${_prefix}" _no_cmake_path _no_cmake_environment_path)
   endif()
diff --git a/Modules/FindProtobuf.cmake b/Modules/FindProtobuf.cmake
index 14e392a..3ffd5a7 100644
--- a/Modules/FindProtobuf.cmake
+++ b/Modules/FindProtobuf.cmake
@@ -264,7 +264,7 @@ function(_protobuf_find_libraries name filename)
     mark_as_advanced(${name}_LIBRARY_RELEASE)
 
     find_library(${name}_LIBRARY_DEBUG
-      NAMES ${filename}
+      NAMES ${filename}d ${filename}
       PATHS ${Protobuf_SRC_ROOT_FOLDER}/vsprojects/${_PROTOBUF_ARCH_DIR}Debug)
     mark_as_advanced(${name}_LIBRARY_DEBUG)
 
diff --git a/Modules/FindPythonInterp.cmake b/Modules/FindPythonInterp.cmake
index 103e820..f255246 100644
--- a/Modules/FindPythonInterp.cmake
+++ b/Modules/FindPythonInterp.cmake
@@ -145,8 +145,6 @@ if(PYTHON_EXECUTABLE)
     unset(_VERSION)
 endif()
 
-# handle the QUIETLY and REQUIRED arguments and set PYTHONINTERP_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(PythonInterp REQUIRED_VARS PYTHON_EXECUTABLE VERSION_VAR PYTHON_VERSION_STRING)
 
diff --git a/Modules/FindPythonLibs.cmake b/Modules/FindPythonLibs.cmake
index 1ebbf29..63ec9a8 100644
--- a/Modules/FindPythonLibs.cmake
+++ b/Modules/FindPythonLibs.cmake
@@ -42,16 +42,16 @@
 
 # Use the executable's path as a hint
 set(_Python_LIBRARY_PATH_HINT)
-if(PYTHON_EXECUTABLE)
+if(IS_ABSOLUTE "${PYTHON_EXECUTABLE}")
   if(WIN32)
-    get_filename_component(_Python_PREFIX ${PYTHON_EXECUTABLE} PATH)
+    get_filename_component(_Python_PREFIX "${PYTHON_EXECUTABLE}" PATH)
     if(_Python_PREFIX)
       set(_Python_LIBRARY_PATH_HINT ${_Python_PREFIX}/libs)
     endif()
     unset(_Python_PREFIX)
   else()
-    get_filename_component(_Python_PREFIX ${PYTHON_EXECUTABLE} PATH)
-    get_filename_component(_Python_PREFIX ${_Python_PREFIX} PATH)
+    get_filename_component(_Python_PREFIX "${PYTHON_EXECUTABLE}" PATH)
+    get_filename_component(_Python_PREFIX "${_Python_PREFIX}" PATH)
     if(_Python_PREFIX)
       set(_Python_LIBRARY_PATH_HINT ${_Python_PREFIX}/lib)
     endif()
@@ -168,12 +168,19 @@ foreach(_CURRENT_VERSION ${_Python_VERSIONS})
 
     # Use the library's install prefix as a hint
     set(_Python_INCLUDE_PATH_HINT)
-    get_filename_component(_Python_PREFIX ${PYTHON_LIBRARY} PATH)
-    get_filename_component(_Python_PREFIX ${_Python_PREFIX} PATH)
-    if(_Python_PREFIX)
-      set(_Python_INCLUDE_PATH_HINT ${_Python_PREFIX}/include)
-    endif()
-    unset(_Python_PREFIX)
+    # PYTHON_LIBRARY may contain a list because of SelectLibraryConfigurations
+    # which may have been run previously. If it is the case, the list can be:
+    #   optimized;<FILEPATH_TO_RELEASE_LIBRARY>;debug;<FILEPATH_TO_DEBUG_LIBRARY>
+    foreach(lib ${PYTHON_LIBRARY} ${PYTHON_DEBUG_LIBRARY})
+      if(IS_ABSOLUTE "${lib}")
+        get_filename_component(_Python_PREFIX "${lib}" PATH)
+        get_filename_component(_Python_PREFIX "${_Python_PREFIX}" PATH)
+        if(_Python_PREFIX)
+          list(APPEND _Python_INCLUDE_PATH_HINT ${_Python_PREFIX}/include)
+        endif()
+        unset(_Python_PREFIX)
+      endif()
+    endforeach()
 
     # Add framework directories to the search paths
     set(PYTHON_FRAMEWORK_INCLUDES)
diff --git a/Modules/FindQuickTime.cmake b/Modules/FindQuickTime.cmake
index 2ee1899..995d882 100644
--- a/Modules/FindQuickTime.cmake
+++ b/Modules/FindQuickTime.cmake
@@ -29,7 +29,5 @@ find_library(QUICKTIME_LIBRARY QuickTime
     lib
 )
 
-# handle the QUIETLY and REQUIRED arguments and set QUICKTIME_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(QuickTime DEFAULT_MSG QUICKTIME_LIBRARY QUICKTIME_INCLUDE_DIR)
diff --git a/Modules/FindRuby.cmake b/Modules/FindRuby.cmake
index b0e9b47..a9f8d35 100644
--- a/Modules/FindRuby.cmake
+++ b/Modules/FindRuby.cmake
@@ -207,19 +207,19 @@ set(_RUBY_POSSIBLE_LIB_NAMES ruby ruby-static ruby${_RUBY_VERSION_SHORT} ruby${_
 
 if(WIN32)
    set( _RUBY_MSVC_RUNTIME "" )
-   if( MSVC60 )
+   if( MSVC_VERSION EQUAL 1200 )
      set( _RUBY_MSVC_RUNTIME "60" )
    endif()
-   if( MSVC70 )
+   if( MSVC_VERSION EQUAL 1300 )
      set( _RUBY_MSVC_RUNTIME "70" )
    endif()
-   if( MSVC71 )
+   if( MSVC_VERSION EQUAL 1310 )
      set( _RUBY_MSVC_RUNTIME "71" )
    endif()
-   if( MSVC80 )
+   if( MSVC_VERSION EQUAL 1400 )
      set( _RUBY_MSVC_RUNTIME "80" )
    endif()
-   if( MSVC90 )
+   if( MSVC_VERSION EQUAL 1500 )
      set( _RUBY_MSVC_RUNTIME "90" )
    endif()
 
diff --git a/Modules/FindSDL.cmake b/Modules/FindSDL.cmake
index c0cdd98..3410018 100644
--- a/Modules/FindSDL.cmake
+++ b/Modules/FindSDL.cmake
@@ -94,6 +94,11 @@ find_library(SDL_LIBRARY_TEMP
   PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX}
 )
 
+# Hide this cache variable from the user, it's an internal implementation
+# detail. The documented library variable for the user is SDL_LIBRARY
+# which is derived from SDL_LIBRARY_TEMP further below.
+set_property(CACHE SDL_LIBRARY_TEMP PROPERTY TYPE INTERNAL)
+
 if(NOT SDL_BUILDING_LIBRARY)
   if(NOT SDL_INCLUDE_DIR MATCHES ".framework")
     # Non-OS X framework versions expect you to also dynamically link to
@@ -122,11 +127,10 @@ if(NOT APPLE)
   find_package(Threads)
 endif()
 
-# MinGW needs an additional library, mwindows
-# It's total link flags should look like -lmingw32 -lSDLmain -lSDL -lmwindows
-# (Actually on second look, I think it only needs one of the m* libraries.)
+# MinGW needs an additional link flag, -mwindows
+# It's total link flags should look like -lmingw32 -lSDLmain -lSDL -mwindows
 if(MINGW)
-  set(MINGW32_LIBRARY mingw32 CACHE STRING "mwindows for MinGW")
+  set(MINGW32_LIBRARY mingw32 "-mwindows" CACHE STRING "link flags for MinGW")
 endif()
 
 if(SDL_LIBRARY_TEMP)
@@ -163,8 +167,6 @@ if(SDL_LIBRARY_TEMP)
 
   # Set the final string here so the GUI reflects the final state.
   set(SDL_LIBRARY ${SDL_LIBRARY_TEMP} CACHE STRING "Where the SDL Library can be found")
-  # Set the temp variable to INTERNAL so it is not seen in the CMake GUI
-  set(SDL_LIBRARY_TEMP "${SDL_LIBRARY_TEMP}" CACHE INTERNAL "")
 endif()
 
 if(SDL_INCLUDE_DIR AND EXISTS "${SDL_INCLUDE_DIR}/SDL_version.h")
diff --git a/Modules/FindSDL_sound.cmake b/Modules/FindSDL_sound.cmake
index 3198088..cf33a4c 100644
--- a/Modules/FindSDL_sound.cmake
+++ b/Modules/FindSDL_sound.cmake
@@ -19,7 +19,7 @@
 #   SDL_SOUND_INCLUDE_DIR, where to find SDL_sound.h
 #   SDL_SOUND_FOUND, if false, do not try to link to SDL_sound
 #   SDL_SOUND_LIBRARIES, this contains the list of libraries that you need
-#     to link against. This is a read-only variable and is marked INTERNAL.
+#     to link against.
 #   SDL_SOUND_EXTRAS, this is an optional variable for you to add your own
 #     flags to SDL_SOUND_LIBRARIES. This is prepended to SDL_SOUND_LIBRARIES.
 #     This is available mostly for cases this module failed to anticipate for
@@ -367,11 +367,10 @@ if(SDL_FOUND AND SDL_SOUND_INCLUDE_DIR AND SDL_SOUND_LIBRARY)
        endif()
      endif()
 
+     set(SDL_SOUND_LIBRARIES ${SDL_SOUND_EXTRAS} ${SDL_SOUND_LIBRARIES_TMP})
    else()
-     set(SDL_SOUND_LIBRARIES "${SDL_SOUND_EXTRAS} ${SDL_SOUND_LIBRARY}" CACHE INTERNAL "SDL_sound and dependent libraries")
+     set(SDL_SOUND_LIBRARIES ${SDL_SOUND_EXTRAS} ${SDL_SOUND_LIBRARY})
    endif()
-
-   set(SDL_SOUND_LIBRARIES "${SDL_SOUND_EXTRAS} ${SDL_SOUND_LIBRARIES_TMP}" CACHE INTERNAL "SDL_sound and dependent libraries")
  endif()
 
 if(SDL_SOUND_INCLUDE_DIR AND EXISTS "${SDL_SOUND_INCLUDE_DIR}/SDL_sound.h")
diff --git a/Modules/FindSquish.cmake b/Modules/FindSquish.cmake
index 6c8813c..09bdf1f 100644
--- a/Modules/FindSquish.cmake
+++ b/Modules/FindSquish.cmake
@@ -119,9 +119,6 @@
 #
 #    This is deprecated. Use SQUISH_V3_ADD_TEST() if you are using Squish 3.x instead.
 
-
-include(CMakeParseArguments)
-
 set(SQUISH_INSTALL_DIR_STRING "Directory containing the bin, doc, and lib directories for Squish; this should be the root of the installation directory.")
 set(SQUISH_SERVER_EXECUTABLE_STRING "The squishserver executable program.")
 set(SQUISH_CLIENT_EXECUTABLE_STRING "The squishclient executable program.")
diff --git a/Modules/FindTCL.cmake b/Modules/FindTCL.cmake
index 12d6616..b6e24a3 100644
--- a/Modules/FindTCL.cmake
+++ b/Modules/FindTCL.cmake
@@ -205,8 +205,6 @@ find_path(TK_INCLUDE_PATH
   HINTS ${TCLTK_POSSIBLE_INCLUDE_PATHS}
   )
 
-# handle the QUIETLY and REQUIRED arguments and set TCL_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(TCL DEFAULT_MSG TCL_LIBRARY TCL_INCLUDE_PATH)
diff --git a/Modules/FindTIFF.cmake b/Modules/FindTIFF.cmake
index 23ae308..b622ca6 100644
--- a/Modules/FindTIFF.cmake
+++ b/Modules/FindTIFF.cmake
@@ -65,8 +65,6 @@ if(TIFF_INCLUDE_DIR AND EXISTS "${TIFF_INCLUDE_DIR}/tiffvers.h")
     unset(tiff_version_str)
 endif()
 
-# handle the QUIETLY and REQUIRED arguments and set TIFF_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(TIFF
                                   REQUIRED_VARS TIFF_LIBRARY TIFF_INCLUDE_DIR
diff --git a/Modules/FindTclsh.cmake b/Modules/FindTclsh.cmake
index c8a87ec..9fcb41c 100644
--- a/Modules/FindTclsh.cmake
+++ b/Modules/FindTclsh.cmake
@@ -89,8 +89,6 @@ if(TCL_TCLSH)
                    OUTPUT_STRIP_TRAILING_WHITESPACE)
 endif()
 
-# handle the QUIETLY and REQUIRED arguments and set TIFF_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(Tclsh
                                   REQUIRED_VARS TCL_TCLSH
diff --git a/Modules/FindVulkan.cmake b/Modules/FindVulkan.cmake
index 820e0eb..1f4c8ad 100644
--- a/Modules/FindVulkan.cmake
+++ b/Modules/FindVulkan.cmake
@@ -39,12 +39,17 @@ if(WIN32)
     find_library(Vulkan_LIBRARY
       NAMES vulkan-1
       PATHS
-        "$ENV{VULKAN_SDK}/Bin")
+        "$ENV{VULKAN_SDK}/Lib"
+        "$ENV{VULKAN_SDK}/Bin"
+        )
   elseif(CMAKE_SIZEOF_VOID_P EQUAL 4)
     find_library(Vulkan_LIBRARY
       NAMES vulkan-1
       PATHS
-        "$ENV{VULKAN_SDK}/Bin32")
+        "$ENV{VULKAN_SDK}/Lib32"
+        "$ENV{VULKAN_SDK}/Bin32"
+        NO_SYSTEM_ENVIRONMENT_PATH
+        )
   endif()
 else()
     find_path(Vulkan_INCLUDE_DIR
diff --git a/Modules/FindWget.cmake b/Modules/FindWget.cmake
index 68419e2..4fcb2fa 100644
--- a/Modules/FindWget.cmake
+++ b/Modules/FindWget.cmake
@@ -21,8 +21,6 @@ find_program(WGET_EXECUTABLE
   ${CYGWIN_INSTALL_PATH}/bin
 )
 
-# handle the QUIETLY and REQUIRED arguments and set WGET_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(Wget DEFAULT_MSG WGET_EXECUTABLE)
 
@@ -30,4 +28,4 @@ mark_as_advanced( WGET_EXECUTABLE )
 
 # WGET option is deprecated.
 # use WGET_EXECUTABLE instead.
-set (WGET ${WGET_EXECUTABLE} )
+set (WGET ${WGET_EXECUTABLE})
diff --git a/Modules/FindZLIB.cmake b/Modules/FindZLIB.cmake
index 5ee55b3..4065999 100644
--- a/Modules/FindZLIB.cmake
+++ b/Modules/FindZLIB.cmake
@@ -108,8 +108,6 @@ if(ZLIB_INCLUDE_DIR AND EXISTS "${ZLIB_INCLUDE_DIR}/zlib.h")
     set(ZLIB_PATCH_VERSION "${ZLIB_VERSION_PATCH}")
 endif()
 
-# handle the QUIETLY and REQUIRED arguments and set ZLIB_FOUND to TRUE if
-# all listed variables are TRUE
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(ZLIB REQUIRED_VARS ZLIB_LIBRARY ZLIB_INCLUDE_DIR
                                        VERSION_VAR ZLIB_VERSION_STRING)
diff --git a/Modules/FindwxWidgets.cmake b/Modules/FindwxWidgets.cmake
index 77091f4..bc906e5 100644
--- a/Modules/FindwxWidgets.cmake
+++ b/Modules/FindwxWidgets.cmake
@@ -423,7 +423,7 @@ if(wxWidgets_FIND_STYLE STREQUAL "win32")
       list(APPEND wxWidgets_LIBRARIES opengl32 glu32)
     endif()
 
-    list(APPEND wxWidgets_LIBRARIES winmm comctl32 rpcrt4 wsock32)
+    list(APPEND wxWidgets_LIBRARIES winmm comctl32 oleacc rpcrt4 shlwapi version wsock32)
   endmacro()
 
   #-------------------------------------------------------------------
@@ -498,15 +498,17 @@ if(wxWidgets_FIND_STYLE STREQUAL "win32")
       set(_WX_TOOL gcc)
     elseif(MSVC)
       set(_WX_TOOL vc)
-      if(MSVC14)
+      if(MSVC_VERSION EQUAL 1910)
+        set(_WX_TOOLVER 141)
+      elseif(MSVC_VERSION EQUAL 1900)
         set(_WX_TOOLVER 140)
-      elseif(MSVC12)
+      elseif(MSVC_VERSION EQUAL 1800)
         set(_WX_TOOLVER 120)
-      elseif(MSVC11)
+      elseif(MSVC_VERSION EQUAL 1700)
         set(_WX_TOOLVER 110)
-      elseif(MSVC10)
+      elseif(MSVC_VERSION EQUAL 1600)
         set(_WX_TOOLVER 100)
-      elseif(MSVC90)
+      elseif(MSVC_VERSION EQUAL 1500)
         set(_WX_TOOLVER 90)
       endif()
       if(CMAKE_SIZEOF_VOID_P EQUAL 8)
diff --git a/Modules/FortranCInterface.cmake b/Modules/FortranCInterface.cmake
index 3899a2d..893a96f 100644
--- a/Modules/FortranCInterface.cmake
+++ b/Modules/FortranCInterface.cmake
@@ -348,7 +348,8 @@ function(FortranCInterface_VERIFY)
     try_compile(FortranCInterface_VERIFY_${lang}_COMPILED
       ${FortranCInterface_BINARY_DIR}/Verify${lang}
       ${FortranCInterface_SOURCE_DIR}/Verify
-      VerifyFortranC
+      VerifyFortranC # project name
+      VerifyFortranC # target name
       CMAKE_FLAGS -DVERIFY_CXX=${verify_cxx}
                   -DCMAKE_VERBOSE_MAKEFILE=ON
                  "-DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS}"
diff --git a/Modules/FortranCInterface/CMakeLists.txt b/Modules/FortranCInterface/CMakeLists.txt
index dee57b5..3a66f68 100644
--- a/Modules/FortranCInterface/CMakeLists.txt
+++ b/Modules/FortranCInterface/CMakeLists.txt
@@ -94,6 +94,9 @@ add_library(myfort STATIC mysub.f my_sub.f ${myfort_modules})
 # Provide symbols through C but fall back to Fortran.
 add_library(symbols STATIC ${symbol_sources})
 target_link_libraries(symbols myfort)
+# In case the Fortran compiler produces PIC by default make sure
+# the C compiler produces PIC even if it is not its default.
+set_property(TARGET symbols PROPERTY POSITION_INDEPENDENT_CODE 1)
 
 # Require symbols through Fortran.
 add_executable(FortranCInterface main.F call_sub.f ${call_mod})
diff --git a/Modules/FortranCInterface/Detect.cmake b/Modules/FortranCInterface/Detect.cmake
index 9984efd..7612890 100644
--- a/Modules/FortranCInterface/Detect.cmake
+++ b/Modules/FortranCInterface/Detect.cmake
@@ -30,7 +30,8 @@ set(_result)
 try_compile(FortranCInterface_COMPILED
   ${FortranCInterface_BINARY_DIR}
   ${FortranCInterface_SOURCE_DIR}
-  FortranCInterface
+  FortranCInterface # project name
+  FortranCInterface # target name
   CMAKE_FLAGS
     "-DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS}"
     "-DCMAKE_Fortran_FLAGS:STRING=${CMAKE_Fortran_FLAGS}"
diff --git a/Modules/GNUInstallDirs.cmake b/Modules/GNUInstallDirs.cmake
index 059a2fc..9599f27 100644
--- a/Modules/GNUInstallDirs.cmake
+++ b/Modules/GNUInstallDirs.cmake
@@ -120,31 +120,54 @@
 #   allow users who create additional path variables to also compute
 #   absolute paths where necessary, using the same logic.
 
-# Installation directories
-#
-if(NOT DEFINED CMAKE_INSTALL_BINDIR)
-  set(CMAKE_INSTALL_BINDIR "bin" CACHE PATH "user executables (bin)")
-endif()
+# Convert a cache variable to PATH type
 
-if(NOT DEFINED CMAKE_INSTALL_SBINDIR)
-  set(CMAKE_INSTALL_SBINDIR "sbin" CACHE PATH "system admin executables (sbin)")
-endif()
+macro(_GNUInstallDirs_cache_convert_to_path var description)
+  get_property(_GNUInstallDirs_cache_type CACHE ${var} PROPERTY TYPE)
+  if(_GNUInstallDirs_cache_type STREQUAL "UNINITIALIZED")
+    file(TO_CMAKE_PATH "${${var}}" _GNUInstallDirs_cmakepath)
+    set_property(CACHE ${var} PROPERTY TYPE PATH)
+    set_property(CACHE ${var} PROPERTY VALUE "${_GNUInstallDirs_cmakepath}")
+    set_property(CACHE ${var} PROPERTY HELPSTRING "${description}")
+    unset(_GNUInstallDirs_cmakepath)
+  endif()
+  unset(_GNUInstallDirs_cache_type)
+endmacro()
 
-if(NOT DEFINED CMAKE_INSTALL_LIBEXECDIR)
-  set(CMAKE_INSTALL_LIBEXECDIR "libexec" CACHE PATH "program executables (libexec)")
-endif()
+# Create a cache variable with default for a path.
+macro(_GNUInstallDirs_cache_path var default description)
+  if(NOT DEFINED ${var})
+    set(${var} "${default}" CACHE PATH "${description}")
+  endif()
+  _GNUInstallDirs_cache_convert_to_path("${var}" "${description}")
+endmacro()
 
-if(NOT DEFINED CMAKE_INSTALL_SYSCONFDIR)
-  set(CMAKE_INSTALL_SYSCONFDIR "etc" CACHE PATH "read-only single-machine data (etc)")
-endif()
+# Create a cache variable with not default for a path, with a fallback
+# when unset; used for entries slaved to other entries such as
+# DATAROOTDIR.
+macro(_GNUInstallDirs_cache_path_fallback var default description)
+  if(NOT ${var})
+    set(${var} "" CACHE PATH "${description}")
+    set(${var} "${default}")
+  endif()
+  _GNUInstallDirs_cache_convert_to_path("${var}" "${description}")
+endmacro()
 
-if(NOT DEFINED CMAKE_INSTALL_SHAREDSTATEDIR)
-  set(CMAKE_INSTALL_SHAREDSTATEDIR "com" CACHE PATH "modifiable architecture-independent data (com)")
-endif()
+# Installation directories
+#
 
-if(NOT DEFINED CMAKE_INSTALL_LOCALSTATEDIR)
-  set(CMAKE_INSTALL_LOCALSTATEDIR "var" CACHE PATH "modifiable single-machine data (var)")
-endif()
+_GNUInstallDirs_cache_path(CMAKE_INSTALL_BINDIR "bin"
+  "User executables (bin)")
+_GNUInstallDirs_cache_path(CMAKE_INSTALL_SBINDIR "sbin"
+  "System admin executables (sbin)")
+_GNUInstallDirs_cache_path(CMAKE_INSTALL_LIBEXECDIR "libexec"
+  "Program executables (libexec)")
+_GNUInstallDirs_cache_path(CMAKE_INSTALL_SYSCONFDIR "etc"
+  "Read-only single-machine data (etc)")
+_GNUInstallDirs_cache_path(CMAKE_INSTALL_SHAREDSTATEDIR "com"
+  "Modifiable architecture-independent data (com)")
+_GNUInstallDirs_cache_path(CMAKE_INSTALL_LOCALSTATEDIR "var"
+  "Modifiable single-machine data (var)")
 
 # We check if the variable was manually set and not cached, in order to
 # allow projects to set the values as normal variables before including
@@ -219,71 +242,50 @@ if(NOT DEFINED CMAKE_INSTALL_LIBDIR OR (_libdir_set
     endif()
   endif()
   if(NOT DEFINED CMAKE_INSTALL_LIBDIR)
-    set(CMAKE_INSTALL_LIBDIR "${_LIBDIR_DEFAULT}" CACHE PATH "object code libraries (${_LIBDIR_DEFAULT})")
+    set(CMAKE_INSTALL_LIBDIR "${_LIBDIR_DEFAULT}" CACHE PATH "Object code libraries (${_LIBDIR_DEFAULT})")
   elseif(DEFINED __LAST_LIBDIR_DEFAULT
       AND "${__LAST_LIBDIR_DEFAULT}" STREQUAL "${CMAKE_INSTALL_LIBDIR}")
     set_property(CACHE CMAKE_INSTALL_LIBDIR PROPERTY VALUE "${_LIBDIR_DEFAULT}")
   endif()
 endif()
+_GNUInstallDirs_cache_convert_to_path(CMAKE_INSTALL_LIBDIR "Object code libraries (lib)")
+
 # Save for next run
 set(_GNUInstallDirs_LAST_CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}" CACHE INTERNAL "CMAKE_INSTALL_PREFIX during last run")
 unset(_libdir_set)
 unset(__LAST_LIBDIR_DEFAULT)
 
-
-if(NOT DEFINED CMAKE_INSTALL_INCLUDEDIR)
-  set(CMAKE_INSTALL_INCLUDEDIR "include" CACHE PATH "C header files (include)")
-endif()
-
-if(NOT DEFINED CMAKE_INSTALL_OLDINCLUDEDIR)
-  set(CMAKE_INSTALL_OLDINCLUDEDIR "/usr/include" CACHE PATH "C header files for non-gcc (/usr/include)")
-endif()
-
-if(NOT DEFINED CMAKE_INSTALL_DATAROOTDIR)
-  set(CMAKE_INSTALL_DATAROOTDIR "share" CACHE PATH "read-only architecture-independent data root (share)")
-endif()
+_GNUInstallDirs_cache_path(CMAKE_INSTALL_INCLUDEDIR "include"
+  "C header files (include)")
+_GNUInstallDirs_cache_path(CMAKE_INSTALL_OLDINCLUDEDIR "/usr/include"
+  "C header files for non-gcc (/usr/include)")
+_GNUInstallDirs_cache_path(CMAKE_INSTALL_DATAROOTDIR "share"
+  "Read-only architecture-independent data root (share)")
 
 #-----------------------------------------------------------------------------
 # Values whose defaults are relative to DATAROOTDIR.  Store empty values in
 # the cache and store the defaults in local variables if the cache values are
 # not set explicitly.  This auto-updates the defaults as DATAROOTDIR changes.
 
-if(NOT CMAKE_INSTALL_DATADIR)
-  set(CMAKE_INSTALL_DATADIR "" CACHE PATH "read-only architecture-independent data (DATAROOTDIR)")
-  set(CMAKE_INSTALL_DATADIR "${CMAKE_INSTALL_DATAROOTDIR}")
-endif()
+_GNUInstallDirs_cache_path_fallback(CMAKE_INSTALL_DATADIR "${CMAKE_INSTALL_DATAROOTDIR}"
+  "Read-only architecture-independent data (DATAROOTDIR)")
 
 if(CMAKE_SYSTEM_NAME MATCHES "^(.*BSD|DragonFly)$")
-  if(NOT CMAKE_INSTALL_INFODIR)
-    set(CMAKE_INSTALL_INFODIR "" CACHE PATH "info documentation (info)")
-    set(CMAKE_INSTALL_INFODIR "info")
-  endif()
-
-  if(NOT CMAKE_INSTALL_MANDIR)
-    set(CMAKE_INSTALL_MANDIR "" CACHE PATH "man documentation (man)")
-    set(CMAKE_INSTALL_MANDIR "man")
-  endif()
+  _GNUInstallDirs_cache_path_fallback(CMAKE_INSTALL_INFODIR "info"
+    "Info documentation (info)")
+  _GNUInstallDirs_cache_path_fallback(CMAKE_INSTALL_MANDIR "man"
+    "Man documentation (man)")
 else()
-  if(NOT CMAKE_INSTALL_INFODIR)
-    set(CMAKE_INSTALL_INFODIR "" CACHE PATH "info documentation (DATAROOTDIR/info)")
-    set(CMAKE_INSTALL_INFODIR "${CMAKE_INSTALL_DATAROOTDIR}/info")
-  endif()
-
-  if(NOT CMAKE_INSTALL_MANDIR)
-    set(CMAKE_INSTALL_MANDIR "" CACHE PATH "man documentation (DATAROOTDIR/man)")
-    set(CMAKE_INSTALL_MANDIR "${CMAKE_INSTALL_DATAROOTDIR}/man")
-  endif()
-endif()
-
-if(NOT CMAKE_INSTALL_LOCALEDIR)
-  set(CMAKE_INSTALL_LOCALEDIR "" CACHE PATH "locale-dependent data (DATAROOTDIR/locale)")
-  set(CMAKE_INSTALL_LOCALEDIR "${CMAKE_INSTALL_DATAROOTDIR}/locale")
+  _GNUInstallDirs_cache_path_fallback(CMAKE_INSTALL_INFODIR "${CMAKE_INSTALL_DATAROOTDIR}/info"
+    "Info documentation (DATAROOTDIR/info)")
+  _GNUInstallDirs_cache_path_fallback(CMAKE_INSTALL_MANDIR "${CMAKE_INSTALL_DATAROOTDIR}/man"
+    "Man documentation (DATAROOTDIR/man)")
 endif()
 
-if(NOT CMAKE_INSTALL_DOCDIR)
-  set(CMAKE_INSTALL_DOCDIR "" CACHE PATH "documentation root (DATAROOTDIR/doc/PROJECT_NAME)")
-  set(CMAKE_INSTALL_DOCDIR "${CMAKE_INSTALL_DATAROOTDIR}/doc/${PROJECT_NAME}")
-endif()
+_GNUInstallDirs_cache_path_fallback(CMAKE_INSTALL_LOCALEDIR "${CMAKE_INSTALL_DATAROOTDIR}/locale"
+  "Locale-dependent data (DATAROOTDIR/locale)")
+_GNUInstallDirs_cache_path_fallback(CMAKE_INSTALL_DOCDIR "${CMAKE_INSTALL_DATAROOTDIR}/doc/${PROJECT_NAME}"
+  "Documentation root (DATAROOTDIR/doc/PROJECT_NAME)")
 
 #-----------------------------------------------------------------------------
 
diff --git a/Modules/GenerateExportHeader.cmake b/Modules/GenerateExportHeader.cmake
index c201714..6d1b4ed 100644
--- a/Modules/GenerateExportHeader.cmake
+++ b/Modules/GenerateExportHeader.cmake
@@ -184,7 +184,6 @@
 # :prop_tgt:`CXX_VISIBILITY_PRESET <<LANG>_VISIBILITY_PRESET>` and
 # :prop_tgt:`VISIBILITY_INLINES_HIDDEN` instead.
 
-include(CMakeParseArguments)
 include(CheckCXXCompilerFlag)
 
 # TODO: Install this macro separately?
diff --git a/Modules/GetPrerequisites.cmake b/Modules/GetPrerequisites.cmake
index 5ab9dc5..1b23800 100644
--- a/Modules/GetPrerequisites.cmake
+++ b/Modules/GetPrerequisites.cmake
@@ -430,8 +430,8 @@ function(gp_resolve_item context item exepath dirs resolved_item_var)
   if(WIN32 AND NOT UNIX)
   if(NOT resolved)
     set(ri "ri-NOTFOUND")
-    find_program(ri "${item}" PATHS "${exepath};${dirs}" NO_DEFAULT_PATH)
-    find_program(ri "${item}" PATHS "${exepath};${dirs}")
+    find_program(ri "${item}" PATHS ${exepath} ${dirs} NO_DEFAULT_PATH)
+    find_program(ri "${item}" PATHS ${exepath} ${dirs})
     if(ri)
       #message(STATUS "info: 'find_program' in exepath/dirs (${ri})")
       set(resolved 1)
@@ -654,6 +654,8 @@ function(get_prerequisites target prerequisites_var exclude_system recurse exepa
 
   if(NOT EXISTS "${target}")
     message("warning: target '${target}' does not exist...")
+    set(${prerequisites_var} "" PARENT_SCOPE)
+    return()
   endif()
 
   set(gp_cmd_paths ${gp_cmd_paths}
@@ -810,6 +812,20 @@ function(get_prerequisites target prerequisites_var exclude_system recurse exepa
     OUTPUT_VARIABLE gp_cmd_ov
     ERROR_VARIABLE gp_ev
     )
+
+  if(gp_tool STREQUAL "dumpbin")
+    # Exclude delay load dependencies under windows (they are listed in dumpbin output after the message below)
+    string(FIND "${gp_cmd_ov}" "Image has the following delay load dependencies" gp_delayload_pos)
+    if (${gp_delayload_pos} GREATER -1)
+      string(SUBSTRING "${gp_cmd_ov}" 0 ${gp_delayload_pos} gp_cmd_ov_no_delayload_deps)
+      string(SUBSTRING "${gp_cmd_ov}" ${gp_delayload_pos} -1 gp_cmd_ov_delayload_deps)
+      if (verbose)
+        message(STATUS "GetPrequisites(${target}) : ignoring the following delay load dependencies :\n ${gp_cmd_ov_delayload_deps}")
+      endif()
+      set(gp_cmd_ov ${gp_cmd_ov_no_delayload_deps})
+    endif()
+  endif()
+
   if(NOT gp_rv STREQUAL "0")
     if(gp_tool STREQUAL "dumpbin")
       # dumpbin error messages seem to go to stdout
diff --git a/Modules/InstallRequiredSystemLibraries.cmake b/Modules/InstallRequiredSystemLibraries.cmake
index b0446c9..a3478a3 100644
--- a/Modules/InstallRequiredSystemLibraries.cmake
+++ b/Modules/InstallRequiredSystemLibraries.cmake
@@ -69,376 +69,437 @@ if(MSVC)
   get_filename_component(devenv_dir "${CMAKE_MAKE_PROGRAM}" PATH)
   get_filename_component(base_dir "${devenv_dir}/../.." ABSOLUTE)
 
-  if(MSVC70)
+  if(MSVC_VERSION EQUAL 1300)
     set(__install__libs
       "${SYSTEMROOT}/system32/msvcp70.dll"
       "${SYSTEMROOT}/system32/msvcr70.dll"
       )
   endif()
 
-  if(MSVC71)
+  if(MSVC_VERSION EQUAL 1310)
     set(__install__libs
       "${SYSTEMROOT}/system32/msvcp71.dll"
       "${SYSTEMROOT}/system32/msvcr71.dll"
       )
   endif()
 
-  if(MSVC80)
+  if(MSVC_VERSION EQUAL 1400)
     # Find the runtime library redistribution directory.
     get_filename_component(msvc_install_dir
       "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\8.0;InstallDir]" ABSOLUTE)
-    find_path(MSVC80_REDIST_DIR NAMES ${CMAKE_MSVC_ARCH}/Microsoft.VC80.CRT/Microsoft.VC80.CRT.manifest
+    if(DEFINED MSVC80_REDIST_DIR AND EXISTS "${MSVC80_REDIST_DIR}")
+      set(MSVC_REDIST_DIR "${MSVC80_REDIST_DIR}") # use old cache entry
+    endif()
+    find_path(MSVC_REDIST_DIR NAMES ${CMAKE_MSVC_ARCH}/Microsoft.VC80.CRT/Microsoft.VC80.CRT.manifest
       PATHS
         "${msvc_install_dir}/../../VC/redist"
         "${base_dir}/VC/redist"
       )
-    mark_as_advanced(MSVC80_REDIST_DIR)
-    set(MSVC80_CRT_DIR "${MSVC80_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC80.CRT")
+    mark_as_advanced(MSVC_REDIST_DIR)
+    set(MSVC_CRT_DIR "${MSVC_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC80.CRT")
 
     # Install the manifest that allows DLLs to be loaded from the
     # directory containing the executable.
     if(NOT CMAKE_INSTALL_DEBUG_LIBRARIES_ONLY)
       set(__install__libs
-        "${MSVC80_CRT_DIR}/Microsoft.VC80.CRT.manifest"
-        "${MSVC80_CRT_DIR}/msvcm80.dll"
-        "${MSVC80_CRT_DIR}/msvcp80.dll"
-        "${MSVC80_CRT_DIR}/msvcr80.dll"
+        "${MSVC_CRT_DIR}/Microsoft.VC80.CRT.manifest"
+        "${MSVC_CRT_DIR}/msvcm80.dll"
+        "${MSVC_CRT_DIR}/msvcp80.dll"
+        "${MSVC_CRT_DIR}/msvcr80.dll"
         )
     else()
       set(__install__libs)
     endif()
 
     if(CMAKE_INSTALL_DEBUG_LIBRARIES)
-      set(MSVC80_CRT_DIR
-        "${MSVC80_REDIST_DIR}/Debug_NonRedist/${CMAKE_MSVC_ARCH}/Microsoft.VC80.DebugCRT")
+      set(MSVC_CRT_DIR
+        "${MSVC_REDIST_DIR}/Debug_NonRedist/${CMAKE_MSVC_ARCH}/Microsoft.VC80.DebugCRT")
       set(__install__libs ${__install__libs}
-        "${MSVC80_CRT_DIR}/Microsoft.VC80.DebugCRT.manifest"
-        "${MSVC80_CRT_DIR}/msvcm80d.dll"
-        "${MSVC80_CRT_DIR}/msvcp80d.dll"
-        "${MSVC80_CRT_DIR}/msvcr80d.dll"
+        "${MSVC_CRT_DIR}/Microsoft.VC80.DebugCRT.manifest"
+        "${MSVC_CRT_DIR}/msvcm80d.dll"
+        "${MSVC_CRT_DIR}/msvcp80d.dll"
+        "${MSVC_CRT_DIR}/msvcr80d.dll"
         )
     endif()
   endif()
 
-  if(MSVC90)
+  if(MSVC_VERSION EQUAL 1500)
     # Find the runtime library redistribution directory.
     get_filename_component(msvc_install_dir
       "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\9.0;InstallDir]" ABSOLUTE)
     get_filename_component(msvc_express_install_dir
       "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\9.0;InstallDir]" ABSOLUTE)
-    find_path(MSVC90_REDIST_DIR NAMES ${CMAKE_MSVC_ARCH}/Microsoft.VC90.CRT/Microsoft.VC90.CRT.manifest
+    if(DEFINED MSVC90_REDIST_DIR AND EXISTS "${MSVC90_REDIST_DIR}")
+      set(MSVC_REDIST_DIR "${MSVC90_REDIST_DIR}") # use old cache entry
+    endif()
+    find_path(MSVC_REDIST_DIR NAMES ${CMAKE_MSVC_ARCH}/Microsoft.VC90.CRT/Microsoft.VC90.CRT.manifest
       PATHS
         "${msvc_install_dir}/../../VC/redist"
         "${msvc_express_install_dir}/../../VC/redist"
         "${base_dir}/VC/redist"
       )
-    mark_as_advanced(MSVC90_REDIST_DIR)
-    set(MSVC90_CRT_DIR "${MSVC90_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC90.CRT")
+    mark_as_advanced(MSVC_REDIST_DIR)
+    set(MSVC_CRT_DIR "${MSVC_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC90.CRT")
 
     # Install the manifest that allows DLLs to be loaded from the
     # directory containing the executable.
     if(NOT CMAKE_INSTALL_DEBUG_LIBRARIES_ONLY)
       set(__install__libs
-        "${MSVC90_CRT_DIR}/Microsoft.VC90.CRT.manifest"
-        "${MSVC90_CRT_DIR}/msvcm90.dll"
-        "${MSVC90_CRT_DIR}/msvcp90.dll"
-        "${MSVC90_CRT_DIR}/msvcr90.dll"
+        "${MSVC_CRT_DIR}/Microsoft.VC90.CRT.manifest"
+        "${MSVC_CRT_DIR}/msvcm90.dll"
+        "${MSVC_CRT_DIR}/msvcp90.dll"
+        "${MSVC_CRT_DIR}/msvcr90.dll"
         )
     else()
       set(__install__libs)
     endif()
 
     if(CMAKE_INSTALL_DEBUG_LIBRARIES)
-      set(MSVC90_CRT_DIR
-        "${MSVC90_REDIST_DIR}/Debug_NonRedist/${CMAKE_MSVC_ARCH}/Microsoft.VC90.DebugCRT")
+      set(MSVC_CRT_DIR
+        "${MSVC_REDIST_DIR}/Debug_NonRedist/${CMAKE_MSVC_ARCH}/Microsoft.VC90.DebugCRT")
       set(__install__libs ${__install__libs}
-        "${MSVC90_CRT_DIR}/Microsoft.VC90.DebugCRT.manifest"
-        "${MSVC90_CRT_DIR}/msvcm90d.dll"
-        "${MSVC90_CRT_DIR}/msvcp90d.dll"
-        "${MSVC90_CRT_DIR}/msvcr90d.dll"
+        "${MSVC_CRT_DIR}/Microsoft.VC90.DebugCRT.manifest"
+        "${MSVC_CRT_DIR}/msvcm90d.dll"
+        "${MSVC_CRT_DIR}/msvcp90d.dll"
+        "${MSVC_CRT_DIR}/msvcr90d.dll"
         )
     endif()
   endif()
 
-  macro(MSVCRT_FILES_FOR_VERSION version)
-    set(v "${version}")
+  if(MSVC_VERSION EQUAL 1910)
+    set(_MSVCRT_DLL_VERSION 140)
+    set(_MSVCRT_IDE_VERSION 15)
+  elseif(MSVC_VERSION EQUAL 1900)
+    set(_MSVCRT_DLL_VERSION 140)
+    set(_MSVCRT_IDE_VERSION 14)
+  elseif(MSVC_VERSION EQUAL 1800)
+    set(_MSVCRT_DLL_VERSION 120)
+    set(_MSVCRT_IDE_VERSION 12)
+  elseif(MSVC_VERSION EQUAL 1700)
+    set(_MSVCRT_DLL_VERSION 110)
+    set(_MSVCRT_IDE_VERSION 11)
+  elseif(MSVC_VERSION EQUAL 1600)
+    set(_MSVCRT_DLL_VERSION 100)
+    set(_MSVCRT_IDE_VERSION 10)
+  else()
+    set(_MSVCRT_DLL_VERSION "")
+    set(_MSVCRT_IDE_VERSION "")
+  endif()
+
+  if(_MSVCRT_DLL_VERSION)
+    set(v "${_MSVCRT_DLL_VERSION}")
+    set(vs "${_MSVCRT_IDE_VERSION}")
 
     # Find the runtime library redistribution directory.
-    get_filename_component(msvc_install_dir
-      "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\${v}.0;InstallDir]" ABSOLUTE)
-    set(programfilesx86 "ProgramFiles(x86)")
-    find_path(MSVC${v}_REDIST_DIR NAMES ${CMAKE_MSVC_ARCH}/Microsoft.VC${v}0.CRT
-      PATHS
-        "${msvc_install_dir}/../../VC/redist"
+    if(vs VERSION_LESS 15 AND DEFINED MSVC${vs}_REDIST_DIR AND EXISTS "${MSVC${vs}_REDIST_DIR}")
+      set(MSVC_REDIST_DIR "${MSVC${vs}_REDIST_DIR}") # use old cache entry
+    endif()
+    if(NOT vs VERSION_LESS 15)
+      set(_vs_redist_paths "")
+      cmake_host_system_information(RESULT _vs_dir QUERY VS_${vs}_DIR) # undocumented query
+      if(IS_DIRECTORY "${_vs_dir}")
+        file(GLOB _vs_redist_paths "${_vs_dir}/VC/Redist/MSVC/*")
+      endif()
+      unset(_vs_dir)
+    else()
+      get_filename_component(_vs_dir
+        "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\${vs}.0;InstallDir]" ABSOLUTE)
+      set(programfilesx86 "ProgramFiles(x86)")
+      set(_vs_redist_paths
+        "${_vs_dir}/../../VC/redist"
         "${base_dir}/VC/redist"
-        "$ENV{ProgramFiles}/Microsoft Visual Studio ${v}.0/VC/redist"
-        "$ENV{${programfilesx86}}/Microsoft Visual Studio ${v}.0/VC/redist"
-      )
-    mark_as_advanced(MSVC${v}_REDIST_DIR)
-    set(MSVC${v}_CRT_DIR "${MSVC${v}_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC${v}0.CRT")
+        "$ENV{ProgramFiles}/Microsoft Visual Studio ${vs}.0/VC/redist"
+        "$ENV{${programfilesx86}}/Microsoft Visual Studio ${vs}.0/VC/redist"
+        )
+      unset(_vs_dir)
+      unset(programfilesx86)
+    endif()
+    find_path(MSVC_REDIST_DIR NAMES ${CMAKE_MSVC_ARCH}/Microsoft.VC${vs}0.CRT PATHS ${_vs_redist_paths})
+    unset(_vs_redist_paths)
+    mark_as_advanced(MSVC_REDIST_DIR)
+    set(MSVC_CRT_DIR "${MSVC_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC${vs}0.CRT")
 
     if(NOT CMAKE_INSTALL_DEBUG_LIBRARIES_ONLY)
       set(__install__libs
-        "${MSVC${v}_CRT_DIR}/msvcp${v}0.dll"
+        "${MSVC_CRT_DIR}/msvcp${v}.dll"
         )
-      if(NOT v VERSION_LESS 14)
-        list(APPEND __install__libs "${MSVC${v}_CRT_DIR}/vcruntime${v}0.dll")
+      if(NOT vs VERSION_LESS 14)
+        list(APPEND __install__libs
+            "${MSVC_CRT_DIR}/vcruntime${v}.dll"
+            "${MSVC_CRT_DIR}/concrt${v}.dll"
+            )
       else()
-        list(APPEND __install__libs "${MSVC${v}_CRT_DIR}/msvcr${v}0.dll")
+        list(APPEND __install__libs "${MSVC_CRT_DIR}/msvcr${v}.dll")
       endif()
     else()
       set(__install__libs)
     endif()
 
     if(CMAKE_INSTALL_DEBUG_LIBRARIES)
-      set(MSVC${v}_CRT_DIR
-        "${MSVC${v}_REDIST_DIR}/Debug_NonRedist/${CMAKE_MSVC_ARCH}/Microsoft.VC${v}0.DebugCRT")
+      set(MSVC_CRT_DIR
+        "${MSVC_REDIST_DIR}/Debug_NonRedist/${CMAKE_MSVC_ARCH}/Microsoft.VC${vs}0.DebugCRT")
       set(__install__libs ${__install__libs}
-        "${MSVC${v}_CRT_DIR}/msvcp${v}0d.dll"
+        "${MSVC_CRT_DIR}/msvcp${v}d.dll"
         )
-      if(NOT v VERSION_LESS 14)
-        list(APPEND __install__libs "${MSVC${v}_CRT_DIR}/vcruntime${v}0d.dll")
+      if(NOT vs VERSION_LESS 14)
+        list(APPEND __install__libs
+            "${MSVC_CRT_DIR}/vcruntime${v}d.dll"
+            "${MSVC_CRT_DIR}/concrt${v}d.dll"
+            )
       else()
-        list(APPEND __install__libs "${MSVC${v}_CRT_DIR}/msvcr${v}0d.dll")
+        list(APPEND __install__libs "${MSVC_CRT_DIR}/msvcr${v}d.dll")
       endif()
     endif()
 
-    if(CMAKE_INSTALL_UCRT_LIBRARIES AND NOT v VERSION_LESS 14)
-      # Find the Windows Universal CRT redistribution directory.
+    if(CMAKE_INSTALL_UCRT_LIBRARIES AND NOT vs VERSION_LESS 14)
+      # Find the Windows Kits directory.
       get_filename_component(windows_kits_dir
         "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots;KitsRoot10]" ABSOLUTE)
       set(programfilesx86 "ProgramFiles(x86)")
-      find_path(WINDOWS_KITS_REDIST_DIR NAMES ucrt/DLLs/${CMAKE_MSVC_ARCH}/ucrtbase.dll
+      find_path(WINDOWS_KITS_DIR NAMES Redist/ucrt/DLLs/${CMAKE_MSVC_ARCH}/ucrtbase.dll
         PATHS
-        "${windows_kits_dir}/Redist"
-        "$ENV{ProgramFiles}/Windows Kits/10/Redist"
-        "$ENV{${programfilesx86}}/Windows Kits/10/Redist"
+        "${windows_kits_dir}"
+        "$ENV{ProgramFiles}/Windows Kits/10"
+        "$ENV{${programfilesx86}}/Windows Kits/10"
         )
-      mark_as_advanced(WINDOWS_KITS_REDIST_DIR)
+      mark_as_advanced(WINDOWS_KITS_DIR)
 
       # Glob the list of UCRT DLLs.
-      file(GLOB __ucrt_dlls "${WINDOWS_KITS_REDIST_DIR}/ucrt/DLLs/${CMAKE_MSVC_ARCH}/*.dll")
-      list(APPEND __install__libs ${__ucrt_dlls})
+      if(NOT CMAKE_INSTALL_DEBUG_LIBRARIES_ONLY)
+        file(GLOB __ucrt_dlls "${WINDOWS_KITS_DIR}/Redist/ucrt/DLLs/${CMAKE_MSVC_ARCH}/*.dll")
+        list(APPEND __install__libs ${__ucrt_dlls})
+      endif()
+      if(CMAKE_INSTALL_DEBUG_LIBRARIES)
+        file(GLOB __ucrt_dlls "${WINDOWS_KITS_DIR}/bin/${CMAKE_MSVC_ARCH}/ucrt/*.dll")
+        list(APPEND __install__libs ${__ucrt_dlls})
+      endif()
     endif()
-  endmacro()
-
-  if(MSVC10)
-    MSVCRT_FILES_FOR_VERSION(10)
-  endif()
-
-  if(MSVC11)
-    MSVCRT_FILES_FOR_VERSION(11)
-  endif()
-
-  if(MSVC12)
-    MSVCRT_FILES_FOR_VERSION(12)
-  endif()
-
-  if(MSVC14)
-    MSVCRT_FILES_FOR_VERSION(14)
   endif()
 
   if(CMAKE_INSTALL_MFC_LIBRARIES)
-    if(MSVC70)
+    if(MSVC_VERSION EQUAL 1300)
       set(__install__libs ${__install__libs}
         "${SYSTEMROOT}/system32/mfc70.dll"
         )
     endif()
 
-    if(MSVC71)
+    if(MSVC_VERSION EQUAL 1310)
       set(__install__libs ${__install__libs}
         "${SYSTEMROOT}/system32/mfc71.dll"
         )
     endif()
 
-    if(MSVC80)
+    if(MSVC_VERSION EQUAL 1400)
       if(CMAKE_INSTALL_DEBUG_LIBRARIES)
-        set(MSVC80_MFC_DIR
-          "${MSVC80_REDIST_DIR}/Debug_NonRedist/${CMAKE_MSVC_ARCH}/Microsoft.VC80.DebugMFC")
+        set(MSVC_MFC_DIR
+          "${MSVC_REDIST_DIR}/Debug_NonRedist/${CMAKE_MSVC_ARCH}/Microsoft.VC80.DebugMFC")
         set(__install__libs ${__install__libs}
-          "${MSVC80_MFC_DIR}/Microsoft.VC80.DebugMFC.manifest"
-          "${MSVC80_MFC_DIR}/mfc80d.dll"
-          "${MSVC80_MFC_DIR}/mfc80ud.dll"
-          "${MSVC80_MFC_DIR}/mfcm80d.dll"
-          "${MSVC80_MFC_DIR}/mfcm80ud.dll"
+          "${MSVC_MFC_DIR}/Microsoft.VC80.DebugMFC.manifest"
+          "${MSVC_MFC_DIR}/mfc80d.dll"
+          "${MSVC_MFC_DIR}/mfc80ud.dll"
+          "${MSVC_MFC_DIR}/mfcm80d.dll"
+          "${MSVC_MFC_DIR}/mfcm80ud.dll"
           )
       endif()
 
-      set(MSVC80_MFC_DIR "${MSVC80_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC80.MFC")
+      set(MSVC_MFC_DIR "${MSVC_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC80.MFC")
       # Install the manifest that allows DLLs to be loaded from the
       # directory containing the executable.
       if(NOT CMAKE_INSTALL_DEBUG_LIBRARIES_ONLY)
         set(__install__libs ${__install__libs}
-          "${MSVC80_MFC_DIR}/Microsoft.VC80.MFC.manifest"
-          "${MSVC80_MFC_DIR}/mfc80.dll"
-          "${MSVC80_MFC_DIR}/mfc80u.dll"
-          "${MSVC80_MFC_DIR}/mfcm80.dll"
-          "${MSVC80_MFC_DIR}/mfcm80u.dll"
+          "${MSVC_MFC_DIR}/Microsoft.VC80.MFC.manifest"
+          "${MSVC_MFC_DIR}/mfc80.dll"
+          "${MSVC_MFC_DIR}/mfc80u.dll"
+          "${MSVC_MFC_DIR}/mfcm80.dll"
+          "${MSVC_MFC_DIR}/mfcm80u.dll"
           )
       endif()
 
       # include the language dll's for vs8 as well as the actuall dll's
-      set(MSVC80_MFCLOC_DIR "${MSVC80_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC80.MFCLOC")
+      set(MSVC_MFCLOC_DIR "${MSVC_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC80.MFCLOC")
       # Install the manifest that allows DLLs to be loaded from the
       # directory containing the executable.
       set(__install__libs ${__install__libs}
-        "${MSVC80_MFCLOC_DIR}/Microsoft.VC80.MFCLOC.manifest"
-        "${MSVC80_MFCLOC_DIR}/mfc80chs.dll"
-        "${MSVC80_MFCLOC_DIR}/mfc80cht.dll"
-        "${MSVC80_MFCLOC_DIR}/mfc80enu.dll"
-        "${MSVC80_MFCLOC_DIR}/mfc80esp.dll"
-        "${MSVC80_MFCLOC_DIR}/mfc80deu.dll"
-        "${MSVC80_MFCLOC_DIR}/mfc80fra.dll"
-        "${MSVC80_MFCLOC_DIR}/mfc80ita.dll"
-        "${MSVC80_MFCLOC_DIR}/mfc80jpn.dll"
-        "${MSVC80_MFCLOC_DIR}/mfc80kor.dll"
+        "${MSVC_MFCLOC_DIR}/Microsoft.VC80.MFCLOC.manifest"
+        "${MSVC_MFCLOC_DIR}/mfc80chs.dll"
+        "${MSVC_MFCLOC_DIR}/mfc80cht.dll"
+        "${MSVC_MFCLOC_DIR}/mfc80enu.dll"
+        "${MSVC_MFCLOC_DIR}/mfc80esp.dll"
+        "${MSVC_MFCLOC_DIR}/mfc80deu.dll"
+        "${MSVC_MFCLOC_DIR}/mfc80fra.dll"
+        "${MSVC_MFCLOC_DIR}/mfc80ita.dll"
+        "${MSVC_MFCLOC_DIR}/mfc80jpn.dll"
+        "${MSVC_MFCLOC_DIR}/mfc80kor.dll"
         )
     endif()
 
-    if(MSVC90)
+    if(MSVC_VERSION EQUAL 1500)
       if(CMAKE_INSTALL_DEBUG_LIBRARIES)
-        set(MSVC90_MFC_DIR
-          "${MSVC90_REDIST_DIR}/Debug_NonRedist/${CMAKE_MSVC_ARCH}/Microsoft.VC90.DebugMFC")
+        set(MSVC_MFC_DIR
+          "${MSVC_REDIST_DIR}/Debug_NonRedist/${CMAKE_MSVC_ARCH}/Microsoft.VC90.DebugMFC")
         set(__install__libs ${__install__libs}
-          "${MSVC90_MFC_DIR}/Microsoft.VC90.DebugMFC.manifest"
-          "${MSVC90_MFC_DIR}/mfc90d.dll"
-          "${MSVC90_MFC_DIR}/mfc90ud.dll"
-          "${MSVC90_MFC_DIR}/mfcm90d.dll"
-          "${MSVC90_MFC_DIR}/mfcm90ud.dll"
+          "${MSVC_MFC_DIR}/Microsoft.VC90.DebugMFC.manifest"
+          "${MSVC_MFC_DIR}/mfc90d.dll"
+          "${MSVC_MFC_DIR}/mfc90ud.dll"
+          "${MSVC_MFC_DIR}/mfcm90d.dll"
+          "${MSVC_MFC_DIR}/mfcm90ud.dll"
           )
       endif()
 
-      set(MSVC90_MFC_DIR "${MSVC90_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC90.MFC")
+      set(MSVC_MFC_DIR "${MSVC_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC90.MFC")
       # Install the manifest that allows DLLs to be loaded from the
       # directory containing the executable.
       if(NOT CMAKE_INSTALL_DEBUG_LIBRARIES_ONLY)
         set(__install__libs ${__install__libs}
-          "${MSVC90_MFC_DIR}/Microsoft.VC90.MFC.manifest"
-          "${MSVC90_MFC_DIR}/mfc90.dll"
-          "${MSVC90_MFC_DIR}/mfc90u.dll"
-          "${MSVC90_MFC_DIR}/mfcm90.dll"
-          "${MSVC90_MFC_DIR}/mfcm90u.dll"
+          "${MSVC_MFC_DIR}/Microsoft.VC90.MFC.manifest"
+          "${MSVC_MFC_DIR}/mfc90.dll"
+          "${MSVC_MFC_DIR}/mfc90u.dll"
+          "${MSVC_MFC_DIR}/mfcm90.dll"
+          "${MSVC_MFC_DIR}/mfcm90u.dll"
           )
       endif()
 
       # include the language dll's for vs9 as well as the actuall dll's
-      set(MSVC90_MFCLOC_DIR "${MSVC90_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC90.MFCLOC")
+      set(MSVC_MFCLOC_DIR "${MSVC_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC90.MFCLOC")
       # Install the manifest that allows DLLs to be loaded from the
       # directory containing the executable.
       set(__install__libs ${__install__libs}
-        "${MSVC90_MFCLOC_DIR}/Microsoft.VC90.MFCLOC.manifest"
-        "${MSVC90_MFCLOC_DIR}/mfc90chs.dll"
-        "${MSVC90_MFCLOC_DIR}/mfc90cht.dll"
-        "${MSVC90_MFCLOC_DIR}/mfc90enu.dll"
-        "${MSVC90_MFCLOC_DIR}/mfc90esp.dll"
-        "${MSVC90_MFCLOC_DIR}/mfc90deu.dll"
-        "${MSVC90_MFCLOC_DIR}/mfc90fra.dll"
-        "${MSVC90_MFCLOC_DIR}/mfc90ita.dll"
-        "${MSVC90_MFCLOC_DIR}/mfc90jpn.dll"
-        "${MSVC90_MFCLOC_DIR}/mfc90kor.dll"
+        "${MSVC_MFCLOC_DIR}/Microsoft.VC90.MFCLOC.manifest"
+        "${MSVC_MFCLOC_DIR}/mfc90chs.dll"
+        "${MSVC_MFCLOC_DIR}/mfc90cht.dll"
+        "${MSVC_MFCLOC_DIR}/mfc90enu.dll"
+        "${MSVC_MFCLOC_DIR}/mfc90esp.dll"
+        "${MSVC_MFCLOC_DIR}/mfc90deu.dll"
+        "${MSVC_MFCLOC_DIR}/mfc90fra.dll"
+        "${MSVC_MFCLOC_DIR}/mfc90ita.dll"
+        "${MSVC_MFCLOC_DIR}/mfc90jpn.dll"
+        "${MSVC_MFCLOC_DIR}/mfc90kor.dll"
         )
     endif()
 
-    macro(MFC_FILES_FOR_VERSION version)
-      set(v "${version}")
+    if(MSVC_VERSION EQUAL 1910)
+      set(_MFC_DLL_VERSION 140)
+      set(_MFC_IDE_VERSION 15)
+    elseif(MSVC_VERSION EQUAL 1900)
+      set(_MFC_DLL_VERSION 140)
+      set(_MFC_IDE_VERSION 14)
+    elseif(MSVC_VERSION EQUAL 1800)
+      set(_MFC_DLL_VERSION 120)
+      set(_MFC_IDE_VERSION 12)
+    elseif(MSVC_VERSION EQUAL 1700)
+      set(_MFC_DLL_VERSION 110)
+      set(_MFC_IDE_VERSION 11)
+    elseif(MSVC_VERSION EQUAL 1600)
+      set(_MFC_DLL_VERSION 100)
+      set(_MFC_IDE_VERSION 10)
+    else()
+      set(_MFC_DLL_VERSION "")
+      set(_MFC_IDE_VERSION "")
+    endif()
+
+    if(_MFC_DLL_VERSION)
+      set(v "${_MFC_DLL_VERSION}")
+      set(vs "${_MFC_IDE_VERSION}")
+
+      # Starting with VS 15 the MFC DLLs may be in a different directory.
+      if (NOT vs VERSION_LESS 15)
+        file(GLOB _MSVC_REDIST_DIRS "${MSVC_REDIST_DIR}/../*")
+        find_path(MSVC_REDIST_MFC_DIR NAMES ${CMAKE_MSVC_ARCH}/Microsoft.VC${vs}0.MFC
+          PATHS ${_MSVC_REDIST_DIRS} NO_DEFAULT_PATH)
+        mark_as_advanced(MSVC_REDIST_MFC_DIR)
+        unset(_MSVC_REDIST_DIRS)
+      else()
+        set(MSVC_REDIST_MFC_DIR "${MSVC_REDIST_DIR}")
+      endif()
 
       # Multi-Byte Character Set versions of MFC are available as optional
       # addon since Visual Studio 12.  So for version 12 or higher, check
       # whether they are available and exclude them if they are not.
 
       if(CMAKE_INSTALL_DEBUG_LIBRARIES)
-        set(MSVC${v}_MFC_DIR
-          "${MSVC${v}_REDIST_DIR}/Debug_NonRedist/${CMAKE_MSVC_ARCH}/Microsoft.VC${v}0.DebugMFC")
+        set(MSVC_MFC_DIR
+          "${MSVC_REDIST_MFC_DIR}/Debug_NonRedist/${CMAKE_MSVC_ARCH}/Microsoft.VC${vs}0.DebugMFC")
         set(__install__libs ${__install__libs}
-          "${MSVC${v}_MFC_DIR}/mfc${v}0ud.dll"
-          "${MSVC${v}_MFC_DIR}/mfcm${v}0ud.dll"
+          "${MSVC_MFC_DIR}/mfc${v}ud.dll"
+          "${MSVC_MFC_DIR}/mfcm${v}ud.dll"
           )
-        if("${v}" LESS 12 OR EXISTS "${MSVC${v}_MFC_DIR}/mfc${v}0d.dll")
+        if("${v}" LESS 12 OR EXISTS "${MSVC_MFC_DIR}/mfc${v}d.dll")
           set(__install__libs ${__install__libs}
-            "${MSVC${v}_MFC_DIR}/mfc${v}0d.dll"
-            "${MSVC${v}_MFC_DIR}/mfcm${v}0d.dll"
+            "${MSVC_MFC_DIR}/mfc${v}d.dll"
+            "${MSVC_MFC_DIR}/mfcm${v}d.dll"
           )
         endif()
       endif()
 
-      set(MSVC${v}_MFC_DIR "${MSVC${v}_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC${v}0.MFC")
+      set(MSVC_MFC_DIR "${MSVC_REDIST_MFC_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC${vs}0.MFC")
       if(NOT CMAKE_INSTALL_DEBUG_LIBRARIES_ONLY)
         set(__install__libs ${__install__libs}
-          "${MSVC${v}_MFC_DIR}/mfc${v}0u.dll"
-          "${MSVC${v}_MFC_DIR}/mfcm${v}0u.dll"
+          "${MSVC_MFC_DIR}/mfc${v}u.dll"
+          "${MSVC_MFC_DIR}/mfcm${v}u.dll"
           )
-        if("${v}" LESS 12 OR EXISTS "${MSVC${v}_MFC_DIR}/mfc${v}0.dll")
+        if("${v}" LESS 12 OR EXISTS "${MSVC_MFC_DIR}/mfc${v}.dll")
           set(__install__libs ${__install__libs}
-            "${MSVC${v}_MFC_DIR}/mfc${v}0.dll"
-            "${MSVC${v}_MFC_DIR}/mfcm${v}0.dll"
+            "${MSVC_MFC_DIR}/mfc${v}.dll"
+            "${MSVC_MFC_DIR}/mfcm${v}.dll"
           )
         endif()
       endif()
 
       # include the language dll's as well as the actuall dll's
-      set(MSVC${v}_MFCLOC_DIR "${MSVC${v}_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC${v}0.MFCLOC")
+      set(MSVC_MFCLOC_DIR "${MSVC_REDIST_MFC_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC${vs}0.MFCLOC")
       set(__install__libs ${__install__libs}
-        "${MSVC${v}_MFCLOC_DIR}/mfc${v}0chs.dll"
-        "${MSVC${v}_MFCLOC_DIR}/mfc${v}0cht.dll"
-        "${MSVC${v}_MFCLOC_DIR}/mfc${v}0deu.dll"
-        "${MSVC${v}_MFCLOC_DIR}/mfc${v}0enu.dll"
-        "${MSVC${v}_MFCLOC_DIR}/mfc${v}0esn.dll"
-        "${MSVC${v}_MFCLOC_DIR}/mfc${v}0fra.dll"
-        "${MSVC${v}_MFCLOC_DIR}/mfc${v}0ita.dll"
-        "${MSVC${v}_MFCLOC_DIR}/mfc${v}0jpn.dll"
-        "${MSVC${v}_MFCLOC_DIR}/mfc${v}0kor.dll"
-        "${MSVC${v}_MFCLOC_DIR}/mfc${v}0rus.dll"
+        "${MSVC_MFCLOC_DIR}/mfc${v}chs.dll"
+        "${MSVC_MFCLOC_DIR}/mfc${v}cht.dll"
+        "${MSVC_MFCLOC_DIR}/mfc${v}deu.dll"
+        "${MSVC_MFCLOC_DIR}/mfc${v}enu.dll"
+        "${MSVC_MFCLOC_DIR}/mfc${v}esn.dll"
+        "${MSVC_MFCLOC_DIR}/mfc${v}fra.dll"
+        "${MSVC_MFCLOC_DIR}/mfc${v}ita.dll"
+        "${MSVC_MFCLOC_DIR}/mfc${v}jpn.dll"
+        "${MSVC_MFCLOC_DIR}/mfc${v}kor.dll"
+        "${MSVC_MFCLOC_DIR}/mfc${v}rus.dll"
         )
-    endmacro()
-
-    if(MSVC10)
-      MFC_FILES_FOR_VERSION(10)
-    endif()
-
-    if(MSVC11)
-      MFC_FILES_FOR_VERSION(11)
-    endif()
-
-    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(MSVC_VERSION EQUAL 1910)
+      set(_MSOMP_DLL_VERSION 140)
+      set(_MSOMP_IDE_VERSION 15)
+    elseif(MSVC_VERSION EQUAL 1900)
+      set(_MSOMP_DLL_VERSION 140)
+      set(_MSOMP_IDE_VERSION 14)
+    elseif(MSVC_VERSION EQUAL 1800)
+      set(_MSOMP_DLL_VERSION 120)
+      set(_MSOMP_IDE_VERSION 12)
+    elseif(MSVC_VERSION EQUAL 1700)
+      set(_MSOMP_DLL_VERSION 110)
+      set(_MSOMP_IDE_VERSION 11)
+    elseif(MSVC_VERSION EQUAL 1600)
+      set(_MSOMP_DLL_VERSION 100)
+      set(_MSOMP_IDE_VERSION 10)
+    elseif(MSVC_VERSION EQUAL 1500)
+      set(_MSOMP_DLL_VERSION 90)
+      set(_MSOMP_IDE_VERSION 9)
+    elseif(MSVC_VERSION EQUAL 1400)
+      set(_MSOMP_DLL_VERSION 80)
+      set(_MSOMP_IDE_VERSION 8)
+    else()
+      set(_MSOMP_DLL_VERSION "")
+      set(_MSOMP_IDE_VERSION "")
+    endif()
+
+    if(_MSOMP_DLL_VERSION)
+      set(v "${_MSOMP_DLL_VERSION}")
+      set(vs "${_MSOMP_IDE_VERSION}")
+      set(MSVC_OPENMP_DIR "${MSVC_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC${vs}0.OPENMP")
 
       if(NOT CMAKE_INSTALL_DEBUG_LIBRARIES_ONLY)
         set(__install__libs ${__install__libs}
-          "${MSVC${va}_OPENMP_DIR}/vcomp${vb}.dll")
+          "${MSVC_OPENMP_DIR}/vcomp${v}.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()
 
diff --git a/Modules/Internal/FeatureTesting.cmake b/Modules/Internal/FeatureTesting.cmake
index 86b89b2..50b8526 100644
--- a/Modules/Internal/FeatureTesting.cmake
+++ b/Modules/Internal/FeatureTesting.cmake
@@ -1,5 +1,5 @@
 
-macro(record_compiler_features lang compile_flags feature_list)
+macro(_record_compiler_features lang compile_flags feature_list)
   include("${CMAKE_ROOT}/Modules/Compiler/${CMAKE_${lang}_COMPILER_ID}-${lang}-FeatureTests.cmake" OPTIONAL)
 
   string(TOLOWER ${lang} lang_lc)
@@ -58,3 +58,13 @@ macro(record_compiler_features lang compile_flags feature_list)
       "Detecting ${lang} [${compile_flags}] compiler features failed to compile with the following output:\n${_output}\n${_copy_error}\n\n")
   endif()
 endmacro()
+
+macro(_record_compiler_features_c std)
+  list(APPEND CMAKE_C${std}_COMPILE_FEATURES c_std_${std})
+  _record_compiler_features(C "${CMAKE_C${std}_STANDARD_COMPILE_OPTION}" CMAKE_C${std}_COMPILE_FEATURES)
+endmacro()
+
+macro(_record_compiler_features_cxx std)
+  list(APPEND CMAKE_CXX${std}_COMPILE_FEATURES cxx_std_${std})
+  _record_compiler_features(CXX "${CMAKE_CXX${std}_STANDARD_COMPILE_OPTION}" CMAKE_CXX${std}_COMPILE_FEATURES)
+endmacro()
diff --git a/Modules/Platform/Android-Clang-ASM.cmake b/Modules/Platform/Android-Clang-ASM.cmake
new file mode 100644
index 0000000..6448da6
--- /dev/null
+++ b/Modules/Platform/Android-Clang-ASM.cmake
@@ -0,0 +1,2 @@
+include(Platform/Android-Clang)
+__android_compiler_clang(ASM)
diff --git a/Modules/Platform/Android-Clang.cmake b/Modules/Platform/Android-Clang.cmake
index f0cf4a5..f739ab1 100644
--- a/Modules/Platform/Android-Clang.cmake
+++ b/Modules/Platform/Android-Clang.cmake
@@ -35,7 +35,9 @@ include(Platform/Android-Common)
 include(Platform/Android/abi-${CMAKE_ANDROID_ARCH_ABI}-Clang)
 
 macro(__android_compiler_clang lang)
-  __android_compiler_common(${lang})
+  if(NOT "x${lang}" STREQUAL "xASM")
+    __android_compiler_common(${lang})
+  endif()
   if(NOT CMAKE_${lang}_COMPILER_TARGET)
     set(CMAKE_${lang}_COMPILER_TARGET "${_ANDROID_ABI_CLANG_TARGET}")
   endif()
diff --git a/Modules/Platform/Android-Common.cmake b/Modules/Platform/Android-Common.cmake
index 8755d4f..cf2785a 100644
--- a/Modules/Platform/Android-Common.cmake
+++ b/Modules/Platform/Android-Common.cmake
@@ -149,4 +149,13 @@ macro(__android_compiler_common lang)
   if("x${lang}" STREQUAL "xCXX")
     __android_stl(CXX)
   endif()
+
+  # <ndk>/build/core/definitions.mk appends the sysroot's include directory
+  # explicitly at the end of the command-line include path so that it
+  # precedes the toolchain's builtin include directories.  This is
+  # necessary so that Android API-version-specific headers are preferred
+  # over those in the toolchain's `include-fixed` directory (which cannot
+  # possibly match all versions).
+  list(APPEND CMAKE_${lang}_STANDARD_INCLUDE_DIRECTORIES "${CMAKE_SYSROOT}/usr/include")
+  list(REMOVE_ITEM CMAKE_${lang}_IMPLICIT_INCLUDE_DIRECTORIES "/usr/include")
 endmacro()
diff --git a/Modules/Platform/Android/ndk-stl-c++.cmake b/Modules/Platform/Android/ndk-stl-c++.cmake
index b27015d..a12411c 100644
--- a/Modules/Platform/Android/ndk-stl-c++.cmake
+++ b/Modules/Platform/Android/ndk-stl-c++.cmake
@@ -6,16 +6,15 @@ macro(__android_stl_cxx lang filename)
   if(EXISTS "${CMAKE_ANDROID_NDK}/sources/cxx-stl/llvm-libc++/libcxx/include/cstddef")
     # r12 and below
     __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/llvm-libc++/libcxx/include" 1)
+    __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/android/support/include" 0)
     __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/llvm-libc++abi/libcxxabi/include" 1)
   else()
     # r13 and above
     __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/llvm-libc++/include" 1)
+    __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/android/support/include" 0)
     __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/llvm-libc++abi/include" 1)
   endif()
 
-  # Add a secondary include directory if it exists.
-  __android_stl_inc(${lang} "${CMAKE_ANDROID_NDK}/sources/android/support/include" 0)
-
   # Add the library file.
   __android_stl_lib(${lang} "${CMAKE_ANDROID_NDK}/sources/cxx-stl/llvm-libc++/libs/${CMAKE_ANDROID_ARCH_ABI}/${filename}" 1)
 endmacro()
diff --git a/Modules/Platform/Darwin-PGI-C.cmake b/Modules/Platform/Darwin-PGI-C.cmake
new file mode 100644
index 0000000..790919b
--- /dev/null
+++ b/Modules/Platform/Darwin-PGI-C.cmake
@@ -0,0 +1,2 @@
+include(Platform/Darwin-PGI)
+__darwin_compiler_pgi(C)
diff --git a/Modules/Platform/Darwin-PGI-CXX.cmake b/Modules/Platform/Darwin-PGI-CXX.cmake
new file mode 100644
index 0000000..ceaed71
--- /dev/null
+++ b/Modules/Platform/Darwin-PGI-CXX.cmake
@@ -0,0 +1,2 @@
+include(Platform/Darwin-PGI)
+__darwin_compiler_pgi(CXX)
diff --git a/Modules/Platform/Darwin-PGI-Fortran.cmake b/Modules/Platform/Darwin-PGI-Fortran.cmake
new file mode 100644
index 0000000..146807b
--- /dev/null
+++ b/Modules/Platform/Darwin-PGI-Fortran.cmake
@@ -0,0 +1,2 @@
+include(Platform/Darwin-PGI)
+__darwin_compiler_pgi(Fortran)
diff --git a/Modules/Platform/Darwin-PGI.cmake b/Modules/Platform/Darwin-PGI.cmake
new file mode 100644
index 0000000..04479a8
--- /dev/null
+++ b/Modules/Platform/Darwin-PGI.cmake
@@ -0,0 +1,14 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# This module is shared by multiple languages; use include blocker.
+if(__DARWIN_COMPILER_PGI)
+  return()
+endif()
+set(__DARWIN_COMPILER_PGI 1)
+
+macro(__darwin_compiler_pgi lang)
+  set(CMAKE_${lang}_OSX_COMPATIBILITY_VERSION_FLAG "-Wl,-compatibility_version,")
+  set(CMAKE_${lang}_OSX_CURRENT_VERSION_FLAG "-Wl,-current_version,")
+  set(CMAKE_SHARED_LIBRARY_SONAME_${lang}_FLAG "-Wl,-install_name")
+endmacro()
diff --git a/Modules/Platform/Darwin.cmake b/Modules/Platform/Darwin.cmake
index 26b12a1..727baa6 100644
--- a/Modules/Platform/Darwin.cmake
+++ b/Modules/Platform/Darwin.cmake
@@ -81,8 +81,6 @@ if("${_CURRENT_OSX_VERSION}" VERSION_LESS "10.5")
   set(CMAKE_LINK_DEPENDENT_LIBRARY_FILES 1)
 endif()
 
-set(CMAKE_C_CREATE_SHARED_LIBRARY_FORBIDDEN_FLAGS -w)
-set(CMAKE_CXX_CREATE_SHARED_LIBRARY_FORBIDDEN_FLAGS -w)
 set(CMAKE_C_CREATE_SHARED_LIBRARY
   "<CMAKE_C_COMPILER> <LANGUAGE_COMPILE_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS> <LINK_FLAGS> -o <TARGET> <SONAME_FLAG> <TARGET_INSTALLNAME_DIR><TARGET_SONAME> <OBJECTS> <LINK_LIBRARIES>")
 set(CMAKE_CXX_CREATE_SHARED_LIBRARY
diff --git a/Modules/Platform/Fuchsia.cmake b/Modules/Platform/Fuchsia.cmake
new file mode 100644
index 0000000..896da7b
--- /dev/null
+++ b/Modules/Platform/Fuchsia.cmake
@@ -0,0 +1,25 @@
+set(FUCHSIA 1)
+
+set(CMAKE_DL_LIBS "")
+set(CMAKE_C_COMPILE_OPTIONS_PIC "-fPIC")
+set(CMAKE_C_COMPILE_OPTIONS_PIE "-fPIE")
+set(CMAKE_SHARED_LIBRARY_C_FLAGS "-fPIC")
+set(CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS "-shared")
+set(CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG "-Wl,-rpath,")
+set(CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG_SEP ":")
+set(CMAKE_SHARED_LIBRARY_RPATH_LINK_C_FLAG "-Wl,-rpath-link,")
+set(CMAKE_SHARED_LIBRARY_SONAME_C_FLAG "-Wl,-soname,")
+set(CMAKE_EXE_EXPORTS_C_FLAG "-Wl,--export-dynamic")
+
+# Shared libraries with no builtin soname may not be linked safely by
+# specifying the file path.
+set(CMAKE_PLATFORM_USES_PATH_WHEN_NO_SONAME 1)
+
+# Initialize C link type selection flags.  These flags are used when
+# building a shared library, shared module, or executable that links
+# to other libraries to select whether to use the static or shared
+# versions of the libraries.
+foreach(type SHARED_LIBRARY SHARED_MODULE EXE)
+  set(CMAKE_${type}_LINK_STATIC_C_FLAGS "-Wl,-Bstatic")
+  set(CMAKE_${type}_LINK_DYNAMIC_C_FLAGS "-Wl,-Bdynamic")
+endforeach()
diff --git a/Modules/Platform/Windows-MSVC.cmake b/Modules/Platform/Windows-MSVC.cmake
index d72ec66..e4aca6e 100644
--- a/Modules/Platform/Windows-MSVC.cmake
+++ b/Modules/Platform/Windows-MSVC.cmake
@@ -54,6 +54,8 @@ if(NOT MSVC_VERSION)
     set(_compiler_version ${CMAKE_CXX_SIMULATE_VERSION})
   elseif(CMAKE_Fortran_SIMULATE_VERSION)
     set(_compiler_version ${CMAKE_Fortran_SIMULATE_VERSION})
+  elseif(CMAKE_CUDA_SIMULATE_VERSION)
+    set(_compiler_version ${CMAKE_CUDA_SIMULATE_VERSION})
   elseif(CMAKE_C_COMPILER_VERSION)
     set(_compiler_version ${CMAKE_C_COMPILER_VERSION})
   else()
@@ -76,7 +78,9 @@ if(NOT MSVC_VERSION)
   set(MSVC90)
   set(CMAKE_COMPILER_2005)
   set(CMAKE_COMPILER_SUPPORTS_PDBTYPE)
-  if(NOT "${_compiler_version}" VERSION_LESS 19)
+  if(NOT "${_compiler_version}" VERSION_LESS 20)
+    # We no longer provide per-version variables.  Use MSVC_VERSION instead.
+  elseif(NOT "${_compiler_version}" VERSION_LESS 19)
     set(MSVC14 1)
   elseif(NOT "${_compiler_version}" VERSION_LESS 18)
     set(MSVC12 1)
@@ -285,13 +289,13 @@ macro(__windows_compiler_msvc lang)
       # note: MSVC 14 2015 Update 1 sets -fno-ms-compatibility by default, but this does not allow one to compile many projects
       # that include MS's own headers. CMake itself is affected project too.
       string(APPEND CMAKE_${lang}_FLAGS_INIT " ${_PLATFORM_DEFINES}${_PLATFORM_DEFINES_${lang}} -fms-extensions -fms-compatibility -D_WINDOWS -Wall${_FLAGS_${lang}}")
-      string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " -D_DEBUG /MDd -gline-tables-only -fno-inline -O0 ${_RTC1}")
+      string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " /MDd -gline-tables-only -fno-inline -O0 ${_RTC1}")
       string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " /MD -O2 -DNDEBUG")
       string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " /MD -gline-tables-only -O2 -fno-inline -DNDEBUG")
       string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " /MD -DNDEBUG") # TODO: Add '-Os' once VS generator maps it properly for Clang
     else()
       string(APPEND CMAKE_${lang}_FLAGS_INIT " ${_PLATFORM_DEFINES}${_PLATFORM_DEFINES_${lang}} /D_WINDOWS /W3${_FLAGS_${lang}}")
-      string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " /D_DEBUG /MDd /Zi /Ob0 /Od ${_RTC1}")
+      string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " /MDd /Zi /Ob0 /Od ${_RTC1}")
       string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " /MD /O2 /Ob2 /DNDEBUG")
       string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " /MD /Zi /O2 /Ob1 /DNDEBUG")
       string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " /MD /O1 /Ob1 /DNDEBUG")
@@ -306,6 +310,9 @@ macro(__windows_compiler_msvc lang)
   if(NOT CMAKE_RC_FLAGS_INIT)
     string(APPEND CMAKE_RC_FLAGS_INIT " ${_PLATFORM_DEFINES} ${_PLATFORM_DEFINES_${lang}}")
   endif()
+  if(NOT CMAKE_RC_FLAGS_DEBUG_INIT)
+    string(APPEND CMAKE_RC_FLAGS_DEBUG_INIT " /D_DEBUG")
+  endif()
 
   enable_language(RC)
   set(CMAKE_NINJA_CMCLDEPS_RC 1)
diff --git a/Modules/Platform/Windows-NVIDIA-CUDA.cmake b/Modules/Platform/Windows-NVIDIA-CUDA.cmake
new file mode 100644
index 0000000..845fa4b
--- /dev/null
+++ b/Modules/Platform/Windows-NVIDIA-CUDA.cmake
@@ -0,0 +1,46 @@
+include(Platform/Windows-MSVC)
+
+set(CMAKE_CUDA_COMPILE_PTX_COMPILATION
+  "<CMAKE_CUDA_COMPILER> ${CMAKE_CUDA_HOST_FLAGS} <DEFINES> <INCLUDES> <FLAGS> -x cu -ptx <SOURCE> -o <OBJECT> -Xcompiler=-Fd<TARGET_COMPILE_PDB>,-FS")
+set(CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION
+  "<CMAKE_CUDA_COMPILER> ${CMAKE_CUDA_HOST_FLAGS} <DEFINES> <INCLUDES> <FLAGS> -x cu -dc <SOURCE> -o <OBJECT> -Xcompiler=-Fd<TARGET_COMPILE_PDB>,-FS")
+set(CMAKE_CUDA_COMPILE_WHOLE_COMPILATION
+  "<CMAKE_CUDA_COMPILER> ${CMAKE_CUDA_HOST_FLAGS} <DEFINES> <INCLUDES> <FLAGS> -x cu -c <SOURCE> -o <OBJECT> -Xcompiler=-Fd<TARGET_COMPILE_PDB>,-FS")
+
+set(__IMPLICT_LINKS )
+foreach(dir ${CMAKE_CUDA_HOST_IMPLICIT_LINK_DIRECTORIES})
+  string(APPEND __IMPLICT_LINKS " -LIBPATH:\"${dir}\"")
+endforeach()
+foreach(lib ${CMAKE_CUDA_HOST_IMPLICIT_LINK_LIBRARIES})
+  string(APPEND __IMPLICT_LINKS " \"${lib}\"")
+endforeach()
+set(CMAKE_CUDA_LINK_EXECUTABLE
+   "<CMAKE_CUDA_HOST_LINK_LAUNCHER> <CMAKE_CUDA_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> /out:<TARGET> /implib:<TARGET_IMPLIB> /pdb:<TARGET_PDB> /version:<TARGET_VERSION_MAJOR>.<TARGET_VERSION_MINOR> <LINK_LIBRARIES>${__IMPLICT_LINKS}")
+
+set(_CMAKE_VS_LINK_DLL "<CMAKE_COMMAND> -E vs_link_dll --intdir=<OBJECT_DIR> --manifests <MANIFESTS> -- ")
+set(_CMAKE_VS_LINK_EXE "<CMAKE_COMMAND> -E vs_link_exe --intdir=<OBJECT_DIR> --manifests <MANIFESTS> -- ")
+set(CMAKE_CUDA_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>${_PLATFORM_LINK_FLAGS} <LINK_FLAGS> <LINK_LIBRARIES>${__IMPLICT_LINKS} ${CMAKE_END_TEMP_FILE}")
+
+set(CMAKE_CUDA_CREATE_SHARED_MODULE ${CMAKE_CUDA_CREATE_SHARED_LIBRARY})
+set(CMAKE_CUDA_CREATE_STATIC_LIBRARY  "<CMAKE_LINKER> /lib ${CMAKE_CL_NOLOGO} <LINK_FLAGS> /out:<TARGET> <OBJECTS> ")
+set(CMAKE_CUDA_LINKER_SUPPORTS_PDB ON)
+set(CMAKE_CUDA_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>${_PLATFORM_LINK_FLAGS} <CMAKE_CUDA_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES>${__IMPLICT_LINKS} ${CMAKE_END_TEMP_FILE}")
+unset(_CMAKE_VS_LINK_EXE)
+unset(_CMAKE_VS_LINK_EXE)
+
+set(CMAKE_CUDA_DEVICE_LINK_LIBRARY
+  "<CMAKE_CUDA_COMPILER> <CMAKE_CUDA_LINK_FLAGS> <LANGUAGE_COMPILE_FLAGS> -shared -dlink <OBJECTS> -o <TARGET> <LINK_LIBRARIES> -Xcompiler=-Fd<TARGET_COMPILE_PDB>,-FS")
+set(CMAKE_CUDA_DEVICE_LINK_EXECUTABLE
+  "<CMAKE_CUDA_COMPILER> <FLAGS> <CMAKE_CUDA_LINK_FLAGS> -shared -dlink <OBJECTS> -o <TARGET> <LINK_LIBRARIES> -Xcompiler=-Fd<TARGET_COMPILE_PDB>,-FS")
+
+string(REPLACE "/D" "-D" _PLATFORM_DEFINES_CUDA "${_PLATFORM_DEFINES}${_PLATFORM_DEFINES_CXX}")
+
+string(APPEND CMAKE_CUDA_FLAGS_INIT " ${PLATFORM_DEFINES_CUDA} -D_WINDOWS -Xcompiler=\"/W3${_FLAGS_CXX}\"")
+string(APPEND CMAKE_CUDA_FLAGS_DEBUG_INIT " -Xcompiler=\"-MDd -Zi -Ob0 -Od ${_RTC1}\"")
+string(APPEND CMAKE_CUDA_FLAGS_RELEASE_INIT " -Xcompiler=\"-MD -O2 -Ob2\" -DNDEBUG")
+string(APPEND CMAKE_CUDA_FLAGS_RELWITHDEBINFO_INIT " -Xcompiler=\"-MD -Zi -O2 -Ob1\" -DNDEBUG")
+string(APPEND CMAKE_CUDA_FLAGS_MINSIZEREL_INIT " -Xcompiler=\"-MD -O1 -Ob1\" -DNDEBUG")
+
+set(CMAKE_CUDA_STANDARD_LIBRARIES_INIT "${CMAKE_C_STANDARD_LIBRARIES_INIT}")
diff --git a/Modules/Platform/Windows.cmake b/Modules/Platform/Windows.cmake
index 9a937a7..d8b3957 100644
--- a/Modules/Platform/Windows.cmake
+++ b/Modules/Platform/Windows.cmake
@@ -17,6 +17,7 @@ set(CMAKE_IMPORT_LIBRARY_SUFFIX ".lib")
 set(CMAKE_EXECUTABLE_SUFFIX ".exe")          # .exe
 set(CMAKE_LINK_LIBRARY_SUFFIX ".lib")
 set(CMAKE_DL_LIBS "")
+set(CMAKE_EXTRA_LINK_EXTENSIONS ".targets")
 
 set(CMAKE_FIND_LIBRARY_PREFIXES "")
 set(CMAKE_FIND_LIBRARY_SUFFIXES ".lib")
diff --git a/Modules/Qt4Macros.cmake b/Modules/Qt4Macros.cmake
index 0279d1c..0478918 100644
--- a/Modules/Qt4Macros.cmake
+++ b/Modules/Qt4Macros.cmake
@@ -439,7 +439,7 @@ macro(QT4_CREATE_TRANSLATION _qm_files)
          get_filename_component(_abs_include "${_pro_include}" ABSOLUTE)
          string(APPEND _pro_includes " \\\n  \"${_abs_include}\"")
        endforeach()
-       file(WRITE ${_ts_pro} "SOURCES =${_pro_srcs}\nINCLUDEPATH =${_pro_includes}\n")
+       file(GENERATE OUTPUT ${_ts_pro} CONTENT "SOURCES =${_pro_srcs}\nINCLUDEPATH =${_pro_includes}\n")
      endif()
      add_custom_command(OUTPUT ${_ts_file}
         COMMAND Qt4::lupdate
diff --git a/Modules/UseJava.cmake b/Modules/UseJava.cmake
index 6b34c8f..93255ae 100644
--- a/Modules/UseJava.cmake
+++ b/Modules/UseJava.cmake
@@ -403,8 +403,6 @@
 #    Sets the directory where the header files will be generated. Same behavior as option
 #    '-d' of javah tool. If not specified, ${CMAKE_CURRENT_BINARY_DIR} is used as output directory.
 
-include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake)
-
 function (__java_copy_file src dest comment)
     add_custom_command(
         OUTPUT  ${dest}
diff --git a/Modules/UseSWIG.cmake b/Modules/UseSWIG.cmake
index d242f87..277f4ca 100644
--- a/Modules/UseSWIG.cmake
+++ b/Modules/UseSWIG.cmake
@@ -9,18 +9,22 @@
 #
 # ::
 #
-#    SWIG_ADD_MODULE(name language [ files ])
+#    SWIG_ADD_LIBRARY(<name>
+#                     [TYPE <SHARED|MODULE|STATIC|USE_BUILD_SHARED_LIBS>]
+#                     LANGUAGE <language>
+#                     SOURCES <file>...
+#                     )
 #      - Define swig module with given name and specified language
 #    SWIG_LINK_LIBRARIES(name [ libraries ])
 #      - Link libraries to swig module
 #
 # Source files properties on module files can be set before the invocation
-# of the SWIG_ADD_MODULE macro to specify special behavior of SWIG.
+# of the SWIG_ADD_LIBRARY macro to specify special behavior of SWIG.
 #
 # The source file property CPLUSPLUS calls SWIG in c++ mode, e.g.::
 #
 #    set_property(SOURCE mymod.i PROPERTY CPLUSPLUS ON)
-#    swig_add_module(mymod python mymod.i)
+#    swig_add_library(mymod LANGUAGE python SOURCES mymod.i)
 #
 # The source file property SWIG_FLAGS adds custom flags to the SWIG executable.
 #
@@ -36,8 +40,11 @@
 #
 # CMAKE_SWIG_FLAGS can be used to add special flags to all swig calls.
 #
-# Another special variable is CMAKE_SWIG_OUTDIR, it allows one to specify
-# where to write all the swig generated module (swig -outdir option)
+# CMAKE_SWIG_OUTDIR allows one to specify where to write
+# the language specific files (swig -outdir option).
+#
+# SWIG_OUTFILE_DIR allows one to specify where to write the output file
+# (swig -o option).  If not specified, CMAKE_SWIG_OUTDIR is used.
 #
 # The name-specific variable SWIG_MODULE_<name>_EXTRA_DEPS may be used to specify extra
 # dependencies for the generated modules.
@@ -50,7 +57,8 @@
 set(SWIG_CXX_EXTENSION "cxx")
 set(SWIG_EXTRA_LIBRARIES "")
 
-set(SWIG_PYTHON_EXTRA_FILE_EXTENSION "py")
+set(SWIG_PYTHON_EXTRA_FILE_EXTENSIONS ".py")
+set(SWIG_JAVA_EXTRA_FILE_EXTENSIONS ".java" "JNI.java")
 
 #
 # For given swig module initialize variables associated with it
@@ -116,9 +124,9 @@ macro(SWIG_GET_EXTRA_OUTPUT_FILES language outfiles generatedpath infile)
     endif ()
 
   endif()
-  foreach(it ${SWIG_${language}_EXTRA_FILE_EXTENSION})
+  foreach(it ${SWIG_${language}_EXTRA_FILE_EXTENSIONS})
     set(${outfiles} ${${outfiles}}
-      "${generatedpath}/${SWIG_GET_EXTRA_OUTPUT_FILES_module_basename}.${it}")
+      "${generatedpath}/${SWIG_GET_EXTRA_OUTPUT_FILES_module_basename}${it}")
   endforeach()
 endmacro()
 
@@ -142,6 +150,13 @@ macro(SWIG_ADD_SOURCE_TO_MODULE name outfiles infile)
   else()
     set(swig_outdir ${CMAKE_CURRENT_BINARY_DIR})
   endif()
+
+  if(SWIG_OUTFILE_DIR)
+    set(swig_outfile_dir ${SWIG_OUTFILE_DIR})
+  else()
+    set(swig_outfile_dir ${swig_outdir})
+  endif()
+
   if (NOT SWIG_MODULE_${name}_NOPROXY)
     SWIG_GET_EXTRA_OUTPUT_FILES(${SWIG_MODULE_${name}_LANGUAGE}
       swig_extra_generated_files
@@ -149,7 +164,7 @@ macro(SWIG_ADD_SOURCE_TO_MODULE name outfiles infile)
       "${swig_source_file_fullname}")
   endif()
   set(swig_generated_file_fullname
-    "${swig_outdir}/${swig_source_file_name_we}")
+    "${swig_outfile_dir}/${swig_source_file_name_we}")
   # add the language into the name of the file (i.e. TCL_wrap)
   # this allows for the same .i file to be wrapped into different languages
   string(APPEND swig_generated_file_fullname
@@ -197,6 +212,7 @@ macro(SWIG_ADD_SOURCE_TO_MODULE name outfiles infile)
     "${swig_source_file_fullname}"
     MAIN_DEPENDENCY "${swig_source_file_fullname}"
     DEPENDS ${SWIG_MODULE_${name}_EXTRA_DEPS}
+    IMPLICIT_DEPENDS CXX "${swig_source_file_fullname}"
     COMMENT "Swig source")
   set_source_files_properties("${swig_generated_file_fullname}" ${swig_extra_generated_files}
     PROPERTIES GENERATED 1)
@@ -207,10 +223,40 @@ endmacro()
 # Create Swig module
 #
 macro(SWIG_ADD_MODULE name language)
-  SWIG_MODULE_INITIALIZE(${name} ${language})
+  message(DEPRECATION "SWIG_ADD_MODULE is deprecated. Use SWIG_ADD_LIBRARY instead.")
+  swig_add_library(${name}
+                   LANGUAGE ${language}
+                   TYPE MODULE
+                   SOURCES ${ARGN})
+endmacro()
+
+
+macro(SWIG_ADD_LIBRARY name)
+  set(options "")
+  set(oneValueArgs LANGUAGE
+                   TYPE)
+  set(multiValueArgs SOURCES)
+  cmake_parse_arguments(_SAM "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
+
+  if(NOT DEFINED _SAM_LANGUAGE)
+    message(FATAL_ERROR "SWIG_ADD_LIBRARY: Missing LANGUAGE argument")
+  endif()
+
+  if(NOT DEFINED _SAM_SOURCES)
+    message(FATAL_ERROR "SWIG_ADD_LIBRARY: Missing SOURCES argument")
+  endif()
+
+  if(NOT DEFINED _SAM_TYPE)
+    set(_SAM_TYPE MODULE)
+  elseif("${_SAM_TYPE}" STREQUAL "USE_BUILD_SHARED_LIBS")
+    unset(_SAM_TYPE)
+  endif()
+
+  swig_module_initialize(${name} ${_SAM_LANGUAGE})
+
   set(swig_dot_i_sources)
   set(swig_other_sources)
-  foreach(it ${ARGN})
+  foreach(it ${_SAM_SOURCES})
     if(${it} MATCHES "\\.i$")
       set(swig_dot_i_sources ${swig_dot_i_sources} "${it}")
     else()
@@ -227,11 +273,13 @@ macro(SWIG_ADD_MODULE name language)
   set_directory_properties(PROPERTIES
     ADDITIONAL_MAKE_CLEAN_FILES "${swig_extra_clean_files};${swig_generated_sources}")
   add_library(${SWIG_MODULE_${name}_REAL_NAME}
-    MODULE
+    ${_SAM_TYPE}
     ${swig_generated_sources}
     ${swig_other_sources})
-  set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES NO_SONAME ON)
-  string(TOLOWER "${language}" swig_lowercase_language)
+  if("${_SAM_TYPE}" STREQUAL "MODULE")
+    set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES NO_SONAME ON)
+  endif()
+  string(TOLOWER "${_SAM_LANGUAGE}" swig_lowercase_language)
   if ("${swig_lowercase_language}" STREQUAL "octave")
     set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "")
     set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES SUFFIX ".oct")
@@ -248,7 +296,9 @@ macro(SWIG_ADD_MODULE name language)
         set_target_properties (${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES SUFFIX ".jnilib")
       endif ()
   elseif ("${swig_lowercase_language}" STREQUAL "lua")
-    set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "")
+    if("${_SAM_TYPE}" STREQUAL "MODULE")
+      set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "")
+    endif()
   elseif ("${swig_lowercase_language}" STREQUAL "python")
     # this is only needed for the python case where a _modulename.so is generated
     set_target_properties(${SWIG_MODULE_${name}_REAL_NAME} PROPERTIES PREFIX "")
@@ -289,4 +339,3 @@ macro(SWIG_LINK_LIBRARIES name)
     message(SEND_ERROR "Cannot find Swig library \"${name}\".")
   endif()
 endmacro()
-
diff --git a/Modules/WriteBasicConfigVersionFile.cmake b/Modules/WriteBasicConfigVersionFile.cmake
index 20c769e..7c9467a 100644
--- a/Modules/WriteBasicConfigVersionFile.cmake
+++ b/Modules/WriteBasicConfigVersionFile.cmake
@@ -18,8 +18,6 @@
 #
 # Deprecated, see WRITE_BASIC_PACKAGE_VERSION_FILE(), it is identical.
 
-include(CMakeParseArguments)
-
 function(WRITE_BASIC_CONFIG_VERSION_FILE _filename)
 
   set(options )
diff --git a/Modules/WriteCompilerDetectionHeader.cmake b/Modules/WriteCompilerDetectionHeader.cmake
index 82e8fba..0b16aa4 100644
--- a/Modules/WriteCompilerDetectionHeader.cmake
+++ b/Modules/WriteCompilerDetectionHeader.cmake
@@ -20,6 +20,8 @@
 #              [VERSION <version>]
 #              [PROLOG <prolog>]
 #              [EPILOG <epilog>]
+#              [ALLOW_UNKNOWN_COMPILERS]
+#              [ALLOW_UNKNOWN_COMPILER_VERSIONS]
 #    )
 #
 # The ``write_compiler_detection_header`` function generates the
@@ -76,10 +78,16 @@
 # Available features in this version of CMake are listed in the
 # :prop_gbl:`CMAKE_C_KNOWN_FEATURES` and
 # :prop_gbl:`CMAKE_CXX_KNOWN_FEATURES` global properties.
+# The ``{c,cxx}_std_*`` meta-features are ignored if requested.
 #
 # See the :manual:`cmake-compile-features(7)` manual for information on
 # compile features.
 #
+# ``ALLOW_UNKNOWN_COMPILERS`` and ``ALLOW_UNKNOWN_COMPILER_VERSIONS`` cause
+# the module to generate conditions that treat unknown compilers as simply
+# lacking all features.  Without these options the default behavior is to
+# generate a ``#error`` for unknown compilers.
+#
 # Feature Test Macros
 # ===================
 #
@@ -215,7 +223,6 @@
 #       CompatSupport_DEPRECATED=
 #   )
 
-include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake)
 include(${CMAKE_CURRENT_LIST_DIR}/CMakeCompilerIdDetection.cmake)
 
 function(_load_compiler_variables CompilerId lang)
@@ -232,6 +239,19 @@ function(_load_compiler_variables CompilerId lang)
   set(_compiler_id_version_compute_${CompilerId} ${_compiler_id_version_compute} PARENT_SCOPE)
 endfunction()
 
+macro(_simpledefine FEATURE_NAME FEATURE_TESTNAME FEATURE_STRING FEATURE_DEFAULT_STRING)
+  if (feature STREQUAL "${FEATURE_NAME}")
+        set(def_value "${prefix_arg}_${FEATURE_TESTNAME}")
+        string(APPEND file_content "
+#  if defined(${def_name}) && ${def_name}
+#    define ${def_value} ${FEATURE_STRING}
+#  else
+#    define ${def_value} ${FEATURE_DEFAULT_STRING}
+#  endif
+\n")
+  endif()
+endmacro()
+
 function(write_compiler_detection_header
     file_keyword file_arg
     prefix_keyword prefix_arg
@@ -242,7 +262,7 @@ function(write_compiler_detection_header
   if (NOT "x${prefix_keyword}" STREQUAL "xPREFIX")
     message(FATAL_ERROR "write_compiler_detection_header: PREFIX parameter missing.")
   endif()
-  set(options)
+  set(options ALLOW_UNKNOWN_COMPILERS ALLOW_UNKNOWN_COMPILER_VERSIONS)
   set(oneValueArgs VERSION EPILOG PROLOG OUTPUT_FILES_VAR OUTPUT_DIR)
   set(multiValueArgs COMPILERS FEATURES)
   cmake_parse_arguments(_WCD "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
@@ -358,7 +378,11 @@ function(write_compiler_detection_header
   endif()
 
   foreach(feature ${_WCD_FEATURES})
-    if (feature MATCHES "^cxx_")
+    if (feature MATCHES "^c_std_")
+      # ignored
+    elseif (feature MATCHES "^cxx_std_")
+      # ignored
+    elseif (feature MATCHES "^cxx_")
       list(APPEND _langs CXX)
       list(APPEND CXX_features ${feature})
     elseif (feature MATCHES "^c_")
@@ -422,10 +446,12 @@ function(write_compiler_detection_header
         set(compiler_file_content file_content)
       endif()
 
-      set(${compiler_file_content} "${${compiler_file_content}}
+      if(NOT _WCD_ALLOW_UNKNOWN_COMPILER_VERSIONS)
+        set(${compiler_file_content} "${${compiler_file_content}}
 #    if !(${_cmake_oldestSupported_${compiler}})
 #      error Unsupported compiler version
 #    endif\n")
+      endif()
 
       set(PREFIX ${prefix_arg}_)
       if (_need_hex_conversion)
@@ -456,67 +482,36 @@ function(write_compiler_detection_header
       endforeach()
     endforeach()
     if(pp_if STREQUAL "elif")
-      string(APPEND file_content "
+      if(_WCD_ALLOW_UNKNOWN_COMPILERS)
+        string(APPEND file_content "
+#  endif\n")
+      else()
+        string(APPEND file_content "
 #  else
 #    error Unsupported compiler
 #  endif\n")
+      endif()
     endif()
     foreach(feature ${${_lang}_features})
       string(TOUPPER ${feature} feature_upper)
       set(feature_PP "COMPILER_${feature_upper}")
       set(def_name ${prefix_arg}_${feature_PP})
-      if (feature STREQUAL c_restrict)
-        set(def_value "${prefix_arg}_RESTRICT")
-        string(APPEND file_content "
-#  if ${def_name}
-#    define ${def_value} restrict
-#  else
-#    define ${def_value}
-#  endif
-\n")
-      endif()
-      if (feature STREQUAL cxx_constexpr)
-        set(def_value "${prefix_arg}_CONSTEXPR")
-        string(APPEND file_content "
-#  if ${def_name}
-#    define ${def_value} constexpr
-#  else
-#    define ${def_value}
-#  endif
-\n")
-      endif()
-      if (feature STREQUAL cxx_final)
-        set(def_value "${prefix_arg}_FINAL")
-        string(APPEND file_content "
-#  if ${def_name}
-#    define ${def_value} final
-#  else
-#    define ${def_value}
-#  endif
-\n")
-      endif()
-      if (feature STREQUAL cxx_override)
-        set(def_value "${prefix_arg}_OVERRIDE")
-        string(APPEND file_content "
-#  if ${def_name}
-#    define ${def_value} override
-#  else
-#    define ${def_value}
-#  endif
-\n")
-      endif()
+      _simpledefine(c_restrict RESTRICT restrict "")
+      _simpledefine(cxx_constexpr CONSTEXPR constexpr "")
+      _simpledefine(cxx_final FINAL final "")
+      _simpledefine(cxx_override OVERRIDE override "")
       if (feature STREQUAL cxx_static_assert)
         set(def_value "${prefix_arg}_STATIC_ASSERT(X)")
         set(def_value_msg "${prefix_arg}_STATIC_ASSERT_MSG(X, MSG)")
         set(static_assert_struct "template<bool> struct ${prefix_arg}StaticAssert;\ntemplate<> struct ${prefix_arg}StaticAssert<true>{};\n")
         set(def_standard "#    define ${def_value} static_assert(X, #X)\n#    define ${def_value_msg} static_assert(X, MSG)")
         set(def_alternative "${static_assert_struct}#    define ${def_value} sizeof(${prefix_arg}StaticAssert<X>)\n#    define ${def_value_msg} sizeof(${prefix_arg}StaticAssert<X>)")
-        string(APPEND file_content "#  if ${def_name}\n${def_standard}\n#  else\n${def_alternative}\n#  endif\n\n")
+        string(APPEND file_content "#  if defined(${def_name}) && ${def_name}\n${def_standard}\n#  else\n${def_alternative}\n#  endif\n\n")
       endif()
       if (feature STREQUAL cxx_alignas)
         set(def_value "${prefix_arg}_ALIGNAS(X)")
         string(APPEND file_content "
-#  if ${def_name}
+#  if defined(${def_name}) && ${def_name}
 #    define ${def_value} alignas(X)
 #  elif ${prefix_arg}_COMPILER_IS_GNU || ${prefix_arg}_COMPILER_IS_Clang || ${prefix_arg}_COMPILER_IS_AppleClang
 #    define ${def_value} __attribute__ ((__aligned__(X)))
@@ -530,7 +525,7 @@ function(write_compiler_detection_header
       if (feature STREQUAL cxx_alignof)
         set(def_value "${prefix_arg}_ALIGNOF(X)")
         string(APPEND file_content "
-#  if ${def_name}
+#  if defined(${def_name}) && ${def_name}
 #    define ${def_value} alignof(X)
 #  elif ${prefix_arg}_COMPILER_IS_GNU || ${prefix_arg}_COMPILER_IS_Clang || ${prefix_arg}_COMPILER_IS_AppleClang
 #    define ${def_value} __alignof__(X)
@@ -539,30 +534,12 @@ function(write_compiler_detection_header
 #  endif
 \n")
       endif()
-      if (feature STREQUAL cxx_deleted_functions)
-        set(def_value "${prefix_arg}_DELETED_FUNCTION")
-        string(APPEND file_content "
-#  if ${def_name}
-#    define ${def_value} = delete
-#  else
-#    define ${def_value}
-#  endif
-\n")
-      endif()
-      if (feature STREQUAL cxx_extern_templates)
-        set(def_value "${prefix_arg}_EXTERN_TEMPLATE")
-        string(APPEND file_content "
-#  if ${def_name}
-#    define ${def_value} extern
-#  else
-#    define ${def_value}
-#  endif
-\n")
-      endif()
+      _simpledefine(cxx_deleted_functions DELETED_FUNCTION "= delete" "")
+      _simpledefine(cxx_extern_templates EXTERN_TEMPLATE extern "")
       if (feature STREQUAL cxx_noexcept)
         set(def_value "${prefix_arg}_NOEXCEPT")
         string(APPEND file_content "
-#  if ${def_name}
+#  if defined(${def_name}) && ${def_name}
 #    define ${def_value} noexcept
 #    define ${def_value}_EXPR(X) noexcept(X)
 #  else
@@ -571,20 +548,11 @@ function(write_compiler_detection_header
 #  endif
 \n")
       endif()
-      if (feature STREQUAL cxx_nullptr)
-        set(def_value "${prefix_arg}_NULLPTR")
-        string(APPEND file_content "
-#  if ${def_name}
-#    define ${def_value} nullptr
-#  else
-#    define ${def_value} 0
-#  endif
-\n")
-      endif()
+      _simpledefine(cxx_nullptr NULLPTR nullptr 0)
       if (feature STREQUAL cxx_thread_local)
         set(def_value "${prefix_arg}_THREAD_LOCAL")
         string(APPEND file_content "
-#  if ${def_name}
+#  if defined(${def_name}) && ${def_name}
 #    define ${def_value} thread_local
 #  elif ${prefix_arg}_COMPILER_IS_GNU || ${prefix_arg}_COMPILER_IS_Clang || ${prefix_arg}_COMPILER_IS_AppleClang
 #    define ${def_value} __thread
@@ -600,7 +568,7 @@ function(write_compiler_detection_header
         set(def_value "${prefix_arg}_DEPRECATED")
         string(APPEND file_content "
 #  ifndef ${def_value}
-#    if ${def_name}
+#    if defined(${def_name}) && ${def_name}
 #      define ${def_value} [[deprecated]]
 #      define ${def_value}_MSG(MSG) [[deprecated(MSG)]]
 #    elif ${prefix_arg}_COMPILER_IS_GNU || ${prefix_arg}_COMPILER_IS_Clang
diff --git a/Packaging/QtSDK/ToolsCMakeXX.cmake b/Packaging/QtSDK/ToolsCMakeXX.cmake
new file mode 100644
index 0000000..99731fb
--- /dev/null
+++ b/Packaging/QtSDK/ToolsCMakeXX.cmake
@@ -0,0 +1,45 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# CMake version
+include("${CMAKE_CURRENT_LIST_DIR}/../../Source/CMakeVersion.cmake")
+
+# Install destinations
+set(CMake_INSTALL_INFIX "Tools/CMake/${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}/"
+  CACHE STRING "Location under install CMake tools")
+
+# Package
+set(CMake_IFW_ROOT_COMPONENT_NAME
+  "qt.tools.cmake.${CMake_VERSION_MAJOR}${CMake_VERSION_MINOR}"
+  CACHE STRING "QtSDK CMake tools component name")
+set(CMake_IFW_ROOT_COMPONENT_DISPLAY_NAME
+  "CMake ${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}.${CMake_VERSION_PATCH}"
+  CACHE STRING "QtSDK CMake tools component display name")
+set(CMake_IFW_ROOT_COMPONENT_DESCRIPTION
+  "CMake Build Tools ${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}.${CMake_VERSION_PATH}"
+  CACHE STRING "QtSDK CMake tools component description")
+set(CMake_IFW_ROOT_COMPONENT_SCRIPT_TEMPLATE
+  "${CMAKE_CURRENT_LIST_DIR}/qt.tools.cmake.xx.qs.in"
+  CACHE FILEPATH "QtSDK CMake tools script template")
+set(CMake_IFW_ROOT_COMPONENT_SCRIPT_GENERATED
+  "${CMAKE_CURRENT_BINARY_DIR}/qt.tools.cmake.${CMake_VERSION_MAJOR}${CMake_VERSION_MINOR}.qs"
+  CACHE FILEPATH "QtSDK CMake tools script generated")
+set(CMake_IFW_ROOT_COMPONENT_PRIORITY
+  "${CMake_VERSION_MAJOR}${CMake_VERSION_MINOR}"
+  CACHE STRING "QtSDK CMake tools component sorting priority")
+set(CMake_IFW_ROOT_COMPONENT_DEFAULT ""
+  CACHE STRING "QtSDK CMake tools component default")
+set(CMake_IFW_ROOT_COMPONENT_FORCED_INSTALLATION ""
+  CACHE STRING "QtSDK CMake tools component forsed installation")
+
+# CPack
+set(CPACK_GENERATOR "IFW"
+  CACHE STRING "Generator to build QtSDK CMake package")
+set(CPACK_PACKAGE_FILE_NAME "CMake"
+  CACHE STRING "Short package name")
+set(CPACK_TOPLEVEL_TAG "../QtSDK"
+  CACHE STRING "QtSDK packages dir")
+set(CPACK_IFW_DOWNLOAD_ALL "TRUE"
+  CACHE STRING "All QtSDK components is downloaded")
+set(CPACK_DOWNLOAD_SITE "file:///${CMAKE_CURRENT_BINARY_DIR}/QtSDK/IFW/CMake/repository"
+  CACHE STRING "Local repository for testing")
diff --git a/Packaging/QtSDK/qt.tools.cmake.xx.qs.in b/Packaging/QtSDK/qt.tools.cmake.xx.qs.in
new file mode 100644
index 0000000..e806dd7
--- /dev/null
+++ b/Packaging/QtSDK/qt.tools.cmake.xx.qs.in
@@ -0,0 +1,46 @@
+/****************************************************************************
+**
+** Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+** file Copyright.txt or https://cmake.org/licensing for details.
+**
+****************************************************************************/
+
+// constructor
+function Component()
+{
+    installer.valueChanged.connect( this, Component.prototype.reactOnTargetDirChange );
+    // set the default values to CMAKE%CMake_VERSION_MAJOR%%CMake_VERSION_MINOR%_BIN_DIR
+    Component.prototype.reactOnTargetDirChange("TargetDir", installer.value("TargetDir"));
+}
+
+Component.prototype.reactOnTargetDirChange = function(key, value)
+{
+    if (key == "TargetDir") {
+        var path = value + "/%CMAKE_BIN_DIR%";
+        installer.setValue("CMAKE%CMake_VERSION_MAJOR%%CMake_VERSION_MINOR%_BIN_DIR", path.replace(/\\/g, "/"));
+    }
+}
+
+Component.prototype.createOperations = function()
+{
+    component.createOperations();
+
+    try {
+        if (installer.value("SDKToolBinary") == "")
+            return;
+
+        var cmId = component.name;
+        installer.setValue("CMAKE%CMake_VERSION_MAJOR%%CMake_VERSION_MINOR%_ID", cmId);
+
+        component.addOperation("Execute",
+                               ["{0,2}", "@SDKToolBinary@", "addCMake",
+                                "--id", cmId,
+                                "--name", "%CMake_IFW_ROOT_COMPONENT_DISPLAY_NAME%",
+                                "--path", "@CMAKE%CMake_VERSION_MAJOR%%CMake_VERSION_MINOR%_BIN_DIR@/cmake%CMAKE_EXECUTABLE_SUFFIX%",
+                                "UNDOEXECUTE",
+                                "@SDKToolBinary@", "rmCMake", "--id", cmId]);
+
+    } catch( e ) {
+        print( e );
+    }
+}
diff --git a/Source/.gitattributes b/Source/.gitattributes
index 5002b2a..1cec8a3 100644
--- a/Source/.gitattributes
+++ b/Source/.gitattributes
@@ -1,7 +1,21 @@
-# Preserve upstream indentation style.
-cm_sha2.*        whitespace=indent-with-non-tab
+/cmCommandArgumentLexer.cxx        generated
+/cmCommandArgumentLexer.h          generated
+/cmCommandArgumentParser.cxx       generated
+/cmCommandArgumentParserTokens.h   generated
+/cmDependsJavaLexer.cxx            generated
+/cmDependsJavaLexer.h              generated
+/cmDependsJavaParser.cxx           generated
+/cmDependsJavaParserTokens.h       generated
+/cmExprLexer.cxx                   generated
+/cmExprLexer.h                     generated
+/cmExprParser.cxx                  generated
+/cmExprParserTokens.h              generated
+/cmFortranLexer.cxx                generated
+/cmFortranLexer.h                  generated
+/cmFortranParser.cxx               generated
+/cmFortranParserTokens.h           generated
+/cmListFileLexer.c                 generated
 
-# Preserve indentation style in generated code.
-cmListFileLexer.c       whitespace=-tab-in-indent,-indent-with-non-tab
-cmFortranLexer.cxx      whitespace=-tab-in-indent,-indent-with-non-tab
-cmFortranLexer.h        whitespace=-tab-in-indent,-indent-with-non-tab
+# Do not format third-party sources.
+/bindexplib.*                              -format.clang-format
+/kwsys/**                                  -format.clang-format
diff --git a/Source/CMakeInstallDestinations.cmake b/Source/CMakeInstallDestinations.cmake
index 023f6c0..28f4e87 100644
--- a/Source/CMakeInstallDestinations.cmake
+++ b/Source/CMakeInstallDestinations.cmake
@@ -25,6 +25,12 @@ set(CMAKE_DOC_DIR_DESC "docs")
 set(CMAKE_MAN_DIR_DESC "man pages")
 set(CMAKE_XDGDATA_DIR_DESC "XDG specific files")
 
+set(CMake_INSTALL_INFIX "" CACHE STRING "")
+set_property(CACHE CMake_INSTALL_INFIX PROPERTY HELPSTRING
+  "Intermediate installation path (empty by default)"
+  )
+mark_as_advanced(CMake_INSTALL_INFIX)
+
 foreach(v
     CMAKE_BIN_DIR
     CMAKE_DATA_DIR
@@ -41,7 +47,7 @@ foreach(v
 
   # Use the default when the user did not set this variable.
   if(NOT ${v})
-    set(${v} "${${v}_DEFAULT}")
+    set(${v} "${CMake_INSTALL_INFIX}${${v}_DEFAULT}")
   endif()
   # Remove leading slash to treat as relative to install prefix.
   string(REGEX REPLACE "^/" "" ${v} "${${v}}")
diff --git a/Source/CMakeLists.txt b/Source/CMakeLists.txt
index ec49481..2835ee6 100644
--- a/Source/CMakeLists.txt
+++ b/Source/CMakeLists.txt
@@ -159,14 +159,10 @@ endif()
 set(SRCS
   cmArchiveWrite.cxx
   cmBase32.cxx
-  cmBootstrapCommands1.cxx
-  cmBootstrapCommands2.cxx
   cmCacheManager.cxx
   cmCacheManager.h
-  "${CMAKE_CURRENT_BINARY_DIR}/cmCommands.cxx"
   cmCLocaleEnvironmentScope.h
   cmCLocaleEnvironmentScope.cxx
-  cmCommands.h
   cmCommandArgumentLexer.cxx
   cmCommandArgumentParser.cxx
   cmCommandArgumentParserHelper.cxx
@@ -247,8 +243,8 @@ set(SRCS
   cmFileLockPool.h
   cmFileLockResult.cxx
   cmFileLockResult.h
-  cmFilePathUuid.cxx
-  cmFilePathUuid.h
+  cmFilePathChecksum.cxx
+  cmFilePathChecksum.h
   cmFileTimeComparison.cxx
   cmFileTimeComparison.h
   cmFortranLexer.cxx
@@ -300,6 +296,10 @@ set(SRCS
   cmInstallDirectoryGenerator.cxx
   cmLinkedTree.h
   cmLinkItem.h
+  cmLinkLineComputer.cxx
+  cmLinkLineComputer.h
+  cmLinkLineDeviceComputer.cxx
+  cmLinkLineDeviceComputer.h
   cmListFileCache.cxx
   cmListFileCache.h
   cmListFileLexer.c
@@ -307,6 +307,8 @@ set(SRCS
   cmLocalCommonGenerator.h
   cmLocalGenerator.cxx
   cmLocalGenerator.h
+  cmRulePlaceholderExpander.cxx
+  cmRulePlaceholderExpander.h
   cmLocalUnixMakefileGenerator3.cxx
   cmLocale.h
   ${MACH_SRCS}
@@ -318,6 +320,8 @@ set(SRCS
   cmMakefileUtilityTargetGenerator.cxx
   cmMessenger.cxx
   cmMessenger.h
+  cmMSVC60LinkLineComputer.cxx
+  cmMSVC60LinkLineComputer.h
   cmOSXBundleGenerator.cxx
   cmOSXBundleGenerator.h
   cmOutputConverter.cxx
@@ -328,6 +332,8 @@ set(SRCS
   cmOrderDirectories.h
   cmPolicies.h
   cmPolicies.cxx
+  cmProcessOutput.cxx
+  cmProcessOutput.h
   cmProcessTools.cxx
   cmProcessTools.h
   cmProperty.cxx
@@ -354,10 +360,17 @@ set(SRCS
   cmSourceGroup.h
   cmState.cxx
   cmState.h
+  cmStateDirectory.cxx
+  cmStateDirectory.h
+  cmStateSnapshot.cxx
+  cmStateSnapshot.h
+  cmStateTypes.h
   cmSystemTools.cxx
   cmSystemTools.h
   cmTarget.cxx
   cmTarget.h
+  cmTargetPropertyComputer.cxx
+  cmTargetPropertyComputer.h
   cmTargetExport.h
   cmTest.cxx
   cmTest.h
@@ -377,60 +390,242 @@ set(SRCS
   cmake.cxx
   cmake.h
 
+  cmCommand.cxx
+  cmCommand.h
+  cmCommands.cxx
+  cmCommands.h
+  cmAddCompileOptionsCommand.cxx
+  cmAddCompileOptionsCommand.h
+  cmAddCustomCommandCommand.cxx
+  cmAddCustomCommandCommand.h
+  cmAddCustomTargetCommand.cxx
+  cmAddCustomTargetCommand.h
+  cmAddDefinitionsCommand.cxx
+  cmAddDefinitionsCommand.h
+  cmAddDependenciesCommand.cxx
+  cmAddDependenciesCommand.h
+  cmAddExecutableCommand.cxx
+  cmAddExecutableCommand.h
+  cmAddLibraryCommand.cxx
+  cmAddLibraryCommand.h
+  cmAddSubDirectoryCommand.cxx
+  cmAddSubDirectoryCommand.h
+  cmAddTestCommand.cxx
+  cmAddTestCommand.h
+  cmAuxSourceDirectoryCommand.cxx
+  cmAuxSourceDirectoryCommand.h
+  cmBreakCommand.cxx
+  cmBreakCommand.h
+  cmBuildCommand.cxx
+  cmBuildCommand.h
+  cmBuildNameCommand.cxx
+  cmBuildNameCommand.h
+  cmCMakeHostSystemInformationCommand.cxx
+  cmCMakeHostSystemInformationCommand.h
+  cmCMakeMinimumRequired.cxx
+  cmCMakeMinimumRequired.h
+  cmCMakePolicyCommand.cxx
+  cmCMakePolicyCommand.h
+  cmCommandArgumentsHelper.cxx
+  cmCommandArgumentsHelper.h
+  cmConditionEvaluator.cxx
+  cmConditionEvaluator.h
+  cmConfigureFileCommand.cxx
+  cmConfigureFileCommand.h
+  cmContinueCommand.cxx
+  cmContinueCommand.h
+  cmCoreTryCompile.cxx
+  cmCoreTryCompile.h
+  cmCreateTestSourceList.cxx
+  cmCreateTestSourceList.h
+  cmDefinePropertyCommand.cxx
+  cmDefinePropertyCommand.h
+  cmEnableLanguageCommand.cxx
+  cmEnableLanguageCommand.h
+  cmEnableTestingCommand.cxx
+  cmEnableTestingCommand.h
+  cmExecProgramCommand.cxx
+  cmExecProgramCommand.h
+  cmExecuteProcessCommand.cxx
+  cmExecuteProcessCommand.h
+  cmExpandedCommandArgument.cxx
+  cmExpandedCommandArgument.h
+  cmExportCommand.cxx
+  cmExportCommand.h
+  cmExportLibraryDependenciesCommand.cxx
+  cmExportLibraryDependenciesCommand.h
+  cmFLTKWrapUICommand.cxx
+  cmFLTKWrapUICommand.h
+  cmFileCommand.cxx
+  cmFileCommand.h
+  cmFindBase.cxx
+  cmFindBase.h
+  cmFindCommon.cxx
+  cmFindCommon.h
+  cmFindFileCommand.cxx
+  cmFindFileCommand.h
+  cmFindLibraryCommand.cxx
+  cmFindLibraryCommand.h
+  cmFindPackageCommand.cxx
+  cmFindPackageCommand.h
+  cmFindPathCommand.cxx
+  cmFindPathCommand.h
+  cmFindProgramCommand.cxx
+  cmFindProgramCommand.h
+  cmForEachCommand.cxx
+  cmForEachCommand.h
+  cmFunctionCommand.cxx
+  cmFunctionCommand.h
+  cmGetCMakePropertyCommand.cxx
+  cmGetCMakePropertyCommand.h
+  cmGetDirectoryPropertyCommand.cxx
+  cmGetDirectoryPropertyCommand.h
+  cmGetFilenameComponentCommand.cxx
+  cmGetFilenameComponentCommand.h
+  cmGetPropertyCommand.cxx
+  cmGetPropertyCommand.h
+  cmGetSourceFilePropertyCommand.cxx
+  cmGetSourceFilePropertyCommand.h
+  cmGetTargetPropertyCommand.cxx
+  cmGetTargetPropertyCommand.h
+  cmGetTestPropertyCommand.cxx
+  cmGetTestPropertyCommand.h
+  cmHexFileConverter.cxx
+  cmHexFileConverter.h
+  cmIfCommand.cxx
+  cmIfCommand.h
+  cmIncludeCommand.cxx
+  cmIncludeCommand.h
+  cmIncludeDirectoryCommand.cxx
+  cmIncludeDirectoryCommand.h
+  cmIncludeExternalMSProjectCommand.cxx
+  cmIncludeExternalMSProjectCommand.h
+  cmIncludeRegularExpressionCommand.cxx
+  cmIncludeRegularExpressionCommand.h
+  cmInstallCommand.cxx
+  cmInstallCommand.h
+  cmInstallCommandArguments.cxx
+  cmInstallCommandArguments.h
+  cmInstallFilesCommand.cxx
+  cmInstallFilesCommand.h
+  cmInstallProgramsCommand.cxx
+  cmInstallProgramsCommand.h
+  cmInstallTargetsCommand.cxx
+  cmInstallTargetsCommand.h
+  cmLinkDirectoriesCommand.cxx
+  cmLinkDirectoriesCommand.h
+  cmLinkLibrariesCommand.cxx
+  cmLinkLibrariesCommand.h
+  cmListCommand.cxx
+  cmListCommand.h
+  cmLoadCacheCommand.cxx
+  cmLoadCacheCommand.h
+  cmLoadCommandCommand.cxx
+  cmLoadCommandCommand.h
+  cmMacroCommand.cxx
+  cmMacroCommand.h
+  cmMakeDirectoryCommand.cxx
+  cmMakeDirectoryCommand.h
+  cmMarkAsAdvancedCommand.cxx
+  cmMarkAsAdvancedCommand.h
+  cmMathCommand.cxx
+  cmMathCommand.h
+  cmMessageCommand.cxx
+  cmMessageCommand.h
+  cmOptionCommand.cxx
+  cmOptionCommand.h
+  cmOutputRequiredFilesCommand.cxx
+  cmOutputRequiredFilesCommand.h
+  cmParseArgumentsCommand.cxx
+  cmParseArgumentsCommand.h
+  cmPathLabel.cxx
+  cmPathLabel.h
+  cmProjectCommand.cxx
+  cmProjectCommand.h
+  cmQTWrapCPPCommand.cxx
+  cmQTWrapCPPCommand.h
+  cmQTWrapUICommand.cxx
+  cmQTWrapUICommand.h
+  cmRemoveCommand.cxx
+  cmRemoveCommand.h
+  cmRemoveDefinitionsCommand.cxx
+  cmRemoveDefinitionsCommand.h
+  cmReturnCommand.cxx
+  cmReturnCommand.h
+  cmSearchPath.cxx
+  cmSearchPath.h
+  cmSeparateArgumentsCommand.cxx
+  cmSeparateArgumentsCommand.h
+  cmSetCommand.cxx
+  cmSetCommand.h
+  cmSetDirectoryPropertiesCommand.cxx
+  cmSetDirectoryPropertiesCommand.h
+  cmSetPropertyCommand.cxx
+  cmSetPropertyCommand.h
+  cmSetSourceFilesPropertiesCommand.cxx
+  cmSetSourceFilesPropertiesCommand.h
+  cmSetTargetPropertiesCommand.cxx
+  cmSetTargetPropertiesCommand.h
+  cmSetTestsPropertiesCommand.cxx
+  cmSetTestsPropertiesCommand.h
+  cmSiteNameCommand.cxx
+  cmSiteNameCommand.h
+  cmSourceGroupCommand.cxx
+  cmSourceGroupCommand.h
+  cmStringCommand.cxx
+  cmStringCommand.h
+  cmSubdirCommand.cxx
+  cmSubdirCommand.h
+  cmSubdirDependsCommand.cxx
+  cmSubdirDependsCommand.h
+  cmTargetCompileDefinitionsCommand.cxx
+  cmTargetCompileDefinitionsCommand.h
+  cmTargetCompileFeaturesCommand.cxx
+  cmTargetCompileFeaturesCommand.h
+  cmTargetCompileOptionsCommand.cxx
+  cmTargetCompileOptionsCommand.h
+  cmTargetIncludeDirectoriesCommand.cxx
+  cmTargetIncludeDirectoriesCommand.h
+  cmTargetLinkLibrariesCommand.cxx
+  cmTargetLinkLibrariesCommand.h
+  cmTargetPropCommandBase.cxx
+  cmTargetPropCommandBase.h
+  cmTargetSourcesCommand.cxx
+  cmTargetSourcesCommand.h
+  cmTimestamp.cxx
+  cmTimestamp.h
+  cmTryCompileCommand.cxx
+  cmTryCompileCommand.h
+  cmTryRunCommand.cxx
+  cmTryRunCommand.h
+  cmUnexpectedCommand.cxx
+  cmUnexpectedCommand.h
+  cmUnsetCommand.cxx
+  cmUnsetCommand.h
+  cmUseMangledMesaCommand.cxx
+  cmUseMangledMesaCommand.h
+  cmUtilitySourceCommand.cxx
+  cmUtilitySourceCommand.h
+  cmVariableRequiresCommand.cxx
+  cmVariableRequiresCommand.h
+  cmVariableWatchCommand.cxx
+  cmVariableWatchCommand.h
+  cmWhileCommand.cxx
+  cmWhileCommand.h
+  cmWriteFileCommand.cxx
+  cmWriteFileCommand.h
+
   cm_auto_ptr.hxx
   cm_get_date.h
   cm_get_date.c
-  cm_sha2.h
-  cm_sha2.c
   cm_utf8.h
   cm_utf8.c
+  cm_codecvt.hxx
+  cm_codecvt.cxx
   )
 
-set(COMMAND_INCLUDES "#include \"cmTargetPropCommandBase.cxx\"\n")
-list(APPEND SRCS cmTargetPropCommandBase.cxx)
-set_property(SOURCE cmTargetPropCommandBase.cxx PROPERTY HEADER_FILE_ONLY ON)
-set(NEW_COMMANDS "")
-foreach(command_file
-    cmAddCompileOptionsCommand
-    cmAuxSourceDirectoryCommand
-    cmBuildNameCommand
-    cmCMakeHostSystemInformationCommand
-    cmElseIfCommand
-    cmExportCommand
-    cmExportLibraryDependenciesCommand
-    cmFLTKWrapUICommand
-    cmIncludeExternalMSProjectCommand
-    cmInstallProgramsCommand
-    cmLinkLibrariesCommand
-    cmLoadCacheCommand
-    cmOutputRequiredFilesCommand
-    cmQTWrapCPPCommand
-    cmQTWrapUICommand
-    cmRemoveCommand
-    cmRemoveDefinitionsCommand
-    cmSourceGroupCommand
-    cmSubdirDependsCommand
-    cmTargetCompileDefinitionsCommand
-    cmTargetCompileFeaturesCommand
-    cmTargetCompileOptionsCommand
-    cmTargetIncludeDirectoriesCommand
-    cmTargetSourcesCommand
-    cmUseMangledMesaCommand
-    cmUtilitySourceCommand
-    cmVariableRequiresCommand
-    cmVariableWatchCommand
-    cmWriteFileCommand
-    # This one must be last because it includes windows.h and
-    # windows.h #defines GetCurrentDirectory which is a member
-    # of cmMakefile
-    cmLoadCommandCommand
-    )
-  set(COMMAND_INCLUDES "${COMMAND_INCLUDES}#include \"${command_file}.cxx\"\n")
-  set(NEW_COMMANDS "${NEW_COMMANDS}commands.push_back(new ${command_file});\n")
-  list(APPEND SRCS ${command_file}.cxx)
-  set_property(SOURCE ${command_file}.cxx PROPERTY HEADER_FILE_ONLY ON)
-endforeach()
-configure_file(cmCommands.cxx.in ${CMAKE_CURRENT_BINARY_DIR}/cmCommands.cxx @ONLY)
+SET_PROPERTY(SOURCE cmProcessOutput.cxx APPEND PROPERTY COMPILE_DEFINITIONS
+  KWSYS_ENCODING_DEFAULT_CODEPAGE=${KWSYS_ENCODING_DEFAULT_CODEPAGE})
 
 # Kdevelop only works on UNIX and not windows
 if(UNIX)
@@ -478,6 +673,8 @@ if (WIN32)
       cmVisualStudioGeneratorOptions.cxx
       cmVisualStudio10TargetGenerator.h
       cmVisualStudio10TargetGenerator.cxx
+      cmVisualStudio10ToolsetOptions.h
+      cmVisualStudio10ToolsetOptions.cxx
       cmLocalVisualStudio10Generator.cxx
       cmLocalVisualStudio10Generator.h
       cmGlobalVisualStudio10Generator.h
@@ -513,6 +710,8 @@ if (WIN32)
       cmGhsMultiTargetGenerator.h
       cmGhsMultiGpj.cxx
       cmGhsMultiGpj.h
+      cmVSSetupHelper.cxx
+      cmVSSetupHelper.h
       )
 
     # Add a manifest file to executables on Windows to allow for
@@ -543,6 +742,8 @@ set(SRCS ${SRCS}
   cmNinjaNormalTargetGenerator.h
   cmNinjaUtilityTargetGenerator.cxx
   cmNinjaUtilityTargetGenerator.h
+  cmNinjaLinkLineComputer.cxx
+  cmNinjaLinkLineComputer.h
   )
 
 # Temporary variable for tools targets
@@ -582,9 +783,19 @@ target_link_libraries(CMakeLib cmsys
   ${CMAKE_CURL_LIBRARIES}
   ${CMAKE_JSONCPP_LIBRARIES}
   ${CMAKE_LIBUV_LIBRARIES}
+  ${CMAKE_LIBRHASH_LIBRARIES}
   ${CMake_KWIML_LIBRARIES}
   )
 
+if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_SYSTEM_PROCESSOR MATCHES "sparc")
+  # the atomic instructions are implemented using libatomic on some platforms,
+  # so linking to that may be required
+  check_library_exists(atomic __atomic_fetch_add_4 "" LIBATOMIC_NEEDED)
+  if(LIBATOMIC_NEEDED)
+    target_link_libraries(CMakeLib atomic)
+  endif()
+endif()
+
 # On Apple we need CoreFoundation
 if(APPLE)
   target_link_libraries(CMakeLib "-framework CoreFoundation")
diff --git a/Source/CMakeVersion.cmake b/Source/CMakeVersion.cmake
index 0c49ee5..65e7b5d 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 7)
-set(CMake_VERSION_PATCH 2)
+set(CMake_VERSION_MINOR 8)
+set(CMake_VERSION_PATCH 0)
 #set(CMake_VERSION_RC 0)
diff --git a/Source/CPack/IFW/cmCPackIFWGenerator.h b/Source/CPack/IFW/cmCPackIFWGenerator.h
index 88a3741..d656063 100644
--- a/Source/CPack/IFW/cmCPackIFWGenerator.h
+++ b/Source/CPack/IFW/cmCPackIFWGenerator.h
@@ -10,7 +10,6 @@
 #include "cmCPackIFWInstaller.h"
 #include "cmCPackIFWPackage.h"
 #include "cmCPackIFWRepository.h"
-#include "cmTypeMacro.h"
 
 #include <map>
 #include <set>
diff --git a/Source/CPack/IFW/cmCPackIFWInstaller.cxx b/Source/CPack/IFW/cmCPackIFWInstaller.cxx
index d9ac909..d8bafee 100644
--- a/Source/CPack/IFW/cmCPackIFWInstaller.cxx
+++ b/Source/CPack/IFW/cmCPackIFWInstaller.cxx
@@ -2,6 +2,11 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackIFWInstaller.h"
 
+#include <cmConfigure.h>
+#include <sstream>
+#include <stddef.h>
+#include <utility>
+
 #include "CPack/cmCPackGenerator.h"
 #include "CPack/cmCPackLog.h"
 #include "cmCPackIFWGenerator.h"
@@ -12,9 +17,6 @@
 #include "cmXMLParser.h"
 #include "cmXMLWriter.h"
 
-#include <cmConfigure.h>
-#include <utility>
-
 #ifdef cmCPackLogger
 #undef cmCPackLogger
 #endif
@@ -26,7 +28,7 @@
       Generator->Logger->Log(logType, __FILE__, __LINE__,                     \
                              cmCPackLog_msg.str().c_str());                   \
     }                                                                         \
-  } while (0)
+  } while (false)
 
 cmCPackIFWInstaller::cmCPackIFWInstaller()
   : Generator(CM_NULLPTR)
@@ -58,6 +60,16 @@ bool cmCPackIFWInstaller::IsVersionEqual(const char* version)
   return Generator ? Generator->IsVersionEqual(version) : false;
 }
 
+void cmCPackIFWInstaller::printSkippedOptionWarning(
+  const std::string& optionName, const std::string& optionValue)
+{
+  cmCPackLogger(
+    cmCPackLog::LOG_WARNING, "Option "
+      << optionName << " is set to \"" << optionValue
+      << "\" but will be skipped because the specified file does not exist."
+      << std::endl);
+}
+
 void cmCPackIFWInstaller::ConfigureFromOptions()
 {
   // Name;
@@ -108,7 +120,7 @@ void cmCPackIFWInstaller::ConfigureFromOptions()
     if (cmSystemTools::FileExists(option)) {
       InstallerApplicationIcon = option;
     } else {
-      // TODO: implement warning
+      printSkippedOptionWarning("CPACK_IFW_PACKAGE_ICON", option);
     }
   }
 
@@ -117,7 +129,7 @@ void cmCPackIFWInstaller::ConfigureFromOptions()
     if (cmSystemTools::FileExists(option)) {
       InstallerWindowIcon = option;
     } else {
-      // TODO: implement warning
+      printSkippedOptionWarning("CPACK_IFW_PACKAGE_WINDOW_ICON", option);
     }
   }
 
@@ -126,8 +138,67 @@ void cmCPackIFWInstaller::ConfigureFromOptions()
     if (cmSystemTools::FileExists(option)) {
       Logo = option;
     } else {
-      // TODO: implement warning
+      printSkippedOptionWarning("CPACK_IFW_PACKAGE_LOGO", option);
+    }
+  }
+
+  // Watermark
+  if (const char* option = GetOption("CPACK_IFW_PACKAGE_WATERMARK")) {
+    if (cmSystemTools::FileExists(option)) {
+      Watermark = option;
+    } else {
+      printSkippedOptionWarning("CPACK_IFW_PACKAGE_WATERMARK", option);
+    }
+  }
+
+  // Banner
+  if (const char* option = GetOption("CPACK_IFW_PACKAGE_BANNER")) {
+    if (cmSystemTools::FileExists(option)) {
+      Banner = option;
+    } else {
+      printSkippedOptionWarning("CPACK_IFW_PACKAGE_BANNER", option);
+    }
+  }
+
+  // Background
+  if (const char* option = GetOption("CPACK_IFW_PACKAGE_BACKGROUND")) {
+    if (cmSystemTools::FileExists(option)) {
+      Background = option;
+    } else {
+      printSkippedOptionWarning("CPACK_IFW_PACKAGE_BACKGROUND", option);
+    }
+  }
+
+  // WizardStyle
+  if (const char* option = GetOption("CPACK_IFW_PACKAGE_WIZARD_STYLE")) {
+    if (WizardStyle.compare("Modern") == 0 &&
+        WizardStyle.compare("Aero") == 0 && WizardStyle.compare("Mac") == 0 &&
+        WizardStyle.compare("Classic") == 0) {
+      cmCPackLogger(
+        cmCPackLog::LOG_WARNING,
+        "Option CPACK_IFW_PACKAGE_WIZARD_STYLE has unknown value \""
+          << option << "\". Expected values are: Modern, Aero, Mac, Classic."
+          << std::endl);
     }
+
+    WizardStyle = option;
+  }
+
+  // WizardDefaultWidth
+  if (const char* option =
+        GetOption("CPACK_IFW_PACKAGE_WIZARD_DEFAULT_WIDTH")) {
+    WizardDefaultWidth = option;
+  }
+
+  // WizardDefaultHeight
+  if (const char* option =
+        GetOption("CPACK_IFW_PACKAGE_WIZARD_DEFAULT_HEIGHT")) {
+    WizardDefaultHeight = option;
+  }
+
+  // TitleColor
+  if (const char* option = GetOption("CPACK_IFW_PACKAGE_TITLE_COLOR")) {
+    TitleColor = option;
   }
 
   // Start menu
@@ -231,7 +302,7 @@ public:
 protected:
   void StartElement(const std::string& name, const char** /*atts*/) CM_OVERRIDE
   {
-    file = name == "file" ? true : false;
+    file = name == "file";
     if (file) {
       hasFiles = true;
     }
@@ -311,6 +382,50 @@ void cmCPackIFWInstaller::GenerateInstallerFile()
     xout.Element("Logo", name);
   }
 
+  // Banner
+  if (!Banner.empty()) {
+    std::string name = cmSystemTools::GetFilenameName(Banner);
+    std::string path = Directory + "/config/" + name;
+    cmsys::SystemTools::CopyFileIfDifferent(Banner.data(), path.data());
+    xout.Element("Banner", name);
+  }
+
+  // Watermark
+  if (!Watermark.empty()) {
+    std::string name = cmSystemTools::GetFilenameName(Watermark);
+    std::string path = Directory + "/config/" + name;
+    cmsys::SystemTools::CopyFileIfDifferent(Watermark.data(), path.data());
+    xout.Element("Watermark", name);
+  }
+
+  // Background
+  if (!Background.empty()) {
+    std::string name = cmSystemTools::GetFilenameName(Background);
+    std::string path = Directory + "/config/" + name;
+    cmsys::SystemTools::CopyFileIfDifferent(Background.data(), path.data());
+    xout.Element("Background", name);
+  }
+
+  // WizardStyle
+  if (!WizardStyle.empty()) {
+    xout.Element("WizardStyle", WizardStyle);
+  }
+
+  // WizardDefaultWidth
+  if (!WizardDefaultWidth.empty()) {
+    xout.Element("WizardDefaultWidth", WizardDefaultWidth);
+  }
+
+  // WizardDefaultHeight
+  if (!WizardDefaultHeight.empty()) {
+    xout.Element("WizardDefaultHeight", WizardDefaultHeight);
+  }
+
+  // TitleColor
+  if (!TitleColor.empty()) {
+    xout.Element("TitleColor", TitleColor);
+  }
+
   // Start menu
   if (!IsVersionLess("2.0")) {
     xout.Element("StartMenuDir", StartMenuDir);
@@ -403,7 +518,11 @@ void cmCPackIFWInstaller::GeneratePackageFiles()
     // Check package group
     if (const char* option = GetOption("CPACK_IFW_PACKAGE_GROUP")) {
       package.ConfigureFromGroup(option);
-      package.ForcedInstallation = "true";
+      std::string forcedOption = "CPACK_IFW_COMPONENT_GROUP_" +
+        cmsys::SystemTools::UpperCase(option) + "_FORCED_INSTALLATION";
+      if (!GetOption(forcedOption)) {
+        package.ForcedInstallation = "true";
+      }
     } else {
       package.ConfigureFromOptions();
     }
diff --git a/Source/CPack/IFW/cmCPackIFWInstaller.h b/Source/CPack/IFW/cmCPackIFWInstaller.h
index eba9bec..4ec3e70 100644
--- a/Source/CPack/IFW/cmCPackIFWInstaller.h
+++ b/Source/CPack/IFW/cmCPackIFWInstaller.h
@@ -60,6 +60,27 @@ public:
   /// Filename for a logo
   std::string Logo;
 
+  /// Filename for a watermark
+  std::string Watermark;
+
+  /// Filename for a banner
+  std::string Banner;
+
+  /// Filename for a background
+  std::string Background;
+
+  /// Wizard style name
+  std::string WizardStyle;
+
+  /// Wizard width
+  std::string WizardDefaultWidth;
+
+  /// Wizard height
+  std::string WizardDefaultHeight;
+
+  /// Title color
+  std::string TitleColor;
+
   /// Name of the default program group in the Windows Start menu
   std::string StartMenuDir;
 
@@ -110,6 +131,10 @@ public:
 
 protected:
   void WriteGeneratedByToStrim(cmXMLWriter& xout);
+
+private:
+  void printSkippedOptionWarning(const std::string& optionName,
+                                 const std::string& optionValue);
 };
 
 #endif // cmCPackIFWInstaller_h
diff --git a/Source/CPack/IFW/cmCPackIFWPackage.cxx b/Source/CPack/IFW/cmCPackIFWPackage.cxx
index 4d46120..e23b1b9 100644
--- a/Source/CPack/IFW/cmCPackIFWPackage.cxx
+++ b/Source/CPack/IFW/cmCPackIFWPackage.cxx
@@ -29,7 +29,7 @@
       Generator->Logger->Log(logType, __FILE__, __LINE__,                     \
                              cmCPackLog_msg.str().c_str());                   \
     }                                                                         \
-  } while (0)
+  } while (false)
 
 //---------------------------------------------------------- CompareStruct ---
 cmCPackIFWPackage::CompareStruct::CompareStruct()
@@ -62,6 +62,13 @@ cmCPackIFWPackage::DependenceStruct::DependenceStruct(
   } else if ((pos = dependence.find('>')) != std::string::npos) {
     Compare.Type = CompareGreater;
     Compare.Value = dependence.substr(pos + 1);
+  } else if ((pos = dependence.find('-')) != std::string::npos) {
+    Compare.Type = CompareNone;
+    Compare.Value = dependence.substr(pos + 1);
+  }
+  size_t dashPos = dependence.find('-');
+  if (dashPos != std::string::npos) {
+    pos = dashPos;
   }
   Name = pos == std::string::npos ? dependence : dependence.substr(0, pos);
 }
@@ -74,6 +81,10 @@ std::string cmCPackIFWPackage::DependenceStruct::NameWithCompare() const
 
   std::string result = Name;
 
+  if (Compare.Type != CompareNone || !Compare.Value.empty()) {
+    result += "-";
+  }
+
   if (Compare.Type == CompareLessOrEqual) {
     result += "<=";
   } else if (Compare.Type == CompareGreaterOrEqual) {
@@ -109,6 +120,16 @@ bool cmCPackIFWPackage::IsOn(const std::string& op) const
   return Generator ? Generator->IsOn(op) : false;
 }
 
+bool cmCPackIFWPackage::IsSetToOff(const std::string& op) const
+{
+  return Generator ? Generator->IsSetToOff(op) : false;
+}
+
+bool cmCPackIFWPackage::IsSetToEmpty(const std::string& op) const
+{
+  return Generator ? Generator->IsSetToEmpty(op) : false;
+}
+
 bool cmCPackIFWPackage::IsVersionLess(const char* version)
 {
   return Generator ? Generator->IsVersionLess(version) : false;
@@ -144,11 +165,14 @@ void cmCPackIFWPackage::DefaultConfiguration()
   Script = "";
   Licenses.clear();
   UserInterfaces.clear();
+  Translations.clear();
   SortingPriority = "";
+  UpdateText = "";
   Default = "";
   Essential = "";
   Virtual = "";
   ForcedInstallation = "";
+  RequiresAdminRights = "";
 }
 
 // Defaul configuration (all in one package)
@@ -235,24 +259,6 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component)
     }
   }
 
-  // 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();
@@ -270,6 +276,11 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component)
   // Priority
   if (const char* option = this->GetOption(prefix + "PRIORITY")) {
     SortingPriority = option;
+    cmCPackLogger(
+      cmCPackLog::LOG_WARNING, "The \"PRIORITY\" option is set "
+        << "for component \"" << component->Name << "\", but there option is "
+        << "deprecated. Please use \"SORTING_PRIORITY\" option instead."
+        << std::endl);
   }
 
   // Default
@@ -286,7 +297,7 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component)
   // ForcedInstallation
   ForcedInstallation = component->IsRequired ? "true" : "false";
 
-  return 1;
+  return ConfigureFromPrefix(prefix);
 }
 
 int cmCPackIFWPackage::ConfigureFromGroup(cmCPackComponentGroup* group)
@@ -342,9 +353,15 @@ int cmCPackIFWPackage::ConfigureFromGroup(cmCPackComponentGroup* group)
   // Priority
   if (const char* option = this->GetOption(prefix + "PRIORITY")) {
     SortingPriority = option;
+    cmCPackLogger(
+      cmCPackLog::LOG_WARNING, "The \"PRIORITY\" option is set "
+        << "for component group \"" << group->Name
+        << "\", but there option is "
+        << "deprecated. Please use \"SORTING_PRIORITY\" option instead."
+        << std::endl);
   }
 
-  return 1;
+  return ConfigureFromPrefix(prefix);
 }
 
 int cmCPackIFWPackage::ConfigureFromGroup(const std::string& groupName)
@@ -380,6 +397,157 @@ int cmCPackIFWPackage::ConfigureFromGroup(const std::string& groupName)
   return ConfigureFromGroup(&group);
 }
 
+// Common options for components and groups
+int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix)
+{
+  // Temporary variable for full option name
+  std::string option;
+
+  // Display name
+  option = prefix + "DISPLAY_NAME";
+  if (IsSetToEmpty(option)) {
+    DisplayName.clear();
+  } else if (const char* value = GetOption(option)) {
+    DisplayName = value;
+  }
+
+  // Description
+  option = prefix + "DESCRIPTION";
+  if (IsSetToEmpty(option)) {
+    Description.clear();
+  } else if (const char* value = GetOption(option)) {
+    Description = value;
+  }
+
+  // Release date
+  option = prefix + "RELEASE_DATE";
+  if (IsSetToEmpty(option)) {
+    ReleaseDate.clear();
+  } else if (const char* value = GetOption(option)) {
+    ReleaseDate = value;
+  }
+
+  // Sorting priority
+  option = prefix + "SORTING_PRIORITY";
+  if (IsSetToEmpty(option)) {
+    SortingPriority.clear();
+  } else if (const char* value = GetOption(option)) {
+    SortingPriority = value;
+  }
+
+  // Update text
+  option = prefix + "UPDATE_TEXT";
+  if (IsSetToEmpty(option)) {
+    UpdateText.clear();
+  } else if (const char* value = GetOption(option)) {
+    UpdateText = value;
+  }
+
+  // Translations
+  option = prefix + "TRANSLATIONS";
+  if (IsSetToEmpty(option)) {
+    Translations.clear();
+  } else if (const char* value = this->GetOption(option)) {
+    Translations.clear();
+    cmSystemTools::ExpandListArgument(value, Translations);
+  }
+
+  // QtIFW dependencies
+  std::vector<std::string> deps;
+  option = prefix + "DEPENDS";
+  if (const char* value = this->GetOption(option)) {
+    cmSystemTools::ExpandListArgument(value, deps);
+  }
+  option = prefix + "DEPENDENCIES";
+  if (const char* value = this->GetOption(option)) {
+    cmSystemTools::ExpandListArgument(value, deps);
+  }
+  for (std::vector<std::string>::iterator dit = deps.begin();
+       dit != deps.end(); ++dit) {
+    DependenceStruct dep(*dit);
+    if (Generator->Packages.count(dep.Name)) {
+      cmCPackIFWPackage& depPkg = Generator->Packages[dep.Name];
+      dep.Name = depPkg.Name;
+    }
+    bool hasDep = Generator->DependentPackages.count(dep.Name) > 0;
+    DependenceStruct& depRef = Generator->DependentPackages[dep.Name];
+    if (!hasDep) {
+      depRef = dep;
+    }
+    AlienDependencies.insert(&depRef);
+  }
+
+  // Automatic dependency on
+  option = prefix + "AUTO_DEPEND_ON";
+  if (IsSetToEmpty(option)) {
+    AlienAutoDependOn.clear();
+  } else if (const char* value = this->GetOption(option)) {
+    std::vector<std::string> depsOn;
+    cmSystemTools::ExpandListArgument(value, depsOn);
+    for (std::vector<std::string>::iterator dit = depsOn.begin();
+         dit != depsOn.end(); ++dit) {
+      DependenceStruct dep(*dit);
+      if (Generator->Packages.count(dep.Name)) {
+        cmCPackIFWPackage& depPkg = Generator->Packages[dep.Name];
+        dep.Name = depPkg.Name;
+      }
+      bool hasDep = Generator->DependentPackages.count(dep.Name) > 0;
+      DependenceStruct& depRef = Generator->DependentPackages[dep.Name];
+      if (!hasDep) {
+        depRef = dep;
+      }
+      AlienAutoDependOn.insert(&depRef);
+    }
+  }
+
+  // Visibility
+  option = prefix + "VIRTUAL";
+  if (IsSetToEmpty(option)) {
+    Virtual.clear();
+  } else if (IsOn(option)) {
+    Virtual = "true";
+  }
+
+  // Default selection
+  option = prefix + "DEFAULT";
+  if (IsSetToEmpty(option)) {
+    Default.clear();
+  } else if (const char* value = GetOption(option)) {
+    std::string lowerValue = cmsys::SystemTools::LowerCase(value);
+    if (lowerValue.compare("true") == 0) {
+      Default = "true";
+    } else if (lowerValue.compare("false") == 0) {
+      Default = "false";
+    } else if (lowerValue.compare("script") == 0) {
+      Default = "script";
+    } else {
+      Default = value;
+    }
+  }
+
+  // Forsed installation
+  option = prefix + "FORCED_INSTALLATION";
+  if (IsSetToEmpty(option)) {
+    ForcedInstallation.clear();
+  } else if (IsOn(option)) {
+    ForcedInstallation = "true";
+  } else if (IsSetToOff(option)) {
+    ForcedInstallation = "false";
+  }
+
+  // Requires admin rights
+  option = prefix + "REQUIRES_ADMIN_RIGHTS";
+  if (IsSetToEmpty(option)) {
+    RequiresAdminRights.clear();
+  } else if (IsOn(option)) {
+    RequiresAdminRights = "true";
+  } else if (IsSetToOff(option)) {
+    RequiresAdminRights = "false";
+  }
+
+  return 1;
+}
+
 void cmCPackIFWPackage::GeneratePackageFile()
 {
   // Lazy directory initialization
@@ -403,6 +571,12 @@ void cmCPackIFWPackage::GeneratePackageFile()
 
   xout.Element("DisplayName", DisplayName);
   xout.Element("Description", Description);
+
+  // Update text
+  if (!UpdateText.empty()) {
+    xout.Element("UpdateText", UpdateText);
+  }
+
   xout.Element("Name", Name);
   xout.Element("Version", Version);
 
@@ -437,6 +611,23 @@ void cmCPackIFWPackage::GeneratePackageFile()
     xout.EndElement();
   }
 
+  // Translations (copy to meta dir)
+  std::vector<std::string> translations = Translations;
+  for (size_t i = 0; i < translations.size(); i++) {
+    std::string name = cmSystemTools::GetFilenameName(translations[i]);
+    std::string path = Directory + "/meta/" + name;
+    cmsys::SystemTools::CopyFileIfDifferent(translations[i].data(),
+                                            path.data());
+    translations[i] = name;
+  }
+  if (!translations.empty()) {
+    xout.StartElement("Translations");
+    for (size_t i = 0; i < translations.size(); i++) {
+      xout.Element("Translation", translations[i]);
+    }
+    xout.EndElement();
+  }
+
   // Dependencies
   std::set<DependenceStruct> compDepSet;
   for (std::set<DependenceStruct*>::iterator ait = AlienDependencies.begin();
@@ -460,6 +651,25 @@ void cmCPackIFWPackage::GeneratePackageFile()
     xout.Element("Dependencies", dependencies.str());
   }
 
+  // Automatic dependency on
+  std::set<DependenceStruct> compAutoDepSet;
+  for (std::set<DependenceStruct*>::iterator ait = AlienAutoDependOn.begin();
+       ait != AlienAutoDependOn.end(); ++ait) {
+    compAutoDepSet.insert(*(*ait));
+  }
+  // Write automatic dependency on
+  if (!compAutoDepSet.empty()) {
+    std::ostringstream dependencies;
+    std::set<DependenceStruct>::iterator it = compAutoDepSet.begin();
+    dependencies << it->NameWithCompare();
+    ++it;
+    while (it != compAutoDepSet.end()) {
+      dependencies << "," << it->NameWithCompare();
+      ++it;
+    }
+    xout.Element("AutoDependOn", dependencies.str());
+  }
+
   // Licenses (copy to meta dir)
   std::vector<std::string> licenses = Licenses;
   for (size_t i = 1; i < licenses.size(); i += 2) {
@@ -483,6 +693,10 @@ void cmCPackIFWPackage::GeneratePackageFile()
     xout.Element("ForcedInstallation", ForcedInstallation);
   }
 
+  if (!RequiresAdminRights.empty()) {
+    xout.Element("RequiresAdminRights", RequiresAdminRights);
+  }
+
   if (!Virtual.empty()) {
     xout.Element("Virtual", Virtual);
   } else if (!Default.empty()) {
diff --git a/Source/CPack/IFW/cmCPackIFWPackage.h b/Source/CPack/IFW/cmCPackIFWPackage.h
index d1af2bd..bd1d6c5 100644
--- a/Source/CPack/IFW/cmCPackIFWPackage.h
+++ b/Source/CPack/IFW/cmCPackIFWPackage.h
@@ -92,9 +92,15 @@ public:
   /// List of pages to load
   std::vector<std::string> UserInterfaces;
 
+  /// List of translation files to load
+  std::vector<std::string> Translations;
+
   /// Priority of the component in the tree
   std::string SortingPriority;
 
+  /// Description added to the component description
+  std::string UpdateText;
+
   /// Set to true to preselect the component in the installer
   std::string Default;
 
@@ -107,11 +113,16 @@ public:
   /// Determines that the package must always be installed
   std::string ForcedInstallation;
 
+  /// Package needs to be installed with elevated permissions
+  std::string RequiresAdminRights;
+
 public:
   // Internal implementation
 
   const char* GetOption(const std::string& op) const;
   bool IsOn(const std::string& op) const;
+  bool IsSetToOff(const std::string& op) const;
+  bool IsSetToEmpty(const std::string& op) const;
 
   bool IsVersionLess(const char* version);
   bool IsVersionGreater(const char* version);
@@ -125,6 +136,7 @@ public:
   int ConfigureFromComponent(cmCPackComponent* component);
   int ConfigureFromGroup(cmCPackComponentGroup* group);
   int ConfigureFromGroup(const std::string& groupName);
+  int ConfigureFromPrefix(const std::string& prefix);
 
   void GeneratePackageFile();
 
@@ -136,6 +148,8 @@ public:
   std::set<cmCPackIFWPackage*> Dependencies;
   // Collection of unresolved dependencies
   std::set<DependenceStruct*> AlienDependencies;
+  // Collection of unresolved automatic dependency on
+  std::set<DependenceStruct*> AlienAutoDependOn;
   // Patch to package directory
   std::string Directory;
 
diff --git a/Source/CPack/IFW/cmCPackIFWRepository.cxx b/Source/CPack/IFW/cmCPackIFWRepository.cxx
index 8d50e30..cc204e8 100644
--- a/Source/CPack/IFW/cmCPackIFWRepository.cxx
+++ b/Source/CPack/IFW/cmCPackIFWRepository.cxx
@@ -23,7 +23,7 @@
       Generator->Logger->Log(logType, __FILE__, __LINE__,                     \
                              cmCPackLog_msg.str().c_str());                   \
     }                                                                         \
-  } while (0)
+  } while (false)
 
 cmCPackIFWRepository::cmCPackIFWRepository()
   : Update(None)
diff --git a/Source/CPack/OSXScriptLauncher.cxx b/Source/CPack/OSXScriptLauncher.cxx
index 6eb4a6c..b159e64 100644
--- a/Source/CPack/OSXScriptLauncher.cxx
+++ b/Source/CPack/OSXScriptLauncher.cxx
@@ -3,8 +3,10 @@
 #include <cmsys/FStream.hxx>
 #include <cmsys/Process.h>
 #include <cmsys/SystemTools.hxx>
-
 #include <iostream>
+#include <stddef.h>
+#include <string>
+#include <vector>
 
 #include <CoreFoundation/CoreFoundation.h>
 
diff --git a/Source/CPack/WiX/cmCPackWIXGenerator.cxx b/Source/CPack/WiX/cmCPackWIXGenerator.cxx
index 5320449..2bccf2e 100644
--- a/Source/CPack/WiX/cmCPackWIXGenerator.cxx
+++ b/Source/CPack/WiX/cmCPackWIXGenerator.cxx
@@ -4,6 +4,7 @@
 
 #include <CPack/cmCPackComponentGroup.h>
 #include <CPack/cmCPackLog.h>
+#include <algorithm>
 #include <cmCryptoHash.h>
 #include <cmGeneratedFileStream.h>
 #include <cmInstalledFile.h>
@@ -410,8 +411,7 @@ void cmCPackWIXGenerator::AddDefinition(cmWIXSourceWriter& source,
   std::ostringstream tmp;
   tmp << name << "=\"" << value << '"';
 
-  source.AddProcessingInstruction(
-    "define", cmWIXSourceWriter::CMakeEncodingToUtf8(tmp.str()));
+  source.AddProcessingInstruction("define", tmp.str());
 }
 
 bool cmCPackWIXGenerator::CreateWiXSourceFiles()
@@ -1061,8 +1061,8 @@ std::string cmCPackWIXGenerator::CreateNewIdForPath(std::string const& path)
 std::string cmCPackWIXGenerator::CreateHashedId(
   std::string const& path, std::string const& normalizedFilename)
 {
-  CM_AUTO_PTR<cmCryptoHash> sha1 = cmCryptoHash::New("SHA1");
-  std::string hash = sha1->HashString(path.c_str());
+  cmCryptoHash sha1(cmCryptoHash::AlgoSHA1);
+  std::string const hash = sha1.HashString(path);
 
   std::string identifier;
   identifier += hash.substr(0, 7) + "_";
diff --git a/Source/CPack/WiX/cmWIXRichTextFormatWriter.h b/Source/CPack/WiX/cmWIXRichTextFormatWriter.h
index b535979..a3c8394 100644
--- a/Source/CPack/WiX/cmWIXRichTextFormatWriter.h
+++ b/Source/CPack/WiX/cmWIXRichTextFormatWriter.h
@@ -5,9 +5,8 @@
 
 #include <cmConfigure.h>
 
-#include "cmStandardIncludes.h"
-
 #include <cmsys/FStream.hxx>
+#include <string>
 
 /** \class cmWIXRichtTextFormatWriter
  * \brief Helper class to generate Rich Text Format (RTF) documents
diff --git a/Source/CPack/WiX/cmWIXSourceWriter.cxx b/Source/CPack/WiX/cmWIXSourceWriter.cxx
index a8b0d7c..b434334 100644
--- a/Source/CPack/WiX/cmWIXSourceWriter.cxx
+++ b/Source/CPack/WiX/cmWIXSourceWriter.cxx
@@ -117,9 +117,7 @@ void cmWIXSourceWriter::AddProcessingInstruction(std::string const& target,
 void cmWIXSourceWriter::AddAttribute(std::string const& key,
                                      std::string const& value)
 {
-  std::string utf8 = CMakeEncodingToUtf8(value);
-
-  File << " " << key << "=\"" << EscapeAttributeValue(utf8) << '"';
+  File << " " << key << "=\"" << EscapeAttributeValue(value) << '"';
 }
 
 void cmWIXSourceWriter::AddAttributeUnlessEmpty(std::string const& key,
@@ -130,43 +128,6 @@ void cmWIXSourceWriter::AddAttributeUnlessEmpty(std::string const& key,
   }
 }
 
-std::string cmWIXSourceWriter::CMakeEncodingToUtf8(std::string const& value)
-{
-#ifdef CMAKE_ENCODING_UTF8
-  return value;
-#else
-  if (value.empty()) {
-    return std::string();
-  }
-
-  int characterCount = MultiByteToWideChar(
-    CP_ACP, 0, value.c_str(), static_cast<int>(value.size()), 0, 0);
-
-  if (characterCount == 0) {
-    return std::string();
-  }
-
-  std::vector<wchar_t> utf16(characterCount);
-
-  MultiByteToWideChar(CP_ACP, 0, value.c_str(), static_cast<int>(value.size()),
-                      &utf16[0], static_cast<int>(utf16.size()));
-
-  int utf8ByteCount = WideCharToMultiByte(
-    CP_UTF8, 0, &utf16[0], static_cast<int>(utf16.size()), 0, 0, 0, 0);
-
-  if (utf8ByteCount == 0) {
-    return std::string();
-  }
-
-  std::vector<char> utf8(utf8ByteCount);
-
-  WideCharToMultiByte(CP_UTF8, 0, &utf16[0], static_cast<int>(utf16.size()),
-                      &utf8[0], static_cast<int>(utf8.size()), 0, 0);
-
-  return std::string(&utf8[0], utf8.size());
-#endif
-}
-
 std::string cmWIXSourceWriter::CreateGuidFromComponentId(
   std::string const& componentId)
 {
diff --git a/Source/CPack/WiX/cmWIXSourceWriter.h b/Source/CPack/WiX/cmWIXSourceWriter.h
index b5c06ab..45aefe5 100644
--- a/Source/CPack/WiX/cmWIXSourceWriter.h
+++ b/Source/CPack/WiX/cmWIXSourceWriter.h
@@ -50,8 +50,6 @@ public:
 
   std::string CreateGuidFromComponentId(std::string const& componentId);
 
-  static std::string CMakeEncodingToUtf8(std::string const& value);
-
 protected:
   cmCPackLog* Logger;
 
diff --git a/Source/CPack/cmCPack7zGenerator.h b/Source/CPack/cmCPack7zGenerator.h
index 063b032..a617d9b 100644
--- a/Source/CPack/cmCPack7zGenerator.h
+++ b/Source/CPack/cmCPack7zGenerator.h
@@ -7,7 +7,6 @@
 
 #include "cmCPackArchiveGenerator.h"
 #include "cmCPackGenerator.h"
-#include "cmTypeMacro.h"
 
 /** \class cmCPack7zGenerator
  * \brief A generator for 7z files
diff --git a/Source/CPack/cmCPackArchiveGenerator.h b/Source/CPack/cmCPackArchiveGenerator.h
index e960a6a..df02ae8 100644
--- a/Source/CPack/cmCPackArchiveGenerator.h
+++ b/Source/CPack/cmCPackArchiveGenerator.h
@@ -7,7 +7,6 @@
 
 #include "cmArchiveWrite.h"
 #include "cmCPackGenerator.h"
-#include "cmTypeMacro.h"
 
 #include <iosfwd>
 #include <string>
@@ -23,7 +22,7 @@ class cmCPackComponent;
 class cmCPackArchiveGenerator : public cmCPackGenerator
 {
 public:
-  cmTypeMacro(cmCPackArchiveGenerator, cmCPackGenerator);
+  typedef cmCPackGenerator Superclass;
 
   /**
    * Construct generator
diff --git a/Source/CPack/cmCPackBundleGenerator.cxx b/Source/CPack/cmCPackBundleGenerator.cxx
index 61d0127..d538901 100644
--- a/Source/CPack/cmCPackBundleGenerator.cxx
+++ b/Source/CPack/cmCPackBundleGenerator.cxx
@@ -2,11 +2,12 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackBundleGenerator.h"
 
+#include <sstream>
+#include <vector>
+
 #include "cmCPackLog.h"
 #include "cmSystemTools.h"
 
-#include <cmsys/RegularExpression.hxx>
-
 cmCPackBundleGenerator::cmCPackBundleGenerator()
 {
 }
diff --git a/Source/CPack/cmCPackBundleGenerator.h b/Source/CPack/cmCPackBundleGenerator.h
index 9ea4304..c9200c1 100644
--- a/Source/CPack/cmCPackBundleGenerator.h
+++ b/Source/CPack/cmCPackBundleGenerator.h
@@ -3,7 +3,11 @@
 #ifndef cmCPackBundleGenerator_h
 #define cmCPackBundleGenerator_h
 
+#include <cmConfigure.h>
+#include <string>
+
 #include "cmCPackDragNDropGenerator.h"
+#include "cmCPackGenerator.h"
 
 /** \class cmCPackBundleGenerator
  * \brief A generator for OSX bundles
diff --git a/Source/CPack/cmCPackDebGenerator.cxx b/Source/CPack/cmCPackDebGenerator.cxx
index 36566a4..5c50da8 100644
--- a/Source/CPack/cmCPackDebGenerator.cxx
+++ b/Source/CPack/cmCPackDebGenerator.cxx
@@ -173,7 +173,11 @@ int cmCPackDebGenerator::PackageComponentsAllInOne(
     std::string(this->GetOption("CPACK_PACKAGE_FILE_NAME")) +
     this->GetOutputExtension());
   // all GROUP in one vs all COMPONENT in one
-  localToplevel += "/" + compInstDirName;
+  // if must be here otherwise non component paths have a trailing / while
+  // components don't
+  if (!compInstDirName.empty()) {
+    localToplevel += "/" + compInstDirName;
+  }
 
   /* replace the TEMP DIRECTORY with the component one */
   this->SetOption("CPACK_TEMPORARY_DIRECTORY", localToplevel.c_str());
diff --git a/Source/CPack/cmCPackDebGenerator.h b/Source/CPack/cmCPackDebGenerator.h
index f46ae5a..7db933e 100644
--- a/Source/CPack/cmCPackDebGenerator.h
+++ b/Source/CPack/cmCPackDebGenerator.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCPackGenerator.h"
-#include "cmTypeMacro.h"
 
 #include <string>
 #include <vector>
diff --git a/Source/CPack/cmCPackDragNDropGenerator.cxx b/Source/CPack/cmCPackDragNDropGenerator.cxx
index bdf4076..fd67df9 100644
--- a/Source/CPack/cmCPackDragNDropGenerator.cxx
+++ b/Source/CPack/cmCPackDragNDropGenerator.cxx
@@ -2,14 +2,16 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackDragNDropGenerator.h"
 
+#include "cmCPackGenerator.h"
 #include "cmCPackLog.h"
 #include "cmGeneratedFileStream.h"
 #include "cmSystemTools.h"
 
 #include <cmsys/FStream.hxx>
 #include <cmsys/RegularExpression.hxx>
-
 #include <iomanip>
+#include <map>
+#include <stdlib.h>
 
 #include <CoreFoundation/CoreFoundation.h>
 
diff --git a/Source/CPack/cmCPackDragNDropGenerator.h b/Source/CPack/cmCPackDragNDropGenerator.h
index f803ad9..876eab7 100644
--- a/Source/CPack/cmCPackDragNDropGenerator.h
+++ b/Source/CPack/cmCPackDragNDropGenerator.h
@@ -3,6 +3,12 @@
 #ifndef cmCPackDragNDropGenerator_h
 #define cmCPackDragNDropGenerator_h
 
+#include <cmConfigure.h>
+#include <sstream>
+#include <stddef.h>
+#include <string>
+#include <vector>
+
 #include "cmCPackGenerator.h"
 
 class cmGeneratedFileStream;
diff --git a/Source/CPack/cmCPackGenerator.cxx b/Source/CPack/cmCPackGenerator.cxx
index d4135ce..21eda79 100644
--- a/Source/CPack/cmCPackGenerator.cxx
+++ b/Source/CPack/cmCPackGenerator.cxx
@@ -2,24 +2,24 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackGenerator.h"
 
+#include <algorithm>
+#include <cmsys/FStream.hxx>
+#include <cmsys/Glob.hxx>
+#include <cmsys/RegularExpression.hxx>
+#include <list>
+#include <utility>
+
 #include "cmCPackComponentGroup.h"
 #include "cmCPackLog.h"
 #include "cmCryptoHash.h"
 #include "cmGeneratedFileStream.h"
 #include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
-#include "cmState.h"
+#include "cmStateSnapshot.h"
 #include "cmXMLSafe.h"
 #include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
-#include <algorithm>
-#include <cmsys/FStream.hxx>
-#include <cmsys/Glob.hxx>
-#include <cmsys/RegularExpression.hxx>
-#include <list>
-#include <utility>
-
 #if defined(__HAIKU__)
 #include <FindDirectory.h>
 #include <StorageDefs.h>
@@ -1074,6 +1074,24 @@ bool cmCPackGenerator::IsOn(const std::string& name) const
   return cmSystemTools::IsOn(GetOption(name));
 }
 
+bool cmCPackGenerator::IsSetToOff(const std::string& op) const
+{
+  const char* ret = this->MakefileMap->GetDefinition(op);
+  if (ret && *ret) {
+    return cmSystemTools::IsOff(ret);
+  }
+  return false;
+}
+
+bool cmCPackGenerator::IsSetToEmpty(const std::string& op) const
+{
+  const char* ret = this->MakefileMap->GetDefinition(op);
+  if (ret) {
+    return !*ret;
+  }
+  return false;
+}
+
 const char* cmCPackGenerator::GetOption(const std::string& op) const
 {
   const char* ret = this->MakefileMap->GetDefinition(op);
diff --git a/Source/CPack/cmCPackGenerator.h b/Source/CPack/cmCPackGenerator.h
index 9232ffc..5354fca 100644
--- a/Source/CPack/cmCPackGenerator.h
+++ b/Source/CPack/cmCPackGenerator.h
@@ -5,22 +5,22 @@
 
 #include <cmConfigure.h>
 
-#include "cmCPackComponentGroup.h"
-#include "cmObject.h"
-#include "cmSystemTools.h"
-#include "cmTypeMacro.h"
-
 #include <map>
 #include <sstream>
 #include <string>
 #include <vector>
 
+#include "cmCPackComponentGroup.h"
+#include "cmSystemTools.h"
+
+class cmCPackGenerator;
 class cmCPackLog;
 class cmInstalledFile;
 class cmMakefile;
 
 #define cmCPackTypeMacro(klass, superclass)                                   \
-  cmTypeMacro(klass, superclass);                                             \
+  typedef superclass Superclass;                                              \
+  const char* GetNameOfClass() CM_OVERRIDE { return #klass; }                 \
   static cmCPackGenerator* CreateGenerator() { return new klass; }            \
   class cmCPackTypeMacro_UseTrailingSemicolon
 
@@ -30,26 +30,16 @@ class cmMakefile;
     cmCPackLog_msg << msg;                                                    \
     this->Logger->Log(logType, __FILE__, __LINE__,                            \
                       cmCPackLog_msg.str().c_str());                          \
-  } while (0)
-
-#ifdef cerr
-#undef cerr
-#endif
-#define cerr no_cerr_use_cmCPack_Log
-
-#ifdef cout
-#undef cout
-#endif
-#define cout no_cout_use_cmCPack_Log
+  } while (false)
 
 /** \class cmCPackGenerator
  * \brief A superclass of all CPack Generators
  *
  */
-class cmCPackGenerator : public cmObject
+class cmCPackGenerator
 {
 public:
-  cmTypeMacro(cmCPackGenerator, cmObject);
+  virtual const char* GetNameOfClass() = 0;
   /**
    * If verbose then more information is printed out
    */
@@ -93,7 +83,7 @@ public:
    * Construct generator
    */
   cmCPackGenerator();
-  ~cmCPackGenerator() CM_OVERRIDE;
+  virtual ~cmCPackGenerator();
 
   //! Set and get the options
   void SetOption(const std::string& op, const char* value);
@@ -102,6 +92,8 @@ public:
   std::vector<std::string> GetOptions() const;
   bool IsSet(const std::string& name) const;
   bool IsOn(const std::string& name) const;
+  bool IsSetToOff(const std::string& op) const;
+  bool IsSetToEmpty(const std::string& op) const;
 
   //! Set the logger
   void SetLogger(cmCPackLog* log) { this->Logger = log; }
diff --git a/Source/CPack/cmCPackGeneratorFactory.cxx b/Source/CPack/cmCPackGeneratorFactory.cxx
index 2a0e65b..b012f01 100644
--- a/Source/CPack/cmCPackGeneratorFactory.cxx
+++ b/Source/CPack/cmCPackGeneratorFactory.cxx
@@ -2,9 +2,15 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackGeneratorFactory.h"
 
+#include <cmConfigure.h>
+#include <ostream>
+#include <utility>
+
 #include "IFW/cmCPackIFWGenerator.h"
+#include "cmAlgorithms.h"
 #include "cmCPack7zGenerator.h"
 #include "cmCPackGenerator.h"
+#include "cmCPackLog.h"
 #include "cmCPackNSISGenerator.h"
 #include "cmCPackSTGZGenerator.h"
 #include "cmCPackTGZGenerator.h"
@@ -36,12 +42,6 @@
 #include "WiX/cmCPackWIXGenerator.h"
 #endif
 
-#include "cmAlgorithms.h"
-#include "cmCPackLog.h"
-
-#include <ostream>
-#include <utility>
-
 cmCPackGeneratorFactory::cmCPackGeneratorFactory()
 {
   if (cmCPackTGZGenerator::CanGenerate()) {
diff --git a/Source/CPack/cmCPackGeneratorFactory.h b/Source/CPack/cmCPackGeneratorFactory.h
index 145867e..4ee0bc1 100644
--- a/Source/CPack/cmCPackGeneratorFactory.h
+++ b/Source/CPack/cmCPackGeneratorFactory.h
@@ -3,10 +3,7 @@
 #ifndef cmCPackGeneratorFactory_h
 #define cmCPackGeneratorFactory_h
 
-#include <cmConfigure.h>
-
-#include "cmObject.h"
-#include "cmTypeMacro.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <map>
 #include <string>
@@ -19,13 +16,11 @@ class cmCPackLog;
  * \brief A container for CPack generators
  *
  */
-class cmCPackGeneratorFactory : public cmObject
+class cmCPackGeneratorFactory
 {
 public:
-  cmTypeMacro(cmCPackGeneratorFactory, cmObject);
-
   cmCPackGeneratorFactory();
-  ~cmCPackGeneratorFactory() CM_OVERRIDE;
+  ~cmCPackGeneratorFactory();
 
   //! Get the generator
   cmCPackGenerator* NewGenerator(const std::string& name);
diff --git a/Source/CPack/cmCPackLog.cxx b/Source/CPack/cmCPackLog.cxx
index be429fe..7d5c192 100644
--- a/Source/CPack/cmCPackLog.cxx
+++ b/Source/CPack/cmCPackLog.cxx
@@ -2,11 +2,12 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackLog.h"
 
+#include <cmConfigure.h>
+#include <iostream>
+
 #include "cmGeneratedFileStream.h"
 #include "cmSystemTools.h"
 
-#include <iostream>
-
 cmCPackLog::cmCPackLog()
 {
   this->Verbose = false;
@@ -15,8 +16,6 @@ cmCPackLog::cmCPackLog()
   this->NewLine = true;
 
   this->LastTag = cmCPackLog::NOTAG;
-#undef cerr
-#undef cout
   this->DefaultOutput = &std::cout;
   this->DefaultError = &std::cerr;
 
diff --git a/Source/CPack/cmCPackLog.h b/Source/CPack/cmCPackLog.h
index 0831843..a988ccc 100644
--- a/Source/CPack/cmCPackLog.h
+++ b/Source/CPack/cmCPackLog.h
@@ -3,10 +3,7 @@
 #ifndef cmCPackLog_h
 #define cmCPackLog_h
 
-#include <cmConfigure.h>
-
-#include "cmObject.h"
-#include "cmTypeMacro.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <ostream>
 #include <string.h>
@@ -17,29 +14,17 @@
     std::ostringstream cmCPackLog_msg;                                        \
     cmCPackLog_msg << msg;                                                    \
     (ctSelf)->Log(logType, __FILE__, __LINE__, cmCPackLog_msg.str().c_str()); \
-  } while (0)
-
-#ifdef cerr
-#undef cerr
-#endif
-#define cerr no_cerr_use_cmCPack_Log
-
-#ifdef cout
-#undef cout
-#endif
-#define cout no_cout_use_cmCPack_Log
+  } while (false)
 
 /** \class cmCPackLog
  * \brief A container for CPack generators
  *
  */
-class cmCPackLog : public cmObject
+class cmCPackLog
 {
 public:
-  cmTypeMacro(cmCPackLog, cmObject);
-
   cmCPackLog();
-  ~cmCPackLog() CM_OVERRIDE;
+  ~cmCPackLog();
 
   enum __log_tags
   {
diff --git a/Source/CPack/cmCPackNSISGenerator.cxx b/Source/CPack/cmCPackNSISGenerator.cxx
index 2c9ca63..1940953 100644
--- a/Source/CPack/cmCPackNSISGenerator.cxx
+++ b/Source/CPack/cmCPackNSISGenerator.cxx
@@ -597,13 +597,11 @@ bool cmCPackNSISGenerator::GetListOfSubdirectories(
 {
   cmsys::Directory dir;
   dir.Load(topdir);
-  size_t fileNum;
-  for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) {
-    if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") &&
-        strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), "..")) {
-      std::string fullPath = topdir;
-      fullPath += "/";
-      fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
+  for (unsigned long i = 0; i < dir.GetNumberOfFiles(); ++i) {
+    const char* fileName = dir.GetFile(i);
+    if (strcmp(fileName, ".") != 0 && strcmp(fileName, "..") != 0) {
+      std::string const fullPath =
+        std::string(topdir).append("/").append(fileName);
       if (cmsys::SystemTools::FileIsDirectory(fullPath) &&
           !cmsys::SystemTools::FileIsSymlink(fullPath)) {
         if (!this->GetListOfSubdirectories(fullPath.c_str(), dirs)) {
diff --git a/Source/CPack/cmCPackNSISGenerator.h b/Source/CPack/cmCPackNSISGenerator.h
index d61341c..b4bf2d4 100644
--- a/Source/CPack/cmCPackNSISGenerator.h
+++ b/Source/CPack/cmCPackNSISGenerator.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCPackGenerator.h"
-#include "cmTypeMacro.h"
 
 #include <iosfwd>
 #include <set>
diff --git a/Source/CPack/cmCPackOSXX11Generator.cxx b/Source/CPack/cmCPackOSXX11Generator.cxx
index 225c1fb..0d8dc48 100644
--- a/Source/CPack/cmCPackOSXX11Generator.cxx
+++ b/Source/CPack/cmCPackOSXX11Generator.cxx
@@ -2,16 +2,13 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackOSXX11Generator.h"
 
+#include <sstream>
+#include <sys/stat.h>
+
+#include "cmCPackGenerator.h"
 #include "cmCPackLog.h"
 #include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
 #include "cmSystemTools.h"
-#include "cmake.h"
-
-#include <cmsys/Glob.hxx>
-#include <cmsys/SystemTools.hxx>
-#include <sys/stat.h>
 
 cmCPackOSXX11Generator::cmCPackOSXX11Generator()
 {
diff --git a/Source/CPack/cmCPackOSXX11Generator.h b/Source/CPack/cmCPackOSXX11Generator.h
index eb1e5ff..1918e21 100644
--- a/Source/CPack/cmCPackOSXX11Generator.h
+++ b/Source/CPack/cmCPackOSXX11Generator.h
@@ -3,6 +3,9 @@
 #ifndef cmCPackOSXX11Generator_h
 #define cmCPackOSXX11Generator_h
 
+#include <cmConfigure.h>
+#include <string>
+
 #include "cmCPackGenerator.h"
 
 /** \class cmCPackOSXX11Generator
diff --git a/Source/CPack/cmCPackPKGGenerator.cxx b/Source/CPack/cmCPackPKGGenerator.cxx
index 785ee01..70ae267 100644
--- a/Source/CPack/cmCPackPKGGenerator.cxx
+++ b/Source/CPack/cmCPackPKGGenerator.cxx
@@ -2,18 +2,13 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackPKGGenerator.h"
 
+#include <vector>
+
 #include "cmCPackComponentGroup.h"
+#include "cmCPackGenerator.h"
 #include "cmCPackLog.h"
-#include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmLocalGenerator.h"
-#include "cmMakefile.h"
 #include "cmSystemTools.h"
 #include "cmXMLWriter.h"
-#include "cmake.h"
-
-#include <cmsys/Glob.hxx>
-#include <cmsys/SystemTools.hxx>
 
 cmCPackPKGGenerator::cmCPackPKGGenerator()
 {
diff --git a/Source/CPack/cmCPackPKGGenerator.h b/Source/CPack/cmCPackPKGGenerator.h
index 5569185..1e96a62 100644
--- a/Source/CPack/cmCPackPKGGenerator.h
+++ b/Source/CPack/cmCPackPKGGenerator.h
@@ -3,9 +3,14 @@
 #ifndef cmCPackPKGGenerator_h
 #define cmCPackPKGGenerator_h
 
+#include <cmConfigure.h>
+#include <set>
+#include <sstream>
+#include <string>
+
+#include "cmCPackComponentGroup.h"
 #include "cmCPackGenerator.h"
 
-class cmCPackComponent;
 class cmXMLWriter;
 
 /** \class cmCPackPKGGenerator
diff --git a/Source/CPack/cmCPackPackageMakerGenerator.cxx b/Source/CPack/cmCPackPackageMakerGenerator.cxx
index 25e8a1c..8000d6e 100644
--- a/Source/CPack/cmCPackPackageMakerGenerator.cxx
+++ b/Source/CPack/cmCPackPackageMakerGenerator.cxx
@@ -2,20 +2,20 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackPackageMakerGenerator.h"
 
+#include <assert.h>
+#include <cmsys/FStream.hxx>
+#include <cmsys/RegularExpression.hxx>
+#include <map>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string>
+
 #include "cmCPackComponentGroup.h"
 #include "cmCPackLog.h"
 #include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
 #include "cmSystemTools.h"
 #include "cmXMLWriter.h"
-#include "cmake.h"
-
-#include <cmsys/FStream.hxx>
-#include <cmsys/Glob.hxx>
-#include <cmsys/SystemTools.hxx>
-
-#include <assert.h>
 
 static inline unsigned int getVersion(unsigned int major, unsigned int minor)
 {
diff --git a/Source/CPack/cmCPackPackageMakerGenerator.h b/Source/CPack/cmCPackPackageMakerGenerator.h
index d679bc1..d4c6744 100644
--- a/Source/CPack/cmCPackPackageMakerGenerator.h
+++ b/Source/CPack/cmCPackPackageMakerGenerator.h
@@ -3,6 +3,9 @@
 #ifndef cmCPackPackageMakerGenerator_h
 #define cmCPackPackageMakerGenerator_h
 
+#include <cmConfigure.h>
+
+#include "cmCPackGenerator.h"
 #include "cmCPackPKGGenerator.h"
 
 class cmCPackComponent;
diff --git a/Source/CPack/cmCPackProductBuildGenerator.cxx b/Source/CPack/cmCPackProductBuildGenerator.cxx
index ff0ec79..a5a18dc 100644
--- a/Source/CPack/cmCPackProductBuildGenerator.cxx
+++ b/Source/CPack/cmCPackProductBuildGenerator.cxx
@@ -2,17 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackProductBuildGenerator.h"
 
+#include <map>
+#include <sstream>
+#include <stddef.h>
+
 #include "cmCPackComponentGroup.h"
 #include "cmCPackLog.h"
 #include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmLocalGenerator.h"
-#include "cmMakefile.h"
 #include "cmSystemTools.h"
-#include "cmake.h"
-
-#include <cmsys/Glob.hxx>
-#include <cmsys/SystemTools.hxx>
 
 cmCPackProductBuildGenerator::cmCPackProductBuildGenerator()
 {
@@ -78,6 +75,14 @@ int cmCPackProductBuildGenerator::PackageFiles()
 
   std::string version = this->GetOption("CPACK_PACKAGE_VERSION");
   std::string productbuild = this->GetOption("CPACK_COMMAND_PRODUCTBUILD");
+  std::string identityName;
+  if (const char* n = this->GetOption("CPACK_PRODUCTBUILD_IDENTITY_NAME")) {
+    identityName = n;
+  }
+  std::string keychainPath;
+  if (const char* p = this->GetOption("CPACK_PRODUCTBUILD_KEYCHAIN_PATH")) {
+    keychainPath = p;
+  }
 
   pkgCmd << productbuild << " --distribution \"" << packageDirFileName
          << "/Contents/distribution.dist\""
@@ -85,6 +90,9 @@ int cmCPackProductBuildGenerator::PackageFiles()
          << "\""
          << " --resources \"" << resDir << "\""
          << " --version \"" << version << "\""
+         << (identityName.empty() ? "" : " --sign \"" + identityName + "\"")
+         << (keychainPath.empty() ? ""
+                                  : " --keychain \"" + keychainPath + "\"")
          << " \"" << packageFileNames[0] << "\"";
 
   // Run ProductBuild
@@ -196,12 +204,23 @@ bool cmCPackProductBuildGenerator::GenerateComponentPackage(
 
   std::string version = this->GetOption("CPACK_PACKAGE_VERSION");
   std::string pkgbuild = this->GetOption("CPACK_COMMAND_PKGBUILD");
+  std::string identityName;
+  if (const char* n = this->GetOption("CPACK_PKGBUILD_IDENTITY_NAME")) {
+    identityName = n;
+  }
+  std::string keychainPath;
+  if (const char* p = this->GetOption("CPACK_PKGBUILD_KEYCHAIN_PATH")) {
+    keychainPath = p;
+  }
 
   pkgCmd << pkgbuild << " --root \"" << packageDir << "\""
          << " --identifier \"" << pkgId << "\""
          << " --scripts \"" << scriptDir << "\""
          << " --version \"" << version << "\""
          << " --install-location \"/\""
+         << (identityName.empty() ? "" : " --sign \"" + identityName + "\"")
+         << (keychainPath.empty() ? ""
+                                  : " --keychain \"" + keychainPath + "\"")
          << " \"" << packageFile << "\"";
 
   // Run ProductBuild
diff --git a/Source/CPack/cmCPackProductBuildGenerator.h b/Source/CPack/cmCPackProductBuildGenerator.h
index 4145eb4..b6da470 100644
--- a/Source/CPack/cmCPackProductBuildGenerator.h
+++ b/Source/CPack/cmCPackProductBuildGenerator.h
@@ -3,6 +3,10 @@
 #ifndef cmCPackProductBuildGenerator_h
 #define cmCPackProductBuildGenerator_h
 
+#include <cmConfigure.h>
+#include <string>
+
+#include "cmCPackGenerator.h"
 #include "cmCPackPKGGenerator.h"
 
 class cmCPackComponent;
diff --git a/Source/CPack/cmCPackRPMGenerator.cxx b/Source/CPack/cmCPackRPMGenerator.cxx
index bd55206..8ec03c2 100644
--- a/Source/CPack/cmCPackRPMGenerator.cxx
+++ b/Source/CPack/cmCPackRPMGenerator.cxx
@@ -2,17 +2,18 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackRPMGenerator.h"
 
-#include "cmCPackComponentGroup.h"
-#include "cmCPackGenerator.h"
-#include "cmCPackLog.h"
-#include "cmSystemTools.h"
-
 #include <algorithm>
+#include <ctype.h>
 #include <map>
 #include <ostream>
 #include <utility>
 #include <vector>
 
+#include "cmCPackComponentGroup.h"
+#include "cmCPackGenerator.h"
+#include "cmCPackLog.h"
+#include "cmSystemTools.h"
+
 cmCPackRPMGenerator::cmCPackRPMGenerator()
 {
 }
@@ -105,39 +106,224 @@ int cmCPackRPMGenerator::PackageComponents(bool ignoreGroup)
   packageFileNames.clear();
   std::string initialTopLevel(this->GetOption("CPACK_TEMPORARY_DIRECTORY"));
 
-  // The default behavior is to have one package by component group
-  // unless CPACK_COMPONENTS_IGNORE_GROUP is specified.
-  if (!ignoreGroup) {
-    std::map<std::string, cmCPackComponentGroup>::iterator compGIt;
-    for (compGIt = this->ComponentGroups.begin();
-         compGIt != this->ComponentGroups.end(); ++compGIt) {
-      cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Packaging component group: "
-                      << compGIt->first << std::endl);
-      retval &= PackageOnePack(initialTopLevel, compGIt->first);
+  const char* mainComponent = this->GetOption("CPACK_RPM_MAIN_COMPONENT");
+
+  if (this->IsOn("CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE") &&
+      !this->IsOn("CPACK_RPM_DEBUGINFO_PACKAGE")) {
+    // check if we need to set CPACK_RPM_DEBUGINFO_PACKAGE because non of
+    // the components is setting per component debuginfo package variable
+    bool shouldSet = true;
+
+    if (ignoreGroup) {
+      std::map<std::string, cmCPackComponent>::iterator compIt;
+      for (compIt = this->Components.begin(); compIt != this->Components.end();
+           ++compIt) {
+        std::string component(compIt->first);
+        std::transform(component.begin(), component.end(), component.begin(),
+                       ::toupper);
+
+        if (this->IsOn("CPACK_RPM_" + compIt->first + "_DEBUGINFO_PACKAGE") ||
+            this->IsOn("CPACK_RPM_" + component + "_DEBUGINFO_PACKAGE")) {
+          shouldSet = false;
+          break;
+        }
+      }
+    } else {
+      std::map<std::string, cmCPackComponentGroup>::iterator compGIt;
+      for (compGIt = this->ComponentGroups.begin();
+           compGIt != this->ComponentGroups.end(); ++compGIt) {
+        std::string component(compGIt->first);
+        std::transform(component.begin(), component.end(), component.begin(),
+                       ::toupper);
+
+        if (this->IsOn("CPACK_RPM_" + compGIt->first + "_DEBUGINFO_PACKAGE") ||
+            this->IsOn("CPACK_RPM_" + component + "_DEBUGINFO_PACKAGE")) {
+          shouldSet = false;
+          break;
+        }
+      }
+
+      if (shouldSet) {
+        std::map<std::string, cmCPackComponent>::iterator compIt;
+        for (compIt = this->Components.begin();
+             compIt != this->Components.end(); ++compIt) {
+          // Does the component belong to a group?
+          if (compIt->second.Group == CM_NULLPTR) {
+            std::string component(compIt->first);
+            std::transform(component.begin(), component.end(),
+                           component.begin(), ::toupper);
+
+            if (this->IsOn("CPACK_RPM_" + compIt->first +
+                           "_DEBUGINFO_PACKAGE") ||
+                this->IsOn("CPACK_RPM_" + component + "_DEBUGINFO_PACKAGE")) {
+              shouldSet = false;
+              break;
+            }
+          }
+        }
+      }
+    }
+
+    if (shouldSet) {
+      cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Setting "
+                      << "CPACK_RPM_DEBUGINFO_PACKAGE because "
+                      << "CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE is set but "
+                      << " none of the "
+                      << "CPACK_RPM_<component>_DEBUGINFO_PACKAGE variables "
+                      << "are set." << std::endl);
+      this->SetOption("CPACK_RPM_DEBUGINFO_PACKAGE", "ON");
     }
-    // Handle Orphan components (components not belonging to any groups)
-    std::map<std::string, cmCPackComponent>::iterator compIt;
-    for (compIt = this->Components.begin(); compIt != this->Components.end();
-         ++compIt) {
-      // Does the component belong to a group?
-      if (compIt->second.Group == CM_NULLPTR) {
-        cmCPackLogger(
-          cmCPackLog::LOG_VERBOSE, "Component <"
-            << compIt->second.Name
-            << "> does not belong to any group, package it separately."
-            << std::endl);
+  }
+
+  if (mainComponent) {
+    if (this->IsOn("CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE")) {
+      this->SetOption("GENERATE_SPEC_PARTS", "ON");
+    }
+
+    std::string mainComponentUpper(mainComponent);
+    std::transform(mainComponentUpper.begin(), mainComponentUpper.end(),
+                   mainComponentUpper.begin(), ::toupper);
+
+    // The default behavior is to have one package by component group
+    // unless CPACK_COMPONENTS_IGNORE_GROUP is specified.
+    if (!ignoreGroup) {
+      std::map<std::string, cmCPackComponentGroup>::iterator mainCompGIt =
+        this->ComponentGroups.end();
+
+      std::map<std::string, cmCPackComponentGroup>::iterator compGIt;
+      for (compGIt = this->ComponentGroups.begin();
+           compGIt != this->ComponentGroups.end(); ++compGIt) {
+        std::string component(compGIt->first);
+        std::transform(component.begin(), component.end(), component.begin(),
+                       ::toupper);
+
+        if (mainComponentUpper == component) {
+          // main component will be handled last
+          mainCompGIt = compGIt;
+          continue;
+        }
+
+        cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Packaging component group: "
+                        << compGIt->first << std::endl);
+        retval &= PackageOnePack(initialTopLevel, compGIt->first);
+      }
+      // Handle Orphan components (components not belonging to any groups)
+      std::map<std::string, cmCPackComponent>::iterator mainCompIt =
+        this->Components.end();
+      std::map<std::string, cmCPackComponent>::iterator compIt;
+      for (compIt = this->Components.begin(); compIt != this->Components.end();
+           ++compIt) {
+        // Does the component belong to a group?
+        if (compIt->second.Group == CM_NULLPTR) {
+          std::string component(compIt->first);
+          std::transform(component.begin(), component.end(), component.begin(),
+                         ::toupper);
+
+          if (mainComponentUpper == component) {
+            // main component will be handled last
+            mainCompIt = compIt;
+            continue;
+          }
+
+          cmCPackLogger(
+            cmCPackLog::LOG_VERBOSE, "Component <"
+              << compIt->second.Name
+              << "> does not belong to any group, package it separately."
+              << std::endl);
+          retval &= PackageOnePack(initialTopLevel, compIt->first);
+        }
+      }
+
+      if (retval) {
+        this->SetOption("GENERATE_SPEC_PARTS", "OFF");
+
+        if (mainCompGIt != this->ComponentGroups.end()) {
+          retval &= PackageOnePack(initialTopLevel, mainCompGIt->first);
+        } else if (mainCompIt != this->Components.end()) {
+          retval &= PackageOnePack(initialTopLevel, mainCompIt->first);
+        } else {
+          cmCPackLogger(cmCPackLog::LOG_ERROR, "CPACK_RPM_MAIN_COMPONENT set"
+                          << " to non existing component.\n");
+          retval = 0;
+        }
+      }
+    }
+    // CPACK_COMPONENTS_IGNORE_GROUPS is set
+    // We build 1 package per component
+    else {
+      std::map<std::string, cmCPackComponent>::iterator mainCompIt =
+        this->Components.end();
+
+      std::map<std::string, cmCPackComponent>::iterator compIt;
+      for (compIt = this->Components.begin(); compIt != this->Components.end();
+           ++compIt) {
+        std::string component(compIt->first);
+        std::transform(component.begin(), component.end(), component.begin(),
+                       ::toupper);
+
+        if (mainComponentUpper == component) {
+          // main component will be handled last
+          mainCompIt = compIt;
+          continue;
+        }
+
         retval &= PackageOnePack(initialTopLevel, compIt->first);
       }
+
+      if (retval) {
+        this->SetOption("GENERATE_SPEC_PARTS", "OFF");
+
+        if (mainCompIt != this->Components.end()) {
+          retval &= PackageOnePack(initialTopLevel, mainCompIt->first);
+        } else {
+          cmCPackLogger(cmCPackLog::LOG_ERROR, "CPACK_RPM_MAIN_COMPONENT set"
+                          << " to non existing component.\n");
+          retval = 0;
+        }
+      }
     }
-  }
-  // CPACK_COMPONENTS_IGNORE_GROUPS is set
-  // We build 1 package per component
-  else {
-    std::map<std::string, cmCPackComponent>::iterator compIt;
-    for (compIt = this->Components.begin(); compIt != this->Components.end();
-         ++compIt) {
-      retval &= PackageOnePack(initialTopLevel, compIt->first);
+  } else if (!this->IsOn("CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE") ||
+             this->Components.size() == 1) {
+    // The default behavior is to have one package by component group
+    // unless CPACK_COMPONENTS_IGNORE_GROUP is specified.
+    if (!ignoreGroup) {
+      std::map<std::string, cmCPackComponentGroup>::iterator compGIt;
+      for (compGIt = this->ComponentGroups.begin();
+           compGIt != this->ComponentGroups.end(); ++compGIt) {
+        cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Packaging component group: "
+                        << compGIt->first << std::endl);
+        retval &= PackageOnePack(initialTopLevel, compGIt->first);
+      }
+      // Handle Orphan components (components not belonging to any groups)
+      std::map<std::string, cmCPackComponent>::iterator compIt;
+      for (compIt = this->Components.begin(); compIt != this->Components.end();
+           ++compIt) {
+        // Does the component belong to a group?
+        if (compIt->second.Group == CM_NULLPTR) {
+          cmCPackLogger(
+            cmCPackLog::LOG_VERBOSE, "Component <"
+              << compIt->second.Name
+              << "> does not belong to any group, package it separately."
+              << std::endl);
+          retval &= PackageOnePack(initialTopLevel, compIt->first);
+        }
+      }
     }
+    // CPACK_COMPONENTS_IGNORE_GROUPS is set
+    // We build 1 package per component
+    else {
+      std::map<std::string, cmCPackComponent>::iterator compIt;
+      for (compIt = this->Components.begin(); compIt != this->Components.end();
+           ++compIt) {
+        retval &= PackageOnePack(initialTopLevel, compIt->first);
+      }
+    }
+  } else {
+    cmCPackLogger(
+      cmCPackLog::LOG_ERROR, "CPACK_RPM_MAIN_COMPONENT not set but"
+        << " it is mandatory with CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE"
+        << " being set.\n");
+    retval = 0;
   }
 
   if (retval) {
@@ -156,6 +342,10 @@ int cmCPackRPMGenerator::PackageComponentsAllInOne(
   packageFileNames.clear();
   std::string initialTopLevel(this->GetOption("CPACK_TEMPORARY_DIRECTORY"));
 
+  if (this->IsOn("CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE")) {
+    this->SetOption("CPACK_RPM_DEBUGINFO_PACKAGE", "ON");
+  }
+
   cmCPackLogger(cmCPackLog::LOG_VERBOSE,
                 "Packaging all groups in one package..."
                 "(CPACK_COMPONENTS_ALL_[GROUPS_]IN_ONE_PACKAGE is set)"
diff --git a/Source/CPack/cmCPackRPMGenerator.h b/Source/CPack/cmCPackRPMGenerator.h
index f8bcbfe..4d48bd8 100644
--- a/Source/CPack/cmCPackRPMGenerator.h
+++ b/Source/CPack/cmCPackRPMGenerator.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCPackGenerator.h"
-#include "cmTypeMacro.h"
 
 #include <string>
 
diff --git a/Source/CPack/cmCPackSTGZGenerator.cxx b/Source/CPack/cmCPackSTGZGenerator.cxx
index 66ba9f6..682394e 100644
--- a/Source/CPack/cmCPackSTGZGenerator.cxx
+++ b/Source/CPack/cmCPackSTGZGenerator.cxx
@@ -2,10 +2,6 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCPackSTGZGenerator.h"
 
-#include "cmCPackGenerator.h"
-#include "cmCPackLog.h"
-#include "cmSystemTools.h"
-
 #include <cmsys/FStream.hxx>
 #include <sstream>
 #include <stdio.h>
@@ -16,6 +12,10 @@
 // include sys/stat.h after sys/types.h
 #include <sys/stat.h>
 
+#include "cmCPackGenerator.h"
+#include "cmCPackLog.h"
+#include "cmSystemTools.h"
+
 cmCPackSTGZGenerator::cmCPackSTGZGenerator()
 {
 }
diff --git a/Source/CPack/cmCPackSTGZGenerator.h b/Source/CPack/cmCPackSTGZGenerator.h
index a1bee5f..4b9c1c6 100644
--- a/Source/CPack/cmCPackSTGZGenerator.h
+++ b/Source/CPack/cmCPackSTGZGenerator.h
@@ -7,7 +7,6 @@
 
 #include "cmCPackGenerator.h"
 #include "cmCPackTGZGenerator.h"
-#include "cmTypeMacro.h"
 
 #include <iosfwd>
 
diff --git a/Source/CPack/cmCPackTGZGenerator.h b/Source/CPack/cmCPackTGZGenerator.h
index e93fb44..ee2e975 100644
--- a/Source/CPack/cmCPackTGZGenerator.h
+++ b/Source/CPack/cmCPackTGZGenerator.h
@@ -7,7 +7,6 @@
 
 #include "cmCPackArchiveGenerator.h"
 #include "cmCPackGenerator.h"
-#include "cmTypeMacro.h"
 
 /** \class cmCPackTGZGenerator
  * \brief A generator for TGZ files
diff --git a/Source/CPack/cmCPackTXZGenerator.h b/Source/CPack/cmCPackTXZGenerator.h
index b8a7597..876ca7d 100644
--- a/Source/CPack/cmCPackTXZGenerator.h
+++ b/Source/CPack/cmCPackTXZGenerator.h
@@ -7,7 +7,6 @@
 
 #include "cmCPackArchiveGenerator.h"
 #include "cmCPackGenerator.h"
-#include "cmTypeMacro.h"
 
 /** \class cmCPackTXZGenerator
  * \brief A generator for TXZ files
diff --git a/Source/CPack/cmCPackTarBZip2Generator.h b/Source/CPack/cmCPackTarBZip2Generator.h
index 2e8ba9b..42214fd 100644
--- a/Source/CPack/cmCPackTarBZip2Generator.h
+++ b/Source/CPack/cmCPackTarBZip2Generator.h
@@ -7,7 +7,6 @@
 
 #include "cmCPackArchiveGenerator.h"
 #include "cmCPackGenerator.h"
-#include "cmTypeMacro.h"
 
 /** \class cmCPackTarBZip2Generator
  * \brief A generator for TarBZip2 files
diff --git a/Source/CPack/cmCPackTarCompressGenerator.h b/Source/CPack/cmCPackTarCompressGenerator.h
index 7d253e1..1476642 100644
--- a/Source/CPack/cmCPackTarCompressGenerator.h
+++ b/Source/CPack/cmCPackTarCompressGenerator.h
@@ -7,7 +7,6 @@
 
 #include "cmCPackArchiveGenerator.h"
 #include "cmCPackGenerator.h"
-#include "cmTypeMacro.h"
 
 /** \class cmCPackTarCompressGenerator
  * \brief A generator for TarCompress files
diff --git a/Source/CPack/cmCPackZIPGenerator.h b/Source/CPack/cmCPackZIPGenerator.h
index e0334fb..95b6489 100644
--- a/Source/CPack/cmCPackZIPGenerator.h
+++ b/Source/CPack/cmCPackZIPGenerator.h
@@ -7,7 +7,6 @@
 
 #include "cmCPackArchiveGenerator.h"
 #include "cmCPackGenerator.h"
-#include "cmTypeMacro.h"
 
 /** \class cmCPackZIPGenerator
  * \brief A generator for ZIP files
diff --git a/Source/CPack/cpack.cxx b/Source/CPack/cpack.cxx
index 5c45b14..af80cbf 100644
--- a/Source/CPack/cpack.cxx
+++ b/Source/CPack/cpack.cxx
@@ -2,6 +2,20 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include <cmConfigure.h>
 
+#include <cmsys/CommandLineArguments.hxx>
+#include <cmsys/Encoding.hxx>
+#include <iostream>
+#include <map>
+#include <sstream>
+#include <stddef.h>
+#include <string>
+#include <utility>
+#include <vector>
+
+#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
+#include <cmsys/ConsoleBuf.hxx>
+#endif
+
 #include "cmCPackGenerator.h"
 #include "cmCPackGeneratorFactory.h"
 #include "cmCPackLog.h"
@@ -10,21 +24,11 @@
 #include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
 #include "cmState.h"
+#include "cmStateSnapshot.h"
 #include "cmSystemTools.h"
-#include "cmTypeMacro.h"
 #include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
-#include <cmsys/CommandLineArguments.hxx>
-#include <cmsys/Encoding.hxx>
-#include <iostream>
-#include <map>
-#include <sstream>
-#include <stddef.h>
-#include <string>
-#include <utility>
-#include <vector>
-
 static const char* cmDocumentationName[][2] = {
   { CM_NULLPTR, "  cpack - Packaging driver provided by CMake." },
   { CM_NULLPTR, CM_NULLPTR }
@@ -84,6 +88,13 @@ int cpackDefinitionArgument(const char* argument, const char* cValue,
 // this is CPack.
 int main(int argc, char const* const* argv)
 {
+#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
+  // Replace streambuf so we can output Unicode to console
+  cmsys::ConsoleBuf::Manager consoleOut(std::cout);
+  consoleOut.SetUTF8Pipes();
+  cmsys::ConsoleBuf::Manager consoleErr(std::cerr, true);
+  consoleErr.SetUTF8Pipes();
+#endif
   cmsys::Encoding::CommandLineArguments args =
     cmsys::Encoding::CommandLineArguments::Main(argc, argv);
   argc = args.argc();
@@ -415,9 +426,7 @@ int main(int argc, char const* const* argv)
     }
     doc.SetSection("Generators", v);
 
-#undef cout
     return doc.PrintRequestedDocumentation(std::cout) ? 0 : 1;
-#define cout no_cout_use_cmCPack_Log
   }
 
   if (cmSystemTools::GetErrorOccuredFlag()) {
diff --git a/Source/CTest/cmCTestBuildAndTestHandler.h b/Source/CTest/cmCTestBuildAndTestHandler.h
index 8d787ea..5885738 100644
--- a/Source/CTest/cmCTestBuildAndTestHandler.h
+++ b/Source/CTest/cmCTestBuildAndTestHandler.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestGenericHandler.h"
-#include "cmTypeMacro.h"
 
 #include <sstream>
 #include <stddef.h>
@@ -22,7 +21,7 @@ class cmake;
 class cmCTestBuildAndTestHandler : public cmCTestGenericHandler
 {
 public:
-  cmTypeMacro(cmCTestBuildAndTestHandler, cmCTestGenericHandler);
+  typedef cmCTestGenericHandler Superclass;
 
   /*
    * The main entry point for this class
diff --git a/Source/CTest/cmCTestBuildCommand.h b/Source/CTest/cmCTestBuildCommand.h
index 0aaf623..9cc6f7e 100644
--- a/Source/CTest/cmCTestBuildCommand.h
+++ b/Source/CTest/cmCTestBuildCommand.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestHandlerCommand.h"
-#include "cmTypeMacro.h"
 
 #include <string>
 #include <vector>
@@ -47,8 +46,6 @@ public:
   bool InitialPass(std::vector<std::string> const& args,
                    cmExecutionStatus& status) CM_OVERRIDE;
 
-  cmTypeMacro(cmCTestBuildCommand, cmCTestHandlerCommand);
-
   cmGlobalGenerator* GlobalGenerator;
 
 protected:
diff --git a/Source/CTest/cmCTestBuildHandler.cxx b/Source/CTest/cmCTestBuildHandler.cxx
index 7b4d994..1868a1e 100644
--- a/Source/CTest/cmCTestBuildHandler.cxx
+++ b/Source/CTest/cmCTestBuildHandler.cxx
@@ -7,6 +7,7 @@
 #include "cmFileTimeComparison.h"
 #include "cmGeneratedFileStream.h"
 #include "cmMakefile.h"
+#include "cmProcessOutput.h"
 #include "cmSystemTools.h"
 #include "cmXMLWriter.h"
 
@@ -505,7 +506,7 @@ public:
     : FTC(CM_NULLPTR)
   {
   }
-  bool operator()(std::string const& l, std::string const& r)
+  bool operator()(std::string const& l, std::string const& r) const
   {
     // Order files by modification time.  Use lexicographic order
     // among files with the same time.
@@ -765,7 +766,7 @@ void cmCTestBuildHandler::LaunchHelper::WriteScrapeMatchers(
 
 int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
                                         const char* dir, int timeout,
-                                        std::ostream& ofs)
+                                        std::ostream& ofs, Encoding encoding)
 {
   // First generate the command and arguments
   std::vector<std::string> args = cmSystemTools::ParseArguments(command);
@@ -809,6 +810,8 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
 
   char* data;
   int length;
+  cmProcessOutput processOutput(encoding);
+  std::string strdata;
   cmCTestOptionalLog(
     this->CTest, HANDLER_PROGRESS_OUTPUT, "   Each symbol represents "
       << tick_len << " bytes of output." << std::endl
@@ -842,13 +845,25 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
 
     // Process the chunk of data
     if (res == cmsysProcess_Pipe_STDERR) {
-      this->ProcessBuffer(data, length, tick, tick_len, ofs,
+      processOutput.DecodeText(data, length, strdata, 1);
+      this->ProcessBuffer(strdata.c_str(), strdata.size(), tick, tick_len, ofs,
                           &this->BuildProcessingErrorQueue);
     } else {
-      this->ProcessBuffer(data, length, tick, tick_len, ofs,
+      processOutput.DecodeText(data, length, strdata, 2);
+      this->ProcessBuffer(strdata.c_str(), strdata.size(), tick, tick_len, ofs,
                           &this->BuildProcessingQueue);
     }
   }
+  processOutput.DecodeText(std::string(), strdata, 1);
+  if (!strdata.empty()) {
+    this->ProcessBuffer(strdata.c_str(), strdata.size(), tick, tick_len, ofs,
+                        &this->BuildProcessingErrorQueue);
+  }
+  processOutput.DecodeText(std::string(), strdata, 2);
+  if (!strdata.empty()) {
+    this->ProcessBuffer(strdata.c_str(), strdata.size(), tick, tick_len, ofs,
+                        &this->BuildProcessingQueue);
+  }
 
   this->ProcessBuffer(CM_NULLPTR, 0, tick, tick_len, ofs,
                       &this->BuildProcessingQueue);
@@ -920,7 +935,7 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
 //######################################################################
 //######################################################################
 
-void cmCTestBuildHandler::ProcessBuffer(const char* data, int length,
+void cmCTestBuildHandler::ProcessBuffer(const char* data, size_t length,
                                         size_t& tick, size_t tick_len,
                                         std::ostream& ofs,
                                         t_BuildProcessingQueueType* queue)
@@ -933,7 +948,7 @@ void cmCTestBuildHandler::ProcessBuffer(const char* data, int length,
   this->BuildOutputLogSize += length;
 
   // until there are any lines left in the buffer
-  while (1) {
+  while (true) {
     // Find the end of line
     t_BuildProcessingQueueType::iterator it;
     for (it = queue->begin(); it != queue->end(); ++it) {
diff --git a/Source/CTest/cmCTestBuildHandler.h b/Source/CTest/cmCTestBuildHandler.h
index 16563ce..a2f6112 100644
--- a/Source/CTest/cmCTestBuildHandler.h
+++ b/Source/CTest/cmCTestBuildHandler.h
@@ -6,8 +6,8 @@
 #include <cmConfigure.h>
 
 #include "cmCTestGenericHandler.h"
-#include "cmTypeMacro.h"
 
+#include <cmProcessOutput.h>
 #include <cmsys/RegularExpression.hxx>
 #include <deque>
 #include <iosfwd>
@@ -25,7 +25,8 @@ class cmXMLWriter;
 class cmCTestBuildHandler : public cmCTestGenericHandler
 {
 public:
-  cmTypeMacro(cmCTestBuildHandler, cmCTestGenericHandler);
+  typedef cmCTestGenericHandler Superclass;
+  typedef cmProcessOutput::Encoding Encoding;
 
   /*
    * The main entry point for this class
@@ -50,7 +51,8 @@ private:
   //! Run command specialized for make and configure. Returns process status
   // and retVal is return value or exception.
   int RunMakeCommand(const char* command, int* retVal, const char* dir,
-                     int timeout, std::ostream& ofs);
+                     int timeout, std::ostream& ofs,
+                     Encoding encoding = cmProcessOutput::Auto);
 
   enum
   {
@@ -108,7 +110,7 @@ private:
 
   typedef std::deque<char> t_BuildProcessingQueueType;
 
-  void ProcessBuffer(const char* data, int length, size_t& tick,
+  void ProcessBuffer(const char* data, size_t length, size_t& tick,
                      size_t tick_len, std::ostream& ofs,
                      t_BuildProcessingQueueType* queue);
   int ProcessSingleLine(const char* data);
diff --git a/Source/CTest/cmCTestCommand.h b/Source/CTest/cmCTestCommand.h
index 2b9b93b..6fc237a 100644
--- a/Source/CTest/cmCTestCommand.h
+++ b/Source/CTest/cmCTestCommand.h
@@ -26,8 +26,6 @@ public:
 
   cmCTest* CTest;
   cmCTestScriptHandler* CTestScriptHandler;
-
-  cmTypeMacro(cmCTestCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/CTest/cmCTestConfigureCommand.cxx b/Source/CTest/cmCTestConfigureCommand.cxx
index 62802ef..73e893d 100644
--- a/Source/CTest/cmCTestConfigureCommand.cxx
+++ b/Source/CTest/cmCTestConfigureCommand.cxx
@@ -102,6 +102,10 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
         cmakeConfigureCommand += "\"";
       }
 
+      if (this->Makefile->IsOn("CTEST_USE_LAUNCHERS")) {
+        cmakeConfigureCommand += " \"-DCTEST_USE_LAUNCHERS:BOOL=TRUE\"";
+      }
+
       cmakeConfigureCommand += " \"-G";
       cmakeConfigureCommand += cmakeGeneratorName;
       cmakeConfigureCommand += "\"";
diff --git a/Source/CTest/cmCTestConfigureCommand.h b/Source/CTest/cmCTestConfigureCommand.h
index 8bc69fe..22d1217 100644
--- a/Source/CTest/cmCTestConfigureCommand.h
+++ b/Source/CTest/cmCTestConfigureCommand.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestHandlerCommand.h"
-#include "cmTypeMacro.h"
 
 #include <string>
 
@@ -39,8 +38,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "ctest_configure"; }
 
-  cmTypeMacro(cmCTestConfigureCommand, cmCTestHandlerCommand);
-
 protected:
   cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
 
diff --git a/Source/CTest/cmCTestConfigureHandler.h b/Source/CTest/cmCTestConfigureHandler.h
index 913e5c9..7fa95ed 100644
--- a/Source/CTest/cmCTestConfigureHandler.h
+++ b/Source/CTest/cmCTestConfigureHandler.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestGenericHandler.h"
-#include "cmTypeMacro.h"
 
 /** \class cmCTestConfigureHandler
  * \brief A class that handles ctest -S invocations
@@ -15,7 +14,7 @@
 class cmCTestConfigureHandler : public cmCTestGenericHandler
 {
 public:
-  cmTypeMacro(cmCTestConfigureHandler, cmCTestGenericHandler);
+  typedef cmCTestGenericHandler Superclass;
 
   /*
    * The main entry point for this class
diff --git a/Source/CTest/cmCTestCoverageCommand.h b/Source/CTest/cmCTestCoverageCommand.h
index d54e68d..bf42aa1 100644
--- a/Source/CTest/cmCTestCoverageCommand.h
+++ b/Source/CTest/cmCTestCoverageCommand.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestHandlerCommand.h"
-#include "cmTypeMacro.h"
 
 #include <set>
 #include <string>
@@ -40,7 +39,7 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "ctest_coverage"; }
 
-  cmTypeMacro(cmCTestCoverageCommand, cmCTestHandlerCommand);
+  typedef cmCTestHandlerCommand Superclass;
 
 protected:
   cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
diff --git a/Source/CTest/cmCTestCoverageHandler.cxx b/Source/CTest/cmCTestCoverageHandler.cxx
index b7ac969..989c096 100644
--- a/Source/CTest/cmCTestCoverageHandler.cxx
+++ b/Source/CTest/cmCTestCoverageHandler.cxx
@@ -977,7 +977,7 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
 
   std::set<std::string> missingFiles;
 
-  std::string actualSourceFile = "";
+  std::string actualSourceFile;
   cmCTestOptionalLog(
     this->CTest, HANDLER_OUTPUT,
     "   Processing coverage (each . represents one file):" << std::endl,
@@ -1006,8 +1006,8 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
     cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                        command << std::endl, this->Quiet);
 
-    std::string output = "";
-    std::string errors = "";
+    std::string output;
+    std::string errors;
     int retVal = 0;
     *cont->OFS << "* Run coverage for: " << fileDir << std::endl;
     *cont->OFS << "  Command: " << command << std::endl;
@@ -1344,7 +1344,7 @@ int cmCTestCoverageHandler::HandleLCovCoverage(
 
   std::set<std::string> missingFiles;
 
-  std::string actualSourceFile = "";
+  std::string actualSourceFile;
   cmCTestOptionalLog(
     this->CTest, HANDLER_OUTPUT,
     "   Processing coverage (each . represents one file):" << std::endl,
@@ -1371,8 +1371,8 @@ int cmCTestCoverageHandler::HandleLCovCoverage(
     cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                        command << std::endl, this->Quiet);
 
-    std::string output = "";
-    std::string errors = "";
+    std::string output;
+    std::string errors;
     int retVal = 0;
     *cont->OFS << "* Run coverage for: " << fileDir << std::endl;
     *cont->OFS << "  Command: " << command << std::endl;
diff --git a/Source/CTest/cmCTestCoverageHandler.h b/Source/CTest/cmCTestCoverageHandler.h
index 062f971..339b5d7 100644
--- a/Source/CTest/cmCTestCoverageHandler.h
+++ b/Source/CTest/cmCTestCoverageHandler.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestGenericHandler.h"
-#include "cmTypeMacro.h"
 
 #include <cmsys/RegularExpression.hxx>
 #include <iosfwd>
@@ -38,7 +37,7 @@ public:
 class cmCTestCoverageHandler : public cmCTestGenericHandler
 {
 public:
-  cmTypeMacro(cmCTestCoverageHandler, cmCTestGenericHandler);
+  typedef cmCTestGenericHandler Superclass;
 
   /*
    * The main entry point for this class
diff --git a/Source/CTest/cmCTestCurl.cxx b/Source/CTest/cmCTestCurl.cxx
index a3c13c4..ab1412d 100644
--- a/Source/CTest/cmCTestCurl.cxx
+++ b/Source/CTest/cmCTestCurl.cxx
@@ -19,6 +19,7 @@ cmCTestCurl::cmCTestCurl(cmCTest* ctest)
   // default is to verify https
   this->VerifyPeerOff = false;
   this->VerifyHostOff = false;
+  this->Quiet = false;
   this->TimeOutSeconds = 0;
   this->Curl = curl_easy_init();
 }
@@ -38,8 +39,8 @@ std::string cmCTestCurl::Escape(std::string const& source)
 }
 
 namespace {
-static size_t curlWriteMemoryCallback(void* ptr, size_t size, size_t nmemb,
-                                      void* data)
+size_t curlWriteMemoryCallback(void* ptr, size_t size, size_t nmemb,
+                               void* data)
 {
   int realsize = (int)(size * nmemb);
 
@@ -49,8 +50,8 @@ static size_t curlWriteMemoryCallback(void* ptr, size_t size, size_t nmemb,
   return realsize;
 }
 
-static size_t curlDebugCallback(CURL* /*unused*/, curl_infotype /*unused*/,
-                                char* chPtr, size_t size, void* data)
+size_t curlDebugCallback(CURL* /*unused*/, curl_infotype /*unused*/,
+                         char* chPtr, size_t size, void* data)
 {
   std::vector<char>* vec = static_cast<std::vector<char>*>(data);
   vec->insert(vec->end(), chPtr, chPtr + size);
@@ -96,6 +97,13 @@ bool cmCTestCurl::InitCurl()
   }
   // enable HTTP ERROR parsing
   curl_easy_setopt(this->Curl, CURLOPT_FAILONERROR, 1);
+
+  // if there is little to no activity for too long stop submitting
+  if (this->TimeOutSeconds) {
+    curl_easy_setopt(this->Curl, CURLOPT_LOW_SPEED_LIMIT, 1);
+    curl_easy_setopt(this->Curl, CURLOPT_LOW_SPEED_TIME, this->TimeOutSeconds);
+  }
+
   return true;
 }
 
@@ -110,12 +118,7 @@ bool cmCTestCurl::UploadFile(std::string const& local_file,
   }
   /* enable uploading */
   curl_easy_setopt(this->Curl, CURLOPT_UPLOAD, 1);
-  // if there is little to no activity for too long stop submitting
-  if (this->TimeOutSeconds) {
-    ::curl_easy_setopt(this->Curl, CURLOPT_LOW_SPEED_LIMIT, 1);
-    ::curl_easy_setopt(this->Curl, CURLOPT_LOW_SPEED_TIME,
-                       this->TimeOutSeconds);
-  }
+
   /* HTTP PUT please */
   ::curl_easy_setopt(this->Curl, CURLOPT_PUT, 1);
   ::curl_easy_setopt(this->Curl, CURLOPT_VERBOSE, 1);
@@ -157,13 +160,14 @@ bool cmCTestCurl::UploadFile(std::string const& local_file,
 
   if (!responseData.empty()) {
     response = std::string(responseData.begin(), responseData.end());
-    cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Curl response: ["
-                 << response << "]\n");
+    cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
+                       "Curl response: [" << response << "]\n", this->Quiet);
   }
   std::string curlDebug;
   if (!debugData.empty()) {
     curlDebug = std::string(debugData.begin(), debugData.end());
-    cmCTestLog(this->CTest, DEBUG, "Curl debug: [" << curlDebug << "]\n");
+    cmCTestOptionalLog(this->CTest, DEBUG,
+                       "Curl debug: [" << curlDebug << "]\n", this->Quiet);
   }
   if (response.empty()) {
     cmCTestLog(this->CTest, ERROR_MESSAGE, "No response from server.\n"
@@ -177,9 +181,10 @@ bool cmCTestCurl::HttpRequest(std::string const& url,
                               std::string const& fields, std::string& response)
 {
   response = "";
-  cmCTestLog(this->CTest, DEBUG, "HttpRequest\n"
-               << "url: " << url << "\n"
-               << "fields " << fields << "\n");
+  cmCTestOptionalLog(this->CTest, DEBUG, "HttpRequest\n"
+                       << "url: " << url << "\n"
+                       << "fields " << fields << "\n",
+                     this->Quiet);
   if (!this->InitCurl()) {
     cmCTestLog(this->CTest, ERROR_MESSAGE, "Initialization of curl failed");
     return false;
@@ -202,13 +207,16 @@ bool cmCTestCurl::HttpRequest(std::string const& url,
 
   if (!responseData.empty()) {
     response = std::string(responseData.begin(), responseData.end());
-    cmCTestLog(this->CTest, DEBUG, "Curl response: [" << response << "]\n");
+    cmCTestOptionalLog(this->CTest, DEBUG,
+                       "Curl response: [" << response << "]\n", this->Quiet);
   }
   if (!debugData.empty()) {
     std::string curlDebug = std::string(debugData.begin(), debugData.end());
-    cmCTestLog(this->CTest, DEBUG, "Curl debug: [" << curlDebug << "]\n");
+    cmCTestOptionalLog(this->CTest, DEBUG,
+                       "Curl debug: [" << curlDebug << "]\n", this->Quiet);
   }
-  cmCTestLog(this->CTest, DEBUG, "Curl res: " << res << "\n");
+  cmCTestOptionalLog(this->CTest, DEBUG, "Curl res: " << res << "\n",
+                     this->Quiet);
   return (res == 0);
 }
 
diff --git a/Source/CTest/cmCTestCurl.h b/Source/CTest/cmCTestCurl.h
index 17fbcff..cdce393 100644
--- a/Source/CTest/cmCTestCurl.h
+++ b/Source/CTest/cmCTestCurl.h
@@ -25,6 +25,7 @@ public:
   void SetCurlOptions(std::vector<std::string> const& args);
   void SetUseHttp10On() { this->UseHttp10 = true; }
   void SetTimeOutSeconds(int s) { this->TimeOutSeconds = s; }
+  void SetQuiet(bool b) { this->Quiet = b; }
   std::string Escape(std::string const& source);
 
 protected:
@@ -40,6 +41,7 @@ private:
   bool VerifyHostOff;
   bool VerifyPeerOff;
   bool UseHttp10;
+  bool Quiet;
   int TimeOutSeconds;
 };
 
diff --git a/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h b/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h
index 8b5d5a4..4c1438b 100644
--- a/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h
+++ b/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestCommand.h"
-#include "cmTypeMacro.h"
 
 #include <string>
 #include <vector>
@@ -51,8 +50,6 @@ public:
   {
     return "ctest_empty_binary_directory";
   }
-
-  cmTypeMacro(cmCTestEmptyBinaryDirectoryCommand, cmCTestCommand);
 };
 
 #endif
diff --git a/Source/CTest/cmCTestGIT.cxx b/Source/CTest/cmCTestGIT.cxx
index 1bc1851..d30f6b3 100644
--- a/Source/CTest/cmCTestGIT.cxx
+++ b/Source/CTest/cmCTestGIT.cxx
@@ -2,12 +2,6 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestGIT.h"
 
-#include "cmAlgorithms.h"
-#include "cmCTest.h"
-#include "cmCTestVC.h"
-#include "cmProcessTools.h"
-#include "cmSystemTools.h"
-
 #include <cmsys/FStream.hxx>
 #include <cmsys/Process.h>
 #include <ctype.h>
@@ -16,6 +10,13 @@
 #include <time.h>
 #include <vector>
 
+#include "cmAlgorithms.h"
+#include "cmCTest.h"
+#include "cmCTestVC.h"
+#include "cmProcessOutput.h"
+#include "cmProcessTools.h"
+#include "cmSystemTools.h"
+
 static unsigned int cmCTestGITVersion(unsigned int epic, unsigned int major,
                                       unsigned int minor, unsigned int fix)
 {
@@ -91,7 +92,8 @@ std::string cmCTestGIT::FindGitDir()
   std::string git_dir_line;
   OneLineParser rev_parse_out(this, "rev-parse-out> ", git_dir_line);
   OutputLogger rev_parse_err(this->Log, "rev-parse-err> ");
-  if (this->RunChild(git_rev_parse, &rev_parse_out, &rev_parse_err)) {
+  if (this->RunChild(git_rev_parse, &rev_parse_out, &rev_parse_err, CM_NULLPTR,
+                     cmProcessOutput::UTF8)) {
     git_dir = git_dir_line;
   }
   if (git_dir.empty()) {
@@ -114,7 +116,8 @@ std::string cmCTestGIT::FindGitDir()
                                 0 };
       OneLineParser cygpath_out(this, "cygpath-out> ", git_dir_line);
       OutputLogger cygpath_err(this->Log, "cygpath-err> ");
-      if (this->RunChild(cygpath, &cygpath_out, &cygpath_err)) {
+      if (this->RunChild(cygpath, &cygpath_out, &cygpath_err, CM_NULLPTR,
+                         cmProcessOutput::UTF8)) {
         git_dir = git_dir_line;
       }
     }
@@ -134,7 +137,8 @@ std::string cmCTestGIT::FindTopDir()
   std::string cdup;
   OneLineParser rev_parse_out(this, "rev-parse-out> ", cdup);
   OutputLogger rev_parse_err(this->Log, "rev-parse-err> ");
-  if (this->RunChild(git_rev_parse, &rev_parse_out, &rev_parse_err) &&
+  if (this->RunChild(git_rev_parse, &rev_parse_out, &rev_parse_err, CM_NULLPTR,
+                     cmProcessOutput::UTF8) &&
       !cdup.empty()) {
     top_dir += "/";
     top_dir += cdup;
@@ -624,7 +628,7 @@ void cmCTestGIT::LoadRevisions()
 
   CommitParser out(this, "dt-out> ");
   OutputLogger err(this->Log, "dt-err> ");
-  this->RunProcess(cp, &out, &err);
+  this->RunProcess(cp, &out, &err, cmProcessOutput::UTF8);
 
   // Send one extra zero-byte to terminate the last record.
   out.Process("", 1);
@@ -641,14 +645,16 @@ void cmCTestGIT::LoadModifications()
                                      CM_NULLPTR };
   OutputLogger ui_out(this->Log, "ui-out> ");
   OutputLogger ui_err(this->Log, "ui-err> ");
-  this->RunChild(git_update_index, &ui_out, &ui_err);
+  this->RunChild(git_update_index, &ui_out, &ui_err, CM_NULLPTR,
+                 cmProcessOutput::UTF8);
 
   // Use 'git diff-index' to get modified files.
   const char* git_diff_index[] = { git,    "diff-index", "-z",
                                    "HEAD", "--",         CM_NULLPTR };
   DiffParser out(this, "di-out> ");
   OutputLogger err(this->Log, "di-err> ");
-  this->RunChild(git_diff_index, &out, &err);
+  this->RunChild(git_diff_index, &out, &err, CM_NULLPTR,
+                 cmProcessOutput::UTF8);
 
   for (std::vector<Change>::const_iterator ci = out.Changes.begin();
        ci != out.Changes.end(); ++ci) {
diff --git a/Source/CTest/cmCTestGenericHandler.cxx b/Source/CTest/cmCTestGenericHandler.cxx
index c093cc6..7638f45 100644
--- a/Source/CTest/cmCTestGenericHandler.cxx
+++ b/Source/CTest/cmCTestGenericHandler.cxx
@@ -2,12 +2,13 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestGenericHandler.h"
 
-#include "cmCTest.h"
-#include "cmSystemTools.h"
-
+#include <cmConfigure.h>
 #include <sstream>
 #include <utility>
 
+#include "cmCTest.h"
+#include "cmSystemTools.h"
+
 cmCTestGenericHandler::cmCTestGenericHandler()
 {
   this->HandlerVerbose = cmSystemTools::OUTPUT_NONE;
diff --git a/Source/CTest/cmCTestGenericHandler.h b/Source/CTest/cmCTestGenericHandler.h
index b2ab1d2..2ebbe70 100644
--- a/Source/CTest/cmCTestGenericHandler.h
+++ b/Source/CTest/cmCTestGenericHandler.h
@@ -3,17 +3,16 @@
 #ifndef cmCTestGenericHandler_h
 #define cmCTestGenericHandler_h
 
-#include <cmConfigure.h>
-
-#include "cmCTest.h"
-#include "cmObject.h"
-#include "cmSystemTools.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <map>
 #include <stddef.h>
 #include <string>
 #include <vector>
 
+#include "cmCTest.h"
+#include "cmSystemTools.h"
+
 class cmCTestCommand;
 class cmGeneratedFileStream;
 class cmMakefile;
@@ -22,7 +21,7 @@ class cmMakefile;
  * \brief A superclass of all CTest Handlers
  *
  */
-class cmCTestGenericHandler : public cmObject
+class cmCTestGenericHandler
 {
 public:
   /**
@@ -70,7 +69,7 @@ public:
    * Construct handler
    */
   cmCTestGenericHandler();
-  ~cmCTestGenericHandler() CM_OVERRIDE;
+  virtual ~cmCTestGenericHandler();
 
   typedef std::map<std::string, std::string> t_StringToString;
 
diff --git a/Source/CTest/cmCTestHandlerCommand.cxx b/Source/CTest/cmCTestHandlerCommand.cxx
index 2e5b56a..a989b12 100644
--- a/Source/CTest/cmCTestHandlerCommand.cxx
+++ b/Source/CTest/cmCTestHandlerCommand.cxx
@@ -226,6 +226,7 @@ bool cmCTestHandlerCommand::InitialPass(std::vector<std::string> const& args,
     this->Makefile->AddDefinition(this->Values[ct_RETURN_VALUE],
                                   str.str().c_str());
   }
+  this->ProcessAdditionalValues(handler);
   // log the error message if there was an error
   if (capureCMakeError) {
     const char* returnString = "0";
@@ -246,6 +247,10 @@ bool cmCTestHandlerCommand::InitialPass(std::vector<std::string> const& args,
   return true;
 }
 
+void cmCTestHandlerCommand::ProcessAdditionalValues(cmCTestGenericHandler*)
+{
+}
+
 bool cmCTestHandlerCommand::CheckArgumentKeyword(std::string const& arg)
 {
   // Look for non-value arguments common to all commands.
diff --git a/Source/CTest/cmCTestHandlerCommand.h b/Source/CTest/cmCTestHandlerCommand.h
index 3fd384f..c86841f 100644
--- a/Source/CTest/cmCTestHandlerCommand.h
+++ b/Source/CTest/cmCTestHandlerCommand.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestCommand.h"
-#include "cmTypeMacro.h"
 
 #include <stddef.h>
 #include <string>
@@ -32,8 +31,6 @@ public:
   bool InitialPass(std::vector<std::string> const& args,
                    cmExecutionStatus& status) CM_OVERRIDE;
 
-  cmTypeMacro(cmCTestHandlerCommand, cmCTestCommand);
-
   enum
   {
     ct_NONE,
@@ -48,6 +45,8 @@ public:
 protected:
   virtual cmCTestGenericHandler* InitializeHandler() = 0;
 
+  virtual void ProcessAdditionalValues(cmCTestGenericHandler* handler);
+
   // Command argument handling.
   virtual bool CheckArgumentKeyword(std::string const& arg);
   virtual bool CheckArgumentValue(std::string const& arg);
diff --git a/Source/CTest/cmCTestLaunch.cxx b/Source/CTest/cmCTestLaunch.cxx
index e5c50b2..03e0319 100644
--- a/Source/CTest/cmCTestLaunch.cxx
+++ b/Source/CTest/cmCTestLaunch.cxx
@@ -4,23 +4,24 @@
 
 #include <cmConfigure.h>
 
-#include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
-#include "cmState.h"
-#include "cmSystemTools.h"
-#include "cmXMLWriter.h"
-#include "cmake.h"
-
-#include <cm_auto_ptr.hxx>
 #include <cmsys/FStream.hxx>
-#include <cmsys/MD5.h>
 #include <cmsys/Process.h>
 #include <cmsys/RegularExpression.hxx>
 #include <iostream>
 #include <stdlib.h>
 #include <string.h>
 
+#include "cmCryptoHash.h"
+#include "cmGeneratedFileStream.h"
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmProcessOutput.h"
+#include "cmStateSnapshot.h"
+#include "cmSystemTools.h"
+#include "cmXMLWriter.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
+
 #ifdef _WIN32
 #include <fcntl.h> // for _O_BINARY
 #include <io.h>    // for _setmode
@@ -167,17 +168,14 @@ void cmCTestLaunch::ComputeFileNames()
 
   // We hash the input command working dir and command line to obtain
   // a repeatable and (probably) unique name for log files.
-  char hash[32];
-  cmsysMD5* md5 = cmsysMD5_New();
-  cmsysMD5_Initialize(md5);
-  cmsysMD5_Append(md5, (unsigned char const*)(this->CWD.c_str()), -1);
+  cmCryptoHash md5(cmCryptoHash::AlgoMD5);
+  md5.Initialize();
+  md5.Append(this->CWD);
   for (std::vector<std::string>::const_iterator ai = this->RealArgs.begin();
        ai != this->RealArgs.end(); ++ai) {
-    cmsysMD5_Append(md5, (unsigned char const*)ai->c_str(), -1);
+    md5.Append(*ai);
   }
-  cmsysMD5_FinalizeHex(md5, hash);
-  cmsysMD5_Delete(md5);
-  this->LogHash.assign(hash, 32);
+  this->LogHash = md5.FinalizeHex();
 
   // We store stdout and stderr in temporary log files.
   this->LogOut = this->LogDir;
@@ -228,17 +226,31 @@ void cmCTestLaunch::RunChild()
   if (!this->Passthru) {
     char* data = CM_NULLPTR;
     int length = 0;
+    cmProcessOutput processOutput;
+    std::string strdata;
     while (int p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
       if (p == cmsysProcess_Pipe_STDOUT) {
-        fout.write(data, length);
-        std::cout.write(data, length);
+        processOutput.DecodeText(data, length, strdata, 1);
+        fout.write(strdata.c_str(), strdata.size());
+        std::cout.write(strdata.c_str(), strdata.size());
         this->HaveOut = true;
       } else if (p == cmsysProcess_Pipe_STDERR) {
-        ferr.write(data, length);
-        std::cerr.write(data, length);
+        processOutput.DecodeText(data, length, strdata, 2);
+        ferr.write(strdata.c_str(), strdata.size());
+        std::cerr.write(strdata.c_str(), strdata.size());
         this->HaveErr = true;
       }
     }
+    processOutput.DecodeText(std::string(), strdata, 1);
+    if (!strdata.empty()) {
+      fout.write(strdata.c_str(), strdata.size());
+      std::cout.write(strdata.c_str(), strdata.size());
+    }
+    processOutput.DecodeText(std::string(), strdata, 2);
+    if (!strdata.empty()) {
+      ferr.write(strdata.c_str(), strdata.size());
+      std::cerr.write(strdata.c_str(), strdata.size());
+    }
   }
 
   // Wait for the real command to finish.
diff --git a/Source/CTest/cmCTestMemCheckCommand.cxx b/Source/CTest/cmCTestMemCheckCommand.cxx
index 05d0a53..fd7c3a9 100644
--- a/Source/CTest/cmCTestMemCheckCommand.cxx
+++ b/Source/CTest/cmCTestMemCheckCommand.cxx
@@ -2,8 +2,20 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestMemCheckCommand.h"
 
+#include <sstream>
+#include <vector>
+
 #include "cmCTest.h"
 #include "cmCTestGenericHandler.h"
+#include "cmCTestMemCheckHandler.h"
+#include "cmMakefile.h"
+
+cmCTestMemCheckCommand::cmCTestMemCheckCommand()
+{
+  this->Arguments[ctm_DEFECT_COUNT] = "DEFECT_COUNT";
+  this->Arguments[ctm_LAST] = CM_NULLPTR;
+  this->Last = ctm_LAST;
+}
 
 cmCTestGenericHandler* cmCTestMemCheckCommand::InitializeActualHandler()
 {
@@ -28,3 +40,14 @@ cmCTestGenericHandler* cmCTestMemCheckCommand::InitializeActualHandler()
   handler->SetQuiet(this->Quiet);
   return handler;
 }
+
+void cmCTestMemCheckCommand::ProcessAdditionalValues(
+  cmCTestGenericHandler* handler)
+{
+  if (this->Values[ctm_DEFECT_COUNT] && *this->Values[ctm_DEFECT_COUNT]) {
+    std::ostringstream str;
+    str << static_cast<cmCTestMemCheckHandler*>(handler)->GetDefectCount();
+    this->Makefile->AddDefinition(this->Values[ctm_DEFECT_COUNT],
+                                  str.str().c_str());
+  }
+}
diff --git a/Source/CTest/cmCTestMemCheckCommand.h b/Source/CTest/cmCTestMemCheckCommand.h
index d3b8be7..458ebb0 100644
--- a/Source/CTest/cmCTestMemCheckCommand.h
+++ b/Source/CTest/cmCTestMemCheckCommand.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestTestCommand.h"
-#include "cmTypeMacro.h"
 
 #include <string>
 
@@ -21,7 +20,7 @@ class cmCommand;
 class cmCTestMemCheckCommand : public cmCTestTestCommand
 {
 public:
-  cmCTestMemCheckCommand() {}
+  cmCTestMemCheckCommand();
 
   /**
    * This is a virtual constructor for the command.
@@ -39,10 +38,16 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "ctest_memcheck"; }
 
-  cmTypeMacro(cmCTestMemCheckCommand, cmCTestTestCommand);
-
 protected:
   cmCTestGenericHandler* InitializeActualHandler() CM_OVERRIDE;
+
+  void ProcessAdditionalValues(cmCTestGenericHandler* handler) CM_OVERRIDE;
+
+  enum
+  {
+    ctm_DEFECT_COUNT = ctt_LAST,
+    ctm_LAST
+  };
 };
 
 #endif
diff --git a/Source/CTest/cmCTestMemCheckHandler.cxx b/Source/CTest/cmCTestMemCheckHandler.cxx
index b37db30..620e237 100644
--- a/Source/CTest/cmCTestMemCheckHandler.cxx
+++ b/Source/CTest/cmCTestMemCheckHandler.cxx
@@ -127,6 +127,7 @@ void cmCTestMemCheckHandler::Initialize()
   this->MemoryTesterOptions.clear();
   this->MemoryTesterStyle = UNKNOWN;
   this->MemoryTesterOutputFile = "";
+  this->DefectCount = 0;
 }
 
 int cmCTestMemCheckHandler::PreProcessHandler()
@@ -279,6 +280,11 @@ void cmCTestMemCheckHandler::PopulateCustomVectors(cmMakefile* mf)
                                      this->Quiet);
 }
 
+int cmCTestMemCheckHandler::GetDefectCount()
+{
+  return this->DefectCount;
+}
+
 void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml)
 {
   if (!this->CTest->GetProduceXML()) {
@@ -299,6 +305,9 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml)
     case cmCTestMemCheckHandler::ADDRESS_SANITIZER:
       xml.Attribute("Checker", "AddressSanitizer");
       break;
+    case cmCTestMemCheckHandler::LEAK_SANITIZER:
+      xml.Attribute("Checker", "LeakSanitizer");
+      break;
     case cmCTestMemCheckHandler::THREAD_SANITIZER:
       xml.Attribute("Checker", "ThreadSanitizer");
       break;
@@ -323,10 +332,8 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml)
   }
   xml.EndElement(); // TestList
   cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
-                     "-- Processing memory checking output: ", this->Quiet);
+                     "-- Processing memory checking output:\n", this->Quiet);
   size_t total = this->TestResults.size();
-  size_t step = total / 10;
-  size_t current = 0;
   for (cc = 0; cc < this->TestResults.size(); cc++) {
     cmCTestTestResult* result = &this->TestResults[cc];
     std::string memcheckstr;
@@ -341,20 +348,31 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml)
       static_cast<size_t>(this->CustomMaximumFailedTestOutputSize));
     this->WriteTestResultHeader(xml, result);
     xml.StartElement("Results");
+    int memoryErrors = 0;
     for (std::vector<int>::size_type kk = 0; kk < memcheckresults.size();
          ++kk) {
       if (memcheckresults[kk]) {
         xml.StartElement("Defect");
         xml.Attribute("type", this->ResultStringsLong[kk]);
         xml.Content(memcheckresults[kk]);
+        memoryErrors += memcheckresults[kk];
         xml.EndElement(); // Defect
       }
       this->GlobalResults[kk] += memcheckresults[kk];
     }
     xml.EndElement(); // Results
-
+    if (memoryErrors > 0) {
+      const int maxTestNameWidth = this->CTest->GetMaxTestNameWidth();
+      std::string outname = result->Name + " ";
+      outname.resize(maxTestNameWidth + 4, '.');
+      cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, cc + 1
+                           << "/" << total << " MemCheck: #"
+                           << result->TestCount << ": " << outname
+                           << "   Defects: " << memoryErrors << std::endl,
+                         this->Quiet);
+    }
     xml.StartElement("Log");
-    if (this->CTest->ShouldCompressMemCheckOutput()) {
+    if (this->CTest->ShouldCompressTestOutput()) {
       this->CTest->CompressString(memcheckstr);
       xml.Attribute("compression", "gzip");
       xml.Attribute("encoding", "base64");
@@ -363,23 +381,22 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml)
     xml.EndElement(); // Log
 
     this->WriteTestResultFooter(xml, result);
-    if (current < cc) {
-      cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "#" << std::flush,
-                         this->Quiet);
-      current += step;
-    }
   }
-  cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, std::endl, this->Quiet);
+  cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
+                     "MemCheck log files can be found here: "
+                     "( * corresponds to test number)"
+                       << std::endl,
+                     this->Quiet);
+  std::string output = this->MemoryTesterOutputFile;
+  cmSystemTools::ReplaceString(output, "??", "*");
+  cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, output << std::endl,
+                     this->Quiet);
   cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
                      "Memory checking results:" << std::endl, this->Quiet);
   xml.StartElement("DefectList");
   for (cc = 0; cc < this->GlobalResults.size(); cc++) {
     if (this->GlobalResults[cc]) {
-#ifdef cerr
-#undef cerr
-#endif
       std::cerr.width(35);
-#define cerr no_cerr
       cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
                          this->ResultStringsLong[cc]
                            << " - " << this->GlobalResults[cc] << std::endl,
@@ -445,6 +462,12 @@ bool cmCTestMemCheckHandler::InitializeMemoryChecking()
     this->LogWithPID = true; // even if we give the log file the pid is added
   }
   if (this->CTest->GetCTestConfiguration("MemoryCheckType") ==
+      "LeakSanitizer") {
+    this->MemoryTester = this->CTest->GetCTestConfiguration("CMakeCommand");
+    this->MemoryTesterStyle = cmCTestMemCheckHandler::LEAK_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");
     this->MemoryTesterStyle = cmCTestMemCheckHandler::THREAD_SANITIZER;
@@ -572,6 +595,7 @@ bool cmCTestMemCheckHandler::InitializeMemoryChecking()
     }
     // these are almost the same but the env var used is different
     case cmCTestMemCheckHandler::ADDRESS_SANITIZER:
+    case cmCTestMemCheckHandler::LEAK_SANITIZER:
     case cmCTestMemCheckHandler::THREAD_SANITIZER:
     case cmCTestMemCheckHandler::MEMORY_SANITIZER:
     case cmCTestMemCheckHandler::UB_SANITIZER: {
@@ -583,12 +607,24 @@ bool cmCTestMemCheckHandler::InitializeMemoryChecking()
       this->MemoryTesterDynamicOptions.push_back("-E");
       this->MemoryTesterDynamicOptions.push_back("env");
       std::string envVar;
-      std::string extraOptions =
-        this->CTest->GetCTestConfiguration("MemoryCheckSanitizerOptions");
+      std::string extraOptions;
+      std::string suppressionsOption;
+      if (!this->CTest->GetCTestConfiguration("MemoryCheckSanitizerOptions")
+             .empty()) {
+        extraOptions = ":" +
+          this->CTest->GetCTestConfiguration("MemoryCheckSanitizerOptions");
+      }
+      if (!this->CTest->GetCTestConfiguration("MemoryCheckSuppressionFile")
+             .empty()) {
+        suppressionsOption = ":suppressions=" +
+          this->CTest->GetCTestConfiguration("MemoryCheckSuppressionFile");
+      }
       if (this->MemoryTesterStyle ==
           cmCTestMemCheckHandler::ADDRESS_SANITIZER) {
         envVar = "ASAN_OPTIONS";
-        extraOptions += " detect_leaks=1";
+      } else if (this->MemoryTesterStyle ==
+                 cmCTestMemCheckHandler::LEAK_SANITIZER) {
+        envVar = "LSAN_OPTIONS";
       } else if (this->MemoryTesterStyle ==
                  cmCTestMemCheckHandler::THREAD_SANITIZER) {
         envVar = "TSAN_OPTIONS";
@@ -599,9 +635,12 @@ bool cmCTestMemCheckHandler::InitializeMemoryChecking()
                  cmCTestMemCheckHandler::UB_SANITIZER) {
         envVar = "UBSAN_OPTIONS";
       }
+      // Quote log_path with single quotes; see
+      // https://bugs.chromium.org/p/chromium/issues/detail?id=467936
       std::string outputFile =
-        envVar + "=log_path=\"" + this->MemoryTesterOutputFile + "\" ";
-      this->MemoryTesterEnvironmentVariable = outputFile + extraOptions;
+        envVar + "=log_path='" + this->MemoryTesterOutputFile + "'";
+      this->MemoryTesterEnvironmentVariable =
+        outputFile + suppressionsOption + extraOptions;
       break;
     }
     default:
@@ -630,6 +669,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckOutput(const std::string& str,
     case cmCTestMemCheckHandler::PURIFY:
       return this->ProcessMemCheckPurifyOutput(str, log, results);
     case cmCTestMemCheckHandler::ADDRESS_SANITIZER:
+    case cmCTestMemCheckHandler::LEAK_SANITIZER:
     case cmCTestMemCheckHandler::THREAD_SANITIZER:
     case cmCTestMemCheckHandler::MEMORY_SANITIZER:
     case cmCTestMemCheckHandler::UB_SANITIZER:
@@ -666,6 +706,9 @@ bool cmCTestMemCheckHandler::ProcessMemCheckSanitizerOutput(
     case cmCTestMemCheckHandler::ADDRESS_SANITIZER:
       regex = "ERROR: AddressSanitizer: (.*) on.*";
       break;
+    case cmCTestMemCheckHandler::LEAK_SANITIZER:
+      // use leakWarning regex
+      break;
     case cmCTestMemCheckHandler::THREAD_SANITIZER:
       regex = "WARNING: ThreadSanitizer: (.*) \\(pid=.*\\)";
       break;
@@ -706,6 +749,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckSanitizerOutput(
     ostr << *i << std::endl;
   }
   log = ostr.str();
+  this->DefectCount += defects;
   return defects == 0;
 }
 bool cmCTestMemCheckHandler::ProcessMemCheckPurifyOutput(
@@ -747,6 +791,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckPurifyOutput(
   }
 
   log = ostr.str();
+  this->DefectCount += defects;
   return defects == 0;
 }
 
@@ -882,6 +927,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckValgrindOutput(
                        << (cmSystemTools::GetTime() - sttime) << std::endl,
                      this->Quiet);
   log = ostr.str();
+  this->DefectCount += defects;
   return defects == 0;
 }
 
@@ -927,9 +973,9 @@ bool cmCTestMemCheckHandler::ProcessMemCheckBoundsCheckerOutput(
     // only put the output of Bounds Checker if there were
     // errors or leaks detected
     log = parser.Log;
-    return false;
   }
-  return true;
+  this->DefectCount += defects;
+  return defects == 0;
 }
 
 // PostProcessTest memcheck results
diff --git a/Source/CTest/cmCTestMemCheckHandler.h b/Source/CTest/cmCTestMemCheckHandler.h
index 8d678af..ff8b593 100644
--- a/Source/CTest/cmCTestMemCheckHandler.h
+++ b/Source/CTest/cmCTestMemCheckHandler.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestTestHandler.h"
-#include "cmTypeMacro.h"
 
 #include <string>
 #include <vector>
@@ -23,7 +22,7 @@ class cmCTestMemCheckHandler : public cmCTestTestHandler
   friend class cmCTestRunTest;
 
 public:
-  cmTypeMacro(cmCTestMemCheckHandler, cmCTestTestHandler);
+  typedef cmCTestTestHandler Superclass;
 
   void PopulateCustomVectors(cmMakefile* mf) CM_OVERRIDE;
 
@@ -31,6 +30,8 @@ public:
 
   void Initialize() CM_OVERRIDE;
 
+  int GetDefectCount();
+
 protected:
   int PreProcessHandler() CM_OVERRIDE;
   int PostProcessHandler() CM_OVERRIDE;
@@ -46,6 +47,7 @@ private:
     BOUNDS_CHECKER,
     // checkers after here do not use the standard error list
     ADDRESS_SANITIZER,
+    LEAK_SANITIZER,
     THREAD_SANITIZER,
     MEMORY_SANITIZER,
     UB_SANITIZER
@@ -106,6 +108,7 @@ private:
   std::vector<std::string> ResultStringsLong;
   std::vector<int> GlobalResults;
   bool LogWithPID; // does log file add pid
+  int DefectCount;
 
   std::vector<int>::size_type FindOrAddWarning(const std::string& warning);
   // initialize the ResultStrings and ResultStringsLong for
diff --git a/Source/CTest/cmCTestMultiProcessHandler.cxx b/Source/CTest/cmCTestMultiProcessHandler.cxx
index 1766aef..c1724ab 100644
--- a/Source/CTest/cmCTestMultiProcessHandler.cxx
+++ b/Source/CTest/cmCTestMultiProcessHandler.cxx
@@ -256,7 +256,7 @@ void cmCTestMultiProcessHandler::StartNextTests()
   bool allTestsFailedTestLoadCheck = false;
   bool usedFakeLoadForTesting = false;
   size_t minProcessorsRequired = this->ParallelLevel;
-  std::string testWithMinProcessors = "";
+  std::string testWithMinProcessors;
 
   cmsys::SystemInformation info;
 
diff --git a/Source/CTest/cmCTestReadCustomFilesCommand.h b/Source/CTest/cmCTestReadCustomFilesCommand.h
index 29eba90..e155595 100644
--- a/Source/CTest/cmCTestReadCustomFilesCommand.h
+++ b/Source/CTest/cmCTestReadCustomFilesCommand.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestCommand.h"
-#include "cmTypeMacro.h"
 
 #include <string>
 #include <vector>
@@ -46,8 +45,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "ctest_read_custom_files"; }
-
-  cmTypeMacro(cmCTestReadCustomFilesCommand, cmCTestCommand);
 };
 
 #endif
diff --git a/Source/CTest/cmCTestRunScriptCommand.h b/Source/CTest/cmCTestRunScriptCommand.h
index 2978bb9..01ed62e 100644
--- a/Source/CTest/cmCTestRunScriptCommand.h
+++ b/Source/CTest/cmCTestRunScriptCommand.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestCommand.h"
-#include "cmTypeMacro.h"
 
 #include <string>
 #include <vector>
@@ -47,8 +46,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "ctest_run_script"; }
-
-  cmTypeMacro(cmCTestRunScriptCommand, cmCTestCommand);
 };
 
 #endif
diff --git a/Source/CTest/cmCTestRunTest.cxx b/Source/CTest/cmCTestRunTest.cxx
index b30f6eb..ac1644f 100644
--- a/Source/CTest/cmCTestRunTest.cxx
+++ b/Source/CTest/cmCTestRunTest.cxx
@@ -119,10 +119,9 @@ void cmCTestRunTest::CompressOutput()
   strm.next_out = out;
   ret = deflate(&strm, Z_FINISH);
 
-  if (ret == Z_STREAM_ERROR || ret != Z_STREAM_END) {
+  if (ret != Z_STREAM_END) {
     cmCTestLog(this->CTest, ERROR_MESSAGE,
-               "Error during output "
-               "compression. Sending uncompressed output."
+               "Error during output compression. Sending uncompressed output."
                  << std::endl);
     delete[] out;
     return;
@@ -135,6 +134,7 @@ void cmCTestRunTest::CompressOutput()
 
   size_t rlen = cmsysBase64_Encode(out, strm.total_out, encoded_buffer, 1);
 
+  this->CompressedOutput.clear();
   for (size_t i = 0; i < rlen; i++) {
     this->CompressedOutput += encoded_buffer[i];
   }
@@ -153,7 +153,7 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started)
   if ((!this->TestHandler->MemCheck &&
        this->CTest->ShouldCompressTestOutput()) ||
       (this->TestHandler->MemCheck &&
-       this->CTest->ShouldCompressMemCheckOutput())) {
+       this->CTest->ShouldCompressTestOutput())) {
     this->CompressOutput();
   }
 
@@ -417,6 +417,7 @@ bool cmCTestRunTest::StartTest(size_t total)
                << std::setw(getNumWidth(this->TestHandler->GetMaxIndex()))
                << this->TestProperties->Index << ": "
                << this->TestProperties->Name << std::endl);
+  this->ProcessOutput.clear();
   this->ComputeArguments();
   std::vector<std::string>& args = this->TestProperties->Args;
   this->TestResult.Properties = this->TestProperties;
diff --git a/Source/CTest/cmCTestRunTest.h b/Source/CTest/cmCTestRunTest.h
index a10e271..ee4630a 100644
--- a/Source/CTest/cmCTestRunTest.h
+++ b/Source/CTest/cmCTestRunTest.h
@@ -5,11 +5,13 @@
 
 #include <cmConfigure.h> // IWYU pragma: keep
 
-#include <cmCTestTestHandler.h>
+#include <set>
 #include <stddef.h>
 #include <string>
 #include <vector>
 
+#include "cmCTestTestHandler.h"
+
 class cmCTest;
 class cmProcess;
 
diff --git a/Source/CTest/cmCTestSVN.cxx b/Source/CTest/cmCTestSVN.cxx
index fc405ca..410e0d4 100644
--- a/Source/CTest/cmCTestSVN.cxx
+++ b/Source/CTest/cmCTestSVN.cxx
@@ -523,8 +523,11 @@ private:
 
 void cmCTestSVN::LoadRepositories()
 {
+  if (!this->Repositories.empty()) {
+    return;
+  }
+
   // Info for root repository
-  this->Repositories.clear();
   this->Repositories.push_back(SVNInfo(""));
   this->RootInfo = &(this->Repositories.back());
 
diff --git a/Source/CTest/cmCTestScriptHandler.cxx b/Source/CTest/cmCTestScriptHandler.cxx
index 8848a70..b537242 100644
--- a/Source/CTest/cmCTestScriptHandler.cxx
+++ b/Source/CTest/cmCTestScriptHandler.cxx
@@ -2,6 +2,15 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestScriptHandler.h"
 
+#include <cmsys/Directory.hxx>
+#include <cmsys/Process.h>
+#include <map>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <utility>
+
 #include "cmCTest.h"
 #include "cmCTestBuildCommand.h"
 #include "cmCTestCommand.h"
@@ -22,18 +31,11 @@
 #include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
 #include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
 #include "cmSystemTools.h"
 #include "cmake.h"
 
-#include <cmsys/Directory.hxx>
-#include <cmsys/Process.h>
-#include <map>
-#include <sstream>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <utility>
-
 #ifdef _WIN32
 #include <windows.h>
 #else
@@ -280,7 +282,7 @@ void cmCTestScriptHandler::CreateCMake()
   this->CMake->AddCMakePaths();
   this->GlobalGenerator = new cmGlobalGenerator(this->CMake);
 
-  cmState::Snapshot snapshot = this->CMake->GetCurrentSnapshot();
+  cmStateSnapshot snapshot = this->CMake->GetCurrentSnapshot();
   std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
   snapshot.GetDirectory().SetCurrentSource(cwd);
   snapshot.GetDirectory().SetCurrentBinary(cwd);
diff --git a/Source/CTest/cmCTestScriptHandler.h b/Source/CTest/cmCTestScriptHandler.h
index 2bace58..47644be 100644
--- a/Source/CTest/cmCTestScriptHandler.h
+++ b/Source/CTest/cmCTestScriptHandler.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestGenericHandler.h"
-#include "cmTypeMacro.h"
 
 #include <string>
 #include <vector>
@@ -56,7 +55,7 @@ class cmake;
 class cmCTestScriptHandler : public cmCTestGenericHandler
 {
 public:
-  cmTypeMacro(cmCTestScriptHandler, cmCTestGenericHandler);
+  typedef cmCTestGenericHandler Superclass;
 
   /**
    * Add a script to run, and if is should run in the current process
diff --git a/Source/CTest/cmCTestSleepCommand.h b/Source/CTest/cmCTestSleepCommand.h
index b144012..1052f76 100644
--- a/Source/CTest/cmCTestSleepCommand.h
+++ b/Source/CTest/cmCTestSleepCommand.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestCommand.h"
-#include "cmTypeMacro.h"
 
 #include <string>
 #include <vector>
@@ -47,8 +46,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "ctest_sleep"; }
-
-  cmTypeMacro(cmCTestSleepCommand, cmCTestCommand);
 };
 
 #endif
diff --git a/Source/CTest/cmCTestStartCommand.h b/Source/CTest/cmCTestStartCommand.h
index 6bb0bc6..cc72d0c 100644
--- a/Source/CTest/cmCTestStartCommand.h
+++ b/Source/CTest/cmCTestStartCommand.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestCommand.h"
-#include "cmTypeMacro.h"
 
 #include <iosfwd>
 #include <string>
@@ -60,8 +59,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "ctest_start"; }
 
-  cmTypeMacro(cmCTestStartCommand, cmCTestCommand);
-
 private:
   bool InitialCheckout(std::ostream& ofs, std::string const& sourceDir);
   bool CreateNewTag;
diff --git a/Source/CTest/cmCTestSubmitCommand.cxx b/Source/CTest/cmCTestSubmitCommand.cxx
index 14b875f..5cf4ddc 100644
--- a/Source/CTest/cmCTestSubmitCommand.cxx
+++ b/Source/CTest/cmCTestSubmitCommand.cxx
@@ -157,6 +157,7 @@ bool cmCTestSubmitCommand::InitialPass(std::vector<std::string> const& args,
 bool cmCTestSubmitCommand::CheckArgumentKeyword(std::string const& arg)
 {
   if (this->CDashUpload) {
+    // Arguments specific to the CDASH_UPLOAD signature.
     if (arg == "CDASH_UPLOAD") {
       this->ArgumentDoing = ArgumentDoingCDashUpload;
       return true;
@@ -167,7 +168,7 @@ bool cmCTestSubmitCommand::CheckArgumentKeyword(std::string const& arg)
       return true;
     }
   } else {
-    // Look for arguments specific to this command.
+    // Arguments that cannot be used with CDASH_UPLOAD.
     if (arg == "PARTS") {
       this->ArgumentDoing = ArgumentDoingParts;
       this->PartsMentioned = true;
@@ -179,21 +180,21 @@ bool cmCTestSubmitCommand::CheckArgumentKeyword(std::string const& arg)
       this->FilesMentioned = true;
       return true;
     }
+  }
+  // Arguments used by both modes.
+  if (arg == "RETRY_COUNT") {
+    this->ArgumentDoing = ArgumentDoingRetryCount;
+    return true;
+  }
 
-    if (arg == "RETRY_COUNT") {
-      this->ArgumentDoing = ArgumentDoingRetryCount;
-      return true;
-    }
-
-    if (arg == "RETRY_DELAY") {
-      this->ArgumentDoing = ArgumentDoingRetryDelay;
-      return true;
-    }
+  if (arg == "RETRY_DELAY") {
+    this->ArgumentDoing = ArgumentDoingRetryDelay;
+    return true;
+  }
 
-    if (arg == "INTERNAL_TEST_CHECKSUM") {
-      this->InternalTest = true;
-      return true;
-    }
+  if (arg == "INTERNAL_TEST_CHECKSUM") {
+    this->InternalTest = true;
+    return true;
   }
 
   // Look for other arguments.
diff --git a/Source/CTest/cmCTestSubmitCommand.h b/Source/CTest/cmCTestSubmitCommand.h
index db8a604..f5b52c1 100644
--- a/Source/CTest/cmCTestSubmitCommand.h
+++ b/Source/CTest/cmCTestSubmitCommand.h
@@ -7,7 +7,6 @@
 
 #include "cmCTest.h"
 #include "cmCTestHandlerCommand.h"
-#include "cmTypeMacro.h"
 
 #include <set>
 #include <string>
@@ -55,7 +54,7 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "ctest_submit"; }
 
-  cmTypeMacro(cmCTestSubmitCommand, cmCTestHandlerCommand);
+  typedef cmCTestHandlerCommand Superclass;
 
 protected:
   cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
diff --git a/Source/CTest/cmCTestSubmitHandler.cxx b/Source/CTest/cmCTestSubmitHandler.cxx
index 06cd77f..5e5119d 100644
--- a/Source/CTest/cmCTestSubmitHandler.cxx
+++ b/Source/CTest/cmCTestSubmitHandler.cxx
@@ -2,24 +2,26 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestSubmitHandler.h"
 
+#include <cm_curl.h>
+#include <cm_jsoncpp_reader.h>
+#include <cm_jsoncpp_value.h>
+#include <cmsys/Process.h>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+
 #include "cmCTest.h"
 #include "cmCTestCurl.h"
 #include "cmCTestScriptHandler.h"
 #include "cmCurl.h"
 #include "cmGeneratedFileStream.h"
+#include "cmProcessOutput.h"
 #include "cmState.h"
 #include "cmSystemTools.h"
+#include "cmThirdParty.h"
 #include "cmXMLParser.h"
 #include "cmake.h"
 
-#include <cm_curl.h>
-#include <cm_jsoncpp_reader.h>
-#include <cm_jsoncpp_value.h>
-#include <cmsys/Process.h>
-#include <sstream>
-#include <stdio.h>
-#include <stdlib.h>
-
 #if defined(CTEST_USE_XMLRPC)
 #include "cmVersion.h"
 #include <cm_xmlrpc.h>
@@ -45,7 +47,6 @@ public:
   };
 
   StatusType Status;
-  std::string CDashVersion;
   std::string Filename;
   std::string MD5;
   std::string Message;
@@ -62,12 +63,10 @@ private:
     return val;
   }
 
-  void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
+  void StartElement(const std::string& /*name*/,
+                    const char** /*atts*/) CM_OVERRIDE
   {
     this->CurrentValue.clear();
-    if (name == "cdash") {
-      this->CDashVersion = this->FindAttribute(atts, "version");
-    }
   }
 
   void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
@@ -389,7 +388,7 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix,
       *this->LogFile << "\tUpload file: " << local_file << " to "
                      << remote_file << std::endl;
 
-      std::string ofile = "";
+      std::string ofile;
       for (kk = 0; kk < remote_file.size(); kk++) {
         char c = remote_file[kk];
         char hexCh[4] = { 0, 0, 0, 0 };
@@ -469,20 +468,6 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix,
       // Now run off and do what you've been told!
       res = ::curl_easy_perform(curl);
 
-      if (cmSystemTools::IsOn(this->GetOption("InternalTest")) &&
-          cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
-                                        this->CTest->GetCDashVersion().c_str(),
-                                        "1.7")) {
-        // mock failure output for internal test case
-        std::string mock_output =
-          "<cdash version=\"1.7.0\">\n"
-          "  <status>ERROR</status>\n"
-          "  <message>Checksum failed for file.</message>\n"
-          "</cdash>\n";
-        chunk.clear();
-        chunk.assign(mock_output.begin(), mock_output.end());
-      }
-
       if (!chunk.empty()) {
         cmCTestOptionalLog(this->CTest, DEBUG, "CURL output: ["
                              << cmCTestLogWrite(&*chunk.begin(), chunk.size())
@@ -597,7 +582,7 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix,
 void cmCTestSubmitHandler::ParseResponse(
   cmCTestSubmitHandlerVectorOfChar chunk)
 {
-  std::string output = "";
+  std::string output;
   output.append(chunk.begin(), chunk.end());
 
   if (output.find("<cdash") != output.npos) {
@@ -677,7 +662,7 @@ bool cmCTestSubmitHandler::TriggerUsingHTTP(const std::set<std::string>& files,
       ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void*)&chunkDebug);
 
       std::string rfile = remoteprefix + cmSystemTools::GetFilenameName(*file);
-      std::string ofile = "";
+      std::string ofile;
       std::string::iterator kk;
       for (kk = rfile.begin(); kk < rfile.end(); ++kk) {
         char c = *kk;
@@ -763,7 +748,7 @@ bool cmCTestSubmitHandler::SubmitUsingSCP(const std::string& scp_command,
 {
   if (scp_command.empty() || localprefix.empty() || files.empty() ||
       remoteprefix.empty() || url.empty()) {
-    return 0;
+    return false;
   }
 
   std::vector<const char*> argv;
@@ -800,10 +785,20 @@ bool cmCTestSubmitHandler::SubmitUsingSCP(const std::string& scp_command,
     cmsysProcess_Execute(cp);
     char* data;
     int length;
+    cmProcessOutput processOutput;
+    std::string strdata;
 
     while (cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
+      processOutput.DecodeText(data, length, strdata);
       cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
-                         cmCTestLogWrite(data, length), this->Quiet);
+                         cmCTestLogWrite(strdata.c_str(), strdata.size()),
+                         this->Quiet);
+    }
+    processOutput.DecodeText(std::string(), strdata);
+    if (!strdata.empty()) {
+      cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
+                         cmCTestLogWrite(strdata.c_str(), strdata.size()),
+                         this->Quiet);
     }
 
     cmsysProcess_WaitForExit(cp, CM_NULLPTR);
@@ -857,7 +852,7 @@ bool cmCTestSubmitHandler::SubmitUsingCP(const std::string& localprefix,
                << "\tremoteprefix: " << remoteprefix << "\n"
                << "\tdestination: " << destination << std::endl);
     /* clang-format on */
-    return 0;
+    return false;
   }
 
   cmCTest::SetOfStrings::const_iterator file;
@@ -925,7 +920,7 @@ bool cmCTestSubmitHandler::SubmitUsingXMLRPC(
       return false;
     }
     size_t fileSize = static_cast<size_t>(st.st_size);
-    FILE* fp = cmsys::SystemTools::Fopen(local_file.c_str(), "rb");
+    FILE* fp = cmsys::SystemTools::Fopen(local_file, "rb");
     if (!fp) {
       cmCTestLog(this->CTest, ERROR_MESSAGE,
                  "  Cannot open file: " << local_file << std::endl);
@@ -1012,6 +1007,7 @@ int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file,
     return -1;
   }
   cmCTestCurl curl(this->CTest);
+  curl.SetQuiet(this->Quiet);
   std::string curlopt(this->CTest->GetCTestConfiguration("CurlOptions"));
   std::vector<std::string> args;
   cmSystemTools::ExpandListArgument(curlopt, args);
@@ -1027,6 +1023,30 @@ int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file,
                "Only http and https are supported for CDASH_UPLOAD\n");
     return -1;
   }
+  bool internalTest = cmSystemTools::IsOn(this->GetOption("InternalTest"));
+
+  // Get RETRY_COUNT and RETRY_DELAY values if they were set.
+  std::string retryDelayString = this->GetOption("RetryDelay") == CM_NULLPTR
+    ? ""
+    : this->GetOption("RetryDelay");
+  std::string retryCountString = this->GetOption("RetryCount") == CM_NULLPTR
+    ? ""
+    : this->GetOption("RetryCount");
+  unsigned long retryDelay = 0;
+  if (retryDelayString != "") {
+    if (!cmSystemTools::StringToULong(retryDelayString.c_str(), &retryDelay)) {
+      cmCTestLog(this->CTest, WARNING, "Invalid value for 'RETRY_DELAY' : "
+                   << retryDelayString << std::endl);
+    }
+  }
+  unsigned long retryCount = 0;
+  if (retryCountString != "") {
+    if (!cmSystemTools::StringToULong(retryCountString.c_str(), &retryCount)) {
+      cmCTestLog(this->CTest, WARNING, "Invalid value for 'RETRY_DELAY' : "
+                   << retryCountString << std::endl);
+    }
+  }
+
   char md5sum[33];
   md5sum[32] = 0;
   cmSystemTools::ComputeFileMD5(file, md5sum);
@@ -1063,7 +1083,33 @@ int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file,
                                 << "\nfile: " << file << "\n",
                      this->Quiet);
   std::string response;
-  if (!curl.HttpRequest(url, fields, response)) {
+
+  bool requestSucceeded = curl.HttpRequest(url, fields, response);
+  if (!internalTest && !requestSucceeded) {
+    // If request failed, wait and retry.
+    for (unsigned long i = 0; i < retryCount; i++) {
+      cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
+                         "   Request failed, waiting " << retryDelay
+                                                       << " seconds...\n",
+                         this->Quiet);
+
+      double stop = cmSystemTools::GetTime() + static_cast<double>(retryDelay);
+      while (cmSystemTools::GetTime() < stop) {
+        cmSystemTools::Delay(100);
+      }
+
+      cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
+                         "   Retry request: Attempt "
+                           << (i + 1) << " of " << retryCount << std::endl,
+                         this->Quiet);
+
+      requestSucceeded = curl.HttpRequest(url, fields, response);
+      if (requestSucceeded) {
+        break;
+      }
+    }
+  }
+  if (!internalTest && !requestSucceeded) {
     cmCTestLog(this->CTest, ERROR_MESSAGE, "Error in HttpRequest\n"
                  << response);
     return -1;
@@ -1073,30 +1119,32 @@ int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file,
                      this->Quiet);
   Json::Value json;
   Json::Reader reader;
-  if (!reader.parse(response, json)) {
+  if (!internalTest && !reader.parse(response, json)) {
     cmCTestLog(this->CTest, ERROR_MESSAGE, "error parsing json string ["
                  << response << "]\n"
                  << reader.getFormattedErrorMessages() << "\n");
     return -1;
   }
-  if (json["status"].asInt() != 0) {
+  if (!internalTest && json["status"].asInt() != 0) {
     cmCTestLog(this->CTest, ERROR_MESSAGE,
                "Bad status returned from CDash: " << json["status"].asInt());
     return -1;
   }
-  if (json["datafilesmd5"].isArray()) {
-    int datares = json["datafilesmd5"][0].asInt();
-    if (datares == 1) {
-      cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
-                         "File already exists on CDash, skip upload " << file
-                                                                      << "\n",
-                         this->Quiet);
-      return 0;
+  if (!internalTest) {
+    if (json["datafilesmd5"].isArray()) {
+      int datares = json["datafilesmd5"][0].asInt();
+      if (datares == 1) {
+        cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
+                           "File already exists on CDash, skip upload "
+                             << file << "\n",
+                           this->Quiet);
+        return 0;
+      }
+    } else {
+      cmCTestLog(this->CTest, ERROR_MESSAGE,
+                 "bad datafilesmd5 value in response " << response << "\n");
+      return -1;
     }
-  } else {
-    cmCTestLog(this->CTest, ERROR_MESSAGE,
-               "bad datafilesmd5 value in response " << response << "\n");
-    return -1;
   }
 
   std::string upload_as = cmSystemTools::GetFilenameName(file);
@@ -1105,7 +1153,40 @@ int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file,
        << "md5=" << md5sum << "&"
        << "filename=" << curl.Escape(upload_as) << "&"
        << "buildid=" << json["buildid"].asString();
-  if (!curl.UploadFile(file, url, fstr.str(), response)) {
+
+  bool uploadSucceeded = false;
+  if (!internalTest) {
+    uploadSucceeded = curl.UploadFile(file, url, fstr.str(), response);
+  }
+
+  if (!uploadSucceeded) {
+    // If upload failed, wait and retry.
+    for (unsigned long i = 0; i < retryCount; i++) {
+      cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
+                         "   Upload failed, waiting " << retryDelay
+                                                      << " seconds...\n",
+                         this->Quiet);
+
+      double stop = cmSystemTools::GetTime() + static_cast<double>(retryDelay);
+      while (cmSystemTools::GetTime() < stop) {
+        cmSystemTools::Delay(100);
+      }
+
+      cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
+                         "   Retry upload: Attempt "
+                           << (i + 1) << " of " << retryCount << std::endl,
+                         this->Quiet);
+
+      if (!internalTest) {
+        uploadSucceeded = curl.UploadFile(file, url, fstr.str(), response);
+      }
+      if (uploadSucceeded) {
+        break;
+      }
+    }
+  }
+
+  if (!uploadSucceeded) {
     cmCTestLog(this->CTest, ERROR_MESSAGE, "error uploading to CDash. "
                  << file << " " << url << " " << fstr.str());
     return -1;
diff --git a/Source/CTest/cmCTestSubmitHandler.h b/Source/CTest/cmCTestSubmitHandler.h
index abe4fa2..baaf8af 100644
--- a/Source/CTest/cmCTestSubmitHandler.h
+++ b/Source/CTest/cmCTestSubmitHandler.h
@@ -7,7 +7,6 @@
 
 #include "cmCTest.h"
 #include "cmCTestGenericHandler.h"
-#include "cmTypeMacro.h"
 
 #include <iosfwd>
 #include <set>
@@ -23,7 +22,7 @@
 class cmCTestSubmitHandler : public cmCTestGenericHandler
 {
 public:
-  cmTypeMacro(cmCTestSubmitHandler, cmCTestGenericHandler);
+  typedef cmCTestGenericHandler Superclass;
 
   cmCTestSubmitHandler();
   ~cmCTestSubmitHandler() CM_OVERRIDE { this->LogFile = CM_NULLPTR; }
diff --git a/Source/CTest/cmCTestTestCommand.h b/Source/CTest/cmCTestTestCommand.h
index 6161acb..3250d93 100644
--- a/Source/CTest/cmCTestTestCommand.h
+++ b/Source/CTest/cmCTestTestCommand.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestHandlerCommand.h"
-#include "cmTypeMacro.h"
 
 #include <string>
 
@@ -39,8 +38,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "ctest_test"; }
 
-  cmTypeMacro(cmCTestTestCommand, cmCTestHandlerCommand);
-
 protected:
   virtual cmCTestGenericHandler* InitializeActualHandler();
   cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
diff --git a/Source/CTest/cmCTestTestHandler.cxx b/Source/CTest/cmCTestTestHandler.cxx
index 0d0237f..6175e50 100644
--- a/Source/CTest/cmCTestTestHandler.cxx
+++ b/Source/CTest/cmCTestTestHandler.cxx
@@ -2,20 +2,6 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestTestHandler.h"
 
-#include "cmCTest.h"
-#include "cmCTestBatchTestHandler.h"
-#include "cmCTestMultiProcessHandler.h"
-#include "cmCommand.h"
-#include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
-#include "cmState.h"
-#include "cmSystemTools.h"
-#include "cmXMLWriter.h"
-#include "cm_auto_ptr.hxx"
-#include "cm_utf8.h"
-#include "cmake.h"
-
 #include <algorithm>
 #include <cmsys/Base64.h>
 #include <cmsys/Directory.hxx>
@@ -31,6 +17,21 @@
 #include <string.h>
 #include <time.h>
 
+#include "cmCTest.h"
+#include "cmCTestBatchTestHandler.h"
+#include "cmCTestMultiProcessHandler.h"
+#include "cmCommand.h"
+#include "cmGeneratedFileStream.h"
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmState.h"
+#include "cmStateSnapshot.h"
+#include "cmSystemTools.h"
+#include "cmXMLWriter.h"
+#include "cm_auto_ptr.hxx"
+#include "cm_utf8.h"
+#include "cmake.h"
+
 class cmExecutionStatus;
 
 class cmCTestSubdirCommand : public cmCommand
@@ -58,8 +59,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "subdirs"; }
 
-  cmTypeMacro(cmCTestSubdirCommand, cmCommand);
-
   cmCTestTestHandler* TestHandler;
 };
 
@@ -139,8 +138,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "add_subdirectory"; }
 
-  cmTypeMacro(cmCTestAddSubdirectoryCommand, cmCommand);
-
   cmCTestTestHandler* TestHandler;
 };
 
@@ -213,8 +210,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "add_test"; }
 
-  cmTypeMacro(cmCTestAddTestCommand, cmCommand);
-
   cmCTestTestHandler* TestHandler;
 };
 
@@ -253,8 +248,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "set_tests_properties"; }
 
-  cmTypeMacro(cmCTestSetTestsPropertiesCommand, cmCommand);
-
   cmCTestTestHandler* TestHandler;
 };
 
@@ -725,7 +718,7 @@ void cmCTestTestHandler::ComputeTestList()
   // Now create a final list of tests to run
   int cnt = 0;
   inREcnt = 0;
-  std::string last_directory = "";
+  std::string last_directory;
   ListOfTests finalList;
   for (it = this->TestList.begin(); it != this->TestList.end(); it++) {
     cnt++;
@@ -804,8 +797,9 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
 
   // Prepare some maps to help us find setup and cleanup tests for
   // any given fixture
-  typedef std::set<ListOfTests::const_iterator> TestIteratorSet;
-  typedef std::map<std::string, TestIteratorSet> FixtureDependencies;
+  typedef ListOfTests::const_iterator TestIterator;
+  typedef std::multimap<std::string, TestIterator> FixtureDependencies;
+  typedef FixtureDependencies::const_iterator FixtureDepsIterator;
   FixtureDependencies fixtureSetups;
   FixtureDependencies fixtureDeps;
 
@@ -816,14 +810,14 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
     const std::set<std::string>& setups = p.FixturesSetup;
     for (std::set<std::string>::const_iterator depsIt = setups.begin();
          depsIt != setups.end(); ++depsIt) {
-      fixtureSetups[*depsIt].insert(it);
-      fixtureDeps[*depsIt].insert(it);
+      fixtureSetups.insert(std::make_pair(*depsIt, it));
+      fixtureDeps.insert(std::make_pair(*depsIt, it));
     }
 
     const std::set<std::string>& cleanups = p.FixturesCleanup;
     for (std::set<std::string>::const_iterator depsIt = cleanups.begin();
          depsIt != cleanups.end(); ++depsIt) {
-      fixtureDeps[*depsIt].insert(it);
+      fixtureDeps.insert(std::make_pair(*depsIt, it));
     }
   }
 
@@ -835,23 +829,31 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
     addedTests.insert(p.Name);
   }
 
-  // This is a lookup of fixture name to a list of indices into the
-  // final tests array for tests which require that fixture. It is
-  // needed at the end to populate dependencies of the cleanup tests
-  // in our final list of tests.
+  // These are lookups of fixture name to a list of indices into the final
+  // tests array for tests which require that fixture and tests which are
+  // setups for that fixture. They are needed at the end to populate
+  // dependencies of the cleanup tests in our final list of tests.
   std::map<std::string, std::vector<size_t> > fixtureRequirements;
+  std::map<std::string, std::vector<size_t> > setupFixturesAdded;
 
   // Use integer index for iteration because we append to
   // the tests vector as we go
   size_t fixtureTestsAdded = 0;
   std::set<std::string> addedFixtures;
   for (size_t i = 0; i < tests.size(); ++i) {
-    if (tests[i].FixturesRequired.empty()) {
-      continue;
-    }
-    // Must copy the set of fixtures because we may invalidate
+    // There are two things to do for each test:
+    //   1. For every fixture required by this test, record that fixture as
+    //      being required and create dependencies on that fixture's setup
+    //      tests.
+    //   2. Record all setup tests in the final test list so we can later make
+    //      cleanup tests in the test list depend on their associated setup
+    //      tests to enforce correct ordering.
+
+    // 1. Handle fixture requirements
+    //
+    // Must copy the set of fixtures required because we may invalidate
     // the tests array by appending to it
-    const std::set<std::string> fixtures = tests[i].FixturesRequired;
+    std::set<std::string> fixtures = tests[i].FixturesRequired;
     for (std::set<std::string>::const_iterator fixturesIt = fixtures.begin();
          fixturesIt != fixtures.end(); ++fixturesIt) {
 
@@ -866,17 +868,15 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
       // associated with the required fixture. If any of those setup
       // tests fail, this test should not run. We make the fixture's
       // cleanup tests depend on this test case later.
-      FixtureDependencies::const_iterator setupIt =
-        fixtureSetups.find(requiredFixtureName);
-      if (setupIt != fixtureSetups.end()) {
-        for (TestIteratorSet::const_iterator sIt = setupIt->second.begin();
-             sIt != setupIt->second.end(); ++sIt) {
-          const std::string& setupTestName = (**sIt).Name;
-          tests[i].RequireSuccessDepends.insert(setupTestName);
-          if (std::find(tests[i].Depends.begin(), tests[i].Depends.end(),
-                        setupTestName) == tests[i].Depends.end()) {
-            tests[i].Depends.push_back(setupTestName);
-          }
+      std::pair<FixtureDepsIterator, FixtureDepsIterator> setupRange =
+        fixtureSetups.equal_range(requiredFixtureName);
+      for (FixtureDepsIterator sIt = setupRange.first;
+           sIt != setupRange.second; ++sIt) {
+        const std::string& setupTestName = sIt->second->Name;
+        tests[i].RequireSuccessDepends.insert(setupTestName);
+        if (std::find(tests[i].Depends.begin(), tests[i].Depends.end(),
+                      setupTestName) == tests[i].Depends.end()) {
+          tests[i].Depends.push_back(setupTestName);
         }
       }
 
@@ -889,17 +889,11 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
         // Already added this fixture
         continue;
       }
-      FixtureDependencies::const_iterator fixtureIt =
-        fixtureDeps.find(requiredFixtureName);
-      if (fixtureIt == fixtureDeps.end()) {
-        // No setup or cleanup tests for this fixture
-        continue;
-      }
-
-      const TestIteratorSet& testIters = fixtureIt->second;
-      for (TestIteratorSet::const_iterator depsIt = testIters.begin();
-           depsIt != testIters.end(); ++depsIt) {
-        ListOfTests::const_iterator lotIt = *depsIt;
+      std::pair<FixtureDepsIterator, FixtureDepsIterator> fixtureRange =
+        fixtureDeps.equal_range(requiredFixtureName);
+      for (FixtureDepsIterator it = fixtureRange.first;
+           it != fixtureRange.second; ++it) {
+        ListOfTests::const_iterator lotIt = it->second;
         const cmCTestTestProperties& p = *lotIt;
 
         if (!addedTests.insert(p.Name).second) {
@@ -922,32 +916,62 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
                            this->Quiet);
       }
     }
+
+    // 2. Record all setup fixtures included in the final list of tests
+    for (std::set<std::string>::const_iterator fixturesIt =
+           tests[i].FixturesSetup.begin();
+         fixturesIt != tests[i].FixturesSetup.end(); ++fixturesIt) {
+
+      const std::string& setupFixtureName = *fixturesIt;
+      if (setupFixtureName.empty()) {
+        continue;
+      }
+
+      setupFixturesAdded[setupFixtureName].push_back(i);
+    }
   }
 
   // Now that we have the final list of tests, we can update all cleanup
-  // tests to depend on those tests which require that fixture
+  // tests to depend on those tests which require that fixture and on any
+  // setup tests for that fixture. The latter is required to handle the
+  // pathological case where setup and cleanup tests are in the test set
+  // but no other test has that fixture as a requirement.
   for (ListOfTests::iterator tIt = tests.begin(); tIt != tests.end(); ++tIt) {
     cmCTestTestProperties& p = *tIt;
     const std::set<std::string>& cleanups = p.FixturesCleanup;
     for (std::set<std::string>::const_iterator fIt = cleanups.begin();
          fIt != cleanups.end(); ++fIt) {
       const std::string& fixture = *fIt;
+
+      // This cleanup test could be part of the original test list that was
+      // passed in. It is then possible that no other test requires the
+      // fIt fixture, so we have to check for this.
       std::map<std::string, std::vector<size_t> >::const_iterator cIt =
         fixtureRequirements.find(fixture);
-      if (cIt == fixtureRequirements.end()) {
-        // No test cases require the fixture this cleanup test is for.
-        // This cleanup test must have been part of the original test
-        // list passed in (which is not an error)
-        continue;
+      if (cIt != fixtureRequirements.end()) {
+        const std::vector<size_t>& indices = cIt->second;
+        for (std::vector<size_t>::const_iterator indexIt = indices.begin();
+             indexIt != indices.end(); ++indexIt) {
+          const std::string& reqTestName = tests[*indexIt].Name;
+          if (std::find(p.Depends.begin(), p.Depends.end(), reqTestName) ==
+              p.Depends.end()) {
+            p.Depends.push_back(reqTestName);
+          }
+        }
       }
 
-      const std::vector<size_t>& indices = cIt->second;
-      for (std::vector<size_t>::const_iterator indexIt = indices.begin();
-           indexIt != indices.end(); ++indexIt) {
-        const std::string& reqTestName = tests[*indexIt].Name;
-        if (std::find(p.Depends.begin(), p.Depends.end(), reqTestName) ==
-            p.Depends.end()) {
-          p.Depends.push_back(reqTestName);
+      // Ensure fixture cleanup tests always run after their setup tests, even
+      // if no other test cases require the fixture
+      cIt = setupFixturesAdded.find(fixture);
+      if (cIt != setupFixturesAdded.end()) {
+        const std::vector<size_t>& indices = cIt->second;
+        for (std::vector<size_t>::const_iterator indexIt = indices.begin();
+             indexIt != indices.end(); ++indexIt) {
+          const std::string& setupTestName = tests[*indexIt].Name;
+          if (std::find(p.Depends.begin(), p.Depends.end(), setupTestName) ==
+              p.Depends.end()) {
+            p.Depends.push_back(setupTestName);
+          }
         }
       }
     }
@@ -1663,7 +1687,7 @@ void cmCTestTestHandler::ExpandTestsToRunInformationForRerunFailed()
   int numFiles =
     static_cast<int>(cmsys::Directory::GetNumberOfFilesInDirectory(dirName));
   std::string pattern = "LastTestsFailed";
-  std::string logName = "";
+  std::string logName;
 
   for (int i = 0; i < numFiles; ++i) {
     std::string fileName = directory.GetFile(i);
diff --git a/Source/CTest/cmCTestTestHandler.h b/Source/CTest/cmCTestTestHandler.h
index 73b3174..5b07e98 100644
--- a/Source/CTest/cmCTestTestHandler.h
+++ b/Source/CTest/cmCTestTestHandler.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestGenericHandler.h"
-#include "cmTypeMacro.h"
 
 #include <cmsys/RegularExpression.hxx>
 #include <iosfwd>
@@ -32,7 +31,7 @@ class cmCTestTestHandler : public cmCTestGenericHandler
   friend class cmCTestBatchTestHandler;
 
 public:
-  cmTypeMacro(cmCTestTestHandler, cmCTestGenericHandler);
+  typedef cmCTestGenericHandler Superclass;
 
   /**
    * The main entry point for this class
diff --git a/Source/CTest/cmCTestUpdateCommand.h b/Source/CTest/cmCTestUpdateCommand.h
index 9d1a86e..5761f50 100644
--- a/Source/CTest/cmCTestUpdateCommand.h
+++ b/Source/CTest/cmCTestUpdateCommand.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestHandlerCommand.h"
-#include "cmTypeMacro.h"
 
 #include <string>
 
@@ -39,8 +38,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "ctest_update"; }
 
-  cmTypeMacro(cmCTestUpdateCommand, cmCTestHandlerCommand);
-
 protected:
   cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
 };
diff --git a/Source/CTest/cmCTestUpdateHandler.h b/Source/CTest/cmCTestUpdateHandler.h
index c9a8682..87781e8 100644
--- a/Source/CTest/cmCTestUpdateHandler.h
+++ b/Source/CTest/cmCTestUpdateHandler.h
@@ -6,7 +6,6 @@
 #include <cmConfigure.h>
 
 #include "cmCTestGenericHandler.h"
-#include "cmTypeMacro.h"
 
 #include <string>
 #include <utility>
@@ -19,7 +18,7 @@
 class cmCTestUpdateHandler : public cmCTestGenericHandler
 {
 public:
-  cmTypeMacro(cmCTestUpdateHandler, cmCTestGenericHandler);
+  typedef cmCTestGenericHandler Superclass;
 
   /*
    * The main entry point for this class
diff --git a/Source/CTest/cmCTestUploadCommand.cxx b/Source/CTest/cmCTestUploadCommand.cxx
index 9266bce..717117a 100644
--- a/Source/CTest/cmCTestUploadCommand.cxx
+++ b/Source/CTest/cmCTestUploadCommand.cxx
@@ -2,6 +2,9 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTestUploadCommand.h"
 
+#include <sstream>
+#include <vector>
+
 #include "cmCTest.h"
 #include "cmCTestGenericHandler.h"
 #include "cmCTestUploadHandler.h"
@@ -9,8 +12,6 @@
 #include "cmSystemTools.h"
 #include "cmake.h"
 
-#include <sstream>
-
 cmCTestGenericHandler* cmCTestUploadCommand::InitializeHandler()
 {
   cmCTestGenericHandler* handler =
diff --git a/Source/CTest/cmCTestUploadCommand.h b/Source/CTest/cmCTestUploadCommand.h
index b858077..474f699 100644
--- a/Source/CTest/cmCTestUploadCommand.h
+++ b/Source/CTest/cmCTestUploadCommand.h
@@ -7,7 +7,6 @@
 
 #include "cmCTest.h"
 #include "cmCTestHandlerCommand.h"
-#include "cmTypeMacro.h"
 
 #include <string>
 
@@ -41,7 +40,7 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "ctest_upload"; }
 
-  cmTypeMacro(cmCTestUploadCommand, cmCTestHandlerCommand);
+  typedef cmCTestHandlerCommand Superclass;
 
 protected:
   cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
diff --git a/Source/CTest/cmCTestUploadHandler.h b/Source/CTest/cmCTestUploadHandler.h
index 251cd3e..77c2aec 100644
--- a/Source/CTest/cmCTestUploadHandler.h
+++ b/Source/CTest/cmCTestUploadHandler.h
@@ -7,7 +7,6 @@
 
 #include "cmCTest.h"
 #include "cmCTestGenericHandler.h"
-#include "cmTypeMacro.h"
 
 /** \class cmCTestUploadHandler
  * \brief Helper class for CTest
@@ -18,7 +17,7 @@
 class cmCTestUploadHandler : public cmCTestGenericHandler
 {
 public:
-  cmTypeMacro(cmCTestUploadHandler, cmCTestGenericHandler);
+  typedef cmCTestGenericHandler Superclass;
 
   cmCTestUploadHandler();
   ~cmCTestUploadHandler() CM_OVERRIDE {}
diff --git a/Source/CTest/cmCTestVC.cxx b/Source/CTest/cmCTestVC.cxx
index 7a2fa69..444c43d 100644
--- a/Source/CTest/cmCTestVC.cxx
+++ b/Source/CTest/cmCTestVC.cxx
@@ -76,7 +76,8 @@ bool cmCTestVC::InitialCheckout(const char* command)
 }
 
 bool cmCTestVC::RunChild(char const* const* cmd, OutputParser* out,
-                         OutputParser* err, const char* workDir)
+                         OutputParser* err, const char* workDir,
+                         Encoding encoding)
 {
   this->Log << this->ComputeCommandLine(cmd) << "\n";
 
@@ -84,7 +85,7 @@ bool cmCTestVC::RunChild(char const* const* cmd, OutputParser* out,
   cmsysProcess_SetCommand(cp, cmd);
   workDir = workDir ? workDir : this->SourceDirectory.c_str();
   cmsysProcess_SetWorkingDirectory(cp, workDir);
-  this->RunProcess(cp, out, err);
+  this->RunProcess(cp, out, err, encoding);
   int result = cmsysProcess_GetExitValue(cp);
   cmsysProcess_Delete(cp);
   return result == 0;
@@ -102,7 +103,7 @@ std::string cmCTestVC::ComputeCommandLine(char const* const* cmd)
 }
 
 bool cmCTestVC::RunUpdateCommand(char const* const* cmd, OutputParser* out,
-                                 OutputParser* err)
+                                 OutputParser* err, Encoding encoding)
 {
   // Report the command line.
   this->UpdateCommandLine = this->ComputeCommandLine(cmd);
@@ -112,7 +113,7 @@ bool cmCTestVC::RunUpdateCommand(char const* const* cmd, OutputParser* out,
   }
 
   // Run the command.
-  return this->RunChild(cmd, out, err);
+  return this->RunChild(cmd, out, err, CM_NULLPTR, encoding);
 }
 
 std::string cmCTestVC::GetNightlyTime()
diff --git a/Source/CTest/cmCTestVC.h b/Source/CTest/cmCTestVC.h
index 4f2bba0..2681ba0 100644
--- a/Source/CTest/cmCTestVC.h
+++ b/Source/CTest/cmCTestVC.h
@@ -5,11 +5,12 @@
 
 #include <cmConfigure.h>
 
-#include "cmProcessTools.h"
-
 #include <iosfwd>
 #include <string>
 
+#include "cmProcessOutput.h"
+#include "cmProcessTools.h"
+
 class cmCTest;
 class cmXMLWriter;
 
@@ -116,11 +117,13 @@ protected:
 
   /** Run a command line and send output to given parsers.  */
   bool RunChild(char const* const* cmd, OutputParser* out, OutputParser* err,
-                const char* workDir = CM_NULLPTR);
+                const char* workDir = CM_NULLPTR,
+                Encoding encoding = cmProcessOutput::Auto);
 
   /** Run VC update command line and send output to given parsers.  */
   bool RunUpdateCommand(char const* const* cmd, OutputParser* out,
-                        OutputParser* err = CM_NULLPTR);
+                        OutputParser* err = CM_NULLPTR,
+                        Encoding encoding = cmProcessOutput::Auto);
 
   /** Write xml element for one file.  */
   void WriteXMLEntry(cmXMLWriter& xml, std::string const& path,
diff --git a/Source/CTest/cmParseCoberturaCoverage.cxx b/Source/CTest/cmParseCoberturaCoverage.cxx
index 0b6d3ce..db17748 100644
--- a/Source/CTest/cmParseCoberturaCoverage.cxx
+++ b/Source/CTest/cmParseCoberturaCoverage.cxx
@@ -54,7 +54,7 @@ protected:
   void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
   {
     std::string FoundSource;
-    std::string finalpath = "";
+    std::string finalpath;
     if (name == "source") {
       this->InSource = true;
     } else if (name == "sources") {
diff --git a/Source/CTest/cmProcess.cxx b/Source/CTest/cmProcess.cxx
index cf3c7ac..32ffa6b 100644
--- a/Source/CTest/cmProcess.cxx
+++ b/Source/CTest/cmProcess.cxx
@@ -3,6 +3,7 @@
 #include "cmProcess.h"
 
 #include <cmConfigure.h>
+#include <cmProcessOutput.h>
 #include <cmSystemTools.h>
 #include <iostream>
 
@@ -104,6 +105,8 @@ bool cmProcess::Buffer::GetLast(std::string& line)
 
 int cmProcess::GetNextOutputLine(std::string& line, double timeout)
 {
+  cmProcessOutput processOutput(cmProcessOutput::UTF8);
+  std::string strdata;
   for (;;) {
     // Look for lines already buffered.
     if (this->Output.GetLine(line)) {
@@ -118,12 +121,17 @@ int cmProcess::GetNextOutputLine(std::string& line, double timeout)
       return cmsysProcess_Pipe_Timeout;
     }
     if (p == cmsysProcess_Pipe_STDOUT) {
-      this->Output.insert(this->Output.end(), data, data + length);
+      processOutput.DecodeText(data, length, strdata);
+      this->Output.insert(this->Output.end(), strdata.begin(), strdata.end());
     } else { // p == cmsysProcess_Pipe_None
       // The process will provide no more data.
       break;
     }
   }
+  processOutput.DecodeText(std::string(), strdata);
+  if (!strdata.empty()) {
+    this->Output.insert(this->Output.end(), strdata.begin(), strdata.end());
+  }
 
   // Look for partial last lines.
   if (this->Output.GetLast(line)) {
@@ -225,6 +233,7 @@ void cmProcess::ChangeTimeout(double t)
 void cmProcess::ResetStartTime()
 {
   cmsysProcess_ResetStartTime(this->Process);
+  this->StartTime = cmSystemTools::GetTime();
 }
 
 int cmProcess::GetExitException()
diff --git a/Source/CursesDialog/ccmake.cxx b/Source/CursesDialog/ccmake.cxx
index 919be4d..ff8e010 100644
--- a/Source/CursesDialog/ccmake.cxx
+++ b/Source/CursesDialog/ccmake.cxx
@@ -52,8 +52,7 @@ void onsig(int /*unused*/)
     initscr();            /* Initialization */
     noecho();             /* Echo off */
     cbreak();             /* nl- or cr not needed */
-    keypad(stdscr, TRUE); /* Use key symbols as
-                             KEY_DOWN*/
+    keypad(stdscr, true); /* Use key symbols as KEY_DOWN */
     refresh();
     int x, y;
     getmaxyx(stdscr, y, x);
@@ -128,8 +127,7 @@ int main(int argc, char const* const* argv)
   initscr();            /* Initialization */
   noecho();             /* Echo off */
   cbreak();             /* nl- or cr not needed */
-  keypad(stdscr, TRUE); /* Use key symbols as
-                           KEY_DOWN*/
+  keypad(stdscr, true); /* Use key symbols as KEY_DOWN */
 
   signal(SIGWINCH, onsig);
 
diff --git a/Source/CursesDialog/cmCursesBoolWidget.cxx b/Source/CursesDialog/cmCursesBoolWidget.cxx
index 5268a5d..80a5b5b 100644
--- a/Source/CursesDialog/cmCursesBoolWidget.cxx
+++ b/Source/CursesDialog/cmCursesBoolWidget.cxx
@@ -3,7 +3,7 @@
 #include "cmCursesBoolWidget.h"
 
 #include "cmCursesWidget.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 
 #include <string>
 
@@ -11,7 +11,7 @@ cmCursesBoolWidget::cmCursesBoolWidget(int width, int height, int left,
                                        int top)
   : cmCursesWidget(width, height, left, top)
 {
-  this->Type = cmState::BOOL;
+  this->Type = cmStateEnums::BOOL;
   set_field_fore(this->Field, A_NORMAL);
   set_field_back(this->Field, A_STANDOUT);
   field_opts_off(this->Field, O_STATIC);
diff --git a/Source/CursesDialog/cmCursesCacheEntryComposite.cxx b/Source/CursesDialog/cmCursesCacheEntryComposite.cxx
index 93785e0..5539fbe 100644
--- a/Source/CursesDialog/cmCursesCacheEntryComposite.cxx
+++ b/Source/CursesDialog/cmCursesCacheEntryComposite.cxx
@@ -10,6 +10,7 @@
 #include "cmCursesStringWidget.h"
 #include "cmCursesWidget.h"
 #include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmake.h"
 
@@ -47,7 +48,7 @@ cmCursesCacheEntryComposite::cmCursesCacheEntryComposite(
   const char* value = cm->GetState()->GetCacheEntryValue(key);
   assert(value);
   switch (cm->GetState()->GetCacheEntryType(key)) {
-    case cmState::BOOL:
+    case cmStateEnums::BOOL:
       this->Entry = new cmCursesBoolWidget(this->EntryWidth, 1, 1, 1);
       if (cmSystemTools::IsOn(value)) {
         static_cast<cmCursesBoolWidget*>(this->Entry)->SetValueAsBool(true);
@@ -55,15 +56,15 @@ cmCursesCacheEntryComposite::cmCursesCacheEntryComposite(
         static_cast<cmCursesBoolWidget*>(this->Entry)->SetValueAsBool(false);
       }
       break;
-    case cmState::PATH:
+    case cmStateEnums::PATH:
       this->Entry = new cmCursesPathWidget(this->EntryWidth, 1, 1, 1);
       static_cast<cmCursesPathWidget*>(this->Entry)->SetString(value);
       break;
-    case cmState::FILEPATH:
+    case cmStateEnums::FILEPATH:
       this->Entry = new cmCursesFilePathWidget(this->EntryWidth, 1, 1, 1);
       static_cast<cmCursesFilePathWidget*>(this->Entry)->SetString(value);
       break;
-    case cmState::STRING: {
+    case cmStateEnums::STRING: {
       const char* stringsProp =
         cm->GetState()->GetCacheEntryProperty(key, "STRINGS");
       if (stringsProp) {
@@ -83,7 +84,7 @@ cmCursesCacheEntryComposite::cmCursesCacheEntryComposite(
       }
       break;
     }
-    case cmState::UNINITIALIZED:
+    case cmStateEnums::UNINITIALIZED:
       cmSystemTools::Error("Found an undefined variable: ", key.c_str());
       break;
     default:
diff --git a/Source/CursesDialog/cmCursesDummyWidget.cxx b/Source/CursesDialog/cmCursesDummyWidget.cxx
index 61d07e2..da0478a 100644
--- a/Source/CursesDialog/cmCursesDummyWidget.cxx
+++ b/Source/CursesDialog/cmCursesDummyWidget.cxx
@@ -3,13 +3,13 @@
 #include "cmCursesDummyWidget.h"
 
 #include "cmCursesWidget.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 
 cmCursesDummyWidget::cmCursesDummyWidget(int width, int height, int left,
                                          int top)
   : cmCursesWidget(width, height, left, top)
 {
-  this->Type = cmState::INTERNAL;
+  this->Type = cmStateEnums::INTERNAL;
 }
 
 bool cmCursesDummyWidget::HandleInput(int& /*key*/, cmCursesMainForm* /*fm*/,
diff --git a/Source/CursesDialog/cmCursesFilePathWidget.cxx b/Source/CursesDialog/cmCursesFilePathWidget.cxx
index 670c50f..518da4f 100644
--- a/Source/CursesDialog/cmCursesFilePathWidget.cxx
+++ b/Source/CursesDialog/cmCursesFilePathWidget.cxx
@@ -3,11 +3,11 @@
 #include "cmCursesFilePathWidget.h"
 
 #include "cmCursesPathWidget.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 
 cmCursesFilePathWidget::cmCursesFilePathWidget(int width, int height, int left,
                                                int top)
   : cmCursesPathWidget(width, height, left, top)
 {
-  this->Type = cmState::FILEPATH;
+  this->Type = cmStateEnums::FILEPATH;
 }
diff --git a/Source/CursesDialog/cmCursesMainForm.cxx b/Source/CursesDialog/cmCursesMainForm.cxx
index 0c3d29d..939c736 100644
--- a/Source/CursesDialog/cmCursesMainForm.cxx
+++ b/Source/CursesDialog/cmCursesMainForm.cxx
@@ -12,6 +12,7 @@
 #include "cmCursesStringWidget.h"
 #include "cmCursesWidget.h"
 #include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmVersion.h"
 #include "cmake.h"
@@ -106,10 +107,10 @@ void cmCursesMainForm::InitializeUI()
 
   for (std::vector<std::string>::const_iterator it = cacheKeys.begin();
        it != cacheKeys.end(); ++it) {
-    cmState::CacheEntryType t =
+    cmStateEnums::CacheEntryType t =
       this->CMakeInstance->GetState()->GetCacheEntryType(*it);
-    if (t != cmState::INTERNAL && t != cmState::STATIC &&
-        t != cmState::UNINITIALIZED) {
+    if (t != cmStateEnums::INTERNAL && t != cmStateEnums::STATIC &&
+        t != cmStateEnums::UNINITIALIZED) {
       ++count;
     }
   }
@@ -130,10 +131,10 @@ void cmCursesMainForm::InitializeUI()
     for (std::vector<std::string>::const_iterator it = cacheKeys.begin();
          it != cacheKeys.end(); ++it) {
       std::string key = *it;
-      cmState::CacheEntryType t =
+      cmStateEnums::CacheEntryType t =
         this->CMakeInstance->GetState()->GetCacheEntryType(*it);
-      if (t == cmState::INTERNAL || t == cmState::STATIC ||
-          t == cmState::UNINITIALIZED) {
+      if (t == cmStateEnums::INTERNAL || t == cmStateEnums::STATIC ||
+          t == cmStateEnums::UNINITIALIZED) {
         continue;
       }
 
@@ -148,10 +149,10 @@ void cmCursesMainForm::InitializeUI()
     for (std::vector<std::string>::const_iterator it = cacheKeys.begin();
          it != cacheKeys.end(); ++it) {
       std::string key = *it;
-      cmState::CacheEntryType t =
+      cmStateEnums::CacheEntryType t =
         this->CMakeInstance->GetState()->GetCacheEntryType(*it);
-      if (t == cmState::INTERNAL || t == cmState::STATIC ||
-          t == cmState::UNINITIALIZED) {
+      if (t == cmStateEnums::INTERNAL || t == cmStateEnums::STATIC ||
+          t == cmStateEnums::UNINITIALIZED) {
         continue;
       }
 
@@ -249,8 +250,9 @@ void cmCursesMainForm::Render(int left, int top, int width, int height)
     cmCursesWidget* cw =
       reinterpret_cast<cmCursesWidget*>(field_userptr(currentField));
     // If in edit mode, get out of it
-    if (cw->GetType() == cmState::STRING || cw->GetType() == cmState::PATH ||
-        cw->GetType() == cmState::FILEPATH) {
+    if (cw->GetType() == cmStateEnums::STRING ||
+        cw->GetType() == cmStateEnums::PATH ||
+        cw->GetType() == cmStateEnums::FILEPATH) {
       cmCursesStringWidget* sw = static_cast<cmCursesStringWidget*>(cw);
       sw->SetInEdit(false);
     }
@@ -345,61 +347,56 @@ void cmCursesMainForm::PrintKeys(int process /* = 0 */)
     cw = reinterpret_cast<cmCursesWidget*>(field_userptr(currentField));
   }
 
-  if (cw) {
-    cw->PrintKeys();
-  }
-
-  //    {
-  //    }
-  //  else
-  //    {
-  char firstLine[512] = "";
-  char secondLine[512] = "";
-  char thirdLine[512] = "";
-  if (process) {
-    const char* clearLine =
-      "                                                                    ";
-    strcpy(firstLine, clearLine);
-    strcpy(secondLine, clearLine);
-    strcpy(thirdLine, clearLine);
-  } else {
-    if (this->OkToGenerate) {
-      sprintf(firstLine,
-              "Press [c] to configure       Press [g] to generate and exit");
+  char fmt_s[] = "%s";
+  if (cw == CM_NULLPTR || !cw->PrintKeys()) {
+    char firstLine[512] = "";
+    char secondLine[512] = "";
+    char thirdLine[512] = "";
+    if (process) {
+      const char* clearLine =
+        "                                                                    ";
+      strcpy(firstLine, clearLine);
+      strcpy(secondLine, clearLine);
+      strcpy(thirdLine, clearLine);
     } else {
-      sprintf(firstLine,
-              "Press [c] to configure                                   ");
-    }
-    {
-      const char* toggleKeyInstruction =
-        "Press [t] to toggle advanced mode (Currently %s)";
-      sprintf(thirdLine, toggleKeyInstruction,
-              this->AdvancedMode ? "On" : "Off");
+      if (this->OkToGenerate) {
+        sprintf(firstLine,
+                "Press [c] to configure       Press [g] to generate and exit");
+      } else {
+        sprintf(firstLine,
+                "Press [c] to configure                                     ");
+      }
+      {
+        const char* toggleKeyInstruction =
+          "Press [t] to toggle advanced mode (Currently %s)";
+        sprintf(thirdLine, toggleKeyInstruction,
+                this->AdvancedMode ? "On" : "Off");
+      }
+      sprintf(secondLine, "Press [h] for help           "
+                          "Press [q] to quit without generating");
     }
-    sprintf(secondLine, "Press [h] for help           "
-                        "Press [q] to quit without generating");
-  }
 
-  curses_move(y - 4, 0);
-  char fmt_s[] = "%s";
-  char fmt[512] = "Press [enter] to edit option Press [d] to delete an entry";
-  if (process) {
-    strcpy(fmt, "                           ");
+    curses_move(y - 4, 0);
+    char fmt[512] =
+      "Press [enter] to edit option Press [d] to delete an entry";
+    if (process) {
+      strcpy(fmt, "                           ");
+    }
+    printw(fmt_s, fmt);
+    curses_move(y - 3, 0);
+    printw(fmt_s, firstLine);
+    curses_move(y - 2, 0);
+    printw(fmt_s, secondLine);
+    curses_move(y - 1, 0);
+    printw(fmt_s, thirdLine);
   }
-  printw(fmt_s, fmt);
-  curses_move(y - 3, 0);
-  printw(fmt_s, firstLine);
-  curses_move(y - 2, 0);
-  printw(fmt_s, secondLine);
-  curses_move(y - 1, 0);
-  printw(fmt_s, thirdLine);
 
   if (cw) {
-    sprintf(firstLine, "Page %d of %d", cw->GetPage(), this->NumberOfPages);
-    curses_move(0, 65 - static_cast<unsigned int>(strlen(firstLine)) - 1);
-    printw(fmt_s, firstLine);
+    char pageLine[512] = "";
+    sprintf(pageLine, "Page %d of %d", cw->GetPage(), this->NumberOfPages);
+    curses_move(0, 65 - static_cast<unsigned int>(strlen(pageLine)) - 1);
+    printw(fmt_s, pageLine);
   }
-  //    }
 
   pos_form_cursor(this->Form);
 }
@@ -579,8 +576,7 @@ int cmCursesMainForm::Configure(int noconfigure)
   }
   this->CMakeInstance->SetProgressCallback(CM_NULLPTR, CM_NULLPTR);
 
-  keypad(stdscr, TRUE); /* Use key symbols as
-                           KEY_DOWN*/
+  keypad(stdscr, true); /* Use key symbols as KEY_DOWN */
 
   if (retVal != 0 || !this->Errors.empty()) {
     // see if there was an error
@@ -633,8 +629,7 @@ int cmCursesMainForm::Generate()
   int retVal = this->CMakeInstance->Generate();
 
   this->CMakeInstance->SetProgressCallback(CM_NULLPTR, CM_NULLPTR);
-  keypad(stdscr, TRUE); /* Use key symbols as
-                           KEY_DOWN*/
+  keypad(stdscr, true); /* Use key symbols as KEY_DOWN */
 
   if (retVal != 0 || !this->Errors.empty()) {
     // see if there was an error
@@ -704,7 +699,7 @@ void cmCursesMainForm::FillCacheManagerFromUI()
       std::string newValue = (*this->Entries)[i]->Entry->GetValue();
       std::string fixedOldValue;
       std::string fixedNewValue;
-      cmState::CacheEntryType t =
+      cmStateEnums::CacheEntryType t =
         this->CMakeInstance->GetState()->GetCacheEntryType(cacheKey);
       this->FixValue(t, oldValue, fixedOldValue);
       this->FixValue(t, newValue, fixedNewValue);
@@ -720,14 +715,14 @@ void cmCursesMainForm::FillCacheManagerFromUI()
   }
 }
 
-void cmCursesMainForm::FixValue(cmState::CacheEntryType type,
+void cmCursesMainForm::FixValue(cmStateEnums::CacheEntryType type,
                                 const std::string& in, std::string& out) const
 {
   out = in.substr(0, in.find_last_not_of(' ') + 1);
-  if (type == cmState::PATH || type == cmState::FILEPATH) {
+  if (type == cmStateEnums::PATH || type == cmStateEnums::FILEPATH) {
     cmSystemTools::ConvertToUnixSlashes(out);
   }
-  if (type == cmState::BOOL) {
+  if (type == cmStateEnums::BOOL) {
     if (cmSystemTools::IsOff(out.c_str())) {
       out = "OFF";
     } else {
diff --git a/Source/CursesDialog/cmCursesMainForm.h b/Source/CursesDialog/cmCursesMainForm.h
index 4bf452d..d891ea0 100644
--- a/Source/CursesDialog/cmCursesMainForm.h
+++ b/Source/CursesDialog/cmCursesMainForm.h
@@ -7,7 +7,7 @@
 
 #include "cmCursesForm.h"
 #include "cmCursesStandardIncludes.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 
 #include <stddef.h>
 #include <string>
@@ -110,7 +110,7 @@ protected:
   // cache.
   void FillCacheManagerFromUI();
   // Fix formatting of values to a consistent form.
-  void FixValue(cmState::CacheEntryType type, const std::string& in,
+  void FixValue(cmStateEnums::CacheEntryType type, const std::string& in,
                 std::string& out) const;
   // Re-post the existing fields. Used to toggle between
   // normal and advanced modes. Render() should be called
diff --git a/Source/CursesDialog/cmCursesOptionsWidget.cxx b/Source/CursesDialog/cmCursesOptionsWidget.cxx
index e23a82d..d26a98f 100644
--- a/Source/CursesDialog/cmCursesOptionsWidget.cxx
+++ b/Source/CursesDialog/cmCursesOptionsWidget.cxx
@@ -3,7 +3,7 @@
 #include "cmCursesOptionsWidget.h"
 
 #include "cmCursesWidget.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 
 #define ctrl(z) ((z)&037)
 
@@ -11,7 +11,7 @@ cmCursesOptionsWidget::cmCursesOptionsWidget(int width, int height, int left,
                                              int top)
   : cmCursesWidget(width, height, left, top)
 {
-  this->Type = cmState::BOOL; // this is a bit of a hack
+  this->Type = cmStateEnums::BOOL; // this is a bit of a hack
   // there is no option type, and string type causes ccmake to cast
   // the widget into a string widget at some point.  BOOL is safe for
   // now.
diff --git a/Source/CursesDialog/cmCursesPathWidget.cxx b/Source/CursesDialog/cmCursesPathWidget.cxx
index d208598..05c3279 100644
--- a/Source/CursesDialog/cmCursesPathWidget.cxx
+++ b/Source/CursesDialog/cmCursesPathWidget.cxx
@@ -4,7 +4,7 @@
 
 #include "cmCursesMainForm.h"
 #include "cmCursesStringWidget.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 
 #include <vector>
@@ -13,7 +13,7 @@ cmCursesPathWidget::cmCursesPathWidget(int width, int height, int left,
                                        int top)
   : cmCursesStringWidget(width, height, left, top)
 {
-  this->Type = cmState::PATH;
+  this->Type = cmStateEnums::PATH;
   this->Cycle = false;
   this->CurrentIndex = 0;
 }
@@ -50,7 +50,7 @@ void cmCursesPathWidget::OnTab(cmCursesMainForm* fm, WINDOW* w)
   std::vector<std::string> dirs;
 
   cmSystemTools::SimpleGlob(glob, dirs,
-                            (this->Type == cmState::PATH ? -1 : 0));
+                            (this->Type == cmStateEnums::PATH ? -1 : 0));
   if (this->CurrentIndex < dirs.size()) {
     cstr = dirs[this->CurrentIndex];
   }
diff --git a/Source/CursesDialog/cmCursesStringWidget.cxx b/Source/CursesDialog/cmCursesStringWidget.cxx
index f068f67..ff189f0 100644
--- a/Source/CursesDialog/cmCursesStringWidget.cxx
+++ b/Source/CursesDialog/cmCursesStringWidget.cxx
@@ -6,7 +6,7 @@
 #include "cmCursesMainForm.h"
 #include "cmCursesStandardIncludes.h"
 #include "cmCursesWidget.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 
 #include <stdio.h>
 #include <string.h>
@@ -21,7 +21,7 @@ cmCursesStringWidget::cmCursesStringWidget(int width, int height, int left,
   : cmCursesWidget(width, height, left, top)
 {
   this->InEdit = false;
-  this->Type = cmState::STRING;
+  this->Type = cmStateEnums::STRING;
   set_field_fore(this->Field, A_NORMAL);
   set_field_back(this->Field, A_STANDOUT);
   field_opts_off(this->Field, O_STATIC);
@@ -202,7 +202,9 @@ bool cmCursesStringWidget::PrintKeys()
     printw(fmt_s, firstLine);
 
     curses_move(y - 3, 0);
-    printw(fmt_s, "Editing option, press [enter] to leave edit.");
+    printw(fmt_s, "Editing option, press [enter] to confirm");
+    curses_move(y - 2, 0);
+    printw(fmt_s, "                press [esc] to cancel");
     return true;
   }
   return false;
diff --git a/Source/CursesDialog/cmCursesWidget.cxx b/Source/CursesDialog/cmCursesWidget.cxx
index 6c76764..a9918f7 100644
--- a/Source/CursesDialog/cmCursesWidget.cxx
+++ b/Source/CursesDialog/cmCursesWidget.cxx
@@ -28,9 +28,9 @@ void cmCursesWidget::Move(int x, int y, bool isNewPage)
 
   move_field(this->Field, y, x);
   if (isNewPage) {
-    set_new_page(this->Field, TRUE);
+    set_new_page(this->Field, true);
   } else {
-    set_new_page(this->Field, FALSE);
+    set_new_page(this->Field, false);
   }
 }
 
diff --git a/Source/CursesDialog/cmCursesWidget.h b/Source/CursesDialog/cmCursesWidget.h
index bb26cf6..d226dd7 100644
--- a/Source/CursesDialog/cmCursesWidget.h
+++ b/Source/CursesDialog/cmCursesWidget.h
@@ -6,7 +6,7 @@
 #include <cmConfigure.h> // IWYU pragma: keep
 
 #include "cmCursesStandardIncludes.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 
 #include <string>
 
@@ -41,7 +41,7 @@ public:
   /**
    * Get the type of the widget (STRING, PATH etc...)
    */
-  cmState::CacheEntryType GetType() { return this->Type; }
+  cmStateEnums::CacheEntryType GetType() { return this->Type; }
 
   /**
    * If there are any, print the widget specific commands
@@ -62,7 +62,7 @@ protected:
   cmCursesWidget(const cmCursesWidget& from);
   void operator=(const cmCursesWidget&);
 
-  cmState::CacheEntryType Type;
+  cmStateEnums::CacheEntryType Type;
   std::string Value;
   FIELD* Field;
   // The page in the main form this widget is in
diff --git a/Source/CursesDialog/form/.gitattributes b/Source/CursesDialog/form/.gitattributes
new file mode 100644
index 0000000..62d728c
--- /dev/null
+++ b/Source/CursesDialog/form/.gitattributes
@@ -0,0 +1 @@
+* -format.clang-format
diff --git a/Source/Modules/FindLibRHash.cmake b/Source/Modules/FindLibRHash.cmake
new file mode 100644
index 0000000..86c6189
--- /dev/null
+++ b/Source/Modules/FindLibRHash.cmake
@@ -0,0 +1,73 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+FindLibRHash
+------------
+
+Find LibRHash include directory and library.
+
+Imported Targets
+^^^^^^^^^^^^^^^^
+
+An :ref:`imported target <Imported targets>` named
+``LibRHash::LibRHash`` is provided if LibRHash has been found.
+
+Result Variables
+^^^^^^^^^^^^^^^^
+
+This module defines the following variables:
+
+``LibRHash_FOUND``
+  True if LibRHash was found, false otherwise.
+``LibRHash_INCLUDE_DIRS``
+  Include directories needed to include LibRHash headers.
+``LibRHash_LIBRARIES``
+  Libraries needed to link to LibRHash.
+
+Cache Variables
+^^^^^^^^^^^^^^^
+
+This module uses the following cache variables:
+
+``LibRHash_LIBRARY``
+  The location of the LibRHash library file.
+``LibRHash_INCLUDE_DIR``
+  The location of the LibRHash include directory containing ``rhash.h``.
+
+The cache variables should not be used by project code.
+They may be set by end users to point at LibRHash components.
+#]=======================================================================]
+
+#-----------------------------------------------------------------------------
+find_library(LibRHash_LIBRARY
+  NAMES rhash
+  )
+mark_as_advanced(LibRHash_LIBRARY)
+
+find_path(LibRHash_INCLUDE_DIR
+  NAMES rhash.h
+  )
+mark_as_advanced(LibRHash_INCLUDE_DIR)
+
+#-----------------------------------------------------------------------------
+include(${CMAKE_CURRENT_LIST_DIR}/../../Modules/FindPackageHandleStandardArgs.cmake)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibRHash
+  FOUND_VAR LibRHash_FOUND
+  REQUIRED_VARS LibRHash_LIBRARY LibRHash_INCLUDE_DIR
+  )
+set(LIBRHASH_FOUND ${LibRHash_FOUND})
+
+#-----------------------------------------------------------------------------
+# Provide documented result variables and targets.
+if(LibRHash_FOUND)
+  set(LibRHash_INCLUDE_DIRS ${LibRHash_INCLUDE_DIR})
+  set(LibRHash_LIBRARIES ${LibRHash_LIBRARY})
+  if(NOT TARGET LibRHash::LibRHash)
+    add_library(LibRHash::LibRHash UNKNOWN IMPORTED)
+    set_target_properties(LibRHash::LibRHash PROPERTIES
+      IMPORTED_LOCATION "${LibRHash_LIBRARY}"
+      INTERFACE_INCLUDE_DIRECTORIES "${LibRHash_INCLUDE_DIRS}"
+      )
+  endif()
+endif()
diff --git a/Source/QtDialog/AddCacheEntry.cxx b/Source/QtDialog/AddCacheEntry.cxx
index daf4bd1..6284ac9 100644
--- a/Source/QtDialog/AddCacheEntry.cxx
+++ b/Source/QtDialog/AddCacheEntry.cxx
@@ -46,7 +46,7 @@ AddCacheEntry::AddCacheEntry(QWidget* p, const QStringList& varNames,
 
 QString AddCacheEntry::name() const
 {
-  return this->Name->text();
+  return this->Name->text().trimmed();
 }
 
 QVariant AddCacheEntry::value() const
diff --git a/Source/QtDialog/CMakeSetup.cxx b/Source/QtDialog/CMakeSetup.cxx
index fad8075..5e03c39 100644
--- a/Source/QtDialog/CMakeSetup.cxx
+++ b/Source/QtDialog/CMakeSetup.cxx
@@ -5,6 +5,7 @@
 #include "CMakeSetupDialog.h"
 #include "cmAlgorithms.h"
 #include "cmDocumentation.h"
+#include "cmDocumentationEntry.h"
 #include "cmVersion.h"
 #include "cmake.h"
 #include <QApplication>
@@ -17,6 +18,7 @@
 #include <cmsys/CommandLineArguments.hxx>
 #include <cmsys/Encoding.hxx>
 #include <cmsys/SystemTools.hxx>
+#include <iostream>
 
 #include "cmSystemTools.h" // IWYU pragma: keep
 
@@ -95,10 +97,8 @@ int main(int argc, char** argv)
 
   setlocale(LC_NUMERIC, "C");
 
-#if defined(CMAKE_ENCODING_UTF8)
   QTextCodec* utf8_codec = QTextCodec::codecForName("UTF-8");
   QTextCodec::setCodecForLocale(utf8_codec);
-#endif
 
 #if QT_VERSION < 0x050000
   // clean out standard Qt paths for plugins, which we don't use anyway
diff --git a/Source/QtDialog/FirstConfigure.cxx b/Source/QtDialog/FirstConfigure.cxx
index c34751a..2f1df4f 100644
--- a/Source/QtDialog/FirstConfigure.cxx
+++ b/Source/QtDialog/FirstConfigure.cxx
@@ -56,7 +56,7 @@ QFrame* StartCompilerSetup::CreateToolsetWidgets()
   QVBoxLayout* l = new QVBoxLayout(frame);
   l->setContentsMargins(0, 0, 0, 0);
 
-  ToolsetLabel = new QLabel(tr("Optional toolset to use (-T parameter)"));
+  ToolsetLabel = new QLabel(tr("Optional toolset to use (argument to -T)"));
   l->addWidget(ToolsetLabel);
 
   Toolset = new QLineEdit(frame);
diff --git a/Source/QtDialog/QCMake.cxx b/Source/QtDialog/QCMake.cxx
index cfb10f3..abeff97 100644
--- a/Source/QtDialog/QCMake.cxx
+++ b/Source/QtDialog/QCMake.cxx
@@ -196,8 +196,8 @@ void QCMake::setProperties(const QCMakePropertyList& newProps)
   std::vector<std::string> cacheKeys = state->GetCacheEntryKeys();
   for (std::vector<std::string>::const_iterator it = cacheKeys.begin();
        it != cacheKeys.end(); ++it) {
-    cmState::CacheEntryType t = state->GetCacheEntryType(*it);
-    if (t == cmState::INTERNAL || t == cmState::STATIC) {
+    cmStateEnums::CacheEntryType t = state->GetCacheEntryType(*it);
+    if (t == cmStateEnums::INTERNAL || t == cmStateEnums::STATIC) {
       continue;
     }
 
@@ -232,19 +232,19 @@ void QCMake::setProperties(const QCMakePropertyList& newProps)
     if (s.Type == QCMakeProperty::BOOL) {
       this->CMakeInstance->AddCacheEntry(
         s.Key.toLocal8Bit().data(), s.Value.toBool() ? "ON" : "OFF",
-        s.Help.toLocal8Bit().data(), cmState::BOOL);
+        s.Help.toLocal8Bit().data(), cmStateEnums::BOOL);
     } else if (s.Type == QCMakeProperty::STRING) {
       this->CMakeInstance->AddCacheEntry(
         s.Key.toLocal8Bit().data(), s.Value.toString().toLocal8Bit().data(),
-        s.Help.toLocal8Bit().data(), cmState::STRING);
+        s.Help.toLocal8Bit().data(), cmStateEnums::STRING);
     } else if (s.Type == QCMakeProperty::PATH) {
       this->CMakeInstance->AddCacheEntry(
         s.Key.toLocal8Bit().data(), s.Value.toString().toLocal8Bit().data(),
-        s.Help.toLocal8Bit().data(), cmState::PATH);
+        s.Help.toLocal8Bit().data(), cmStateEnums::PATH);
     } else if (s.Type == QCMakeProperty::FILEPATH) {
       this->CMakeInstance->AddCacheEntry(
         s.Key.toLocal8Bit().data(), s.Value.toString().toLocal8Bit().data(),
-        s.Help.toLocal8Bit().data(), cmState::FILEPATH);
+        s.Help.toLocal8Bit().data(), cmStateEnums::FILEPATH);
     }
   }
 
@@ -259,9 +259,9 @@ QCMakePropertyList QCMake::properties() const
   std::vector<std::string> cacheKeys = state->GetCacheEntryKeys();
   for (std::vector<std::string>::const_iterator i = cacheKeys.begin();
        i != cacheKeys.end(); ++i) {
-    cmState::CacheEntryType t = state->GetCacheEntryType(*i);
-    if (t == cmState::INTERNAL || t == cmState::STATIC ||
-        t == cmState::UNINITIALIZED) {
+    cmStateEnums::CacheEntryType t = state->GetCacheEntryType(*i);
+    if (t == cmStateEnums::INTERNAL || t == cmStateEnums::STATIC ||
+        t == cmStateEnums::UNINITIALIZED) {
       continue;
     }
 
@@ -273,14 +273,14 @@ QCMakePropertyList QCMake::properties() const
       QString::fromLocal8Bit(state->GetCacheEntryProperty(*i, "HELPSTRING"));
     prop.Value = QString::fromLocal8Bit(cachedValue);
     prop.Advanced = state->GetCacheEntryPropertyAsBool(*i, "ADVANCED");
-    if (t == cmState::BOOL) {
+    if (t == cmStateEnums::BOOL) {
       prop.Type = QCMakeProperty::BOOL;
       prop.Value = cmSystemTools::IsOn(cachedValue);
-    } else if (t == cmState::PATH) {
+    } else if (t == cmStateEnums::PATH) {
       prop.Type = QCMakeProperty::PATH;
-    } else if (t == cmState::FILEPATH) {
+    } else if (t == cmStateEnums::FILEPATH) {
       prop.Type = QCMakeProperty::FILEPATH;
-    } else if (t == cmState::STRING) {
+    } else if (t == cmStateEnums::STRING) {
       prop.Type = QCMakeProperty::STRING;
       const char* stringsProperty =
         state->GetCacheEntryProperty(*i, "STRINGS");
diff --git a/Source/QtDialog/RegexExplorer.cxx b/Source/QtDialog/RegexExplorer.cxx
index 1512166..abed70e 100644
--- a/Source/QtDialog/RegexExplorer.cxx
+++ b/Source/QtDialog/RegexExplorer.cxx
@@ -64,10 +64,32 @@ void RegexExplorer::on_inputText_textChanged()
     return;
   }
 
+  std::string matchingText;
+
+  if (matchAll->isChecked()) {
+    const char* p = m_text.c_str();
+    while (m_regexParser.find(p)) {
+      std::string::size_type l = m_regexParser.start();
+      std::string::size_type r = m_regexParser.end();
+      if (r - l == 0) {
+        // matched empty string
+        clearMatch();
+        return;
+      }
+      if (!matchingText.empty()) {
+        matchingText += ";";
+      }
+      matchingText += std::string(p + l, r - l);
+      p += r;
+    }
+  } else {
+    matchingText = m_regexParser.match(0);
+  }
+
 #ifdef QT_NO_STL
-  QString matchText = m_regexParser.match(0).c_str();
+  QString matchText = matchingText.c_str();
 #else
-  QString matchText = QString::fromStdString(m_regexParser.match(0));
+  QString matchText = QString::fromStdString(matchingText);
 #endif
   match0->setPlainText(matchText);
 
@@ -95,8 +117,16 @@ void RegexExplorer::on_matchNumber_currentIndexChanged(int index)
   matchN->setPlainText(match);
 }
 
+void RegexExplorer::on_matchAll_toggled(bool checked)
+{
+  Q_UNUSED(checked);
+
+  on_inputText_textChanged();
+}
+
 void RegexExplorer::clearMatch()
 {
+  m_matched = false;
   match0->clear();
   matchN->clear();
 }
diff --git a/Source/QtDialog/RegexExplorer.h b/Source/QtDialog/RegexExplorer.h
index f1c1e5f..caef975 100644
--- a/Source/QtDialog/RegexExplorer.h
+++ b/Source/QtDialog/RegexExplorer.h
@@ -22,6 +22,7 @@ private slots:
   void on_regularExpression_textChanged(const QString& text);
   void on_inputText_textChanged();
   void on_matchNumber_currentIndexChanged(int index);
+  void on_matchAll_toggled(bool checked);
 
 private:
   static void setStatusColor(QWidget* widget, bool successful);
diff --git a/Source/QtDialog/RegexExplorer.ui b/Source/QtDialog/RegexExplorer.ui
index 2c2d761..0af6999 100644
--- a/Source/QtDialog/RegexExplorer.ui
+++ b/Source/QtDialog/RegexExplorer.ui
@@ -104,11 +104,38 @@
     <widget class="QLineEdit" name="regularExpression"/>
    </item>
    <item>
-    <widget class="QLabel" name="label_3">
-     <property name="text">
-      <string>Complete Match</string>
-     </property>
-    </widget>
+    <layout class="QHBoxLayout" name="horizontalLayout_3">
+     <item>
+      <widget class="QLabel" name="label_3">
+       <property name="text">
+        <string>Complete Match</string>
+       </property>
+      </widget>
+     </item>
+     <item>
+      <spacer name="horizontalSpacer_5">
+       <property name="orientation">
+        <enum>Qt::Horizontal</enum>
+       </property>
+       <property name="sizeType">
+        <enum>QSizePolicy::Fixed</enum>
+       </property>
+       <property name="sizeHint" stdset="0">
+        <size>
+         <width>40</width>
+         <height>20</height>
+        </size>
+       </property>
+      </spacer>
+     </item>
+     <item>
+      <widget class="QCheckBox" name="matchAll">
+       <property name="text">
+        <string>Match All</string>
+       </property>
+      </widget>
+     </item>
+    </layout>
    </item>
    <item>
     <widget class="QPlainTextEdit" name="match0">
diff --git a/Source/QtIFW/CMake.DeveloperReference.HTML.qs.in b/Source/QtIFW/CMake.DeveloperReference.HTML.qs.in
index e3d8554..8cc5835 100644
--- a/Source/QtIFW/CMake.DeveloperReference.HTML.qs.in
+++ b/Source/QtIFW/CMake.DeveloperReference.HTML.qs.in
@@ -11,8 +11,8 @@ Component.prototype.createOperations = function()
     if (installer.value("os") === "win") {
 
         component.addOperation("CreateShortcut",
-                               installer.value("TargetDir") + "/@CMAKE_DOC_DIR@/developer-reference/html/index.html",
-                               installer.value("StartMenuDir") + "/CMake Developer Reference.lnk");
+                               "@TargetDir@/%CMAKE_DOC_DIR%/developer-reference/html/index.html",
+                               "@StartMenuDir@/CMake Developer Reference.lnk");
 
     }
 
diff --git a/Source/QtIFW/CMake.Dialogs.QtGUI.qs b/Source/QtIFW/CMake.Dialogs.QtGUI.qs
deleted file mode 100644
index 219a0a9..0000000
--- a/Source/QtIFW/CMake.Dialogs.QtGUI.qs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Component: CMake.Dialogs.QtGUI
-
-function Component()
-{
-    // Default constructor
-}
-
-Component.prototype.createOperations = function()
-{
-    // Create shortcut
-    if (installer.value("os") === "win") {
-
-        component.addOperation("CreateShortcut",
-                               installer.value("TargetDir") + "/bin/cmake-gui.exe",
-                               installer.value("StartMenuDir") + "/CMake (cmake-gui).lnk");
-
-    }
-
-    // Call default implementation
-    component.createOperations();
-}
diff --git a/Source/QtIFW/CMake.Dialogs.QtGUI.qs.in b/Source/QtIFW/CMake.Dialogs.QtGUI.qs.in
new file mode 100644
index 0000000..71f395a
--- /dev/null
+++ b/Source/QtIFW/CMake.Dialogs.QtGUI.qs.in
@@ -0,0 +1,21 @@
+// Component: CMake.Dialogs.QtGUI
+
+function Component()
+{
+    // Default constructor
+}
+
+Component.prototype.createOperations = function()
+{
+    // Create shortcut
+    if (installer.value("os") === "win") {
+
+        component.addOperation("CreateShortcut",
+                               "@TargetDir@/%CMAKE_BIN_DIR%/cmake-gui.exe",
+                               "@StartMenuDir@/CMake (cmake-gui).lnk");
+
+    }
+
+    // Call default implementation
+    component.createOperations();
+}
diff --git a/Source/QtIFW/CMake.Documentation.SphinxHTML.qs.in b/Source/QtIFW/CMake.Documentation.SphinxHTML.qs.in
index 5c929e8..54bc14a 100644
--- a/Source/QtIFW/CMake.Documentation.SphinxHTML.qs.in
+++ b/Source/QtIFW/CMake.Documentation.SphinxHTML.qs.in
@@ -11,8 +11,8 @@ Component.prototype.createOperations = function()
     if (installer.value("os") === "win") {
 
         component.addOperation("CreateShortcut",
-                               installer.value("TargetDir") + "/@CMAKE_DOC_DIR@/html/index.html",
-                               installer.value("StartMenuDir") + "/CMake Documentation.lnk");
+                               "@TargetDir@/%CMAKE_DOC_DIR%/html/index.html",
+                               "@StartMenuDir@/CMake Documentation.lnk");
 
     }
 
diff --git a/Source/QtIFW/CMake.qs.in b/Source/QtIFW/CMake.qs.in
index 828cc7c..1f3166e 100644
--- a/Source/QtIFW/CMake.qs.in
+++ b/Source/QtIFW/CMake.qs.in
@@ -1,3 +1,5 @@
+// Component: CMake
+
 function Component()
 {
     // Default constructor
@@ -9,12 +11,12 @@ Component.prototype.createOperations = function()
     if (installer.value("os") === "win") {
 
         component.addOperation("CreateShortcut",
-                               installer.value("TargetDir") + "/@CMAKE_DOC_DIR@/cmake.org.html",
-                               installer.value("StartMenuDir") + "/CMake Web Site.lnk");
+                               "@TargetDir@/%CMAKE_DOC_DIR%/cmake.org.html",
+                               "@StartMenuDir@/CMake Web Site.lnk");
 
         component.addOperation("CreateShortcut",
-                               installer.value("TargetDir") + "/cmake-maintenance.exe",
-                               installer.value("StartMenuDir") + "/CMake Maintenance Tool.lnk");
+                               "@TargetDir@/cmake-maintenance.exe",
+                               "@StartMenuDir@/CMake Maintenance Tool.lnk");
     }
 
     // Call default implementation
diff --git a/Source/QtIFW/installscript.qs.in b/Source/QtIFW/installscript.qs.in
index 39a8795..72d49e8 100644
--- a/Source/QtIFW/installscript.qs.in
+++ b/Source/QtIFW/installscript.qs.in
@@ -1,3 +1,5 @@
+// Component: CMake
+
 function Component()
 {
     // Do not show component selection page
@@ -9,15 +11,15 @@ Component.prototype.createOperations = function()
     // Create shortcut
     if (installer.value("os") === "win") {
 
- at _CPACK_IFW_SHORTCUT_OPTIONAL@
+%_CPACK_IFW_SHORTCUT_OPTIONAL%
 
         component.addOperation("CreateShortcut",
-                               installer.value("TargetDir") + "/@CMAKE_DOC_DIR@/cmake.org.html",
-                               installer.value("StartMenuDir") + "/CMake Web Site.lnk");
+                               "@TargetDir@/%CMAKE_DOC_DIR%/cmake.org.html",
+                               "@StartMenuDir@/CMake Web Site.lnk");
 
         component.addOperation("CreateShortcut",
-                               installer.value("TargetDir") + "/cmake-maintenance.exe",
-                               installer.value("StartMenuDir") + "/CMake Maintenance Tool.lnk");
+                               "@TargetDir@/cmake-maintenance.exe",
+                               "@StartMenuDir@/CMake Maintenance Tool.lnk");
     }
 
     // Call default implementation
diff --git a/Source/bindexplib.cxx b/Source/bindexplib.cxx
index db97c47..eded883 100644
--- a/Source/bindexplib.cxx
+++ b/Source/bindexplib.cxx
@@ -62,11 +62,10 @@
 *----------------------------------------------------------------------
 */
 #include "bindexplib.h"
+
 #include <cmsys/Encoding.hxx>
 #include <fstream>
 #include <iostream>
-#include <stdio.h>
-#include <string>
 #include <windows.h>
 
 typedef struct cmANON_OBJECT_HEADER_BIGOBJ {
diff --git a/Source/bindexplib.h b/Source/bindexplib.h
index 1a0c3a3..d6900ba 100644
--- a/Source/bindexplib.h
+++ b/Source/bindexplib.h
@@ -5,8 +5,9 @@
 
 #include <cmConfigure.h>
 
-#include "cmStandardIncludes.h"
-
+#include <set>
+#include <stdio.h>
+#include <string>
 
 class bindexplib
 {
diff --git a/Source/cmAddCompileOptionsCommand.cxx b/Source/cmAddCompileOptionsCommand.cxx
index 9265cba..21a8012 100644
--- a/Source/cmAddCompileOptionsCommand.cxx
+++ b/Source/cmAddCompileOptionsCommand.cxx
@@ -2,6 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddCompileOptionsCommand.h"
 
+#include "cmMakefile.h"
+
+class cmExecutionStatus;
+
 bool cmAddCompileOptionsCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
 {
diff --git a/Source/cmAddCompileOptionsCommand.h b/Source/cmAddCompileOptionsCommand.h
index 52c4b51..71009b4 100644
--- a/Source/cmAddCompileOptionsCommand.h
+++ b/Source/cmAddCompileOptionsCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmAddCompileOptionsCommand_h
 #define cmAddCompileOptionsCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 class cmAddCompileOptionsCommand : public cmCommand
 {
 public:
@@ -24,8 +30,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "add_compile_options"; }
-
-  cmTypeMacro(cmAddCompileOptionsCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmAddCustomCommandCommand.cxx b/Source/cmAddCustomCommandCommand.cxx
index 1ab4ef6..a100617 100644
--- a/Source/cmAddCustomCommandCommand.cxx
+++ b/Source/cmAddCustomCommandCommand.cxx
@@ -2,11 +2,19 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddCustomCommandCommand.h"
 
-#include "cmTarget.h"
+#include <sstream>
 
+#include "cmCustomCommand.h"
+#include "cmCustomCommandLines.h"
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
 #include "cmSourceFile.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmake.h"
 
-#include "cmGlobalGenerator.h"
+class cmExecutionStatus;
 
 // cmAddCustomCommandCommand
 bool cmAddCustomCommandCommand::InitialPass(
@@ -28,6 +36,7 @@ bool cmAddCustomCommandCommand::InitialPass(
   bool verbatim = false;
   bool append = false;
   bool uses_terminal = false;
+  bool command_expand_lists = false;
   std::string implicit_depends_lang;
   cmCustomCommand::ImplicitDependsList implicit_depends;
 
@@ -84,6 +93,8 @@ bool cmAddCustomCommandCommand::InitialPass(
       append = true;
     } else if (copy == "USES_TERMINAL") {
       uses_terminal = true;
+    } else if (copy == "COMMAND_EXPAND_LISTS") {
+      command_expand_lists = true;
     } else if (copy == "TARGET") {
       doing = doing_target;
     } else if (copy == "ARGS") {
@@ -273,12 +284,14 @@ bool cmAddCustomCommandCommand::InitialPass(
     std::vector<std::string> no_depends;
     this->Makefile->AddCustomCommandToTarget(
       target, byproducts, no_depends, commandLines, cctype, comment,
-      working.c_str(), escapeOldStyle, uses_terminal, depfile);
+      working.c_str(), escapeOldStyle, uses_terminal, depfile,
+      command_expand_lists);
   } else if (target.empty()) {
     // Target is empty, use the output.
     this->Makefile->AddCustomCommandToOutput(
       output, byproducts, depends, main_dependency, commandLines, comment,
-      working.c_str(), false, escapeOldStyle, uses_terminal, depfile);
+      working.c_str(), false, escapeOldStyle, uses_terminal,
+      command_expand_lists, depfile);
 
     // Add implicit dependency scanning requests if any were given.
     if (!implicit_depends.empty()) {
diff --git a/Source/cmAddCustomCommandCommand.h b/Source/cmAddCustomCommandCommand.h
index 527bb6c..ea92163 100644
--- a/Source/cmAddCustomCommandCommand.h
+++ b/Source/cmAddCustomCommandCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmAddCustomCommandCommand_h
 #define cmAddCustomCommandCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmAddCustomCommandCommand
  * \brief cmAddCustomCommandCommand defines a new command (rule) that can
  *  be executed within the build process
@@ -31,8 +37,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "add_custom_command"; }
 
-  cmTypeMacro(cmAddCustomCommandCommand, cmCommand);
-
 protected:
   bool CheckOutputs(const std::vector<std::string>& outputs);
 };
diff --git a/Source/cmAddCustomTargetCommand.cxx b/Source/cmAddCustomTargetCommand.cxx
index 9c41dac..0d01493 100644
--- a/Source/cmAddCustomTargetCommand.cxx
+++ b/Source/cmAddCustomTargetCommand.cxx
@@ -2,8 +2,18 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddCustomTargetCommand.h"
 
+#include <sstream>
+
+#include "cmCustomCommandLines.h"
 #include "cmGeneratorExpression.h"
 #include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 // cmAddCustomTargetCommand
 bool cmAddCustomTargetCommand::InitialPass(
@@ -37,6 +47,7 @@ bool cmAddCustomTargetCommand::InitialPass(
   std::string working_directory;
   bool verbatim = false;
   bool uses_terminal = false;
+  bool command_expand_lists = false;
   std::string comment_buffer;
   const char* comment = CM_NULLPTR;
   std::vector<std::string> sources;
@@ -80,6 +91,9 @@ bool cmAddCustomTargetCommand::InitialPass(
     } else if (copy == "USES_TERMINAL") {
       doing = doing_nothing;
       uses_terminal = true;
+    } else if (copy == "COMMAND_EXPAND_LISTS") {
+      doing = doing_nothing;
+      command_expand_lists = true;
     } else if (copy == "COMMENT") {
       doing = doing_comment;
     } else if (copy == "COMMAND") {
@@ -144,7 +158,7 @@ bool cmAddCustomTargetCommand::InitialPass(
   bool nameOk = cmGeneratorExpression::IsValidTargetName(targetName) &&
     !cmGlobalGenerator::IsReservedTarget(targetName);
   if (nameOk) {
-    nameOk = targetName.find(":") == std::string::npos;
+    nameOk = targetName.find(':') == std::string::npos;
   }
   if (!nameOk) {
     cmake::MessageType messageType = cmake::AUTHOR_WARNING;
@@ -211,12 +225,19 @@ bool cmAddCustomTargetCommand::InitialPass(
       "USES_TERMINAL may not be specified without any COMMAND");
     return true;
   }
+  if (commandLines.empty() && command_expand_lists) {
+    this->Makefile->IssueMessage(
+      cmake::FATAL_ERROR,
+      "COMMAND_EXPAND_LISTS may not be specified without any COMMAND");
+    return true;
+  }
 
   // Add the utility target to the makefile.
   bool escapeOldStyle = !verbatim;
   cmTarget* target = this->Makefile->AddUtilityCommand(
     targetName, excludeFromAll, working_directory.c_str(), byproducts, depends,
-    commandLines, escapeOldStyle, comment, uses_terminal);
+    commandLines, escapeOldStyle, comment, uses_terminal,
+    command_expand_lists);
 
   // Add additional user-specified source files to the target.
   target->AddSources(sources);
diff --git a/Source/cmAddCustomTargetCommand.h b/Source/cmAddCustomTargetCommand.h
index a4475c7..b679247 100644
--- a/Source/cmAddCustomTargetCommand.h
+++ b/Source/cmAddCustomTargetCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmAddCustomTargetCommand_h
 #define cmAddCustomTargetCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmAddCustomTargetCommand
  * \brief Command that adds a target to the build system.
  *
@@ -31,8 +37,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "add_custom_target"; }
-
-  cmTypeMacro(cmAddCustomTargetCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmAddDefinitionsCommand.cxx b/Source/cmAddDefinitionsCommand.cxx
index 8d82e71..9e0607c 100644
--- a/Source/cmAddDefinitionsCommand.cxx
+++ b/Source/cmAddDefinitionsCommand.cxx
@@ -2,6 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddDefinitionsCommand.h"
 
+#include "cmMakefile.h"
+
+class cmExecutionStatus;
+
 // cmAddDefinitionsCommand
 bool cmAddDefinitionsCommand::InitialPass(std::vector<std::string> const& args,
                                           cmExecutionStatus&)
diff --git a/Source/cmAddDefinitionsCommand.h b/Source/cmAddDefinitionsCommand.h
index 43d0199..735f8cc 100644
--- a/Source/cmAddDefinitionsCommand.h
+++ b/Source/cmAddDefinitionsCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmAddDefinitionsCommand_h
 #define cmAddDefinitionsCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmAddDefinitionsCommand
  * \brief Specify a list of compiler defines
  *
@@ -30,8 +36,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "add_definitions"; }
-
-  cmTypeMacro(cmAddDefinitionsCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmAddDependenciesCommand.cxx b/Source/cmAddDependenciesCommand.cxx
index 0fa8943..e49d5d5 100644
--- a/Source/cmAddDependenciesCommand.cxx
+++ b/Source/cmAddDependenciesCommand.cxx
@@ -2,7 +2,13 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddDependenciesCommand.h"
 
-#include "cmGlobalGenerator.h"
+#include <sstream>
+
+#include "cmMakefile.h"
+#include "cmTarget.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 // cmDependenciesCommand
 bool cmAddDependenciesCommand::InitialPass(
diff --git a/Source/cmAddDependenciesCommand.h b/Source/cmAddDependenciesCommand.h
index 95e2ac6..8be546c 100644
--- a/Source/cmAddDependenciesCommand.h
+++ b/Source/cmAddDependenciesCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmDependenciessCommand_h
 #define cmDependenciessCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmAddDependenciesCommand
  * \brief Add a dependency to a target
  *
@@ -29,8 +35,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "add_dependencies"; }
-
-  cmTypeMacro(cmAddDependenciesCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmAddExecutableCommand.cxx b/Source/cmAddExecutableCommand.cxx
index 96ad82a..aae1085 100644
--- a/Source/cmAddExecutableCommand.cxx
+++ b/Source/cmAddExecutableCommand.cxx
@@ -2,6 +2,18 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddExecutableCommand.h"
 
+#include <sstream>
+
+#include "cmGeneratorExpression.h"
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmStateTypes.h"
+#include "cmTarget.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
+
 // cmExecutableCommand
 bool cmAddExecutableCommand::InitialPass(std::vector<std::string> const& args,
                                          cmExecutionStatus&)
@@ -49,7 +61,7 @@ bool cmAddExecutableCommand::InitialPass(std::vector<std::string> const& args,
     !cmGlobalGenerator::IsReservedTarget(exename);
 
   if (nameOk && !importTarget && !isAlias) {
-    nameOk = exename.find(":") == std::string::npos;
+    nameOk = exename.find(':') == std::string::npos;
   }
   if (!nameOk) {
     cmake::MessageType messageType = cmake::AUTHOR_WARNING;
@@ -133,8 +145,8 @@ bool cmAddExecutableCommand::InitialPass(std::vector<std::string> const& args,
       this->SetError(e.str());
       return false;
     }
-    cmState::TargetType type = aliasedTarget->GetType();
-    if (type != cmState::EXECUTABLE) {
+    cmStateEnums::TargetType type = aliasedTarget->GetType();
+    if (type != cmStateEnums::EXECUTABLE) {
       std::ostringstream e;
       e << "cannot create ALIAS target \"" << exename << "\" because target \""
         << aliasedName << "\" is not an "
@@ -165,7 +177,7 @@ bool cmAddExecutableCommand::InitialPass(std::vector<std::string> const& args,
     }
 
     // Create the imported target.
-    this->Makefile->AddImportedTarget(exename, cmState::EXECUTABLE,
+    this->Makefile->AddImportedTarget(exename, cmStateEnums::EXECUTABLE,
                                       importGlobal);
     return true;
   }
diff --git a/Source/cmAddExecutableCommand.h b/Source/cmAddExecutableCommand.h
index fc08e8b..62583d8 100644
--- a/Source/cmAddExecutableCommand.h
+++ b/Source/cmAddExecutableCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmExecutablesCommand_h
 #define cmExecutablesCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmExecutablesCommand
  * \brief Defines a list of executables to build.
  *
@@ -30,8 +36,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "add_executable"; }
-
-  cmTypeMacro(cmAddExecutableCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmAddLibraryCommand.cxx b/Source/cmAddLibraryCommand.cxx
index 26e38b8..9ae4ace 100644
--- a/Source/cmAddLibraryCommand.cxx
+++ b/Source/cmAddLibraryCommand.cxx
@@ -2,9 +2,20 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddLibraryCommand.h"
 
+#include <sstream>
+
+#include "cmGeneratorExpression.h"
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
 #include "cmState.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
 #include "cmake.h"
 
+class cmExecutionStatus;
+
 // cmLibraryCommand
 bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args,
                                       cmExecutionStatus&)
@@ -15,10 +26,10 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args,
   }
   // Library type defaults to value of BUILD_SHARED_LIBS, if it exists,
   // otherwise it defaults to static library.
-  cmState::TargetType type = cmState::SHARED_LIBRARY;
+  cmStateEnums::TargetType type = cmStateEnums::SHARED_LIBRARY;
   if (cmSystemTools::IsOff(
         this->Makefile->GetDefinition("BUILD_SHARED_LIBS"))) {
-    type = cmState::STATIC_LIBRARY;
+    type = cmStateEnums::STATIC_LIBRARY;
   }
   bool excludeFromAll = false;
   bool importTarget = false;
@@ -38,57 +49,57 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args,
   while (s != args.end()) {
     std::string libType = *s;
     if (libType == "STATIC") {
-      if (type == cmState::INTERFACE_LIBRARY) {
+      if (type == cmStateEnums::INTERFACE_LIBRARY) {
         std::ostringstream e;
         e << "INTERFACE library specified with conflicting STATIC type.";
         this->SetError(e.str());
         return false;
       }
       ++s;
-      type = cmState::STATIC_LIBRARY;
+      type = cmStateEnums::STATIC_LIBRARY;
       haveSpecifiedType = true;
     } else if (libType == "SHARED") {
-      if (type == cmState::INTERFACE_LIBRARY) {
+      if (type == cmStateEnums::INTERFACE_LIBRARY) {
         std::ostringstream e;
         e << "INTERFACE library specified with conflicting SHARED type.";
         this->SetError(e.str());
         return false;
       }
       ++s;
-      type = cmState::SHARED_LIBRARY;
+      type = cmStateEnums::SHARED_LIBRARY;
       haveSpecifiedType = true;
     } else if (libType == "MODULE") {
-      if (type == cmState::INTERFACE_LIBRARY) {
+      if (type == cmStateEnums::INTERFACE_LIBRARY) {
         std::ostringstream e;
         e << "INTERFACE library specified with conflicting MODULE type.";
         this->SetError(e.str());
         return false;
       }
       ++s;
-      type = cmState::MODULE_LIBRARY;
+      type = cmStateEnums::MODULE_LIBRARY;
       haveSpecifiedType = true;
     } else if (libType == "OBJECT") {
-      if (type == cmState::INTERFACE_LIBRARY) {
+      if (type == cmStateEnums::INTERFACE_LIBRARY) {
         std::ostringstream e;
         e << "INTERFACE library specified with conflicting OBJECT type.";
         this->SetError(e.str());
         return false;
       }
       ++s;
-      type = cmState::OBJECT_LIBRARY;
+      type = cmStateEnums::OBJECT_LIBRARY;
       haveSpecifiedType = true;
     } else if (libType == "UNKNOWN") {
-      if (type == cmState::INTERFACE_LIBRARY) {
+      if (type == cmStateEnums::INTERFACE_LIBRARY) {
         std::ostringstream e;
         e << "INTERFACE library specified with conflicting UNKNOWN type.";
         this->SetError(e.str());
         return false;
       }
       ++s;
-      type = cmState::UNKNOWN_LIBRARY;
+      type = cmStateEnums::UNKNOWN_LIBRARY;
       haveSpecifiedType = true;
     } else if (libType == "ALIAS") {
-      if (type == cmState::INTERFACE_LIBRARY) {
+      if (type == cmStateEnums::INTERFACE_LIBRARY) {
         std::ostringstream e;
         e << "INTERFACE library specified with conflicting ALIAS type.";
         this->SetError(e.str());
@@ -116,10 +127,10 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args,
         return false;
       }
       ++s;
-      type = cmState::INTERFACE_LIBRARY;
+      type = cmStateEnums::INTERFACE_LIBRARY;
       haveSpecifiedType = true;
     } else if (*s == "EXCLUDE_FROM_ALL") {
-      if (type == cmState::INTERFACE_LIBRARY) {
+      if (type == cmStateEnums::INTERFACE_LIBRARY) {
         std::ostringstream e;
         e << "INTERFACE library may not be used with EXCLUDE_FROM_ALL.";
         this->SetError(e.str());
@@ -133,7 +144,7 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args,
     } else if (importTarget && *s == "GLOBAL") {
       ++s;
       importGlobal = true;
-    } else if (type == cmState::INTERFACE_LIBRARY && *s == "GLOBAL") {
+    } else if (type == cmStateEnums::INTERFACE_LIBRARY && *s == "GLOBAL") {
       std::ostringstream e;
       e << "GLOBAL option may only be used with IMPORTED libraries.";
       this->SetError(e.str());
@@ -143,7 +154,7 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args,
     }
   }
 
-  if (type == cmState::INTERFACE_LIBRARY) {
+  if (type == cmStateEnums::INTERFACE_LIBRARY) {
     if (s != args.end()) {
       std::ostringstream e;
       e << "INTERFACE library requires no source arguments.";
@@ -162,7 +173,7 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args,
     !cmGlobalGenerator::IsReservedTarget(libName);
 
   if (nameOk && !importTarget && !isAlias) {
-    nameOk = libName.find(":") == std::string::npos;
+    nameOk = libName.find(':') == std::string::npos;
   }
   if (!nameOk) {
     cmake::MessageType messageType = cmake::AUTHOR_WARNING;
@@ -170,7 +181,7 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args,
     bool issueMessage = false;
     switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0037)) {
       case cmPolicies::WARN:
-        if (type != cmState::INTERFACE_LIBRARY) {
+        if (type != cmStateEnums::INTERFACE_LIBRARY) {
           e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0037) << "\n";
           issueMessage = true;
         }
@@ -233,12 +244,12 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args,
       this->SetError(e.str());
       return false;
     }
-    cmState::TargetType aliasedType = aliasedTarget->GetType();
-    if (aliasedType != cmState::SHARED_LIBRARY &&
-        aliasedType != cmState::STATIC_LIBRARY &&
-        aliasedType != cmState::MODULE_LIBRARY &&
-        aliasedType != cmState::OBJECT_LIBRARY &&
-        aliasedType != cmState::INTERFACE_LIBRARY) {
+    cmStateEnums::TargetType aliasedType = aliasedTarget->GetType();
+    if (aliasedType != cmStateEnums::SHARED_LIBRARY &&
+        aliasedType != cmStateEnums::STATIC_LIBRARY &&
+        aliasedType != cmStateEnums::MODULE_LIBRARY &&
+        aliasedType != cmStateEnums::OBJECT_LIBRARY &&
+        aliasedType != cmStateEnums::INTERFACE_LIBRARY) {
       std::ostringstream e;
       e << "cannot create ALIAS target \"" << libName << "\" because target \""
         << aliasedName << "\" is not a library.";
@@ -265,16 +276,17 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args,
     CMAKE_${LANG}_CREATE_SHARED_LIBRARY is defined and if not default to
     STATIC. But at this point we know only the name of the target, but not
     yet its linker language. */
-  if ((type == cmState::SHARED_LIBRARY || type == cmState::MODULE_LIBRARY) &&
-      (this->Makefile->GetState()->GetGlobalPropertyAsBool(
-         "TARGET_SUPPORTS_SHARED_LIBS") == false)) {
+  if ((type == cmStateEnums::SHARED_LIBRARY ||
+       type == cmStateEnums::MODULE_LIBRARY) &&
+      !this->Makefile->GetState()->GetGlobalPropertyAsBool(
+        "TARGET_SUPPORTS_SHARED_LIBS")) {
     std::ostringstream w;
     w << "ADD_LIBRARY called with "
-      << (type == cmState::SHARED_LIBRARY ? "SHARED" : "MODULE")
+      << (type == cmStateEnums::SHARED_LIBRARY ? "SHARED" : "MODULE")
       << " option but the target platform does not support dynamic linking. "
          "Building a STATIC library instead. This may lead to problems.";
     this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
-    type = cmState::STATIC_LIBRARY;
+    type = cmStateEnums::STATIC_LIBRARY;
   }
 
   // Handle imported target creation.
@@ -284,13 +296,13 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args,
       this->SetError("called with IMPORTED argument but no library type.");
       return false;
     }
-    if (type == cmState::OBJECT_LIBRARY) {
+    if (type == cmStateEnums::OBJECT_LIBRARY) {
       this->Makefile->IssueMessage(
         cmake::FATAL_ERROR,
         "The OBJECT library type may not be used for IMPORTED libraries.");
       return true;
     }
-    if (type == cmState::INTERFACE_LIBRARY) {
+    if (type == cmStateEnums::INTERFACE_LIBRARY) {
       if (!cmGeneratorExpression::IsValidTargetName(libName)) {
         std::ostringstream e;
         e << "Invalid name for IMPORTED INTERFACE library target: " << libName;
@@ -314,7 +326,7 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args,
   }
 
   // A non-imported target may not have UNKNOWN type.
-  if (type == cmState::UNKNOWN_LIBRARY) {
+  if (type == cmStateEnums::UNKNOWN_LIBRARY) {
     this->Makefile->IssueMessage(
       cmake::FATAL_ERROR,
       "The UNKNOWN library type may be used only for IMPORTED libraries.");
@@ -332,7 +344,7 @@ bool cmAddLibraryCommand::InitialPass(std::vector<std::string> const& args,
 
   std::vector<std::string> srclists;
 
-  if (type == cmState::INTERFACE_LIBRARY) {
+  if (type == cmStateEnums::INTERFACE_LIBRARY) {
     if (!cmGeneratorExpression::IsValidTargetName(libName) ||
         libName.find("::") != std::string::npos) {
       std::ostringstream e;
diff --git a/Source/cmAddLibraryCommand.h b/Source/cmAddLibraryCommand.h
index d072b80..c23b299 100644
--- a/Source/cmAddLibraryCommand.h
+++ b/Source/cmAddLibraryCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmLibrarysCommand_h
 #define cmLibrarysCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmLibrarysCommand
  * \brief Defines a list of executables to build.
  *
@@ -30,8 +36,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "add_library"; }
-
-  cmTypeMacro(cmAddLibraryCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmAddSubDirectoryCommand.cxx b/Source/cmAddSubDirectoryCommand.cxx
index bb1e239..34ec0e3 100644
--- a/Source/cmAddSubDirectoryCommand.cxx
+++ b/Source/cmAddSubDirectoryCommand.cxx
@@ -2,6 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddSubDirectoryCommand.h"
 
+#include <sstream>
+#include <string.h>
+
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmAddSubDirectoryCommand
 bool cmAddSubDirectoryCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
diff --git a/Source/cmAddSubDirectoryCommand.h b/Source/cmAddSubDirectoryCommand.h
index 7347482..85305e6 100644
--- a/Source/cmAddSubDirectoryCommand.h
+++ b/Source/cmAddSubDirectoryCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmAddSubDirectoryCommand_h
 #define cmAddSubDirectoryCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmAddSubDirectoryCommand
  * \brief Specify a subdirectory to build
  *
@@ -31,8 +37,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "add_subdirectory"; }
-
-  cmTypeMacro(cmAddSubDirectoryCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmAddTestCommand.cxx b/Source/cmAddTestCommand.cxx
index 11342ee..3a3afdb 100644
--- a/Source/cmAddTestCommand.cxx
+++ b/Source/cmAddTestCommand.cxx
@@ -2,9 +2,13 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAddTestCommand.h"
 
-#include "cmTestGenerator.h"
+#include <sstream>
 
+#include "cmMakefile.h"
 #include "cmTest.h"
+#include "cmTestGenerator.h"
+
+class cmExecutionStatus;
 
 // cmExecutableCommand
 bool cmAddTestCommand::InitialPass(std::vector<std::string> const& args,
diff --git a/Source/cmAddTestCommand.h b/Source/cmAddTestCommand.h
index 92db7bc..07eff68 100644
--- a/Source/cmAddTestCommand.h
+++ b/Source/cmAddTestCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmAddTestCommand_h
 #define cmAddTestCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmAddTestCommand
  * \brief Add a test to the lists of tests to run.
  *
@@ -30,8 +36,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "add_test"; }
 
-  cmTypeMacro(cmAddTestCommand, cmCommand);
-
 private:
   bool HandleNameMode(std::vector<std::string> const& args);
 };
diff --git a/Source/cmAlgorithms.h b/Source/cmAlgorithms.h
index aa55379..7c683ad 100644
--- a/Source/cmAlgorithms.h
+++ b/Source/cmAlgorithms.h
@@ -3,9 +3,17 @@
 #ifndef cmAlgorithms_h
 #define cmAlgorithms_h
 
-#include <cmConfigure.h>
-
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <algorithm>
+#include <cm_kwiml.h>
+#include <functional>
+#include <iterator>
+#include <sstream>
+#include <string.h>
+#include <string>
+#include <utility>
+#include <vector>
 
 inline bool cmHasLiteralPrefixImpl(const std::string& str1, const char* str2,
                                    size_t N)
@@ -234,7 +242,7 @@ std::string cmJoin(Range const& r, const char* delimiter)
 }
 
 template <typename Range>
-std::string cmJoin(Range const& r, std::string delimiter)
+std::string cmJoin(Range const& r, std::string const& delimiter)
 {
   return cmJoin(r, delimiter.c_str());
 }
@@ -336,13 +344,13 @@ typename Range::const_iterator cmRemoveDuplicates(Range& r)
 }
 
 template <typename Range>
-std::string cmWrap(std::string prefix, Range const& r, std::string suffix,
-                   std::string sep)
+std::string cmWrap(std::string const& prefix, Range const& r,
+                   std::string const& suffix, std::string const& sep)
 {
   if (r.empty()) {
     return std::string();
   }
-  return prefix + cmJoin(r, (suffix + sep + prefix).c_str()) + suffix;
+  return prefix + cmJoin(r, suffix + sep + prefix) + suffix;
 }
 
 template <typename Range>
diff --git a/Source/cmAuxSourceDirectoryCommand.cxx b/Source/cmAuxSourceDirectoryCommand.cxx
index 6655911..7cfa4d8 100644
--- a/Source/cmAuxSourceDirectoryCommand.cxx
+++ b/Source/cmAuxSourceDirectoryCommand.cxx
@@ -2,9 +2,17 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmAuxSourceDirectoryCommand.h"
 
+#include <algorithm>
+#include <cmsys/Directory.hxx>
+#include <stddef.h>
+
+#include "cmAlgorithms.h"
+#include "cmMakefile.h"
 #include "cmSourceFile.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
 
-#include <cmsys/Directory.hxx>
+class cmExecutionStatus;
 
 // cmAuxSourceDirectoryCommand
 bool cmAuxSourceDirectoryCommand::InitialPass(
@@ -36,12 +44,12 @@ bool cmAuxSourceDirectoryCommand::InitialPass(
 
   // Load all the files in the directory
   cmsys::Directory dir;
-  if (dir.Load(tdir.c_str())) {
+  if (dir.Load(tdir)) {
     size_t numfiles = dir.GetNumberOfFiles();
     for (size_t i = 0; i < numfiles; ++i) {
       std::string file = dir.GetFile(static_cast<unsigned long>(i));
       // Split the filename into base and extension
-      std::string::size_type dotpos = file.rfind(".");
+      std::string::size_type dotpos = file.rfind('.');
       if (dotpos != std::string::npos) {
         std::string ext = file.substr(dotpos + 1);
         std::string base = file.substr(0, dotpos);
diff --git a/Source/cmAuxSourceDirectoryCommand.h b/Source/cmAuxSourceDirectoryCommand.h
index cca70dc..d99bf7b 100644
--- a/Source/cmAuxSourceDirectoryCommand.h
+++ b/Source/cmAuxSourceDirectoryCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmAuxSourceDirectoryCommand_h
 #define cmAuxSourceDirectoryCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmAuxSourceDirectoryCommand
  * \brief Specify auxiliary source code directories.
  *
@@ -33,8 +39,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "aux_source_directory"; }
-
-  cmTypeMacro(cmAuxSourceDirectoryCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmBootstrapCommands1.cxx b/Source/cmBootstrapCommands1.cxx
deleted file mode 100644
index 2b3b62f..0000000
--- a/Source/cmBootstrapCommands1.cxx
+++ /dev/null
@@ -1,87 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-// This file is used to compile all the commands
-// that CMake knows about at compile time.
-// This is sort of a boot strapping approach since you would
-// like to have CMake to build CMake.
-#include "cmAddCustomCommandCommand.cxx"
-#include "cmAddCustomTargetCommand.cxx"
-#include "cmAddDefinitionsCommand.cxx"
-#include "cmAddDependenciesCommand.cxx"
-#include "cmAddExecutableCommand.cxx"
-#include "cmAddLibraryCommand.cxx"
-#include "cmAddSubDirectoryCommand.cxx"
-#include "cmAddTestCommand.cxx"
-#include "cmBreakCommand.cxx"
-#include "cmBuildCommand.cxx"
-#include "cmCMakeMinimumRequired.cxx"
-#include "cmCMakePolicyCommand.cxx"
-#include "cmCommandArgumentsHelper.cxx"
-#include "cmCommands.h"
-#include "cmConfigureFileCommand.cxx"
-#include "cmContinueCommand.cxx"
-#include "cmCoreTryCompile.cxx"
-#include "cmCreateTestSourceList.cxx"
-#include "cmDefinePropertyCommand.cxx"
-#include "cmElseCommand.cxx"
-#include "cmEnableLanguageCommand.cxx"
-#include "cmEnableTestingCommand.cxx"
-#include "cmEndForEachCommand.cxx"
-#include "cmEndFunctionCommand.cxx"
-#include "cmEndIfCommand.cxx"
-#include "cmEndMacroCommand.cxx"
-#include "cmEndWhileCommand.cxx"
-#include "cmExecProgramCommand.cxx"
-#include "cmExecuteProcessCommand.cxx"
-#include "cmFileCommand.cxx"
-#include "cmFindBase.cxx"
-#include "cmFindCommon.cxx"
-#include "cmFindFileCommand.cxx"
-#include "cmFindLibraryCommand.cxx"
-#include "cmFindPackageCommand.cxx"
-#include "cmFindPathCommand.cxx"
-#include "cmFindProgramCommand.cxx"
-#include "cmForEachCommand.cxx"
-#include "cmFunctionCommand.cxx"
-#include "cmParseArgumentsCommand.cxx"
-#include "cmPathLabel.cxx"
-#include "cmSearchPath.cxx"
-
-void GetBootstrapCommands1(std::vector<cmCommand*>& commands)
-{
-  commands.push_back(new cmAddCustomCommandCommand);
-  commands.push_back(new cmAddCustomTargetCommand);
-  commands.push_back(new cmAddDefinitionsCommand);
-  commands.push_back(new cmAddDependenciesCommand);
-  commands.push_back(new cmAddExecutableCommand);
-  commands.push_back(new cmAddLibraryCommand);
-  commands.push_back(new cmAddSubDirectoryCommand);
-  commands.push_back(new cmAddTestCommand);
-  commands.push_back(new cmBreakCommand);
-  commands.push_back(new cmBuildCommand);
-  commands.push_back(new cmCMakeMinimumRequired);
-  commands.push_back(new cmCMakePolicyCommand);
-  commands.push_back(new cmConfigureFileCommand);
-  commands.push_back(new cmContinueCommand);
-  commands.push_back(new cmCreateTestSourceList);
-  commands.push_back(new cmDefinePropertyCommand);
-  commands.push_back(new cmElseCommand);
-  commands.push_back(new cmEnableLanguageCommand);
-  commands.push_back(new cmEnableTestingCommand);
-  commands.push_back(new cmEndForEachCommand);
-  commands.push_back(new cmEndFunctionCommand);
-  commands.push_back(new cmEndIfCommand);
-  commands.push_back(new cmEndMacroCommand);
-  commands.push_back(new cmEndWhileCommand);
-  commands.push_back(new cmExecProgramCommand);
-  commands.push_back(new cmExecuteProcessCommand);
-  commands.push_back(new cmFileCommand);
-  commands.push_back(new cmFindFileCommand);
-  commands.push_back(new cmFindLibraryCommand);
-  commands.push_back(new cmFindPackageCommand);
-  commands.push_back(new cmFindPathCommand);
-  commands.push_back(new cmFindProgramCommand);
-  commands.push_back(new cmForEachCommand);
-  commands.push_back(new cmFunctionCommand);
-  commands.push_back(new cmParseArgumentsCommand);
-}
diff --git a/Source/cmBootstrapCommands2.cxx b/Source/cmBootstrapCommands2.cxx
deleted file mode 100644
index 625c3e0..0000000
--- a/Source/cmBootstrapCommands2.cxx
+++ /dev/null
@@ -1,94 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-// This file is used to compile all the commands
-// that CMake knows about at compile time.
-// 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 "cmGetCMakePropertyCommand.cxx"
-#include "cmGetDirectoryPropertyCommand.cxx"
-#include "cmGetFilenameComponentCommand.cxx"
-#include "cmGetPropertyCommand.cxx"
-#include "cmGetSourceFilePropertyCommand.cxx"
-#include "cmGetTargetPropertyCommand.cxx"
-#include "cmGetTestPropertyCommand.cxx"
-#include "cmHexFileConverter.cxx"
-#include "cmIfCommand.cxx"
-#include "cmIncludeCommand.cxx"
-#include "cmIncludeDirectoryCommand.cxx"
-#include "cmIncludeRegularExpressionCommand.cxx"
-#include "cmInstallCommand.cxx"
-#include "cmInstallCommandArguments.cxx"
-#include "cmInstallFilesCommand.cxx"
-#include "cmInstallTargetsCommand.cxx"
-#include "cmLinkDirectoriesCommand.cxx"
-#include "cmListCommand.cxx"
-#include "cmMacroCommand.cxx"
-#include "cmMakeDirectoryCommand.cxx"
-#include "cmMarkAsAdvancedCommand.cxx"
-#include "cmMathCommand.cxx"
-#include "cmMessageCommand.cxx"
-#include "cmOptionCommand.cxx"
-#include "cmProjectCommand.cxx"
-#include "cmReturnCommand.cxx"
-#include "cmSeparateArgumentsCommand.cxx"
-#include "cmSetCommand.cxx"
-#include "cmSetDirectoryPropertiesCommand.cxx"
-#include "cmSetPropertyCommand.cxx"
-#include "cmSetSourceFilesPropertiesCommand.cxx"
-#include "cmSetTargetPropertiesCommand.cxx"
-#include "cmSetTestsPropertiesCommand.cxx"
-#include "cmSiteNameCommand.cxx"
-#include "cmStringCommand.cxx"
-#include "cmSubdirCommand.cxx"
-#include "cmTargetLinkLibrariesCommand.cxx"
-#include "cmTimestamp.cxx"
-#include "cmTryCompileCommand.cxx"
-#include "cmTryRunCommand.cxx"
-#include "cmUnsetCommand.cxx"
-#include "cmWhileCommand.cxx"
-
-void GetBootstrapCommands2(std::vector<cmCommand*>& commands)
-{
-  commands.push_back(new cmGetCMakePropertyCommand);
-  commands.push_back(new cmGetDirectoryPropertyCommand);
-  commands.push_back(new cmGetFilenameComponentCommand);
-  commands.push_back(new cmGetPropertyCommand);
-  commands.push_back(new cmGetSourceFilePropertyCommand);
-  commands.push_back(new cmGetTargetPropertyCommand);
-  commands.push_back(new cmIfCommand);
-  commands.push_back(new cmIncludeCommand);
-  commands.push_back(new cmIncludeDirectoryCommand);
-  commands.push_back(new cmIncludeRegularExpressionCommand);
-  commands.push_back(new cmInstallCommand);
-  commands.push_back(new cmInstallFilesCommand);
-  commands.push_back(new cmInstallTargetsCommand);
-  commands.push_back(new cmLinkDirectoriesCommand);
-  commands.push_back(new cmListCommand);
-  commands.push_back(new cmMacroCommand);
-  commands.push_back(new cmMakeDirectoryCommand);
-  commands.push_back(new cmMarkAsAdvancedCommand);
-  commands.push_back(new cmMathCommand);
-  commands.push_back(new cmMessageCommand);
-  commands.push_back(new cmOptionCommand);
-  commands.push_back(new cmProjectCommand);
-  commands.push_back(new cmReturnCommand);
-  commands.push_back(new cmSeparateArgumentsCommand);
-  commands.push_back(new cmSetCommand);
-  commands.push_back(new cmSetDirectoryPropertiesCommand);
-  commands.push_back(new cmSetPropertyCommand);
-  commands.push_back(new cmSetSourceFilesPropertiesCommand);
-  commands.push_back(new cmSetTargetPropertiesCommand);
-  commands.push_back(new cmGetTestPropertyCommand);
-  commands.push_back(new cmSetTestsPropertiesCommand);
-  commands.push_back(new cmSiteNameCommand);
-  commands.push_back(new cmStringCommand);
-  commands.push_back(new cmSubdirCommand);
-  commands.push_back(new cmTargetLinkLibrariesCommand);
-  commands.push_back(new cmTryCompileCommand);
-  commands.push_back(new cmTryRunCommand);
-  commands.push_back(new cmUnsetCommand);
-  commands.push_back(new cmWhileCommand);
-}
diff --git a/Source/cmBreakCommand.cxx b/Source/cmBreakCommand.cxx
index a5b6e84..9bb6137 100644
--- a/Source/cmBreakCommand.cxx
+++ b/Source/cmBreakCommand.cxx
@@ -2,7 +2,12 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmBreakCommand.h"
 
+#include <sstream>
+
 #include "cmExecutionStatus.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmake.h"
 
 // cmBreakCommand
 bool cmBreakCommand::InitialPass(std::vector<std::string> const& args,
diff --git a/Source/cmBreakCommand.h b/Source/cmBreakCommand.h
index ab58ab2..5113e18 100644
--- a/Source/cmBreakCommand.h
+++ b/Source/cmBreakCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmBreakCommand_h
 #define cmBreakCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmBreakCommand
  * \brief Break from an enclosing foreach or while loop
  *
@@ -34,8 +40,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "break"; }
-
-  cmTypeMacro(cmBreakCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmBuildCommand.cxx b/Source/cmBuildCommand.cxx
index 365a426..6836151 100644
--- a/Source/cmBuildCommand.cxx
+++ b/Source/cmBuildCommand.cxx
@@ -2,7 +2,15 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmBuildCommand.h"
 
+#include <sstream>
+
 #include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 bool cmBuildCommand::InitialPass(std::vector<std::string> const& args,
                                  cmExecutionStatus&)
@@ -82,8 +90,7 @@ bool cmBuildCommand::MainSignature(std::vector<std::string> const& args)
 
   std::string makecommand =
     this->Makefile->GetGlobalGenerator()->GenerateCMakeBuildCommand(
-      target, configuration.c_str(), "",
-      this->Makefile->IgnoreErrorsCMP0061());
+      target, configuration, "", this->Makefile->IgnoreErrorsCMP0061());
 
   this->Makefile->AddDefinition(variable, makecommand.c_str());
 
@@ -116,6 +123,6 @@ bool cmBuildCommand::TwoArgsSignature(std::vector<std::string> const& args)
   this->Makefile->AddCacheDefinition(define, makecommand.c_str(),
                                      "Command used to build entire project "
                                      "from the command line.",
-                                     cmState::STRING);
+                                     cmStateEnums::STRING);
   return true;
 }
diff --git a/Source/cmBuildCommand.h b/Source/cmBuildCommand.h
index a53a099..62f1fd3 100644
--- a/Source/cmBuildCommand.h
+++ b/Source/cmBuildCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmBuildCommand_h
 #define cmBuildCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmBuildCommand
  * \brief build_command command
  *
@@ -40,8 +46,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "build_command"; }
 
-  cmTypeMacro(cmBuildCommand, cmCommand);
-
 private:
   bool IgnoreErrors() const;
 };
diff --git a/Source/cmBuildNameCommand.cxx b/Source/cmBuildNameCommand.cxx
index 9134b9a..1e1cd21 100644
--- a/Source/cmBuildNameCommand.cxx
+++ b/Source/cmBuildNameCommand.cxx
@@ -2,8 +2,16 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmBuildNameCommand.h"
 
+#include <algorithm>
 #include <cmsys/RegularExpression.hxx>
 
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmBuildNameCommand
 bool cmBuildNameCommand::InitialPass(std::vector<std::string> const& args,
                                      cmExecutionStatus&)
@@ -27,7 +35,7 @@ bool cmBuildNameCommand::InitialPass(std::vector<std::string> const& args,
       std::replace(cv.begin(), cv.end(), '(', '_');
       std::replace(cv.begin(), cv.end(), ')', '_');
       this->Makefile->AddCacheDefinition(args[0], cv.c_str(), "Name of build.",
-                                         cmState::STRING);
+                                         cmStateEnums::STRING);
     }
     return true;
   }
@@ -53,6 +61,6 @@ bool cmBuildNameCommand::InitialPass(std::vector<std::string> const& args,
   std::replace(buildname.begin(), buildname.end(), ')', '_');
 
   this->Makefile->AddCacheDefinition(args[0], buildname.c_str(),
-                                     "Name of build.", cmState::STRING);
+                                     "Name of build.", cmStateEnums::STRING);
   return true;
 }
diff --git a/Source/cmBuildNameCommand.h b/Source/cmBuildNameCommand.h
index 7c09d73..1e1f4b5 100644
--- a/Source/cmBuildNameCommand.h
+++ b/Source/cmBuildNameCommand.h
@@ -3,12 +3,17 @@
 #ifndef cmBuildNameCommand_h
 #define cmBuildNameCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 class cmBuildNameCommand : public cmCommand
 {
 public:
-  cmTypeMacro(cmBuildNameCommand, cmCommand);
   cmCommand* Clone() CM_OVERRIDE { return new cmBuildNameCommand; }
   bool InitialPass(std::vector<std::string> const& args,
                    cmExecutionStatus& status) CM_OVERRIDE;
diff --git a/Source/cmCMakeHostSystemInformationCommand.cxx b/Source/cmCMakeHostSystemInformationCommand.cxx
index 018010e..e135ac6 100644
--- a/Source/cmCMakeHostSystemInformationCommand.cxx
+++ b/Source/cmCMakeHostSystemInformationCommand.cxx
@@ -2,6 +2,19 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCMakeHostSystemInformationCommand.h"
 
+#include <sstream>
+
+#include "cmMakefile.h"
+#include "cmsys/SystemInformation.hxx"
+
+#if defined(_WIN32)
+#include "cmSystemTools.h"
+#include "cmVSSetupHelper.h"
+#define HAVE_VS_SETUP_HELPER
+#endif
+
+class cmExecutionStatus;
+
 // cmCMakeHostSystemInformation
 bool cmCMakeHostSystemInformationCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
@@ -63,6 +76,13 @@ bool cmCMakeHostSystemInformationCommand::GetValue(
     value = this->ValueToString(info.GetTotalPhysicalMemory());
   } else if (key == "AVAILABLE_PHYSICAL_MEMORY") {
     value = this->ValueToString(info.GetAvailablePhysicalMemory());
+#ifdef HAVE_VS_SETUP_HELPER
+  } else if (key == "VS_15_DIR") {
+    cmVSSetupAPIHelper vsSetupAPIHelper;
+    if (vsSetupAPIHelper.GetVSInstanceInfo(value)) {
+      cmSystemTools::ConvertToUnixSlashes(value);
+    }
+#endif
   } else {
     std::string e = "does not recognize <key> " + key;
     this->SetError(e);
diff --git a/Source/cmCMakeHostSystemInformationCommand.h b/Source/cmCMakeHostSystemInformationCommand.h
index 4ab6aa1..22f3d54 100644
--- a/Source/cmCMakeHostSystemInformationCommand.h
+++ b/Source/cmCMakeHostSystemInformationCommand.h
@@ -3,9 +3,17 @@
 #ifndef cmCMakeHostSystemInformationCommand_h
 #define cmCMakeHostSystemInformationCommand_h
 
+#include <cmConfigure.h>
+#include <stddef.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
-#include <cmsys/SystemInformation.hxx>
+class cmExecutionStatus;
+namespace cmsys {
+class SystemInformation;
+} // namespace cmsys
 
 /** \class cmCMakeHostSystemInformationCommand
  * \brief Query host system specific information
@@ -44,8 +52,6 @@ public:
     return "cmake_host_system_information";
   }
 
-  cmTypeMacro(cmCMakeHostSystemInformationCommand, cmCommand);
-
 private:
   bool GetValue(cmsys::SystemInformation& info, std::string const& key,
                 std::string& value);
diff --git a/Source/cmCMakeMinimumRequired.cxx b/Source/cmCMakeMinimumRequired.cxx
index 80b5108..942688c 100644
--- a/Source/cmCMakeMinimumRequired.cxx
+++ b/Source/cmCMakeMinimumRequired.cxx
@@ -2,7 +2,15 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCMakeMinimumRequired.h"
 
+#include <sstream>
+#include <stdio.h>
+
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
 #include "cmVersion.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 // cmCMakeMinimumRequired
 bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args,
diff --git a/Source/cmCMakeMinimumRequired.h b/Source/cmCMakeMinimumRequired.h
index 425aeed..08a5c38 100644
--- a/Source/cmCMakeMinimumRequired.h
+++ b/Source/cmCMakeMinimumRequired.h
@@ -3,8 +3,14 @@
 #ifndef cmCMakeMinimumRequired_h
 #define cmCMakeMinimumRequired_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmCMakeMinimumRequired
  * \brief cmake_minimum_required command
  *
@@ -35,8 +41,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "cmake_minimum_required"; }
 
-  cmTypeMacro(cmCMakeMinimumRequired, cmCommand);
-
 private:
   std::vector<std::string> UnknownArguments;
   bool EnforceUnknownArguments();
diff --git a/Source/cmCMakePolicyCommand.cxx b/Source/cmCMakePolicyCommand.cxx
index eea76f2..3ccc815 100644
--- a/Source/cmCMakePolicyCommand.cxx
+++ b/Source/cmCMakePolicyCommand.cxx
@@ -2,7 +2,15 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCMakePolicyCommand.h"
 
-#include "cmVersion.h"
+#include <sstream>
+
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmState.h"
+#include "cmStateTypes.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 // cmCMakePolicyCommand
 bool cmCMakePolicyCommand::InitialPass(std::vector<std::string> const& args,
@@ -79,7 +87,7 @@ bool cmCMakePolicyCommand::HandleSetMode(std::vector<std::string> const& args)
         "For backwards compatibility, what version of CMake "
         "commands and "
         "syntax should this version of CMake try to support.",
-        cmState::STRING);
+        cmStateEnums::STRING);
     }
   }
   return true;
diff --git a/Source/cmCMakePolicyCommand.h b/Source/cmCMakePolicyCommand.h
index d5c5cb5..409fc59 100644
--- a/Source/cmCMakePolicyCommand.h
+++ b/Source/cmCMakePolicyCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmCMakePolicyCommand_h
 #define cmCMakePolicyCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmCMakePolicyCommand
  * \brief Set how CMake should handle policies
  *
@@ -36,8 +42,6 @@ public:
     */
   std::string GetName() const CM_OVERRIDE { return "cmake_policy"; }
 
-  cmTypeMacro(cmCMakePolicyCommand, cmCommand);
-
 private:
   bool HandleSetMode(std::vector<std::string> const& args);
   bool HandleGetMode(std::vector<std::string> const& args);
diff --git a/Source/cmCPluginAPI.cxx b/Source/cmCPluginAPI.cxx
index 3a08aea..e78f5fe 100644
--- a/Source/cmCPluginAPI.cxx
+++ b/Source/cmCPluginAPI.cxx
@@ -7,10 +7,12 @@
 
 #include "cmCPluginAPI.h"
 
+#include "cmExecutionStatus.h"
+#include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
-#include "cmVersion.h"
-
 #include "cmSourceFile.h"
+#include "cmState.h"
+#include "cmVersion.h"
 
 #include <stdlib.h>
 
@@ -75,22 +77,22 @@ void CCONV cmAddCacheDefinition(void* arg, const char* name, const char* value,
 
   switch (type) {
     case CM_CACHE_BOOL:
-      mf->AddCacheDefinition(name, value, doc, cmState::BOOL);
+      mf->AddCacheDefinition(name, value, doc, cmStateEnums::BOOL);
       break;
     case CM_CACHE_PATH:
-      mf->AddCacheDefinition(name, value, doc, cmState::PATH);
+      mf->AddCacheDefinition(name, value, doc, cmStateEnums::PATH);
       break;
     case CM_CACHE_FILEPATH:
-      mf->AddCacheDefinition(name, value, doc, cmState::FILEPATH);
+      mf->AddCacheDefinition(name, value, doc, cmStateEnums::FILEPATH);
       break;
     case CM_CACHE_STRING:
-      mf->AddCacheDefinition(name, value, doc, cmState::STRING);
+      mf->AddCacheDefinition(name, value, doc, cmStateEnums::STRING);
       break;
     case CM_CACHE_INTERNAL:
-      mf->AddCacheDefinition(name, value, doc, cmState::INTERNAL);
+      mf->AddCacheDefinition(name, value, doc, cmStateEnums::INTERNAL);
       break;
     case CM_CACHE_STATIC:
-      mf->AddCacheDefinition(name, value, doc, cmState::STATIC);
+      mf->AddCacheDefinition(name, value, doc, cmStateEnums::STATIC);
       break;
   }
 }
@@ -162,7 +164,14 @@ void CCONV cmAddLinkDirectoryForTarget(void* arg, const char* tgt,
                                        const char* d)
 {
   cmMakefile* mf = static_cast<cmMakefile*>(arg);
-  mf->AddLinkDirectoryForTarget(tgt, d);
+  cmTarget* t = mf->FindLocalNonAliasTarget(tgt);
+  if (!t) {
+    cmSystemTools::Error(
+      "Attempt to add link directories to non-existent target: ", tgt,
+      " for directory ", d);
+    return;
+  }
+  t->AddLinkDirectory(d);
 }
 
 void CCONV cmAddExecutable(void* arg, const char* exename, int numSrcs,
@@ -330,6 +339,35 @@ void CCONV cmAddCustomCommandToTarget(void* arg, const char* target,
                                cctype, no_comment, no_working_dir);
 }
 
+static void addLinkLibrary(cmMakefile* mf, std::string const& target,
+                           std::string const& lib, cmTargetLinkLibraryType llt)
+{
+  cmTarget* t = mf->FindLocalNonAliasTarget(target);
+  if (!t) {
+    std::ostringstream e;
+    e << "Attempt to add link library \"" << lib << "\" to target \"" << target
+      << "\" which is not built in this directory.";
+    mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+    return;
+  }
+
+  cmTarget* tgt = mf->GetGlobalGenerator()->FindTarget(lib);
+  if (tgt && (tgt->GetType() != cmStateEnums::STATIC_LIBRARY) &&
+      (tgt->GetType() != cmStateEnums::SHARED_LIBRARY) &&
+      (tgt->GetType() != cmStateEnums::INTERFACE_LIBRARY) &&
+      !tgt->IsExecutableWithExports()) {
+    std::ostringstream e;
+    e << "Target \"" << lib << "\" of type "
+      << cmState::GetTargetTypeName(tgt->GetType())
+      << " may not be linked into another target.  "
+      << "One may link only to STATIC or SHARED libraries, or "
+      << "to executables with the ENABLE_EXPORTS property set.";
+    mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+  }
+
+  t->AddLinkLibrary(*mf, lib, llt);
+}
+
 void CCONV cmAddLinkLibraryForTarget(void* arg, const char* tgt,
                                      const char* value, int libtype)
 {
@@ -337,13 +375,13 @@ void CCONV cmAddLinkLibraryForTarget(void* arg, const char* tgt,
 
   switch (libtype) {
     case CM_LIBRARY_GENERAL:
-      mf->AddLinkLibraryForTarget(tgt, value, GENERAL_LibraryType);
+      addLinkLibrary(mf, tgt, value, GENERAL_LibraryType);
       break;
     case CM_LIBRARY_DEBUG:
-      mf->AddLinkLibraryForTarget(tgt, value, DEBUG_LibraryType);
+      addLinkLibrary(mf, tgt, value, DEBUG_LibraryType);
       break;
     case CM_LIBRARY_OPTIMIZED:
-      mf->AddLinkLibraryForTarget(tgt, value, OPTIMIZED_LibraryType);
+      addLinkLibrary(mf, tgt, value, OPTIMIZED_LibraryType);
       break;
   }
 }
@@ -357,8 +395,8 @@ void CCONV cmAddLibrary(void* arg, const char* libname, int shared,
   for (i = 0; i < numSrcs; ++i) {
     srcs2.push_back(srcs[i]);
   }
-  mf->AddLibrary(libname,
-                 (shared ? cmState::SHARED_LIBRARY : cmState::STATIC_LIBRARY),
+  mf->AddLibrary(libname, (shared ? cmStateEnums::SHARED_LIBRARY
+                                  : cmStateEnums::STATIC_LIBRARY),
                  srcs2);
 }
 
@@ -370,7 +408,7 @@ char CCONV* cmExpandVariablesInString(void* arg, const char* source,
   std::string result = mf->ExpandVariablesInString(
     barf, (escapeQuotes ? true : false), (atOnly ? true : false));
   char* res = static_cast<char*>(malloc(result.size() + 1));
-  if (result.size()) {
+  if (!result.empty()) {
     strcpy(res, result.c_str());
   }
   res[result.size()] = '\0';
@@ -532,7 +570,7 @@ void* CCONV cmAddSource(void* arg, void* arg2)
   rsf->GetProperties() = osf->Properties;
   for (std::vector<std::string>::iterator i = osf->Depends.begin();
        i != osf->Depends.end(); ++i) {
-    rsf->AddDepend(i->c_str());
+    rsf->AddDepend(*i);
   }
 
   // Create the proxy for the real source file.
@@ -638,7 +676,7 @@ void CCONV cmSourceFileSetName(void* arg, const char* name, const char* dir,
   std::string hname = pathname;
   if (cmSystemTools::FileExists(hname.c_str())) {
     sf->SourceName = cmSystemTools::GetFilenamePath(name);
-    if (sf->SourceName.size() > 0) {
+    if (!sf->SourceName.empty()) {
       sf->SourceName += "/";
     }
     sf->SourceName += cmSystemTools::GetFilenameWithoutLastExtension(name);
@@ -695,7 +733,6 @@ void CCONV cmSourceFileSetName(void* arg, const char* name, const char* dir,
     e << " ." << *ext;
   }
   cmSystemTools::Error(e.str().c_str());
-  return;
 }
 
 void CCONV cmSourceFileSetName2(void* arg, const char* name, const char* dir,
@@ -718,7 +755,7 @@ void CCONV cmSourceFileSetName2(void* arg, const char* name, const char* dir,
     fname += ".";
     fname += ext;
   }
-  sf->FullPath = cmSystemTools::CollapseFullPath(fname.c_str(), dir);
+  sf->FullPath = cmSystemTools::CollapseFullPath(fname, dir);
   cmSystemTools::ConvertToUnixSlashes(sf->FullPath);
   sf->SourceExtension = ext;
 }
diff --git a/Source/cmCTest.cxx b/Source/cmCTest.cxx
index 1824d94..559275e 100644
--- a/Source/cmCTest.cxx
+++ b/Source/cmCTest.cxx
@@ -2,6 +2,27 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCTest.h"
 
+#include <cm_curl.h>
+#include <cm_zlib.h>
+#include <cmsys/Base64.h>
+#include <cmsys/Directory.hxx>
+#include <cmsys/FStream.hxx>
+#include <cmsys/Glob.hxx>
+#include <cmsys/Process.h>
+#include <cmsys/String.hxx>
+#include <cmsys/SystemInformation.hxx>
+#include <ctype.h>
+#include <iostream>
+#include <map>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <string>
+#include <time.h>
+#include <utility>
+#include <vector>
+
 #include "cmAlgorithms.h"
 #include "cmCTestBuildAndTestHandler.h"
 #include "cmCTestBuildHandler.h"
@@ -20,35 +41,17 @@
 #include "cmGeneratedFileStream.h"
 #include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
+#include "cmProcessOutput.h"
 #include "cmState.h"
+#include "cmStateSnapshot.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmVersion.h"
 #include "cmVersionConfig.h"
 #include "cmXMLWriter.h"
+#include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
-#include <cm_auto_ptr.hxx>
-#include <cm_curl.h>
-#include <cm_zlib.h>
-#include <cmsys/Base64.h>
-#include <cmsys/Directory.hxx>
-#include <cmsys/FStream.hxx>
-#include <cmsys/Glob.hxx>
-#include <cmsys/Process.h>
-#include <cmsys/String.hxx>
-#include <cmsys/SystemInformation.hxx>
-#include <ctype.h>
-#include <iostream>
-#include <map>
-#include <sstream>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <string>
-#include <time.h>
-#include <utility>
-#include <vector>
-
 #if defined(__BEOS__) || defined(__HAIKU__)
 #include <be/kernel/OS.h> /* disable_debugger() API. */
 #endif
@@ -269,7 +272,6 @@ cmCTest::cmCTest()
   this->UseHTTP10 = false;
   this->PrintLabels = false;
   this->CompressTestOutput = true;
-  this->CompressMemCheckOutput = true;
   this->TestModel = cmCTest::EXPERIMENTAL;
   this->MaxTestNameWidth = 30;
   this->InteractiveDebugMode = true;
@@ -287,8 +289,6 @@ cmCTest::cmCTest()
   this->DartVersion = 1;
   this->DropSiteCDash = false;
   this->OutputTestOutputOnTestFailure = false;
-  this->ComputedCompressTestOutput = false;
-  this->ComputedCompressMemCheckOutput = false;
   this->RepeatTests = 1; // default to run each test once
   this->RepeatUntilFail = false;
   std::string outOnFail;
@@ -356,53 +356,9 @@ void cmCTest::SetTestLoad(unsigned long load)
 
 bool cmCTest::ShouldCompressTestOutput()
 {
-  if (!this->ComputedCompressTestOutput) {
-    std::string cdashVersion = this->GetCDashVersion();
-    // version >= 1.6?
-    bool cdashSupportsGzip = cmSystemTools::VersionCompare(
-      cmSystemTools::OP_GREATER_EQUAL, cdashVersion.c_str(), "1.6");
-    this->CompressTestOutput &= cdashSupportsGzip;
-    this->ComputedCompressTestOutput = true;
-  }
   return this->CompressTestOutput;
 }
 
-bool cmCTest::ShouldCompressMemCheckOutput()
-{
-  if (!this->ComputedCompressMemCheckOutput) {
-    std::string cdashVersion = this->GetCDashVersion();
-
-    bool compressionSupported = cmSystemTools::VersionCompare(
-      cmSystemTools::OP_GREATER, cdashVersion.c_str(), "1.9.0");
-    this->CompressMemCheckOutput &= compressionSupported;
-    this->ComputedCompressMemCheckOutput = true;
-  }
-  return this->CompressMemCheckOutput;
-}
-
-std::string cmCTest::GetCDashVersion()
-{
-#ifdef CMAKE_BUILD_WITH_CMAKE
-  // First query the server.  If that fails, fall back to the local setting
-  std::string response;
-  std::string url = "http://";
-  url += this->GetCTestConfiguration("DropSite");
-
-  std::string cdashUri = this->GetCTestConfiguration("DropLocation");
-  cdashUri = cdashUri.substr(0, cdashUri.find("/submit.php"));
-
-  int res = 1;
-  if (!cdashUri.empty()) {
-    url += cdashUri + "/api/getversion.php";
-    res = cmCTest::HTTPRequest(url, cmCTest::HTTP_GET, response, "", "", 3);
-  }
-
-  return res ? this->GetCTestConfiguration("CDashVersion") : response;
-#else
-  return this->GetCTestConfiguration("CDashVersion");
-#endif
-}
-
 cmCTest::Part cmCTest::GetPartFromName(const char* name)
 {
   // Look up by lower-case to make names case-insensitive.
@@ -1005,7 +961,7 @@ int cmCTest::GetTestModelFromString(const char* str)
 
 int cmCTest::RunMakeCommand(const char* command, std::string& output,
                             int* retVal, const char* dir, int timeout,
-                            std::ostream& ofs)
+                            std::ostream& ofs, Encoding encoding)
 {
   // First generate the command and arguments
   std::vector<std::string> args = cmSystemTools::ParseArguments(command);
@@ -1044,16 +1000,19 @@ int cmCTest::RunMakeCommand(const char* command, std::string& output,
 
   char* data;
   int length;
+  cmProcessOutput processOutput(encoding);
+  std::string strdata;
   cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, "   Each . represents "
                << tick_len << " bytes of output" << std::endl
                << "    " << std::flush);
   while (cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
-    for (int cc = 0; cc < length; ++cc) {
-      if (data[cc] == 0) {
-        data[cc] = '\n';
+    processOutput.DecodeText(data, length, strdata);
+    for (size_t cc = 0; cc < strdata.size(); ++cc) {
+      if (strdata[cc] == 0) {
+        strdata[cc] = '\n';
       }
     }
-    output.append(data, length);
+    output.append(strdata);
     while (output.size() > (tick * tick_len)) {
       tick++;
       cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, "." << std::flush);
@@ -1064,9 +1023,19 @@ int cmCTest::RunMakeCommand(const char* command, std::string& output,
                               << "    " << std::flush);
       }
     }
-    cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, cmCTestLogWrite(data, length));
+    cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
+               cmCTestLogWrite(strdata.c_str(), strdata.size()));
+    if (ofs) {
+      ofs << cmCTestLogWrite(strdata.c_str(), strdata.size());
+    }
+  }
+  processOutput.DecodeText(std::string(), strdata);
+  if (!strdata.empty()) {
+    output.append(strdata);
+    cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
+               cmCTestLogWrite(strdata.c_str(), strdata.size()));
     if (ofs) {
-      ofs << cmCTestLogWrite(data, length);
+      ofs << cmCTestLogWrite(strdata.c_str(), strdata.size());
     }
   }
   cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, " Size of output: "
@@ -1106,7 +1075,7 @@ int cmCTest::RunMakeCommand(const char* command, std::string& output,
 
 int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
                      int* retVal, std::ostream* log, double testTimeOut,
-                     std::vector<std::string>* environment)
+                     std::vector<std::string>* environment, Encoding encoding)
 {
   bool modifyEnv = (environment && !environment->empty());
 
@@ -1201,17 +1170,30 @@ int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
 
   char* data;
   int length;
+  cmProcessOutput processOutput(encoding);
+  std::string strdata;
   while (cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
+    processOutput.DecodeText(data, length, strdata);
     if (output) {
       tempOutput.insert(tempOutput.end(), data, data + length);
     }
-    cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, cmCTestLogWrite(data, length));
+    cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
+               cmCTestLogWrite(strdata.c_str(), strdata.size()));
+    if (log) {
+      log->write(strdata.c_str(), strdata.size());
+    }
+  }
+  processOutput.DecodeText(std::string(), strdata);
+  if (!strdata.empty()) {
+    cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
+               cmCTestLogWrite(strdata.c_str(), strdata.size()));
     if (log) {
-      log->write(data, length);
+      log->write(strdata.c_str(), strdata.size());
     }
   }
 
   cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+  processOutput.DecodeText(tempOutput, tempOutput);
   if (output && tempOutput.begin() != tempOutput.end()) {
     output->append(&*tempOutput.begin(), tempOutput.size());
   }
@@ -1527,7 +1509,7 @@ bool cmCTest::SubmitExtraFiles(const VectorOfStrings& files)
 bool cmCTest::SubmitExtraFiles(const char* cfiles)
 {
   if (!cfiles) {
-    return 1;
+    return true;
   }
 
   VectorOfStrings files;
@@ -1536,7 +1518,7 @@ bool cmCTest::SubmitExtraFiles(const char* cfiles)
 
   files = cmSystemTools::SplitString(cfiles, ';');
   if (files.empty()) {
-    return 1;
+    return true;
   }
 
   return this->SubmitExtraFiles(files);
@@ -1744,7 +1726,6 @@ bool cmCTest::HandleCommandLineArguments(size_t& i,
 
   if (this->CheckArgument(arg, "--no-compress-output")) {
     this->CompressTestOutput = false;
-    this->CompressMemCheckOutput = false;
   }
 
   if (this->CheckArgument(arg, "--print-labels")) {
@@ -1969,7 +1950,7 @@ bool cmCTest::AddVariableDefinition(const std::string& arg)
 {
   std::string name;
   std::string value;
-  cmState::CacheEntryType type = cmState::UNINITIALIZED;
+  cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
 
   if (cmake::ParseCacheEntry(arg, name, value, type)) {
     this->Definitions[name] = value;
@@ -2542,7 +2523,7 @@ bool cmCTest::SetCTestConfigurationFromCMakeVariable(
 
 bool cmCTest::RunCommand(const char* command, std::string* stdOut,
                          std::string* stdErr, int* retVal, const char* dir,
-                         double timeout)
+                         double timeout, Encoding encoding)
 {
   std::vector<std::string> args = cmSystemTools::ParseArguments(command);
 
@@ -2573,6 +2554,8 @@ bool cmCTest::RunCommand(const char* command, std::string* stdOut,
   std::vector<char> tempError;
   char* data;
   int length;
+  cmProcessOutput processOutput(encoding);
+  std::string strdata;
   int res;
   bool done = false;
   while (!done) {
@@ -2589,15 +2572,24 @@ bool cmCTest::RunCommand(const char* command, std::string* stdOut,
     }
     if ((res == cmsysProcess_Pipe_STDOUT || res == cmsysProcess_Pipe_STDERR) &&
         this->ExtraVerbose) {
-      cmSystemTools::Stdout(data, length);
+      processOutput.DecodeText(data, length, strdata);
+      cmSystemTools::Stdout(strdata.c_str(), strdata.size());
+    }
+  }
+  if (this->ExtraVerbose) {
+    processOutput.DecodeText(std::string(), strdata);
+    if (!strdata.empty()) {
+      cmSystemTools::Stdout(strdata.c_str(), strdata.size());
     }
   }
 
   cmsysProcess_WaitForExit(cp, CM_NULLPTR);
   if (!tempOutput.empty()) {
+    processOutput.DecodeText(tempOutput, tempOutput);
     stdOut->append(&*tempOutput.begin(), tempOutput.size());
   }
   if (!tempError.empty()) {
+    processOutput.DecodeText(tempError, tempError);
     stdErr->append(&*tempError.begin(), tempError.size());
   }
 
@@ -2651,13 +2643,6 @@ static const char* cmCTestStringLogType[] = { "DEBUG",
                                               "ERROR_MESSAGE",
                                               CM_NULLPTR };
 
-#ifdef cerr
-#undef cerr
-#endif
-#ifdef cout
-#undef cout
-#endif
-
 #define cmCTestLogOutputFileLine(stream)                                      \
   if (this->ShowLineNumbers) {                                                \
     (stream) << std::endl << file << ":" << line << " ";                      \
@@ -2802,7 +2787,7 @@ bool cmCTest::CompressString(std::string& str)
   strm.next_out = &out[0];
   ret = deflate(&strm, Z_FINISH);
 
-  if (ret == Z_STREAM_ERROR || ret != Z_STREAM_END) {
+  if (ret != Z_STREAM_END) {
     cmCTestLog(this, ERROR_MESSAGE, "Error during gzip compression."
                  << std::endl);
     return false;
diff --git a/Source/cmCTest.h b/Source/cmCTest.h
index 8d3f8fb..4d33458 100644
--- a/Source/cmCTest.h
+++ b/Source/cmCTest.h
@@ -5,6 +5,7 @@
 
 #include <cmConfigure.h>
 
+#include <cmProcessOutput.h>
 #include <cmsys/String.hxx>
 #include <map>
 #include <set>
@@ -13,6 +14,7 @@
 #include <time.h>
 #include <vector>
 
+class cmCTest;
 class cmCTestGenericHandler;
 class cmCTestStartCommand;
 class cmGeneratedFileStream;
@@ -25,7 +27,7 @@ class cmXMLWriter;
     cmCTestLog_msg << msg;                                                    \
     (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__,                       \
                   cmCTestLog_msg.str().c_str());                              \
-  } while (0)
+  } while (false)
 
 #define cmCTestOptionalLog(ctSelf, logType, msg, suppress)                    \
   do {                                                                        \
@@ -33,7 +35,7 @@ class cmXMLWriter;
     cmCTestLog_msg << msg;                                                    \
     (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__,                       \
                   cmCTestLog_msg.str().c_str(), suppress);                    \
-  } while (0)
+  } while (false)
 
 /** \class cmCTest
  * \brief Represents a ctest invocation.
@@ -48,6 +50,7 @@ class cmCTest
   friend class cmCTestMultiProcessHandler;
 
 public:
+  typedef cmProcessOutput::Encoding Encoding;
   /** Enumerate parts of the testing and submission process.  */
   enum Part
   {
@@ -232,17 +235,14 @@ public:
   bool ShouldPrintLabels() { return this->PrintLabels; }
 
   bool ShouldCompressTestOutput();
-  bool ShouldCompressMemCheckOutput();
   bool CompressString(std::string& str);
 
-  std::string GetCDashVersion();
-
   std::string GetStopTime() { return this->StopTime; }
   void SetStopTime(std::string const& time);
 
   /** Used for parallel ctest job scheduling */
   std::string GetScheduleType() { return this->ScheduleType; }
-  void SetScheduleType(std::string type) { this->ScheduleType = type; }
+  void SetScheduleType(std::string const& type) { this->ScheduleType = type; }
 
   /** The max output width */
   int GetMaxTestNameWidth() const;
@@ -270,7 +270,8 @@ public:
    */
   bool RunCommand(const char* command, std::string* stdOut,
                   std::string* stdErr, int* retVal = CM_NULLPTR,
-                  const char* dir = CM_NULLPTR, double timeout = 0.0);
+                  const char* dir = CM_NULLPTR, double timeout = 0.0,
+                  Encoding encoding = cmProcessOutput::Auto);
 
   /**
    * Clean/make safe for xml the given value such that it may be used as
@@ -289,7 +290,8 @@ public:
    * and retVal is return value or exception.
    */
   int RunMakeCommand(const char* command, std::string& output, int* retVal,
-                     const char* dir, int timeout, std::ostream& ofs);
+                     const char* dir, int timeout, std::ostream& ofs,
+                     Encoding encoding = cmProcessOutput::Auto);
 
   /** Return the current tag */
   std::string GetCurrentTag();
@@ -336,7 +338,8 @@ public:
    */
   int RunTest(std::vector<const char*> args, std::string* output, int* retVal,
               std::ostream* logfile, double testTimeOut,
-              std::vector<std::string>* environment);
+              std::vector<std::string>* environment,
+              Encoding encoding = cmProcessOutput::Auto);
 
   /**
    * Execute handler and return its result. If the handler fails, it returns
@@ -487,10 +490,6 @@ private:
 
   bool RunConfigurationScript;
 
-  // flag for lazy getter (optimization)
-  bool ComputedCompressTestOutput;
-  bool ComputedCompressMemCheckOutput;
-
   int GenerateNotesFile(const char* files);
 
   void DetermineNextDayStop();
@@ -547,7 +546,6 @@ private:
 
   bool CompressXMLFiles;
   bool CompressTestOutput;
-  bool CompressMemCheckOutput;
 
   void InitStreams();
   std::ostream* StreamOut;
diff --git a/Source/cmCacheManager.cxx b/Source/cmCacheManager.cxx
index 4b03499..cb0ba63 100644
--- a/Source/cmCacheManager.cxx
+++ b/Source/cmCacheManager.cxx
@@ -2,11 +2,6 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCacheManager.h"
 
-#include "cmGeneratedFileStream.h"
-#include "cmSystemTools.h"
-#include "cmVersion.h"
-#include "cmake.h"
-
 #include <algorithm>
 #include <cmsys/FStream.hxx>
 #include <cmsys/Glob.hxx>
@@ -14,6 +9,12 @@
 #include <stdio.h>
 #include <string.h>
 
+#include "cmGeneratedFileStream.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmVersion.h"
+#include "cmake.h"
+
 cmCacheManager::cmCacheManager()
 {
   this->CacheMajorVersion = 0;
@@ -94,13 +95,13 @@ bool cmCacheManager::LoadCache(const std::string& path, bool internal,
         // If the entry is not internal to the cache being loaded
         // or if it is in the list of internal entries to be
         // imported, load it.
-        if (internal || (e.Type != cmState::INTERNAL) ||
+        if (internal || (e.Type != cmStateEnums::INTERNAL) ||
             (includes.find(entryKey) != includes.end())) {
           // If we are loading the cache from another project,
           // make all loaded entries internal so that it is
           // not visible in the gui
           if (!internal) {
-            e.Type = cmState::INTERNAL;
+            e.Type = cmStateEnums::INTERNAL;
             helpString = "DO NOT EDIT, ";
             helpString += entryKey;
             helpString += " loaded from external file.  "
@@ -142,11 +143,11 @@ bool cmCacheManager::LoadCache(const std::string& path, bool internal,
     this->AddCacheEntry("CMAKE_CACHE_MINOR_VERSION", "0",
                         "Minor version of cmake used to create the "
                         "current loaded cache",
-                        cmState::INTERNAL);
+                        cmStateEnums::INTERNAL);
     this->AddCacheEntry("CMAKE_CACHE_MAJOR_VERSION", "0",
                         "Major version of cmake used to create the "
                         "current loaded cache",
-                        cmState::INTERNAL);
+                        cmStateEnums::INTERNAL);
   }
   // check to make sure the cache directory has not
   // been moved
@@ -178,7 +179,7 @@ bool cmCacheManager::ReadPropertyEntry(std::string const& entryKey,
                                        CacheEntry& e)
 {
   // All property entries are internal.
-  if (e.Type != cmState::INTERNAL) {
+  if (e.Type != cmStateEnums::INTERNAL) {
     return false;
   }
 
@@ -192,7 +193,7 @@ bool cmCacheManager::ReadPropertyEntry(std::string const& entryKey,
       if (it.IsAtEnd()) {
         // Create an entry and store the property.
         CacheEntry& ne = this->Cache[key];
-        ne.Type = cmState::UNINITIALIZED;
+        ne.Type = cmStateEnums::UNINITIALIZED;
         ne.SetProperty(*p, e.Value.c_str());
       } else {
         // Store this property on its entry.
@@ -244,17 +245,17 @@ bool cmCacheManager::SaveCache(const std::string& path)
   this->AddCacheEntry("CMAKE_CACHE_MINOR_VERSION", temp,
                       "Minor version of cmake used to create the "
                       "current loaded cache",
-                      cmState::INTERNAL);
+                      cmStateEnums::INTERNAL);
   sprintf(temp, "%d", cmVersion::GetMajorVersion());
   this->AddCacheEntry("CMAKE_CACHE_MAJOR_VERSION", temp,
                       "Major version of cmake used to create the "
                       "current loaded cache",
-                      cmState::INTERNAL);
+                      cmStateEnums::INTERNAL);
   sprintf(temp, "%d", cmVersion::GetPatchVersion());
   this->AddCacheEntry("CMAKE_CACHE_PATCH_VERSION", temp,
                       "Patch version of cmake used to create the "
                       "current loaded cache",
-                      cmState::INTERNAL);
+                      cmStateEnums::INTERNAL);
 
   // Let us store the current working directory so that if somebody
   // Copies it, he will not be surprised
@@ -268,7 +269,7 @@ bool cmCacheManager::SaveCache(const std::string& path)
   this->AddCacheEntry("CMAKE_CACHEFILE_DIR", currentcwd.c_str(),
                       "This is the directory where this CMakeCache.txt"
                       " was created",
-                      cmState::INTERNAL);
+                      cmStateEnums::INTERNAL);
 
   /* clang-format off */
   fout << "# This is the CMakeCache file.\n"
@@ -301,14 +302,14 @@ bool cmCacheManager::SaveCache(const std::string& path)
          this->Cache.begin();
        i != this->Cache.end(); ++i) {
     const CacheEntry& ce = (*i).second;
-    cmState::CacheEntryType t = ce.Type;
+    cmStateEnums::CacheEntryType t = ce.Type;
     if (!ce.Initialized) {
       /*
         // This should be added in, but is not for now.
       cmSystemTools::Error("Cache entry \"", (*i).first.c_str(),
                            "\" is uninitialized");
       */
-    } else if (t != cmState::INTERNAL) {
+    } else if (t != cmStateEnums::INTERNAL) {
       // Format is key:type=value
       if (const char* help = ce.GetProperty("HELPSTRING")) {
         cmCacheManager::OutputHelpString(fout, help);
@@ -334,9 +335,9 @@ bool cmCacheManager::SaveCache(const std::string& path)
       continue;
     }
 
-    cmState::CacheEntryType t = i.GetType();
+    cmStateEnums::CacheEntryType t = i.GetType();
     this->WritePropertyEntries(fout, i);
-    if (t == cmState::INTERNAL) {
+    if (t == cmStateEnums::INTERNAL) {
       // Format is key:type=value
       if (const char* help = i.GetProperty("HELPSTRING")) {
         this->OutputHelpString(fout, help);
@@ -465,7 +466,7 @@ void cmCacheManager::PrintCache(std::ostream& out) const
   for (std::map<std::string, CacheEntry>::const_iterator i =
          this->Cache.begin();
        i != this->Cache.end(); ++i) {
-    if ((*i).second.Type != cmState::INTERNAL) {
+    if ((*i).second.Type != cmStateEnums::INTERNAL) {
       out << (*i).first << " = " << (*i).second.Value << std::endl;
     }
   }
@@ -477,7 +478,7 @@ void cmCacheManager::PrintCache(std::ostream& out) const
 
 void cmCacheManager::AddCacheEntry(const std::string& key, const char* value,
                                    const char* helpString,
-                                   cmState::CacheEntryType type)
+                                   cmStateEnums::CacheEntryType type)
 {
   CacheEntry& e = this->Cache[key];
   if (value) {
@@ -488,7 +489,7 @@ void cmCacheManager::AddCacheEntry(const std::string& key, const char* value,
   }
   e.Type = type;
   // make sure we only use unix style paths
-  if (type == cmState::FILEPATH || type == cmState::PATH) {
+  if (type == cmStateEnums::FILEPATH || type == cmStateEnums::PATH) {
     if (e.Value.find(';') != e.Value.npos) {
       std::vector<std::string> paths;
       cmSystemTools::ExpandListArgument(e.Value, paths);
diff --git a/Source/cmCacheManager.h b/Source/cmCacheManager.h
index 16a2e78..e82c9ef 100644
--- a/Source/cmCacheManager.h
+++ b/Source/cmCacheManager.h
@@ -5,9 +5,6 @@
 
 #include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmPropertyMap.h"
-#include "cmState.h"
-
 #include <iosfwd>
 #include <map>
 #include <set>
@@ -15,6 +12,9 @@
 #include <utility>
 #include <vector>
 
+#include "cmPropertyMap.h"
+#include "cmStateTypes.h"
+
 class cmake;
 
 /** \class cmCacheManager
@@ -34,7 +34,7 @@ private:
   struct CacheEntry
   {
     std::string Value;
-    cmState::CacheEntryType Type;
+    cmStateEnums::CacheEntryType Type;
     cmPropertyMap Properties;
     std::vector<std::string> GetPropertyList() const;
     const char* GetProperty(const std::string&) const;
@@ -44,7 +44,7 @@ private:
     bool Initialized;
     CacheEntry()
       : Value("")
-      , Type(cmState::UNINITIALIZED)
+      , Type(cmStateEnums::UNINITIALIZED)
       , Initialized(false)
     {
     }
@@ -70,8 +70,14 @@ public:
     const char* GetValue() const { return this->GetEntry().Value.c_str(); }
     bool GetValueAsBool() const;
     void SetValue(const char*);
-    cmState::CacheEntryType GetType() const { return this->GetEntry().Type; }
-    void SetType(cmState::CacheEntryType ty) { this->GetEntry().Type = ty; }
+    cmStateEnums::CacheEntryType GetType() const
+    {
+      return this->GetEntry().Type;
+    }
+    void SetType(cmStateEnums::CacheEntryType ty)
+    {
+      this->GetEntry().Type = ty;
+    }
     bool Initialized() { return this->GetEntry().Initialized; }
     cmCacheManager& Container;
     std::map<std::string, CacheEntry>::iterator Position;
@@ -137,7 +143,7 @@ public:
     return this->GetCacheIterator(key.c_str()).GetProperty(propName);
   }
 
-  cmState::CacheEntryType GetCacheEntryType(std::string const& key)
+  cmStateEnums::CacheEntryType GetCacheEntryType(std::string const& key)
   {
     return this->GetCacheIterator(key.c_str()).GetType();
   }
@@ -200,7 +206,8 @@ public:
 protected:
   ///! Add an entry into the cache
   void AddCacheEntry(const std::string& key, const char* value,
-                     const char* helpString, cmState::CacheEntryType type);
+                     const char* helpString,
+                     cmStateEnums::CacheEntryType type);
 
   ///! Get a cache entry object for a key
   CacheEntry* GetCacheEntry(const std::string& key);
diff --git a/Source/cmCallVisualStudioMacro.cxx b/Source/cmCallVisualStudioMacro.cxx
index a21a7d2..99fe587 100644
--- a/Source/cmCallVisualStudioMacro.cxx
+++ b/Source/cmCallVisualStudioMacro.cxx
@@ -2,6 +2,8 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCallVisualStudioMacro.h"
 
+#include <sstream>
+
 #include "cmSystemTools.h"
 
 #if defined(_MSC_VER)
diff --git a/Source/cmCallVisualStudioMacro.h b/Source/cmCallVisualStudioMacro.h
index 7ff4513..e9d34e5 100644
--- a/Source/cmCallVisualStudioMacro.h
+++ b/Source/cmCallVisualStudioMacro.h
@@ -5,7 +5,7 @@
 
 #include <cmConfigure.h>
 
-#include "cmStandardIncludes.h"
+#include <string>
 
 /** \class cmCallVisualStudioMacro
  * \brief Control class for communicating with CMake's Visual Studio macros
diff --git a/Source/cmCommand.cxx b/Source/cmCommand.cxx
new file mode 100644
index 0000000..181b412
--- /dev/null
+++ b/Source/cmCommand.cxx
@@ -0,0 +1,54 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmCommand.h"
+
+#include "cmMakefile.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
+struct cmListFileArgument;
+
+bool cmCommand::InvokeInitialPass(const std::vector<cmListFileArgument>& args,
+                                  cmExecutionStatus& status)
+{
+  std::vector<std::string> expandedArguments;
+  if (!this->Makefile->ExpandArguments(args, expandedArguments)) {
+    // There was an error expanding arguments.  It was already
+    // reported, so we can skip this command without error.
+    return true;
+  }
+  return this->InitialPass(expandedArguments, status);
+}
+
+const char* cmCommand::GetError()
+{
+  if (this->Error.empty()) {
+    this->Error = this->GetName();
+    this->Error += " unknown error.";
+  }
+  return this->Error.c_str();
+}
+
+void cmCommand::SetError(const std::string& e)
+{
+  this->Error = this->GetName();
+  this->Error += " ";
+  this->Error += e;
+}
+
+bool cmCommand::Disallowed(cmPolicies::PolicyID pol, const char* e)
+{
+  switch (this->Makefile->GetPolicyStatus(pol)) {
+    case cmPolicies::WARN:
+      this->Makefile->IssueMessage(cmake::AUTHOR_WARNING,
+                                   cmPolicies::GetPolicyWarning(pol));
+    case cmPolicies::OLD:
+      return false;
+    case cmPolicies::REQUIRED_IF_USED:
+    case cmPolicies::REQUIRED_ALWAYS:
+    case cmPolicies::NEW:
+      this->Makefile->IssueMessage(cmake::FATAL_ERROR, e);
+      break;
+  }
+  return true;
+}
diff --git a/Source/cmCommand.h b/Source/cmCommand.h
index d8e337d..d9fd5a2 100644
--- a/Source/cmCommand.h
+++ b/Source/cmCommand.h
@@ -3,11 +3,16 @@
 #ifndef cmCommand_h
 #define cmCommand_h
 
-#include "cmObject.h"
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
 
 #include "cmCommandArgumentsHelper.h"
-#include "cmListFileCache.h"
-#include "cmMakefile.h"
+#include "cmPolicies.h"
+
+class cmExecutionStatus;
+class cmMakefile;
+struct cmListFileArgument;
 
 /** \class cmCommand
  * \brief Superclass for all commands in CMake.
@@ -19,24 +24,21 @@
  * to support such features as enable/disable, inheritance,
  * documentation, and construction.
  */
-class cmCommand : public cmObject
+class cmCommand
 {
 public:
-  cmTypeMacro(cmCommand, cmObject);
-
   /**
-   * Construct the command. By default it is enabled with no makefile.
+   * Construct the command. By default it has no makefile.
    */
   cmCommand()
+    : Makefile(CM_NULLPTR)
   {
-    this->Makefile = CM_NULLPTR;
-    this->Enabled = true;
   }
 
   /**
    * Need virtual destructor to destroy real command type.
    */
-  ~cmCommand() CM_OVERRIDE {}
+  virtual ~cmCommand() {}
 
   /**
    * Specify the makefile.
@@ -50,16 +52,7 @@ public:
    * arguments and then invokes the InitialPass.
    */
   virtual bool InvokeInitialPass(const std::vector<cmListFileArgument>& args,
-                                 cmExecutionStatus& status)
-  {
-    std::vector<std::string> expandedArguments;
-    if (!this->Makefile->ExpandArguments(args, expandedArguments)) {
-      // There was an error expanding arguments.  It was already
-      // reported, so we can skip this command without error.
-      return true;
-    }
-    return this->InitialPass(expandedArguments, status);
-  }
+                                 cmExecutionStatus& status);
 
   /**
    * This is called when the command is first encountered in
@@ -92,12 +85,10 @@ public:
   virtual bool IsScriptable() const { return false; }
 
   /**
-   * This is used to avoid including this command
-   * in documentation. This is mainly used by
-   * cmMacroHelperCommand and cmFunctionHelperCommand
-   * which cannot provide appropriate documentation.
+   * This determines if the command is defined in a cmake script.
+   * It is the case for cmMacroHelperCommand and cmFunctionHelperCommand.
    */
-  virtual bool ShouldAppearInDocumentation() const { return true; }
+  virtual bool IsUserDefined() const { return false; }
 
   /**
    * The name of the command as specified in CMakeList.txt.
@@ -105,71 +96,23 @@ public:
   virtual std::string GetName() const = 0;
 
   /**
-   * Enable the command.
-   */
-  void EnabledOn() { this->Enabled = true; }
-
-  /**
-   * Disable the command.
-   */
-  void EnabledOff() { this->Enabled = false; }
-
-  /**
-   * Query whether the command is enabled.
-   */
-  bool GetEnabled() const { return this->Enabled; }
-
-  /**
-   * Disable or enable the command.
-   */
-  void SetEnabled(bool enabled) { this->Enabled = enabled; }
-
-  /**
    * Return the last error string.
    */
-  const char* GetError()
-  {
-    if (this->Error.empty()) {
-      this->Error = this->GetName();
-      this->Error += " unknown error.";
-    }
-    return this->Error.c_str();
-  }
+  const char* GetError();
 
   /**
    * Set the error message
    */
-  void SetError(const std::string& e)
-  {
-    this->Error = this->GetName();
-    this->Error += " ";
-    this->Error += e;
-  }
+  void SetError(const std::string& e);
 
   /** Check if the command is disallowed by a policy.  */
-  bool Disallowed(cmPolicies::PolicyID pol, const char* e)
-  {
-    switch (this->Makefile->GetPolicyStatus(pol)) {
-      case cmPolicies::WARN:
-        this->Makefile->IssueMessage(cmake::AUTHOR_WARNING,
-                                     cmPolicies::GetPolicyWarning(pol));
-      case cmPolicies::OLD:
-        return false;
-      case cmPolicies::REQUIRED_IF_USED:
-      case cmPolicies::REQUIRED_ALWAYS:
-      case cmPolicies::NEW:
-        this->Makefile->IssueMessage(cmake::FATAL_ERROR, e);
-        break;
-    }
-    return true;
-  }
+  bool Disallowed(cmPolicies::PolicyID pol, const char* e);
 
 protected:
   cmMakefile* Makefile;
   cmCommandArgumentsHelper Helper;
 
 private:
-  bool Enabled;
   std::string Error;
 };
 
diff --git a/Source/cmCommandArgumentLexer.cxx b/Source/cmCommandArgumentLexer.cxx
index fe460ba..12dce37 100644
--- a/Source/cmCommandArgumentLexer.cxx
+++ b/Source/cmCommandArgumentLexer.cxx
@@ -1,19 +1,17 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmStandardIncludes.h"
-
+#include "cmStandardLexer.h"
 #line 2 "cmCommandArgumentLexer.cxx"
 
 #line 4 "cmCommandArgumentLexer.cxx"
 
+#define FLEXINT_H 1
 #define  YY_INT_ALIGNED short int
 
 /* A lexical scanner generated by flex */
 
 #define FLEX_SCANNER
 #define YY_FLEX_MAJOR_VERSION 2
-#define YY_FLEX_MINOR_VERSION 5
-#define YY_FLEX_SUBMINOR_VERSION 35
+#define YY_FLEX_MINOR_VERSION 6
+#define YY_FLEX_SUBMINOR_VERSION 1
 #if YY_FLEX_SUBMINOR_VERSION > 0
 #define FLEX_BETA
 #endif
@@ -92,25 +90,13 @@ typedef unsigned int flex_uint32_t;
 
 #endif /* ! FLEXINT_H */
 
-#ifdef __cplusplus
-
-/* The "const" storage-class-modifier is valid. */
-#define YY_USE_CONST
-
-#else   /* ! __cplusplus */
-
-/* C99 requires __STDC__ to be defined as 1. */
-#if defined (__STDC__)
-
-#define YY_USE_CONST
-
-#endif  /* defined (__STDC__) */
-#endif  /* ! __cplusplus */
-
-#ifdef YY_USE_CONST
+/* TODO: this is always defined, so inline it */
 #define yyconst const
+
+#if defined(__GNUC__) && __GNUC__ >= 3
+#define yynoreturn __attribute__((__noreturn__))
 #else
-#define yyconst
+#define yynoreturn
 #endif
 
 /* Returned upon end-of-file. */
@@ -163,7 +149,15 @@ typedef void* yyscan_t;
 
 /* Size of default input buffer. */
 #ifndef YY_BUF_SIZE
+#ifdef __ia64__
+/* On IA-64, the buffer size is 16k, not 8k.
+ * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case.
+ * Ditto for the __ia64__ case accordingly.
+ */
+#define YY_BUF_SIZE 32768
+#else
 #define YY_BUF_SIZE 16384
+#endif /* __ia64__ */
 #endif
 
 /* The state buf must be large enough to hold one state per character in the main buffer.
@@ -175,96 +169,97 @@ typedef void* yyscan_t;
 typedef struct yy_buffer_state *YY_BUFFER_STATE;
 #endif
 
+#ifndef YY_TYPEDEF_YY_SIZE_T
+#define YY_TYPEDEF_YY_SIZE_T
+typedef size_t yy_size_t;
+#endif
+
 #define EOB_ACT_CONTINUE_SCAN 0
 #define EOB_ACT_END_OF_FILE 1
 #define EOB_ACT_LAST_MATCH 2
 
     #define YY_LESS_LINENO(n)
+    #define YY_LINENO_REWIND_TO(ptr)
 
 /* Return all but the first "n" matched characters back to the input stream. */
 #define yyless(n) \
-        do \
-                { \
-                /* Undo effects of setting up yytext. */ \
+	do \
+		{ \
+		/* Undo effects of setting up yytext. */ \
         int yyless_macro_arg = (n); \
         YY_LESS_LINENO(yyless_macro_arg);\
-                *yy_cp = yyg->yy_hold_char; \
-                YY_RESTORE_YY_MORE_OFFSET \
-                yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
-                YY_DO_BEFORE_ACTION; /* set up yytext again */ \
-                } \
-        while ( 0 )
+		*yy_cp = yyg->yy_hold_char; \
+		YY_RESTORE_YY_MORE_OFFSET \
+		yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
+		YY_DO_BEFORE_ACTION; /* set up yytext again */ \
+		} \
+	while ( 0 )
 
 #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner )
 
-#ifndef YY_TYPEDEF_YY_SIZE_T
-#define YY_TYPEDEF_YY_SIZE_T
-typedef size_t yy_size_t;
-#endif
-
 #ifndef YY_STRUCT_YY_BUFFER_STATE
 #define YY_STRUCT_YY_BUFFER_STATE
 struct yy_buffer_state
-        {
-        FILE *yy_input_file;
-
-        char *yy_ch_buf;                /* input buffer */
-        char *yy_buf_pos;               /* current position in input buffer */
-
-        /* Size of input buffer in bytes, not including room for EOB
-         * characters.
-         */
-        yy_size_t yy_buf_size;
-
-        /* Number of characters read into yy_ch_buf, not including EOB
-         * characters.
-         */
-        int yy_n_chars;
-
-        /* Whether we "own" the buffer - i.e., we know we created it,
-         * and can realloc() it to grow it, and should free() it to
-         * delete it.
-         */
-        int yy_is_our_buffer;
-
-        /* Whether this is an "interactive" input source; if so, and
-         * if we're using stdio for input, then we want to use getc()
-         * instead of fread(), to make sure we stop fetching input after
-         * each newline.
-         */
-        int yy_is_interactive;
-
-        /* Whether we're considered to be at the beginning of a line.
-         * If so, '^' rules will be active on the next match, otherwise
-         * not.
-         */
-        int yy_at_bol;
+	{
+	FILE *yy_input_file;
+
+	char *yy_ch_buf;		/* input buffer */
+	char *yy_buf_pos;		/* current position in input buffer */
+
+	/* Size of input buffer in bytes, not including room for EOB
+	 * characters.
+	 */
+	int yy_buf_size;
+
+	/* Number of characters read into yy_ch_buf, not including EOB
+	 * characters.
+	 */
+	int yy_n_chars;
+
+	/* Whether we "own" the buffer - i.e., we know we created it,
+	 * and can realloc() it to grow it, and should free() it to
+	 * delete it.
+	 */
+	int yy_is_our_buffer;
+
+	/* Whether this is an "interactive" input source; if so, and
+	 * if we're using stdio for input, then we want to use getc()
+	 * instead of fread(), to make sure we stop fetching input after
+	 * each newline.
+	 */
+	int yy_is_interactive;
+
+	/* Whether we're considered to be at the beginning of a line.
+	 * If so, '^' rules will be active on the next match, otherwise
+	 * not.
+	 */
+	int yy_at_bol;
 
     int yy_bs_lineno; /**< The line count. */
     int yy_bs_column; /**< The column count. */
 
-        /* Whether to try to fill the input buffer when we reach the
-         * end of it.
-         */
-        int yy_fill_buffer;
+	/* Whether to try to fill the input buffer when we reach the
+	 * end of it.
+	 */
+	int yy_fill_buffer;
 
-        int yy_buffer_status;
+	int yy_buffer_status;
 
 #define YY_BUFFER_NEW 0
 #define YY_BUFFER_NORMAL 1
-        /* When an EOF's been seen but there's still some text to process
-         * then we mark the buffer as YY_EOF_PENDING, to indicate that we
-         * shouldn't try reading from the input source any more.  We might
-         * still have a bunch of tokens to match, though, because of
-         * possible backing-up.
-         *
-         * When we actually see the EOF, we change the status to "new"
-         * (via cmCommandArgument_yyrestart()), so that the user can continue scanning by
-         * just pointing yyin at a new input file.
-         */
+	/* When an EOF's been seen but there's still some text to process
+	 * then we mark the buffer as YY_EOF_PENDING, to indicate that we
+	 * shouldn't try reading from the input source any more.  We might
+	 * still have a bunch of tokens to match, though, because of
+	 * possible backing-up.
+	 *
+	 * When we actually see the EOF, we change the status to "new"
+	 * (via cmCommandArgument_yyrestart()), so that the user can continue scanning by
+	 * just pointing yyin at a new input file.
+	 */
 #define YY_BUFFER_EOF_PENDING 2
 
-        };
+	};
 #endif /* !YY_STRUCT_YY_BUFFER_STATE */
 
 /* We provide macros for accessing buffer states in case in the
@@ -307,30 +302,30 @@ void cmCommandArgument_yyfree (void * ,yyscan_t yyscanner );
 #define yy_new_buffer cmCommandArgument_yy_create_buffer
 
 #define yy_set_interactive(is_interactive) \
-        { \
-        if ( ! YY_CURRENT_BUFFER ){ \
+	{ \
+	if ( ! YY_CURRENT_BUFFER ){ \
         cmCommandArgument_yyensure_buffer_stack (yyscanner); \
-                YY_CURRENT_BUFFER_LVALUE =    \
+		YY_CURRENT_BUFFER_LVALUE =    \
             cmCommandArgument_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
-        } \
-        YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
-        }
+	} \
+	YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
+	}
 
 #define yy_set_bol(at_bol) \
-        { \
-        if ( ! YY_CURRENT_BUFFER ){\
+	{ \
+	if ( ! YY_CURRENT_BUFFER ){\
         cmCommandArgument_yyensure_buffer_stack (yyscanner); \
-                YY_CURRENT_BUFFER_LVALUE =    \
+		YY_CURRENT_BUFFER_LVALUE =    \
             cmCommandArgument_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
-        } \
-        YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
-        }
+	} \
+	YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
+	}
 
 #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
 
 /* Begin user sect3 */
 
-#define cmCommandArgument_yywrap(n) 1
+#define cmCommandArgument_yywrap(yyscanner) (/*CONSTCOND*/1)
 #define YY_SKIP_YYWRAP
 
 typedef unsigned char YY_CHAR;
@@ -342,27 +337,27 @@ typedef int yy_state_type;
 static yy_state_type yy_get_previous_state (yyscan_t yyscanner );
 static yy_state_type yy_try_NUL_trans (yy_state_type current_state  ,yyscan_t yyscanner);
 static int yy_get_next_buffer (yyscan_t yyscanner );
-static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner );
+static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );
 
 /* Done after the current pattern has been matched and before the
  * corresponding action - sets up yytext.
  */
 #define YY_DO_BEFORE_ACTION \
-        yyg->yytext_ptr = yy_bp; \
-        yyleng = (size_t) (yy_cp - yy_bp); \
-        yyg->yy_hold_char = *yy_cp; \
-        *yy_cp = '\0'; \
-        yyg->yy_c_buf_p = yy_cp;
+	yyg->yytext_ptr = yy_bp; \
+	yyleng = (int) (yy_cp - yy_bp); \
+	yyg->yy_hold_char = *yy_cp; \
+	*yy_cp = '\0'; \
+	yyg->yy_c_buf_p = yy_cp;
 
 #define YY_NUM_RULES 14
 #define YY_END_OF_BUFFER 15
 /* This struct is not used in this scanner,
    but its presence is necessary. */
 struct yy_trans_info
-        {
-        flex_int32_t yy_verify;
-        flex_int32_t yy_nxt;
-        };
+	{
+	flex_int32_t yy_verify;
+	flex_int32_t yy_nxt;
+	};
 static yyconst flex_int16_t yy_accept[30] =
     {   0,
         0,    0,    0,    0,    0,    0,   15,    9,   10,    7,
@@ -370,7 +365,7 @@ static yyconst flex_int16_t yy_accept[30] =
         7,    0,    8,    2,    0,    3,    0,    1,    0
     } ;
 
-static yyconst flex_int32_t yy_ec[256] =
+static yyconst YY_CHAR yy_ec[256] =
     {   0,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    2,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
@@ -402,13 +397,13 @@ static yyconst flex_int32_t yy_ec[256] =
         1,    1,    1,    1,    1
     } ;
 
-static yyconst flex_int32_t yy_meta[12] =
+static yyconst YY_CHAR yy_meta[12] =
     {   0,
         1,    2,    3,    4,    3,    4,    4,    4,    3,    5,
         3
     } ;
 
-static yyconst flex_int16_t yy_base[35] =
+static yyconst flex_uint16_t yy_base[35] =
     {   0,
         0,    0,   31,   30,   29,   28,   36,    0,    6,   16,
         0,   41,   41,   41,    0,   41,    0,   22,   22,   41,
@@ -424,7 +419,7 @@ static yyconst flex_int16_t yy_def[35] =
        29,   29,   29,   29
     } ;
 
-static yyconst flex_int16_t yy_nxt[53] =
+static yyconst flex_uint16_t yy_nxt[53] =
     {   0,
         8,    8,    9,   10,   11,   10,   10,   10,   12,   13,
        14,   19,   22,   28,   27,   20,   17,   17,   17,   17,
@@ -457,31 +452,21 @@ static yyconst flex_int16_t yy_chk[53] =
    file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
-This file must be translated to C and modified to build everywhere.
+This file must be translated to C++ and modified to build everywhere.
 
-Run flex like this:
+Run flex >= 2.6 like this:
 
-  flex --prefix=cmCommandArgument_yy --header-file=cmCommandArgumentLexer.h -ocmCommandArgumentLexer.cxx cmCommandArgumentLexer.in.l
+  flex --nounistd -DFLEXINT_H --prefix=cmCommandArgument_yy --header-file=cmCommandArgumentLexer.h -ocmCommandArgumentLexer.cxx cmCommandArgumentLexer.in.l
 
 Modify cmCommandArgumentLexer.cxx:
-  - add #include "cmStandardIncludes.h" to top of file
-  - put header block at top of file
-  - remove TABs
-  - remove "yyscanner" argument from these methods:
-      yy_fatal_error, cmCommandArgument_yyalloc, cmCommandArgument_yyrealloc, cmCommandArgument_yyfree
-  - remove all YY_BREAK lines occurring right after return statements
-  - change while ( 1 ) to for(;;)
-  - add "return 0;" to end of cmCommandArgument_yylex
-
-Modify cmCommandArgumentLexer.h:
-  - remove TABs
-  - remove the yy_init_globals function
-  - remove the block that includes unistd.h
-  - remove #line directives (avoids bogus warning on old Sun)
+  - remove trailing whitespace: sed -i 's/\s*$//' cmCommandArgumentLexer.h cmCommandArgumentLexer.cxx
+  - remove blank lines at end of file
+  - #include "cmStandardLexer.h" at the top
+  - add cast in cmCommandArgument_yy_scan_bytes for loop condition of _yybytes_len to size_t
 
 */
 
-#include "cmStandardLexer.h"
+/* IWYU pragma: no_forward_declare yyguts_t */
 
 #include "cmCommandArgumentParserHelper.h"
 
@@ -496,20 +481,12 @@ Modify cmCommandArgumentLexer.h:
 /*--------------------------------------------------------------------------*/
 
 
-#line 508 "cmCommandArgumentLexer.cxx"
+#line 484 "cmCommandArgumentLexer.cxx"
 
 #define INITIAL 0
 #define ESCAPES 1
 #define NOESCAPES 2
 
-#ifndef YY_NO_UNISTD_H
-/* Special case for "unistd.h", since it is non-ANSI. We include it way
- * down here because we want the user's section 1 to have been scanned first.
- * The user has a chance to override it with an option.
- */
-#include <unistd.h>
-#endif
-
 #ifndef YY_EXTRA_TYPE
 #define YY_EXTRA_TYPE void *
 #endif
@@ -569,19 +546,23 @@ void cmCommandArgument_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscann
 
 FILE *cmCommandArgument_yyget_in (yyscan_t yyscanner );
 
-void cmCommandArgument_yyset_in  (FILE * in_str ,yyscan_t yyscanner );
+void cmCommandArgument_yyset_in  (FILE * _in_str ,yyscan_t yyscanner );
 
 FILE *cmCommandArgument_yyget_out (yyscan_t yyscanner );
 
-void cmCommandArgument_yyset_out  (FILE * out_str ,yyscan_t yyscanner );
+void cmCommandArgument_yyset_out  (FILE * _out_str ,yyscan_t yyscanner );
 
-int cmCommandArgument_yyget_leng (yyscan_t yyscanner );
+			int cmCommandArgument_yyget_leng (yyscan_t yyscanner );
 
 char *cmCommandArgument_yyget_text (yyscan_t yyscanner );
 
 int cmCommandArgument_yyget_lineno (yyscan_t yyscanner );
 
-void cmCommandArgument_yyset_lineno (int line_number ,yyscan_t yyscanner );
+void cmCommandArgument_yyset_lineno (int _line_number ,yyscan_t yyscanner );
+
+int cmCommandArgument_yyget_column  (yyscan_t yyscanner );
+
+void cmCommandArgument_yyset_column (int _column_no ,yyscan_t yyscanner );
 
 /* Macros after this point can all be overridden by user definitions in
  * section 1.
@@ -595,6 +576,10 @@ extern int cmCommandArgument_yywrap (yyscan_t yyscanner );
 #endif
 #endif
 
+#ifndef YY_NO_UNPUT
+
+#endif
+
 #ifndef yytext_ptr
 static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
 #endif
@@ -615,7 +600,12 @@ static int input (yyscan_t yyscanner );
 
 /* Amount of stuff to slurp up with each read. */
 #ifndef YY_READ_BUF_SIZE
+#ifdef __ia64__
+/* On IA-64, the buffer size is 16k, not 8k */
+#define YY_READ_BUF_SIZE 16384
+#else
 #define YY_READ_BUF_SIZE 8192
+#endif /* __ia64__ */
 #endif
 
 /* Copy whatever the last rule matched to the standard output. */
@@ -623,7 +613,7 @@ static int input (yyscan_t yyscanner );
 /* This used to be an fputs(), but since the string might contain NUL's,
  * we now use fwrite().
  */
-#define ECHO fwrite( yytext, yyleng, 1, yyout )
+#define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0)
 #endif
 
 /* Gets input and stuffs it into "buf".  number of characters read, or YY_NULL,
@@ -631,33 +621,33 @@ static int input (yyscan_t yyscanner );
  */
 #ifndef YY_INPUT
 #define YY_INPUT(buf,result,max_size) \
-        if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
-                { \
-                int c = '*'; \
-                size_t n; \
-                for ( n = 0; n < max_size && \
-                             (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
-                        buf[n] = (char) c; \
-                if ( c == '\n' ) \
-                        buf[n++] = (char) c; \
-                if ( c == EOF && ferror( yyin ) ) \
-                        YY_FATAL_ERROR( "input in flex scanner failed" ); \
-                result = n; \
-                } \
-        else \
-                { \
-                errno=0; \
-                while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
-                        { \
-                        if( errno != EINTR) \
-                                { \
-                                YY_FATAL_ERROR( "input in flex scanner failed" ); \
-                                break; \
-                                } \
-                        errno=0; \
-                        clearerr(yyin); \
-                        } \
-                }\
+	if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
+		{ \
+		int c = '*'; \
+		size_t n; \
+		for ( n = 0; n < max_size && \
+			     (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
+			buf[n] = (char) c; \
+		if ( c == '\n' ) \
+			buf[n++] = (char) c; \
+		if ( c == EOF && ferror( yyin ) ) \
+			YY_FATAL_ERROR( "input in flex scanner failed" ); \
+		result = n; \
+		} \
+	else \
+		{ \
+		errno=0; \
+		while ( (result = (int) fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
+			{ \
+			if( errno != EINTR) \
+				{ \
+				YY_FATAL_ERROR( "input in flex scanner failed" ); \
+				break; \
+				} \
+			errno=0; \
+			clearerr(yyin); \
+			} \
+		}\
 \
 
 #endif
@@ -702,169 +692,177 @@ extern int cmCommandArgument_yylex (yyscan_t yyscanner);
 
 /* Code executed at the end of each rule. */
 #ifndef YY_BREAK
-#define YY_BREAK break;
+#define YY_BREAK /*LINTED*/break;
 #endif
 
 #define YY_RULE_SETUP \
-        YY_USER_ACTION
+	YY_USER_ACTION
 
 /** The main scanner function which does all the work.
  */
 YY_DECL
 {
-        yy_state_type yy_current_state;
-        char *yy_cp, *yy_bp;
-        int yy_act;
+	yy_state_type yy_current_state;
+	char *yy_cp, *yy_bp;
+	int yy_act;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-#line 64 "cmCommandArgumentLexer.in.l"
+	if ( !yyg->yy_init )
+		{
+		yyg->yy_init = 1;
 
+#ifdef YY_USER_INIT
+		YY_USER_INIT;
+#endif
 
-#line 732 "cmCommandArgumentLexer.cxx"
+		if ( ! yyg->yy_start )
+			yyg->yy_start = 1;	/* first start state */
 
-        if ( !yyg->yy_init )
-                {
-                yyg->yy_init = 1;
+		if ( ! yyin )
+			yyin = stdin;
 
-#ifdef YY_USER_INIT
-                YY_USER_INIT;
-#endif
+		if ( ! yyout )
+			yyout = stdout;
 
-                if ( ! yyg->yy_start )
-                        yyg->yy_start = 1;      /* first start state */
+		if ( ! YY_CURRENT_BUFFER ) {
+			cmCommandArgument_yyensure_buffer_stack (yyscanner);
+			YY_CURRENT_BUFFER_LVALUE =
+				cmCommandArgument_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
+		}
 
-                if ( ! yyin )
-                        yyin = stdin;
+		cmCommandArgument_yy_load_buffer_state(yyscanner );
+		}
 
-                if ( ! yyout )
-                        yyout = stdout;
+	{
+#line 42 "cmCommandArgumentLexer.in.l"
 
-                if ( ! YY_CURRENT_BUFFER ) {
-                        cmCommandArgument_yyensure_buffer_stack (yyscanner);
-                        YY_CURRENT_BUFFER_LVALUE =
-                                cmCommandArgument_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
-                }
 
-                cmCommandArgument_yy_load_buffer_state(yyscanner );
-                }
+#line 740 "cmCommandArgumentLexer.cxx"
 
-        for(;;)             /* loops until end-of-file is reached */
-                {
-                yy_cp = yyg->yy_c_buf_p;
+	while ( /*CONSTCOND*/1 )		/* loops until end-of-file is reached */
+		{
+		yy_cp = yyg->yy_c_buf_p;
 
-                /* Support of yytext. */
-                *yy_cp = yyg->yy_hold_char;
+		/* Support of yytext. */
+		*yy_cp = yyg->yy_hold_char;
 
-                /* yy_bp points to the position in yy_ch_buf of the start of
-                 * the current run.
-                 */
-                yy_bp = yy_cp;
+		/* yy_bp points to the position in yy_ch_buf of the start of
+		 * the current run.
+		 */
+		yy_bp = yy_cp;
 
-                yy_current_state = yyg->yy_start;
+		yy_current_state = yyg->yy_start;
 yy_match:
-                do
-                        {
-                        YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
-                        if ( yy_accept[yy_current_state] )
-                                {
-                                yyg->yy_last_accepting_state = yy_current_state;
-                                yyg->yy_last_accepting_cpos = yy_cp;
-                                }
-                        while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
-                                {
-                                yy_current_state = (int) yy_def[yy_current_state];
-                                if ( yy_current_state >= 30 )
-                                        yy_c = yy_meta[(unsigned int) yy_c];
-                                }
-                        yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-                        ++yy_cp;
-                        }
-                while ( yy_base[yy_current_state] != 41 );
+		do
+			{
+			YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ;
+			if ( yy_accept[yy_current_state] )
+				{
+				yyg->yy_last_accepting_state = yy_current_state;
+				yyg->yy_last_accepting_cpos = yy_cp;
+				}
+			while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+				{
+				yy_current_state = (int) yy_def[yy_current_state];
+				if ( yy_current_state >= 30 )
+					yy_c = yy_meta[(unsigned int) yy_c];
+				}
+			yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+			++yy_cp;
+			}
+		while ( yy_base[yy_current_state] != 41 );
 
 yy_find_action:
-                yy_act = yy_accept[yy_current_state];
-                if ( yy_act == 0 )
-                        { /* have to back up */
-                        yy_cp = yyg->yy_last_accepting_cpos;
-                        yy_current_state = yyg->yy_last_accepting_state;
-                        yy_act = yy_accept[yy_current_state];
-                        }
-
-                YY_DO_BEFORE_ACTION;
-
-do_action:      /* This label is used only to access EOF actions. */
-
-                switch ( yy_act )
-        { /* beginning of action switch */
-                        case 0: /* must back up */
-                        /* undo the effects of YY_DO_BEFORE_ACTION */
-                        *yy_cp = yyg->yy_hold_char;
-                        yy_cp = yyg->yy_last_accepting_cpos;
-                        yy_current_state = yyg->yy_last_accepting_state;
-                        goto yy_find_action;
+		yy_act = yy_accept[yy_current_state];
+		if ( yy_act == 0 )
+			{ /* have to back up */
+			yy_cp = yyg->yy_last_accepting_cpos;
+			yy_current_state = yyg->yy_last_accepting_state;
+			yy_act = yy_accept[yy_current_state];
+			}
+
+		YY_DO_BEFORE_ACTION;
+
+do_action:	/* This label is used only to access EOF actions. */
+
+		switch ( yy_act )
+	{ /* beginning of action switch */
+			case 0: /* must back up */
+			/* undo the effects of YY_DO_BEFORE_ACTION */
+			*yy_cp = yyg->yy_hold_char;
+			yy_cp = yyg->yy_last_accepting_cpos;
+			yy_current_state = yyg->yy_last_accepting_state;
+			goto yy_find_action;
 
 case 1:
 YY_RULE_SETUP
-#line 66 "cmCommandArgumentLexer.in.l"
+#line 44 "cmCommandArgumentLexer.in.l"
 {
   //std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
   yyextra->AllocateParserType(yylvalp, yytext+1, strlen(yytext)-2);
   return cal_ENVCURLY;
 }
+	YY_BREAK
 case 2:
 YY_RULE_SETUP
-#line 72 "cmCommandArgumentLexer.in.l"
+#line 50 "cmCommandArgumentLexer.in.l"
 {
   //std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
   yyextra->AllocateParserType(yylvalp, yytext+1, strlen(yytext)-2);
   return cal_NCURLY;
 }
+	YY_BREAK
 case 3:
 YY_RULE_SETUP
-#line 78 "cmCommandArgumentLexer.in.l"
+#line 56 "cmCommandArgumentLexer.in.l"
 {
   //std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
   yyextra->AllocateParserType(yylvalp, yytext+1, strlen(yytext)-2);
   return cal_ATNAME;
 }
+	YY_BREAK
 case 4:
 YY_RULE_SETUP
-#line 84 "cmCommandArgumentLexer.in.l"
+#line 62 "cmCommandArgumentLexer.in.l"
 {
   //std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
   //yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
   yylvalp->str = yyextra->DCURLYVariable;
   return cal_DCURLY;
 }
+	YY_BREAK
 case 5:
 YY_RULE_SETUP
-#line 91 "cmCommandArgumentLexer.in.l"
+#line 69 "cmCommandArgumentLexer.in.l"
 {
   //std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
   //yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
   yylvalp->str = yyextra->RCURLYVariable;
   return cal_RCURLY;
 }
+	YY_BREAK
 case 6:
 YY_RULE_SETUP
-#line 98 "cmCommandArgumentLexer.in.l"
+#line 76 "cmCommandArgumentLexer.in.l"
 {
   //std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
   //yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
   yylvalp->str = yyextra->ATVariable;
   return cal_AT;
 }
+	YY_BREAK
 case 7:
 YY_RULE_SETUP
-#line 105 "cmCommandArgumentLexer.in.l"
+#line 83 "cmCommandArgumentLexer.in.l"
 {
   //std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
   yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
   return cal_NAME;
 }
+	YY_BREAK
 case 8:
 YY_RULE_SETUP
-#line 111 "cmCommandArgumentLexer.in.l"
+#line 89 "cmCommandArgumentLexer.in.l"
 {
   if ( !yyextra->HandleEscapeSymbol(yylvalp, *(yytext+1)) )
     {
@@ -872,387 +870,398 @@ YY_RULE_SETUP
     }
   return cal_SYMBOL;
 }
+	YY_BREAK
 case 9:
 /* rule 9 can match eol */
 YY_RULE_SETUP
-#line 119 "cmCommandArgumentLexer.in.l"
+#line 97 "cmCommandArgumentLexer.in.l"
 {
   //std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
   yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
   return cal_SYMBOL;
 }
+	YY_BREAK
 case 10:
 YY_RULE_SETUP
-#line 125 "cmCommandArgumentLexer.in.l"
+#line 103 "cmCommandArgumentLexer.in.l"
 {
   //yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
   yylvalp->str = yyextra->DOLLARVariable;
   return cal_DOLLAR;
 }
+	YY_BREAK
 case 11:
 YY_RULE_SETUP
-#line 131 "cmCommandArgumentLexer.in.l"
+#line 109 "cmCommandArgumentLexer.in.l"
 {
   //yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
   yylvalp->str = yyextra->LCURLYVariable;
   return cal_LCURLY;
 }
+	YY_BREAK
 case 12:
 YY_RULE_SETUP
-#line 137 "cmCommandArgumentLexer.in.l"
+#line 115 "cmCommandArgumentLexer.in.l"
 {
   //yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
   yylvalp->str = yyextra->BSLASHVariable;
   return cal_BSLASH;
 }
+	YY_BREAK
 case 13:
 YY_RULE_SETUP
-#line 143 "cmCommandArgumentLexer.in.l"
+#line 121 "cmCommandArgumentLexer.in.l"
 {
   //yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
   yylvalp->str = yyextra->BSLASHVariable;
   return cal_SYMBOL;
 }
+	YY_BREAK
 case 14:
 YY_RULE_SETUP
-#line 149 "cmCommandArgumentLexer.in.l"
+#line 127 "cmCommandArgumentLexer.in.l"
 ECHO;
-        YY_BREAK
-#line 943 "cmCommandArgumentLexer.cxx"
+	YY_BREAK
+#line 925 "cmCommandArgumentLexer.cxx"
 case YY_STATE_EOF(INITIAL):
 case YY_STATE_EOF(ESCAPES):
 case YY_STATE_EOF(NOESCAPES):
-        yyterminate();
-
-        case YY_END_OF_BUFFER:
-                {
-                /* Amount of text matched not including the EOB char. */
-                int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1;
-
-                /* Undo the effects of YY_DO_BEFORE_ACTION. */
-                *yy_cp = yyg->yy_hold_char;
-                YY_RESTORE_YY_MORE_OFFSET
-
-                if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
-                        {
-                        /* We're scanning a new file or input source.  It's
-                         * possible that this happened because the user
-                         * just pointed yyin at a new source and called
-                         * cmCommandArgument_yylex().  If so, then we have to assure
-                         * consistency between YY_CURRENT_BUFFER and our
-                         * globals.  Here is the right place to do so, because
-                         * this is the first action (other than possibly a
-                         * back-up) that will match for the new input source.
-                         */
-                        yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
-                        YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
-                        YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
-                        }
-
-                /* Note that here we test for yy_c_buf_p "<=" to the position
-                 * of the first EOB in the buffer, since yy_c_buf_p will
-                 * already have been incremented past the NUL character
-                 * (since all states make transitions on EOB to the
-                 * end-of-buffer state).  Contrast this with the test
-                 * in input().
-                 */
-                if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
-                        { /* This was really a NUL. */
-                        yy_state_type yy_next_state;
-
-                        yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text;
-
-                        yy_current_state = yy_get_previous_state( yyscanner );
-
-                        /* Okay, we're now positioned to make the NUL
-                         * transition.  We couldn't have
-                         * yy_get_previous_state() go ahead and do it
-                         * for us because it doesn't know how to deal
-                         * with the possibility of jamming (and we don't
-                         * want to build jamming into it because then it
-                         * will run more slowly).
-                         */
-
-                        yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner);
-
-                        yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
-
-                        if ( yy_next_state )
-                                {
-                                /* Consume the NUL. */
-                                yy_cp = ++yyg->yy_c_buf_p;
-                                yy_current_state = yy_next_state;
-                                goto yy_match;
-                                }
-
-                        else
-                                {
-                                yy_cp = yyg->yy_c_buf_p;
-                                goto yy_find_action;
-                                }
-                        }
-
-                else switch ( yy_get_next_buffer( yyscanner ) )
-                        {
-                        case EOB_ACT_END_OF_FILE:
-                                {
-                                yyg->yy_did_buffer_switch_on_eof = 0;
-
-                                if ( cmCommandArgument_yywrap(yyscanner ) )
-                                        {
-                                        /* Note: because we've taken care in
-                                         * yy_get_next_buffer() to have set up
-                                         * yytext, we can now set up
-                                         * yy_c_buf_p so that if some total
-                                         * hoser (like flex itself) wants to
-                                         * call the scanner after we return the
-                                         * YY_NULL, it'll still work - another
-                                         * YY_NULL will get returned.
-                                         */
-                                        yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ;
-
-                                        yy_act = YY_STATE_EOF(YY_START);
-                                        goto do_action;
-                                        }
-
-                                else
-                                        {
-                                        if ( ! yyg->yy_did_buffer_switch_on_eof )
-                                                YY_NEW_FILE;
-                                        }
-                                break;
-                                }
-
-                        case EOB_ACT_CONTINUE_SCAN:
-                                yyg->yy_c_buf_p =
-                                        yyg->yytext_ptr + yy_amount_of_matched_text;
-
-                                yy_current_state = yy_get_previous_state( yyscanner );
-
-                                yy_cp = yyg->yy_c_buf_p;
-                                yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
-                                goto yy_match;
-
-                        case EOB_ACT_LAST_MATCH:
-                                yyg->yy_c_buf_p =
-                                &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars];
-
-                                yy_current_state = yy_get_previous_state( yyscanner );
-
-                                yy_cp = yyg->yy_c_buf_p;
-                                yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
-                                goto yy_find_action;
-                        }
-                break;
-                }
-
-        default:
-                YY_FATAL_ERROR(
-                        "fatal flex scanner internal error--no action found" );
-        } /* end of action switch */
-                } /* end of scanning one token */
-return 0; /* this should not happen but it quiets some compilers */
+	yyterminate();
+
+	case YY_END_OF_BUFFER:
+		{
+		/* Amount of text matched not including the EOB char. */
+		int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1;
+
+		/* Undo the effects of YY_DO_BEFORE_ACTION. */
+		*yy_cp = yyg->yy_hold_char;
+		YY_RESTORE_YY_MORE_OFFSET
+
+		if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
+			{
+			/* We're scanning a new file or input source.  It's
+			 * possible that this happened because the user
+			 * just pointed yyin at a new source and called
+			 * cmCommandArgument_yylex().  If so, then we have to assure
+			 * consistency between YY_CURRENT_BUFFER and our
+			 * globals.  Here is the right place to do so, because
+			 * this is the first action (other than possibly a
+			 * back-up) that will match for the new input source.
+			 */
+			yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+			YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
+			YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
+			}
+
+		/* Note that here we test for yy_c_buf_p "<=" to the position
+		 * of the first EOB in the buffer, since yy_c_buf_p will
+		 * already have been incremented past the NUL character
+		 * (since all states make transitions on EOB to the
+		 * end-of-buffer state).  Contrast this with the test
+		 * in input().
+		 */
+		if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
+			{ /* This was really a NUL. */
+			yy_state_type yy_next_state;
+
+			yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text;
+
+			yy_current_state = yy_get_previous_state( yyscanner );
+
+			/* Okay, we're now positioned to make the NUL
+			 * transition.  We couldn't have
+			 * yy_get_previous_state() go ahead and do it
+			 * for us because it doesn't know how to deal
+			 * with the possibility of jamming (and we don't
+			 * want to build jamming into it because then it
+			 * will run more slowly).
+			 */
+
+			yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner);
+
+			yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
+
+			if ( yy_next_state )
+				{
+				/* Consume the NUL. */
+				yy_cp = ++yyg->yy_c_buf_p;
+				yy_current_state = yy_next_state;
+				goto yy_match;
+				}
+
+			else
+				{
+				yy_cp = yyg->yy_c_buf_p;
+				goto yy_find_action;
+				}
+			}
+
+		else switch ( yy_get_next_buffer( yyscanner ) )
+			{
+			case EOB_ACT_END_OF_FILE:
+				{
+				yyg->yy_did_buffer_switch_on_eof = 0;
+
+				if ( cmCommandArgument_yywrap(yyscanner ) )
+					{
+					/* Note: because we've taken care in
+					 * yy_get_next_buffer() to have set up
+					 * yytext, we can now set up
+					 * yy_c_buf_p so that if some total
+					 * hoser (like flex itself) wants to
+					 * call the scanner after we return the
+					 * YY_NULL, it'll still work - another
+					 * YY_NULL will get returned.
+					 */
+					yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ;
+
+					yy_act = YY_STATE_EOF(YY_START);
+					goto do_action;
+					}
+
+				else
+					{
+					if ( ! yyg->yy_did_buffer_switch_on_eof )
+						YY_NEW_FILE;
+					}
+				break;
+				}
+
+			case EOB_ACT_CONTINUE_SCAN:
+				yyg->yy_c_buf_p =
+					yyg->yytext_ptr + yy_amount_of_matched_text;
+
+				yy_current_state = yy_get_previous_state( yyscanner );
+
+				yy_cp = yyg->yy_c_buf_p;
+				yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
+				goto yy_match;
+
+			case EOB_ACT_LAST_MATCH:
+				yyg->yy_c_buf_p =
+				&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars];
+
+				yy_current_state = yy_get_previous_state( yyscanner );
+
+				yy_cp = yyg->yy_c_buf_p;
+				yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
+				goto yy_find_action;
+			}
+		break;
+		}
+
+	default:
+		YY_FATAL_ERROR(
+			"fatal flex scanner internal error--no action found" );
+	} /* end of action switch */
+		} /* end of scanning one token */
+	} /* end of user's declarations */
 } /* end of cmCommandArgument_yylex */
 
 /* yy_get_next_buffer - try to read in a new buffer
  *
  * Returns a code representing an action:
- *      EOB_ACT_LAST_MATCH -
- *      EOB_ACT_CONTINUE_SCAN - continue scanning from current position
- *      EOB_ACT_END_OF_FILE - end of file
+ *	EOB_ACT_LAST_MATCH -
+ *	EOB_ACT_CONTINUE_SCAN - continue scanning from current position
+ *	EOB_ACT_END_OF_FILE - end of file
  */
 static int yy_get_next_buffer (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-        char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
-        char *source = yyg->yytext_ptr;
-        int number_to_move, i;
-        int ret_val;
-
-        if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
-                YY_FATAL_ERROR(
-                "fatal flex scanner internal error--end of buffer missed" );
-
-        if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
-                { /* Don't try to fill the buffer, so this is an EOF. */
-                if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 )
-                        {
-                        /* We matched a single character, the EOB, so
-                         * treat this as a final EOF.
-                         */
-                        return EOB_ACT_END_OF_FILE;
-                        }
-
-                else
-                        {
-                        /* We matched some text prior to the EOB, first
-                         * process it.
-                         */
-                        return EOB_ACT_LAST_MATCH;
-                        }
-                }
-
-        /* Try to read more data. */
-
-        /* First move last chars to start of buffer. */
-        number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
-
-        for ( i = 0; i < number_to_move; ++i )
-                *(dest++) = *(source++);
-
-        if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
-                /* don't do the read, it's not guaranteed to return an EOF,
-                 * just force an EOF
-                 */
-                YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0;
-
-        else
-                {
-                        int num_to_read =
-                        YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
-
-                while ( num_to_read <= 0 )
-                        { /* Not enough room in the buffer - grow it. */
-
-                        /* just a shorter name for the current buffer */
-                        YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
-
-                        int yy_c_buf_p_offset =
-                                (int) (yyg->yy_c_buf_p - b->yy_ch_buf);
-
-                        if ( b->yy_is_our_buffer )
-                                {
-                                int new_size = b->yy_buf_size * 2;
-
-                                if ( new_size <= 0 )
-                                        b->yy_buf_size += b->yy_buf_size / 8;
-                                else
-                                        b->yy_buf_size *= 2;
-
-                                b->yy_ch_buf = (char *)
-                                        /* Include room in for 2 EOB chars. */
-                                        cmCommandArgument_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
-                                }
-                        else
-                                /* Can't grow it, we don't own it. */
-                                b->yy_ch_buf = 0;
-
-                        if ( ! b->yy_ch_buf )
-                                YY_FATAL_ERROR(
-                                "fatal error - scanner input buffer overflow" );
-
-                        yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
-
-                        num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
-                                                number_to_move - 1;
-
-                        }
-
-                if ( num_to_read > YY_READ_BUF_SIZE )
-                        num_to_read = YY_READ_BUF_SIZE;
-
-                /* Read in more data. */
-                YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
-                        yyg->yy_n_chars, (size_t) num_to_read );
-
-                YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
-                }
-
-        if ( yyg->yy_n_chars == 0 )
-                {
-                if ( number_to_move == YY_MORE_ADJ )
-                        {
-                        ret_val = EOB_ACT_END_OF_FILE;
-                        cmCommandArgument_yyrestart(yyin  ,yyscanner);
-                        }
-
-                else
-                        {
-                        ret_val = EOB_ACT_LAST_MATCH;
-                        YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
-                                YY_BUFFER_EOF_PENDING;
-                        }
-                }
-
-        else
-                ret_val = EOB_ACT_CONTINUE_SCAN;
-
-        if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
-                /* Extend the array by 50%, plus the number we really need. */
-                yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
-                YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) cmCommandArgument_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );
-                if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
-                        YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
-        }
-
-        yyg->yy_n_chars += number_to_move;
-        YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR;
-        YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
-
-        yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
+	char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
+	char *source = yyg->yytext_ptr;
+	yy_size_t number_to_move, i;
+	int ret_val;
+
+	if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
+		YY_FATAL_ERROR(
+		"fatal flex scanner internal error--end of buffer missed" );
+
+	if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
+		{ /* Don't try to fill the buffer, so this is an EOF. */
+		if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 )
+			{
+			/* We matched a single character, the EOB, so
+			 * treat this as a final EOF.
+			 */
+			return EOB_ACT_END_OF_FILE;
+			}
+
+		else
+			{
+			/* We matched some text prior to the EOB, first
+			 * process it.
+			 */
+			return EOB_ACT_LAST_MATCH;
+			}
+		}
+
+	/* Try to read more data. */
+
+	/* First move last chars to start of buffer. */
+	number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
+
+	for ( i = 0; i < number_to_move; ++i )
+		*(dest++) = *(source++);
+
+	if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
+		/* don't do the read, it's not guaranteed to return an EOF,
+		 * just force an EOF
+		 */
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0;
+
+	else
+		{
+			int num_to_read =
+			YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
+
+		while ( num_to_read <= 0 )
+			{ /* Not enough room in the buffer - grow it. */
+
+			/* just a shorter name for the current buffer */
+			YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE;
+
+			int yy_c_buf_p_offset =
+				(int) (yyg->yy_c_buf_p - b->yy_ch_buf);
+
+			if ( b->yy_is_our_buffer )
+				{
+				int new_size = b->yy_buf_size * 2;
+
+				if ( new_size <= 0 )
+					b->yy_buf_size += b->yy_buf_size / 8;
+				else
+					b->yy_buf_size *= 2;
+
+				b->yy_ch_buf = (char *)
+					/* Include room in for 2 EOB chars. */
+					cmCommandArgument_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
+				}
+			else
+				/* Can't grow it, we don't own it. */
+				b->yy_ch_buf = NULL;
+
+			if ( ! b->yy_ch_buf )
+				YY_FATAL_ERROR(
+				"fatal error - scanner input buffer overflow" );
+
+			yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
+
+			num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
+						number_to_move - 1;
+
+			}
+
+		if ( num_to_read > YY_READ_BUF_SIZE )
+			num_to_read = YY_READ_BUF_SIZE;
+
+		/* Read in more data. */
+		YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
+			yyg->yy_n_chars, num_to_read );
+
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
+		}
+
+	if ( yyg->yy_n_chars == 0 )
+		{
+		if ( number_to_move == YY_MORE_ADJ )
+			{
+			ret_val = EOB_ACT_END_OF_FILE;
+			cmCommandArgument_yyrestart(yyin  ,yyscanner);
+			}
+
+		else
+			{
+			ret_val = EOB_ACT_LAST_MATCH;
+			YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
+				YY_BUFFER_EOF_PENDING;
+			}
+		}
+
+	else
+		ret_val = EOB_ACT_CONTINUE_SCAN;
+
+	if ((int) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
+		/* Extend the array by 50%, plus the number we really need. */
+		int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
+		YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) cmCommandArgument_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );
+		if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
+			YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
+	}
+
+	yyg->yy_n_chars += number_to_move;
+	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR;
+	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
+
+	yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
 
-        return ret_val;
+	return ret_val;
 }
 
 /* yy_get_previous_state - get the state just before the EOB char was reached */
 
     static yy_state_type yy_get_previous_state (yyscan_t yyscanner)
 {
-        yy_state_type yy_current_state;
-        char *yy_cp;
+	yy_state_type yy_current_state;
+	char *yy_cp;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-        yy_current_state = yyg->yy_start;
-
-        for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp )
-                {
-                YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
-                if ( yy_accept[yy_current_state] )
-                        {
-                        yyg->yy_last_accepting_state = yy_current_state;
-                        yyg->yy_last_accepting_cpos = yy_cp;
-                        }
-                while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
-                        {
-                        yy_current_state = (int) yy_def[yy_current_state];
-                        if ( yy_current_state >= 30 )
-                                yy_c = yy_meta[(unsigned int) yy_c];
-                        }
-                yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-                }
-
-        return yy_current_state;
+	yy_current_state = yyg->yy_start;
+
+	for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp )
+		{
+		YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
+		if ( yy_accept[yy_current_state] )
+			{
+			yyg->yy_last_accepting_state = yy_current_state;
+			yyg->yy_last_accepting_cpos = yy_cp;
+			}
+		while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+			{
+			yy_current_state = (int) yy_def[yy_current_state];
+			if ( yy_current_state >= 30 )
+				yy_c = yy_meta[(unsigned int) yy_c];
+			}
+		yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+		}
+
+	return yy_current_state;
 }
 
 /* yy_try_NUL_trans - try to make a transition on the NUL character
  *
  * synopsis
- *      next_state = yy_try_NUL_trans( current_state );
+ *	next_state = yy_try_NUL_trans( current_state );
  */
     static yy_state_type yy_try_NUL_trans  (yy_state_type yy_current_state , yyscan_t yyscanner)
 {
-        int yy_is_jam;
+	int yy_is_jam;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */
-        char *yy_cp = yyg->yy_c_buf_p;
-
-        YY_CHAR yy_c = 1;
-        if ( yy_accept[yy_current_state] )
-                {
-                yyg->yy_last_accepting_state = yy_current_state;
-                yyg->yy_last_accepting_cpos = yy_cp;
-                }
-        while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
-                {
-                yy_current_state = (int) yy_def[yy_current_state];
-                if ( yy_current_state >= 30 )
-                        yy_c = yy_meta[(unsigned int) yy_c];
-                }
-        yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-        yy_is_jam = (yy_current_state == 29);
-
-        return yy_is_jam ? 0 : yy_current_state;
+	char *yy_cp = yyg->yy_c_buf_p;
+
+	YY_CHAR yy_c = 1;
+	if ( yy_accept[yy_current_state] )
+		{
+		yyg->yy_last_accepting_state = yy_current_state;
+		yyg->yy_last_accepting_cpos = yy_cp;
+		}
+	while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+		{
+		yy_current_state = (int) yy_def[yy_current_state];
+		if ( yy_current_state >= 30 )
+			yy_c = yy_meta[(unsigned int) yy_c];
+		}
+	yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+	yy_is_jam = (yy_current_state == 29);
+
+	(void)yyg;
+	return yy_is_jam ? 0 : yy_current_state;
 }
 
+#ifndef YY_NO_UNPUT
+
+#endif
+
 #ifndef YY_NO_INPUT
 #ifdef __cplusplus
     static int yyinput (yyscan_t yyscanner)
@@ -1261,72 +1270,72 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 #endif
 
 {
-        int c;
+	int c;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-        *yyg->yy_c_buf_p = yyg->yy_hold_char;
-
-        if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
-                {
-                /* yy_c_buf_p now points to the character we want to return.
-                 * If this occurs *before* the EOB characters, then it's a
-                 * valid NUL; if not, then we've hit the end of the buffer.
-                 */
-                if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
-                        /* This was really a NUL. */
-                        *yyg->yy_c_buf_p = '\0';
-
-                else
-                        { /* need more input */
-                        int offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
-                        ++yyg->yy_c_buf_p;
-
-                        switch ( yy_get_next_buffer( yyscanner ) )
-                                {
-                                case EOB_ACT_LAST_MATCH:
-                                        /* This happens because yy_g_n_b()
-                                         * sees that we've accumulated a
-                                         * token and flags that we need to
-                                         * try matching the token before
-                                         * proceeding.  But for input(),
-                                         * there's no matching to consider.
-                                         * So convert the EOB_ACT_LAST_MATCH
-                                         * to EOB_ACT_END_OF_FILE.
-                                         */
-
-                                        /* Reset buffer status. */
-                                        cmCommandArgument_yyrestart(yyin ,yyscanner);
-
-                                        /*FALLTHROUGH*/
-
-                                case EOB_ACT_END_OF_FILE:
-                                        {
-                                        if ( cmCommandArgument_yywrap(yyscanner ) )
-                                                return EOF;
-
-                                        if ( ! yyg->yy_did_buffer_switch_on_eof )
-                                                YY_NEW_FILE;
+	*yyg->yy_c_buf_p = yyg->yy_hold_char;
+
+	if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
+		{
+		/* yy_c_buf_p now points to the character we want to return.
+		 * If this occurs *before* the EOB characters, then it's a
+		 * valid NUL; if not, then we've hit the end of the buffer.
+		 */
+		if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
+			/* This was really a NUL. */
+			*yyg->yy_c_buf_p = '\0';
+
+		else
+			{ /* need more input */
+			int offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
+			++yyg->yy_c_buf_p;
+
+			switch ( yy_get_next_buffer( yyscanner ) )
+				{
+				case EOB_ACT_LAST_MATCH:
+					/* This happens because yy_g_n_b()
+					 * sees that we've accumulated a
+					 * token and flags that we need to
+					 * try matching the token before
+					 * proceeding.  But for input(),
+					 * there's no matching to consider.
+					 * So convert the EOB_ACT_LAST_MATCH
+					 * to EOB_ACT_END_OF_FILE.
+					 */
+
+					/* Reset buffer status. */
+					cmCommandArgument_yyrestart(yyin ,yyscanner);
+
+					/*FALLTHROUGH*/
+
+				case EOB_ACT_END_OF_FILE:
+					{
+					if ( cmCommandArgument_yywrap(yyscanner ) )
+						return 0;
+
+					if ( ! yyg->yy_did_buffer_switch_on_eof )
+						YY_NEW_FILE;
 #ifdef __cplusplus
-                                        return yyinput(yyscanner);
+					return yyinput(yyscanner);
 #else
-                                        return input(yyscanner);
+					return input(yyscanner);
 #endif
-                                        }
+					}
 
-                                case EOB_ACT_CONTINUE_SCAN:
-                                        yyg->yy_c_buf_p = yyg->yytext_ptr + offset;
-                                        break;
-                                }
-                        }
-                }
+				case EOB_ACT_CONTINUE_SCAN:
+					yyg->yy_c_buf_p = yyg->yytext_ptr + offset;
+					break;
+				}
+			}
+		}
 
-        c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */
-        *yyg->yy_c_buf_p = '\0';        /* preserve yytext */
-        yyg->yy_hold_char = *++yyg->yy_c_buf_p;
+	c = *(unsigned char *) yyg->yy_c_buf_p;	/* cast for 8-bit char's */
+	*yyg->yy_c_buf_p = '\0';	/* preserve yytext */
+	yyg->yy_hold_char = *++yyg->yy_c_buf_p;
 
-        return c;
+	return c;
 }
-#endif  /* ifndef YY_NO_INPUT */
+#endif	/* ifndef YY_NO_INPUT */
 
 /** Immediately switch to a different input stream.
  * @param input_file A readable stream.
@@ -1337,14 +1346,14 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-        if ( ! YY_CURRENT_BUFFER ){
+	if ( ! YY_CURRENT_BUFFER ){
         cmCommandArgument_yyensure_buffer_stack (yyscanner);
-                YY_CURRENT_BUFFER_LVALUE =
+		YY_CURRENT_BUFFER_LVALUE =
             cmCommandArgument_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
-        }
+	}
 
-        cmCommandArgument_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
-        cmCommandArgument_yy_load_buffer_state(yyscanner );
+	cmCommandArgument_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
+	cmCommandArgument_yy_load_buffer_state(yyscanner );
 }
 
 /** Switch to a different input buffer.
@@ -1355,41 +1364,41 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-        /* TODO. We should be able to replace this entire function body
-         * with
-         *              cmCommandArgument_yypop_buffer_state();
-         *              cmCommandArgument_yypush_buffer_state(new_buffer);
+	/* TODO. We should be able to replace this entire function body
+	 * with
+	 *		cmCommandArgument_yypop_buffer_state();
+	 *		cmCommandArgument_yypush_buffer_state(new_buffer);
      */
-        cmCommandArgument_yyensure_buffer_stack (yyscanner);
-        if ( YY_CURRENT_BUFFER == new_buffer )
-                return;
-
-        if ( YY_CURRENT_BUFFER )
-                {
-                /* Flush out information for old buffer. */
-                *yyg->yy_c_buf_p = yyg->yy_hold_char;
-                YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
-                YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
-                }
-
-        YY_CURRENT_BUFFER_LVALUE = new_buffer;
-        cmCommandArgument_yy_load_buffer_state(yyscanner );
-
-        /* We don't actually know whether we did this switch during
-         * EOF (cmCommandArgument_yywrap()) processing, but the only time this flag
-         * is looked at is after cmCommandArgument_yywrap() is called, so it's safe
-         * to go ahead and always set it.
-         */
-        yyg->yy_did_buffer_switch_on_eof = 1;
+	cmCommandArgument_yyensure_buffer_stack (yyscanner);
+	if ( YY_CURRENT_BUFFER == new_buffer )
+		return;
+
+	if ( YY_CURRENT_BUFFER )
+		{
+		/* Flush out information for old buffer. */
+		*yyg->yy_c_buf_p = yyg->yy_hold_char;
+		YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
+		}
+
+	YY_CURRENT_BUFFER_LVALUE = new_buffer;
+	cmCommandArgument_yy_load_buffer_state(yyscanner );
+
+	/* We don't actually know whether we did this switch during
+	 * EOF (cmCommandArgument_yywrap()) processing, but the only time this flag
+	 * is looked at is after cmCommandArgument_yywrap() is called, so it's safe
+	 * to go ahead and always set it.
+	 */
+	yyg->yy_did_buffer_switch_on_eof = 1;
 }
 
 static void cmCommandArgument_yy_load_buffer_state  (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-        yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
-        yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
-        yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
-        yyg->yy_hold_char = *yyg->yy_c_buf_p;
+	yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+	yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
+	yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
+	yyg->yy_hold_char = *yyg->yy_c_buf_p;
 }
 
 /** Allocate and initialize an input buffer state.
@@ -1400,26 +1409,26 @@ static void cmCommandArgument_yy_load_buffer_state  (yyscan_t yyscanner)
  */
     YY_BUFFER_STATE cmCommandArgument_yy_create_buffer  (FILE * file, int  size , yyscan_t yyscanner)
 {
-        YY_BUFFER_STATE b;
+	YY_BUFFER_STATE b;
 
-        b = (YY_BUFFER_STATE) cmCommandArgument_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
-        if ( ! b )
-                YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yy_create_buffer()" );
+	b = (YY_BUFFER_STATE) cmCommandArgument_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+	if ( ! b )
+		YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yy_create_buffer()" );
 
-        b->yy_buf_size = size;
+	b->yy_buf_size = (yy_size_t)size;
 
-        /* yy_ch_buf has to be 2 characters longer than the size given because
-         * we need to put in 2 end-of-buffer characters.
-         */
-        b->yy_ch_buf = (char *) cmCommandArgument_yyalloc(b->yy_buf_size + 2 ,yyscanner );
-        if ( ! b->yy_ch_buf )
-                YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yy_create_buffer()" );
+	/* yy_ch_buf has to be 2 characters longer than the size given because
+	 * we need to put in 2 end-of-buffer characters.
+	 */
+	b->yy_ch_buf = (char *) cmCommandArgument_yyalloc(b->yy_buf_size + 2 ,yyscanner );
+	if ( ! b->yy_ch_buf )
+		YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yy_create_buffer()" );
 
-        b->yy_is_our_buffer = 1;
+	b->yy_is_our_buffer = 1;
 
-        cmCommandArgument_yy_init_buffer(b,file ,yyscanner);
+	cmCommandArgument_yy_init_buffer(b,file ,yyscanner);
 
-        return b;
+	return b;
 }
 
 /** Destroy the buffer.
@@ -1430,22 +1439,18 @@ static void cmCommandArgument_yy_load_buffer_state  (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-        if ( ! b )
-                return;
+	if ( ! b )
+		return;
 
-        if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
-                YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
+	if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
+		YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
 
-        if ( b->yy_is_our_buffer )
-                cmCommandArgument_yyfree((void *) b->yy_ch_buf ,yyscanner );
+	if ( b->yy_is_our_buffer )
+		cmCommandArgument_yyfree((void *) b->yy_ch_buf ,yyscanner );
 
-        cmCommandArgument_yyfree((void *) b ,yyscanner );
+	cmCommandArgument_yyfree((void *) b ,yyscanner );
 }
 
-#ifndef __cplusplus
-extern int isatty (int );
-#endif /* __cplusplus */
-
 /* Initializes or reinitializes a buffer.
  * This function is sometimes called more than once on the same buffer,
  * such as during a cmCommandArgument_yyrestart() or at EOF.
@@ -1453,13 +1458,13 @@ extern int isatty (int );
     static void cmCommandArgument_yy_init_buffer  (YY_BUFFER_STATE  b, FILE * file , yyscan_t yyscanner)
 
 {
-        int oerrno = errno;
+	int oerrno = errno;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-        cmCommandArgument_yy_flush_buffer(b ,yyscanner);
+	cmCommandArgument_yy_flush_buffer(b ,yyscanner);
 
-        b->yy_input_file = file;
-        b->yy_fill_buffer = 1;
+	b->yy_input_file = file;
+	b->yy_fill_buffer = 1;
 
     /* If b is the current buffer, then cmCommandArgument_yy_init_buffer was _probably_
      * called from cmCommandArgument_yyrestart() or through yy_get_next_buffer.
@@ -1472,7 +1477,7 @@ extern int isatty (int );
 
         b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
 
-        errno = oerrno;
+	errno = oerrno;
 }
 
 /** Discard all buffered characters. On the next scan, YY_INPUT will be called.
@@ -1482,25 +1487,25 @@ extern int isatty (int );
     void cmCommandArgument_yy_flush_buffer (YY_BUFFER_STATE  b , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-        if ( ! b )
-                return;
+	if ( ! b )
+		return;
 
-        b->yy_n_chars = 0;
+	b->yy_n_chars = 0;
 
-        /* We always need two end-of-buffer characters.  The first causes
-         * a transition to the end-of-buffer state.  The second causes
-         * a jam in that state.
-         */
-        b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
-        b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
+	/* We always need two end-of-buffer characters.  The first causes
+	 * a transition to the end-of-buffer state.  The second causes
+	 * a jam in that state.
+	 */
+	b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
+	b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
 
-        b->yy_buf_pos = &b->yy_ch_buf[0];
+	b->yy_buf_pos = &b->yy_ch_buf[0];
 
-        b->yy_at_bol = 1;
-        b->yy_buffer_status = YY_BUFFER_NEW;
+	b->yy_at_bol = 1;
+	b->yy_buffer_status = YY_BUFFER_NEW;
 
-        if ( b == YY_CURRENT_BUFFER )
-                cmCommandArgument_yy_load_buffer_state(yyscanner );
+	if ( b == YY_CURRENT_BUFFER )
+		cmCommandArgument_yy_load_buffer_state(yyscanner );
 }
 
 /** Pushes the new state onto the stack. The new state becomes
@@ -1512,28 +1517,28 @@ extern int isatty (int );
 void cmCommandArgument_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-        if (new_buffer == NULL)
-                return;
-
-        cmCommandArgument_yyensure_buffer_stack(yyscanner);
-
-        /* This block is copied from cmCommandArgument_yy_switch_to_buffer. */
-        if ( YY_CURRENT_BUFFER )
-                {
-                /* Flush out information for old buffer. */
-                *yyg->yy_c_buf_p = yyg->yy_hold_char;
-                YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
-                YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
-                }
-
-        /* Only push if top exists. Otherwise, replace top. */
-        if (YY_CURRENT_BUFFER)
-                yyg->yy_buffer_stack_top++;
-        YY_CURRENT_BUFFER_LVALUE = new_buffer;
-
-        /* copied from cmCommandArgument_yy_switch_to_buffer. */
-        cmCommandArgument_yy_load_buffer_state(yyscanner );
-        yyg->yy_did_buffer_switch_on_eof = 1;
+	if (new_buffer == NULL)
+		return;
+
+	cmCommandArgument_yyensure_buffer_stack(yyscanner);
+
+	/* This block is copied from cmCommandArgument_yy_switch_to_buffer. */
+	if ( YY_CURRENT_BUFFER )
+		{
+		/* Flush out information for old buffer. */
+		*yyg->yy_c_buf_p = yyg->yy_hold_char;
+		YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
+		}
+
+	/* Only push if top exists. Otherwise, replace top. */
+	if (YY_CURRENT_BUFFER)
+		yyg->yy_buffer_stack_top++;
+	YY_CURRENT_BUFFER_LVALUE = new_buffer;
+
+	/* copied from cmCommandArgument_yy_switch_to_buffer. */
+	cmCommandArgument_yy_load_buffer_state(yyscanner );
+	yyg->yy_did_buffer_switch_on_eof = 1;
 }
 
 /** Removes and deletes the top of the stack, if present.
@@ -1543,18 +1548,18 @@ void cmCommandArgument_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_
 void cmCommandArgument_yypop_buffer_state (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-        if (!YY_CURRENT_BUFFER)
-                return;
-
-        cmCommandArgument_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
-        YY_CURRENT_BUFFER_LVALUE = NULL;
-        if (yyg->yy_buffer_stack_top > 0)
-                --yyg->yy_buffer_stack_top;
-
-        if (YY_CURRENT_BUFFER) {
-                cmCommandArgument_yy_load_buffer_state(yyscanner );
-                yyg->yy_did_buffer_switch_on_eof = 1;
-        }
+	if (!YY_CURRENT_BUFFER)
+		return;
+
+	cmCommandArgument_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
+	YY_CURRENT_BUFFER_LVALUE = NULL;
+	if (yyg->yy_buffer_stack_top > 0)
+		--yyg->yy_buffer_stack_top;
+
+	if (YY_CURRENT_BUFFER) {
+		cmCommandArgument_yy_load_buffer_state(yyscanner );
+		yyg->yy_did_buffer_switch_on_eof = 1;
+	}
 }
 
 /* Allocates the stack if it does not exist.
@@ -1562,46 +1567,46 @@ void cmCommandArgument_yypop_buffer_state (yyscan_t yyscanner)
  */
 static void cmCommandArgument_yyensure_buffer_stack (yyscan_t yyscanner)
 {
-        int num_to_alloc;
+	int num_to_alloc;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-        if (!yyg->yy_buffer_stack) {
+	if (!yyg->yy_buffer_stack) {
 
-                /* First allocation is just for 2 elements, since we don't know if this
-                 * scanner will even need a stack. We use 2 instead of 1 to avoid an
-                 * immediate realloc on the next call.
+		/* First allocation is just for 2 elements, since we don't know if this
+		 * scanner will even need a stack. We use 2 instead of 1 to avoid an
+		 * immediate realloc on the next call.
          */
-                num_to_alloc = 1;
-                yyg->yy_buffer_stack = (struct yy_buffer_state**)cmCommandArgument_yyalloc
-                                                                (num_to_alloc * sizeof(struct yy_buffer_state*)
-                                                                , yyscanner);
-                if ( ! yyg->yy_buffer_stack )
-                        YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yyensure_buffer_stack()" );
-
-                memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
-
-                yyg->yy_buffer_stack_max = num_to_alloc;
-                yyg->yy_buffer_stack_top = 0;
-                return;
-        }
-
-        if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
-
-                /* Increase the buffer to prepare for a possible push. */
-                int grow_size = 8 /* arbitrary grow size */;
-
-                num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
-                yyg->yy_buffer_stack = (struct yy_buffer_state**)cmCommandArgument_yyrealloc
-                                                                (yyg->yy_buffer_stack,
-                                                                num_to_alloc * sizeof(struct yy_buffer_state*)
-                                                                , yyscanner);
-                if ( ! yyg->yy_buffer_stack )
-                        YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yyensure_buffer_stack()" );
-
-                /* zero only the new slots.*/
-                memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
-                yyg->yy_buffer_stack_max = num_to_alloc;
-        }
+      num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
+		yyg->yy_buffer_stack = (struct yy_buffer_state**)cmCommandArgument_yyalloc
+								(num_to_alloc * sizeof(struct yy_buffer_state*)
+								, yyscanner);
+		if ( ! yyg->yy_buffer_stack )
+			YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yyensure_buffer_stack()" );
+
+		memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
+
+		yyg->yy_buffer_stack_max = num_to_alloc;
+		yyg->yy_buffer_stack_top = 0;
+		return;
+	}
+
+	if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
+
+		/* Increase the buffer to prepare for a possible push. */
+		yy_size_t grow_size = 8 /* arbitrary grow size */;
+
+		num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
+		yyg->yy_buffer_stack = (struct yy_buffer_state**)cmCommandArgument_yyrealloc
+								(yyg->yy_buffer_stack,
+								num_to_alloc * sizeof(struct yy_buffer_state*)
+								, yyscanner);
+		if ( ! yyg->yy_buffer_stack )
+			YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yyensure_buffer_stack()" );
+
+		/* zero only the new slots.*/
+		memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
+		yyg->yy_buffer_stack_max = num_to_alloc;
+	}
 }
 
 /** Setup the input buffer state to scan directly from a user-specified character buffer.
@@ -1612,31 +1617,31 @@ static void cmCommandArgument_yyensure_buffer_stack (yyscan_t yyscanner)
  */
 YY_BUFFER_STATE cmCommandArgument_yy_scan_buffer  (char * base, yy_size_t  size , yyscan_t yyscanner)
 {
-        YY_BUFFER_STATE b;
-
-        if ( size < 2 ||
-             base[size-2] != YY_END_OF_BUFFER_CHAR ||
-             base[size-1] != YY_END_OF_BUFFER_CHAR )
-                /* They forgot to leave room for the EOB's. */
-                return 0;
-
-        b = (YY_BUFFER_STATE) cmCommandArgument_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
-        if ( ! b )
-                YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yy_scan_buffer()" );
-
-        b->yy_buf_size = size - 2;      /* "- 2" to take care of EOB's */
-        b->yy_buf_pos = b->yy_ch_buf = base;
-        b->yy_is_our_buffer = 0;
-        b->yy_input_file = 0;
-        b->yy_n_chars = b->yy_buf_size;
-        b->yy_is_interactive = 0;
-        b->yy_at_bol = 1;
-        b->yy_fill_buffer = 0;
-        b->yy_buffer_status = YY_BUFFER_NEW;
-
-        cmCommandArgument_yy_switch_to_buffer(b ,yyscanner );
-
-        return b;
+	YY_BUFFER_STATE b;
+
+	if ( size < 2 ||
+	     base[size-2] != YY_END_OF_BUFFER_CHAR ||
+	     base[size-1] != YY_END_OF_BUFFER_CHAR )
+		/* They forgot to leave room for the EOB's. */
+		return NULL;
+
+	b = (YY_BUFFER_STATE) cmCommandArgument_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+	if ( ! b )
+		YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yy_scan_buffer()" );
+
+	b->yy_buf_size = size - 2;	/* "- 2" to take care of EOB's */
+	b->yy_buf_pos = b->yy_ch_buf = base;
+	b->yy_is_our_buffer = 0;
+	b->yy_input_file = NULL;
+	b->yy_n_chars = b->yy_buf_size;
+	b->yy_is_interactive = 0;
+	b->yy_at_bol = 1;
+	b->yy_fill_buffer = 0;
+	b->yy_buffer_status = YY_BUFFER_NEW;
+
+	cmCommandArgument_yy_switch_to_buffer(b ,yyscanner );
+
+	return b;
 }
 
 /** Setup the input buffer state to scan a string. The next call to cmCommandArgument_yylex() will
@@ -1650,11 +1655,11 @@ YY_BUFFER_STATE cmCommandArgument_yy_scan_buffer  (char * base, yy_size_t  size
 YY_BUFFER_STATE cmCommandArgument_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner)
 {
 
-        return cmCommandArgument_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner);
+	return cmCommandArgument_yy_scan_bytes(yystr,(int) strlen(yystr) ,yyscanner);
 }
 
 /** Setup the input buffer state to scan the given bytes. The next call to cmCommandArgument_yylex() will
- * scan from a @e copy of @a yybytes.
+ * scan from a @e copy of @a bytes.
  * @param yybytes the byte buffer to scan
  * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
  * @param yyscanner The scanner object.
@@ -1662,60 +1667,62 @@ YY_BUFFER_STATE cmCommandArgument_yy_scan_string (yyconst char * yystr , yyscan_
  */
 YY_BUFFER_STATE cmCommandArgument_yy_scan_bytes  (yyconst char * yybytes, int  _yybytes_len , yyscan_t yyscanner)
 {
-        YY_BUFFER_STATE b;
-        char *buf;
-        yy_size_t n;
-        int i;
+	YY_BUFFER_STATE b;
+	char *buf;
+	yy_size_t n;
+	yy_size_t i;
 
-        /* Get memory for full buffer, including space for trailing EOB's. */
-        n = _yybytes_len + 2;
-        buf = (char *) cmCommandArgument_yyalloc(n ,yyscanner );
-        if ( ! buf )
-                YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yy_scan_bytes()" );
+	/* Get memory for full buffer, including space for trailing EOB's. */
+	n = (yy_size_t) _yybytes_len + 2;
+	buf = (char *) cmCommandArgument_yyalloc(n ,yyscanner );
+	if ( ! buf )
+		YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yy_scan_bytes()" );
 
-        for ( i = 0; i < _yybytes_len; ++i )
-                buf[i] = yybytes[i];
+	for ( i = 0; i < (size_t)_yybytes_len; ++i )
+		buf[i] = yybytes[i];
 
-        buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
+	buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
 
-        b = cmCommandArgument_yy_scan_buffer(buf,n ,yyscanner);
-        if ( ! b )
-                YY_FATAL_ERROR( "bad buffer in cmCommandArgument_yy_scan_bytes()" );
+	b = cmCommandArgument_yy_scan_buffer(buf,n ,yyscanner);
+	if ( ! b )
+		YY_FATAL_ERROR( "bad buffer in cmCommandArgument_yy_scan_bytes()" );
 
-        /* It's okay to grow etc. this buffer, and we should throw it
-         * away when we're done.
-         */
-        b->yy_is_our_buffer = 1;
+	/* It's okay to grow etc. this buffer, and we should throw it
+	 * away when we're done.
+	 */
+	b->yy_is_our_buffer = 1;
 
-        return b;
+	return b;
 }
 
 #ifndef YY_EXIT_FAILURE
 #define YY_EXIT_FAILURE 2
 #endif
 
-static void yy_fatal_error (yyconst char* msg , yyscan_t)
+static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
 {
-        (void) fprintf( stderr, "%s\n", msg );
-        exit( YY_EXIT_FAILURE );
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+	(void) fprintf( stderr, "%s\n", msg );
+	exit( YY_EXIT_FAILURE );
 }
 
 /* Redefine yyless() so it works in section 3 code. */
 
 #undef yyless
 #define yyless(n) \
-        do \
-                { \
-                /* Undo effects of setting up yytext. */ \
+	do \
+		{ \
+		/* Undo effects of setting up yytext. */ \
         int yyless_macro_arg = (n); \
         YY_LESS_LINENO(yyless_macro_arg);\
-                yytext[yyleng] = yyg->yy_hold_char; \
-                yyg->yy_c_buf_p = yytext + yyless_macro_arg; \
-                yyg->yy_hold_char = *yyg->yy_c_buf_p; \
-                *yyg->yy_c_buf_p = '\0'; \
-                yyleng = yyless_macro_arg; \
-                } \
-        while ( 0 )
+		yytext[yyleng] = yyg->yy_hold_char; \
+		yyg->yy_c_buf_p = yytext + yyless_macro_arg; \
+		yyg->yy_hold_char = *yyg->yy_c_buf_p; \
+		*yyg->yy_c_buf_p = '\0'; \
+		yyleng = yyless_macro_arg; \
+		} \
+	while ( 0 )
 
 /* Accessor  methods (get/set functions) to struct members. */
 
@@ -1802,51 +1809,51 @@ void cmCommandArgument_yyset_extra (YY_EXTRA_TYPE  user_defined , yyscan_t yysca
 }
 
 /** Set the current line number.
- * @param line_number The line number to set.
+ * @param _line_number line number
  * @param yyscanner The scanner object.
  */
-void cmCommandArgument_yyset_lineno (int  line_number , yyscan_t yyscanner)
+void cmCommandArgument_yyset_lineno (int  _line_number , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
         /* lineno is only valid if an input buffer exists. */
         if (! YY_CURRENT_BUFFER )
-           yy_fatal_error( "cmCommandArgument_yyset_lineno called with no buffer" , yyscanner);
+           YY_FATAL_ERROR( "cmCommandArgument_yyset_lineno called with no buffer" );
 
-    yylineno = line_number;
+    yylineno = _line_number;
 }
 
 /** Set the current column.
- * @param column_no The column number to set.
+ * @param _column_no column number
  * @param yyscanner The scanner object.
  */
-void cmCommandArgument_yyset_column (int  column_no , yyscan_t yyscanner)
+void cmCommandArgument_yyset_column (int  _column_no , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
         /* column is only valid if an input buffer exists. */
         if (! YY_CURRENT_BUFFER )
-           yy_fatal_error( "cmCommandArgument_yyset_column called with no buffer" , yyscanner);
+           YY_FATAL_ERROR( "cmCommandArgument_yyset_column called with no buffer" );
 
-    yycolumn = column_no;
+    yycolumn = _column_no;
 }
 
 /** Set the input stream. This does not discard the current
  * input buffer.
- * @param in_str A readable stream.
+ * @param _in_str A readable stream.
  * @param yyscanner The scanner object.
  * @see cmCommandArgument_yy_switch_to_buffer
  */
-void cmCommandArgument_yyset_in (FILE *  in_str , yyscan_t yyscanner)
+void cmCommandArgument_yyset_in (FILE *  _in_str , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-    yyin = in_str ;
+    yyin = _in_str ;
 }
 
-void cmCommandArgument_yyset_out (FILE *  out_str , yyscan_t yyscanner)
+void cmCommandArgument_yyset_out (FILE *  _out_str , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-    yyout = out_str ;
+    yyout = _out_str ;
 }
 
 int cmCommandArgument_yyget_debug  (yyscan_t yyscanner)
@@ -1855,10 +1862,10 @@ int cmCommandArgument_yyget_debug  (yyscan_t yyscanner)
     return yy_flex_debug;
 }
 
-void cmCommandArgument_yyset_debug (int  bdebug , yyscan_t yyscanner)
+void cmCommandArgument_yyset_debug (int  _bdebug , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-    yy_flex_debug = bdebug ;
+    yy_flex_debug = _bdebug ;
 }
 
 /* Accessor methods for yylval and yylloc */
@@ -1934,10 +1941,10 @@ static int yy_init_globals (yyscan_t yyscanner)
      * This function is called from cmCommandArgument_yylex_destroy(), so don't allocate here.
      */
 
-    yyg->yy_buffer_stack = 0;
+    yyg->yy_buffer_stack = NULL;
     yyg->yy_buffer_stack_top = 0;
     yyg->yy_buffer_stack_max = 0;
-    yyg->yy_c_buf_p = (char *) 0;
+    yyg->yy_c_buf_p = NULL;
     yyg->yy_init = 0;
     yyg->yy_start = 0;
 
@@ -1950,8 +1957,8 @@ static int yy_init_globals (yyscan_t yyscanner)
     yyin = stdin;
     yyout = stdout;
 #else
-    yyin = (FILE *) 0;
-    yyout = (FILE *) 0;
+    yyin = NULL;
+    yyout = NULL;
 #endif
 
     /* For future reference: Set errno on error, since we are called by
@@ -1966,15 +1973,15 @@ int cmCommandArgument_yylex_destroy  (yyscan_t yyscanner)
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
     /* Pop the buffer stack, destroying each element. */
-        while(YY_CURRENT_BUFFER){
-                cmCommandArgument_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
-                YY_CURRENT_BUFFER_LVALUE = NULL;
-                cmCommandArgument_yypop_buffer_state(yyscanner);
-        }
+	while(YY_CURRENT_BUFFER){
+		cmCommandArgument_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
+		YY_CURRENT_BUFFER_LVALUE = NULL;
+		cmCommandArgument_yypop_buffer_state(yyscanner);
+	}
 
-        /* Destroy the stack itself. */
-        cmCommandArgument_yyfree(yyg->yy_buffer_stack ,yyscanner);
-        yyg->yy_buffer_stack = NULL;
+	/* Destroy the stack itself. */
+	cmCommandArgument_yyfree(yyg->yy_buffer_stack ,yyscanner);
+	yyg->yy_buffer_stack = NULL;
 
     /* Destroy the start condition stack. */
         cmCommandArgument_yyfree(yyg->yy_start_stack ,yyscanner );
@@ -1997,48 +2004,58 @@ int cmCommandArgument_yylex_destroy  (yyscan_t yyscanner)
 #ifndef yytext_ptr
 static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner)
 {
-        int i;
-        for ( i = 0; i < n; ++i )
-                s1[i] = s2[i];
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+
+	int i;
+	for ( i = 0; i < n; ++i )
+		s1[i] = s2[i];
 }
 #endif
 
 #ifdef YY_NEED_STRLEN
 static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
 {
-        int n;
-        for ( n = 0; s[n]; ++n )
-                ;
+	int n;
+	for ( n = 0; s[n]; ++n )
+		;
 
-        return n;
+	return n;
 }
 #endif
 
-void *cmCommandArgument_yyalloc (yy_size_t  size , yyscan_t)
+void *cmCommandArgument_yyalloc (yy_size_t  size , yyscan_t yyscanner)
 {
-        return (void *) malloc( size );
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+	return malloc(size);
 }
 
-void *cmCommandArgument_yyrealloc  (void * ptr, yy_size_t  size , yyscan_t)
+void *cmCommandArgument_yyrealloc  (void * ptr, yy_size_t  size , yyscan_t yyscanner)
 {
-        /* The cast to (char *) in the following accommodates both
-         * implementations that use char* generic pointers, and those
-         * that use void* generic pointers.  It works with the latter
-         * because both ANSI C and C++ allow castless assignment from
-         * any pointer type to void*, and deal with argument conversions
-         * as though doing an assignment.
-         */
-        return (void *) realloc( (char *) ptr, size );
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+
+	/* The cast to (char *) in the following accommodates both
+	 * implementations that use char* generic pointers, and those
+	 * that use void* generic pointers.  It works with the latter
+	 * because both ANSI C and C++ allow castless assignment from
+	 * any pointer type to void*, and deal with argument conversions
+	 * as though doing an assignment.
+	 */
+	return realloc(ptr, size);
 }
 
-void cmCommandArgument_yyfree (void * ptr , yyscan_t)
+void cmCommandArgument_yyfree (void * ptr , yyscan_t yyscanner)
 {
-        free( (char *) ptr );   /* see cmCommandArgument_yyrealloc() for (char *) cast */
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+	free( (char *) ptr );	/* see cmCommandArgument_yyrealloc() for (char *) cast */
 }
 
 #define YYTABLES_NAME "yytables"
 
-#line 149 "cmCommandArgumentLexer.in.l"
+#line 127 "cmCommandArgumentLexer.in.l"
 
 
 
@@ -2047,13 +2064,9 @@ void cmCommandArgument_SetupEscapes(yyscan_t yyscanner, bool noEscapes)
 {
   /* Hack into the internal flex-generated scanner to set the state.  */
   struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  if(noEscapes)
-    {
+  if(noEscapes) {
     BEGIN(NOESCAPES);
-    }
-  else
-    {
+  } else {
     BEGIN(ESCAPES);
-    }
+  }
 }
-
diff --git a/Source/cmCommandArgumentLexer.h b/Source/cmCommandArgumentLexer.h
index 7234fe1..82e87b5 100644
--- a/Source/cmCommandArgumentLexer.h
+++ b/Source/cmCommandArgumentLexer.h
@@ -1,17 +1,20 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmCommandArgument_yyHEADER_H
 #define cmCommandArgument_yyHEADER_H 1
 #define cmCommandArgument_yyIN_HEADER 1
 
+#line 6 "cmCommandArgumentLexer.h"
+
+#line 8 "cmCommandArgumentLexer.h"
+
+#define FLEXINT_H 1
 #define  YY_INT_ALIGNED short int
 
 /* A lexical scanner generated by flex */
 
 #define FLEX_SCANNER
 #define YY_FLEX_MAJOR_VERSION 2
-#define YY_FLEX_MINOR_VERSION 5
-#define YY_FLEX_SUBMINOR_VERSION 35
+#define YY_FLEX_MINOR_VERSION 6
+#define YY_FLEX_SUBMINOR_VERSION 1
 #if YY_FLEX_SUBMINOR_VERSION > 0
 #define FLEX_BETA
 #endif
@@ -90,25 +93,13 @@ typedef unsigned int flex_uint32_t;
 
 #endif /* ! FLEXINT_H */
 
-#ifdef __cplusplus
-
-/* The "const" storage-class-modifier is valid. */
-#define YY_USE_CONST
-
-#else   /* ! __cplusplus */
-
-/* C99 requires __STDC__ to be defined as 1. */
-#if defined (__STDC__)
-
-#define YY_USE_CONST
-
-#endif  /* defined (__STDC__) */
-#endif  /* ! __cplusplus */
-
-#ifdef YY_USE_CONST
+/* TODO: this is always defined, so inline it */
 #define yyconst const
+
+#if defined(__GNUC__) && __GNUC__ >= 3
+#define yynoreturn __attribute__((__noreturn__))
 #else
-#define yyconst
+#define yynoreturn
 #endif
 
 /* An opaque pointer. */
@@ -130,7 +121,15 @@ typedef void* yyscan_t;
 
 /* Size of default input buffer. */
 #ifndef YY_BUF_SIZE
+#ifdef __ia64__
+/* On IA-64, the buffer size is 16k, not 8k.
+ * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case.
+ * Ditto for the __ia64__ case accordingly.
+ */
+#define YY_BUF_SIZE 32768
+#else
 #define YY_BUF_SIZE 16384
+#endif /* __ia64__ */
 #endif
 
 #ifndef YY_TYPEDEF_YY_BUFFER_STATE
@@ -146,52 +145,52 @@ typedef size_t yy_size_t;
 #ifndef YY_STRUCT_YY_BUFFER_STATE
 #define YY_STRUCT_YY_BUFFER_STATE
 struct yy_buffer_state
-        {
-        FILE *yy_input_file;
-
-        char *yy_ch_buf;                /* input buffer */
-        char *yy_buf_pos;               /* current position in input buffer */
-
-        /* Size of input buffer in bytes, not including room for EOB
-         * characters.
-         */
-        yy_size_t yy_buf_size;
-
-        /* Number of characters read into yy_ch_buf, not including EOB
-         * characters.
-         */
-        int yy_n_chars;
-
-        /* Whether we "own" the buffer - i.e., we know we created it,
-         * and can realloc() it to grow it, and should free() it to
-         * delete it.
-         */
-        int yy_is_our_buffer;
-
-        /* Whether this is an "interactive" input source; if so, and
-         * if we're using stdio for input, then we want to use getc()
-         * instead of fread(), to make sure we stop fetching input after
-         * each newline.
-         */
-        int yy_is_interactive;
-
-        /* Whether we're considered to be at the beginning of a line.
-         * If so, '^' rules will be active on the next match, otherwise
-         * not.
-         */
-        int yy_at_bol;
+	{
+	FILE *yy_input_file;
+
+	char *yy_ch_buf;		/* input buffer */
+	char *yy_buf_pos;		/* current position in input buffer */
+
+	/* Size of input buffer in bytes, not including room for EOB
+	 * characters.
+	 */
+	int yy_buf_size;
+
+	/* Number of characters read into yy_ch_buf, not including EOB
+	 * characters.
+	 */
+	int yy_n_chars;
+
+	/* Whether we "own" the buffer - i.e., we know we created it,
+	 * and can realloc() it to grow it, and should free() it to
+	 * delete it.
+	 */
+	int yy_is_our_buffer;
+
+	/* Whether this is an "interactive" input source; if so, and
+	 * if we're using stdio for input, then we want to use getc()
+	 * instead of fread(), to make sure we stop fetching input after
+	 * each newline.
+	 */
+	int yy_is_interactive;
+
+	/* Whether we're considered to be at the beginning of a line.
+	 * If so, '^' rules will be active on the next match, otherwise
+	 * not.
+	 */
+	int yy_at_bol;
 
     int yy_bs_lineno; /**< The line count. */
     int yy_bs_column; /**< The column count. */
 
-        /* Whether to try to fill the input buffer when we reach the
-         * end of it.
-         */
-        int yy_fill_buffer;
+	/* Whether to try to fill the input buffer when we reach the
+	 * end of it.
+	 */
+	int yy_fill_buffer;
 
-        int yy_buffer_status;
+	int yy_buffer_status;
 
-        };
+	};
 #endif /* !YY_STRUCT_YY_BUFFER_STATE */
 
 void cmCommandArgument_yyrestart (FILE *input_file ,yyscan_t yyscanner );
@@ -212,7 +211,7 @@ void cmCommandArgument_yyfree (void * ,yyscan_t yyscanner );
 
 /* Begin user sect3 */
 
-#define cmCommandArgument_yywrap(n) 1
+#define cmCommandArgument_yywrap(yyscanner) (/*CONSTCOND*/1)
 #define YY_SKIP_YYWRAP
 
 #define yytext_ptr yytext_r
@@ -247,19 +246,23 @@ void cmCommandArgument_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscann
 
 FILE *cmCommandArgument_yyget_in (yyscan_t yyscanner );
 
-void cmCommandArgument_yyset_in  (FILE * in_str ,yyscan_t yyscanner );
+void cmCommandArgument_yyset_in  (FILE * _in_str ,yyscan_t yyscanner );
 
 FILE *cmCommandArgument_yyget_out (yyscan_t yyscanner );
 
-void cmCommandArgument_yyset_out  (FILE * out_str ,yyscan_t yyscanner );
+void cmCommandArgument_yyset_out  (FILE * _out_str ,yyscan_t yyscanner );
 
-int cmCommandArgument_yyget_leng (yyscan_t yyscanner );
+			int cmCommandArgument_yyget_leng (yyscan_t yyscanner );
 
 char *cmCommandArgument_yyget_text (yyscan_t yyscanner );
 
 int cmCommandArgument_yyget_lineno (yyscan_t yyscanner );
 
-void cmCommandArgument_yyset_lineno (int line_number ,yyscan_t yyscanner );
+void cmCommandArgument_yyset_lineno (int _line_number ,yyscan_t yyscanner );
+
+int cmCommandArgument_yyget_column  (yyscan_t yyscanner );
+
+void cmCommandArgument_yyset_column (int _column_no ,yyscan_t yyscanner );
 
 /* Macros after this point can all be overridden by user definitions in
  * section 1.
@@ -287,7 +290,12 @@ static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
 
 /* Amount of stuff to slurp up with each read. */
 #ifndef YY_READ_BUF_SIZE
+#ifdef __ia64__
+/* On IA-64, the buffer size is 16k, not 8k */
+#define YY_READ_BUF_SIZE 16384
+#else
 #define YY_READ_BUF_SIZE 8192
+#endif /* __ia64__ */
 #endif
 
 /* Number of entries by which start-condition stack grows. */
@@ -320,5 +328,9 @@ extern int cmCommandArgument_yylex (yyscan_t yyscanner);
 #undef YY_DECL
 #endif
 
+#line 127 "cmCommandArgumentLexer.in.l"
+
+
+#line 335 "cmCommandArgumentLexer.h"
 #undef cmCommandArgument_yyIN_HEADER
 #endif /* cmCommandArgument_yyHEADER_H */
diff --git a/Source/cmCommandArgumentLexer.in.l b/Source/cmCommandArgumentLexer.in.l
index eb9d08c..e3a8094 100644
--- a/Source/cmCommandArgumentLexer.in.l
+++ b/Source/cmCommandArgumentLexer.in.l
@@ -3,32 +3,21 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
-This file must be translated to C and modified to build everywhere.
+This file must be translated to C++ and modified to build everywhere.
 
-Run flex like this:
+Run flex >= 2.6 like this:
 
-  flex --prefix=cmCommandArgument_yy --header-file=cmCommandArgumentLexer.h -ocmCommandArgumentLexer.cxx cmCommandArgumentLexer.in.l
+  flex --nounistd -DFLEXINT_H --prefix=cmCommandArgument_yy --header-file=cmCommandArgumentLexer.h -ocmCommandArgumentLexer.cxx cmCommandArgumentLexer.in.l
 
 Modify cmCommandArgumentLexer.cxx:
-  - add #include "cmStandardIncludes.h" to top of file
-  - put header block at top of file
-  - remove TABs
-  - remove use of the 'register' storage class specifier
-  - remove "yyscanner" argument from these methods:
-      yy_fatal_error, cmCommandArgument_yyalloc, cmCommandArgument_yyrealloc, cmCommandArgument_yyfree
-  - remove all YY_BREAK lines occurring right after return statements
-  - change while ( 1 ) to for(;;)
-  - add "return 0;" to end of cmCommandArgument_yylex
-
-Modify cmCommandArgumentLexer.h:
-  - remove TABs
-  - remove the yy_init_globals function
-  - remove the block that includes unistd.h
-  - remove #line directives (avoids bogus warning on old Sun)
+  - remove trailing whitespace: sed -i 's/\s*$//' cmCommandArgumentLexer.h cmCommandArgumentLexer.cxx
+  - remove blank lines at end of file
+  - #include "cmStandardLexer.h" at the top
+  - add cast in yy_scan_bytes for loop condition of _yybytes_len to size_t
 
 */
 
-#include "cmStandardLexer.h"
+/* IWYU pragma: no_forward_declare yyguts_t */
 
 #include "cmCommandArgumentParserHelper.h"
 
@@ -142,12 +131,9 @@ void cmCommandArgument_SetupEscapes(yyscan_t yyscanner, bool noEscapes)
 {
   /* Hack into the internal flex-generated scanner to set the state.  */
   struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  if(noEscapes)
-    {
+  if(noEscapes) {
     BEGIN(NOESCAPES);
-    }
-  else
-    {
+  } else {
     BEGIN(ESCAPES);
-    }
+  }
 }
diff --git a/Source/cmCommandArgumentsHelper.h b/Source/cmCommandArgumentsHelper.h
index 50af2e2..b19b0f9 100644
--- a/Source/cmCommandArgumentsHelper.h
+++ b/Source/cmCommandArgumentsHelper.h
@@ -5,10 +5,12 @@
 
 #include <cmConfigure.h>
 
-#include "cmStandardIncludes.h"
+#include <set>
+#include <string>
+#include <vector>
 
-class cmCommandArgumentsHelper;
 class cmCommandArgumentGroup;
+class cmCommandArgumentsHelper;
 
 /* cmCommandArgumentsHelper, cmCommandArgumentGroup and cmCommandArgument (i.e.
 its derived classes cmCAXXX can be used to simplify the processing of
diff --git a/Source/cmCommands.cxx b/Source/cmCommands.cxx
new file mode 100644
index 0000000..4c5b093
--- /dev/null
+++ b/Source/cmCommands.cxx
@@ -0,0 +1,241 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmCommands.h"
+
+#include "cmAddCustomCommandCommand.h"
+#include "cmAddCustomTargetCommand.h"
+#include "cmAddDefinitionsCommand.h"
+#include "cmAddDependenciesCommand.h"
+#include "cmAddExecutableCommand.h"
+#include "cmAddLibraryCommand.h"
+#include "cmAddSubDirectoryCommand.h"
+#include "cmAddTestCommand.h"
+#include "cmBreakCommand.h"
+#include "cmBuildCommand.h"
+#include "cmCMakeMinimumRequired.h"
+#include "cmCMakePolicyCommand.h"
+#include "cmConfigureFileCommand.h"
+#include "cmContinueCommand.h"
+#include "cmCreateTestSourceList.h"
+#include "cmDefinePropertyCommand.h"
+#include "cmEnableLanguageCommand.h"
+#include "cmEnableTestingCommand.h"
+#include "cmExecProgramCommand.h"
+#include "cmExecuteProcessCommand.h"
+#include "cmFileCommand.h"
+#include "cmFindFileCommand.h"
+#include "cmFindLibraryCommand.h"
+#include "cmFindPackageCommand.h"
+#include "cmFindPathCommand.h"
+#include "cmFindProgramCommand.h"
+#include "cmForEachCommand.h"
+#include "cmFunctionCommand.h"
+#include "cmGetCMakePropertyCommand.h"
+#include "cmGetDirectoryPropertyCommand.h"
+#include "cmGetFilenameComponentCommand.h"
+#include "cmGetPropertyCommand.h"
+#include "cmGetSourceFilePropertyCommand.h"
+#include "cmGetTargetPropertyCommand.h"
+#include "cmGetTestPropertyCommand.h"
+#include "cmIfCommand.h"
+#include "cmIncludeCommand.h"
+#include "cmIncludeDirectoryCommand.h"
+#include "cmIncludeRegularExpressionCommand.h"
+#include "cmInstallCommand.h"
+#include "cmInstallFilesCommand.h"
+#include "cmInstallTargetsCommand.h"
+#include "cmLinkDirectoriesCommand.h"
+#include "cmListCommand.h"
+#include "cmMacroCommand.h"
+#include "cmMakeDirectoryCommand.h"
+#include "cmMarkAsAdvancedCommand.h"
+#include "cmMathCommand.h"
+#include "cmMessageCommand.h"
+#include "cmOptionCommand.h"
+#include "cmParseArgumentsCommand.h"
+#include "cmProjectCommand.h"
+#include "cmReturnCommand.h"
+#include "cmSeparateArgumentsCommand.h"
+#include "cmSetCommand.h"
+#include "cmSetDirectoryPropertiesCommand.h"
+#include "cmSetPropertyCommand.h"
+#include "cmSetSourceFilesPropertiesCommand.h"
+#include "cmSetTargetPropertiesCommand.h"
+#include "cmSetTestsPropertiesCommand.h"
+#include "cmSiteNameCommand.h"
+#include "cmStringCommand.h"
+#include "cmSubdirCommand.h"
+#include "cmTargetLinkLibrariesCommand.h"
+#include "cmTryCompileCommand.h"
+#include "cmTryRunCommand.h"
+#include "cmUnexpectedCommand.h"
+#include "cmUnsetCommand.h"
+#include "cmWhileCommand.h"
+
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include "cmAddCompileOptionsCommand.h"
+#include "cmAuxSourceDirectoryCommand.h"
+#include "cmBuildNameCommand.h"
+#include "cmCMakeHostSystemInformationCommand.h"
+#include "cmExportCommand.h"
+#include "cmExportLibraryDependenciesCommand.h"
+#include "cmFLTKWrapUICommand.h"
+#include "cmIncludeExternalMSProjectCommand.h"
+#include "cmInstallProgramsCommand.h"
+#include "cmLinkLibrariesCommand.h"
+#include "cmLoadCacheCommand.h"
+#include "cmLoadCommandCommand.h"
+#include "cmOutputRequiredFilesCommand.h"
+#include "cmQTWrapCPPCommand.h"
+#include "cmQTWrapUICommand.h"
+#include "cmRemoveCommand.h"
+#include "cmRemoveDefinitionsCommand.h"
+#include "cmSourceGroupCommand.h"
+#include "cmSubdirDependsCommand.h"
+#include "cmTargetCompileDefinitionsCommand.h"
+#include "cmTargetCompileFeaturesCommand.h"
+#include "cmTargetCompileOptionsCommand.h"
+#include "cmTargetIncludeDirectoriesCommand.h"
+#include "cmTargetSourcesCommand.h"
+#include "cmUseMangledMesaCommand.h"
+#include "cmUtilitySourceCommand.h"
+#include "cmVariableRequiresCommand.h"
+#include "cmVariableWatchCommand.h"
+#include "cmWriteFileCommand.h"
+#endif
+
+std::vector<cmCommand*> GetPredefinedCommands()
+{
+  std::vector<cmCommand*> commands;
+
+  commands.push_back(new cmAddCustomCommandCommand);
+  commands.push_back(new cmAddCustomTargetCommand);
+  commands.push_back(new cmAddDefinitionsCommand);
+  commands.push_back(new cmAddDependenciesCommand);
+  commands.push_back(new cmAddExecutableCommand);
+  commands.push_back(new cmAddLibraryCommand);
+  commands.push_back(new cmAddSubDirectoryCommand);
+  commands.push_back(new cmAddTestCommand);
+  commands.push_back(new cmBreakCommand);
+  commands.push_back(new cmBuildCommand);
+  commands.push_back(new cmCMakeMinimumRequired);
+  commands.push_back(new cmCMakePolicyCommand);
+  commands.push_back(new cmConfigureFileCommand);
+  commands.push_back(new cmContinueCommand);
+  commands.push_back(new cmCreateTestSourceList);
+  commands.push_back(new cmDefinePropertyCommand);
+  commands.push_back(new cmEnableLanguageCommand);
+  commands.push_back(new cmEnableTestingCommand);
+  commands.push_back(new cmExecProgramCommand);
+  commands.push_back(new cmExecuteProcessCommand);
+  commands.push_back(new cmFileCommand);
+  commands.push_back(new cmFindFileCommand);
+  commands.push_back(new cmFindLibraryCommand);
+  commands.push_back(new cmFindPackageCommand);
+  commands.push_back(new cmFindPathCommand);
+  commands.push_back(new cmFindProgramCommand);
+  commands.push_back(new cmForEachCommand);
+  commands.push_back(new cmFunctionCommand);
+  commands.push_back(new cmGetCMakePropertyCommand);
+  commands.push_back(new cmGetDirectoryPropertyCommand);
+  commands.push_back(new cmGetFilenameComponentCommand);
+  commands.push_back(new cmGetPropertyCommand);
+  commands.push_back(new cmGetSourceFilePropertyCommand);
+  commands.push_back(new cmGetTargetPropertyCommand);
+  commands.push_back(new cmGetTestPropertyCommand);
+  commands.push_back(new cmIfCommand);
+  commands.push_back(new cmIncludeCommand);
+  commands.push_back(new cmIncludeDirectoryCommand);
+  commands.push_back(new cmIncludeRegularExpressionCommand);
+  commands.push_back(new cmInstallCommand);
+  commands.push_back(new cmInstallFilesCommand);
+  commands.push_back(new cmInstallTargetsCommand);
+  commands.push_back(new cmLinkDirectoriesCommand);
+  commands.push_back(new cmListCommand);
+  commands.push_back(new cmMacroCommand);
+  commands.push_back(new cmMakeDirectoryCommand);
+  commands.push_back(new cmMarkAsAdvancedCommand);
+  commands.push_back(new cmMathCommand);
+  commands.push_back(new cmMessageCommand);
+  commands.push_back(new cmOptionCommand);
+  commands.push_back(new cmParseArgumentsCommand);
+  commands.push_back(new cmProjectCommand);
+  commands.push_back(new cmReturnCommand);
+  commands.push_back(new cmSeparateArgumentsCommand);
+  commands.push_back(new cmSetCommand);
+  commands.push_back(new cmSetDirectoryPropertiesCommand);
+  commands.push_back(new cmSetPropertyCommand);
+  commands.push_back(new cmSetSourceFilesPropertiesCommand);
+  commands.push_back(new cmSetTargetPropertiesCommand);
+  commands.push_back(new cmSetTestsPropertiesCommand);
+  commands.push_back(new cmSiteNameCommand);
+  commands.push_back(new cmStringCommand);
+  commands.push_back(new cmSubdirCommand);
+  commands.push_back(new cmTargetLinkLibrariesCommand);
+  commands.push_back(new cmTryCompileCommand);
+  commands.push_back(new cmTryRunCommand);
+  commands.push_back(new cmUnsetCommand);
+  commands.push_back(new cmWhileCommand);
+
+  commands.push_back(new cmUnexpectedCommand(
+    "else", "An ELSE command was found outside of a proper "
+            "IF ENDIF structure. Or its arguments did not match "
+            "the opening IF command."));
+  commands.push_back(new cmUnexpectedCommand(
+    "elseif", "An ELSEIF command was found outside of a proper "
+              "IF ENDIF structure."));
+  commands.push_back(new cmUnexpectedCommand(
+    "endforeach", "An ENDFOREACH command was found outside of a proper "
+                  "FOREACH ENDFOREACH structure. Or its arguments did "
+                  "not match the opening FOREACH command."));
+  commands.push_back(new cmUnexpectedCommand(
+    "endfunction", "An ENDFUNCTION command was found outside of a proper "
+                   "FUNCTION ENDFUNCTION structure. Or its arguments did not "
+                   "match the opening FUNCTION command."));
+  commands.push_back(new cmUnexpectedCommand(
+    "endif", "An ENDIF command was found outside of a proper "
+             "IF ENDIF structure. Or its arguments did not match "
+             "the opening IF command."));
+  commands.push_back(new cmUnexpectedCommand(
+    "endmacro", "An ENDMACRO command was found outside of a proper "
+                "MACRO ENDMACRO structure. Or its arguments did not "
+                "match the opening MACRO command."));
+  commands.push_back(new cmUnexpectedCommand(
+    "endwhile", "An ENDWHILE command was found outside of a proper "
+                "WHILE ENDWHILE structure. Or its arguments did not "
+                "match the opening WHILE command."));
+
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+  commands.push_back(new cmAddCompileOptionsCommand);
+  commands.push_back(new cmAuxSourceDirectoryCommand);
+  commands.push_back(new cmBuildNameCommand);
+  commands.push_back(new cmCMakeHostSystemInformationCommand);
+  commands.push_back(new cmExportCommand);
+  commands.push_back(new cmExportLibraryDependenciesCommand);
+  commands.push_back(new cmFLTKWrapUICommand);
+  commands.push_back(new cmIncludeExternalMSProjectCommand);
+  commands.push_back(new cmInstallProgramsCommand);
+  commands.push_back(new cmLinkLibrariesCommand);
+  commands.push_back(new cmLoadCacheCommand);
+  commands.push_back(new cmLoadCommandCommand);
+  commands.push_back(new cmOutputRequiredFilesCommand);
+  commands.push_back(new cmQTWrapCPPCommand);
+  commands.push_back(new cmQTWrapUICommand);
+  commands.push_back(new cmRemoveCommand);
+  commands.push_back(new cmRemoveDefinitionsCommand);
+  commands.push_back(new cmSourceGroupCommand);
+  commands.push_back(new cmSubdirDependsCommand);
+  commands.push_back(new cmTargetCompileDefinitionsCommand);
+  commands.push_back(new cmTargetCompileFeaturesCommand);
+  commands.push_back(new cmTargetCompileOptionsCommand);
+  commands.push_back(new cmTargetIncludeDirectoriesCommand);
+  commands.push_back(new cmTargetSourcesCommand);
+  commands.push_back(new cmUseMangledMesaCommand);
+  commands.push_back(new cmUtilitySourceCommand);
+  commands.push_back(new cmVariableRequiresCommand);
+  commands.push_back(new cmVariableWatchCommand);
+  commands.push_back(new cmWriteFileCommand);
+#endif
+
+  return commands;
+}
diff --git a/Source/cmCommands.cxx.in b/Source/cmCommands.cxx.in
deleted file mode 100644
index 9eddf30..0000000
--- a/Source/cmCommands.cxx.in
+++ /dev/null
@@ -1,10 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmCommands.h"
-
- at COMMAND_INCLUDES@
-
-void GetPredefinedCommands(std::vector<cmCommand*>& commands)
-{
- at NEW_COMMANDS@
-}
diff --git a/Source/cmCommands.h b/Source/cmCommands.h
index c2a59b8..649dea6 100644
--- a/Source/cmCommands.h
+++ b/Source/cmCommands.h
@@ -10,13 +10,9 @@
 class cmCommand;
 /**
  * Global function to return all compiled in commands.
- * To add a new command edit cmCommands.cxx or cmBootstrapCommands[12].cxx
- * and add your command.
- * It is up to the caller to delete the commands created by this
- * call.
+ * To add a new command edit cmCommands.cxx and add your command.
+ * It is up to the caller to delete the commands created by this call.
  */
-void GetBootstrapCommands1(std::vector<cmCommand*>& commands);
-void GetBootstrapCommands2(std::vector<cmCommand*>& commands);
-void GetPredefinedCommands(std::vector<cmCommand*>& commands);
+std::vector<cmCommand*> GetPredefinedCommands();
 
 #endif
diff --git a/Source/cmCommandsForBootstrap.cxx b/Source/cmCommandsForBootstrap.cxx
deleted file mode 100644
index 1b3bf51..0000000
--- a/Source/cmCommandsForBootstrap.cxx
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmCommands.h"
-
-void GetPredefinedCommands(std::vector<cmCommand*>&)
-{
-}
diff --git a/Source/cmCommonTargetGenerator.cxx b/Source/cmCommonTargetGenerator.cxx
index 6887a31..239582f 100644
--- a/Source/cmCommonTargetGenerator.cxx
+++ b/Source/cmCommonTargetGenerator.cxx
@@ -2,7 +2,6 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCommonTargetGenerator.h"
 
-#include <algorithm>
 #include <cmConfigure.h>
 #include <set>
 #include <sstream>
@@ -12,11 +11,13 @@
 #include "cmComputeLinkInformation.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalCommonGenerator.h"
+#include "cmLinkLineComputer.h"
 #include "cmLocalCommonGenerator.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
+#include "cmOutputConverter.h"
 #include "cmSourceFile.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 
 cmCommonTargetGenerator::cmCommonTargetGenerator(cmGeneratorTarget* gt)
   : GeneratorTarget(gt)
@@ -59,8 +60,16 @@ void cmCommonTargetGenerator::AddFeatureFlags(std::string& flags,
   }
 }
 
-void cmCommonTargetGenerator::AddModuleDefinitionFlag(std::string& flags)
+void cmCommonTargetGenerator::AddModuleDefinitionFlag(
+  cmLinkLineComputer* linkLineComputer, std::string& flags)
 {
+  // A module definition file only makes sense on certain target types.
+  if (this->GeneratorTarget->GetType() != cmStateEnums::SHARED_LIBRARY &&
+      this->GeneratorTarget->GetType() != cmStateEnums::MODULE_LIBRARY &&
+      this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE) {
+    return;
+  }
+
   if (!this->ModuleDefinitionFile) {
     return;
   }
@@ -75,8 +84,10 @@ void cmCommonTargetGenerator::AddModuleDefinitionFlag(std::string& flags)
   // Append the flag and value.  Use ConvertToLinkReference to help
   // vs6's "cl -link" pass it to the linker.
   std::string flag = defFileFlag;
-  flag += (this->LocalGenerator->ConvertToLinkReference(
-    this->ModuleDefinitionFile->GetFullPath()));
+  flag += this->LocalGenerator->ConvertToOutputFormat(
+    linkLineComputer->ConvertToLinkReference(
+      this->ModuleDefinitionFile->GetFullPath()),
+    cmOutputConverter::SHELL);
   this->LocalGenerator->AppendFlags(flags, flag);
 }
 
@@ -167,7 +178,7 @@ std::vector<std::string> cmCommonTargetGenerator::GetLinkedTargetDirectories()
           // We can ignore the INTERFACE_LIBRARY items because
           // Target->GetLinkInformation already processed their
           // link interface and they don't have any output themselves.
-          && linkee->GetType() != cmState::INTERFACE_LIBRARY &&
+          && linkee->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
           emitted.insert(linkee).second) {
         cmLocalGenerator* lg = linkee->GetLocalGenerator();
         std::string di = lg->GetCurrentBinaryDirectory();
@@ -180,6 +191,28 @@ std::vector<std::string> cmCommonTargetGenerator::GetLinkedTargetDirectories()
   return dirs;
 }
 
+std::string cmCommonTargetGenerator::ComputeTargetCompilePDB() const
+{
+  std::string compilePdbPath;
+  if (this->GeneratorTarget->GetType() > cmStateEnums::OBJECT_LIBRARY) {
+    return compilePdbPath;
+  }
+  compilePdbPath =
+    this->GeneratorTarget->GetCompilePDBPath(this->GetConfigName());
+  if (compilePdbPath.empty()) {
+    // Match VS default: `$(IntDir)vc$(PlatformToolsetVersion).pdb`.
+    // A trailing slash tells the toolchain to add its default file name.
+    compilePdbPath = this->GeneratorTarget->GetSupportDirectory() + "/";
+    if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
+      // Match VS default for static libs: `$(IntDir)$(ProjectName).pdb`.
+      compilePdbPath += this->GeneratorTarget->GetName();
+      compilePdbPath += ".pdb";
+    }
+  }
+
+  return compilePdbPath;
+}
+
 std::string cmCommonTargetGenerator::GetManifests()
 {
   std::vector<cmSourceFile const*> manifest_srcs;
diff --git a/Source/cmCommonTargetGenerator.h b/Source/cmCommonTargetGenerator.h
index 707b81e..d67fefb 100644
--- a/Source/cmCommonTargetGenerator.h
+++ b/Source/cmCommonTargetGenerator.h
@@ -4,15 +4,13 @@
 #define cmCommonTargetGenerator_h
 
 #include <cmConfigure.h> // IWYU pragma: keep
-
-#include "cmOutputConverter.h"
-
 #include <map>
 #include <string>
 #include <vector>
 
 class cmGeneratorTarget;
 class cmGlobalCommonGenerator;
+class cmLinkLineComputer;
 class cmLocalCommonGenerator;
 class cmMakefile;
 class cmSourceFile;
@@ -37,7 +35,8 @@ protected:
   bool GetFeatureAsBool(const std::string& feature);
 
   // Helper to add flag for windows .def file.
-  void AddModuleDefinitionFlag(std::string& flags);
+  void AddModuleDefinitionFlag(cmLinkLineComputer* linkLineComputer,
+                               std::string& flags);
 
   cmGeneratorTarget* GeneratorTarget;
   cmMakefile* Makefile;
@@ -67,6 +66,7 @@ protected:
   std::string GetManifests();
 
   std::vector<std::string> GetLinkedTargetDirectories() const;
+  std::string ComputeTargetCompilePDB() const;
 };
 
 #endif
diff --git a/Source/cmComputeLinkDepends.cxx b/Source/cmComputeLinkDepends.cxx
index 93f3289..3e2cf18 100644
--- a/Source/cmComputeLinkDepends.cxx
+++ b/Source/cmComputeLinkDepends.cxx
@@ -8,7 +8,7 @@
 #include "cmGlobalGenerator.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cmake.h"
@@ -262,7 +262,7 @@ cmComputeLinkDepends::Compute()
     LinkEntry const& e = this->EntryList[i];
     cmGeneratorTarget const* t = e.Target;
     // Entries that we know the linker will re-use do not need to be repeated.
-    bool uniquify = t && t->GetType() == cmState::SHARED_LIBRARY;
+    bool uniquify = t && t->GetType() == cmStateEnums::SHARED_LIBRARY;
     if (!uniquify || emmitted.insert(i).second) {
       this->FinalLinkEntries.push_back(e);
     }
@@ -345,7 +345,7 @@ void cmComputeLinkDepends::FollowLinkEntry(BFSEntry const& qe)
     if (cmLinkInterface const* iface =
           entry.Target->GetLinkInterface(this->Config, this->Target)) {
       const bool isIface =
-        entry.Target->GetType() == cmState::INTERFACE_LIBRARY;
+        entry.Target->GetType() == cmStateEnums::INTERFACE_LIBRARY;
       // This target provides its own link interface information.
       this->AddLinkEntries(depender_index, iface->Libraries);
 
diff --git a/Source/cmComputeLinkInformation.cxx b/Source/cmComputeLinkInformation.cxx
index dc8236d..80e7e7d 100644
--- a/Source/cmComputeLinkInformation.cxx
+++ b/Source/cmComputeLinkInformation.cxx
@@ -12,6 +12,7 @@
 #include "cmOutputConverter.h"
 #include "cmPolicies.h"
 #include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cmake.h"
@@ -282,7 +283,7 @@ cmComputeLinkInformation::cmComputeLinkInformation(
   // the program that will load it.
   this->LoaderFlag = CM_NULLPTR;
   if (!this->UseImportLibrary &&
-      this->Target->GetType() == cmState::MODULE_LIBRARY) {
+      this->Target->GetType() == cmStateEnums::MODULE_LIBRARY) {
     std::string loader_flag_var = "CMAKE_SHARED_MODULE_LOADER_";
     loader_flag_var += this->LinkLanguage;
     loader_flag_var += "_FLAG";
@@ -299,10 +300,10 @@ cmComputeLinkInformation::cmComputeLinkInformation(
 
   // Get options needed to specify RPATHs.
   this->RuntimeUseChrpath = false;
-  if (this->Target->GetType() != cmState::STATIC_LIBRARY) {
-    const char* tType =
-      ((this->Target->GetType() == cmState::EXECUTABLE) ? "EXECUTABLE"
-                                                        : "SHARED_LIBRARY");
+  if (this->Target->GetType() != cmStateEnums::STATIC_LIBRARY) {
+    const char* tType = ((this->Target->GetType() == cmStateEnums::EXECUTABLE)
+                           ? "EXECUTABLE"
+                           : "SHARED_LIBRARY");
     std::string rtVar = "CMAKE_";
     rtVar += tType;
     rtVar += "_RUNTIME_";
@@ -446,10 +447,10 @@ cmComputeLinkInformation::GetSharedLibrariesLinked()
 bool cmComputeLinkInformation::Compute()
 {
   // Skip targets that do not link.
-  if (!(this->Target->GetType() == cmState::EXECUTABLE ||
-        this->Target->GetType() == cmState::SHARED_LIBRARY ||
-        this->Target->GetType() == cmState::MODULE_LIBRARY ||
-        this->Target->GetType() == cmState::STATIC_LIBRARY)) {
+  if (!(this->Target->GetType() == cmStateEnums::EXECUTABLE ||
+        this->Target->GetType() == cmStateEnums::SHARED_LIBRARY ||
+        this->Target->GetType() == cmStateEnums::MODULE_LIBRARY ||
+        this->Target->GetType() == cmStateEnums::STATIC_LIBRARY)) {
     return false;
   }
 
@@ -498,7 +499,7 @@ bool cmComputeLinkInformation::Compute()
          i != wrongItems.end(); ++i) {
       cmGeneratorTarget const* tgt = *i;
       bool implib = (this->UseImportLibrary &&
-                     (tgt->GetType() == cmState::SHARED_LIBRARY));
+                     (tgt->GetType() == cmStateEnums::SHARED_LIBRARY));
       std::string lib = tgt->GetFullPath(this->Config, implib, true);
       this->OldLinkDirItems.push_back(lib);
     }
@@ -600,20 +601,27 @@ void cmComputeLinkInformation::AddItem(std::string const& item,
       linkItem += exe;
       this->Items.push_back(Item(linkItem, true, tgt));
       this->Depends.push_back(exe);
-    } else if (tgt->GetType() == cmState::INTERFACE_LIBRARY) {
+    } else if (tgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       // Add the interface library as an item so it can be considered as part
       // of COMPATIBLE_INTERFACE_ enforcement.  The generators will ignore
       // this for the actual link line.
       this->Items.push_back(Item(std::string(), false, tgt));
+
+      // Also add the item the interface specifies to be used in its place.
+      std::string const& libName = tgt->GetImportedLibName(config);
+      if (!libName.empty()) {
+        this->AddItem(libName, CM_NULLPTR);
+      }
     } else {
       // Decide whether to use an import library.
-      bool implib = (this->UseImportLibrary &&
-                     (impexe || tgt->GetType() == cmState::SHARED_LIBRARY));
+      bool implib =
+        (this->UseImportLibrary &&
+         (impexe || tgt->GetType() == cmStateEnums::SHARED_LIBRARY));
 
       // Pass the full path to the target file.
       std::string lib = tgt->GetFullPath(config, implib, true);
       if (!this->LinkDependsNoShared ||
-          tgt->GetType() != cmState::SHARED_LIBRARY) {
+          tgt->GetType() != cmStateEnums::SHARED_LIBRARY) {
         this->Depends.push_back(lib);
       }
 
@@ -652,7 +660,7 @@ void cmComputeLinkInformation::AddSharedDepItem(std::string const& item,
   if (tgt) {
     // The target will provide a full path.  Make sure it is a shared
     // library.
-    if (tgt->GetType() != cmState::SHARED_LIBRARY) {
+    if (tgt->GetType() != cmStateEnums::SHARED_LIBRARY) {
       return;
     }
   } else {
@@ -725,13 +733,13 @@ void cmComputeLinkInformation::ComputeLinkTypeInfo()
   const char* shared_link_type_flag = CM_NULLPTR;
   const char* target_type_str = CM_NULLPTR;
   switch (this->Target->GetType()) {
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       target_type_str = "EXE";
       break;
-    case cmState::SHARED_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
       target_type_str = "SHARED_LIBRARY";
       break;
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       target_type_str = "SHARED_MODULE";
       break;
     default:
@@ -964,12 +972,12 @@ void cmComputeLinkInformation::AddTargetItem(std::string const& item,
   // shared and static libraries but static-mode can handle only
   // static libraries.  If a previous user item changed the link type
   // to static we need to make sure it is back to shared.
-  if (target->GetType() != cmState::STATIC_LIBRARY) {
+  if (target->GetType() != cmStateEnums::STATIC_LIBRARY) {
     this->SetCurrentLinkType(LinkShared);
   }
 
   // Keep track of shared library targets linked.
-  if (target->GetType() == cmState::SHARED_LIBRARY) {
+  if (target->GetType() == cmStateEnums::SHARED_LIBRARY) {
     this->SharedLibrariesLinked.insert(target);
   }
 
@@ -1590,13 +1598,13 @@ void cmComputeLinkInformation::AddLibraryRuntimeInfo(
 
   // Libraries with unknown type must be handled using just the file
   // on disk.
-  if (target->GetType() == cmState::UNKNOWN_LIBRARY) {
+  if (target->GetType() == cmStateEnums::UNKNOWN_LIBRARY) {
     this->AddLibraryRuntimeInfo(fullPath);
     return;
   }
 
   // Skip targets that are not shared libraries (modules cannot be linked).
-  if (target->GetType() != cmState::SHARED_LIBRARY) {
+  if (target->GetType() != cmStateEnums::SHARED_LIBRARY) {
     return;
   }
 
@@ -1710,6 +1718,12 @@ void cmComputeLinkInformation::GetRPath(std::vector<std::string>& runtimeDirs,
     const char* install_rpath = this->Target->GetProperty("INSTALL_RPATH");
     cmCLI_ExpandListUnique(install_rpath, runtimeDirs, emitted);
   }
+  if (use_build_rpath) {
+    // Add directories explicitly specified by user
+    if (const char* build_rpath = this->Target->GetProperty("BUILD_RPATH")) {
+      cmCLI_ExpandListUnique(build_rpath, runtimeDirs, emitted);
+    }
+  }
   if (use_build_rpath || use_link_rpath) {
     std::string rootPath = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
     const char* stagePath =
diff --git a/Source/cmComputeLinkInformation.h b/Source/cmComputeLinkInformation.h
index 1d29c26..3d26ea7 100644
--- a/Source/cmComputeLinkInformation.h
+++ b/Source/cmComputeLinkInformation.h
@@ -70,6 +70,7 @@ public:
   std::string const& GetRPathLinkFlag() const { return this->RPathLinkFlag; }
   std::string GetRPathLinkString();
 
+  std::string GetConfig() const { return this->Config; }
 private:
   void AddItem(std::string const& item, const cmGeneratorTarget* tgt);
   void AddSharedDepItem(std::string const& item, cmGeneratorTarget const* tgt);
diff --git a/Source/cmComputeTargetDepends.cxx b/Source/cmComputeTargetDepends.cxx
index 735bc32..cfebda2 100644
--- a/Source/cmComputeTargetDepends.cxx
+++ b/Source/cmComputeTargetDepends.cxx
@@ -11,6 +11,7 @@
 #include "cmPolicies.h"
 #include "cmSourceFile.h"
 #include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cmTargetDepend.h"
@@ -187,7 +188,7 @@ void cmComputeTargetDepends::CollectTargetDepends(int depender_index)
 {
   // Get the depender.
   cmGeneratorTarget const* depender = this->Targets[depender_index];
-  if (depender->GetType() == cmState::INTERFACE_LIBRARY) {
+  if (depender->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
     return;
   }
 
@@ -212,10 +213,10 @@ void cmComputeTargetDepends::CollectTargetDepends(int depender_index)
            oi != objectFiles.end(); ++oi) {
         std::string objLib = (*oi)->GetObjectLibrary();
         if (!objLib.empty() && emitted.insert(objLib).second) {
-          if (depender->GetType() != cmState::EXECUTABLE &&
-              depender->GetType() != cmState::STATIC_LIBRARY &&
-              depender->GetType() != cmState::SHARED_LIBRARY &&
-              depender->GetType() != cmState::MODULE_LIBRARY) {
+          if (depender->GetType() != cmStateEnums::EXECUTABLE &&
+              depender->GetType() != cmStateEnums::STATIC_LIBRARY &&
+              depender->GetType() != cmStateEnums::SHARED_LIBRARY &&
+              depender->GetType() != cmStateEnums::MODULE_LIBRARY) {
             this->GlobalGenerator->GetCMakeInstance()->IssueMessage(
               cmake::FATAL_ERROR,
               "Only executables and non-OBJECT libraries may "
@@ -287,7 +288,7 @@ void cmComputeTargetDepends::AddInterfaceDepends(
   // 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 (dependee && dependee->GetType() == cmState::EXECUTABLE &&
+  if (dependee && dependee->GetType() == cmStateEnums::EXECUTABLE &&
       !dependee->IsExecutableWithExports()) {
     dependee = CM_NULLPTR;
   }
@@ -316,7 +317,7 @@ void cmComputeTargetDepends::AddTargetDepend(int depender_index,
   cmGeneratorTarget const* dependee = dependee_name.Target;
 
   if (!dependee && !linking &&
-      (depender->GetType() != cmState::GLOBAL_TARGET)) {
+      (depender->GetType() != cmStateEnums::GLOBAL_TARGET)) {
     cmake::MessageType messageType = cmake::AUTHOR_WARNING;
     bool issueMessage = false;
     std::ostringstream e;
@@ -351,7 +352,7 @@ void cmComputeTargetDepends::AddTargetDepend(int depender_index,
   // 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 && dependee->GetType() == cmState::EXECUTABLE &&
+  if (linking && dependee && dependee->GetType() == cmStateEnums::EXECUTABLE &&
       !dependee->IsExecutableWithExports()) {
     dependee = CM_NULLPTR;
   }
@@ -366,7 +367,7 @@ void cmComputeTargetDepends::AddTargetDepend(int depender_index,
                                              bool linking)
 {
   if (dependee->IsImported() ||
-      dependee->GetType() == cmState::INTERFACE_LIBRARY) {
+      dependee->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
     // Skip IMPORTED and INTERFACE targets but follow their utility
     // dependencies.
     std::set<cmLinkItem> const& utils = dependee->GetUtilityItems();
@@ -452,7 +453,7 @@ bool cmComputeTargetDepends::CheckComponents(
 
     // Make sure the component is all STATIC_LIBRARY targets.
     for (NodeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) {
-      if (this->Targets[*ni]->GetType() != cmState::STATIC_LIBRARY) {
+      if (this->Targets[*ni]->GetType() != cmStateEnums::STATIC_LIBRARY) {
         this->ComplainAboutBadComponent(ccg, c);
         return false;
       }
diff --git a/Source/cmConditionEvaluator.cxx b/Source/cmConditionEvaluator.cxx
index 420a777..f2eb601 100644
--- a/Source/cmConditionEvaluator.cxx
+++ b/Source/cmConditionEvaluator.cxx
@@ -2,10 +2,22 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmConditionEvaluator.h"
 
+#include <algorithm>
+#include <cmConfigure.h>
+#include <cmsys/RegularExpression.hxx>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
 #include "cmAlgorithms.h"
-#include "cmOutputConverter.h"
+#include "cmMakefile.h"
+#include "cmState.h"
 #include "cmSystemTools.h"
 
+class cmCommand;
+class cmTest;
+
 static std::string const keyAND = "AND";
 static std::string const keyCOMMAND = "COMMAND";
 static std::string const keyDEFINED = "DEFINED";
@@ -221,7 +233,7 @@ bool cmConditionEvaluator::GetBooleanValue(
     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;
+      return static_cast<bool>(d);
     }
   }
 
@@ -443,7 +455,7 @@ bool cmConditionEvaluator::HandleLevel1(cmArgumentList& newArgs, std::string&,
       if (this->IsKeyword(keyCOMMAND, *arg) && argP1 != newArgs.end()) {
         cmCommand* command =
           this->Makefile.GetState()->GetCommand(argP1->c_str());
-        this->HandlePredicate(command ? true : false, reducible, arg, newArgs,
+        this->HandlePredicate(command != CM_NULLPTR, reducible, arg, newArgs,
                               argP1, argP2);
       }
       // does a policy exist
@@ -455,7 +467,7 @@ bool cmConditionEvaluator::HandleLevel1(cmArgumentList& newArgs, std::string&,
       // does a target exist
       if (this->IsKeyword(keyTARGET, *arg) && argP1 != newArgs.end()) {
         this->HandlePredicate(
-          this->Makefile.FindTargetToUse(argP1->GetValue()) ? true : false,
+          this->Makefile.FindTargetToUse(argP1->GetValue()) != CM_NULLPTR,
           reducible, arg, newArgs, argP1, argP2);
       }
       // does a test exist
@@ -463,7 +475,7 @@ bool cmConditionEvaluator::HandleLevel1(cmArgumentList& newArgs, std::string&,
           this->Policy64Status != cmPolicies::WARN) {
         if (this->IsKeyword(keyTEST, *arg) && argP1 != newArgs.end()) {
           const cmTest* haveTest = this->Makefile.GetTest(argP1->c_str());
-          this->HandlePredicate(haveTest ? true : false, reducible, arg,
+          this->HandlePredicate(haveTest != CM_NULLPTR, reducible, arg,
                                 newArgs, argP1, argP2);
         }
       } else if (this->Policy64Status == cmPolicies::WARN &&
@@ -637,8 +649,8 @@ bool cmConditionEvaluator::HandleLevel2(cmArgumentList& newArgs,
         bool success = cmSystemTools::FileTimeCompare(
           arg->GetValue(), (argP2)->GetValue(), &fileIsNewer);
         this->HandleBinaryOp(
-          (success == false || fileIsNewer == 1 || fileIsNewer == 0),
-          reducible, arg, newArgs, argP1, argP2);
+          (!success || fileIsNewer == 1 || fileIsNewer == 0), reducible, arg,
+          newArgs, argP1, argP2);
       }
 
       if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
diff --git a/Source/cmConditionEvaluator.h b/Source/cmConditionEvaluator.h
index 306bee4..5815177 100644
--- a/Source/cmConditionEvaluator.h
+++ b/Source/cmConditionEvaluator.h
@@ -3,10 +3,18 @@
 #ifndef cmConditionEvaluator_h
 #define cmConditionEvaluator_h
 
-#include "cmCommand.h"
-#include "cmExpandedCommandArgument.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <list>
+#include <string>
+#include <vector>
+
+#include "cmExpandedCommandArgument.h"
+#include "cmListFileCache.h"
+#include "cmPolicies.h"
+#include "cmake.h"
+
+class cmMakefile;
 
 class cmConditionEvaluator
 {
diff --git a/Source/cmConfigure.cmake.h.in b/Source/cmConfigure.cmake.h.in
index 057c6c0..26f1df2 100644
--- a/Source/cmConfigure.cmake.h.in
+++ b/Source/cmConfigure.cmake.h.in
@@ -20,7 +20,6 @@
 #cmakedefine CMAKE_USE_ELF_PARSER
 #cmakedefine CMAKE_USE_MACH_PARSER
 #cmakedefine CMAKE_USE_LIBUV
-#cmakedefine CMAKE_ENCODING_UTF8
 #cmakedefine CMake_HAVE_CXX_AUTO_PTR
 #cmakedefine CMake_HAVE_CXX_MAKE_UNIQUE
 #cmakedefine CMake_HAVE_CXX_NULLPTR
diff --git a/Source/cmConfigureFileCommand.cxx b/Source/cmConfigureFileCommand.cxx
index 6a451f5..b9c7549 100644
--- a/Source/cmConfigureFileCommand.cxx
+++ b/Source/cmConfigureFileCommand.cxx
@@ -2,7 +2,13 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmConfigureFileCommand.h"
 
-#include <cmsys/RegularExpression.hxx>
+#include <sstream>
+
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 // cmConfigureFileCommand
 bool cmConfigureFileCommand::InitialPass(std::vector<std::string> const& args,
diff --git a/Source/cmConfigureFileCommand.h b/Source/cmConfigureFileCommand.h
index f9a0f2a..e558b85 100644
--- a/Source/cmConfigureFileCommand.h
+++ b/Source/cmConfigureFileCommand.h
@@ -3,13 +3,18 @@
 #ifndef cmConfigureFileCommand_h
 #define cmConfigureFileCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
+#include "cmNewLineStyle.h"
+
+class cmExecutionStatus;
 
 class cmConfigureFileCommand : public cmCommand
 {
 public:
-  cmTypeMacro(cmConfigureFileCommand, cmCommand);
-
   cmCommand* Clone() CM_OVERRIDE { return new cmConfigureFileCommand; }
 
   /**
diff --git a/Source/cmContinueCommand.cxx b/Source/cmContinueCommand.cxx
index ce36463..53d035d 100644
--- a/Source/cmContinueCommand.cxx
+++ b/Source/cmContinueCommand.cxx
@@ -2,6 +2,11 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmContinueCommand.h"
 
+#include "cmExecutionStatus.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
 // cmContinueCommand
 bool cmContinueCommand::InitialPass(std::vector<std::string> const& args,
                                     cmExecutionStatus& status)
diff --git a/Source/cmContinueCommand.h b/Source/cmContinueCommand.h
index a36d5f3..c5b8919 100644
--- a/Source/cmContinueCommand.h
+++ b/Source/cmContinueCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmContinueCommand_h
 #define cmContinueCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmContinueCommand
  * \brief Continue from an enclosing foreach or while loop
  *
@@ -34,8 +40,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "continue"; }
-
-  cmTypeMacro(cmContinueCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmConvertMSBuildXMLToJSON.py b/Source/cmConvertMSBuildXMLToJSON.py
new file mode 100644
index 0000000..93ab8a8
--- /dev/null
+++ b/Source/cmConvertMSBuildXMLToJSON.py
@@ -0,0 +1,453 @@
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+import argparse
+import codecs
+import copy
+import logging
+import json
+import os
+
+from collections import OrderedDict
+from xml.dom.minidom import parse, parseString, Element
+
+
+class VSFlags:
+    """Flags corresponding to cmIDEFlagTable."""
+    UserValue = "UserValue"  # (1 << 0)
+    UserIgnored = "UserIgnored"  # (1 << 1)
+    UserRequired = "UserRequired"  # (1 << 2)
+    Continue = "Continue"  #(1 << 3)
+    SemicolonAppendable = "SemicolonAppendable"  # (1 << 4)
+    UserFollowing = "UserFollowing"  # (1 << 5)
+    CaseInsensitive = "CaseInsensitive"  # (1 << 6)
+    UserValueIgnored = [UserValue, UserIgnored]
+    UserValueRequired = [UserValue, UserRequired]
+
+
+def vsflags(*args):
+    """Combines the flags."""
+    values = []
+
+    for arg in args:
+        __append_list(values, arg)
+
+    return values
+
+
+def read_msbuild_xml(path, values={}):
+    """Reads the MS Build XML file at the path and returns its contents.
+
+    Keyword arguments:
+    values -- The map to append the contents to (default {})
+    """
+
+    # Attempt to read the file contents
+    try:
+        document = parse(path)
+    except Exception as e:
+        logging.exception('Could not read MS Build XML file at %s', path)
+        return values
+
+    # Convert the XML to JSON format
+    logging.info('Processing MS Build XML file at %s', path)
+
+    # Get the rule node
+    rule = document.getElementsByTagName('Rule')[0]
+
+    rule_name = rule.attributes['Name'].value
+
+    logging.info('Found rules for %s', rule_name)
+
+    # Proprocess Argument values
+    __preprocess_arguments(rule)
+
+    # Get all the values
+    converted_values = []
+    __convert(rule, 'EnumProperty', converted_values, __convert_enum)
+    __convert(rule, 'BoolProperty', converted_values, __convert_bool)
+    __convert(rule, 'StringListProperty', converted_values,
+              __convert_string_list)
+    __convert(rule, 'StringProperty', converted_values, __convert_string)
+    __convert(rule, 'IntProperty', converted_values, __convert_string)
+
+    values[rule_name] = converted_values
+
+    return values
+
+
+def read_msbuild_json(path, values=[]):
+    """Reads the MS Build JSON file at the path and returns its contents.
+
+    Keyword arguments:
+    values -- The list to append the contents to (default [])
+    """
+    if not os.path.exists(path):
+        logging.info('Could not find MS Build JSON file at %s', path)
+        return values
+
+    try:
+        values.extend(__read_json_file(path))
+    except Exception as e:
+        logging.exception('Could not read MS Build JSON file at %s', path)
+        return values
+
+    logging.info('Processing MS Build JSON file at %s', path)
+
+    return values
+
+
+def main():
+    """Script entrypoint."""
+    # Parse the arguments
+    parser = argparse.ArgumentParser(
+        description='Convert MSBuild XML to JSON format')
+
+    parser.add_argument(
+        '-t', '--toolchain', help='The name of the toolchain', required=True)
+    parser.add_argument(
+        '-o', '--output', help='The output directory', default='')
+    parser.add_argument(
+        '-r',
+        '--overwrite',
+        help='Whether previously output should be overwritten',
+        dest='overwrite',
+        action='store_true')
+    parser.set_defaults(overwrite=False)
+    parser.add_argument(
+        '-d',
+        '--debug',
+        help="Debug tool output",
+        action="store_const",
+        dest="loglevel",
+        const=logging.DEBUG,
+        default=logging.WARNING)
+    parser.add_argument(
+        '-v',
+        '--verbose',
+        help="Verbose output",
+        action="store_const",
+        dest="loglevel",
+        const=logging.INFO)
+    parser.add_argument('input', help='The input files', nargs='+')
+
+    args = parser.parse_args()
+
+    toolchain = args.toolchain
+
+    logging.basicConfig(level=args.loglevel)
+    logging.info('Creating %s toolchain files', toolchain)
+
+    values = {}
+
+    # Iterate through the inputs
+    for input in args.input:
+        input = __get_path(input)
+
+        read_msbuild_xml(input, values)
+
+    # Determine if the output directory needs to be created
+    output_dir = __get_path(args.output)
+
+    if not os.path.exists(output_dir):
+        os.mkdir(output_dir)
+        logging.info('Created output directory %s', output_dir)
+
+    for key, value in values.items():
+        output_path = __output_path(toolchain, key, output_dir)
+
+        if os.path.exists(output_path) and not args.overwrite:
+            logging.info('Comparing previous output to current')
+
+            __merge_json_values(value, read_msbuild_json(output_path))
+        else:
+            logging.info('Original output will be overwritten')
+
+        logging.info('Writing MS Build JSON file at %s', output_path)
+
+        __write_json_file(output_path, value)
+
+
+###########################################################################################
+# private joining functions
+def __merge_json_values(current, previous):
+    """Merges the values between the current and previous run of the script."""
+    for value in current:
+        name = value['name']
+
+        # Find the previous value
+        previous_value = __find_and_remove_value(previous, value)
+
+        if previous_value is not None:
+            flags = value['flags']
+            previous_flags = previous_value['flags']
+
+            if flags != previous_flags:
+                logging.warning(
+                    'Flags for %s are different. Using previous value.', name)
+
+                value['flags'] = previous_flags
+        else:
+            logging.warning('Value %s is a new value', name)
+
+    for value in previous:
+        name = value['name']
+        logging.warning(
+            'Value %s not present in current run. Appending value.', name)
+
+        current.append(value)
+
+
+def __find_and_remove_value(list, compare):
+    """Finds the value in the list that corresponds with the value of compare."""
+    # next throws if there are no matches
+    try:
+        found = next(value for value in list
+                     if value['name'] == compare['name'] and value['switch'] ==
+                     compare['switch'])
+    except:
+        return None
+
+    list.remove(found)
+
+    return found
+
+
+###########################################################################################
+# private xml functions
+def __convert(root, tag, values, func):
+    """Converts the tag type found in the root and converts them using the func
+    and appends them to the values.
+    """
+    elements = root.getElementsByTagName(tag)
+
+    for element in elements:
+        converted = func(element)
+
+        # Append to the list
+        __append_list(values, converted)
+
+
+def __convert_enum(node):
+    """Converts an EnumProperty node to JSON format."""
+    name = __get_attribute(node, 'Name')
+    logging.debug('Found EnumProperty named %s', name)
+
+    converted_values = []
+
+    for value in node.getElementsByTagName('EnumValue'):
+        converted = __convert_node(value)
+
+        converted['value'] = converted['name']
+        converted['name'] = name
+
+        # Modify flags when there is an argument child
+        __with_argument(value, converted)
+
+        converted_values.append(converted)
+
+    return converted_values
+
+
+def __convert_bool(node):
+    """Converts an BoolProperty node to JSON format."""
+    converted = __convert_node(node, default_value='true')
+
+    # Check for a switch for reversing the value
+    reverse_switch = __get_attribute(node, 'ReverseSwitch')
+
+    if reverse_switch:
+        converted_reverse = copy.deepcopy(converted)
+
+        converted_reverse['switch'] = reverse_switch
+        converted_reverse['value'] = 'false'
+
+        return [converted_reverse, converted]
+
+    # Modify flags when there is an argument child
+    __with_argument(node, converted)
+
+    return __check_for_flag(converted)
+
+
+def __convert_string_list(node):
+    """Converts a StringListProperty node to JSON format."""
+    converted = __convert_node(node)
+
+    # Determine flags for the string list
+    flags = vsflags(VSFlags.UserValue)
+
+    # Check for a separator to determine if it is semicolon appendable
+    # If not present assume the value should be ;
+    separator = __get_attribute(node, 'Separator', default_value=';')
+
+    if separator == ';':
+        flags = vsflags(flags, VSFlags.SemicolonAppendable)
+
+    converted['flags'] = flags
+
+    return __check_for_flag(converted)
+
+
+def __convert_string(node):
+    """Converts a StringProperty node to JSON format."""
+    converted = __convert_node(node, default_flags=vsflags(VSFlags.UserValue))
+
+    return __check_for_flag(converted)
+
+
+def __convert_node(node, default_value='', default_flags=vsflags()):
+    """Converts a XML node to a JSON equivalent."""
+    name = __get_attribute(node, 'Name')
+    logging.debug('Found %s named %s', node.tagName, name)
+
+    converted = {}
+    converted['name'] = name
+    converted['switch'] = __get_attribute(node, 'Switch')
+    converted['comment'] = __get_attribute(node, 'DisplayName')
+    converted['value'] = default_value
+
+    # Check for the Flags attribute in case it was created during preprocessing
+    flags = __get_attribute(node, 'Flags')
+
+    if flags:
+        flags = flags.split(',')
+    else:
+        flags = default_flags
+
+    converted['flags'] = flags
+
+    return converted
+
+
+def __check_for_flag(value):
+    """Checks whether the value has a switch value.
+
+    If not then returns None as it should not be added.
+    """
+    if value['switch']:
+        return value
+    else:
+        logging.warning('Skipping %s which has no command line switch',
+                        value['name'])
+        return None
+
+
+def __with_argument(node, value):
+    """Modifies the flags in value if the node contains an Argument."""
+    arguments = node.getElementsByTagName('Argument')
+
+    if arguments:
+        logging.debug('Found argument within %s', value['name'])
+        value['flags'] = vsflags(VSFlags.UserValueIgnored, VSFlags.Continue)
+
+
+def __preprocess_arguments(root):
+    """Preprocesses occurrances of Argument within the root.
+
+    Argument XML values reference other values within the document by name. The
+    referenced value does not contain a switch. This function will add the
+    switch associated with the argument.
+    """
+    # Set the flags to require a value
+    flags = ','.join(vsflags(VSFlags.UserValueRequired))
+
+    # Search through the arguments
+    arguments = root.getElementsByTagName('Argument')
+
+    for argument in arguments:
+        reference = __get_attribute(argument, 'Property')
+        found = None
+
+        # Look for the argument within the root's children
+        for child in root.childNodes:
+            # Ignore Text nodes
+            if isinstance(child, Element):
+                name = __get_attribute(child, 'Name')
+
+                if name == reference:
+                    found = child
+                    break
+
+        if found is not None:
+            logging.info('Found property named %s', reference)
+            # Get the associated switch
+            switch = __get_attribute(argument.parentNode, 'Switch')
+
+            # See if there is already a switch associated with the element.
+            if __get_attribute(found, 'Switch'):
+                logging.debug('Copying node %s', reference)
+                clone = found.cloneNode(True)
+                root.insertBefore(clone, found)
+                found = clone
+
+            found.setAttribute('Switch', switch)
+            found.setAttribute('Flags', flags)
+        else:
+            logging.warning('Could not find property named %s', reference)
+
+
+def __get_attribute(node, name, default_value=''):
+    """Retrieves the attribute of the given name from the node.
+
+    If not present then the default_value is used.
+    """
+    if node.hasAttribute(name):
+        return node.attributes[name].value.strip()
+    else:
+        return default_value
+
+
+###########################################################################################
+# private path functions
+def __get_path(path):
+    """Gets the path to the file."""
+    if not os.path.isabs(path):
+        path = os.path.join(os.getcwd(), path)
+
+    return os.path.normpath(path)
+
+
+def __output_path(toolchain, rule, output_dir):
+    """Gets the output path for a file given the toolchain, rule and output_dir"""
+    filename = '%s_%s.json' % (toolchain, rule)
+    return os.path.join(output_dir, filename)
+
+
+###########################################################################################
+# private JSON file functions
+def __read_json_file(path):
+    """Reads a JSON file at the path."""
+    with open(path, 'r') as f:
+        return json.load(f)
+
+
+def __write_json_file(path, values):
+    """Writes a JSON file at the path with the values provided."""
+    # Sort the keys to ensure ordering
+    sort_order = ['name', 'switch', 'comment', 'value', 'flags']
+    sorted_values = [
+        OrderedDict(
+            sorted(
+                value.items(), key=lambda value: sort_order.index(value[0])))
+        for value in values
+    ]
+
+    with open(path, 'w') as f:
+        json.dump(sorted_values, f, indent=2, separators=(',', ': '))
+
+
+###########################################################################################
+# private list helpers
+def __append_list(append_to, value):
+    """Appends the value to the list."""
+    if value is not None:
+        if isinstance(value, list):
+            append_to.extend(value)
+        else:
+            append_to.append(value)
+
+###########################################################################################
+# main entry point
+if __name__ == "__main__":
+    main()
diff --git a/Source/cmCoreTryCompile.cxx b/Source/cmCoreTryCompile.cxx
index a409d40..ff9ffc0 100644
--- a/Source/cmCoreTryCompile.cxx
+++ b/Source/cmCoreTryCompile.cxx
@@ -2,14 +2,24 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCoreTryCompile.h"
 
+#include <cmConfigure.h>
+#include <cmsys/Directory.hxx>
+#include <set>
+#include <sstream>
+#include <stdio.h>
+#include <string.h>
+
 #include "cmAlgorithms.h"
 #include "cmExportTryCompileFileGenerator.h"
 #include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
 #include "cmOutputConverter.h"
+#include "cmPolicies.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmVersion.h"
 #include "cmake.h"
-#include <cmsys/Directory.hxx>
-
-#include <assert.h>
 
 static std::string const kCMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN =
   "CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN";
@@ -34,33 +44,54 @@ static std::string const kCMAKE_TRY_COMPILE_OSX_ARCHITECTURES =
   "CMAKE_TRY_COMPILE_OSX_ARCHITECTURES";
 static std::string const kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES =
   "CMAKE_TRY_COMPILE_PLATFORM_VARIABLES";
+static std::string const kCMAKE_WARN_DEPRECATED = "CMAKE_WARN_DEPRECATED";
+
+static void writeProperty(FILE* fout, std::string const& targetName,
+                          std::string const& prop, std::string const& value)
+{
+  fprintf(fout, "set_property(TARGET %s PROPERTY %s %s)\n", targetName.c_str(),
+          cmOutputConverter::EscapeForCMake(prop).c_str(),
+          cmOutputConverter::EscapeForCMake(value).c_str());
+}
+
+std::string cmCoreTryCompile::LookupStdVar(std::string const& var,
+                                           bool warnCMP0067)
+{
+  std::string value = this->Makefile->GetSafeDefinition(var);
+  if (warnCMP0067 && !value.empty()) {
+    value.clear();
+    this->WarnCMP0067.push_back(var);
+  }
+  return value;
+}
 
 int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
                                      bool isTryRun)
 {
-  this->BinaryDirectory = argv[1].c_str();
+  this->BinaryDirectory = argv[1];
   this->OutputFile = "";
   // which signature were we called with ?
   this->SrcFileSignature = true;
 
-  cmState::TargetType targetType = cmState::EXECUTABLE;
+  cmStateEnums::TargetType targetType = cmStateEnums::EXECUTABLE;
   const char* tt =
     this->Makefile->GetDefinition("CMAKE_TRY_COMPILE_TARGET_TYPE");
   if (!isTryRun && tt && *tt) {
-    if (strcmp(tt, cmState::GetTargetTypeName(cmState::EXECUTABLE)) == 0) {
-      targetType = cmState::EXECUTABLE;
+    if (strcmp(tt, cmState::GetTargetTypeName(cmStateEnums::EXECUTABLE)) ==
+        0) {
+      targetType = cmStateEnums::EXECUTABLE;
     } else if (strcmp(tt, cmState::GetTargetTypeName(
-                            cmState::STATIC_LIBRARY)) == 0) {
-      targetType = cmState::STATIC_LIBRARY;
+                            cmStateEnums::STATIC_LIBRARY)) == 0) {
+      targetType = cmStateEnums::STATIC_LIBRARY;
     } else {
       this->Makefile->IssueMessage(
         cmake::FATAL_ERROR, std::string("Invalid value '") + tt +
           "' for "
           "CMAKE_TRY_COMPILE_TARGET_TYPE.  Only "
           "'" +
-          cmState::GetTargetTypeName(cmState::EXECUTABLE) + "' and "
-                                                            "'" +
-          cmState::GetTargetTypeName(cmState::STATIC_LIBRARY) +
+          cmState::GetTargetTypeName(cmStateEnums::EXECUTABLE) + "' and "
+                                                                 "'" +
+          cmState::GetTargetTypeName(cmStateEnums::STATIC_LIBRARY) +
           "' "
           "are allowed.");
       return -1;
@@ -75,6 +106,15 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
   std::string outputVariable;
   std::string copyFile;
   std::string copyFileError;
+  std::string cStandard;
+  std::string cxxStandard;
+  std::string cudaStandard;
+  std::string cStandardRequired;
+  std::string cxxStandardRequired;
+  std::string cudaStandardRequired;
+  std::string cExtensions;
+  std::string cxxExtensions;
+  std::string cudaExtensions;
   std::vector<std::string> targets;
   std::string libsToLink = " ";
   bool useOldLinkLibs = true;
@@ -82,6 +122,15 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
   bool didOutputVariable = false;
   bool didCopyFile = false;
   bool didCopyFileError = false;
+  bool didCStandard = false;
+  bool didCxxStandard = false;
+  bool didCudaStandard = false;
+  bool didCStandardRequired = false;
+  bool didCxxStandardRequired = false;
+  bool didCudaStandardRequired = false;
+  bool didCExtensions = false;
+  bool didCxxExtensions = false;
+  bool didCudaExtensions = false;
   bool useSources = argv[2] == "SOURCES";
   std::vector<std::string> sources;
 
@@ -94,6 +143,15 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
     DoingOutputVariable,
     DoingCopyFile,
     DoingCopyFileError,
+    DoingCStandard,
+    DoingCxxStandard,
+    DoingCudaStandard,
+    DoingCStandardRequired,
+    DoingCxxStandardRequired,
+    DoingCudaStandardRequired,
+    DoingCExtensions,
+    DoingCxxExtensions,
+    DoingCudaExtensions,
     DoingSources
   };
   Doing doing = useSources ? DoingSources : DoingNone;
@@ -114,6 +172,33 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
     } else if (argv[i] == "COPY_FILE_ERROR") {
       doing = DoingCopyFileError;
       didCopyFileError = true;
+    } else if (argv[i] == "C_STANDARD") {
+      doing = DoingCStandard;
+      didCStandard = true;
+    } else if (argv[i] == "CXX_STANDARD") {
+      doing = DoingCxxStandard;
+      didCxxStandard = true;
+    } else if (argv[i] == "CUDA_STANDARD") {
+      doing = DoingCudaStandard;
+      didCudaStandard = true;
+    } else if (argv[i] == "C_STANDARD_REQUIRED") {
+      doing = DoingCStandardRequired;
+      didCStandardRequired = true;
+    } else if (argv[i] == "CXX_STANDARD_REQUIRED") {
+      doing = DoingCxxStandardRequired;
+      didCxxStandardRequired = true;
+    } else if (argv[i] == "CUDA_STANDARD_REQUIRED") {
+      doing = DoingCudaStandardRequired;
+      didCudaStandardRequired = true;
+    } else if (argv[i] == "C_EXTENSIONS") {
+      doing = DoingCExtensions;
+      didCExtensions = true;
+    } else if (argv[i] == "CXX_EXTENSIONS") {
+      doing = DoingCxxExtensions;
+      didCxxExtensions = true;
+    } else if (argv[i] == "CUDA_EXTENSIONS") {
+      doing = DoingCudaExtensions;
+      didCudaExtensions = true;
     } else if (doing == DoingCMakeFlags) {
       cmakeFlags.push_back(argv[i]);
     } else if (doing == DoingCompileDefinitions) {
@@ -122,12 +207,12 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
       libsToLink += "\"" + cmSystemTools::TrimWhitespace(argv[i]) + "\" ";
       if (cmTarget* tgt = this->Makefile->FindTargetToUse(argv[i])) {
         switch (tgt->GetType()) {
-          case cmState::SHARED_LIBRARY:
-          case cmState::STATIC_LIBRARY:
-          case cmState::INTERFACE_LIBRARY:
-          case cmState::UNKNOWN_LIBRARY:
+          case cmStateEnums::SHARED_LIBRARY:
+          case cmStateEnums::STATIC_LIBRARY:
+          case cmStateEnums::INTERFACE_LIBRARY:
+          case cmStateEnums::UNKNOWN_LIBRARY:
             break;
-          case cmState::EXECUTABLE:
+          case cmStateEnums::EXECUTABLE:
             if (tgt->IsExecutableWithExports()) {
               break;
             }
@@ -146,13 +231,40 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
         }
       }
     } else if (doing == DoingOutputVariable) {
-      outputVariable = argv[i].c_str();
+      outputVariable = argv[i];
       doing = DoingNone;
     } else if (doing == DoingCopyFile) {
-      copyFile = argv[i].c_str();
+      copyFile = argv[i];
       doing = DoingNone;
     } else if (doing == DoingCopyFileError) {
-      copyFileError = argv[i].c_str();
+      copyFileError = argv[i];
+      doing = DoingNone;
+    } else if (doing == DoingCStandard) {
+      cStandard = argv[i];
+      doing = DoingNone;
+    } else if (doing == DoingCxxStandard) {
+      cxxStandard = argv[i];
+      doing = DoingNone;
+    } else if (doing == DoingCudaStandard) {
+      cudaStandard = argv[i];
+      doing = DoingNone;
+    } else if (doing == DoingCStandardRequired) {
+      cStandardRequired = argv[i];
+      doing = DoingNone;
+    } else if (doing == DoingCxxStandardRequired) {
+      cxxStandardRequired = argv[i];
+      doing = DoingNone;
+    } else if (doing == DoingCudaStandardRequired) {
+      cudaStandardRequired = argv[i];
+      doing = DoingNone;
+    } else if (doing == DoingCExtensions) {
+      cExtensions = argv[i];
+      doing = DoingNone;
+    } else if (doing == DoingCxxExtensions) {
+      cxxExtensions = argv[i];
+      doing = DoingNone;
+    } else if (doing == DoingCudaExtensions) {
+      cudaExtensions = argv[i];
       doing = DoingNone;
     } else if (doing == DoingSources) {
       sources.push_back(argv[i]);
@@ -160,7 +272,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
       this->SrcFileSignature = false;
       projectName = argv[i].c_str();
     } else if (i == 4 && !this->SrcFileSignature) {
-      targetName = argv[i].c_str();
+      targetName = argv[i];
     } else {
       std::ostringstream m;
       m << "try_compile given unknown argument \"" << argv[i] << "\".";
@@ -201,6 +313,60 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
     return -1;
   }
 
+  if (didCStandard && !this->SrcFileSignature) {
+    this->Makefile->IssueMessage(
+      cmake::FATAL_ERROR, "C_STANDARD allowed only in source file signature.");
+    return -1;
+  }
+  if (didCxxStandard && !this->SrcFileSignature) {
+    this->Makefile->IssueMessage(
+      cmake::FATAL_ERROR,
+      "CXX_STANDARD allowed only in source file signature.");
+    return -1;
+  }
+  if (didCudaStandard && !this->SrcFileSignature) {
+    this->Makefile->IssueMessage(
+      cmake::FATAL_ERROR,
+      "CUDA_STANDARD allowed only in source file signature.");
+    return -1;
+  }
+  if (didCStandardRequired && !this->SrcFileSignature) {
+    this->Makefile->IssueMessage(
+      cmake::FATAL_ERROR,
+      "C_STANDARD_REQUIRED allowed only in source file signature.");
+    return -1;
+  }
+  if (didCxxStandardRequired && !this->SrcFileSignature) {
+    this->Makefile->IssueMessage(
+      cmake::FATAL_ERROR,
+      "CXX_STANDARD_REQUIRED allowed only in source file signature.");
+    return -1;
+  }
+  if (didCudaStandardRequired && !this->SrcFileSignature) {
+    this->Makefile->IssueMessage(
+      cmake::FATAL_ERROR,
+      "CUDA_STANDARD_REQUIRED allowed only in source file signature.");
+    return -1;
+  }
+  if (didCExtensions && !this->SrcFileSignature) {
+    this->Makefile->IssueMessage(
+      cmake::FATAL_ERROR,
+      "C_EXTENSIONS allowed only in source file signature.");
+    return -1;
+  }
+  if (didCxxExtensions && !this->SrcFileSignature) {
+    this->Makefile->IssueMessage(
+      cmake::FATAL_ERROR,
+      "CXX_EXTENSIONS allowed only in source file signature.");
+    return -1;
+  }
+  if (didCudaExtensions && !this->SrcFileSignature) {
+    this->Makefile->IssueMessage(
+      cmake::FATAL_ERROR,
+      "CUDA_EXTENSIONS allowed only in source file signature.");
+    return -1;
+  }
+
   // compute the binary dir when TRY_COMPILE is called with a src file
   // signature
   if (this->SrcFileSignature) {
@@ -442,6 +608,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
       vars.insert(kCMAKE_OSX_SYSROOT);
       vars.insert(kCMAKE_POSITION_INDEPENDENT_CODE);
       vars.insert(kCMAKE_SYSROOT);
+      vars.insert(kCMAKE_WARN_DEPRECATED);
 
       if (const char* varListStr = this->Makefile->GetDefinition(
             kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES)) {
@@ -481,13 +648,13 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
               ? "NEW"
               : "OLD");
 
-    if (targetType == cmState::EXECUTABLE) {
+    if (targetType == cmStateEnums::EXECUTABLE) {
       /* Put the executable at a known location (for COPY_FILE).  */
       fprintf(fout, "set(CMAKE_RUNTIME_OUTPUT_DIRECTORY \"%s\")\n",
               this->BinaryDirectory.c_str());
       /* Create the actual executable.  */
       fprintf(fout, "add_executable(%s", targetName.c_str());
-    } else // if (targetType == cmState::STATIC_LIBRARY)
+    } else // if (targetType == cmStateEnums::STATIC_LIBRARY)
     {
       /* Put the static library at a known location (for COPY_FILE).  */
       fprintf(fout, "set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY \"%s\")\n",
@@ -505,6 +672,134 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
       }
     }
     fprintf(fout, ")\n");
+
+    bool const testC = testLangs.find("C") != testLangs.end();
+    bool const testCxx = testLangs.find("CXX") != testLangs.end();
+    bool const testCuda = testLangs.find("CUDA") != testLangs.end();
+
+    bool warnCMP0067 = false;
+    bool honorStandard = true;
+
+    if (!didCStandard && !didCxxStandard && !didCudaStandard &&
+        !didCStandardRequired && !didCxxStandardRequired &&
+        !didCudaStandardRequired && !didCExtensions && !didCxxExtensions &&
+        !didCudaExtensions) {
+      switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0067)) {
+        case cmPolicies::WARN:
+          warnCMP0067 = this->Makefile->PolicyOptionalWarningEnabled(
+            "CMAKE_POLICY_WARNING_CMP0067");
+        case cmPolicies::OLD:
+          // OLD behavior is to not honor the language standard variables.
+          honorStandard = false;
+          break;
+        case cmPolicies::REQUIRED_IF_USED:
+        case cmPolicies::REQUIRED_ALWAYS:
+          this->Makefile->IssueMessage(
+            cmake::FATAL_ERROR,
+            cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0067));
+        case cmPolicies::NEW:
+          // NEW behavior is to honor the language standard variables.
+          // We already initialized honorStandard to true.
+          break;
+      }
+    }
+
+    if (honorStandard || warnCMP0067) {
+      if (testC) {
+        if (!didCStandard) {
+          cStandard = this->LookupStdVar("CMAKE_C_STANDARD", warnCMP0067);
+        }
+        if (!didCStandardRequired) {
+          cStandardRequired =
+            this->LookupStdVar("CMAKE_C_STANDARD_REQUIRED", warnCMP0067);
+        }
+        if (!didCExtensions) {
+          cExtensions = this->LookupStdVar("CMAKE_C_EXTENSIONS", warnCMP0067);
+        }
+      }
+      if (testCxx) {
+        if (!didCxxStandard) {
+          cxxStandard = this->LookupStdVar("CMAKE_CXX_STANDARD", warnCMP0067);
+        }
+        if (!didCxxStandardRequired) {
+          cxxStandardRequired =
+            this->LookupStdVar("CMAKE_CXX_STANDARD_REQUIRED", warnCMP0067);
+        }
+        if (!didCxxExtensions) {
+          cxxExtensions =
+            this->LookupStdVar("CMAKE_CXX_EXTENSIONS", warnCMP0067);
+        }
+      }
+      if (testCuda) {
+        if (!didCudaStandard) {
+          cudaStandard =
+            this->LookupStdVar("CMAKE_CUDA_STANDARD", warnCMP0067);
+        }
+        if (!didCudaStandardRequired) {
+          cudaStandardRequired =
+            this->LookupStdVar("CMAKE_CUDA_STANDARD_REQUIRED", warnCMP0067);
+        }
+        if (!didCudaExtensions) {
+          cudaExtensions =
+            this->LookupStdVar("CMAKE_CUDA_EXTENSIONS", warnCMP0067);
+        }
+      }
+    }
+
+    if (!this->WarnCMP0067.empty()) {
+      std::ostringstream w;
+      /* clang-format off */
+      w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0067) << "\n"
+        "For compatibility with older versions of CMake, try_compile "
+        "is not honoring language standard variables in the test project:\n"
+        ;
+      /* clang-format on */
+      for (std::vector<std::string>::iterator vi = this->WarnCMP0067.begin();
+           vi != this->WarnCMP0067.end(); ++vi) {
+        w << "  " << *vi << "\n";
+      }
+      this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
+    }
+
+    if (testC) {
+      if (!cStandard.empty()) {
+        writeProperty(fout, targetName, "C_STANDARD", cStandard);
+      }
+      if (!cStandardRequired.empty()) {
+        writeProperty(fout, targetName, "C_STANDARD_REQUIRED",
+                      cStandardRequired);
+      }
+      if (!cExtensions.empty()) {
+        writeProperty(fout, targetName, "C_EXTENSIONS", cExtensions);
+      }
+    }
+
+    if (testCxx) {
+      if (!cxxStandard.empty()) {
+        writeProperty(fout, targetName, "CXX_STANDARD", cxxStandard);
+      }
+      if (!cxxStandardRequired.empty()) {
+        writeProperty(fout, targetName, "CXX_STANDARD_REQUIRED",
+                      cxxStandardRequired);
+      }
+      if (!cxxExtensions.empty()) {
+        writeProperty(fout, targetName, "CXX_EXTENSIONS", cxxExtensions);
+      }
+    }
+
+    if (testCuda) {
+      if (!cudaStandard.empty()) {
+        writeProperty(fout, targetName, "CUDA_STANDARD", cudaStandard);
+      }
+      if (!cudaStandardRequired.empty()) {
+        writeProperty(fout, targetName, "CUDA_STANDARD_REQUIRED",
+                      cudaStandardRequired);
+      }
+      if (!cudaExtensions.empty()) {
+        writeProperty(fout, targetName, "CUDA_EXTENSIONS", cudaExtensions);
+      }
+    }
+
     if (useOldLinkLibs) {
       fprintf(fout, "target_link_libraries(%s ${LINK_LIBRARIES})\n",
               targetName.c_str());
@@ -530,7 +825,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
   // set the result var to the return value to indicate success or failure
   this->Makefile->AddCacheDefinition(argv[0], (res == 0 ? "TRUE" : "FALSE"),
                                      "Result of TRY_COMPILE",
-                                     cmState::INTERNAL);
+                                     cmStateEnums::INTERNAL);
 
   if (!outputVariable.empty()) {
     this->Makefile->AddDefinition(outputVariable, output.c_str());
@@ -586,18 +881,13 @@ void cmCoreTryCompile::CleanupFiles(const char* binDir)
 
   cmsys::Directory dir;
   dir.Load(binDir);
-  size_t fileNum;
   std::set<std::string> deletedFiles;
-  for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) {
-    if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") &&
-        strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), "..")) {
-
-      if (deletedFiles.find(dir.GetFile(
-            static_cast<unsigned long>(fileNum))) == deletedFiles.end()) {
-        deletedFiles.insert(dir.GetFile(static_cast<unsigned long>(fileNum)));
-        std::string fullPath = binDir;
-        fullPath += "/";
-        fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
+  for (unsigned long i = 0; i < dir.GetNumberOfFiles(); ++i) {
+    const char* fileName = dir.GetFile(i);
+    if (strcmp(fileName, ".") != 0 && strcmp(fileName, "..") != 0) {
+      if (deletedFiles.insert(fileName).second) {
+        std::string const fullPath =
+          std::string(binDir).append("/").append(fileName);
         if (cmSystemTools::FileIsDirectory(fullPath)) {
           this->CleanupFiles(fullPath.c_str());
           cmSystemTools::RemoveADirectory(fullPath);
@@ -627,16 +917,16 @@ void cmCoreTryCompile::CleanupFiles(const char* binDir)
 }
 
 void cmCoreTryCompile::FindOutputFile(const std::string& targetName,
-                                      cmState::TargetType targetType)
+                                      cmStateEnums::TargetType targetType)
 {
   this->FindErrorMessage = "";
   this->OutputFile = "";
   std::string tmpOutputFile = "/";
-  if (targetType == cmState::EXECUTABLE) {
+  if (targetType == cmStateEnums::EXECUTABLE) {
     tmpOutputFile += targetName;
     tmpOutputFile +=
       this->Makefile->GetSafeDefinition("CMAKE_EXECUTABLE_SUFFIX");
-  } else // if (targetType == cmState::STATIC_LIBRARY)
+  } else // if (targetType == cmStateEnums::STATIC_LIBRARY)
   {
     tmpOutputFile +=
       this->Makefile->GetSafeDefinition("CMAKE_STATIC_LIBRARY_PREFIX");
@@ -681,5 +971,4 @@ void cmCoreTryCompile::FindOutputFile(const std::string& targetName,
   emsg << cmWrap("  " + this->BinaryDirectory, searchDirs, tmpOutputFile, "\n")
        << "\n";
   this->FindErrorMessage = emsg.str();
-  return;
 }
diff --git a/Source/cmCoreTryCompile.h b/Source/cmCoreTryCompile.h
index e173a16..4b96aed 100644
--- a/Source/cmCoreTryCompile.h
+++ b/Source/cmCoreTryCompile.h
@@ -3,7 +3,13 @@
 #ifndef cmCoreTryCompile_h
 #define cmCoreTryCompile_h
 
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
+#include "cmStateTypes.h"
 
 /** \class cmCoreTryCompile
  * \brief Base class for cmTryCompileCommand and cmTryRunCommand
@@ -35,14 +41,16 @@ protected:
   the error message is stored in FindErrorMessage.
    */
   void FindOutputFile(const std::string& targetName,
-                      cmState::TargetType targetType);
-
-  cmTypeMacro(cmCoreTryCompile, cmCommand);
+                      cmStateEnums::TargetType targetType);
 
   std::string BinaryDirectory;
   std::string OutputFile;
   std::string FindErrorMessage;
   bool SrcFileSignature;
+
+private:
+  std::vector<std::string> WarnCMP0067;
+  std::string LookupStdVar(std::string const& var, bool warnCMP0067);
 };
 
 #endif
diff --git a/Source/cmCreateTestSourceList.cxx b/Source/cmCreateTestSourceList.cxx
index ec62c5b..69532e6 100644
--- a/Source/cmCreateTestSourceList.cxx
+++ b/Source/cmCreateTestSourceList.cxx
@@ -2,7 +2,13 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCreateTestSourceList.h"
 
+#include <algorithm>
+
+#include "cmMakefile.h"
 #include "cmSourceFile.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
 
 // cmCreateTestSourceList
 bool cmCreateTestSourceList::InitialPass(std::vector<std::string> const& args,
diff --git a/Source/cmCreateTestSourceList.h b/Source/cmCreateTestSourceList.h
index ffd06f0..5e003cf 100644
--- a/Source/cmCreateTestSourceList.h
+++ b/Source/cmCreateTestSourceList.h
@@ -3,8 +3,15 @@
 #ifndef cmCreateTestSourceList_h
 #define cmCreateTestSourceList_h
 
+#include <cmConfigure.h>
+
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmCreateTestSourceList
  * \brief Test driver generation command
  *
@@ -29,8 +36,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "create_test_sourcelist"; }
-
-  cmTypeMacro(cmCreateTestSourceList, cmCommand);
 };
 
 #endif
diff --git a/Source/cmCryptoHash.cxx b/Source/cmCryptoHash.cxx
index 9b3f84a..d5807b1 100644
--- a/Source/cmCryptoHash.cxx
+++ b/Source/cmCryptoHash.cxx
@@ -2,31 +2,78 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmCryptoHash.h"
 
-#include "cm_sha2.h"
-
+#include <cm_kwiml.h>
+#include <cm_rhash.h>
 #include <cmsys/FStream.hxx>
-#include <cmsys/MD5.h>
 #include <string.h>
 
+static unsigned int const cmCryptoHashAlgoToId[] = {
+  /* clang-format needs this comment to break after the opening brace */
+  RHASH_MD5,      //
+  RHASH_SHA1,     //
+  RHASH_SHA224,   //
+  RHASH_SHA256,   //
+  RHASH_SHA384,   //
+  RHASH_SHA512,   //
+  RHASH_SHA3_224, //
+  RHASH_SHA3_256, //
+  RHASH_SHA3_384, //
+  RHASH_SHA3_512
+};
+
+static int cmCryptoHash_rhash_library_initialized;
+
+static rhash cmCryptoHash_rhash_init(unsigned int id)
+{
+  if (!cmCryptoHash_rhash_library_initialized) {
+    cmCryptoHash_rhash_library_initialized = 1;
+    rhash_library_init();
+  }
+  return rhash_init(id);
+}
+
+cmCryptoHash::cmCryptoHash(Algo algo)
+  : Id(cmCryptoHashAlgoToId[algo])
+  , CTX(cmCryptoHash_rhash_init(Id))
+{
+}
+
+cmCryptoHash::~cmCryptoHash()
+{
+  rhash_free(this->CTX);
+}
+
 CM_AUTO_PTR<cmCryptoHash> cmCryptoHash::New(const char* algo)
 {
   if (strcmp(algo, "MD5") == 0) {
-    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashMD5);
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoMD5));
   }
   if (strcmp(algo, "SHA1") == 0) {
-    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA1);
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA1));
   }
   if (strcmp(algo, "SHA224") == 0) {
-    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA224);
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA224));
   }
   if (strcmp(algo, "SHA256") == 0) {
-    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA256);
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA256));
   }
   if (strcmp(algo, "SHA384") == 0) {
-    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA384);
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA384));
   }
   if (strcmp(algo, "SHA512") == 0) {
-    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHashSHA512);
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA512));
+  }
+  if (strcmp(algo, "SHA3_224") == 0) {
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_224));
+  }
+  if (strcmp(algo, "SHA3_256") == 0) {
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_256));
+  }
+  if (strcmp(algo, "SHA3_384") == 0) {
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_384));
+  }
+  if (strcmp(algo, "SHA3_512") == 0) {
+    return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_512));
   }
   return CM_AUTO_PTR<cmCryptoHash>(CM_NULLPTR);
 }
@@ -80,7 +127,7 @@ std::vector<unsigned char> cmCryptoHash::ByteHashFile(const std::string& file)
     this->Initialize();
     {
       // Should be efficient enough on most system:
-      cm_sha2_uint64_t buffer[512];
+      KWIML_INT_uint64_t buffer[512];
       char* buffer_c = reinterpret_cast<char*>(buffer);
       unsigned char const* buffer_uc =
         reinterpret_cast<unsigned char const*>(buffer);
@@ -117,51 +164,29 @@ std::string cmCryptoHash::HashFile(const std::string& file)
   return ByteHashToString(this->ByteHashFile(file));
 }
 
-cmCryptoHashMD5::cmCryptoHashMD5()
-  : MD5(cmsysMD5_New())
+void cmCryptoHash::Initialize()
 {
+  rhash_reset(this->CTX);
 }
 
-cmCryptoHashMD5::~cmCryptoHashMD5()
+void cmCryptoHash::Append(void const* buf, size_t sz)
 {
-  cmsysMD5_Delete(this->MD5);
+  rhash_update(this->CTX, buf, sz);
 }
 
-void cmCryptoHashMD5::Initialize()
+void cmCryptoHash::Append(std::string const& str)
 {
-  cmsysMD5_Initialize(this->MD5);
+  this->Append(str.c_str(), str.size());
 }
 
-void cmCryptoHashMD5::Append(unsigned char const* buf, int sz)
+std::vector<unsigned char> cmCryptoHash::Finalize()
 {
-  cmsysMD5_Append(this->MD5, buf, sz);
+  std::vector<unsigned char> hash(rhash_get_digest_size(this->Id), 0);
+  rhash_final(this->CTX, &hash[0]);
+  return hash;
 }
 
-std::vector<unsigned char> cmCryptoHashMD5::Finalize()
+std::string cmCryptoHash::FinalizeHex()
 {
-  std::vector<unsigned char> hash(16, 0);
-  cmsysMD5_Finalize(this->MD5, &hash[0]);
-  return hash;
+  return cmCryptoHash::ByteHashToString(this->Finalize());
 }
-
-#define cmCryptoHash_SHA_CLASS_IMPL(SHA)                                      \
-  cmCryptoHash##SHA::cmCryptoHash##SHA()                                      \
-    : SHA(new SHA_CTX)                                                        \
-  {                                                                           \
-  }                                                                           \
-  cmCryptoHash##SHA::~cmCryptoHash##SHA() { delete this->SHA; }               \
-  void cmCryptoHash##SHA::Initialize() { SHA##_Init(this->SHA); }             \
-  void cmCryptoHash##SHA::Append(unsigned char const* buf, int sz)            \
-  {                                                                           \
-    SHA##_Update(this->SHA, buf, sz);                                         \
-  }                                                                           \
-  std::vector<unsigned char> cmCryptoHash##SHA::Finalize()                    \
-  {                                                                           \
-    std::vector<unsigned char> hash(SHA##_DIGEST_LENGTH, 0);                  \
-    SHA##_Final(&hash[0], this->SHA);                                         \
-    return hash;                                                              \
-  }
-
-cmCryptoHash_SHA_CLASS_IMPL(SHA1) cmCryptoHash_SHA_CLASS_IMPL(SHA224)
-  cmCryptoHash_SHA_CLASS_IMPL(SHA256) cmCryptoHash_SHA_CLASS_IMPL(SHA384)
-    cmCryptoHash_SHA_CLASS_IMPL(SHA512)
diff --git a/Source/cmCryptoHash.h b/Source/cmCryptoHash.h
index 5c2d3ca..0b562da 100644
--- a/Source/cmCryptoHash.h
+++ b/Source/cmCryptoHash.h
@@ -3,23 +3,41 @@
 #ifndef cmCryptoHash_h
 #define cmCryptoHash_h
 
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include <cm_auto_ptr.hxx>
+#include <stddef.h>
 #include <string>
 #include <vector>
 
+#include "cm_auto_ptr.hxx"
+
 /**
  * @brief Abstract base class for cryptographic hash generators
  */
 class cmCryptoHash
 {
 public:
-  virtual ~cmCryptoHash() {}
+  enum Algo
+  {
+    AlgoMD5,
+    AlgoSHA1,
+    AlgoSHA224,
+    AlgoSHA256,
+    AlgoSHA384,
+    AlgoSHA512,
+    AlgoSHA3_224,
+    AlgoSHA3_256,
+    AlgoSHA3_384,
+    AlgoSHA3_512
+  };
+
+  cmCryptoHash(Algo algo);
+  ~cmCryptoHash();
 
   /// @brief Returns a new hash generator of the requested type
   /// @arg algo Hash type name. Supported hash types are
-  ///      MD5, SHA1, SHA224, SHA256, SHA384, SHA512
+  ///      MD5, SHA1, SHA224, SHA256, SHA384, SHA512,
+  ///      SHA3_224, SHA3_256, SHA3_384, SHA3_512
   /// @return A valid auto pointer if algo is supported or
   ///         an invalid/NULL pointer otherwise
   static CM_AUTO_PTR<cmCryptoHash> New(const char* algo);
@@ -53,47 +71,15 @@ public:
   ///         An empty string otherwise.
   std::string HashFile(const std::string& file);
 
-protected:
-  virtual void Initialize() = 0;
-  virtual void Append(unsigned char const*, int) = 0;
-  virtual std::vector<unsigned char> Finalize() = 0;
-};
+  void Initialize();
+  void Append(void const*, size_t);
+  void Append(std::string const& str);
+  std::vector<unsigned char> Finalize();
+  std::string FinalizeHex();
 
-class cmCryptoHashMD5 : public cmCryptoHash
-{
-  struct cmsysMD5_s* MD5;
-
-public:
-  cmCryptoHashMD5();
-  ~cmCryptoHashMD5() CM_OVERRIDE;
-
-protected:
-  void Initialize() CM_OVERRIDE;
-  void Append(unsigned char const* buf, int sz) CM_OVERRIDE;
-  std::vector<unsigned char> Finalize() CM_OVERRIDE;
+private:
+  unsigned int Id;
+  struct rhash_context* CTX;
 };
 
-#define cmCryptoHash_SHA_CLASS_DECL(SHA)                                      \
-  class cmCryptoHash##SHA : public cmCryptoHash                               \
-  {                                                                           \
-    union _SHA_CTX* SHA;                                                      \
-                                                                              \
-  public:                                                                     \
-    cmCryptoHash##SHA();                                                      \
-    ~cmCryptoHash##SHA();                                                     \
-                                                                              \
-  protected:                                                                  \
-    virtual void Initialize();                                                \
-    virtual void Append(unsigned char const* buf, int sz);                    \
-    virtual std::vector<unsigned char> Finalize();                            \
-  }
-
-cmCryptoHash_SHA_CLASS_DECL(SHA1);
-cmCryptoHash_SHA_CLASS_DECL(SHA224);
-cmCryptoHash_SHA_CLASS_DECL(SHA256);
-cmCryptoHash_SHA_CLASS_DECL(SHA384);
-cmCryptoHash_SHA_CLASS_DECL(SHA512);
-
-#undef cmCryptoHash_SHA_CLASS_DECL
-
 #endif
diff --git a/Source/cmCustomCommand.cxx b/Source/cmCustomCommand.cxx
index 6645b8e..050de17 100644
--- a/Source/cmCustomCommand.cxx
+++ b/Source/cmCustomCommand.cxx
@@ -13,6 +13,7 @@ cmCustomCommand::cmCustomCommand()
   this->EscapeOldStyle = true;
   this->EscapeAllowMakeVars = false;
   this->UsesTerminal = false;
+  this->CommandExpandLists = false;
 }
 
 cmCustomCommand::cmCustomCommand(cmMakefile const* mf,
@@ -32,6 +33,7 @@ cmCustomCommand::cmCustomCommand(cmMakefile const* mf,
   , HaveComment(comment != CM_NULLPTR)
   , EscapeAllowMakeVars(false)
   , EscapeOldStyle(true)
+  , CommandExpandLists(false)
 {
   if (mf) {
     this->Backtrace = mf->GetBacktrace();
@@ -127,6 +129,16 @@ void cmCustomCommand::SetUsesTerminal(bool b)
   this->UsesTerminal = b;
 }
 
+bool cmCustomCommand::GetCommandExpandLists() const
+{
+  return this->CommandExpandLists;
+}
+
+void cmCustomCommand::SetCommandExpandLists(bool b)
+{
+  this->CommandExpandLists = b;
+}
+
 const std::string& cmCustomCommand::GetDepfile() const
 {
   return this->Depfile;
diff --git a/Source/cmCustomCommand.h b/Source/cmCustomCommand.h
index 66f8fa9..73d53ff 100644
--- a/Source/cmCustomCommand.h
+++ b/Source/cmCustomCommand.h
@@ -85,6 +85,10 @@ public:
   bool GetUsesTerminal() const;
   void SetUsesTerminal(bool b);
 
+  /** Set/Get whether lists in command lines should be expanded. */
+  bool GetCommandExpandLists() const;
+  void SetCommandExpandLists(bool b);
+
   /** Set/Get the depfile (used by the Ninja generator) */
   const std::string& GetDepfile() const;
   void SetDepfile(const std::string& depfile);
@@ -103,6 +107,7 @@ private:
   bool EscapeAllowMakeVars;
   bool EscapeOldStyle;
   bool UsesTerminal;
+  bool CommandExpandLists;
 };
 
 #endif
diff --git a/Source/cmCustomCommandGenerator.cxx b/Source/cmCustomCommandGenerator.cxx
index 0fd4ffb..8f4ff4b 100644
--- a/Source/cmCustomCommandGenerator.cxx
+++ b/Source/cmCustomCommandGenerator.cxx
@@ -9,7 +9,7 @@
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmOutputConverter.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cm_auto_ptr.hxx"
 
@@ -26,6 +26,24 @@ cmCustomCommandGenerator::cmCustomCommandGenerator(cmCustomCommand const& cc,
   , GE(new cmGeneratorExpression(cc.GetBacktrace()))
   , DependsDone(false)
 {
+  const cmCustomCommandLines& cmdlines = this->CC.GetCommandLines();
+  for (cmCustomCommandLines::const_iterator cmdline = cmdlines.begin();
+       cmdline != cmdlines.end(); ++cmdline) {
+    cmCustomCommandLine argv;
+    for (cmCustomCommandLine::const_iterator clarg = cmdline->begin();
+         clarg != cmdline->end(); ++clarg) {
+      CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = this->GE->Parse(*clarg);
+      std::string parsed_arg = cge->Evaluate(this->LG, this->Config);
+      if (this->CC.GetCommandExpandLists()) {
+        std::vector<std::string> ExpandedArg;
+        cmSystemTools::ExpandListArgument(parsed_arg, ExpandedArg);
+        argv.insert(argv.end(), ExpandedArg.begin(), ExpandedArg.end());
+      } else {
+        argv.push_back(parsed_arg);
+      }
+    }
+    this->CommandLines.push_back(argv);
+  }
 }
 
 cmCustomCommandGenerator::~cmCustomCommandGenerator()
@@ -38,36 +56,44 @@ unsigned int cmCustomCommandGenerator::GetNumberOfCommands() const
   return static_cast<unsigned int>(this->CC.GetCommandLines().size());
 }
 
-bool cmCustomCommandGenerator::UseCrossCompilingEmulator(unsigned int c) const
+const char* cmCustomCommandGenerator::GetCrossCompilingEmulator(
+  unsigned int c) const
 {
-  std::string const& argv0 = this->CC.GetCommandLines()[c][0];
+  if (!this->LG->GetMakefile()->IsOn("CMAKE_CROSSCOMPILING")) {
+    return CM_NULLPTR;
+  }
+  std::string const& argv0 = this->CommandLines[c][0];
   cmGeneratorTarget* target = this->LG->FindGeneratorTargetToUse(argv0);
-  if (target && target->GetType() == cmState::EXECUTABLE) {
-    return target->GetProperty("CROSSCOMPILING_EMULATOR") != CM_NULLPTR;
+  if (target && target->GetType() == cmStateEnums::EXECUTABLE &&
+      !target->IsImported()) {
+    return target->GetProperty("CROSSCOMPILING_EMULATOR");
   }
-  return false;
+  return CM_NULLPTR;
 }
 
-std::string cmCustomCommandGenerator::GetCommand(unsigned int c) const
+const char* cmCustomCommandGenerator::GetArgv0Location(unsigned int c) const
 {
-  std::string const& argv0 = this->CC.GetCommandLines()[c][0];
+  std::string const& argv0 = this->CommandLines[c][0];
   cmGeneratorTarget* target = this->LG->FindGeneratorTargetToUse(argv0);
-  if (target && target->GetType() == cmState::EXECUTABLE &&
+  if (target && target->GetType() == cmStateEnums::EXECUTABLE &&
       (target->IsImported() ||
+       target->GetProperty("CROSSCOMPILING_EMULATOR") ||
        !this->LG->GetMakefile()->IsOn("CMAKE_CROSSCOMPILING"))) {
     return target->GetLocation(this->Config);
   }
-  if (target && target->GetType() == cmState::EXECUTABLE) {
-    const char* emulator = target->GetProperty("CROSSCOMPILING_EMULATOR");
-    if (emulator) {
-      return std::string(emulator);
-    }
-  }
+  return CM_NULLPTR;
+}
 
-  CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = this->GE->Parse(argv0);
-  std::string exe = cge->Evaluate(this->LG, this->Config);
+std::string cmCustomCommandGenerator::GetCommand(unsigned int c) const
+{
+  if (const char* emulator = this->GetCrossCompilingEmulator(c)) {
+    return std::string(emulator);
+  }
+  if (const char* location = this->GetArgv0Location(c)) {
+    return std::string(location);
+  }
 
-  return exe;
+  return this->CommandLines[c][0];
 }
 
 std::string escapeForShellOldStyle(const std::string& str)
@@ -99,13 +125,20 @@ void cmCustomCommandGenerator::AppendArguments(unsigned int c,
                                                std::string& cmd) const
 {
   unsigned int offset = 1;
-  if (this->UseCrossCompilingEmulator(c)) {
+  if (this->GetCrossCompilingEmulator(c) != CM_NULLPTR) {
     offset = 0;
   }
-  cmCustomCommandLine const& commandLine = this->CC.GetCommandLines()[c];
+  cmCustomCommandLine const& commandLine = this->CommandLines[c];
   for (unsigned int j = offset; j < commandLine.size(); ++j) {
-    std::string arg =
-      this->GE->Parse(commandLine[j])->Evaluate(this->LG, this->Config);
+    std::string arg;
+    if (const char* location =
+          j == 0 ? this->GetArgv0Location(c) : CM_NULLPTR) {
+      // GetCommand returned the emulator instead of the argv0 location,
+      // so transform the latter now.
+      arg = location;
+    } else {
+      arg = commandLine[j];
+    }
     cmd += " ";
     if (this->OldStyle) {
       cmd += escapeForShellOldStyle(arg);
diff --git a/Source/cmCustomCommandGenerator.h b/Source/cmCustomCommandGenerator.h
index 23cc596..286aaf3 100644
--- a/Source/cmCustomCommandGenerator.h
+++ b/Source/cmCustomCommandGenerator.h
@@ -3,6 +3,7 @@
 #ifndef cmCustomCommandGenerator_h
 #define cmCustomCommandGenerator_h
 
+#include "cmCustomCommandLines.h"
 #include <cmConfigure.h> // IWYU pragma: keep
 
 #include <string>
@@ -22,6 +23,10 @@ class cmCustomCommandGenerator
   cmGeneratorExpression* GE;
   mutable bool DependsDone;
   mutable std::vector<std::string> Depends;
+  cmCustomCommandLines CommandLines;
+
+  const char* GetCrossCompilingEmulator(unsigned int c) const;
+  const char* GetArgv0Location(unsigned int c) const;
 
 public:
   cmCustomCommandGenerator(cmCustomCommand const& cc,
@@ -30,7 +35,6 @@ public:
   cmCustomCommand const& GetCC() const { return this->CC; }
   unsigned int GetNumberOfCommands() const;
   std::string GetCommand(unsigned int c) const;
-  bool UseCrossCompilingEmulator(unsigned int c) const;
   void AppendArguments(unsigned int c, std::string& cmd) const;
   const char* GetComment() const;
   std::string GetWorkingDirectory() const;
diff --git a/Source/cmDefinePropertyCommand.cxx b/Source/cmDefinePropertyCommand.cxx
index 8800363..9a097f3 100644
--- a/Source/cmDefinePropertyCommand.cxx
+++ b/Source/cmDefinePropertyCommand.cxx
@@ -2,8 +2,13 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmDefinePropertyCommand.h"
 
+#include <sstream>
+
+#include "cmMakefile.h"
+#include "cmProperty.h"
 #include "cmState.h"
-#include "cmake.h"
+
+class cmExecutionStatus;
 
 bool cmDefinePropertyCommand::InitialPass(std::vector<std::string> const& args,
                                           cmExecutionStatus&)
diff --git a/Source/cmDefinePropertyCommand.h b/Source/cmDefinePropertyCommand.h
index f494123..02e5b88 100644
--- a/Source/cmDefinePropertyCommand.h
+++ b/Source/cmDefinePropertyCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmDefinesPropertyCommand_h
 #define cmDefinesPropertyCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 class cmDefinePropertyCommand : public cmCommand
 {
 public:
@@ -22,8 +28,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "define_property"; }
 
-  cmTypeMacro(cmDefinePropertyCommand, cmCommand);
-
 private:
   std::string PropertyName;
   std::string BriefDocs;
diff --git a/Source/cmDefinitions.cxx b/Source/cmDefinitions.cxx
index 0b459f9..47fe76a 100644
--- a/Source/cmDefinitions.cxx
+++ b/Source/cmDefinitions.cxx
@@ -3,6 +3,7 @@
 #include "cmDefinitions.h"
 
 #include <assert.h>
+#include <cmConfigure.h>
 #include <set>
 #include <utility>
 
diff --git a/Source/cmDefinitions.h b/Source/cmDefinitions.h
index 569b3a2..ad40665 100644
--- a/Source/cmDefinitions.h
+++ b/Source/cmDefinitions.h
@@ -3,22 +3,13 @@
 #ifndef cmDefinitions_h
 #define cmDefinitions_h
 
-#include <cmConfigure.h>
-
-#include "cmLinkedTree.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <string>
 #include <vector>
 
-#if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX_UNORDERED_MAP
-#include <unordered_map>
-#else
-#include "cmsys/hash_map.hxx"
-#endif
-#else
-#include <map>
-#endif
+#include "cmLinkedTree.h"
+#include "cm_unordered_map.hxx"
 
 /** \class cmDefinitions
  * \brief Store a scope of variable definitions for CMake language.
@@ -85,15 +76,7 @@ private:
   };
   static Def NoDef;
 
-#if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX_UNORDERED_MAP
-  typedef std::unordered_map<std::string, Def> MapType;
-#else
-  typedef cmsys::hash_map<std::string, Def> MapType;
-#endif
-#else
-  typedef std::map<std::string, Def> MapType;
-#endif
+  typedef CM_UNORDERED_MAP<std::string, Def> MapType;
   MapType Map;
 
   static Def const& GetInternal(const std::string& key, StackIter begin,
diff --git a/Source/cmDependsC.cxx b/Source/cmDependsC.cxx
index 84ab072..9d4b9cc 100644
--- a/Source/cmDependsC.cxx
+++ b/Source/cmDependsC.cxx
@@ -2,18 +2,17 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmDependsC.h"
 
+#include <cmsys/FStream.hxx>
+#include <utility>
+
 #include "cmAlgorithms.h"
 #include "cmFileTimeComparison.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
-#include "cmOutputConverter.h"
 #include "cmSystemTools.h"
 
-#include <cmsys/FStream.hxx>
-#include <utility>
-
 #define INCLUDE_REGEX_LINE                                                    \
-  "^[ \t]*#[ \t]*(include|import)[ \t]*[<\"]([^\">]+)([\">])"
+  "^[ \t]*[#%][ \t]*(include|import)[ \t]*[<\"]([^\">]+)([\">])"
 
 #define INCLUDE_REGEX_LINE_MARKER "#IncludeRegexLine: "
 #define INCLUDE_REGEX_SCAN_MARKER "#IncludeRegexScan: "
@@ -421,7 +420,7 @@ void cmDependsC::SetupTransforms()
   if (!this->TransformRules.empty()) {
     // Construct the regular expression to match lines to be
     // transformed.
-    std::string xform = "^([ \t]*#[ \t]*(include|import)[ \t]*)(";
+    std::string xform = "^([ \t]*[#%][ \t]*(include|import)[ \t]*)(";
     const char* sep = "";
     for (TransformRulesType::const_iterator tri = this->TransformRules.begin();
          tri != this->TransformRules.end(); ++tri) {
diff --git a/Source/cmDependsFortran.cxx b/Source/cmDependsFortran.cxx
index c1c8880..7927402 100644
--- a/Source/cmDependsFortran.cxx
+++ b/Source/cmDependsFortran.cxx
@@ -2,13 +2,6 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmDependsFortran.h"
 
-#include "cmFortranParser.h" /* Interface to parser object.  */
-#include "cmGeneratedFileStream.h"
-#include "cmLocalGenerator.h"
-#include "cmMakefile.h"
-#include "cmOutputConverter.h"
-#include "cmSystemTools.h"
-
 #include <assert.h>
 #include <cmsys/FStream.hxx>
 #include <iostream>
@@ -17,6 +10,15 @@
 #include <string.h>
 #include <utility>
 
+#include "cmFortranParser.h" /* Interface to parser object.  */
+#include "cmGeneratedFileStream.h"
+#include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmOutputConverter.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
+#include "cmSystemTools.h"
+
 // TODO: Test compiler for the case of the mod file.  Some always
 // use lower case and some always use upper case.  I do not know if any
 // use the case from the source code.
@@ -198,16 +200,13 @@ bool cmDependsFortran::Finalize(std::ostream& makeDepends,
       stamp += ".mod.stamp";
       fcStream << "\n";
       fcStream << "  \""
-               << this->LocalGenerator->ConvertToRelativePath(currentBinDir,
-                                                              mod_lower)
+               << this->MaybeConvertToRelativePath(currentBinDir, mod_lower)
                << "\"\n";
       fcStream << "  \""
-               << this->LocalGenerator->ConvertToRelativePath(currentBinDir,
-                                                              mod_upper)
+               << this->MaybeConvertToRelativePath(currentBinDir, mod_upper)
                << "\"\n";
       fcStream << "  \""
-               << this->LocalGenerator->ConvertToRelativePath(currentBinDir,
-                                                              stamp)
+               << this->MaybeConvertToRelativePath(currentBinDir, stamp)
                << "\"\n";
     }
     fcStream << "  )\n";
@@ -323,17 +322,16 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
 
   // Write the include dependencies to the output stream.
   std::string binDir = this->LocalGenerator->GetBinaryDirectory();
-  std::string obj_i = this->LocalGenerator->ConvertToRelativePath(binDir, obj);
+  std::string obj_i = this->MaybeConvertToRelativePath(binDir, obj);
   std::string obj_m = cmSystemTools::ConvertToOutputPath(obj_i.c_str());
   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_m << ": "
-      << cmSystemTools::ConvertToOutputPath(
-           this->LocalGenerator->ConvertToRelativePath(binDir, *i).c_str())
-      << std::endl;
+    makeDepends << obj_m << ": "
+                << cmSystemTools::ConvertToOutputPath(
+                     this->MaybeConvertToRelativePath(binDir, *i).c_str())
+                << std::endl;
     internalDepends << " " << *i << std::endl;
   }
   makeDepends << std::endl;
@@ -359,7 +357,7 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
       proxy += *i;
       proxy += ".mod.proxy";
       proxy = cmSystemTools::ConvertToOutputPath(
-        this->LocalGenerator->ConvertToRelativePath(binDir, proxy).c_str());
+        this->MaybeConvertToRelativePath(binDir, proxy).c_str());
 
       // since we require some things add them to our list of requirements
       makeDepends << obj_m << ".requires: " << proxy << std::endl;
@@ -375,8 +373,7 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
     if (!required->second.empty()) {
       // This module is known.  Depend on its timestamp file.
       std::string stampFile = cmSystemTools::ConvertToOutputPath(
-        this->LocalGenerator->ConvertToRelativePath(binDir, required->second)
-          .c_str());
+        this->MaybeConvertToRelativePath(binDir, required->second).c_str());
       makeDepends << obj_m << ": " << stampFile << "\n";
     } else {
       // This module is not known to CMake.  Try to locate it where
@@ -384,7 +381,7 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
       std::string module;
       if (this->FindModule(*i, module)) {
         module = cmSystemTools::ConvertToOutputPath(
-          this->LocalGenerator->ConvertToRelativePath(binDir, module).c_str());
+          this->MaybeConvertToRelativePath(binDir, module).c_str());
         makeDepends << obj_m << ": " << module << "\n";
       }
     }
@@ -398,7 +395,7 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
     proxy += *i;
     proxy += ".mod.proxy";
     proxy = cmSystemTools::ConvertToOutputPath(
-      this->LocalGenerator->ConvertToRelativePath(binDir, proxy).c_str());
+      this->MaybeConvertToRelativePath(binDir, proxy).c_str());
     makeDepends << proxy << ": " << obj_m << ".provides" << std::endl;
   }
 
@@ -420,14 +417,14 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
       modFile += "/";
       modFile += *i;
       modFile = this->LocalGenerator->ConvertToOutputFormat(
-        this->LocalGenerator->ConvertToRelativePath(binDir, modFile),
+        this->MaybeConvertToRelativePath(binDir, modFile),
         cmOutputConverter::SHELL);
       std::string stampFile = stamp_dir;
       stampFile += "/";
       stampFile += m;
       stampFile += ".mod.stamp";
       stampFile = this->LocalGenerator->ConvertToOutputFormat(
-        this->LocalGenerator->ConvertToRelativePath(binDir, stampFile),
+        this->MaybeConvertToRelativePath(binDir, stampFile),
         cmOutputConverter::SHELL);
       makeDepends << "\t$(CMAKE_COMMAND) -E cmake_copy_f90_mod " << modFile
                   << " " << stampFile;
@@ -448,7 +445,7 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
     std::string driver = this->TargetDirectory;
     driver += "/build";
     driver = cmSystemTools::ConvertToOutputPath(
-      this->LocalGenerator->ConvertToRelativePath(binDir, driver).c_str());
+      this->MaybeConvertToRelativePath(binDir, driver).c_str());
     makeDepends << driver << ": " << obj_m << ".provides.build\n";
   }
 
@@ -708,3 +705,13 @@ bool cmDependsFortran::ModulesDiffer(const char* modFile,
   // content.
   return cmFortranStreamsDiffer(finModFile, finStampFile);
 }
+
+std::string cmDependsFortran::MaybeConvertToRelativePath(
+  std::string const& base, std::string const& path)
+{
+  if (!cmOutputConverter::ContainedInDirectory(
+        base, path, this->LocalGenerator->GetStateSnapshot().GetDirectory())) {
+    return path;
+  }
+  return cmOutputConverter::ForceToRelativePath(base, path);
+}
diff --git a/Source/cmDependsFortran.h b/Source/cmDependsFortran.h
index 8d347f4..90b82d4 100644
--- a/Source/cmDependsFortran.h
+++ b/Source/cmDependsFortran.h
@@ -78,6 +78,9 @@ protected:
 private:
   cmDependsFortran(cmDependsFortran const&); // Purposely not implemented.
   void operator=(cmDependsFortran const&);   // Purposely not implemented.
+
+  std::string MaybeConvertToRelativePath(std::string const& base,
+                                         std::string const& path);
 };
 
 #endif
diff --git a/Source/cmDependsJavaLexer.cxx b/Source/cmDependsJavaLexer.cxx
index aa4c4e0..8159f47 100644
--- a/Source/cmDependsJavaLexer.cxx
+++ b/Source/cmDependsJavaLexer.cxx
@@ -1,18 +1,17 @@
-#include <cmConfigure.h>
-
-#include "cmStandardIncludes.h"
+#include "cmStandardLexer.h"
 #line 2 "cmDependsJavaLexer.cxx"
 
 #line 4 "cmDependsJavaLexer.cxx"
 
+#define FLEXINT_H 1
 #define  YY_INT_ALIGNED short int
 
 /* A lexical scanner generated by flex */
 
 #define FLEX_SCANNER
 #define YY_FLEX_MAJOR_VERSION 2
-#define YY_FLEX_MINOR_VERSION 5
-#define YY_FLEX_SUBMINOR_VERSION 31
+#define YY_FLEX_MINOR_VERSION 6
+#define YY_FLEX_SUBMINOR_VERSION 1
 #if YY_FLEX_SUBMINOR_VERSION > 0
 #define FLEX_BETA
 #endif
@@ -25,10 +24,6 @@
 #include <errno.h>
 #include <stdlib.h>
 
-#if defined(__BEOS__) || defined (__HAIKU__)
-#include <unistd.h>   /* prevents a conflict with a #define later on... */
-#endif
-
 /* end standard C headers. */
 
 /* flex integer type definitions */
@@ -38,7 +33,15 @@
 
 /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
 
-#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L
+#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+
+/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
+ * if you want the limit (max/min) macros for int types.
+ */
+#ifndef __STDC_LIMIT_MACROS
+#define __STDC_LIMIT_MACROS 1
+#endif
+
 #include <inttypes.h>
 typedef int8_t flex_int8_t;
 typedef uint8_t flex_uint8_t;
@@ -53,7 +56,6 @@ typedef int flex_int32_t;
 typedef unsigned char flex_uint8_t;
 typedef unsigned short int flex_uint16_t;
 typedef unsigned int flex_uint32_t;
-#endif /* ! C99 */
 
 /* Limits of integral types. */
 #ifndef INT8_MIN
@@ -84,26 +86,17 @@ typedef unsigned int flex_uint32_t;
 #define UINT32_MAX             (4294967295U)
 #endif
 
-#endif /* ! FLEXINT_H */
-
-#ifdef __cplusplus
-
-/* The "const" storage-class-modifier is valid. */
-#define YY_USE_CONST
-
-#else  /* ! __cplusplus */
-
-#if __STDC__
-
-#define YY_USE_CONST
+#endif /* ! C99 */
 
-#endif  /* __STDC__ */
-#endif  /* ! __cplusplus */
+#endif /* ! FLEXINT_H */
 
-#ifdef YY_USE_CONST
+/* TODO: this is always defined, so inline it */
 #define yyconst const
+
+#if defined(__GNUC__) && __GNUC__ >= 3
+#define yynoreturn __attribute__((__noreturn__))
 #else
-#define yyconst
+#define yynoreturn
 #endif
 
 /* Returned upon end-of-file. */
@@ -133,8 +126,6 @@ typedef void* yyscan_t;
 #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column)
 #define yy_flex_debug yyg->yy_flex_debug_r
 
-int cmDependsJava_yylex_init (yyscan_t* scanner);
-
 /* Enter a start condition.  This macro really ought to take a parameter,
  * but we do it the disgusting crufty way forced on us by the ()-less
  * definition of BEGIN.
@@ -158,107 +149,117 @@ int cmDependsJava_yylex_init (yyscan_t* scanner);
 
 /* Size of default input buffer. */
 #ifndef YY_BUF_SIZE
+#ifdef __ia64__
+/* On IA-64, the buffer size is 16k, not 8k.
+ * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case.
+ * Ditto for the __ia64__ case accordingly.
+ */
+#define YY_BUF_SIZE 32768
+#else
 #define YY_BUF_SIZE 16384
+#endif /* __ia64__ */
 #endif
 
+/* The state buf must be large enough to hold one state per character in the main buffer.
+ */
+#define YY_STATE_BUF_SIZE   ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
+
 #ifndef YY_TYPEDEF_YY_BUFFER_STATE
 #define YY_TYPEDEF_YY_BUFFER_STATE
 typedef struct yy_buffer_state *YY_BUFFER_STATE;
 #endif
 
+#ifndef YY_TYPEDEF_YY_SIZE_T
+#define YY_TYPEDEF_YY_SIZE_T
+typedef size_t yy_size_t;
+#endif
+
 #define EOB_ACT_CONTINUE_SCAN 0
 #define EOB_ACT_END_OF_FILE 1
 #define EOB_ACT_LAST_MATCH 2
 
     #define YY_LESS_LINENO(n)
+    #define YY_LINENO_REWIND_TO(ptr)
 
 /* Return all but the first "n" matched characters back to the input stream. */
 #define yyless(n) \
-  do \
-    { \
-    /* Undo effects of setting up yytext. */ \
+	do \
+		{ \
+		/* Undo effects of setting up yytext. */ \
         int yyless_macro_arg = (n); \
         YY_LESS_LINENO(yyless_macro_arg);\
-    *yy_cp = yyg->yy_hold_char; \
-    YY_RESTORE_YY_MORE_OFFSET \
-    yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
-    YY_DO_BEFORE_ACTION; /* set up yytext again */ \
-    } \
-  while ( 0 )
-
-/* The following is because we cannot portably get our hands on size_t
- * (without autoconf's help, which isn't available because we want
- * flex-generated scanners to compile on their own).
- */
+		*yy_cp = yyg->yy_hold_char; \
+		YY_RESTORE_YY_MORE_OFFSET \
+		yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
+		YY_DO_BEFORE_ACTION; /* set up yytext again */ \
+		} \
+	while ( 0 )
 
-#ifndef YY_TYPEDEF_YY_SIZE_T
-#define YY_TYPEDEF_YY_SIZE_T
-typedef unsigned int yy_size_t;
-#endif
+#define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner )
 
 #ifndef YY_STRUCT_YY_BUFFER_STATE
 #define YY_STRUCT_YY_BUFFER_STATE
 struct yy_buffer_state
-  {
-  FILE *yy_input_file;
-
-  char *yy_ch_buf;    /* input buffer */
-  char *yy_buf_pos;    /* current position in input buffer */
-
-  /* Size of input buffer in bytes, not including room for EOB
-   * characters.
-   */
-  yy_size_t yy_buf_size;
-
-  /* Number of characters read into yy_ch_buf, not including EOB
-   * characters.
-   */
-  int yy_n_chars;
-
-  /* Whether we "own" the buffer - i.e., we know we created it,
-   * and can realloc() it to grow it, and should free() it to
-   * delete it.
-   */
-  int yy_is_our_buffer;
-
-  /* Whether this is an "interactive" input source; if so, and
-   * if we're using stdio for input, then we want to use getc()
-   * instead of fread(), to make sure we stop fetching input after
-   * each newline.
-   */
-  int yy_is_interactive;
-
-  /* Whether we're considered to be at the beginning of a line.
-   * If so, '^' rules will be active on the next match, otherwise
-   * not.
-   */
-  int yy_at_bol;
+	{
+	FILE *yy_input_file;
+
+	char *yy_ch_buf;		/* input buffer */
+	char *yy_buf_pos;		/* current position in input buffer */
+
+	/* Size of input buffer in bytes, not including room for EOB
+	 * characters.
+	 */
+	int yy_buf_size;
+
+	/* Number of characters read into yy_ch_buf, not including EOB
+	 * characters.
+	 */
+	int yy_n_chars;
+
+	/* Whether we "own" the buffer - i.e., we know we created it,
+	 * and can realloc() it to grow it, and should free() it to
+	 * delete it.
+	 */
+	int yy_is_our_buffer;
+
+	/* Whether this is an "interactive" input source; if so, and
+	 * if we're using stdio for input, then we want to use getc()
+	 * instead of fread(), to make sure we stop fetching input after
+	 * each newline.
+	 */
+	int yy_is_interactive;
+
+	/* Whether we're considered to be at the beginning of a line.
+	 * If so, '^' rules will be active on the next match, otherwise
+	 * not.
+	 */
+	int yy_at_bol;
 
     int yy_bs_lineno; /**< The line count. */
     int yy_bs_column; /**< The column count. */
 
-  /* Whether to try to fill the input buffer when we reach the
-   * end of it.
-   */
-  int yy_fill_buffer;
+	/* Whether to try to fill the input buffer when we reach the
+	 * end of it.
+	 */
+	int yy_fill_buffer;
 
-  int yy_buffer_status;
+	int yy_buffer_status;
 
 #define YY_BUFFER_NEW 0
 #define YY_BUFFER_NORMAL 1
-  /* When an EOF's been seen but there's still some text to process
-   * then we mark the buffer as YY_EOF_PENDING, to indicate that we
-   * shouldn't try reading from the input source any more.  We might
-   * still have a bunch of tokens to match, though, because of
-   * possible backing-up.
-   *
-   * When we actually see the EOF, we change the status to "new"
-   * (via cmDependsJava_yyrestart()), so that the user can continue scanning by
-   * just pointing yyin at a new input file.
-   */
+	/* When an EOF's been seen but there's still some text to process
+	 * then we mark the buffer as YY_EOF_PENDING, to indicate that we
+	 * shouldn't try reading from the input source any more.  We might
+	 * still have a bunch of tokens to match, though, because of
+	 * possible backing-up.
+	 *
+	 * When we actually see the EOF, we change the status to "new"
+	 * (via cmDependsJava_yyrestart()), so that the user can continue scanning by
+	 * just pointing yyin at a new input file.
+	 */
 #define YY_BUFFER_EOF_PENDING 2
 
-  };
+	};
 #endif /* !YY_STRUCT_YY_BUFFER_STATE */
 
 /* We provide macros for accessing buffer states in case in the
@@ -301,30 +302,30 @@ void cmDependsJava_yyfree (void * ,yyscan_t yyscanner );
 #define yy_new_buffer cmDependsJava_yy_create_buffer
 
 #define yy_set_interactive(is_interactive) \
-  { \
-  if ( ! YY_CURRENT_BUFFER ){ \
+	{ \
+	if ( ! YY_CURRENT_BUFFER ){ \
         cmDependsJava_yyensure_buffer_stack (yyscanner); \
-    YY_CURRENT_BUFFER_LVALUE =    \
+		YY_CURRENT_BUFFER_LVALUE =    \
             cmDependsJava_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
-  } \
-  YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
-  }
+	} \
+	YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
+	}
 
 #define yy_set_bol(at_bol) \
-  { \
-  if ( ! YY_CURRENT_BUFFER ){\
+	{ \
+	if ( ! YY_CURRENT_BUFFER ){\
         cmDependsJava_yyensure_buffer_stack (yyscanner); \
-    YY_CURRENT_BUFFER_LVALUE =    \
+		YY_CURRENT_BUFFER_LVALUE =    \
             cmDependsJava_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
-  } \
-  YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
-  }
+	} \
+	YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
+	}
 
 #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
 
 /* Begin user sect3 */
 
-#define cmDependsJava_yywrap(n) 1
+#define cmDependsJava_yywrap(yyscanner) (/*CONSTCOND*/1)
 #define YY_SKIP_YYWRAP
 
 typedef unsigned char YY_CHAR;
@@ -336,27 +337,27 @@ typedef int yy_state_type;
 static yy_state_type yy_get_previous_state (yyscan_t yyscanner );
 static yy_state_type yy_try_NUL_trans (yy_state_type current_state  ,yyscan_t yyscanner);
 static int yy_get_next_buffer (yyscan_t yyscanner );
-static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner );
+static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );
 
 /* Done after the current pattern has been matched and before the
  * corresponding action - sets up yytext.
  */
 #define YY_DO_BEFORE_ACTION \
-  yyg->yytext_ptr = yy_bp; \
-  yyleng = (size_t) (yy_cp - yy_bp); \
-  yyg->yy_hold_char = *yy_cp; \
-  *yy_cp = '\0'; \
-  yyg->yy_c_buf_p = yy_cp;
+	yyg->yytext_ptr = yy_bp; \
+	yyleng = (int) (yy_cp - yy_bp); \
+	yyg->yy_hold_char = *yy_cp; \
+	*yy_cp = '\0'; \
+	yyg->yy_c_buf_p = yy_cp;
 
 #define YY_NUM_RULES 111
 #define YY_END_OF_BUFFER 112
 /* This struct is not used in this scanner,
    but its presence is necessary. */
 struct yy_trans_info
-  {
-  flex_int32_t yy_verify;
-  flex_int32_t yy_nxt;
-  };
+	{
+	flex_int32_t yy_verify;
+	flex_int32_t yy_nxt;
+	};
 static yyconst flex_int16_t yy_accept[327] =
     {   0,
         0,    0,    0,    0,    0,    0,  112,  110,  109,  109,
@@ -397,7 +398,7 @@ static yyconst flex_int16_t yy_accept[327] =
        27,   29,  107,  107,   45,    0
     } ;
 
-static yyconst flex_int32_t yy_ec[256] =
+static yyconst YY_CHAR yy_ec[256] =
     {   0,
         1,    1,    1,    1,    1,    1,    1,    1,    2,    3,
         1,    2,    2,    1,    1,    1,    1,    1,    1,    1,
@@ -429,7 +430,7 @@ static yyconst flex_int32_t yy_ec[256] =
         1,    1,    1,    1,    1
     } ;
 
-static yyconst flex_int32_t yy_meta[65] =
+static yyconst YY_CHAR yy_meta[65] =
     {   0,
         1,    1,    1,    1,    1,    1,    1,    1,    2,    1,
         1,    1,    1,    1,    1,    1,    1,    3,    3,    3,
@@ -440,7 +441,7 @@ static yyconst flex_int32_t yy_meta[65] =
         1,    1,    1,    1
     } ;
 
-static yyconst flex_int16_t yy_base[334] =
+static yyconst flex_uint16_t yy_base[334] =
     {   0,
         0,    0,  401,  400,   62,   63,  411,  414,  414,  414,
       386,  414,  414,  385,   61,  374,  414,  414,  383,   57,
@@ -522,7 +523,7 @@ static yyconst flex_int16_t yy_def[334] =
       326,  326,  326
     } ;
 
-static yyconst flex_int16_t yy_nxt[479] =
+static yyconst flex_uint16_t yy_nxt[479] =
     {   0,
         8,    9,   10,   11,   12,   13,   14,   15,   16,   17,
        18,   19,   20,   21,   22,   23,   24,   25,   26,   26,
@@ -647,28 +648,23 @@ static yyconst flex_int16_t yy_chk[479] =
    file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
-This file must be translated to C and modified to build everywhere.
-
-Run flex like this:
+This file must be translated to C++ and modified to build everywhere.
 
-  flex --prefix=cmDependsJava_yy --header-file=cmDependsJavaLexer.h -ocmDependsJavaLexer.cxx cmDependsJavaLexer.in.l
+Run flex >= 2.6 like this:
 
-Modify cmDependsJavaLexer.c:
-  - remove TABs
-  - remove "yyscanner" argument from these methods:
-      yy_fatal_error, cmDependsJava_yyalloc, cmDependsJava_yyrealloc, cmDependsJava_yyfree
-  - remove all YY_BREAK lines occurring right after return statements
-  - change while ( 1 ) to for(;;)
+  flex --nounistd -DFLEXINT_H --prefix=cmDependsJava_yy --header-file=cmDependsJavaLexer.h -ocmDependsJavaLexer.cxx cmDependsJavaLexer.in.l
 
-Modify cmDependsJavaLexer.h:
-  - remove TABs
-  - remove the yy_init_globals function
-  - remove the block that includes unistd.h
-  - remove #line directives (avoids bogus warning on old Sun)
+Modify cmDependsJavaLexer.cxx:
+  - remove trailing whitespace: sed -i 's/\s*$//' cmDependsJavaLexer.h cmDependsJavaLexer.cxx
+  - remove blank lines at end of file
+  - #include "cmStandardLexer.h" at the top
+  - add cast in cmDependsJava_yy_scan_bytes for loop condition of _yybytes_len to size_t
 
 */
 
-#include "cmStandardLexer.h"
+/* IWYU pragma: no_forward_declare yyguts_t */
+
+#include <iostream>
 
 #include "cmDependsJavaParserHelper.h"
 
@@ -687,20 +683,12 @@ Modify cmDependsJavaLexer.h:
 /*--------------------------------------------------------------------------*/
 
 
-#line 721 "cmDependsJavaLexer.cxx"
+#line 686 "cmDependsJavaLexer.cxx"
 
 #define INITIAL 0
 #define comment 1
 #define string 2
 
-#ifndef YY_NO_UNISTD_H
-/* Special case for "unistd.h", since it is non-ANSI. We include it way
- * down here because we want the user's section 1 to have been scanned first.
- * The user has a chance to override it with an option.
- */
-#include <unistd.h>
-#endif
-
 #ifndef YY_EXTRA_TYPE
 #define YY_EXTRA_TYPE void *
 #endif
@@ -739,6 +727,12 @@ struct yyguts_t
 
     }; /* end struct yyguts_t */
 
+static int yy_init_globals (yyscan_t yyscanner );
+
+int cmDependsJava_yylex_init (yyscan_t* scanner);
+
+int cmDependsJava_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
+
 /* Accessor methods to globals.
    These are made visible to non-reentrant scanners for convenience. */
 
@@ -754,19 +748,23 @@ void cmDependsJava_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner )
 
 FILE *cmDependsJava_yyget_in (yyscan_t yyscanner );
 
-void cmDependsJava_yyset_in  (FILE * in_str ,yyscan_t yyscanner );
+void cmDependsJava_yyset_in  (FILE * _in_str ,yyscan_t yyscanner );
 
 FILE *cmDependsJava_yyget_out (yyscan_t yyscanner );
 
-void cmDependsJava_yyset_out  (FILE * out_str ,yyscan_t yyscanner );
+void cmDependsJava_yyset_out  (FILE * _out_str ,yyscan_t yyscanner );
 
-int cmDependsJava_yyget_leng (yyscan_t yyscanner );
+			int cmDependsJava_yyget_leng (yyscan_t yyscanner );
 
 char *cmDependsJava_yyget_text (yyscan_t yyscanner );
 
 int cmDependsJava_yyget_lineno (yyscan_t yyscanner );
 
-void cmDependsJava_yyset_lineno (int line_number ,yyscan_t yyscanner );
+void cmDependsJava_yyset_lineno (int _line_number ,yyscan_t yyscanner );
+
+int cmDependsJava_yyget_column  (yyscan_t yyscanner );
+
+void cmDependsJava_yyset_column (int _column_no ,yyscan_t yyscanner );
 
 /* Macros after this point can all be overridden by user definitions in
  * section 1.
@@ -780,6 +778,12 @@ extern int cmDependsJava_yywrap (yyscan_t yyscanner );
 #endif
 #endif
 
+#ifndef YY_NO_UNPUT
+
+    static void yyunput (int c,char *buf_ptr  ,yyscan_t yyscanner);
+
+#endif
+
 #ifndef yytext_ptr
 static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
 #endif
@@ -800,7 +804,12 @@ static int input (yyscan_t yyscanner );
 
 /* Amount of stuff to slurp up with each read. */
 #ifndef YY_READ_BUF_SIZE
+#ifdef __ia64__
+/* On IA-64, the buffer size is 16k, not 8k */
+#define YY_READ_BUF_SIZE 16384
+#else
 #define YY_READ_BUF_SIZE 8192
+#endif /* __ia64__ */
 #endif
 
 /* Copy whatever the last rule matched to the standard output. */
@@ -808,7 +817,7 @@ static int input (yyscan_t yyscanner );
 /* This used to be an fputs(), but since the string might contain NUL's,
  * we now use fwrite().
  */
-#define ECHO (void) fwrite( yytext, yyleng, 1, yyout )
+#define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0)
 #endif
 
 /* Gets input and stuffs it into "buf".  number of characters read, or YY_NULL,
@@ -816,33 +825,33 @@ static int input (yyscan_t yyscanner );
  */
 #ifndef YY_INPUT
 #define YY_INPUT(buf,result,max_size) \
-  if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
-    { \
-    int c = '*'; \
-    size_t n; \
-    for ( n = 0; n < max_size && \
-           (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
-      buf[n] = (char) c; \
-    if ( c == '\n' ) \
-      buf[n++] = (char) c; \
-    if ( c == EOF && ferror( yyin ) ) \
-      YY_FATAL_ERROR( "input in flex scanner failed" ); \
-    result = n; \
-    } \
-  else \
-    { \
-    errno=0; \
-    while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
-      { \
-      if( errno != EINTR) \
-        { \
-        YY_FATAL_ERROR( "input in flex scanner failed" ); \
-        break; \
-        } \
-      errno=0; \
-      clearerr(yyin); \
-      } \
-    }\
+	if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
+		{ \
+		int c = '*'; \
+		size_t n; \
+		for ( n = 0; n < max_size && \
+			     (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
+			buf[n] = (char) c; \
+		if ( c == '\n' ) \
+			buf[n++] = (char) c; \
+		if ( c == EOF && ferror( yyin ) ) \
+			YY_FATAL_ERROR( "input in flex scanner failed" ); \
+		result = n; \
+		} \
+	else \
+		{ \
+		errno=0; \
+		while ( (result = (int) fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
+			{ \
+			if( errno != EINTR) \
+				{ \
+				YY_FATAL_ERROR( "input in flex scanner failed" ); \
+				break; \
+				} \
+			errno=0; \
+			clearerr(yyin); \
+			} \
+		}\
 \
 
 #endif
@@ -887,897 +896,1052 @@ extern int cmDependsJava_yylex (yyscan_t yyscanner);
 
 /* Code executed at the end of each rule. */
 #ifndef YY_BREAK
-#define YY_BREAK break;
+#define YY_BREAK /*LINTED*/break;
 #endif
 
 #define YY_RULE_SETUP \
-  YY_USER_ACTION
+	YY_USER_ACTION
 
 /** The main scanner function which does all the work.
  */
 YY_DECL
 {
-  yy_state_type yy_current_state;
-  char *yy_cp, *yy_bp;
-  int yy_act;
+	yy_state_type yy_current_state;
+	char *yy_cp, *yy_bp;
+	int yy_act;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-#line 88 "cmDependsJavaLexer.in.l"
-
-#line 940 "cmDependsJavaLexer.cxx"
-
-  if ( yyg->yy_init )
-    {
-    yyg->yy_init = 0;
+	if ( !yyg->yy_init )
+		{
+		yyg->yy_init = 1;
 
 #ifdef YY_USER_INIT
-    YY_USER_INIT;
+		YY_USER_INIT;
 #endif
 
-    if ( ! yyg->yy_start )
-      yyg->yy_start = 1;  /* first start state */
+		if ( ! yyg->yy_start )
+			yyg->yy_start = 1;	/* first start state */
 
-    if ( ! yyin )
-      yyin = stdin;
+		if ( ! yyin )
+			yyin = stdin;
 
-    if ( ! yyout )
-      yyout = stdout;
+		if ( ! yyout )
+			yyout = stdout;
 
-    if ( ! YY_CURRENT_BUFFER ) {
-      cmDependsJava_yyensure_buffer_stack (yyscanner);
-      YY_CURRENT_BUFFER_LVALUE =
-        cmDependsJava_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
-    }
+		if ( ! YY_CURRENT_BUFFER ) {
+			cmDependsJava_yyensure_buffer_stack (yyscanner);
+			YY_CURRENT_BUFFER_LVALUE =
+				cmDependsJava_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
+		}
 
-    cmDependsJava_yy_load_buffer_state(yyscanner );
-    }
+		cmDependsJava_yy_load_buffer_state(yyscanner );
+		}
 
-  for(;;)    /* loops until end-of-file is reached */
-    {
-    yy_cp = yyg->yy_c_buf_p;
+	{
+#line 48 "cmDependsJavaLexer.in.l"
 
-    /* Support of yytext. */
-    *yy_cp = yyg->yy_hold_char;
+#line 943 "cmDependsJavaLexer.cxx"
 
-    /* yy_bp points to the position in yy_ch_buf of the start of
-     * the current run.
-     */
-    yy_bp = yy_cp;
+	while ( /*CONSTCOND*/1 )		/* loops until end-of-file is reached */
+		{
+		yy_cp = yyg->yy_c_buf_p;
+
+		/* Support of yytext. */
+		*yy_cp = yyg->yy_hold_char;
 
-    yy_current_state = yyg->yy_start;
+		/* yy_bp points to the position in yy_ch_buf of the start of
+		 * the current run.
+		 */
+		yy_bp = yy_cp;
+
+		yy_current_state = yyg->yy_start;
 yy_match:
-    do
-      {
-      YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
-      if ( yy_accept[yy_current_state] )
-        {
-        yyg->yy_last_accepting_state = yy_current_state;
-        yyg->yy_last_accepting_cpos = yy_cp;
-        }
-      while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
-        {
-        yy_current_state = (int) yy_def[yy_current_state];
-        if ( yy_current_state >= 327 )
-          yy_c = yy_meta[(unsigned int) yy_c];
-        }
-      yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-      ++yy_cp;
-      }
-    while ( yy_base[yy_current_state] != 414 );
+		do
+			{
+			YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ;
+			if ( yy_accept[yy_current_state] )
+				{
+				yyg->yy_last_accepting_state = yy_current_state;
+				yyg->yy_last_accepting_cpos = yy_cp;
+				}
+			while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+				{
+				yy_current_state = (int) yy_def[yy_current_state];
+				if ( yy_current_state >= 327 )
+					yy_c = yy_meta[(unsigned int) yy_c];
+				}
+			yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+			++yy_cp;
+			}
+		while ( yy_base[yy_current_state] != 414 );
 
 yy_find_action:
-    yy_act = yy_accept[yy_current_state];
-    if ( yy_act == 0 )
-      { /* have to back up */
-      yy_cp = yyg->yy_last_accepting_cpos;
-      yy_current_state = yyg->yy_last_accepting_state;
-      yy_act = yy_accept[yy_current_state];
-      }
-
-    YY_DO_BEFORE_ACTION;
-
-do_action:  /* This label is used only to access EOF actions. */
-
-    switch ( yy_act )
-  { /* beginning of action switch */
-      case 0: /* must back up */
-      /* undo the effects of YY_DO_BEFORE_ACTION */
-      *yy_cp = yyg->yy_hold_char;
-      yy_cp = yyg->yy_last_accepting_cpos;
-      yy_current_state = yyg->yy_last_accepting_state;
-      goto yy_find_action;
+		yy_act = yy_accept[yy_current_state];
+		if ( yy_act == 0 )
+			{ /* have to back up */
+			yy_cp = yyg->yy_last_accepting_cpos;
+			yy_current_state = yyg->yy_last_accepting_state;
+			yy_act = yy_accept[yy_current_state];
+			}
+
+		YY_DO_BEFORE_ACTION;
+
+do_action:	/* This label is used only to access EOF actions. */
+
+		switch ( yy_act )
+	{ /* beginning of action switch */
+			case 0: /* must back up */
+			/* undo the effects of YY_DO_BEFORE_ACTION */
+			*yy_cp = yyg->yy_hold_char;
+			yy_cp = yyg->yy_last_accepting_cpos;
+			yy_current_state = yyg->yy_last_accepting_state;
+			goto yy_find_action;
 
 case 1:
 YY_RULE_SETUP
-#line 89 "cmDependsJavaLexer.in.l"
+#line 49 "cmDependsJavaLexer.in.l"
 { BEGIN(comment); }
-  YY_BREAK
+	YY_BREAK
 case 2:
 YY_RULE_SETUP
-#line 90 "cmDependsJavaLexer.in.l"
+#line 50 "cmDependsJavaLexer.in.l"
 { BEGIN(INITIAL); }
-  YY_BREAK
+	YY_BREAK
 case 3:
 /* rule 3 can match eol */
 YY_RULE_SETUP
-#line 91 "cmDependsJavaLexer.in.l"
+#line 51 "cmDependsJavaLexer.in.l"
 {}
-  YY_BREAK
+	YY_BREAK
 case 4:
 YY_RULE_SETUP
-#line 93 "cmDependsJavaLexer.in.l"
+#line 53 "cmDependsJavaLexer.in.l"
 { BEGIN(string); }
-  YY_BREAK
+	YY_BREAK
 case 5:
 YY_RULE_SETUP
-#line 94 "cmDependsJavaLexer.in.l"
+#line 54 "cmDependsJavaLexer.in.l"
 { BEGIN(INITIAL); return jp_STRINGLITERAL; }
+	YY_BREAK
 case 6:
 YY_RULE_SETUP
-#line 95 "cmDependsJavaLexer.in.l"
+#line 55 "cmDependsJavaLexer.in.l"
 {}
-  YY_BREAK
+	YY_BREAK
 case 7:
 YY_RULE_SETUP
-#line 97 "cmDependsJavaLexer.in.l"
+#line 57 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_ABSTRACT; }
+	YY_BREAK
 case 8:
 YY_RULE_SETUP
-#line 98 "cmDependsJavaLexer.in.l"
+#line 58 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_ASSERT; }
+	YY_BREAK
 case 9:
 YY_RULE_SETUP
-#line 99 "cmDependsJavaLexer.in.l"
+#line 59 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_BOOLEAN_TYPE; }
+	YY_BREAK
 case 10:
 YY_RULE_SETUP
-#line 100 "cmDependsJavaLexer.in.l"
+#line 60 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_BREAK; }
+	YY_BREAK
 case 11:
 YY_RULE_SETUP
-#line 101 "cmDependsJavaLexer.in.l"
+#line 61 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_BYTE_TYPE; }
+	YY_BREAK
 case 12:
 YY_RULE_SETUP
-#line 102 "cmDependsJavaLexer.in.l"
+#line 62 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_CASE; }
+	YY_BREAK
 case 13:
 YY_RULE_SETUP
-#line 103 "cmDependsJavaLexer.in.l"
+#line 63 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_CATCH; }
+	YY_BREAK
 case 14:
 YY_RULE_SETUP
-#line 104 "cmDependsJavaLexer.in.l"
+#line 64 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_CHAR_TYPE; }
+	YY_BREAK
 case 15:
 YY_RULE_SETUP
-#line 105 "cmDependsJavaLexer.in.l"
+#line 65 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_CLASS; }
+	YY_BREAK
 case 16:
 YY_RULE_SETUP
-#line 106 "cmDependsJavaLexer.in.l"
+#line 66 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_CONTINUE; }
+	YY_BREAK
 case 17:
 YY_RULE_SETUP
-#line 107 "cmDependsJavaLexer.in.l"
+#line 67 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_DEFAULT; }
+	YY_BREAK
 case 18:
 YY_RULE_SETUP
-#line 108 "cmDependsJavaLexer.in.l"
+#line 68 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_DO; }
+	YY_BREAK
 case 19:
 YY_RULE_SETUP
-#line 109 "cmDependsJavaLexer.in.l"
+#line 69 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_DOUBLE_TYPE; }
+	YY_BREAK
 case 20:
 YY_RULE_SETUP
-#line 110 "cmDependsJavaLexer.in.l"
+#line 70 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_ELSE; }
+	YY_BREAK
 case 21:
 YY_RULE_SETUP
-#line 111 "cmDependsJavaLexer.in.l"
+#line 71 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_EXTENDS; }
+	YY_BREAK
 case 22:
 YY_RULE_SETUP
-#line 112 "cmDependsJavaLexer.in.l"
+#line 72 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_FINAL; }
+	YY_BREAK
 case 23:
 YY_RULE_SETUP
-#line 113 "cmDependsJavaLexer.in.l"
+#line 73 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_FINALLY; }
+	YY_BREAK
 case 24:
 YY_RULE_SETUP
-#line 114 "cmDependsJavaLexer.in.l"
+#line 74 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_FLOAT_TYPE; }
+	YY_BREAK
 case 25:
 YY_RULE_SETUP
-#line 115 "cmDependsJavaLexer.in.l"
+#line 75 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_FOR; }
+	YY_BREAK
 case 26:
 YY_RULE_SETUP
-#line 116 "cmDependsJavaLexer.in.l"
+#line 76 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_IF; }
+	YY_BREAK
 case 27:
 YY_RULE_SETUP
-#line 117 "cmDependsJavaLexer.in.l"
+#line 77 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_IMPLEMENTS; }
+	YY_BREAK
 case 28:
 YY_RULE_SETUP
-#line 118 "cmDependsJavaLexer.in.l"
+#line 78 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_IMPORT; }
+	YY_BREAK
 case 29:
 YY_RULE_SETUP
-#line 119 "cmDependsJavaLexer.in.l"
+#line 79 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_INSTANCEOF; }
+	YY_BREAK
 case 30:
 YY_RULE_SETUP
-#line 120 "cmDependsJavaLexer.in.l"
+#line 80 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_INT_TYPE; }
+	YY_BREAK
 case 31:
 YY_RULE_SETUP
-#line 121 "cmDependsJavaLexer.in.l"
+#line 81 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_INTERFACE; }
+	YY_BREAK
 case 32:
 YY_RULE_SETUP
-#line 122 "cmDependsJavaLexer.in.l"
+#line 82 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_LONG_TYPE; }
+	YY_BREAK
 case 33:
 YY_RULE_SETUP
-#line 123 "cmDependsJavaLexer.in.l"
+#line 83 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_NATIVE; }
+	YY_BREAK
 case 34:
 YY_RULE_SETUP
-#line 124 "cmDependsJavaLexer.in.l"
+#line 84 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_NEW; }
+	YY_BREAK
 case 35:
 YY_RULE_SETUP
-#line 125 "cmDependsJavaLexer.in.l"
+#line 85 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_PACKAGE; }
+	YY_BREAK
 case 36:
 YY_RULE_SETUP
-#line 126 "cmDependsJavaLexer.in.l"
+#line 86 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_PRIVATE; }
+	YY_BREAK
 case 37:
 YY_RULE_SETUP
-#line 127 "cmDependsJavaLexer.in.l"
+#line 87 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_PROTECTED; }
+	YY_BREAK
 case 38:
 YY_RULE_SETUP
-#line 128 "cmDependsJavaLexer.in.l"
+#line 88 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_PUBLIC; }
+	YY_BREAK
 case 39:
 YY_RULE_SETUP
-#line 129 "cmDependsJavaLexer.in.l"
+#line 89 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_RETURN; }
+	YY_BREAK
 case 40:
 YY_RULE_SETUP
-#line 130 "cmDependsJavaLexer.in.l"
+#line 90 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_SHORT_TYPE; }
+	YY_BREAK
 case 41:
 YY_RULE_SETUP
-#line 131 "cmDependsJavaLexer.in.l"
+#line 91 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_STATIC; }
+	YY_BREAK
 case 42:
 YY_RULE_SETUP
-#line 132 "cmDependsJavaLexer.in.l"
+#line 92 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_STRICTFP; }
+	YY_BREAK
 case 43:
 YY_RULE_SETUP
-#line 133 "cmDependsJavaLexer.in.l"
+#line 93 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_SUPER; }
+	YY_BREAK
 case 44:
 YY_RULE_SETUP
-#line 134 "cmDependsJavaLexer.in.l"
+#line 94 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_SWITCH; }
+	YY_BREAK
 case 45:
 YY_RULE_SETUP
-#line 135 "cmDependsJavaLexer.in.l"
+#line 95 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_SYNCHRONIZED; }
+	YY_BREAK
 case 46:
 YY_RULE_SETUP
-#line 136 "cmDependsJavaLexer.in.l"
+#line 96 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_THIS; }
+	YY_BREAK
 case 47:
 YY_RULE_SETUP
-#line 137 "cmDependsJavaLexer.in.l"
+#line 97 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_THROW; }
+	YY_BREAK
 case 48:
 YY_RULE_SETUP
-#line 138 "cmDependsJavaLexer.in.l"
+#line 98 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_THROWS; }
+	YY_BREAK
 case 49:
 YY_RULE_SETUP
-#line 139 "cmDependsJavaLexer.in.l"
+#line 99 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_TRANSIENT; }
+	YY_BREAK
 case 50:
 YY_RULE_SETUP
-#line 140 "cmDependsJavaLexer.in.l"
+#line 100 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_TRY; }
+	YY_BREAK
 case 51:
 YY_RULE_SETUP
-#line 141 "cmDependsJavaLexer.in.l"
+#line 101 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_VOID; }
+	YY_BREAK
 case 52:
 YY_RULE_SETUP
-#line 142 "cmDependsJavaLexer.in.l"
+#line 102 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_VOLATILE; }
+	YY_BREAK
 case 53:
 YY_RULE_SETUP
-#line 143 "cmDependsJavaLexer.in.l"
+#line 103 "cmDependsJavaLexer.in.l"
 { KEYWORD; return jp_WHILE; }
+	YY_BREAK
 case 54:
 YY_RULE_SETUP
-#line 145 "cmDependsJavaLexer.in.l"
+#line 105 "cmDependsJavaLexer.in.l"
 { PRIMITIVE; return jp_BOOLEANLITERAL; }
+	YY_BREAK
 case 55:
 /* rule 55 can match eol */
 YY_RULE_SETUP
-#line 146 "cmDependsJavaLexer.in.l"
+#line 106 "cmDependsJavaLexer.in.l"
 { PRIMITIVE; return jp_CHARACTERLITERAL; }
+	YY_BREAK
 case 56:
 YY_RULE_SETUP
-#line 147 "cmDependsJavaLexer.in.l"
+#line 107 "cmDependsJavaLexer.in.l"
 { PRIMITIVE; return jp_DECIMALINTEGERLITERAL; }
+	YY_BREAK
 case 57:
 YY_RULE_SETUP
-#line 148 "cmDependsJavaLexer.in.l"
+#line 108 "cmDependsJavaLexer.in.l"
 { PRIMITIVE; return jp_FLOATINGPOINTLITERAL; }
+	YY_BREAK
 case 58:
 YY_RULE_SETUP
-#line 149 "cmDependsJavaLexer.in.l"
+#line 109 "cmDependsJavaLexer.in.l"
 { PRIMITIVE; return jp_HEXINTEGERLITERAL; }
+	YY_BREAK
 case 59:
 YY_RULE_SETUP
-#line 150 "cmDependsJavaLexer.in.l"
+#line 110 "cmDependsJavaLexer.in.l"
 { PRIMITIVE; return jp_NULLLITERAL; }
+	YY_BREAK
 case 60:
 YY_RULE_SETUP
-#line 152 "cmDependsJavaLexer.in.l"
+#line 112 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_AND; }
+	YY_BREAK
 case 61:
 YY_RULE_SETUP
-#line 153 "cmDependsJavaLexer.in.l"
+#line 113 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_ANDAND; }
+	YY_BREAK
 case 62:
 YY_RULE_SETUP
-#line 154 "cmDependsJavaLexer.in.l"
+#line 114 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_ANDEQUALS; }
+	YY_BREAK
 case 63:
 YY_RULE_SETUP
-#line 155 "cmDependsJavaLexer.in.l"
+#line 115 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_BRACKETEND; }
+	YY_BREAK
 case 64:
 YY_RULE_SETUP
-#line 156 "cmDependsJavaLexer.in.l"
+#line 116 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_BRACKETSTART; }
+	YY_BREAK
 case 65:
 YY_RULE_SETUP
-#line 157 "cmDependsJavaLexer.in.l"
+#line 117 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_CARROT; }
+	YY_BREAK
 case 66:
 YY_RULE_SETUP
-#line 158 "cmDependsJavaLexer.in.l"
+#line 118 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_CARROTEQUALS; }
+	YY_BREAK
 case 67:
 YY_RULE_SETUP
-#line 159 "cmDependsJavaLexer.in.l"
+#line 119 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_COLON; }
+	YY_BREAK
 case 68:
 YY_RULE_SETUP
-#line 160 "cmDependsJavaLexer.in.l"
+#line 120 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_COMMA; }
+	YY_BREAK
 case 69:
 YY_RULE_SETUP
-#line 161 "cmDependsJavaLexer.in.l"
+#line 121 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_CURLYEND; }
+	YY_BREAK
 case 70:
 YY_RULE_SETUP
-#line 162 "cmDependsJavaLexer.in.l"
+#line 122 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_CURLYSTART; }
+	YY_BREAK
 case 71:
 YY_RULE_SETUP
-#line 163 "cmDependsJavaLexer.in.l"
+#line 123 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_DIVIDE; }
+	YY_BREAK
 case 72:
 YY_RULE_SETUP
-#line 164 "cmDependsJavaLexer.in.l"
+#line 124 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_DIVIDEEQUALS; }
+	YY_BREAK
 case 73:
 YY_RULE_SETUP
-#line 165 "cmDependsJavaLexer.in.l"
+#line 125 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_DOLLAR; }
+	YY_BREAK
 case 74:
 YY_RULE_SETUP
-#line 166 "cmDependsJavaLexer.in.l"
+#line 126 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_DOT; }
+	YY_BREAK
 case 75:
 YY_RULE_SETUP
-#line 167 "cmDependsJavaLexer.in.l"
+#line 127 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_EQUALS; }
+	YY_BREAK
 case 76:
 YY_RULE_SETUP
-#line 168 "cmDependsJavaLexer.in.l"
+#line 128 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_EQUALSEQUALS; }
+	YY_BREAK
 case 77:
 YY_RULE_SETUP
-#line 169 "cmDependsJavaLexer.in.l"
+#line 129 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_EXCLAMATION; }
+	YY_BREAK
 case 78:
 YY_RULE_SETUP
-#line 170 "cmDependsJavaLexer.in.l"
+#line 130 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_EXCLAMATIONEQUALS; }
+	YY_BREAK
 case 79:
 YY_RULE_SETUP
-#line 171 "cmDependsJavaLexer.in.l"
+#line 131 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_GREATER; }
+	YY_BREAK
 case 80:
 YY_RULE_SETUP
-#line 172 "cmDependsJavaLexer.in.l"
+#line 132 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_GTEQUALS; }
+	YY_BREAK
 case 81:
 YY_RULE_SETUP
-#line 173 "cmDependsJavaLexer.in.l"
+#line 133 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_GTGT; }
+	YY_BREAK
 case 82:
 YY_RULE_SETUP
-#line 174 "cmDependsJavaLexer.in.l"
+#line 134 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_GTGTEQUALS; }
+	YY_BREAK
 case 83:
 YY_RULE_SETUP
-#line 175 "cmDependsJavaLexer.in.l"
+#line 135 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_GTGTGT; }
+	YY_BREAK
 case 84:
 YY_RULE_SETUP
-#line 176 "cmDependsJavaLexer.in.l"
+#line 136 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_GTGTGTEQUALS; }
+	YY_BREAK
 case 85:
 YY_RULE_SETUP
-#line 177 "cmDependsJavaLexer.in.l"
+#line 137 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_LESLESEQUALS; }
+	YY_BREAK
 case 86:
 YY_RULE_SETUP
-#line 178 "cmDependsJavaLexer.in.l"
+#line 138 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_LESSTHAN; }
+	YY_BREAK
 case 87:
 YY_RULE_SETUP
-#line 179 "cmDependsJavaLexer.in.l"
+#line 139 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_LTEQUALS; }
+	YY_BREAK
 case 88:
 YY_RULE_SETUP
-#line 180 "cmDependsJavaLexer.in.l"
+#line 140 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_LTLT; }
+	YY_BREAK
 case 89:
 YY_RULE_SETUP
-#line 181 "cmDependsJavaLexer.in.l"
+#line 141 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_MINUS; }
+	YY_BREAK
 case 90:
 YY_RULE_SETUP
-#line 182 "cmDependsJavaLexer.in.l"
+#line 142 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_MINUSEQUALS; }
+	YY_BREAK
 case 91:
 YY_RULE_SETUP
-#line 183 "cmDependsJavaLexer.in.l"
+#line 143 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_MINUSMINUS; }
+	YY_BREAK
 case 92:
 YY_RULE_SETUP
-#line 184 "cmDependsJavaLexer.in.l"
+#line 144 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_PAREEND; }
+	YY_BREAK
 case 93:
 YY_RULE_SETUP
-#line 185 "cmDependsJavaLexer.in.l"
+#line 145 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_PARESTART; }
+	YY_BREAK
 case 94:
 YY_RULE_SETUP
-#line 186 "cmDependsJavaLexer.in.l"
+#line 146 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_PERCENT; }
+	YY_BREAK
 case 95:
 YY_RULE_SETUP
-#line 187 "cmDependsJavaLexer.in.l"
+#line 147 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_PERCENTEQUALS; }
+	YY_BREAK
 case 96:
 YY_RULE_SETUP
-#line 188 "cmDependsJavaLexer.in.l"
+#line 148 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_PIPE; }
+	YY_BREAK
 case 97:
 YY_RULE_SETUP
-#line 189 "cmDependsJavaLexer.in.l"
+#line 149 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_PIPEEQUALS; }
+	YY_BREAK
 case 98:
 YY_RULE_SETUP
-#line 190 "cmDependsJavaLexer.in.l"
+#line 150 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_PIPEPIPE; }
+	YY_BREAK
 case 99:
 YY_RULE_SETUP
-#line 191 "cmDependsJavaLexer.in.l"
+#line 151 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_PLUS; }
+	YY_BREAK
 case 100:
 YY_RULE_SETUP
-#line 192 "cmDependsJavaLexer.in.l"
+#line 152 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_PLUSEQUALS; }
+	YY_BREAK
 case 101:
 YY_RULE_SETUP
-#line 193 "cmDependsJavaLexer.in.l"
+#line 153 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_PLUSPLUS; }
+	YY_BREAK
 case 102:
 YY_RULE_SETUP
-#line 194 "cmDependsJavaLexer.in.l"
+#line 154 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_QUESTION; }
+	YY_BREAK
 case 103:
 YY_RULE_SETUP
-#line 195 "cmDependsJavaLexer.in.l"
+#line 155 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_SEMICOL; }
+	YY_BREAK
 case 104:
 YY_RULE_SETUP
-#line 196 "cmDependsJavaLexer.in.l"
+#line 156 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_TILDE; }
+	YY_BREAK
 case 105:
 YY_RULE_SETUP
-#line 197 "cmDependsJavaLexer.in.l"
+#line 157 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_TIMES; }
+	YY_BREAK
 case 106:
 YY_RULE_SETUP
-#line 198 "cmDependsJavaLexer.in.l"
+#line 158 "cmDependsJavaLexer.in.l"
 { SYMBOL; return jp_TIMESEQUALS; }
+	YY_BREAK
 case 107:
 YY_RULE_SETUP
-#line 200 "cmDependsJavaLexer.in.l"
+#line 160 "cmDependsJavaLexer.in.l"
 {
   yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
   return jp_NAME;
 }
+	YY_BREAK
 case 108:
 /* rule 108 can match eol */
 YY_RULE_SETUP
-#line 205 "cmDependsJavaLexer.in.l"
+#line 165 "cmDependsJavaLexer.in.l"
 { }
-  YY_BREAK
+	YY_BREAK
 case 109:
 /* rule 109 can match eol */
 YY_RULE_SETUP
-#line 206 "cmDependsJavaLexer.in.l"
+#line 166 "cmDependsJavaLexer.in.l"
 { }
-  YY_BREAK
+	YY_BREAK
 case 110:
 YY_RULE_SETUP
-#line 207 "cmDependsJavaLexer.in.l"
+#line 167 "cmDependsJavaLexer.in.l"
 {
   std::cerr << "Unknown character: " << yytext[0]
     << " (" << (int)yytext[0] << ")" << std::endl;
   yyextra->Error("Unknown character");
   return jp_ERROR;
 }
+	YY_BREAK
 case 111:
 YY_RULE_SETUP
-#line 214 "cmDependsJavaLexer.in.l"
+#line 174 "cmDependsJavaLexer.in.l"
 ECHO;
-  YY_BREAK
-#line 1590 "cmDependsJavaLexer.cxx"
+	YY_BREAK
+#line 1567 "cmDependsJavaLexer.cxx"
 case YY_STATE_EOF(INITIAL):
 case YY_STATE_EOF(comment):
 case YY_STATE_EOF(string):
-  yyterminate();
-
-  case YY_END_OF_BUFFER:
-    {
-    /* Amount of text matched not including the EOB char. */
-    int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1;
-
-    /* Undo the effects of YY_DO_BEFORE_ACTION. */
-    *yy_cp = yyg->yy_hold_char;
-    YY_RESTORE_YY_MORE_OFFSET
-
-    if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
-      {
-      /* We're scanning a new file or input source.  It's
-       * possible that this happened because the user
-       * just pointed yyin at a new source and called
-       * cmDependsJava_yylex().  If so, then we have to assure
-       * consistency between YY_CURRENT_BUFFER and our
-       * globals.  Here is the right place to do so, because
-       * this is the first action (other than possibly a
-       * back-up) that will match for the new input source.
-       */
-      yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
-      YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
-      YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
-      }
-
-    /* Note that here we test for yy_c_buf_p "<=" to the position
-     * of the first EOB in the buffer, since yy_c_buf_p will
-     * already have been incremented past the NUL character
-     * (since all states make transitions on EOB to the
-     * end-of-buffer state).  Contrast this with the test
-     * in input().
-     */
-    if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
-      { /* This was really a NUL. */
-      yy_state_type yy_next_state;
-
-      yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text;
-
-      yy_current_state = yy_get_previous_state( yyscanner );
-
-      /* Okay, we're now positioned to make the NUL
-       * transition.  We couldn't have
-       * yy_get_previous_state() go ahead and do it
-       * for us because it doesn't know how to deal
-       * with the possibility of jamming (and we don't
-       * want to build jamming into it because then it
-       * will run more slowly).
-       */
-
-      yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner);
-
-      yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
-
-      if ( yy_next_state )
-        {
-        /* Consume the NUL. */
-        yy_cp = ++yyg->yy_c_buf_p;
-        yy_current_state = yy_next_state;
-        goto yy_match;
-        }
-
-      else
-        {
-        yy_cp = yyg->yy_c_buf_p;
-        goto yy_find_action;
-        }
-      }
-
-    else switch ( yy_get_next_buffer( yyscanner ) )
-      {
-      case EOB_ACT_END_OF_FILE:
-        {
-        yyg->yy_did_buffer_switch_on_eof = 0;
-
-        if ( cmDependsJava_yywrap(yyscanner ) )
-          {
-          /* Note: because we've taken care in
-           * yy_get_next_buffer() to have set up
-           * yytext, we can now set up
-           * yy_c_buf_p so that if some total
-           * hoser (like flex itself) wants to
-           * call the scanner after we return the
-           * YY_NULL, it'll still work - another
-           * YY_NULL will get returned.
-           */
-          yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ;
-
-          yy_act = YY_STATE_EOF(YY_START);
-          goto do_action;
-          }
-
-        else
-          {
-          if ( ! yyg->yy_did_buffer_switch_on_eof )
-            YY_NEW_FILE;
-          }
-        break;
-        }
-
-      case EOB_ACT_CONTINUE_SCAN:
-        yyg->yy_c_buf_p =
-          yyg->yytext_ptr + yy_amount_of_matched_text;
-
-        yy_current_state = yy_get_previous_state( yyscanner );
-
-        yy_cp = yyg->yy_c_buf_p;
-        yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
-        goto yy_match;
-
-      case EOB_ACT_LAST_MATCH:
-        yyg->yy_c_buf_p =
-        &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars];
-
-        yy_current_state = yy_get_previous_state( yyscanner );
-
-        yy_cp = yyg->yy_c_buf_p;
-        yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
-        goto yy_find_action;
-      }
-    break;
-    }
-
-  default:
-    YY_FATAL_ERROR(
-      "fatal flex scanner internal error--no action found" );
-  } /* end of action switch */
-    } /* end of scanning one token */
-return 0; /* this should not happen but it quiets some compilers */
+	yyterminate();
+
+	case YY_END_OF_BUFFER:
+		{
+		/* Amount of text matched not including the EOB char. */
+		int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1;
+
+		/* Undo the effects of YY_DO_BEFORE_ACTION. */
+		*yy_cp = yyg->yy_hold_char;
+		YY_RESTORE_YY_MORE_OFFSET
+
+		if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
+			{
+			/* We're scanning a new file or input source.  It's
+			 * possible that this happened because the user
+			 * just pointed yyin at a new source and called
+			 * cmDependsJava_yylex().  If so, then we have to assure
+			 * consistency between YY_CURRENT_BUFFER and our
+			 * globals.  Here is the right place to do so, because
+			 * this is the first action (other than possibly a
+			 * back-up) that will match for the new input source.
+			 */
+			yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+			YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
+			YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
+			}
+
+		/* Note that here we test for yy_c_buf_p "<=" to the position
+		 * of the first EOB in the buffer, since yy_c_buf_p will
+		 * already have been incremented past the NUL character
+		 * (since all states make transitions on EOB to the
+		 * end-of-buffer state).  Contrast this with the test
+		 * in input().
+		 */
+		if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
+			{ /* This was really a NUL. */
+			yy_state_type yy_next_state;
+
+			yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text;
+
+			yy_current_state = yy_get_previous_state( yyscanner );
+
+			/* Okay, we're now positioned to make the NUL
+			 * transition.  We couldn't have
+			 * yy_get_previous_state() go ahead and do it
+			 * for us because it doesn't know how to deal
+			 * with the possibility of jamming (and we don't
+			 * want to build jamming into it because then it
+			 * will run more slowly).
+			 */
+
+			yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner);
+
+			yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
+
+			if ( yy_next_state )
+				{
+				/* Consume the NUL. */
+				yy_cp = ++yyg->yy_c_buf_p;
+				yy_current_state = yy_next_state;
+				goto yy_match;
+				}
+
+			else
+				{
+				yy_cp = yyg->yy_c_buf_p;
+				goto yy_find_action;
+				}
+			}
+
+		else switch ( yy_get_next_buffer( yyscanner ) )
+			{
+			case EOB_ACT_END_OF_FILE:
+				{
+				yyg->yy_did_buffer_switch_on_eof = 0;
+
+				if ( cmDependsJava_yywrap(yyscanner ) )
+					{
+					/* Note: because we've taken care in
+					 * yy_get_next_buffer() to have set up
+					 * yytext, we can now set up
+					 * yy_c_buf_p so that if some total
+					 * hoser (like flex itself) wants to
+					 * call the scanner after we return the
+					 * YY_NULL, it'll still work - another
+					 * YY_NULL will get returned.
+					 */
+					yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ;
+
+					yy_act = YY_STATE_EOF(YY_START);
+					goto do_action;
+					}
+
+				else
+					{
+					if ( ! yyg->yy_did_buffer_switch_on_eof )
+						YY_NEW_FILE;
+					}
+				break;
+				}
+
+			case EOB_ACT_CONTINUE_SCAN:
+				yyg->yy_c_buf_p =
+					yyg->yytext_ptr + yy_amount_of_matched_text;
+
+				yy_current_state = yy_get_previous_state( yyscanner );
+
+				yy_cp = yyg->yy_c_buf_p;
+				yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
+				goto yy_match;
+
+			case EOB_ACT_LAST_MATCH:
+				yyg->yy_c_buf_p =
+				&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars];
+
+				yy_current_state = yy_get_previous_state( yyscanner );
+
+				yy_cp = yyg->yy_c_buf_p;
+				yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
+				goto yy_find_action;
+			}
+		break;
+		}
+
+	default:
+		YY_FATAL_ERROR(
+			"fatal flex scanner internal error--no action found" );
+	} /* end of action switch */
+		} /* end of scanning one token */
+	} /* end of user's declarations */
 } /* end of cmDependsJava_yylex */
 
 /* yy_get_next_buffer - try to read in a new buffer
  *
  * Returns a code representing an action:
- *  EOB_ACT_LAST_MATCH -
- *  EOB_ACT_CONTINUE_SCAN - continue scanning from current position
- *  EOB_ACT_END_OF_FILE - end of file
+ *	EOB_ACT_LAST_MATCH -
+ *	EOB_ACT_CONTINUE_SCAN - continue scanning from current position
+ *	EOB_ACT_END_OF_FILE - end of file
  */
 static int yy_get_next_buffer (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
-  char *source = yyg->yytext_ptr;
-  int number_to_move, i;
-  int ret_val;
-
-  if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
-    YY_FATAL_ERROR(
-    "fatal flex scanner internal error--end of buffer missed" );
-
-  if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
-    { /* Don't try to fill the buffer, so this is an EOF. */
-    if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 )
-      {
-      /* We matched a single character, the EOB, so
-       * treat this as a final EOF.
-       */
-      return EOB_ACT_END_OF_FILE;
-      }
-
-    else
-      {
-      /* We matched some text prior to the EOB, first
-       * process it.
-       */
-      return EOB_ACT_LAST_MATCH;
-      }
-    }
-
-  /* Try to read more data. */
-
-  /* First move last chars to start of buffer. */
-  number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
-
-  for ( i = 0; i < number_to_move; ++i )
-    *(dest++) = *(source++);
-
-  if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
-    /* don't do the read, it's not guaranteed to return an EOF,
-     * just force an EOF
-     */
-    YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0;
-
-  else
-    {
-      size_t nuto_read =
-      YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
-
-    while ( nuto_read <= 0 )
-      { /* Not enough room in the buffer - grow it. */
-
-      /* just a shorter name for the current buffer */
-      YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
-
-      int yy_c_buf_p_offset =
-        (int) (yyg->yy_c_buf_p - b->yy_ch_buf);
-
-      if ( b->yy_is_our_buffer )
-        {
-        int new_size = b->yy_buf_size * 2;
-
-        if ( new_size <= 0 )
-          b->yy_buf_size += b->yy_buf_size / 8;
-        else
-          b->yy_buf_size *= 2;
-
-        b->yy_ch_buf = (char *)
-          /* Include room in for 2 EOB chars. */
-          cmDependsJava_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
-        }
-      else
-        /* Can't grow it, we don't own it. */
-        b->yy_ch_buf = 0;
-
-      if ( ! b->yy_ch_buf )
-        YY_FATAL_ERROR(
-        "fatal error - scanner input buffer overflow" );
-
-      yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
-
-      nuto_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
-            number_to_move - 1;
-
-      }
-
-    if ( nuto_read > YY_READ_BUF_SIZE )
-      nuto_read = YY_READ_BUF_SIZE;
-
-    /* Read in more data. */
-    YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
-      yyg->yy_n_chars, nuto_read );
-
-    YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
-    }
-
-  if ( yyg->yy_n_chars == 0 )
-    {
-    if ( number_to_move == YY_MORE_ADJ )
-      {
-      ret_val = EOB_ACT_END_OF_FILE;
-      cmDependsJava_yyrestart(yyin  ,yyscanner);
-      }
-
-    else
-      {
-      ret_val = EOB_ACT_LAST_MATCH;
-      YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
-        YY_BUFFER_EOF_PENDING;
-      }
-    }
-
-  else
-    ret_val = EOB_ACT_CONTINUE_SCAN;
+	char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
+	char *source = yyg->yytext_ptr;
+	yy_size_t number_to_move, i;
+	int ret_val;
+
+	if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
+		YY_FATAL_ERROR(
+		"fatal flex scanner internal error--end of buffer missed" );
+
+	if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
+		{ /* Don't try to fill the buffer, so this is an EOF. */
+		if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 )
+			{
+			/* We matched a single character, the EOB, so
+			 * treat this as a final EOF.
+			 */
+			return EOB_ACT_END_OF_FILE;
+			}
+
+		else
+			{
+			/* We matched some text prior to the EOB, first
+			 * process it.
+			 */
+			return EOB_ACT_LAST_MATCH;
+			}
+		}
+
+	/* Try to read more data. */
+
+	/* First move last chars to start of buffer. */
+	number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
+
+	for ( i = 0; i < number_to_move; ++i )
+		*(dest++) = *(source++);
+
+	if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
+		/* don't do the read, it's not guaranteed to return an EOF,
+		 * just force an EOF
+		 */
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0;
+
+	else
+		{
+			int num_to_read =
+			YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
+
+		while ( num_to_read <= 0 )
+			{ /* Not enough room in the buffer - grow it. */
+
+			/* just a shorter name for the current buffer */
+			YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE;
+
+			int yy_c_buf_p_offset =
+				(int) (yyg->yy_c_buf_p - b->yy_ch_buf);
+
+			if ( b->yy_is_our_buffer )
+				{
+				int new_size = b->yy_buf_size * 2;
+
+				if ( new_size <= 0 )
+					b->yy_buf_size += b->yy_buf_size / 8;
+				else
+					b->yy_buf_size *= 2;
+
+				b->yy_ch_buf = (char *)
+					/* Include room in for 2 EOB chars. */
+					cmDependsJava_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
+				}
+			else
+				/* Can't grow it, we don't own it. */
+				b->yy_ch_buf = NULL;
+
+			if ( ! b->yy_ch_buf )
+				YY_FATAL_ERROR(
+				"fatal error - scanner input buffer overflow" );
+
+			yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
+
+			num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
+						number_to_move - 1;
+
+			}
+
+		if ( num_to_read > YY_READ_BUF_SIZE )
+			num_to_read = YY_READ_BUF_SIZE;
+
+		/* Read in more data. */
+		YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
+			yyg->yy_n_chars, num_to_read );
+
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
+		}
+
+	if ( yyg->yy_n_chars == 0 )
+		{
+		if ( number_to_move == YY_MORE_ADJ )
+			{
+			ret_val = EOB_ACT_END_OF_FILE;
+			cmDependsJava_yyrestart(yyin  ,yyscanner);
+			}
+
+		else
+			{
+			ret_val = EOB_ACT_LAST_MATCH;
+			YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
+				YY_BUFFER_EOF_PENDING;
+			}
+		}
+
+	else
+		ret_val = EOB_ACT_CONTINUE_SCAN;
+
+	if ((int) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
+		/* Extend the array by 50%, plus the number we really need. */
+		int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
+		YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) cmDependsJava_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );
+		if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
+			YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
+	}
+
+	yyg->yy_n_chars += number_to_move;
+	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR;
+	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
+
+	yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
 
-  yyg->yy_n_chars += number_to_move;
-  YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR;
-  YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
-
-  yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
-
-  return ret_val;
+	return ret_val;
 }
 
 /* yy_get_previous_state - get the state just before the EOB char was reached */
 
     static yy_state_type yy_get_previous_state (yyscan_t yyscanner)
 {
-  yy_state_type yy_current_state;
-  char *yy_cp;
+	yy_state_type yy_current_state;
+	char *yy_cp;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-  yy_current_state = yyg->yy_start;
-
-  for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp )
-    {
-    YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
-    if ( yy_accept[yy_current_state] )
-      {
-      yyg->yy_last_accepting_state = yy_current_state;
-      yyg->yy_last_accepting_cpos = yy_cp;
-      }
-    while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
-      {
-      yy_current_state = (int) yy_def[yy_current_state];
-      if ( yy_current_state >= 327 )
-        yy_c = yy_meta[(unsigned int) yy_c];
-      }
-    yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-    }
-
-  return yy_current_state;
+	yy_current_state = yyg->yy_start;
+
+	for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp )
+		{
+		YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
+		if ( yy_accept[yy_current_state] )
+			{
+			yyg->yy_last_accepting_state = yy_current_state;
+			yyg->yy_last_accepting_cpos = yy_cp;
+			}
+		while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+			{
+			yy_current_state = (int) yy_def[yy_current_state];
+			if ( yy_current_state >= 327 )
+				yy_c = yy_meta[(unsigned int) yy_c];
+			}
+		yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+		}
+
+	return yy_current_state;
 }
 
 /* yy_try_NUL_trans - try to make a transition on the NUL character
  *
  * synopsis
- *  next_state = yy_try_NUL_trans( current_state );
+ *	next_state = yy_try_NUL_trans( current_state );
  */
     static yy_state_type yy_try_NUL_trans  (yy_state_type yy_current_state , yyscan_t yyscanner)
 {
-  int yy_is_jam;
+	int yy_is_jam;
+    struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */
+	char *yy_cp = yyg->yy_c_buf_p;
+
+	YY_CHAR yy_c = 1;
+	if ( yy_accept[yy_current_state] )
+		{
+		yyg->yy_last_accepting_state = yy_current_state;
+		yyg->yy_last_accepting_cpos = yy_cp;
+		}
+	while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+		{
+		yy_current_state = (int) yy_def[yy_current_state];
+		if ( yy_current_state >= 327 )
+			yy_c = yy_meta[(unsigned int) yy_c];
+		}
+	yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+	yy_is_jam = (yy_current_state == 326);
+
+	(void)yyg;
+	return yy_is_jam ? 0 : yy_current_state;
+}
+
+#ifndef YY_NO_UNPUT
+
+    static void yyunput (int c, char * yy_bp , yyscan_t yyscanner)
+{
+	char *yy_cp;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  char *yy_cp = yyg->yy_c_buf_p;
 
-  YY_CHAR yy_c = 1;
-  if ( yy_accept[yy_current_state] )
-    {
-    yyg->yy_last_accepting_state = yy_current_state;
-    yyg->yy_last_accepting_cpos = yy_cp;
-    }
-  while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
-    {
-    yy_current_state = (int) yy_def[yy_current_state];
-    if ( yy_current_state >= 327 )
-      yy_c = yy_meta[(unsigned int) yy_c];
-    }
-  yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-  yy_is_jam = (yy_current_state == 326);
+    yy_cp = yyg->yy_c_buf_p;
+
+	/* undo effects of setting up yytext */
+	*yy_cp = yyg->yy_hold_char;
+
+	if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
+		{ /* need to shift things up to make room */
+		/* +2 for EOB chars. */
+		int number_to_move = yyg->yy_n_chars + 2;
+		char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
+					YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
+		char *source =
+				&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
+
+		while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
+			*--dest = *--source;
+
+		yy_cp += (int) (dest - source);
+		yy_bp += (int) (dest - source);
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
+			yyg->yy_n_chars = (int) YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
+
+		if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
+			YY_FATAL_ERROR( "flex scanner push-back overflow" );
+		}
 
-  return yy_is_jam ? 0 : yy_current_state;
+	*--yy_cp = (char) c;
+
+	yyg->yytext_ptr = yy_bp;
+	yyg->yy_hold_char = *yy_cp;
+	yyg->yy_c_buf_p = yy_cp;
 }
 
+#endif
+
 #ifndef YY_NO_INPUT
 #ifdef __cplusplus
     static int yyinput (yyscan_t yyscanner)
@@ -1786,72 +1950,72 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 #endif
 
 {
-  int c;
+	int c;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-  *yyg->yy_c_buf_p = yyg->yy_hold_char;
-
-  if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
-    {
-    /* yy_c_buf_p now points to the character we want to return.
-     * If this occurs *before* the EOB characters, then it's a
-     * valid NUL; if not, then we've hit the end of the buffer.
-     */
-    if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
-      /* This was really a NUL. */
-      *yyg->yy_c_buf_p = '\0';
-
-    else
-      { /* need more input */
-      int offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
-      ++yyg->yy_c_buf_p;
-
-      switch ( yy_get_next_buffer( yyscanner ) )
-        {
-        case EOB_ACT_LAST_MATCH:
-          /* This happens because yy_g_n_b()
-           * sees that we've accumulated a
-           * token and flags that we need to
-           * try matching the token before
-           * proceeding.  But for input(),
-           * there's no matching to consider.
-           * So convert the EOB_ACT_LAST_MATCH
-           * to EOB_ACT_END_OF_FILE.
-           */
-
-          /* Reset buffer status. */
-          cmDependsJava_yyrestart(yyin ,yyscanner);
-
-          /*FALLTHROUGH*/
-
-        case EOB_ACT_END_OF_FILE:
-          {
-          if ( cmDependsJava_yywrap(yyscanner ) )
-            return EOF;
-
-          if ( ! yyg->yy_did_buffer_switch_on_eof )
-            YY_NEW_FILE;
+	*yyg->yy_c_buf_p = yyg->yy_hold_char;
+
+	if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
+		{
+		/* yy_c_buf_p now points to the character we want to return.
+		 * If this occurs *before* the EOB characters, then it's a
+		 * valid NUL; if not, then we've hit the end of the buffer.
+		 */
+		if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
+			/* This was really a NUL. */
+			*yyg->yy_c_buf_p = '\0';
+
+		else
+			{ /* need more input */
+			int offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
+			++yyg->yy_c_buf_p;
+
+			switch ( yy_get_next_buffer( yyscanner ) )
+				{
+				case EOB_ACT_LAST_MATCH:
+					/* This happens because yy_g_n_b()
+					 * sees that we've accumulated a
+					 * token and flags that we need to
+					 * try matching the token before
+					 * proceeding.  But for input(),
+					 * there's no matching to consider.
+					 * So convert the EOB_ACT_LAST_MATCH
+					 * to EOB_ACT_END_OF_FILE.
+					 */
+
+					/* Reset buffer status. */
+					cmDependsJava_yyrestart(yyin ,yyscanner);
+
+					/*FALLTHROUGH*/
+
+				case EOB_ACT_END_OF_FILE:
+					{
+					if ( cmDependsJava_yywrap(yyscanner ) )
+						return 0;
+
+					if ( ! yyg->yy_did_buffer_switch_on_eof )
+						YY_NEW_FILE;
 #ifdef __cplusplus
-          return yyinput(yyscanner);
+					return yyinput(yyscanner);
 #else
-          return input(yyscanner);
+					return input(yyscanner);
 #endif
-          }
+					}
 
-        case EOB_ACT_CONTINUE_SCAN:
-          yyg->yy_c_buf_p = yyg->yytext_ptr + offset;
-          break;
-        }
-      }
-    }
+				case EOB_ACT_CONTINUE_SCAN:
+					yyg->yy_c_buf_p = yyg->yytext_ptr + offset;
+					break;
+				}
+			}
+		}
 
-  c = *(unsigned char *) yyg->yy_c_buf_p;  /* cast for 8-bit char's */
-  *yyg->yy_c_buf_p = '\0';  /* preserve yytext */
-  yyg->yy_hold_char = *++yyg->yy_c_buf_p;
+	c = *(unsigned char *) yyg->yy_c_buf_p;	/* cast for 8-bit char's */
+	*yyg->yy_c_buf_p = '\0';	/* preserve yytext */
+	yyg->yy_hold_char = *++yyg->yy_c_buf_p;
 
-  return c;
+	return c;
 }
-#endif  /* ifndef YY_NO_INPUT */
+#endif	/* ifndef YY_NO_INPUT */
 
 /** Immediately switch to a different input stream.
  * @param input_file A readable stream.
@@ -1862,14 +2026,14 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-  if ( ! YY_CURRENT_BUFFER ){
+	if ( ! YY_CURRENT_BUFFER ){
         cmDependsJava_yyensure_buffer_stack (yyscanner);
-    YY_CURRENT_BUFFER_LVALUE =
+		YY_CURRENT_BUFFER_LVALUE =
             cmDependsJava_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
-  }
+	}
 
-  cmDependsJava_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
-  cmDependsJava_yy_load_buffer_state(yyscanner );
+	cmDependsJava_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
+	cmDependsJava_yy_load_buffer_state(yyscanner );
 }
 
 /** Switch to a different input buffer.
@@ -1880,41 +2044,41 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-  /* TODO. We should be able to replace this entire function body
-   * with
-   *    cmDependsJava_yypop_buffer_state();
-   *    cmDependsJava_yypush_buffer_state(new_buffer);
+	/* TODO. We should be able to replace this entire function body
+	 * with
+	 *		cmDependsJava_yypop_buffer_state();
+	 *		cmDependsJava_yypush_buffer_state(new_buffer);
      */
-  cmDependsJava_yyensure_buffer_stack (yyscanner);
-  if ( YY_CURRENT_BUFFER == new_buffer )
-    return;
-
-  if ( YY_CURRENT_BUFFER )
-    {
-    /* Flush out information for old buffer. */
-    *yyg->yy_c_buf_p = yyg->yy_hold_char;
-    YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
-    YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
-    }
-
-  YY_CURRENT_BUFFER_LVALUE = new_buffer;
-  cmDependsJava_yy_load_buffer_state(yyscanner );
-
-  /* We don't actually know whether we did this switch during
-   * EOF (cmDependsJava_yywrap()) processing, but the only time this flag
-   * is looked at is after cmDependsJava_yywrap() is called, so it's safe
-   * to go ahead and always set it.
-   */
-  yyg->yy_did_buffer_switch_on_eof = 1;
+	cmDependsJava_yyensure_buffer_stack (yyscanner);
+	if ( YY_CURRENT_BUFFER == new_buffer )
+		return;
+
+	if ( YY_CURRENT_BUFFER )
+		{
+		/* Flush out information for old buffer. */
+		*yyg->yy_c_buf_p = yyg->yy_hold_char;
+		YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
+		}
+
+	YY_CURRENT_BUFFER_LVALUE = new_buffer;
+	cmDependsJava_yy_load_buffer_state(yyscanner );
+
+	/* We don't actually know whether we did this switch during
+	 * EOF (cmDependsJava_yywrap()) processing, but the only time this flag
+	 * is looked at is after cmDependsJava_yywrap() is called, so it's safe
+	 * to go ahead and always set it.
+	 */
+	yyg->yy_did_buffer_switch_on_eof = 1;
 }
 
 static void cmDependsJava_yy_load_buffer_state  (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
-  yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
-  yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
-  yyg->yy_hold_char = *yyg->yy_c_buf_p;
+	yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+	yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
+	yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
+	yyg->yy_hold_char = *yyg->yy_c_buf_p;
 }
 
 /** Allocate and initialize an input buffer state.
@@ -1925,26 +2089,26 @@ static void cmDependsJava_yy_load_buffer_state  (yyscan_t yyscanner)
  */
     YY_BUFFER_STATE cmDependsJava_yy_create_buffer  (FILE * file, int  size , yyscan_t yyscanner)
 {
-  YY_BUFFER_STATE b;
+	YY_BUFFER_STATE b;
 
-  b = (YY_BUFFER_STATE) cmDependsJava_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
-  if ( ! b )
-    YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yy_create_buffer()" );
+	b = (YY_BUFFER_STATE) cmDependsJava_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+	if ( ! b )
+		YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yy_create_buffer()" );
 
-  b->yy_buf_size = size;
+	b->yy_buf_size = (yy_size_t)size;
 
-  /* yy_ch_buf has to be 2 characters longer than the size given because
-   * we need to put in 2 end-of-buffer characters.
-   */
-  b->yy_ch_buf = (char *) cmDependsJava_yyalloc(b->yy_buf_size + 2 ,yyscanner );
-  if ( ! b->yy_ch_buf )
-    YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yy_create_buffer()" );
+	/* yy_ch_buf has to be 2 characters longer than the size given because
+	 * we need to put in 2 end-of-buffer characters.
+	 */
+	b->yy_ch_buf = (char *) cmDependsJava_yyalloc(b->yy_buf_size + 2 ,yyscanner );
+	if ( ! b->yy_ch_buf )
+		YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yy_create_buffer()" );
 
-  b->yy_is_our_buffer = 1;
+	b->yy_is_our_buffer = 1;
 
-  cmDependsJava_yy_init_buffer(b,file ,yyscanner);
+	cmDependsJava_yy_init_buffer(b,file ,yyscanner);
 
-  return b;
+	return b;
 }
 
 /** Destroy the buffer.
@@ -1955,22 +2119,18 @@ static void cmDependsJava_yy_load_buffer_state  (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-  if ( ! b )
-    return;
+	if ( ! b )
+		return;
 
-  if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
-    YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
+	if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
+		YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
 
-  if ( b->yy_is_our_buffer )
-    cmDependsJava_yyfree((void *) b->yy_ch_buf ,yyscanner );
+	if ( b->yy_is_our_buffer )
+		cmDependsJava_yyfree((void *) b->yy_ch_buf ,yyscanner );
 
-  cmDependsJava_yyfree((void *) b ,yyscanner );
+	cmDependsJava_yyfree((void *) b ,yyscanner );
 }
 
-#ifndef __cplusplus
-extern int isatty (int );
-#endif /* __cplusplus */
-
 /* Initializes or reinitializes a buffer.
  * This function is sometimes called more than once on the same buffer,
  * such as during a cmDependsJava_yyrestart() or at EOF.
@@ -1978,13 +2138,13 @@ extern int isatty (int );
     static void cmDependsJava_yy_init_buffer  (YY_BUFFER_STATE  b, FILE * file , yyscan_t yyscanner)
 
 {
-  int oerrno = errno;
+	int oerrno = errno;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-  cmDependsJava_yy_flush_buffer(b ,yyscanner);
+	cmDependsJava_yy_flush_buffer(b ,yyscanner);
 
-  b->yy_input_file = file;
-  b->yy_fill_buffer = 1;
+	b->yy_input_file = file;
+	b->yy_fill_buffer = 1;
 
     /* If b is the current buffer, then cmDependsJava_yy_init_buffer was _probably_
      * called from cmDependsJava_yyrestart() or through yy_get_next_buffer.
@@ -1997,7 +2157,7 @@ extern int isatty (int );
 
         b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
 
-  errno = oerrno;
+	errno = oerrno;
 }
 
 /** Discard all buffered characters. On the next scan, YY_INPUT will be called.
@@ -2007,25 +2167,25 @@ extern int isatty (int );
     void cmDependsJava_yy_flush_buffer (YY_BUFFER_STATE  b , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  if ( ! b )
-    return;
+	if ( ! b )
+		return;
 
-  b->yy_n_chars = 0;
+	b->yy_n_chars = 0;
 
-  /* We always need two end-of-buffer characters.  The first causes
-   * a transition to the end-of-buffer state.  The second causes
-   * a jam in that state.
-   */
-  b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
-  b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
+	/* We always need two end-of-buffer characters.  The first causes
+	 * a transition to the end-of-buffer state.  The second causes
+	 * a jam in that state.
+	 */
+	b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
+	b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
 
-  b->yy_buf_pos = &b->yy_ch_buf[0];
+	b->yy_buf_pos = &b->yy_ch_buf[0];
 
-  b->yy_at_bol = 1;
-  b->yy_buffer_status = YY_BUFFER_NEW;
+	b->yy_at_bol = 1;
+	b->yy_buffer_status = YY_BUFFER_NEW;
 
-  if ( b == YY_CURRENT_BUFFER )
-    cmDependsJava_yy_load_buffer_state(yyscanner );
+	if ( b == YY_CURRENT_BUFFER )
+		cmDependsJava_yy_load_buffer_state(yyscanner );
 }
 
 /** Pushes the new state onto the stack. The new state becomes
@@ -2037,28 +2197,28 @@ extern int isatty (int );
 void cmDependsJava_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  if (new_buffer == NULL)
-    return;
-
-  cmDependsJava_yyensure_buffer_stack(yyscanner);
-
-  /* This block is copied from cmDependsJava_yy_switch_to_buffer. */
-  if ( YY_CURRENT_BUFFER )
-    {
-    /* Flush out information for old buffer. */
-    *yyg->yy_c_buf_p = yyg->yy_hold_char;
-    YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
-    YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
-    }
-
-  /* Only push if top exists. Otherwise, replace top. */
-  if (YY_CURRENT_BUFFER)
-    yyg->yy_buffer_stack_top++;
-  YY_CURRENT_BUFFER_LVALUE = new_buffer;
-
-  /* copied from cmDependsJava_yy_switch_to_buffer. */
-  cmDependsJava_yy_load_buffer_state(yyscanner );
-  yyg->yy_did_buffer_switch_on_eof = 1;
+	if (new_buffer == NULL)
+		return;
+
+	cmDependsJava_yyensure_buffer_stack(yyscanner);
+
+	/* This block is copied from cmDependsJava_yy_switch_to_buffer. */
+	if ( YY_CURRENT_BUFFER )
+		{
+		/* Flush out information for old buffer. */
+		*yyg->yy_c_buf_p = yyg->yy_hold_char;
+		YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
+		}
+
+	/* Only push if top exists. Otherwise, replace top. */
+	if (YY_CURRENT_BUFFER)
+		yyg->yy_buffer_stack_top++;
+	YY_CURRENT_BUFFER_LVALUE = new_buffer;
+
+	/* copied from cmDependsJava_yy_switch_to_buffer. */
+	cmDependsJava_yy_load_buffer_state(yyscanner );
+	yyg->yy_did_buffer_switch_on_eof = 1;
 }
 
 /** Removes and deletes the top of the stack, if present.
@@ -2068,18 +2228,18 @@ void cmDependsJava_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yy
 void cmDependsJava_yypop_buffer_state (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  if (!YY_CURRENT_BUFFER)
-    return;
-
-  cmDependsJava_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
-  YY_CURRENT_BUFFER_LVALUE = NULL;
-  if (yyg->yy_buffer_stack_top > 0)
-    --yyg->yy_buffer_stack_top;
-
-  if (YY_CURRENT_BUFFER) {
-    cmDependsJava_yy_load_buffer_state(yyscanner );
-    yyg->yy_did_buffer_switch_on_eof = 1;
-  }
+	if (!YY_CURRENT_BUFFER)
+		return;
+
+	cmDependsJava_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
+	YY_CURRENT_BUFFER_LVALUE = NULL;
+	if (yyg->yy_buffer_stack_top > 0)
+		--yyg->yy_buffer_stack_top;
+
+	if (YY_CURRENT_BUFFER) {
+		cmDependsJava_yy_load_buffer_state(yyscanner );
+		yyg->yy_did_buffer_switch_on_eof = 1;
+	}
 }
 
 /* Allocates the stack if it does not exist.
@@ -2087,42 +2247,46 @@ void cmDependsJava_yypop_buffer_state (yyscan_t yyscanner)
  */
 static void cmDependsJava_yyensure_buffer_stack (yyscan_t yyscanner)
 {
-  int nuto_alloc;
+	int num_to_alloc;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-  if (!yyg->yy_buffer_stack) {
+	if (!yyg->yy_buffer_stack) {
 
-    /* First allocation is just for 2 elements, since we don't know if this
-     * scanner will even need a stack. We use 2 instead of 1 to avoid an
-     * immediate realloc on the next call.
+		/* First allocation is just for 2 elements, since we don't know if this
+		 * scanner will even need a stack. We use 2 instead of 1 to avoid an
+		 * immediate realloc on the next call.
          */
-    nuto_alloc = 1;
-    yyg->yy_buffer_stack = (struct yy_buffer_state**)cmDependsJava_yyalloc
-                (nuto_alloc * sizeof(struct yy_buffer_state*)
-                , yyscanner);
-
-    memset(yyg->yy_buffer_stack, 0, nuto_alloc * sizeof(struct yy_buffer_state*));
-
-    yyg->yy_buffer_stack_max = nuto_alloc;
-    yyg->yy_buffer_stack_top = 0;
-    return;
-  }
-
-  if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
-
-    /* Increase the buffer to prepare for a possible push. */
-    int grow_size = 8 /* arbitrary grow size */;
-
-    nuto_alloc = yyg->yy_buffer_stack_max + grow_size;
-    yyg->yy_buffer_stack = (struct yy_buffer_state**)cmDependsJava_yyrealloc
-                (yyg->yy_buffer_stack,
-                nuto_alloc * sizeof(struct yy_buffer_state*)
-                , yyscanner);
-
-    /* zero only the new slots.*/
-    memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
-    yyg->yy_buffer_stack_max = nuto_alloc;
-  }
+      num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
+		yyg->yy_buffer_stack = (struct yy_buffer_state**)cmDependsJava_yyalloc
+								(num_to_alloc * sizeof(struct yy_buffer_state*)
+								, yyscanner);
+		if ( ! yyg->yy_buffer_stack )
+			YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yyensure_buffer_stack()" );
+
+		memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
+
+		yyg->yy_buffer_stack_max = num_to_alloc;
+		yyg->yy_buffer_stack_top = 0;
+		return;
+	}
+
+	if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
+
+		/* Increase the buffer to prepare for a possible push. */
+		yy_size_t grow_size = 8 /* arbitrary grow size */;
+
+		num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
+		yyg->yy_buffer_stack = (struct yy_buffer_state**)cmDependsJava_yyrealloc
+								(yyg->yy_buffer_stack,
+								num_to_alloc * sizeof(struct yy_buffer_state*)
+								, yyscanner);
+		if ( ! yyg->yy_buffer_stack )
+			YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yyensure_buffer_stack()" );
+
+		/* zero only the new slots.*/
+		memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
+		yyg->yy_buffer_stack_max = num_to_alloc;
+	}
 }
 
 /** Setup the input buffer state to scan directly from a user-specified character buffer.
@@ -2133,110 +2297,112 @@ static void cmDependsJava_yyensure_buffer_stack (yyscan_t yyscanner)
  */
 YY_BUFFER_STATE cmDependsJava_yy_scan_buffer  (char * base, yy_size_t  size , yyscan_t yyscanner)
 {
-  YY_BUFFER_STATE b;
-
-  if ( size < 2 ||
-       base[size-2] != YY_END_OF_BUFFER_CHAR ||
-       base[size-1] != YY_END_OF_BUFFER_CHAR )
-    /* They forgot to leave room for the EOB's. */
-    return 0;
-
-  b = (YY_BUFFER_STATE) cmDependsJava_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
-  if ( ! b )
-    YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yy_scan_buffer()" );
-
-  b->yy_buf_size = size - 2;  /* "- 2" to take care of EOB's */
-  b->yy_buf_pos = b->yy_ch_buf = base;
-  b->yy_is_our_buffer = 0;
-  b->yy_input_file = 0;
-  b->yy_n_chars = b->yy_buf_size;
-  b->yy_is_interactive = 0;
-  b->yy_at_bol = 1;
-  b->yy_fill_buffer = 0;
-  b->yy_buffer_status = YY_BUFFER_NEW;
-
-  cmDependsJava_yy_switch_to_buffer(b ,yyscanner );
-
-  return b;
+	YY_BUFFER_STATE b;
+
+	if ( size < 2 ||
+	     base[size-2] != YY_END_OF_BUFFER_CHAR ||
+	     base[size-1] != YY_END_OF_BUFFER_CHAR )
+		/* They forgot to leave room for the EOB's. */
+		return NULL;
+
+	b = (YY_BUFFER_STATE) cmDependsJava_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+	if ( ! b )
+		YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yy_scan_buffer()" );
+
+	b->yy_buf_size = size - 2;	/* "- 2" to take care of EOB's */
+	b->yy_buf_pos = b->yy_ch_buf = base;
+	b->yy_is_our_buffer = 0;
+	b->yy_input_file = NULL;
+	b->yy_n_chars = b->yy_buf_size;
+	b->yy_is_interactive = 0;
+	b->yy_at_bol = 1;
+	b->yy_fill_buffer = 0;
+	b->yy_buffer_status = YY_BUFFER_NEW;
+
+	cmDependsJava_yy_switch_to_buffer(b ,yyscanner );
+
+	return b;
 }
 
 /** Setup the input buffer state to scan a string. The next call to cmDependsJava_yylex() will
- * scan from a @e copy of @a yy_str.
- * @param yy_str a NUL-terminated string to scan
+ * scan from a @e copy of @a str.
+ * @param yystr a NUL-terminated string to scan
  * @param yyscanner The scanner object.
  * @return the newly allocated buffer state object.
  * @note If you want to scan bytes that may contain NUL values, then use
  *       cmDependsJava_yy_scan_bytes() instead.
  */
-YY_BUFFER_STATE cmDependsJava_yy_scan_string (yyconst char * yy_str , yyscan_t yyscanner)
+YY_BUFFER_STATE cmDependsJava_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner)
 {
 
-  return cmDependsJava_yy_scan_bytes(yy_str,strlen(yy_str) ,yyscanner);
+	return cmDependsJava_yy_scan_bytes(yystr,(int) strlen(yystr) ,yyscanner);
 }
 
 /** Setup the input buffer state to scan the given bytes. The next call to cmDependsJava_yylex() will
  * scan from a @e copy of @a bytes.
- * @param bytes the byte buffer to scan
- * @param len the number of bytes in the buffer pointed to by @a bytes.
+ * @param yybytes the byte buffer to scan
+ * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
  * @param yyscanner The scanner object.
  * @return the newly allocated buffer state object.
  */
-YY_BUFFER_STATE cmDependsJava_yy_scan_bytes  (yyconst char * bytes, int  len , yyscan_t yyscanner)
+YY_BUFFER_STATE cmDependsJava_yy_scan_bytes  (yyconst char * yybytes, int  _yybytes_len , yyscan_t yyscanner)
 {
-  YY_BUFFER_STATE b;
-  char *buf;
-  yy_size_t n;
-  int i;
+	YY_BUFFER_STATE b;
+	char *buf;
+	yy_size_t n;
+	yy_size_t i;
 
-  /* Get memory for full buffer, including space for trailing EOB's. */
-  n = len + 2;
-  buf = (char *) cmDependsJava_yyalloc(n ,yyscanner );
-  if ( ! buf )
-    YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yy_scan_bytes()" );
+	/* Get memory for full buffer, including space for trailing EOB's. */
+	n = (yy_size_t) _yybytes_len + 2;
+	buf = (char *) cmDependsJava_yyalloc(n ,yyscanner );
+	if ( ! buf )
+		YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yy_scan_bytes()" );
 
-  for ( i = 0; i < len; ++i )
-    buf[i] = bytes[i];
+	for ( i = 0; i < (size_t)_yybytes_len; ++i )
+		buf[i] = yybytes[i];
 
-  buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR;
+	buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
 
-  b = cmDependsJava_yy_scan_buffer(buf,n ,yyscanner);
-  if ( ! b )
-    YY_FATAL_ERROR( "bad buffer in cmDependsJava_yy_scan_bytes()" );
+	b = cmDependsJava_yy_scan_buffer(buf,n ,yyscanner);
+	if ( ! b )
+		YY_FATAL_ERROR( "bad buffer in cmDependsJava_yy_scan_bytes()" );
 
-  /* It's okay to grow etc. this buffer, and we should throw it
-   * away when we're done.
-   */
-  b->yy_is_our_buffer = 1;
+	/* It's okay to grow etc. this buffer, and we should throw it
+	 * away when we're done.
+	 */
+	b->yy_is_our_buffer = 1;
 
-  return b;
+	return b;
 }
 
 #ifndef YY_EXIT_FAILURE
 #define YY_EXIT_FAILURE 2
 #endif
 
-static void yy_fatal_error (yyconst char* msg , yyscan_t)
+static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
 {
-      (void) fprintf( stderr, "%s\n", msg );
-  exit( YY_EXIT_FAILURE );
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+	(void) fprintf( stderr, "%s\n", msg );
+	exit( YY_EXIT_FAILURE );
 }
 
 /* Redefine yyless() so it works in section 3 code. */
 
 #undef yyless
 #define yyless(n) \
-  do \
-    { \
-    /* Undo effects of setting up yytext. */ \
+	do \
+		{ \
+		/* Undo effects of setting up yytext. */ \
         int yyless_macro_arg = (n); \
         YY_LESS_LINENO(yyless_macro_arg);\
-    yytext[yyleng] = yyg->yy_hold_char; \
-    yyg->yy_c_buf_p = yytext + yyless_macro_arg; \
-    yyg->yy_hold_char = *yyg->yy_c_buf_p; \
-    *yyg->yy_c_buf_p = '\0'; \
-    yyleng = yyless_macro_arg; \
-    } \
-  while ( 0 )
+		yytext[yyleng] = yyg->yy_hold_char; \
+		yyg->yy_c_buf_p = yytext + yyless_macro_arg; \
+		yyg->yy_hold_char = *yyg->yy_c_buf_p; \
+		*yyg->yy_c_buf_p = '\0'; \
+		yyleng = yyless_macro_arg; \
+		} \
+	while ( 0 )
 
 /* Accessor  methods (get/set functions) to struct members. */
 
@@ -2323,51 +2489,51 @@ void cmDependsJava_yyset_extra (YY_EXTRA_TYPE  user_defined , yyscan_t yyscanner
 }
 
 /** Set the current line number.
- * @param line_number The line number to set.
+ * @param _line_number line number
  * @param yyscanner The scanner object.
  */
-void cmDependsJava_yyset_lineno (int  line_number , yyscan_t yyscanner)
+void cmDependsJava_yyset_lineno (int  _line_number , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
         /* lineno is only valid if an input buffer exists. */
         if (! YY_CURRENT_BUFFER )
-           yy_fatal_error( "cmDependsJava_yyset_lineno called with no buffer" , yyscanner);
+           YY_FATAL_ERROR( "cmDependsJava_yyset_lineno called with no buffer" );
 
-    yylineno = line_number;
+    yylineno = _line_number;
 }
 
 /** Set the current column.
- * @param column_no The column number to set.
+ * @param _column_no column number
  * @param yyscanner The scanner object.
  */
-void cmDependsJava_yyset_column (int  column_no , yyscan_t yyscanner)
+void cmDependsJava_yyset_column (int  _column_no , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
         /* column is only valid if an input buffer exists. */
         if (! YY_CURRENT_BUFFER )
-           yy_fatal_error( "cmDependsJava_yyset_column called with no buffer" , yyscanner);
+           YY_FATAL_ERROR( "cmDependsJava_yyset_column called with no buffer" );
 
-    yycolumn = column_no;
+    yycolumn = _column_no;
 }
 
 /** Set the input stream. This does not discard the current
  * input buffer.
- * @param in_str A readable stream.
+ * @param _in_str A readable stream.
  * @param yyscanner The scanner object.
  * @see cmDependsJava_yy_switch_to_buffer
  */
-void cmDependsJava_yyset_in (FILE *  in_str , yyscan_t yyscanner)
+void cmDependsJava_yyset_in (FILE *  _in_str , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-    yyin = in_str ;
+    yyin = _in_str ;
 }
 
-void cmDependsJava_yyset_out (FILE *  out_str , yyscan_t yyscanner)
+void cmDependsJava_yyset_out (FILE *  _out_str , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-    yyout = out_str ;
+    yyout = _out_str ;
 }
 
 int cmDependsJava_yyget_debug  (yyscan_t yyscanner)
@@ -2376,45 +2542,14 @@ int cmDependsJava_yyget_debug  (yyscan_t yyscanner)
     return yy_flex_debug;
 }
 
-void cmDependsJava_yyset_debug (int  bdebug , yyscan_t yyscanner)
+void cmDependsJava_yyset_debug (int  _bdebug , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-    yy_flex_debug = bdebug ;
+    yy_flex_debug = _bdebug ;
 }
 
 /* Accessor methods for yylval and yylloc */
 
-static int yy_init_globals (yyscan_t yyscanner)
-{
-    struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-    /* Initialization is the same as for the non-reentrant scanner.
-       This function is called once per scanner lifetime. */
-
-    yyg->yy_buffer_stack = 0;
-    yyg->yy_buffer_stack_top = 0;
-    yyg->yy_buffer_stack_max = 0;
-    yyg->yy_c_buf_p = (char *) 0;
-    yyg->yy_init = 1;
-    yyg->yy_start = 0;
-    yyg->yy_start_stack_ptr = 0;
-    yyg->yy_start_stack_depth = 0;
-    yyg->yy_start_stack = (int *) 0;
-
-/* Defined in main.c */
-#ifdef YY_STDINIT
-    yyin = stdin;
-    yyout = stdout;
-#else
-    yyin = (FILE *) 0;
-    yyout = (FILE *) 0;
-#endif
-
-    /* For future reference: Set errno on error, since we are called by
-     * cmDependsJava_yylex_init()
-     */
-    return 0;
-}
-
 /* User-visible API */
 
 /* cmDependsJava_yylex_init is special because it creates the scanner itself, so it is
@@ -2437,33 +2572,108 @@ int cmDependsJava_yylex_init(yyscan_t* ptr_yy_globals)
         return 1;
     }
 
-    memset(*ptr_yy_globals,0,sizeof(struct yyguts_t));
+    /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */
+    memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
 
     return yy_init_globals ( *ptr_yy_globals );
 }
 
+/* cmDependsJava_yylex_init_extra has the same functionality as cmDependsJava_yylex_init, but follows the
+ * convention of taking the scanner as the last argument. Note however, that
+ * this is a *pointer* to a scanner, as it will be allocated by this call (and
+ * is the reason, too, why this function also must handle its own declaration).
+ * The user defined value in the first argument will be available to cmDependsJava_yyalloc in
+ * the yyextra field.
+ */
+
+int cmDependsJava_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals )
+
+{
+    struct yyguts_t dummy_yyguts;
+
+    cmDependsJava_yyset_extra (yy_user_defined, &dummy_yyguts);
+
+    if (ptr_yy_globals == NULL){
+        errno = EINVAL;
+        return 1;
+    }
+
+    *ptr_yy_globals = (yyscan_t) cmDependsJava_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
+
+    if (*ptr_yy_globals == NULL){
+        errno = ENOMEM;
+        return 1;
+    }
+
+    /* By setting to 0xAA, we expose bugs in
+    yy_init_globals. Leave at 0x00 for releases. */
+    memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
+
+    cmDependsJava_yyset_extra (yy_user_defined, *ptr_yy_globals);
+
+    return yy_init_globals ( *ptr_yy_globals );
+}
+
+static int yy_init_globals (yyscan_t yyscanner)
+{
+    struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+    /* Initialization is the same as for the non-reentrant scanner.
+     * This function is called from cmDependsJava_yylex_destroy(), so don't allocate here.
+     */
+
+    yyg->yy_buffer_stack = NULL;
+    yyg->yy_buffer_stack_top = 0;
+    yyg->yy_buffer_stack_max = 0;
+    yyg->yy_c_buf_p = NULL;
+    yyg->yy_init = 0;
+    yyg->yy_start = 0;
+
+    yyg->yy_start_stack_ptr = 0;
+    yyg->yy_start_stack_depth = 0;
+    yyg->yy_start_stack =  NULL;
+
+/* Defined in main.c */
+#ifdef YY_STDINIT
+    yyin = stdin;
+    yyout = stdout;
+#else
+    yyin = NULL;
+    yyout = NULL;
+#endif
+
+    /* For future reference: Set errno on error, since we are called by
+     * cmDependsJava_yylex_init()
+     */
+    return 0;
+}
+
 /* cmDependsJava_yylex_destroy is for both reentrant and non-reentrant scanners. */
 int cmDependsJava_yylex_destroy  (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
     /* Pop the buffer stack, destroying each element. */
-  while(YY_CURRENT_BUFFER){
-    cmDependsJava_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
-    YY_CURRENT_BUFFER_LVALUE = NULL;
-    cmDependsJava_yypop_buffer_state(yyscanner);
-  }
+	while(YY_CURRENT_BUFFER){
+		cmDependsJava_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
+		YY_CURRENT_BUFFER_LVALUE = NULL;
+		cmDependsJava_yypop_buffer_state(yyscanner);
+	}
 
-  /* Destroy the stack itself. */
-  cmDependsJava_yyfree(yyg->yy_buffer_stack ,yyscanner);
-  yyg->yy_buffer_stack = NULL;
+	/* Destroy the stack itself. */
+	cmDependsJava_yyfree(yyg->yy_buffer_stack ,yyscanner);
+	yyg->yy_buffer_stack = NULL;
 
     /* Destroy the start condition stack. */
         cmDependsJava_yyfree(yyg->yy_start_stack ,yyscanner );
         yyg->yy_start_stack = NULL;
 
+    /* Reset the globals. This is important in a non-reentrant scanner so the next time
+     * cmDependsJava_yylex() is called, initialization will occur. */
+    yy_init_globals( yyscanner);
+
     /* Destroy the main struct (reentrant only). */
     cmDependsJava_yyfree ( yyscanner , yyscanner );
+    yyscanner = NULL;
     return 0;
 }
 
@@ -2474,62 +2684,55 @@ int cmDependsJava_yylex_destroy  (yyscan_t yyscanner)
 #ifndef yytext_ptr
 static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner)
 {
-  int i;
-    struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  for ( i = 0; i < n; ++i )
-    s1[i] = s2[i];
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+
+	int i;
+	for ( i = 0; i < n; ++i )
+		s1[i] = s2[i];
 }
 #endif
 
 #ifdef YY_NEED_STRLEN
 static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
 {
-  int n;
-    struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  for ( n = 0; s[n]; ++n )
-    ;
+	int n;
+	for ( n = 0; s[n]; ++n )
+		;
 
-  return n;
+	return n;
 }
 #endif
 
-void *cmDependsJava_yyalloc (yy_size_t  size , yyscan_t)
+void *cmDependsJava_yyalloc (yy_size_t  size , yyscan_t yyscanner)
 {
-  return (void *) malloc( size );
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+	return malloc(size);
 }
 
-void *cmDependsJava_yyrealloc  (void * ptr, yy_size_t  size , yyscan_t)
+void *cmDependsJava_yyrealloc  (void * ptr, yy_size_t  size , yyscan_t yyscanner)
 {
-  /* The cast to (char *) in the following accommodates both
-   * implementations that use char* generic pointers, and those
-   * that use void* generic pointers.  It works with the latter
-   * because both ANSI C and C++ allow castless assignment from
-   * any pointer type to void*, and deal with argument conversions
-   * as though doing an assignment.
-   */
-  return (void *) realloc( (char *) ptr, size );
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+
+	/* The cast to (char *) in the following accommodates both
+	 * implementations that use char* generic pointers, and those
+	 * that use void* generic pointers.  It works with the latter
+	 * because both ANSI C and C++ allow castless assignment from
+	 * any pointer type to void*, and deal with argument conversions
+	 * as though doing an assignment.
+	 */
+	return realloc(ptr, size);
 }
 
-void cmDependsJava_yyfree (void * ptr , yyscan_t)
+void cmDependsJava_yyfree (void * ptr , yyscan_t yyscanner)
 {
-  free( (char *) ptr );  /* see cmDependsJava_yyrealloc() for (char *) cast */
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+	free( (char *) ptr );	/* see cmDependsJava_yyrealloc() for (char *) cast */
 }
 
 #define YYTABLES_NAME "yytables"
 
-#undef YY_NEW_FILE
-#undef YY_FLUSH_BUFFER
-#undef yy_set_bol
-#undef yy_new_buffer
-#undef yy_set_interactive
-#undef yytext_ptr
-#undef YY_DO_BEFORE_ACTION
-
-#ifdef YY_DECL_IS_OURS
-#undef YY_DECL_IS_OURS
-#undef YY_DECL
-#endif
-#line 214 "cmDependsJavaLexer.in.l"
-
-
-
+#line 174 "cmDependsJavaLexer.in.l"
diff --git a/Source/cmDependsJavaLexer.h b/Source/cmDependsJavaLexer.h
index e82db26..ccadd70 100644
--- a/Source/cmDependsJavaLexer.h
+++ b/Source/cmDependsJavaLexer.h
@@ -1,17 +1,20 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmDependsJava_yyHEADER_H
 #define cmDependsJava_yyHEADER_H 1
 #define cmDependsJava_yyIN_HEADER 1
 
+#line 6 "cmDependsJavaLexer.h"
+
+#line 8 "cmDependsJavaLexer.h"
+
+#define FLEXINT_H 1
 #define  YY_INT_ALIGNED short int
 
 /* A lexical scanner generated by flex */
 
 #define FLEX_SCANNER
 #define YY_FLEX_MAJOR_VERSION 2
-#define YY_FLEX_MINOR_VERSION 5
-#define YY_FLEX_SUBMINOR_VERSION 31
+#define YY_FLEX_MINOR_VERSION 6
+#define YY_FLEX_SUBMINOR_VERSION 1
 #if YY_FLEX_SUBMINOR_VERSION > 0
 #define FLEX_BETA
 #endif
@@ -24,10 +27,6 @@
 #include <errno.h>
 #include <stdlib.h>
 
-#if defined(__BEOS__) || defined(__HAIKU__)
-#include <unistd.h>   /* prevents a conflict with a #define later on... */
-#endif
-
 /* end standard C headers. */
 
 /* flex integer type definitions */
@@ -37,7 +36,15 @@
 
 /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
 
-#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L
+#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+
+/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
+ * if you want the limit (max/min) macros for int types.
+ */
+#ifndef __STDC_LIMIT_MACROS
+#define __STDC_LIMIT_MACROS 1
+#endif
+
 #include <inttypes.h>
 typedef int8_t flex_int8_t;
 typedef uint8_t flex_uint8_t;
@@ -52,7 +59,6 @@ typedef int flex_int32_t;
 typedef unsigned char flex_uint8_t;
 typedef unsigned short int flex_uint16_t;
 typedef unsigned int flex_uint32_t;
-#endif /* ! C99 */
 
 /* Limits of integral types. */
 #ifndef INT8_MIN
@@ -83,26 +89,17 @@ typedef unsigned int flex_uint32_t;
 #define UINT32_MAX             (4294967295U)
 #endif
 
-#endif /* ! FLEXINT_H */
-
-#ifdef __cplusplus
-
-/* The "const" storage-class-modifier is valid. */
-#define YY_USE_CONST
-
-#else  /* ! __cplusplus */
-
-#if __STDC__
-
-#define YY_USE_CONST
+#endif /* ! C99 */
 
-#endif  /* __STDC__ */
-#endif  /* ! __cplusplus */
+#endif /* ! FLEXINT_H */
 
-#ifdef YY_USE_CONST
+/* TODO: this is always defined, so inline it */
 #define yyconst const
+
+#if defined(__GNUC__) && __GNUC__ >= 3
+#define yynoreturn __attribute__((__noreturn__))
 #else
-#define yyconst
+#define yynoreturn
 #endif
 
 /* An opaque pointer. */
@@ -122,91 +119,91 @@ typedef void* yyscan_t;
 #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column)
 #define yy_flex_debug yyg->yy_flex_debug_r
 
-int cmDependsJava_yylex_init (yyscan_t* scanner);
+/* Size of default input buffer. */
+#ifndef YY_BUF_SIZE
+#ifdef __ia64__
+/* On IA-64, the buffer size is 16k, not 8k.
+ * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case.
+ * Ditto for the __ia64__ case accordingly.
+ */
+#define YY_BUF_SIZE 32768
+#else
+#define YY_BUF_SIZE 16384
+#endif /* __ia64__ */
+#endif
 
 #ifndef YY_TYPEDEF_YY_BUFFER_STATE
 #define YY_TYPEDEF_YY_BUFFER_STATE
 typedef struct yy_buffer_state *YY_BUFFER_STATE;
 #endif
 
-/* The following is because we cannot portably get our hands on size_t
- * (without autoconf's help, which isn't available because we want
- * flex-generated scanners to compile on their own).
- */
-
 #ifndef YY_TYPEDEF_YY_SIZE_T
 #define YY_TYPEDEF_YY_SIZE_T
-typedef unsigned int yy_size_t;
+typedef size_t yy_size_t;
 #endif
 
 #ifndef YY_STRUCT_YY_BUFFER_STATE
 #define YY_STRUCT_YY_BUFFER_STATE
 struct yy_buffer_state
-  {
-  FILE *yy_input_file;
-
-  char *yy_ch_buf;    /* input buffer */
-  char *yy_buf_pos;    /* current position in input buffer */
-
-  /* Size of input buffer in bytes, not including room for EOB
-   * characters.
-   */
-  yy_size_t yy_buf_size;
-
-  /* Number of characters read into yy_ch_buf, not including EOB
-   * characters.
-   */
-  int yy_n_chars;
-
-  /* Whether we "own" the buffer - i.e., we know we created it,
-   * and can realloc() it to grow it, and should free() it to
-   * delete it.
-   */
-  int yy_is_our_buffer;
-
-  /* Whether this is an "interactive" input source; if so, and
-   * if we're using stdio for input, then we want to use getc()
-   * instead of fread(), to make sure we stop fetching input after
-   * each newline.
-   */
-  int yy_is_interactive;
-
-  /* Whether we're considered to be at the beginning of a line.
-   * If so, '^' rules will be active on the next match, otherwise
-   * not.
-   */
-  int yy_at_bol;
+	{
+	FILE *yy_input_file;
+
+	char *yy_ch_buf;		/* input buffer */
+	char *yy_buf_pos;		/* current position in input buffer */
+
+	/* Size of input buffer in bytes, not including room for EOB
+	 * characters.
+	 */
+	int yy_buf_size;
+
+	/* Number of characters read into yy_ch_buf, not including EOB
+	 * characters.
+	 */
+	int yy_n_chars;
+
+	/* Whether we "own" the buffer - i.e., we know we created it,
+	 * and can realloc() it to grow it, and should free() it to
+	 * delete it.
+	 */
+	int yy_is_our_buffer;
+
+	/* Whether this is an "interactive" input source; if so, and
+	 * if we're using stdio for input, then we want to use getc()
+	 * instead of fread(), to make sure we stop fetching input after
+	 * each newline.
+	 */
+	int yy_is_interactive;
+
+	/* Whether we're considered to be at the beginning of a line.
+	 * If so, '^' rules will be active on the next match, otherwise
+	 * not.
+	 */
+	int yy_at_bol;
 
     int yy_bs_lineno; /**< The line count. */
     int yy_bs_column; /**< The column count. */
 
-  /* Whether to try to fill the input buffer when we reach the
-   * end of it.
-   */
-  int yy_fill_buffer;
+	/* Whether to try to fill the input buffer when we reach the
+	 * end of it.
+	 */
+	int yy_fill_buffer;
 
-  int yy_buffer_status;
+	int yy_buffer_status;
 
-  };
+	};
 #endif /* !YY_STRUCT_YY_BUFFER_STATE */
 
 void cmDependsJava_yyrestart (FILE *input_file ,yyscan_t yyscanner );
-void cmDependsJava_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,
-                                        yyscan_t yyscanner );
-YY_BUFFER_STATE cmDependsJava_yy_create_buffer (FILE *file,int size ,
-                                                yyscan_t yyscanner );
+void cmDependsJava_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
+YY_BUFFER_STATE cmDependsJava_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner );
 void cmDependsJava_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
 void cmDependsJava_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmDependsJava_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,
-                                        yyscan_t yyscanner );
+void cmDependsJava_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
 void cmDependsJava_yypop_buffer_state (yyscan_t yyscanner );
 
-YY_BUFFER_STATE cmDependsJava_yy_scan_buffer (char *base,yy_size_t size ,
-                                              yyscan_t yyscanner );
-YY_BUFFER_STATE cmDependsJava_yy_scan_string (yyconst char *yy_str ,
-                                              yyscan_t yyscanner );
-YY_BUFFER_STATE cmDependsJava_yy_scan_bytes (yyconst char *bytes,int len ,
-                                             yyscan_t yyscanner );
+YY_BUFFER_STATE cmDependsJava_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
+YY_BUFFER_STATE cmDependsJava_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
+YY_BUFFER_STATE cmDependsJava_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
 
 void *cmDependsJava_yyalloc (yy_size_t ,yyscan_t yyscanner );
 void *cmDependsJava_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
@@ -214,7 +211,7 @@ void cmDependsJava_yyfree (void * ,yyscan_t yyscanner );
 
 /* Begin user sect3 */
 
-#define cmDependsJava_yywrap(n) 1
+#define cmDependsJava_yywrap(yyscanner) (/*CONSTCOND*/1)
 #define YY_SKIP_YYWRAP
 
 #define yytext_ptr yytext_r
@@ -230,6 +227,10 @@ void cmDependsJava_yyfree (void * ,yyscan_t yyscanner );
 #define YY_EXTRA_TYPE void *
 #endif
 
+int cmDependsJava_yylex_init (yyscan_t* scanner);
+
+int cmDependsJava_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
+
 /* Accessor methods to globals.
    These are made visible to non-reentrant scanners for convenience. */
 
@@ -241,24 +242,27 @@ void cmDependsJava_yyset_debug (int debug_flag ,yyscan_t yyscanner );
 
 YY_EXTRA_TYPE cmDependsJava_yyget_extra (yyscan_t yyscanner );
 
-void cmDependsJava_yyset_extra (YY_EXTRA_TYPE user_defined ,
-                                yyscan_t yyscanner );
+void cmDependsJava_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
 
 FILE *cmDependsJava_yyget_in (yyscan_t yyscanner );
 
-void cmDependsJava_yyset_in  (FILE * in_str ,yyscan_t yyscanner );
+void cmDependsJava_yyset_in  (FILE * _in_str ,yyscan_t yyscanner );
 
 FILE *cmDependsJava_yyget_out (yyscan_t yyscanner );
 
-void cmDependsJava_yyset_out  (FILE * out_str ,yyscan_t yyscanner );
+void cmDependsJava_yyset_out  (FILE * _out_str ,yyscan_t yyscanner );
 
-int cmDependsJava_yyget_leng (yyscan_t yyscanner );
+			int cmDependsJava_yyget_leng (yyscan_t yyscanner );
 
 char *cmDependsJava_yyget_text (yyscan_t yyscanner );
 
 int cmDependsJava_yyget_lineno (yyscan_t yyscanner );
 
-void cmDependsJava_yyset_lineno (int line_number ,yyscan_t yyscanner );
+void cmDependsJava_yyset_lineno (int _line_number ,yyscan_t yyscanner );
+
+int cmDependsJava_yyget_column  (yyscan_t yyscanner );
+
+void cmDependsJava_yyset_column (int _column_no ,yyscan_t yyscanner );
 
 /* Macros after this point can all be overridden by user definitions in
  * section 1.
@@ -286,7 +290,12 @@ static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
 
 /* Amount of stuff to slurp up with each read. */
 #ifndef YY_READ_BUF_SIZE
+#ifdef __ia64__
+/* On IA-64, the buffer size is 16k, not 8k */
+#define YY_READ_BUF_SIZE 16384
+#else
 #define YY_READ_BUF_SIZE 8192
+#endif /* __ia64__ */
 #endif
 
 /* Number of entries by which start-condition stack grows. */
@@ -305,15 +314,13 @@ extern int cmDependsJava_yylex (yyscan_t yyscanner);
 #define YY_DECL int cmDependsJava_yylex (yyscan_t yyscanner)
 #endif /* !YY_DECL */
 
-/* yy_get_previous_state - get the state just before the
-   EOB char was reached */
+/* yy_get_previous_state - get the state just before the EOB char was reached */
 
 #undef YY_NEW_FILE
 #undef YY_FLUSH_BUFFER
 #undef yy_set_bol
 #undef yy_new_buffer
 #undef yy_set_interactive
-#undef yytext_ptr
 #undef YY_DO_BEFORE_ACTION
 
 #ifdef YY_DECL_IS_OURS
@@ -321,5 +328,9 @@ extern int cmDependsJava_yylex (yyscan_t yyscanner);
 #undef YY_DECL
 #endif
 
+#line 174 "cmDependsJavaLexer.in.l"
+
+
+#line 335 "cmDependsJavaLexer.h"
 #undef cmDependsJava_yyIN_HEADER
 #endif /* cmDependsJava_yyHEADER_H */
diff --git a/Source/cmDependsJavaLexer.in.l b/Source/cmDependsJavaLexer.in.l
index fcc5693..8cb42b1 100644
--- a/Source/cmDependsJavaLexer.in.l
+++ b/Source/cmDependsJavaLexer.in.l
@@ -3,29 +3,23 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
-This file must be translated to C and modified to build everywhere.
+This file must be translated to C++ and modified to build everywhere.
 
-Run flex like this:
+Run flex >= 2.6 like this:
 
-  flex --prefix=cmDependsJava_yy --header-file=cmDependsJavaLexer.h -ocmDependsJavaLexer.cxx cmDependsJavaLexer.in.l
+  flex --nounistd -DFLEXINT_H --prefix=cmDependsJava_yy --header-file=cmDependsJavaLexer.h -ocmDependsJavaLexer.cxx cmDependsJavaLexer.in.l
 
-Modify cmDependsJavaLexer.c:
-  - remove TABs
-  - remove use of the 'register' storage class specifier
-  - remove "yyscanner" argument from these methods:
-      yy_fatal_error, cmDependsJava_yyalloc, cmDependsJava_yyrealloc, cmDependsJava_yyfree
-  - remove all YY_BREAK lines occurring right after return statements
-  - change while ( 1 ) to for(;;)
-
-Modify cmDependsJavaLexer.h:
-  - remove TABs
-  - remove the yy_init_globals function
-  - remove the block that includes unistd.h
-  - remove #line directives (avoids bogus warning on old Sun)
+Modify cmDependsJavaLexer.cxx:
+  - remove trailing whitespace: sed -i 's/\s*$//' cmDependsJavaLexer.h cmDependsJavaLexer.cxx
+  - remove blank lines at end of file
+  - #include "cmStandardLexer.h" at the top
+  - add cast in yy_scan_bytes for loop condition of _yybytes_len to size_t
 
 */
 
-#include "cmStandardLexer.h"
+/* IWYU pragma: no_forward_declare yyguts_t */
+
+#include <iostream>
 
 #include "cmDependsJavaParserHelper.h"
 
@@ -170,7 +164,7 @@ null { PRIMITIVE; return jp_NULLLITERAL; }
 
 \/\/.*\n { }
 [ \f\t\n\r] { }
-. 	{
+. {
   std::cerr << "Unknown character: " << yytext[0]
     << " (" << (int)yytext[0] << ")" << std::endl;
   yyextra->Error("Unknown character");
diff --git a/Source/cmDependsJavaParserHelper.cxx b/Source/cmDependsJavaParserHelper.cxx
index b5d68d0..f5998ef 100644
--- a/Source/cmDependsJavaParserHelper.cxx
+++ b/Source/cmDependsJavaParserHelper.cxx
@@ -35,7 +35,7 @@ cmDependsJavaParserHelper::~cmDependsJavaParserHelper()
 void cmDependsJavaParserHelper::CurrentClass::AddFileNamesForPrinting(
   std::vector<std::string>* files, const char* prefix, const char* sep) const
 {
-  std::string rname = "";
+  std::string rname;
   if (prefix) {
     rname += prefix;
     rname += sep;
@@ -341,7 +341,7 @@ int cmDependsJavaParserHelper::ParseFile(const char* file)
     return 0;
   }
 
-  std::string fullfile = "";
+  std::string fullfile;
   std::string line;
   while (cmSystemTools::GetLineFromStream(ifs, line)) {
     fullfile += line + "\n";
diff --git a/Source/cmDependsJavaParserHelper.h b/Source/cmDependsJavaParserHelper.h
index 1597ea7..71b939c 100644
--- a/Source/cmDependsJavaParserHelper.h
+++ b/Source/cmDependsJavaParserHelper.h
@@ -8,6 +8,8 @@
 #include <string>
 #include <vector>
 
+class cmDependsJavaParserHelper;
+
 #define YYSTYPE cmDependsJavaParserHelper::ParserType
 #define YYSTYPE_IS_DECLARED
 #define YY_EXTRA_TYPE cmDependsJavaParserHelper*
diff --git a/Source/cmDocumentationFormatter.cxx b/Source/cmDocumentationFormatter.cxx
index 21a5209..0018263 100644
--- a/Source/cmDocumentationFormatter.cxx
+++ b/Source/cmDocumentationFormatter.cxx
@@ -156,7 +156,7 @@ void cmDocumentationFormatter::PrintColumn(std::ostream& os, const char* text)
 
     // Move to beginning of next word.  Skip over whitespace.
     l = r;
-    while (*l && (*l == ' ')) {
+    while (*l == ' ') {
       ++l;
     }
   }
diff --git a/Source/cmELF.cxx b/Source/cmELF.cxx
index 2d86674..0655da9 100644
--- a/Source/cmELF.cxx
+++ b/Source/cmELF.cxx
@@ -132,18 +132,13 @@ public:
 
   // Forward to the per-class implementation.
   virtual unsigned int GetNumberOfSections() const = 0;
-  virtual unsigned int GetDynamicEntryCount() = 0;
   virtual unsigned long GetDynamicEntryPosition(int j) = 0;
+  virtual cmELF::DynamicEntryList GetDynamicEntries() = 0;
+  virtual std::vector<char> EncodeDynamicEntries(
+    const cmELF::DynamicEntryList&) = 0;
   virtual StringEntry const* GetDynamicSectionString(unsigned int tag) = 0;
   virtual void PrintInfo(std::ostream& os) const = 0;
 
-  bool ReadBytes(unsigned long pos, unsigned long size, char* buf)
-  {
-    this->Stream.seekg(pos);
-    this->Stream.read(buf, size);
-    return !this->Stream.fail();
-  }
-
   // Lookup the SONAME in the DYNAMIC section.
   StringEntry const* GetSOName()
   {
@@ -246,10 +241,13 @@ public:
     return static_cast<unsigned int>(this->ELFHeader.e_shnum);
   }
 
-  // Get the file position and size of a dynamic section entry.
-  unsigned int GetDynamicEntryCount() CM_OVERRIDE;
+  // Get the file position of a dynamic section entry.
   unsigned long GetDynamicEntryPosition(int j) CM_OVERRIDE;
 
+  cmELF::DynamicEntryList GetDynamicEntries() CM_OVERRIDE;
+  std::vector<char> EncodeDynamicEntries(const cmELF::DynamicEntryList&)
+    CM_OVERRIDE;
+
   // Lookup a string from the dynamic section with the given tag.
   StringEntry const* GetDynamicSectionString(unsigned int tag) CM_OVERRIDE;
 
@@ -289,6 +287,10 @@ public:
   }
 
 private:
+  // ByteSwap(ELF_Dyn) assumes d_val and d_ptr are the same size
+  typedef char dyn_size_assert
+    [sizeof(ELF_Dyn().d_un.d_val) == sizeof(ELF_Dyn().d_un.d_ptr) ? 1 : -1];
+
   void ByteSwap(ELF_Ehdr& elf_header)
   {
     cmELFByteSwap(elf_header.e_type);
@@ -323,121 +325,7 @@ private:
   void ByteSwap(ELF_Dyn& dyn)
   {
     cmELFByteSwap(dyn.d_tag);
-    switch (dyn.d_tag) {
-      case DT_NULL: /* dyn.d_un ignored */
-        break;
-      case DT_NEEDED:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-      case DT_PLTRELSZ:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-      case DT_PLTGOT:
-        cmELFByteSwap(dyn.d_un.d_ptr);
-        break;
-      case DT_HASH:
-        cmELFByteSwap(dyn.d_un.d_ptr);
-        break;
-      case DT_STRTAB:
-        cmELFByteSwap(dyn.d_un.d_ptr);
-        break;
-      case DT_SYMTAB:
-        cmELFByteSwap(dyn.d_un.d_ptr);
-        break;
-      case DT_RELA:
-        cmELFByteSwap(dyn.d_un.d_ptr);
-        break;
-      case DT_RELASZ:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-      case DT_RELAENT:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-      case DT_STRSZ:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-      case DT_SYMENT:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-      case DT_INIT:
-        cmELFByteSwap(dyn.d_un.d_ptr);
-        break;
-      case DT_FINI:
-        cmELFByteSwap(dyn.d_un.d_ptr);
-        break;
-      case DT_SONAME:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-      case DT_RPATH:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-      case DT_SYMBOLIC: /* dyn.d_un ignored */
-        break;
-      case DT_REL:
-        cmELFByteSwap(dyn.d_un.d_ptr);
-        break;
-      case DT_RELSZ:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-      case DT_RELENT:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-      case DT_PLTREL:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-      case DT_DEBUG:
-        cmELFByteSwap(dyn.d_un.d_ptr);
-        break;
-      case DT_TEXTREL: /* dyn.d_un ignored */
-        break;
-      case DT_JMPREL:
-        cmELFByteSwap(dyn.d_un.d_ptr);
-        break;
-#ifdef T_BIND_NOW
-      case T_BIND_NOW: /* dyn.d_un ignored */
-        break;
-#endif
-#ifdef DT_INIT_ARRAY
-      case DT_INIT_ARRAY:
-        cmELFByteSwap(dyn.d_un.d_ptr);
-        break;
-#endif
-#ifdef DT_FINI_ARRAY
-      case DT_FINI_ARRAY:
-        cmELFByteSwap(dyn.d_un.d_ptr);
-        break;
-#endif
-#ifdef DT_INIT_ARRAYSZ
-      case DT_INIT_ARRAYSZ:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-#endif
-#ifdef DT_FINI_ARRAYSZ
-      case DT_FINI_ARRAYSZ:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-#endif
-#ifdef DT_RUNPATH
-      case DT_RUNPATH:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-#endif
-#ifdef DT_FLAGS
-      case DT_FLAGS:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-#endif
-#ifdef DT_PREINIT_ARRAY
-      case DT_PREINIT_ARRAY:
-        cmELFByteSwap(dyn.d_un.d_ptr);
-        break;
-#endif
-#ifdef DT_PREINIT_ARRAYSZ
-      case DT_PREINIT_ARRAYSZ:
-        cmELFByteSwap(dyn.d_un.d_val);
-        break;
-#endif
-    }
+    cmELFByteSwap(dyn.d_un.d_val);
   }
 
   bool FileTypeValid(ELF_Half et)
@@ -636,30 +524,64 @@ bool cmELFInternalImpl<Types>::LoadDynamicSection()
 }
 
 template <class Types>
-unsigned int cmELFInternalImpl<Types>::GetDynamicEntryCount()
+unsigned long cmELFInternalImpl<Types>::GetDynamicEntryPosition(int j)
 {
   if (!this->LoadDynamicSection()) {
     return 0;
   }
-  for (unsigned int i = 0; i < this->DynamicSectionEntries.size(); ++i) {
-    if (this->DynamicSectionEntries[i].d_tag == DT_NULL) {
-      return i;
-    }
+  if (j < 0 || j >= static_cast<int>(this->DynamicSectionEntries.size())) {
+    return 0;
   }
-  return static_cast<unsigned int>(this->DynamicSectionEntries.size());
+  ELF_Shdr const& sec = this->SectionHeaders[this->DynamicSectionIndex];
+  return static_cast<unsigned long>(sec.sh_offset + sec.sh_entsize * j);
 }
 
 template <class Types>
-unsigned long cmELFInternalImpl<Types>::GetDynamicEntryPosition(int j)
+cmELF::DynamicEntryList cmELFInternalImpl<Types>::GetDynamicEntries()
 {
+  cmELF::DynamicEntryList result;
+
+  // Ensure entries have been read from file
   if (!this->LoadDynamicSection()) {
-    return 0;
+    return result;
   }
-  if (j < 0 || j >= static_cast<int>(this->DynamicSectionEntries.size())) {
-    return 0;
+
+  // Copy into public array
+  result.reserve(this->DynamicSectionEntries.size());
+  for (typename std::vector<ELF_Dyn>::iterator di =
+         this->DynamicSectionEntries.begin();
+       di != this->DynamicSectionEntries.end(); ++di) {
+    ELF_Dyn& dyn = *di;
+    result.push_back(
+      std::pair<unsigned long, unsigned long>(dyn.d_tag, dyn.d_un.d_val));
   }
-  ELF_Shdr const& sec = this->SectionHeaders[this->DynamicSectionIndex];
-  return static_cast<unsigned long>(sec.sh_offset + sec.sh_entsize * j);
+
+  return result;
+}
+
+template <class Types>
+std::vector<char> cmELFInternalImpl<Types>::EncodeDynamicEntries(
+  const cmELF::DynamicEntryList& entries)
+{
+  std::vector<char> result;
+  result.reserve(sizeof(ELF_Dyn) * entries.size());
+
+  for (cmELF::DynamicEntryList::const_iterator it = entries.begin();
+       it != entries.end(); it++) {
+    // Store the entry in an ELF_Dyn, byteswap it, then serialize to chars
+    ELF_Dyn dyn;
+    dyn.d_tag = static_cast<tagtype>(it->first);
+    dyn.d_un.d_val = static_cast<tagtype>(it->second);
+
+    if (this->NeedSwap) {
+      ByteSwap(dyn);
+    }
+
+    char* pdyn = reinterpret_cast<char*>(&dyn);
+    result.insert(result.end(), pdyn, pdyn + sizeof(ELF_Dyn));
+  }
+
+  return result;
 }
 
 template <class Types>
@@ -752,6 +674,15 @@ cmELF::StringEntry const* cmELFInternalImpl<Types>::GetDynamicSectionString(
 //============================================================================
 // External class implementation.
 
+const long cmELF::TagRPath = DT_RPATH;
+const long cmELF::TagRunPath = DT_RUNPATH;
+
+#ifdef DT_MIPS_RLD_MAP_REL
+const long cmELF::TagMipsRldMapRel = DT_MIPS_RLD_MAP_REL;
+#else
+const long cmELF::TagMipsRldMapRel = 0;
+#endif
+
 cmELF::cmELF(const char* fname)
   : Internal(CM_NULLPTR)
 {
@@ -839,28 +770,31 @@ unsigned int cmELF::GetNumberOfSections() const
   return 0;
 }
 
-unsigned int cmELF::GetDynamicEntryCount() const
+unsigned long cmELF::GetDynamicEntryPosition(int index) const
 {
   if (this->Valid()) {
-    return this->Internal->GetDynamicEntryCount();
+    return this->Internal->GetDynamicEntryPosition(index);
   }
   return 0;
 }
 
-unsigned long cmELF::GetDynamicEntryPosition(int index) const
+cmELF::DynamicEntryList cmELF::GetDynamicEntries() const
 {
   if (this->Valid()) {
-    return this->Internal->GetDynamicEntryPosition(index);
+    return this->Internal->GetDynamicEntries();
   }
-  return 0;
+
+  return cmELF::DynamicEntryList();
 }
 
-bool cmELF::ReadBytes(unsigned long pos, unsigned long size, char* buf) const
+std::vector<char> cmELF::EncodeDynamicEntries(
+  const cmELF::DynamicEntryList& dentries) const
 {
   if (this->Valid()) {
-    return this->Internal->ReadBytes(pos, size, buf);
+    return this->Internal->EncodeDynamicEntries(dentries);
   }
-  return false;
+
+  return std::vector<char>();
 }
 
 bool cmELF::GetSOName(std::string& soname)
diff --git a/Source/cmELF.h b/Source/cmELF.h
index 7e7c1d6..763a240 100644
--- a/Source/cmELF.h
+++ b/Source/cmELF.h
@@ -7,6 +7,8 @@
 
 #include <iosfwd>
 #include <string>
+#include <utility>
+#include <vector>
 
 #if !defined(CMAKE_USE_ELF_PARSER)
 #error "This file may be included only if CMAKE_USE_ELF_PARSER is enabled."
@@ -61,22 +63,27 @@ public:
     int IndexInSection;
   };
 
+  /** Represent entire dynamic section header */
+  typedef std::vector<std::pair<long, unsigned long> > DynamicEntryList;
+
   /** Get the type of the file opened.  */
   FileType GetFileType() const;
 
   /** Get the number of ELF sections present.  */
   unsigned int GetNumberOfSections() const;
 
-  /** Get the number of DYNAMIC section entries before the first
-      DT_NULL.  Returns zero on error.  */
-  unsigned int GetDynamicEntryCount() const;
-
   /** Get the position of a DYNAMIC section header entry.  Returns
       zero on error.  */
   unsigned long GetDynamicEntryPosition(int index) const;
 
-  /** Read bytes from the file.  */
-  bool ReadBytes(unsigned long pos, unsigned long size, char* buf) const;
+  /** Get a copy of all the DYNAMIC section header entries.
+      Returns an empty vector on error */
+  DynamicEntryList GetDynamicEntries() const;
+
+  /** Encodes a DYNAMIC section header entry list into a char vector according
+      to the type of ELF file this is */
+  std::vector<char> EncodeDynamicEntries(
+    const DynamicEntryList& entries) const;
 
   /** Get the SONAME field if any.  */
   bool GetSOName(std::string& soname);
@@ -91,6 +98,10 @@ public:
   /** Print human-readable information about the ELF file.  */
   void PrintInfo(std::ostream& os) const;
 
+  /** Interesting dynamic tags.
+      If the tag is 0, it does not exist in the host ELF implementation */
+  static const long TagRPath, TagRunPath, TagMipsRldMapRel;
+
 private:
   friend class cmELFInternal;
   bool Valid() const;
diff --git a/Source/cmElseCommand.cxx b/Source/cmElseCommand.cxx
deleted file mode 100644
index 16e53f6..0000000
--- a/Source/cmElseCommand.cxx
+++ /dev/null
@@ -1,12 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmElseCommand.h"
-
-bool cmElseCommand::InitialPass(std::vector<std::string> const&,
-                                cmExecutionStatus&)
-{
-  this->SetError("An ELSE command was found outside of a proper "
-                 "IF ENDIF structure. Or its arguments did not match "
-                 "the opening IF command.");
-  return false;
-}
diff --git a/Source/cmElseCommand.h b/Source/cmElseCommand.h
deleted file mode 100644
index 33f73ee..0000000
--- a/Source/cmElseCommand.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#ifndef cmElseCommand_h
-#define cmElseCommand_h
-
-#include "cmIfCommand.h"
-
-/** \class cmElseCommand
- * \brief ends an if block
- *
- * cmElseCommand ends an if block
- */
-class cmElseCommand : public cmCommand
-{
-public:
-  /**
-   * This is a virtual constructor for the command.
-   */
-  cmCommand* Clone() CM_OVERRIDE { return new cmElseCommand; }
-
-  /**
-   * This is called when the command is first encountered in
-   * the CMakeLists.txt file.
-   */
-  bool InitialPass(std::vector<std::string> const& args,
-                   cmExecutionStatus& status) CM_OVERRIDE;
-
-  /**
-   * This determines if the command is invoked when in script mode.
-   */
-  bool IsScriptable() const CM_OVERRIDE { return true; }
-
-  /**
-   * The name of the command as specified in CMakeList.txt.
-   */
-  std::string GetName() const CM_OVERRIDE { return "else"; }
-
-  cmTypeMacro(cmElseCommand, cmCommand);
-};
-
-#endif
diff --git a/Source/cmElseIfCommand.cxx b/Source/cmElseIfCommand.cxx
deleted file mode 100644
index cc3624b..0000000
--- a/Source/cmElseIfCommand.cxx
+++ /dev/null
@@ -1,11 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmElseIfCommand.h"
-
-bool cmElseIfCommand::InitialPass(std::vector<std::string> const&,
-                                  cmExecutionStatus&)
-{
-  this->SetError("An ELSEIF command was found outside of a proper "
-                 "IF ENDIF structure.");
-  return false;
-}
diff --git a/Source/cmElseIfCommand.h b/Source/cmElseIfCommand.h
deleted file mode 100644
index a489e30..0000000
--- a/Source/cmElseIfCommand.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#ifndef cmElseIfCommand_h
-#define cmElseIfCommand_h
-
-#include "cmIfCommand.h"
-
-/** \class cmElseIfCommand
- * \brief ends an if block
- *
- * cmElseIfCommand ends an if block
- */
-class cmElseIfCommand : public cmCommand
-{
-public:
-  /**
-   * This is a virtual constructor for the command.
-   */
-  cmCommand* Clone() CM_OVERRIDE { return new cmElseIfCommand; }
-
-  /**
-   * This is called when the command is first encountered in
-   * the CMakeLists.txt file.
-   */
-  bool InitialPass(std::vector<std::string> const& args,
-                   cmExecutionStatus& status) CM_OVERRIDE;
-
-  /**
-   * This determines if the command is invoked when in script mode.
-   */
-  bool IsScriptable() const CM_OVERRIDE { return true; }
-
-  /**
-   * The name of the command as specified in CMakeList.txt.
-   */
-  std::string GetName() const CM_OVERRIDE { return "elseif"; }
-
-  cmTypeMacro(cmElseIfCommand, cmCommand);
-};
-
-#endif
diff --git a/Source/cmEnableLanguageCommand.cxx b/Source/cmEnableLanguageCommand.cxx
index 49fd6fd..c57b7b1 100644
--- a/Source/cmEnableLanguageCommand.cxx
+++ b/Source/cmEnableLanguageCommand.cxx
@@ -2,6 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmEnableLanguageCommand.h"
 
+#include "cmMakefile.h"
+
+class cmExecutionStatus;
+
 // cmEnableLanguageCommand
 bool cmEnableLanguageCommand::InitialPass(std::vector<std::string> const& args,
                                           cmExecutionStatus&)
diff --git a/Source/cmEnableLanguageCommand.h b/Source/cmEnableLanguageCommand.h
index 98b3841..bafb79e 100644
--- a/Source/cmEnableLanguageCommand.h
+++ b/Source/cmEnableLanguageCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmEnableLanguageCommand_h
 #define cmEnableLanguageCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmEnableLanguageCommand
  * \brief Specify the name for this build project.
  *
@@ -32,8 +38,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "enable_language"; }
-
-  cmTypeMacro(cmEnableLanguageCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmEnableTestingCommand.cxx b/Source/cmEnableTestingCommand.cxx
index d66c5b3..6a64450 100644
--- a/Source/cmEnableTestingCommand.cxx
+++ b/Source/cmEnableTestingCommand.cxx
@@ -2,6 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmEnableTestingCommand.h"
 
+#include "cmMakefile.h"
+
+class cmExecutionStatus;
+
 // we do this in the final pass so that we now the subdirs have all
 // been defined
 bool cmEnableTestingCommand::InitialPass(std::vector<std::string> const&,
diff --git a/Source/cmEnableTestingCommand.h b/Source/cmEnableTestingCommand.h
index 750ae8c..67cd237 100644
--- a/Source/cmEnableTestingCommand.h
+++ b/Source/cmEnableTestingCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmEnableTestingCommand_h
 #define cmEnableTestingCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmEnableTestingCommand
  * \brief Enable testing for this directory and below.
  *
@@ -37,8 +43,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "enable_testing"; }
-
-  cmTypeMacro(cmEnableTestingCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmEndForEachCommand.cxx b/Source/cmEndForEachCommand.cxx
deleted file mode 100644
index 7184bae..0000000
--- a/Source/cmEndForEachCommand.cxx
+++ /dev/null
@@ -1,12 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmEndForEachCommand.h"
-
-bool cmEndForEachCommand::InvokeInitialPass(
-  std::vector<cmListFileArgument> const&, cmExecutionStatus&)
-{
-  this->SetError("An ENDFOREACH command was found outside of a proper "
-                 "FOREACH ENDFOREACH structure. Or its arguments did "
-                 "not match the opening FOREACH command.");
-  return false;
-}
diff --git a/Source/cmEndForEachCommand.h b/Source/cmEndForEachCommand.h
deleted file mode 100644
index 3bcc7cf..0000000
--- a/Source/cmEndForEachCommand.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#ifndef cmEndForEachCommand_h
-#define cmEndForEachCommand_h
-
-#include "cmCommand.h"
-
-/** \class cmEndForEachCommand
- * \brief ends an if block
- *
- * cmEndForEachCommand ends an if block
- */
-class cmEndForEachCommand : public cmCommand
-{
-public:
-  /**
-   * This is a virtual constructor for the command.
-   */
-  cmCommand* Clone() CM_OVERRIDE { return new cmEndForEachCommand; }
-
-  /**
-   * Override cmCommand::InvokeInitialPass to get arguments before
-   * expansion.
-   */
-  bool InvokeInitialPass(std::vector<cmListFileArgument> const&,
-                         cmExecutionStatus&) CM_OVERRIDE;
-
-  /**
-   * This is called when the command is first encountered in
-   * the CMakeLists.txt file.
-   */
-  bool InitialPass(std::vector<std::string> const&,
-                   cmExecutionStatus&) CM_OVERRIDE
-  {
-    return false;
-  }
-
-  /**
-   * This determines if the command is invoked when in script mode.
-   */
-  bool IsScriptable() const CM_OVERRIDE { return true; }
-
-  /**
-   * The name of the command as specified in CMakeList.txt.
-   */
-  std::string GetName() const CM_OVERRIDE { return "endforeach"; }
-
-  cmTypeMacro(cmEndForEachCommand, cmCommand);
-};
-
-#endif
diff --git a/Source/cmEndFunctionCommand.cxx b/Source/cmEndFunctionCommand.cxx
deleted file mode 100644
index 82344c6..0000000
--- a/Source/cmEndFunctionCommand.cxx
+++ /dev/null
@@ -1,12 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmEndFunctionCommand.h"
-
-bool cmEndFunctionCommand::InvokeInitialPass(
-  std::vector<cmListFileArgument> const&, cmExecutionStatus&)
-{
-  this->SetError("An ENDFUNCTION command was found outside of a proper "
-                 "FUNCTION ENDFUNCTION structure. Or its arguments did not "
-                 "match the opening FUNCTION command.");
-  return false;
-}
diff --git a/Source/cmEndFunctionCommand.h b/Source/cmEndFunctionCommand.h
deleted file mode 100644
index 8b4d2f9..0000000
--- a/Source/cmEndFunctionCommand.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#ifndef cmEndFunctionCommand_h
-#define cmEndFunctionCommand_h
-
-#include "cmCommand.h"
-
-/** \class cmEndFunctionCommand
- * \brief ends an if block
- *
- * cmEndFunctionCommand ends an if block
- */
-class cmEndFunctionCommand : public cmCommand
-{
-public:
-  /**
-   * This is a virtual constructor for the command.
-   */
-  cmCommand* Clone() CM_OVERRIDE { return new cmEndFunctionCommand; }
-
-  /**
-   * Override cmCommand::InvokeInitialPass to get arguments before
-   * expansion.
-   */
-  bool InvokeInitialPass(std::vector<cmListFileArgument> const&,
-                         cmExecutionStatus&) CM_OVERRIDE;
-
-  /**
-   * This is called when the command is first encountered in
-   * the CMakeLists.txt file.
-   */
-  bool InitialPass(std::vector<std::string> const&,
-                   cmExecutionStatus&) CM_OVERRIDE
-  {
-    return false;
-  }
-
-  /**
-   * This determines if the command is invoked when in script mode.
-   */
-  bool IsScriptable() const CM_OVERRIDE { return true; }
-
-  /**
-   * The name of the command as specified in CMakeList.txt.
-   */
-  std::string GetName() const CM_OVERRIDE { return "endfunction"; }
-
-  cmTypeMacro(cmEndFunctionCommand, cmCommand);
-};
-
-#endif
diff --git a/Source/cmEndIfCommand.cxx b/Source/cmEndIfCommand.cxx
deleted file mode 100644
index 78a0d0f..0000000
--- a/Source/cmEndIfCommand.cxx
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmEndIfCommand.h"
-
-#include <stdlib.h> // required for atof
-bool cmEndIfCommand::InitialPass(std::vector<std::string> const&,
-                                 cmExecutionStatus&)
-{
-  const char* versionValue =
-    this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION");
-  if (!versionValue || (atof(versionValue) <= 1.4)) {
-    return true;
-  }
-
-  this->SetError("An ENDIF command was found outside of a proper "
-                 "IF ENDIF structure. Or its arguments did not match "
-                 "the opening IF command.");
-  return false;
-}
diff --git a/Source/cmEndIfCommand.h b/Source/cmEndIfCommand.h
deleted file mode 100644
index b476c72..0000000
--- a/Source/cmEndIfCommand.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#ifndef cmEndIfCommand_h
-#define cmEndIfCommand_h
-
-#include "cmIfCommand.h"
-
-/** \class cmEndIfCommand
- * \brief ends an if block
- *
- * cmEndIfCommand ends an if block
- */
-class cmEndIfCommand : public cmCommand
-{
-public:
-  /**
-   * This is a virtual constructor for the command.
-   */
-  cmCommand* Clone() CM_OVERRIDE { return new cmEndIfCommand; }
-
-  /**
-   * This is called when the command is first encountered in
-   * the CMakeLists.txt file.
-   */
-  bool InitialPass(std::vector<std::string> const& args,
-                   cmExecutionStatus& status) CM_OVERRIDE;
-
-  /**
-   * This determines if the command is invoked when in script mode.
-   */
-  bool IsScriptable() const CM_OVERRIDE { return true; }
-
-  /**
-   * The name of the command as specified in CMakeList.txt.
-   */
-  std::string GetName() const CM_OVERRIDE { return "endif"; }
-
-  cmTypeMacro(cmEndIfCommand, cmCommand);
-};
-
-#endif
diff --git a/Source/cmEndMacroCommand.cxx b/Source/cmEndMacroCommand.cxx
deleted file mode 100644
index 189d969..0000000
--- a/Source/cmEndMacroCommand.cxx
+++ /dev/null
@@ -1,12 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmEndMacroCommand.h"
-
-bool cmEndMacroCommand::InvokeInitialPass(
-  std::vector<cmListFileArgument> const&, cmExecutionStatus&)
-{
-  this->SetError("An ENDMACRO command was found outside of a proper "
-                 "MACRO ENDMACRO structure. Or its arguments did not "
-                 "match the opening MACRO command.");
-  return false;
-}
diff --git a/Source/cmEndMacroCommand.h b/Source/cmEndMacroCommand.h
deleted file mode 100644
index 806750d..0000000
--- a/Source/cmEndMacroCommand.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#ifndef cmEndMacroCommand_h
-#define cmEndMacroCommand_h
-
-#include "cmCommand.h"
-
-/** \class cmEndMacroCommand
- * \brief ends an if block
- *
- * cmEndMacroCommand ends an if block
- */
-class cmEndMacroCommand : public cmCommand
-{
-public:
-  /**
-   * This is a virtual constructor for the command.
-   */
-  cmCommand* Clone() CM_OVERRIDE { return new cmEndMacroCommand; }
-
-  /**
-   * Override cmCommand::InvokeInitialPass to get arguments before
-   * expansion.
-   */
-  bool InvokeInitialPass(std::vector<cmListFileArgument> const&,
-                         cmExecutionStatus&) CM_OVERRIDE;
-
-  /**
-   * This is called when the command is first encountered in
-   * the CMakeLists.txt file.
-   */
-  bool InitialPass(std::vector<std::string> const&,
-                   cmExecutionStatus&) CM_OVERRIDE
-  {
-    return false;
-  }
-
-  /**
-   * This determines if the command is invoked when in script mode.
-   */
-  bool IsScriptable() const CM_OVERRIDE { return true; }
-
-  /**
-   * The name of the command as specified in CMakeList.txt.
-   */
-  std::string GetName() const CM_OVERRIDE { return "endmacro"; }
-
-  cmTypeMacro(cmEndMacroCommand, cmCommand);
-};
-
-#endif
diff --git a/Source/cmEndWhileCommand.cxx b/Source/cmEndWhileCommand.cxx
deleted file mode 100644
index b635168..0000000
--- a/Source/cmEndWhileCommand.cxx
+++ /dev/null
@@ -1,18 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmEndWhileCommand.h"
-
-bool cmEndWhileCommand::InvokeInitialPass(
-  std::vector<cmListFileArgument> const& args, cmExecutionStatus&)
-{
-  if (args.empty()) {
-    this->SetError("An ENDWHILE command was found outside of a proper "
-                   "WHILE ENDWHILE structure.");
-  } else {
-    this->SetError("An ENDWHILE command was found outside of a proper "
-                   "WHILE ENDWHILE structure. Or its arguments did not "
-                   "match the opening WHILE command.");
-  }
-
-  return false;
-}
diff --git a/Source/cmEndWhileCommand.h b/Source/cmEndWhileCommand.h
deleted file mode 100644
index 861d2f0..0000000
--- a/Source/cmEndWhileCommand.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#ifndef cmEndWhileCommand_h
-#define cmEndWhileCommand_h
-
-#include "cmCommand.h"
-
-/** \class cmEndWhileCommand
- * \brief ends a while loop
- *
- * cmEndWhileCommand ends a while loop
- */
-class cmEndWhileCommand : public cmCommand
-{
-public:
-  /**
-   * This is a virtual constructor for the command.
-   */
-  cmCommand* Clone() CM_OVERRIDE { return new cmEndWhileCommand; }
-
-  /**
-   * Override cmCommand::InvokeInitialPass to get arguments before
-   * expansion.
-   */
-  bool InvokeInitialPass(std::vector<cmListFileArgument> const& args,
-                         cmExecutionStatus& status) CM_OVERRIDE;
-
-  /**
-   * This is called when the command is first encountered in
-   * the CMakeLists.txt file.
-   */
-  bool InitialPass(std::vector<std::string> const&,
-                   cmExecutionStatus&) CM_OVERRIDE
-  {
-    return false;
-  }
-
-  /**
-   * This determines if the command is invoked when in script mode.
-   */
-  bool IsScriptable() const CM_OVERRIDE { return true; }
-
-  /**
-   * The name of the command as specified in CMakeList.txt.
-   */
-  std::string GetName() const CM_OVERRIDE { return "endwhile"; }
-
-  cmTypeMacro(cmEndWhileCommand, cmCommand);
-};
-
-#endif
diff --git a/Source/cmExecProgramCommand.cxx b/Source/cmExecProgramCommand.cxx
index a3d6852..6a7292d 100644
--- a/Source/cmExecProgramCommand.cxx
+++ b/Source/cmExecProgramCommand.cxx
@@ -2,9 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExecProgramCommand.h"
 
+#include <cmsys/Process.h>
+#include <stdio.h>
+
+#include "cmMakefile.h"
+#include "cmProcessOutput.h"
 #include "cmSystemTools.h"
 
-#include <cmsys/Process.h>
+class cmExecutionStatus;
 
 // cmExecProgramCommand
 bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args,
@@ -112,7 +117,7 @@ bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args,
 
 bool cmExecProgramCommand::RunCommand(const char* command, std::string& output,
                                       int& retVal, const char* dir,
-                                      bool verbose)
+                                      bool verbose, Encoding encoding)
 {
   if (cmSystemTools::GetRunCommandOutput()) {
     verbose = false;
@@ -210,17 +215,28 @@ bool cmExecProgramCommand::RunCommand(const char* command, std::string& output,
   int length;
   char* data;
   int p;
+  cmProcessOutput processOutput(encoding);
+  std::string strdata;
   while ((p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR), p)) {
     if (p == cmsysProcess_Pipe_STDOUT || p == cmsysProcess_Pipe_STDERR) {
       if (verbose) {
-        cmSystemTools::Stdout(data, length);
+        processOutput.DecodeText(data, length, strdata);
+        cmSystemTools::Stdout(strdata.c_str(), strdata.size());
       }
       output.append(data, length);
     }
   }
 
+  if (verbose) {
+    processOutput.DecodeText(std::string(), strdata);
+    if (!strdata.empty()) {
+      cmSystemTools::Stdout(strdata.c_str(), strdata.size());
+    }
+  }
+
   // All output has been read.  Wait for the process to exit.
   cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+  processOutput.DecodeText(output, output);
 
   // Check the result of running the process.
   std::string msg;
diff --git a/Source/cmExecProgramCommand.h b/Source/cmExecProgramCommand.h
index 1cc46d3..58e948e 100644
--- a/Source/cmExecProgramCommand.h
+++ b/Source/cmExecProgramCommand.h
@@ -3,7 +3,14 @@
 #ifndef cmExecProgramCommand_h
 #define cmExecProgramCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
+#include "cmProcessOutput.h"
+
+class cmExecutionStatus;
 
 /** \class cmExecProgramCommand
  * \brief Command that adds a target to the build system.
@@ -15,6 +22,7 @@
 class cmExecProgramCommand : public cmCommand
 {
 public:
+  typedef cmProcessOutput::Encoding Encoding;
   /**
    * This is a virtual constructor for the command.
    */
@@ -37,12 +45,11 @@ public:
    */
   bool IsScriptable() const CM_OVERRIDE { return true; }
 
-  cmTypeMacro(cmExecProgramCommand, cmCommand);
-
 private:
   static bool RunCommand(const char* command, std::string& output, int& retVal,
                          const char* directory = CM_NULLPTR,
-                         bool verbose = true);
+                         bool verbose = true,
+                         Encoding encoding = cmProcessOutput::Auto);
 };
 
 #endif
diff --git a/Source/cmExecuteProcessCommand.cxx b/Source/cmExecuteProcessCommand.cxx
index 2bcf244..92cdf64 100644
--- a/Source/cmExecuteProcessCommand.cxx
+++ b/Source/cmExecuteProcessCommand.cxx
@@ -2,11 +2,16 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExecuteProcessCommand.h"
 
-#include "cmSystemTools.h"
-
 #include <cmsys/Process.h>
-
 #include <ctype.h> /* isspace */
+#include <sstream>
+#include <stdio.h>
+
+#include "cmMakefile.h"
+#include "cmProcessOutput.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
 
 static bool cmExecuteProcessCommandIsWhitespace(char c)
 {
@@ -42,6 +47,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
   std::string error_variable;
   std::string result_variable;
   std::string working_directory;
+  cmProcessOutput::Encoding encoding = cmProcessOutput::None;
   for (size_t i = 0; i < args.size(); ++i) {
     if (args[i] == "COMMAND") {
       doing_command = true;
@@ -123,6 +129,14 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
     } else if (args[i] == "ERROR_STRIP_TRAILING_WHITESPACE") {
       doing_command = false;
       error_strip_trailing_whitespace = true;
+    } else if (args[i] == "ENCODING") {
+      doing_command = false;
+      if (++i < args.size()) {
+        encoding = cmProcessOutput::FindEncoding(args[i]);
+      } else {
+        this->SetError(" called with no value for ENCODING.");
+        return false;
+      }
     } else if (doing_command) {
       cmds[command_index].push_back(args[i].c_str());
     } else {
@@ -218,25 +232,43 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
   int length;
   char* data;
   int p;
+  cmProcessOutput processOutput(encoding);
+  std::string strdata;
   while ((p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR), p)) {
     // Put the output in the right place.
     if (p == cmsysProcess_Pipe_STDOUT && !output_quiet) {
       if (output_variable.empty()) {
-        cmSystemTools::Stdout(data, length);
+        processOutput.DecodeText(data, length, strdata, 1);
+        cmSystemTools::Stdout(strdata.c_str(), strdata.size());
       } else {
         cmExecuteProcessCommandAppend(tempOutput, data, length);
       }
     } else if (p == cmsysProcess_Pipe_STDERR && !error_quiet) {
       if (error_variable.empty()) {
-        cmSystemTools::Stderr(data, length);
+        processOutput.DecodeText(data, length, strdata, 2);
+        cmSystemTools::Stderr(strdata.c_str(), strdata.size());
       } else {
         cmExecuteProcessCommandAppend(tempError, data, length);
       }
     }
   }
+  if (!output_quiet && output_variable.empty()) {
+    processOutput.DecodeText(std::string(), strdata, 1);
+    if (!strdata.empty()) {
+      cmSystemTools::Stdout(strdata.c_str(), strdata.size());
+    }
+  }
+  if (!error_quiet && error_variable.empty()) {
+    processOutput.DecodeText(std::string(), strdata, 2);
+    if (!strdata.empty()) {
+      cmSystemTools::Stderr(strdata.c_str(), strdata.size());
+    }
+  }
 
   // All output has been read.  Wait for the process to exit.
   cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+  processOutput.DecodeText(tempOutput, tempOutput);
+  processOutput.DecodeText(tempError, tempError);
 
   // Fix the text in the output strings.
   cmExecuteProcessCommandFixText(tempOutput, output_strip_trailing_whitespace);
diff --git a/Source/cmExecuteProcessCommand.h b/Source/cmExecuteProcessCommand.h
index f7e376a..9ce4338 100644
--- a/Source/cmExecuteProcessCommand.h
+++ b/Source/cmExecuteProcessCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmExecuteProcessCommand_h
 #define cmExecuteProcessCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmExecuteProcessCommand
  * \brief Command that adds a target to the build system.
  *
@@ -35,8 +41,6 @@ public:
    * This determines if the command is invoked when in script mode.
    */
   bool IsScriptable() const CM_OVERRIDE { return true; }
-
-  cmTypeMacro(cmExecuteProcessCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmExecutionStatus.h b/Source/cmExecutionStatus.h
index 7d4e97c..fd3c416 100644
--- a/Source/cmExecutionStatus.h
+++ b/Source/cmExecutionStatus.h
@@ -3,10 +3,6 @@
 #ifndef cmExecutionStatus_h
 #define cmExecutionStatus_h
 
-#include <cmConfigure.h>
-
-#include "cmStandardIncludes.h"
-
 /** \class cmExecutionStatus
  * \brief Superclass for all command status classes
  *
diff --git a/Source/cmExpandedCommandArgument.h b/Source/cmExpandedCommandArgument.h
index 39cffce..9770fe6 100644
--- a/Source/cmExpandedCommandArgument.h
+++ b/Source/cmExpandedCommandArgument.h
@@ -3,9 +3,9 @@
 #ifndef cmExpandedCommandArgument_h
 #define cmExpandedCommandArgument_h
 
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmStandardIncludes.h"
+#include <string>
 
 /** \class cmExpandedCommandArgument
  * \brief Represents an expanded command argument
diff --git a/Source/cmExportBuildAndroidMKGenerator.cxx b/Source/cmExportBuildAndroidMKGenerator.cxx
index f5e6628..b443fb0 100644
--- a/Source/cmExportBuildAndroidMKGenerator.cxx
+++ b/Source/cmExportBuildAndroidMKGenerator.cxx
@@ -2,14 +2,22 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExportBuildAndroidMKGenerator.h"
 
-#include "cmExportSet.h"
+#include <algorithm>
+#include <map>
+#include <sstream>
+#include <utility>
+
+#include "cmGeneratorExpression.h"
 #include "cmGeneratorTarget.h"
-#include "cmGlobalGenerator.h"
+#include "cmLinkItem.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
-#include "cmTargetExport.h"
-
-#include <algorithm>
+#include "cmPolicies.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
 
 cmExportBuildAndroidMKGenerator::cmExportBuildAndroidMKGenerator()
 {
@@ -61,7 +69,7 @@ void cmExportBuildAndroidMKGenerator::GenerateInterfaceProperties(
   const cmGeneratorTarget* target, std::ostream& os,
   const ImportPropertyMap& properties)
 {
-  std::string config = "";
+  std::string config;
   if (!this->Configurations.empty()) {
     config = this->Configurations[0];
   }
@@ -111,8 +119,8 @@ void cmExportBuildAndroidMKGenerator::GenerateInterfaceProperties(
             target->GetLocalGenerator()->FindGeneratorTargetToUse(*i);
           if (gt) {
 
-            if (gt->GetType() == cmState::SHARED_LIBRARY ||
-                gt->GetType() == cmState::MODULE_LIBRARY) {
+            if (gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
+                gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
               sharedLibs += " " + *i;
             } else {
               staticLibs += " " + *i;
@@ -168,7 +176,7 @@ void cmExportBuildAndroidMKGenerator::GenerateInterfaceProperties(
   }
 
   // Tell the NDK build system if prebuilt static libraries use C++.
-  if (target->GetType() == cmState::STATIC_LIBRARY) {
+  if (target->GetType() == cmStateEnums::STATIC_LIBRARY) {
     cmLinkImplementation const* li = target->GetLinkImplementation(config);
     if (std::find(li->Languages.begin(), li->Languages.end(), "CXX") !=
         li->Languages.end()) {
@@ -177,19 +185,19 @@ void cmExportBuildAndroidMKGenerator::GenerateInterfaceProperties(
   }
 
   switch (target->GetType()) {
-    case cmState::SHARED_LIBRARY:
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       os << "include $(PREBUILT_SHARED_LIBRARY)\n";
       break;
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
       os << "include $(PREBUILT_STATIC_LIBRARY)\n";
       break;
-    case cmState::EXECUTABLE:
-    case cmState::UTILITY:
-    case cmState::OBJECT_LIBRARY:
-    case cmState::GLOBAL_TARGET:
-    case cmState::INTERFACE_LIBRARY:
-    case cmState::UNKNOWN_LIBRARY:
+    case cmStateEnums::EXECUTABLE:
+    case cmStateEnums::UTILITY:
+    case cmStateEnums::OBJECT_LIBRARY:
+    case cmStateEnums::GLOBAL_TARGET:
+    case cmStateEnums::INTERFACE_LIBRARY:
+    case cmStateEnums::UNKNOWN_LIBRARY:
       break;
   }
   os << "\n";
diff --git a/Source/cmExportBuildAndroidMKGenerator.h b/Source/cmExportBuildAndroidMKGenerator.h
index c9e0145..2a5a42e 100644
--- a/Source/cmExportBuildAndroidMKGenerator.h
+++ b/Source/cmExportBuildAndroidMKGenerator.h
@@ -3,10 +3,16 @@
 #ifndef cmExportBuildAndroidMKGenerator_h
 #define cmExportBuildAndroidMKGenerator_h
 
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <string>
+#include <vector>
+
 #include "cmExportBuildFileGenerator.h"
-#include "cmListFileCache.h"
+#include "cmExportFileGenerator.h"
 
-class cmExportSet;
+class cmGeneratorTarget;
 
 /** \class cmExportBuildAndroidMKGenerator
  * \brief Generate a file exporting targets from a build tree.
diff --git a/Source/cmExportBuildFileGenerator.cxx b/Source/cmExportBuildFileGenerator.cxx
index 68831c7..0c25268 100644
--- a/Source/cmExportBuildFileGenerator.cxx
+++ b/Source/cmExportBuildFileGenerator.cxx
@@ -9,7 +9,7 @@
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmPolicies.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cmTargetExport.h"
@@ -57,7 +57,7 @@ bool cmExportBuildFileGenerator::GenerateMainFile(std::ostream& os)
           this->LG->GetMakefile()->GetBacktrace());
         return false;
       }
-      if (te->GetType() == cmState::INTERFACE_LIBRARY) {
+      if (te->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
         this->GenerateRequiredCMakeVersion(os, "3.0.0");
       }
     }
@@ -134,12 +134,12 @@ void cmExportBuildFileGenerator::GenerateImportTargetsConfig(
     cmGeneratorTarget* target = *tei;
     ImportPropertyMap properties;
 
-    if (target->GetType() != cmState::INTERFACE_LIBRARY) {
+    if (target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
       this->SetImportLocationProperty(config, suffix, target, properties);
     }
     if (!properties.empty()) {
       // Get the rest of the target details.
-      if (target->GetType() != cmState::INTERFACE_LIBRARY) {
+      if (target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
         this->SetImportDetailProperties(config, suffix, target, properties,
                                         missingTargets);
         this->SetImportLinkInterface(config, suffix,
@@ -186,7 +186,7 @@ void cmExportBuildFileGenerator::SetImportLocationProperty(
 
   // Add the import library for windows DLLs.
   if (target->IsDLLPlatform() &&
-      (target->GetType() == cmState::SHARED_LIBRARY ||
+      (target->GetType() == cmStateEnums::SHARED_LIBRARY ||
        target->IsExecutableWithExports()) &&
       mf->GetDefinition("CMAKE_IMPORT_LIBRARY_SUFFIX")) {
     std::string prop = "IMPORTED_IMPLIB";
diff --git a/Source/cmExportCommand.cxx b/Source/cmExportCommand.cxx
index d438363..8102276 100644
--- a/Source/cmExportCommand.cxx
+++ b/Source/cmExportCommand.cxx
@@ -2,15 +2,22 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExportCommand.h"
 
-#include "cmGeneratedFileStream.h"
-#include "cmGlobalGenerator.h"
-#include "cmake.h"
-
-#include <cmsys/Encoding.hxx>
 #include <cmsys/RegularExpression.hxx>
+#include <map>
+#include <sstream>
 
 #include "cmExportBuildAndroidMKGenerator.h"
 #include "cmExportBuildFileGenerator.h"
+#include "cmExportSetMap.h"
+#include "cmGeneratedFileStream.h"
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 #if defined(__HAIKU__)
 #include <FindDirectory.h>
@@ -141,14 +148,14 @@ bool cmExportCommand::InitialPass(std::vector<std::string> const& args,
       }
 
       if (cmTarget* target = gg->FindTarget(*currentTarget)) {
-        if (target->GetType() == cmState::OBJECT_LIBRARY) {
+        if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
           std::ostringstream e;
           e << "given OBJECT library \"" << *currentTarget
             << "\" which may not be exported.";
           this->SetError(e.str());
           return false;
         }
-        if (target->GetType() == cmState::UTILITY) {
+        if (target->GetType() == cmStateEnums::UTILITY) {
           this->SetError("given custom target \"" + *currentTarget +
                          "\" which may not be exported.");
           return false;
@@ -271,6 +278,7 @@ bool cmExportCommand::HandlePackage(std::vector<std::string> const& args)
 
 #if defined(_WIN32) && !defined(__CYGWIN__)
 #include <windows.h>
+
 #undef GetCurrentDirectory
 void cmExportCommand::ReportRegistryError(std::string const& msg,
                                           std::string const& key, long err)
diff --git a/Source/cmExportCommand.h b/Source/cmExportCommand.h
index ebde71c..99dac7d 100644
--- a/Source/cmExportCommand.h
+++ b/Source/cmExportCommand.h
@@ -3,9 +3,14 @@
 #ifndef cmExportCommand_h
 #define cmExportCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
+#include "cmCommandArgumentsHelper.h"
 
-class cmExportBuildFileGenerator;
+class cmExecutionStatus;
 class cmExportSet;
 
 /** \class cmExportLibraryDependenciesCommand
@@ -35,8 +40,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "export"; }
 
-  cmTypeMacro(cmExportCommand, cmCommand);
-
 private:
   cmCommandArgumentGroup ArgumentGroup;
   cmCAStringVector Targets;
diff --git a/Source/cmExportFileGenerator.cxx b/Source/cmExportFileGenerator.cxx
index d3a99fa..6c21eaf 100644
--- a/Source/cmExportFileGenerator.cxx
+++ b/Source/cmExportFileGenerator.cxx
@@ -11,7 +11,7 @@
 #include "cmMakefile.h"
 #include "cmOutputConverter.h"
 #include "cmPolicies.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cmTargetExport.h"
@@ -492,7 +492,7 @@ void cmExportFileGenerator::PopulateCompatibleInterfaceProperties(
   getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MAX",
                       ifaceProperties);
 
-  if (gtarget->GetType() != cmState::INTERFACE_LIBRARY) {
+  if (gtarget->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
     getCompatibleInterfaceProperties(gtarget, ifaceProperties, "");
 
     std::vector<std::string> configNames;
@@ -735,8 +735,8 @@ void cmExportFileGenerator::SetImportDetailProperties(
   cmMakefile* mf = target->Makefile;
 
   // Add the soname for unix shared libraries.
-  if (target->GetType() == cmState::SHARED_LIBRARY ||
-      target->GetType() == cmState::MODULE_LIBRARY) {
+  if (target->GetType() == cmStateEnums::SHARED_LIBRARY ||
+      target->GetType() == cmStateEnums::MODULE_LIBRARY) {
     if (!target->IsDLLPlatform()) {
       std::string prop;
       std::string value;
@@ -912,22 +912,22 @@ void cmExportFileGenerator::GenerateImportTargetCode(
   // Create the imported target.
   os << "# Create imported target " << targetName << "\n";
   switch (target->GetType()) {
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       os << "add_executable(" << targetName << " IMPORTED)\n";
       break;
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
       os << "add_library(" << targetName << " STATIC IMPORTED)\n";
       break;
-    case cmState::SHARED_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
       os << "add_library(" << targetName << " SHARED IMPORTED)\n";
       break;
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       os << "add_library(" << targetName << " MODULE IMPORTED)\n";
       break;
-    case cmState::UNKNOWN_LIBRARY:
+    case cmStateEnums::UNKNOWN_LIBRARY:
       os << "add_library(" << targetName << " UNKNOWN IMPORTED)\n";
       break;
-    case cmState::INTERFACE_LIBRARY:
+    case cmStateEnums::INTERFACE_LIBRARY:
       os << "add_library(" << targetName << " INTERFACE IMPORTED)\n";
       break;
     default: // should never happen
diff --git a/Source/cmExportInstallAndroidMKGenerator.cxx b/Source/cmExportInstallAndroidMKGenerator.cxx
index 58b7510..9a1c647 100644
--- a/Source/cmExportInstallAndroidMKGenerator.cxx
+++ b/Source/cmExportInstallAndroidMKGenerator.cxx
@@ -2,16 +2,17 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExportInstallAndroidMKGenerator.h"
 
-#include "cmAlgorithms.h"
+#include <ostream>
+#include <stddef.h>
+
 #include "cmExportBuildAndroidMKGenerator.h"
 #include "cmExportSet.h"
-#include "cmExportSetMap.h"
-#include "cmGeneratedFileStream.h"
 #include "cmGeneratorTarget.h"
-#include "cmGlobalGenerator.h"
 #include "cmInstallExportGenerator.h"
 #include "cmInstallTargetGenerator.h"
-#include "cmLocalGenerator.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
 #include "cmTargetExport.h"
 
 cmExportInstallAndroidMKGenerator::cmExportInstallAndroidMKGenerator(
@@ -26,7 +27,7 @@ void cmExportInstallAndroidMKGenerator::GenerateImportHeaderCode(
   std::string installDir = this->IEGen->GetDestination();
   os << "LOCAL_PATH := $(call my-dir)\n";
   size_t numDotDot = cmSystemTools::CountChar(installDir.c_str(), '/');
-  numDotDot += (installDir.size() > 0) ? 1 : 0;
+  numDotDot += installDir.empty() ? 0 : 1;
   std::string path;
   for (size_t n = 0; n < numDotDot; n++) {
     path += "/..";
@@ -38,7 +39,7 @@ void cmExportInstallAndroidMKGenerator::GenerateImportHeaderCode(
        tei != this->IEGen->GetExportSet()->GetTargetExports()->end(); ++tei) {
     // Collect import properties for this target.
     cmTargetExport const* te = *tei;
-    if (te->Target->GetType() == cmState::INTERFACE_LIBRARY) {
+    if (te->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     std::string dest;
@@ -66,7 +67,7 @@ void cmExportInstallAndroidMKGenerator::GenerateImportTargetCode(
   os << targetName << "\n";
   os << "LOCAL_SRC_FILES := $(_IMPORT_PREFIX)/";
   os << target->Target->GetProperty("__dest") << "/";
-  std::string config = "";
+  std::string config;
   if (!this->Configurations.empty()) {
     config = this->Configurations[0];
   }
@@ -93,7 +94,7 @@ void cmExportInstallAndroidMKGenerator::GenerateInterfaceProperties(
   cmGeneratorTarget const* target, std::ostream& os,
   const ImportPropertyMap& properties)
 {
-  std::string config = "";
+  std::string config;
   if (!this->Configurations.empty()) {
     config = this->Configurations[0];
   }
diff --git a/Source/cmExportInstallAndroidMKGenerator.h b/Source/cmExportInstallAndroidMKGenerator.h
index c713027..f2f8927 100644
--- a/Source/cmExportInstallAndroidMKGenerator.h
+++ b/Source/cmExportInstallAndroidMKGenerator.h
@@ -3,10 +3,18 @@
 #ifndef cmExportInstallAndroidMKGenerator_h
 #define cmExportInstallAndroidMKGenerator_h
 
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <set>
+#include <string>
+#include <vector>
+
+#include "cmExportFileGenerator.h"
 #include "cmExportInstallFileGenerator.h"
 
+class cmGeneratorTarget;
 class cmInstallExportGenerator;
-class cmInstallTargetGenerator;
 
 /** \class cmExportInstallAndroidMKGenerator
  * \brief Generate a file exporting targets from an install tree.
diff --git a/Source/cmExportInstallFileGenerator.cxx b/Source/cmExportInstallFileGenerator.cxx
index 0e043de..64ea3c8 100644
--- a/Source/cmExportInstallFileGenerator.cxx
+++ b/Source/cmExportInstallFileGenerator.cxx
@@ -14,7 +14,7 @@
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmPolicies.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cmTargetExport.h"
@@ -81,7 +81,7 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os)
     cmGeneratorTarget* gt = (*tei)->Target;
 
     requiresConfigFiles =
-      requiresConfigFiles || gt->GetType() != cmState::INTERFACE_LIBRARY;
+      requiresConfigFiles || gt->GetType() != cmStateEnums::INTERFACE_LIBRARY;
 
     this->GenerateImportTargetCode(os, gt);
 
@@ -120,7 +120,7 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os)
         require2_8_12 = true;
       }
     }
-    if (gt->GetType() == cmState::INTERFACE_LIBRARY) {
+    if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       require3_0_0 = true;
     }
     if (gt->GetProperty("INTERFACE_SOURCES")) {
@@ -316,7 +316,7 @@ void cmExportInstallFileGenerator::GenerateImportTargetsConfig(
        tei != this->IEGen->GetExportSet()->GetTargetExports()->end(); ++tei) {
     // Collect import properties for this target.
     cmTargetExport const* te = *tei;
-    if (te->Target->GetType() == cmState::INTERFACE_LIBRARY) {
+    if (te->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
 
diff --git a/Source/cmExportLibraryDependenciesCommand.cxx b/Source/cmExportLibraryDependenciesCommand.cxx
index f80980a..ac4f040 100644
--- a/Source/cmExportLibraryDependenciesCommand.cxx
+++ b/Source/cmExportLibraryDependenciesCommand.cxx
@@ -2,12 +2,23 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExportLibraryDependenciesCommand.h"
 
+#include <cmsys/FStream.hxx>
+#include <map>
+#include <utility>
+
 #include "cmGeneratedFileStream.h"
 #include "cmGlobalGenerator.h"
-#include "cmVersion.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmTargetLinkLibraryType.h"
+#include "cm_auto_ptr.hxx"
+#include "cm_unordered_map.hxx"
 #include "cmake.h"
 
-#include <cm_auto_ptr.hxx>
+class cmExecutionStatus;
 
 bool cmExportLibraryDependenciesCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
@@ -79,8 +90,8 @@ void cmExportLibraryDependenciesCommand::ConstFinalPass() const
       cmTarget const& target = l->second;
 
       // Skip non-library targets.
-      if (target.GetType() < cmState::STATIC_LIBRARY ||
-          target.GetType() > cmState::MODULE_LIBRARY) {
+      if (target.GetType() < cmStateEnums::STATIC_LIBRARY ||
+          target.GetType() > cmStateEnums::MODULE_LIBRARY) {
         continue;
       }
 
@@ -169,5 +180,4 @@ void cmExportLibraryDependenciesCommand::ConstFinalPass() const
     }
   }
   fout << "endif()\n";
-  return;
 }
diff --git a/Source/cmExportLibraryDependenciesCommand.h b/Source/cmExportLibraryDependenciesCommand.h
index fa9f353..be53349 100644
--- a/Source/cmExportLibraryDependenciesCommand.h
+++ b/Source/cmExportLibraryDependenciesCommand.h
@@ -3,12 +3,17 @@
 #ifndef cmExportLibraryDependenciesCommand_h
 #define cmExportLibraryDependenciesCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 class cmExportLibraryDependenciesCommand : public cmCommand
 {
 public:
-  cmTypeMacro(cmExportLibraryDependenciesCommand, cmCommand);
   cmCommand* Clone() CM_OVERRIDE
   {
     return new cmExportLibraryDependenciesCommand;
diff --git a/Source/cmExportTryCompileFileGenerator.cxx b/Source/cmExportTryCompileFileGenerator.cxx
index 9fc71f6..cd0a7e6 100644
--- a/Source/cmExportTryCompileFileGenerator.cxx
+++ b/Source/cmExportTryCompileFileGenerator.cxx
@@ -8,7 +8,7 @@
 #include "cmGlobalGenerator.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cm_auto_ptr.hxx"
@@ -67,7 +67,7 @@ std::string cmExportTryCompileFileGenerator::FindTargets(
 
   CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(prop);
 
-  cmTarget dummyHead("try_compile_dummy_exe", cmState::EXECUTABLE,
+  cmTarget dummyHead("try_compile_dummy_exe", cmStateEnums::EXECUTABLE,
                      cmTarget::VisibilityNormal, tgt->Target->GetMakefile());
 
   cmGeneratorTarget gDummyHead(&dummyHead, tgt->GetLocalGenerator());
diff --git a/Source/cmExprLexer.cxx b/Source/cmExprLexer.cxx
index 0ecab22..fb6f0db 100644
--- a/Source/cmExprLexer.cxx
+++ b/Source/cmExprLexer.cxx
@@ -1,18 +1,17 @@
-#include <cmConfigure.h>
-
-#include "cmStandardIncludes.h"
-#line 2 "/home/andy/vtk/CMake-bin/Source/cmExprLexer.cxx"
+#include "cmStandardLexer.h"
+#line 2 "cmExprLexer.cxx"
 
-#line 4 "/home/andy/vtk/CMake-bin/Source/cmExprLexer.cxx"
+#line 4 "cmExprLexer.cxx"
 
+#define FLEXINT_H 1
 #define  YY_INT_ALIGNED short int
 
 /* A lexical scanner generated by flex */
 
 #define FLEX_SCANNER
 #define YY_FLEX_MAJOR_VERSION 2
-#define YY_FLEX_MINOR_VERSION 5
-#define YY_FLEX_SUBMINOR_VERSION 31
+#define YY_FLEX_MINOR_VERSION 6
+#define YY_FLEX_SUBMINOR_VERSION 1
 #if YY_FLEX_SUBMINOR_VERSION > 0
 #define FLEX_BETA
 #endif
@@ -34,7 +33,15 @@
 
 /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
 
-#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L
+#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+
+/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
+ * if you want the limit (max/min) macros for int types.
+ */
+#ifndef __STDC_LIMIT_MACROS
+#define __STDC_LIMIT_MACROS 1
+#endif
+
 #include <inttypes.h>
 typedef int8_t flex_int8_t;
 typedef uint8_t flex_uint8_t;
@@ -49,7 +56,6 @@ typedef int flex_int32_t;
 typedef unsigned char flex_uint8_t;
 typedef unsigned short int flex_uint16_t;
 typedef unsigned int flex_uint32_t;
-#endif /* ! C99 */
 
 /* Limits of integral types. */
 #ifndef INT8_MIN
@@ -80,26 +86,17 @@ typedef unsigned int flex_uint32_t;
 #define UINT32_MAX             (4294967295U)
 #endif
 
-#endif /* ! FLEXINT_H */
-
-#ifdef __cplusplus
-
-/* The "const" storage-class-modifier is valid. */
-#define YY_USE_CONST
-
-#else  /* ! __cplusplus */
-
-#if __STDC__
-
-#define YY_USE_CONST
+#endif /* ! C99 */
 
-#endif  /* __STDC__ */
-#endif  /* ! __cplusplus */
+#endif /* ! FLEXINT_H */
 
-#ifdef YY_USE_CONST
+/* TODO: this is always defined, so inline it */
 #define yyconst const
+
+#if defined(__GNUC__) && __GNUC__ >= 3
+#define yynoreturn __attribute__((__noreturn__))
 #else
-#define yyconst
+#define yynoreturn
 #endif
 
 /* Returned upon end-of-file. */
@@ -129,8 +126,6 @@ typedef void* yyscan_t;
 #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column)
 #define yy_flex_debug yyg->yy_flex_debug_r
 
-int cmExpr_yylex_init (yyscan_t* scanner);
-
 /* Enter a start condition.  This macro really ought to take a parameter,
  * but we do it the disgusting crufty way forced on us by the ()-less
  * definition of BEGIN.
@@ -154,108 +149,117 @@ int cmExpr_yylex_init (yyscan_t* scanner);
 
 /* Size of default input buffer. */
 #ifndef YY_BUF_SIZE
+#ifdef __ia64__
+/* On IA-64, the buffer size is 16k, not 8k.
+ * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case.
+ * Ditto for the __ia64__ case accordingly.
+ */
+#define YY_BUF_SIZE 32768
+#else
 #define YY_BUF_SIZE 16384
+#endif /* __ia64__ */
 #endif
 
+/* The state buf must be large enough to hold one state per character in the main buffer.
+ */
+#define YY_STATE_BUF_SIZE   ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
+
 #ifndef YY_TYPEDEF_YY_BUFFER_STATE
 #define YY_TYPEDEF_YY_BUFFER_STATE
 typedef struct yy_buffer_state *YY_BUFFER_STATE;
 #endif
 
+#ifndef YY_TYPEDEF_YY_SIZE_T
+#define YY_TYPEDEF_YY_SIZE_T
+typedef size_t yy_size_t;
+#endif
+
 #define EOB_ACT_CONTINUE_SCAN 0
 #define EOB_ACT_END_OF_FILE 1
 #define EOB_ACT_LAST_MATCH 2
 
     #define YY_LESS_LINENO(n)
+    #define YY_LINENO_REWIND_TO(ptr)
 
-/* Return all but the first "n" matched characters back to the input
-   stream. */
+/* Return all but the first "n" matched characters back to the input stream. */
 #define yyless(n) \
-  do \
-    { \
-    /* Undo effects of setting up yytext. */ \
+	do \
+		{ \
+		/* Undo effects of setting up yytext. */ \
         int yyless_macro_arg = (n); \
         YY_LESS_LINENO(yyless_macro_arg);\
-    *yy_cp = yyg->yy_hold_char; \
-    YY_RESTORE_YY_MORE_OFFSET \
-    yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
-    YY_DO_BEFORE_ACTION; /* set up yytext again */ \
-    } \
-  while ( 0 )
-
-/* The following is because we cannot portably get our hands on size_t
- * (without autoconf's help, which isn't available because we want
- * flex-generated scanners to compile on their own).
- */
+		*yy_cp = yyg->yy_hold_char; \
+		YY_RESTORE_YY_MORE_OFFSET \
+		yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
+		YY_DO_BEFORE_ACTION; /* set up yytext again */ \
+		} \
+	while ( 0 )
 
-#ifndef YY_TYPEDEF_YY_SIZE_T
-#define YY_TYPEDEF_YY_SIZE_T
-typedef unsigned int yy_size_t;
-#endif
+#define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner )
 
 #ifndef YY_STRUCT_YY_BUFFER_STATE
 #define YY_STRUCT_YY_BUFFER_STATE
 struct yy_buffer_state
-  {
-  FILE *yy_input_file;
-
-  char *yy_ch_buf;    /* input buffer */
-  char *yy_buf_pos;    /* current position in input buffer */
-
-  /* Size of input buffer in bytes, not including room for EOB
-   * characters.
-   */
-  yy_size_t yy_buf_size;
-
-  /* Number of characters read into yy_ch_buf, not including EOB
-   * characters.
-   */
-  int yy_n_chars;
-
-  /* Whether we "own" the buffer - i.e., we know we created it,
-   * and can realloc() it to grow it, and should free() it to
-   * delete it.
-   */
-  int yy_is_our_buffer;
-
-  /* Whether this is an "interactive" input source; if so, and
-   * if we're using stdio for input, then we want to use getc()
-   * instead of fread(), to make sure we stop fetching input after
-   * each newline.
-   */
-  int yy_is_interactive;
-
-  /* Whether we're considered to be at the beginning of a line.
-   * If so, '^' rules will be active on the next match, otherwise
-   * not.
-   */
-  int yy_at_bol;
+	{
+	FILE *yy_input_file;
+
+	char *yy_ch_buf;		/* input buffer */
+	char *yy_buf_pos;		/* current position in input buffer */
+
+	/* Size of input buffer in bytes, not including room for EOB
+	 * characters.
+	 */
+	int yy_buf_size;
+
+	/* Number of characters read into yy_ch_buf, not including EOB
+	 * characters.
+	 */
+	int yy_n_chars;
+
+	/* Whether we "own" the buffer - i.e., we know we created it,
+	 * and can realloc() it to grow it, and should free() it to
+	 * delete it.
+	 */
+	int yy_is_our_buffer;
+
+	/* Whether this is an "interactive" input source; if so, and
+	 * if we're using stdio for input, then we want to use getc()
+	 * instead of fread(), to make sure we stop fetching input after
+	 * each newline.
+	 */
+	int yy_is_interactive;
+
+	/* Whether we're considered to be at the beginning of a line.
+	 * If so, '^' rules will be active on the next match, otherwise
+	 * not.
+	 */
+	int yy_at_bol;
 
     int yy_bs_lineno; /**< The line count. */
     int yy_bs_column; /**< The column count. */
 
-  /* Whether to try to fill the input buffer when we reach the
-   * end of it.
-   */
-  int yy_fill_buffer;
+	/* Whether to try to fill the input buffer when we reach the
+	 * end of it.
+	 */
+	int yy_fill_buffer;
 
-  int yy_buffer_status;
+	int yy_buffer_status;
 
 #define YY_BUFFER_NEW 0
 #define YY_BUFFER_NORMAL 1
-  /* When an EOF's been seen but there's still some text to process
-   * then we mark the buffer as YY_EOF_PENDING, to indicate that we
-   * shouldn't try reading from the input source any more.  We might
-   * still have a bunch of tokens to match, though, because of
-   * possible backing-up.
-   *
-   * When we actually see the EOF, we change the status to "new"
-   * (via cmExpr_yyrestart()), so that the user can continue scanning by
-   * just pointing yyin at a new input file.
-   */
+	/* When an EOF's been seen but there's still some text to process
+	 * then we mark the buffer as YY_EOF_PENDING, to indicate that we
+	 * shouldn't try reading from the input source any more.  We might
+	 * still have a bunch of tokens to match, though, because of
+	 * possible backing-up.
+	 *
+	 * When we actually see the EOF, we change the status to "new"
+	 * (via cmExpr_yyrestart()), so that the user can continue scanning by
+	 * just pointing yyin at a new input file.
+	 */
 #define YY_BUFFER_EOF_PENDING 2
 
-  };
+	};
 #endif /* !YY_STRUCT_YY_BUFFER_STATE */
 
 /* We provide macros for accessing buffer states in case in the
@@ -268,8 +272,8 @@ struct yy_buffer_state
                           ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \
                           : NULL)
 
-/* Same as previous macro, but useful when we know that the buffer stack is
- * not NULL or when we need an lvalue. For internal use only.
+/* Same as previous macro, but useful when we know that the buffer stack is not
+ * NULL or when we need an lvalue. For internal use only.
  */
 #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top]
 
@@ -298,30 +302,30 @@ void cmExpr_yyfree (void * ,yyscan_t yyscanner );
 #define yy_new_buffer cmExpr_yy_create_buffer
 
 #define yy_set_interactive(is_interactive) \
-  { \
-  if ( ! YY_CURRENT_BUFFER ){ \
+	{ \
+	if ( ! YY_CURRENT_BUFFER ){ \
         cmExpr_yyensure_buffer_stack (yyscanner); \
-    YY_CURRENT_BUFFER_LVALUE =    \
+		YY_CURRENT_BUFFER_LVALUE =    \
             cmExpr_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
-  } \
-  YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
-  }
+	} \
+	YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
+	}
 
 #define yy_set_bol(at_bol) \
-  { \
-  if ( ! YY_CURRENT_BUFFER ){\
+	{ \
+	if ( ! YY_CURRENT_BUFFER ){\
         cmExpr_yyensure_buffer_stack (yyscanner); \
-    YY_CURRENT_BUFFER_LVALUE =    \
+		YY_CURRENT_BUFFER_LVALUE =    \
             cmExpr_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
-  } \
-  YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
-  }
+	} \
+	YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
+	}
 
 #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
 
 /* Begin user sect3 */
 
-#define cmExpr_yywrap(n) 1
+#define cmExpr_yywrap(yyscanner) (/*CONSTCOND*/1)
 #define YY_SKIP_YYWRAP
 
 typedef unsigned char YY_CHAR;
@@ -331,30 +335,29 @@ typedef int yy_state_type;
 #define yytext_ptr yytext_r
 
 static yy_state_type yy_get_previous_state (yyscan_t yyscanner );
-static yy_state_type yy_try_NUL_trans (yy_state_type current_state  ,
-                                       yyscan_t yyscanner);
+static yy_state_type yy_try_NUL_trans (yy_state_type current_state  ,yyscan_t yyscanner);
 static int yy_get_next_buffer (yyscan_t yyscanner );
-static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner );
+static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );
 
 /* Done after the current pattern has been matched and before the
  * corresponding action - sets up yytext.
  */
 #define YY_DO_BEFORE_ACTION \
-  yyg->yytext_ptr = yy_bp; \
-  yyleng = (size_t) (yy_cp - yy_bp); \
-  yyg->yy_hold_char = *yy_cp; \
-  *yy_cp = '\0'; \
-  yyg->yy_c_buf_p = yy_cp;
+	yyg->yytext_ptr = yy_bp; \
+	yyleng = (int) (yy_cp - yy_bp); \
+	yyg->yy_hold_char = *yy_cp; \
+	*yy_cp = '\0'; \
+	yyg->yy_c_buf_p = yy_cp;
 
 #define YY_NUM_RULES 15
 #define YY_END_OF_BUFFER 16
 /* This struct is not used in this scanner,
    but its presence is necessary. */
 struct yy_trans_info
-  {
-  flex_int32_t yy_verify;
-  flex_int32_t yy_nxt;
-  };
+	{
+	flex_int32_t yy_verify;
+	flex_int32_t yy_nxt;
+	};
 static yyconst flex_int16_t yy_accept[23] =
     {   0,
         0,    0,   16,   15,    6,    8,   13,   14,    4,    2,
@@ -362,7 +365,7 @@ static yyconst flex_int16_t yy_accept[23] =
        12,    0
     } ;
 
-static yyconst flex_int32_t yy_ec[256] =
+static yyconst YY_CHAR yy_ec[256] =
     {   0,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
@@ -394,13 +397,13 @@ static yyconst flex_int32_t yy_ec[256] =
         1,    1,    1,    1,    1
     } ;
 
-static yyconst flex_int32_t yy_meta[16] =
+static yyconst YY_CHAR yy_meta[16] =
     {   0,
         1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
         1,    1,    1,    1,    1
     } ;
 
-static yyconst flex_int16_t yy_base[23] =
+static yyconst flex_uint16_t yy_base[23] =
     {   0,
         0,    0,   20,   21,   21,   21,   21,   21,   21,   21,
        21,   21,    9,    7,    5,   21,   21,   21,    6,   21,
@@ -414,7 +417,7 @@ static yyconst flex_int16_t yy_def[23] =
        22,    0
     } ;
 
-static yyconst flex_int16_t yy_nxt[37] =
+static yyconst flex_uint16_t yy_nxt[37] =
     {   0,
         4,    5,    6,    7,    8,    9,   10,   11,   12,   13,
        14,   15,   16,   17,   18,   19,   21,   20,   19,   22,
@@ -437,34 +440,27 @@ static yyconst flex_int16_t yy_chk[37] =
 #define yymore() yymore_used_but_not_detected
 #define YY_MORE_ADJ 0
 #define YY_RESTORE_YY_MORE_OFFSET
-#line 1 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
-#line 2 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 1 "cmExprLexer.in.l"
+#line 2 "cmExprLexer.in.l"
 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
    file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
-This file must be translated to C and modified to build everywhere.
+This file must be translated to C++ and modified to build everywhere.
 
-Run flex like this:
+Run flex >= 2.6 like this:
 
-  flex --prefix=cmExpr_yy --header-file=cmExprLexer.h -ocmExprLexer.cxx cmExprLexer.in.l
+  flex --nounistd -DFLEXINT_H --prefix=cmExpr_yy --header-file=cmExprLexer.h -ocmExprLexer.cxx cmExprLexer.in.l
 
 Modify cmExprLexer.cxx:
-  - remove TABs
-  - remove "yyscanner" argument from these methods:
-      yy_fatal_error, cmExpr_yyalloc, cmExpr_yyrealloc, cmExpr_yyfree
-  - remove all YY_BREAK lines occurring right after return statements
-  - change while ( 1 ) to for(;;)
-
-Modify cmExprLexer.h:
-  - remove TABs
-  - remove the yy_init_globals function
-  - remove the block that includes unistd.h
-  - remove #line directives (avoids bogus warning on old Sun)
+  - remove trailing whitespace: sed -i 's/\s*$//' cmExprLexer.h cmExprLexer.cxx
+  - remove blank lines at end of file
+  - #include "cmStandardLexer.h" at the top
+  - add cast in cmExpr_yy_scan_bytes for loop condition of _yybytes_len to size_t
 
 */
 
-#include "cmStandardLexer.h"
+/* IWYU pragma: no_forward_declare yyguts_t */
 
 #include "cmExprParserHelper.h"
 
@@ -477,18 +473,10 @@ Modify cmExprLexer.h:
 #include "cmExprParserTokens.h"
 
 /*--------------------------------------------------------------------------*/
-#line 518 "/home/andy/vtk/CMake-bin/Source/cmExprLexer.cxx"
+#line 476 "cmExprLexer.cxx"
 
 #define INITIAL 0
 
-#ifndef YY_NO_UNISTD_H
-/* Special case for "unistd.h", since it is non-ANSI. We include it way
- * down here because we want the user's section 1 to have been scanned first.
- * The user has a chance to override it with an option.
- */
-#include <unistd.h>
-#endif
-
 #ifndef YY_EXTRA_TYPE
 #define YY_EXTRA_TYPE void *
 #endif
@@ -500,8 +488,7 @@ struct yyguts_t
     /* User-defined. Not touched by flex. */
     YY_EXTRA_TYPE yyextra_r;
 
-    /* The rest are the same as the globals declared in the non-reentrant
-       scanner. */
+    /* The rest are the same as the globals declared in the non-reentrant scanner. */
     FILE *yyin_r, *yyout_r;
     size_t yy_buffer_stack_top; /**< index of top of stack. */
     size_t yy_buffer_stack_max; /**< capacity of stack. */
@@ -528,6 +515,12 @@ struct yyguts_t
 
     }; /* end struct yyguts_t */
 
+static int yy_init_globals (yyscan_t yyscanner );
+
+int cmExpr_yylex_init (yyscan_t* scanner);
+
+int cmExpr_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
+
 /* Accessor methods to globals.
    These are made visible to non-reentrant scanners for convenience. */
 
@@ -543,19 +536,23 @@ void cmExpr_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
 
 FILE *cmExpr_yyget_in (yyscan_t yyscanner );
 
-void cmExpr_yyset_in  (FILE * in_str ,yyscan_t yyscanner );
+void cmExpr_yyset_in  (FILE * _in_str ,yyscan_t yyscanner );
 
 FILE *cmExpr_yyget_out (yyscan_t yyscanner );
 
-void cmExpr_yyset_out  (FILE * out_str ,yyscan_t yyscanner );
+void cmExpr_yyset_out  (FILE * _out_str ,yyscan_t yyscanner );
 
-int cmExpr_yyget_leng (yyscan_t yyscanner );
+			int cmExpr_yyget_leng (yyscan_t yyscanner );
 
 char *cmExpr_yyget_text (yyscan_t yyscanner );
 
 int cmExpr_yyget_lineno (yyscan_t yyscanner );
 
-void cmExpr_yyset_lineno (int line_number ,yyscan_t yyscanner );
+void cmExpr_yyset_lineno (int _line_number ,yyscan_t yyscanner );
+
+int cmExpr_yyget_column  (yyscan_t yyscanner );
+
+void cmExpr_yyset_column (int _column_no ,yyscan_t yyscanner );
 
 /* Macros after this point can all be overridden by user definitions in
  * section 1.
@@ -569,6 +566,12 @@ extern int cmExpr_yywrap (yyscan_t yyscanner );
 #endif
 #endif
 
+#ifndef YY_NO_UNPUT
+
+    static void yyunput (int c,char *buf_ptr  ,yyscan_t yyscanner);
+
+#endif
+
 #ifndef yytext_ptr
 static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
 #endif
@@ -589,7 +592,12 @@ static int input (yyscan_t yyscanner );
 
 /* Amount of stuff to slurp up with each read. */
 #ifndef YY_READ_BUF_SIZE
+#ifdef __ia64__
+/* On IA-64, the buffer size is 16k, not 8k */
+#define YY_READ_BUF_SIZE 16384
+#else
 #define YY_READ_BUF_SIZE 8192
+#endif /* __ia64__ */
 #endif
 
 /* Copy whatever the last rule matched to the standard output. */
@@ -597,7 +605,7 @@ static int input (yyscan_t yyscanner );
 /* This used to be an fputs(), but since the string might contain NUL's,
  * we now use fwrite().
  */
-#define ECHO (void) fwrite( yytext, yyleng, 1, yyout )
+#define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0)
 #endif
 
 /* Gets input and stuffs it into "buf".  number of characters read, or YY_NULL,
@@ -605,33 +613,33 @@ static int input (yyscan_t yyscanner );
  */
 #ifndef YY_INPUT
 #define YY_INPUT(buf,result,max_size) \
-  if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
-    { \
-    int c = '*'; \
-    size_t n; \
-    for ( n = 0; n < max_size && \
-           (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
-      buf[n] = (char) c; \
-    if ( c == '\n' ) \
-      buf[n++] = (char) c; \
-    if ( c == EOF && ferror( yyin ) ) \
-      YY_FATAL_ERROR( "input in flex scanner failed" ); \
-    result = n; \
-    } \
-  else \
-    { \
-    errno=0; \
-    while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
-      { \
-      if( errno != EINTR) \
-        { \
-        YY_FATAL_ERROR( "input in flex scanner failed" ); \
-        break; \
-        } \
-      errno=0; \
-      clearerr(yyin); \
-      } \
-    }\
+	if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
+		{ \
+		int c = '*'; \
+		size_t n; \
+		for ( n = 0; n < max_size && \
+			     (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
+			buf[n] = (char) c; \
+		if ( c == '\n' ) \
+			buf[n++] = (char) c; \
+		if ( c == EOF && ferror( yyin ) ) \
+			YY_FATAL_ERROR( "input in flex scanner failed" ); \
+		result = n; \
+		} \
+	else \
+		{ \
+		errno=0; \
+		while ( (result = (int) fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
+			{ \
+			if( errno != EINTR) \
+				{ \
+				YY_FATAL_ERROR( "input in flex scanner failed" ); \
+				break; \
+				} \
+			errno=0; \
+			clearerr(yyin); \
+			} \
+		}\
 \
 
 #endif
@@ -676,494 +684,559 @@ extern int cmExpr_yylex (yyscan_t yyscanner);
 
 /* Code executed at the end of each rule. */
 #ifndef YY_BREAK
-#define YY_BREAK break;
+#define YY_BREAK /*LINTED*/break;
 #endif
 
 #define YY_RULE_SETUP \
-  YY_USER_ACTION
+	YY_USER_ACTION
 
 /** The main scanner function which does all the work.
  */
 YY_DECL
 {
-  yy_state_type yy_current_state;
-  char *yy_cp, *yy_bp;
-  int yy_act;
+	yy_state_type yy_current_state;
+	char *yy_cp, *yy_bp;
+	int yy_act;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-#line 86 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+	if ( !yyg->yy_init )
+		{
+		yyg->yy_init = 1;
 
+#ifdef YY_USER_INIT
+		YY_USER_INIT;
+#endif
 
-#line 736 "/home/andy/vtk/CMake-bin/Source/cmExprLexer.cxx"
+		if ( ! yyg->yy_start )
+			yyg->yy_start = 1;	/* first start state */
 
-  if ( yyg->yy_init )
-    {
-    yyg->yy_init = 0;
+		if ( ! yyin )
+			yyin = stdin;
 
-#ifdef YY_USER_INIT
-    YY_USER_INIT;
-#endif
+		if ( ! yyout )
+			yyout = stdout;
 
-    if ( ! yyg->yy_start )
-      yyg->yy_start = 1;  /* first start state */
+		if ( ! YY_CURRENT_BUFFER ) {
+			cmExpr_yyensure_buffer_stack (yyscanner);
+			YY_CURRENT_BUFFER_LVALUE =
+				cmExpr_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
+		}
 
-    if ( ! yyin )
-      yyin = stdin;
+		cmExpr_yy_load_buffer_state(yyscanner );
+		}
 
-    if ( ! yyout )
-      yyout = stdout;
+	{
+#line 39 "cmExprLexer.in.l"
 
-    if ( ! YY_CURRENT_BUFFER ) {
-      cmExpr_yyensure_buffer_stack (yyscanner);
-      YY_CURRENT_BUFFER_LVALUE =
-        cmExpr_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
-    }
 
-    cmExpr_yy_load_buffer_state(yyscanner );
-    }
+#line 732 "cmExprLexer.cxx"
 
-  for(;;)    /* loops until end-of-file is reached */
-    {
-    yy_cp = yyg->yy_c_buf_p;
+	while ( /*CONSTCOND*/1 )		/* loops until end-of-file is reached */
+		{
+		yy_cp = yyg->yy_c_buf_p;
 
-    /* Support of yytext. */
-    *yy_cp = yyg->yy_hold_char;
+		/* Support of yytext. */
+		*yy_cp = yyg->yy_hold_char;
 
-    /* yy_bp points to the position in yy_ch_buf of the start of
-     * the current run.
-     */
-    yy_bp = yy_cp;
+		/* yy_bp points to the position in yy_ch_buf of the start of
+		 * the current run.
+		 */
+		yy_bp = yy_cp;
 
-    yy_current_state = yyg->yy_start;
+		yy_current_state = yyg->yy_start;
 yy_match:
-    do
-      {
-      YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
-      if ( yy_accept[yy_current_state] )
-        {
-        yyg->yy_last_accepting_state = yy_current_state;
-        yyg->yy_last_accepting_cpos = yy_cp;
-        }
-      while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
-        {
-        yy_current_state = (int) yy_def[yy_current_state];
-        if ( yy_current_state >= 23 )
-          yy_c = yy_meta[(unsigned int) yy_c];
-        }
-      yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-      ++yy_cp;
-      }
-    while ( yy_base[yy_current_state] != 21 );
+		do
+			{
+			YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ;
+			if ( yy_accept[yy_current_state] )
+				{
+				yyg->yy_last_accepting_state = yy_current_state;
+				yyg->yy_last_accepting_cpos = yy_cp;
+				}
+			while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+				{
+				yy_current_state = (int) yy_def[yy_current_state];
+				if ( yy_current_state >= 23 )
+					yy_c = yy_meta[(unsigned int) yy_c];
+				}
+			yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+			++yy_cp;
+			}
+		while ( yy_base[yy_current_state] != 21 );
 
 yy_find_action:
-    yy_act = yy_accept[yy_current_state];
-    if ( yy_act == 0 )
-      { /* have to back up */
-      yy_cp = yyg->yy_last_accepting_cpos;
-      yy_current_state = yyg->yy_last_accepting_state;
-      yy_act = yy_accept[yy_current_state];
-      }
-
-    YY_DO_BEFORE_ACTION;
-
-do_action:  /* This label is used only to access EOF actions. */
-
-    switch ( yy_act )
-  { /* beginning of action switch */
-      case 0: /* must back up */
-      /* undo the effects of YY_DO_BEFORE_ACTION */
-      *yy_cp = yyg->yy_hold_char;
-      yy_cp = yyg->yy_last_accepting_cpos;
-      yy_current_state = yyg->yy_last_accepting_state;
-      goto yy_find_action;
+		yy_act = yy_accept[yy_current_state];
+		if ( yy_act == 0 )
+			{ /* have to back up */
+			yy_cp = yyg->yy_last_accepting_cpos;
+			yy_current_state = yyg->yy_last_accepting_state;
+			yy_act = yy_accept[yy_current_state];
+			}
+
+		YY_DO_BEFORE_ACTION;
+
+do_action:	/* This label is used only to access EOF actions. */
+
+		switch ( yy_act )
+	{ /* beginning of action switch */
+			case 0: /* must back up */
+			/* undo the effects of YY_DO_BEFORE_ACTION */
+			*yy_cp = yyg->yy_hold_char;
+			yy_cp = yyg->yy_last_accepting_cpos;
+			yy_current_state = yyg->yy_last_accepting_state;
+			goto yy_find_action;
 
 case 1:
 YY_RULE_SETUP
-#line 88 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 41 "cmExprLexer.in.l"
 { yylvalp->Number = atoi(yytext); return exp_NUMBER; }
+	YY_BREAK
 case 2:
 YY_RULE_SETUP
-#line 90 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 43 "cmExprLexer.in.l"
 { return exp_PLUS; }
+	YY_BREAK
 case 3:
 YY_RULE_SETUP
-#line 91 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 44 "cmExprLexer.in.l"
 { return exp_MINUS; }
+	YY_BREAK
 case 4:
 YY_RULE_SETUP
-#line 92 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 45 "cmExprLexer.in.l"
 { return exp_TIMES; }
+	YY_BREAK
 case 5:
 YY_RULE_SETUP
-#line 93 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 46 "cmExprLexer.in.l"
 { return exp_DIVIDE; }
+	YY_BREAK
 case 6:
 YY_RULE_SETUP
-#line 94 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 47 "cmExprLexer.in.l"
 { return exp_MOD; }
+	YY_BREAK
 case 7:
 YY_RULE_SETUP
-#line 95 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 48 "cmExprLexer.in.l"
 { return exp_OR; }
+	YY_BREAK
 case 8:
 YY_RULE_SETUP
-#line 96 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 49 "cmExprLexer.in.l"
 { return exp_AND; }
+	YY_BREAK
 case 9:
 YY_RULE_SETUP
-#line 97 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 50 "cmExprLexer.in.l"
 { return exp_XOR; }
+	YY_BREAK
 case 10:
 YY_RULE_SETUP
-#line 98 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 51 "cmExprLexer.in.l"
 { return exp_NOT; }
+	YY_BREAK
 case 11:
 YY_RULE_SETUP
-#line 99 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 52 "cmExprLexer.in.l"
 { return exp_SHIFTLEFT; }
+	YY_BREAK
 case 12:
 YY_RULE_SETUP
-#line 100 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 53 "cmExprLexer.in.l"
 { return exp_SHIFTRIGHT; }
+	YY_BREAK
 case 13:
 YY_RULE_SETUP
-#line 101 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 54 "cmExprLexer.in.l"
 { return exp_OPENPARENT; }
+	YY_BREAK
 case 14:
 YY_RULE_SETUP
-#line 102 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 55 "cmExprLexer.in.l"
 { return exp_CLOSEPARENT; }
+	YY_BREAK
 case 15:
 YY_RULE_SETUP
-#line 104 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
+#line 57 "cmExprLexer.in.l"
 ECHO;
-  YY_BREAK
-#line 894 "/home/andy/vtk/CMake-bin/Source/cmExprLexer.cxx"
+	YY_BREAK
+#line 864 "cmExprLexer.cxx"
 case YY_STATE_EOF(INITIAL):
-  yyterminate();
-
-  case YY_END_OF_BUFFER:
-    {
-    /* Amount of text matched not including the EOB char. */
-    int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1;
-
-    /* Undo the effects of YY_DO_BEFORE_ACTION. */
-    *yy_cp = yyg->yy_hold_char;
-    YY_RESTORE_YY_MORE_OFFSET
-
-    if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
-      {
-      /* We're scanning a new file or input source.  It's
-       * possible that this happened because the user
-       * just pointed yyin at a new source and called
-       * cmExpr_yylex().  If so, then we have to assure
-       * consistency between YY_CURRENT_BUFFER and our
-       * globals.  Here is the right place to do so, because
-       * this is the first action (other than possibly a
-       * back-up) that will match for the new input source.
-       */
-      yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
-      YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
-      YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
-      }
-
-    /* Note that here we test for yy_c_buf_p "<=" to the position
-     * of the first EOB in the buffer, since yy_c_buf_p will
-     * already have been incremented past the NUL character
-     * (since all states make transitions on EOB to the
-     * end-of-buffer state).  Contrast this with the test
-     * in input().
-     */
-    if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
-      { /* This was really a NUL. */
-      yy_state_type yy_next_state;
-
-      yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text;
-
-      yy_current_state = yy_get_previous_state( yyscanner );
-
-      /* Okay, we're now positioned to make the NUL
-       * transition.  We couldn't have
-       * yy_get_previous_state() go ahead and do it
-       * for us because it doesn't know how to deal
-       * with the possibility of jamming (and we don't
-       * want to build jamming into it because then it
-       * will run more slowly).
-       */
-
-      yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner);
-
-      yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
-
-      if ( yy_next_state )
-        {
-        /* Consume the NUL. */
-        yy_cp = ++yyg->yy_c_buf_p;
-        yy_current_state = yy_next_state;
-        goto yy_match;
-        }
-
-      else
-        {
-        yy_cp = yyg->yy_c_buf_p;
-        goto yy_find_action;
-        }
-      }
-
-    else switch ( yy_get_next_buffer( yyscanner ) )
-      {
-      case EOB_ACT_END_OF_FILE:
-        {
-        yyg->yy_did_buffer_switch_on_eof = 0;
-
-        if ( cmExpr_yywrap(yyscanner ) )
-          {
-          /* Note: because we've taken care in
-           * yy_get_next_buffer() to have set up
-           * yytext, we can now set up
-           * yy_c_buf_p so that if some total
-           * hoser (like flex itself) wants to
-           * call the scanner after we return the
-           * YY_NULL, it'll still work - another
-           * YY_NULL will get returned.
-           */
-          yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ;
-
-          yy_act = YY_STATE_EOF(YY_START);
-          goto do_action;
-          }
-
-        else
-          {
-          if ( ! yyg->yy_did_buffer_switch_on_eof )
-            YY_NEW_FILE;
-          }
-        break;
-        }
-
-      case EOB_ACT_CONTINUE_SCAN:
-        yyg->yy_c_buf_p =
-          yyg->yytext_ptr + yy_amount_of_matched_text;
-
-        yy_current_state = yy_get_previous_state( yyscanner );
-
-        yy_cp = yyg->yy_c_buf_p;
-        yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
-        goto yy_match;
-
-      case EOB_ACT_LAST_MATCH:
-        yyg->yy_c_buf_p =
-        &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars];
-
-        yy_current_state = yy_get_previous_state( yyscanner );
-
-        yy_cp = yyg->yy_c_buf_p;
-        yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
-        goto yy_find_action;
-      }
-    break;
-    }
-
-  default:
-    YY_FATAL_ERROR(
-      "fatal flex scanner internal error--no action found" );
-  } /* end of action switch */
-    } /* end of scanning one token */
-return 0; /* this should not happen but it quiets some compilers */
+	yyterminate();
+
+	case YY_END_OF_BUFFER:
+		{
+		/* Amount of text matched not including the EOB char. */
+		int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1;
+
+		/* Undo the effects of YY_DO_BEFORE_ACTION. */
+		*yy_cp = yyg->yy_hold_char;
+		YY_RESTORE_YY_MORE_OFFSET
+
+		if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
+			{
+			/* We're scanning a new file or input source.  It's
+			 * possible that this happened because the user
+			 * just pointed yyin at a new source and called
+			 * cmExpr_yylex().  If so, then we have to assure
+			 * consistency between YY_CURRENT_BUFFER and our
+			 * globals.  Here is the right place to do so, because
+			 * this is the first action (other than possibly a
+			 * back-up) that will match for the new input source.
+			 */
+			yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+			YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
+			YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
+			}
+
+		/* Note that here we test for yy_c_buf_p "<=" to the position
+		 * of the first EOB in the buffer, since yy_c_buf_p will
+		 * already have been incremented past the NUL character
+		 * (since all states make transitions on EOB to the
+		 * end-of-buffer state).  Contrast this with the test
+		 * in input().
+		 */
+		if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
+			{ /* This was really a NUL. */
+			yy_state_type yy_next_state;
+
+			yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text;
+
+			yy_current_state = yy_get_previous_state( yyscanner );
+
+			/* Okay, we're now positioned to make the NUL
+			 * transition.  We couldn't have
+			 * yy_get_previous_state() go ahead and do it
+			 * for us because it doesn't know how to deal
+			 * with the possibility of jamming (and we don't
+			 * want to build jamming into it because then it
+			 * will run more slowly).
+			 */
+
+			yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner);
+
+			yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
+
+			if ( yy_next_state )
+				{
+				/* Consume the NUL. */
+				yy_cp = ++yyg->yy_c_buf_p;
+				yy_current_state = yy_next_state;
+				goto yy_match;
+				}
+
+			else
+				{
+				yy_cp = yyg->yy_c_buf_p;
+				goto yy_find_action;
+				}
+			}
+
+		else switch ( yy_get_next_buffer( yyscanner ) )
+			{
+			case EOB_ACT_END_OF_FILE:
+				{
+				yyg->yy_did_buffer_switch_on_eof = 0;
+
+				if ( cmExpr_yywrap(yyscanner ) )
+					{
+					/* Note: because we've taken care in
+					 * yy_get_next_buffer() to have set up
+					 * yytext, we can now set up
+					 * yy_c_buf_p so that if some total
+					 * hoser (like flex itself) wants to
+					 * call the scanner after we return the
+					 * YY_NULL, it'll still work - another
+					 * YY_NULL will get returned.
+					 */
+					yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ;
+
+					yy_act = YY_STATE_EOF(YY_START);
+					goto do_action;
+					}
+
+				else
+					{
+					if ( ! yyg->yy_did_buffer_switch_on_eof )
+						YY_NEW_FILE;
+					}
+				break;
+				}
+
+			case EOB_ACT_CONTINUE_SCAN:
+				yyg->yy_c_buf_p =
+					yyg->yytext_ptr + yy_amount_of_matched_text;
+
+				yy_current_state = yy_get_previous_state( yyscanner );
+
+				yy_cp = yyg->yy_c_buf_p;
+				yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
+				goto yy_match;
+
+			case EOB_ACT_LAST_MATCH:
+				yyg->yy_c_buf_p =
+				&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars];
+
+				yy_current_state = yy_get_previous_state( yyscanner );
+
+				yy_cp = yyg->yy_c_buf_p;
+				yy_bp = yyg->yytext_ptr + YY_MORE_ADJ;
+				goto yy_find_action;
+			}
+		break;
+		}
+
+	default:
+		YY_FATAL_ERROR(
+			"fatal flex scanner internal error--no action found" );
+	} /* end of action switch */
+		} /* end of scanning one token */
+	} /* end of user's declarations */
 } /* end of cmExpr_yylex */
 
 /* yy_get_next_buffer - try to read in a new buffer
  *
  * Returns a code representing an action:
- *  EOB_ACT_LAST_MATCH -
- *  EOB_ACT_CONTINUE_SCAN - continue scanning from current position
- *  EOB_ACT_END_OF_FILE - end of file
+ *	EOB_ACT_LAST_MATCH -
+ *	EOB_ACT_CONTINUE_SCAN - continue scanning from current position
+ *	EOB_ACT_END_OF_FILE - end of file
  */
 static int yy_get_next_buffer (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
-  char *source = yyg->yytext_ptr;
-  int number_to_move, i;
-  int ret_val;
-
-  if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
-    YY_FATAL_ERROR(
-    "fatal flex scanner internal error--end of buffer missed" );
-
-  if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
-    { /* Don't try to fill the buffer, so this is an EOF. */
-    if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 )
-      {
-      /* We matched a single character, the EOB, so
-       * treat this as a final EOF.
-       */
-      return EOB_ACT_END_OF_FILE;
-      }
-
-    else
-      {
-      /* We matched some text prior to the EOB, first
-       * process it.
-       */
-      return EOB_ACT_LAST_MATCH;
-      }
-    }
-
-  /* Try to read more data. */
-
-  /* First move last chars to start of buffer. */
-  number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
-
-  for ( i = 0; i < number_to_move; ++i )
-    *(dest++) = *(source++);
-
-  if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
-    /* don't do the read, it's not guaranteed to return an EOF,
-     * just force an EOF
-     */
-    YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0;
-
-  else
-    {
-      size_t nuto_read =
-      YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
-
-    while ( nuto_read <= 0 )
-      { /* Not enough room in the buffer - grow it. */
-
-      /* just a shorter name for the current buffer */
-      YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
-
-      int yy_c_buf_p_offset =
-        (int) (yyg->yy_c_buf_p - b->yy_ch_buf);
-
-      if ( b->yy_is_our_buffer )
-        {
-        int new_size = b->yy_buf_size * 2;
-
-        if ( new_size <= 0 )
-          b->yy_buf_size += b->yy_buf_size / 8;
-        else
-          b->yy_buf_size *= 2;
-
-        b->yy_ch_buf = (char *)
-          /* Include room in for 2 EOB chars. */
-          cmExpr_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
-        }
-      else
-        /* Can't grow it, we don't own it. */
-        b->yy_ch_buf = 0;
-
-      if ( ! b->yy_ch_buf )
-        YY_FATAL_ERROR(
-        "fatal error - scanner input buffer overflow" );
-
-      yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
-
-      nuto_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
-            number_to_move - 1;
-
-      }
-
-    if ( nuto_read > YY_READ_BUF_SIZE )
-      nuto_read = YY_READ_BUF_SIZE;
-
-    /* Read in more data. */
-    YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
-      yyg->yy_n_chars, nuto_read );
-
-    YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
-    }
+	char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
+	char *source = yyg->yytext_ptr;
+	yy_size_t number_to_move, i;
+	int ret_val;
+
+	if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
+		YY_FATAL_ERROR(
+		"fatal flex scanner internal error--end of buffer missed" );
+
+	if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
+		{ /* Don't try to fill the buffer, so this is an EOF. */
+		if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 )
+			{
+			/* We matched a single character, the EOB, so
+			 * treat this as a final EOF.
+			 */
+			return EOB_ACT_END_OF_FILE;
+			}
+
+		else
+			{
+			/* We matched some text prior to the EOB, first
+			 * process it.
+			 */
+			return EOB_ACT_LAST_MATCH;
+			}
+		}
+
+	/* Try to read more data. */
+
+	/* First move last chars to start of buffer. */
+	number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
+
+	for ( i = 0; i < number_to_move; ++i )
+		*(dest++) = *(source++);
+
+	if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
+		/* don't do the read, it's not guaranteed to return an EOF,
+		 * just force an EOF
+		 */
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0;
+
+	else
+		{
+			int num_to_read =
+			YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
+
+		while ( num_to_read <= 0 )
+			{ /* Not enough room in the buffer - grow it. */
+
+			/* just a shorter name for the current buffer */
+			YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE;
+
+			int yy_c_buf_p_offset =
+				(int) (yyg->yy_c_buf_p - b->yy_ch_buf);
+
+			if ( b->yy_is_our_buffer )
+				{
+				int new_size = b->yy_buf_size * 2;
+
+				if ( new_size <= 0 )
+					b->yy_buf_size += b->yy_buf_size / 8;
+				else
+					b->yy_buf_size *= 2;
+
+				b->yy_ch_buf = (char *)
+					/* Include room in for 2 EOB chars. */
+					cmExpr_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
+				}
+			else
+				/* Can't grow it, we don't own it. */
+				b->yy_ch_buf = NULL;
+
+			if ( ! b->yy_ch_buf )
+				YY_FATAL_ERROR(
+				"fatal error - scanner input buffer overflow" );
+
+			yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset];
+
+			num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
+						number_to_move - 1;
+
+			}
+
+		if ( num_to_read > YY_READ_BUF_SIZE )
+			num_to_read = YY_READ_BUF_SIZE;
+
+		/* Read in more data. */
+		YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
+			yyg->yy_n_chars, num_to_read );
+
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
+		}
+
+	if ( yyg->yy_n_chars == 0 )
+		{
+		if ( number_to_move == YY_MORE_ADJ )
+			{
+			ret_val = EOB_ACT_END_OF_FILE;
+			cmExpr_yyrestart(yyin  ,yyscanner);
+			}
+
+		else
+			{
+			ret_val = EOB_ACT_LAST_MATCH;
+			YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
+				YY_BUFFER_EOF_PENDING;
+			}
+		}
+
+	else
+		ret_val = EOB_ACT_CONTINUE_SCAN;
+
+	if ((int) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
+		/* Extend the array by 50%, plus the number we really need. */
+		int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
+		YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) cmExpr_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );
+		if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
+			YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
+	}
+
+	yyg->yy_n_chars += number_to_move;
+	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR;
+	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
+
+	yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
 
-  if ( yyg->yy_n_chars == 0 )
-    {
-    if ( number_to_move == YY_MORE_ADJ )
-      {
-      ret_val = EOB_ACT_END_OF_FILE;
-      cmExpr_yyrestart(yyin  ,yyscanner);
-      }
-
-    else
-      {
-      ret_val = EOB_ACT_LAST_MATCH;
-      YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
-        YY_BUFFER_EOF_PENDING;
-      }
-    }
-
-  else
-    ret_val = EOB_ACT_CONTINUE_SCAN;
-
-  yyg->yy_n_chars += number_to_move;
-  YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR;
-  YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR;
-
-  yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
-
-  return ret_val;
+	return ret_val;
 }
 
-/* yy_get_previous_state - get the state just before the EOB char was
-   reached */
+/* yy_get_previous_state - get the state just before the EOB char was reached */
 
     static yy_state_type yy_get_previous_state (yyscan_t yyscanner)
 {
-  yy_state_type yy_current_state;
-  char *yy_cp;
+	yy_state_type yy_current_state;
+	char *yy_cp;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-  yy_current_state = yyg->yy_start;
-
-  for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp )
-    {
-    YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
-    if ( yy_accept[yy_current_state] )
-      {
-      yyg->yy_last_accepting_state = yy_current_state;
-      yyg->yy_last_accepting_cpos = yy_cp;
-      }
-    while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
-      {
-      yy_current_state = (int) yy_def[yy_current_state];
-      if ( yy_current_state >= 23 )
-        yy_c = yy_meta[(unsigned int) yy_c];
-      }
-    yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-    }
-
-  return yy_current_state;
+	yy_current_state = yyg->yy_start;
+
+	for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp )
+		{
+		YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
+		if ( yy_accept[yy_current_state] )
+			{
+			yyg->yy_last_accepting_state = yy_current_state;
+			yyg->yy_last_accepting_cpos = yy_cp;
+			}
+		while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+			{
+			yy_current_state = (int) yy_def[yy_current_state];
+			if ( yy_current_state >= 23 )
+				yy_c = yy_meta[(unsigned int) yy_c];
+			}
+		yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+		}
+
+	return yy_current_state;
 }
 
 /* yy_try_NUL_trans - try to make a transition on the NUL character
  *
  * synopsis
- *  next_state = yy_try_NUL_trans( current_state );
+ *	next_state = yy_try_NUL_trans( current_state );
  */
     static yy_state_type yy_try_NUL_trans  (yy_state_type yy_current_state , yyscan_t yyscanner)
 {
-  int yy_is_jam;
+	int yy_is_jam;
+    struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */
+	char *yy_cp = yyg->yy_c_buf_p;
+
+	YY_CHAR yy_c = 1;
+	if ( yy_accept[yy_current_state] )
+		{
+		yyg->yy_last_accepting_state = yy_current_state;
+		yyg->yy_last_accepting_cpos = yy_cp;
+		}
+	while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+		{
+		yy_current_state = (int) yy_def[yy_current_state];
+		if ( yy_current_state >= 23 )
+			yy_c = yy_meta[(unsigned int) yy_c];
+		}
+	yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+	yy_is_jam = (yy_current_state == 22);
+
+	(void)yyg;
+	return yy_is_jam ? 0 : yy_current_state;
+}
+
+#ifndef YY_NO_UNPUT
+
+    static void yyunput (int c, char * yy_bp , yyscan_t yyscanner)
+{
+	char *yy_cp;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  char *yy_cp = yyg->yy_c_buf_p;
 
-  YY_CHAR yy_c = 1;
-  if ( yy_accept[yy_current_state] )
-    {
-    yyg->yy_last_accepting_state = yy_current_state;
-    yyg->yy_last_accepting_cpos = yy_cp;
-    }
-  while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
-    {
-    yy_current_state = (int) yy_def[yy_current_state];
-    if ( yy_current_state >= 23 )
-      yy_c = yy_meta[(unsigned int) yy_c];
-    }
-  yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
-  yy_is_jam = (yy_current_state == 22);
+    yy_cp = yyg->yy_c_buf_p;
+
+	/* undo effects of setting up yytext */
+	*yy_cp = yyg->yy_hold_char;
+
+	if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
+		{ /* need to shift things up to make room */
+		/* +2 for EOB chars. */
+		int number_to_move = yyg->yy_n_chars + 2;
+		char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
+					YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
+		char *source =
+				&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
 
-  return yy_is_jam ? 0 : yy_current_state;
+		while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
+			*--dest = *--source;
+
+		yy_cp += (int) (dest - source);
+		yy_bp += (int) (dest - source);
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
+			yyg->yy_n_chars = (int) YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
+
+		if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
+			YY_FATAL_ERROR( "flex scanner push-back overflow" );
+		}
+
+	*--yy_cp = (char) c;
+
+	yyg->yytext_ptr = yy_bp;
+	yyg->yy_hold_char = *yy_cp;
+	yyg->yy_c_buf_p = yy_cp;
 }
 
+#endif
+
 #ifndef YY_NO_INPUT
 #ifdef __cplusplus
     static int yyinput (yyscan_t yyscanner)
@@ -1172,72 +1245,72 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 #endif
 
 {
-  int c;
+	int c;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-  *yyg->yy_c_buf_p = yyg->yy_hold_char;
-
-  if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
-    {
-    /* yy_c_buf_p now points to the character we want to return.
-     * If this occurs *before* the EOB characters, then it's a
-     * valid NUL; if not, then we've hit the end of the buffer.
-     */
-    if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
-      /* This was really a NUL. */
-      *yyg->yy_c_buf_p = '\0';
-
-    else
-      { /* need more input */
-      int offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
-      ++yyg->yy_c_buf_p;
-
-      switch ( yy_get_next_buffer( yyscanner ) )
-        {
-        case EOB_ACT_LAST_MATCH:
-          /* This happens because yy_g_n_b()
-           * sees that we've accumulated a
-           * token and flags that we need to
-           * try matching the token before
-           * proceeding.  But for input(),
-           * there's no matching to consider.
-           * So convert the EOB_ACT_LAST_MATCH
-           * to EOB_ACT_END_OF_FILE.
-           */
-
-          /* Reset buffer status. */
-          cmExpr_yyrestart(yyin ,yyscanner);
-
-          /*FALLTHROUGH*/
-
-        case EOB_ACT_END_OF_FILE:
-          {
-          if ( cmExpr_yywrap(yyscanner ) )
-            return EOF;
-
-          if ( ! yyg->yy_did_buffer_switch_on_eof )
-            YY_NEW_FILE;
+	*yyg->yy_c_buf_p = yyg->yy_hold_char;
+
+	if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR )
+		{
+		/* yy_c_buf_p now points to the character we want to return.
+		 * If this occurs *before* the EOB characters, then it's a
+		 * valid NUL; if not, then we've hit the end of the buffer.
+		 */
+		if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] )
+			/* This was really a NUL. */
+			*yyg->yy_c_buf_p = '\0';
+
+		else
+			{ /* need more input */
+			int offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
+			++yyg->yy_c_buf_p;
+
+			switch ( yy_get_next_buffer( yyscanner ) )
+				{
+				case EOB_ACT_LAST_MATCH:
+					/* This happens because yy_g_n_b()
+					 * sees that we've accumulated a
+					 * token and flags that we need to
+					 * try matching the token before
+					 * proceeding.  But for input(),
+					 * there's no matching to consider.
+					 * So convert the EOB_ACT_LAST_MATCH
+					 * to EOB_ACT_END_OF_FILE.
+					 */
+
+					/* Reset buffer status. */
+					cmExpr_yyrestart(yyin ,yyscanner);
+
+					/*FALLTHROUGH*/
+
+				case EOB_ACT_END_OF_FILE:
+					{
+					if ( cmExpr_yywrap(yyscanner ) )
+						return 0;
+
+					if ( ! yyg->yy_did_buffer_switch_on_eof )
+						YY_NEW_FILE;
 #ifdef __cplusplus
-          return yyinput(yyscanner);
+					return yyinput(yyscanner);
 #else
-          return input(yyscanner);
+					return input(yyscanner);
 #endif
-          }
+					}
 
-        case EOB_ACT_CONTINUE_SCAN:
-          yyg->yy_c_buf_p = yyg->yytext_ptr + offset;
-          break;
-        }
-      }
-    }
+				case EOB_ACT_CONTINUE_SCAN:
+					yyg->yy_c_buf_p = yyg->yytext_ptr + offset;
+					break;
+				}
+			}
+		}
 
-  c = *(unsigned char *) yyg->yy_c_buf_p;  /* cast for 8-bit char's */
-  *yyg->yy_c_buf_p = '\0';  /* preserve yytext */
-  yyg->yy_hold_char = *++yyg->yy_c_buf_p;
+	c = *(unsigned char *) yyg->yy_c_buf_p;	/* cast for 8-bit char's */
+	*yyg->yy_c_buf_p = '\0';	/* preserve yytext */
+	yyg->yy_hold_char = *++yyg->yy_c_buf_p;
 
-  return c;
+	return c;
 }
-#endif  /* ifndef YY_NO_INPUT */
+#endif	/* ifndef YY_NO_INPUT */
 
 /** Immediately switch to a different input stream.
  * @param input_file A readable stream.
@@ -1248,14 +1321,14 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-  if ( ! YY_CURRENT_BUFFER ){
+	if ( ! YY_CURRENT_BUFFER ){
         cmExpr_yyensure_buffer_stack (yyscanner);
-    YY_CURRENT_BUFFER_LVALUE =
+		YY_CURRENT_BUFFER_LVALUE =
             cmExpr_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
-  }
+	}
 
-  cmExpr_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
-  cmExpr_yy_load_buffer_state(yyscanner );
+	cmExpr_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
+	cmExpr_yy_load_buffer_state(yyscanner );
 }
 
 /** Switch to a different input buffer.
@@ -1266,41 +1339,41 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-  /* TODO. We should be able to replace this entire function body
-   * with
-   *    cmExpr_yypop_buffer_state();
-   *    cmExpr_yypush_buffer_state(new_buffer);
+	/* TODO. We should be able to replace this entire function body
+	 * with
+	 *		cmExpr_yypop_buffer_state();
+	 *		cmExpr_yypush_buffer_state(new_buffer);
      */
-  cmExpr_yyensure_buffer_stack (yyscanner);
-  if ( YY_CURRENT_BUFFER == new_buffer )
-    return;
-
-  if ( YY_CURRENT_BUFFER )
-    {
-    /* Flush out information for old buffer. */
-    *yyg->yy_c_buf_p = yyg->yy_hold_char;
-    YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
-    YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
-    }
-
-  YY_CURRENT_BUFFER_LVALUE = new_buffer;
-  cmExpr_yy_load_buffer_state(yyscanner );
-
-  /* We don't actually know whether we did this switch during
-   * EOF (cmExpr_yywrap()) processing, but the only time this flag
-   * is looked at is after cmExpr_yywrap() is called, so it's safe
-   * to go ahead and always set it.
-   */
-  yyg->yy_did_buffer_switch_on_eof = 1;
+	cmExpr_yyensure_buffer_stack (yyscanner);
+	if ( YY_CURRENT_BUFFER == new_buffer )
+		return;
+
+	if ( YY_CURRENT_BUFFER )
+		{
+		/* Flush out information for old buffer. */
+		*yyg->yy_c_buf_p = yyg->yy_hold_char;
+		YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
+		}
+
+	YY_CURRENT_BUFFER_LVALUE = new_buffer;
+	cmExpr_yy_load_buffer_state(yyscanner );
+
+	/* We don't actually know whether we did this switch during
+	 * EOF (cmExpr_yywrap()) processing, but the only time this flag
+	 * is looked at is after cmExpr_yywrap() is called, so it's safe
+	 * to go ahead and always set it.
+	 */
+	yyg->yy_did_buffer_switch_on_eof = 1;
 }
 
 static void cmExpr_yy_load_buffer_state  (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
-  yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
-  yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
-  yyg->yy_hold_char = *yyg->yy_c_buf_p;
+	yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+	yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
+	yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
+	yyg->yy_hold_char = *yyg->yy_c_buf_p;
 }
 
 /** Allocate and initialize an input buffer state.
@@ -1311,26 +1384,26 @@ static void cmExpr_yy_load_buffer_state  (yyscan_t yyscanner)
  */
     YY_BUFFER_STATE cmExpr_yy_create_buffer  (FILE * file, int  size , yyscan_t yyscanner)
 {
-  YY_BUFFER_STATE b;
+	YY_BUFFER_STATE b;
 
-  b = (YY_BUFFER_STATE) cmExpr_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
-  if ( ! b )
-    YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yy_create_buffer()" );
+	b = (YY_BUFFER_STATE) cmExpr_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+	if ( ! b )
+		YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yy_create_buffer()" );
 
-  b->yy_buf_size = size;
+	b->yy_buf_size = (yy_size_t)size;
 
-  /* yy_ch_buf has to be 2 characters longer than the size given because
-   * we need to put in 2 end-of-buffer characters.
-   */
-  b->yy_ch_buf = (char *) cmExpr_yyalloc(b->yy_buf_size + 2 ,yyscanner );
-  if ( ! b->yy_ch_buf )
-    YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yy_create_buffer()" );
+	/* yy_ch_buf has to be 2 characters longer than the size given because
+	 * we need to put in 2 end-of-buffer characters.
+	 */
+	b->yy_ch_buf = (char *) cmExpr_yyalloc(b->yy_buf_size + 2 ,yyscanner );
+	if ( ! b->yy_ch_buf )
+		YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yy_create_buffer()" );
 
-  b->yy_is_our_buffer = 1;
+	b->yy_is_our_buffer = 1;
 
-  cmExpr_yy_init_buffer(b,file ,yyscanner);
+	cmExpr_yy_init_buffer(b,file ,yyscanner);
 
-  return b;
+	return b;
 }
 
 /** Destroy the buffer.
@@ -1341,22 +1414,18 @@ static void cmExpr_yy_load_buffer_state  (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-  if ( ! b )
-    return;
+	if ( ! b )
+		return;
 
-  if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
-    YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
+	if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
+		YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
 
-  if ( b->yy_is_our_buffer )
-    cmExpr_yyfree((void *) b->yy_ch_buf ,yyscanner );
+	if ( b->yy_is_our_buffer )
+		cmExpr_yyfree((void *) b->yy_ch_buf ,yyscanner );
 
-  cmExpr_yyfree((void *) b ,yyscanner );
+	cmExpr_yyfree((void *) b ,yyscanner );
 }
 
-#ifndef __cplusplus
-extern int isatty (int );
-#endif /* __cplusplus */
-
 /* Initializes or reinitializes a buffer.
  * This function is sometimes called more than once on the same buffer,
  * such as during a cmExpr_yyrestart() or at EOF.
@@ -1364,13 +1433,13 @@ extern int isatty (int );
     static void cmExpr_yy_init_buffer  (YY_BUFFER_STATE  b, FILE * file , yyscan_t yyscanner)
 
 {
-  int oerrno = errno;
+	int oerrno = errno;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-  cmExpr_yy_flush_buffer(b ,yyscanner);
+	cmExpr_yy_flush_buffer(b ,yyscanner);
 
-  b->yy_input_file = file;
-  b->yy_fill_buffer = 1;
+	b->yy_input_file = file;
+	b->yy_fill_buffer = 1;
 
     /* If b is the current buffer, then cmExpr_yy_init_buffer was _probably_
      * called from cmExpr_yyrestart() or through yy_get_next_buffer.
@@ -1383,7 +1452,7 @@ extern int isatty (int );
 
         b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
 
-  errno = oerrno;
+	errno = oerrno;
 }
 
 /** Discard all buffered characters. On the next scan, YY_INPUT will be called.
@@ -1393,25 +1462,25 @@ extern int isatty (int );
     void cmExpr_yy_flush_buffer (YY_BUFFER_STATE  b , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  if ( ! b )
-    return;
+	if ( ! b )
+		return;
 
-  b->yy_n_chars = 0;
+	b->yy_n_chars = 0;
 
-  /* We always need two end-of-buffer characters.  The first causes
-   * a transition to the end-of-buffer state.  The second causes
-   * a jam in that state.
-   */
-  b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
-  b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
+	/* We always need two end-of-buffer characters.  The first causes
+	 * a transition to the end-of-buffer state.  The second causes
+	 * a jam in that state.
+	 */
+	b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
+	b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
 
-  b->yy_buf_pos = &b->yy_ch_buf[0];
+	b->yy_buf_pos = &b->yy_ch_buf[0];
 
-  b->yy_at_bol = 1;
-  b->yy_buffer_status = YY_BUFFER_NEW;
+	b->yy_at_bol = 1;
+	b->yy_buffer_status = YY_BUFFER_NEW;
 
-  if ( b == YY_CURRENT_BUFFER )
-    cmExpr_yy_load_buffer_state(yyscanner );
+	if ( b == YY_CURRENT_BUFFER )
+		cmExpr_yy_load_buffer_state(yyscanner );
 }
 
 /** Pushes the new state onto the stack. The new state becomes
@@ -1423,28 +1492,28 @@ extern int isatty (int );
 void cmExpr_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  if (new_buffer == NULL)
-    return;
-
-  cmExpr_yyensure_buffer_stack(yyscanner);
-
-  /* This block is copied from cmExpr_yy_switch_to_buffer. */
-  if ( YY_CURRENT_BUFFER )
-    {
-    /* Flush out information for old buffer. */
-    *yyg->yy_c_buf_p = yyg->yy_hold_char;
-    YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
-    YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
-    }
-
-  /* Only push if top exists. Otherwise, replace top. */
-  if (YY_CURRENT_BUFFER)
-    yyg->yy_buffer_stack_top++;
-  YY_CURRENT_BUFFER_LVALUE = new_buffer;
-
-  /* copied from cmExpr_yy_switch_to_buffer. */
-  cmExpr_yy_load_buffer_state(yyscanner );
-  yyg->yy_did_buffer_switch_on_eof = 1;
+	if (new_buffer == NULL)
+		return;
+
+	cmExpr_yyensure_buffer_stack(yyscanner);
+
+	/* This block is copied from cmExpr_yy_switch_to_buffer. */
+	if ( YY_CURRENT_BUFFER )
+		{
+		/* Flush out information for old buffer. */
+		*yyg->yy_c_buf_p = yyg->yy_hold_char;
+		YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p;
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars;
+		}
+
+	/* Only push if top exists. Otherwise, replace top. */
+	if (YY_CURRENT_BUFFER)
+		yyg->yy_buffer_stack_top++;
+	YY_CURRENT_BUFFER_LVALUE = new_buffer;
+
+	/* copied from cmExpr_yy_switch_to_buffer. */
+	cmExpr_yy_load_buffer_state(yyscanner );
+	yyg->yy_did_buffer_switch_on_eof = 1;
 }
 
 /** Removes and deletes the top of the stack, if present.
@@ -1454,18 +1523,18 @@ void cmExpr_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner
 void cmExpr_yypop_buffer_state (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  if (!YY_CURRENT_BUFFER)
-    return;
-
-  cmExpr_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
-  YY_CURRENT_BUFFER_LVALUE = NULL;
-  if (yyg->yy_buffer_stack_top > 0)
-    --yyg->yy_buffer_stack_top;
-
-  if (YY_CURRENT_BUFFER) {
-    cmExpr_yy_load_buffer_state(yyscanner );
-    yyg->yy_did_buffer_switch_on_eof = 1;
-  }
+	if (!YY_CURRENT_BUFFER)
+		return;
+
+	cmExpr_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
+	YY_CURRENT_BUFFER_LVALUE = NULL;
+	if (yyg->yy_buffer_stack_top > 0)
+		--yyg->yy_buffer_stack_top;
+
+	if (YY_CURRENT_BUFFER) {
+		cmExpr_yy_load_buffer_state(yyscanner );
+		yyg->yy_did_buffer_switch_on_eof = 1;
+	}
 }
 
 /* Allocates the stack if it does not exist.
@@ -1473,42 +1542,46 @@ void cmExpr_yypop_buffer_state (yyscan_t yyscanner)
  */
 static void cmExpr_yyensure_buffer_stack (yyscan_t yyscanner)
 {
-  int nuto_alloc;
+	int num_to_alloc;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
-  if (!yyg->yy_buffer_stack) {
+	if (!yyg->yy_buffer_stack) {
 
-    /* First allocation is just for 2 elements, since we don't know if this
-     * scanner will even need a stack. We use 2 instead of 1 to avoid an
-     * immediate realloc on the next call.
+		/* First allocation is just for 2 elements, since we don't know if this
+		 * scanner will even need a stack. We use 2 instead of 1 to avoid an
+		 * immediate realloc on the next call.
          */
-    nuto_alloc = 1;
-    yyg->yy_buffer_stack = (struct yy_buffer_state**)cmExpr_yyalloc
-                (nuto_alloc * sizeof(struct yy_buffer_state*)
-                , yyscanner);
-
-    memset(yyg->yy_buffer_stack, 0, nuto_alloc * sizeof(struct yy_buffer_state*));
-
-    yyg->yy_buffer_stack_max = nuto_alloc;
-    yyg->yy_buffer_stack_top = 0;
-    return;
-  }
-
-  if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
-
-    /* Increase the buffer to prepare for a possible push. */
-    int grow_size = 8 /* arbitrary grow size */;
-
-    nuto_alloc = yyg->yy_buffer_stack_max + grow_size;
-    yyg->yy_buffer_stack = (struct yy_buffer_state**)cmExpr_yyrealloc
-                (yyg->yy_buffer_stack,
-                nuto_alloc * sizeof(struct yy_buffer_state*)
-                , yyscanner);
-
-    /* zero only the new slots.*/
-    memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
-    yyg->yy_buffer_stack_max = nuto_alloc;
-  }
+      num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
+		yyg->yy_buffer_stack = (struct yy_buffer_state**)cmExpr_yyalloc
+								(num_to_alloc * sizeof(struct yy_buffer_state*)
+								, yyscanner);
+		if ( ! yyg->yy_buffer_stack )
+			YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yyensure_buffer_stack()" );
+
+		memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
+
+		yyg->yy_buffer_stack_max = num_to_alloc;
+		yyg->yy_buffer_stack_top = 0;
+		return;
+	}
+
+	if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
+
+		/* Increase the buffer to prepare for a possible push. */
+		yy_size_t grow_size = 8 /* arbitrary grow size */;
+
+		num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
+		yyg->yy_buffer_stack = (struct yy_buffer_state**)cmExpr_yyrealloc
+								(yyg->yy_buffer_stack,
+								num_to_alloc * sizeof(struct yy_buffer_state*)
+								, yyscanner);
+		if ( ! yyg->yy_buffer_stack )
+			YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yyensure_buffer_stack()" );
+
+		/* zero only the new slots.*/
+		memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
+		yyg->yy_buffer_stack_max = num_to_alloc;
+	}
 }
 
 /** Setup the input buffer state to scan directly from a user-specified character buffer.
@@ -1519,110 +1592,112 @@ static void cmExpr_yyensure_buffer_stack (yyscan_t yyscanner)
  */
 YY_BUFFER_STATE cmExpr_yy_scan_buffer  (char * base, yy_size_t  size , yyscan_t yyscanner)
 {
-  YY_BUFFER_STATE b;
-
-  if ( size < 2 ||
-       base[size-2] != YY_END_OF_BUFFER_CHAR ||
-       base[size-1] != YY_END_OF_BUFFER_CHAR )
-    /* They forgot to leave room for the EOB's. */
-    return 0;
-
-  b = (YY_BUFFER_STATE) cmExpr_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
-  if ( ! b )
-    YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yy_scan_buffer()" );
-
-  b->yy_buf_size = size - 2;  /* "- 2" to take care of EOB's */
-  b->yy_buf_pos = b->yy_ch_buf = base;
-  b->yy_is_our_buffer = 0;
-  b->yy_input_file = 0;
-  b->yy_n_chars = b->yy_buf_size;
-  b->yy_is_interactive = 0;
-  b->yy_at_bol = 1;
-  b->yy_fill_buffer = 0;
-  b->yy_buffer_status = YY_BUFFER_NEW;
-
-  cmExpr_yy_switch_to_buffer(b ,yyscanner );
-
-  return b;
+	YY_BUFFER_STATE b;
+
+	if ( size < 2 ||
+	     base[size-2] != YY_END_OF_BUFFER_CHAR ||
+	     base[size-1] != YY_END_OF_BUFFER_CHAR )
+		/* They forgot to leave room for the EOB's. */
+		return NULL;
+
+	b = (YY_BUFFER_STATE) cmExpr_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+	if ( ! b )
+		YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yy_scan_buffer()" );
+
+	b->yy_buf_size = size - 2;	/* "- 2" to take care of EOB's */
+	b->yy_buf_pos = b->yy_ch_buf = base;
+	b->yy_is_our_buffer = 0;
+	b->yy_input_file = NULL;
+	b->yy_n_chars = b->yy_buf_size;
+	b->yy_is_interactive = 0;
+	b->yy_at_bol = 1;
+	b->yy_fill_buffer = 0;
+	b->yy_buffer_status = YY_BUFFER_NEW;
+
+	cmExpr_yy_switch_to_buffer(b ,yyscanner );
+
+	return b;
 }
 
 /** Setup the input buffer state to scan a string. The next call to cmExpr_yylex() will
- * scan from a @e copy of @a yy_str.
- * @param yy_str a NUL-terminated string to scan
+ * scan from a @e copy of @a str.
+ * @param yystr a NUL-terminated string to scan
  * @param yyscanner The scanner object.
  * @return the newly allocated buffer state object.
  * @note If you want to scan bytes that may contain NUL values, then use
  *       cmExpr_yy_scan_bytes() instead.
  */
-YY_BUFFER_STATE cmExpr_yy_scan_string (yyconst char * yy_str , yyscan_t yyscanner)
+YY_BUFFER_STATE cmExpr_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner)
 {
 
-  return cmExpr_yy_scan_bytes(yy_str,strlen(yy_str) ,yyscanner);
+	return cmExpr_yy_scan_bytes(yystr,(int) strlen(yystr) ,yyscanner);
 }
 
 /** Setup the input buffer state to scan the given bytes. The next call to cmExpr_yylex() will
  * scan from a @e copy of @a bytes.
- * @param bytes the byte buffer to scan
- * @param len the number of bytes in the buffer pointed to by @a bytes.
+ * @param yybytes the byte buffer to scan
+ * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
  * @param yyscanner The scanner object.
  * @return the newly allocated buffer state object.
  */
-YY_BUFFER_STATE cmExpr_yy_scan_bytes  (yyconst char * bytes, int  len , yyscan_t yyscanner)
+YY_BUFFER_STATE cmExpr_yy_scan_bytes  (yyconst char * yybytes, int  _yybytes_len , yyscan_t yyscanner)
 {
-  YY_BUFFER_STATE b;
-  char *buf;
-  yy_size_t n;
-  int i;
+	YY_BUFFER_STATE b;
+	char *buf;
+	yy_size_t n;
+	yy_size_t i;
 
-  /* Get memory for full buffer, including space for trailing EOB's. */
-  n = len + 2;
-  buf = (char *) cmExpr_yyalloc(n ,yyscanner );
-  if ( ! buf )
-    YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yy_scan_bytes()" );
+	/* Get memory for full buffer, including space for trailing EOB's. */
+	n = (yy_size_t) _yybytes_len + 2;
+	buf = (char *) cmExpr_yyalloc(n ,yyscanner );
+	if ( ! buf )
+		YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yy_scan_bytes()" );
 
-  for ( i = 0; i < len; ++i )
-    buf[i] = bytes[i];
+	for ( i = 0; i < (size_t)_yybytes_len; ++i )
+		buf[i] = yybytes[i];
 
-  buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR;
+	buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
 
-  b = cmExpr_yy_scan_buffer(buf,n ,yyscanner);
-  if ( ! b )
-    YY_FATAL_ERROR( "bad buffer in cmExpr_yy_scan_bytes()" );
+	b = cmExpr_yy_scan_buffer(buf,n ,yyscanner);
+	if ( ! b )
+		YY_FATAL_ERROR( "bad buffer in cmExpr_yy_scan_bytes()" );
 
-  /* It's okay to grow etc. this buffer, and we should throw it
-   * away when we're done.
-   */
-  b->yy_is_our_buffer = 1;
+	/* It's okay to grow etc. this buffer, and we should throw it
+	 * away when we're done.
+	 */
+	b->yy_is_our_buffer = 1;
 
-  return b;
+	return b;
 }
 
 #ifndef YY_EXIT_FAILURE
 #define YY_EXIT_FAILURE 2
 #endif
 
-static void yy_fatal_error (yyconst char* msg , yyscan_t)
+static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
 {
-      (void) fprintf( stderr, "%s\n", msg );
-  exit( YY_EXIT_FAILURE );
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+	(void) fprintf( stderr, "%s\n", msg );
+	exit( YY_EXIT_FAILURE );
 }
 
 /* Redefine yyless() so it works in section 3 code. */
 
 #undef yyless
 #define yyless(n) \
-  do \
-    { \
-    /* Undo effects of setting up yytext. */ \
+	do \
+		{ \
+		/* Undo effects of setting up yytext. */ \
         int yyless_macro_arg = (n); \
         YY_LESS_LINENO(yyless_macro_arg);\
-    yytext[yyleng] = yyg->yy_hold_char; \
-    yyg->yy_c_buf_p = yytext + yyless_macro_arg; \
-    yyg->yy_hold_char = *yyg->yy_c_buf_p; \
-    *yyg->yy_c_buf_p = '\0'; \
-    yyleng = yyless_macro_arg; \
-    } \
-  while ( 0 )
+		yytext[yyleng] = yyg->yy_hold_char; \
+		yyg->yy_c_buf_p = yytext + yyless_macro_arg; \
+		yyg->yy_hold_char = *yyg->yy_c_buf_p; \
+		*yyg->yy_c_buf_p = '\0'; \
+		yyleng = yyless_macro_arg; \
+		} \
+	while ( 0 )
 
 /* Accessor  methods (get/set functions) to struct members. */
 
@@ -1709,51 +1784,51 @@ void cmExpr_yyset_extra (YY_EXTRA_TYPE  user_defined , yyscan_t yyscanner)
 }
 
 /** Set the current line number.
- * @param line_number The line number to set.
+ * @param _line_number line number
  * @param yyscanner The scanner object.
  */
-void cmExpr_yyset_lineno (int  line_number , yyscan_t yyscanner)
+void cmExpr_yyset_lineno (int  _line_number , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
         /* lineno is only valid if an input buffer exists. */
         if (! YY_CURRENT_BUFFER )
-           yy_fatal_error( "cmExpr_yyset_lineno called with no buffer" , yyscanner);
+           YY_FATAL_ERROR( "cmExpr_yyset_lineno called with no buffer" );
 
-    yylineno = line_number;
+    yylineno = _line_number;
 }
 
 /** Set the current column.
- * @param column_no The column number to set.
+ * @param _column_no column number
  * @param yyscanner The scanner object.
  */
-void cmExpr_yyset_column (int  column_no , yyscan_t yyscanner)
+void cmExpr_yyset_column (int  _column_no , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
         /* column is only valid if an input buffer exists. */
         if (! YY_CURRENT_BUFFER )
-           yy_fatal_error( "cmExpr_yyset_column called with no buffer" , yyscanner);
+           YY_FATAL_ERROR( "cmExpr_yyset_column called with no buffer" );
 
-    yycolumn = column_no;
+    yycolumn = _column_no;
 }
 
 /** Set the input stream. This does not discard the current
  * input buffer.
- * @param in_str A readable stream.
+ * @param _in_str A readable stream.
  * @param yyscanner The scanner object.
  * @see cmExpr_yy_switch_to_buffer
  */
-void cmExpr_yyset_in (FILE *  in_str , yyscan_t yyscanner)
+void cmExpr_yyset_in (FILE *  _in_str , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-    yyin = in_str ;
+    yyin = _in_str ;
 }
 
-void cmExpr_yyset_out (FILE *  out_str , yyscan_t yyscanner)
+void cmExpr_yyset_out (FILE *  _out_str , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-    yyout = out_str ;
+    yyout = _out_str ;
 }
 
 int cmExpr_yyget_debug  (yyscan_t yyscanner)
@@ -1762,45 +1837,14 @@ int cmExpr_yyget_debug  (yyscan_t yyscanner)
     return yy_flex_debug;
 }
 
-void cmExpr_yyset_debug (int  bdebug , yyscan_t yyscanner)
+void cmExpr_yyset_debug (int  _bdebug , yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-    yy_flex_debug = bdebug ;
+    yy_flex_debug = _bdebug ;
 }
 
 /* Accessor methods for yylval and yylloc */
 
-static int yy_init_globals (yyscan_t yyscanner)
-{
-    struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-    /* Initialization is the same as for the non-reentrant scanner.
-       This function is called once per scanner lifetime. */
-
-    yyg->yy_buffer_stack = 0;
-    yyg->yy_buffer_stack_top = 0;
-    yyg->yy_buffer_stack_max = 0;
-    yyg->yy_c_buf_p = (char *) 0;
-    yyg->yy_init = 1;
-    yyg->yy_start = 0;
-    yyg->yy_start_stack_ptr = 0;
-    yyg->yy_start_stack_depth = 0;
-    yyg->yy_start_stack = (int *) 0;
-
-/* Defined in main.c */
-#ifdef YY_STDINIT
-    yyin = stdin;
-    yyout = stdout;
-#else
-    yyin = (FILE *) 0;
-    yyout = (FILE *) 0;
-#endif
-
-    /* For future reference: Set errno on error, since we are called by
-     * cmExpr_yylex_init()
-     */
-    return 0;
-}
-
 /* User-visible API */
 
 /* cmExpr_yylex_init is special because it creates the scanner itself, so it is
@@ -1823,33 +1867,108 @@ int cmExpr_yylex_init(yyscan_t* ptr_yy_globals)
         return 1;
     }
 
-    memset(*ptr_yy_globals,0,sizeof(struct yyguts_t));
+    /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */
+    memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
+
+    return yy_init_globals ( *ptr_yy_globals );
+}
+
+/* cmExpr_yylex_init_extra has the same functionality as cmExpr_yylex_init, but follows the
+ * convention of taking the scanner as the last argument. Note however, that
+ * this is a *pointer* to a scanner, as it will be allocated by this call (and
+ * is the reason, too, why this function also must handle its own declaration).
+ * The user defined value in the first argument will be available to cmExpr_yyalloc in
+ * the yyextra field.
+ */
+
+int cmExpr_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals )
+
+{
+    struct yyguts_t dummy_yyguts;
+
+    cmExpr_yyset_extra (yy_user_defined, &dummy_yyguts);
+
+    if (ptr_yy_globals == NULL){
+        errno = EINVAL;
+        return 1;
+    }
+
+    *ptr_yy_globals = (yyscan_t) cmExpr_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
+
+    if (*ptr_yy_globals == NULL){
+        errno = ENOMEM;
+        return 1;
+    }
+
+    /* By setting to 0xAA, we expose bugs in
+    yy_init_globals. Leave at 0x00 for releases. */
+    memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
+
+    cmExpr_yyset_extra (yy_user_defined, *ptr_yy_globals);
 
     return yy_init_globals ( *ptr_yy_globals );
 }
 
+static int yy_init_globals (yyscan_t yyscanner)
+{
+    struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+    /* Initialization is the same as for the non-reentrant scanner.
+     * This function is called from cmExpr_yylex_destroy(), so don't allocate here.
+     */
+
+    yyg->yy_buffer_stack = NULL;
+    yyg->yy_buffer_stack_top = 0;
+    yyg->yy_buffer_stack_max = 0;
+    yyg->yy_c_buf_p = NULL;
+    yyg->yy_init = 0;
+    yyg->yy_start = 0;
+
+    yyg->yy_start_stack_ptr = 0;
+    yyg->yy_start_stack_depth = 0;
+    yyg->yy_start_stack =  NULL;
+
+/* Defined in main.c */
+#ifdef YY_STDINIT
+    yyin = stdin;
+    yyout = stdout;
+#else
+    yyin = NULL;
+    yyout = NULL;
+#endif
+
+    /* For future reference: Set errno on error, since we are called by
+     * cmExpr_yylex_init()
+     */
+    return 0;
+}
+
 /* cmExpr_yylex_destroy is for both reentrant and non-reentrant scanners. */
 int cmExpr_yylex_destroy  (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
     /* Pop the buffer stack, destroying each element. */
-  while(YY_CURRENT_BUFFER){
-    cmExpr_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
-    YY_CURRENT_BUFFER_LVALUE = NULL;
-    cmExpr_yypop_buffer_state(yyscanner);
-  }
+	while(YY_CURRENT_BUFFER){
+		cmExpr_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
+		YY_CURRENT_BUFFER_LVALUE = NULL;
+		cmExpr_yypop_buffer_state(yyscanner);
+	}
 
-  /* Destroy the stack itself. */
-  cmExpr_yyfree(yyg->yy_buffer_stack ,yyscanner);
-  yyg->yy_buffer_stack = NULL;
+	/* Destroy the stack itself. */
+	cmExpr_yyfree(yyg->yy_buffer_stack ,yyscanner);
+	yyg->yy_buffer_stack = NULL;
 
     /* Destroy the start condition stack. */
         cmExpr_yyfree(yyg->yy_start_stack ,yyscanner );
         yyg->yy_start_stack = NULL;
 
+    /* Reset the globals. This is important in a non-reentrant scanner so the next time
+     * cmExpr_yylex() is called, initialization will occur. */
+    yy_init_globals( yyscanner);
+
     /* Destroy the main struct (reentrant only). */
     cmExpr_yyfree ( yyscanner , yyscanner );
+    yyscanner = NULL;
     return 0;
 }
 
@@ -1860,62 +1979,55 @@ int cmExpr_yylex_destroy  (yyscan_t yyscanner)
 #ifndef yytext_ptr
 static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner)
 {
-  int i;
-    struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  for ( i = 0; i < n; ++i )
-    s1[i] = s2[i];
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+
+	int i;
+	for ( i = 0; i < n; ++i )
+		s1[i] = s2[i];
 }
 #endif
 
 #ifdef YY_NEED_STRLEN
 static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
 {
-  int n;
-    struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
-  for ( n = 0; s[n]; ++n )
-    ;
+	int n;
+	for ( n = 0; s[n]; ++n )
+		;
 
-  return n;
+	return n;
 }
 #endif
 
-void *cmExpr_yyalloc (yy_size_t  size , yyscan_t)
+void *cmExpr_yyalloc (yy_size_t  size , yyscan_t yyscanner)
 {
-  return (void *) malloc( size );
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+	return malloc(size);
 }
 
-void *cmExpr_yyrealloc  (void * ptr, yy_size_t  size , yyscan_t)
+void *cmExpr_yyrealloc  (void * ptr, yy_size_t  size , yyscan_t yyscanner)
 {
-  /* The cast to (char *) in the following accommodates both
-   * implementations that use char* generic pointers, and those
-   * that use void* generic pointers.  It works with the latter
-   * because both ANSI C and C++ allow castless assignment from
-   * any pointer type to void*, and deal with argument conversions
-   * as though doing an assignment.
-   */
-  return (void *) realloc( (char *) ptr, size );
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+
+	/* The cast to (char *) in the following accommodates both
+	 * implementations that use char* generic pointers, and those
+	 * that use void* generic pointers.  It works with the latter
+	 * because both ANSI C and C++ allow castless assignment from
+	 * any pointer type to void*, and deal with argument conversions
+	 * as though doing an assignment.
+	 */
+	return realloc(ptr, size);
 }
 
-void cmExpr_yyfree (void * ptr , yyscan_t)
+void cmExpr_yyfree (void * ptr , yyscan_t yyscanner)
 {
-  free( (char *) ptr );  /* see cmExpr_yyrealloc() for (char *) cast */
+	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
+	(void)yyg;
+	free( (char *) ptr );	/* see cmExpr_yyrealloc() for (char *) cast */
 }
 
 #define YYTABLES_NAME "yytables"
 
-#undef YY_NEW_FILE
-#undef YY_FLUSH_BUFFER
-#undef yy_set_bol
-#undef yy_new_buffer
-#undef yy_set_interactive
-#undef yytext_ptr
-#undef YY_DO_BEFORE_ACTION
-
-#ifdef YY_DECL_IS_OURS
-#undef YY_DECL_IS_OURS
-#undef YY_DECL
-#endif
-#line 104 "/home/andy/vtk/CMake/Source/cmExprLexer.in.l"
-
-
-
+#line 57 "cmExprLexer.in.l"
diff --git a/Source/cmExprLexer.h b/Source/cmExprLexer.h
index efe6440..835a7a3 100644
--- a/Source/cmExprLexer.h
+++ b/Source/cmExprLexer.h
@@ -1,21 +1,20 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
 #ifndef cmExpr_yyHEADER_H
 #define cmExpr_yyHEADER_H 1
 #define cmExpr_yyIN_HEADER 1
 
+#line 6 "cmExprLexer.h"
 
+#line 8 "cmExprLexer.h"
 
-
-
+#define FLEXINT_H 1
 #define  YY_INT_ALIGNED short int
 
 /* A lexical scanner generated by flex */
 
 #define FLEX_SCANNER
 #define YY_FLEX_MAJOR_VERSION 2
-#define YY_FLEX_MINOR_VERSION 5
-#define YY_FLEX_SUBMINOR_VERSION 31
+#define YY_FLEX_MINOR_VERSION 6
+#define YY_FLEX_SUBMINOR_VERSION 1
 #if YY_FLEX_SUBMINOR_VERSION > 0
 #define FLEX_BETA
 #endif
@@ -37,7 +36,15 @@
 
 /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
 
-#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L
+#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+
+/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
+ * if you want the limit (max/min) macros for int types.
+ */
+#ifndef __STDC_LIMIT_MACROS
+#define __STDC_LIMIT_MACROS 1
+#endif
+
 #include <inttypes.h>
 typedef int8_t flex_int8_t;
 typedef uint8_t flex_uint8_t;
@@ -52,7 +59,6 @@ typedef int flex_int32_t;
 typedef unsigned char flex_uint8_t;
 typedef unsigned short int flex_uint16_t;
 typedef unsigned int flex_uint32_t;
-#endif /* ! C99 */
 
 /* Limits of integral types. */
 #ifndef INT8_MIN
@@ -83,26 +89,17 @@ typedef unsigned int flex_uint32_t;
 #define UINT32_MAX             (4294967295U)
 #endif
 
-#endif /* ! FLEXINT_H */
-
-#ifdef __cplusplus
-
-/* The "const" storage-class-modifier is valid. */
-#define YY_USE_CONST
-
-#else  /* ! __cplusplus */
-
-#if __STDC__
-
-#define YY_USE_CONST
+#endif /* ! C99 */
 
-#endif  /* __STDC__ */
-#endif  /* ! __cplusplus */
+#endif /* ! FLEXINT_H */
 
-#ifdef YY_USE_CONST
+/* TODO: this is always defined, so inline it */
 #define yyconst const
+
+#if defined(__GNUC__) && __GNUC__ >= 3
+#define yynoreturn __attribute__((__noreturn__))
 #else
-#define yyconst
+#define yynoreturn
 #endif
 
 /* An opaque pointer. */
@@ -122,91 +119,91 @@ typedef void* yyscan_t;
 #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column)
 #define yy_flex_debug yyg->yy_flex_debug_r
 
-int cmExpr_yylex_init (yyscan_t* scanner);
+/* Size of default input buffer. */
+#ifndef YY_BUF_SIZE
+#ifdef __ia64__
+/* On IA-64, the buffer size is 16k, not 8k.
+ * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case.
+ * Ditto for the __ia64__ case accordingly.
+ */
+#define YY_BUF_SIZE 32768
+#else
+#define YY_BUF_SIZE 16384
+#endif /* __ia64__ */
+#endif
 
 #ifndef YY_TYPEDEF_YY_BUFFER_STATE
 #define YY_TYPEDEF_YY_BUFFER_STATE
 typedef struct yy_buffer_state *YY_BUFFER_STATE;
 #endif
 
-/* The following is because we cannot portably get our hands on size_t
- * (without autoconf's help, which isn't available because we want
- * flex-generated scanners to compile on their own).
- */
-
 #ifndef YY_TYPEDEF_YY_SIZE_T
 #define YY_TYPEDEF_YY_SIZE_T
-typedef unsigned int yy_size_t;
+typedef size_t yy_size_t;
 #endif
 
 #ifndef YY_STRUCT_YY_BUFFER_STATE
 #define YY_STRUCT_YY_BUFFER_STATE
 struct yy_buffer_state
-  {
-  FILE *yy_input_file;
-
-  char *yy_ch_buf;    /* input buffer */
-  char *yy_buf_pos;    /* current position in input buffer */
-
-  /* Size of input buffer in bytes, not including room for EOB
-   * characters.
-   */
-  yy_size_t yy_buf_size;
-
-  /* Number of characters read into yy_ch_buf, not including EOB
-   * characters.
-   */
-  int yy_n_chars;
-
-  /* Whether we "own" the buffer - i.e., we know we created it,
-   * and can realloc() it to grow it, and should free() it to
-   * delete it.
-   */
-  int yy_is_our_buffer;
-
-  /* Whether this is an "interactive" input source; if so, and
-   * if we're using stdio for input, then we want to use getc()
-   * instead of fread(), to make sure we stop fetching input after
-   * each newline.
-   */
-  int yy_is_interactive;
-
-  /* Whether we're considered to be at the beginning of a line.
-   * If so, '^' rules will be active on the next match, otherwise
-   * not.
-   */
-  int yy_at_bol;
+	{
+	FILE *yy_input_file;
+
+	char *yy_ch_buf;		/* input buffer */
+	char *yy_buf_pos;		/* current position in input buffer */
+
+	/* Size of input buffer in bytes, not including room for EOB
+	 * characters.
+	 */
+	int yy_buf_size;
+
+	/* Number of characters read into yy_ch_buf, not including EOB
+	 * characters.
+	 */
+	int yy_n_chars;
+
+	/* Whether we "own" the buffer - i.e., we know we created it,
+	 * and can realloc() it to grow it, and should free() it to
+	 * delete it.
+	 */
+	int yy_is_our_buffer;
+
+	/* Whether this is an "interactive" input source; if so, and
+	 * if we're using stdio for input, then we want to use getc()
+	 * instead of fread(), to make sure we stop fetching input after
+	 * each newline.
+	 */
+	int yy_is_interactive;
+
+	/* Whether we're considered to be at the beginning of a line.
+	 * If so, '^' rules will be active on the next match, otherwise
+	 * not.
+	 */
+	int yy_at_bol;
 
     int yy_bs_lineno; /**< The line count. */
     int yy_bs_column; /**< The column count. */
 
-  /* Whether to try to fill the input buffer when we reach the
-   * end of it.
-   */
-  int yy_fill_buffer;
+	/* Whether to try to fill the input buffer when we reach the
+	 * end of it.
+	 */
+	int yy_fill_buffer;
 
-  int yy_buffer_status;
+	int yy_buffer_status;
 
-  };
+	};
 #endif /* !YY_STRUCT_YY_BUFFER_STATE */
 
 void cmExpr_yyrestart (FILE *input_file ,yyscan_t yyscanner );
-void cmExpr_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,
-                                 yyscan_t yyscanner );
-YY_BUFFER_STATE cmExpr_yy_create_buffer (FILE *file,int size ,
-                                         yyscan_t yyscanner );
+void cmExpr_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
+YY_BUFFER_STATE cmExpr_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner );
 void cmExpr_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
 void cmExpr_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmExpr_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,
-                                 yyscan_t yyscanner );
+void cmExpr_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
 void cmExpr_yypop_buffer_state (yyscan_t yyscanner );
 
-YY_BUFFER_STATE cmExpr_yy_scan_buffer (char *base,yy_size_t size ,
-                                       yyscan_t yyscanner );
-YY_BUFFER_STATE cmExpr_yy_scan_string (yyconst char *yy_str ,
-                                       yyscan_t yyscanner );
-YY_BUFFER_STATE cmExpr_yy_scan_bytes (yyconst char *bytes,int len ,
-                                      yyscan_t yyscanner );
+YY_BUFFER_STATE cmExpr_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
+YY_BUFFER_STATE cmExpr_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
+YY_BUFFER_STATE cmExpr_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
 
 void *cmExpr_yyalloc (yy_size_t ,yyscan_t yyscanner );
 void *cmExpr_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
@@ -214,7 +211,7 @@ void cmExpr_yyfree (void * ,yyscan_t yyscanner );
 
 /* Begin user sect3 */
 
-#define cmExpr_yywrap(n) 1
+#define cmExpr_yywrap(yyscanner) (/*CONSTCOND*/1)
 #define YY_SKIP_YYWRAP
 
 #define yytext_ptr yytext_r
@@ -228,6 +225,10 @@ void cmExpr_yyfree (void * ,yyscan_t yyscanner );
 #define YY_EXTRA_TYPE void *
 #endif
 
+int cmExpr_yylex_init (yyscan_t* scanner);
+
+int cmExpr_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
+
 /* Accessor methods to globals.
    These are made visible to non-reentrant scanners for convenience. */
 
@@ -243,19 +244,23 @@ void cmExpr_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
 
 FILE *cmExpr_yyget_in (yyscan_t yyscanner );
 
-void cmExpr_yyset_in  (FILE * in_str ,yyscan_t yyscanner );
+void cmExpr_yyset_in  (FILE * _in_str ,yyscan_t yyscanner );
 
 FILE *cmExpr_yyget_out (yyscan_t yyscanner );
 
-void cmExpr_yyset_out  (FILE * out_str ,yyscan_t yyscanner );
+void cmExpr_yyset_out  (FILE * _out_str ,yyscan_t yyscanner );
 
-int cmExpr_yyget_leng (yyscan_t yyscanner );
+			int cmExpr_yyget_leng (yyscan_t yyscanner );
 
 char *cmExpr_yyget_text (yyscan_t yyscanner );
 
 int cmExpr_yyget_lineno (yyscan_t yyscanner );
 
-void cmExpr_yyset_lineno (int line_number ,yyscan_t yyscanner );
+void cmExpr_yyset_lineno (int _line_number ,yyscan_t yyscanner );
+
+int cmExpr_yyget_column  (yyscan_t yyscanner );
+
+void cmExpr_yyset_column (int _column_no ,yyscan_t yyscanner );
 
 /* Macros after this point can all be overridden by user definitions in
  * section 1.
@@ -283,7 +288,12 @@ static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
 
 /* Amount of stuff to slurp up with each read. */
 #ifndef YY_READ_BUF_SIZE
+#ifdef __ia64__
+/* On IA-64, the buffer size is 16k, not 8k */
+#define YY_READ_BUF_SIZE 16384
+#else
 #define YY_READ_BUF_SIZE 8192
+#endif /* __ia64__ */
 #endif
 
 /* Number of entries by which start-condition stack grows. */
@@ -302,15 +312,13 @@ extern int cmExpr_yylex (yyscan_t yyscanner);
 #define YY_DECL int cmExpr_yylex (yyscan_t yyscanner)
 #endif /* !YY_DECL */
 
-/* yy_get_previous_state - get the state just before the EOB char was
-   reached */
+/* yy_get_previous_state - get the state just before the EOB char was reached */
 
 #undef YY_NEW_FILE
 #undef YY_FLUSH_BUFFER
 #undef yy_set_bol
 #undef yy_new_buffer
 #undef yy_set_interactive
-#undef yytext_ptr
 #undef YY_DO_BEFORE_ACTION
 
 #ifdef YY_DECL_IS_OURS
@@ -318,8 +326,9 @@ extern int cmExpr_yylex (yyscan_t yyscanner);
 #undef YY_DECL
 #endif
 
+#line 57 "cmExprLexer.in.l"
 
 
-
+#line 333 "cmExprLexer.h"
 #undef cmExpr_yyIN_HEADER
 #endif /* cmExpr_yyHEADER_H */
diff --git a/Source/cmExprLexer.in.l b/Source/cmExprLexer.in.l
index e32abd9..25ddba4 100644
--- a/Source/cmExprLexer.in.l
+++ b/Source/cmExprLexer.in.l
@@ -3,29 +3,21 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 /*
 
-This file must be translated to C and modified to build everywhere.
+This file must be translated to C++ and modified to build everywhere.
 
-Run flex like this:
+Run flex >= 2.6 like this:
 
-  flex --prefix=cmExpr_yy --header-file=cmExprLexer.h -ocmExprLexer.cxx cmExprLexer.in.l
+  flex --nounistd -DFLEXINT_H --prefix=cmExpr_yy --header-file=cmExprLexer.h -ocmExprLexer.cxx cmExprLexer.in.l
 
 Modify cmExprLexer.cxx:
-  - remove TABs
-  - remove use of the 'register' storage class specifier
-  - remove "yyscanner" argument from these methods:
-      yy_fatal_error, cmExpr_yyalloc, cmExpr_yyrealloc, cmExpr_yyfree
-  - remove all YY_BREAK lines occurring right after return statements
-  - change while ( 1 ) to for(;;)
-
-Modify cmExprLexer.h:
-  - remove TABs
-  - remove the yy_init_globals function
-  - remove the block that includes unistd.h
-  - remove #line directives (avoids bogus warning on old Sun)
+  - remove trailing whitespace: sed -i 's/\s*$//' cmExprLexer.h cmExprLexer.cxx
+  - remove blank lines at end of file
+  - #include "cmStandardLexer.h" at the top
+  - add cast in yy_scan_bytes for loop condition of _yybytes_len to size_t
 
 */
 
-#include "cmStandardLexer.h"
+/* IWYU pragma: no_forward_declare yyguts_t */
 
 #include "cmExprParserHelper.h"
 
diff --git a/Source/cmExprParser.cxx b/Source/cmExprParser.cxx
index 077106f..d11d0b6 100644
--- a/Source/cmExprParser.cxx
+++ b/Source/cmExprParser.cxx
@@ -1,12 +1,13 @@
-/* A Bison parser, made by GNU Bison 1.875d.  */
+/* A Bison parser, made by GNU Bison 3.0.4.  */
 
-/* Skeleton parser for Yacc-like parsing with Bison, Copyright (C) 1984,
-   1989, 1990, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
+/* Bison implementation for Yacc-like parsers in C
 
-   This program is free software; you can redistribute it and/or modify
+   Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc.
+
+   This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2, or (at your option)
-   any later version.
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -14,17 +15,23 @@
    GNU General Public License for more details.
 
    You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 59 Temple Place - Suite 330,
-   Boston, MA 02111-1307, USA.  */
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+/* As a special exception, you may create a larger work that contains
+   part or all of the Bison parser skeleton and distribute that work
+   under terms of your choice, so long as that work isn't itself a
+   parser generator using the skeleton or a modified version thereof
+   as a parser skeleton.  Alternatively, if you modify or redistribute
+   the parser skeleton itself, you may (at your option) remove this
+   special exception, which will cause the skeleton and the resulting
+   Bison output files to be licensed under the GNU General Public
+   License without this special exception.
 
-/* As a special exception, when this file is copied by Bison into a
-   Bison output file, you may use that output file without restriction.
-   This special exception was added by the Free Software Foundation
-   in version 1.24 of Bison.  */
+   This special exception was added by the Free Software Foundation in
+   version 2.2 of Bison.  */
 
-/* Written by Richard Stallman by simplifying the original so called
-   ``semantic'' parser.  */
+/* C LALR(1) parser skeleton written by Richard Stallman, by
+   simplifying the original so-called "semantic" parser.  */
 
 /* All symbols defined below should begin with yy or YY, to avoid
    infringing on user name space.  This should be done even for local
@@ -33,76 +40,35 @@
    define necessary library symbols; they are noted "INFRINGES ON
    USER NAME SPACE" below.  */
 
-/* turn off some warning as this is generated code */
-#if defined(_MSC_VER)
-#  pragma warning ( disable : 4702 ) /* unreachable code */
-#endif
-
 /* Identify Bison output.  */
 #define YYBISON 1
 
+/* Bison version.  */
+#define YYBISON_VERSION "3.0.4"
+
 /* Skeleton name.  */
 #define YYSKELETON_NAME "yacc.c"
 
 /* Pure parsers.  */
 #define YYPURE 1
 
-/* Using locations.  */
-#define YYLSP_NEEDED 0
-
-/* If NAME_PREFIX is specified substitute the variables and functions
-   names.  */
-#define yyparse cmExpr_yyparse
-#define yylex   cmExpr_yylex
-#define yyerror cmExpr_yyerror
-#define yylval  cmExpr_yylval
-#define yychar  cmExpr_yychar
-#define yydebug cmExpr_yydebug
-#define yynerrs cmExpr_yynerrs
-
+/* Push parsers.  */
+#define YYPUSH 0
 
-/* Tokens.  */
-#ifndef YYTOKENTYPE
-# define YYTOKENTYPE
-   /* Put the tokens into the symbol table, so that GDB and other debuggers
-      know about them.  */
-   enum yytokentype {
-     exp_PLUS = 258,
-     exp_MINUS = 259,
-     exp_TIMES = 260,
-     exp_DIVIDE = 261,
-     exp_MOD = 262,
-     exp_SHIFTLEFT = 263,
-     exp_SHIFTRIGHT = 264,
-     exp_OPENPARENT = 265,
-     exp_CLOSEPARENT = 266,
-     exp_OR = 267,
-     exp_AND = 268,
-     exp_XOR = 269,
-     exp_NOT = 270,
-     exp_NUMBER = 271
-   };
-#endif
-#define exp_PLUS 258
-#define exp_MINUS 259
-#define exp_TIMES 260
-#define exp_DIVIDE 261
-#define exp_MOD 262
-#define exp_SHIFTLEFT 263
-#define exp_SHIFTRIGHT 264
-#define exp_OPENPARENT 265
-#define exp_CLOSEPARENT 266
-#define exp_OR 267
-#define exp_AND 268
-#define exp_XOR 269
-#define exp_NOT 270
-#define exp_NUMBER 271
+/* Pull parsers.  */
+#define YYPULL 1
 
 
+/* Substitute the variable and function names.  */
+#define yyparse         cmExpr_yyparse
+#define yylex           cmExpr_yylex
+#define yyerror         cmExpr_yyerror
+#define yydebug         cmExpr_yydebug
+#define yynerrs         cmExpr_yynerrs
 
 
 /* Copy the first part of user declarations.  */
-
+#line 1 "cmExprParser.y" /* yacc.c:339  */
 
 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
    file Copyright.txt or https://cmake.org/licensing for details.  */
@@ -112,24 +78,15 @@ This file must be translated to C and modified to build everywhere.
 
 Run bison like this:
 
-  bison --yacc --name-prefix=cmExpr_yy --defines=cmExprParserTokens.h
-  -ocmExprParser.cxx cmExprParser.y
+  bison --yacc --name-prefix=cmExpr_yy --defines=cmExprParserTokens.h -ocmExprParser.cxx cmExprParser.y
 
 Modify cmExprParser.cxx:
-  - remove TABs
-  - add __HP_aCC to the #if test for yyerrorlab warning suppression
+  - "#if 0" out yyerrorlab block in range ["goto yyerrlab1", "yyerrlab1:"]
 
 */
 
-/* Configure the parser to use a lexer object.  */
-#define YYPARSE_PARAM yyscanner
-#define YYLEX_PARAM yyscanner
-#define YYERROR_VERBOSE 1
-#define cmExpr_yyerror(x) \
-        cmExprError(yyscanner, x)
-#define yyGetParser (cmExpr_yyget_extra(yyscanner))
-
 /*-------------------------------------------------------------------------*/
+#define YYDEBUG 1
 #include "cmExprParserHelper.h" /* Interface to parser object.  */
 #include "cmExprLexer.h"  /* Interface to lexer object.  */
 #include "cmExprParserTokens.h" /* Need YYSTYPE for YY_DECL.  */
@@ -139,99 +96,281 @@ Modify cmExprParser.cxx:
 /* Forward declare the lexer entry point.  */
 YY_DECL;
 
-/* Internal utility functions.  */
-static void cmExprError(yyscan_t yyscanner, const char* message);
-
-#define YYDEBUG 1
-//#define YYMAXDEPTH 100000
-//#define YYINITDEPTH 10000
-
+/* Helper function to forward error callback from parser.  */
+static void cmExpr_yyerror(yyscan_t yyscanner, const char* message);
 
 /* Disable some warnings in the generated code.  */
 #ifdef _MSC_VER
 # pragma warning (disable: 4102) /* Unused goto label.  */
-# pragma warning (disable: 4065) /* Switch statement contains default but
-                                    no case. */
+# pragma warning (disable: 4065) /* Switch statement contains default but no case. */
 #endif
 
+#line 109 "cmExprParser.cxx" /* yacc.c:339  */
 
-/* Enabling traces.  */
-#ifndef YYDEBUG
-# define YYDEBUG 0
-#endif
+# ifndef YY_NULLPTR
+#  if defined __cplusplus && 201103L <= __cplusplus
+#   define YY_NULLPTR nullptr
+#  else
+#   define YY_NULLPTR 0
+#  endif
+# endif
 
 /* Enabling verbose error messages.  */
 #ifdef YYERROR_VERBOSE
 # undef YYERROR_VERBOSE
 # define YYERROR_VERBOSE 1
 #else
-# define YYERROR_VERBOSE 0
+# define YYERROR_VERBOSE 1
 #endif
 
-#if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED)
-typedef int YYSTYPE;
-# define yystype YYSTYPE /* obsolescent; will be withdrawn */
-# define YYSTYPE_IS_DECLARED 1
-# define YYSTYPE_IS_TRIVIAL 1
+/* In a future release of Bison, this section will be replaced
+   by #include "cmExprParserTokens.h".  */
+#ifndef YY_CMEXPR_YY_CMEXPRPARSERTOKENS_H_INCLUDED
+# define YY_CMEXPR_YY_CMEXPRPARSERTOKENS_H_INCLUDED
+/* Debug traces.  */
+#ifndef YYDEBUG
+# define YYDEBUG 0
+#endif
+#if YYDEBUG
+extern int cmExpr_yydebug;
 #endif
 
+/* Token type.  */
+#ifndef YYTOKENTYPE
+# define YYTOKENTYPE
+  enum yytokentype
+  {
+    exp_PLUS = 258,
+    exp_MINUS = 259,
+    exp_TIMES = 260,
+    exp_DIVIDE = 261,
+    exp_MOD = 262,
+    exp_SHIFTLEFT = 263,
+    exp_SHIFTRIGHT = 264,
+    exp_OPENPARENT = 265,
+    exp_CLOSEPARENT = 266,
+    exp_OR = 267,
+    exp_AND = 268,
+    exp_XOR = 269,
+    exp_NOT = 270,
+    exp_NUMBER = 271
+  };
+#endif
+/* Tokens.  */
+#define exp_PLUS 258
+#define exp_MINUS 259
+#define exp_TIMES 260
+#define exp_DIVIDE 261
+#define exp_MOD 262
+#define exp_SHIFTLEFT 263
+#define exp_SHIFTRIGHT 264
+#define exp_OPENPARENT 265
+#define exp_CLOSEPARENT 266
+#define exp_OR 267
+#define exp_AND 268
+#define exp_XOR 269
+#define exp_NOT 270
+#define exp_NUMBER 271
+
+/* Value type.  */
+
+
+
+int cmExpr_yyparse (yyscan_t yyscanner);
 
+#endif /* !YY_CMEXPR_YY_CMEXPRPARSERTOKENS_H_INCLUDED  */
 
 /* Copy the second part of user declarations.  */
 
+#line 186 "cmExprParser.cxx" /* yacc.c:358  */
+
+#ifdef short
+# undef short
+#endif
+
+#ifdef YYTYPE_UINT8
+typedef YYTYPE_UINT8 yytype_uint8;
+#else
+typedef unsigned char yytype_uint8;
+#endif
 
-/* Line 214 of yacc.c.  */
+#ifdef YYTYPE_INT8
+typedef YYTYPE_INT8 yytype_int8;
+#else
+typedef signed char yytype_int8;
+#endif
 
+#ifdef YYTYPE_UINT16
+typedef YYTYPE_UINT16 yytype_uint16;
+#else
+typedef unsigned short int yytype_uint16;
+#endif
 
-#if ! defined (yyoverflow) || YYERROR_VERBOSE
+#ifdef YYTYPE_INT16
+typedef YYTYPE_INT16 yytype_int16;
+#else
+typedef short int yytype_int16;
+#endif
 
-# ifndef YYFREE
-#  define YYFREE free
+#ifndef YYSIZE_T
+# ifdef __SIZE_TYPE__
+#  define YYSIZE_T __SIZE_TYPE__
+# elif defined size_t
+#  define YYSIZE_T size_t
+# elif ! defined YYSIZE_T
+#  include <stddef.h> /* INFRINGES ON USER NAME SPACE */
+#  define YYSIZE_T size_t
+# else
+#  define YYSIZE_T unsigned int
 # endif
-# ifndef YYMALLOC
-#  define YYMALLOC malloc
+#endif
+
+#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
+
+#ifndef YY_
+# if defined YYENABLE_NLS && YYENABLE_NLS
+#  if ENABLE_NLS
+#   include <libintl.h> /* INFRINGES ON USER NAME SPACE */
+#   define YY_(Msgid) dgettext ("bison-runtime", Msgid)
+#  endif
+# endif
+# ifndef YY_
+#  define YY_(Msgid) Msgid
+# endif
+#endif
+
+#ifndef YY_ATTRIBUTE
+# if (defined __GNUC__                                               \
+      && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__)))  \
+     || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C
+#  define YY_ATTRIBUTE(Spec) __attribute__(Spec)
+# else
+#  define YY_ATTRIBUTE(Spec) /* empty */
 # endif
+#endif
+
+#ifndef YY_ATTRIBUTE_PURE
+# define YY_ATTRIBUTE_PURE   YY_ATTRIBUTE ((__pure__))
+#endif
+
+#ifndef YY_ATTRIBUTE_UNUSED
+# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__))
+#endif
+
+#if !defined _Noreturn \
+     && (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112)
+# if defined _MSC_VER && 1200 <= _MSC_VER
+#  define _Noreturn __declspec (noreturn)
+# else
+#  define _Noreturn YY_ATTRIBUTE ((__noreturn__))
+# endif
+#endif
+
+/* Suppress unused-variable warnings by "using" E.  */
+#if ! defined lint || defined __GNUC__
+# define YYUSE(E) ((void) (E))
+#else
+# define YYUSE(E) /* empty */
+#endif
+
+#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__
+/* Suppress an incorrect diagnostic about yylval being uninitialized.  */
+# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
+    _Pragma ("GCC diagnostic push") \
+    _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\
+    _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
+# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
+    _Pragma ("GCC diagnostic pop")
+#else
+# define YY_INITIAL_VALUE(Value) Value
+#endif
+#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+# define YY_IGNORE_MAYBE_UNINITIALIZED_END
+#endif
+#ifndef YY_INITIAL_VALUE
+# define YY_INITIAL_VALUE(Value) /* Nothing. */
+#endif
+
+
+#if ! defined yyoverflow || YYERROR_VERBOSE
 
 /* The parser invokes alloca or malloc; define the necessary symbols.  */
 
 # ifdef YYSTACK_USE_ALLOCA
 #  if YYSTACK_USE_ALLOCA
-#   define YYSTACK_ALLOC alloca
-#  endif
-# else
-#  if defined (alloca) || defined (_ALLOCA_H)
-#   define YYSTACK_ALLOC alloca
-#  else
 #   ifdef __GNUC__
 #    define YYSTACK_ALLOC __builtin_alloca
+#   elif defined __BUILTIN_VA_ARG_INCR
+#    include <alloca.h> /* INFRINGES ON USER NAME SPACE */
+#   elif defined _AIX
+#    define YYSTACK_ALLOC __alloca
+#   elif defined _MSC_VER
+#    include <malloc.h> /* INFRINGES ON USER NAME SPACE */
+#    define alloca _alloca
+#   else
+#    define YYSTACK_ALLOC alloca
+#    if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS
+#     include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
+      /* Use EXIT_SUCCESS as a witness for stdlib.h.  */
+#     ifndef EXIT_SUCCESS
+#      define EXIT_SUCCESS 0
+#     endif
+#    endif
 #   endif
 #  endif
 # endif
 
 # ifdef YYSTACK_ALLOC
-   /* Pacify GCC's `empty if-body' warning. */
+   /* Pacify GCC's 'empty if-body' warning.  */
 #  define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)
-# else
-#  if defined (__STDC__) || defined (__cplusplus)
-#   include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
-#   define YYSIZE_T size_t
+#  ifndef YYSTACK_ALLOC_MAXIMUM
+    /* The OS might guarantee only one guard page at the bottom of the stack,
+       and a page size can be as small as 4096 bytes.  So we cannot safely
+       invoke alloca (N) if N exceeds 4096.  Use a slightly smaller number
+       to allow for a few compiler-allocated temporary stack slots.  */
+#   define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
 #  endif
+# else
 #  define YYSTACK_ALLOC YYMALLOC
 #  define YYSTACK_FREE YYFREE
+#  ifndef YYSTACK_ALLOC_MAXIMUM
+#   define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
+#  endif
+#  if (defined __cplusplus && ! defined EXIT_SUCCESS \
+       && ! ((defined YYMALLOC || defined malloc) \
+             && (defined YYFREE || defined free)))
+#   include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
+#   ifndef EXIT_SUCCESS
+#    define EXIT_SUCCESS 0
+#   endif
+#  endif
+#  ifndef YYMALLOC
+#   define YYMALLOC malloc
+#   if ! defined malloc && ! defined EXIT_SUCCESS
+void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
+#   endif
+#  endif
+#  ifndef YYFREE
+#   define YYFREE free
+#   if ! defined free && ! defined EXIT_SUCCESS
+void free (void *); /* INFRINGES ON USER NAME SPACE */
+#   endif
+#  endif
 # endif
-#endif /* ! defined (yyoverflow) || YYERROR_VERBOSE */
+#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
 
 
-#if (! defined (yyoverflow) \
-     && (! defined (__cplusplus) \
-   || (defined (YYSTYPE_IS_TRIVIAL) && YYSTYPE_IS_TRIVIAL)))
+#if (! defined yyoverflow \
+     && (! defined __cplusplus \
+         || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
 
 /* A type that is properly aligned for any stack member.  */
 union yyalloc
 {
-  short int yyss;
-  YYSTYPE yyvs;
-  };
+  yytype_int16 yyss_alloc;
+  YYSTYPE yyvs_alloc;
+};
 
 /* The size of the maximum gap between one aligned stack and the next.  */
 # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
@@ -239,74 +378,74 @@ union yyalloc
 /* The size of an array large to enough to hold all stacks, each with
    N elements.  */
 # define YYSTACK_BYTES(N) \
-     ((N) * (sizeof (short int) + sizeof (YYSTYPE))      \
+     ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
       + YYSTACK_GAP_MAXIMUM)
 
-/* Copy COUNT objects from FROM to TO.  The source and destination do
-   not overlap.  */
-# ifndef YYCOPY
-#  if defined (__GNUC__) && 1 < __GNUC__
-#   define YYCOPY(To, From, Count) \
-      __builtin_memcpy (To, From, (Count) * sizeof (*(From)))
-#  else
-#   define YYCOPY(To, From, Count)    \
-      do          \
-  {          \
-    YYSIZE_T yyi;    \
-    for (yyi = 0; yyi < (Count); yyi++)  \
-      (To)[yyi] = (From)[yyi];    \
-  }          \
-      while (0)
-#  endif
-# endif
+# define YYCOPY_NEEDED 1
 
 /* Relocate STACK from its old location to the new one.  The
    local variables YYSIZE and YYSTACKSIZE give the old and new number of
    elements in the stack, and YYPTR gives the new location of the
    stack.  Advance YYPTR to a properly aligned location for the next
    stack.  */
-# define YYSTACK_RELOCATE(Stack)          \
-    do                  \
-      {                  \
-  YYSIZE_T yynewbytes;            \
-  YYCOPY (&yyptr->Stack, Stack, yysize);        \
-  Stack = &yyptr->Stack;            \
-  yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
-  yyptr += yynewbytes / sizeof (*yyptr);        \
-      }                  \
+# define YYSTACK_RELOCATE(Stack_alloc, Stack)                           \
+    do                                                                  \
+      {                                                                 \
+        YYSIZE_T yynewbytes;                                            \
+        YYCOPY (&yyptr->Stack_alloc, Stack, yysize);                    \
+        Stack = &yyptr->Stack_alloc;                                    \
+        yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
+        yyptr += yynewbytes / sizeof (*yyptr);                          \
+      }                                                                 \
     while (0)
 
 #endif
 
-#if defined (__STDC__) || defined (__cplusplus)
-   typedef signed char yysigned_char;
-#else
-   typedef short int yysigned_char;
-#endif
+#if defined YYCOPY_NEEDED && YYCOPY_NEEDED
+/* Copy COUNT objects from SRC to DST.  The source and destination do
+   not overlap.  */
+# ifndef YYCOPY
+#  if defined __GNUC__ && 1 < __GNUC__
+#   define YYCOPY(Dst, Src, Count) \
+      __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src)))
+#  else
+#   define YYCOPY(Dst, Src, Count)              \
+      do                                        \
+        {                                       \
+          YYSIZE_T yyi;                         \
+          for (yyi = 0; yyi < (Count); yyi++)   \
+            (Dst)[yyi] = (Src)[yyi];            \
+        }                                       \
+      while (0)
+#  endif
+# endif
+#endif /* !YYCOPY_NEEDED */
 
-/* YYFINAL -- State number of the termination state. */
-#define YYFINAL  12
+/* YYFINAL -- State number of the termination state.  */
+#define YYFINAL  17
 /* YYLAST -- Last index in YYTABLE.  */
-#define YYLAST   25
+#define YYLAST   30
 
-/* YYNTOKENS -- Number of terminals. */
+/* YYNTOKENS -- Number of terminals.  */
 #define YYNTOKENS  17
-/* YYNNTS -- Number of nonterminals. */
-#define YYNNTS  9
-/* YYNRULES -- Number of rules. */
-#define YYNRULES  20
-/* YYNRULES -- Number of states. */
-#define YYNSTATES  34
-
-/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX.  */
+/* YYNNTS -- Number of nonterminals.  */
+#define YYNNTS  10
+/* YYNRULES -- Number of rules.  */
+#define YYNRULES  23
+/* YYNSTATES -- Number of states.  */
+#define YYNSTATES  39
+
+/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned
+   by yylex, with out-of-bounds checking.  */
 #define YYUNDEFTOK  2
 #define YYMAXUTOK   271
 
-#define YYTRANSLATE(YYX)             \
+#define YYTRANSLATE(YYX)                                                \
   ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
 
-/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX.  */
-static const unsigned char yytranslate[] =
+/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM
+   as returned by yylex, without out-of-bounds checking.  */
+static const yytype_uint8 yytranslate[] =
 {
        0,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
@@ -339,210 +478,161 @@ static const unsigned char yytranslate[] =
 };
 
 #if YYDEBUG
-/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
-   YYRHS.  */
-static const unsigned char yyprhs[] =
-{
-       0,     0,     3,     5,     7,    11,    13,    17,    19,    23,
-      25,    29,    33,    35,    39,    43,    45,    49,    53,    57,
-      59
-};
-
-/* YYRHS -- A `-1'-separated list of the rules' RHS. */
-static const yysigned_char yyrhs[] =
-{
-      18,     0,    -1,    19,    -1,    20,    -1,    19,    12,    20,
-      -1,    21,    -1,    20,    14,    21,    -1,    22,    -1,    21,
-      13,    22,    -1,    23,    -1,    22,     8,    23,    -1,    22,
-       9,    23,    -1,    24,    -1,    23,     3,    24,    -1,    23,
-       4,    24,    -1,    25,    -1,    24,     5,    25,    -1,    24,
-       6,    25,    -1,    24,     7,    25,    -1,    16,    -1,    10,
-      19,    11,    -1
-};
-
-/* YYRLINE[YYN] -- source line where rule number YYN was defined.  */
-static const unsigned char yyrline[] =
+  /* YYRLINE[YYN] -- Source line where rule number YYN was defined.  */
+static const yytype_uint8 yyrline[] =
 {
-       0,    94,    94,   100,   103,   107,   110,   114,   117,   121,
-     124,   127,   132,   135,   138,   142,   145,   148,   151,   155,
-     158
+       0,    70,    70,    75,    78,    83,    86,    91,    94,    99,
+     102,   105,   110,   113,   116,   121,   124,   127,   130,   135,
+     138,   141,   146,   149
 };
 #endif
 
-#if YYDEBUG || YYERROR_VERBOSE
-/* YYTNME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
-   First, the terminals, then, starting at YYNTOKENS, nonterminals. */
+#if YYDEBUG || YYERROR_VERBOSE || 1
+/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
+   First, the terminals, then, starting at YYNTOKENS, nonterminals.  */
 static const char *const yytname[] =
 {
   "$end", "error", "$undefined", "exp_PLUS", "exp_MINUS", "exp_TIMES",
   "exp_DIVIDE", "exp_MOD", "exp_SHIFTLEFT", "exp_SHIFTRIGHT",
   "exp_OPENPARENT", "exp_CLOSEPARENT", "exp_OR", "exp_AND", "exp_XOR",
-  "exp_NOT", "exp_NUMBER", "$accept", "Start", "exp", "bitwiseor",
-  "bitwisexor", "bitwiseand", "shift", "term", "factor", 0
+  "exp_NOT", "exp_NUMBER", "$accept", "start", "exp", "bitwiseor",
+  "bitwisexor", "bitwiseand", "shift", "term", "unary", "factor", YY_NULLPTR
 };
 #endif
 
 # ifdef YYPRINT
-/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
-   token YYLEX-NUM.  */
-static const unsigned short int yytoknum[] =
+/* YYTOKNUM[NUM] -- (External) token number corresponding to the
+   (internal) symbol number NUM (which must be that of a token).  */
+static const yytype_uint16 yytoknum[] =
 {
        0,   256,   257,   258,   259,   260,   261,   262,   263,   264,
      265,   266,   267,   268,   269,   270,   271
 };
 # endif
 
-/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives.  */
-static const unsigned char yyr1[] =
+#define YYPACT_NINF -8
+
+#define yypact_value_is_default(Yystate) \
+  (!!((Yystate) == (-8)))
+
+#define YYTABLE_NINF -1
+
+#define yytable_value_is_error(Yytable_value) \
+  0
+
+  /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
+     STATE-NUM.  */
+static const yytype_int8 yypact[] =
 {
-       0,    17,    18,    19,    19,    20,    20,    21,    21,    22,
-      22,    22,    23,    23,    23,    24,    24,    24,    24,    25,
-      25
+       0,     0,     0,     0,    -8,     2,    -7,    -5,     8,     3,
+      10,     1,    -8,    -8,    -8,    -8,     6,    -8,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,    -8,    -5,
+       8,     3,    10,    10,     1,     1,    -8,    -8,    -8
 };
 
-/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN.  */
-static const unsigned char yyr2[] =
+  /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
+     Performed when YYTABLE does not specify something else to do.  Zero
+     means the default is an error.  */
+static const yytype_uint8 yydefact[] =
 {
-       0,     2,     1,     1,     3,     1,     3,     1,     3,     1,
-       3,     3,     1,     3,     3,     1,     3,     3,     3,     1,
-       3
+       0,     0,     0,     0,    22,     0,     2,     3,     5,     7,
+       9,    12,    15,    19,    20,    21,     0,     1,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,    23,     4,
+       6,     8,    10,    11,    13,    14,    16,    17,    18
 };
 
-/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
-   STATE-NUM when YYTABLE doesn't specify something else to do.  Zero
-   means the default is an error.  */
-static const unsigned char yydefact[] =
+  /* YYPGOTO[NTERM-NUM].  */
+static const yytype_int8 yypgoto[] =
 {
-       0,     0,    19,     0,     2,     3,     5,     7,     9,    12,
-      15,     0,     1,     0,     0,     0,     0,     0,     0,     0,
-       0,     0,     0,    20,     4,     6,     8,    10,    11,    13,
-      14,    16,    17,    18
+      -8,    -8,    12,     5,    11,     9,    -2,     4,    -1,    -8
 };
 
-/* YYDEFGOTO[NTERM-NUM]. */
-static const yysigned_char yydefgoto[] =
+  /* YYDEFGOTO[NTERM-NUM].  */
+static const yytype_int8 yydefgoto[] =
 {
-      -1,     3,     4,     5,     6,     7,     8,     9,    10
+      -1,     5,     6,     7,     8,     9,    10,    11,    12,    13
 };
 
-/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
-   STATE-NUM.  */
-#define YYPACT_NINF -14
-static const yysigned_char yypact[] =
+  /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM.  If
+     positive, shift that token.  If negative, reduce the rule whose
+     number is the opposite.  If YYTABLE_NINF, syntax error.  */
+static const yytype_uint8 yytable[] =
 {
-     -10,   -10,   -14,    18,     7,     6,     8,     2,     1,    -4,
-     -14,     3,   -14,   -10,   -10,   -10,   -10,   -10,   -10,   -10,
-     -10,   -10,   -10,   -14,     6,     8,     2,     1,     1,    -4,
-      -4,   -14,   -14,   -14
+      14,    15,    17,     1,     2,    18,    25,    26,    27,    19,
+       3,    21,    22,    23,    24,    16,     4,    28,    18,    32,
+      33,    20,     0,    29,    36,    37,    38,    34,    35,    31,
+      30
 };
 
-/* YYPGOTO[NTERM-NUM].  */
-static const yysigned_char yypgoto[] =
+static const yytype_int8 yycheck[] =
 {
-     -14,   -14,    21,    10,    11,     9,     0,    -6,   -13
+       1,     2,     0,     3,     4,    12,     5,     6,     7,    14,
+      10,     8,     9,     3,     4,     3,    16,    11,    12,    21,
+      22,    13,    -1,    18,    25,    26,    27,    23,    24,    20,
+      19
 };
 
-/* YYTABLE[YYPACT[STATE-NUM]].  What to do in state STATE-NUM.  If
-   positive, shift that token.  If negative, reduce the rule which
-   number is the opposite.  If zero, do what YYDEFACT says.
-   If YYTABLE_NINF, syntax error.  */
-#define YYTABLE_NINF -1
-static const unsigned char yytable[] =
+  /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
+     symbol of state STATE-NUM.  */
+static const yytype_uint8 yystos[] =
 {
-       1,    20,    21,    22,    18,    19,     2,    31,    32,    33,
-      16,    17,    29,    30,    23,    13,    27,    28,    12,    13,
-      14,    15,    11,    24,    26,    25
+       0,     3,     4,    10,    16,    18,    19,    20,    21,    22,
+      23,    24,    25,    26,    25,    25,    19,     0,    12,    14,
+      13,     8,     9,     3,     4,     5,     6,     7,    11,    20,
+      21,    22,    23,    23,    24,    24,    25,    25,    25
 };
 
-static const unsigned char yycheck[] =
+  /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives.  */
+static const yytype_uint8 yyr1[] =
 {
-      10,     5,     6,     7,     3,     4,    16,    20,    21,    22,
-       8,     9,    18,    19,    11,    12,    16,    17,     0,    12,
-      14,    13,     1,    13,    15,    14
+       0,    17,    18,    19,    19,    20,    20,    21,    21,    22,
+      22,    22,    23,    23,    23,    24,    24,    24,    24,    25,
+      25,    25,    26,    26
 };
 
-/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
-   symbol of state STATE-NUM.  */
-static const unsigned char yystos[] =
+  /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN.  */
+static const yytype_uint8 yyr2[] =
 {
-       0,    10,    16,    18,    19,    20,    21,    22,    23,    24,
-      25,    19,     0,    12,    14,    13,     8,     9,     3,     4,
-       5,     6,     7,    11,    20,    21,    22,    23,    23,    24,
-      24,    25,    25,    25
+       0,     2,     1,     1,     3,     1,     3,     1,     3,     1,
+       3,     3,     1,     3,     3,     1,     3,     3,     3,     1,
+       2,     2,     1,     3
 };
 
-#if ! defined (YYSIZE_T) && defined (__SIZE_TYPE__)
-# define YYSIZE_T __SIZE_TYPE__
-#endif
-#if ! defined (YYSIZE_T) && defined (size_t)
-# define YYSIZE_T size_t
-#endif
-#if ! defined (YYSIZE_T)
-# if defined (__STDC__) || defined (__cplusplus)
-#  include <stddef.h> /* INFRINGES ON USER NAME SPACE */
-#  define YYSIZE_T size_t
-# endif
-#endif
-#if ! defined (YYSIZE_T)
-# define YYSIZE_T unsigned int
-#endif
-
-#define yyerrok    (yyerrstatus = 0)
-#define yyclearin  (yychar = YYEMPTY)
-#define YYEMPTY    (-2)
-#define YYEOF    0
-
-#define YYACCEPT  goto yyacceptlab
-#define YYABORT    goto yyabortlab
-#define YYERROR    goto yyerrorlab
 
+#define yyerrok         (yyerrstatus = 0)
+#define yyclearin       (yychar = YYEMPTY)
+#define YYEMPTY         (-2)
+#define YYEOF           0
 
-/* Like YYERROR except do call yyerror.  This remains here temporarily
-   to ease the transition to the new meaning of YYERROR, for GCC.
-   Once GCC version 2 has supplanted version 1, this can go.  */
+#define YYACCEPT        goto yyacceptlab
+#define YYABORT         goto yyabortlab
+#define YYERROR         goto yyerrorlab
 
-#define YYFAIL    goto yyerrlab
 
 #define YYRECOVERING()  (!!yyerrstatus)
 
-#define YYBACKUP(Token, Value)          \
-do                \
-  if (yychar == YYEMPTY && yylen == 1)        \
-    {                \
-      yychar = (Token);            \
-      yylval = (Value);            \
-      yytoken = YYTRANSLATE (yychar);        \
-      YYPOPSTACK;            \
-      goto yybackup;            \
-    }                \
-  else                \
-    {                 \
-      yyerror ("syntax error: cannot back up");\
-      YYERROR;              \
-    }                \
+#define YYBACKUP(Token, Value)                                  \
+do                                                              \
+  if (yychar == YYEMPTY)                                        \
+    {                                                           \
+      yychar = (Token);                                         \
+      yylval = (Value);                                         \
+      YYPOPSTACK (yylen);                                       \
+      yystate = *yyssp;                                         \
+      goto yybackup;                                            \
+    }                                                           \
+  else                                                          \
+    {                                                           \
+      yyerror (yyscanner, YY_("syntax error: cannot back up")); \
+      YYERROR;                                                  \
+    }                                                           \
 while (0)
 
-#define YYTERROR  1
-#define YYERRCODE  256
-
-/* YYLLOC_DEFAULT -- Compute the default location (before the actions
-   are run).  */
-
-#ifndef YYLLOC_DEFAULT
-# define YYLLOC_DEFAULT(Current, Rhs, N)    \
-   ((Current).first_line   = (Rhs)[1].first_line,  \
-    (Current).first_column = (Rhs)[1].first_column,  \
-    (Current).last_line    = (Rhs)[N].last_line,  \
-    (Current).last_column  = (Rhs)[N].last_column)
-#endif
+/* Error token number */
+#define YYTERROR        1
+#define YYERRCODE       256
 
-/* YYLEX -- calling `yylex' with the right arguments.  */
 
-#ifdef YYLEX_PARAM
-# define YYLEX yylex (&yylval, YYLEX_PARAM)
-#else
-# define YYLEX yylex (&yylval)
-#endif
 
 /* Enable debugging if requested.  */
 #if YYDEBUG
@@ -552,54 +642,85 @@ while (0)
 #  define YYFPRINTF fprintf
 # endif
 
-# define YYDPRINTF(Args)      \
-do {            \
-  if (yydebug)          \
-    YYFPRINTF Args;        \
+# define YYDPRINTF(Args)                        \
+do {                                            \
+  if (yydebug)                                  \
+    YYFPRINTF Args;                             \
 } while (0)
 
-# define YYDSYMPRINT(Args)      \
-do {            \
-  if (yydebug)          \
-    yysymprint Args;        \
-} while (0)
+/* This macro is provided for backward compatibility. */
+#ifndef YY_LOCATION_PRINT
+# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
+#endif
 
-# define YYDSYMPRINTF(Title, Token, Value, Location)    \
-do {                \
-  if (yydebug)              \
-    {                \
-      YYFPRINTF (stderr, "%s ", Title);        \
-      yysymprint (stderr,           \
-                  Token, Value);  \
-      YYFPRINTF (stderr, "\n");          \
-    }                \
+
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location)                    \
+do {                                                                      \
+  if (yydebug)                                                            \
+    {                                                                     \
+      YYFPRINTF (stderr, "%s ", Title);                                   \
+      yy_symbol_print (stderr,                                            \
+                  Type, Value, yyscanner); \
+      YYFPRINTF (stderr, "\n");                                           \
+    }                                                                     \
 } while (0)
 
+
+/*----------------------------------------.
+| Print this symbol's value on YYOUTPUT.  |
+`----------------------------------------*/
+
+static void
+yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, yyscan_t yyscanner)
+{
+  FILE *yyo = yyoutput;
+  YYUSE (yyo);
+  YYUSE (yyscanner);
+  if (!yyvaluep)
+    return;
+# ifdef YYPRINT
+  if (yytype < YYNTOKENS)
+    YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
+# endif
+  YYUSE (yytype);
+}
+
+
+/*--------------------------------.
+| Print this symbol on YYOUTPUT.  |
+`--------------------------------*/
+
+static void
+yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, yyscan_t yyscanner)
+{
+  YYFPRINTF (yyoutput, "%s %s (",
+             yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]);
+
+  yy_symbol_value_print (yyoutput, yytype, yyvaluep, yyscanner);
+  YYFPRINTF (yyoutput, ")");
+}
+
 /*------------------------------------------------------------------.
 | yy_stack_print -- Print the state stack from its BOTTOM up to its |
 | TOP (included).                                                   |
 `------------------------------------------------------------------*/
 
-#if defined (__STDC__) || defined (__cplusplus)
-static void
-yy_stack_print (short int *bottom, short int *top)
-#else
 static void
-yy_stack_print (bottom, top)
-    short int *bottom;
-    short int *top;
-#endif
+yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
 {
   YYFPRINTF (stderr, "Stack now");
-  for (/* Nothing. */; bottom <= top; ++bottom)
-    YYFPRINTF (stderr, " %d", *bottom);
+  for (; yybottom <= yytop; yybottom++)
+    {
+      int yybot = *yybottom;
+      YYFPRINTF (stderr, " %d", yybot);
+    }
   YYFPRINTF (stderr, "\n");
 }
 
-# define YY_STACK_PRINT(Bottom, Top)        \
-do {                \
-  if (yydebug)              \
-    yy_stack_print ((Bottom), (Top));        \
+# define YY_STACK_PRINT(Bottom, Top)                            \
+do {                                                            \
+  if (yydebug)                                                  \
+    yy_stack_print ((Bottom), (Top));                           \
 } while (0)
 
 
@@ -607,29 +728,30 @@ do {                \
 | Report that the YYRULE is going to be reduced.  |
 `------------------------------------------------*/
 
-#if defined (__STDC__) || defined (__cplusplus)
 static void
-yy_reduce_print (int yyrule)
-#else
-static void
-yy_reduce_print (yyrule)
-    int yyrule;
-#endif
+yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule, yyscan_t yyscanner)
 {
+  unsigned long int yylno = yyrline[yyrule];
+  int yynrhs = yyr2[yyrule];
   int yyi;
-  unsigned int yylno = yyrline[yyrule];
-  YYFPRINTF (stderr, "Reducing stack by rule %d (line %u), ",
+  YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
              yyrule - 1, yylno);
-  /* Print the symbols being reduced, and their result.  */
-  for (yyi = yyprhs[yyrule]; 0 <= yyrhs[yyi]; yyi++)
-    YYFPRINTF (stderr, "%s ", yytname [yyrhs[yyi]]);
-  YYFPRINTF (stderr, "-> %s\n", yytname [yyr1[yyrule]]);
+  /* The symbols being reduced.  */
+  for (yyi = 0; yyi < yynrhs; yyi++)
+    {
+      YYFPRINTF (stderr, "   $%d = ", yyi + 1);
+      yy_symbol_print (stderr,
+                       yystos[yyssp[yyi + 1 - yynrhs]],
+                       &(yyvsp[(yyi + 1) - (yynrhs)])
+                                              , yyscanner);
+      YYFPRINTF (stderr, "\n");
+    }
 }
 
-# define YY_REDUCE_PRINT(Rule)    \
-do {          \
-  if (yydebug)        \
-    yy_reduce_print (Rule);    \
+# define YY_REDUCE_PRINT(Rule)          \
+do {                                    \
+  if (yydebug)                          \
+    yy_reduce_print (yyssp, yyvsp, Rule, yyscanner); \
 } while (0)
 
 /* Nonzero means print parse trace.  It is left uninitialized so that
@@ -637,15 +759,14 @@ do {          \
 int yydebug;
 #else /* !YYDEBUG */
 # define YYDPRINTF(Args)
-# define YYDSYMPRINT(Args)
-# define YYDSYMPRINTF(Title, Token, Value, Location)
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
 # define YY_STACK_PRINT(Bottom, Top)
 # define YY_REDUCE_PRINT(Rule)
 #endif /* !YYDEBUG */
 
 
 /* YYINITDEPTH -- initial size of the parser's stacks.  */
-#ifndef  YYINITDEPTH
+#ifndef YYINITDEPTH
 # define YYINITDEPTH 200
 #endif
 
@@ -653,58 +774,40 @@ int yydebug;
    if the built-in stack extension method is used).
 
    Do not make this value too large; the results are undefined if
-   SIZE_MAX < YYSTACK_BYTES (YYMAXDEPTH)
+   YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
    evaluated with infinite-precision integer arithmetic.  */
 
-#if defined (YYMAXDEPTH) && YYMAXDEPTH == 0
-# undef YYMAXDEPTH
-#endif
-
 #ifndef YYMAXDEPTH
 # define YYMAXDEPTH 10000
 #endif
 
-

 
 #if YYERROR_VERBOSE
 
 # ifndef yystrlen
-#  if defined (__GLIBC__) && defined (_STRING_H)
+#  if defined __GLIBC__ && defined _STRING_H
 #   define yystrlen strlen
 #  else
 /* Return the length of YYSTR.  */
 static YYSIZE_T
-#   if defined (__STDC__) || defined (__cplusplus)
 yystrlen (const char *yystr)
-#   else
-yystrlen (yystr)
-     const char *yystr;
-#   endif
 {
-  const char *yys = yystr;
-
-  while (*yys++ != '\0')
+  YYSIZE_T yylen;
+  for (yylen = 0; yystr[yylen]; yylen++)
     continue;
-
-  return yys - yystr - 1;
+  return yylen;
 }
 #  endif
 # endif
 
 # ifndef yystpcpy
-#  if defined (__GLIBC__) && defined (_STRING_H) && defined (_GNU_SOURCE)
+#  if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
 #   define yystpcpy stpcpy
 #  else
 /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
    YYDEST.  */
 static char *
-#   if defined (__STDC__) || defined (__cplusplus)
 yystpcpy (char *yydest, const char *yysrc)
-#   else
-yystpcpy (yydest, yysrc)
-     char *yydest;
-     const char *yysrc;
-#   endif
 {
   char *yyd = yydest;
   const char *yys = yysrc;
@@ -717,91 +820,207 @@ yystpcpy (yydest, yysrc)
 #  endif
 # endif
 
-#endif /* !YYERROR_VERBOSE */
+# ifndef yytnamerr
+/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
+   quotes and backslashes, so that it's suitable for yyerror.  The
+   heuristic is that double-quoting is unnecessary unless the string
+   contains an apostrophe, a comma, or backslash (other than
+   backslash-backslash).  YYSTR is taken from yytname.  If YYRES is
+   null, do not copy; instead, return the length of what the result
+   would have been.  */
+static YYSIZE_T
+yytnamerr (char *yyres, const char *yystr)
+{
+  if (*yystr == '"')
+    {
+      YYSIZE_T yyn = 0;
+      char const *yyp = yystr;
 
-

+      for (;;)
+        switch (*++yyp)
+          {
+          case '\'':
+          case ',':
+            goto do_not_strip_quotes;
+
+          case '\\':
+            if (*++yyp != '\\')
+              goto do_not_strip_quotes;
+            /* Fall through.  */
+          default:
+            if (yyres)
+              yyres[yyn] = *yyp;
+            yyn++;
+            break;
+
+          case '"':
+            if (yyres)
+              yyres[yyn] = '\0';
+            return yyn;
+          }
+    do_not_strip_quotes: ;
+    }
 
-#if YYDEBUG
-/*--------------------------------.
-| Print this symbol on YYOUTPUT.  |
-`--------------------------------*/
+  if (! yyres)
+    return yystrlen (yystr);
 
-#if defined (__STDC__) || defined (__cplusplus)
-static void
-yysymprint (FILE *yyoutput, int yytype, YYSTYPE *yyvaluep)
-#else
-static void
-yysymprint (yyoutput, yytype, yyvaluep)
-    FILE *yyoutput;
-    int yytype;
-    YYSTYPE *yyvaluep;
-#endif
+  return yystpcpy (yyres, yystr) - yyres;
+}
+# endif
+
+/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message
+   about the unexpected token YYTOKEN for the state stack whose top is
+   YYSSP.
+
+   Return 0 if *YYMSG was successfully written.  Return 1 if *YYMSG is
+   not large enough to hold the message.  In that case, also set
+   *YYMSG_ALLOC to the required number of bytes.  Return 2 if the
+   required number of bytes is too large to store.  */
+static int
+yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
+                yytype_int16 *yyssp, int yytoken)
 {
-  /* Pacify ``unused variable'' warnings.  */
-  (void) yyvaluep;
+  YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]);
+  YYSIZE_T yysize = yysize0;
+  enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
+  /* Internationalized format string. */
+  const char *yyformat = YY_NULLPTR;
+  /* Arguments of yyformat. */
+  char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
+  /* Number of reported tokens (one for the "unexpected", one per
+     "expected"). */
+  int yycount = 0;
+
+  /* There are many possibilities here to consider:
+     - If this state is a consistent state with a default action, then
+       the only way this function was invoked is if the default action
+       is an error action.  In that case, don't check for expected
+       tokens because there are none.
+     - The only way there can be no lookahead present (in yychar) is if
+       this state is a consistent state with a default action.  Thus,
+       detecting the absence of a lookahead is sufficient to determine
+       that there is no unexpected or expected token to report.  In that
+       case, just report a simple "syntax error".
+     - Don't assume there isn't a lookahead just because this state is a
+       consistent state with a default action.  There might have been a
+       previous inconsistent state, consistent state with a non-default
+       action, or user semantic action that manipulated yychar.
+     - Of course, the expected token list depends on states to have
+       correct lookahead information, and it depends on the parser not
+       to perform extra reductions after fetching a lookahead from the
+       scanner and before detecting a syntax error.  Thus, state merging
+       (from LALR or IELR) and default reductions corrupt the expected
+       token list.  However, the list is correct for canonical LR with
+       one exception: it will still contain any token that will not be
+       accepted due to an error action in a later state.
+  */
+  if (yytoken != YYEMPTY)
+    {
+      int yyn = yypact[*yyssp];
+      yyarg[yycount++] = yytname[yytoken];
+      if (!yypact_value_is_default (yyn))
+        {
+          /* Start YYX at -YYN if negative to avoid negative indexes in
+             YYCHECK.  In other words, skip the first -YYN actions for
+             this state because they are default actions.  */
+          int yyxbegin = yyn < 0 ? -yyn : 0;
+          /* Stay within bounds of both yycheck and yytname.  */
+          int yychecklim = YYLAST - yyn + 1;
+          int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
+          int yyx;
+
+          for (yyx = yyxbegin; yyx < yyxend; ++yyx)
+            if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR
+                && !yytable_value_is_error (yytable[yyx + yyn]))
+              {
+                if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
+                  {
+                    yycount = 1;
+                    yysize = yysize0;
+                    break;
+                  }
+                yyarg[yycount++] = yytname[yyx];
+                {
+                  YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]);
+                  if (! (yysize <= yysize1
+                         && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
+                    return 2;
+                  yysize = yysize1;
+                }
+              }
+        }
+    }
 
-  if (yytype < YYNTOKENS)
+  switch (yycount)
     {
-      YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
-# ifdef YYPRINT
-      YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
-# endif
+# define YYCASE_(N, S)                      \
+      case N:                               \
+        yyformat = S;                       \
+      break
+      YYCASE_(0, YY_("syntax error"));
+      YYCASE_(1, YY_("syntax error, unexpected %s"));
+      YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
+      YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
+      YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
+      YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
+# undef YYCASE_
     }
-  else
-    YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);
 
-  switch (yytype)
+  {
+    YYSIZE_T yysize1 = yysize + yystrlen (yyformat);
+    if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
+      return 2;
+    yysize = yysize1;
+  }
+
+  if (*yymsg_alloc < yysize)
     {
-      default:
-        break;
+      *yymsg_alloc = 2 * yysize;
+      if (! (yysize <= *yymsg_alloc
+             && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM))
+        *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM;
+      return 1;
     }
-  YYFPRINTF (yyoutput, ")");
+
+  /* Avoid sprintf, as that infringes on the user's name space.
+     Don't have undefined behavior even if the translation
+     produced a string with the wrong number of "%s"s.  */
+  {
+    char *yyp = *yymsg;
+    int yyi = 0;
+    while ((*yyp = *yyformat) != '\0')
+      if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount)
+        {
+          yyp += yytnamerr (yyp, yyarg[yyi++]);
+          yyformat += 2;
+        }
+      else
+        {
+          yyp++;
+          yyformat++;
+        }
+  }
+  return 0;
 }
+#endif /* YYERROR_VERBOSE */
 
-#endif /* ! YYDEBUG */
 /*-----------------------------------------------.
 | Release the memory associated to this symbol.  |
 `-----------------------------------------------*/
 
-#if defined (__STDC__) || defined (__cplusplus)
-static void
-yydestruct (int yytype, YYSTYPE *yyvaluep)
-#else
 static void
-yydestruct (yytype, yyvaluep)
-    int yytype;
-    YYSTYPE *yyvaluep;
-#endif
+yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, yyscan_t yyscanner)
 {
-  /* Pacify ``unused variable'' warnings.  */
-  (void) yyvaluep;
-
-  switch (yytype)
-    {
-
-      default:
-        break;
-    }
+  YYUSE (yyvaluep);
+  YYUSE (yyscanner);
+  if (!yymsg)
+    yymsg = "Deleting";
+  YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
+
+  YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+  YYUSE (yytype);
+  YY_IGNORE_MAYBE_UNINITIALIZED_END
 }
-

-
-/* Prevent warnings from -Wmissing-prototypes.  */
-
-#ifdef YYPARSE_PARAM
-# if defined (__STDC__) || defined (__cplusplus)
-int yyparse (void *YYPARSE_PARAM);
-# else
-int yyparse ();
-# endif
-#else /* ! YYPARSE_PARAM */
-#if defined (__STDC__) || defined (__cplusplus)
-int yyparse (void);
-#else
-int yyparse ();
-#endif
-#endif /* ! YYPARSE_PARAM */
-
-
 
 
 
@@ -810,90 +1029,76 @@ int yyparse ();
 | yyparse.  |
 `----------*/
 
-#ifdef YYPARSE_PARAM
-# if defined (__STDC__) || defined (__cplusplus)
-int yyparse (void *YYPARSE_PARAM)
-# else
-int yyparse (YYPARSE_PARAM)
-  void *YYPARSE_PARAM;
-# endif
-#else /* ! YYPARSE_PARAM */
-#if defined (__STDC__) || defined (__cplusplus)
-int
-yyparse (void)
-#else
 int
-yyparse ()
-
-#endif
-#endif
+yyparse (yyscan_t yyscanner)
 {
-  /* The lookahead symbol.  */
+/* The lookahead symbol.  */
 int yychar;
 
-/* The semantic value of the lookahead symbol.  */
-YYSTYPE yylval;
-
-/* Number of syntax errors so far.  */
-int yynerrs;
-
-  int yystate;
-  int yyn;
-  int yyresult;
-  /* Number of tokens to shift before error messages enabled.  */
-  int yyerrstatus;
-  /* Lookahead token as an internal (translated) token number.  */
-  int yytoken = 0;
 
-  /* Three stacks and their tools:
-     `yyss': related to states,
-     `yyvs': related to semantic values,
-     `yyls': related to locations.
+/* The semantic value of the lookahead symbol.  */
+/* Default value used for initialization, for pacifying older GCCs
+   or non-GCC compilers.  */
+YY_INITIAL_VALUE (static YYSTYPE yyval_default;)
+YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default);
 
-     Refer to the stacks thru separate pointers, to allow yyoverflow
-     to reallocate them elsewhere.  */
+    /* Number of syntax errors so far.  */
+    int yynerrs;
 
-  /* The state stack.  */
-  short int yyssa[YYINITDEPTH];
-  short int *yyss = yyssa;
-  short int *yyssp;
+    int yystate;
+    /* Number of tokens to shift before error messages enabled.  */
+    int yyerrstatus;
 
-  /* The semantic value stack.  */
-  YYSTYPE yyvsa[YYINITDEPTH];
-  YYSTYPE *yyvs = yyvsa;
-  YYSTYPE *yyvsp;
+    /* The stacks and their tools:
+       'yyss': related to states.
+       'yyvs': related to semantic values.
 
+       Refer to the stacks through separate pointers, to allow yyoverflow
+       to reallocate them elsewhere.  */
 
+    /* The state stack.  */
+    yytype_int16 yyssa[YYINITDEPTH];
+    yytype_int16 *yyss;
+    yytype_int16 *yyssp;
 
-#define YYPOPSTACK   (yyvsp--, yyssp--)
+    /* The semantic value stack.  */
+    YYSTYPE yyvsa[YYINITDEPTH];
+    YYSTYPE *yyvs;
+    YYSTYPE *yyvsp;
 
-  YYSIZE_T yystacksize = YYINITDEPTH;
+    YYSIZE_T yystacksize;
 
+  int yyn;
+  int yyresult;
+  /* Lookahead token as an internal (translated) token number.  */
+  int yytoken = 0;
   /* The variables used to return semantic value and location from the
      action routines.  */
   YYSTYPE yyval;
 
+#if YYERROR_VERBOSE
+  /* Buffer for error messages, and its allocated size.  */
+  char yymsgbuf[128];
+  char *yymsg = yymsgbuf;
+  YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
+#endif
+
+#define YYPOPSTACK(N)   (yyvsp -= (N), yyssp -= (N))
 
-  /* When reducing, the number of symbols on the RHS of the reduced
-     rule.  */
-  int yylen;
+  /* The number of symbols on the RHS of the reduced rule.
+     Keep to zero when no symbol should be popped.  */
+  int yylen = 0;
+
+  yyssp = yyss = yyssa;
+  yyvsp = yyvs = yyvsa;
+  yystacksize = YYINITDEPTH;
 
   YYDPRINTF ((stderr, "Starting parse\n"));
 
   yystate = 0;
   yyerrstatus = 0;
   yynerrs = 0;
-  yychar = YYEMPTY;    /* Cause a token to be read.  */
-
-  /* Initialize stack pointers.
-     Waste one element of value and location stack
-     so that they stay on the same level as the state stack.
-     The wasted elements are never initialized.  */
-
-  yyssp = yyss;
-  yyvsp = yyvs;
-
-
+  yychar = YYEMPTY; /* Cause a token to be read.  */
   goto yysetstate;
 
 /*------------------------------------------------------------.
@@ -901,8 +1106,7 @@ int yynerrs;
 `------------------------------------------------------------*/
  yynewstate:
   /* In all cases, when you get here, the value and location stacks
-     have just been pushed. so pushing a state here evens the stacks.
-     */
+     have just been pushed.  So pushing a state here evens the stacks.  */
   yyssp++;
 
  yysetstate:
@@ -915,49 +1119,46 @@ int yynerrs;
 
 #ifdef yyoverflow
       {
-  /* Give user a chance to reallocate the stack. Use copies of
-     these so that the &'s don't force the real ones into
-     memory.  */
-  YYSTYPE *yyvs1 = yyvs;
-  short int *yyss1 = yyss;
-
-
-  /* Each stack pointer address is followed by the size of the
-     data in use in that stack, in bytes.  This used to be a
-     conditional around just the two extra args, but that might
-     be undefined if yyoverflow is a macro.  */
-  yyoverflow ("parser stack overflow",
-        &yyss1, yysize * sizeof (*yyssp),
-        &yyvs1, yysize * sizeof (*yyvsp),
-
-        &yystacksize);
-
-  yyss = yyss1;
-  yyvs = yyvs1;
+        /* Give user a chance to reallocate the stack.  Use copies of
+           these so that the &'s don't force the real ones into
+           memory.  */
+        YYSTYPE *yyvs1 = yyvs;
+        yytype_int16 *yyss1 = yyss;
+
+        /* Each stack pointer address is followed by the size of the
+           data in use in that stack, in bytes.  This used to be a
+           conditional around just the two extra args, but that might
+           be undefined if yyoverflow is a macro.  */
+        yyoverflow (YY_("memory exhausted"),
+                    &yyss1, yysize * sizeof (*yyssp),
+                    &yyvs1, yysize * sizeof (*yyvsp),
+                    &yystacksize);
+
+        yyss = yyss1;
+        yyvs = yyvs1;
       }
 #else /* no yyoverflow */
 # ifndef YYSTACK_RELOCATE
-      goto yyoverflowlab;
+      goto yyexhaustedlab;
 # else
       /* Extend the stack our own way.  */
       if (YYMAXDEPTH <= yystacksize)
-  goto yyoverflowlab;
+        goto yyexhaustedlab;
       yystacksize *= 2;
       if (YYMAXDEPTH < yystacksize)
-  yystacksize = YYMAXDEPTH;
+        yystacksize = YYMAXDEPTH;
 
       {
-  short int *yyss1 = yyss;
-  union yyalloc *yyptr =
-    (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
-  if (! yyptr)
-    goto yyoverflowlab;
-  YYSTACK_RELOCATE (yyss);
-  YYSTACK_RELOCATE (yyvs);
-
+        yytype_int16 *yyss1 = yyss;
+        union yyalloc *yyptr =
+          (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
+        if (! yyptr)
+          goto yyexhaustedlab;
+        YYSTACK_RELOCATE (yyss_alloc, yyss);
+        YYSTACK_RELOCATE (yyvs_alloc, yyvs);
 #  undef YYSTACK_RELOCATE
-  if (yyss1 != yyssa)
-    YYSTACK_FREE (yyss1);
+        if (yyss1 != yyssa)
+          YYSTACK_FREE (yyss1);
       }
 # endif
 #endif /* no yyoverflow */
@@ -965,16 +1166,18 @@ int yynerrs;
       yyssp = yyss + yysize - 1;
       yyvsp = yyvs + yysize - 1;
 
-
       YYDPRINTF ((stderr, "Stack size increased to %lu\n",
-      (unsigned long int) yystacksize));
+                  (unsigned long int) yystacksize));
 
       if (yyss + yystacksize - 1 <= yyssp)
-  YYABORT;
+        YYABORT;
     }
 
   YYDPRINTF ((stderr, "Entering state %d\n", yystate));
 
+  if (yystate == YYFINAL)
+    YYACCEPT;
+
   goto yybackup;
 
 /*-----------.
@@ -982,14 +1185,12 @@ int yynerrs;
 `-----------*/
 yybackup:
 
-/* Do appropriate processing given the current state.  */
-/* Read a lookahead token if we need one and don't already have one.  */
-/* yyresume: */
+  /* Do appropriate processing given the current state.  Read a
+     lookahead token if we need one and don't already have one.  */
 
   /* First try to decide what to do without reference to lookahead token.  */
-
   yyn = yypact[yystate];
-  if (yyn == YYPACT_NINF)
+  if (yypact_value_is_default (yyn))
     goto yydefault;
 
   /* Not known => get a lookahead token if don't already have one.  */
@@ -998,7 +1199,7 @@ yybackup:
   if (yychar == YYEMPTY)
     {
       YYDPRINTF ((stderr, "Reading a token: "));
-      yychar = YYLEX;
+      yychar = yylex (&yylval, yyscanner);
     }
 
   if (yychar <= YYEOF)
@@ -1009,7 +1210,7 @@ yybackup:
   else
     {
       yytoken = YYTRANSLATE (yychar);
-      YYDSYMPRINTF ("Next token is", yytoken, &yylval, &yylloc);
+      YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
     }
 
   /* If the proper action on seeing token YYTOKEN is to reduce or to
@@ -1020,31 +1221,28 @@ yybackup:
   yyn = yytable[yyn];
   if (yyn <= 0)
     {
-      if (yyn == 0 || yyn == YYTABLE_NINF)
-  goto yyerrlab;
+      if (yytable_value_is_error (yyn))
+        goto yyerrlab;
       yyn = -yyn;
       goto yyreduce;
     }
 
-  if (yyn == YYFINAL)
-    YYACCEPT;
-
-  /* Shift the lookahead token.  */
-  YYDPRINTF ((stderr, "Shifting token %s, ", yytname[yytoken]));
-
-  /* Discard the token being shifted unless it is eof.  */
-  if (yychar != YYEOF)
-    yychar = YYEMPTY;
-
-  *++yyvsp = yylval;
-
-
   /* Count tokens shifted since error; after three, turn off error
      status.  */
   if (yyerrstatus)
     yyerrstatus--;
 
+  /* Shift the lookahead token.  */
+  YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
+
+  /* Discard the shifted token.  */
+  yychar = YYEMPTY;
+
   yystate = yyn;
+  YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+  *++yyvsp = yylval;
+  YY_IGNORE_MAYBE_UNINITIALIZED_END
+
   goto yynewstate;
 
 
@@ -1066,7 +1264,7 @@ yyreduce:
   yylen = yyr2[yyn];
 
   /* If YYLEN is nonzero, implement the default value of the action:
-     `$$ = $1'.
+     '$$ = $1'.
 
      Otherwise, the following line sets YYVAL to garbage.
      This behavior is undocumented and Bison
@@ -1080,118 +1278,205 @@ yyreduce:
   switch (yyn)
     {
         case 2:
-
+#line 70 "cmExprParser.y" /* yacc.c:1646  */
     {
-  yyGetParser->SetResult(yyvsp[0].Number);
-}
+    cmExpr_yyget_extra(yyscanner)->SetResult((yyvsp[0].Number));
+  }
+#line 1286 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 3:
-
-    {yyval.Number = yyvsp[0].Number;}
+#line 75 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[0].Number);
+  }
+#line 1294 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 4:
-
-    {yyval.Number = yyvsp[-2].Number | yyvsp[0].Number;}
+#line 78 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[-2].Number) | (yyvsp[0].Number);
+  }
+#line 1302 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 5:
-
-    {yyval.Number = yyvsp[0].Number;}
+#line 83 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[0].Number);
+  }
+#line 1310 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 6:
-
-    {yyval.Number = yyvsp[-2].Number ^ yyvsp[0].Number;}
+#line 86 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[-2].Number) ^ (yyvsp[0].Number);
+  }
+#line 1318 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 7:
-
-    {yyval.Number = yyvsp[0].Number;}
+#line 91 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[0].Number);
+  }
+#line 1326 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 8:
-
-    {yyval.Number = yyvsp[-2].Number & yyvsp[0].Number;}
+#line 94 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[-2].Number) & (yyvsp[0].Number);
+  }
+#line 1334 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 9:
-
-    {yyval.Number = yyvsp[0].Number;}
+#line 99 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[0].Number);
+  }
+#line 1342 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 10:
-
-    {yyval.Number = yyvsp[-2].Number << yyvsp[0].Number;}
+#line 102 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[-2].Number) << (yyvsp[0].Number);
+  }
+#line 1350 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 11:
-
-    {yyval.Number = yyvsp[-2].Number >> yyvsp[0].Number;}
+#line 105 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[-2].Number) >> (yyvsp[0].Number);
+  }
+#line 1358 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 12:
-
-    {yyval.Number = yyvsp[0].Number;}
+#line 110 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[0].Number);
+  }
+#line 1366 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 13:
-
-    {yyval.Number = yyvsp[-2].Number + yyvsp[0].Number;}
+#line 113 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[-2].Number) + (yyvsp[0].Number);
+  }
+#line 1374 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 14:
-
-    {yyval.Number = yyvsp[-2].Number - yyvsp[0].Number;}
+#line 116 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[-2].Number) - (yyvsp[0].Number);
+  }
+#line 1382 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 15:
-
-    {yyval.Number = yyvsp[0].Number;}
+#line 121 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[0].Number);
+  }
+#line 1390 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 16:
-
-    {yyval.Number = yyvsp[-2].Number * yyvsp[0].Number;}
+#line 124 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[-2].Number) * (yyvsp[0].Number);
+  }
+#line 1398 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 17:
-
-    {yyval.Number = yyvsp[-2].Number / yyvsp[0].Number;}
+#line 127 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[-2].Number) / (yyvsp[0].Number);
+  }
+#line 1406 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 18:
-
-    {yyval.Number = yyvsp[-2].Number % yyvsp[0].Number;}
+#line 130 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[-2].Number) % (yyvsp[0].Number);
+  }
+#line 1414 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 19:
-
-    {yyval.Number = yyvsp[0].Number;}
+#line 135 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[0].Number);
+  }
+#line 1422 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
   case 20:
-
-    {yyval.Number = yyvsp[-1].Number;}
+#line 138 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = + (yyvsp[0].Number);
+  }
+#line 1430 "cmExprParser.cxx" /* yacc.c:1646  */
     break;
 
+  case 21:
+#line 141 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = - (yyvsp[0].Number);
+  }
+#line 1438 "cmExprParser.cxx" /* yacc.c:1646  */
+    break;
 
-    }
-
-/* Line 1010 of yacc.c.  */
+  case 22:
+#line 146 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[0].Number);
+  }
+#line 1446 "cmExprParser.cxx" /* yacc.c:1646  */
+    break;
 
-

-  yyvsp -= yylen;
-  yyssp -= yylen;
+  case 23:
+#line 149 "cmExprParser.y" /* yacc.c:1646  */
+    {
+    (yyval.Number) = (yyvsp[-1].Number);
+  }
+#line 1454 "cmExprParser.cxx" /* yacc.c:1646  */
+    break;
 
 
+#line 1458 "cmExprParser.cxx" /* yacc.c:1646  */
+      default: break;
+    }
+  /* User semantic actions sometimes alter yychar, and that requires
+     that yytoken be updated with the new translation.  We take the
+     approach of translating immediately before every use of yytoken.
+     One alternative is translating here after every semantic action,
+     but that translation would be missed if the semantic action invokes
+     YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
+     if it invokes YYBACKUP.  In the case of YYABORT or YYACCEPT, an
+     incorrect destructor might then be invoked immediately.  In the
+     case of YYERROR or YYBACKUP, subsequent parser actions might lead
+     to an incorrect destructor call or verbose syntax error message
+     before the lookahead is translated.  */
+  YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
+
+  YYPOPSTACK (yylen);
+  yylen = 0;
   YY_STACK_PRINT (yyss, yyssp);
 
   *++yyvsp = yyval;
 
-
-  /* Now `shift' the result of the reduction.  Determine what state
+  /* Now 'shift' the result of the reduction.  Determine what state
      that goes to, based on the state we popped back to and the rule
      number reduced by.  */
 
@@ -1206,74 +1491,52 @@ yyreduce:
   goto yynewstate;
 
 
-/*------------------------------------.
-| yyerrlab -- here on detecting error |
-`------------------------------------*/
+/*--------------------------------------.
+| yyerrlab -- here on detecting error.  |
+`--------------------------------------*/
 yyerrlab:
+  /* Make sure we have latest lookahead translation.  See comments at
+     user semantic actions for why this is necessary.  */
+  yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);
+
   /* If not already recovering from an error, report this error.  */
   if (!yyerrstatus)
     {
       ++yynerrs;
-#if YYERROR_VERBOSE
-      yyn = yypact[yystate];
-
-      if (YYPACT_NINF < yyn && yyn < YYLAST)
-  {
-    YYSIZE_T yysize = 0;
-    int yytype = YYTRANSLATE (yychar);
-    const char* yyprefix;
-    char *yymsg;
-    int yyx;
-
-    /* Start YYX at -YYN if negative to avoid negative indexes in
-       YYCHECK.  */
-    int yyxbegin = yyn < 0 ? -yyn : 0;
-
-    /* Stay within bounds of both yycheck and yytname.  */
-    int yychecklim = YYLAST - yyn;
-    int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
-    int yycount = 0;
-
-    yyprefix = ", expecting ";
-    for (yyx = yyxbegin; yyx < yyxend; ++yyx)
-      if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
-        {
-    yysize += yystrlen (yyprefix) + yystrlen (yytname [yyx]);
-    yycount += 1;
-    if (yycount == 5)
-      {
-        yysize = 0;
-        break;
-      }
-        }
-    yysize += (sizeof ("syntax error, unexpected ")
-         + yystrlen (yytname[yytype]));
-    yymsg = (char *) YYSTACK_ALLOC (yysize);
-    if (yymsg != 0)
+#if ! YYERROR_VERBOSE
+      yyerror (yyscanner, YY_("syntax error"));
+#else
+# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
+                                        yyssp, yytoken)
       {
-        char *yyp = yystpcpy (yymsg, "syntax error, unexpected ");
-        yyp = yystpcpy (yyp, yytname[yytype]);
-
-        if (yycount < 5)
-    {
-      yyprefix = ", expecting ";
-      for (yyx = yyxbegin; yyx < yyxend; ++yyx)
-        if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
+        char const *yymsgp = YY_("syntax error");
+        int yysyntax_error_status;
+        yysyntax_error_status = YYSYNTAX_ERROR;
+        if (yysyntax_error_status == 0)
+          yymsgp = yymsg;
+        else if (yysyntax_error_status == 1)
           {
-      yyp = yystpcpy (yyp, yyprefix);
-      yyp = yystpcpy (yyp, yytname[yyx]);
-      yyprefix = " or ";
+            if (yymsg != yymsgbuf)
+              YYSTACK_FREE (yymsg);
+            yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
+            if (!yymsg)
+              {
+                yymsg = yymsgbuf;
+                yymsg_alloc = sizeof yymsgbuf;
+                yysyntax_error_status = 2;
+              }
+            else
+              {
+                yysyntax_error_status = YYSYNTAX_ERROR;
+                yymsgp = yymsg;
+              }
           }
-    }
-        yyerror (yymsg);
-        YYSTACK_FREE (yymsg);
+        yyerror (yyscanner, yymsgp);
+        if (yysyntax_error_status == 2)
+          goto yyexhaustedlab;
       }
-    else
-      yyerror ("syntax error; also virtual memory exhausted");
-  }
-      else
-#endif /* YYERROR_VERBOSE */
-  yyerror ("syntax error");
+# undef YYSYNTAX_ERROR
+#endif
     }
 
 
@@ -1281,31 +1544,23 @@ yyerrlab:
   if (yyerrstatus == 3)
     {
       /* If just tried and failed to reuse lookahead token after an
-   error, discard it.  */
+         error, discard it.  */
 
       if (yychar <= YYEOF)
         {
-          /* If at end of input, pop the error token,
-       then the rest of the stack, then return failure.  */
-    if (yychar == YYEOF)
-       for (;;)
-         {
-     YYPOPSTACK;
-     if (yyssp == yyss)
-       YYABORT;
-     YYDSYMPRINTF ("Error: popping", yystos[*yyssp], yyvsp, yylsp);
-     yydestruct (yystos[*yyssp], yyvsp);
-         }
+          /* Return failure if at end of input.  */
+          if (yychar == YYEOF)
+            YYABORT;
         }
       else
-  {
-    YYDSYMPRINTF ("Error: discarding", yytoken, &yylval, &yylloc);
-    yydestruct (yytoken, &yylval);
-    yychar = YYEMPTY;
-
-  }
+        {
+          yydestruct ("Error: discarding",
+                      yytoken, &yylval, yyscanner);
+          yychar = YYEMPTY;
+        }
     }
 
+#if 0
   /* Else will try to reuse lookahead token after shifting the error
      token.  */
   goto yyerrlab1;
@@ -1316,15 +1571,17 @@ yyerrlab:
 `---------------------------------------------------*/
 yyerrorlab:
 
-#if defined( __GNUC__ ) || defined(__HP_aCC)
-  /* Pacify GCC when the user code never invokes YYERROR and the label
-     yyerrorlab therefore never appears in user code.  */
-  if (0)
+  /* Pacify compilers like GCC when the user code never invokes
+     YYERROR and the label yyerrorlab therefore never appears in user
+     code.  */
+  if (/*CONSTCOND*/ 0)
      goto yyerrorlab;
-#endif
 
-  yyvsp -= yylen;
-  yyssp -= yylen;
+  /* Do not reclaim the symbols of the rule whose action triggered
+     this YYERROR.  */
+  YYPOPSTACK (yylen);
+  yylen = 0;
+  YY_STACK_PRINT (yyss, yyssp);
   yystate = *yyssp;
   goto yyerrlab1;
 
@@ -1333,40 +1590,42 @@ yyerrorlab:
 | yyerrlab1 -- common code for both syntax error and YYERROR.  |
 `-------------------------------------------------------------*/
 yyerrlab1:
-  yyerrstatus = 3;  /* Each real token shifted decrements this.  */
+#endif
+  yyerrstatus = 3;      /* Each real token shifted decrements this.  */
 
   for (;;)
     {
       yyn = yypact[yystate];
-      if (yyn != YYPACT_NINF)
-  {
-    yyn += YYTERROR;
-    if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
-      {
-        yyn = yytable[yyn];
-        if (0 < yyn)
-    break;
-      }
-  }
+      if (!yypact_value_is_default (yyn))
+        {
+          yyn += YYTERROR;
+          if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
+            {
+              yyn = yytable[yyn];
+              if (0 < yyn)
+                break;
+            }
+        }
 
       /* Pop the current state because it cannot handle the error token.  */
       if (yyssp == yyss)
-  YYABORT;
+        YYABORT;
 
-      YYDSYMPRINTF ("Error: popping", yystos[*yyssp], yyvsp, yylsp);
-      yydestruct (yystos[yystate], yyvsp);
-      YYPOPSTACK;
+
+      yydestruct ("Error: popping",
+                  yystos[yystate], yyvsp, yyscanner);
+      YYPOPSTACK (1);
       yystate = *yyssp;
       YY_STACK_PRINT (yyss, yyssp);
     }
 
-  if (yyn == YYFINAL)
-    YYACCEPT;
-
-  YYDPRINTF ((stderr, "Shifting error token, "));
-
+  YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
   *++yyvsp = yylval;
+  YY_IGNORE_MAYBE_UNINITIALIZED_END
+
 
+  /* Shift the error token.  */
+  YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
 
   yystate = yyn;
   goto yynewstate;
@@ -1386,33 +1645,52 @@ yyabortlab:
   yyresult = 1;
   goto yyreturn;
 
-#ifndef yyoverflow
-/*----------------------------------------------.
-| yyoverflowlab -- parser overflow comes here.  |
-`----------------------------------------------*/
-yyoverflowlab:
-  yyerror ("parser stack overflow");
+#if !defined yyoverflow || YYERROR_VERBOSE
+/*-------------------------------------------------.
+| yyexhaustedlab -- memory exhaustion comes here.  |
+`-------------------------------------------------*/
+yyexhaustedlab:
+  yyerror (yyscanner, YY_("memory exhausted"));
   yyresult = 2;
   /* Fall through.  */
 #endif
 
 yyreturn:
+  if (yychar != YYEMPTY)
+    {
+      /* Make sure we have latest lookahead translation.  See comments at
+         user semantic actions for why this is necessary.  */
+      yytoken = YYTRANSLATE (yychar);
+      yydestruct ("Cleanup: discarding lookahead",
+                  yytoken, &yylval, yyscanner);
+    }
+  /* Do not reclaim the symbols of the rule whose action triggered
+     this YYABORT or YYACCEPT.  */
+  YYPOPSTACK (yylen);
+  YY_STACK_PRINT (yyss, yyssp);
+  while (yyssp != yyss)
+    {
+      yydestruct ("Cleanup: popping",
+                  yystos[*yyssp], yyvsp, yyscanner);
+      YYPOPSTACK (1);
+    }
 #ifndef yyoverflow
   if (yyss != yyssa)
     YYSTACK_FREE (yyss);
 #endif
+#if YYERROR_VERBOSE
+  if (yymsg != yymsgbuf)
+    YYSTACK_FREE (yymsg);
+#endif
   return yyresult;
 }
-
-
-
+#line 154 "cmExprParser.y" /* yacc.c:1906  */
 
 /* End of grammar */
 
 /*--------------------------------------------------------------------------*/
-void cmExprError(yyscan_t yyscanner, const char* message)
+void cmExpr_yyerror(yyscan_t yyscanner, const char* message)
 {
-  yyGetParser->Error(message);
+  cmExpr_yyget_extra(yyscanner)->Error(message);
 }
 
-
diff --git a/Source/cmExprParser.y b/Source/cmExprParser.y
index a265c20..c7c4a7b 100644
--- a/Source/cmExprParser.y
+++ b/Source/cmExprParser.y
@@ -10,21 +10,12 @@ Run bison like this:
   bison --yacc --name-prefix=cmExpr_yy --defines=cmExprParserTokens.h -ocmExprParser.cxx cmExprParser.y
 
 Modify cmExprParser.cxx:
-  - remove TABs
-  - remove use of the 'register' storage class specifier
-  - add __HP_aCC to the #if test for yyerrorlab warning suppression
+  - "#if 0" out yyerrorlab block in range ["goto yyerrlab1", "yyerrlab1:"]
 
 */
 
-/* Configure the parser to use a lexer object.  */
-#define YYPARSE_PARAM yyscanner
-#define YYLEX_PARAM yyscanner
-#define YYERROR_VERBOSE 1
-#define cmExpr_yyerror(x) \
-        cmExprError(yyscanner, x)
-#define yyGetParser (cmExpr_yyget_extra(yyscanner))
-
 /*-------------------------------------------------------------------------*/
+#define YYDEBUG 1
 #include "cmExprParserHelper.h" /* Interface to parser object.  */
 #include "cmExprLexer.h"  /* Interface to lexer object.  */
 #include "cmExprParserTokens.h" /* Need YYSTYPE for YY_DECL.  */
@@ -34,13 +25,8 @@ Modify cmExprParser.cxx:
 /* Forward declare the lexer entry point.  */
 YY_DECL;
 
-/* Internal utility functions.  */
-static void cmExprError(yyscan_t yyscanner, const char* message);
-
-#define YYDEBUG 1
-//#define YYMAXDEPTH 100000
-//#define YYINITDEPTH 10000
-
+/* Helper function to forward error callback from parser.  */
+static void cmExpr_yyerror(yyscan_t yyscanner, const char* message);
 
 /* Disable some warnings in the generated code.  */
 #ifdef _MSC_VER
@@ -50,7 +36,13 @@ static void cmExprError(yyscan_t yyscanner, const char* message);
 %}
 
 /* Generate a reentrant parser object.  */
-%pure_parser
+%define api.pure
+
+/* Configure the parser to use a lexer object.  */
+%lex-param   {yyscan_t yyscanner}
+%parse-param {yyscan_t yyscanner}
+
+%define parse.error verbose
 
 /*-------------------------------------------------------------------------*/
 /* Tokens */
@@ -74,82 +66,97 @@ static void cmExprError(yyscan_t yyscanner, const char* message);
 %%
 
 
-Start:
-exp
-{
-  yyGetParser->SetResult($<Number>1);
-}
+start:
+  exp {
+    cmExpr_yyget_extra(yyscanner)->SetResult($<Number>1);
+  }
 
 exp:
-bitwiseor
-{$<Number>$ = $<Number>1;}
-|
-exp exp_OR bitwiseor
-{$<Number>$ = $<Number>1 | $<Number>3;}
+  bitwiseor {
+    $<Number>$ = $<Number>1;
+  }
+| exp exp_OR bitwiseor {
+    $<Number>$ = $<Number>1 | $<Number>3;
+  }
 
 bitwiseor:
-bitwisexor
-{$<Number>$ = $<Number>1;}
-|
-bitwiseor exp_XOR bitwisexor
-{$<Number>$ = $<Number>1 ^ $<Number>3;}
+  bitwisexor {
+    $<Number>$ = $<Number>1;
+  }
+| bitwiseor exp_XOR bitwisexor {
+    $<Number>$ = $<Number>1 ^ $<Number>3;
+  }
 
 bitwisexor:
-bitwiseand
-{$<Number>$ = $<Number>1;}
-|
-bitwisexor exp_AND bitwiseand
-{$<Number>$ = $<Number>1 & $<Number>3;}
+  bitwiseand {
+    $<Number>$ = $<Number>1;
+  }
+| bitwisexor exp_AND bitwiseand {
+    $<Number>$ = $<Number>1 & $<Number>3;
+  }
 
 bitwiseand:
-shift
-{$<Number>$ = $<Number>1;}
-|
-bitwiseand exp_SHIFTLEFT shift
-{$<Number>$ = $<Number>1 << $<Number>3;}
-|
-bitwiseand exp_SHIFTRIGHT shift
-{$<Number>$ = $<Number>1 >> $<Number>3;}
-
+  shift {
+    $<Number>$ = $<Number>1;
+  }
+| bitwiseand exp_SHIFTLEFT shift {
+    $<Number>$ = $<Number>1 << $<Number>3;
+  }
+| bitwiseand exp_SHIFTRIGHT shift {
+    $<Number>$ = $<Number>1 >> $<Number>3;
+  }
 
 shift:
-term
-{$<Number>$ = $<Number>1;}
-|
-shift exp_PLUS term
-{$<Number>$ = $<Number>1 + $<Number>3;}
-|
-shift exp_MINUS term
-{$<Number>$ = $<Number>1 - $<Number>3;}
+  term {
+    $<Number>$ = $<Number>1;
+  }
+| shift exp_PLUS term {
+    $<Number>$ = $<Number>1 + $<Number>3;
+  }
+| shift exp_MINUS term {
+    $<Number>$ = $<Number>1 - $<Number>3;
+  }
 
 term:
-factor
-{$<Number>$ = $<Number>1;}
-|
-term exp_TIMES factor
-{$<Number>$ = $<Number>1 * $<Number>3;}
-|
-term exp_DIVIDE factor
-{$<Number>$ = $<Number>1 / $<Number>3;}
-|
-term exp_MOD factor
-{$<Number>$ = $<Number>1 % $<Number>3;}
+  unary {
+    $<Number>$ = $<Number>1;
+  }
+| term exp_TIMES unary {
+    $<Number>$ = $<Number>1 * $<Number>3;
+  }
+| term exp_DIVIDE unary {
+    $<Number>$ = $<Number>1 / $<Number>3;
+  }
+| term exp_MOD unary {
+    $<Number>$ = $<Number>1 % $<Number>3;
+  }
+
+unary:
+  factor {
+    $<Number>$ = $<Number>1;
+  }
+| exp_PLUS unary {
+    $<Number>$ = + $<Number>2;
+  }
+| exp_MINUS unary {
+    $<Number>$ = - $<Number>2;
+  }
 
 factor:
-exp_NUMBER
-{$<Number>$ = $<Number>1;}
-|
-exp_OPENPARENT exp exp_CLOSEPARENT
-{$<Number>$ = $<Number>2;}
+  exp_NUMBER {
+    $<Number>$ = $<Number>1;
+  }
+| exp_OPENPARENT exp exp_CLOSEPARENT {
+    $<Number>$ = $<Number>2;
+  }
 ;
 
-
 %%
 /* End of grammar */
 
 /*--------------------------------------------------------------------------*/
-void cmExprError(yyscan_t yyscanner, const char* message)
+void cmExpr_yyerror(yyscan_t yyscanner, const char* message)
 {
-  yyGetParser->Error(message);
+  cmExpr_yyget_extra(yyscanner)->Error(message);
 }
 
diff --git a/Source/cmExprParserTokens.h b/Source/cmExprParserTokens.h
index 0309c09..84b2bbd 100644
--- a/Source/cmExprParserTokens.h
+++ b/Source/cmExprParserTokens.h
@@ -1,12 +1,13 @@
-/* A Bison parser, made by GNU Bison 1.875d.  */
+/* A Bison parser, made by GNU Bison 3.0.4.  */
 
-/* Skeleton parser for Yacc-like parsing with Bison, Copyright (C) 1984,
-   1989, 1990, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
+/* Bison interface for Yacc-like parsers in C
 
-   This program is free software; you can redistribute it and/or modify
+   Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc.
+
+   This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2, or (at your option)
-   any later version.
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -14,37 +15,53 @@
    GNU General Public License for more details.
 
    You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 59 Temple Place - Suite 330,
-   Boston, MA 02111-1307, USA.  */
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
 
-/* As a special exception, when this file is copied by Bison into a
-   Bison output file, you may use that output file without restriction.
-   This special exception was added by the Free Software Foundation
-   in version 1.24 of Bison.  */
+/* As a special exception, you may create a larger work that contains
+   part or all of the Bison parser skeleton and distribute that work
+   under terms of your choice, so long as that work isn't itself a
+   parser generator using the skeleton or a modified version thereof
+   as a parser skeleton.  Alternatively, if you modify or redistribute
+   the parser skeleton itself, you may (at your option) remove this
+   special exception, which will cause the skeleton and the resulting
+   Bison output files to be licensed under the GNU General Public
+   License without this special exception.
 
-/* Tokens.  */
+   This special exception was added by the Free Software Foundation in
+   version 2.2 of Bison.  */
+
+#ifndef YY_CMEXPR_YY_CMEXPRPARSERTOKENS_H_INCLUDED
+# define YY_CMEXPR_YY_CMEXPRPARSERTOKENS_H_INCLUDED
+/* Debug traces.  */
+#ifndef YYDEBUG
+# define YYDEBUG 0
+#endif
+#if YYDEBUG
+extern int cmExpr_yydebug;
+#endif
+
+/* Token type.  */
 #ifndef YYTOKENTYPE
 # define YYTOKENTYPE
-   /* Put the tokens into the symbol table, so that GDB and other debuggers
-      know about them.  */
-   enum yytokentype {
-     exp_PLUS = 258,
-     exp_MINUS = 259,
-     exp_TIMES = 260,
-     exp_DIVIDE = 261,
-     exp_MOD = 262,
-     exp_SHIFTLEFT = 263,
-     exp_SHIFTRIGHT = 264,
-     exp_OPENPARENT = 265,
-     exp_CLOSEPARENT = 266,
-     exp_OR = 267,
-     exp_AND = 268,
-     exp_XOR = 269,
-     exp_NOT = 270,
-     exp_NUMBER = 271
-   };
+  enum yytokentype
+  {
+    exp_PLUS = 258,
+    exp_MINUS = 259,
+    exp_TIMES = 260,
+    exp_DIVIDE = 261,
+    exp_MOD = 262,
+    exp_SHIFTLEFT = 263,
+    exp_SHIFTRIGHT = 264,
+    exp_OPENPARENT = 265,
+    exp_CLOSEPARENT = 266,
+    exp_OR = 267,
+    exp_AND = 268,
+    exp_XOR = 269,
+    exp_NOT = 270,
+    exp_NUMBER = 271
+  };
 #endif
+/* Tokens.  */
 #define exp_PLUS 258
 #define exp_MINUS 259
 #define exp_TIMES 260
@@ -60,17 +77,10 @@
 #define exp_NOT 270
 #define exp_NUMBER 271
 
+/* Value type.  */
 
 
 
-#if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED)
-typedef int YYSTYPE;
-# define yystype YYSTYPE /* obsolescent; will be withdrawn */
-# define YYSTYPE_IS_DECLARED 1
-# define YYSTYPE_IS_TRIVIAL 1
-#endif
-
-
-
-
+int cmExpr_yyparse (yyscan_t yyscanner);
 
+#endif /* !YY_CMEXPR_YY_CMEXPRPARSERTOKENS_H_INCLUDED  */
diff --git a/Source/cmExtraCodeBlocksGenerator.cxx b/Source/cmExtraCodeBlocksGenerator.cxx
index 18c732d..2dffcaa 100644
--- a/Source/cmExtraCodeBlocksGenerator.cxx
+++ b/Source/cmExtraCodeBlocksGenerator.cxx
@@ -2,6 +2,11 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExtraCodeBlocksGenerator.h"
 
+#include <map>
+#include <ostream>
+#include <string.h>
+#include <utility>
+
 #include "cmAlgorithms.h"
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorTarget.h"
@@ -9,17 +14,11 @@
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmXMLWriter.h"
 #include "cmake.h"
 
-#include <algorithm>
-#include <map>
-#include <ostream>
-#include <string.h>
-#include <utility>
-
 /* Some useful URLs:
 Homepage:
 http://www.codeblocks.org
@@ -49,6 +48,7 @@ cmExtraCodeBlocksGenerator::GetFactory()
 #if defined(_WIN32)
     factory.AddSupportedGlobalGenerator("MinGW Makefiles");
     factory.AddSupportedGlobalGenerator("NMake Makefiles");
+    factory.AddSupportedGlobalGenerator("NMake Makefiles JOM");
 // disable until somebody actually tests it:
 // this->AddSupportedGlobalGenerator("MSYS Makefiles");
 #endif
@@ -138,7 +138,6 @@ void Tree::InsertPath(const std::vector<std::string>& splitted,
   // last part of splitted
   newFolder.files.push_back(fileName);
   folders.push_back(newFolder);
-  return;
 }
 
 void Tree::BuildVirtualFolder(cmXMLWriter& xml) const
@@ -302,7 +301,7 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
          ti != targets.end(); ti++) {
       std::string targetName = (*ti)->GetName();
       switch ((*ti)->GetType()) {
-        case cmState::GLOBAL_TARGET: {
+        case cmStateEnums::GLOBAL_TARGET: {
           // Only add the global targets from CMAKE_BINARY_DIR,
           // not from the subdirs
           if (strcmp((*lg)->GetCurrentBinaryDirectory(),
@@ -311,7 +310,7 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
                                compiler.c_str(), makeArgs);
           }
         } break;
-        case cmState::UTILITY:
+        case cmStateEnums::UTILITY:
           // Add all utility targets, except the Nightly/Continuous/
           // Experimental-"sub"targets as e.g. NightlyStart
           if (((targetName.find("Nightly") == 0) &&
@@ -326,11 +325,11 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
           this->AppendTarget(xml, targetName, CM_NULLPTR, make.c_str(), *lg,
                              compiler.c_str(), makeArgs);
           break;
-        case cmState::EXECUTABLE:
-        case cmState::STATIC_LIBRARY:
-        case cmState::SHARED_LIBRARY:
-        case cmState::MODULE_LIBRARY:
-        case cmState::OBJECT_LIBRARY: {
+        case cmStateEnums::EXECUTABLE:
+        case cmStateEnums::STATIC_LIBRARY:
+        case cmStateEnums::SHARED_LIBRARY:
+        case cmStateEnums::MODULE_LIBRARY:
+        case cmStateEnums::OBJECT_LIBRARY: {
           cmGeneratorTarget* gt = *ti;
           this->AppendTarget(xml, targetName, gt, make.c_str(), *lg,
                              compiler.c_str(), makeArgs);
@@ -364,12 +363,12 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
     for (std::vector<cmGeneratorTarget*>::iterator ti = targets.begin();
          ti != targets.end(); ti++) {
       switch ((*ti)->GetType()) {
-        case cmState::EXECUTABLE:
-        case cmState::STATIC_LIBRARY:
-        case cmState::SHARED_LIBRARY:
-        case cmState::MODULE_LIBRARY:
-        case cmState::OBJECT_LIBRARY:
-        case cmState::UTILITY: // can have sources since 2.6.3
+        case cmStateEnums::EXECUTABLE:
+        case cmStateEnums::STATIC_LIBRARY:
+        case cmStateEnums::SHARED_LIBRARY:
+        case cmStateEnums::MODULE_LIBRARY:
+        case cmStateEnums::OBJECT_LIBRARY:
+        case cmStateEnums::UTILITY: // can have sources since 2.6.3
         {
           std::vector<cmSourceFile*> sources;
           cmGeneratorTarget* gt = *ti;
@@ -379,7 +378,7 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
                si != sources.end(); si++) {
             // don't add source files from UTILITY target which have the
             // GENERATED property set:
-            if (gt->GetType() == cmState::UTILITY &&
+            if (gt->GetType() == cmStateEnums::UTILITY &&
                 (*si)->GetPropertyAsBool("GENERATED")) {
               continue;
             }
@@ -519,7 +518,7 @@ void cmExtraCodeBlocksGenerator::AppendTarget(
   if (target != CM_NULLPTR) {
     int cbTargetType = this->GetCBTargetType(target);
     std::string workingDir = lg->GetCurrentBinaryDirectory();
-    if (target->GetType() == cmState::EXECUTABLE) {
+    if (target->GetType() == cmStateEnums::EXECUTABLE) {
       // Determine the directory where the executable target is created, and
       // set the working directory to this dir.
       const char* runtimeOutputDir =
@@ -537,7 +536,7 @@ void cmExtraCodeBlocksGenerator::AppendTarget(
 
     std::string buildType = makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
     std::string location;
-    if (target->GetType() == cmState::OBJECT_LIBRARY) {
+    if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
       location =
         this->CreateDummyTargetFile(const_cast<cmLocalGenerator*>(lg), target);
     } else {
@@ -713,17 +712,17 @@ std::string cmExtraCodeBlocksGenerator::GetCBCompilerId(const cmMakefile* mf)
 int cmExtraCodeBlocksGenerator::GetCBTargetType(cmGeneratorTarget* target)
 {
   switch (target->GetType()) {
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       if ((target->GetPropertyAsBool("WIN32_EXECUTABLE")) ||
           (target->GetPropertyAsBool("MACOSX_BUNDLE"))) {
         return 0;
       }
       return 1;
-    case cmState::STATIC_LIBRARY:
-    case cmState::OBJECT_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
+    case cmStateEnums::OBJECT_LIBRARY:
       return 2;
-    case cmState::SHARED_LIBRARY:
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       return 3;
     default:
       return 4;
@@ -743,7 +742,7 @@ std::string cmExtraCodeBlocksGenerator::BuildMakeCommand(
   }
 
   std::string generator = this->GlobalGenerator->GetName();
-  if (generator == "NMake Makefiles") {
+  if (generator == "NMake Makefiles" || generator == "NMake Makefiles JOM") {
     // For Windows ConvertToOutputPath already adds quotes when required.
     // These need to be escaped, see
     // https://gitlab.kitware.com/cmake/cmake/issues/13952
diff --git a/Source/cmExtraCodeLiteGenerator.cxx b/Source/cmExtraCodeLiteGenerator.cxx
index 360c852..fd7da18 100644
--- a/Source/cmExtraCodeLiteGenerator.cxx
+++ b/Source/cmExtraCodeLiteGenerator.cxx
@@ -8,7 +8,7 @@
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmXMLWriter.h"
 #include "cmake.h"
@@ -127,20 +127,21 @@ std::vector<std::string> cmExtraCodeLiteGenerator::CreateProjectsByTarget(
     for (std::vector<cmGeneratorTarget*>::const_iterator lt =
            (*lg)->GetGeneratorTargets().begin();
          lt != (*lg)->GetGeneratorTargets().end(); lt++) {
-      cmState::TargetType type = (*lt)->GetType();
+      cmStateEnums::TargetType type = (*lt)->GetType();
       std::string outputDir = (*lg)->GetCurrentBinaryDirectory();
-      std::string filename = outputDir + "/" + (*lt)->GetName() + ".project";
-      retval.push_back((*lt)->GetName());
+      std::string targetName = (*lt)->GetName();
+      std::string filename = outputDir + "/" + targetName + ".project";
+      retval.push_back(targetName);
       // Make the project file relative to the workspace
       std::string relafilename = cmSystemTools::RelativePath(
         this->WorkspacePath.c_str(), filename.c_str());
-      std::string visualname = (*lt)->GetName();
+      std::string visualname = targetName;
       switch (type) {
-        case cmState::SHARED_LIBRARY:
-        case cmState::STATIC_LIBRARY:
-        case cmState::MODULE_LIBRARY:
+        case cmStateEnums::SHARED_LIBRARY:
+        case cmStateEnums::STATIC_LIBRARY:
+        case cmStateEnums::MODULE_LIBRARY:
           visualname = "lib" + visualname;
-        case cmState::EXECUTABLE:
+        case cmStateEnums::EXECUTABLE:
           xml->StartElement("Project");
           xml->Attribute("Name", visualname);
           xml->Attribute("Path", relafilename);
@@ -209,16 +210,16 @@ std::string cmExtraCodeLiteGenerator::CollectSourceFiles(
 
   std::string projectType;
   switch (gt->GetType()) {
-    case cmState::EXECUTABLE: {
+    case cmStateEnums::EXECUTABLE: {
       projectType = "Executable";
     } break;
-    case cmState::STATIC_LIBRARY: {
+    case cmStateEnums::STATIC_LIBRARY: {
       projectType = "Static Library";
     } break;
-    case cmState::SHARED_LIBRARY: {
+    case cmStateEnums::SHARED_LIBRARY: {
       projectType = "Dynamic Library";
     } break;
-    case cmState::MODULE_LIBRARY: {
+    case cmStateEnums::MODULE_LIBRARY: {
       projectType = "Dynamic Library";
     } break;
     default: // intended fallthrough
@@ -226,10 +227,10 @@ std::string cmExtraCodeLiteGenerator::CollectSourceFiles(
   }
 
   switch (gt->GetType()) {
-    case cmState::EXECUTABLE:
-    case cmState::STATIC_LIBRARY:
-    case cmState::SHARED_LIBRARY:
-    case cmState::MODULE_LIBRARY: {
+    case cmStateEnums::EXECUTABLE:
+    case cmStateEnums::STATIC_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY: {
       std::vector<cmSourceFile*> sources;
       gt->GetSourceFiles(sources,
                          makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
@@ -302,7 +303,7 @@ void cmExtraCodeLiteGenerator::CreateNewProjectFile(
   std::string projectPath = cmSystemTools::GetFilenamePath(filename);
 
   CreateProjectSourceEntries(cFiles, otherFiles, &xml, projectPath, mf,
-                             projectType);
+                             projectType, "");
 
   xml.EndElement(); // CodeLite_Project
 }
@@ -352,7 +353,7 @@ void cmExtraCodeLiteGenerator::CreateProjectSourceEntries(
   std::map<std::string, cmSourceFile*>& cFiles,
   std::set<std::string>& otherFiles, cmXMLWriter* _xml,
   const std::string& projectPath, const cmMakefile* mf,
-  const std::string& projectType)
+  const std::string& projectType, const std::string& targetName)
 {
 
   cmXMLWriter& xml(*_xml);
@@ -430,17 +431,22 @@ void cmExtraCodeLiteGenerator::CreateProjectSourceEntries(
 
   xml.StartElement("General");
   std::string outputPath = mf->GetSafeDefinition("EXECUTABLE_OUTPUT_PATH");
-  if (!outputPath.empty())
-    xml.Attribute("OutputFile", outputPath + "/$(ProjectName)");
-  else
+  std::string relapath;
+  if (!outputPath.empty()) {
+    relapath = cmSystemTools::RelativePath(this->WorkspacePath.c_str(),
+                                           outputPath.c_str());
+    xml.Attribute("OutputFile", relapath + "/$(ProjectName)");
+  } else {
     xml.Attribute("OutputFile", "$(IntermediateDirectory)/$(ProjectName)");
+  }
   xml.Attribute("IntermediateDirectory", "./");
   xml.Attribute("Command", "./$(ProjectName)");
   xml.Attribute("CommandArguments", "");
-  if (!outputPath.empty())
-    xml.Attribute("WorkingDirectory", outputPath);
-  else
+  if (!outputPath.empty()) {
+    xml.Attribute("WorkingDirectory", relapath);
+  } else {
     xml.Attribute("WorkingDirectory", "$(IntermediateDirectory)");
+  }
   xml.Attribute("PauseExecWhenProcTerminates", "yes");
   xml.EndElement(); // General
 
@@ -458,9 +464,9 @@ void cmExtraCodeLiteGenerator::CreateProjectSourceEntries(
 
   xml.StartElement("CustomBuild");
   xml.Attribute("Enabled", "yes");
-  xml.Element("RebuildCommand", GetRebuildCommand(mf));
-  xml.Element("CleanCommand", GetCleanCommand(mf));
-  xml.Element("BuildCommand", GetBuildCommand(mf));
+  xml.Element("RebuildCommand", GetRebuildCommand(mf, targetName));
+  xml.Element("CleanCommand", GetCleanCommand(mf, targetName));
+  xml.Element("BuildCommand", GetBuildCommand(mf, targetName));
   xml.Element("SingleFileCommand", GetSingleFileBuildCommand(mf));
   xml.Element("PreprocessFileCommand");
   xml.Element("WorkingDirectory", "$(WorkspacePath)");
@@ -509,12 +515,13 @@ void cmExtraCodeLiteGenerator::CreateNewProjectFile(
   ////////////////////////////////////
   xml.StartDocument("utf-8");
   xml.StartElement("CodeLite_Project");
-  std::string visualname = gt->GetName();
+  std::string targetName = gt->GetName();
+  std::string visualname = targetName;
   switch (gt->GetType()) {
-    case cmState::STATIC_LIBRARY:
-    case cmState::SHARED_LIBRARY:
-    case cmState::MODULE_LIBRARY:
-      visualname = "lib" + visualname;
+    case cmStateEnums::STATIC_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
+      visualname = "lib" + targetName;
     default: // intended fallthrough
       break;
   }
@@ -539,7 +546,7 @@ void cmExtraCodeLiteGenerator::CreateNewProjectFile(
   std::string projectPath = cmSystemTools::GetFilenamePath(filename);
 
   CreateProjectSourceEntries(cFiles, otherFiles, &xml, projectPath, mf,
-                             projectType);
+                             projectType, targetName);
 
   xml.EndElement(); // CodeLite_Project
 }
@@ -584,31 +591,43 @@ std::string cmExtraCodeLiteGenerator::GetConfigurationName(
 }
 
 std::string cmExtraCodeLiteGenerator::GetBuildCommand(
-  const cmMakefile* mf) const
+  const cmMakefile* mf, const std::string& targetName) const
 {
   std::string generator = mf->GetSafeDefinition("CMAKE_GENERATOR");
   std::string make = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM");
   std::string buildCommand = make; // Default
+  std::ostringstream ss;
   if (generator == "NMake Makefiles" || generator == "Ninja") {
-    buildCommand = make;
+    ss << make;
   } else if (generator == "MinGW Makefiles" || generator == "Unix Makefiles") {
-    std::ostringstream ss;
     ss << make << " -j " << this->CpuCount;
-    buildCommand = ss.str();
   }
+  if (!targetName.empty()) {
+    ss << " " << targetName;
+  }
+  buildCommand = ss.str();
   return buildCommand;
 }
 
 std::string cmExtraCodeLiteGenerator::GetCleanCommand(
-  const cmMakefile* mf) const
+  const cmMakefile* mf, const std::string& targetName) const
 {
-  return GetBuildCommand(mf) + " clean";
+  std::string generator = mf->GetSafeDefinition("CMAKE_GENERATOR");
+  std::ostringstream ss;
+  std::string buildcommand = GetBuildCommand(mf, "");
+  if (!targetName.empty() && generator == "Ninja") {
+    ss << buildcommand << " -t clean " << targetName;
+  } else {
+    ss << buildcommand << " clean";
+  }
+  return ss.str();
 }
 
 std::string cmExtraCodeLiteGenerator::GetRebuildCommand(
-  const cmMakefile* mf) const
+  const cmMakefile* mf, const std::string& targetName) const
 {
-  return GetCleanCommand(mf) + " && " + GetBuildCommand(mf);
+  return GetCleanCommand(mf, targetName) + " && " +
+    GetBuildCommand(mf, targetName);
 }
 
 std::string cmExtraCodeLiteGenerator::GetSingleFileBuildCommand(
diff --git a/Source/cmExtraCodeLiteGenerator.h b/Source/cmExtraCodeLiteGenerator.h
index a349db5..773515d 100644
--- a/Source/cmExtraCodeLiteGenerator.h
+++ b/Source/cmExtraCodeLiteGenerator.h
@@ -28,9 +28,12 @@ protected:
 protected:
   std::string GetCodeLiteCompilerName(const cmMakefile* mf) const;
   std::string GetConfigurationName(const cmMakefile* mf) const;
-  std::string GetBuildCommand(const cmMakefile* mf) const;
-  std::string GetCleanCommand(const cmMakefile* mf) const;
-  std::string GetRebuildCommand(const cmMakefile* mf) const;
+  std::string GetBuildCommand(const cmMakefile* mf,
+                              const std::string& targetName) const;
+  std::string GetCleanCommand(const cmMakefile* mf,
+                              const std::string& targetName) const;
+  std::string GetRebuildCommand(const cmMakefile* mf,
+                                const std::string& targetName) const;
   std::string GetSingleFileBuildCommand(const cmMakefile* mf) const;
   std::vector<std::string> CreateProjectsByTarget(cmXMLWriter* xml);
   std::vector<std::string> CreateProjectsByProjectMaps(cmXMLWriter* xml);
@@ -45,7 +48,8 @@ protected:
                                   cmXMLWriter* xml,
                                   const std::string& projectPath,
                                   const cmMakefile* mf,
-                                  const std::string& projectType);
+                                  const std::string& projectType,
+                                  const std::string& targetName);
 
 public:
   cmExtraCodeLiteGenerator();
diff --git a/Source/cmExtraEclipseCDT4Generator.cxx b/Source/cmExtraEclipseCDT4Generator.cxx
index e342f4c..b4fc771 100644
--- a/Source/cmExtraEclipseCDT4Generator.cxx
+++ b/Source/cmExtraEclipseCDT4Generator.cxx
@@ -2,28 +2,28 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExtraEclipseCDT4Generator.h"
 
+#include <algorithm>
+#include <assert.h>
+#include <cmsys/RegularExpression.hxx>
+#include <map>
+#include <sstream>
+#include <stdio.h>
+#include <utility>
+
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorExpression.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
-#include "cmOutputConverter.h"
 #include "cmSourceFile.h"
 #include "cmSourceGroup.h"
 #include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmXMLWriter.h"
 #include "cmake.h"
 
-#include <algorithm>
-#include <assert.h>
-#include <cmsys/RegularExpression.hxx>
-#include <map>
-#include <sstream>
-#include <stdio.h>
-#include <utility>
-
 static void AppendAttribute(cmXMLWriter& xml, const char* keyval)
 {
   xml.StartElement("attribute");
@@ -230,7 +230,7 @@ void cmExtraEclipseCDT4Generator::AddEnvVar(std::ostream& out,
     // in the cache
     valueToUse = envVarValue;
     mf->AddCacheDefinition(cacheEntryName, valueToUse.c_str(),
-                           cacheEntryName.c_str(), cmState::STRING, true);
+                           cacheEntryName.c_str(), cmStateEnums::STRING, true);
     mf->GetCMakeInstance()->SaveCache(lg->GetBinaryDirectory());
   } else if (!envVarSet && cacheValue != CM_NULLPTR) {
     // It is already in the cache, but not in the env, so use it from the cache
@@ -245,7 +245,8 @@ void cmExtraEclipseCDT4Generator::AddEnvVar(std::ostream& out,
     if (valueToUse.find(envVarValue) == std::string::npos) {
       valueToUse = envVarValue;
       mf->AddCacheDefinition(cacheEntryName, valueToUse.c_str(),
-                             cacheEntryName.c_str(), cmState::STRING, true);
+                             cacheEntryName.c_str(), cmStateEnums::STRING,
+                             true);
       mf->GetCMakeInstance()->SaveCache(lg->GetBinaryDirectory());
     }
   }
@@ -482,13 +483,14 @@ void cmExtraEclipseCDT4Generator::CreateLinksForTargets(cmXMLWriter& xml)
       std::string linkName2 = linkName;
       linkName2 += "/";
       switch ((*ti)->GetType()) {
-        case cmState::EXECUTABLE:
-        case cmState::STATIC_LIBRARY:
-        case cmState::SHARED_LIBRARY:
-        case cmState::MODULE_LIBRARY:
-        case cmState::OBJECT_LIBRARY: {
+        case cmStateEnums::EXECUTABLE:
+        case cmStateEnums::STATIC_LIBRARY:
+        case cmStateEnums::SHARED_LIBRARY:
+        case cmStateEnums::MODULE_LIBRARY:
+        case cmStateEnums::OBJECT_LIBRARY: {
           const char* prefix =
-            ((*ti)->GetType() == cmState::EXECUTABLE ? "[exe] " : "[lib] ");
+            ((*ti)->GetType() == cmStateEnums::EXECUTABLE ? "[exe] "
+                                                          : "[lib] ");
           linkName2 += prefix;
           linkName2 += (*ti)->GetName();
           this->AppendLinkedResource(xml, linkName2, "virtual:/virtual",
@@ -701,6 +703,14 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const
    * Also on the cdt-dev list didn't bring any information:
    * http://web.archiveorange.com/archive/v/B4NlJDNIpYoOS1SbxFNy
    * Alex */
+  // include subprojects directory to the src pathentry
+  // eclipse cdt indexer uses this entries as reference to index source files
+  if (this->GenerateLinkedResources) {
+    xml.StartElement("pathentry");
+    xml.Attribute("kind", "src");
+    xml.Attribute("path", "[Subprojects]");
+    xml.EndElement();
+  }
 
   for (std::vector<std::string>::const_iterator it =
          this->SrcLinkedResources.begin();
@@ -912,14 +922,14 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const
          ti != targets.end(); ++ti) {
       std::string targetName = (*ti)->GetName();
       switch ((*ti)->GetType()) {
-        case cmState::GLOBAL_TARGET: {
+        case cmStateEnums::GLOBAL_TARGET: {
           // Only add the global targets from CMAKE_BINARY_DIR,
           // not from the subdirs
           if (subdir.empty()) {
             this->AppendTarget(xml, targetName, make, makeArgs, subdir, ": ");
           }
         } break;
-        case cmState::UTILITY:
+        case cmStateEnums::UTILITY:
           // Add all utility targets, except the Nightly/Continuous/
           // Experimental-"sub"targets as e.g. NightlyStart
           if (((targetName.find("Nightly") == 0) &&
@@ -933,13 +943,14 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const
 
           this->AppendTarget(xml, targetName, make, makeArgs, subdir, ": ");
           break;
-        case cmState::EXECUTABLE:
-        case cmState::STATIC_LIBRARY:
-        case cmState::SHARED_LIBRARY:
-        case cmState::MODULE_LIBRARY:
-        case cmState::OBJECT_LIBRARY: {
+        case cmStateEnums::EXECUTABLE:
+        case cmStateEnums::STATIC_LIBRARY:
+        case cmStateEnums::SHARED_LIBRARY:
+        case cmStateEnums::MODULE_LIBRARY:
+        case cmStateEnums::OBJECT_LIBRARY: {
           const char* prefix =
-            ((*ti)->GetType() == cmState::EXECUTABLE ? "[exe] " : "[lib] ");
+            ((*ti)->GetType() == cmStateEnums::EXECUTABLE ? "[exe] "
+                                                          : "[lib] ");
           this->AppendTarget(xml, targetName, make, makeArgs, subdir, prefix);
           std::string fastTarget = targetName;
           fastTarget += "/fast";
diff --git a/Source/cmExtraKateGenerator.cxx b/Source/cmExtraKateGenerator.cxx
index b78d09a..3730433 100644
--- a/Source/cmExtraKateGenerator.cxx
+++ b/Source/cmExtraKateGenerator.cxx
@@ -8,7 +8,7 @@
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 
 #include <ostream>
@@ -124,7 +124,7 @@ void cmExtraKateGenerator::WriteTargets(const cmLocalGenerator* lg,
          ti != targets.end(); ++ti) {
       std::string targetName = (*ti)->GetName();
       switch ((*ti)->GetType()) {
-        case cmState::GLOBAL_TARGET: {
+        case cmStateEnums::GLOBAL_TARGET: {
           bool insertTarget = false;
           // Only add the global targets from CMAKE_BINARY_DIR,
           // not from the subdirs
@@ -147,7 +147,7 @@ void cmExtraKateGenerator::WriteTargets(const cmLocalGenerator* lg,
                                homeOutputDir);
           }
         } break;
-        case cmState::UTILITY:
+        case cmStateEnums::UTILITY:
           // Add all utility targets, except the Nightly/Continuous/
           // Experimental-"sub"targets as e.g. NightlyStart
           if (((targetName.find("Nightly") == 0) &&
@@ -162,11 +162,11 @@ void cmExtraKateGenerator::WriteTargets(const cmLocalGenerator* lg,
           this->AppendTarget(fout, targetName, make, makeArgs, currentDir,
                              homeOutputDir);
           break;
-        case cmState::EXECUTABLE:
-        case cmState::STATIC_LIBRARY:
-        case cmState::SHARED_LIBRARY:
-        case cmState::MODULE_LIBRARY:
-        case cmState::OBJECT_LIBRARY: {
+        case cmStateEnums::EXECUTABLE:
+        case cmStateEnums::STATIC_LIBRARY:
+        case cmStateEnums::SHARED_LIBRARY:
+        case cmStateEnums::MODULE_LIBRARY:
+        case cmStateEnums::OBJECT_LIBRARY: {
           this->AppendTarget(fout, targetName, make, makeArgs, currentDir,
                              homeOutputDir);
           std::string fastTarget = targetName;
diff --git a/Source/cmExtraSublimeTextGenerator.cxx b/Source/cmExtraSublimeTextGenerator.cxx
index 5ae969b..36ba520 100644
--- a/Source/cmExtraSublimeTextGenerator.cxx
+++ b/Source/cmExtraSublimeTextGenerator.cxx
@@ -2,20 +2,22 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmExtraSublimeTextGenerator.h"
 
+#include <cmsys/RegularExpression.hxx>
+#include <set>
+#include <sstream>
+#include <string.h>
+#include <utility>
+
 #include "cmGeneratedFileStream.h"
+#include "cmGeneratorExpression.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
-
-#include <cmsys/RegularExpression.hxx>
-#include <ostream>
-#include <set>
-#include <string.h>
-#include <utility>
+#include "cmake.h"
 
 /*
 Sublime Text 2 Generator
@@ -55,10 +57,16 @@ cmExtraSublimeTextGenerator::GetFactory()
 cmExtraSublimeTextGenerator::cmExtraSublimeTextGenerator()
   : cmExternalMakefileProjectGenerator()
 {
+  this->ExcludeBuildFolder = false;
 }
 
 void cmExtraSublimeTextGenerator::Generate()
 {
+  this->ExcludeBuildFolder = this->GlobalGenerator->GlobalSettingIsOn(
+    "CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE");
+  this->EnvSettings = this->GlobalGenerator->GetSafeGlobalSetting(
+    "CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS");
+
   // for each sub project in the project create a sublime text 2 project
   for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator
          it = this->GlobalGenerator->GetProjectMap().begin();
@@ -84,6 +92,7 @@ void cmExtraSublimeTextGenerator::CreateNewProjectFile(
   const std::vector<cmLocalGenerator*>& lgs, const std::string& filename)
 {
   const cmMakefile* mf = lgs[0]->GetMakefile();
+
   cmGeneratedFileStream fout(filename.c_str());
   if (!fout) {
     return;
@@ -102,8 +111,10 @@ void cmExtraSublimeTextGenerator::CreateNewProjectFile(
     if ((!outputRelativeToSourceRoot.empty()) &&
         ((outputRelativeToSourceRoot.length() < 3) ||
          (outputRelativeToSourceRoot.substr(0, 3) != "../"))) {
-      fout << ",\n\t\t\t\"folder_exclude_patterns\": [\""
-           << outputRelativeToSourceRoot << "\"]";
+      if (this->ExcludeBuildFolder) {
+        fout << ",\n\t\t\t\"folder_exclude_patterns\": [\""
+             << outputRelativeToSourceRoot << "\"]";
+      }
     }
   } else {
     fout << "\t{\n\t\t\t\"path\": \"./\"";
@@ -123,7 +134,37 @@ void cmExtraSublimeTextGenerator::CreateNewProjectFile(
 
   // End of build_systems
   fout << "\n\t]";
-  fout << "\n\t}";
+  std::string systemName = mf->GetSafeDefinition("CMAKE_SYSTEM_NAME");
+  std::vector<std::string> tokens;
+  cmSystemTools::ExpandListArgument(this->EnvSettings, tokens);
+
+  if (!this->EnvSettings.empty()) {
+    fout << ",";
+    fout << "\n\t\"env\":";
+    fout << "\n\t{";
+    fout << "\n\t\t" << systemName << ":";
+    fout << "\n\t\t{";
+    for (std::vector<std::string>::iterator i = tokens.begin();
+         i != tokens.end(); ++i) {
+      size_t const pos = i->find_first_of('=');
+
+      if (pos != std::string::npos) {
+        std::string varName = i->substr(0, pos);
+        std::string varValue = i->substr(pos + 1);
+
+        fout << "\n\t\t\t\"" << varName << "\":\"" << varValue << "\"";
+      } else {
+        std::ostringstream e;
+        e << "Could not parse Env Vars specified in "
+             "\"CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS\""
+          << ", corrupted string " << *i;
+        mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+      }
+    }
+    fout << "\n\t\t}";
+    fout << "\n\t}";
+  }
+  fout << "\n}";
 }
 
 void cmExtraSublimeTextGenerator::AppendAllTargets(
@@ -131,7 +172,7 @@ void cmExtraSublimeTextGenerator::AppendAllTargets(
   cmGeneratedFileStream& fout, MapSourceFileFlags& sourceFileFlags)
 {
   std::string make = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM");
-  std::string compiler = "";
+  std::string compiler;
   if (!lgs.empty()) {
     this->AppendTarget(fout, "all", lgs[0], CM_NULLPTR, make.c_str(), mf,
                        compiler.c_str(), sourceFileFlags, true);
@@ -149,7 +190,7 @@ void cmExtraSublimeTextGenerator::AppendAllTargets(
          ti != targets.end(); ti++) {
       std::string targetName = (*ti)->GetName();
       switch ((*ti)->GetType()) {
-        case cmState::GLOBAL_TARGET: {
+        case cmStateEnums::GLOBAL_TARGET: {
           // Only add the global targets from CMAKE_BINARY_DIR,
           // not from the subdirs
           if (strcmp((*lg)->GetCurrentBinaryDirectory(),
@@ -159,7 +200,7 @@ void cmExtraSublimeTextGenerator::AppendAllTargets(
                                false);
           }
         } break;
-        case cmState::UTILITY:
+        case cmStateEnums::UTILITY:
           // Add all utility targets, except the Nightly/Continuous/
           // Experimental-"sub"targets as e.g. NightlyStart
           if (((targetName.find("Nightly") == 0) &&
@@ -175,11 +216,11 @@ void cmExtraSublimeTextGenerator::AppendAllTargets(
                              makefile, compiler.c_str(), sourceFileFlags,
                              false);
           break;
-        case cmState::EXECUTABLE:
-        case cmState::STATIC_LIBRARY:
-        case cmState::SHARED_LIBRARY:
-        case cmState::MODULE_LIBRARY:
-        case cmState::OBJECT_LIBRARY: {
+        case cmStateEnums::EXECUTABLE:
+        case cmStateEnums::STATIC_LIBRARY:
+        case cmStateEnums::SHARED_LIBRARY:
+        case cmStateEnums::MODULE_LIBRARY:
+        case cmStateEnums::OBJECT_LIBRARY: {
           this->AppendTarget(fout, targetName, *lg, *ti, make.c_str(),
                              makefile, compiler.c_str(), sourceFileFlags,
                              false);
@@ -264,7 +305,9 @@ void cmExtraSublimeTextGenerator::AppendTarget(
        << this->BuildMakeCommand(make, makefileName.c_str(), targetName)
        << "],\n";
   fout << "\t\t\t\"working_dir\": \"${project_path}\",\n";
-  fout << "\t\t\t\"file_regex\": \"^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$\"\n";
+  fout << "\t\t\t\"file_regex\": \""
+          "^(..[^:]*)(?::|\\\\()([0-9]+)(?::|\\\\))(?:([0-9]+):)?\\\\s*(.*)"
+          "\"\n";
   fout << "\t\t}";
 }
 
@@ -280,16 +323,12 @@ std::string cmExtraSublimeTextGenerator::BuildMakeCommand(
     std::string makefileName = cmSystemTools::ConvertToOutputPath(makefile);
     command += ", \"/NOLOGO\", \"/f\", \"";
     command += makefileName + "\"";
-    command += ", \"VERBOSE=1\", \"";
-    command += target;
-    command += "\"";
+    command += ", \"" + target + "\"";
   } else if (generator == "Ninja") {
     std::string makefileName = cmSystemTools::ConvertToOutputPath(makefile);
     command += ", \"-f\", \"";
     command += makefileName + "\"";
-    command += ", \"-v\", \"";
-    command += target;
-    command += "\"";
+    command += ", \"" + target + "\"";
   } else {
     std::string makefileName;
     if (generator == "MinGW Makefiles") {
@@ -301,9 +340,7 @@ std::string cmExtraSublimeTextGenerator::BuildMakeCommand(
     }
     command += ", \"-f\", \"";
     command += makefileName + "\"";
-    command += ", \"VERBOSE=1\", \"";
-    command += target;
-    command += "\"";
+    command += ", \"" + target + "\"";
   }
   return command;
 }
@@ -332,7 +369,11 @@ std::string cmExtraSublimeTextGenerator::ComputeFlagsForObject(
   }
 
   // Add source file specific flags.
-  lg->AppendFlags(flags, source->GetProperty("COMPILE_FLAGS"));
+  if (const char* cflags = source->GetProperty("COMPILE_FLAGS")) {
+    cmGeneratorExpression ge;
+    const char* processed = ge.Parse(cflags)->Evaluate(lg, config);
+    lg->AppendFlags(flags, processed);
+  }
 
   return flags;
 }
diff --git a/Source/cmExtraSublimeTextGenerator.h b/Source/cmExtraSublimeTextGenerator.h
index c917992..a860d34 100644
--- a/Source/cmExtraSublimeTextGenerator.h
+++ b/Source/cmExtraSublimeTextGenerator.h
@@ -64,6 +64,9 @@ private:
 
   std::string ComputeDefines(cmSourceFile* source, cmLocalGenerator* lg,
                              cmGeneratorTarget* gtgt);
+
+  bool ExcludeBuildFolder;
+  std::string EnvSettings;
 };
 
 #endif
diff --git a/Source/cmFLTKWrapUICommand.cxx b/Source/cmFLTKWrapUICommand.cxx
index 5f621f1..ff78f52 100644
--- a/Source/cmFLTKWrapUICommand.cxx
+++ b/Source/cmFLTKWrapUICommand.cxx
@@ -2,7 +2,15 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFLTKWrapUICommand.h"
 
+#include <stddef.h>
+
+#include "cmCustomCommandLines.h"
+#include "cmMakefile.h"
 #include "cmSourceFile.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+class cmTarget;
 
 // cmFLTKWrapUICommand
 bool cmFLTKWrapUICommand::InitialPass(std::vector<std::string> const& args,
@@ -63,7 +71,7 @@ bool cmFLTKWrapUICommand::InitialPass(std::vector<std::string> const& args,
       commandLines.push_back(commandLine);
 
       // Add command for generating the .h and .cxx files
-      std::string no_main_dependency = "";
+      std::string no_main_dependency;
       const char* no_comment = CM_NULLPTR;
       const char* no_working_dir = CM_NULLPTR;
       this->Makefile->AddCustomCommandToOutput(
@@ -74,8 +82,8 @@ bool cmFLTKWrapUICommand::InitialPass(std::vector<std::string> const& args,
         no_working_dir);
 
       cmSourceFile* sf = this->Makefile->GetSource(cxxres);
-      sf->AddDepend(hname.c_str());
-      sf->AddDepend(origname.c_str());
+      sf->AddDepend(hname);
+      sf->AddDepend(origname);
       this->GeneratedSourcesClasses.push_back(sf);
     }
   }
diff --git a/Source/cmFLTKWrapUICommand.h b/Source/cmFLTKWrapUICommand.h
index 202067f..835f0a7 100644
--- a/Source/cmFLTKWrapUICommand.h
+++ b/Source/cmFLTKWrapUICommand.h
@@ -3,8 +3,15 @@
 #ifndef cmFLTKWrapUICommand_h
 #define cmFLTKWrapUICommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+class cmSourceFile;
+
 /** \class cmFLTKWrapUICommand
  * \brief Create .h and .cxx files rules for FLTK user interfaces files
  *
@@ -14,8 +21,6 @@
 class cmFLTKWrapUICommand : public cmCommand
 {
 public:
-  cmTypeMacro(cmFLTKWrapUICommand, cmCommand);
-
   /**
    * This is a virtual constructor for the command.
    */
diff --git a/Source/cmFileCommand.cxx b/Source/cmFileCommand.cxx
index a71ff71..91cecb3 100644
--- a/Source/cmFileCommand.cxx
+++ b/Source/cmFileCommand.cxx
@@ -2,35 +2,47 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFileCommand.h"
 
+#include <algorithm>
+#include <assert.h>
+#include <cm_kwiml.h>
+#include <cmsys/Directory.hxx>
+#include <cmsys/FStream.hxx>
+#include <cmsys/Glob.hxx>
+#include <cmsys/RegularExpression.hxx>
+#include <cmsys/String.hxx>
+#include <list>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <sys/types.h>
+// include sys/stat.h after sys/types.h
+#include <sys/stat.h>
+
 #include "cmAlgorithms.h"
+#include "cmCommandArgumentsHelper.h"
 #include "cmCryptoHash.h"
-#include "cmCryptoHash.h"
+#include "cmFileLockPool.h"
 #include "cmFileTimeComparison.h"
+#include "cmGeneratorExpression.h"
 #include "cmGlobalGenerator.h"
 #include "cmHexFileConverter.h"
 #include "cmInstallType.h"
-#include "cmake.h"
-
+#include "cmListFileCache.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmSystemTools.h"
 #include "cmTimestamp.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
 #include "cmCurl.h"
 #include "cmFileLockResult.h"
 #endif
 
-#undef GetCurrentDirectory
-#include <assert.h>
-
-#include <sys/types.h>
-// include sys/stat.h after sys/types.h
-#include <sys/stat.h>
-
-#include <cm_auto_ptr.hxx>
-#include <cmsys/Directory.hxx>
-#include <cmsys/Encoding.hxx>
-#include <cmsys/FStream.hxx>
-#include <cmsys/Glob.hxx>
-#include <cmsys/RegularExpression.hxx>
+class cmSystemToolsFileTime;
 
 // Table of permissions flags.
 #if defined(_WIN32) && !defined(__CYGWIN__)
@@ -59,7 +71,7 @@ static mode_t mode_setuid = S_ISUID;
 static mode_t mode_setgid = S_ISGID;
 #endif
 
-#if defined(_WIN32) && defined(CMAKE_ENCODING_UTF8)
+#if defined(_WIN32)
 // libcurl doesn't support file:// urls for unicode filenames on Windows.
 // Convert string from UTF-8 to ACP if this is a file:// URL.
 static std::string fix_file_url_windows(const std::string& url)
@@ -110,46 +122,66 @@ bool cmFileCommand::InitialPass(std::vector<std::string> const& args,
   }
   if (subCommand == "MD5" || subCommand == "SHA1" || subCommand == "SHA224" ||
       subCommand == "SHA256" || subCommand == "SHA384" ||
-      subCommand == "SHA512") {
+      subCommand == "SHA512" || subCommand == "SHA3_224" ||
+      subCommand == "SHA3_256" || subCommand == "SHA3_384" ||
+      subCommand == "SHA3_512") {
     return this->HandleHashCommand(args);
   }
   if (subCommand == "STRINGS") {
     return this->HandleStringsCommand(args);
-  } else if (subCommand == "GLOB") {
+  }
+  if (subCommand == "GLOB") {
     return this->HandleGlobCommand(args, false);
-  } else if (subCommand == "GLOB_RECURSE") {
+  }
+  if (subCommand == "GLOB_RECURSE") {
     return this->HandleGlobCommand(args, true);
-  } else if (subCommand == "MAKE_DIRECTORY") {
+  }
+  if (subCommand == "MAKE_DIRECTORY") {
     return this->HandleMakeDirectoryCommand(args);
-  } else if (subCommand == "RENAME") {
+  }
+  if (subCommand == "RENAME") {
     return this->HandleRename(args);
-  } else if (subCommand == "REMOVE") {
+  }
+  if (subCommand == "REMOVE") {
     return this->HandleRemove(args, false);
-  } else if (subCommand == "REMOVE_RECURSE") {
+  }
+  if (subCommand == "REMOVE_RECURSE") {
     return this->HandleRemove(args, true);
-  } else if (subCommand == "COPY") {
+  }
+  if (subCommand == "COPY") {
     return this->HandleCopyCommand(args);
-  } else if (subCommand == "INSTALL") {
+  }
+  if (subCommand == "INSTALL") {
     return this->HandleInstallCommand(args);
-  } else if (subCommand == "DIFFERENT") {
+  }
+  if (subCommand == "DIFFERENT") {
     return this->HandleDifferentCommand(args);
-  } else if (subCommand == "RPATH_CHANGE" || subCommand == "CHRPATH") {
+  }
+  if (subCommand == "RPATH_CHANGE" || subCommand == "CHRPATH") {
     return this->HandleRPathChangeCommand(args);
-  } else if (subCommand == "RPATH_CHECK") {
+  }
+  if (subCommand == "RPATH_CHECK") {
     return this->HandleRPathCheckCommand(args);
-  } else if (subCommand == "RPATH_REMOVE") {
+  }
+  if (subCommand == "RPATH_REMOVE") {
     return this->HandleRPathRemoveCommand(args);
-  } else if (subCommand == "RELATIVE_PATH") {
+  }
+  if (subCommand == "RELATIVE_PATH") {
     return this->HandleRelativePathCommand(args);
-  } else if (subCommand == "TO_CMAKE_PATH") {
+  }
+  if (subCommand == "TO_CMAKE_PATH") {
     return this->HandleCMakePathCommand(args, false);
-  } else if (subCommand == "TO_NATIVE_PATH") {
+  }
+  if (subCommand == "TO_NATIVE_PATH") {
     return this->HandleCMakePathCommand(args, true);
-  } else if (subCommand == "TIMESTAMP") {
+  }
+  if (subCommand == "TIMESTAMP") {
     return this->HandleTimestampCommand(args);
-  } else if (subCommand == "GENERATE") {
+  }
+  if (subCommand == "GENERATE") {
     return this->HandleGenerateCommand(args);
-  } else if (subCommand == "LOCK") {
+  }
+  if (subCommand == "LOCK") {
     return this->HandleLockCommand(args);
   }
 
@@ -736,7 +768,7 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args,
     }
   }
 
-  std::string output = "";
+  std::string output;
   bool first = true;
   for (; i != args.end(); ++i) {
     if (*i == "LIST_DIRECTORIES") {
@@ -756,7 +788,7 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args,
         this->SetError("LIST_DIRECTORIES missing bool value.");
         return false;
       }
-      ++i;
+      continue;
     }
 
     if (recurse && (*i == "FOLLOW_SYMLINKS")) {
@@ -2311,9 +2343,8 @@ size_t cmWriteToMemoryCallback(void* ptr, size_t size, size_t nmemb,
   return realsize;
 }
 
-static size_t cmFileCommandCurlDebugCallback(CURL*, curl_infotype type,
-                                             char* chPtr, size_t size,
-                                             void* data)
+size_t cmFileCommandCurlDebugCallback(CURL*, curl_infotype type, char* chPtr,
+                                      size_t size, void* data)
 {
   cmFileCommandVectorOfChar* vec =
     static_cast<cmFileCommandVectorOfChar*>(data);
@@ -2382,9 +2413,8 @@ private:
   std::string Text;
 };
 
-static int cmFileDownloadProgressCallback(void* clientp, double dltotal,
-                                          double dlnow, double ultotal,
-                                          double ulnow)
+int cmFileDownloadProgressCallback(void* clientp, double dltotal, double dlnow,
+                                   double ultotal, double ulnow)
 {
   cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
 
@@ -2401,9 +2431,8 @@ static int cmFileDownloadProgressCallback(void* clientp, double dltotal,
   return 0;
 }
 
-static int cmFileUploadProgressCallback(void* clientp, double dltotal,
-                                        double dlnow, double ultotal,
-                                        double ulnow)
+int cmFileUploadProgressCallback(void* clientp, double dltotal, double dlnow,
+                                 double ultotal, double ulnow)
 {
   cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
 
@@ -2431,18 +2460,14 @@ public:
   {
   }
 
-  ~cURLEasyGuard(void)
+  ~cURLEasyGuard()
   {
     if (this->Easy) {
       ::curl_easy_cleanup(this->Easy);
     }
   }
 
-  inline void release(void)
-  {
-    this->Easy = CM_NULLPTR;
-    return;
-  }
+  void release() { this->Easy = CM_NULLPTR; }
 
 private:
   ::CURL* Easy;
@@ -2539,7 +2564,8 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
         this->SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
         return false;
       }
-      hash = CM_AUTO_PTR<cmCryptoHash>(cmCryptoHash::New("MD5"));
+      hash =
+        CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(cmCryptoHash::AlgoMD5));
       hashMatchMSG = "MD5 sum";
       expectedHash = cmSystemTools::LowerCase(*i);
     } else if (*i == "SHOW_PROGRESS") {
@@ -2586,7 +2612,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
       // Do not return error for compatibility reason.
       std::string err = "Unexpected argument: ";
       err += *i;
-      this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, err.c_str());
+      this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, err);
     }
     ++i;
   }
@@ -2628,7 +2654,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
     return false;
   }
 
-#if defined(_WIN32) && defined(CMAKE_ENCODING_UTF8)
+#if defined(_WIN32)
   url = fix_file_url_windows(url);
 #endif
 
@@ -2870,7 +2896,7 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
       // Do not return error for compatibility reason.
       std::string err = "Unexpected argument: ";
       err += *i;
-      this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, err.c_str());
+      this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, err);
     }
 
     ++i;
@@ -2888,7 +2914,7 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
 
   unsigned long file_size = cmsys::SystemTools::FileLength(filename);
 
-#if defined(_WIN32) && defined(CMAKE_ENCODING_UTF8)
+#if defined(_WIN32)
   url = fix_file_url_windows(url);
 #endif
 
diff --git a/Source/cmFileCommand.h b/Source/cmFileCommand.h
index 1d21a19..319864c 100644
--- a/Source/cmFileCommand.h
+++ b/Source/cmFileCommand.h
@@ -3,9 +3,13 @@
 #ifndef cmFileCommand_h
 #define cmFileCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
-struct cmFileInstaller;
+class cmExecutionStatus;
 
 /** \class cmFileCommand
  * \brief Command for manipulation of files
@@ -36,8 +40,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "file"; }
 
-  cmTypeMacro(cmFileCommand, cmCommand);
-
 protected:
   bool HandleRename(std::vector<std::string> const& args);
   bool HandleRemove(std::vector<std::string> const& args, bool recurse);
diff --git a/Source/cmFileMonitor.cxx b/Source/cmFileMonitor.cxx
index 815de95..909be78 100644
--- a/Source/cmFileMonitor.cxx
+++ b/Source/cmFileMonitor.cxx
@@ -36,7 +36,7 @@ public:
 class cmVirtualDirectoryWatcher : public cmIBaseWatcher
 {
 public:
-  ~cmVirtualDirectoryWatcher()
+  ~cmVirtualDirectoryWatcher() override
   {
     for (auto i : this->Children) {
       delete i.second;
@@ -156,7 +156,7 @@ public:
     p->AddChildWatcher(ps, this);
   }
 
-  ~cmRealDirectoryWatcher()
+  ~cmRealDirectoryWatcher() override
   {
     // Handle is freed via uv_handle_close callback!
   }
@@ -247,7 +247,10 @@ public:
 
   void StopWatching() final {}
 
-  void AppendCallback(cmFileMonitor::Callback cb) { CbList.push_back(cb); }
+  void AppendCallback(cmFileMonitor::Callback const& cb)
+  {
+    this->CbList.push_back(cb);
+  }
 
   std::string Path() const final
   {
@@ -310,7 +313,7 @@ cmFileMonitor::~cmFileMonitor()
 }
 
 void cmFileMonitor::MonitorPaths(const std::vector<std::string>& paths,
-                                 Callback cb)
+                                 Callback const& cb)
 {
   for (const auto& p : paths) {
     std::vector<std::string> pathSegments;
diff --git a/Source/cmFileMonitor.h b/Source/cmFileMonitor.h
index e05f48d..48169b8 100644
--- a/Source/cmFileMonitor.h
+++ b/Source/cmFileMonitor.h
@@ -17,7 +17,7 @@ public:
   ~cmFileMonitor();
 
   using Callback = std::function<void(const std::string&, int, int)>;
-  void MonitorPaths(const std::vector<std::string>& paths, Callback cb);
+  void MonitorPaths(const std::vector<std::string>& paths, Callback const& cb);
   void StopMonitoring();
 
   std::vector<std::string> WatchedFiles() const;
diff --git a/Source/cmFilePathChecksum.cxx b/Source/cmFilePathChecksum.cxx
new file mode 100644
index 0000000..3d8b695
--- /dev/null
+++ b/Source/cmFilePathChecksum.cxx
@@ -0,0 +1,88 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmFilePathChecksum.h"
+
+#include "cmBase32.h"
+#include "cmCryptoHash.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+#include <vector>
+
+cmFilePathChecksum::cmFilePathChecksum()
+{
+}
+
+cmFilePathChecksum::cmFilePathChecksum(const std::string& currentSrcDir,
+                                       const std::string& currentBinDir,
+                                       const std::string& projectSrcDir,
+                                       const std::string& projectBinDir)
+{
+  setupParentDirs(currentSrcDir, currentBinDir, projectSrcDir, projectBinDir);
+}
+
+cmFilePathChecksum::cmFilePathChecksum(cmMakefile* makefile)
+{
+  setupParentDirs(makefile->GetCurrentSourceDirectory(),
+                  makefile->GetCurrentBinaryDirectory(),
+                  makefile->GetHomeDirectory(),
+                  makefile->GetHomeOutputDirectory());
+}
+
+void cmFilePathChecksum::setupParentDirs(const std::string& currentSrcDir,
+                                         const std::string& currentBinDir,
+                                         const std::string& projectSrcDir,
+                                         const std::string& projectBinDir)
+{
+  parentDirs[0].first = cmsys::SystemTools::GetRealPath(currentSrcDir);
+  parentDirs[1].first = cmsys::SystemTools::GetRealPath(currentBinDir);
+  parentDirs[2].first = cmsys::SystemTools::GetRealPath(projectSrcDir);
+  parentDirs[3].first = cmsys::SystemTools::GetRealPath(projectBinDir);
+
+  parentDirs[0].second = "CurrentSource";
+  parentDirs[1].second = "CurrentBinary";
+  parentDirs[2].second = "ProjectSource";
+  parentDirs[3].second = "ProjectBinary";
+}
+
+std::string cmFilePathChecksum::get(const std::string& filePath)
+{
+  std::string relPath;
+  std::string relSeed;
+  {
+    const std::string fileReal = cmsys::SystemTools::GetRealPath(filePath);
+    std::string parentDir;
+    // Find closest project parent directory
+    for (size_t ii = 0; ii != numParentDirs; ++ii) {
+      const std::string& pDir = parentDirs[ii].first;
+      if (!pDir.empty() &&
+          cmsys::SystemTools::IsSubDirectory(fileReal, pDir)) {
+        relSeed = parentDirs[ii].second;
+        parentDir = pDir;
+        break;
+      }
+    }
+    // Use file system root as fallback parent directory
+    if (parentDir.empty()) {
+      relSeed = "FileSystemRoot";
+      cmsys::SystemTools::SplitPathRootComponent(fileReal, &parentDir);
+    }
+    // Calculate relative path from project parent directory
+    relPath = cmsys::SystemTools::RelativePath(
+      parentDir, cmsys::SystemTools::GetParentDirectory(fileReal));
+  }
+
+  // Calculate the file ( seed + relative path ) binary checksum
+  std::vector<unsigned char> hashBytes =
+    cmCryptoHash(cmCryptoHash::AlgoSHA256).ByteHashString(relSeed + relPath);
+
+  // Convert binary checksum to string
+  return cmBase32Encoder().encodeString(&hashBytes[0], hashBytes.size(),
+                                        false);
+}
+
+std::string cmFilePathChecksum::getPart(const std::string& filePath,
+                                        size_t length)
+{
+  return get(filePath).substr(0, length);
+}
diff --git a/Source/cmFilePathChecksum.h b/Source/cmFilePathChecksum.h
new file mode 100644
index 0000000..df19053
--- /dev/null
+++ b/Source/cmFilePathChecksum.h
@@ -0,0 +1,65 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef cmFilePathChecksum_h
+#define cmFilePathChecksum_h
+
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <stddef.h>
+#include <string>
+#include <utility>
+
+class cmMakefile;
+
+/** \class cmFilePathChecksum
+ * @brief Generates a checksum for the parent directory of a file
+ *
+ * The checksum is calculated from the relative file path to the
+ * closest known project directory. This guarantees reproducibility
+ * when source and build directory differ e.g. for different project
+ * build directories.
+ */
+class cmFilePathChecksum
+{
+public:
+  /// Maximum number of characters to use from the path checksum
+  static const size_t partLengthDefault = 10;
+
+  /// @brief Parent directories are empty
+  cmFilePathChecksum();
+
+  /// @brief Initilizes the parent directories manually
+  cmFilePathChecksum(const std::string& currentSrcDir,
+                     const std::string& currentBinDir,
+                     const std::string& projectSrcDir,
+                     const std::string& projectBinDir);
+
+  /// @brief Initilizes the parent directories from a makefile
+  cmFilePathChecksum(cmMakefile* makefile);
+
+  /// @brief Allows parent directories setup after construction
+  ///
+  void setupParentDirs(const std::string& currentSrcDir,
+                       const std::string& currentBinDir,
+                       const std::string& projectSrcDir,
+                       const std::string& projectBinDir);
+
+  /* @brief Calculates the path checksum for the parent directory of a file
+   *
+   */
+  std::string get(const std::string& filePath);
+
+  /* @brief Same as get() but returns only the first length characters
+   *
+   */
+  std::string getPart(const std::string& filePath,
+                      size_t length = partLengthDefault);
+
+private:
+  /// Size of the parent directory list
+  static const size_t numParentDirs = 4;
+  /// List of (directory name, seed name) pairs
+  std::pair<std::string, std::string> parentDirs[numParentDirs];
+};
+
+#endif
diff --git a/Source/cmFilePathUuid.cxx b/Source/cmFilePathUuid.cxx
deleted file mode 100644
index ad434e3..0000000
--- a/Source/cmFilePathUuid.cxx
+++ /dev/null
@@ -1,118 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmFilePathUuid.h"
-
-#include "cmBase32.h"
-#include "cmCryptoHash.h"
-#include "cmMakefile.h"
-#include "cmSystemTools.h"
-
-#include <vector>
-
-cmFilePathUuid::cmFilePathUuid(cmMakefile* makefile)
-{
-  initParentDirs(makefile->GetCurrentSourceDirectory(),
-                 makefile->GetCurrentBinaryDirectory(),
-                 makefile->GetHomeDirectory(),
-                 makefile->GetHomeOutputDirectory());
-}
-
-cmFilePathUuid::cmFilePathUuid(const std::string& currentSrcDir,
-                               const std::string& currentBinDir,
-                               const std::string& projectSrcDir,
-                               const std::string& projectBinDir)
-{
-  initParentDirs(currentSrcDir, currentBinDir, projectSrcDir, projectBinDir);
-}
-
-void cmFilePathUuid::initParentDirs(const std::string& currentSrcDir,
-                                    const std::string& currentBinDir,
-                                    const std::string& projectSrcDir,
-                                    const std::string& projectBinDir)
-{
-  parentDirs[0].first = cmsys::SystemTools::GetRealPath(currentSrcDir);
-  parentDirs[1].first = cmsys::SystemTools::GetRealPath(currentBinDir);
-  parentDirs[2].first = cmsys::SystemTools::GetRealPath(projectSrcDir);
-  parentDirs[3].first = cmsys::SystemTools::GetRealPath(projectBinDir);
-
-  parentDirs[0].second = "CurrentSource";
-  parentDirs[1].second = "CurrentBinary";
-  parentDirs[2].second = "ProjectSource";
-  parentDirs[3].second = "ProjectBinary";
-}
-
-std::string cmFilePathUuid::get(const std::string& filePath,
-                                const char* outputPrefix,
-                                const char* outputSuffix)
-{
-  std::string sourceFilename = cmsys::SystemTools::GetFilenameName(filePath);
-  std::string sourceBasename =
-    cmsys::SystemTools::GetFilenameWithoutLastExtension(sourceFilename);
-
-  // Acquire checksum string
-  std::string checksum;
-  {
-    std::string sourceRelPath;
-    std::string sourceRelSeed;
-    GetRelPathSeed(filePath, sourceRelPath, sourceRelSeed);
-    checksum = GetChecksumString(sourceFilename, sourceRelPath, sourceRelSeed);
-  }
-
-  // Compose the file name
-  std::string uuid;
-  if (outputPrefix) {
-    uuid += outputPrefix;
-  }
-  uuid += sourceBasename.substr(0, partLengthName);
-  uuid += "_";
-  uuid += checksum.substr(0, partLengthCheckSum);
-  if (outputSuffix) {
-    uuid += outputSuffix;
-  }
-  return uuid;
-}
-
-void cmFilePathUuid::GetRelPathSeed(const std::string& filePath,
-                                    std::string& sourceRelPath,
-                                    std::string& sourceRelSeed)
-{
-  const std::string sourceNameReal = cmsys::SystemTools::GetRealPath(filePath);
-  std::string parentDirectory;
-  // Find closest project parent directory
-  for (size_t ii = 0; ii != numParentDirs; ++ii) {
-    const std::string& pDir = parentDirs[ii].first;
-    if (!pDir.empty() &&
-        cmsys::SystemTools::IsSubDirectory(sourceNameReal, pDir)) {
-      sourceRelSeed = parentDirs[ii].second;
-      parentDirectory = pDir;
-      break;
-    }
-  }
-  // Check if the file path is below a known project directory
-  if (parentDirectory.empty()) {
-    // Use file syste root as fallback parent directory
-    sourceRelSeed = "FileSystemRoot";
-    cmsys::SystemTools::SplitPathRootComponent(sourceNameReal,
-                                               &parentDirectory);
-  }
-  sourceRelPath = cmsys::SystemTools::RelativePath(
-    parentDirectory, cmsys::SystemTools::GetParentDirectory(sourceNameReal));
-}
-
-std::string cmFilePathUuid::GetChecksumString(
-  const std::string& sourceFilename, const std::string& sourceRelPath,
-  const std::string& sourceRelSeed)
-{
-  std::string checksumBase32;
-  {
-    // Calculate the file ( seed + relative path + name ) checksum
-    std::vector<unsigned char> hashBytes =
-      cmCryptoHash::New("SHA256")->ByteHashString(
-        sourceRelSeed + sourceRelPath + sourceFilename);
-
-    checksumBase32 =
-      cmBase32Encoder().encodeString(&hashBytes[0], hashBytes.size(), false);
-  }
-
-  return checksumBase32;
-}
diff --git a/Source/cmFilePathUuid.h b/Source/cmFilePathUuid.h
deleted file mode 100644
index a450526..0000000
--- a/Source/cmFilePathUuid.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#ifndef cmFilePathUuid_h
-#define cmFilePathUuid_h
-
-#include <cmConfigure.h> // IWYU pragma: keep
-
-#include <stddef.h>
-#include <string>
-#include <utility>
-
-class cmMakefile;
-
-/** \class cmFilePathUuid
- * @brief Generates a unique pathless file name with a checksum component
- *        calculated from the file path.
- *
- * The checksum is calculated from the relative file path to the
- * closest known project directory. This guarantees reproducibility
- * when source and build directory differ e.g. for different project
- * build directories.
- */
-class cmFilePathUuid
-{
-public:
-  /// Maximum number of characters to use from the file name
-  static const size_t partLengthName = 14;
-  /// Maximum number of characters to use from the path checksum
-  static const size_t partLengthCheckSum = 14;
-
-  /// @brief Initilizes the parent directories from a makefile
-  cmFilePathUuid(cmMakefile* makefile);
-
-  /// @brief Initilizes the parent directories manually
-  cmFilePathUuid(const std::string& currentSrcDir,
-                 const std::string& currentBinDir,
-                 const std::string& projectSrcDir,
-                 const std::string& projectBinDir);
-
-  /* @brief Calculates and returns the uuid for a file path
-   *
-   * @arg outputPrefix optional string to prepend to the result
-   * @arg outputSuffix optional string to append to the result
-   */
-  std::string get(const std::string& filePath,
-                  const char* outputPrefix = CM_NULLPTR,
-                  const char* outputSuffix = CM_NULLPTR);
-
-private:
-  void initParentDirs(const std::string& currentSrcDir,
-                      const std::string& currentBinDir,
-                      const std::string& projectSrcDir,
-                      const std::string& projectBinDir);
-
-  /// Returns the relative path and the parent directory key string (seed)
-  void GetRelPathSeed(const std::string& filePath, std::string& sourceRelPath,
-                      std::string& sourceRelSeed);
-
-  std::string GetChecksumString(const std::string& sourceFilename,
-                                const std::string& sourceRelPath,
-                                const std::string& sourceRelSeed);
-
-  /// Size of the parent directory list
-  static const size_t numParentDirs = 4;
-  /// List of (directory name, seed name) pairs
-  std::pair<std::string, std::string> parentDirs[numParentDirs];
-};
-
-#endif
diff --git a/Source/cmFileTimeComparison.cxx b/Source/cmFileTimeComparison.cxx
index a6c9cd0..991ebb8 100644
--- a/Source/cmFileTimeComparison.cxx
+++ b/Source/cmFileTimeComparison.cxx
@@ -2,19 +2,11 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFileTimeComparison.h"
 
-#include <cmConfigure.h>
 #include <string>
 #include <time.h>
 #include <utility>
 
-// Use a hash table to avoid duplicate file time checks from disk.
-#if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX_UNORDERED_MAP
-#include <unordered_map>
-#else
-#include <cmsys/hash_map.hxx>
-#endif
-#endif
+#include "cm_unordered_map.hxx"
 
 // Use a platform-specific API to get file times efficiently.
 #if !defined(_WIN32) || defined(__CYGWIN__)
@@ -35,27 +27,9 @@ public:
   bool FileTimesDiffer(const char* f1, const char* f2);
 
 private:
-#if defined(CMAKE_BUILD_WITH_CMAKE)
-  // Use a hash table to efficiently map from file name to modification time.
-  class HashString
-  {
-  public:
-    size_t operator()(const std::string& s) const { return h(s.c_str()); }
-#ifdef CMake_HAVE_CXX_UNORDERED_MAP
-    std::hash<const char*> h;
-#else
-    cmsys::hash<const char*> h;
-#endif
-  };
-#ifdef CMake_HAVE_CXX_UNORDERED_MAP
-  typedef std::unordered_map<std::string,
-#else
-  typedef cmsys::hash_map<std::string,
-#endif
-                             cmFileTimeComparison_Type, HashString>
+  typedef CM_UNORDERED_MAP<std::string, cmFileTimeComparison_Type>
     FileStatsMap;
   FileStatsMap Files;
-#endif
 
   // Internal methods to lookup and compare modification times.
   inline bool Stat(const char* fname, cmFileTimeComparison_Type* st);
@@ -68,7 +42,6 @@ private:
 bool cmFileTimeComparisonInternal::Stat(const char* fname,
                                         cmFileTimeComparison_Type* st)
 {
-#if defined(CMAKE_BUILD_WITH_CMAKE)
   // Use the stored time if available.
   cmFileTimeComparisonInternal::FileStatsMap::iterator fit =
     this->Files.find(fname);
@@ -76,7 +49,6 @@ bool cmFileTimeComparisonInternal::Stat(const char* fname,
     *st = fit->second;
     return true;
   }
-#endif
 
 #if !defined(_WIN32) || defined(__CYGWIN__)
   // POSIX version.  Use the stat function.
@@ -97,11 +69,8 @@ bool cmFileTimeComparisonInternal::Stat(const char* fname,
   *st = fdata.ftLastWriteTime;
 #endif
 
-#if defined(CMAKE_BUILD_WITH_CMAKE)
   // Store the time for future use.
   this->Files[fname] = *st;
-#endif
-
   return true;
 }
 
diff --git a/Source/cmFindBase.cxx b/Source/cmFindBase.cxx
index 982d740..dce5021 100644
--- a/Source/cmFindBase.cxx
+++ b/Source/cmFindBase.cxx
@@ -2,8 +2,17 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFindBase.h"
 
+#include <cmConfigure.h>
+#include <iostream>
+#include <map>
+#include <stddef.h>
+
 #include "cmAlgorithms.h"
+#include "cmMakefile.h"
+#include "cmSearchPath.h"
 #include "cmState.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
 
 cmFindBase::cmFindBase()
 {
@@ -300,7 +309,7 @@ bool cmFindBase::CheckForVariableInCache()
     cmState* state = this->Makefile->GetState();
     const char* cacheEntry = state->GetCacheEntryValue(this->VariableName);
     bool found = !cmSystemTools::IsNOTFOUND(cacheValue);
-    bool cached = cacheEntry ? true : false;
+    bool cached = cacheEntry != CM_NULLPTR;
     if (found) {
       // If the user specifies the entry on the command line without a
       // type we should add the type and docstring but keep the
@@ -308,7 +317,7 @@ bool cmFindBase::CheckForVariableInCache()
       // this.
       if (cached &&
           state->GetCacheEntryType(this->VariableName) ==
-            cmState::UNINITIALIZED) {
+            cmStateEnums::UNINITIALIZED) {
         this->AlreadyInCacheWithoutMetaInfo = true;
       }
       return true;
diff --git a/Source/cmFindBase.h b/Source/cmFindBase.h
index 8561f5d..423d453 100644
--- a/Source/cmFindBase.h
+++ b/Source/cmFindBase.h
@@ -3,6 +3,11 @@
 #ifndef cmFindBase_h
 #define cmFindBase_h
 
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
 #include "cmFindCommon.h"
 
 /** \class cmFindBase
@@ -20,7 +25,6 @@ public:
    * the CMakeLists.txt file.
    */
   virtual bool ParseArguments(std::vector<std::string> const& args);
-  cmTypeMacro(cmFindBase, cmFindCommon);
 
 protected:
   void PrintFindStuff();
diff --git a/Source/cmFindCommon.cxx b/Source/cmFindCommon.cxx
index bd5298d..110195c 100644
--- a/Source/cmFindCommon.cxx
+++ b/Source/cmFindCommon.cxx
@@ -3,7 +3,11 @@
 #include "cmFindCommon.h"
 
 #include <algorithm>
-#include <functional>
+#include <string.h>
+#include <utility>
+
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
 
 cmFindCommon::PathGroup cmFindCommon::PathGroup::All("ALL");
 cmFindCommon::PathLabel cmFindCommon::PathLabel::CMake("CMAKE");
diff --git a/Source/cmFindCommon.h b/Source/cmFindCommon.h
index 3211bc2..4d6d569 100644
--- a/Source/cmFindCommon.h
+++ b/Source/cmFindCommon.h
@@ -3,10 +3,19 @@
 #ifndef cmFindCommon_h
 #define cmFindCommon_h
 
+#include <cmConfigure.h>
+
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 #include "cmPathLabel.h"
 #include "cmSearchPath.h"
 
+class cmMakefile;
+
 /** \class cmFindCommon
  * \brief Base class for FIND_XXX implementations.
  *
@@ -19,7 +28,6 @@ class cmFindCommon : public cmCommand
 public:
   cmFindCommon();
   ~cmFindCommon() CM_OVERRIDE;
-  cmTypeMacro(cmFindCommon, cmCommand);
 
 protected:
   friend class cmSearchPath;
diff --git a/Source/cmFindFileCommand.cxx b/Source/cmFindFileCommand.cxx
index 9c66cd2..9840c4f 100644
--- a/Source/cmFindFileCommand.cxx
+++ b/Source/cmFindFileCommand.cxx
@@ -2,8 +2,6 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFindFileCommand.h"
 
-#include "cmSystemTools.h"
-
 cmFindFileCommand::cmFindFileCommand()
 {
   this->IncludeFileInPath = true;
diff --git a/Source/cmFindFileCommand.h b/Source/cmFindFileCommand.h
index feb6ad2..5c94ebf 100644
--- a/Source/cmFindFileCommand.h
+++ b/Source/cmFindFileCommand.h
@@ -3,8 +3,13 @@
 #ifndef cmFindFileCommand_h
 #define cmFindFileCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+
 #include "cmFindPathCommand.h"
 
+class cmCommand;
+
 /** \class cmFindFileCommand
  * \brief Define a command to search for an executable program.
  *
@@ -22,8 +27,6 @@ public:
    */
   cmCommand* Clone() CM_OVERRIDE { return new cmFindFileCommand; }
   std::string GetName() const CM_OVERRIDE { return "find_file"; }
-
-  cmTypeMacro(cmFindFileCommand, cmFindPathCommand);
 };
 
 #endif
diff --git a/Source/cmFindLibraryCommand.cxx b/Source/cmFindLibraryCommand.cxx
index 082350f..c86f9c1 100644
--- a/Source/cmFindLibraryCommand.cxx
+++ b/Source/cmFindLibraryCommand.cxx
@@ -2,7 +2,19 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFindLibraryCommand.h"
 
-#include <cmsys/Directory.hxx>
+#include <algorithm>
+#include <cmsys/RegularExpression.hxx>
+#include <set>
+#include <stdio.h>
+#include <string.h>
+
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmState.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
 
 cmFindLibraryCommand::cmFindLibraryCommand()
 {
@@ -26,7 +38,7 @@ bool cmFindLibraryCommand::InitialPass(std::vector<std::string> const& argsIn,
     if (this->AlreadyInCacheWithoutMetaInfo) {
       this->Makefile->AddCacheDefinition(this->VariableName, "",
                                          this->VariableDocumentation.c_str(),
-                                         cmState::FILEPATH);
+                                         cmStateEnums::FILEPATH);
     }
     return true;
   }
@@ -52,13 +64,13 @@ bool cmFindLibraryCommand::InitialPass(std::vector<std::string> const& argsIn,
     // Save the value in the cache
     this->Makefile->AddCacheDefinition(this->VariableName, library.c_str(),
                                        this->VariableDocumentation.c_str(),
-                                       cmState::FILEPATH);
+                                       cmStateEnums::FILEPATH);
     return true;
   }
   std::string notfound = this->VariableName + "-NOTFOUND";
   this->Makefile->AddCacheDefinition(this->VariableName, notfound.c_str(),
                                      this->VariableDocumentation.c_str(),
-                                     cmState::FILEPATH);
+                                     cmStateEnums::FILEPATH);
   return true;
 }
 
@@ -72,36 +84,68 @@ void cmFindLibraryCommand::AddArchitecturePaths(const char* suffix)
   }
 }
 
+static bool cmLibDirsLinked(std::string const& l, std::string const& r)
+{
+  // Compare the real paths of the two directories.
+  // Since our caller only changed the trailing component of each
+  // directory, the real paths can be the same only if at least one of
+  // the trailing components is a symlink.  Use this as an optimization
+  // to avoid excessive realpath calls.
+  return (cmSystemTools::FileIsSymlink(l) ||
+          cmSystemTools::FileIsSymlink(r)) &&
+    cmSystemTools::GetRealPath(l) == cmSystemTools::GetRealPath(r);
+}
+
 void cmFindLibraryCommand::AddArchitecturePath(
   std::string const& dir, std::string::size_type start_pos, const char* suffix,
   bool fresh)
 {
   std::string::size_type pos = dir.find("lib/", start_pos);
+
   if (pos != std::string::npos) {
-    std::string cur_dir = dir.substr(0, pos + 3);
-
-    // Follow "lib<suffix>".
-    std::string next_dir = cur_dir + suffix;
-    if (cmSystemTools::FileIsDirectory(next_dir)) {
-      next_dir += dir.substr(pos + 3);
-      std::string::size_type next_pos = pos + 3 + strlen(suffix) + 1;
-      this->AddArchitecturePath(next_dir, next_pos, suffix);
+    // Check for "lib".
+    std::string lib = dir.substr(0, pos + 3);
+    bool use_lib = cmSystemTools::FileIsDirectory(lib);
+
+    // Check for "lib<suffix>" and use it first.
+    std::string libX = lib + suffix;
+    bool use_libX = cmSystemTools::FileIsDirectory(libX);
+
+    // Avoid copies of the same directory due to symlinks.
+    if (use_libX && use_lib && cmLibDirsLinked(libX, lib)) {
+      use_libX = false;
     }
 
-    // Follow "lib".
-    if (cmSystemTools::FileIsDirectory(cur_dir)) {
+    if (use_libX) {
+      libX += dir.substr(pos + 3);
+      std::string::size_type libX_pos = pos + 3 + strlen(suffix) + 1;
+      this->AddArchitecturePath(libX, libX_pos, suffix);
+    }
+
+    if (use_lib) {
       this->AddArchitecturePath(dir, pos + 3 + 1, suffix, false);
     }
   }
+
   if (fresh) {
-    // Check for <dir><suffix>/.
-    std::string cur_dir = dir + suffix + "/";
-    if (cmSystemTools::FileIsDirectory(cur_dir)) {
-      this->SearchPaths.push_back(cur_dir);
+    // Check for the original unchanged path.
+    bool use_dir = cmSystemTools::FileIsDirectory(dir);
+
+    // Check for <dir><suffix>/ and use it first.
+    std::string dirX = dir + suffix;
+    bool use_dirX = cmSystemTools::FileIsDirectory(dirX);
+
+    // Avoid copies of the same directory due to symlinks.
+    if (use_dirX && use_dir && cmLibDirsLinked(dirX, dir)) {
+      use_dirX = false;
+    }
+
+    if (use_dirX) {
+      dirX += "/";
+      this->SearchPaths.push_back(dirX);
     }
 
-    // Now add the original unchanged path
-    if (cmSystemTools::FileIsDirectory(dir)) {
+    if (use_dir) {
       this->SearchPaths.push_back(dir);
     }
   }
diff --git a/Source/cmFindLibraryCommand.h b/Source/cmFindLibraryCommand.h
index 39393f6..aeff629 100644
--- a/Source/cmFindLibraryCommand.h
+++ b/Source/cmFindLibraryCommand.h
@@ -3,8 +3,15 @@
 #ifndef cmFindLibraryCommand_h
 #define cmFindLibraryCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmFindBase.h"
 
+class cmCommand;
+class cmExecutionStatus;
+
 /** \class cmFindLibraryCommand
  * \brief Define a command to search for a library.
  *
@@ -38,8 +45,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "find_library"; }
 
-  cmTypeMacro(cmFindLibraryCommand, cmFindBase);
-
 protected:
   void AddArchitecturePaths(const char* suffix);
   void AddArchitecturePath(std::string const& dir,
diff --git a/Source/cmFindPackageCommand.cxx b/Source/cmFindPackageCommand.cxx
index 554618e..60de74f 100644
--- a/Source/cmFindPackageCommand.cxx
+++ b/Source/cmFindPackageCommand.cxx
@@ -2,22 +2,38 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFindPackageCommand.h"
 
-#include "cmAlgorithms.h"
+#include <algorithm>
+#include <assert.h>
 #include <cmSystemTools.h>
 #include <cmsys/Directory.hxx>
-#include <cmsys/Encoding.hxx>
+#include <cmsys/FStream.hxx>
+#include <cmsys/Glob.hxx>
 #include <cmsys/RegularExpression.hxx>
+#include <cmsys/String.h>
+#include <functional>
+#include <iterator>
+#include <sstream>
+#include <stdio.h>
+#include <string.h>
+#include <utility>
 
-#ifdef CMAKE_BUILD_WITH_CMAKE
-#include "cmVariableWatch.h"
-#endif
+#include "cmAlgorithms.h"
+#include "cmMakefile.h"
+#include "cmSearchPath.h"
+#include "cmState.h"
+#include "cmStateTypes.h"
+#include "cmVersion.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
 
 #if defined(__HAIKU__)
 #include <FindDirectory.h>
 #include <StorageDefs.h>
-#include <string.h>
 #endif
 
+class cmExecutionStatus;
+class cmFileList;
+
 cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::UserRegistry(
   "PACKAGE_REGISTRY");
 cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::Builds(
@@ -669,8 +685,8 @@ bool cmFindPackageCommand::HandlePackageMode()
   bool configFileSetFOUNDFalse = false;
 
   if (fileFound) {
-    if ((this->Makefile->IsDefinitionSet(foundVar)) &&
-        (this->Makefile->IsOn(foundVar) == false)) {
+    if (this->Makefile->IsDefinitionSet(foundVar) &&
+        !this->Makefile->IsOn(foundVar)) {
       // by removing Foo_FOUND here if it is FALSE, we don't really change
       // the situation for the Config file which is about to be included,
       // but we make it possible to detect later on whether the Config file
@@ -689,8 +705,8 @@ bool cmFindPackageCommand::HandlePackageMode()
       found = true;
 
       // Check whether the Config file has set Foo_FOUND to FALSE:
-      if ((this->Makefile->IsDefinitionSet(foundVar)) &&
-          (this->Makefile->IsOn(foundVar) == false)) {
+      if (this->Makefile->IsDefinitionSet(foundVar) &&
+          !this->Makefile->IsOn(foundVar)) {
         // we get here if the Config file has set Foo_FOUND actively to FALSE
         found = false;
         configFileSetFOUNDFalse = true;
@@ -890,7 +906,7 @@ bool cmFindPackageCommand::FindConfig()
   help += ".";
   // We force the value since we do not get here if it was already set.
   this->Makefile->AddCacheDefinition(this->Variable, init.c_str(),
-                                     help.c_str(), cmState::PATH, true);
+                                     help.c_str(), cmStateEnums::PATH, true);
   return found;
 }
 
@@ -1412,8 +1428,7 @@ bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
   // Look for foo-config-version.cmake
   std::string version_file = version_file_base;
   version_file += "-version.cmake";
-  if ((haveResult == false) &&
-      (cmSystemTools::FileExists(version_file.c_str(), true))) {
+  if (!haveResult && cmSystemTools::FileExists(version_file.c_str(), true)) {
     result = this->CheckVersionFile(version_file, version);
     haveResult = true;
   }
@@ -1421,14 +1436,13 @@ bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
   // Look for fooConfigVersion.cmake
   version_file = version_file_base;
   version_file += "Version.cmake";
-  if ((haveResult == false) &&
-      (cmSystemTools::FileExists(version_file.c_str(), true))) {
+  if (!haveResult && cmSystemTools::FileExists(version_file.c_str(), true)) {
     result = this->CheckVersionFile(version_file, version);
     haveResult = true;
   }
 
   // If no version was requested a versionless package is acceptable.
-  if ((haveResult == false) && (this->Version.empty())) {
+  if (!haveResult && this->Version.empty()) {
     result = true;
   }
 
@@ -1547,11 +1561,6 @@ void cmFindPackageCommand::StoreVersionFound()
   this->Makefile->AddDefinition(ver + "_COUNT", buf);
 }
 
-#include <cm_auto_ptr.hxx>
-#include <cmsys/Glob.hxx>
-#include <cmsys/String.h>
-
-class cmFileList;
 class cmFileListGeneratorBase
 {
 public:
diff --git a/Source/cmFindPackageCommand.h b/Source/cmFindPackageCommand.h
index 501a5a5..d454892 100644
--- a/Source/cmFindPackageCommand.h
+++ b/Source/cmFindPackageCommand.h
@@ -3,9 +3,18 @@
 #ifndef cmFindPackageCommand_h
 #define cmFindPackageCommand_h
 
+#include <cmConfigure.h>
+#include <cm_kwiml.h>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
 #include "cmFindCommon.h"
 
-class cmFindPackageFileList;
+class cmCommand;
+class cmExecutionStatus;
+class cmSearchPath;
 
 /** \class cmFindPackageCommand
  * \brief Load settings from an external project.
@@ -60,8 +69,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "find_package"; }
 
-  cmTypeMacro(cmFindPackageCommand, cmFindCommon);
-
 private:
   class PathLabel : public cmFindCommon::PathLabel
   {
diff --git a/Source/cmFindPathCommand.cxx b/Source/cmFindPathCommand.cxx
index 35929fe..8d4bcf3 100644
--- a/Source/cmFindPathCommand.cxx
+++ b/Source/cmFindPathCommand.cxx
@@ -4,6 +4,12 @@
 
 #include <cmsys/Glob.hxx>
 
+#include "cmMakefile.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 cmFindPathCommand::cmFindPathCommand()
 {
   this->EnvironmentPath = "INCLUDE";
@@ -26,7 +32,8 @@ bool cmFindPathCommand::InitialPass(std::vector<std::string> const& argsIn,
     if (this->AlreadyInCacheWithoutMetaInfo) {
       this->Makefile->AddCacheDefinition(
         this->VariableName, "", this->VariableDocumentation.c_str(),
-        (this->IncludeFileInPath ? cmState::FILEPATH : cmState::PATH));
+        (this->IncludeFileInPath ? cmStateEnums::FILEPATH
+                                 : cmStateEnums::PATH));
     }
     return true;
   }
@@ -35,13 +42,13 @@ bool cmFindPathCommand::InitialPass(std::vector<std::string> const& argsIn,
   if (!result.empty()) {
     this->Makefile->AddCacheDefinition(
       this->VariableName, result.c_str(), this->VariableDocumentation.c_str(),
-      (this->IncludeFileInPath) ? cmState::FILEPATH : cmState::PATH);
+      (this->IncludeFileInPath) ? cmStateEnums::FILEPATH : cmStateEnums::PATH);
     return true;
   }
   this->Makefile->AddCacheDefinition(
     this->VariableName, (this->VariableName + "-NOTFOUND").c_str(),
     this->VariableDocumentation.c_str(),
-    (this->IncludeFileInPath) ? cmState::FILEPATH : cmState::PATH);
+    (this->IncludeFileInPath) ? cmStateEnums::FILEPATH : cmStateEnums::PATH);
   return true;
 }
 
@@ -65,7 +72,7 @@ std::string cmFindPathCommand::FindHeaderInFramework(std::string const& file,
 {
   std::string fileName = file;
   std::string frameWorkName;
-  std::string::size_type pos = fileName.find("/");
+  std::string::size_type pos = fileName.find('/');
   // if there is a / in the name try to find the header as a framework
   // For example bar/foo.h would look for:
   // bar.framework/Headers/foo.h
@@ -76,7 +83,7 @@ std::string cmFindPathCommand::FindHeaderInFramework(std::string const& file,
     frameWorkName =
       frameWorkName.substr(0, frameWorkName.size() - fileName.size() - 1);
     // if the framework has a path in it then just use the filename
-    if (frameWorkName.find("/") != frameWorkName.npos) {
+    if (frameWorkName.find('/') != frameWorkName.npos) {
       fileName = file;
       frameWorkName = "";
     }
diff --git a/Source/cmFindPathCommand.h b/Source/cmFindPathCommand.h
index 58cc0f3..edeeb3a 100644
--- a/Source/cmFindPathCommand.h
+++ b/Source/cmFindPathCommand.h
@@ -3,8 +3,15 @@
 #ifndef cmFindPathCommand_h
 #define cmFindPathCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmFindBase.h"
 
+class cmCommand;
+class cmExecutionStatus;
+
 /** \class cmFindPathCommand
  * \brief Define a command to search for a library.
  *
@@ -38,7 +45,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "find_path"; }
 
-  cmTypeMacro(cmFindPathCommand, cmFindBase);
   bool IncludeFileInPath;
 
 private:
diff --git a/Source/cmFindProgramCommand.cxx b/Source/cmFindProgramCommand.cxx
index a6f2518..ea031cf 100644
--- a/Source/cmFindProgramCommand.cxx
+++ b/Source/cmFindProgramCommand.cxx
@@ -2,7 +2,11 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFindProgramCommand.h"
 
-#include <stdlib.h>
+#include "cmMakefile.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
 
 #if defined(__APPLE__)
 #include <CoreFoundation/CoreFoundation.h>
@@ -90,7 +94,7 @@ bool cmFindProgramCommand::InitialPass(std::vector<std::string> const& argsIn,
     if (this->AlreadyInCacheWithoutMetaInfo) {
       this->Makefile->AddCacheDefinition(this->VariableName, "",
                                          this->VariableDocumentation.c_str(),
-                                         cmState::FILEPATH);
+                                         cmStateEnums::FILEPATH);
     }
     return true;
   }
@@ -100,19 +104,19 @@ bool cmFindProgramCommand::InitialPass(std::vector<std::string> const& argsIn,
     // Save the value in the cache
     this->Makefile->AddCacheDefinition(this->VariableName, result.c_str(),
                                        this->VariableDocumentation.c_str(),
-                                       cmState::FILEPATH);
+                                       cmStateEnums::FILEPATH);
 
     return true;
   }
   this->Makefile->AddCacheDefinition(
     this->VariableName, (this->VariableName + "-NOTFOUND").c_str(),
-    this->VariableDocumentation.c_str(), cmState::FILEPATH);
+    this->VariableDocumentation.c_str(), cmStateEnums::FILEPATH);
   return true;
 }
 
 std::string cmFindProgramCommand::FindProgram()
 {
-  std::string program = "";
+  std::string program;
 
   if (this->SearchAppBundleFirst || this->SearchAppBundleOnly) {
     program = FindAppBundle();
@@ -210,7 +214,7 @@ std::string cmFindProgramCommand::FindAppBundle()
 
 std::string cmFindProgramCommand::GetBundleExecutable(std::string bundlePath)
 {
-  std::string executable = "";
+  std::string executable;
   (void)bundlePath;
 #if defined(__APPLE__)
   // Started with an example on developer.apple.com about finding bundles
diff --git a/Source/cmFindProgramCommand.h b/Source/cmFindProgramCommand.h
index 2d88b79..dc17803 100644
--- a/Source/cmFindProgramCommand.h
+++ b/Source/cmFindProgramCommand.h
@@ -3,8 +3,15 @@
 #ifndef cmFindProgramCommand_h
 #define cmFindProgramCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmFindBase.h"
 
+class cmCommand;
+class cmExecutionStatus;
+
 /** \class cmFindProgramCommand
  * \brief Define a command to search for an executable program.
  *
@@ -39,8 +46,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "find_program"; }
 
-  cmTypeMacro(cmFindProgramCommand, cmFindBase);
-
 private:
   std::string FindProgram();
   std::string FindNormalProgram();
diff --git a/Source/cmForEachCommand.cxx b/Source/cmForEachCommand.cxx
index 987741b..6273f6e 100644
--- a/Source/cmForEachCommand.cxx
+++ b/Source/cmForEachCommand.cxx
@@ -2,7 +2,15 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmForEachCommand.h"
 
-#include <cm_auto_ptr.hxx>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "cmExecutionStatus.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
 
 cmForEachFunctionBlocker::cmForEachFunctionBlocker(cmMakefile* mf)
   : Makefile(mf)
diff --git a/Source/cmForEachCommand.h b/Source/cmForEachCommand.h
index 1e3d786..93c4676 100644
--- a/Source/cmForEachCommand.h
+++ b/Source/cmForEachCommand.h
@@ -3,11 +3,17 @@
 #ifndef cmForEachCommand_h
 #define cmForEachCommand_h
 
-#include "cmCommand.h"
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
 
+#include "cmCommand.h"
 #include "cmFunctionBlocker.h"
 #include "cmListFileCache.h"
 
+class cmExecutionStatus;
+class cmMakefile;
+
 class cmForEachFunctionBlocker : public cmFunctionBlocker
 {
 public:
@@ -51,8 +57,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "foreach"; }
 
-  cmTypeMacro(cmForEachCommand, cmCommand);
-
 private:
   bool HandleInMode(std::vector<std::string> const& args);
 };
diff --git a/Source/cmFortranLexer.cxx b/Source/cmFortranLexer.cxx
index a5ef47d..01c09ac 100644
--- a/Source/cmFortranLexer.cxx
+++ b/Source/cmFortranLexer.cxx
@@ -1,7 +1,9 @@
+#include "cmStandardLexer.h"
 #line 2 "cmFortranLexer.cxx"
 
 #line 4 "cmFortranLexer.cxx"
 
+#define FLEXINT_H 1
 #define  YY_INT_ALIGNED short int
 
 /* A lexical scanner generated by flex */
@@ -651,22 +653,22 @@ static yyconst flex_int16_t yy_chk[633] =
 
 /*
 
-This file must be translated to C and modified to build everywhere.
+This file must be translated to C++ and modified to build everywhere.
 
 Run flex >= 2.6 like this:
 
-  flex -i --prefix=cmFortran_yy --header-file=cmFortranLexer.h -ocmFortranLexer.cxx cmFortranLexer.in.l
+  flex -i --nounistd -DFLEXINT_H --prefix=cmFortran_yy --header-file=cmFortranLexer.h -ocmFortranLexer.cxx cmFortranLexer.in.l
 
 Modify cmFortranLexer.cxx:
   - remove trailing whitespace: sed -i 's/\s*$//' cmFortranLexer.h cmFortranLexer.cxx
   - remove blank lines at end of file
-  - remove "yyscanner = NULL" from end of cmFortran_yylex_destroy
-  - remove all YY_BREAK lines occurring right after return statements
+  - #include "cmStandardLexer.h" at the top
   - add cast in cmFortran_yy_scan_bytes for loop condition of _yybytes_len to size_t
 
 */
 
-#include "cmStandardLexer.h"
+/* IWYU pragma: no_forward_declare yyguts_t */
+
 #undef YY_NO_UNPUT
 
 #define cmFortranLexer_cxx
@@ -683,7 +685,7 @@ Modify cmFortranLexer.cxx:
 /*--------------------------------------------------------------------------*/
 
 
-#line 696 "cmFortranLexer.cxx"
+#line 688 "cmFortranLexer.cxx"
 
 #define INITIAL 0
 #define free_fmt 1
@@ -691,14 +693,6 @@ Modify cmFortranLexer.cxx:
 #define str_sq 3
 #define str_dq 4
 
-#ifndef YY_NO_UNISTD_H
-/* Special case for "unistd.h", since it is non-ANSI. We include it way
- * down here because we want the user's section 1 to have been scanned first.
- * The user has a chance to override it with an option.
- */
-#include <unistd.h>
-#endif
-
 #ifndef YY_EXTRA_TYPE
 #define YY_EXTRA_TYPE void *
 #endif
@@ -951,10 +945,10 @@ YY_DECL
 		}
 
 	{
-#line 65 "cmFortranLexer.in.l"
+#line 56 "cmFortranLexer.in.l"
 
 
-#line 967 "cmFortranLexer.cxx"
+#line 951 "cmFortranLexer.cxx"
 
 	while ( /*CONSTCOND*/1 )		/* loops until end-of-file is reached */
 		{
@@ -1014,7 +1008,7 @@ do_action:	/* This label is used only to access EOF actions. */
 
 case 1:
 YY_RULE_SETUP
-#line 67 "cmFortranLexer.in.l"
+#line 58 "cmFortranLexer.in.l"
 {
   cmFortranParser_StringStart(yyextra);
   cmFortranParser_SetOldStartcond(yyextra, YY_START);
@@ -1023,7 +1017,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 2:
 YY_RULE_SETUP
-#line 73 "cmFortranLexer.in.l"
+#line 64 "cmFortranLexer.in.l"
 {
   cmFortranParser_StringStart(yyextra);
   cmFortranParser_SetOldStartcond(yyextra, YY_START);
@@ -1031,28 +1025,29 @@ YY_RULE_SETUP
 }
 	YY_BREAK
 case 3:
-#line 80 "cmFortranLexer.in.l"
+#line 71 "cmFortranLexer.in.l"
 case 4:
 YY_RULE_SETUP
-#line 80 "cmFortranLexer.in.l"
+#line 71 "cmFortranLexer.in.l"
 {
   BEGIN(cmFortranParser_GetOldStartcond(yyextra) );
   yylvalp->string = strdup(cmFortranParser_StringEnd(yyextra));
   return STRING;
 }
+	YY_BREAK
 case 5:
 /* rule 5 can match eol */
-#line 87 "cmFortranLexer.in.l"
+#line 78 "cmFortranLexer.in.l"
 case 6:
 /* rule 6 can match eol */
 YY_RULE_SETUP
-#line 87 "cmFortranLexer.in.l"
+#line 78 "cmFortranLexer.in.l"
 /* Ignore (continued strings, free fmt) */
 	YY_BREAK
 case 7:
 /* rule 7 can match eol */
 YY_RULE_SETUP
-#line 89 "cmFortranLexer.in.l"
+#line 80 "cmFortranLexer.in.l"
 {
   if (cmFortranParser_GetOldStartcond(yyextra) == fixed_fmt)
     ; /* Ignore (cont. strings, fixed fmt) */
@@ -1065,15 +1060,16 @@ YY_RULE_SETUP
 case 8:
 /* rule 8 can match eol */
 YY_RULE_SETUP
-#line 99 "cmFortranLexer.in.l"
+#line 90 "cmFortranLexer.in.l"
 {
   unput ('\n');
   BEGIN(INITIAL);
   return UNTERMINATED_STRING;
 }
+	YY_BREAK
 case 9:
 YY_RULE_SETUP
-#line 105 "cmFortranLexer.in.l"
+#line 96 "cmFortranLexer.in.l"
 {
   cmFortranParser_StringAppend(yyextra, yytext[0]);
 }
@@ -1081,205 +1077,245 @@ YY_RULE_SETUP
 case 10:
 /* rule 10 can match eol */
 YY_RULE_SETUP
-#line 109 "cmFortranLexer.in.l"
+#line 100 "cmFortranLexer.in.l"
 { return EOSTMT; } /* Treat comments like */
+	YY_BREAK
 case 11:
 /* rule 11 can match eol */
 YY_RULE_SETUP
-#line 110 "cmFortranLexer.in.l"
+#line 101 "cmFortranLexer.in.l"
 { return EOSTMT; } /* empty lines */
+	YY_BREAK
 case 12:
 YY_RULE_SETUP
-#line 112 "cmFortranLexer.in.l"
+#line 103 "cmFortranLexer.in.l"
 { return CPP_LINE_DIRECTIVE; }
+	YY_BREAK
 case 13:
 /* rule 13 can match eol */
 YY_RULE_SETUP
-#line 113 "cmFortranLexer.in.l"
+#line 104 "cmFortranLexer.in.l"
 {
   yytext[yyleng-1] = 0;
   yylvalp->string = strdup(strchr(yytext, '<')+1);
   return CPP_INCLUDE_ANGLE;
 }
+	YY_BREAK
 case 14:
 YY_RULE_SETUP
-#line 118 "cmFortranLexer.in.l"
+#line 109 "cmFortranLexer.in.l"
 { return CPP_INCLUDE; }
+	YY_BREAK
 case 15:
 YY_RULE_SETUP
-#line 119 "cmFortranLexer.in.l"
+#line 110 "cmFortranLexer.in.l"
 { return F90PPR_INCLUDE; }
+	YY_BREAK
 case 16:
 YY_RULE_SETUP
-#line 120 "cmFortranLexer.in.l"
+#line 111 "cmFortranLexer.in.l"
 { return COCO_INCLUDE; }
+	YY_BREAK
 case 17:
 YY_RULE_SETUP
-#line 122 "cmFortranLexer.in.l"
+#line 113 "cmFortranLexer.in.l"
 { return CPP_DEFINE; }
+	YY_BREAK
 case 18:
 YY_RULE_SETUP
-#line 123 "cmFortranLexer.in.l"
+#line 114 "cmFortranLexer.in.l"
 { return F90PPR_DEFINE; }
+	YY_BREAK
 case 19:
 YY_RULE_SETUP
-#line 125 "cmFortranLexer.in.l"
+#line 116 "cmFortranLexer.in.l"
 { return CPP_UNDEF; }
+	YY_BREAK
 case 20:
 YY_RULE_SETUP
-#line 126 "cmFortranLexer.in.l"
+#line 117 "cmFortranLexer.in.l"
 { return F90PPR_UNDEF; }
+	YY_BREAK
 case 21:
 YY_RULE_SETUP
-#line 128 "cmFortranLexer.in.l"
+#line 119 "cmFortranLexer.in.l"
 { return CPP_IFDEF; }
+	YY_BREAK
 case 22:
 YY_RULE_SETUP
-#line 129 "cmFortranLexer.in.l"
+#line 120 "cmFortranLexer.in.l"
 { return CPP_IFNDEF; }
+	YY_BREAK
 case 23:
 YY_RULE_SETUP
-#line 130 "cmFortranLexer.in.l"
+#line 121 "cmFortranLexer.in.l"
 { return CPP_IF; }
+	YY_BREAK
 case 24:
 YY_RULE_SETUP
-#line 131 "cmFortranLexer.in.l"
+#line 122 "cmFortranLexer.in.l"
 { return CPP_ELIF; }
+	YY_BREAK
 case 25:
 YY_RULE_SETUP
-#line 132 "cmFortranLexer.in.l"
+#line 123 "cmFortranLexer.in.l"
 { return CPP_ELSE; }
+	YY_BREAK
 case 26:
 YY_RULE_SETUP
-#line 133 "cmFortranLexer.in.l"
+#line 124 "cmFortranLexer.in.l"
 { return CPP_ENDIF; }
+	YY_BREAK
 case 27:
 YY_RULE_SETUP
-#line 135 "cmFortranLexer.in.l"
+#line 126 "cmFortranLexer.in.l"
 { return F90PPR_IFDEF; }
+	YY_BREAK
 case 28:
 YY_RULE_SETUP
-#line 136 "cmFortranLexer.in.l"
+#line 127 "cmFortranLexer.in.l"
 { return F90PPR_IFNDEF; }
+	YY_BREAK
 case 29:
 YY_RULE_SETUP
-#line 137 "cmFortranLexer.in.l"
+#line 128 "cmFortranLexer.in.l"
 { return F90PPR_IF; }
+	YY_BREAK
 case 30:
 YY_RULE_SETUP
-#line 138 "cmFortranLexer.in.l"
+#line 129 "cmFortranLexer.in.l"
 { return F90PPR_ELIF; }
+	YY_BREAK
 case 31:
 YY_RULE_SETUP
-#line 139 "cmFortranLexer.in.l"
+#line 130 "cmFortranLexer.in.l"
 { return F90PPR_ELSE; }
+	YY_BREAK
 case 32:
 YY_RULE_SETUP
-#line 140 "cmFortranLexer.in.l"
+#line 131 "cmFortranLexer.in.l"
 { return F90PPR_ENDIF; }
+	YY_BREAK
 /* Line continuations, possible involving comments.  */
 case 33:
 /* rule 33 can match eol */
 YY_RULE_SETUP
-#line 143 "cmFortranLexer.in.l"
+#line 134 "cmFortranLexer.in.l"
 
 	YY_BREAK
 case 34:
 /* rule 34 can match eol */
 YY_RULE_SETUP
-#line 144 "cmFortranLexer.in.l"
+#line 135 "cmFortranLexer.in.l"
 
 	YY_BREAK
 case 35:
 YY_RULE_SETUP
-#line 146 "cmFortranLexer.in.l"
+#line 137 "cmFortranLexer.in.l"
 { return COMMA; }
+	YY_BREAK
 case 36:
 YY_RULE_SETUP
-#line 148 "cmFortranLexer.in.l"
+#line 139 "cmFortranLexer.in.l"
 { return DCOLON; }
+	YY_BREAK
 case 37:
 YY_RULE_SETUP
-#line 149 "cmFortranLexer.in.l"
+#line 140 "cmFortranLexer.in.l"
 { return COLON; }
+	YY_BREAK
 case 38:
 /* rule 38 can match eol */
 YY_RULE_SETUP
-#line 151 "cmFortranLexer.in.l"
+#line 142 "cmFortranLexer.in.l"
 { return GARBAGE; }
+	YY_BREAK
 case 39:
 YY_RULE_SETUP
-#line 153 "cmFortranLexer.in.l"
+#line 144 "cmFortranLexer.in.l"
 { return ASSIGNMENT_OP; }
+	YY_BREAK
 case 40:
 YY_RULE_SETUP
-#line 155 "cmFortranLexer.in.l"
+#line 146 "cmFortranLexer.in.l"
 { return END; }
+	YY_BREAK
 case 41:
 YY_RULE_SETUP
-#line 156 "cmFortranLexer.in.l"
+#line 147 "cmFortranLexer.in.l"
 { return INCLUDE; }
+	YY_BREAK
 case 42:
 YY_RULE_SETUP
-#line 157 "cmFortranLexer.in.l"
+#line 148 "cmFortranLexer.in.l"
 { return INTERFACE; }
+	YY_BREAK
 case 43:
 YY_RULE_SETUP
-#line 158 "cmFortranLexer.in.l"
+#line 149 "cmFortranLexer.in.l"
 { return MODULE; }
+	YY_BREAK
 case 44:
 YY_RULE_SETUP
-#line 159 "cmFortranLexer.in.l"
+#line 150 "cmFortranLexer.in.l"
 { return SUBMODULE; }
+	YY_BREAK
 case 45:
 YY_RULE_SETUP
-#line 160 "cmFortranLexer.in.l"
+#line 151 "cmFortranLexer.in.l"
 { return USE; }
+	YY_BREAK
 case 46:
 YY_RULE_SETUP
-#line 162 "cmFortranLexer.in.l"
+#line 153 "cmFortranLexer.in.l"
 {
   yylvalp->string = strdup(yytext);
   return WORD;
 }
+	YY_BREAK
 case 47:
 YY_RULE_SETUP
-#line 167 "cmFortranLexer.in.l"
+#line 158 "cmFortranLexer.in.l"
 { return LPAREN; }
+	YY_BREAK
 case 48:
 YY_RULE_SETUP
-#line 168 "cmFortranLexer.in.l"
+#line 159 "cmFortranLexer.in.l"
 { return RPAREN; }
+	YY_BREAK
 case 49:
 YY_RULE_SETUP
-#line 170 "cmFortranLexer.in.l"
+#line 161 "cmFortranLexer.in.l"
 { return GARBAGE; }
+	YY_BREAK
 case 50:
 /* rule 50 can match eol */
 YY_RULE_SETUP
-#line 172 "cmFortranLexer.in.l"
+#line 163 "cmFortranLexer.in.l"
 { return EOSTMT; }
+	YY_BREAK
 case 51:
 YY_RULE_SETUP
-#line 175 "cmFortranLexer.in.l"
+#line 166 "cmFortranLexer.in.l"
 /* Ignore */
 	YY_BREAK
 case 52:
 /* rule 52 can match eol */
 YY_RULE_SETUP
-#line 176 "cmFortranLexer.in.l"
+#line 167 "cmFortranLexer.in.l"
 /* Ignore line-endings preceded by \ */
 	YY_BREAK
 case 53:
 YY_RULE_SETUP
-#line 178 "cmFortranLexer.in.l"
+#line 169 "cmFortranLexer.in.l"
 { return *yytext; }
+	YY_BREAK
 case YY_STATE_EOF(INITIAL):
 case YY_STATE_EOF(free_fmt):
 case YY_STATE_EOF(fixed_fmt):
 case YY_STATE_EOF(str_sq):
 case YY_STATE_EOF(str_dq):
-#line 180 "cmFortranLexer.in.l"
+#line 171 "cmFortranLexer.in.l"
 {
   if(!cmFortranParser_FilePop(yyextra) )
     {
@@ -1289,10 +1325,10 @@ case YY_STATE_EOF(str_dq):
 	YY_BREAK
 case 54:
 YY_RULE_SETUP
-#line 187 "cmFortranLexer.in.l"
+#line 178 "cmFortranLexer.in.l"
 ECHO;
 	YY_BREAK
-#line 1347 "cmFortranLexer.cxx"
+#line 1331 "cmFortranLexer.cxx"
 
 	case YY_END_OF_BUFFER:
 		{
@@ -2400,6 +2436,7 @@ int cmFortran_yylex_destroy  (yyscan_t yyscanner)
 
     /* Destroy the main struct (reentrant only). */
     cmFortran_yyfree ( yyscanner , yyscanner );
+    yyscanner = NULL;
     return 0;
 }
 
@@ -2461,7 +2498,7 @@ void cmFortran_yyfree (void * ptr , yyscan_t yyscanner)
 
 #define YYTABLES_NAME "yytables"
 
-#line 187 "cmFortranLexer.in.l"
+#line 178 "cmFortranLexer.in.l"
 
 
 
diff --git a/Source/cmFortranLexer.h b/Source/cmFortranLexer.h
index 851f37f..ddda919 100644
--- a/Source/cmFortranLexer.h
+++ b/Source/cmFortranLexer.h
@@ -6,6 +6,7 @@
 
 #line 8 "cmFortranLexer.h"
 
+#define FLEXINT_H 1
 #define  YY_INT_ALIGNED short int
 
 /* A lexical scanner generated by flex */
@@ -224,14 +225,6 @@ void cmFortran_yyfree (void * ,yyscan_t yyscanner );
 
 #endif
 
-#ifndef YY_NO_UNISTD_H
-/* Special case for "unistd.h", since it is non-ANSI. We include it way
- * down here because we want the user's section 1 to have been scanned first.
- * The user has a chance to override it with an option.
- */
-#include <unistd.h>
-#endif
-
 #ifndef YY_EXTRA_TYPE
 #define YY_EXTRA_TYPE void *
 #endif
@@ -337,9 +330,9 @@ extern int cmFortran_yylex (yyscan_t yyscanner);
 #undef YY_DECL
 #endif
 
-#line 187 "cmFortranLexer.in.l"
+#line 178 "cmFortranLexer.in.l"
 
 
-#line 344 "cmFortranLexer.h"
+#line 337 "cmFortranLexer.h"
 #undef cmFortran_yyIN_HEADER
 #endif /* cmFortran_yyHEADER_H */
diff --git a/Source/cmFortranLexer.in.l b/Source/cmFortranLexer.in.l
index e82eaa0..1121210 100644
--- a/Source/cmFortranLexer.in.l
+++ b/Source/cmFortranLexer.in.l
@@ -13,22 +13,22 @@
 
 /*
 
-This file must be translated to C and modified to build everywhere.
+This file must be translated to C++ and modified to build everywhere.
 
 Run flex >= 2.6 like this:
 
-  flex -i --prefix=cmFortran_yy --header-file=cmFortranLexer.h -ocmFortranLexer.cxx cmFortranLexer.in.l
+  flex -i --nounistd -DFLEXINT_H --prefix=cmFortran_yy --header-file=cmFortranLexer.h -ocmFortranLexer.cxx cmFortranLexer.in.l
 
 Modify cmFortranLexer.cxx:
   - remove trailing whitespace: sed -i 's/\s*$//' cmFortranLexer.h cmFortranLexer.cxx
   - remove blank lines at end of file
-  - remove "yyscanner = NULL" from end of cmFortran_yylex_destroy
-  - remove all YY_BREAK lines occurring right after return statements
+  - #include "cmStandardLexer.h" at the top
   - add cast in yy_scan_bytes for loop condition of _yybytes_len to size_t
 
 */
 
-#include "cmStandardLexer.h"
+/* IWYU pragma: no_forward_declare yyguts_t */
+
 #undef YY_NO_UNPUT
 
 #define cmFortranLexer_cxx
diff --git a/Source/cmFortranParserImpl.cxx b/Source/cmFortranParserImpl.cxx
index 23f881a..1a5e6c5 100644
--- a/Source/cmFortranParserImpl.cxx
+++ b/Source/cmFortranParserImpl.cxx
@@ -52,7 +52,7 @@ cmFortranParser_s::cmFortranParser_s(std::vector<std::string> const& includes,
   , PPDefinitions(defines)
   , Info(info)
 {
-  this->InInterface = 0;
+  this->InInterface = false;
   this->InPPFalseBranch = 0;
 
   // Initialize the lexical scanner.
@@ -83,9 +83,9 @@ bool cmFortranParser_FilePush(cmFortranParser* parser, const char* fname)
       cmFortran_yy_create_buffer(CM_NULLPTR, 16384, parser->Scanner);
     cmFortran_yy_switch_to_buffer(buffer, parser->Scanner);
     parser->FileStack.push(f);
-    return 1;
+    return true;
   }
-  return 0;
+  return false;
 }
 
 bool cmFortranParser_FilePop(cmFortranParser* parser)
@@ -93,7 +93,7 @@ bool cmFortranParser_FilePop(cmFortranParser* parser)
   // Pop one file off the stack and close it.  Switch the lexer back
   // to the next one on the stack.
   if (parser->FileStack.empty()) {
-    return 0;
+    return false;
   }
   cmFortranFile f = parser->FileStack.top();
   parser->FileStack.pop();
@@ -101,7 +101,7 @@ bool cmFortranParser_FilePop(cmFortranParser* parser)
   YY_BUFFER_STATE current = cmFortranLexer_GetCurrentBuffer(parser->Scanner);
   cmFortran_yy_delete_buffer(current, parser->Scanner);
   cmFortran_yy_switch_to_buffer(f.Buffer, parser->Scanner);
-  return 1;
+  return true;
 }
 
 int cmFortranParser_Input(cmFortranParser* parser, char* buffer,
diff --git a/Source/cmFunctionBlocker.h b/Source/cmFunctionBlocker.h
index 388115d..b3450b3 100644
--- a/Source/cmFunctionBlocker.h
+++ b/Source/cmFunctionBlocker.h
@@ -3,12 +3,9 @@
 #ifndef cmFunctionBlocker_h
 #define cmFunctionBlocker_h
 
-#include <cmConfigure.h>
-
-#include "cmStandardIncludes.h"
-
-#include "cmExecutionStatus.h"
 #include "cmListFileCache.h"
+
+class cmExecutionStatus;
 class cmMakefile;
 
 class cmFunctionBlocker
diff --git a/Source/cmFunctionCommand.cxx b/Source/cmFunctionCommand.cxx
index 99d883a..31adcb7 100644
--- a/Source/cmFunctionCommand.cxx
+++ b/Source/cmFunctionCommand.cxx
@@ -2,7 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmFunctionCommand.h"
 
-#include "cmake.h"
+#include <sstream>
+
+#include "cmAlgorithms.h"
+#include "cmExecutionStatus.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
 
 // define the class for function commands
 class cmFunctionHelperCommand : public cmCommand
@@ -14,12 +21,9 @@ public:
   ~cmFunctionHelperCommand() CM_OVERRIDE {}
 
   /**
-   * This is used to avoid including this command
-   * in documentation. This is mainly used by
-   * cmMacroHelperCommand and cmFunctionHelperCommand
-   * which cannot provide appropriate documentation.
+   * This determines if the command is defined in a cmake script.
    */
-  bool ShouldAppearInDocumentation() const CM_OVERRIDE { return false; }
+  bool IsUserDefined() const CM_OVERRIDE { return true; }
 
   /**
    * This is a virtual constructor for the command.
@@ -58,8 +62,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return this->Args[0]; }
 
-  cmTypeMacro(cmFunctionHelperCommand, cmCommand);
-
   std::vector<std::string> Args;
   std::vector<cmListFileFunction> Functions;
   cmPolicies::PolicyMap Policies;
diff --git a/Source/cmFunctionCommand.h b/Source/cmFunctionCommand.h
index 277708b..afea6f9 100644
--- a/Source/cmFunctionCommand.h
+++ b/Source/cmFunctionCommand.h
@@ -3,9 +3,16 @@
 #ifndef cmFunctionCommand_h
 #define cmFunctionCommand_h
 
-#include "cmCommand.h"
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
 
+#include "cmCommand.h"
 #include "cmFunctionBlocker.h"
+#include "cmListFileCache.h"
+
+class cmExecutionStatus;
+class cmMakefile;
 
 class cmFunctionFunctionBlocker : public cmFunctionBlocker
 {
@@ -46,8 +53,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "function"; }
-
-  cmTypeMacro(cmFunctionCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmGeneratedFileStream.cxx b/Source/cmGeneratedFileStream.cxx
index 02717a4..4731493 100644
--- a/Source/cmGeneratedFileStream.cxx
+++ b/Source/cmGeneratedFileStream.cxx
@@ -2,21 +2,30 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGeneratedFileStream.h"
 
-#include "cmSystemTools.h"
-
 #include <stdio.h>
 
+#include "cmSystemTools.h"
+
 #if defined(CMAKE_BUILD_WITH_CMAKE)
+#include "cm_codecvt.hxx"
 #include <cm_zlib.h>
 #endif
 
-cmGeneratedFileStream::cmGeneratedFileStream()
+cmGeneratedFileStream::cmGeneratedFileStream(Encoding encoding)
   : cmGeneratedFileStreamBase()
   , Stream()
 {
+#ifdef CMAKE_BUILD_WITH_CMAKE
+  if (encoding != codecvt::None) {
+    imbue(std::locale(getloc(), new codecvt(encoding)));
+  }
+#else
+  static_cast<void>(encoding);
+#endif
 }
 
-cmGeneratedFileStream::cmGeneratedFileStream(const char* name, bool quiet)
+cmGeneratedFileStream::cmGeneratedFileStream(const char* name, bool quiet,
+                                             Encoding encoding)
   : cmGeneratedFileStreamBase(name)
   , Stream(TempName.c_str())
 {
@@ -26,6 +35,13 @@ cmGeneratedFileStream::cmGeneratedFileStream(const char* name, bool quiet)
                          this->TempName.c_str());
     cmSystemTools::ReportLastSystemError("");
   }
+#ifdef CMAKE_BUILD_WITH_CMAKE
+  if (encoding != codecvt::None) {
+    imbue(std::locale(getloc(), new codecvt(encoding)));
+  }
+#else
+  static_cast<void>(encoding);
+#endif
 }
 
 cmGeneratedFileStream::~cmGeneratedFileStream()
diff --git a/Source/cmGeneratedFileStream.h b/Source/cmGeneratedFileStream.h
index 515954c..a027b01 100644
--- a/Source/cmGeneratedFileStream.h
+++ b/Source/cmGeneratedFileStream.h
@@ -5,6 +5,7 @@
 
 #include <cmConfigure.h>
 
+#include <cm_codecvt.hxx>
 #include <cmsys/FStream.hxx>
 #include <string>
 
@@ -71,12 +72,13 @@ class cmGeneratedFileStream : private cmGeneratedFileStreamBase,
 {
 public:
   typedef cmsys::ofstream Stream;
+  typedef codecvt::Encoding Encoding;
 
   /**
    * This constructor prepares a default stream.  The open method must
    * be used before writing to the stream.
    */
-  cmGeneratedFileStream();
+  cmGeneratedFileStream(Encoding encoding = codecvt::None);
 
   /**
    * This constructor takes the name of the file to be generated.  It
@@ -84,7 +86,8 @@ public:
    * file cannot be opened an error message is produced unless the
    * second argument is set to true.
    */
-  cmGeneratedFileStream(const char* name, bool quiet = false);
+  cmGeneratedFileStream(const char* name, bool quiet = false,
+                        Encoding encoding = codecvt::None);
 
   /**
    * The destructor checks the stream status to be sure the temporary
diff --git a/Source/cmGeneratorExpression.cxx b/Source/cmGeneratorExpression.cxx
index 34f763c..e70bbfe 100644
--- a/Source/cmGeneratorExpression.cxx
+++ b/Source/cmGeneratorExpression.cxx
@@ -2,6 +2,9 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGeneratorExpression.h"
 
+#include <cmsys/RegularExpression.hxx>
+#include <utility>
+
 #include "assert.h"
 #include "cmAlgorithms.h"
 #include "cmGeneratorExpressionContext.h"
@@ -9,9 +12,7 @@
 #include "cmGeneratorExpressionLexer.h"
 #include "cmGeneratorExpressionParser.h"
 #include "cmSystemTools.h"
-
-#include <cmsys/RegularExpression.hxx>
-#include <utility>
+#include "cm_auto_ptr.hxx"
 
 cmGeneratorExpression::cmGeneratorExpression(
   const cmListFileBacktrace& backtrace)
@@ -350,7 +351,8 @@ std::string cmGeneratorExpression::Preprocess(const std::string& input,
     return stripExportInterface(input, context, resolveRelative);
   }
 
-  assert(0 && "cmGeneratorExpression::Preprocess called with invalid args");
+  assert(false &&
+         "cmGeneratorExpression::Preprocess called with invalid args");
   return std::string();
 }
 
diff --git a/Source/cmGeneratorExpressionDAGChecker.cxx b/Source/cmGeneratorExpressionDAGChecker.cxx
index aff1ecd..c026631 100644
--- a/Source/cmGeneratorExpressionDAGChecker.cxx
+++ b/Source/cmGeneratorExpressionDAGChecker.cxx
@@ -53,8 +53,9 @@ void cmGeneratorExpressionDAGChecker::Initialize()
 
 #define TEST_TRANSITIVE_PROPERTY_METHOD(METHOD) top->METHOD() ||
 
-  if (CheckResult == DAG && (CM_FOR_EACH_TRANSITIVE_PROPERTY_METHOD(
-                              TEST_TRANSITIVE_PROPERTY_METHOD) false))
+  if (CheckResult == DAG &&
+      (CM_FOR_EACH_TRANSITIVE_PROPERTY_METHOD(
+        TEST_TRANSITIVE_PROPERTY_METHOD) false)) // NOLINT(clang-tidy)
 #undef TEST_TRANSITIVE_PROPERTY_METHOD
   {
     std::map<std::string, std::set<std::string> >::const_iterator it =
diff --git a/Source/cmGeneratorExpressionEvaluationFile.cxx b/Source/cmGeneratorExpressionEvaluationFile.cxx
index c6c4c3a..aeb005f 100644
--- a/Source/cmGeneratorExpressionEvaluationFile.cxx
+++ b/Source/cmGeneratorExpressionEvaluationFile.cxx
@@ -2,6 +2,11 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGeneratorExpressionEvaluationFile.h"
 
+#include <cmConfigure.h>
+#include <cmsys/FStream.hxx>
+#include <sstream>
+#include <utility>
+
 #include "cmGeneratedFileStream.h"
 #include "cmGlobalGenerator.h"
 #include "cmListFileCache.h"
@@ -9,13 +14,9 @@
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
 #include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
-#include <cmConfigure.h>
-#include <cmsys/FStream.hxx>
-#include <sstream>
-#include <utility>
-
 cmGeneratorExpressionEvaluationFile::cmGeneratorExpressionEvaluationFile(
   const std::string& input,
   CM_AUTO_PTR<cmCompiledGeneratorExpression> outputFileExpr,
diff --git a/Source/cmGeneratorExpressionEvaluationFile.h b/Source/cmGeneratorExpressionEvaluationFile.h
index d597270..26135df 100644
--- a/Source/cmGeneratorExpressionEvaluationFile.h
+++ b/Source/cmGeneratorExpressionEvaluationFile.h
@@ -5,14 +5,19 @@
 
 #include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmGeneratorExpression.h"
-
-#include <cm_auto_ptr.hxx>
 #include <map>
 #include <string>
-#include <sys/types.h>
 #include <vector>
 
+#include "cmGeneratorExpression.h"
+#include "cm_auto_ptr.hxx"
+
+#if defined(_MSC_VER)
+typedef unsigned short mode_t;
+#else
+#include <sys/types.h>
+#endif
+
 class cmLocalGenerator;
 
 class cmGeneratorExpressionEvaluationFile
diff --git a/Source/cmGeneratorExpressionEvaluator.h b/Source/cmGeneratorExpressionEvaluator.h
index 122e9cf..41bea9b 100644
--- a/Source/cmGeneratorExpressionEvaluator.h
+++ b/Source/cmGeneratorExpressionEvaluator.h
@@ -65,13 +65,15 @@ private:
 struct GeneratorExpressionContent : public cmGeneratorExpressionEvaluator
 {
   GeneratorExpressionContent(const char* startContent, size_t length);
-  void SetIdentifier(std::vector<cmGeneratorExpressionEvaluator*> identifier)
+  void SetIdentifier(
+    std::vector<cmGeneratorExpressionEvaluator*> const& identifier)
   {
     this->IdentifierChildren = identifier;
   }
 
   void SetParameters(
-    std::vector<std::vector<cmGeneratorExpressionEvaluator*> > parameters)
+    std::vector<std::vector<cmGeneratorExpressionEvaluator*> > const&
+      parameters)
   {
     this->ParamChildren = parameters;
   }
diff --git a/Source/cmGeneratorExpressionNode.cxx b/Source/cmGeneratorExpressionNode.cxx
index f866605..66202df 100644
--- a/Source/cmGeneratorExpressionNode.cxx
+++ b/Source/cmGeneratorExpressionNode.cxx
@@ -15,7 +15,7 @@
 #include "cmOutputConverter.h"
 #include "cmPolicies.h"
 #include "cmSourceFile.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cm_auto_ptr.hxx"
@@ -162,6 +162,27 @@ static const struct BoolNode : public cmGeneratorExpressionNode
   }
 } boolNode;
 
+static const struct IfNode : public cmGeneratorExpressionNode
+{
+  IfNode() {}
+
+  int NumExpectedParameters() const CM_OVERRIDE { return 3; }
+
+  std::string Evaluate(const std::vector<std::string>& parameters,
+                       cmGeneratorExpressionContext* context,
+                       const GeneratorExpressionContent* content,
+                       cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE
+  {
+    if (parameters[0] != "1" && parameters[0] != "0") {
+      reportError(context, content->GetOriginalExpression(),
+                  "First parameter to $<IF> must resolve to exactly one '0' "
+                  "or '1' value.");
+      return std::string();
+    }
+    return parameters[0] == "1" ? parameters[1] : parameters[2];
+  }
+} ifNode;
+
 static const struct StrEqualNode : public cmGeneratorExpressionNode
 {
   StrEqualNode() {}
@@ -1035,7 +1056,7 @@ static const struct TargetPropertyNode : public cmGeneratorExpressionNode
 #define TRANSITIVE_PROPERTY_COMPARE(PROPERTY)                                 \
   (#PROPERTY == propertyName || "INTERFACE_" #PROPERTY == propertyName) ||
         if (CM_FOR_EACH_TRANSITIVE_PROPERTY_NAME(
-              TRANSITIVE_PROPERTY_COMPARE) false) {
+              TRANSITIVE_PROPERTY_COMPARE) false) { // NOLINT(clang-tidy)
           reportError(
             context, content->GetOriginalExpression(),
             "$<TARGET_PROPERTY:...> expression in link libraries "
@@ -1052,7 +1073,7 @@ static const struct TargetPropertyNode : public cmGeneratorExpressionNode
 #define ASSERT_TRANSITIVE_PROPERTY_METHOD(METHOD) dagCheckerParent->METHOD() ||
 
         assert(CM_FOR_EACH_TRANSITIVE_PROPERTY_METHOD(
-          ASSERT_TRANSITIVE_PROPERTY_METHOD) false);
+          ASSERT_TRANSITIVE_PROPERTY_METHOD) false); // NOLINT(clang-tidy)
 #undef ASSERT_TRANSITIVE_PROPERTY_METHOD
       }
     }
@@ -1104,7 +1125,7 @@ static const struct TargetPropertyNode : public cmGeneratorExpressionNode
 
     if (!prop) {
       if (target->IsImported() ||
-          target->GetType() == cmState::INTERFACE_LIBRARY) {
+          target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
         return linkedTargetsContent;
       }
       if (target->IsLinkInterfaceDependentBoolProperty(propertyName,
@@ -1224,7 +1245,7 @@ static const struct TargetObjectsNode : public cmGeneratorExpressionNode
       reportError(context, content->GetOriginalExpression(), e.str());
       return std::string();
     }
-    if (gt->GetType() != cmState::OBJECT_LIBRARY) {
+    if (gt->GetType() != cmStateEnums::OBJECT_LIBRARY) {
       std::ostringstream e;
       e << "Objects of target \"" << tgtName
         << "\" referenced but is not an OBJECT library.";
@@ -1377,7 +1398,7 @@ cmPolicies::PolicyStatus statusForTarget(cmGeneratorTarget const* tgt,
 
 #undef RETURN_POLICY
 
-  assert(0 && "Unreachable code. Not a valid policy");
+  assert(false && "Unreachable code. Not a valid policy");
   return cmPolicies::WARN;
 }
 
@@ -1392,7 +1413,7 @@ cmPolicies::PolicyID policyForString(const char* policy_id)
 
 #undef RETURN_POLICY_ID
 
-  assert(0 && "Unreachable code. Not a valid policy");
+  assert(false && "Unreachable code. Not a valid policy");
   return cmPolicies::CMP0002;
 }
 
@@ -1506,7 +1527,7 @@ struct TargetFilesystemArtifactResultCreator<ArtifactSonameTag>
                     "for DLL target platforms.");
       return std::string();
     }
-    if (target->GetType() != cmState::SHARED_LIBRARY) {
+    if (target->GetType() != cmStateEnums::SHARED_LIBRARY) {
       ::reportError(context, content->GetOriginalExpression(),
                     "TARGET_SONAME_FILE is allowed only for "
                     "SHARED libraries.");
@@ -1542,11 +1563,11 @@ struct TargetFilesystemArtifactResultCreator<ArtifactPdbTag>
       return std::string();
     }
 
-    cmState::TargetType targetType = target->GetType();
+    cmStateEnums::TargetType targetType = target->GetType();
 
-    if (targetType != cmState::SHARED_LIBRARY &&
-        targetType != cmState::MODULE_LIBRARY &&
-        targetType != cmState::EXECUTABLE) {
+    if (targetType != cmStateEnums::SHARED_LIBRARY &&
+        targetType != cmStateEnums::MODULE_LIBRARY &&
+        targetType != cmStateEnums::EXECUTABLE) {
       ::reportError(context, content->GetOriginalExpression(),
                     "TARGET_PDB_FILE is allowed only for "
                     "targets with linker created artifacts.");
@@ -1646,8 +1667,8 @@ struct TargetFilesystemArtifact : public cmGeneratorExpressionNode
                     "No target \"" + name + "\"");
       return std::string();
     }
-    if (target->GetType() >= cmState::OBJECT_LIBRARY &&
-        target->GetType() != cmState::UNKNOWN_LIBRARY) {
+    if (target->GetType() >= cmStateEnums::OBJECT_LIBRARY &&
+        target->GetType() != cmStateEnums::UNKNOWN_LIBRARY) {
       ::reportError(context, content->GetOriginalExpression(), "Target \"" +
                       name + "\" is not an executable or library.");
       return std::string();
@@ -1757,6 +1778,7 @@ const cmGeneratorExpressionNode* cmGeneratorExpressionNode::GetNode(
     nodeMap["UPPER_CASE"] = &upperCaseNode;
     nodeMap["MAKE_C_IDENTIFIER"] = &makeCIdentifierNode;
     nodeMap["BOOL"] = &boolNode;
+    nodeMap["IF"] = &ifNode;
     nodeMap["ANGLE-R"] = &angle_rNode;
     nodeMap["COMMA"] = &commaNode;
     nodeMap["SEMICOLON"] = &semicolonNode;
diff --git a/Source/cmGeneratorExpressionParser.cxx b/Source/cmGeneratorExpressionParser.cxx
index 3b56416..c33349a 100644
--- a/Source/cmGeneratorExpressionParser.cxx
+++ b/Source/cmGeneratorExpressionParser.cxx
@@ -242,11 +242,11 @@ void cmGeneratorExpressionParser::ParseContent(
       if (this->NestingLevel == 0) {
         extendText(result, this->it);
       } else {
-        assert(0 && "Got unexpected syntax token.");
+        assert(false && "Got unexpected syntax token.");
       }
       assert(this->it != this->Tokens.end());
       ++this->it;
       return;
   }
-  assert(0 && "Unhandled token in generator expression.");
+  assert(false && "Unhandled token in generator expression.");
 }
diff --git a/Source/cmGeneratorTarget.cxx b/Source/cmGeneratorTarget.cxx
index e8d66a2..3fe5c83 100644
--- a/Source/cmGeneratorTarget.cxx
+++ b/Source/cmGeneratorTarget.cxx
@@ -2,6 +2,17 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGeneratorTarget.h"
 
+#include <algorithm>
+#include <assert.h>
+#include <cmsys/RegularExpression.hxx>
+#include <errno.h>
+#include <iterator>
+#include <queue>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
 #include "cmAlgorithms.h"
 #include "cmComputeLinkInformation.h"
 #include "cmCustomCommand.h"
@@ -15,32 +26,38 @@
 #include "cmPropertyMap.h"
 #include "cmSourceFile.h"
 #include "cmSourceFileLocation.h"
+#include "cmState.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cmTargetLinkLibraryType.h"
+#include "cmTargetPropertyComputer.h"
 #include "cm_auto_ptr.hxx"
+#include "cm_unordered_set.hxx"
 #include "cmake.h"
 
-#include <algorithm>
-#include <assert.h>
-#include <cmsys/RegularExpression.hxx>
-#include <errno.h>
-#include <iterator>
-#include <queue>
-#include <sstream>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
+class cmMessenger;
 
-#if defined(CMake_HAVE_CXX_UNORDERED_SET)
-#include <unordered_set>
-#define UNORDERED_SET std::unordered_set
-#elif defined(CMAKE_BUILD_WITH_CMAKE)
-#include <cmsys/hash_set.hxx>
-#define UNORDERED_SET cmsys::hash_set
-#else
-#define UNORDERED_SET std::set
-#endif
+template <>
+const char* cmTargetPropertyComputer::GetSources<cmGeneratorTarget>(
+  cmGeneratorTarget const* tgt, cmMessenger* /* messenger */,
+  cmListFileBacktrace const& /* context */)
+{
+  return tgt->GetSourcesProperty();
+}
+
+template <>
+const char* cmTargetPropertyComputer::ComputeLocationForBuild<
+  cmGeneratorTarget>(cmGeneratorTarget const* tgt)
+{
+  return tgt->GetLocation("");
+}
+
+template <>
+const char* cmTargetPropertyComputer::ComputeLocation<cmGeneratorTarget>(
+  cmGeneratorTarget const* tgt, const std::string& config)
+{
+  return tgt->GetLocation(config);
+}
 
 class cmGeneratorTarget::TargetPropertyEntry
 {
@@ -192,7 +209,7 @@ struct TagVisitor
     , Target(target)
     , GlobalGenerator(target->GetLocalGenerator()->GetGlobalGenerator())
     , Header(CM_HEADER_REGEX)
-    , IsObjLib(target->GetType() == cmState::OBJECT_LIBRARY)
+    , IsObjLib(target->GetType() == cmStateEnums::OBJECT_LIBRARY)
   {
   }
 
@@ -207,7 +224,7 @@ struct TagVisitor
     std::string ext = cmSystemTools::LowerCase(sf->GetExtension());
     if (sf->GetCustomCommand()) {
       DoAccept<IsSameTag<Tag, CustomCommandsTag>::Result>::Do(this->Data, sf);
-    } else if (this->Target->GetType() == cmState::UTILITY) {
+    } else if (this->Target->GetType() == cmStateEnums::UTILITY) {
       DoAccept<IsSameTag<Tag, ExtraSourcesTag>::Result>::Do(this->Data, sf);
     } else if (sf->GetPropertyAsBool("HEADER_FILE_ONLY")) {
       DoAccept<IsSameTag<Tag, HeaderSourcesTag>::Result>::Do(this->Data, sf);
@@ -320,12 +337,32 @@ cmGeneratorTarget::~cmGeneratorTarget()
   cmDeleteAll(this->LinkInformation);
 }
 
+const char* cmGeneratorTarget::GetSourcesProperty() const
+{
+  std::vector<std::string> values;
+  for (std::vector<cmGeneratorTarget::TargetPropertyEntry *>::const_iterator
+         it = this->SourceEntries.begin(),
+         end = this->SourceEntries.end();
+       it != end; ++it) {
+    values.push_back((*it)->ge->GetInput());
+  }
+  static std::string value;
+  value.clear();
+  value = cmJoin(values, "");
+  return value.c_str();
+}
+
+cmGlobalGenerator* cmGeneratorTarget::GetGlobalGenerator() const
+{
+  return this->GetLocalGenerator()->GetGlobalGenerator();
+}
+
 cmLocalGenerator* cmGeneratorTarget::GetLocalGenerator() const
 {
   return this->LocalGenerator;
 }
 
-cmState::TargetType cmGeneratorTarget::GetType() const
+cmStateEnums::TargetType cmGeneratorTarget::GetType() const
 {
   return this->Target->GetType();
 }
@@ -354,13 +391,25 @@ std::string cmGeneratorTarget::GetExportName() const
 
 const char* cmGeneratorTarget::GetProperty(const std::string& prop) const
 {
+  if (!cmTargetPropertyComputer::PassesWhitelist(
+        this->GetType(), prop, this->Makefile->GetMessenger(),
+        this->GetBacktrace())) {
+    return CM_NULLPTR;
+  }
+  if (const char* result = cmTargetPropertyComputer::GetProperty(
+        this, prop, this->Makefile->GetMessenger(), this->GetBacktrace())) {
+    return result;
+  }
+  if (cmSystemTools::GetFatalErrorOccured()) {
+    return CM_NULLPTR;
+  }
   return this->Target->GetProperty(prop);
 }
 
 const char* cmGeneratorTarget::GetOutputTargetType(bool implib) const
 {
   switch (this->GetType()) {
-    case cmState::SHARED_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
       if (this->IsDLLPlatform()) {
         if (implib) {
           // A DLL import library is treated as an archive target.
@@ -373,10 +422,10 @@ const char* cmGeneratorTarget::GetOutputTargetType(bool implib) const
         // library targets.
         return "LIBRARY";
       }
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
       // Static libraries are always treated as archive targets.
       return "ARCHIVE";
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       if (implib) {
         // Module libraries are always treated as library targets.
         return "ARCHIVE";
@@ -384,7 +433,7 @@ const char* cmGeneratorTarget::GetOutputTargetType(bool implib) const
         // Module import libraries are treated as archive targets.
         return "LIBRARY";
       }
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       if (implib) {
         // Executable import libraries are treated as archive targets.
         return "ARCHIVE";
@@ -484,6 +533,21 @@ void cmGeneratorTarget::AddTracedSources(std::vector<std::string> const& srcs)
   }
 }
 
+void cmGeneratorTarget::AddIncludeDirectory(const std::string& src,
+                                            bool before)
+{
+  this->Target->InsertInclude(src, this->Makefile->GetBacktrace(), before);
+  cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
+  cmGeneratorExpression ge(lfbt);
+  CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(src);
+  cge->SetEvaluateForBuildsystem(true);
+  // Insert before begin/end
+  std::vector<TargetPropertyEntry*>::iterator pos = before
+    ? this->IncludeDirectoriesEntries.begin()
+    : this->IncludeDirectoriesEntries.end();
+  this->IncludeDirectoriesEntries.insert(pos, new TargetPropertyEntry(cge));
+}
+
 std::vector<cmSourceFile*> const* cmGeneratorTarget::GetSourceDepends(
   cmSourceFile const* sf) const
 {
@@ -790,7 +854,7 @@ const char* cmGeneratorTarget::GetLocationForBuild() const
 bool cmGeneratorTarget::IsSystemIncludeDirectory(
   const std::string& dir, const std::string& config) const
 {
-  assert(this->GetType() != cmState::INTERFACE_LIBRARY);
+  assert(this->GetType() != cmStateEnums::INTERFACE_LIBRARY);
   std::string config_upper;
   if (!config.empty()) {
     config_upper = cmSystemTools::UpperCase(config);
@@ -870,7 +934,7 @@ static void AddInterfaceEntries(
 static bool processSources(
   cmGeneratorTarget const* tgt,
   const std::vector<cmGeneratorTarget::TargetPropertyEntry*>& entries,
-  std::vector<std::string>& srcs, UNORDERED_SET<std::string>& uniqueSrcs,
+  std::vector<std::string>& srcs, CM_UNORDERED_SET<std::string>& uniqueSrcs,
   cmGeneratorExpressionDAGChecker* dagChecker, std::string const& config,
   bool debugSources)
 {
@@ -951,7 +1015,7 @@ static bool processSources(
 void cmGeneratorTarget::GetSourceFiles(std::vector<std::string>& files,
                                        const std::string& config) const
 {
-  assert(this->GetType() != cmState::INTERFACE_LIBRARY);
+  assert(this->GetType() != cmStateEnums::INTERFACE_LIBRARY);
 
   if (!this->LocalGenerator->GetGlobalGenerator()->GetConfigureDoneCMP0026()) {
     // At configure-time, this method can be called as part of getting the
@@ -997,7 +1061,7 @@ void cmGeneratorTarget::GetSourceFiles(std::vector<std::string>& files,
   cmGeneratorExpressionDAGChecker dagChecker(this->GetName(), "SOURCES",
                                              CM_NULLPTR, CM_NULLPTR);
 
-  UNORDERED_SET<std::string> uniqueSrcs;
+  CM_UNORDERED_SET<std::string> uniqueSrcs;
   bool contextDependentDirectSources =
     processSources(this, this->SourceEntries, files, uniqueSrcs, &dagChecker,
                    config, debugSources);
@@ -1083,7 +1147,7 @@ std::string cmGeneratorTarget::GetCompilePDBPath(
 {
   std::string dir = this->GetCompilePDBDirectory(config);
   std::string name = this->GetCompilePDBName(config);
-  if (dir.empty() && !name.empty()) {
+  if (dir.empty() && !name.empty() && this->HaveWellDefinedOutputFiles()) {
     dir = this->GetPDBDirectory(config);
   }
   if (!dir.empty()) {
@@ -1096,7 +1160,7 @@ bool cmGeneratorTarget::HasSOName(const std::string& config) const
 {
   // soname is supported only for shared libraries and modules,
   // and then only when the platform supports an soname flag.
-  return ((this->GetType() == cmState::SHARED_LIBRARY) &&
+  return ((this->GetType() == cmStateEnums::SHARED_LIBRARY) &&
           !this->GetPropertyAsBool("NO_SONAME") &&
           this->Makefile->GetSONameFlag(this->GetLinkerLanguage(config)));
 }
@@ -1106,9 +1170,9 @@ bool cmGeneratorTarget::NeedRelinkBeforeInstall(
 {
   // Only executables and shared libraries can have an rpath and may
   // need relinking.
-  if (this->GetType() != cmState::EXECUTABLE &&
-      this->GetType() != cmState::SHARED_LIBRARY &&
-      this->GetType() != cmState::MODULE_LIBRARY) {
+  if (this->GetType() != cmStateEnums::EXECUTABLE &&
+      this->GetType() != cmStateEnums::SHARED_LIBRARY &&
+      this->GetType() != cmStateEnums::MODULE_LIBRARY) {
     return false;
   }
 
@@ -1180,9 +1244,9 @@ bool cmGeneratorTarget::NeedRelinkBeforeInstall(
 bool cmGeneratorTarget::IsChrpathUsed(const std::string& config) const
 {
   // Only certain target types have an rpath.
-  if (!(this->GetType() == cmState::SHARED_LIBRARY ||
-        this->GetType() == cmState::MODULE_LIBRARY ||
-        this->GetType() == cmState::EXECUTABLE)) {
+  if (!(this->GetType() == cmStateEnums::SHARED_LIBRARY ||
+        this->GetType() == cmStateEnums::MODULE_LIBRARY ||
+        this->GetType() == cmStateEnums::EXECUTABLE)) {
     return false;
   }
 
@@ -1237,7 +1301,7 @@ bool cmGeneratorTarget::IsChrpathUsed(const std::string& config) const
 bool cmGeneratorTarget::IsImportedSharedLibWithoutSOName(
   const std::string& config) const
 {
-  if (this->IsImported() && this->GetType() == cmState::SHARED_LIBRARY) {
+  if (this->IsImported() && this->GetType() == cmStateEnums::SHARED_LIBRARY) {
     if (cmGeneratorTarget::ImportInfo const* info =
           this->GetImportInfo(config)) {
       return info->NoSOName;
@@ -1253,7 +1317,7 @@ bool cmGeneratorTarget::HasMacOSXRpathInstallNameDir(
   bool macosx_rpath = false;
 
   if (!this->IsImported()) {
-    if (this->GetType() != cmState::SHARED_LIBRARY) {
+    if (this->GetType() != cmStateEnums::SHARED_LIBRARY) {
       return false;
     }
     const char* install_name = this->GetProperty("INSTALL_NAME_DIR");
@@ -1507,17 +1571,17 @@ const cmListFileBacktrace* cmGeneratorTarget::GetUtilityBacktrace(
 
 bool cmGeneratorTarget::HaveWellDefinedOutputFiles() const
 {
-  return this->GetType() == cmState::STATIC_LIBRARY ||
-    this->GetType() == cmState::SHARED_LIBRARY ||
-    this->GetType() == cmState::MODULE_LIBRARY ||
-    this->GetType() == cmState::EXECUTABLE;
+  return this->GetType() == cmStateEnums::STATIC_LIBRARY ||
+    this->GetType() == cmStateEnums::SHARED_LIBRARY ||
+    this->GetType() == cmStateEnums::MODULE_LIBRARY ||
+    this->GetType() == cmStateEnums::EXECUTABLE;
 }
 
 const char* cmGeneratorTarget::GetExportMacro() const
 {
   // Define the symbol for targets that export symbols.
-  if (this->GetType() == cmState::SHARED_LIBRARY ||
-      this->GetType() == cmState::MODULE_LIBRARY ||
+  if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
+      this->GetType() == cmStateEnums::MODULE_LIBRARY ||
       this->IsExecutableWithExports()) {
     if (const char* custom_export_name = this->GetProperty("DEFINE_SYMBOL")) {
       this->ExportMacro = custom_export_name;
@@ -1536,7 +1600,7 @@ class cmTargetCollectLinkLanguages
 public:
   cmTargetCollectLinkLanguages(cmGeneratorTarget const* target,
                                const std::string& config,
-                               UNORDERED_SET<std::string>& languages,
+                               CM_UNORDERED_SET<std::string>& languages,
                                cmGeneratorTarget const* head)
     : Config(config)
     , Languages(languages)
@@ -1603,7 +1667,7 @@ public:
 
 private:
   std::string Config;
-  UNORDERED_SET<std::string>& Languages;
+  CM_UNORDERED_SET<std::string>& Languages;
   cmGeneratorTarget const* HeadTarget;
   const cmGeneratorTarget* Target;
   std::set<cmGeneratorTarget const*> Visited;
@@ -1675,7 +1739,7 @@ void cmGeneratorTarget::ComputeLinkClosure(const std::string& config,
                                            LinkClosure& lc) const
 {
   // Get languages built in this target.
-  UNORDERED_SET<std::string> languages;
+  CM_UNORDERED_SET<std::string> languages;
   cmLinkImplementation const* impl = this->GetLinkImplementation(config);
   assert(impl);
   for (std::vector<std::string>::const_iterator li = impl->Languages.begin();
@@ -1692,7 +1756,7 @@ void cmGeneratorTarget::ComputeLinkClosure(const std::string& config,
   }
 
   // Store the transitive closure of languages.
-  for (UNORDERED_SET<std::string>::const_iterator li = languages.begin();
+  for (CM_UNORDERED_SET<std::string>::const_iterator li = languages.begin();
        li != languages.end(); ++li) {
     lc.Languages.push_back(*li);
   }
@@ -1713,7 +1777,7 @@ void cmGeneratorTarget::ComputeLinkClosure(const std::string& config,
     }
 
     // Now consider languages that propagate from linked targets.
-    for (UNORDERED_SET<std::string>::const_iterator sit = languages.begin();
+    for (CM_UNORDERED_SET<std::string>::const_iterator sit = languages.begin();
          sit != languages.end(); ++sit) {
       std::string propagates =
         "CMAKE_" + *sit + "_LINKER_PREFERENCE_PROPAGATES";
@@ -1767,6 +1831,22 @@ std::string cmGeneratorTarget::GetMacContentDirectory(
   return fpath;
 }
 
+std::string cmGeneratorTarget::GetEffectiveFolderName() const
+{
+  std::string effectiveFolder;
+
+  if (!this->GlobalGenerator->UseFolderProperty()) {
+    return effectiveFolder;
+  }
+
+  const char* targetFolder = this->GetProperty("FOLDER");
+  if (targetFolder) {
+    effectiveFolder += targetFolder;
+  }
+
+  return effectiveFolder;
+}
+
 cmGeneratorTarget::CompileInfo const* cmGeneratorTarget::GetCompileInfo(
   const std::string& config) const
 {
@@ -1775,7 +1855,7 @@ cmGeneratorTarget::CompileInfo const* cmGeneratorTarget::GetCompileInfo(
     return CM_NULLPTR;
   }
 
-  if (this->GetType() > cmState::OBJECT_LIBRARY) {
+  if (this->GetType() > cmStateEnums::OBJECT_LIBRARY) {
     std::string msg = "cmTarget::GetCompileInfo called for ";
     msg += this->GetName();
     msg += " which has type ";
@@ -1952,7 +2032,7 @@ cmTargetTraceDependencies::cmTargetTraceDependencies(cmGeneratorTarget* target)
   this->CurrentEntry = CM_NULLPTR;
 
   // Queue all the source files already specified for the target.
-  if (target->GetType() != cmState::INTERFACE_LIBRARY) {
+  if (target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
     std::vector<std::string> configs;
     this->Makefile->GetConfigurations(configs);
     if (configs.empty()) {
@@ -2087,8 +2167,8 @@ bool cmTargetTraceDependencies::IsUtility(std::string const& dep)
     // then make sure it was not a full path to something else, and
     // the fact that the name matched a target was just a coincidence.
     if (cmSystemTools::FileIsFullPath(dep.c_str())) {
-      if (t->GetType() >= cmState::EXECUTABLE &&
-          t->GetType() <= cmState::MODULE_LIBRARY) {
+      if (t->GetType() >= cmStateEnums::EXECUTABLE &&
+          t->GetType() <= cmStateEnums::MODULE_LIBRARY) {
         // This is really only for compatibility so we do not need to
         // worry about configuration names and output names.
         std::string tLocation = t->GetLocationForBuild();
@@ -2128,7 +2208,7 @@ void cmTargetTraceDependencies::CheckCustomCommand(cmCustomCommand const& cc)
     // Check for a target with this name.
     if (cmGeneratorTarget* t =
           this->LocalGenerator->FindGeneratorTargetToUse(command)) {
-      if (t->GetType() == cmState::EXECUTABLE) {
+      if (t->GetType() == cmStateEnums::EXECUTABLE) {
         // The command refers to an executable target built in
         // this project.  Add the target-level dependency to make
         // sure the executable is up to date before this custom
@@ -2202,7 +2282,7 @@ void cmGeneratorTarget::TraceDependencies()
   // would find nothing anyway, but when building CMake itself the "install"
   // target command ends up referencing the "cmake" target but we do not
   // really want the dependency because "install" depend on "all" anyway.
-  if (this->GetType() == cmState::GLOBAL_TARGET) {
+  if (this->GetType() == cmStateEnums::GLOBAL_TARGET) {
     return;
   }
 
@@ -2241,7 +2321,7 @@ std::string cmGeneratorTarget::GetCreateRuleVariable(
   std::string const& lang, std::string const& config) const
 {
   switch (this->GetType()) {
-    case cmState::STATIC_LIBRARY: {
+    case cmStateEnums::STATIC_LIBRARY: {
       std::string var = "CMAKE_" + lang + "_CREATE_STATIC_LIBRARY";
       if (this->GetFeatureAsBool("INTERPROCEDURAL_OPTIMIZATION", config)) {
         std::string varIPO = var + "_IPO";
@@ -2251,11 +2331,11 @@ std::string cmGeneratorTarget::GetCreateRuleVariable(
       }
       return var;
     }
-    case cmState::SHARED_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
       return "CMAKE_" + lang + "_CREATE_SHARED_LIBRARY";
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       return "CMAKE_" + lang + "_CREATE_SHARED_MODULE";
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       return "CMAKE_" + lang + "_LINK_EXECUTABLE";
     default:
       break;
@@ -2266,7 +2346,7 @@ static void processIncludeDirectories(
   cmGeneratorTarget const* tgt,
   const std::vector<cmGeneratorTarget::TargetPropertyEntry*>& entries,
   std::vector<std::string>& includes,
-  UNORDERED_SET<std::string>& uniqueIncludes,
+  CM_UNORDERED_SET<std::string>& uniqueIncludes,
   cmGeneratorExpressionDAGChecker* dagChecker, const std::string& config,
   bool debugIncludes, const std::string& language)
 {
@@ -2379,7 +2459,7 @@ std::vector<std::string> cmGeneratorTarget::GetIncludeDirectories(
   const std::string& config, const std::string& lang) const
 {
   std::vector<std::string> includes;
-  UNORDERED_SET<std::string> uniqueIncludes;
+  CM_UNORDERED_SET<std::string> uniqueIncludes;
 
   cmGeneratorExpressionDAGChecker dagChecker(
     this->GetName(), "INCLUDE_DIRECTORIES", CM_NULLPTR, CM_NULLPTR);
@@ -2456,7 +2536,8 @@ std::vector<std::string> cmGeneratorTarget::GetIncludeDirectories(
 static void processCompileOptionsInternal(
   cmGeneratorTarget const* tgt,
   const std::vector<cmGeneratorTarget::TargetPropertyEntry*>& entries,
-  std::vector<std::string>& options, UNORDERED_SET<std::string>& uniqueOptions,
+  std::vector<std::string>& options,
+  CM_UNORDERED_SET<std::string>& uniqueOptions,
   cmGeneratorExpressionDAGChecker* dagChecker, const std::string& config,
   bool debugOptions, const char* logName, std::string const& language)
 {
@@ -2493,7 +2574,8 @@ static void processCompileOptionsInternal(
 static void processCompileOptions(
   cmGeneratorTarget const* tgt,
   const std::vector<cmGeneratorTarget::TargetPropertyEntry*>& entries,
-  std::vector<std::string>& options, UNORDERED_SET<std::string>& uniqueOptions,
+  std::vector<std::string>& options,
+  CM_UNORDERED_SET<std::string>& uniqueOptions,
   cmGeneratorExpressionDAGChecker* dagChecker, const std::string& config,
   bool debugOptions, std::string const& language)
 {
@@ -2506,7 +2588,7 @@ void cmGeneratorTarget::GetCompileOptions(std::vector<std::string>& result,
                                           const std::string& config,
                                           const std::string& language) const
 {
-  UNORDERED_SET<std::string> uniqueOptions;
+  CM_UNORDERED_SET<std::string> uniqueOptions;
 
   cmGeneratorExpressionDAGChecker dagChecker(
     this->GetName(), "COMPILE_OPTIONS", CM_NULLPTR, CM_NULLPTR);
@@ -2546,7 +2628,8 @@ void cmGeneratorTarget::GetCompileOptions(std::vector<std::string>& result,
 static void processCompileFeatures(
   cmGeneratorTarget const* tgt,
   const std::vector<cmGeneratorTarget::TargetPropertyEntry*>& entries,
-  std::vector<std::string>& options, UNORDERED_SET<std::string>& uniqueOptions,
+  std::vector<std::string>& options,
+  CM_UNORDERED_SET<std::string>& uniqueOptions,
   cmGeneratorExpressionDAGChecker* dagChecker, const std::string& config,
   bool debugOptions)
 {
@@ -2558,7 +2641,7 @@ static void processCompileFeatures(
 void cmGeneratorTarget::GetCompileFeatures(std::vector<std::string>& result,
                                            const std::string& config) const
 {
-  UNORDERED_SET<std::string> uniqueFeatures;
+  CM_UNORDERED_SET<std::string> uniqueFeatures;
 
   cmGeneratorExpressionDAGChecker dagChecker(
     this->GetName(), "COMPILE_FEATURES", CM_NULLPTR, CM_NULLPTR);
@@ -2595,7 +2678,8 @@ void cmGeneratorTarget::GetCompileFeatures(std::vector<std::string>& result,
 static void processCompileDefinitions(
   cmGeneratorTarget const* tgt,
   const std::vector<cmGeneratorTarget::TargetPropertyEntry*>& entries,
-  std::vector<std::string>& options, UNORDERED_SET<std::string>& uniqueOptions,
+  std::vector<std::string>& options,
+  CM_UNORDERED_SET<std::string>& uniqueOptions,
   cmGeneratorExpressionDAGChecker* dagChecker, const std::string& config,
   bool debugOptions, std::string const& language)
 {
@@ -2608,7 +2692,7 @@ void cmGeneratorTarget::GetCompileDefinitions(
   std::vector<std::string>& list, const std::string& config,
   const std::string& language) const
 {
-  UNORDERED_SET<std::string> uniqueOptions;
+  CM_UNORDERED_SET<std::string> uniqueOptions;
 
   cmGeneratorExpressionDAGChecker dagChecker(
     this->GetName(), "COMPILE_DEFINITIONS", CM_NULLPTR, CM_NULLPTR);
@@ -2682,11 +2766,11 @@ void cmGeneratorTarget::ComputeTargetManifest(const std::string& config) const
   std::string realName;
   std::string impName;
   std::string pdbName;
-  if (this->GetType() == cmState::EXECUTABLE) {
+  if (this->GetType() == cmStateEnums::EXECUTABLE) {
     this->GetExecutableNames(name, realName, impName, pdbName, config);
-  } else if (this->GetType() == cmState::STATIC_LIBRARY ||
-             this->GetType() == cmState::SHARED_LIBRARY ||
-             this->GetType() == cmState::MODULE_LIBRARY) {
+  } else if (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
+             this->GetType() == cmStateEnums::SHARED_LIBRARY ||
+             this->GetType() == cmStateEnums::MODULE_LIBRARY) {
     this->GetLibraryNames(name, soName, realName, impName, pdbName, config);
   } else {
     return;
@@ -2729,6 +2813,16 @@ void cmGeneratorTarget::ComputeTargetManifest(const std::string& config) const
   }
 }
 
+std::string cmGeneratorTarget::GetImportedLibName(
+  std::string const& config) const
+{
+  if (cmGeneratorTarget::ImportInfo const* info =
+        this->GetImportInfo(config)) {
+    return info->LibName;
+  }
+  return std::string();
+}
+
 std::string cmGeneratorTarget::GetFullPath(const std::string& config,
                                            bool implib, bool realname) const
 {
@@ -2772,7 +2866,7 @@ std::string cmGeneratorTarget::NormalGetRealName(
     this->LocalGenerator->IssueMessage(cmake::INTERNAL_ERROR, msg);
   }
 
-  if (this->GetType() == cmState::EXECUTABLE) {
+  if (this->GetType() == cmStateEnums::EXECUTABLE) {
     // Compute the real name that will be built.
     std::string name;
     std::string realName;
@@ -2855,8 +2949,8 @@ void cmGeneratorTarget::GetLibraryNames(std::string& name, std::string& soName,
   }
 
   // The import library name.
-  if (this->GetType() == cmState::SHARED_LIBRARY ||
-      this->GetType() == cmState::MODULE_LIBRARY) {
+  if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
+      this->GetType() == cmStateEnums::MODULE_LIBRARY) {
     impName = this->GetFullNameInternal(config, true);
   } else {
     impName = "";
@@ -2888,7 +2982,7 @@ void cmGeneratorTarget::GetExecutableNames(std::string& name,
 #else
   // Check for executable version properties.
   const char* version = this->GetProperty("VERSION");
-  if (this->GetType() != cmState::EXECUTABLE ||
+  if (this->GetType() != cmStateEnums::EXECUTABLE ||
       this->Makefile->IsOn("XCODE")) {
     version = CM_NULLPTR;
   }
@@ -2957,10 +3051,10 @@ void cmGeneratorTarget::GetFullNameInternal(const std::string& config,
                                             std::string& outSuffix) const
 {
   // Use just the target name for non-main target types.
-  if (this->GetType() != cmState::STATIC_LIBRARY &&
-      this->GetType() != cmState::SHARED_LIBRARY &&
-      this->GetType() != cmState::MODULE_LIBRARY &&
-      this->GetType() != cmState::EXECUTABLE) {
+  if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
+      this->GetType() != cmStateEnums::SHARED_LIBRARY &&
+      this->GetType() != cmStateEnums::MODULE_LIBRARY &&
+      this->GetType() != cmStateEnums::EXECUTABLE) {
     outPrefix = "";
     outBase = this->GetName();
     outSuffix = "";
@@ -2979,9 +3073,9 @@ void cmGeneratorTarget::GetFullNameInternal(const std::string& config,
 
   // The implib option is only allowed for shared libraries, module
   // libraries, and executables.
-  if (this->GetType() != cmState::SHARED_LIBRARY &&
-      this->GetType() != cmState::MODULE_LIBRARY &&
-      this->GetType() != cmState::EXECUTABLE) {
+  if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
+      this->GetType() != cmStateEnums::MODULE_LIBRARY &&
+      this->GetType() != cmStateEnums::EXECUTABLE) {
     implib = false;
   }
 
@@ -3059,7 +3153,7 @@ void cmGeneratorTarget::GetFullNameInternal(const std::string& config,
 
   // Name shared libraries with their version number on some platforms.
   if (const char* soversion = this->GetProperty("SOVERSION")) {
-    if (this->GetType() == cmState::SHARED_LIBRARY && !implib &&
+    if (this->GetType() == cmStateEnums::SHARED_LIBRARY && !implib &&
         this->Makefile->IsOn("CMAKE_SHARED_LIBRARY_NAME_WITH_VERSION")) {
       outBase += "-";
       outBase += soversion;
@@ -3225,8 +3319,8 @@ cmGeneratorTarget::GetCompatibleInterfaces(std::string const& config) const
 bool cmGeneratorTarget::IsLinkInterfaceDependentBoolProperty(
   const std::string& p, const std::string& config) const
 {
-  if (this->GetType() == cmState::OBJECT_LIBRARY ||
-      this->GetType() == cmState::INTERFACE_LIBRARY) {
+  if (this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
+      this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
     return false;
   }
   return this->GetCompatibleInterfaces(config).PropsBool.count(p) > 0;
@@ -3235,8 +3329,8 @@ bool cmGeneratorTarget::IsLinkInterfaceDependentBoolProperty(
 bool cmGeneratorTarget::IsLinkInterfaceDependentStringProperty(
   const std::string& p, const std::string& config) const
 {
-  if (this->GetType() == cmState::OBJECT_LIBRARY ||
-      this->GetType() == cmState::INTERFACE_LIBRARY) {
+  if (this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
+      this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
     return false;
   }
   return this->GetCompatibleInterfaces(config).PropsString.count(p) > 0;
@@ -3245,8 +3339,8 @@ bool cmGeneratorTarget::IsLinkInterfaceDependentStringProperty(
 bool cmGeneratorTarget::IsLinkInterfaceDependentNumberMinProperty(
   const std::string& p, const std::string& config) const
 {
-  if (this->GetType() == cmState::OBJECT_LIBRARY ||
-      this->GetType() == cmState::INTERFACE_LIBRARY) {
+  if (this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
+      this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
     return false;
   }
   return this->GetCompatibleInterfaces(config).PropsNumberMin.count(p) > 0;
@@ -3255,8 +3349,8 @@ bool cmGeneratorTarget::IsLinkInterfaceDependentNumberMinProperty(
 bool cmGeneratorTarget::IsLinkInterfaceDependentNumberMaxProperty(
   const std::string& p, const std::string& config) const
 {
-  if (this->GetType() == cmState::OBJECT_LIBRARY ||
-      this->GetType() == cmState::INTERFACE_LIBRARY) {
+  if (this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
+      this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
     return false;
   }
   return this->GetCompatibleInterfaces(config).PropsNumberMax.count(p) > 0;
@@ -3295,7 +3389,8 @@ const char* getLinkInterfaceDependentProperty(cmGeneratorTarget const* tgt,
 {
   switch (t) {
     case BoolType:
-      assert(0 && "String compatibility check function called for boolean");
+      assert(false &&
+             "String compatibility check function called for boolean");
       return CM_NULLPTR;
     case StringType:
       return tgt->GetLinkInterfaceDependentStringProperty(prop, config);
@@ -3304,7 +3399,7 @@ const char* getLinkInterfaceDependentProperty(cmGeneratorTarget const* tgt,
     case NumberMaxType:
       return tgt->GetLinkInterfaceDependentNumberMaxProperty(prop, config);
   }
-  assert(0 && "Unreachable!");
+  assert(false && "Unreachable!");
   return CM_NULLPTR;
 }
 
@@ -3495,7 +3590,7 @@ std::string compatibilityType(CompatibleType t)
     case NumberMinType:
       return "Numeric minimum compatibility";
   }
-  assert(0 && "Unreachable!");
+  assert(false && "Unreachable!");
   return "";
 }
 
@@ -3509,7 +3604,7 @@ std::string compatibilityAgree(CompatibleType t, bool dominant)
     case NumberMinType:
       return dominant ? "(Dominant)\n" : "(Ignored)\n";
   }
-  assert(0 && "Unreachable!");
+  assert(false && "Unreachable!");
   return "";
 }
 
@@ -3619,7 +3714,7 @@ std::pair<bool, const char*> consistentProperty(const char* lhs,
 
   switch (t) {
     case BoolType:
-      assert(0 && "consistentProperty for strings called with BoolType");
+      assert(false && "consistentProperty for strings called with BoolType");
       return std::pair<bool, const char*>(false, null_ptr);
     case StringType:
       return consistentStringProperty(lhs, rhs);
@@ -3627,7 +3722,7 @@ std::pair<bool, const char*> consistentProperty(const char* lhs,
     case NumberMaxType:
       return consistentNumberProperty(lhs, rhs, t);
   }
-  assert(0 && "Unreachable!");
+  assert(false && "Unreachable!");
   return std::pair<bool, const char*>(false, null_ptr);
 }
 
@@ -3850,7 +3945,7 @@ void cmGeneratorTarget::GetTargetVersion(bool soversion, int& major,
   minor = 0;
   patch = 0;
 
-  assert(this->GetType() != cmState::INTERFACE_LIBRARY);
+  assert(this->GetType() != cmStateEnums::INTERFACE_LIBRARY);
 
   // Look for a VERSION or SOVERSION property.
   const char* prop = soversion ? "SOVERSION" : "VERSION";
@@ -3878,9 +3973,9 @@ std::string cmGeneratorTarget::GetFortranModuleDirectory(
   std::string const& working_dir) const
 {
   if (!this->FortranModuleDirectoryCreated) {
-    this->FortranModuleDirectory = true;
     this->FortranModuleDirectory =
       this->CreateFortranModuleDirectory(working_dir);
+    this->FortranModuleDirectoryCreated = true;
   }
 
   return this->FortranModuleDirectory;
@@ -3922,7 +4017,7 @@ std::string cmGeneratorTarget::CreateFortranModuleDirectory(
 
 std::string cmGeneratorTarget::GetFrameworkVersion() const
 {
-  assert(this->GetType() != cmState::INTERFACE_LIBRARY);
+  assert(this->GetType() != cmStateEnums::INTERFACE_LIBRARY);
 
   if (const char* fversion = this->GetProperty("FRAMEWORK_VERSION")) {
     return fversion;
@@ -3950,7 +4045,7 @@ void cmGeneratorTarget::ComputeVersionedName(std::string& vName,
 
 std::vector<std::string> cmGeneratorTarget::GetPropertyKeys() const
 {
-  cmPropertyMap propsObject = this->Target->GetProperties();
+  cmPropertyMap const& propsObject = this->Target->GetProperties();
   std::vector<std::string> props;
   props.reserve(propsObject.size());
   for (cmPropertyMap::const_iterator it = propsObject.begin();
@@ -4038,7 +4133,7 @@ cmLinkInterface const* cmGeneratorTarget::GetLinkInterface(
 
   // Link interfaces are not supported for executables that do not
   // export symbols.
-  if (this->GetType() == cmState::EXECUTABLE &&
+  if (this->GetType() == cmStateEnums::EXECUTABLE &&
       !this->IsExecutableWithExports()) {
     return CM_NULLPTR;
   }
@@ -4072,18 +4167,18 @@ void cmGeneratorTarget::ComputeLinkInterface(
   cmGeneratorTarget const* headTarget) const
 {
   if (iface.ExplicitLibraries) {
-    if (this->GetType() == cmState::SHARED_LIBRARY ||
-        this->GetType() == cmState::STATIC_LIBRARY ||
-        this->GetType() == cmState::INTERFACE_LIBRARY) {
+    if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
+        this->GetType() == cmStateEnums::STATIC_LIBRARY ||
+        this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       // Shared libraries may have runtime implementation dependencies
       // on other shared libraries that are not in the interface.
-      UNORDERED_SET<std::string> emitted;
+      CM_UNORDERED_SET<std::string> emitted;
       for (std::vector<cmLinkItem>::const_iterator li =
              iface.Libraries.begin();
            li != iface.Libraries.end(); ++li) {
         emitted.insert(*li);
       }
-      if (this->GetType() != cmState::INTERFACE_LIBRARY) {
+      if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
         cmLinkImplementation const* impl = this->GetLinkImplementation(config);
         for (std::vector<cmLinkImplItem>::const_iterator li =
                impl->Libraries.begin();
@@ -4091,7 +4186,7 @@ void cmGeneratorTarget::ComputeLinkInterface(
           if (emitted.insert(*li).second) {
             if (li->Target) {
               // This is a runtime dependency on another shared library.
-              if (li->Target->GetType() == cmState::SHARED_LIBRARY) {
+              if (li->Target->GetType() == cmStateEnums::SHARED_LIBRARY) {
                 iface.SharedDeps.push_back(*li);
               }
             } else {
@@ -4121,7 +4216,7 @@ void cmGeneratorTarget::ComputeLinkInterface(
     }
   }
 
-  if (this->GetType() == cmState::STATIC_LIBRARY) {
+  if (this->GetType() == cmStateEnums::STATIC_LIBRARY) {
     // Construct the property name suffix for this configuration.
     std::string suffix = "_";
     if (!config.empty()) {
@@ -4154,7 +4249,7 @@ const cmLinkInterfaceLibraries* cmGeneratorTarget::GetLinkInterfaceLibraries(
 
   // Link interfaces are not supported for executables that do not
   // export symbols.
-  if (this->GetType() == cmState::EXECUTABLE &&
+  if (this->GetType() == cmStateEnums::EXECUTABLE &&
       !this->IsExecutableWithExports()) {
     return CM_NULLPTR;
   }
@@ -4301,12 +4396,12 @@ bool cmGeneratorTarget::ComputeOutputDir(const std::string& config,
     if (out != outdir) {
       conf = "";
     }
-  } else if (this->GetType() == cmState::EXECUTABLE) {
+  } else if (this->GetType() == cmStateEnums::EXECUTABLE) {
     // Lookup the output path for executables.
     out = this->Makefile->GetSafeDefinition("EXECUTABLE_OUTPUT_PATH");
-  } else if (this->GetType() == cmState::STATIC_LIBRARY ||
-             this->GetType() == cmState::SHARED_LIBRARY ||
-             this->GetType() == cmState::MODULE_LIBRARY) {
+  } else if (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
+             this->GetType() == cmStateEnums::SHARED_LIBRARY ||
+             this->GetType() == cmStateEnums::MODULE_LIBRARY) {
     // Lookup the output path for libraries.
     out = this->Makefile->GetSafeDefinition("LIBRARY_OUTPUT_PATH");
   }
@@ -4324,9 +4419,10 @@ bool cmGeneratorTarget::ComputeOutputDir(const std::string& config,
 
   // The generator may add the configuration's subdirectory.
   if (!conf.empty()) {
-    bool iosPlatform = this->Makefile->PlatformIsAppleIos();
+    bool useEPN =
+      this->GlobalGenerator->UseEffectivePlatformName(this->Makefile);
     std::string suffix =
-      usesDefaultOutputDir && iosPlatform ? "${EFFECTIVE_PLATFORM_NAME}" : "";
+      usesDefaultOutputDir && useEPN ? "${EFFECTIVE_PLATFORM_NAME}" : "";
     this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
       "/", conf, suffix, out);
   }
@@ -4415,7 +4511,7 @@ void cmGeneratorTarget::ComputeLinkInterfaceLibraries(
     // CMP0022 NEW behavior is to use INTERFACE_LINK_LIBRARIES.
     linkIfaceProp = "INTERFACE_LINK_LIBRARIES";
     explicitLibraries = this->GetProperty(linkIfaceProp);
-  } else if (this->GetType() == cmState::SHARED_LIBRARY ||
+  } else if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
              this->IsExecutableWithExports()) {
     // CMP0022 OLD behavior is to use LINK_INTERFACE_LIBRARIES if set on a
     // shared lib or executable.
@@ -4460,8 +4556,9 @@ void cmGeneratorTarget::ComputeLinkInterfaceLibraries(
 
   // 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() == cmState::EXECUTABLE ||
-                             (this->GetType() == cmState::MODULE_LIBRARY))) {
+  if (!explicitLibraries &&
+      (this->GetType() == cmStateEnums::EXECUTABLE ||
+       (this->GetType() == cmStateEnums::MODULE_LIBRARY))) {
     return;
   }
   iface.Exists = true;
@@ -4590,7 +4687,7 @@ cmGeneratorTarget::ImportInfo const* cmGeneratorTarget::GetImportInfo(
     i = this->ImportInfoMap.insert(entry).first;
   }
 
-  if (this->GetType() == cmState::INTERFACE_LIBRARY) {
+  if (this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
     return &i->second;
   }
   // If the location is empty then the target is not available for
@@ -4625,7 +4722,7 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
     std::string linkProp = "INTERFACE_LINK_LIBRARIES";
     const char* propertyLibs = this->GetProperty(linkProp);
 
-    if (this->GetType() != cmState::INTERFACE_LIBRARY) {
+    if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
       if (!propertyLibs) {
         linkProp = "IMPORTED_LINK_INTERFACE_LIBRARIES";
         linkProp += suffix;
@@ -4642,7 +4739,10 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
       info.Libraries = propertyLibs;
     }
   }
-  if (this->GetType() == cmState::INTERFACE_LIBRARY) {
+  if (this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
+    if (loc) {
+      info.LibName = loc;
+    }
     return;
   }
 
@@ -4663,7 +4763,7 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
   }
 
   // Get the soname.
-  if (this->GetType() == cmState::SHARED_LIBRARY) {
+  if (this->GetType() == cmStateEnums::SHARED_LIBRARY) {
     std::string soProp = "IMPORTED_SONAME";
     soProp += suffix;
     if (const char* config_soname = this->GetProperty(soProp)) {
@@ -4674,7 +4774,7 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
   }
 
   // Get the "no-soname" mark.
-  if (this->GetType() == cmState::SHARED_LIBRARY) {
+  if (this->GetType() == cmStateEnums::SHARED_LIBRARY) {
     std::string soProp = "IMPORTED_NO_SONAME";
     soProp += suffix;
     if (const char* config_no_soname = this->GetProperty(soProp)) {
@@ -4688,7 +4788,7 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
   // Get the import library.
   if (imp) {
     info.ImportLibrary = imp;
-  } else if (this->GetType() == cmState::SHARED_LIBRARY ||
+  } else if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
              this->IsExecutableWithExports()) {
     std::string impProp = "IMPORTED_IMPLIB";
     impProp += suffix;
@@ -4724,7 +4824,7 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
   }
 
   // Get the cyclic repetition count.
-  if (this->GetType() == cmState::STATIC_LIBRARY) {
+  if (this->GetType() == cmStateEnums::STATIC_LIBRARY) {
     std::string linkProp = "IMPORTED_LINK_INTERFACE_MULTIPLICITY";
     linkProp += suffix;
     if (const char* config_reps = this->GetProperty(linkProp)) {
@@ -4965,6 +5065,9 @@ bool cmGeneratorTarget::HaveBuildTreeRPATH(const std::string& config) const
   if (this->GetPropertyAsBool("SKIP_BUILD_RPATH")) {
     return false;
   }
+  if (this->GetProperty("BUILD_RPATH")) {
+    return true;
+  }
   if (cmLinkImplementationLibraries const* impl =
         this->GetLinkImplementationLibraries(config)) {
     return !impl->Libraries.empty();
@@ -5117,12 +5220,12 @@ cmGeneratorTarget* cmGeneratorTarget::FindTargetToLink(
   // 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() == cmState::EXECUTABLE &&
+  if (tgt && tgt->GetType() == cmStateEnums::EXECUTABLE &&
       !tgt->IsExecutableWithExports()) {
     tgt = CM_NULLPTR;
   }
 
-  if (tgt && tgt->GetType() == cmState::OBJECT_LIBRARY) {
+  if (tgt && tgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
     std::ostringstream e;
     e << "Target \"" << this->GetName() << "\" links to "
                                            "OBJECT library \""
@@ -5168,14 +5271,14 @@ bool cmGeneratorTarget::GetImplibGNUtoMS(std::string const& gnuName,
 
 bool cmGeneratorTarget::IsExecutableWithExports() const
 {
-  return (this->GetType() == cmState::EXECUTABLE &&
+  return (this->GetType() == cmStateEnums::EXECUTABLE &&
           this->GetPropertyAsBool("ENABLE_EXPORTS"));
 }
 
 bool cmGeneratorTarget::HasImportLibrary() const
 {
   return (this->IsDLLPlatform() &&
-          (this->GetType() == cmState::SHARED_LIBRARY ||
+          (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
            this->IsExecutableWithExports()));
 }
 
@@ -5195,24 +5298,25 @@ std::string cmGeneratorTarget::GetSupportDirectory() const
 
 bool cmGeneratorTarget::IsLinkable() const
 {
-  return (this->GetType() == cmState::STATIC_LIBRARY ||
-          this->GetType() == cmState::SHARED_LIBRARY ||
-          this->GetType() == cmState::MODULE_LIBRARY ||
-          this->GetType() == cmState::UNKNOWN_LIBRARY ||
-          this->GetType() == cmState::INTERFACE_LIBRARY ||
+  return (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
+          this->GetType() == cmStateEnums::SHARED_LIBRARY ||
+          this->GetType() == cmStateEnums::MODULE_LIBRARY ||
+          this->GetType() == cmStateEnums::UNKNOWN_LIBRARY ||
+          this->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
           this->IsExecutableWithExports());
 }
 
 bool cmGeneratorTarget::IsFrameworkOnApple() const
 {
-  return (this->GetType() == cmState::SHARED_LIBRARY &&
+  return ((this->GetType() == cmStateEnums::SHARED_LIBRARY ||
+           this->GetType() == cmStateEnums::STATIC_LIBRARY) &&
           this->Makefile->IsOn("APPLE") &&
           this->GetPropertyAsBool("FRAMEWORK"));
 }
 
 bool cmGeneratorTarget::IsAppBundleOnApple() const
 {
-  return (this->GetType() == cmState::EXECUTABLE &&
+  return (this->GetType() == cmStateEnums::EXECUTABLE &&
           this->Makefile->IsOn("APPLE") &&
           this->GetPropertyAsBool("MACOSX_BUNDLE"));
 }
@@ -5224,6 +5328,6 @@ bool cmGeneratorTarget::IsXCTestOnApple() const
 
 bool cmGeneratorTarget::IsCFBundleOnApple() const
 {
-  return (this->GetType() == cmState::MODULE_LIBRARY &&
+  return (this->GetType() == cmStateEnums::MODULE_LIBRARY &&
           this->Makefile->IsOn("APPLE") && this->GetPropertyAsBool("BUNDLE"));
 }
diff --git a/Source/cmGeneratorTarget.h b/Source/cmGeneratorTarget.h
index 68ffd5c..f568699 100644
--- a/Source/cmGeneratorTarget.h
+++ b/Source/cmGeneratorTarget.h
@@ -8,7 +8,7 @@
 #include "cmLinkItem.h"
 #include "cmListFileCache.h"
 #include "cmPolicies.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 
 #include <map>
 #include <set>
@@ -32,6 +32,8 @@ public:
 
   cmLocalGenerator* GetLocalGenerator() const;
 
+  cmGlobalGenerator* GetGlobalGenerator() const;
+
   bool IsImported() const;
   bool IsImportedGloballyVisible() const;
   const char* GetLocation(const std::string& config) const;
@@ -58,7 +60,7 @@ public:
   cmComputeLinkInformation* GetLinkInformation(
     const std::string& config) const;
 
-  cmState::TargetType GetType() const;
+  cmStateEnums::TargetType GetType() const;
   const std::string& GetName() const;
   std::string GetExportName() const;
 
@@ -145,6 +147,9 @@ public:
                                      const cmGeneratorTarget* head,
                                      bool usage_requirements_only) const;
 
+  /** Get the library name for an imported interface library.  */
+  std::string GetImportedLibName(std::string const& config) const;
+
   /** Get the full path to the target according to the settings in its
       makefile and the configuration type.  */
   std::string GetFullPath(const std::string& config = "", bool implib = false,
@@ -196,7 +201,7 @@ public:
 
   bool LinkLanguagePropagatesToDependents() const
   {
-    return this->GetType() == cmState::STATIC_LIBRARY;
+    return this->GetType() == cmStateEnums::STATIC_LIBRARY;
   }
 
   /** Get the macro to define when building sources in this target.
@@ -220,6 +225,9 @@ public:
   std::string GetMacContentDirectory(const std::string& config = CM_NULLPTR,
                                      bool implib = false) const;
 
+  /** @return folder prefix for IDEs. */
+  std::string GetEffectiveFolderName() const;
+
   cmTarget* Target;
   cmMakefile* Makefile;
   cmLocalGenerator* LocalGenerator;
@@ -388,6 +396,12 @@ public:
   void AddTracedSources(std::vector<std::string> const& srcs);
 
   /**
+   * Adds an entry to the INCLUDE_DIRECTORIES list.
+   * If before is true the entry is pushed at the front.
+   */
+  void AddIncludeDirectory(const std::string& src, bool before = false);
+
+  /**
    * Flags for a given source file as used in this target. Typically assigned
    * via SET_TARGET_PROPERTIES when the property is a list of source files.
    */
@@ -530,6 +544,8 @@ public:
 
   std::string GetFortranModuleDirectory(std::string const& working_dir) const;
 
+  const char* GetSourcesProperty() const;
+
 private:
   void AddSourceCommon(const std::string& src);
 
@@ -636,6 +652,7 @@ private:
     std::string Location;
     std::string SOName;
     std::string ImportLibrary;
+    std::string LibName;
     std::string Languages;
     std::string Libraries;
     std::string LibrariesProp;
diff --git a/Source/cmGetCMakePropertyCommand.cxx b/Source/cmGetCMakePropertyCommand.cxx
index 11373b7..7962da6 100644
--- a/Source/cmGetCMakePropertyCommand.cxx
+++ b/Source/cmGetCMakePropertyCommand.cxx
@@ -2,10 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGetCMakePropertyCommand.h"
 
+#include <set>
+
 #include "cmAlgorithms.h"
 #include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
 #include "cmState.h"
-#include "cmake.h"
+
+class cmExecutionStatus;
 
 // cmGetCMakePropertyCommand
 bool cmGetCMakePropertyCommand::InitialPass(
diff --git a/Source/cmGetCMakePropertyCommand.h b/Source/cmGetCMakePropertyCommand.h
index 644db33..41a51a4 100644
--- a/Source/cmGetCMakePropertyCommand.h
+++ b/Source/cmGetCMakePropertyCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmGetCMakePropertyCommand_h
 #define cmGetCMakePropertyCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 class cmGetCMakePropertyCommand : public cmCommand
 {
 public:
@@ -26,8 +32,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "get_cmake_property"; }
-
-  cmTypeMacro(cmGetCMakePropertyCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmGetDirectoryPropertyCommand.cxx b/Source/cmGetDirectoryPropertyCommand.cxx
index 8ebad4e..920e1a0 100644
--- a/Source/cmGetDirectoryPropertyCommand.cxx
+++ b/Source/cmGetDirectoryPropertyCommand.cxx
@@ -2,8 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGetDirectoryPropertyCommand.h"
 
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmSystemTools.h"
 #include "cmake.h"
 
+class cmExecutionStatus;
+
 // cmGetDirectoryPropertyCommand
 bool cmGetDirectoryPropertyCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
diff --git a/Source/cmGetDirectoryPropertyCommand.h b/Source/cmGetDirectoryPropertyCommand.h
index c6d9329..1ae3125 100644
--- a/Source/cmGetDirectoryPropertyCommand.h
+++ b/Source/cmGetDirectoryPropertyCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmGetDirectoryPropertyCommand_h
 #define cmGetDirectoryPropertyCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 class cmGetDirectoryPropertyCommand : public cmCommand
 {
 public:
@@ -27,8 +33,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "get_directory_property"; }
 
-  cmTypeMacro(cmGetDirectoryPropertyCommand, cmCommand);
-
 private:
   void StoreResult(const std::string& variable, const char* prop);
 };
diff --git a/Source/cmGetFilenameComponentCommand.cxx b/Source/cmGetFilenameComponentCommand.cxx
index 05dbfb4..5915a67 100644
--- a/Source/cmGetFilenameComponentCommand.cxx
+++ b/Source/cmGetFilenameComponentCommand.cxx
@@ -2,8 +2,12 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGetFilenameComponentCommand.h"
 
+#include "cmMakefile.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 
+class cmExecutionStatus;
+
 // cmGetFilenameComponentCommand
 bool cmGetFilenameComponentCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
@@ -88,13 +92,13 @@ bool cmGetFilenameComponentCommand::InitialPass(
 
   if (args.size() >= 4 && args[args.size() - 1] == "CACHE") {
     if (!programArgs.empty() && !storeArgs.empty()) {
-      this->Makefile->AddCacheDefinition(storeArgs, programArgs.c_str(), "",
-                                         args[2] == "PATH" ? cmState::FILEPATH
-                                                           : cmState::STRING);
+      this->Makefile->AddCacheDefinition(
+        storeArgs, programArgs.c_str(), "",
+        args[2] == "PATH" ? cmStateEnums::FILEPATH : cmStateEnums::STRING);
     }
-    this->Makefile->AddCacheDefinition(args[0], result.c_str(), "",
-                                       args[2] == "PATH" ? cmState::FILEPATH
-                                                         : cmState::STRING);
+    this->Makefile->AddCacheDefinition(
+      args[0], result.c_str(), "",
+      args[2] == "PATH" ? cmStateEnums::FILEPATH : cmStateEnums::STRING);
   } else {
     if (!programArgs.empty() && !storeArgs.empty()) {
       this->Makefile->AddDefinition(storeArgs, programArgs.c_str());
diff --git a/Source/cmGetFilenameComponentCommand.h b/Source/cmGetFilenameComponentCommand.h
index 32096d1..c0ad903 100644
--- a/Source/cmGetFilenameComponentCommand.h
+++ b/Source/cmGetFilenameComponentCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmGetFilenameComponentCommand_h
 #define cmGetFilenameComponentCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmGetFilenameComponentCommand
  * \brief Get a specific component of a filename.
  *
@@ -35,8 +41,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "get_filename_component"; }
-
-  cmTypeMacro(cmGetFilenameComponentCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmGetPropertyCommand.cxx b/Source/cmGetPropertyCommand.cxx
index ba03568..d2056d2 100644
--- a/Source/cmGetPropertyCommand.cxx
+++ b/Source/cmGetPropertyCommand.cxx
@@ -2,13 +2,26 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGetPropertyCommand.h"
 
+#include <sstream>
+
 #include "cmGlobalGenerator.h"
+#include "cmInstalledFile.h"
+#include "cmListFileCache.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmProperty.h"
 #include "cmPropertyDefinition.h"
 #include "cmSourceFile.h"
 #include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmTargetPropertyComputer.h"
 #include "cmTest.h"
 #include "cmake.h"
 
+class cmExecutionStatus;
+class cmMessenger;
+
 cmGetPropertyCommand::cmGetPropertyCommand()
 {
   this->InfoType = OutValue;
@@ -246,8 +259,18 @@ bool cmGetPropertyCommand::HandleTargetMode()
       }
       return this->StoreResult(CM_NULLPTR);
     }
-    return this->StoreResult(
-      target->GetProperty(this->PropertyName, this->Makefile));
+    const char* prop_cstr = CM_NULLPTR;
+    cmListFileBacktrace bt = this->Makefile->GetBacktrace();
+    cmMessenger* messenger = this->Makefile->GetMessenger();
+    if (cmTargetPropertyComputer::PassesWhitelist(
+          target->GetType(), this->PropertyName, messenger, bt)) {
+      prop_cstr =
+        target->GetComputedProperty(this->PropertyName, messenger, bt);
+      if (!prop_cstr) {
+        prop_cstr = target->GetProperty(this->PropertyName);
+      }
+    }
+    return this->StoreResult(prop_cstr);
   }
   std::ostringstream e;
   e << "could not find TARGET " << this->Name
diff --git a/Source/cmGetPropertyCommand.h b/Source/cmGetPropertyCommand.h
index ee61416..f9a33ac 100644
--- a/Source/cmGetPropertyCommand.h
+++ b/Source/cmGetPropertyCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmGetPropertyCommand_h
 #define cmGetPropertyCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 class cmGetPropertyCommand : public cmCommand
 {
 public:
@@ -29,8 +35,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "get_property"; }
 
-  cmTypeMacro(cmGetPropertyCommand, cmCommand);
-
 private:
   enum OutType
   {
diff --git a/Source/cmGetSourceFilePropertyCommand.cxx b/Source/cmGetSourceFilePropertyCommand.cxx
index 43f9256..509ef95 100644
--- a/Source/cmGetSourceFilePropertyCommand.cxx
+++ b/Source/cmGetSourceFilePropertyCommand.cxx
@@ -2,8 +2,11 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGetSourceFilePropertyCommand.h"
 
+#include "cmMakefile.h"
 #include "cmSourceFile.h"
 
+class cmExecutionStatus;
+
 // cmSetSourceFilePropertyCommand
 bool cmGetSourceFilePropertyCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
diff --git a/Source/cmGetSourceFilePropertyCommand.h b/Source/cmGetSourceFilePropertyCommand.h
index 184b3ce..0f71851 100644
--- a/Source/cmGetSourceFilePropertyCommand.h
+++ b/Source/cmGetSourceFilePropertyCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmGetSourceFilePropertyCommand_h
 #define cmGetSourceFilePropertyCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 class cmGetSourceFilePropertyCommand : public cmCommand
 {
 public:
@@ -24,8 +30,6 @@ public:
   {
     return "get_source_file_property";
   }
-
-  cmTypeMacro(cmGetSourceFilePropertyCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmGetTargetPropertyCommand.cxx b/Source/cmGetTargetPropertyCommand.cxx
index fe09442..2379292 100644
--- a/Source/cmGetTargetPropertyCommand.cxx
+++ b/Source/cmGetTargetPropertyCommand.cxx
@@ -2,6 +2,18 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGetTargetPropertyCommand.h"
 
+#include <sstream>
+
+#include "cmListFileCache.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmTarget.h"
+#include "cmTargetPropertyComputer.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
+class cmMessenger;
+
 // cmSetTargetPropertyCommand
 bool cmGetTargetPropertyCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
@@ -22,7 +34,16 @@ bool cmGetTargetPropertyCommand::InitialPass(
         prop_exists = true;
       }
     } else if (!args[2].empty()) {
-      const char* prop_cstr = tgt->GetProperty(args[2], this->Makefile);
+      const char* prop_cstr = CM_NULLPTR;
+      cmListFileBacktrace bt = this->Makefile->GetBacktrace();
+      cmMessenger* messenger = this->Makefile->GetMessenger();
+      if (cmTargetPropertyComputer::PassesWhitelist(tgt->GetType(), args[2],
+                                                    messenger, bt)) {
+        prop_cstr = tgt->GetComputedProperty(args[2], messenger, bt);
+        if (!prop_cstr) {
+          prop_cstr = tgt->GetProperty(args[2]);
+        }
+      }
       if (prop_cstr) {
         prop = prop_cstr;
         prop_exists = true;
diff --git a/Source/cmGetTargetPropertyCommand.h b/Source/cmGetTargetPropertyCommand.h
index f16dea7..32fe803 100644
--- a/Source/cmGetTargetPropertyCommand.h
+++ b/Source/cmGetTargetPropertyCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmGetTargetPropertyCommand_h
 #define cmGetTargetPropertyCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 class cmGetTargetPropertyCommand : public cmCommand
 {
 public:
@@ -21,8 +27,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "get_target_property"; }
-
-  cmTypeMacro(cmGetTargetPropertyCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmGetTestPropertyCommand.cxx b/Source/cmGetTestPropertyCommand.cxx
index 4a445dc..a8a44b7 100644
--- a/Source/cmGetTestPropertyCommand.cxx
+++ b/Source/cmGetTestPropertyCommand.cxx
@@ -2,8 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGetTestPropertyCommand.h"
 
+#include "cmMakefile.h"
 #include "cmTest.h"
-#include "cmake.h"
+
+class cmExecutionStatus;
 
 // cmGetTestPropertyCommand
 bool cmGetTestPropertyCommand::InitialPass(
diff --git a/Source/cmGetTestPropertyCommand.h b/Source/cmGetTestPropertyCommand.h
index 527ee1a..0491cc8 100644
--- a/Source/cmGetTestPropertyCommand.h
+++ b/Source/cmGetTestPropertyCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmGetTestPropertyCommand_h
 #define cmGetTestPropertyCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 class cmGetTestPropertyCommand : public cmCommand
 {
 public:
@@ -21,8 +27,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "get_test_property"; }
-
-  cmTypeMacro(cmGetTestPropertyCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmGhsMultiGpj.h b/Source/cmGhsMultiGpj.h
index 793d471..2c2b123 100644
--- a/Source/cmGhsMultiGpj.h
+++ b/Source/cmGhsMultiGpj.h
@@ -5,8 +5,6 @@
 
 #include <cmConfigure.h>
 
-#include "cmStandardIncludes.h"
-
 class cmGeneratedFileStream;
 
 class GhsMultiGpj
diff --git a/Source/cmGhsMultiTargetGenerator.cxx b/Source/cmGhsMultiTargetGenerator.cxx
index 959dfdb..ba623d5 100644
--- a/Source/cmGhsMultiTargetGenerator.cxx
+++ b/Source/cmGhsMultiTargetGenerator.cxx
@@ -5,6 +5,7 @@
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalGhsMultiGenerator.h"
+#include "cmLinkLineComputer.h"
 #include "cmLocalGhsMultiGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
@@ -43,9 +44,7 @@ cmGhsMultiTargetGenerator::~cmGhsMultiTargetGenerator()
 std::string cmGhsMultiTargetGenerator::GetRelBuildFilePath(
   const cmGeneratorTarget* target)
 {
-  std::string output;
-  char const* folderProp = target->GetProperty("FOLDER");
-  output = NULL == folderProp ? "" : folderProp;
+  std::string output = target->GetEffectiveFolderName();
   cmSystemTools::ConvertToUnixSlashes(output);
   if (!output.empty()) {
     output += "/";
@@ -131,7 +130,7 @@ void cmGhsMultiTargetGenerator::Generate()
     this->WriteCompilerFlags(config, language);
     this->WriteCompilerDefinitions(config, language);
     this->WriteIncludes(config, language);
-    if (this->GeneratorTarget->GetType() == cmState::EXECUTABLE) {
+    if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
       this->WriteTargetLinkLibraries(config, language);
     }
     this->WriteCustomCommands();
@@ -175,7 +174,7 @@ GhsMultiGpj::Types cmGhsMultiTargetGenerator::GetGpjTag(
   GhsMultiGpj::Types output;
   if (cmGhsMultiTargetGenerator::DetermineIfTargetGroup(target)) {
     output = GhsMultiGpj::INTERGRITY_APPLICATION;
-  } else if (target->GetType() == cmState::STATIC_LIBRARY) {
+  } else if (target->GetType() == cmStateEnums::STATIC_LIBRARY) {
     output = GhsMultiGpj::LIBRARY;
   } else {
     output = GhsMultiGpj::PROGRAM;
@@ -196,13 +195,13 @@ void cmGhsMultiTargetGenerator::WriteTypeSpecifics(const std::string& config,
   std::string outputDir(this->GetOutputDirectory(config));
   std::string outputFilename(this->GetOutputFilename(config));
 
-  if (this->GeneratorTarget->GetType() == cmState::STATIC_LIBRARY) {
+  if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
     std::string const static_library_suffix =
       this->Makefile->GetSafeDefinition("CMAKE_STATIC_LIBRARY_SUFFIX");
     *this->GetFolderBuildStreams() << "    -o \"" << outputDir
                                    << outputFilename << static_library_suffix
                                    << "\"" << std::endl;
-  } else if (this->GeneratorTarget->GetType() == cmState::EXECUTABLE) {
+  } else if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
     if (notKernel && !this->IsTargetGroup()) {
       *this->GetFolderBuildStreams() << "    -relprog" << std::endl;
     }
@@ -244,7 +243,7 @@ void cmGhsMultiTargetGenerator::SetCompilerFlags(std::string const& config,
       flags, this->GeneratorTarget, lang);
 
     // Append old-style preprocessor definition flags.
-    if (std::string(" ") != std::string(this->Makefile->GetDefineFlags())) {
+    if (this->Makefile->GetDefineFlags() != " ") {
       this->LocalGenerator->AppendFlags(flags,
                                         this->Makefile->GetDefineFlags());
     }
@@ -362,9 +361,15 @@ void cmGhsMultiTargetGenerator::WriteTargetLinkLibraries(
       this->GeneratorTarget->GetCreateRuleVariable(language, config);
     bool useWatcomQuote =
       this->Makefile->IsOn(createRule + "_USE_WATCOM_QUOTE");
+    CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+      this->GetGlobalGenerator()->CreateLinkLineComputer(
+        this->LocalGenerator,
+        this->LocalGenerator->GetStateSnapshot().GetDirectory()));
+    linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
+
     this->LocalGenerator->GetTargetFlags(
-      config, linkLibraries, flags, linkFlags, frameworkPath, linkPath,
-      this->GeneratorTarget, useWatcomQuote);
+      linkLineComputer.get(), config, linkLibraries, flags, linkFlags,
+      frameworkPath, linkPath, this->GeneratorTarget);
     linkFlags = cmSystemTools::TrimWhitespace(linkFlags);
 
     if (!linkPath.empty()) {
diff --git a/Source/cmGlobalBorlandMakefileGenerator.cxx b/Source/cmGlobalBorlandMakefileGenerator.cxx
index 5a2150d..d2372a7 100644
--- a/Source/cmGlobalBorlandMakefileGenerator.cxx
+++ b/Source/cmGlobalBorlandMakefileGenerator.cxx
@@ -2,8 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalBorlandMakefileGenerator.h"
 
+#include "cmDocumentationEntry.h"
 #include "cmLocalUnixMakefileGenerator3.h"
 #include "cmMakefile.h"
+#include "cmState.h"
 #include "cmake.h"
 
 cmGlobalBorlandMakefileGenerator::cmGlobalBorlandMakefileGenerator(cmake* cm)
diff --git a/Source/cmGlobalGenerator.cxx b/Source/cmGlobalGenerator.cxx
index 7132ade..f118250 100644
--- a/Source/cmGlobalGenerator.cxx
+++ b/Source/cmGlobalGenerator.cxx
@@ -9,6 +9,16 @@
 
 #include "cmGlobalGenerator.h"
 
+#include <algorithm>
+#include <assert.h>
+#include <cmsys/Directory.hxx>
+#include <cmsys/FStream.hxx>
+#include <iterator>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
 #include "cmAlgorithms.h"
 #include "cmCPackPropertiesGenerator.h"
 #include "cmComputeTargetDepends.h"
@@ -20,32 +30,29 @@
 #include "cmGeneratorExpression.h"
 #include "cmGeneratorTarget.h"
 #include "cmInstallGenerator.h"
+#include "cmLinkLineComputer.h"
 #include "cmLocalGenerator.h"
+#include "cmMSVC60LinkLineComputer.h"
 #include "cmMakefile.h"
 #include "cmOutputConverter.h"
 #include "cmPolicies.h"
 #include "cmQtAutoGeneratorInitializer.h"
 #include "cmSourceFile.h"
 #include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateTypes.h"
 #include "cmVersion.h"
 #include "cmake.h"
 
-#include <algorithm>
-#include <assert.h>
-#include <cmsys/Directory.hxx>
-#include <cmsys/FStream.hxx>
-#include <iterator>
-#include <sstream>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
 #if defined(CMAKE_BUILD_WITH_CMAKE)
+#include "cmCryptoHash.h"
 #include <cm_jsoncpp_value.h>
 #include <cm_jsoncpp_writer.h>
-#include <cmsys/MD5.h>
 #endif
 
+const std::string kCMAKE_PLATFORM_INFO_INITIALIZED =
+  "CMAKE_PLATFORM_INFO_INITIALIZED";
+
 class cmInstalledFile;
 
 bool cmTarget::StrictTargetComparison::operator()(cmTarget const* t1,
@@ -266,12 +273,13 @@ bool cmGlobalGenerator::IsExportedTargetsFile(
 }
 
 // Find the make program for the generator, required for try compiles
-void cmGlobalGenerator::FindMakeProgram(cmMakefile* mf)
+bool cmGlobalGenerator::FindMakeProgram(cmMakefile* mf)
 {
   if (this->FindMakeProgramFile.empty()) {
     cmSystemTools::Error(
       "Generator implementation error, "
       "all generators must specify this->FindMakeProgramFile");
+    return false;
   }
   if (!mf->GetDefinition("CMAKE_MAKE_PROGRAM") ||
       cmSystemTools::IsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) {
@@ -289,7 +297,7 @@ void cmGlobalGenerator::FindMakeProgram(cmMakefile* mf)
         << "probably need to select a different build tool.";
     cmSystemTools::Error(err.str().c_str());
     cmSystemTools::SetFatalErrorOccured();
-    return;
+    return false;
   }
   std::string makeProgram = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM");
   // if there are spaces in the make program use short path
@@ -306,8 +314,9 @@ void cmGlobalGenerator::FindMakeProgram(cmMakefile* mf)
     makeProgram += "/";
     makeProgram += saveFile;
     mf->AddCacheDefinition("CMAKE_MAKE_PROGRAM", makeProgram.c_str(),
-                           "make program", cmState::FILEPATH);
+                           "make program", cmStateEnums::FILEPATH);
   }
+  return true;
 }
 
 bool cmGlobalGenerator::CheckLanguages(
@@ -422,8 +431,27 @@ void cmGlobalGenerator::EnableLanguage(
   // set the dir for parent files so they can be used by modules
   mf->AddDefinition("CMAKE_PLATFORM_INFO_DIR", rootBin.c_str());
 
+  if (!this->CMakeInstance->GetIsInTryCompile()) {
+    // Keep a mark in the cache to indicate that we've initialized the
+    // platform information directory.  If the platform information
+    // directory exists but the mark is missing then CMakeCache.txt
+    // has been removed or replaced without also removing the CMakeFiles/
+    // directory.  In this case remove the platform information directory
+    // so that it will be re-initialized and the relevant information
+    // restored in the cache.
+    if (cmSystemTools::FileIsDirectory(rootBin) &&
+        !mf->IsOn(kCMAKE_PLATFORM_INFO_INITIALIZED)) {
+      cmSystemTools::RemoveADirectory(rootBin);
+    }
+    this->GetCMakeInstance()->AddCacheEntry(
+      kCMAKE_PLATFORM_INFO_INITIALIZED, "1",
+      "Platform information initialized", cmStateEnums::INTERNAL);
+  }
+
   // find and make sure CMAKE_MAKE_PROGRAM is defined
-  this->FindMakeProgram(mf);
+  if (!this->FindMakeProgram(mf)) {
+    return;
+  }
 
   if (!this->CheckLanguages(languages, mf)) {
     return;
@@ -1060,7 +1088,7 @@ void cmGlobalGenerator::Configure()
   this->FirstTimeProgress = 0.0f;
   this->ClearGeneratorMembers();
 
-  cmState::Snapshot snapshot = this->CMakeInstance->GetCurrentSnapshot();
+  cmStateSnapshot snapshot = this->CMakeInstance->GetCurrentSnapshot();
 
   snapshot.GetDirectory().SetCurrentSource(
     this->CMakeInstance->GetHomeDirectory());
@@ -1101,7 +1129,7 @@ void cmGlobalGenerator::Configure()
   sprintf(num, "%d", static_cast<int>(this->Makefiles.size()));
   this->GetCMakeInstance()->AddCacheEntry("CMAKE_NUMBER_OF_MAKEFILES", num,
                                           "number of local generators",
-                                          cmState::INTERNAL);
+                                          cmStateEnums::INTERNAL);
 
   // check for link libraries and include directories containing "NOTFOUND"
   // and for infinite loops
@@ -1369,14 +1397,14 @@ cmGlobalGenerator::CreateQtAutoGeneratorsTargets()
     filteredTargets.reserve(targets.size());
     for (std::vector<cmGeneratorTarget*>::iterator ti = targets.begin();
          ti != targets.end(); ++ti) {
-      if ((*ti)->GetType() == cmState::GLOBAL_TARGET) {
+      if ((*ti)->GetType() == cmStateEnums::GLOBAL_TARGET) {
         continue;
       }
-      if ((*ti)->GetType() != cmState::EXECUTABLE &&
-          (*ti)->GetType() != cmState::STATIC_LIBRARY &&
-          (*ti)->GetType() != cmState::SHARED_LIBRARY &&
-          (*ti)->GetType() != cmState::MODULE_LIBRARY &&
-          (*ti)->GetType() != cmState::OBJECT_LIBRARY) {
+      if ((*ti)->GetType() != cmStateEnums::EXECUTABLE &&
+          (*ti)->GetType() != cmStateEnums::STATIC_LIBRARY &&
+          (*ti)->GetType() != cmStateEnums::SHARED_LIBRARY &&
+          (*ti)->GetType() != cmStateEnums::MODULE_LIBRARY &&
+          (*ti)->GetType() != cmStateEnums::OBJECT_LIBRARY) {
         continue;
       }
       if ((!(*ti)->GetPropertyAsBool("AUTOMOC") &&
@@ -1412,6 +1440,18 @@ cmGlobalGenerator::CreateQtAutoGeneratorsTargets()
   return autogenTargets;
 }
 
+cmLinkLineComputer* cmGlobalGenerator::CreateLinkLineComputer(
+  cmOutputConverter* outputConverter, cmStateDirectory stateDir) const
+{
+  return new cmLinkLineComputer(outputConverter, stateDir);
+}
+
+cmLinkLineComputer* cmGlobalGenerator::CreateMSVC60LinkLineComputer(
+  cmOutputConverter* outputConverter, cmStateDirectory stateDir) const
+{
+  return new cmMSVC60LinkLineComputer(outputConverter, stateDir);
+}
+
 void cmGlobalGenerator::FinalizeTargetCompileInfo()
 {
   std::vector<std::string> const langs =
@@ -1429,13 +1469,13 @@ void cmGlobalGenerator::FinalizeTargetCompileInfo()
     cmTargets& targets = mf->GetTargets();
     for (cmTargets::iterator ti = targets.begin(); ti != targets.end(); ++ti) {
       cmTarget* t = &ti->second;
-      if (t->GetType() == cmState::GLOBAL_TARGET) {
+      if (t->GetType() == cmStateEnums::GLOBAL_TARGET) {
         continue;
       }
 
       t->AppendBuildInterfaceIncludes();
 
-      if (t->GetType() == cmState::INTERFACE_LIBRARY) {
+      if (t->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
         continue;
       }
 
@@ -1561,7 +1601,7 @@ void cmGlobalGenerator::CheckTargetProperties()
     this->Makefiles[i]->ConfigureFinalPass();
     cmTargets& targets = this->Makefiles[i]->GetTargets();
     for (cmTargets::iterator l = targets.begin(); l != targets.end(); l++) {
-      if (l->second.GetType() == cmState::INTERFACE_LIBRARY) {
+      if (l->second.GetType() == cmStateEnums::INTERFACE_LIBRARY) {
         continue;
       }
       const cmTarget::LinkLibraryVectorType& libs =
@@ -1872,8 +1912,8 @@ void cmGlobalGenerator::EnableLanguagesFromGenerator(cmGlobalGenerator* gen,
   this->TryCompileOuterMakefile = mf;
   const char* make =
     gen->GetCMakeInstance()->GetCacheDefinition("CMAKE_MAKE_PROGRAM");
-  this->GetCMakeInstance()->AddCacheEntry("CMAKE_MAKE_PROGRAM", make,
-                                          "make program", cmState::FILEPATH);
+  this->GetCMakeInstance()->AddCacheEntry(
+    "CMAKE_MAKE_PROGRAM", make, "make program", cmStateEnums::FILEPATH);
   // copy the enabled languages
   this->GetCMakeInstance()->GetState()->SetEnabledLanguages(
     gen->GetCMakeInstance()->GetState()->GetEnabledLanguages());
@@ -1895,10 +1935,10 @@ void cmGlobalGenerator::SetConfiguredFilesPath(cmGlobalGenerator* gen)
   }
 }
 
-bool cmGlobalGenerator::IsExcluded(cmState::Snapshot const& rootSnp,
-                                   cmState::Snapshot const& snp_) const
+bool cmGlobalGenerator::IsExcluded(cmStateSnapshot const& rootSnp,
+                                   cmStateSnapshot const& snp_) const
 {
-  cmState::Snapshot snp = snp_;
+  cmStateSnapshot snp = snp_;
   while (snp.IsValid()) {
     if (snp == rootSnp) {
       // No directory excludes itself.
@@ -1919,8 +1959,8 @@ bool cmGlobalGenerator::IsExcluded(cmLocalGenerator* root,
 {
   assert(gen);
 
-  cmState::Snapshot rootSnp = root->GetStateSnapshot();
-  cmState::Snapshot snp = gen->GetStateSnapshot();
+  cmStateSnapshot rootSnp = root->GetStateSnapshot();
+  cmStateSnapshot snp = gen->GetStateSnapshot();
 
   return this->IsExcluded(rootSnp, snp);
 }
@@ -1928,7 +1968,7 @@ bool cmGlobalGenerator::IsExcluded(cmLocalGenerator* root,
 bool cmGlobalGenerator::IsExcluded(cmLocalGenerator* root,
                                    cmGeneratorTarget* target) const
 {
-  if (target->GetType() == cmState::INTERFACE_LIBRARY ||
+  if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
       target->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
     // This target is excluded from its directory.
     return true;
@@ -1960,7 +2000,7 @@ void cmGlobalGenerator::FillProjectMap()
   unsigned int i;
   for (i = 0; i < this->LocalGenerators.size(); ++i) {
     // for each local generator add all projects
-    cmState::Snapshot snp = this->LocalGenerators[i]->GetStateSnapshot();
+    cmStateSnapshot snp = this->LocalGenerators[i]->GetStateSnapshot();
     std::string name;
     do {
       std::string snpProjName = snp.GetProjectName();
@@ -2302,8 +2342,8 @@ void cmGlobalGenerator::AddGlobalTarget_Install(
     singleLine.push_back(cmd);
     if (cmakeCfgIntDir && *cmakeCfgIntDir && cmakeCfgIntDir[0] != '.') {
       std::string cfgArg = "-DBUILD_TYPE=";
-      bool iosPlatform = mf->PlatformIsAppleIos();
-      if (iosPlatform) {
+      bool useEPN = this->UseEffectivePlatformName(mf);
+      if (useEPN) {
         cfgArg += "$(CONFIGURATION)";
         singleLine.push_back(cfgArg);
         cfgArg = "-DEFFECTIVE_PLATFORM_NAME=$(EFFECTIVE_PLATFORM_NAME)";
@@ -2363,7 +2403,7 @@ const char* cmGlobalGenerator::GetPredefinedTargetsFolder()
   return "CMakePredefinedTargets";
 }
 
-bool cmGlobalGenerator::UseFolderProperty()
+bool cmGlobalGenerator::UseFolderProperty() const
 {
   const char* prop =
     this->GetCMakeInstance()->GetState()->GetGlobalProperty("USE_FOLDERS");
@@ -2384,8 +2424,8 @@ cmTarget cmGlobalGenerator::CreateGlobalTarget(GlobalTargetInfo const& gti,
                                                cmMakefile* mf)
 {
   // Package
-  cmTarget target(gti.Name, cmState::GLOBAL_TARGET, cmTarget::VisibilityNormal,
-                  mf);
+  cmTarget target(gti.Name, cmStateEnums::GLOBAL_TARGET,
+                  cmTarget::VisibilityNormal, mf);
   target.SetProperty("EXCLUDE_FROM_ALL", "TRUE");
 
   std::vector<std::string> no_outputs;
@@ -2530,7 +2570,7 @@ void cmGlobalGenerator::GetTargetSets(TargetDependSet& projectTargets,
 
 bool cmGlobalGenerator::IsRootOnlyTarget(cmGeneratorTarget* target) const
 {
-  return (target->GetType() == cmState::GLOBAL_TARGET ||
+  return (target->GetType() == cmStateEnums::GLOBAL_TARGET ||
           target->GetName() == this->GetAllTargetName());
 }
 
@@ -2597,14 +2637,9 @@ void cmGlobalGenerator::AddRuleHash(const std::vector<std::string>& outputs,
   // Compute a hash of the rule.
   RuleHash hash;
   {
-    unsigned char const* data =
-      reinterpret_cast<unsigned char const*>(content.c_str());
-    int length = static_cast<int>(content.length());
-    cmsysMD5* sum = cmsysMD5_New();
-    cmsysMD5_Initialize(sum);
-    cmsysMD5_Append(sum, data, length);
-    cmsysMD5_FinalizeHex(sum, hash.Data);
-    cmsysMD5_Delete(sum);
+    cmCryptoHash md5(cmCryptoHash::AlgoMD5);
+    std::string const md5_hex = md5.HashString(content);
+    memcpy(hash.Data, md5_hex.c_str(), 32);
   }
 
   // Shorten the output name (in expected use case).
@@ -2715,7 +2750,7 @@ void cmGlobalGenerator::WriteSummary()
       this->LocalGenerators[i]->GetGeneratorTargets();
     for (std::vector<cmGeneratorTarget*>::iterator it = tgts.begin();
          it != tgts.end(); ++it) {
-      if ((*it)->GetType() == cmState::INTERFACE_LIBRARY) {
+      if ((*it)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
         continue;
       }
       this->WriteSummary(*it);
diff --git a/Source/cmGlobalGenerator.h b/Source/cmGlobalGenerator.h
index add2b92..18e3730 100644
--- a/Source/cmGlobalGenerator.h
+++ b/Source/cmGlobalGenerator.h
@@ -5,12 +5,6 @@
 
 #include <cmConfigure.h>
 
-#include "cmExportSetMap.h"
-#include "cmState.h"
-#include "cmSystemTools.h"
-#include "cmTarget.h"
-#include "cmTargetDepend.h"
-
 #include <iosfwd>
 #include <map>
 #include <set>
@@ -18,22 +12,28 @@
 #include <utility>
 #include <vector>
 
+#include "cmCustomCommandLines.h"
+#include "cmExportSetMap.h"
+#include "cmStateSnapshot.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmTargetDepend.h"
+#include "cm_codecvt.hxx"
+#include "cm_unordered_map.hxx"
+
 #if defined(CMAKE_BUILD_WITH_CMAKE)
 #include "cmFileLockPool.h"
-#ifdef CMake_HAVE_CXX_UNORDERED_MAP
-#include <unordered_map>
-#else
-#include <cmsys/hash_map.hxx>
-#endif
 #endif
 
-class cmCustomCommandLines;
-class cmSourceFile;
 class cmExportBuildFileGenerator;
 class cmExternalMakefileProjectGenerator;
 class cmGeneratorTarget;
+class cmLinkLineComputer;
 class cmLocalGenerator;
 class cmMakefile;
+class cmOutputConverter;
+class cmSourceFile;
+class cmStateDirectory;
 class cmake;
 
 /** \class cmGlobalGenerator
@@ -60,6 +60,12 @@ public:
     return this->GetName() == name;
   }
 
+  /** Get encoding used by generator for makefile files */
+  virtual codecvt::Encoding GetMakefileEncoding() const
+  {
+    return codecvt::None;
+  }
+
   /** Tell the generator about the target system.  */
   virtual bool SetSystemName(std::string const&, cmMakefile*) { return true; }
 
@@ -98,6 +104,12 @@ public:
    */
   virtual void Generate();
 
+  virtual cmLinkLineComputer* CreateLinkLineComputer(
+    cmOutputConverter* outputConverter, cmStateDirectory stateDir) const;
+
+  cmLinkLineComputer* CreateMSVC60LinkLineComputer(
+    cmOutputConverter* outputConverter, cmStateDirectory stateDir) const;
+
   /**
    * Set/Get and Clear the enabled languages.
    */
@@ -234,7 +246,7 @@ public:
   /*
    * Determine what program to use for building the project.
    */
-  virtual void FindMakeProgram(cmMakefile*);
+  virtual bool FindMakeProgram(cmMakefile*);
 
   ///! Find a target by name by searching the local generators.
   cmTarget* FindTarget(const std::string& name,
@@ -319,6 +331,12 @@ public:
       i.e. "Can I build Debug and Release in the same tree?" */
   virtual bool IsMultiConfig() const { return false; }
 
+  virtual bool UseFolderProperty() const;
+
+  /** Return whether the generator should use EFFECTIVE_PLATFORM_NAME. This is
+      relevant for mixed macOS and iOS builds. */
+  virtual bool UseEffectivePlatformName(cmMakefile*) const { return false; }
+
   std::string GetSharedLibFlagsForLanguage(std::string const& lang) const;
 
   /** Generate an <output>.rule file path for a given command output.  */
@@ -393,8 +411,8 @@ protected:
   // has been populated.
   void FillProjectMap();
   void CheckTargetProperties();
-  bool IsExcluded(cmState::Snapshot const& root,
-                  cmState::Snapshot const& snp) const;
+  bool IsExcluded(cmStateSnapshot const& root,
+                  cmStateSnapshot const& snp) const;
   bool IsExcluded(cmLocalGenerator* root, cmLocalGenerator* gen) const;
   bool IsExcluded(cmLocalGenerator* root, cmGeneratorTarget* target) const;
   virtual void InitializeProgressMarks() {}
@@ -448,25 +466,11 @@ protected:
     std::string const& name) const;
 
   const char* GetPredefinedTargetsFolder();
-  virtual bool UseFolderProperty();
 
 private:
-#if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX_UNORDERED_MAP
-  typedef std::unordered_map<std::string, cmTarget*> TargetMap;
-  typedef std::unordered_map<std::string, cmGeneratorTarget*>
-    GeneratorTargetMap;
-  typedef std::unordered_map<std::string, cmMakefile*> MakefileMap;
-#else
-  typedef cmsys::hash_map<std::string, cmTarget*> TargetMap;
-  typedef cmsys::hash_map<std::string, cmGeneratorTarget*> GeneratorTargetMap;
-  typedef cmsys::hash_map<std::string, cmMakefile*> MakefileMap;
-#endif
-#else
-  typedef std::map<std::string, cmTarget*> TargetMap;
-  typedef std::map<std::string, cmGeneratorTarget*> GeneratorTargetMap;
-  typedef std::map<std::string, cmMakefile*> MakefileMap;
-#endif
+  typedef CM_UNORDERED_MAP<std::string, cmTarget*> TargetMap;
+  typedef CM_UNORDERED_MAP<std::string, cmGeneratorTarget*> GeneratorTargetMap;
+  typedef CM_UNORDERED_MAP<std::string, cmMakefile*> MakefileMap;
   // Map efficiently from target name to cmTarget instance.
   // Do not use this structure for looping over all targets.
   // It contains both normal and globally visible imported targets.
diff --git a/Source/cmGlobalGeneratorFactory.h b/Source/cmGlobalGeneratorFactory.h
index 528e118..5e948f7 100644
--- a/Source/cmGlobalGeneratorFactory.h
+++ b/Source/cmGlobalGeneratorFactory.h
@@ -5,12 +5,11 @@
 
 #include <cmConfigure.h>
 
-#include <cmConfigure.h>
-
-#include "cmStandardIncludes.h"
+#include <string>
+#include <vector>
 
-class cmake;
 class cmGlobalGenerator;
+class cmake;
 struct cmDocumentationEntry;
 
 /** \class cmGlobalGeneratorFactory
diff --git a/Source/cmGlobalGhsMultiGenerator.cxx b/Source/cmGlobalGhsMultiGenerator.cxx
index 0eac338..286f375 100644
--- a/Source/cmGlobalGhsMultiGenerator.cxx
+++ b/Source/cmGlobalGhsMultiGenerator.cxx
@@ -2,14 +2,16 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalGhsMultiGenerator.h"
 
+#include <cmsys/SystemTools.hxx>
+
+#include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorTarget.h"
 #include "cmGhsMultiTargetGenerator.h"
 #include "cmLocalGhsMultiGenerator.h"
 #include "cmMakefile.h"
 #include "cmVersion.h"
-#include <cmAlgorithms.h>
-#include <cmsys/SystemTools.hxx>
 
 const char* cmGlobalGhsMultiGenerator::FILE_EXTENSION = ".gpj";
 const char* cmGlobalGhsMultiGenerator::DEFAULT_MAKE_PROGRAM = "gbuild";
@@ -73,7 +75,7 @@ void cmGlobalGhsMultiGenerator::EnableLanguage(
   this->cmGlobalGenerator::EnableLanguage(l, mf, optional);
 }
 
-void cmGlobalGhsMultiGenerator::FindMakeProgram(cmMakefile* mf)
+bool cmGlobalGhsMultiGenerator::FindMakeProgram(cmMakefile* mf)
 {
   // The GHS generator knows how to lookup its build tool
   // directly instead of needing a helper module to do it, so we
@@ -82,6 +84,7 @@ void cmGlobalGhsMultiGenerator::FindMakeProgram(cmMakefile* mf)
     mf->AddDefinition("CMAKE_MAKE_PROGRAM",
                       this->GetGhsBuildCommand().c_str());
   }
+  return true;
 }
 
 std::string const& cmGlobalGhsMultiGenerator::GetGhsBuildCommand()
@@ -439,11 +442,7 @@ void cmGlobalGhsMultiGenerator::UpdateBuildFiles(
        tgtsI != tgts.end(); ++tgtsI) {
     const cmGeneratorTarget* tgt = *tgtsI;
     if (IsTgtForBuild(tgt)) {
-      char const* rawFolderName = tgt->GetProperty("FOLDER");
-      if (NULL == rawFolderName) {
-        rawFolderName = "";
-      }
-      std::string folderName(rawFolderName);
+      std::string folderName = tgt->GetEffectiveFolderName();
       if (this->TargetFolderBuildStreams.end() ==
           this->TargetFolderBuildStreams.find(folderName)) {
         this->AddFilesUpToPath(
diff --git a/Source/cmGlobalGhsMultiGenerator.h b/Source/cmGlobalGhsMultiGenerator.h
index 27a40ba..7b3eebb 100644
--- a/Source/cmGlobalGhsMultiGenerator.h
+++ b/Source/cmGlobalGhsMultiGenerator.h
@@ -57,7 +57,7 @@ public:
   /*
   * Determine what program to use for building the project.
   */
-  virtual void FindMakeProgram(cmMakefile*);
+  bool FindMakeProgram(cmMakefile* mf) CM_OVERRIDE;
 
   cmGeneratedFileStream* GetBuildFileStream()
   {
diff --git a/Source/cmGlobalJOMMakefileGenerator.cxx b/Source/cmGlobalJOMMakefileGenerator.cxx
index a846773..18c45e0 100644
--- a/Source/cmGlobalJOMMakefileGenerator.cxx
+++ b/Source/cmGlobalJOMMakefileGenerator.cxx
@@ -2,8 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalJOMMakefileGenerator.h"
 
+#include "cmDocumentationEntry.h"
 #include "cmLocalUnixMakefileGenerator3.h"
 #include "cmMakefile.h"
+#include "cmState.h"
 
 cmGlobalJOMMakefileGenerator::cmGlobalJOMMakefileGenerator(cmake* cm)
   : cmGlobalUnixMakefileGenerator3(cm)
diff --git a/Source/cmGlobalKdevelopGenerator.cxx b/Source/cmGlobalKdevelopGenerator.cxx
index 57d9aca..75209c3 100644
--- a/Source/cmGlobalKdevelopGenerator.cxx
+++ b/Source/cmGlobalKdevelopGenerator.cxx
@@ -8,7 +8,7 @@
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cmXMLWriter.h"
@@ -74,7 +74,7 @@ void cmGlobalKdevelopGenerator::Generate()
       for (std::vector<cmGeneratorTarget*>::const_iterator ti =
              targets.begin();
            ti != targets.end(); ti++) {
-        if ((*ti)->GetType() == cmState::EXECUTABLE) {
+        if ((*ti)->GetType() == cmStateEnums::EXECUTABLE) {
           executable = (*ti)->GetLocation("");
           break;
         }
diff --git a/Source/cmGlobalMSYSMakefileGenerator.cxx b/Source/cmGlobalMSYSMakefileGenerator.cxx
index 6d314d6..7e0d0d4 100644
--- a/Source/cmGlobalMSYSMakefileGenerator.cxx
+++ b/Source/cmGlobalMSYSMakefileGenerator.cxx
@@ -2,10 +2,13 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalMSYSMakefileGenerator.h"
 
+#include <cmsys/FStream.hxx>
+
+#include "cmDocumentationEntry.h"
 #include "cmLocalUnixMakefileGenerator3.h"
 #include "cmMakefile.h"
+#include "cmState.h"
 #include "cmake.h"
-#include <cmsys/FStream.hxx>
 
 cmGlobalMSYSMakefileGenerator::cmGlobalMSYSMakefileGenerator(cmake* cm)
   : cmGlobalUnixMakefileGenerator3(cm)
diff --git a/Source/cmGlobalMinGWMakefileGenerator.cxx b/Source/cmGlobalMinGWMakefileGenerator.cxx
index d5decfb..3c3a5d1 100644
--- a/Source/cmGlobalMinGWMakefileGenerator.cxx
+++ b/Source/cmGlobalMinGWMakefileGenerator.cxx
@@ -2,8 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalMinGWMakefileGenerator.h"
 
+#include "cmDocumentationEntry.h"
 #include "cmLocalUnixMakefileGenerator3.h"
 #include "cmMakefile.h"
+#include "cmState.h"
 
 cmGlobalMinGWMakefileGenerator::cmGlobalMinGWMakefileGenerator(cmake* cm)
   : cmGlobalUnixMakefileGenerator3(cm)
diff --git a/Source/cmGlobalNMakeMakefileGenerator.cxx b/Source/cmGlobalNMakeMakefileGenerator.cxx
index 48798fb..da683fb 100644
--- a/Source/cmGlobalNMakeMakefileGenerator.cxx
+++ b/Source/cmGlobalNMakeMakefileGenerator.cxx
@@ -2,8 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalNMakeMakefileGenerator.h"
 
+#include "cmDocumentationEntry.h"
 #include "cmLocalUnixMakefileGenerator3.h"
 #include "cmMakefile.h"
+#include "cmState.h"
 
 cmGlobalNMakeMakefileGenerator::cmGlobalNMakeMakefileGenerator(cmake* cm)
   : cmGlobalUnixMakefileGenerator3(cm)
diff --git a/Source/cmGlobalNMakeMakefileGenerator.h b/Source/cmGlobalNMakeMakefileGenerator.h
index f169e76..6eb2124 100644
--- a/Source/cmGlobalNMakeMakefileGenerator.h
+++ b/Source/cmGlobalNMakeMakefileGenerator.h
@@ -26,6 +26,12 @@ public:
   }
   static std::string GetActualName() { return "NMake Makefiles"; }
 
+  /** Get encoding used by generator for makefile files */
+  codecvt::Encoding GetMakefileEncoding() const CM_OVERRIDE
+  {
+    return codecvt::ANSI;
+  }
+
   /** Get the documentation entry for this generator.  */
   static void GetDocumentation(cmDocumentationEntry& entry);
 
diff --git a/Source/cmGlobalNinjaGenerator.cxx b/Source/cmGlobalNinjaGenerator.cxx
index 5e6036d..1bdef53 100644
--- a/Source/cmGlobalNinjaGenerator.cxx
+++ b/Source/cmGlobalNinjaGenerator.cxx
@@ -2,6 +2,17 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalNinjaGenerator.h"
 
+#include <algorithm>
+#include <cm_jsoncpp_reader.h>
+#include <cm_jsoncpp_value.h>
+#include <cm_jsoncpp_writer.h>
+#include <cmsys/FStream.hxx>
+#include <ctype.h>
+#include <functional>
+#include <iterator>
+#include <sstream>
+#include <stdio.h>
+
 #include "cmAlgorithms.h"
 #include "cmDocumentationEntry.h"
 #include "cmFortranParser.h"
@@ -11,8 +22,12 @@
 #include "cmLocalGenerator.h"
 #include "cmLocalNinjaGenerator.h"
 #include "cmMakefile.h"
+#include "cmNinjaLinkLineComputer.h"
 #include "cmOutputConverter.h"
 #include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cmTargetDepend.h"
@@ -20,19 +35,16 @@
 #include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
-#include "cm_jsoncpp_reader.h"
-#include "cm_jsoncpp_writer.h"
-
-#include <algorithm>
-#include <ctype.h>
-#include <functional>
-#include <iterator>
-#include <sstream>
-#include <stdio.h>
+class cmLinkLineComputer;
 
 const char* cmGlobalNinjaGenerator::NINJA_BUILD_FILE = "build.ninja";
 const char* cmGlobalNinjaGenerator::NINJA_RULES_FILE = "rules.ninja";
 const char* cmGlobalNinjaGenerator::INDENT = "  ";
+#ifdef _WIN32
+std::string const cmGlobalNinjaGenerator::SHELL_NOOP = "cd .";
+#else
+std::string const cmGlobalNinjaGenerator::SHELL_NOOP = ":";
+#endif
 
 void cmGlobalNinjaGenerator::Indent(std::ostream& os, int count)
 {
@@ -64,6 +76,14 @@ void cmGlobalNinjaGenerator::WriteComment(std::ostream& os,
   os << "# " << comment.substr(lpos) << "\n\n";
 }
 
+cmLinkLineComputer* cmGlobalNinjaGenerator::CreateLinkLineComputer(
+  cmOutputConverter* outputConverter, cmStateDirectory /* stateDir */) const
+{
+  return new cmNinjaLinkLineComputer(
+    outputConverter,
+    this->LocalGenerators[0]->GetStateSnapshot().GetDirectory(), this);
+}
+
 std::string cmGlobalNinjaGenerator::EncodeRuleName(std::string const& name)
 {
   // Ninja rule names must match "[a-zA-Z0-9_.-]+".  Use ".xx" to encode
@@ -116,7 +136,7 @@ std::string cmGlobalNinjaGenerator::EncodeLiteral(const std::string& lit)
 
 std::string cmGlobalNinjaGenerator::EncodePath(const std::string& path)
 {
-  std::string result = path;
+  std::string result = path; // NOLINT(clang-tidy)
 #ifdef _WIN32
   if (this->IsGCCOnWindows())
     std::replace(result.begin(), result.end(), '\\', '/');
@@ -269,7 +289,7 @@ void cmGlobalNinjaGenerator::WriteCustomCommandBuild(
   bool restat, const cmNinjaDeps& outputs, const cmNinjaDeps& deps,
   const cmNinjaDeps& orderOnly)
 {
-  std::string cmd = command;
+  std::string cmd = command; // NOLINT(clang-tidy)
 #ifdef _WIN32
   if (cmd.empty())
     // TODO Shouldn't an empty command be handled by ninja?
@@ -487,6 +507,18 @@ cmLocalGenerator* cmGlobalNinjaGenerator::CreateLocalGenerator(cmMakefile* mf)
   return new cmLocalNinjaGenerator(this, mf);
 }
 
+codecvt::Encoding cmGlobalNinjaGenerator::GetMakefileEncoding() const
+{
+#ifdef _WIN32
+  // Ninja on Windows does not support non-ANSI characters.
+  // https://github.com/ninja-build/ninja/issues/1195
+  return codecvt::ANSI;
+#else
+  // No encoding conversion needed on other platforms.
+  return codecvt::None;
+#endif
+}
+
 void cmGlobalNinjaGenerator::GetDocumentation(cmDocumentationEntry& entry)
 {
   entry.Name = cmGlobalNinjaGenerator::GetActualName();
@@ -544,20 +576,32 @@ void cmGlobalNinjaGenerator::Generate()
   this->CloseBuildFileStream();
 }
 
-void cmGlobalNinjaGenerator::FindMakeProgram(cmMakefile* mf)
+bool cmGlobalNinjaGenerator::FindMakeProgram(cmMakefile* mf)
 {
-  this->cmGlobalGenerator::FindMakeProgram(mf);
+  if (!this->cmGlobalGenerator::FindMakeProgram(mf)) {
+    return false;
+  }
   if (const char* ninjaCommand = mf->GetDefinition("CMAKE_MAKE_PROGRAM")) {
     this->NinjaCommand = ninjaCommand;
     std::vector<std::string> command;
     command.push_back(this->NinjaCommand);
     command.push_back("--version");
     std::string version;
-    cmSystemTools::RunSingleCommand(command, &version, CM_NULLPTR, CM_NULLPTR,
-                                    CM_NULLPTR, cmSystemTools::OUTPUT_NONE);
+    std::string error;
+    if (!cmSystemTools::RunSingleCommand(command, &version, &error, CM_NULLPTR,
+                                         CM_NULLPTR,
+                                         cmSystemTools::OUTPUT_NONE)) {
+      mf->IssueMessage(cmake::FATAL_ERROR, "Running\n '" +
+                         cmJoin(command, "' '") + "'\n"
+                                                  "failed with:\n " +
+                         error);
+      cmSystemTools::SetFatalErrorOccured();
+      return false;
+    }
     this->NinjaVersion = cmSystemTools::TrimWhitespace(version);
     this->CheckNinjaFeatures();
   }
+  return true;
 }
 
 void cmGlobalNinjaGenerator::CheckNinjaFeatures()
@@ -745,7 +789,8 @@ void cmGlobalNinjaGenerator::OpenBuildFileStream()
 
   // Get a stream where to generate things.
   if (!this->BuildFileStream) {
-    this->BuildFileStream = new cmGeneratedFileStream(buildFilePath.c_str());
+    this->BuildFileStream = new cmGeneratedFileStream(
+      buildFilePath.c_str(), false, this->GetMakefileEncoding());
     if (!this->BuildFileStream) {
       // An error message is generated by the constructor if it cannot
       // open the file.
@@ -782,7 +827,8 @@ void cmGlobalNinjaGenerator::OpenRulesFileStream()
 
   // Get a stream where to generate things.
   if (!this->RulesFileStream) {
-    this->RulesFileStream = new cmGeneratedFileStream(rulesFilePath.c_str());
+    this->RulesFileStream = new cmGeneratedFileStream(
+      rulesFilePath.c_str(), false, this->GetMakefileEncoding());
     if (!this->RulesFileStream) {
       // An error message is generated by the constructor if it cannot
       // open the file.
@@ -830,7 +876,8 @@ static void EnsureTrailingSlash(std::string& path)
 #endif
 }
 
-std::string cmGlobalNinjaGenerator::ConvertToNinjaPath(const std::string& path)
+std::string cmGlobalNinjaGenerator::ConvertToNinjaPath(
+  const std::string& path) const
 {
   cmLocalNinjaGenerator* ng =
     static_cast<cmLocalNinjaGenerator*>(this->LocalGenerators[0]);
@@ -932,17 +979,17 @@ void cmGlobalNinjaGenerator::AppendTargetOutputs(
   bool realname = target->IsFrameworkOnApple();
 
   switch (target->GetType()) {
-    case cmState::EXECUTABLE:
-    case cmState::SHARED_LIBRARY:
-    case cmState::STATIC_LIBRARY:
-    case cmState::MODULE_LIBRARY: {
+    case cmStateEnums::EXECUTABLE:
+    case cmStateEnums::SHARED_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY: {
       outputs.push_back(this->ConvertToNinjaPath(
         target->GetFullPath(configName, false, realname)));
       break;
     }
-    case cmState::OBJECT_LIBRARY:
-    case cmState::GLOBAL_TARGET:
-    case cmState::UTILITY: {
+    case cmStateEnums::OBJECT_LIBRARY:
+    case cmStateEnums::GLOBAL_TARGET:
+    case cmStateEnums::UTILITY: {
       std::string path =
         target->GetLocalGenerator()->GetCurrentBinaryDirectory() +
         std::string("/") + target->GetName();
@@ -958,7 +1005,7 @@ void cmGlobalNinjaGenerator::AppendTargetOutputs(
 void cmGlobalNinjaGenerator::AppendTargetDepends(
   cmGeneratorTarget const* target, cmNinjaDeps& outputs)
 {
-  if (target->GetType() == cmState::GLOBAL_TARGET) {
+  if (target->GetType() == cmStateEnums::GLOBAL_TARGET) {
     // These depend only on other CMake-provided targets, e.g. "all".
     std::set<std::string> const& utils = target->GetUtilities();
     for (std::set<std::string>::const_iterator i = utils.begin();
@@ -973,7 +1020,7 @@ void cmGlobalNinjaGenerator::AppendTargetDepends(
     cmTargetDependSet const& targetDeps = this->GetTargetDirectDepends(target);
     for (cmTargetDependSet::const_iterator i = targetDeps.begin();
          i != targetDeps.end(); ++i) {
-      if ((*i)->GetType() == cmState::INTERFACE_LIBRARY) {
+      if ((*i)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
         continue;
       }
       this->AppendTargetOutputs(*i, outs);
@@ -1010,7 +1057,7 @@ void cmGlobalNinjaGenerator::ComputeTargetDependsClosure(
   cmTargetDependSet const& targetDeps = this->GetTargetDirectDepends(target);
   for (cmTargetDependSet::const_iterator i = targetDeps.begin();
        i != targetDeps.end(); ++i) {
-    if ((*i)->GetType() == cmState::INTERFACE_LIBRARY) {
+    if ((*i)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     if (depends.insert(*i).second) {
@@ -1078,11 +1125,13 @@ void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os)
            lg->GetGeneratorTargets().begin();
          ti != lg->GetGeneratorTargets().end(); ++ti) {
       cmGeneratorTarget const* gt = *ti;
-      cmState::TargetType const type = gt->GetType();
-      if ((type == cmState::EXECUTABLE || type == cmState::STATIC_LIBRARY ||
-           type == cmState::SHARED_LIBRARY ||
-           type == cmState::MODULE_LIBRARY ||
-           type == cmState::OBJECT_LIBRARY || type == cmState::UTILITY) &&
+      cmStateEnums::TargetType const type = gt->GetType();
+      if ((type == cmStateEnums::EXECUTABLE ||
+           type == cmStateEnums::STATIC_LIBRARY ||
+           type == cmStateEnums::SHARED_LIBRARY ||
+           type == cmStateEnums::MODULE_LIBRARY ||
+           type == cmStateEnums::OBJECT_LIBRARY ||
+           type == cmStateEnums::UTILITY) &&
           !gt->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
         targetsPerFolder[currentBinaryFolder].push_back(gt->GetName());
       }
@@ -1090,9 +1139,9 @@ void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os)
 
     // The directory-level rule should depend on the directory-level
     // rules of the subdirectories.
-    std::vector<cmState::Snapshot> const& children =
+    std::vector<cmStateSnapshot> const& children =
       lg->GetStateSnapshot().GetChildren();
-    for (std::vector<cmState::Snapshot>::const_iterator stateIt =
+    for (std::vector<cmStateSnapshot>::const_iterator stateIt =
            children.begin();
          stateIt != children.end(); ++stateIt) {
       std::string const currentBinaryDir =
@@ -1409,7 +1458,8 @@ void cmGlobalNinjaGenerator::InitOutputPathPrefix()
   EnsureTrailingSlash(this->OutputPathPrefix);
 }
 
-std::string cmGlobalNinjaGenerator::NinjaOutputPath(std::string const& path)
+std::string cmGlobalNinjaGenerator::NinjaOutputPath(
+  std::string const& path) const
 {
   if (!this->HasOutputPathPrefix() || cmSystemTools::FileIsFullPath(path)) {
     return path;
@@ -1642,8 +1692,7 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile(
 {
   // Setup path conversions.
   {
-    cmState::Snapshot snapshot =
-      this->GetCMakeInstance()->GetCurrentSnapshot();
+    cmStateSnapshot snapshot = this->GetCMakeInstance()->GetCurrentSnapshot();
     snapshot.GetDirectory().SetCurrentSource(dir_cur_src);
     snapshot.GetDirectory().SetCurrentBinary(dir_cur_bld);
     snapshot.GetDirectory().SetRelativePathTopSource(dir_top_src.c_str());
diff --git a/Source/cmGlobalNinjaGenerator.h b/Source/cmGlobalNinjaGenerator.h
index 2ce3c80..a51e919 100644
--- a/Source/cmGlobalNinjaGenerator.h
+++ b/Source/cmGlobalNinjaGenerator.h
@@ -5,12 +5,6 @@
 
 #include <cmConfigure.h>
 
-#include "cmGlobalCommonGenerator.h"
-#include "cmGlobalGenerator.h"
-#include "cmGlobalGeneratorFactory.h"
-#include "cmNinjaTypes.h"
-#include "cmPolicies.h"
-
 #include <iosfwd>
 #include <map>
 #include <set>
@@ -18,13 +12,23 @@
 #include <utility>
 #include <vector>
 
+#include "cmGlobalCommonGenerator.h"
+#include "cmGlobalGenerator.h"
+#include "cmGlobalGeneratorFactory.h"
+#include "cmNinjaTypes.h"
+#include "cmPolicies.h"
+#include "cm_codecvt.hxx"
+
 class cmCustomCommand;
-class cmMakefile;
-class cmake;
-struct cmDocumentationEntry;
 class cmGeneratedFileStream;
 class cmGeneratorTarget;
+class cmLinkLineComputer;
 class cmLocalGenerator;
+class cmMakefile;
+class cmOutputConverter;
+class cmStateDirectory;
+class cmake;
+struct cmDocumentationEntry;
 
 /**
  * \class cmGlobalNinjaGenerator
@@ -58,6 +62,9 @@ public:
   /// The indentation string used when generating Ninja's build file.
   static const char* INDENT;
 
+  /// The shell command used for a no-op.
+  static std::string const SHELL_NOOP;
+
   /// Write @a count times INDENT level to output stream @a os.
   static void Indent(std::ostream& os, int count);
 
@@ -70,6 +77,10 @@ public:
   std::string EncodePath(const std::string& path);
   static std::string EncodeDepfileSpace(const std::string& path);
 
+  cmLinkLineComputer* CreateLinkLineComputer(
+    cmOutputConverter* outputConverter,
+    cmStateDirectory stateDir) const CM_OVERRIDE;
+
   /**
    * Write the given @a comment to the output stream @a os. It
    * handles new line character properly.
@@ -182,6 +193,9 @@ public:
 
   static std::string GetActualName() { return "Ninja"; }
 
+  /** Get encoding used by generator for ninja files */
+  codecvt::Encoding GetMakefileEncoding() const CM_OVERRIDE;
+
   static void GetDocumentation(cmDocumentationEntry& entry);
 
   void EnableLanguage(std::vector<std::string> const& languages,
@@ -233,7 +247,7 @@ public:
     return this->RulesFileStream;
   }
 
-  std::string ConvertToNinjaPath(const std::string& path);
+  std::string ConvertToNinjaPath(const std::string& path) const;
 
   struct MapToNinjaPathImpl
   {
@@ -332,7 +346,7 @@ public:
   bool SupportsConsolePool() const;
   bool SupportsImplicitOuts() const;
 
-  std::string NinjaOutputPath(std::string const& path);
+  std::string NinjaOutputPath(std::string const& path) const;
   bool HasOutputPathPrefix() const { return !this->OutputPathPrefix.empty(); }
   void StripNinjaOutputPathPrefixAsSuffix(std::string& path);
 
@@ -352,7 +366,7 @@ protected:
 
 private:
   std::string GetEditCacheCommand() const CM_OVERRIDE;
-  void FindMakeProgram(cmMakefile* mf) CM_OVERRIDE;
+  bool FindMakeProgram(cmMakefile* mf) CM_OVERRIDE;
   void CheckNinjaFeatures();
   bool CheckLanguages(std::vector<std::string> const& languages,
                       cmMakefile* mf) const CM_OVERRIDE;
diff --git a/Source/cmGlobalUnixMakefileGenerator3.cxx b/Source/cmGlobalUnixMakefileGenerator3.cxx
index 4a5cc77..23b3718 100644
--- a/Source/cmGlobalUnixMakefileGenerator3.cxx
+++ b/Source/cmGlobalUnixMakefileGenerator3.cxx
@@ -2,6 +2,11 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalUnixMakefileGenerator3.h"
 
+#include <algorithm>
+#include <functional>
+#include <sstream>
+#include <utility>
+
 #include "cmAlgorithms.h"
 #include "cmDocumentationEntry.h"
 #include "cmGeneratedFileStream.h"
@@ -12,16 +17,14 @@
 #include "cmMakefile.h"
 #include "cmMakefileTargetGenerator.h"
 #include "cmOutputConverter.h"
+#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cmTargetDepend.h"
 #include "cmake.h"
 
-#include <algorithm>
-#include <functional>
-#include <sstream>
-#include <utility>
-
 cmGlobalUnixMakefileGenerator3::cmGlobalUnixMakefileGenerator3(cmake* cm)
   : cmGlobalCommonGenerator(cm)
 {
@@ -93,7 +96,7 @@ std::string cmGlobalUnixMakefileGenerator3::GetEditCacheCommand() const
     if (!editCacheCommand.empty()) {
       cm->AddCacheEntry("CMAKE_EDIT_COMMAND", editCacheCommand.c_str(),
                         "Path to cache edit program executable.",
-                        cmState::INTERNAL);
+                        cmStateEnums::INTERNAL);
     }
   }
   const char* edit_cmd = cm->GetCacheDefinition("CMAKE_EDIT_COMMAND");
@@ -201,7 +204,8 @@ void cmGlobalUnixMakefileGenerator3::WriteMainMakefile2()
     this->GetCMakeInstance()->GetHomeOutputDirectory();
   makefileName += cmake::GetCMakeFilesDirectory();
   makefileName += "/Makefile2";
-  cmGeneratedFileStream makefileStream(makefileName.c_str());
+  cmGeneratedFileStream makefileStream(makefileName.c_str(), false,
+                                       this->GetMakefileEncoding());
   if (!makefileStream) {
     return;
   }
@@ -306,16 +310,12 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile()
   // reset lg to the first makefile
   lg = static_cast<cmLocalUnixMakefileGenerator3*>(this->LocalGenerators[0]);
 
-  // Build the path to the cache file.
-  std::string cache = this->GetCMakeInstance()->GetHomeOutputDirectory();
-  cache += "/CMakeCache.txt";
-
   std::string currentBinDir = lg->GetCurrentBinaryDirectory();
   // Save the list to the cmake file.
   cmakefileStream
     << "# The top level Makefile was generated from the following files:\n"
     << "set(CMAKE_MAKEFILE_DEPENDS\n"
-    << "  \"" << lg->ConvertToRelativePath(currentBinDir, cache) << "\"\n";
+    << "  \"CMakeCache.txt\"\n";
   for (std::vector<std::string>::const_iterator i = lfiles.begin();
        i != lfiles.end(); ++i) {
     cmakefileStream << "  \"" << lg->ConvertToRelativePath(currentBinDir, *i)
@@ -385,12 +385,12 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefileLanguageRules(
     std::vector<cmGeneratorTarget*> tgts = lg->GetGeneratorTargets();
     for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
          l != tgts.end(); l++) {
-      if (((*l)->GetType() == cmState::EXECUTABLE) ||
-          ((*l)->GetType() == cmState::STATIC_LIBRARY) ||
-          ((*l)->GetType() == cmState::SHARED_LIBRARY) ||
-          ((*l)->GetType() == cmState::MODULE_LIBRARY) ||
-          ((*l)->GetType() == cmState::OBJECT_LIBRARY) ||
-          ((*l)->GetType() == cmState::UTILITY)) {
+      if (((*l)->GetType() == cmStateEnums::EXECUTABLE) ||
+          ((*l)->GetType() == cmStateEnums::STATIC_LIBRARY) ||
+          ((*l)->GetType() == cmStateEnums::SHARED_LIBRARY) ||
+          ((*l)->GetType() == cmStateEnums::MODULE_LIBRARY) ||
+          ((*l)->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
+          ((*l)->GetType() == cmStateEnums::UTILITY)) {
         cmGeneratorTarget* gt = *l;
         std::string tname = lg->GetRelativeTargetDirectory(gt);
         tname += "/DependInfo.cmake";
@@ -419,10 +419,12 @@ void cmGlobalUnixMakefileGenerator3::WriteDirectoryRule2(
        l != targets.end(); ++l) {
     cmGeneratorTarget* gtarget = *l;
     int type = gtarget->GetType();
-    if ((type == cmState::EXECUTABLE) || (type == cmState::STATIC_LIBRARY) ||
-        (type == cmState::SHARED_LIBRARY) ||
-        (type == cmState::MODULE_LIBRARY) ||
-        (type == cmState::OBJECT_LIBRARY) || (type == cmState::UTILITY)) {
+    if ((type == cmStateEnums::EXECUTABLE) ||
+        (type == cmStateEnums::STATIC_LIBRARY) ||
+        (type == cmStateEnums::SHARED_LIBRARY) ||
+        (type == cmStateEnums::MODULE_LIBRARY) ||
+        (type == cmStateEnums::OBJECT_LIBRARY) ||
+        (type == cmStateEnums::UTILITY)) {
       // Add this to the list of depends rules in this directory.
       if ((!check_all || !gtarget->GetPropertyAsBool("EXCLUDE_FROM_ALL")) &&
           (!check_relink ||
@@ -437,9 +439,8 @@ void cmGlobalUnixMakefileGenerator3::WriteDirectoryRule2(
 
   // The directory-level rule should depend on the directory-level
   // rules of the subdirectories.
-  std::vector<cmState::Snapshot> children =
-    lg->GetStateSnapshot().GetChildren();
-  for (std::vector<cmState::Snapshot>::const_iterator ci = children.begin();
+  std::vector<cmStateSnapshot> children = lg->GetStateSnapshot().GetChildren();
+  for (std::vector<cmStateSnapshot>::const_iterator ci = children.begin();
        ci != children.end(); ++ci) {
     std::string subdir = ci->GetDirectory().GetCurrentBinary();
     subdir += "/";
@@ -508,7 +509,7 @@ void cmGlobalUnixMakefileGenerator3::GenerateBuildCommand(
     if (!this->Makefiles.empty()) {
       mf = this->Makefiles[0];
     } else {
-      cmState::Snapshot snapshot = this->CMakeInstance->GetCurrentSnapshot();
+      cmStateSnapshot snapshot = this->CMakeInstance->GetCurrentSnapshot();
       snapshot.GetDirectory().SetCurrentSource(
         this->CMakeInstance->GetHomeDirectory());
       snapshot.GetDirectory().SetCurrentBinary(
@@ -557,11 +558,12 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules(
       if (!name.empty() && emitted.insert(name).second &&
           // Handle user targets here.  Global targets are handled in
           // the local generator on a per-directory basis.
-          ((type == cmState::EXECUTABLE) ||
-           (type == cmState::STATIC_LIBRARY) ||
-           (type == cmState::SHARED_LIBRARY) ||
-           (type == cmState::MODULE_LIBRARY) ||
-           (type == cmState::OBJECT_LIBRARY) || (type == cmState::UTILITY))) {
+          ((type == cmStateEnums::EXECUTABLE) ||
+           (type == cmStateEnums::STATIC_LIBRARY) ||
+           (type == cmStateEnums::SHARED_LIBRARY) ||
+           (type == cmStateEnums::MODULE_LIBRARY) ||
+           (type == cmStateEnums::OBJECT_LIBRARY) ||
+           (type == cmStateEnums::UTILITY))) {
         // Add a rule to build the target by name.
         lg->WriteDivider(ruleFileStream);
         ruleFileStream << "# Target rules for targets named " << name
@@ -633,11 +635,12 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2(
     cmGeneratorTarget* gtarget = *t;
     int type = gtarget->GetType();
     std::string name = gtarget->GetName();
-    if (!name.empty() &&
-        ((type == cmState::EXECUTABLE) || (type == cmState::STATIC_LIBRARY) ||
-         (type == cmState::SHARED_LIBRARY) ||
-         (type == cmState::MODULE_LIBRARY) ||
-         (type == cmState::OBJECT_LIBRARY) || (type == cmState::UTILITY))) {
+    if (!name.empty() && ((type == cmStateEnums::EXECUTABLE) ||
+                          (type == cmStateEnums::STATIC_LIBRARY) ||
+                          (type == cmStateEnums::SHARED_LIBRARY) ||
+                          (type == cmStateEnums::MODULE_LIBRARY) ||
+                          (type == cmStateEnums::OBJECT_LIBRARY) ||
+                          (type == cmStateEnums::UTILITY))) {
       std::string makefileName;
       // Add a rule to build the target by name.
       localName = lg->GetRelativeTargetDirectory(gtarget);
@@ -811,13 +814,13 @@ void cmGlobalUnixMakefileGenerator3::InitializeProgressMarks()
 
       cmLocalGenerator* tlg = gt->GetLocalGenerator();
 
-      if (gt->GetType() == cmState::INTERFACE_LIBRARY ||
+      if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
           gt->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
         continue;
       }
 
-      cmState::Snapshot csnp = lg->GetStateSnapshot();
-      cmState::Snapshot tsnp = tlg->GetStateSnapshot();
+      cmStateSnapshot csnp = lg->GetStateSnapshot();
+      cmStateSnapshot tsnp = tlg->GetStateSnapshot();
 
       // Consider the directory containing the target and all its
       // parents until something excludes the target.
@@ -850,7 +853,7 @@ size_t cmGlobalUnixMakefileGenerator3::CountProgressMarksInTarget(
     TargetDependSet const& depends = this->GetTargetDirectDepends(target);
     for (TargetDependSet::const_iterator di = depends.begin();
          di != depends.end(); ++di) {
-      if ((*di)->GetType() == cmState::INTERFACE_LIBRARY) {
+      if ((*di)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
         continue;
       }
       count += this->CountProgressMarksInTarget(*di, emitted);
@@ -911,7 +914,7 @@ void cmGlobalUnixMakefileGenerator3::AppendGlobalTargetDepends(
        i != depends_set.end(); ++i) {
     // Create the target-level dependency.
     cmGeneratorTarget const* dep = *i;
-    if (dep->GetType() == cmState::INTERFACE_LIBRARY) {
+    if (dep->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     cmLocalUnixMakefileGenerator3* lg3 =
@@ -953,14 +956,15 @@ void cmGlobalUnixMakefileGenerator3::WriteHelpRule(
       for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
            t != targets.end(); ++t) {
         cmGeneratorTarget* target = *t;
-        cmState::TargetType type = target->GetType();
-        if ((type == cmState::EXECUTABLE) ||
-            (type == cmState::STATIC_LIBRARY) ||
-            (type == cmState::SHARED_LIBRARY) ||
-            (type == cmState::MODULE_LIBRARY) ||
-            (type == cmState::OBJECT_LIBRARY) ||
-            (type == cmState::GLOBAL_TARGET) || (type == cmState::UTILITY)) {
-          std::string name = target->GetName();
+        cmStateEnums::TargetType type = target->GetType();
+        if ((type == cmStateEnums::EXECUTABLE) ||
+            (type == cmStateEnums::STATIC_LIBRARY) ||
+            (type == cmStateEnums::SHARED_LIBRARY) ||
+            (type == cmStateEnums::MODULE_LIBRARY) ||
+            (type == cmStateEnums::OBJECT_LIBRARY) ||
+            (type == cmStateEnums::GLOBAL_TARGET) ||
+            (type == cmStateEnums::UTILITY)) {
+          std::string const& name = target->GetName();
           if (emittedTargets.insert(name).second) {
             path = "... ";
             path += name;
diff --git a/Source/cmGlobalUnixMakefileGenerator3.h b/Source/cmGlobalUnixMakefileGenerator3.h
index 1019d86..67d7bc9 100644
--- a/Source/cmGlobalUnixMakefileGenerator3.h
+++ b/Source/cmGlobalUnixMakefileGenerator3.h
@@ -5,11 +5,6 @@
 
 #include <cmConfigure.h>
 
-#include "cmGeneratorTarget.h"
-#include "cmGlobalCommonGenerator.h"
-#include "cmGlobalGeneratorFactory.h"
-#include "cmState.h"
-
 #include <iosfwd>
 #include <map>
 #include <set>
@@ -17,6 +12,11 @@
 #include <string>
 #include <vector>
 
+#include "cmGeneratorTarget.h"
+#include "cmGlobalCommonGenerator.h"
+#include "cmGlobalGeneratorFactory.h"
+#include "cmStateSnapshot.h"
+
 class cmGeneratedFileStream;
 class cmLocalGenerator;
 class cmLocalUnixMakefileGenerator3;
@@ -248,8 +248,8 @@ private:
   const char* GetBuildIgnoreErrorsFlag() const CM_OVERRIDE { return "-i"; }
   std::string GetEditCacheCommand() const CM_OVERRIDE;
 
-  std::map<cmState::Snapshot, std::set<cmGeneratorTarget const*>,
-           cmState::Snapshot::StrictWeakOrder>
+  std::map<cmStateSnapshot, std::set<cmGeneratorTarget const*>,
+           cmStateSnapshot::StrictWeakOrder>
     DirectoryTargetsMap;
   void InitializeProgressMarks() CM_OVERRIDE;
 };
diff --git a/Source/cmGlobalVisualStudio10Generator.cxx b/Source/cmGlobalVisualStudio10Generator.cxx
index 502c93a..e27615a 100644
--- a/Source/cmGlobalVisualStudio10Generator.cxx
+++ b/Source/cmGlobalVisualStudio10Generator.cxx
@@ -1,14 +1,19 @@
 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
    file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "windows.h" // this must be first to define GetCurrentDirectory
-
 #include "cmGlobalVisualStudio10Generator.h"
 
 #include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
 #include "cmGeneratorTarget.h"
 #include "cmLocalVisualStudio10Generator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
+#include "cmVS10CLFlagTable.h"
+#include "cmVS10CSharpFlagTable.h"
+#include "cmVS10LibFlagTable.h"
+#include "cmVS10LinkFlagTable.h"
+#include "cmVS10MASMFlagTable.h"
+#include "cmVS10RCFlagTable.h"
 #include "cmVisualStudioSlnData.h"
 #include "cmVisualStudioSlnParser.h"
 #include "cmake.h"
@@ -103,6 +108,12 @@ cmGlobalVisualStudio10Generator::cmGlobalVisualStudio10Generator(
       this->DefaultPlatformToolset = "v100";
     }
   }
+  this->DefaultClFlagTable = cmVS10CLFlagTable;
+  this->DefaultCSharpFlagTable = cmVS10CSharpFlagTable;
+  this->DefaultLibFlagTable = cmVS10LibFlagTable;
+  this->DefaultLinkFlagTable = cmVS10LinkFlagTable;
+  this->DefaultMasmFlagTable = cmVS10MASMFlagTable;
+  this->DefaultRcFlagTable = cmVS10RCFlagTable;
   this->Version = VS10;
 }
 
@@ -154,10 +165,36 @@ bool cmGlobalVisualStudio10Generator::SetGeneratorToolset(
     return false;
   }
 
-  this->GeneratorToolset = ts;
+  if (!this->ParseGeneratorToolset(ts, mf)) {
+    return false;
+  }
   if (const char* toolset = this->GetPlatformToolset()) {
     mf->AddDefinition("CMAKE_VS_PLATFORM_TOOLSET", toolset);
   }
+  if (const char* hostArch = this->GetPlatformToolsetHostArchitecture()) {
+    mf->AddDefinition("CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE", hostArch);
+  }
+  return true;
+}
+
+bool cmGlobalVisualStudio10Generator::ParseGeneratorToolset(
+  std::string const& ts, cmMakefile* mf)
+{
+  if (ts.find_first_of(",=") != ts.npos) {
+    std::ostringstream e;
+    /* clang-format off */
+    e <<
+      "Generator\n"
+      "  " << this->GetName() << "\n"
+      "does not recognize the toolset\n"
+      "  " << ts << "\n"
+      "that was specified.";
+    /* clang-format on */
+    mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+    return false;
+  }
+
+  this->GeneratorToolset = ts;
   return true;
 }
 
@@ -322,20 +359,43 @@ void cmGlobalVisualStudio10Generator::EnableLanguage(
 
 const char* cmGlobalVisualStudio10Generator::GetPlatformToolset() const
 {
+  std::string const& toolset = this->GetPlatformToolsetString();
+  if (toolset.empty()) {
+    return CM_NULLPTR;
+  }
+  return toolset.c_str();
+}
+
+std::string const& cmGlobalVisualStudio10Generator::GetPlatformToolsetString()
+  const
+{
   if (!this->GeneratorToolset.empty()) {
-    return this->GeneratorToolset.c_str();
+    return this->GeneratorToolset;
   }
   if (!this->DefaultPlatformToolset.empty()) {
-    return this->DefaultPlatformToolset.c_str();
+    return this->DefaultPlatformToolset;
   }
-  return 0;
+  static std::string const empty;
+  return empty;
 }
 
-void cmGlobalVisualStudio10Generator::FindMakeProgram(cmMakefile* mf)
+const char*
+cmGlobalVisualStudio10Generator::GetPlatformToolsetHostArchitecture() const
 {
-  this->cmGlobalVisualStudio8Generator::FindMakeProgram(mf);
+  if (!this->GeneratorToolsetHostArchitecture.empty()) {
+    return this->GeneratorToolsetHostArchitecture.c_str();
+  }
+  return CM_NULLPTR;
+}
+
+bool cmGlobalVisualStudio10Generator::FindMakeProgram(cmMakefile* mf)
+{
+  if (!this->cmGlobalVisualStudio8Generator::FindMakeProgram(mf)) {
+    return false;
+  }
   mf->AddDefinition("CMAKE_VS_MSBUILD_COMMAND",
                     this->GetMSBuildCommand().c_str());
+  return true;
 }
 
 std::string const& cmGlobalVisualStudio10Generator::GetMSBuildCommand()
@@ -365,20 +425,6 @@ std::string cmGlobalVisualStudio10Generator::FindMSBuildCommand()
     }
   }
 
-  // Search where VS15Preview places it.
-  mskey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7;";
-  mskey += this->GetIDEVersion();
-  if (cmSystemTools::ReadRegistryValue(mskey.c_str(), msbuild,
-                                       cmSystemTools::KeyWOW64_32)) {
-    cmSystemTools::ConvertToUnixSlashes(msbuild);
-    msbuild += "/MSBuild/";
-    msbuild += this->GetIDEVersion();
-    msbuild += "/Bin/MSBuild.exe";
-    if (cmSystemTools::FileExists(msbuild, true)) {
-      return msbuild;
-    }
-  }
-
   msbuild = "MSBuild.exe";
   return msbuild;
 }
@@ -568,3 +614,52 @@ std::string cmGlobalVisualStudio10Generator::GetInstalledNsightTegraVersion()
     version, cmSystemTools::KeyWOW64_32);
   return version;
 }
+
+cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetClFlagTable() const
+{
+  cmIDEFlagTable const* table = this->ToolsetOptions.GetClFlagTable(
+    this->GetPlatformName(), this->GetPlatformToolsetString());
+
+  return (table != CM_NULLPTR) ? table : this->DefaultClFlagTable;
+}
+
+cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetCSharpFlagTable()
+  const
+{
+  cmIDEFlagTable const* table = this->ToolsetOptions.GetCSharpFlagTable(
+    this->GetPlatformName(), this->GetPlatformToolsetString());
+
+  return (table != CM_NULLPTR) ? table : this->DefaultCSharpFlagTable;
+}
+
+cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetRcFlagTable() const
+{
+  cmIDEFlagTable const* table = this->ToolsetOptions.GetRcFlagTable(
+    this->GetPlatformName(), this->GetPlatformToolsetString());
+
+  return (table != CM_NULLPTR) ? table : this->DefaultRcFlagTable;
+}
+
+cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetLibFlagTable() const
+{
+  cmIDEFlagTable const* table = this->ToolsetOptions.GetLibFlagTable(
+    this->GetPlatformName(), this->GetPlatformToolsetString());
+
+  return (table != CM_NULLPTR) ? table : this->DefaultLibFlagTable;
+}
+
+cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetLinkFlagTable() const
+{
+  cmIDEFlagTable const* table = this->ToolsetOptions.GetLinkFlagTable(
+    this->GetPlatformName(), this->GetPlatformToolsetString());
+
+  return (table != CM_NULLPTR) ? table : this->DefaultLinkFlagTable;
+}
+
+cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetMasmFlagTable() const
+{
+  cmIDEFlagTable const* table = this->ToolsetOptions.GetMasmFlagTable(
+    this->GetPlatformName(), this->GetPlatformToolsetString());
+
+  return (table != CM_NULLPTR) ? table : this->DefaultMasmFlagTable;
+}
diff --git a/Source/cmGlobalVisualStudio10Generator.h b/Source/cmGlobalVisualStudio10Generator.h
index 19c60aa..5bfaf38 100644
--- a/Source/cmGlobalVisualStudio10Generator.h
+++ b/Source/cmGlobalVisualStudio10Generator.h
@@ -4,6 +4,7 @@
 #define cmGlobalVisualStudio10Generator_h
 
 #include "cmGlobalVisualStudio8Generator.h"
+#include "cmVisualStudio10ToolsetOptions.h"
 
 /** \class cmGlobalVisualStudio10Generator
  * \brief Write a Unix makefiles.
@@ -22,6 +23,7 @@ public:
   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 bool ParseGeneratorToolset(std::string const& ts, cmMakefile* mf);
 
   virtual void GenerateBuildCommand(
     std::vector<std::string>& makeCommand, const std::string& makeProgram,
@@ -47,6 +49,10 @@ public:
 
   /** The toolset name for the target platform.  */
   const char* GetPlatformToolset() const;
+  std::string const& GetPlatformToolsetString() const;
+
+  /** The toolset host architecture name (e.g. x64 for 64-bit host tools).  */
+  const char* GetPlatformToolsetHostArchitecture() const;
 
   /** Return the CMAKE_SYSTEM_NAME.  */
   std::string const& GetSystemName() const { return this->SystemName; }
@@ -80,10 +86,17 @@ public:
 
   virtual const char* GetToolsVersion() { return "4.0"; }
 
-  virtual void FindMakeProgram(cmMakefile*);
+  bool FindMakeProgram(cmMakefile* mf) CM_OVERRIDE;
 
   static std::string GetInstalledNsightTegraVersion();
 
+  cmIDEFlagTable const* GetClFlagTable() const;
+  cmIDEFlagTable const* GetCSharpFlagTable() const;
+  cmIDEFlagTable const* GetRcFlagTable() const;
+  cmIDEFlagTable const* GetLibFlagTable() const;
+  cmIDEFlagTable const* GetLinkFlagTable() const;
+  cmIDEFlagTable const* GetMasmFlagTable() const;
+
 protected:
   virtual void Generate();
   virtual bool InitializeSystem(cmMakefile* mf);
@@ -101,11 +114,18 @@ protected:
   std::string const& GetMSBuildCommand();
 
   std::string GeneratorToolset;
+  std::string GeneratorToolsetHostArchitecture;
   std::string DefaultPlatformToolset;
   std::string WindowsTargetPlatformVersion;
   std::string SystemName;
   std::string SystemVersion;
   std::string NsightTegraVersion;
+  cmIDEFlagTable const* DefaultClFlagTable;
+  cmIDEFlagTable const* DefaultCSharpFlagTable;
+  cmIDEFlagTable const* DefaultLibFlagTable;
+  cmIDEFlagTable const* DefaultLinkFlagTable;
+  cmIDEFlagTable const* DefaultMasmFlagTable;
+  cmIDEFlagTable const* DefaultRcFlagTable;
   bool SystemIsWindowsCE;
   bool SystemIsWindowsPhone;
   bool SystemIsWindowsStore;
@@ -129,6 +149,7 @@ private:
 
   std::string MSBuildCommand;
   bool MSBuildCommandInitialized;
+  cmVisualStudio10ToolsetOptions ToolsetOptions;
   virtual std::string FindMSBuildCommand();
   virtual std::string FindDevEnvCommand();
   virtual std::string GetVSMakeProgram() { return this->GetMSBuildCommand(); }
diff --git a/Source/cmGlobalVisualStudio11Generator.cxx b/Source/cmGlobalVisualStudio11Generator.cxx
index 5d9a02b..d37d4b0 100644
--- a/Source/cmGlobalVisualStudio11Generator.cxx
+++ b/Source/cmGlobalVisualStudio11Generator.cxx
@@ -3,8 +3,15 @@
 #include "cmGlobalVisualStudio11Generator.h"
 
 #include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
 #include "cmLocalVisualStudio10Generator.h"
 #include "cmMakefile.h"
+#include "cmVS11CLFlagTable.h"
+#include "cmVS11CSharpFlagTable.h"
+#include "cmVS11LibFlagTable.h"
+#include "cmVS11LinkFlagTable.h"
+#include "cmVS11MASMFlagTable.h"
+#include "cmVS11RCFlagTable.h"
 
 static const char vs11generatorName[] = "Visual Studio 11 2012";
 
@@ -101,6 +108,12 @@ cmGlobalVisualStudio11Generator::cmGlobalVisualStudio11Generator(
     "ProductDir",
     vc11Express, cmSystemTools::KeyWOW64_32);
   this->DefaultPlatformToolset = "v110";
+  this->DefaultClFlagTable = cmVS11CLFlagTable;
+  this->DefaultCSharpFlagTable = cmVS11CSharpFlagTable;
+  this->DefaultLibFlagTable = cmVS11LibFlagTable;
+  this->DefaultLinkFlagTable = cmVS11LinkFlagTable;
+  this->DefaultMasmFlagTable = cmVS11MASMFlagTable;
+  this->DefaultRcFlagTable = cmVS11RCFlagTable;
   this->Version = VS11;
 }
 
@@ -230,9 +243,10 @@ cmGlobalVisualStudio11Generator::GetInstalledWindowsCESDKs()
 }
 
 bool cmGlobalVisualStudio11Generator::NeedsDeploy(
-  cmState::TargetType type) const
+  cmStateEnums::TargetType type) const
 {
-  if ((type == cmState::EXECUTABLE || type == cmState::SHARED_LIBRARY) &&
+  if ((type == cmStateEnums::EXECUTABLE ||
+       type == cmStateEnums::SHARED_LIBRARY) &&
       (this->SystemIsWindowsPhone || this->SystemIsWindowsStore)) {
     return true;
   }
diff --git a/Source/cmGlobalVisualStudio11Generator.h b/Source/cmGlobalVisualStudio11Generator.h
index 0c03b0a..ae99408 100644
--- a/Source/cmGlobalVisualStudio11Generator.h
+++ b/Source/cmGlobalVisualStudio11Generator.h
@@ -3,7 +3,18 @@
 #ifndef cmGlobalVisualStudio11Generator_h
 #define cmGlobalVisualStudio11Generator_h
 
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <set>
+#include <string>
+
 #include "cmGlobalVisualStudio10Generator.h"
+#include "cmStateTypes.h"
+
+class cmGlobalGeneratorFactory;
+class cmMakefile;
+class cmake;
 
 /** \class cmGlobalVisualStudio11Generator  */
 class cmGlobalVisualStudio11Generator : public cmGlobalVisualStudio10Generator
@@ -37,7 +48,7 @@ protected:
   static std::set<std::string> GetInstalledWindowsCESDKs();
 
   /** Return true if the configuration needs to be deployed */
-  virtual bool NeedsDeploy(cmState::TargetType type) const;
+  virtual bool NeedsDeploy(cmStateEnums::TargetType type) const;
 
 private:
   class Factory;
diff --git a/Source/cmGlobalVisualStudio12Generator.cxx b/Source/cmGlobalVisualStudio12Generator.cxx
index 5fdeec7..2656dcc 100644
--- a/Source/cmGlobalVisualStudio12Generator.cxx
+++ b/Source/cmGlobalVisualStudio12Generator.cxx
@@ -3,8 +3,15 @@
 #include "cmGlobalVisualStudio12Generator.h"
 
 #include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
 #include "cmLocalVisualStudio10Generator.h"
 #include "cmMakefile.h"
+#include "cmVS12CLFlagTable.h"
+#include "cmVS12CSharpFlagTable.h"
+#include "cmVS12LibFlagTable.h"
+#include "cmVS12LinkFlagTable.h"
+#include "cmVS12MASMFlagTable.h"
+#include "cmVS12RCFlagTable.h"
 
 static const char vs12generatorName[] = "Visual Studio 12 2013";
 
@@ -83,6 +90,12 @@ cmGlobalVisualStudio12Generator::cmGlobalVisualStudio12Generator(
     "ProductDir",
     vc12Express, cmSystemTools::KeyWOW64_32);
   this->DefaultPlatformToolset = "v120";
+  this->DefaultClFlagTable = cmVS12CLFlagTable;
+  this->DefaultCSharpFlagTable = cmVS12CSharpFlagTable;
+  this->DefaultLibFlagTable = cmVS12LibFlagTable;
+  this->DefaultLinkFlagTable = cmVS12LinkFlagTable;
+  this->DefaultMasmFlagTable = cmVS12MASMFlagTable;
+  this->DefaultRcFlagTable = cmVS12RCFlagTable;
   this->Version = VS12;
 }
 
@@ -96,6 +109,21 @@ bool cmGlobalVisualStudio12Generator::MatchesGeneratorName(
   return false;
 }
 
+bool cmGlobalVisualStudio12Generator::ParseGeneratorToolset(
+  std::string const& ts, cmMakefile* mf)
+{
+  std::string::size_type ts_end = ts.size();
+  if (cmHasLiteralSuffix(ts, ",host=x64")) {
+    this->GeneratorToolsetHostArchitecture = "x64";
+    ts_end -= 9;
+  } else if (ts == "host=x64") {
+    this->GeneratorToolsetHostArchitecture = "x64";
+    ts_end = 0;
+  }
+  return this->cmGlobalVisualStudio11Generator::ParseGeneratorToolset(
+    ts.substr(0, ts_end), mf);
+}
+
 bool cmGlobalVisualStudio12Generator::InitializeWindowsPhone(cmMakefile* mf)
 {
   if (!this->SelectWindowsPhoneToolset(this->DefaultPlatformToolset)) {
diff --git a/Source/cmGlobalVisualStudio12Generator.h b/Source/cmGlobalVisualStudio12Generator.h
index 78bb637..79efe52 100644
--- a/Source/cmGlobalVisualStudio12Generator.h
+++ b/Source/cmGlobalVisualStudio12Generator.h
@@ -3,8 +3,17 @@
 #ifndef cmGlobalVisualStudio12Generator_h
 #define cmGlobalVisualStudio12Generator_h
 
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <string>
+
 #include "cmGlobalVisualStudio11Generator.h"
 
+class cmGlobalGeneratorFactory;
+class cmMakefile;
+class cmake;
+
 /** \class cmGlobalVisualStudio12Generator  */
 class cmGlobalVisualStudio12Generator : public cmGlobalVisualStudio11Generator
 {
@@ -22,6 +31,9 @@ public:
   // version number
   virtual const char* GetToolsVersion() { return "12.0"; }
 protected:
+  bool ParseGeneratorToolset(std::string const& ts,
+                             cmMakefile* mf) CM_OVERRIDE;
+
   virtual bool InitializeWindowsPhone(cmMakefile* mf);
   virtual bool InitializeWindowsStore(cmMakefile* mf);
   virtual bool SelectWindowsPhoneToolset(std::string& toolset) const;
diff --git a/Source/cmGlobalVisualStudio14Generator.cxx b/Source/cmGlobalVisualStudio14Generator.cxx
index 586fe3c..81c305c 100644
--- a/Source/cmGlobalVisualStudio14Generator.cxx
+++ b/Source/cmGlobalVisualStudio14Generator.cxx
@@ -3,8 +3,15 @@
 #include "cmGlobalVisualStudio14Generator.h"
 
 #include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
 #include "cmLocalVisualStudio10Generator.h"
 #include "cmMakefile.h"
+#include "cmVS140CLFlagTable.h"
+#include "cmVS140CSharpFlagTable.h"
+#include "cmVS14LibFlagTable.h"
+#include "cmVS14LinkFlagTable.h"
+#include "cmVS14MASMFlagTable.h"
+#include "cmVS14RCFlagTable.h"
 
 static const char vs14generatorName[] = "Visual Studio 14 2015";
 
@@ -83,6 +90,12 @@ cmGlobalVisualStudio14Generator::cmGlobalVisualStudio14Generator(
     "ProductDir",
     vc14Express, cmSystemTools::KeyWOW64_32);
   this->DefaultPlatformToolset = "v140";
+  this->DefaultClFlagTable = cmVS140CLFlagTable;
+  this->DefaultCSharpFlagTable = cmVS140CSharpFlagTable;
+  this->DefaultLibFlagTable = cmVS14LibFlagTable;
+  this->DefaultLinkFlagTable = cmVS14LinkFlagTable;
+  this->DefaultMasmFlagTable = cmVS14MASMFlagTable;
+  this->DefaultRcFlagTable = cmVS14RCFlagTable;
   this->Version = VS14;
 }
 
diff --git a/Source/cmGlobalVisualStudio14Generator.h b/Source/cmGlobalVisualStudio14Generator.h
index 991f018..ab22978 100644
--- a/Source/cmGlobalVisualStudio14Generator.h
+++ b/Source/cmGlobalVisualStudio14Generator.h
@@ -3,8 +3,17 @@
 #ifndef cmGlobalVisualStudio14Generator_h
 #define cmGlobalVisualStudio14Generator_h
 
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <string>
+
 #include "cmGlobalVisualStudio12Generator.h"
 
+class cmGlobalGeneratorFactory;
+class cmMakefile;
+class cmake;
+
 /** \class cmGlobalVisualStudio14Generator  */
 class cmGlobalVisualStudio14Generator : public cmGlobalVisualStudio12Generator
 {
diff --git a/Source/cmGlobalVisualStudio15Generator.cxx b/Source/cmGlobalVisualStudio15Generator.cxx
index 0c6beb2..2312bc0 100644
--- a/Source/cmGlobalVisualStudio15Generator.cxx
+++ b/Source/cmGlobalVisualStudio15Generator.cxx
@@ -3,8 +3,12 @@
 #include "cmGlobalVisualStudio15Generator.h"
 
 #include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
 #include "cmLocalVisualStudio10Generator.h"
 #include "cmMakefile.h"
+#include "cmVS141CLFlagTable.h"
+#include "cmVS141CSharpFlagTable.h"
+#include "cmVSSetupHelper.h"
 
 static const char vs15generatorName[] = "Visual Studio 15 2017";
 
@@ -77,12 +81,10 @@ cmGlobalVisualStudio15Generator::cmGlobalVisualStudio15Generator(
   cmake* cm, const std::string& name, const std::string& platformName)
   : cmGlobalVisualStudio14Generator(cm, name, platformName)
 {
-  std::string vc15Express;
-  this->ExpressEdition = cmSystemTools::ReadRegistryValue(
-    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\15.0\\Setup\\VC;"
-    "ProductDir",
-    vc15Express, cmSystemTools::KeyWOW64_32);
+  this->ExpressEdition = false;
   this->DefaultPlatformToolset = "v141";
+  this->DefaultClFlagTable = cmVS141CLFlagTable;
+  this->DefaultCSharpFlagTable = cmVS141CSharpFlagTable;
   this->Version = VS15;
 }
 
@@ -107,13 +109,25 @@ void cmGlobalVisualStudio15Generator::WriteSLNHeader(std::ostream& fout)
   }
 }
 
+bool cmGlobalVisualStudio15Generator::InitializeWindows(cmMakefile* mf)
+{
+  // If the Win 8.1 SDK is installed then we can select a SDK matching
+  // the target Windows version.
+  if (this->IsWin81SDKInstalled()) {
+    return cmGlobalVisualStudio14Generator::InitializeWindows(mf);
+  }
+  // Otherwise we must choose a Win 10 SDK even if we are not targeting
+  // Windows 10.
+  return this->SelectWindows10SDK(mf, false);
+}
+
 bool cmGlobalVisualStudio15Generator::SelectWindowsStoreToolset(
   std::string& toolset) const
 {
   if (cmHasLiteralPrefix(this->SystemVersion, "10.0")) {
     if (this->IsWindowsStoreToolsetInstalled() &&
         this->IsWindowsDesktopToolsetInstalled()) {
-      toolset = "v140"; // VS 15 uses v140 toolset
+      toolset = "v141"; // VS 15 uses v141 toolset
       return true;
     } else {
       return false;
@@ -125,21 +139,66 @@ bool cmGlobalVisualStudio15Generator::SelectWindowsStoreToolset(
 
 bool cmGlobalVisualStudio15Generator::IsWindowsDesktopToolsetInstalled() const
 {
-  const char desktop10Key[] = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\"
-                              "VisualStudio\\15.0\\VC\\Runtimes";
-
-  std::vector<std::string> vc15;
-  return cmSystemTools::GetRegistrySubKeys(desktop10Key, vc15,
-                                           cmSystemTools::KeyWOW64_32);
+  return vsSetupAPIHelper.IsVS2017Installed();
 }
 
 bool cmGlobalVisualStudio15Generator::IsWindowsStoreToolsetInstalled() const
 {
-  const char universal10Key[] =
-    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\"
-    "VisualStudio\\15.0\\Setup\\Build Tools for Windows 10;SrcPath";
+  return vsSetupAPIHelper.IsWin10SDKInstalled();
+}
+
+bool cmGlobalVisualStudio15Generator::IsWin81SDKInstalled() const
+{
+  // Does the VS installer tool know about one?
+  if (vsSetupAPIHelper.IsWin81SDKInstalled()) {
+    return true;
+  }
+
+  // Does the registry know about one (e.g. from VS 2015)?
+  std::string win81Root;
+  if (cmSystemTools::ReadRegistryValue(
+        "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\"
+        "Windows Kits\\Installed Roots;KitsRoot81",
+        win81Root, cmSystemTools::KeyWOW64_32) ||
+      cmSystemTools::ReadRegistryValue(
+        "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\"
+        "Windows Kits\\Installed Roots;KitsRoot81",
+        win81Root, cmSystemTools::KeyWOW64_32)) {
+    return true;
+  }
+  return false;
+}
+
+std::string cmGlobalVisualStudio15Generator::FindMSBuildCommand()
+{
+  std::string msbuild;
+
+  // Ask Visual Studio Installer tool.
+  std::string vs;
+  if (vsSetupAPIHelper.GetVSInstanceInfo(vs)) {
+    msbuild = vs + "/MSBuild/15.0/Bin/MSBuild.exe";
+    if (cmSystemTools::FileExists(msbuild)) {
+      return msbuild;
+    }
+  }
+
+  msbuild = "MSBuild.exe";
+  return msbuild;
+}
+
+std::string cmGlobalVisualStudio15Generator::FindDevEnvCommand()
+{
+  std::string devenv;
+
+  // Ask Visual Studio Installer tool.
+  std::string vs;
+  if (vsSetupAPIHelper.GetVSInstanceInfo(vs)) {
+    devenv = vs + "/Common7/IDE/devenv.com";
+    if (cmSystemTools::FileExists(devenv)) {
+      return devenv;
+    }
+  }
 
-  std::string win10SDK;
-  return cmSystemTools::ReadRegistryValue(universal10Key, win10SDK,
-                                          cmSystemTools::KeyWOW64_32);
+  devenv = "devenv.com";
+  return devenv;
 }
diff --git a/Source/cmGlobalVisualStudio15Generator.h b/Source/cmGlobalVisualStudio15Generator.h
index 2e458f4..f979b65 100644
--- a/Source/cmGlobalVisualStudio15Generator.h
+++ b/Source/cmGlobalVisualStudio15Generator.h
@@ -3,7 +3,16 @@
 #ifndef cmGlobalVisualStudio15Generator_h
 #define cmGlobalVisualStudio15Generator_h
 
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <string>
+
 #include "cmGlobalVisualStudio14Generator.h"
+#include "cmVSSetupHelper.h"
+
+class cmGlobalGeneratorFactory;
+class cmake;
 
 /** \class cmGlobalVisualStudio15Generator  */
 class cmGlobalVisualStudio15Generator : public cmGlobalVisualStudio14Generator
@@ -19,6 +28,7 @@ public:
 
   virtual const char* GetToolsVersion() { return "15.0"; }
 protected:
+  bool InitializeWindows(cmMakefile* mf) CM_OVERRIDE;
   virtual bool SelectWindowsStoreToolset(std::string& toolset) const;
 
   virtual const char* GetIDEVersion() { return "15.0"; }
@@ -31,7 +41,14 @@ protected:
   // of the toolset is installed
   bool IsWindowsStoreToolsetInstalled() const;
 
+  // Check for a Win 8 SDK known to the registry or VS installer tool.
+  bool IsWin81SDKInstalled() const;
+
+  std::string FindMSBuildCommand() CM_OVERRIDE;
+  std::string FindDevEnvCommand() CM_OVERRIDE;
+
 private:
   class Factory;
+  mutable cmVSSetupAPIHelper vsSetupAPIHelper;
 };
 #endif
diff --git a/Source/cmGlobalVisualStudio71Generator.cxx b/Source/cmGlobalVisualStudio71Generator.cxx
index ffd87e2..55a788f 100644
--- a/Source/cmGlobalVisualStudio71Generator.cxx
+++ b/Source/cmGlobalVisualStudio71Generator.cxx
@@ -1,9 +1,8 @@
 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
    file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "windows.h" // this must be first to define GetCurrentDirectory
-
 #include "cmGlobalVisualStudio71Generator.h"
 
+#include "cmDocumentationEntry.h"
 #include "cmGeneratorTarget.h"
 #include "cmLocalVisualStudio7Generator.h"
 #include "cmMakefile.h"
@@ -159,6 +158,10 @@ void cmGlobalVisualStudio71Generator::WriteProject(std::ostream& fout,
     ext = ".vfproj";
     project = "Project(\"{6989167D-11E4-40FE-8C1A-2192A86A7E90}\") = \"";
   }
+  if (this->TargetIsCSharpOnly(t)) {
+    ext = ".csproj";
+    project = "Project(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"";
+  }
   const char* targetExt = t->GetProperty("GENERATOR_FILE_NAME_EXT");
   if (targetExt) {
     ext = targetExt;
@@ -246,7 +249,7 @@ void cmGlobalVisualStudio71Generator::WriteExternalProject(
 // Write a dsp file into the SLN file, Note, that dependencies from
 // executables to the libraries it uses are also done here
 void cmGlobalVisualStudio71Generator::WriteProjectConfigurations(
-  std::ostream& fout, const std::string& name, cmState::TargetType,
+  std::ostream& fout, const std::string& name, cmStateEnums::TargetType,
   std::vector<std::string> const& configs,
   const std::set<std::string>& configsPartOfDefaultBuild,
   std::string const& platformMapping)
diff --git a/Source/cmGlobalVisualStudio71Generator.h b/Source/cmGlobalVisualStudio71Generator.h
index eb65bcb..9953047 100644
--- a/Source/cmGlobalVisualStudio71Generator.h
+++ b/Source/cmGlobalVisualStudio71Generator.h
@@ -56,7 +56,7 @@ protected:
                                    const char* path,
                                    cmGeneratorTarget const* t);
   virtual void WriteProjectConfigurations(
-    std::ostream& fout, const std::string& name, cmState::TargetType type,
+    std::ostream& fout, const std::string& name, cmStateEnums::TargetType type,
     std::vector<std::string> const& configs,
     const std::set<std::string>& configsPartOfDefaultBuild,
     const std::string& platformMapping = "");
diff --git a/Source/cmGlobalVisualStudio7Generator.cxx b/Source/cmGlobalVisualStudio7Generator.cxx
index 3637fed..602666e 100644
--- a/Source/cmGlobalVisualStudio7Generator.cxx
+++ b/Source/cmGlobalVisualStudio7Generator.cxx
@@ -8,6 +8,7 @@
 #include "cmGeneratorTarget.h"
 #include "cmLocalVisualStudio7Generator.h"
 #include "cmMakefile.h"
+#include "cmState.h"
 #include "cmUuid.h"
 #include "cmake.h"
 #include <cmsys/Encoding.hxx>
@@ -101,7 +102,7 @@ void cmGlobalVisualStudio7Generator::EnableLanguage(
       "Semicolon separated list of supported configuration types, "
       "only supports Debug, Release, MinSizeRel, and RelWithDebInfo, "
       "anything else will be ignored.",
-      cmState::STRING);
+      cmStateEnums::STRING);
   }
 
   // Create list of configurations requested by user's cache, if any.
@@ -118,15 +119,18 @@ void cmGlobalVisualStudio7Generator::EnableLanguage(
   if (cmSystemTools::GetEnv("CMAKE_MSVCIDE_RUN_PATH", extraPath)) {
     mf->AddCacheDefinition("CMAKE_MSVCIDE_RUN_PATH", extraPath.c_str(),
                            "Saved environment variable CMAKE_MSVCIDE_RUN_PATH",
-                           cmState::STATIC);
+                           cmStateEnums::STATIC);
   }
 }
 
-void cmGlobalVisualStudio7Generator::FindMakeProgram(cmMakefile* mf)
+bool cmGlobalVisualStudio7Generator::FindMakeProgram(cmMakefile* mf)
 {
-  this->cmGlobalVisualStudioGenerator::FindMakeProgram(mf);
+  if (!this->cmGlobalVisualStudioGenerator::FindMakeProgram(mf)) {
+    return false;
+  }
   mf->AddDefinition("CMAKE_VS_DEVENV_COMMAND",
                     this->GetDevEnvCommand().c_str());
+  return true;
 }
 
 std::string const& cmGlobalVisualStudio7Generator::GetDevEnvCommand()
@@ -345,7 +349,7 @@ void cmGlobalVisualStudio7Generator::WriteTargetConfigurations(
   for (OrderedTargetDependSet::const_iterator tt = projectTargets.begin();
        tt != projectTargets.end(); ++tt) {
     cmGeneratorTarget const* target = *tt;
-    if (target->GetType() == cmState::INTERFACE_LIBRARY) {
+    if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     const char* expath = target->GetProperty("EXTERNAL_MSPROJECT");
@@ -377,7 +381,7 @@ void cmGlobalVisualStudio7Generator::WriteTargetsToSolution(
   for (OrderedTargetDependSet::const_iterator tt = projectTargets.begin();
        tt != projectTargets.end(); ++tt) {
     cmGeneratorTarget const* target = *tt;
-    if (target->GetType() == cmState::INTERFACE_LIBRARY) {
+    if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     bool written = false;
@@ -409,8 +413,8 @@ void cmGlobalVisualStudio7Generator::WriteTargetsToSolution(
     // Create "solution folder" information from FOLDER target property
     //
     if (written && this->UseFolderProperty()) {
-      const char* targetFolder = target->GetProperty("FOLDER");
-      if (targetFolder) {
+      const std::string targetFolder = target->GetEffectiveFolderName();
+      if (!targetFolder.empty()) {
         std::vector<cmsys::String> tokens =
           cmSystemTools::SplitString(targetFolder, '/', false);
 
@@ -446,7 +450,7 @@ void cmGlobalVisualStudio7Generator::WriteTargetDepends(
   for (OrderedTargetDependSet::const_iterator tt = projectTargets.begin();
        tt != projectTargets.end(); ++tt) {
     cmGeneratorTarget const* target = *tt;
-    if (target->GetType() == cmState::INTERFACE_LIBRARY) {
+    if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     const char* vcprojName = target->GetProperty("GENERATOR_FILE_NAME");
@@ -676,27 +680,34 @@ std::set<std::string> cmGlobalVisualStudio7Generator::IsPartOfDefaultBuild(
   // if it is a utilitiy target then only make it part of the
   // default build if another target depends on it
   int type = target->GetType();
-  if (type == cmState::GLOBAL_TARGET) {
-    // check if INSTALL target is part of default build
-    if (target->GetName() == "INSTALL") {
-      // inspect CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD properties
-      for (std::vector<std::string>::const_iterator i = configs.begin();
-           i != configs.end(); ++i) {
-        const char* propertyValue =
-          target->Target->GetMakefile()->GetDefinition(
-            "CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD");
-        cmGeneratorExpression ge;
-        CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
-          ge.Parse(propertyValue);
-        if (cmSystemTools::IsOn(
-              cge->Evaluate(target->GetLocalGenerator(), *i))) {
-          activeConfigs.insert(*i);
+  if (type == cmStateEnums::GLOBAL_TARGET) {
+    std::list<std::string> targetNames;
+    targetNames.push_back("INSTALL");
+    targetNames.push_back("PACKAGE");
+    for (std::list<std::string>::const_iterator t = targetNames.begin();
+         t != targetNames.end(); ++t) {
+      // check if target <*t> is part of default build
+      if (target->GetName() == *t) {
+        const std::string propertyName =
+          "CMAKE_VS_INCLUDE_" + *t + "_TO_DEFAULT_BUILD";
+        // inspect CMAKE_VS_INCLUDE_<*t>_TO_DEFAULT_BUILD properties
+        for (std::vector<std::string>::const_iterator i = configs.begin();
+             i != configs.end(); ++i) {
+          const char* propertyValue =
+            target->Target->GetMakefile()->GetDefinition(propertyName);
+          cmGeneratorExpression ge;
+          CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
+            ge.Parse(propertyValue);
+          if (cmSystemTools::IsOn(
+                cge->Evaluate(target->GetLocalGenerator(), *i))) {
+            activeConfigs.insert(*i);
+          }
         }
       }
     }
     return activeConfigs;
   }
-  if (type == cmState::UTILITY &&
+  if (type == cmStateEnums::UTILITY &&
       !this->IsDependedOn(projectTargets, target)) {
     return activeConfigs;
   }
@@ -727,11 +738,5 @@ bool cmGlobalVisualStudio7Generator::IsDependedOn(
 
 std::string cmGlobalVisualStudio7Generator::Encoding()
 {
-  std::ostringstream encoding;
-#ifdef CMAKE_ENCODING_UTF8
-  encoding << "UTF-8";
-#else
-  encoding << "Windows-1252";
-#endif
-  return encoding.str();
+  return "UTF-8";
 }
diff --git a/Source/cmGlobalVisualStudio7Generator.h b/Source/cmGlobalVisualStudio7Generator.h
index 3c6ce11..62194c3 100644
--- a/Source/cmGlobalVisualStudio7Generator.h
+++ b/Source/cmGlobalVisualStudio7Generator.h
@@ -91,7 +91,7 @@ public:
 
   const char* GetIntelProjectVersion();
 
-  virtual void FindMakeProgram(cmMakefile*);
+  bool FindMakeProgram(cmMakefile* mf) CM_OVERRIDE;
 
   /** Is the Microsoft Assembler enabled?  */
   bool IsMasmEnabled() const { return this->MasmEnabled; }
@@ -120,7 +120,7 @@ protected:
                                    const char* path,
                                    cmGeneratorTarget const* t) = 0;
   virtual void WriteProjectConfigurations(
-    std::ostream& fout, const std::string& name, cmState::TargetType type,
+    std::ostream& fout, const std::string& name, cmStateEnums::TargetType type,
     std::vector<std::string> const& configs,
     const std::set<std::string>& configsPartOfDefaultBuild,
     const std::string& platformMapping = "") = 0;
diff --git a/Source/cmGlobalVisualStudio8Generator.cxx b/Source/cmGlobalVisualStudio8Generator.cxx
index 2ce0098..8353a3f 100644
--- a/Source/cmGlobalVisualStudio8Generator.cxx
+++ b/Source/cmGlobalVisualStudio8Generator.cxx
@@ -1,9 +1,8 @@
 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
    file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "windows.h" // this must be first to define GetCurrentDirectory
-
 #include "cmGlobalVisualStudio8Generator.h"
 
+#include "cmDocumentationEntry.h"
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorTarget.h"
 #include "cmLocalVisualStudio7Generator.h"
@@ -161,6 +160,11 @@ void cmGlobalVisualStudio8Generator::GetDocumentation(
   entry.Brief = "Generates Visual Studio 8 2005 project files.";
 }
 
+std::string cmGlobalVisualStudio8Generator::GetGenerateStampList()
+{
+  return "generate.stamp.list";
+}
+
 void cmGlobalVisualStudio8Generator::Configure()
 {
   this->cmGlobalVisualStudio7Generator::Configure();
@@ -244,7 +248,7 @@ bool cmGlobalVisualStudio8Generator::AddCheckTarget()
   // Create a list of all stamp files for this project.
   std::vector<std::string> stamps;
   std::string stampList = cmake::GetCMakeFilesDirectoryPostSlash();
-  stampList += "generate.stamp.list";
+  stampList += cmGlobalVisualStudio8Generator::GetGenerateStampList();
   {
     std::string stampListFile =
       generators[0]->GetMakefile()->GetCurrentBinaryDirectory();
@@ -294,7 +298,9 @@ bool cmGlobalVisualStudio8Generator::AddCheckTarget()
     commandLine.push_back("--check-stamp-list");
     commandLine.push_back(stampList.c_str());
     commandLine.push_back("--vs-solution-file");
-    commandLine.push_back("\"$(SolutionPath)\"");
+    std::string const sln = std::string(lg->GetBinaryDirectory()) + "/" +
+      lg->GetProjectName() + ".sln";
+    commandLine.push_back(sln);
     cmCustomCommandLines commandLines;
     commandLines.push_back(commandLine);
 
@@ -306,7 +312,7 @@ bool cmGlobalVisualStudio8Generator::AddCheckTarget()
     std::vector<std::string> no_byproducts;
     if (cmSourceFile* file = mf->AddCustomCommandToOutput(
           stamps, no_byproducts, listFiles, no_main_dependency, commandLines,
-          "Checking Build System", no_working_directory, true)) {
+          "Checking Build System", no_working_directory, true, false)) {
       gt->AddSource(file->GetFullPath());
     } else {
       cmSystemTools::Error("Error adding rule for ", stamps[0].c_str());
@@ -347,7 +353,7 @@ void cmGlobalVisualStudio8Generator::WriteSolutionConfigurations(
 }
 
 void cmGlobalVisualStudio8Generator::WriteProjectConfigurations(
-  std::ostream& fout, const std::string& name, cmState::TargetType type,
+  std::ostream& fout, const std::string& name, cmStateEnums::TargetType type,
   std::vector<std::string> const& configs,
   const std::set<std::string>& configsPartOfDefaultBuild,
   std::string const& platformMapping)
@@ -380,10 +386,10 @@ void cmGlobalVisualStudio8Generator::WriteProjectConfigurations(
 }
 
 bool cmGlobalVisualStudio8Generator::NeedsDeploy(
-  cmState::TargetType type) const
+  cmStateEnums::TargetType type) const
 {
   bool needsDeploy =
-    (type == cmState::EXECUTABLE || type == cmState::SHARED_LIBRARY);
+    (type == cmStateEnums::EXECUTABLE || type == cmStateEnums::SHARED_LIBRARY);
   return this->TargetsWindowsCE() && needsDeploy;
 }
 
@@ -402,7 +408,7 @@ void cmGlobalVisualStudio8Generator::WriteProjectDepends(
   OrderedTargetDependSet depends(unordered, std::string());
   for (OrderedTargetDependSet::const_iterator i = depends.begin();
        i != depends.end(); ++i) {
-    if ((*i)->GetType() == cmState::INTERFACE_LIBRARY) {
+    if ((*i)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     std::string guid = this->GetGUID((*i)->GetName().c_str());
@@ -419,7 +425,7 @@ bool cmGlobalVisualStudio8Generator::NeedLinkLibraryDependencies(
        ui != target->GetUtilities().end(); ++ui) {
     if (cmGeneratorTarget* depTarget =
           target->GetLocalGenerator()->FindGeneratorTargetToUse(ui->c_str())) {
-      if (depTarget->GetType() != cmState::INTERFACE_LIBRARY &&
+      if (depTarget->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
           depTarget->GetProperty("EXTERNAL_MSPROJECT")) {
         // This utility dependency names an external .vcproj target.
         // We use LinkLibraryDependencies="true" to link to it without
diff --git a/Source/cmGlobalVisualStudio8Generator.h b/Source/cmGlobalVisualStudio8Generator.h
index 2543ec1..53feb47 100644
--- a/Source/cmGlobalVisualStudio8Generator.h
+++ b/Source/cmGlobalVisualStudio8Generator.h
@@ -23,6 +23,9 @@ public:
   /** Get the documentation entry for this generator.  */
   static void GetDocumentation(cmDocumentationEntry& entry);
 
+  /** Get the name of the main stamp list file. */
+  static std::string GetGenerateStampList();
+
   virtual void EnableLanguage(std::vector<std::string> const& languages,
                               cmMakefile*, bool optional);
   virtual void AddPlatformDefinitions(cmMakefile* mf);
@@ -72,14 +75,14 @@ protected:
   bool AddCheckTarget();
 
   /** Return true if the configuration needs to be deployed */
-  virtual bool NeedsDeploy(cmState::TargetType type) const;
+  virtual bool NeedsDeploy(cmStateEnums::TargetType type) const;
 
   static cmIDEFlagTable const* GetExtraFlagTableVS8();
   virtual void WriteSLNHeader(std::ostream& fout);
   virtual void WriteSolutionConfigurations(
     std::ostream& fout, std::vector<std::string> const& configs);
   virtual void WriteProjectConfigurations(
-    std::ostream& fout, const std::string& name, cmState::TargetType type,
+    std::ostream& fout, const std::string& name, cmStateEnums::TargetType type,
     std::vector<std::string> const& configs,
     const std::set<std::string>& configsPartOfDefaultBuild,
     const std::string& platformMapping = "");
diff --git a/Source/cmGlobalVisualStudio9Generator.cxx b/Source/cmGlobalVisualStudio9Generator.cxx
index 32ba849..b1634e2 100644
--- a/Source/cmGlobalVisualStudio9Generator.cxx
+++ b/Source/cmGlobalVisualStudio9Generator.cxx
@@ -1,9 +1,8 @@
 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
    file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "windows.h" // this must be first to define GetCurrentDirectory
-
 #include "cmGlobalVisualStudio9Generator.h"
 
+#include "cmDocumentationEntry.h"
 #include "cmLocalVisualStudio7Generator.h"
 #include "cmMakefile.h"
 #include "cmVisualStudioWCEPlatformParser.h"
diff --git a/Source/cmGlobalVisualStudioGenerator.cxx b/Source/cmGlobalVisualStudioGenerator.cxx
index 6296dd2..ced0c26 100644
--- a/Source/cmGlobalVisualStudioGenerator.cxx
+++ b/Source/cmGlobalVisualStudioGenerator.cxx
@@ -3,6 +3,9 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalVisualStudioGenerator.h"
 
+#include <cmsys/Encoding.hxx>
+#include <iostream>
+
 #include "cmAlgorithms.h"
 #include "cmCallVisualStudioMacro.h"
 #include "cmGeneratedFileStream.h"
@@ -10,8 +13,8 @@
 #include "cmLocalVisualStudioGenerator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
+#include "cmState.h"
 #include "cmTarget.h"
-#include <cmsys/Encoding.hxx>
 
 cmGlobalVisualStudioGenerator::cmGlobalVisualStudioGenerator(cmake* cm)
   : cmGlobalGenerator(cm)
@@ -81,7 +84,8 @@ void cmGlobalVisualStudioGenerator::AddExtraIDETargets()
         for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
              t != targets.end(); ++t) {
           cmGeneratorTarget* tgt = *t;
-          if (tgt->GetType() == cmState::GLOBAL_TARGET || tgt->IsImported()) {
+          if (tgt->GetType() == cmStateEnums::GLOBAL_TARGET ||
+              tgt->IsImported()) {
             continue;
           }
           if (!this->IsExcluded(gen[0], tgt)) {
@@ -265,11 +269,11 @@ cmGlobalVisualStudioGenerator::GetTargetLinkClosure(cmGeneratorTarget* target)
 void cmGlobalVisualStudioGenerator::FollowLinkDepends(
   const cmGeneratorTarget* target, std::set<const cmGeneratorTarget*>& linked)
 {
-  if (target->GetType() == cmState::INTERFACE_LIBRARY) {
+  if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
     return;
   }
   if (linked.insert(target).second &&
-      target->GetType() == cmState::STATIC_LIBRARY) {
+      target->GetType() == cmStateEnums::STATIC_LIBRARY) {
     // Static library targets do not list their link dependencies so
     // we must follow them transitively now.
     TargetDependSet const& depends = this->GetTargetDirectDepends(target);
@@ -304,7 +308,7 @@ bool cmGlobalVisualStudioGenerator::ComputeTargetDepends()
 
 static bool VSLinkable(cmGeneratorTarget const* t)
 {
-  return t->IsLinkable() || t->GetType() == cmState::OBJECT_LIBRARY;
+  return t->IsLinkable() || t->GetType() == cmStateEnums::OBJECT_LIBRARY;
 }
 
 void cmGlobalVisualStudioGenerator::ComputeVSTargetDepends(
@@ -333,10 +337,10 @@ void cmGlobalVisualStudioGenerator::ComputeVSTargetDepends(
   // leaving them out for the static library itself but following them
   // transitively for other targets.
 
-  bool allowLinkable = (target->GetType() != cmState::STATIC_LIBRARY &&
-                        target->GetType() != cmState::SHARED_LIBRARY &&
-                        target->GetType() != cmState::MODULE_LIBRARY &&
-                        target->GetType() != cmState::EXECUTABLE);
+  bool allowLinkable = (target->GetType() != cmStateEnums::STATIC_LIBRARY &&
+                        target->GetType() != cmStateEnums::SHARED_LIBRARY &&
+                        target->GetType() != cmStateEnums::MODULE_LIBRARY &&
+                        target->GetType() != cmStateEnums::EXECUTABLE);
 
   TargetDependSet const& depends = this->GetTargetDirectDepends(target);
 
@@ -344,7 +348,7 @@ void cmGlobalVisualStudioGenerator::ComputeVSTargetDepends(
   // Static libraries cannot depend on their link implementation
   // due to behavior (2), but they do not really need to.
   std::set<cmGeneratorTarget const*> linkDepends;
-  if (target->GetType() != cmState::STATIC_LIBRARY) {
+  if (target->GetType() != cmStateEnums::STATIC_LIBRARY) {
     for (TargetDependSet::const_iterator di = depends.begin();
          di != depends.end(); ++di) {
       cmTargetDepend dep = *di;
@@ -367,7 +371,7 @@ void cmGlobalVisualStudioGenerator::ComputeVSTargetDepends(
   // Collect all targets linked by this target so we can avoid
   // intermediate targets below.
   TargetSet linked;
-  if (target->GetType() != cmState::STATIC_LIBRARY) {
+  if (target->GetType() != cmStateEnums::STATIC_LIBRARY) {
     linked = this->GetTargetLinkClosure(target);
   }
 
@@ -393,7 +397,7 @@ void cmGlobalVisualStudioGenerator::ComputeVSTargetDepends(
   }
 }
 
-void cmGlobalVisualStudioGenerator::FindMakeProgram(cmMakefile* mf)
+bool cmGlobalVisualStudioGenerator::FindMakeProgram(cmMakefile* mf)
 {
   // Visual Studio generators know how to lookup their build tool
   // directly instead of needing a helper module to do it, so we
@@ -401,6 +405,7 @@ void cmGlobalVisualStudioGenerator::FindMakeProgram(cmMakefile* mf)
   if (cmSystemTools::IsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) {
     mf->AddDefinition("CMAKE_MAKE_PROGRAM", this->GetVSMakeProgram().c_str());
   }
+  return true;
 }
 
 std::string cmGlobalVisualStudioGenerator::GetUtilityDepend(
@@ -734,6 +739,31 @@ bool cmGlobalVisualStudioGenerator::TargetIsFortranOnly(
   return false;
 }
 
+bool cmGlobalVisualStudioGenerator::TargetIsCSharpOnly(
+  cmGeneratorTarget const* gt)
+{
+  // check to see if this is a C# build
+  std::set<std::string> languages;
+  {
+    // Issue diagnostic if the source files depend on the config.
+    std::vector<cmSourceFile*> sources;
+    if (!gt->GetConfigCommonSourceFiles(sources)) {
+      return false;
+    }
+    // Only "real" targets are allowed to be C# targets.
+    if (gt->Target->GetType() > cmStateEnums::OBJECT_LIBRARY) {
+      return false;
+    }
+  }
+  gt->GetLanguages(languages, "");
+  if (languages.size() == 1) {
+    if (*languages.begin() == "CSharp") {
+      return true;
+    }
+  }
+  return false;
+}
+
 bool cmGlobalVisualStudioGenerator::TargetCompare::operator()(
   cmGeneratorTarget const* l, cmGeneratorTarget const* r) const
 {
@@ -830,6 +860,14 @@ void cmGlobalVisualStudioGenerator::AddSymbolExportCommand(
     std::string objFile = obj_dir + map_it->second;
     objs.push_back(objFile);
   }
+  std::vector<cmSourceFile const*> externalObjectSources;
+  gt->GetExternalObjects(externalObjectSources, configName);
+  for (std::vector<cmSourceFile const*>::const_iterator it =
+         externalObjectSources.begin();
+       it != externalObjectSources.end(); ++it) {
+    objs.push_back((*it)->GetFullPath());
+  }
+
   gt->UseObjectLibraries(objs, configName);
   for (std::vector<std::string>::iterator it = objs.begin(); it != objs.end();
        ++it) {
diff --git a/Source/cmGlobalVisualStudioGenerator.h b/Source/cmGlobalVisualStudioGenerator.h
index a774d96..f32f0bb 100644
--- a/Source/cmGlobalVisualStudioGenerator.h
+++ b/Source/cmGlobalVisualStudioGenerator.h
@@ -3,7 +3,22 @@
 #ifndef cmGlobalVisualStudioGenerator_h
 #define cmGlobalVisualStudioGenerator_h
 
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
 #include "cmGlobalGenerator.h"
+#include "cmTargetDepend.h"
+
+class cmCustomCommand;
+class cmGeneratorTarget;
+class cmLocalGenerator;
+class cmMakefile;
+class cmake;
 
 /** \class cmGlobalVisualStudioGenerator
  * \brief Base class for global Visual Studio generators.
@@ -69,6 +84,9 @@ public:
   // return true if target is fortran only
   bool TargetIsFortranOnly(const cmGeneratorTarget* gt);
 
+  // return true if target is C# only
+  static bool TargetIsCSharpOnly(cmGeneratorTarget const* gt);
+
   /** Get the top-level registry key for this VS version.  */
   std::string GetRegistryBase();
 
@@ -99,7 +117,7 @@ public:
   };
   class OrderedTargetDependSet;
 
-  virtual void FindMakeProgram(cmMakefile*);
+  bool FindMakeProgram(cmMakefile*) CM_OVERRIDE;
 
   virtual std::string ExpandCFGIntDir(const std::string& str,
                                       const std::string& config) const;
diff --git a/Source/cmGlobalXCodeGenerator.cxx b/Source/cmGlobalXCodeGenerator.cxx
index 537aa16..dd771b1 100644
--- a/Source/cmGlobalXCodeGenerator.cxx
+++ b/Source/cmGlobalXCodeGenerator.cxx
@@ -2,20 +2,36 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGlobalXCodeGenerator.h"
 
-#include "cmAlgorithms.h"
+#include <assert.h>
+#include <cmsys/RegularExpression.hxx>
+#include <iomanip>
+#include <sstream>
+#include <stdio.h>
+#include <string.h>
+
 #include "cmComputeLinkInformation.h"
 #include "cmCustomCommandGenerator.h"
+#include "cmDocumentationEntry.h"
 #include "cmGeneratedFileStream.h"
+#include "cmGeneratorExpression.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalGeneratorFactory.h"
+#include "cmLocalGenerator.h"
 #include "cmLocalXCodeGenerator.h"
 #include "cmMakefile.h"
+#include "cmOutputConverter.h"
 #include "cmSourceFile.h"
+#include "cmSourceGroup.h"
+#include "cmState.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
 #include "cmXCode21Object.h"
 #include "cmXCodeObject.h"
+#include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
-#include <cm_auto_ptr.hxx>
+struct cmLinkImplementation;
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
 #include "cmXMLParser.h"
@@ -182,7 +198,7 @@ cmGlobalGenerator* cmGlobalXCodeGenerator::Factory::CreateGlobalGenerator(
 #endif
 }
 
-void cmGlobalXCodeGenerator::FindMakeProgram(cmMakefile* mf)
+bool cmGlobalXCodeGenerator::FindMakeProgram(cmMakefile* mf)
 {
   // The Xcode generator knows how to lookup its build tool
   // directly instead of needing a helper module to do it, so we
@@ -191,6 +207,7 @@ void cmGlobalXCodeGenerator::FindMakeProgram(cmMakefile* mf)
     mf->AddDefinition("CMAKE_MAKE_PROGRAM",
                       this->GetXcodeBuildCommand().c_str());
   }
+  return true;
 }
 
 std::string const& cmGlobalXCodeGenerator::GetXcodeBuildCommand()
@@ -220,6 +237,19 @@ bool cmGlobalXCodeGenerator::SetGeneratorToolset(std::string const& ts,
                                                  cmMakefile* mf)
 {
   if (this->XcodeVersion >= 30) {
+    if (ts.find_first_of(",=") != ts.npos) {
+      std::ostringstream e;
+      /* clang-format off */
+      e <<
+        "Generator\n"
+        "  " << this->GetName() << "\n"
+        "does not recognize the toolset\n"
+        "  " << ts << "\n"
+        "that was specified.";
+      /* clang-format on */
+      mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+      return false;
+    }
     this->GeneratorToolset = ts;
     if (!this->GeneratorToolset.empty()) {
       mf->AddDefinition("CMAKE_XCODE_PLATFORM_TOOLSET",
@@ -244,7 +274,7 @@ void cmGlobalXCodeGenerator::EnableLanguage(
         "Semicolon separated list of supported configuration types, "
         "only supports Debug, Release, MinSizeRel, and RelWithDebInfo, "
         "anything else will be ignored.",
-        cmState::STRING);
+        cmStateEnums::STRING);
     }
   }
   mf->AddDefinition("CMAKE_GENERATOR_NO_COMPILER_ENV", "1");
@@ -431,7 +461,7 @@ void cmGlobalXCodeGenerator::AddExtraTargets(
          l != tgts.end(); l++) {
       cmGeneratorTarget* target = *l;
 
-      if (target->GetType() == cmState::GLOBAL_TARGET) {
+      if (target->GetType() == cmStateEnums::GLOBAL_TARGET) {
         continue;
       }
 
@@ -446,12 +476,12 @@ void cmGlobalXCodeGenerator::AddExtraTargets(
       // this will make sure that when the next target is built
       // things are up-to-date
       if (!makeHelper.empty() &&
-          (target->GetType() == cmState::EXECUTABLE ||
+          (target->GetType() == cmStateEnums::EXECUTABLE ||
            // Nope - no post-build for OBJECT_LIRBRARY
-           //          target->GetType() == cmState::OBJECT_LIBRARY ||
-           target->GetType() == cmState::STATIC_LIBRARY ||
-           target->GetType() == cmState::SHARED_LIBRARY ||
-           target->GetType() == cmState::MODULE_LIBRARY)) {
+           //          target->GetType() == cmStateEnums::OBJECT_LIBRARY ||
+           target->GetType() == cmStateEnums::STATIC_LIBRARY ||
+           target->GetType() == cmStateEnums::SHARED_LIBRARY ||
+           target->GetType() == cmStateEnums::MODULE_LIBRARY)) {
         makeHelper[makeHelper.size() - 1] = // fill placeholder
           this->PostBuildMakeTarget(target->GetName(), "$(CONFIGURATION)");
         cmCustomCommandLines commandLines;
@@ -462,7 +492,7 @@ void cmGlobalXCodeGenerator::AddExtraTargets(
           cmTarget::POST_BUILD, "Depend check for xcode", dir.c_str());
       }
 
-      if (target->GetType() != cmState::INTERFACE_LIBRARY &&
+      if (target->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
           !target->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
         allbuild->AddUtility(target->GetName());
       }
@@ -661,7 +691,24 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeSourceFile(
     default:
       break;
   }
-  lg->AppendFlags(flags, sf->GetProperty("COMPILE_FLAGS"));
+  if (const char* cflags = sf->GetProperty("COMPILE_FLAGS")) {
+    cmGeneratorExpression ge;
+    std::string configName = "NO-PER-CONFIG-SUPPORT-IN-XCODE";
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> compiledExpr = ge.Parse(cflags);
+    const char* processed = compiledExpr->Evaluate(lg, configName);
+    if (compiledExpr->GetHadContextSensitiveCondition()) {
+      std::ostringstream e;
+      /* clang-format off */
+      e <<
+        "Xcode does not support per-config per-source COMPILE_FLAGS:\n"
+        "  " << cflags << "\n"
+        "specified for source:\n"
+        "  " << sf->GetFullPath() << "\n";
+      /* clang-format on */
+      lg->IssueMessage(cmake::FATAL_ERROR, e.str());
+    }
+    lg->AppendFlags(flags, processed);
+  }
 
   // Add per-source definitions.
   BuildObjectListOrString flagsBuild(this, false);
@@ -942,12 +989,12 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets(
       continue;
     }
 
-    if (gtgt->GetType() == cmState::INTERFACE_LIBRARY) {
+    if (gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
 
-    if (gtgt->GetType() == cmState::UTILITY ||
-        gtgt->GetType() == cmState::GLOBAL_TARGET) {
+    if (gtgt->GetType() == cmStateEnums::UTILITY ||
+        gtgt->GetType() == cmStateEnums::GLOBAL_TARGET) {
       cmXCodeObject* t = this->CreateUtilityTarget(gtgt);
       if (!t) {
         return false;
@@ -1175,9 +1222,9 @@ void cmGlobalXCodeGenerator::ForceLinkerLanguages()
 void cmGlobalXCodeGenerator::ForceLinkerLanguage(cmGeneratorTarget* gtgt)
 {
   // This matters only for targets that link.
-  if (gtgt->GetType() != cmState::EXECUTABLE &&
-      gtgt->GetType() != cmState::SHARED_LIBRARY &&
-      gtgt->GetType() != cmState::MODULE_LIBRARY) {
+  if (gtgt->GetType() != cmStateEnums::EXECUTABLE &&
+      gtgt->GetType() != cmStateEnums::SHARED_LIBRARY &&
+      gtgt->GetType() != cmStateEnums::MODULE_LIBRARY) {
     return;
   }
 
@@ -1255,7 +1302,7 @@ void cmGlobalXCodeGenerator::CreateCustomCommands(
   std::vector<cmCustomCommand> const& prelink = gtgt->GetPreLinkCommands();
   std::vector<cmCustomCommand> postbuild = gtgt->GetPostBuildCommands();
 
-  if (gtgt->GetType() == cmState::SHARED_LIBRARY &&
+  if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY &&
       !gtgt->IsFrameworkOnApple()) {
     cmCustomCommandLines cmd;
     cmd.resize(1);
@@ -1577,16 +1624,16 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
                                                  cmXCodeObject* buildSettings,
                                                  const std::string& configName)
 {
-  if (gtgt->GetType() == cmState::INTERFACE_LIBRARY) {
+  if (gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
     return;
   }
 
   std::string defFlags;
-  bool shared = ((gtgt->GetType() == cmState::SHARED_LIBRARY) ||
-                 (gtgt->GetType() == cmState::MODULE_LIBRARY));
-  bool binary = ((gtgt->GetType() == cmState::OBJECT_LIBRARY) ||
-                 (gtgt->GetType() == cmState::STATIC_LIBRARY) ||
-                 (gtgt->GetType() == cmState::EXECUTABLE) || shared);
+  bool shared = ((gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) ||
+                 (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY));
+  bool binary = ((gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
+                 (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) ||
+                 (gtgt->GetType() == cmStateEnums::EXECUTABLE) || shared);
 
   // Compute the compilation flags for each language.
   std::set<std::string> languages;
@@ -1640,11 +1687,11 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
 
   std::string extraLinkOptionsVar;
   std::string extraLinkOptions;
-  if (gtgt->GetType() == cmState::EXECUTABLE) {
+  if (gtgt->GetType() == cmStateEnums::EXECUTABLE) {
     extraLinkOptionsVar = "CMAKE_EXE_LINKER_FLAGS";
-  } else if (gtgt->GetType() == cmState::SHARED_LIBRARY) {
+  } else if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
     extraLinkOptionsVar = "CMAKE_SHARED_LINKER_FLAGS";
-  } else if (gtgt->GetType() == cmState::MODULE_LIBRARY) {
+  } else if (gtgt->GetType() == cmStateEnums::MODULE_LIBRARY) {
     extraLinkOptionsVar = "CMAKE_MODULE_LINKER_FLAGS";
   }
   if (!extraLinkOptionsVar.empty()) {
@@ -1652,8 +1699,8 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
       extraLinkOptions, extraLinkOptionsVar, configName);
   }
 
-  if (gtgt->GetType() == cmState::OBJECT_LIBRARY ||
-      gtgt->GetType() == cmState::STATIC_LIBRARY) {
+  if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
+      gtgt->GetType() == cmStateEnums::STATIC_LIBRARY) {
     this->CurrentLocalGenerator->GetStaticLibraryFlags(
       extraLinkOptions, cmSystemTools::UpperCase(configName), gtgt);
   } else {
@@ -1723,10 +1770,10 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
 
   // Set attributes to specify the proper name for the target.
   std::string pndir = this->CurrentLocalGenerator->GetCurrentBinaryDirectory();
-  if (gtgt->GetType() == cmState::STATIC_LIBRARY ||
-      gtgt->GetType() == cmState::SHARED_LIBRARY ||
-      gtgt->GetType() == cmState::MODULE_LIBRARY ||
-      gtgt->GetType() == cmState::EXECUTABLE) {
+  if (gtgt->GetType() == cmStateEnums::STATIC_LIBRARY ||
+      gtgt->GetType() == cmStateEnums::SHARED_LIBRARY ||
+      gtgt->GetType() == cmStateEnums::MODULE_LIBRARY ||
+      gtgt->GetType() == cmStateEnums::EXECUTABLE) {
     if (this->XcodeVersion >= 21) {
       if (!gtgt->UsesDefaultOutputDir(configName, false)) {
         std::string pncdir = gtgt->GetDirectory(configName);
@@ -1746,7 +1793,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
                                 this->CreateString(pnprefix));
     buildSettings->AddAttribute("EXECUTABLE_SUFFIX",
                                 this->CreateString(pnsuffix));
-  } else if (gtgt->GetType() == cmState::OBJECT_LIBRARY) {
+  } else if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
     pnprefix = "lib";
     pnbase = gtgt->GetName();
     pnsuffix = ".a";
@@ -1769,14 +1816,40 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
 
   // Handle settings for each target type.
   switch (gtgt->GetType()) {
-    case cmState::OBJECT_LIBRARY:
-    case cmState::STATIC_LIBRARY: {
+    case cmStateEnums::STATIC_LIBRARY:
+      if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
+        std::string fw_version = gtgt->GetFrameworkVersion();
+        buildSettings->AddAttribute("FRAMEWORK_VERSION",
+                                    this->CreateString(fw_version));
+        const char* ext = gtgt->GetProperty("BUNDLE_EXTENSION");
+        if (ext) {
+          buildSettings->AddAttribute("WRAPPER_EXTENSION",
+                                      this->CreateString(ext));
+        }
+
+        std::string plist = this->ComputeInfoPListLocation(gtgt);
+        // Xcode will create the final version of Info.plist at build time,
+        // so let it replace the framework name. This avoids creating
+        // a per-configuration Info.plist file.
+        this->CurrentLocalGenerator->GenerateFrameworkInfoPList(
+          gtgt, "$(EXECUTABLE_NAME)", plist.c_str());
+        buildSettings->AddAttribute("INFOPLIST_FILE",
+                                    this->CreateString(plist));
+        buildSettings->AddAttribute("MACH_O_TYPE",
+                                    this->CreateString("staticlib"));
+      } else {
+        buildSettings->AddAttribute("LIBRARY_STYLE",
+                                    this->CreateString("STATIC"));
+      }
+      break;
+
+    case cmStateEnums::OBJECT_LIBRARY: {
       buildSettings->AddAttribute("LIBRARY_STYLE",
                                   this->CreateString("STATIC"));
       break;
     }
 
-    case cmState::MODULE_LIBRARY: {
+    case cmStateEnums::MODULE_LIBRARY: {
       buildSettings->AddAttribute("LIBRARY_STYLE",
                                   this->CreateString("BUNDLE"));
       if (gtgt->IsCFBundleOnApple()) {
@@ -1826,7 +1899,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
       }
       break;
     }
-    case cmState::SHARED_LIBRARY: {
+    case cmStateEnums::SHARED_LIBRARY: {
       if (gtgt->GetPropertyAsBool("FRAMEWORK")) {
         std::string fw_version = gtgt->GetFrameworkVersion();
         buildSettings->AddAttribute("FRAMEWORK_VERSION",
@@ -1859,7 +1932,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
                                   this->CreateString("DYNAMIC"));
       break;
     }
-    case cmState::EXECUTABLE: {
+    case cmStateEnums::EXECUTABLE: {
       // Add the flags to create an executable.
       std::string createFlags =
         this->LookupFlags("CMAKE_", llang, "_LINK_FLAGS", "");
@@ -1931,6 +2004,22 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
     buildSettings->AddAttribute("HEADER_SEARCH_PATHS", dirs.CreateList());
   }
 
+  if (this->XcodeVersion >= 60) {
+    // Add those per-language flags in addition to HEADER_SEARCH_PATHS to gain
+    // system include directory awareness. We need to also keep on setting
+    // HEADER_SEARCH_PATHS to work around a missing compile options flag for
+    // GNU assembly files (#16449)
+    for (std::set<std::string>::iterator li = languages.begin();
+         li != languages.end(); ++li) {
+      std::string includeFlags = this->CurrentLocalGenerator->GetIncludeFlags(
+        includes, gtgt, *li, true, false, configName);
+
+      if (!includeFlags.empty()) {
+        cflags[*li] += " " + includeFlags;
+      }
+    }
+  }
+
   bool same_gflags = true;
   std::map<std::string, std::string> gflags;
   std::string const* last_gflag = 0;
@@ -2022,7 +2111,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
 
   // Create the INSTALL_PATH attribute.
   std::string install_name_dir;
-  if (gtgt->GetType() == cmState::SHARED_LIBRARY) {
+  if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
     // Get the install_name directory for the build tree.
     install_name_dir = gtgt->GetInstallNameDirForBuildTree(configName);
     // Xcode doesn't create the correct install_name in some cases.
@@ -2095,7 +2184,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
   }
 
   // Runtime version information.
-  if (gtgt->GetType() == cmState::SHARED_LIBRARY) {
+  if (gtgt->GetType() == cmStateEnums::SHARED_LIBRARY) {
     int major;
     int minor;
     int patch;
@@ -2190,7 +2279,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget(
   this->XCodeObjectMap[gtgt] = target;
 
   // Add source files without build rules for editing convenience.
-  if (gtgt->GetType() == cmState::UTILITY) {
+  if (gtgt->GetType() == cmStateEnums::UTILITY) {
     std::vector<cmSourceFile*> sources;
     if (!gtgt->GetConfigCommonSourceFiles(sources)) {
       return 0;
@@ -2256,8 +2345,8 @@ const char* cmGlobalXCodeGenerator::GetTargetLinkFlagsVar(
   cmGeneratorTarget const* target) const
 {
   if (this->XcodeVersion >= 60 &&
-      (target->GetType() == cmState::STATIC_LIBRARY ||
-       target->GetType() == cmState::OBJECT_LIBRARY)) {
+      (target->GetType() == cmStateEnums::STATIC_LIBRARY ||
+       target->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
     return "OTHER_LIBTOOLFLAGS";
   } else {
     return "OTHER_LDFLAGS";
@@ -2267,11 +2356,17 @@ const char* cmGlobalXCodeGenerator::GetTargetLinkFlagsVar(
 const char* cmGlobalXCodeGenerator::GetTargetFileType(
   cmGeneratorTarget* target)
 {
+  if (const char* e = target->GetProperty("XCODE_EXPLICIT_FILE_TYPE")) {
+    return e;
+  }
+
   switch (target->GetType()) {
-    case cmState::OBJECT_LIBRARY:
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::OBJECT_LIBRARY:
       return "archive.ar";
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
+      return (target->GetPropertyAsBool("FRAMEWORK") ? "wrapper.framework"
+                                                     : "archive.ar");
+    case cmStateEnums::MODULE_LIBRARY:
       if (target->IsXCTestOnApple())
         return "wrapper.cfbundle";
       else if (target->IsCFBundleOnApple())
@@ -2279,11 +2374,11 @@ const char* cmGlobalXCodeGenerator::GetTargetFileType(
       else
         return ((this->XcodeVersion >= 22) ? "compiled.mach-o.executable"
                                            : "compiled.mach-o.dylib");
-    case cmState::SHARED_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
       return (target->GetPropertyAsBool("FRAMEWORK")
                 ? "wrapper.framework"
                 : "compiled.mach-o.dylib");
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       return "compiled.mach-o.executable";
     default:
       break;
@@ -2294,11 +2389,18 @@ const char* cmGlobalXCodeGenerator::GetTargetFileType(
 const char* cmGlobalXCodeGenerator::GetTargetProductType(
   cmGeneratorTarget* target)
 {
+  if (const char* e = target->GetProperty("XCODE_PRODUCT_TYPE")) {
+    return e;
+  }
+
   switch (target->GetType()) {
-    case cmState::OBJECT_LIBRARY:
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::OBJECT_LIBRARY:
       return "com.apple.product-type.library.static";
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
+      return (target->GetPropertyAsBool("FRAMEWORK")
+                ? "com.apple.product-type.framework"
+                : "com.apple.product-type.library.static");
+    case cmStateEnums::MODULE_LIBRARY:
       if (target->IsXCTestOnApple())
         return "com.apple.product-type.bundle.unit-test";
       else if (target->IsCFBundleOnApple())
@@ -2307,11 +2409,11 @@ const char* cmGlobalXCodeGenerator::GetTargetProductType(
         return ((this->XcodeVersion >= 22)
                   ? "com.apple.product-type.tool"
                   : "com.apple.product-type.library.dynamic");
-    case cmState::SHARED_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
       return (target->GetPropertyAsBool("FRAMEWORK")
                 ? "com.apple.product-type.framework"
                 : "com.apple.product-type.library.dynamic");
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       return (target->GetPropertyAsBool("MACOSX_BUNDLE")
                 ? "com.apple.product-type.application"
                 : "com.apple.product-type.tool");
@@ -2324,7 +2426,7 @@ const char* cmGlobalXCodeGenerator::GetTargetProductType(
 cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
   cmGeneratorTarget* gtgt, cmXCodeObject* buildPhases)
 {
-  if (gtgt->GetType() == cmState::INTERFACE_LIBRARY) {
+  if (gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
     return 0;
   }
   cmXCodeObject* target = this->CreateObject(cmXCodeObject::PBXNativeTarget);
@@ -2351,7 +2453,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
     fileRef->AddAttribute("explicitFileType", this->CreateString(fileType));
   }
   std::string fullName;
-  if (gtgt->GetType() == cmState::OBJECT_LIBRARY) {
+  if (gtgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
     fullName = "lib";
     fullName += gtgt->GetName();
     fullName += ".a";
@@ -2403,8 +2505,9 @@ std::string cmGlobalXCodeGenerator::GetOrCreateId(const std::string& name,
     return storedGUID;
   }
 
-  this->CMakeInstance->AddCacheEntry(
-    guidStoreName, id.c_str(), "Stored Xcode object GUID", cmState::INTERNAL);
+  this->CMakeInstance->AddCacheEntry(guidStoreName, id.c_str(),
+                                     "Stored Xcode object GUID",
+                                     cmStateEnums::INTERNAL);
 
   return id;
 }
@@ -2498,7 +2601,7 @@ void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
     cmSystemTools::Error("Error no target on xobject\n");
     return;
   }
-  if (gt->GetType() == cmState::INTERFACE_LIBRARY) {
+  if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
     return;
   }
 
@@ -2535,8 +2638,8 @@ void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
     }
 
     // Skip link information for object libraries.
-    if (gt->GetType() == cmState::OBJECT_LIBRARY ||
-        gt->GetType() == cmState::STATIC_LIBRARY) {
+    if (gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
+        gt->GetType() == cmStateEnums::STATIC_LIBRARY) {
       continue;
     }
 
@@ -2591,7 +2694,7 @@ void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
         if (li->IsPath) {
           linkLibs += this->XCodeEscapePath(li->Value);
         } else if (!li->Target ||
-                   li->Target->GetType() != cmState::INTERFACE_LIBRARY) {
+                   li->Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
           linkLibs += li->Value;
         }
         if (li->Target && !li->Target->IsImported()) {
@@ -2620,10 +2723,10 @@ bool cmGlobalXCodeGenerator::CreateGroups(
       // end up with (empty anyhow) ALL_BUILD and XCODE_DEPEND_HELPER source
       // groups:
       //
-      if (gtgt->GetType() == cmState::GLOBAL_TARGET) {
+      if (gtgt->GetType() == cmStateEnums::GLOBAL_TARGET) {
         continue;
       }
-      if (gtgt->GetType() == cmState::INTERFACE_LIBRARY) {
+      if (gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
         continue;
       }
 
@@ -2694,8 +2797,8 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup(
 {
   std::string s;
   std::string target;
-  const char* targetFolder = gtgt->GetProperty("FOLDER");
-  if (targetFolder) {
+  const std::string targetFolder = gtgt->GetEffectiveFolderName();
+  if (!targetFolder.empty()) {
     target = targetFolder;
     target += "/";
   }
@@ -2972,10 +3075,14 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects(
                                 this->CreateString(this->GeneratorToolset));
   }
   if (this->GetLanguageEnabled("Swift")) {
-    std::string swiftVersion = "2.3";
+    std::string swiftVersion;
     if (const char* vers = this->CurrentMakefile->GetDefinition(
           "CMAKE_Swift_LANGUAGE_VERSION")) {
       swiftVersion = vers;
+    } else if (this->XcodeVersion >= 83) {
+      swiftVersion = "3.0";
+    } else {
+      swiftVersion = "2.3";
     }
     buildSettings->AddAttribute("SWIFT_VERSION",
                                 this->CreateString(swiftVersion));
@@ -3120,20 +3227,20 @@ void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget(
       cmXCodeObject* target = *i;
       cmGeneratorTarget* gt = target->GetTarget();
 
-      if (gt->GetType() == cmState::EXECUTABLE ||
+      if (gt->GetType() == cmStateEnums::EXECUTABLE ||
           // Nope - no post-build for OBJECT_LIRBRARY
-          //         gt->GetType() == cmState::OBJECT_LIBRARY ||
-          gt->GetType() == cmState::STATIC_LIBRARY ||
-          gt->GetType() == cmState::SHARED_LIBRARY ||
-          gt->GetType() == cmState::MODULE_LIBRARY) {
+          //         gt->GetType() == cmStateEnums::OBJECT_LIBRARY ||
+          gt->GetType() == cmStateEnums::STATIC_LIBRARY ||
+          gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
+          gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
         // Declare an entry point for the target post-build phase.
         makefileStream << this->PostBuildMakeTarget(gt->GetName(), *ct)
                        << ":\n";
       }
 
-      if (gt->GetType() == cmState::EXECUTABLE ||
-          gt->GetType() == cmState::SHARED_LIBRARY ||
-          gt->GetType() == cmState::MODULE_LIBRARY) {
+      if (gt->GetType() == cmStateEnums::EXECUTABLE ||
+          gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
+          gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
         std::string tfull = gt->GetFullPath(configName);
         std::string trel = this->ConvertToRelativeForMake(tfull.c_str());
 
@@ -3309,14 +3416,14 @@ std::string cmGlobalXCodeGenerator::RelativeToSource(const char* p)
 {
   // We force conversion because Xcode breakpoints do not work unless
   // they are in a file named relative to the source tree.
-  return this->CurrentLocalGenerator->ConvertToRelativePath(
-    this->ProjectSourceDirectoryComponents, p, true);
+  return cmOutputConverter::ForceToRelativePath(
+    cmSystemTools::JoinPath(this->ProjectSourceDirectoryComponents), p);
 }
 
 std::string cmGlobalXCodeGenerator::RelativeToBinary(const char* p)
 {
   return this->CurrentLocalGenerator->ConvertToRelativePath(
-    this->ProjectOutputDirectoryComponents, p);
+    cmSystemTools::JoinPath(this->ProjectOutputDirectoryComponents), p);
 }
 
 std::string cmGlobalXCodeGenerator::XCodeEscapePath(const std::string& p)
@@ -3473,6 +3580,19 @@ bool cmGlobalXCodeGenerator::IsMultiConfig() const
   return true;
 }
 
+bool cmGlobalXCodeGenerator::UseEffectivePlatformName(cmMakefile* mf) const
+{
+  const char* epnValue =
+    this->GetCMakeInstance()->GetState()->GetGlobalProperty(
+      "XCODE_EMIT_EFFECTIVE_PLATFORM_NAME");
+
+  if (!epnValue) {
+    return mf->PlatformIsAppleIos();
+  }
+
+  return cmSystemTools::IsOn(epnValue);
+}
+
 void cmGlobalXCodeGenerator::ComputeTargetObjectDirectory(
   cmGeneratorTarget* gt) const
 {
diff --git a/Source/cmGlobalXCodeGenerator.h b/Source/cmGlobalXCodeGenerator.h
index dbd5205..1aaf9c7 100644
--- a/Source/cmGlobalXCodeGenerator.h
+++ b/Source/cmGlobalXCodeGenerator.h
@@ -3,13 +3,25 @@
 #ifndef cmGlobalXCodeGenerator_h
 #define cmGlobalXCodeGenerator_h
 
-#include "cmGlobalGenerator.h"
+#include <cmConfigure.h>
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
 
-#include "cmCustomCommand.h"
+#include "cmGlobalGenerator.h"
 #include "cmXCodeObject.h"
+
+class cmCustomCommand;
+class cmGeneratorTarget;
 class cmGlobalGeneratorFactory;
+class cmLocalGenerator;
+class cmMakefile;
 class cmSourceFile;
 class cmSourceGroup;
+class cmake;
+struct cmDocumentationEntry;
 
 /** \class cmGlobalXCodeGenerator
  * \brief Write a Unix makefiles.
@@ -23,7 +35,7 @@ public:
   static cmGlobalGeneratorFactory* NewFactory();
 
   ///! Get the name for the generator.
-  virtual std::string GetName() const
+  std::string GetName() const CM_OVERRIDE
   {
     return cmGlobalXCodeGenerator::GetActualName();
   }
@@ -33,51 +45,55 @@ public:
   static void GetDocumentation(cmDocumentationEntry& entry);
 
   ///! Create a local generator appropriate to this Global Generator
-  virtual cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf);
+  cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) CM_OVERRIDE;
 
   /**
    * 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);
+  void EnableLanguage(std::vector<std::string> const& languages, cmMakefile*,
+                      bool optional) CM_OVERRIDE;
   /**
    * Try running cmake and building a file. This is used for dynalically
    * loaded commands, not as part of the usual build process.
    */
-  virtual void GenerateBuildCommand(
-    std::vector<std::string>& makeCommand, const std::string& makeProgram,
-    const std::string& projectName, const std::string& projectDir,
-    const std::string& targetName, const std::string& config, bool fast,
-    bool verbose,
-    std::vector<std::string> const& makeOptions = std::vector<std::string>());
+  void GenerateBuildCommand(std::vector<std::string>& makeCommand,
+                            const std::string& makeProgram,
+                            const std::string& projectName,
+                            const std::string& projectDir,
+                            const std::string& targetName,
+                            const std::string& config, bool fast, bool verbose,
+                            std::vector<std::string> const& makeOptions =
+                              std::vector<std::string>()) CM_OVERRIDE;
 
   /** Append the subdirectory for the given configuration.  */
-  virtual void AppendDirectoryForConfig(const std::string& prefix,
-                                        const std::string& config,
-                                        const std::string& suffix,
-                                        std::string& dir);
+  void AppendDirectoryForConfig(const std::string& prefix,
+                                const std::string& config,
+                                const std::string& suffix,
+                                std::string& dir) CM_OVERRIDE;
 
-  virtual void FindMakeProgram(cmMakefile*);
+  bool FindMakeProgram(cmMakefile*) CM_OVERRIDE;
 
   ///! What is the configurations directory variable called?
-  virtual const char* GetCMakeCFGIntDir() const;
+  const char* GetCMakeCFGIntDir() const CM_OVERRIDE;
   ///! expand CFGIntDir
-  virtual std::string ExpandCFGIntDir(const std::string& str,
-                                      const std::string& config) const;
+  std::string ExpandCFGIntDir(const std::string& str,
+                              const std::string& config) const CM_OVERRIDE;
 
   void SetCurrentLocalGenerator(cmLocalGenerator*);
 
   /** Return true if the generated build tree may contain multiple builds.
       i.e. "Can I build Debug and Release in the same tree?" */
-  virtual bool IsMultiConfig() const;
+  bool IsMultiConfig() const CM_OVERRIDE;
+
+  bool UseEffectivePlatformName(cmMakefile* mf) const CM_OVERRIDE;
 
-  virtual bool SetGeneratorToolset(std::string const& ts, cmMakefile* mf);
+  bool SetGeneratorToolset(std::string const& ts, cmMakefile* mf) CM_OVERRIDE;
   void AppendFlag(std::string& flags, std::string const& flag);
 
 protected:
-  virtual void AddExtraIDETargets();
-  virtual void Generate();
+  void AddExtraIDETargets() CM_OVERRIDE;
+  void Generate() CM_OVERRIDE;
 
 private:
   cmXCodeObject* CreateOrGetPBXGroup(cmGeneratorTarget* gtgt,
@@ -120,7 +136,7 @@ private:
   cmXCodeObject* CreateFlatClone(cmXCodeObject*);
   cmXCodeObject* CreateXCodeTarget(cmGeneratorTarget* gtgt,
                                    cmXCodeObject* buildPhases);
-  void ForceLinkerLanguages();
+  void ForceLinkerLanguages() CM_OVERRIDE;
   void ForceLinkerLanguage(cmGeneratorTarget* gtgt);
   const char* GetTargetLinkFlagsVar(const cmGeneratorTarget* target) const;
   const char* GetTargetFileType(cmGeneratorTarget* target);
@@ -192,11 +208,11 @@ private:
                      std::vector<std::string> const& defines,
                      bool dflag = false);
 
-  void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const;
+  void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const CM_OVERRIDE;
 
 protected:
-  virtual const char* GetInstallTargetName() const { return "install"; }
-  virtual const char* GetPackageTargetName() const { return "package"; }
+  const char* GetInstallTargetName() const CM_OVERRIDE { return "install"; }
+  const char* GetPackageTargetName() const CM_OVERRIDE { return "package"; }
 
   unsigned int XcodeVersion;
   std::string VersionString;
@@ -211,7 +227,7 @@ private:
   bool XcodeBuildCommandInitialized;
 
   void PrintCompilerAdvice(std::ostream&, std::string const&,
-                           const char*) const
+                           const char*) const CM_OVERRIDE
   {
   }
 
diff --git a/Source/cmGraphAdjacencyList.h b/Source/cmGraphAdjacencyList.h
index a154373..e6aec47 100644
--- a/Source/cmGraphAdjacencyList.h
+++ b/Source/cmGraphAdjacencyList.h
@@ -3,9 +3,9 @@
 #ifndef cmGraphAdjacencyList_h
 #define cmGraphAdjacencyList_h
 
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmStandardIncludes.h"
+#include <vector>
 
 /**
  * Graph edge representation.  Most use cases just need the
diff --git a/Source/cmGraphVizWriter.cxx b/Source/cmGraphVizWriter.cxx
index db11bd3..0f69aaa 100644
--- a/Source/cmGraphVizWriter.cxx
+++ b/Source/cmGraphVizWriter.cxx
@@ -2,21 +2,22 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmGraphVizWriter.h"
 
+#include <cmConfigure.h>
+#include <iostream>
+#include <sstream>
+#include <utility>
+
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
+#include "cmStateSnapshot.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
-#include <cmConfigure.h>
-#include <iostream>
-#include <sstream>
-#include <utility>
-
 static const char* getShapeForTarget(const cmGeneratorTarget* target)
 {
   if (!target) {
@@ -24,13 +25,13 @@ static const char* getShapeForTarget(const cmGeneratorTarget* target)
   }
 
   switch (target->GetType()) {
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       return "house";
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
       return "diamond";
-    case cmState::SHARED_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
       return "polygon";
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       return "octagon";
     default:
       break;
@@ -495,16 +496,16 @@ bool cmGraphVizWriter::IgnoreThisTarget(const std::string& name)
 }
 
 bool cmGraphVizWriter::GenerateForTargetType(
-  cmState::TargetType targetType) const
+  cmStateEnums::TargetType targetType) const
 {
   switch (targetType) {
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       return this->GenerateForExecutables;
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
       return this->GenerateForStaticLibs;
-    case cmState::SHARED_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
       return this->GenerateForSharedLibs;
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       return this->GenerateForModuleLibs;
     default:
       break;
diff --git a/Source/cmGraphVizWriter.h b/Source/cmGraphVizWriter.h
index 0efe2b7..1ff07ab 100644
--- a/Source/cmGraphVizWriter.h
+++ b/Source/cmGraphVizWriter.h
@@ -5,7 +5,7 @@
 
 #include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmState.h"
+#include "cmStateTypes.h"
 
 #include <cmsys/RegularExpression.hxx>
 #include <map>
@@ -60,7 +60,7 @@ protected:
 
   bool IgnoreThisTarget(const std::string& name);
 
-  bool GenerateForTargetType(cmState::TargetType targetType) const;
+  bool GenerateForTargetType(cmStateEnums::TargetType targetType) const;
 
   std::string GraphType;
   std::string GraphName;
diff --git a/Source/cmHexFileConverter.cxx b/Source/cmHexFileConverter.cxx
index e121ece..d9d6598 100644
--- a/Source/cmHexFileConverter.cxx
+++ b/Source/cmHexFileConverter.cxx
@@ -2,9 +2,12 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmHexFileConverter.h"
 
+#include <cmConfigure.h>
 #include <stdio.h>
 #include <string.h>
 
+#include "cmSystemTools.h"
+
 #define INTEL_HEX_MIN_LINE_LENGTH (1 + 8 + 2)
 #define INTEL_HEX_MAX_LINE_LENGTH (1 + 8 + (256 * 2) + 2)
 #define MOTOROLA_SREC_MIN_LINE_LENGTH (2 + 2 + 4 + 2)
@@ -204,7 +207,7 @@ bool cmHexFileConverter::TryConvert(const char* inFileName,
     } else if (type == IntelHex) {
       success = ConvertIntelHexLine(buf, outFile);
     }
-    if (success == false) {
+    if (!success) {
       break;
     }
   }
diff --git a/Source/cmHexFileConverter.h b/Source/cmHexFileConverter.h
index cb550bb..1050bc1 100644
--- a/Source/cmHexFileConverter.h
+++ b/Source/cmHexFileConverter.h
@@ -3,10 +3,6 @@
 #ifndef cmHexFileConverter_h
 #define cmHexFileConverter_h
 
-#include <cmConfigure.h>
-
-#include "cmStandardIncludes.h"
-
 /** \class cmHexFileConverter
  * \brief Can detects Intel Hex and Motorola S-record files and convert them
  *        to binary files.
diff --git a/Source/cmIDEOptions.cxx b/Source/cmIDEOptions.cxx
index 286076f..8d07776 100644
--- a/Source/cmIDEOptions.cxx
+++ b/Source/cmIDEOptions.cxx
@@ -2,9 +2,12 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmIDEOptions.h"
 
-#include "cmSystemTools.h"
-
 #include <cmsys/String.h>
+#include <iterator>
+#include <string.h>
+
+#include "cmIDEFlagTable.h"
+#include "cmSystemTools.h"
 
 cmIDEOptions::cmIDEOptions()
 {
@@ -145,6 +148,11 @@ void cmIDEOptions::AddDefines(const std::vector<std::string>& defines)
   this->Defines.insert(this->Defines.end(), defines.begin(), defines.end());
 }
 
+std::vector<std::string> const& cmIDEOptions::GetDefines() const
+{
+  return this->Defines;
+}
+
 void cmIDEOptions::AddFlag(const char* flag, const char* value)
 {
   this->FlagMap[flag] = value;
diff --git a/Source/cmIDEOptions.h b/Source/cmIDEOptions.h
index 1067c40..be2fd6d 100644
--- a/Source/cmIDEOptions.h
+++ b/Source/cmIDEOptions.h
@@ -5,9 +5,11 @@
 
 #include <cmConfigure.h>
 
-#include "cmStandardIncludes.h"
+#include <map>
+#include <string>
+#include <vector>
 
-#include "cmIDEFlagTable.h"
+struct cmIDEFlagTable;
 
 /** \class cmIDEOptions
  * \brief Superclass for IDE option processing
@@ -22,6 +24,8 @@ public:
   void AddDefine(const std::string& define);
   void AddDefines(const char* defines);
   void AddDefines(const std::vector<std::string>& defines);
+  std::vector<std::string> const& GetDefines() const;
+
   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);
diff --git a/Source/cmIfCommand.cxx b/Source/cmIfCommand.cxx
index a2dec55..a8fa4f9 100644
--- a/Source/cmIfCommand.cxx
+++ b/Source/cmIfCommand.cxx
@@ -2,14 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmIfCommand.h"
 
-#include "cmOutputConverter.h"
-#include "cmStringCommand.h"
-
 #include "cmConditionEvaluator.h"
-
-#include <cmsys/RegularExpression.hxx>
-#include <list>
-#include <stdlib.h> // required for atof
+#include "cmExecutionStatus.h"
+#include "cmExpandedCommandArgument.h"
+#include "cmMakefile.h"
+#include "cmOutputConverter.h"
+#include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
 
 static std::string cmIfCommandError(
   std::vector<cmExpandedCommandArgument> const& args)
diff --git a/Source/cmIfCommand.h b/Source/cmIfCommand.h
index f449023..56eef30 100644
--- a/Source/cmIfCommand.h
+++ b/Source/cmIfCommand.h
@@ -3,9 +3,17 @@
 #ifndef cmIfCommand_h
 #define cmIfCommand_h
 
-#include "cmCommand.h"
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
 
+#include "cmCommand.h"
 #include "cmFunctionBlocker.h"
+#include "cmListFileCache.h"
+
+class cmExecutionStatus;
+class cmExpandedCommandArgument;
+class cmMakefile;
 
 class cmIfFunctionBlocker : public cmFunctionBlocker
 {
@@ -66,8 +74,6 @@ public:
   // Filter the given variable definition based on policy CMP0054.
   static const char* GetDefinitionIfUnquoted(
     const cmMakefile* mf, cmExpandedCommandArgument const& argument);
-
-  cmTypeMacro(cmIfCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmIncludeCommand.cxx b/Source/cmIncludeCommand.cxx
index acf51a7..12e0c9a 100644
--- a/Source/cmIncludeCommand.cxx
+++ b/Source/cmIncludeCommand.cxx
@@ -2,6 +2,16 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmIncludeCommand.h"
 
+#include <sstream>
+
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
+
 // cmIncludeCommand
 bool cmIncludeCommand::InitialPass(std::vector<std::string> const& args,
                                    cmExecutionStatus&)
@@ -59,7 +69,7 @@ bool cmIncludeCommand::InitialPass(std::vector<std::string> const& args,
     module += ".cmake";
     std::string mfile = this->Makefile->GetModulesFile(module.c_str());
     if (!mfile.empty()) {
-      fname = mfile.c_str();
+      fname = mfile;
     }
   }
 
@@ -101,7 +111,7 @@ bool cmIncludeCommand::InitialPass(std::vector<std::string> const& args,
   }
 
   std::string listFile = cmSystemTools::CollapseFullPath(
-    fname.c_str(), this->Makefile->GetCurrentSourceDirectory());
+    fname, this->Makefile->GetCurrentSourceDirectory());
   if (optional && !cmSystemTools::FileExists(listFile.c_str())) {
     if (!resultVarName.empty()) {
       this->Makefile->AddDefinition(resultVarName, "NOTFOUND");
diff --git a/Source/cmIncludeCommand.h b/Source/cmIncludeCommand.h
index 7ff7b9d..78edd43 100644
--- a/Source/cmIncludeCommand.h
+++ b/Source/cmIncludeCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmIncludeCommand_h
 #define cmIncludeCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmIncludeCommand
  * \brief cmIncludeCommand defines a list of distant
  *  files that can be "included" in the current list file.
@@ -35,8 +41,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "include"; }
-
-  cmTypeMacro(cmIncludeCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmIncludeDirectoryCommand.cxx b/Source/cmIncludeDirectoryCommand.cxx
index f37f1ca..cdb0279 100644
--- a/Source/cmIncludeDirectoryCommand.cxx
+++ b/Source/cmIncludeDirectoryCommand.cxx
@@ -2,6 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmIncludeDirectoryCommand.h"
 
+#include <algorithm>
+#include <set>
+
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmIncludeDirectoryCommand
 bool cmIncludeDirectoryCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
diff --git a/Source/cmIncludeDirectoryCommand.h b/Source/cmIncludeDirectoryCommand.h
index 46e433a..287b5d3 100644
--- a/Source/cmIncludeDirectoryCommand.h
+++ b/Source/cmIncludeDirectoryCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmIncludeDirectoryCommand_h
 #define cmIncludeDirectoryCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmIncludeDirectoryCommand
  * \brief Add include directories to the build.
  *
@@ -31,8 +37,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "include_directories"; }
 
-  cmTypeMacro(cmIncludeDirectoryCommand, cmCommand);
-
 protected:
   // used internally
   void GetIncludes(const std::string& arg, std::vector<std::string>& incs);
diff --git a/Source/cmIncludeExternalMSProjectCommand.cxx b/Source/cmIncludeExternalMSProjectCommand.cxx
index 166bc7c..03388c7 100644
--- a/Source/cmIncludeExternalMSProjectCommand.cxx
+++ b/Source/cmIncludeExternalMSProjectCommand.cxx
@@ -2,6 +2,15 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmIncludeExternalMSProjectCommand.h"
 
+#ifdef _WIN32
+#include "cmMakefile.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#endif
+
+class cmExecutionStatus;
+
 // cmIncludeExternalMSProjectCommand
 bool cmIncludeExternalMSProjectCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
@@ -66,12 +75,12 @@ bool cmIncludeExternalMSProjectCommand::InitialPass(
       std::string guidVariable = utility_name + "_GUID_CMAKE";
       this->Makefile->GetCMakeInstance()->AddCacheEntry(
         guidVariable.c_str(), customGuid.c_str(), "Stored GUID",
-        cmState::INTERNAL);
+        cmStateEnums::INTERNAL);
     }
 
     // Create a target instance for this utility.
-    cmTarget* target =
-      this->Makefile->AddNewTarget(cmState::UTILITY, utility_name.c_str());
+    cmTarget* target = this->Makefile->AddNewTarget(cmStateEnums::UTILITY,
+                                                    utility_name.c_str());
 
     target->SetProperty("GENERATOR_FILE_NAME", utility_name.c_str());
     target->SetProperty("EXTERNAL_MSPROJECT", path.c_str());
diff --git a/Source/cmIncludeExternalMSProjectCommand.h b/Source/cmIncludeExternalMSProjectCommand.h
index 9401016..9fcf467 100644
--- a/Source/cmIncludeExternalMSProjectCommand.h
+++ b/Source/cmIncludeExternalMSProjectCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmIncludeExternalMSProjectCommand_h
 #define cmIncludeExternalMSProjectCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmIncludeExternalMSProjectCommand
  * \brief Specify an external MS project file for inclusion in the workspace.
  *
@@ -37,8 +43,6 @@ public:
   {
     return "include_external_msproject";
   }
-
-  cmTypeMacro(cmIncludeExternalMSProjectCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmIncludeRegularExpressionCommand.cxx b/Source/cmIncludeRegularExpressionCommand.cxx
index 6dc20a0..073c95f 100644
--- a/Source/cmIncludeRegularExpressionCommand.cxx
+++ b/Source/cmIncludeRegularExpressionCommand.cxx
@@ -2,6 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmIncludeRegularExpressionCommand.h"
 
+#include "cmMakefile.h"
+
+class cmExecutionStatus;
+
 // cmIncludeRegularExpressionCommand
 bool cmIncludeRegularExpressionCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
diff --git a/Source/cmIncludeRegularExpressionCommand.h b/Source/cmIncludeRegularExpressionCommand.h
index 648bce2..c68d9f2 100644
--- a/Source/cmIncludeRegularExpressionCommand.h
+++ b/Source/cmIncludeRegularExpressionCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmIncludeRegularExpressionCommand_h
 #define cmIncludeRegularExpressionCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmIncludeRegularExpressionCommand
  * \brief Set the regular expression for following #includes.
  *
@@ -36,8 +42,6 @@ public:
   {
     return "include_regular_expression";
   }
-
-  cmTypeMacro(cmIncludeRegularExpressionCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmInstallCommand.cxx b/Source/cmInstallCommand.cxx
index f040a4e..4c331c7 100644
--- a/Source/cmInstallCommand.cxx
+++ b/Source/cmInstallCommand.cxx
@@ -2,16 +2,32 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallCommand.h"
 
+#include <cmsys/Glob.hxx>
+#include <sstream>
+#include <stddef.h>
+
+#include "cmAlgorithms.h"
+#include "cmCommandArgumentsHelper.h"
 #include "cmExportSet.h"
+#include "cmExportSetMap.h"
+#include "cmGeneratorExpression.h"
+#include "cmGlobalGenerator.h"
 #include "cmInstallCommandArguments.h"
 #include "cmInstallDirectoryGenerator.h"
 #include "cmInstallExportGenerator.h"
 #include "cmInstallFilesGenerator.h"
+#include "cmInstallGenerator.h"
 #include "cmInstallScriptGenerator.h"
 #include "cmInstallTargetGenerator.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
 #include "cmTargetExport.h"
+#include "cmake.h"
 
-#include <cmsys/Glob.hxx>
+class cmExecutionStatus;
 
 static cmInstallTargetGenerator* CreateInstallTargetGenerator(
   cmTarget& target, const cmInstallCommandArguments& args, bool impLib,
@@ -327,19 +343,19 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
     if (cmTarget* target =
           this->Makefile->FindLocalNonAliasTarget(*targetIt)) {
       // Found the target.  Check its type.
-      if (target->GetType() != cmState::EXECUTABLE &&
-          target->GetType() != cmState::STATIC_LIBRARY &&
-          target->GetType() != cmState::SHARED_LIBRARY &&
-          target->GetType() != cmState::MODULE_LIBRARY &&
-          target->GetType() != cmState::OBJECT_LIBRARY &&
-          target->GetType() != cmState::INTERFACE_LIBRARY) {
+      if (target->GetType() != cmStateEnums::EXECUTABLE &&
+          target->GetType() != cmStateEnums::STATIC_LIBRARY &&
+          target->GetType() != cmStateEnums::SHARED_LIBRARY &&
+          target->GetType() != cmStateEnums::MODULE_LIBRARY &&
+          target->GetType() != cmStateEnums::OBJECT_LIBRARY &&
+          target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
         std::ostringstream e;
         e << "TARGETS given target \"" << (*targetIt)
           << "\" which is not an executable, library, or module.";
         this->SetError(e.str());
         return false;
       }
-      if (target->GetType() == cmState::OBJECT_LIBRARY) {
+      if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
         std::ostringstream e;
         e << "TARGETS given OBJECT library \"" << (*targetIt)
           << "\" which may not be installed.";
@@ -387,7 +403,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
     bool namelinkOnly = false;
 
     switch (target.GetType()) {
-      case cmState::SHARED_LIBRARY: {
+      case cmStateEnums::SHARED_LIBRARY: {
         // Shared libraries are handled differently on DLL and non-DLL
         // platforms.  All windows platforms are DLL platforms including
         // cygwin.  Currently no other platform is a DLL platform.
@@ -454,21 +470,43 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
           }
         }
       } break;
-      case cmState::STATIC_LIBRARY: {
-        // Static libraries use ARCHIVE properties.
-        if (!archiveArgs.GetDestination().empty()) {
-          archiveGenerator =
-            CreateInstallTargetGenerator(target, archiveArgs, false);
+      case cmStateEnums::STATIC_LIBRARY: {
+        // If it is marked with FRAMEWORK property use the FRAMEWORK set of
+        // INSTALL properties. Otherwise, use the LIBRARY properties.
+        if (target.IsFrameworkOnApple()) {
+          // When in namelink only mode skip frameworks.
+          if (namelinkMode == cmInstallTargetGenerator::NamelinkModeOnly) {
+            continue;
+          }
+
+          // Use the FRAMEWORK properties.
+          if (!frameworkArgs.GetDestination().empty()) {
+            frameworkGenerator =
+              CreateInstallTargetGenerator(target, frameworkArgs, false);
+          } else {
+            std::ostringstream e;
+            e << "TARGETS given no FRAMEWORK DESTINATION for static library "
+                 "FRAMEWORK target \""
+              << target.GetName() << "\".";
+            this->SetError(e.str());
+            return false;
+          }
         } else {
-          std::ostringstream e;
-          e << "TARGETS given no ARCHIVE DESTINATION for static library "
-               "target \""
-            << target.GetName() << "\".";
-          this->SetError(e.str());
-          return false;
+          // Static libraries use ARCHIVE properties.
+          if (!archiveArgs.GetDestination().empty()) {
+            archiveGenerator =
+              CreateInstallTargetGenerator(target, archiveArgs, false);
+          } else {
+            std::ostringstream e;
+            e << "TARGETS given no ARCHIVE DESTINATION for static library "
+                 "target \""
+              << target.GetName() << "\".";
+            this->SetError(e.str());
+            return false;
+          }
         }
       } break;
-      case cmState::MODULE_LIBRARY: {
+      case cmStateEnums::MODULE_LIBRARY: {
         // Modules use LIBRARY properties.
         if (!libraryArgs.GetDestination().empty()) {
           libraryGenerator =
@@ -484,7 +522,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
           return false;
         }
       } break;
-      case cmState::EXECUTABLE: {
+      case cmStateEnums::EXECUTABLE: {
         if (target.IsAppBundleOnApple()) {
           // Application bundles use the BUNDLE properties.
           if (!bundleArgs.GetDestination().empty()) {
@@ -534,7 +572,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
             CreateInstallTargetGenerator(target, archiveArgs, true, true);
         }
       } break;
-      case cmState::INTERFACE_LIBRARY:
+      case cmStateEnums::INTERFACE_LIBRARY:
         // Nothing to do. An INTERFACE_LIBRARY can be installed, but the
         // only effect of that is to make it exportable. It installs no
         // other files itself.
@@ -553,7 +591,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
     bool createInstallGeneratorsForTargetFileSets = true;
 
     if (target.IsFrameworkOnApple() ||
-        target.GetType() == cmState::INTERFACE_LIBRARY) {
+        target.GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       createInstallGeneratorsForTargetFileSets = false;
     }
 
@@ -969,7 +1007,7 @@ bool cmInstallCommand::HandleDirectoryMode(
         std::ostringstream e;
         e << args[0] << " does not allow \"" << args[i]
           << "\" after PATTERN or REGEX.";
-        this->SetError(e.str().c_str());
+        this->SetError(e.str());
         return false;
       }
       exclude_from_all = true;
diff --git a/Source/cmInstallCommand.h b/Source/cmInstallCommand.h
index 6f785ae..187a6ce 100644
--- a/Source/cmInstallCommand.h
+++ b/Source/cmInstallCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmInstallCommand_h
 #define cmInstallCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmInstallCommand
  * \brief Specifies where to install some files
  *
@@ -31,8 +37,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "install"; }
 
-  cmTypeMacro(cmInstallCommand, cmCommand);
-
 private:
   bool HandleScriptMode(std::vector<std::string> const& args);
   bool HandleTargetsMode(std::vector<std::string> const& args);
diff --git a/Source/cmInstallCommandArguments.cxx b/Source/cmInstallCommandArguments.cxx
index de6919b..6b15468 100644
--- a/Source/cmInstallCommandArguments.cxx
+++ b/Source/cmInstallCommandArguments.cxx
@@ -2,6 +2,8 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallCommandArguments.h"
 
+#include <cmConfigure.h>
+
 #include "cmSystemTools.h"
 
 // Table of valid permissions.
diff --git a/Source/cmInstallCommandArguments.h b/Source/cmInstallCommandArguments.h
index 82c2310..c1523b2 100644
--- a/Source/cmInstallCommandArguments.h
+++ b/Source/cmInstallCommandArguments.h
@@ -3,9 +3,10 @@
 #ifndef cmInstallCommandArguments_h
 #define cmInstallCommandArguments_h
 
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmStandardIncludes.h"
+#include <string>
+#include <vector>
 
 #include "cmCommandArgumentsHelper.h"
 
diff --git a/Source/cmInstallFilesCommand.cxx b/Source/cmInstallFilesCommand.cxx
index f072ff5..86fd46d 100644
--- a/Source/cmInstallFilesCommand.cxx
+++ b/Source/cmInstallFilesCommand.cxx
@@ -2,7 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallFilesCommand.h"
 
+#include "cmGeneratorExpression.h"
+#include "cmGlobalGenerator.h"
 #include "cmInstallFilesGenerator.h"
+#include "cmInstallGenerator.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
 
 // cmExecutableCommand
 bool cmInstallFilesCommand::InitialPass(std::vector<std::string> const& args,
diff --git a/Source/cmInstallFilesCommand.h b/Source/cmInstallFilesCommand.h
index a80184a..c3e2919 100644
--- a/Source/cmInstallFilesCommand.h
+++ b/Source/cmInstallFilesCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmInstallFilesCommand_h
 #define cmInstallFilesCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmInstallFilesCommand
  * \brief Specifies where to install some files
  *
@@ -40,8 +46,6 @@ public:
   void FinalPass() CM_OVERRIDE;
   bool HasFinalPass() const CM_OVERRIDE { return !this->IsFilesForm; }
 
-  cmTypeMacro(cmInstallFilesCommand, cmCommand);
-
 protected:
   void CreateInstallGenerator() const;
   std::string FindInstallSource(const char* name) const;
diff --git a/Source/cmInstallProgramsCommand.cxx b/Source/cmInstallProgramsCommand.cxx
index bb2b61f..5ee81fb 100644
--- a/Source/cmInstallProgramsCommand.cxx
+++ b/Source/cmInstallProgramsCommand.cxx
@@ -2,7 +2,15 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallProgramsCommand.h"
 
+#include "cmGeneratorExpression.h"
+#include "cmGlobalGenerator.h"
 #include "cmInstallFilesGenerator.h"
+#include "cmInstallGenerator.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmExecutableCommand
 bool cmInstallProgramsCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
diff --git a/Source/cmInstallProgramsCommand.h b/Source/cmInstallProgramsCommand.h
index cb85cce..ca07a2f 100644
--- a/Source/cmInstallProgramsCommand.h
+++ b/Source/cmInstallProgramsCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmInstallProgramsCommand_h
 #define cmInstallProgramsCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmInstallProgramsCommand
  * \brief Specifies where to install some programs
  *
@@ -41,8 +47,6 @@ public:
 
   bool HasFinalPass() const CM_OVERRIDE { return true; }
 
-  cmTypeMacro(cmInstallProgramsCommand, cmCommand);
-
 protected:
   std::string FindInstallSource(const char* name) const;
 
diff --git a/Source/cmInstallTargetGenerator.cxx b/Source/cmInstallTargetGenerator.cxx
index 70ae204..88fcc56 100644
--- a/Source/cmInstallTargetGenerator.cxx
+++ b/Source/cmInstallTargetGenerator.cxx
@@ -2,6 +2,12 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallTargetGenerator.h"
 
+#include <assert.h>
+#include <map>
+#include <set>
+#include <sstream>
+#include <utility>
+
 #include "cmComputeLinkInformation.h"
 #include "cmGeneratorExpression.h"
 #include "cmGeneratorTarget.h"
@@ -9,18 +15,11 @@
 #include "cmInstallType.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
-#include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
-#include <assert.h>
-#include <map>
-#include <set>
-#include <sstream>
-#include <utility>
-
 cmInstallTargetGenerator::cmInstallTargetGenerator(
   const std::string& targetName, const char* dest, bool implib,
   const char* file_permissions, std::vector<std::string> const& configurations,
@@ -80,36 +79,37 @@ void cmInstallTargetGenerator::GenerateScriptForConfig(
   std::vector<std::string> filesFrom;
   std::vector<std::string> filesTo;
   std::string literal_args;
-  cmState::TargetType targetType = this->Target->GetType();
+  cmStateEnums::TargetType targetType = this->Target->GetType();
   cmInstallType type = cmInstallType();
   switch (targetType) {
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       type = cmInstallType_EXECUTABLE;
       break;
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
       type = cmInstallType_STATIC_LIBRARY;
       break;
-    case cmState::SHARED_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
       type = cmInstallType_SHARED_LIBRARY;
       break;
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       type = cmInstallType_MODULE_LIBRARY;
       break;
-    case cmState::INTERFACE_LIBRARY:
+    case cmStateEnums::INTERFACE_LIBRARY:
       // Not reachable. We never create a cmInstallTargetGenerator for
       // an INTERFACE_LIBRARY.
-      assert(0 && "INTERFACE_LIBRARY targets have no installable outputs.");
+      assert(false &&
+             "INTERFACE_LIBRARY targets have no installable outputs.");
       break;
-    case cmState::OBJECT_LIBRARY:
-    case cmState::UTILITY:
-    case cmState::GLOBAL_TARGET:
-    case cmState::UNKNOWN_LIBRARY:
+    case cmStateEnums::OBJECT_LIBRARY:
+    case cmStateEnums::UTILITY:
+    case cmStateEnums::GLOBAL_TARGET:
+    case cmStateEnums::UNKNOWN_LIBRARY:
       this->Target->GetLocalGenerator()->IssueMessage(
         cmake::INTERNAL_ERROR,
         "cmInstallTargetGenerator created with non-installable target.");
       return;
   }
-  if (targetType == cmState::EXECUTABLE) {
+  if (targetType == cmStateEnums::EXECUTABLE) {
     // There is a bug in cmInstallCommand if this fails.
     assert(this->NamelinkMode == NamelinkModeNone);
 
@@ -337,7 +337,7 @@ std::string cmInstallTargetGenerator::GetInstallFilename(
 {
   std::string fname;
   // Compute the name of the library.
-  if (target->GetType() == cmState::EXECUTABLE) {
+  if (target->GetType() == cmStateEnums::EXECUTABLE) {
     std::string targetName;
     std::string targetNameReal;
     std::string targetNameImport;
@@ -471,9 +471,9 @@ void cmInstallTargetGenerator::AddInstallNamePatchRule(
   std::string const& toDestDirPath)
 {
   if (this->ImportLibrary ||
-      !(this->Target->GetType() == cmState::SHARED_LIBRARY ||
-        this->Target->GetType() == cmState::MODULE_LIBRARY ||
-        this->Target->GetType() == cmState::EXECUTABLE)) {
+      !(this->Target->GetType() == cmStateEnums::SHARED_LIBRARY ||
+        this->Target->GetType() == cmStateEnums::MODULE_LIBRARY ||
+        this->Target->GetType() == cmStateEnums::EXECUTABLE)) {
     return;
   }
 
@@ -527,7 +527,7 @@ void cmInstallTargetGenerator::AddInstallNamePatchRule(
 
   // Edit the install_name of the target itself if necessary.
   std::string new_id;
-  if (this->Target->GetType() == cmState::SHARED_LIBRARY) {
+  if (this->Target->GetType() == cmStateEnums::SHARED_LIBRARY) {
     std::string for_build =
       this->Target->GetInstallNameDirForBuildTree(config);
     std::string for_install = this->Target->GetInstallNameDirForInstallTree();
@@ -704,7 +704,7 @@ void cmInstallTargetGenerator::AddStripRule(std::ostream& os,
 
   // don't strip static and import libraries, because it removes the only
   // symbol table they have so you can't link to them anymore
-  if (this->Target->GetType() == cmState::STATIC_LIBRARY ||
+  if (this->Target->GetType() == cmStateEnums::STATIC_LIBRARY ||
       this->ImportLibrary) {
     return;
   }
@@ -731,7 +731,7 @@ void cmInstallTargetGenerator::AddRanlibRule(std::ostream& os,
                                              const std::string& toDestDirPath)
 {
   // Static libraries need ranlib on this platform.
-  if (this->Target->GetType() != cmState::STATIC_LIBRARY) {
+  if (this->Target->GetType() != cmStateEnums::STATIC_LIBRARY) {
     return;
   }
 
@@ -767,10 +767,10 @@ void cmInstallTargetGenerator::AddUniversalInstallRule(
   }
 
   switch (this->Target->GetType()) {
-    case cmState::EXECUTABLE:
-    case cmState::STATIC_LIBRARY:
-    case cmState::SHARED_LIBRARY:
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::EXECUTABLE:
+    case cmStateEnums::STATIC_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       break;
 
     default:
diff --git a/Source/cmInstallTargetsCommand.cxx b/Source/cmInstallTargetsCommand.cxx
index fca0bf1..e00eba0 100644
--- a/Source/cmInstallTargetsCommand.cxx
+++ b/Source/cmInstallTargetsCommand.cxx
@@ -2,6 +2,15 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmInstallTargetsCommand.h"
 
+#include <utility>
+
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmTarget.h"
+#include "cm_unordered_map.hxx"
+
+class cmExecutionStatus;
+
 // cmExecutableCommand
 bool cmInstallTargetsCommand::InitialPass(std::vector<std::string> const& args,
                                           cmExecutionStatus&)
diff --git a/Source/cmInstallTargetsCommand.h b/Source/cmInstallTargetsCommand.h
index 2ddeaf0..150397d 100644
--- a/Source/cmInstallTargetsCommand.h
+++ b/Source/cmInstallTargetsCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmInstallTargetsCommand_h
 #define cmInstallTargetsCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmInstallTargetsCommand
  * \brief Specifies where to install some targets
  *
@@ -31,8 +37,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "install_targets"; }
-
-  cmTypeMacro(cmInstallTargetsCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmLinkDirectoriesCommand.cxx b/Source/cmLinkDirectoriesCommand.cxx
index fc6bf29..f863292 100644
--- a/Source/cmLinkDirectoriesCommand.cxx
+++ b/Source/cmLinkDirectoriesCommand.cxx
@@ -2,6 +2,15 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLinkDirectoriesCommand.h"
 
+#include <sstream>
+
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
+
 // cmLinkDirectoriesCommand
 bool cmLinkDirectoriesCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
diff --git a/Source/cmLinkDirectoriesCommand.h b/Source/cmLinkDirectoriesCommand.h
index cd6d2de..387b3b9 100644
--- a/Source/cmLinkDirectoriesCommand.h
+++ b/Source/cmLinkDirectoriesCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmLinkDirectoriesCommand_h
 #define cmLinkDirectoriesCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmLinkDirectoriesCommand
  * \brief Define a list of directories containing files to link.
  *
@@ -33,8 +39,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "link_directories"; }
 
-  cmTypeMacro(cmLinkDirectoriesCommand, cmCommand);
-
 private:
   void AddLinkDir(std::string const& dir);
 };
diff --git a/Source/cmLinkItem.h b/Source/cmLinkItem.h
index 74d6774..6fd6f50 100644
--- a/Source/cmLinkItem.h
+++ b/Source/cmLinkItem.h
@@ -3,8 +3,16 @@
 #ifndef cmLinkItem_h
 #define cmLinkItem_h
 
+#include <cmConfigure.h>
+
+#include <algorithm>
+#include <map>
+#include <string>
+#include <vector>
+
 #include "cmListFileCache.h"
 #include "cmSystemTools.h"
+#include "cmTargetLinkLibraryType.h"
 
 class cmGeneratorTarget;
 
diff --git a/Source/cmLinkLibrariesCommand.cxx b/Source/cmLinkLibrariesCommand.cxx
index bb0e27b..708ec8c 100644
--- a/Source/cmLinkLibrariesCommand.cxx
+++ b/Source/cmLinkLibrariesCommand.cxx
@@ -2,6 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLinkLibrariesCommand.h"
 
+#include "cmMakefile.h"
+
+class cmExecutionStatus;
+
 // cmLinkLibrariesCommand
 bool cmLinkLibrariesCommand::InitialPass(std::vector<std::string> const& args,
                                          cmExecutionStatus&)
@@ -20,7 +24,7 @@ bool cmLinkLibrariesCommand::InitialPass(std::vector<std::string> const& args,
                        "a library");
         return false;
       }
-      this->Makefile->AddLinkLibrary(*i, DEBUG_LibraryType);
+      this->Makefile->AppendProperty("LINK_LIBRARIES", "debug");
     } else if (*i == "optimized") {
       ++i;
       if (i == args.end()) {
@@ -28,10 +32,9 @@ bool cmLinkLibrariesCommand::InitialPass(std::vector<std::string> const& args,
                        "a library");
         return false;
       }
-      this->Makefile->AddLinkLibrary(*i, OPTIMIZED_LibraryType);
-    } else {
-      this->Makefile->AddLinkLibrary(*i);
+      this->Makefile->AppendProperty("LINK_LIBRARIES", "optimized");
     }
+    this->Makefile->AppendProperty("LINK_LIBRARIES", i->c_str());
   }
 
   return true;
diff --git a/Source/cmLinkLibrariesCommand.h b/Source/cmLinkLibrariesCommand.h
index b4943b6..66d7ec4 100644
--- a/Source/cmLinkLibrariesCommand.h
+++ b/Source/cmLinkLibrariesCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmLinkLibrariesCommand_h
 #define cmLinkLibrariesCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmLinkLibrariesCommand
  * \brief Specify a list of libraries to link into executables.
  *
@@ -31,8 +37,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "link_libraries"; }
-
-  cmTypeMacro(cmLinkLibrariesCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmLinkLineComputer.cxx b/Source/cmLinkLineComputer.cxx
new file mode 100644
index 0000000..e728632
--- /dev/null
+++ b/Source/cmLinkLineComputer.cxx
@@ -0,0 +1,192 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#include "cmLinkLineComputer.h"
+
+#include <sstream>
+#include <vector>
+
+#include "cmComputeLinkInformation.h"
+#include "cmGeneratorTarget.h"
+#include "cmOutputConverter.h"
+#include "cmStateDirectory.h"
+#include "cmStateTypes.h"
+
+cmLinkLineComputer::cmLinkLineComputer(cmOutputConverter* outputConverter,
+                                       cmStateDirectory stateDir)
+  : StateDir(stateDir)
+  , OutputConverter(outputConverter)
+  , ForResponse(false)
+  , UseWatcomQuote(false)
+  , Relink(false)
+{
+}
+
+cmLinkLineComputer::~cmLinkLineComputer()
+{
+}
+
+void cmLinkLineComputer::SetUseWatcomQuote(bool useWatcomQuote)
+{
+  this->UseWatcomQuote = useWatcomQuote;
+}
+
+void cmLinkLineComputer::SetForResponse(bool forResponse)
+{
+  this->ForResponse = forResponse;
+}
+
+void cmLinkLineComputer::SetRelink(bool relink)
+{
+  this->Relink = relink;
+}
+
+std::string cmLinkLineComputer::ConvertToLinkReference(
+  std::string const& lib) const
+{
+  std::string relLib = lib;
+
+  if (cmOutputConverter::ContainedInDirectory(
+        this->StateDir.GetCurrentBinary(), lib, this->StateDir)) {
+    relLib = cmOutputConverter::ForceToRelativePath(
+      this->StateDir.GetCurrentBinary(), lib);
+  }
+  return relLib;
+}
+
+std::string cmLinkLineComputer::ComputeLinkLibs(cmComputeLinkInformation& cli)
+{
+  std::string linkLibs;
+  typedef cmComputeLinkInformation::ItemVector ItemVector;
+  ItemVector const& items = cli.GetItems();
+  for (ItemVector::const_iterator li = items.begin(); li != items.end();
+       ++li) {
+    if (li->Target &&
+        li->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
+      continue;
+    }
+    if (li->IsPath) {
+      linkLibs +=
+        this->ConvertToOutputFormat(this->ConvertToLinkReference(li->Value));
+    } else {
+      linkLibs += li->Value;
+    }
+    linkLibs += " ";
+  }
+  return linkLibs;
+}
+
+std::string cmLinkLineComputer::ConvertToOutputFormat(std::string const& input)
+{
+  cmOutputConverter::OutputFormat shellFormat = (this->ForResponse)
+    ? cmOutputConverter::RESPONSE
+    : ((this->UseWatcomQuote) ? cmOutputConverter::WATCOMQUOTE
+                              : cmOutputConverter::SHELL);
+
+  return this->OutputConverter->ConvertToOutputFormat(input, shellFormat);
+}
+
+std::string cmLinkLineComputer::ConvertToOutputForExisting(
+  std::string const& input)
+{
+  cmOutputConverter::OutputFormat shellFormat = (this->ForResponse)
+    ? cmOutputConverter::RESPONSE
+    : ((this->UseWatcomQuote) ? cmOutputConverter::WATCOMQUOTE
+                              : cmOutputConverter::SHELL);
+
+  return this->OutputConverter->ConvertToOutputForExisting(input, shellFormat);
+}
+
+std::string cmLinkLineComputer::ComputeLinkPath(
+  cmComputeLinkInformation& cli, std::string const& libPathFlag,
+  std::string const& libPathTerminator)
+{
+  std::string linkPath;
+  std::vector<std::string> const& libDirs = cli.GetDirectories();
+  for (std::vector<std::string>::const_iterator libDir = libDirs.begin();
+       libDir != libDirs.end(); ++libDir) {
+    std::string libpath = this->ConvertToOutputForExisting(*libDir);
+    linkPath += " " + libPathFlag;
+    linkPath += libpath;
+    linkPath += libPathTerminator;
+    linkPath += " ";
+  }
+  return linkPath;
+}
+
+std::string cmLinkLineComputer::ComputeRPath(cmComputeLinkInformation& cli)
+{
+  std::string rpath;
+  // Check what kind of rpath flags to use.
+  if (cli.GetRuntimeSep().empty()) {
+    // Each rpath entry gets its own option ("-R a -R b -R c")
+    std::vector<std::string> runtimeDirs;
+    cli.GetRPath(runtimeDirs, this->Relink);
+
+    for (std::vector<std::string>::iterator ri = runtimeDirs.begin();
+         ri != runtimeDirs.end(); ++ri) {
+      rpath += cli.GetRuntimeFlag();
+      rpath += this->ConvertToOutputFormat(*ri);
+      rpath += " ";
+    }
+  } else {
+    // All rpath entries are combined ("-Wl,-rpath,a:b:c").
+    std::string rpathString = cli.GetRPathString(this->Relink);
+
+    // Store the rpath option in the stream.
+    if (!rpathString.empty()) {
+      rpath += cli.GetRuntimeFlag();
+      rpath +=
+        this->OutputConverter->EscapeForShell(rpathString, !this->ForResponse);
+      rpath += " ";
+    }
+  }
+  return rpath;
+}
+
+std::string cmLinkLineComputer::ComputeFrameworkPath(
+  cmComputeLinkInformation& cli, std::string const& fwSearchFlag)
+{
+  std::string frameworkPath;
+  if (!fwSearchFlag.empty()) {
+    std::vector<std::string> const& fwDirs = cli.GetFrameworkPaths();
+    for (std::vector<std::string>::const_iterator fdi = fwDirs.begin();
+         fdi != fwDirs.end(); ++fdi) {
+      frameworkPath += fwSearchFlag;
+      frameworkPath += this->ConvertToOutputFormat(*fdi);
+      frameworkPath += " ";
+    }
+  }
+  return frameworkPath;
+}
+
+std::string cmLinkLineComputer::ComputeLinkLibraries(
+  cmComputeLinkInformation& cli, std::string const& stdLibString)
+{
+  std::ostringstream fout;
+  fout << this->ComputeRPath(cli);
+
+  // Write the library flags to the build rule.
+  fout << this->ComputeLinkLibs(cli);
+
+  // Add the linker runtime search path if any.
+  std::string rpath_link = cli.GetRPathLinkString();
+  if (!cli.GetRPathLinkFlag().empty() && !rpath_link.empty()) {
+    fout << cli.GetRPathLinkFlag();
+    fout << this->OutputConverter->EscapeForShell(rpath_link,
+                                                  !this->ForResponse);
+    fout << " ";
+  }
+
+  if (!stdLibString.empty()) {
+    fout << stdLibString << " ";
+  }
+
+  return fout.str();
+}
+
+std::string cmLinkLineComputer::GetLinkerLanguage(cmGeneratorTarget* target,
+                                                  std::string const& config)
+{
+  return target->GetLinkerLanguage(config);
+}
diff --git a/Source/cmLinkLineComputer.h b/Source/cmLinkLineComputer.h
new file mode 100644
index 0000000..57a70bc
--- /dev/null
+++ b/Source/cmLinkLineComputer.h
@@ -0,0 +1,58 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#ifndef cmLinkLineComputer_h
+#define cmLinkLineComputer_h
+
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+
+#include "cmStateDirectory.h"
+
+class cmComputeLinkInformation;
+class cmGeneratorTarget;
+class cmOutputConverter;
+
+class cmLinkLineComputer
+{
+public:
+  cmLinkLineComputer(cmOutputConverter* outputConverter,
+                     cmStateDirectory stateDir);
+  virtual ~cmLinkLineComputer();
+
+  void SetUseWatcomQuote(bool useWatcomQuote);
+  void SetForResponse(bool forResponse);
+  void SetRelink(bool relink);
+
+  virtual std::string ConvertToLinkReference(std::string const& input) const;
+
+  std::string ComputeLinkPath(cmComputeLinkInformation& cli,
+                              std::string const& libPathFlag,
+                              std::string const& libPathTerminator);
+
+  std::string ComputeFrameworkPath(cmComputeLinkInformation& cli,
+                                   std::string const& fwSearchFlag);
+
+  virtual std::string ComputeLinkLibraries(cmComputeLinkInformation& cli,
+                                           std::string const& stdLibString);
+
+  virtual std::string GetLinkerLanguage(cmGeneratorTarget* target,
+                                        std::string const& config);
+
+protected:
+  std::string ComputeLinkLibs(cmComputeLinkInformation& cli);
+  std::string ComputeRPath(cmComputeLinkInformation& cli);
+
+  std::string ConvertToOutputFormat(std::string const& input);
+  std::string ConvertToOutputForExisting(std::string const& input);
+
+  cmStateDirectory StateDir;
+  cmOutputConverter* OutputConverter;
+
+  bool ForResponse;
+  bool UseWatcomQuote;
+  bool Relink;
+};
+
+#endif
diff --git a/Source/cmLinkLineDeviceComputer.cxx b/Source/cmLinkLineDeviceComputer.cxx
new file mode 100644
index 0000000..6a700ff
--- /dev/null
+++ b/Source/cmLinkLineDeviceComputer.cxx
@@ -0,0 +1,80 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#include "cmLinkLineDeviceComputer.h"
+#include "cmComputeLinkInformation.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalNinjaGenerator.h"
+#include "cmOutputConverter.h"
+
+cmLinkLineDeviceComputer::cmLinkLineDeviceComputer(
+  cmOutputConverter* outputConverter, cmStateDirectory stateDir)
+  : cmLinkLineComputer(outputConverter, stateDir)
+{
+}
+
+cmLinkLineDeviceComputer::~cmLinkLineDeviceComputer()
+{
+}
+
+std::string cmLinkLineDeviceComputer::ComputeLinkLibraries(
+  cmComputeLinkInformation& cli, std::string const& stdLibString)
+{
+  // Write the library flags to the build rule.
+  std::ostringstream fout;
+  typedef cmComputeLinkInformation::ItemVector ItemVector;
+  ItemVector const& items = cli.GetItems();
+  std::string config = cli.GetConfig();
+  for (ItemVector::const_iterator li = items.begin(); li != items.end();
+       ++li) {
+    if (!li->Target) {
+      continue;
+    }
+
+    if (li->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
+        li->Target->GetType() == cmStateEnums::SHARED_LIBRARY ||
+        li->Target->GetType() == cmStateEnums::MODULE_LIBRARY) {
+      continue;
+    }
+
+    std::set<std::string> langs;
+    li->Target->GetLanguages(langs, config);
+    if (langs.count("CUDA") == 0) {
+      continue;
+    }
+
+    if (li->IsPath) {
+      fout << this->ConvertToOutputFormat(
+        this->ConvertToLinkReference(li->Value));
+    } else {
+      fout << li->Value;
+    }
+    fout << " ";
+  }
+
+  if (!stdLibString.empty()) {
+    fout << stdLibString << " ";
+  }
+
+  return fout.str();
+}
+
+std::string cmLinkLineDeviceComputer::GetLinkerLanguage(cmGeneratorTarget*,
+                                                        std::string const&)
+{
+  return "CUDA";
+}
+
+cmNinjaLinkLineDeviceComputer::cmNinjaLinkLineDeviceComputer(
+  cmOutputConverter* outputConverter, cmStateDirectory stateDir,
+  cmGlobalNinjaGenerator const* gg)
+  : cmLinkLineDeviceComputer(outputConverter, stateDir)
+  , GG(gg)
+{
+}
+
+std::string cmNinjaLinkLineDeviceComputer::ConvertToLinkReference(
+  std::string const& lib) const
+{
+  return GG->ConvertToNinjaPath(lib);
+}
diff --git a/Source/cmLinkLineDeviceComputer.h b/Source/cmLinkLineDeviceComputer.h
new file mode 100644
index 0000000..f4bb3eb
--- /dev/null
+++ b/Source/cmLinkLineDeviceComputer.h
@@ -0,0 +1,39 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#ifndef cmLinkLineDeviceComputer_h
+#define cmLinkLineDeviceComputer_h
+
+#include "cmLinkLineComputer.h"
+class cmGlobalNinjaGenerator;
+
+class cmLinkLineDeviceComputer : public cmLinkLineComputer
+{
+public:
+  cmLinkLineDeviceComputer(cmOutputConverter* outputConverter,
+                           cmStateDirectory stateDir);
+  ~cmLinkLineDeviceComputer() CM_OVERRIDE;
+
+  std::string ComputeLinkLibraries(cmComputeLinkInformation& cli,
+                                   std::string const& stdLibString)
+    CM_OVERRIDE;
+
+  std::string GetLinkerLanguage(cmGeneratorTarget* target,
+                                std::string const& config) CM_OVERRIDE;
+};
+
+class cmNinjaLinkLineDeviceComputer : public cmLinkLineDeviceComputer
+{
+public:
+  cmNinjaLinkLineDeviceComputer(cmOutputConverter* outputConverter,
+                                cmStateDirectory stateDir,
+                                cmGlobalNinjaGenerator const* gg);
+
+  std::string ConvertToLinkReference(std::string const& input) const
+    CM_OVERRIDE;
+
+private:
+  cmGlobalNinjaGenerator const* GG;
+};
+
+#endif
diff --git a/Source/cmLinkedTree.h b/Source/cmLinkedTree.h
index d2c6f33..4f95522 100644
--- a/Source/cmLinkedTree.h
+++ b/Source/cmLinkedTree.h
@@ -5,9 +5,9 @@
 
 #include <cmConfigure.h>
 
-#include "cmStandardIncludes.h"
-
 #include <assert.h>
+#include <iterator>
+#include <vector>
 
 /**
   @brief A adaptor for traversing a tree structure in a vector
diff --git a/Source/cmListCommand.cxx b/Source/cmListCommand.cxx
index 98f3aa3..295ea28 100644
--- a/Source/cmListCommand.cxx
+++ b/Source/cmListCommand.cxx
@@ -2,14 +2,22 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmListCommand.h"
 
-#include "cmAlgorithms.h"
-#include <cmsys/RegularExpression.hxx>
-#include <cmsys/SystemTools.hxx>
-
 #include <algorithm>
 #include <assert.h>
-#include <ctype.h>
+#include <cmsys/RegularExpression.hxx>
+#include <iterator>
+#include <sstream>
+#include <stdio.h>
 #include <stdlib.h> // required for atoi
+
+#include "cmAlgorithms.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
+
 bool cmListCommand::InitialPass(std::vector<std::string> const& args,
                                 cmExecutionStatus&)
 {
diff --git a/Source/cmListCommand.h b/Source/cmListCommand.h
index b6b0a47..e7413ca 100644
--- a/Source/cmListCommand.h
+++ b/Source/cmListCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmListCommand_h
 #define cmListCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmListCommand
  * \brief Common list operations
  *
@@ -34,8 +40,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "list"; }
 
-  cmTypeMacro(cmListCommand, cmCommand);
-
 protected:
   bool HandleLengthCommand(std::vector<std::string> const& args);
   bool HandleGetCommand(std::vector<std::string> const& args);
diff --git a/Source/cmListFileCache.cxx b/Source/cmListFileCache.cxx
index 5e6273c..b1cd889 100644
--- a/Source/cmListFileCache.cxx
+++ b/Source/cmListFileCache.cxx
@@ -5,6 +5,7 @@
 #include "cmListFileLexer.h"
 #include "cmMessenger.h"
 #include "cmOutputConverter.h"
+#include "cmState.h"
 #include "cmSystemTools.h"
 #include "cmake.h"
 
@@ -298,7 +299,7 @@ struct cmListFileBacktrace::Entry : public cmListFileContext
   unsigned int RefCount;
 };
 
-cmListFileBacktrace::cmListFileBacktrace(cmState::Snapshot bottom, Entry* up,
+cmListFileBacktrace::cmListFileBacktrace(cmStateSnapshot bottom, Entry* up,
                                          cmListFileContext const& lfc)
   : Bottom(bottom)
   , Cur(new Entry(lfc, up))
@@ -307,7 +308,7 @@ cmListFileBacktrace::cmListFileBacktrace(cmState::Snapshot bottom, Entry* up,
   this->Cur->Ref();
 }
 
-cmListFileBacktrace::cmListFileBacktrace(cmState::Snapshot bottom, Entry* cur)
+cmListFileBacktrace::cmListFileBacktrace(cmStateSnapshot bottom, Entry* cur)
   : Bottom(bottom)
   , Cur(cur)
 {
@@ -323,7 +324,7 @@ cmListFileBacktrace::cmListFileBacktrace()
 {
 }
 
-cmListFileBacktrace::cmListFileBacktrace(cmState::Snapshot snapshot)
+cmListFileBacktrace::cmListFileBacktrace(cmStateSnapshot snapshot)
   : Bottom(snapshot.GetCallStackBottom())
   , Cur(CM_NULLPTR)
 {
diff --git a/Source/cmListFileCache.h b/Source/cmListFileCache.h
index 4dacee0..1a30f29 100644
--- a/Source/cmListFileCache.h
+++ b/Source/cmListFileCache.h
@@ -9,7 +9,7 @@
 #include <string>
 #include <vector>
 
-#include "cmState.h"
+#include "cmStateSnapshot.h"
 
 /** \class cmListFileCache
  * \brief A class to cache list file contents.
@@ -113,13 +113,15 @@ public:
 
   // Construct an empty backtrace whose bottom sits in the directory
   // indicated by the given valid snapshot.
-  cmListFileBacktrace(cmState::Snapshot snapshot);
+  cmListFileBacktrace(cmStateSnapshot snapshot);
 
   // Backtraces may be copied and assigned as values.
   cmListFileBacktrace(cmListFileBacktrace const& r);
   cmListFileBacktrace& operator=(cmListFileBacktrace const& r);
   ~cmListFileBacktrace();
 
+  cmStateSnapshot GetBottom() const { return this->Bottom; }
+
   // Get a backtrace with the given file scope added to the top.
   // May not be called until after construction with a valid snapshot.
   cmListFileBacktrace Push(std::string const& file) const;
@@ -145,11 +147,11 @@ public:
 private:
   struct Entry;
 
-  cmState::Snapshot Bottom;
+  cmStateSnapshot Bottom;
   Entry* Cur;
-  cmListFileBacktrace(cmState::Snapshot bottom, Entry* up,
+  cmListFileBacktrace(cmStateSnapshot bottom, Entry* up,
                       cmListFileContext const& lfc);
-  cmListFileBacktrace(cmState::Snapshot bottom, Entry* cur);
+  cmListFileBacktrace(cmStateSnapshot bottom, Entry* cur);
 };
 
 struct cmListFile
diff --git a/Source/cmListFileLexer.c b/Source/cmListFileLexer.c
index 0f73c3d..56559f6 100644
--- a/Source/cmListFileLexer.c
+++ b/Source/cmListFileLexer.c
@@ -1,7 +1,9 @@
+#include "cmStandardLexer.h"
 #line 2 "cmListFileLexer.c"
 
 #line 4 "cmListFileLexer.c"
 
+#define FLEXINT_H 1
 #define  YY_INT_ALIGNED short int
 
 /* A lexical scanner generated by flex */
@@ -9,7 +11,7 @@
 #define FLEX_SCANNER
 #define YY_FLEX_MAJOR_VERSION 2
 #define YY_FLEX_MINOR_VERSION 6
-#define YY_FLEX_SUBMINOR_VERSION 0
+#define YY_FLEX_SUBMINOR_VERSION 1
 #if YY_FLEX_SUBMINOR_VERSION > 0
 #define FLEX_BETA
 #endif
@@ -88,25 +90,13 @@ typedef unsigned int flex_uint32_t;
 
 #endif /* ! FLEXINT_H */
 
-#ifdef __cplusplus
-
-/* The "const" storage-class-modifier is valid. */
-#define YY_USE_CONST
-
-#else	/* ! __cplusplus */
-
-/* C99 requires __STDC__ to be defined as 1. */
-#if defined (__STDC__)
-
-#define YY_USE_CONST
-
-#endif	/* defined (__STDC__) */
-#endif	/* ! __cplusplus */
-
-#ifdef YY_USE_CONST
+/* TODO: this is always defined, so inline it */
 #define yyconst const
+
+#if defined(__GNUC__) && __GNUC__ >= 3
+#define yynoreturn __attribute__((__noreturn__))
 #else
-#define yyconst
+#define yynoreturn
 #endif
 
 /* Returned upon end-of-file. */
@@ -238,7 +228,7 @@ struct yy_buffer_state
 	/* Size of input buffer in bytes, not including room for EOB
 	 * characters.
 	 */
-	yy_size_t yy_buf_size;
+	int yy_buf_size;
 
 	/* Number of characters read into yy_ch_buf, not including EOB
 	 * characters.
@@ -322,7 +312,7 @@ static void cmListFileLexer_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan
 
 YY_BUFFER_STATE cmListFileLexer_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
 YY_BUFFER_STATE cmListFileLexer_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmListFileLexer_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner );
+YY_BUFFER_STATE cmListFileLexer_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
 
 void *cmListFileLexer_yyalloc (yy_size_t ,yyscan_t yyscanner );
 void *cmListFileLexer_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
@@ -366,17 +356,14 @@ typedef int yy_state_type;
 static yy_state_type yy_get_previous_state (yyscan_t yyscanner );
 static yy_state_type yy_try_NUL_trans (yy_state_type current_state  ,yyscan_t yyscanner);
 static int yy_get_next_buffer (yyscan_t yyscanner );
-#if defined(__GNUC__) && __GNUC__ >= 3
-__attribute__((__noreturn__))
-#endif
-static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner );
+static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );
 
 /* Done after the current pattern has been matched and before the
  * corresponding action - sets up yytext.
  */
 #define YY_DO_BEFORE_ACTION \
 	yyg->yytext_ptr = yy_bp; \
-	yyleng = (size_t) (yy_cp - yy_bp); \
+	yyleng = (int) (yy_cp - yy_bp); \
 	yyg->yy_hold_char = *yy_cp; \
 	*yy_cp = '\0'; \
 	yyg->yy_c_buf_p = yy_cp;
@@ -557,18 +544,19 @@ This file must be translated to C and modified to build everywhere.
 
 Run flex >= 2.6 like this:
 
-  flex --prefix=cmListFileLexer_yy -ocmListFileLexer.c cmListFileLexer.in.l
+  flex --nounistd -DFLEXINT_H --prefix=cmListFileLexer_yy -ocmListFileLexer.c cmListFileLexer.in.l
 
 Modify cmListFileLexer.c:
   - remove trailing whitespace: sed -i 's/\s*$//' cmListFileLexer.c
   - remove blank lines at end of file
-  - remove statement "yyscanner = NULL;" from cmListFileLexer_yylex_destroy
-  - remove all YY_BREAK lines occurring right after return statements
-  - remove unnecessary cast to (int) in yy_get_next_buffer
+  - #include "cmStandardLexer.h" at the top
+  - add cast in cmListFileLexer_yy_scan_bytes for loop condition of _yybytes_len to size_t
+  - change type of variable yyl under yy_find_action from yy_size_t to int
 
 */
 
-#include "cmStandardLexer.h"
+/* IWYU pragma: no_forward_declare yyguts_t */
+
 #ifdef WIN32
 #include <cmsys/Encoding.h>
 #endif
@@ -583,7 +571,7 @@ Modify cmListFileLexer.c:
 struct cmListFileLexer_s
 {
   cmListFileLexer_Token token;
-  yy_size_t bracket;
+  int bracket;
   int comment;
   int line;
   int column;
@@ -615,7 +603,7 @@ static void cmListFileLexerDestroy(cmListFileLexer* lexer);
 
 
 
-#line 628 "cmListFileLexer.c"
+#line 606 "cmListFileLexer.c"
 
 #define INITIAL 0
 #define STRING 1
@@ -623,14 +611,6 @@ static void cmListFileLexerDestroy(cmListFileLexer* lexer);
 #define BRACKETEND 3
 #define COMMENT 4
 
-#ifndef YY_NO_UNISTD_H
-/* Special case for "unistd.h", since it is non-ANSI. We include it way
- * down here because we want the user's section 1 to have been scanned first.
- * The user has a chance to override it with an option.
- */
-#include <unistd.h>
-#endif
-
 #ifndef YY_EXTRA_TYPE
 #define YY_EXTRA_TYPE void *
 #endif
@@ -649,7 +629,7 @@ struct yyguts_t
     YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */
     char yy_hold_char;
     int yy_n_chars;
-    yy_size_t yyleng_r;
+    int yyleng_r;
     char *yy_c_buf_p;
     int yy_init;
     int yy_start;
@@ -696,7 +676,7 @@ FILE *cmListFileLexer_yyget_out (yyscan_t yyscanner );
 
 void cmListFileLexer_yyset_out  (FILE * _out_str ,yyscan_t yyscanner );
 
-yy_size_t cmListFileLexer_yyget_leng (yyscan_t yyscanner );
+			int cmListFileLexer_yyget_leng (yyscan_t yyscanner );
 
 char *cmListFileLexer_yyget_text (yyscan_t yyscanner );
 
@@ -759,7 +739,7 @@ static int input (yyscan_t yyscanner );
 /* This used to be an fputs(), but since the string might contain NUL's,
  * we now use fwrite().
  */
-#define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0)
+#define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0)
 #endif
 
 /* Gets input and stuffs it into "buf".  number of characters read, or YY_NULL,
@@ -783,7 +763,7 @@ static int input (yyscan_t yyscanner );
 	else \
 		{ \
 		errno=0; \
-		while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
+		while ( (result = (int) fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
 			{ \
 			if( errno != EINTR) \
 				{ \
@@ -880,10 +860,10 @@ YY_DECL
 		}
 
 	{
-#line 88 "cmListFileLexer.in.l"
+#line 80 "cmListFileLexer.in.l"
 
 
-#line 896 "cmListFileLexer.c"
+#line 866 "cmListFileLexer.c"
 
 	while ( /*CONSTCOND*/1 )		/* loops until end-of-file is reached */
 		{
@@ -913,7 +893,7 @@ yy_match:
 				if ( yy_current_state >= 77 )
 					yy_c = yy_meta[(unsigned int) yy_c];
 				}
-			yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
+			yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
 			++yy_cp;
 			}
 		while ( yy_base[yy_current_state] != 237 );
@@ -931,7 +911,7 @@ yy_find_action:
 
 		if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] )
 			{
-			yy_size_t yyl;
+			int yyl;
 			for ( yyl = 0; yyl < yyleng; ++yyl )
 				if ( yytext[yyl] == '\n' )
 
@@ -955,7 +935,7 @@ do_action:	/* This label is used only to access EOF actions. */
 case 1:
 /* rule 1 can match eol */
 YY_RULE_SETUP
-#line 90 "cmListFileLexer.in.l"
+#line 82 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_Newline;
   cmListFileLexerSetToken(lexer, yytext, yyleng);
@@ -964,10 +944,11 @@ YY_RULE_SETUP
   BEGIN(INITIAL);
   return 1;
 }
+	YY_BREAK
 case 2:
 /* rule 2 can match eol */
 YY_RULE_SETUP
-#line 99 "cmListFileLexer.in.l"
+#line 91 "cmListFileLexer.in.l"
 {
   const char* bracket = yytext;
   lexer->comment = yytext[0] == '#';
@@ -990,7 +971,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 3:
 YY_RULE_SETUP
-#line 119 "cmListFileLexer.in.l"
+#line 111 "cmListFileLexer.in.l"
 {
   lexer->column += yyleng;
   BEGIN(COMMENT);
@@ -998,41 +979,44 @@ YY_RULE_SETUP
 	YY_BREAK
 case 4:
 YY_RULE_SETUP
-#line 124 "cmListFileLexer.in.l"
+#line 116 "cmListFileLexer.in.l"
 {
   lexer->column += yyleng;
 }
 	YY_BREAK
 case 5:
 YY_RULE_SETUP
-#line 128 "cmListFileLexer.in.l"
+#line 120 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_ParenLeft;
   cmListFileLexerSetToken(lexer, yytext, yyleng);
   lexer->column += yyleng;
   return 1;
 }
+	YY_BREAK
 case 6:
 YY_RULE_SETUP
-#line 135 "cmListFileLexer.in.l"
+#line 127 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_ParenRight;
   cmListFileLexerSetToken(lexer, yytext, yyleng);
   lexer->column += yyleng;
   return 1;
 }
+	YY_BREAK
 case 7:
 YY_RULE_SETUP
-#line 142 "cmListFileLexer.in.l"
+#line 134 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_Identifier;
   cmListFileLexerSetToken(lexer, yytext, yyleng);
   lexer->column += yyleng;
   return 1;
 }
+	YY_BREAK
 case 8:
 YY_RULE_SETUP
-#line 149 "cmListFileLexer.in.l"
+#line 141 "cmListFileLexer.in.l"
 {
   /* Handle ]]====]=======]*/
   cmListFileLexerAppend(lexer, yytext, yyleng);
@@ -1044,7 +1028,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 9:
 YY_RULE_SETUP
-#line 158 "cmListFileLexer.in.l"
+#line 150 "cmListFileLexer.in.l"
 {
   lexer->column += yyleng;
   /* Erase the partial bracket from the token.  */
@@ -1053,9 +1037,10 @@ YY_RULE_SETUP
   BEGIN(INITIAL);
   return 1;
 }
+	YY_BREAK
 case 10:
 YY_RULE_SETUP
-#line 167 "cmListFileLexer.in.l"
+#line 159 "cmListFileLexer.in.l"
 {
   cmListFileLexerAppend(lexer, yytext, yyleng);
   lexer->column += yyleng;
@@ -1064,7 +1049,7 @@ YY_RULE_SETUP
 case 11:
 /* rule 11 can match eol */
 YY_RULE_SETUP
-#line 172 "cmListFileLexer.in.l"
+#line 164 "cmListFileLexer.in.l"
 {
   cmListFileLexerAppend(lexer, yytext, yyleng);
   ++lexer->line;
@@ -1074,7 +1059,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 12:
 YY_RULE_SETUP
-#line 179 "cmListFileLexer.in.l"
+#line 171 "cmListFileLexer.in.l"
 {
   cmListFileLexerAppend(lexer, yytext, yyleng);
   lexer->column += yyleng;
@@ -1083,42 +1068,46 @@ YY_RULE_SETUP
 	YY_BREAK
 case YY_STATE_EOF(BRACKET):
 case YY_STATE_EOF(BRACKETEND):
-#line 185 "cmListFileLexer.in.l"
+#line 177 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_BadBracket;
   BEGIN(INITIAL);
   return 1;
 }
+	YY_BREAK
 case 13:
 YY_RULE_SETUP
-#line 191 "cmListFileLexer.in.l"
+#line 183 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_ArgumentUnquoted;
   cmListFileLexerSetToken(lexer, yytext, yyleng);
   lexer->column += yyleng;
   return 1;
 }
+	YY_BREAK
 case 14:
 YY_RULE_SETUP
-#line 198 "cmListFileLexer.in.l"
+#line 190 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_ArgumentUnquoted;
   cmListFileLexerSetToken(lexer, yytext, yyleng);
   lexer->column += yyleng;
   return 1;
 }
+	YY_BREAK
 case 15:
 YY_RULE_SETUP
-#line 205 "cmListFileLexer.in.l"
+#line 197 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_ArgumentUnquoted;
   cmListFileLexerSetToken(lexer, yytext, yyleng);
   lexer->column += yyleng;
   return 1;
 }
+	YY_BREAK
 case 16:
 YY_RULE_SETUP
-#line 212 "cmListFileLexer.in.l"
+#line 204 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_ArgumentQuoted;
   cmListFileLexerSetToken(lexer, "", 0);
@@ -1128,7 +1117,7 @@ YY_RULE_SETUP
 	YY_BREAK
 case 17:
 YY_RULE_SETUP
-#line 219 "cmListFileLexer.in.l"
+#line 211 "cmListFileLexer.in.l"
 {
   cmListFileLexerAppend(lexer, yytext, yyleng);
   lexer->column += yyleng;
@@ -1137,7 +1126,7 @@ YY_RULE_SETUP
 case 18:
 /* rule 18 can match eol */
 YY_RULE_SETUP
-#line 224 "cmListFileLexer.in.l"
+#line 216 "cmListFileLexer.in.l"
 {
   /* Continuation: text is not part of string */
   ++lexer->line;
@@ -1147,7 +1136,7 @@ YY_RULE_SETUP
 case 19:
 /* rule 19 can match eol */
 YY_RULE_SETUP
-#line 230 "cmListFileLexer.in.l"
+#line 222 "cmListFileLexer.in.l"
 {
   cmListFileLexerAppend(lexer, yytext, yyleng);
   ++lexer->line;
@@ -1156,59 +1145,64 @@ YY_RULE_SETUP
 	YY_BREAK
 case 20:
 YY_RULE_SETUP
-#line 236 "cmListFileLexer.in.l"
+#line 228 "cmListFileLexer.in.l"
 {
   lexer->column += yyleng;
   BEGIN(INITIAL);
   return 1;
 }
+	YY_BREAK
 case 21:
 YY_RULE_SETUP
-#line 242 "cmListFileLexer.in.l"
+#line 234 "cmListFileLexer.in.l"
 {
   cmListFileLexerAppend(lexer, yytext, yyleng);
   lexer->column += yyleng;
 }
 	YY_BREAK
 case YY_STATE_EOF(STRING):
-#line 247 "cmListFileLexer.in.l"
+#line 239 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_BadString;
   BEGIN(INITIAL);
   return 1;
 }
+	YY_BREAK
 case 22:
 YY_RULE_SETUP
-#line 253 "cmListFileLexer.in.l"
+#line 245 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_Space;
   cmListFileLexerSetToken(lexer, yytext, yyleng);
   lexer->column += yyleng;
   return 1;
 }
+	YY_BREAK
 case 23:
 YY_RULE_SETUP
-#line 260 "cmListFileLexer.in.l"
+#line 252 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_BadCharacter;
   cmListFileLexerSetToken(lexer, yytext, yyleng);
   lexer->column += yyleng;
   return 1;
 }
+	YY_BREAK
 case YY_STATE_EOF(INITIAL):
 case YY_STATE_EOF(COMMENT):
-#line 267 "cmListFileLexer.in.l"
+#line 259 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_None;
   cmListFileLexerSetToken(lexer, 0, 0);
   return 0;
 }
+	YY_BREAK
 case 24:
 YY_RULE_SETUP
-#line 273 "cmListFileLexer.in.l"
+#line 265 "cmListFileLexer.in.l"
 ECHO;
 	YY_BREAK
-#line 1235 "cmListFileLexer.c"
+#line 1205 "cmListFileLexer.c"
 
 	case YY_END_OF_BUFFER:
 		{
@@ -1394,7 +1388,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 
 	else
 		{
-			yy_size_t num_to_read =
+			int num_to_read =
 			YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
 
 		while ( num_to_read <= 0 )
@@ -1408,7 +1402,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 
 			if ( b->yy_is_our_buffer )
 				{
-				yy_size_t new_size = b->yy_buf_size * 2;
+				int new_size = b->yy_buf_size * 2;
 
 				if ( new_size <= 0 )
 					b->yy_buf_size += b->yy_buf_size / 8;
@@ -1421,7 +1415,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 				}
 			else
 				/* Can't grow it, we don't own it. */
-				b->yy_ch_buf = 0;
+				b->yy_ch_buf = NULL;
 
 			if ( ! b->yy_ch_buf )
 				YY_FATAL_ERROR(
@@ -1463,7 +1457,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 	else
 		ret_val = EOB_ACT_CONTINUE_SCAN;
 
-	if ((yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
+	if ((int) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
 		/* Extend the array by 50%, plus the number we really need. */
 		int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
 		YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) cmListFileLexer_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );
@@ -1504,7 +1498,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 			if ( yy_current_state >= 77 )
 				yy_c = yy_meta[(unsigned int) yy_c];
 			}
-		yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
+		yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
 		}
 
 	return yy_current_state;
@@ -1533,7 +1527,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 		if ( yy_current_state >= 77 )
 			yy_c = yy_meta[(unsigned int) yy_c];
 		}
-	yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
+	yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
 	yy_is_jam = (yy_current_state == 76);
 
 	(void)yyg;
@@ -1555,7 +1549,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 	if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
 		{ /* need to shift things up to make room */
 		/* +2 for EOB chars. */
-		yy_size_t number_to_move = yyg->yy_n_chars + 2;
+		int number_to_move = yyg->yy_n_chars + 2;
 		char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
 					YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
 		char *source =
@@ -1567,7 +1561,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 		yy_cp += (int) (dest - source);
 		yy_bp += (int) (dest - source);
 		YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
-			yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
+			yyg->yy_n_chars = (int) YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
 
 		if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
 			YY_FATAL_ERROR( "flex scanner push-back overflow" );
@@ -1611,7 +1605,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 
 		else
 			{ /* need more input */
-			yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
+			int offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
 			++yyg->yy_c_buf_p;
 
 			switch ( yy_get_next_buffer( yyscanner ) )
@@ -1635,7 +1629,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
 				case EOB_ACT_END_OF_FILE:
 					{
 					if ( cmListFileLexer_yywrap(yyscanner ) )
-						return EOF;
+						return 0;
 
 					if ( ! yyg->yy_did_buffer_switch_on_eof )
 						YY_NEW_FILE;
@@ -1898,7 +1892,7 @@ void cmListFileLexer_yypop_buffer_state (yyscan_t yyscanner)
  */
 static void cmListFileLexer_yyensure_buffer_stack (yyscan_t yyscanner)
 {
-	yy_size_t num_to_alloc;
+	int num_to_alloc;
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 
 	if (!yyg->yy_buffer_stack) {
@@ -1907,7 +1901,7 @@ static void cmListFileLexer_yyensure_buffer_stack (yyscan_t yyscanner)
 		 * scanner will even need a stack. We use 2 instead of 1 to avoid an
 		 * immediate realloc on the next call.
          */
-		num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
+      num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
 		yyg->yy_buffer_stack = (struct yy_buffer_state**)cmListFileLexer_yyalloc
 								(num_to_alloc * sizeof(struct yy_buffer_state*)
 								, yyscanner);
@@ -1954,7 +1948,7 @@ YY_BUFFER_STATE cmListFileLexer_yy_scan_buffer  (char * base, yy_size_t  size ,
 	     base[size-2] != YY_END_OF_BUFFER_CHAR ||
 	     base[size-1] != YY_END_OF_BUFFER_CHAR )
 		/* They forgot to leave room for the EOB's. */
-		return 0;
+		return NULL;
 
 	b = (YY_BUFFER_STATE) cmListFileLexer_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
 	if ( ! b )
@@ -1963,7 +1957,7 @@ YY_BUFFER_STATE cmListFileLexer_yy_scan_buffer  (char * base, yy_size_t  size ,
 	b->yy_buf_size = size - 2;	/* "- 2" to take care of EOB's */
 	b->yy_buf_pos = b->yy_ch_buf = base;
 	b->yy_is_our_buffer = 0;
-	b->yy_input_file = 0;
+	b->yy_input_file = NULL;
 	b->yy_n_chars = b->yy_buf_size;
 	b->yy_is_interactive = 0;
 	b->yy_at_bol = 1;
@@ -1986,7 +1980,7 @@ YY_BUFFER_STATE cmListFileLexer_yy_scan_buffer  (char * base, yy_size_t  size ,
 YY_BUFFER_STATE cmListFileLexer_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner)
 {
 
-	return cmListFileLexer_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner);
+	return cmListFileLexer_yy_scan_bytes(yystr,(int) strlen(yystr) ,yyscanner);
 }
 
 /** Setup the input buffer state to scan the given bytes. The next call to cmListFileLexer_yylex() will
@@ -1996,7 +1990,7 @@ YY_BUFFER_STATE cmListFileLexer_yy_scan_string (yyconst char * yystr , yyscan_t
  * @param yyscanner The scanner object.
  * @return the newly allocated buffer state object.
  */
-YY_BUFFER_STATE cmListFileLexer_yy_scan_bytes  (yyconst char * yybytes, yy_size_t  _yybytes_len , yyscan_t yyscanner)
+YY_BUFFER_STATE cmListFileLexer_yy_scan_bytes  (yyconst char * yybytes, int  _yybytes_len , yyscan_t yyscanner)
 {
 	YY_BUFFER_STATE b;
 	char *buf;
@@ -2004,12 +1998,12 @@ YY_BUFFER_STATE cmListFileLexer_yy_scan_bytes  (yyconst char * yybytes, yy_size_
 	yy_size_t i;
 
 	/* Get memory for full buffer, including space for trailing EOB's. */
-	n = _yybytes_len + 2;
+	n = (yy_size_t) _yybytes_len + 2;
 	buf = (char *) cmListFileLexer_yyalloc(n ,yyscanner );
 	if ( ! buf )
 		YY_FATAL_ERROR( "out of dynamic memory in cmListFileLexer_yy_scan_bytes()" );
 
-	for ( i = 0; i < _yybytes_len; ++i )
+	for ( i = 0; i < (size_t)_yybytes_len; ++i )
 		buf[i] = yybytes[i];
 
 	buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
@@ -2030,7 +2024,7 @@ YY_BUFFER_STATE cmListFileLexer_yy_scan_bytes  (yyconst char * yybytes, yy_size_
 #define YY_EXIT_FAILURE 2
 #endif
 
-static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
+static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
 {
 	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 	(void)yyg;
@@ -2113,7 +2107,7 @@ FILE *cmListFileLexer_yyget_out  (yyscan_t yyscanner)
 /** Get the length of the current token.
  * @param yyscanner The scanner object.
  */
-yy_size_t cmListFileLexer_yyget_leng  (yyscan_t yyscanner)
+int cmListFileLexer_yyget_leng  (yyscan_t yyscanner)
 {
     struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
     return yyleng;
@@ -2272,10 +2266,10 @@ static int yy_init_globals (yyscan_t yyscanner)
      * This function is called from cmListFileLexer_yylex_destroy(), so don't allocate here.
      */
 
-    yyg->yy_buffer_stack = 0;
+    yyg->yy_buffer_stack = NULL;
     yyg->yy_buffer_stack_top = 0;
     yyg->yy_buffer_stack_max = 0;
-    yyg->yy_c_buf_p = (char *) 0;
+    yyg->yy_c_buf_p = NULL;
     yyg->yy_init = 0;
     yyg->yy_start = 0;
 
@@ -2288,8 +2282,8 @@ static int yy_init_globals (yyscan_t yyscanner)
     yyin = stdin;
     yyout = stdout;
 #else
-    yyin = (FILE *) 0;
-    yyout = (FILE *) 0;
+    yyin = NULL;
+    yyout = NULL;
 #endif
 
     /* For future reference: Set errno on error, since we are called by
@@ -2324,6 +2318,7 @@ int cmListFileLexer_yylex_destroy  (yyscan_t yyscanner)
 
     /* Destroy the main struct (reentrant only). */
     cmListFileLexer_yyfree ( yyscanner , yyscanner );
+    yyscanner = NULL;
     return 0;
 }
 
@@ -2358,7 +2353,7 @@ void *cmListFileLexer_yyalloc (yy_size_t  size , yyscan_t yyscanner)
 {
 	struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
 	(void)yyg;
-	return (void *) malloc( size );
+	return malloc(size);
 }
 
 void *cmListFileLexer_yyrealloc  (void * ptr, yy_size_t  size , yyscan_t yyscanner)
@@ -2373,7 +2368,7 @@ void *cmListFileLexer_yyrealloc  (void * ptr, yy_size_t  size , yyscan_t yyscann
 	 * any pointer type to void*, and deal with argument conversions
 	 * as though doing an assignment.
 	 */
-	return (void *) realloc( (char *) ptr, size );
+	return realloc(ptr, size);
 }
 
 void cmListFileLexer_yyfree (void * ptr , yyscan_t yyscanner)
@@ -2385,7 +2380,7 @@ void cmListFileLexer_yyfree (void * ptr , yyscan_t yyscanner)
 
 #define YYTABLES_NAME "yytables"
 
-#line 273 "cmListFileLexer.in.l"
+#line 265 "cmListFileLexer.in.l"
 
 
 
@@ -2523,7 +2518,7 @@ static void cmListFileLexerDestroy(cmListFileLexer* lexer)
 }
 
 /*--------------------------------------------------------------------------*/
-cmListFileLexer* cmListFileLexer_New()
+cmListFileLexer* cmListFileLexer_New(void)
 {
   cmListFileLexer* lexer = (cmListFileLexer*)malloc(sizeof(cmListFileLexer));
   if (!lexer) {
diff --git a/Source/cmListFileLexer.h b/Source/cmListFileLexer.h
index dfbad5e..c9fb6da 100644
--- a/Source/cmListFileLexer.h
+++ b/Source/cmListFileLexer.h
@@ -46,7 +46,7 @@ typedef struct cmListFileLexer_s cmListFileLexer;
 extern "C" {
 #endif
 
-cmListFileLexer* cmListFileLexer_New();
+cmListFileLexer* cmListFileLexer_New(void);
 int cmListFileLexer_SetFileName(cmListFileLexer*, const char*,
                                 cmListFileLexer_BOM* bom);
 int cmListFileLexer_SetString(cmListFileLexer*, const char*);
diff --git a/Source/cmListFileLexer.in.l b/Source/cmListFileLexer.in.l
index 75df1bc..dd64923 100644
--- a/Source/cmListFileLexer.in.l
+++ b/Source/cmListFileLexer.in.l
@@ -7,18 +7,19 @@ This file must be translated to C and modified to build everywhere.
 
 Run flex >= 2.6 like this:
 
-  flex --prefix=cmListFileLexer_yy -ocmListFileLexer.c cmListFileLexer.in.l
+  flex --nounistd -DFLEXINT_H --prefix=cmListFileLexer_yy -ocmListFileLexer.c cmListFileLexer.in.l
 
 Modify cmListFileLexer.c:
   - remove trailing whitespace: sed -i 's/\s*$//' cmListFileLexer.c
   - remove blank lines at end of file
-  - remove statement "yyscanner = NULL;" from cmListFileLexer_yylex_destroy
-  - remove all YY_BREAK lines occurring right after return statements
-  - remove unnecessary cast to (int) in yy_get_next_buffer
+  - #include "cmStandardLexer.h" at the top
+  - add cast in yy_scan_bytes for loop condition of _yybytes_len to size_t
+  - change type of variable yyl under yy_find_action from yy_size_t to int
 
 */
 
-#include "cmStandardLexer.h"
+/* IWYU pragma: no_forward_declare yyguts_t */
+
 #ifdef WIN32
 #include <cmsys/Encoding.h>
 #endif
@@ -33,7 +34,7 @@ Modify cmListFileLexer.c:
 struct cmListFileLexer_s
 {
   cmListFileLexer_Token token;
-  yy_size_t bracket;
+  int bracket;
   int comment;
   int line;
   int column;
@@ -397,7 +398,7 @@ static void cmListFileLexerDestroy(cmListFileLexer* lexer)
 }
 
 /*--------------------------------------------------------------------------*/
-cmListFileLexer* cmListFileLexer_New()
+cmListFileLexer* cmListFileLexer_New(void)
 {
   cmListFileLexer* lexer = (cmListFileLexer*)malloc(sizeof(cmListFileLexer));
   if (!lexer) {
diff --git a/Source/cmLoadCacheCommand.cxx b/Source/cmLoadCacheCommand.cxx
index 3428a6c..ea84877 100644
--- a/Source/cmLoadCacheCommand.cxx
+++ b/Source/cmLoadCacheCommand.cxx
@@ -3,7 +3,13 @@
 #include "cmLoadCacheCommand.h"
 
 #include <cmsys/FStream.hxx>
-#include <cmsys/RegularExpression.hxx>
+
+#include "cmMakefile.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 // cmLoadCacheCommand
 bool cmLoadCacheCommand::InitialPass(std::vector<std::string> const& args,
@@ -140,7 +146,7 @@ void cmLoadCacheCommand::CheckLine(const char* line)
   // Check one line of the cache file.
   std::string var;
   std::string value;
-  cmState::CacheEntryType type = cmState::UNINITIALIZED;
+  cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
   if (cmake::ParseCacheEntry(line, var, value, type)) {
     // Found a real entry.  See if this one was requested.
     if (this->VariablesToRead.find(var) != this->VariablesToRead.end()) {
diff --git a/Source/cmLoadCacheCommand.h b/Source/cmLoadCacheCommand.h
index 57f64cd..539c74e 100644
--- a/Source/cmLoadCacheCommand.h
+++ b/Source/cmLoadCacheCommand.h
@@ -3,8 +3,15 @@
 #ifndef cmLoadCacheCommand_h
 #define cmLoadCacheCommand_h
 
+#include <cmConfigure.h>
+#include <set>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmLoadCacheCommand
  * \brief load a cache file
  *
@@ -30,8 +37,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "load_cache"; }
 
-  cmTypeMacro(cmLoadCacheCommand, cmCommand);
-
 protected:
   std::set<std::string> VariablesToRead;
   std::string Prefix;
diff --git a/Source/cmLoadCommandCommand.cxx b/Source/cmLoadCommandCommand.cxx
index bcfec79..b6743f1 100644
--- a/Source/cmLoadCommandCommand.cxx
+++ b/Source/cmLoadCommandCommand.cxx
@@ -5,16 +5,23 @@
 #include "cmCPluginAPI.cxx"
 #include "cmCPluginAPI.h"
 #include "cmDynamicLoader.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
 
-#include <cmsys/DynamicLoader.hxx>
+class cmExecutionStatus;
 
+#include <signal.h>
+#include <sstream>
+#include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
 
 #ifdef __QNX__
 #include <malloc.h> /* for malloc/free on QNX */
 #endif
 
-#include <signal.h>
 extern "C" void TrapsForSignalsCFunction(int sig);
 
 // a class for loadabple commands
@@ -57,7 +64,7 @@ public:
   void FinalPass() CM_OVERRIDE;
   bool HasFinalPass() const CM_OVERRIDE
   {
-    return this->info.FinalPass ? true : false;
+    return this->info.FinalPass != CM_NULLPTR;
   }
 
   /**
@@ -93,8 +100,6 @@ public:
     }
   }
 
-  cmTypeMacro(cmLoadedCommand, cmCommand);
-
   cmLoadedCommandInfo info;
 };
 
@@ -203,7 +208,7 @@ bool cmLoadCommandCommand::InitialPass(std::vector<std::string> const& args,
   }
 
   // Try to find the program.
-  std::string fullPath = cmSystemTools::FindFile(moduleName.c_str(), path);
+  std::string fullPath = cmSystemTools::FindFile(moduleName, path);
   if (fullPath == "") {
     std::ostringstream e;
     e << "Attempt to load command failed from file \"" << moduleName << "\"";
@@ -232,14 +237,14 @@ bool cmLoadCommandCommand::InitialPass(std::vector<std::string> const& args,
   // find the init function
   std::string initFuncName = args[0] + "Init";
   CM_INIT_FUNCTION initFunction =
-    (CM_INIT_FUNCTION)cmsys::DynamicLoader::GetSymbolAddress(
-      lib, initFuncName.c_str());
+    (CM_INIT_FUNCTION)cmsys::DynamicLoader::GetSymbolAddress(lib,
+                                                             initFuncName);
   if (!initFunction) {
     initFuncName = "_";
     initFuncName += args[0];
     initFuncName += "Init";
     initFunction = (CM_INIT_FUNCTION)(
-      cmsys::DynamicLoader::GetSymbolAddress(lib, initFuncName.c_str()));
+      cmsys::DynamicLoader::GetSymbolAddress(lib, initFuncName));
   }
   // if the symbol is found call it to set the name on the
   // function blocker
diff --git a/Source/cmLoadCommandCommand.h b/Source/cmLoadCommandCommand.h
index e42d46a..d16dfea 100644
--- a/Source/cmLoadCommandCommand.h
+++ b/Source/cmLoadCommandCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmLoadCommandCommand_h
 #define cmLoadCommandCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 class cmLoadCommandCommand : public cmCommand
 {
 public:
@@ -12,7 +18,6 @@ public:
   bool InitialPass(std::vector<std::string> const& args,
                    cmExecutionStatus& status) CM_OVERRIDE;
   std::string GetName() const CM_OVERRIDE { return "load_command"; }
-  cmTypeMacro(cmLoadCommandCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmLocalCommonGenerator.cxx b/Source/cmLocalCommonGenerator.cxx
index 6b49f1e..d5f9d27 100644
--- a/Source/cmLocalCommonGenerator.cxx
+++ b/Source/cmLocalCommonGenerator.cxx
@@ -2,10 +2,11 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLocalCommonGenerator.h"
 
+#include <vector>
+
 #include "cmGeneratorTarget.h"
 #include "cmMakefile.h"
-
-#include <vector>
+#include "cmOutputConverter.h"
 
 class cmGlobalGenerator;
 
diff --git a/Source/cmLocalCommonGenerator.h b/Source/cmLocalCommonGenerator.h
index eb5f850..f83f371 100644
--- a/Source/cmLocalCommonGenerator.h
+++ b/Source/cmLocalCommonGenerator.h
@@ -5,11 +5,10 @@
 
 #include <cmConfigure.h>
 
-#include "cmLocalGenerator.h"
-#include "cmOutputConverter.h"
-
 #include <string>
 
+#include "cmLocalGenerator.h"
+
 class cmGeneratorTarget;
 class cmGlobalGenerator;
 class cmMakefile;
diff --git a/Source/cmLocalGenerator.cxx b/Source/cmLocalGenerator.cxx
index f24b717..7077bbb 100644
--- a/Source/cmLocalGenerator.cxx
+++ b/Source/cmLocalGenerator.cxx
@@ -12,8 +12,14 @@
 #include "cmInstallGenerator.h"
 #include "cmInstallScriptGenerator.h"
 #include "cmInstallTargetGenerator.h"
+#include "cmLinkLineComputer.h"
+#include "cmLinkLineDeviceComputer.h"
 #include "cmMakefile.h"
+#include "cmRulePlaceholderExpander.h"
 #include "cmSourceFile.h"
+#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cmTestGenerator.h"
@@ -22,16 +28,16 @@
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
 #define CM_LG_ENCODE_OBJECT_NAMES
-#include <cmsys/MD5.h>
+#include "cmCryptoHash.h"
 #endif
 
 #include <algorithm>
 #include <assert.h>
 #include <cmsys/RegularExpression.hxx>
-#include <ctype.h>
 #include <iterator>
 #include <sstream>
 #include <stdio.h>
+#include <string.h>
 #include <utility>
 
 #if defined(__HAIKU__)
@@ -39,6 +45,30 @@
 #include <StorageDefs.h>
 #endif
 
+// List of variables that are replaced when
+// rules are expanced.  These variables are
+// replaced in the form <var> with GetSafeDefinition(var).
+// ${LANG} is replaced in the variable first with all enabled
+// languages.
+static const char* ruleReplaceVars[] = {
+  "CMAKE_${LANG}_COMPILER",
+  "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
+  "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
+  "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
+  "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
+  "CMAKE_${LANG}_LINK_FLAGS",
+  "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
+  "CMAKE_${LANG}_ARCHIVE",
+  "CMAKE_AR",
+  "CMAKE_CURRENT_SOURCE_DIR",
+  "CMAKE_CURRENT_BINARY_DIR",
+  "CMAKE_RANLIB",
+  "CMAKE_LINKER",
+  "CMAKE_CUDA_HOST_COMPILER",
+  "CMAKE_CUDA_HOST_LINK_LAUNCHER",
+  "CMAKE_CL_SHOWINCLUDES_PREFIX"
+};
+
 cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
   : cmOutputConverter(makefile->GetStateSnapshot())
   , StateSnapshot(makefile->GetStateSnapshot())
@@ -55,6 +85,65 @@ cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
   this->BackwardsCompatibilityFinal = false;
 
   this->ComputeObjectMaxPath();
+
+  std::vector<std::string> enabledLanguages =
+    this->GetState()->GetEnabledLanguages();
+
+  this->CompilerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
+
+  for (std::vector<std::string>::iterator i = enabledLanguages.begin();
+       i != enabledLanguages.end(); ++i) {
+    std::string const& lang = *i;
+    if (lang == "NONE") {
+      continue;
+    }
+    this->Compilers["CMAKE_" + lang + "_COMPILER"] = lang;
+
+    this->VariableMappings["CMAKE_" + lang + "_COMPILER"] =
+      this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER");
+
+    std::string const& compilerArg1 = "CMAKE_" + lang + "_COMPILER_ARG1";
+    std::string const& compilerTarget = "CMAKE_" + lang + "_COMPILER_TARGET";
+    std::string const& compilerOptionTarget =
+      "CMAKE_" + lang + "_COMPILE_OPTIONS_TARGET";
+    std::string const& compilerExternalToolchain =
+      "CMAKE_" + lang + "_COMPILER_EXTERNAL_TOOLCHAIN";
+    std::string const& compilerOptionExternalToolchain =
+      "CMAKE_" + lang + "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN";
+    std::string const& compilerOptionSysroot =
+      "CMAKE_" + lang + "_COMPILE_OPTIONS_SYSROOT";
+
+    this->VariableMappings[compilerArg1] =
+      this->Makefile->GetSafeDefinition(compilerArg1);
+    this->VariableMappings[compilerTarget] =
+      this->Makefile->GetSafeDefinition(compilerTarget);
+    this->VariableMappings[compilerOptionTarget] =
+      this->Makefile->GetSafeDefinition(compilerOptionTarget);
+    this->VariableMappings[compilerExternalToolchain] =
+      this->Makefile->GetSafeDefinition(compilerExternalToolchain);
+    this->VariableMappings[compilerOptionExternalToolchain] =
+      this->Makefile->GetSafeDefinition(compilerOptionExternalToolchain);
+    this->VariableMappings[compilerOptionSysroot] =
+      this->Makefile->GetSafeDefinition(compilerOptionSysroot);
+
+    for (const char* const* replaceIter = cmArrayBegin(ruleReplaceVars);
+         replaceIter != cmArrayEnd(ruleReplaceVars); ++replaceIter) {
+      std::string actualReplace = *replaceIter;
+      if (actualReplace.find("${LANG}") != actualReplace.npos) {
+        cmSystemTools::ReplaceString(actualReplace, "${LANG}", lang);
+      }
+
+      this->VariableMappings[actualReplace] =
+        this->Makefile->GetSafeDefinition(actualReplace);
+    }
+  }
+}
+
+cmRulePlaceholderExpander* cmLocalGenerator::CreateRulePlaceholderExpander()
+  const
+{
+  return new cmRulePlaceholderExpander(this->Compilers, this->VariableMappings,
+                                       this->CompilerSysroot);
 }
 
 cmLocalGenerator::~cmLocalGenerator()
@@ -116,7 +205,7 @@ void cmLocalGenerator::TraceDependencies()
   std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
   for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
        t != targets.end(); ++t) {
-    if ((*t)->GetType() == cmState::INTERFACE_LIBRARY) {
+    if ((*t)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     (*t)->TraceDependencies();
@@ -166,7 +255,7 @@ void cmLocalGenerator::GenerateTestFiles()
     (*gi)->Compute(this);
     (*gi)->Generate(fout, config, configurationTypes);
   }
-  typedef std::vector<cmState::Snapshot> vec_t;
+  typedef std::vector<cmStateSnapshot> vec_t;
   vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
   std::string parentBinDir = this->GetCurrentBinaryDirectory();
   for (vec_t::const_iterator i = children.begin(); i != children.end(); ++i) {
@@ -363,12 +452,12 @@ void cmLocalGenerator::GenerateInstallRules()
   this->GenerateTargetInstallRules(fout, config, configurationTypes);
 
   // Include install scripts from subdirectories.
-  std::vector<cmState::Snapshot> children =
+  std::vector<cmStateSnapshot> children =
     this->Makefile->GetStateSnapshot().GetChildren();
   if (!children.empty()) {
     fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
     fout << "  # Include the install script for each subdirectory.\n";
-    for (std::vector<cmState::Snapshot>::const_iterator ci = children.begin();
+    for (std::vector<cmStateSnapshot>::const_iterator ci = children.begin();
          ci != children.end(); ++ci) {
       if (!ci->GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
         std::string odir = ci->GetDirectory().GetCurrentBinary();
@@ -459,7 +548,7 @@ void cmLocalGenerator::ComputeTargetManifest()
   for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
        t != targets.end(); ++t) {
     cmGeneratorTarget* target = *t;
-    if (target->GetType() == cmState::INTERFACE_LIBRARY) {
+    if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     for (std::vector<std::string>::iterator ci = configNames.begin();
@@ -480,330 +569,11 @@ cmState* cmLocalGenerator::GetState() const
   return this->GlobalGenerator->GetCMakeInstance()->GetState();
 }
 
-cmState::Snapshot cmLocalGenerator::GetStateSnapshot() const
+cmStateSnapshot cmLocalGenerator::GetStateSnapshot() const
 {
   return this->Makefile->GetStateSnapshot();
 }
 
-// List of variables that are replaced when
-// rules are expanced.  These variables are
-// replaced in the form <var> with GetSafeDefinition(var).
-// ${LANG} is replaced in the variable first with all enabled
-// languages.
-static const char* ruleReplaceVars[] = {
-  "CMAKE_${LANG}_COMPILER",
-  "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
-  "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
-  "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
-  "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
-  "CMAKE_${LANG}_LINK_FLAGS",
-  "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
-  "CMAKE_${LANG}_ARCHIVE",
-  "CMAKE_AR",
-  "CMAKE_CURRENT_SOURCE_DIR",
-  "CMAKE_CURRENT_BINARY_DIR",
-  "CMAKE_RANLIB",
-  "CMAKE_LINKER",
-  "CMAKE_CL_SHOWINCLUDES_PREFIX",
-  CM_NULLPTR
-};
-
-std::string cmLocalGenerator::ExpandRuleVariable(
-  std::string const& variable, const RuleVariables& replaceValues)
-{
-  if (replaceValues.LinkFlags) {
-    if (variable == "LINK_FLAGS") {
-      return replaceValues.LinkFlags;
-    }
-  }
-  if (replaceValues.Manifests) {
-    if (variable == "MANIFESTS") {
-      return replaceValues.Manifests;
-    }
-  }
-  if (replaceValues.Flags) {
-    if (variable == "FLAGS") {
-      return replaceValues.Flags;
-    }
-  }
-
-  if (replaceValues.Source) {
-    if (variable == "SOURCE") {
-      return replaceValues.Source;
-    }
-  }
-  if (replaceValues.PreprocessedSource) {
-    if (variable == "PREPROCESSED_SOURCE") {
-      return replaceValues.PreprocessedSource;
-    }
-  }
-  if (replaceValues.AssemblySource) {
-    if (variable == "ASSEMBLY_SOURCE") {
-      return replaceValues.AssemblySource;
-    }
-  }
-  if (replaceValues.Object) {
-    if (variable == "OBJECT") {
-      return replaceValues.Object;
-    }
-  }
-  if (replaceValues.ObjectDir) {
-    if (variable == "OBJECT_DIR") {
-      return replaceValues.ObjectDir;
-    }
-  }
-  if (replaceValues.ObjectFileDir) {
-    if (variable == "OBJECT_FILE_DIR") {
-      return replaceValues.ObjectFileDir;
-    }
-  }
-  if (replaceValues.Objects) {
-    if (variable == "OBJECTS") {
-      return replaceValues.Objects;
-    }
-  }
-  if (replaceValues.ObjectsQuoted) {
-    if (variable == "OBJECTS_QUOTED") {
-      return replaceValues.ObjectsQuoted;
-    }
-  }
-  if (replaceValues.Defines && variable == "DEFINES") {
-    return replaceValues.Defines;
-  }
-  if (replaceValues.Includes && variable == "INCLUDES") {
-    return replaceValues.Includes;
-  }
-  if (replaceValues.TargetPDB) {
-    if (variable == "TARGET_PDB") {
-      return replaceValues.TargetPDB;
-    }
-  }
-  if (replaceValues.TargetCompilePDB) {
-    if (variable == "TARGET_COMPILE_PDB") {
-      return replaceValues.TargetCompilePDB;
-    }
-  }
-  if (replaceValues.DependencyFile) {
-    if (variable == "DEP_FILE") {
-      return replaceValues.DependencyFile;
-    }
-  }
-
-  if (replaceValues.Target) {
-    if (variable == "TARGET_QUOTED") {
-      std::string targetQuoted = replaceValues.Target;
-      if (!targetQuoted.empty() && targetQuoted[0] != '\"') {
-        targetQuoted = '\"';
-        targetQuoted += replaceValues.Target;
-        targetQuoted += '\"';
-      }
-      return targetQuoted;
-    }
-    if (variable == "TARGET_UNQUOTED") {
-      std::string unquoted = replaceValues.Target;
-      std::string::size_type sz = unquoted.size();
-      if (sz > 2 && unquoted[0] == '\"' && unquoted[sz - 1] == '\"') {
-        unquoted = unquoted.substr(1, sz - 2);
-      }
-      return unquoted;
-    }
-    if (replaceValues.LanguageCompileFlags) {
-      if (variable == "LANGUAGE_COMPILE_FLAGS") {
-        return replaceValues.LanguageCompileFlags;
-      }
-    }
-    if (replaceValues.Target) {
-      if (variable == "TARGET") {
-        return replaceValues.Target;
-      }
-    }
-    if (variable == "TARGET_IMPLIB") {
-      return this->TargetImplib;
-    }
-    if (variable == "TARGET_VERSION_MAJOR") {
-      if (replaceValues.TargetVersionMajor) {
-        return replaceValues.TargetVersionMajor;
-      }
-      return "0";
-    }
-    if (variable == "TARGET_VERSION_MINOR") {
-      if (replaceValues.TargetVersionMinor) {
-        return replaceValues.TargetVersionMinor;
-      }
-      return "0";
-    }
-    if (replaceValues.Target) {
-      if (variable == "TARGET_BASE") {
-        // Strip the last extension off the target name.
-        std::string targetBase = replaceValues.Target;
-        std::string::size_type pos = targetBase.rfind('.');
-        if (pos != targetBase.npos) {
-          return targetBase.substr(0, pos);
-        }
-        return targetBase;
-      }
-    }
-  }
-  if (variable == "TARGET_SONAME" || variable == "SONAME_FLAG" ||
-      variable == "TARGET_INSTALLNAME_DIR") {
-    // All these variables depend on TargetSOName
-    if (replaceValues.TargetSOName) {
-      if (variable == "TARGET_SONAME") {
-        return replaceValues.TargetSOName;
-      }
-      if (variable == "SONAME_FLAG" && replaceValues.SONameFlag) {
-        return replaceValues.SONameFlag;
-      }
-      if (replaceValues.TargetInstallNameDir &&
-          variable == "TARGET_INSTALLNAME_DIR") {
-        return replaceValues.TargetInstallNameDir;
-      }
-    }
-    return "";
-  }
-  if (replaceValues.LinkLibraries) {
-    if (variable == "LINK_LIBRARIES") {
-      return replaceValues.LinkLibraries;
-    }
-  }
-  if (replaceValues.Language) {
-    if (variable == "LANGUAGE") {
-      return replaceValues.Language;
-    }
-  }
-  if (replaceValues.CMTarget) {
-    if (variable == "TARGET_NAME") {
-      return replaceValues.CMTarget->GetName();
-    }
-    if (variable == "TARGET_TYPE") {
-      return cmState::GetTargetTypeName(replaceValues.CMTarget->GetType());
-    }
-  }
-  if (replaceValues.Output) {
-    if (variable == "OUTPUT") {
-      return replaceValues.Output;
-    }
-  }
-  if (variable == "CMAKE_COMMAND") {
-    return this->ConvertToOutputFormat(
-      cmSystemTools::CollapseFullPath(cmSystemTools::GetCMakeCommand()),
-      SHELL);
-  }
-  std::vector<std::string> enabledLanguages =
-    this->GetState()->GetEnabledLanguages();
-  // loop over language specific replace variables
-  int pos = 0;
-  while (ruleReplaceVars[pos]) {
-    for (std::vector<std::string>::iterator i = enabledLanguages.begin();
-         i != enabledLanguages.end(); ++i) {
-      const char* lang = i->c_str();
-      std::string actualReplace = ruleReplaceVars[pos];
-      // If this is the compiler then look for the extra variable
-      // _COMPILER_ARG1 which must be the first argument to the compiler
-      const char* compilerArg1 = CM_NULLPTR;
-      const char* compilerTarget = CM_NULLPTR;
-      const char* compilerOptionTarget = CM_NULLPTR;
-      const char* compilerExternalToolchain = CM_NULLPTR;
-      const char* compilerOptionExternalToolchain = CM_NULLPTR;
-      const char* compilerSysroot = CM_NULLPTR;
-      const char* compilerOptionSysroot = CM_NULLPTR;
-      if (actualReplace == "CMAKE_${LANG}_COMPILER") {
-        std::string arg1 = actualReplace + "_ARG1";
-        cmSystemTools::ReplaceString(arg1, "${LANG}", lang);
-        compilerArg1 = this->Makefile->GetDefinition(arg1);
-        compilerTarget = this->Makefile->GetDefinition(
-          std::string("CMAKE_") + lang + "_COMPILER_TARGET");
-        compilerOptionTarget = this->Makefile->GetDefinition(
-          std::string("CMAKE_") + lang + "_COMPILE_OPTIONS_TARGET");
-        compilerExternalToolchain = this->Makefile->GetDefinition(
-          std::string("CMAKE_") + lang + "_COMPILER_EXTERNAL_TOOLCHAIN");
-        compilerOptionExternalToolchain =
-          this->Makefile->GetDefinition(std::string("CMAKE_") + lang +
-                                        "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN");
-        compilerSysroot = this->Makefile->GetDefinition("CMAKE_SYSROOT");
-        compilerOptionSysroot = this->Makefile->GetDefinition(
-          std::string("CMAKE_") + lang + "_COMPILE_OPTIONS_SYSROOT");
-      }
-      if (actualReplace.find("${LANG}") != actualReplace.npos) {
-        cmSystemTools::ReplaceString(actualReplace, "${LANG}", lang);
-      }
-      if (actualReplace == variable) {
-        std::string replace = this->Makefile->GetSafeDefinition(variable);
-        // if the variable is not a FLAG then treat it like a path
-        if (variable.find("_FLAG") == variable.npos) {
-          std::string ret = this->ConvertToOutputForExisting(replace);
-          // if there is a required first argument to the compiler add it
-          // to the compiler string
-          if (compilerArg1) {
-            ret += " ";
-            ret += compilerArg1;
-          }
-          if (compilerTarget && compilerOptionTarget) {
-            ret += " ";
-            ret += compilerOptionTarget;
-            ret += compilerTarget;
-          }
-          if (compilerExternalToolchain && compilerOptionExternalToolchain) {
-            ret += " ";
-            ret += compilerOptionExternalToolchain;
-            ret += this->EscapeForShell(compilerExternalToolchain, true);
-          }
-          if (compilerSysroot && compilerOptionSysroot) {
-            ret += " ";
-            ret += compilerOptionSysroot;
-            ret += this->EscapeForShell(compilerSysroot, true);
-          }
-          return ret;
-        }
-        return replace;
-      }
-    }
-    pos++;
-  }
-  return variable;
-}
-
-void cmLocalGenerator::ExpandRuleVariables(std::string& s,
-                                           const RuleVariables& replaceValues)
-{
-  if (replaceValues.RuleLauncher) {
-    this->InsertRuleLauncher(s, replaceValues.CMTarget,
-                             replaceValues.RuleLauncher);
-  }
-  std::string::size_type start = s.find('<');
-  // no variables to expand
-  if (start == s.npos) {
-    return;
-  }
-  std::string::size_type pos = 0;
-  std::string expandedInput;
-  while (start != s.npos && start < s.size() - 2) {
-    std::string::size_type end = s.find('>', start);
-    // if we find a < with no > we are done
-    if (end == s.npos) {
-      return;
-    }
-    char c = s[start + 1];
-    // if the next char after the < is not A-Za-z then
-    // skip it and try to find the next < in the string
-    if (!isalpha(c)) {
-      start = s.find('<', start + 1);
-    } else {
-      // extract the var
-      std::string var = s.substr(start + 1, end - start - 1);
-      std::string replace = this->ExpandRuleVariable(var, replaceValues);
-      expandedInput += s.substr(pos, start - pos);
-      expandedInput += replace;
-      // move to next one
-      start = s.find('<', start + var.size() + 2);
-      pos = end + 1;
-    }
-  }
-  // add the rest of the input
-  expandedInput += s.substr(pos, s.size() - pos);
-  s = expandedInput;
-}
-
 const char* cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
                                               const std::string& prop)
 {
@@ -813,17 +583,6 @@ const char* cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
   return this->Makefile->GetProperty(prop);
 }
 
-void cmLocalGenerator::InsertRuleLauncher(std::string& s,
-                                          cmGeneratorTarget* target,
-                                          const std::string& prop)
-{
-  if (const char* val = this->GetRuleLauncher(target, prop)) {
-    std::ostringstream wrapped;
-    wrapped << val << " " << s;
-    s = wrapped.str();
-  }
-}
-
 std::string cmLocalGenerator::ConvertToIncludeReference(
   std::string const& path, OutputFormat format, bool forceFullPaths)
 {
@@ -1148,21 +907,22 @@ void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
 }
 
 void cmLocalGenerator::GetTargetFlags(
-  const std::string& config, std::string& linkLibs, std::string& flags,
-  std::string& linkFlags, std::string& frameworkPath, std::string& linkPath,
-  cmGeneratorTarget* target, bool useWatcomQuote)
+  cmLinkLineComputer* linkLineComputer, const std::string& config,
+  std::string& linkLibs, std::string& flags, std::string& linkFlags,
+  std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
 {
   const std::string buildType = cmSystemTools::UpperCase(config);
+  cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
   const char* libraryLinkVariable =
     "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
 
   switch (target->GetType()) {
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
       this->GetStaticLibraryFlags(linkFlags, buildType, target);
       break;
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
-    case cmState::SHARED_LIBRARY: {
+    case cmStateEnums::SHARED_LIBRARY: {
       linkFlags = this->Makefile->GetSafeDefinition(libraryLinkVariable);
       linkFlags += " ";
       if (!buildType.empty()) {
@@ -1176,12 +936,13 @@ void cmLocalGenerator::GetTargetFlags(
           !(this->Makefile->IsOn("CYGWIN") || this->Makefile->IsOn("MINGW"))) {
         std::vector<cmSourceFile*> sources;
         target->GetSourceFiles(sources, buildType);
+        std::string defFlag =
+          this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
         for (std::vector<cmSourceFile*>::const_iterator i = sources.begin();
              i != sources.end(); ++i) {
           cmSourceFile* sf = *i;
           if (sf->GetExtension() == "def") {
-            linkFlags +=
-              this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
+            linkFlags += defFlag;
             linkFlags += this->ConvertToOutputFormat(
               cmSystemTools::CollapseFullPath(sf->GetFullPath()), SHELL);
             linkFlags += " ";
@@ -1202,10 +963,12 @@ void cmLocalGenerator::GetTargetFlags(
           linkFlags += " ";
         }
       }
-      this->OutputLinkLibraries(linkLibs, frameworkPath, linkPath, *target,
-                                false, false, useWatcomQuote);
+      if (pcli) {
+        this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
+                                  frameworkPath, linkPath);
+      }
     } break;
-    case cmState::EXECUTABLE: {
+    case cmStateEnums::EXECUTABLE: {
       linkFlags += this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
       linkFlags += " ";
       if (!buildType.empty()) {
@@ -1214,7 +977,9 @@ void cmLocalGenerator::GetTargetFlags(
         linkFlags += this->Makefile->GetSafeDefinition(build);
         linkFlags += " ";
       }
-      std::string linkLanguage = target->GetLinkerLanguage(buildType);
+
+      const std::string linkLanguage =
+        linkLineComputer->GetLinkerLanguage(target, buildType);
       if (linkLanguage.empty()) {
         cmSystemTools::Error(
           "CMake can not determine linker language for target: ",
@@ -1222,8 +987,10 @@ void cmLocalGenerator::GetTargetFlags(
         return;
       }
       this->AddLanguageFlags(flags, linkLanguage, buildType);
-      this->OutputLinkLibraries(linkLibs, frameworkPath, linkPath, *target,
-                                false, false, useWatcomQuote);
+      if (pcli) {
+        this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
+                                  frameworkPath, linkPath);
+      }
       if (cmSystemTools::IsOn(
             this->Makefile->GetDefinition("BUILD_SHARED_LIBS"))) {
         std::string sFlagVar = std::string("CMAKE_SHARED_BUILD_") +
@@ -1248,6 +1015,14 @@ void cmLocalGenerator::GetTargetFlags(
         linkFlags += this->Makefile->GetSafeDefinition(exportFlagVar);
         linkFlags += " ";
       }
+
+      std::string cmp0065Flags =
+        this->GetLinkLibsCMP0065(linkLanguage, *target);
+      if (!cmp0065Flags.empty()) {
+        linkFlags += cmp0065Flags;
+        linkFlags += " ";
+      }
+
       const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
       if (targetLinkFlags) {
         linkFlags += targetLinkFlags;
@@ -1374,63 +1149,18 @@ std::string cmLocalGenerator::GetTargetFortranFlags(
   return std::string();
 }
 
-std::string cmLocalGenerator::ConvertToLinkReference(std::string const& lib,
-                                                     OutputFormat format)
-{
-#if defined(_WIN32) && !defined(__CYGWIN__)
-  // Work-ardound command line parsing limitations in MSVC 6.0
-  if (this->Makefile->IsOn("MSVC60")) {
-    // Search for the last space.
-    std::string::size_type pos = lib.rfind(' ');
-    if (pos != lib.npos) {
-      // Find the slash after the last space, if any.
-      pos = lib.find('/', pos);
-
-      // Convert the portion of the path with a space to a short path.
-      std::string sp;
-      if (cmSystemTools::GetShortPath(lib.substr(0, pos).c_str(), sp)) {
-        // Append the rest of the path with no space.
-        sp += lib.substr(pos);
-
-        // Convert to an output path.
-        return this->ConvertToOutputFormat(sp.c_str(), format);
-      }
-    }
-  }
-#endif
-
-  // Normal behavior.
-  return this->ConvertToOutputFormat(
-    this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(), lib),
-    format);
-}
-
 /**
  * Output the linking rules on a command line.  For executables,
  * targetLibrary should be a NULL pointer.  For libraries, it should point
  * to the name of the library.  This will not link a library against itself.
  */
-void cmLocalGenerator::OutputLinkLibraries(std::string& linkLibraries,
-                                           std::string& frameworkPath,
-                                           std::string& linkPath,
-                                           cmGeneratorTarget& tgt, bool relink,
-                                           bool forResponseFile,
-                                           bool useWatcomQuote)
-{
-  OutputFormat shellFormat =
-    (forResponseFile) ? RESPONSE : ((useWatcomQuote) ? WATCOMQUOTE : SHELL);
-  bool escapeAllowMakeVars = !forResponseFile;
-  std::ostringstream fout;
-  std::string config = this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
-  cmComputeLinkInformation* pcli = tgt.GetLinkInformation(config);
-  if (!pcli) {
-    return;
-  }
+void cmLocalGenerator::OutputLinkLibraries(
+  cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
+  std::string& linkLibraries, std::string& frameworkPath,
+  std::string& linkPath)
+{
   cmComputeLinkInformation& cli = *pcli;
 
-  // Collect library linking flags command line options.
-  std::string linkLibs;
-
   std::string linkLanguage = cli.GetLinkLanguage();
 
   std::string libPathFlag =
@@ -1438,8 +1168,36 @@ void cmLocalGenerator::OutputLinkLibraries(std::string& linkLibraries,
   std::string libPathTerminator =
     this->Makefile->GetSafeDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
 
+  // Add standard libraries for this language.
+  std::string standardLibsVar = "CMAKE_";
+  standardLibsVar += cli.GetLinkLanguage();
+  standardLibsVar += "_STANDARD_LIBRARIES";
+  std::string stdLibString;
+  if (const char* stdLibs = this->Makefile->GetDefinition(standardLibsVar)) {
+    stdLibString = stdLibs;
+  }
+
+  // Append the framework search path flags.
+  std::string fwSearchFlagVar = "CMAKE_";
+  fwSearchFlagVar += linkLanguage;
+  fwSearchFlagVar += "_FRAMEWORK_SEARCH_FLAG";
+  std::string fwSearchFlag =
+    this->Makefile->GetSafeDefinition(fwSearchFlagVar);
+
+  frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
+  linkPath =
+    linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator);
+
+  linkLibraries = linkLineComputer->ComputeLinkLibraries(cli, stdLibString);
+}
+
+std::string cmLocalGenerator::GetLinkLibsCMP0065(
+  std::string const& linkLanguage, cmGeneratorTarget& tgt) const
+{
+  std::string linkFlags;
+
   // Flags to link an executable to shared libraries.
-  if (tgt.GetType() == cmState::EXECUTABLE &&
+  if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
       this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
         "TARGET_SUPPORTS_SHARED_LIBS")) {
     bool add_shlib_flags = false;
@@ -1476,100 +1234,10 @@ void cmLocalGenerator::OutputLinkLibraries(std::string& linkLibraries,
       std::string linkFlagsVar = "CMAKE_SHARED_LIBRARY_LINK_";
       linkFlagsVar += linkLanguage;
       linkFlagsVar += "_FLAGS";
-      linkLibs = this->Makefile->GetSafeDefinition(linkFlagsVar);
-      linkLibs += " ";
-    }
-  }
-
-  // Append the framework search path flags.
-  std::string fwSearchFlagVar = "CMAKE_";
-  fwSearchFlagVar += linkLanguage;
-  fwSearchFlagVar += "_FRAMEWORK_SEARCH_FLAG";
-  const char* fwSearchFlag = this->Makefile->GetDefinition(fwSearchFlagVar);
-  if (fwSearchFlag && *fwSearchFlag) {
-    std::vector<std::string> const& fwDirs = cli.GetFrameworkPaths();
-    for (std::vector<std::string>::const_iterator fdi = fwDirs.begin();
-         fdi != fwDirs.end(); ++fdi) {
-      frameworkPath += fwSearchFlag;
-      frameworkPath += this->ConvertToOutputFormat(*fdi, shellFormat);
-      frameworkPath += " ";
-    }
-  }
-
-  // Append the library search path flags.
-  std::vector<std::string> const& libDirs = cli.GetDirectories();
-  for (std::vector<std::string>::const_iterator libDir = libDirs.begin();
-       libDir != libDirs.end(); ++libDir) {
-    std::string libpath =
-      this->ConvertToOutputForExisting(*libDir, shellFormat);
-    linkPath += " " + libPathFlag;
-    linkPath += libpath;
-    linkPath += libPathTerminator;
-    linkPath += " ";
-  }
-
-  // Append the link items.
-  typedef cmComputeLinkInformation::ItemVector ItemVector;
-  ItemVector const& items = cli.GetItems();
-  for (ItemVector::const_iterator li = items.begin(); li != items.end();
-       ++li) {
-    if (li->Target && li->Target->GetType() == cmState::INTERFACE_LIBRARY) {
-      continue;
-    }
-    if (li->IsPath) {
-      linkLibs += this->ConvertToLinkReference(li->Value, shellFormat);
-    } else {
-      linkLibs += li->Value;
-    }
-    linkLibs += " ";
-  }
-
-  // Check what kind of rpath flags to use.
-  if (cli.GetRuntimeSep().empty()) {
-    // Each rpath entry gets its own option ("-R a -R b -R c")
-    std::vector<std::string> runtimeDirs;
-    cli.GetRPath(runtimeDirs, relink);
-
-    std::string rpath;
-    for (std::vector<std::string>::iterator ri = runtimeDirs.begin();
-         ri != runtimeDirs.end(); ++ri) {
-      rpath += cli.GetRuntimeFlag();
-      rpath += this->ConvertToOutputFormat(*ri, shellFormat);
-      rpath += " ";
+      linkFlags = this->Makefile->GetSafeDefinition(linkFlagsVar);
     }
-    fout << rpath;
-  } else {
-    // All rpath entries are combined ("-Wl,-rpath,a:b:c").
-    std::string rpath = cli.GetRPathString(relink);
-
-    // Store the rpath option in the stream.
-    if (!rpath.empty()) {
-      fout << cli.GetRuntimeFlag();
-      fout << this->EscapeForShell(rpath, escapeAllowMakeVars);
-      fout << " ";
-    }
-  }
-
-  // Write the library flags to the build rule.
-  fout << linkLibs;
-
-  // Add the linker runtime search path if any.
-  std::string rpath_link = cli.GetRPathLinkString();
-  if (!cli.GetRPathLinkFlag().empty() && !rpath_link.empty()) {
-    fout << cli.GetRPathLinkFlag();
-    fout << this->EscapeForShell(rpath_link, escapeAllowMakeVars);
-    fout << " ";
-  }
-
-  // Add standard libraries for this language.
-  std::string standardLibsVar = "CMAKE_";
-  standardLibsVar += cli.GetLinkLanguage();
-  standardLibsVar += "_STANDARD_LIBRARIES";
-  if (const char* stdLibs = this->Makefile->GetDefinition(standardLibsVar)) {
-    fout << stdLibs << " ";
   }
-
-  linkLibraries = fout.str();
+  return linkFlags;
 }
 
 void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
@@ -1674,8 +1342,8 @@ bool cmLocalGenerator::GetRealDependency(const std::string& inName,
     // found is part of the inName
     if (cmSystemTools::FileIsFullPath(inName.c_str())) {
       std::string tLocation;
-      if (target->GetType() >= cmState::EXECUTABLE &&
-          target->GetType() <= cmState::MODULE_LIBRARY) {
+      if (target->GetType() >= cmStateEnums::EXECUTABLE &&
+          target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
         tLocation = target->GetLocation(config);
         tLocation = cmSystemTools::GetFilenamePath(tLocation);
         tLocation = cmSystemTools::CollapseFullPath(tLocation);
@@ -1692,23 +1360,23 @@ bool cmLocalGenerator::GetRealDependency(const std::string& inName,
       }
     }
     switch (target->GetType()) {
-      case cmState::EXECUTABLE:
-      case cmState::STATIC_LIBRARY:
-      case cmState::SHARED_LIBRARY:
-      case cmState::MODULE_LIBRARY:
-      case cmState::UNKNOWN_LIBRARY:
+      case cmStateEnums::EXECUTABLE:
+      case cmStateEnums::STATIC_LIBRARY:
+      case cmStateEnums::SHARED_LIBRARY:
+      case cmStateEnums::MODULE_LIBRARY:
+      case cmStateEnums::UNKNOWN_LIBRARY:
         dep = target->GetLocation(config);
         return true;
-      case cmState::OBJECT_LIBRARY:
+      case cmStateEnums::OBJECT_LIBRARY:
         // An object library has no single file on which to depend.
         // This was listed to get the target-level dependency.
         return false;
-      case cmState::INTERFACE_LIBRARY:
+      case cmStateEnums::INTERFACE_LIBRARY:
         // An interface library has no file on which to depend.
         // This was listed to get the target-level dependency.
         return false;
-      case cmState::UTILITY:
-      case cmState::GLOBAL_TARGET:
+      case cmStateEnums::UTILITY:
+      case cmStateEnums::GLOBAL_TARGET:
         // A utility target has no file on which to depend.  This was listed
         // only to get the target-level dependency.
         return false;
@@ -1802,6 +1470,7 @@ void cmLocalGenerator::AddCompilerRequirementFlag(
   static std::map<std::string, std::vector<std::string> > langStdMap;
   if (langStdMap.empty()) {
     // Maintain sorted order, most recent first.
+    langStdMap["CXX"].push_back("17");
     langStdMap["CXX"].push_back("14");
     langStdMap["CXX"].push_back("11");
     langStdMap["CXX"].push_back("98");
@@ -1809,6 +1478,9 @@ void cmLocalGenerator::AddCompilerRequirementFlag(
     langStdMap["C"].push_back("11");
     langStdMap["C"].push_back("99");
     langStdMap["C"].push_back("90");
+
+    langStdMap["CUDA"].push_back("11");
+    langStdMap["CUDA"].push_back("98");
   }
 
   std::string standard(standardProp);
@@ -1924,8 +1596,8 @@ void cmLocalGenerator::AddVisibilityPresetFlags(
 
   std::string warnCMP0063;
   std::string* pWarnCMP0063 = CM_NULLPTR;
-  if (target->GetType() != cmState::SHARED_LIBRARY &&
-      target->GetType() != cmState::MODULE_LIBRARY &&
+  if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
+      target->GetType() != cmStateEnums::MODULE_LIBRARY &&
       !target->IsExecutableWithExports()) {
     switch (target->GetPolicyStatusCMP0063()) {
       case cmPolicies::OLD:
@@ -1967,13 +1639,13 @@ void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
 {
   int targetType = target->GetType();
 
-  bool shared = ((targetType == cmState::SHARED_LIBRARY) ||
-                 (targetType == cmState::MODULE_LIBRARY));
+  bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
+                 (targetType == cmStateEnums::MODULE_LIBRARY));
 
   if (this->GetShouldUseOldFlags(shared, lang)) {
     this->AddSharedFlags(flags, lang, shared);
   } else {
-    if (target->GetType() == cmState::OBJECT_LIBRARY) {
+    if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
       if (target->GetPropertyAsBool("POSITION_INDEPENDENT_CODE")) {
         this->AddPositionIndependentFlags(flags, lang, targetType);
       }
@@ -2036,7 +1708,7 @@ void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
 {
   const char* picFlags = CM_NULLPTR;
 
-  if (targetType == cmState::EXECUTABLE) {
+  if (targetType == cmStateEnums::EXECUTABLE) {
     std::string flagsVar = "CMAKE_";
     flagsVar += lang;
     flagsVar += "_COMPILE_OPTIONS_PIE";
@@ -2208,7 +1880,7 @@ const char* cmLocalGenerator::GetFeature(const std::string& feature,
     featureName += "_";
     featureName += cmSystemTools::UpperCase(config);
   }
-  cmState::Snapshot snp = this->StateSnapshot;
+  cmStateSnapshot snp = this->StateSnapshot;
   while (snp.IsValid()) {
     if (const char* value = snp.GetDirectory().GetProperty(featureName)) {
       return value;
@@ -2273,7 +1945,7 @@ void cmLocalGenerator::GenerateTargetInstallRules(
   std::vector<cmGeneratorTarget*> tgts = this->GetGeneratorTargets();
   for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
        l != tgts.end(); ++l) {
-    if ((*l)->GetType() == cmState::INTERFACE_LIBRARY) {
+    if ((*l)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
 
@@ -2296,15 +1968,15 @@ void cmLocalGenerator::GenerateTargetInstallRules(
 
       // Generate the proper install generator for this target type.
       switch ((*l)->GetType()) {
-        case cmState::EXECUTABLE:
-        case cmState::STATIC_LIBRARY:
-        case cmState::MODULE_LIBRARY: {
+        case cmStateEnums::EXECUTABLE:
+        case cmStateEnums::STATIC_LIBRARY:
+        case cmStateEnums::MODULE_LIBRARY: {
           // Use a target install generator.
           cmInstallTargetGeneratorLocal g(this, (*l)->GetName(),
                                           destination.c_str(), false);
           g.Generate(os, config, configurationTypes);
         } break;
-        case cmState::SHARED_LIBRARY: {
+        case cmStateEnums::SHARED_LIBRARY: {
 #if defined(_WIN32) || defined(__CYGWIN__)
           // Special code to handle DLL.  Install the import library
           // to the normal destination and the DLL to the runtime
@@ -2339,17 +2011,6 @@ void cmLocalGenerator::GenerateTargetInstallRules(
 }
 
 #if defined(CM_LG_ENCODE_OBJECT_NAMES)
-static std::string cmLocalGeneratorMD5(const char* input)
-{
-  char md5out[32];
-  cmsysMD5* md5 = cmsysMD5_New();
-  cmsysMD5_Initialize(md5);
-  cmsysMD5_Append(md5, reinterpret_cast<unsigned char const*>(input), -1);
-  cmsysMD5_FinalizeHex(md5, md5out);
-  cmsysMD5_Delete(md5);
-  return std::string(md5out, 32);
-}
-
 static bool cmLocalGeneratorShortenObjectName(std::string& objName,
                                               std::string::size_type max_len)
 {
@@ -2358,7 +2019,8 @@ static bool cmLocalGeneratorShortenObjectName(std::string& objName,
   std::string::size_type pos =
     objName.find('/', objName.size() - max_len + 32);
   if (pos != objName.npos) {
-    std::string md5name = cmLocalGeneratorMD5(objName.substr(0, pos).c_str());
+    cmCryptoHash md5(cmCryptoHash::AlgoMD5);
+    std::string md5name = md5.HashString(objName.substr(0, pos));
     md5name += objName.substr(pos);
     objName = md5name;
 
diff --git a/Source/cmLocalGenerator.h b/Source/cmLocalGenerator.h
index 19469be..901ca35 100644
--- a/Source/cmLocalGenerator.h
+++ b/Source/cmLocalGenerator.h
@@ -5,25 +5,28 @@
 
 #include <cmConfigure.h>
 
-#include "cmListFileCache.h"
-#include "cmOutputConverter.h"
-#include "cmPolicies.h"
-#include "cmState.h"
-#include "cmake.h"
-
 #include <cm_kwiml.h>
 #include <iosfwd>
 #include <map>
 #include <set>
-#include <string.h>
 #include <string>
 #include <vector>
 
+#include "cmListFileCache.h"
+#include "cmOutputConverter.h"
+#include "cmPolicies.h"
+#include "cmStateSnapshot.h"
+#include "cmake.h"
+
+class cmComputeLinkInformation;
 class cmCustomCommandGenerator;
 class cmGeneratorTarget;
 class cmGlobalGenerator;
+class cmLinkLineComputer;
 class cmMakefile;
+class cmRulePlaceholderExpander;
 class cmSourceFile;
+class cmState;
 
 /** \class cmLocalGenerator
  * \brief Create required build files for a directory.
@@ -82,8 +85,13 @@ public:
     return this->GlobalGenerator;
   }
 
+  virtual cmRulePlaceholderExpander* CreateRulePlaceholderExpander() const;
+
+  std::string GetLinkLibsCMP0065(std::string const& linkLanguage,
+                                 cmGeneratorTarget& tgt) const;
+
   cmState* GetState() const;
-  cmState::Snapshot GetStateSnapshot() const;
+  cmStateSnapshot GetStateSnapshot() const;
 
   void AddArchitectureFlags(std::string& flags,
                             cmGeneratorTarget const* target,
@@ -140,7 +148,7 @@ public:
   void AppendDefines(std::set<std::string>& defines,
                      const char* defines_list) const;
   void AppendDefines(std::set<std::string>& defines,
-                     std::string defines_list) const
+                     std::string const& defines_list) const
   {
     this->AppendDefines(defines, defines_list.c_str());
   }
@@ -212,42 +220,6 @@ public:
   // preprocessed files and assembly files.
   void GetIndividualFileTargets(std::vector<std::string>&) {}
 
-  // Create a struct to hold the varibles passed into
-  // ExpandRuleVariables
-  struct RuleVariables
-  {
-    RuleVariables() { memset(this, 0, sizeof(*this)); }
-    cmGeneratorTarget* CMTarget;
-    const char* TargetPDB;
-    const char* TargetCompilePDB;
-    const char* TargetVersionMajor;
-    const char* TargetVersionMinor;
-    const char* Language;
-    const char* Objects;
-    const char* Target;
-    const char* LinkLibraries;
-    const char* Source;
-    const char* AssemblySource;
-    const char* PreprocessedSource;
-    const char* Output;
-    const char* Object;
-    const char* ObjectDir;
-    const char* ObjectFileDir;
-    const char* Flags;
-    const char* ObjectsQuoted;
-    const char* SONameFlag;
-    const char* TargetSOName;
-    const char* TargetInstallNameDir;
-    const char* LinkFlags;
-    const char* Manifests;
-    const char* LanguageCompileFlags;
-    const char* Defines;
-    const char* Includes;
-    const char* RuleLauncher;
-    const char* DependencyFile;
-    const char* FilterPrefix;
-  };
-
   /**
    * Get the relative path from the generator output directory to a
    * per-target support directory.
@@ -309,10 +281,11 @@ public:
 
   /** Fill out these strings for the given target.  Libraries to link,
    *  flags, and linkflags. */
-  void GetTargetFlags(const std::string& config, std::string& linkLibs,
+  void GetTargetFlags(cmLinkLineComputer* linkLineComputer,
+                      const std::string& config, std::string& linkLibs,
                       std::string& flags, std::string& linkFlags,
                       std::string& frameworkPath, std::string& linkPath,
-                      cmGeneratorTarget* target, bool useWatcomQuote);
+                      cmGeneratorTarget* target);
   void GetTargetDefines(cmGeneratorTarget const* target,
                         std::string const& config, std::string const& lang,
                         std::set<std::string>& defines) const;
@@ -340,24 +313,15 @@ public:
   void CreateEvaluationFileOutputs(const std::string& config);
   void ProcessEvaluationFiles(std::vector<std::string>& generatedFiles);
 
-protected:
-  ///! put all the libraries for a target on into the given stream
-  void OutputLinkLibraries(std::string& linkLibraries,
-                           std::string& frameworkPath, std::string& linkPath,
-                           cmGeneratorTarget&, bool relink,
-                           bool forResponseFile, bool useWatcomQuote);
-
-  // Expand rule variables in CMake of the type found in language rules
-  void ExpandRuleVariables(std::string& string,
-                           const RuleVariables& replaceValues);
-  // Expand rule variables in a single string
-  std::string ExpandRuleVariable(std::string const& variable,
-                                 const RuleVariables& replaceValues);
-
   const char* GetRuleLauncher(cmGeneratorTarget* target,
                               const std::string& prop);
-  void InsertRuleLauncher(std::string& s, cmGeneratorTarget* target,
-                          const std::string& prop);
+
+protected:
+  ///! put all the libraries for a target on into the given stream
+  void OutputLinkLibraries(cmComputeLinkInformation* pcli,
+                           cmLinkLineComputer* linkLineComputer,
+                           std::string& linkLibraries,
+                           std::string& frameworkPath, std::string& linkPath);
 
   // Handle old-style install rules stored in the targets.
   void GenerateTargetInstallRules(
@@ -367,16 +331,12 @@ protected:
   std::string& CreateSafeUniqueObjectFileName(const std::string& sin,
                                               std::string const& dir_max);
 
-  virtual std::string ConvertToLinkReference(
-    std::string const& lib,
-    cmOutputConverter::OutputFormat format = cmOutputConverter::SHELL);
-
   /** Check whether the native build system supports the given
       definition.  Issues a warning.  */
   virtual bool CheckDefinition(std::string const& define) const;
 
   cmMakefile* Makefile;
-  cmState::Snapshot StateSnapshot;
+  cmStateSnapshot StateSnapshot;
   cmListFileBacktrace DirectoryBacktrace;
   cmGlobalGenerator* GlobalGenerator;
   std::map<std::string, std::string> UniqueObjectNamesMap;
@@ -389,11 +349,11 @@ protected:
   std::vector<cmGeneratorTarget*> OwnedImportedGeneratorTargets;
   std::map<std::string, std::string> AliasTargets;
 
-  bool EmitUniversalBinaryFlags;
+  std::map<std::string, std::string> Compilers;
+  std::map<std::string, std::string> VariableMappings;
+  std::string CompilerSysroot;
 
-  // Hack for ExpandRuleVariable until object-oriented version is
-  // committed.
-  std::string TargetImplib;
+  bool EmitUniversalBinaryFlags;
 
   KWIML_INT_uint64_t BackwardsCompatibility;
   bool BackwardsCompatibilityFinal;
diff --git a/Source/cmLocalGhsMultiGenerator.cxx b/Source/cmLocalGhsMultiGenerator.cxx
index 157b32e..5f37af5 100644
--- a/Source/cmLocalGhsMultiGenerator.cxx
+++ b/Source/cmLocalGhsMultiGenerator.cxx
@@ -24,7 +24,7 @@ void cmLocalGhsMultiGenerator::Generate()
 
   for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
        l != tgts.end(); ++l) {
-    if ((*l)->GetType() == cmState::INTERFACE_LIBRARY) {
+    if ((*l)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     cmGhsMultiTargetGenerator tg(*l);
diff --git a/Source/cmLocalNinjaGenerator.cxx b/Source/cmLocalNinjaGenerator.cxx
index 11b87e3..c2d9d57 100644
--- a/Source/cmLocalNinjaGenerator.cxx
+++ b/Source/cmLocalNinjaGenerator.cxx
@@ -2,6 +2,13 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLocalNinjaGenerator.h"
 
+#include <algorithm>
+#include <assert.h>
+#include <iterator>
+#include <sstream>
+#include <stdio.h>
+#include <utility>
+
 #include "cmCustomCommand.h"
 #include "cmCustomCommandGenerator.h"
 #include "cmGeneratedFileStream.h"
@@ -10,28 +17,32 @@
 #include "cmGlobalNinjaGenerator.h"
 #include "cmMakefile.h"
 #include "cmNinjaTargetGenerator.h"
+#include "cmRulePlaceholderExpander.h"
 #include "cmSourceFile.h"
 #include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
-#include <algorithm>
-#include <assert.h>
-#include <iterator>
-#include <sstream>
-#include <stdio.h>
-#include <utility>
-
 cmLocalNinjaGenerator::cmLocalNinjaGenerator(cmGlobalGenerator* gg,
                                              cmMakefile* mf)
   : cmLocalCommonGenerator(gg, mf, mf->GetState()->GetBinaryDirectory())
   , HomeRelativeOutputPath("")
 {
-  this->TargetImplib = "$TARGET_IMPLIB";
 }
 
 // Virtual public methods.
 
+cmRulePlaceholderExpander*
+cmLocalNinjaGenerator::CreateRulePlaceholderExpander() const
+{
+  cmRulePlaceholderExpander* ret = new cmRulePlaceholderExpander(
+    this->Compilers, this->VariableMappings, this->CompilerSysroot);
+  ret->SetTargetImpLib("$TARGET_IMPLIB");
+  return ret;
+}
+
 cmLocalNinjaGenerator::~cmLocalNinjaGenerator()
 {
 }
@@ -72,7 +83,7 @@ void cmLocalNinjaGenerator::Generate()
   std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
   for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
        t != targets.end(); ++t) {
-    if ((*t)->GetType() == cmState::INTERFACE_LIBRARY) {
+    if ((*t)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     cmNinjaTargetGenerator* tg = cmNinjaTargetGenerator::New(*t);
@@ -120,13 +131,6 @@ cmGlobalNinjaGenerator* cmLocalNinjaGenerator::GetGlobalNinjaGenerator()
 
 // Virtual protected methods.
 
-std::string cmLocalNinjaGenerator::ConvertToLinkReference(
-  std::string const& lib, cmOutputConverter::OutputFormat format)
-{
-  std::string path = this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(lib);
-  return this->ConvertToOutputFormat(path, format);
-}
-
 std::string cmLocalNinjaGenerator::ConvertToIncludeReference(
   std::string const& path, cmOutputConverter::OutputFormat format,
   bool forceFullPaths)
@@ -296,15 +300,11 @@ void cmLocalNinjaGenerator::AppendCustomCommandDeps(
 std::string cmLocalNinjaGenerator::BuildCommandLine(
   const std::vector<std::string>& cmdLines)
 {
-  // If we have no commands but we need to build a command anyway, use ":".
+  // If we have no commands but we need to build a command anyway, use noop.
   // This happens when building a POST_BUILD value for link targets that
   // don't use POST_BUILD.
   if (cmdLines.empty()) {
-#ifdef _WIN32
-    return "cd .";
-#else
-    return ":";
-#endif
+    return cmGlobalNinjaGenerator::SHELL_NOOP;
   }
 
   std::ostringstream cmd;
@@ -475,8 +475,8 @@ void cmLocalNinjaGenerator::WriteCustomCommandBuildStatements()
 std::string cmLocalNinjaGenerator::MakeCustomLauncher(
   cmCustomCommandGenerator const& ccg)
 {
-  const char* property = "RULE_LAUNCH_CUSTOM";
-  const char* property_value = this->Makefile->GetProperty(property);
+  const char* property_value =
+    this->Makefile->GetProperty("RULE_LAUNCH_CUSTOM");
 
   if (!property_value || !*property_value) {
     return std::string();
@@ -484,25 +484,27 @@ std::string cmLocalNinjaGenerator::MakeCustomLauncher(
 
   // Expand rules in the empty string.  It may insert the launcher and
   // perform replacements.
-  RuleVariables vars;
-  vars.RuleLauncher = property;
+  cmRulePlaceholderExpander::RuleVariables vars;
+
   std::string output;
   const std::vector<std::string>& outputs = ccg.GetOutputs();
   if (!outputs.empty()) {
+    output = outputs[0];
     if (ccg.GetWorkingDirectory().empty()) {
-      output = this->ConvertToOutputFormat(
-        this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(),
-                                    outputs[0]),
-        cmOutputConverter::SHELL);
-    } else {
       output =
-        this->ConvertToOutputFormat(outputs[0], cmOutputConverter::SHELL);
+        this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(), output);
     }
+    output = this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
   }
   vars.Output = output.c_str();
 
-  std::string launcher;
-  this->ExpandRuleVariables(launcher, vars);
+  std::string launcher = property_value;
+  launcher += " ";
+
+  CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+    this->CreateRulePlaceholderExpander());
+
+  rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
   if (!launcher.empty()) {
     launcher += " ";
   }
diff --git a/Source/cmLocalNinjaGenerator.h b/Source/cmLocalNinjaGenerator.h
index 875f8c6..1080319 100644
--- a/Source/cmLocalNinjaGenerator.h
+++ b/Source/cmLocalNinjaGenerator.h
@@ -5,17 +5,16 @@
 
 #include <cmConfigure.h>
 
-#include "cmLocalCommonGenerator.h"
-#include "cmLocalGenerator.h"
-#include "cmNinjaTypes.h"
-#include "cmOutputConverter.h"
-
 #include <iosfwd>
 #include <map>
 #include <set>
 #include <string>
 #include <vector>
 
+#include "cmLocalCommonGenerator.h"
+#include "cmNinjaTypes.h"
+#include "cmOutputConverter.h"
+
 class cmCustomCommand;
 class cmCustomCommandGenerator;
 class cmGeneratedFileStream;
@@ -23,6 +22,7 @@ class cmGeneratorTarget;
 class cmGlobalGenerator;
 class cmGlobalNinjaGenerator;
 class cmMakefile;
+class cmRulePlaceholderExpander;
 class cmSourceFile;
 class cmake;
 
@@ -42,6 +42,8 @@ public:
 
   void Generate() CM_OVERRIDE;
 
+  cmRulePlaceholderExpander* CreateRulePlaceholderExpander() const CM_OVERRIDE;
+
   std::string GetTargetDirectory(cmGeneratorTarget const* target) const
     CM_OVERRIDE;
 
@@ -58,12 +60,6 @@ public:
     return this->HomeRelativeOutputPath;
   }
 
-  void ExpandRuleVariables(std::string& string,
-                           const RuleVariables& replaceValues)
-  {
-    cmLocalGenerator::ExpandRuleVariables(string, replaceValues);
-  }
-
   std::string BuildCommandLine(const std::vector<std::string>& cmdLines);
 
   void AppendTargetOutputs(cmGeneratorTarget* target, cmNinjaDeps& outputs);
@@ -76,10 +72,6 @@ public:
   void AppendCustomCommandDeps(cmCustomCommandGenerator const& ccg,
                                cmNinjaDeps& ninjaDeps);
 
-  std::string ConvertToLinkReference(std::string const& lib,
-                                     cmOutputConverter::OutputFormat format =
-                                       cmOutputConverter::SHELL) CM_OVERRIDE;
-
   void ComputeObjectFilenames(
     std::map<cmSourceFile const*, std::string>& mapping,
     cmGeneratorTarget const* gt = CM_NULLPTR) CM_OVERRIDE;
diff --git a/Source/cmLocalUnixMakefileGenerator3.cxx b/Source/cmLocalUnixMakefileGenerator3.cxx
index 8825b46..41a4caf 100644
--- a/Source/cmLocalUnixMakefileGenerator3.cxx
+++ b/Source/cmLocalUnixMakefileGenerator3.cxx
@@ -2,6 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmLocalUnixMakefileGenerator3.h"
 
+#include <algorithm>
+#include <cmsys/FStream.hxx>
+#include <cmsys/Terminal.h>
+#include <functional>
+#include <sstream>
+#include <stdio.h>
+#include <utility>
+
 #include "cmAlgorithms.h"
 #include "cmCustomCommand.h"
 #include "cmCustomCommandGenerator.h"
@@ -14,10 +22,15 @@
 #include "cmMakefile.h"
 #include "cmMakefileTargetGenerator.h"
 #include "cmOutputConverter.h"
+#include "cmRulePlaceholderExpander.h"
 #include "cmSourceFile.h"
 #include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmVersion.h"
+#include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
 // Include dependency scanners for supported languages.  Only the
@@ -28,15 +41,6 @@
 #include "cmDependsJava.h"
 #endif
 
-#include <algorithm>
-#include <cm_auto_ptr.hxx>
-#include <cmsys/FStream.hxx>
-#include <cmsys/Terminal.h>
-#include <functional>
-#include <sstream>
-#include <stdio.h>
-#include <utility>
-
 // Escape special characters in Makefile dependency lines
 class cmMakeSafe
 {
@@ -119,7 +123,7 @@ void cmLocalUnixMakefileGenerator3::Generate()
     static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
   for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
        t != targets.end(); ++t) {
-    if ((*t)->GetType() == cmState::INTERFACE_LIBRARY) {
+    if ((*t)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     CM_AUTO_PTR<cmMakefileTargetGenerator> tg(
@@ -141,7 +145,7 @@ void cmLocalUnixMakefileGenerator3::ComputeHomeRelativeOutputPath()
 {
   // Compute the path to use when referencing the current output
   // directory from the top output directory.
-  this->HomeRelativeOutputPath = this->ConvertToRelativePath(
+  this->HomeRelativeOutputPath = this->MaybeConvertToRelativePath(
     this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory());
   if (this->HomeRelativeOutputPath == ".") {
     this->HomeRelativeOutputPath = "";
@@ -171,7 +175,7 @@ void cmLocalUnixMakefileGenerator3::GetLocalObjectFiles(
   for (std::vector<cmGeneratorTarget*>::iterator ti = targets.begin();
        ti != targets.end(); ++ti) {
     cmGeneratorTarget* gt = *ti;
-    if (gt->GetType() == cmState::INTERFACE_LIBRARY) {
+    if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     std::vector<cmSourceFile const*> objectSources;
@@ -230,7 +234,9 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefile()
   // Open the rule file.  This should be copy-if-different because the
   // rules may depend on this file itself.
   std::string ruleFileNameFull = this->ConvertToFullPath(ruleFileName);
-  cmGeneratedFileStream ruleFileStream(ruleFileNameFull.c_str());
+  cmGeneratedFileStream ruleFileStream(
+    ruleFileNameFull.c_str(), false,
+    this->GlobalGenerator->GetMakefileEncoding());
   if (!ruleFileStream) {
     return;
   }
@@ -279,8 +285,8 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefile()
     for (std::vector<LocalObjectEntry>::const_iterator ei = lo->second.begin();
          ei != lo->second.end(); ++ei) {
       if (ei->Language == "C" || ei->Language == "CXX" ||
-          ei->Language == "Fortran") {
-        // Right now, C, C++ and Fortran have both a preprocessor and the
+          ei->Language == "CUDA" || ei->Language == "Fortran") {
+        // Right now, C, C++, Fortran and CUDA have both a preprocessor and the
         // ability to generate assembly code
         lang_has_preprocessor = true;
         lang_has_assembly = true;
@@ -379,12 +385,12 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets(
   std::string localName;
   for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
        t != targets.end(); ++t) {
-    if (((*t)->GetType() == cmState::EXECUTABLE) ||
-        ((*t)->GetType() == cmState::STATIC_LIBRARY) ||
-        ((*t)->GetType() == cmState::SHARED_LIBRARY) ||
-        ((*t)->GetType() == cmState::MODULE_LIBRARY) ||
-        ((*t)->GetType() == cmState::OBJECT_LIBRARY) ||
-        ((*t)->GetType() == cmState::UTILITY)) {
+    if (((*t)->GetType() == cmStateEnums::EXECUTABLE) ||
+        ((*t)->GetType() == cmStateEnums::STATIC_LIBRARY) ||
+        ((*t)->GetType() == cmStateEnums::SHARED_LIBRARY) ||
+        ((*t)->GetType() == cmStateEnums::MODULE_LIBRARY) ||
+        ((*t)->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
+        ((*t)->GetType() == cmStateEnums::UTILITY)) {
       emitted.insert((*t)->GetName());
 
       // for subdirs add a rule to build this specific target by name.
@@ -548,7 +554,8 @@ void cmLocalUnixMakefileGenerator3::WriteMakeRule(
 
   // Construct the left hand side of the rule.
   std::string tgt = cmSystemTools::ConvertToOutputPath(
-    this->ConvertToRelativePath(this->GetBinaryDirectory(), target).c_str());
+    this->MaybeConvertToRelativePath(this->GetBinaryDirectory(), target)
+      .c_str());
 
   const char* space = "";
   if (tgt.size() == 1) {
@@ -577,7 +584,7 @@ void cmLocalUnixMakefileGenerator3::WriteMakeRule(
          dep != depends.end(); ++dep) {
       replace = *dep;
       replace = cmSystemTools::ConvertToOutputPath(
-        this->ConvertToRelativePath(binDir, replace).c_str());
+        this->MaybeConvertToRelativePath(binDir, replace).c_str());
       os << cmMakeSafe(tgt) << space << ": " << cmMakeSafe(replace) << "\n";
     }
   }
@@ -942,6 +949,9 @@ void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
     *content << dir;
   }
 
+  CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+    this->CreateRulePlaceholderExpander());
+
   // Add each command line to the set of commands.
   std::vector<std::string> commands1;
   std::string currentBinDir = this->GetCurrentBinaryDirectory();
@@ -969,7 +979,7 @@ void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
       // working directory will be the start-output directory.
       bool had_slash = cmd.find('/') != cmd.npos;
       if (workingDir.empty()) {
-        cmd = this->ConvertToRelativePath(currentBinDir, cmd);
+        cmd = this->MaybeConvertToRelativePath(currentBinDir, cmd);
       }
       bool has_slash = cmd.find('/') != cmd.npos;
       if (had_slash && !has_slash) {
@@ -981,31 +991,29 @@ void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
 
       std::string launcher;
       // Short-circuit if there is no launcher.
-      const char* prop = "RULE_LAUNCH_CUSTOM";
-      const char* val = this->GetRuleLauncher(target, prop);
+      const char* val = this->GetRuleLauncher(target, "RULE_LAUNCH_CUSTOM");
       if (val && *val) {
         // Expand rules in the empty string.  It may insert the launcher and
         // perform replacements.
-        RuleVariables vars;
-        vars.RuleLauncher = prop;
-        vars.CMTarget = target;
+        cmRulePlaceholderExpander::RuleVariables vars;
+        vars.CMTargetName = target->GetName().c_str();
+        vars.CMTargetType = cmState::GetTargetTypeName(target->GetType());
         std::string output;
         const std::vector<std::string>& outputs = ccg.GetOutputs();
         if (!outputs.empty()) {
+          output = outputs[0];
           if (workingDir.empty()) {
-            output = this->ConvertToOutputFormat(
-              this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(),
-                                          outputs[0]),
-              cmOutputConverter::SHELL);
-
-          } else {
-            output = this->ConvertToOutputFormat(outputs[0],
-                                                 cmOutputConverter::SHELL);
+            output = this->MaybeConvertToRelativePath(
+              this->GetCurrentBinaryDirectory(), output);
           }
+          output =
+            this->ConvertToOutputFormat(output, cmOutputConverter::SHELL);
         }
         vars.Output = output.c_str();
 
-        this->ExpandRuleVariables(launcher, vars);
+        launcher = val;
+        launcher += " ";
+        rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
         if (!launcher.empty()) {
           launcher += " ";
         }
@@ -1082,14 +1090,15 @@ void cmLocalUnixMakefileGenerator3::AppendCleanCommand(
     fout << "file(REMOVE_RECURSE\n";
     for (std::vector<std::string>::const_iterator f = files.begin();
          f != files.end(); ++f) {
-      std::string fc = this->ConvertToRelativePath(currentBinDir, *f);
+      std::string fc = this->MaybeConvertToRelativePath(currentBinDir, *f);
       fout << "  " << cmOutputConverter::EscapeForCMake(fc) << "\n";
     }
     fout << ")\n";
   }
   std::string remove = "$(CMAKE_COMMAND) -P ";
   remove += this->ConvertToOutputFormat(
-    this->ConvertToRelativePath(this->GetCurrentBinaryDirectory(), cleanfile),
+    this->MaybeConvertToRelativePath(this->GetCurrentBinaryDirectory(),
+                                     cleanfile),
     cmOutputConverter::SHELL);
   commands.push_back(remove);
 
@@ -1415,7 +1424,9 @@ bool cmLocalUnixMakefileGenerator3::ScanDependencies(
   // because the make tool may try to reload it needlessly otherwise.
   std::string ruleFileNameFull = dir;
   ruleFileNameFull += "/depend.make";
-  cmGeneratedFileStream ruleFileStream(ruleFileNameFull.c_str());
+  cmGeneratedFileStream ruleFileStream(
+    ruleFileNameFull.c_str(), false,
+    this->GlobalGenerator->GetMakefileEncoding());
   ruleFileStream.SetCopyIfDifferent(true);
   if (!ruleFileStream) {
     return false;
@@ -1427,7 +1438,8 @@ bool cmLocalUnixMakefileGenerator3::ScanDependencies(
   std::string internalRuleFileNameFull = dir;
   internalRuleFileNameFull += "/depend.internal";
   cmGeneratedFileStream internalRuleFileStream(
-    internalRuleFileNameFull.c_str());
+    internalRuleFileNameFull.c_str(), false,
+    this->GlobalGenerator->GetMakefileEncoding());
   if (!internalRuleFileStream) {
     return false;
   }
@@ -1446,7 +1458,8 @@ bool cmLocalUnixMakefileGenerator3::ScanDependencies(
 
     // Create the scanner for this language
     cmDepends* scanner = CM_NULLPTR;
-    if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM") {
+    if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
+        lang == "CUDA") {
       // TODO: Handle RC (resource files) dependencies correctly.
       scanner = new cmDependsC(this, targetDir, lang, &validDeps);
     }
@@ -1549,7 +1562,7 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
   std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
   std::vector<cmGeneratorTarget*>::iterator glIt;
   for (glIt = targets.begin(); glIt != targets.end(); ++glIt) {
-    if ((*glIt)->GetType() == cmState::GLOBAL_TARGET) {
+    if ((*glIt)->GetType() == cmStateEnums::GLOBAL_TARGET) {
       std::string targetString =
         "Special rule for the target " + (*glIt)->GetName();
       std::vector<std::string> commands;
@@ -1579,8 +1592,8 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
 
       // Provide a "/fast" version of the target.
       depends.clear();
-      if ((targetName == "install") || (targetName == "install_local") ||
-          (targetName == "install_strip")) {
+      if ((targetName == "install") || (targetName == "install/local") ||
+          (targetName == "install/strip")) {
         // Provide a fast install target that does not depend on all
         // but has the same command.
         depends.push_back("preinstall/fast");
@@ -1858,7 +1871,8 @@ void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
     }
     for (std::vector<std::string>::iterator i = includes.begin();
          i != includes.end(); ++i) {
-      cmakefileStream << "  \"" << this->ConvertToRelativePath(binaryDir, *i)
+      cmakefileStream << "  \""
+                      << this->MaybeConvertToRelativePath(binaryDir, *i)
                       << "\"\n";
     }
     cmakefileStream << "  )\n";
@@ -1923,7 +1937,7 @@ std::string cmLocalUnixMakefileGenerator3::GetRecursiveMakeCall(
   if (!tgt.empty()) {
     // The make target is always relative to the top of the build tree.
     std::string tgt2 =
-      this->ConvertToRelativePath(this->GetBinaryDirectory(), tgt);
+      this->MaybeConvertToRelativePath(this->GetBinaryDirectory(), tgt);
 
     // The target may have been written with windows paths.
     cmSystemTools::ConvertToOutputSlashes(tgt2);
@@ -2095,3 +2109,13 @@ void cmLocalUnixMakefileGenerator3::CreateCDCommand(
                    std::bind1st(std::plus<std::string>(), prefix));
   }
 }
+
+std::string cmLocalUnixMakefileGenerator3::MaybeConvertToRelativePath(
+  std::string const& base, std::string const& path)
+{
+  if (!cmOutputConverter::ContainedInDirectory(
+        base, path, this->GetStateSnapshot().GetDirectory())) {
+    return path;
+  }
+  return cmOutputConverter::ForceToRelativePath(base, path);
+}
diff --git a/Source/cmLocalUnixMakefileGenerator3.h b/Source/cmLocalUnixMakefileGenerator3.h
index fc5c8e7..c3ecda4 100644
--- a/Source/cmLocalUnixMakefileGenerator3.h
+++ b/Source/cmLocalUnixMakefileGenerator3.h
@@ -184,6 +184,9 @@ public:
   // Eclipse generator.
   void GetIndividualFileTargets(std::vector<std::string>& targets);
 
+  std::string MaybeConvertToRelativePath(std::string const& base,
+                                         std::string const& path);
+
 protected:
   void WriteLocalMakefile();
 
diff --git a/Source/cmLocalVisualStudio10Generator.cxx b/Source/cmLocalVisualStudio10Generator.cxx
index 6f9f009..0516bdf 100644
--- a/Source/cmLocalVisualStudio10Generator.cxx
+++ b/Source/cmLocalVisualStudio10Generator.cxx
@@ -63,7 +63,7 @@ void cmLocalVisualStudio10Generator::Generate()
   std::vector<cmGeneratorTarget*> tgts = this->GetGeneratorTargets();
   for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
        l != tgts.end(); ++l) {
-    if ((*l)->GetType() == cmState::INTERFACE_LIBRARY) {
+    if ((*l)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     if (static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator)
@@ -95,7 +95,7 @@ void cmLocalVisualStudio10Generator::ReadAndStoreExternalGUID(
   // save the GUID in the cache
   this->GlobalGenerator->GetCMakeInstance()->AddCacheEntry(
     guidStoreName.c_str(), parser.GUID.c_str(), "Stored GUID",
-    cmState::INTERNAL);
+    cmStateEnums::INTERNAL);
 }
 
 const char* cmLocalVisualStudio10Generator::ReportErrorLabel() const
diff --git a/Source/cmLocalVisualStudio10Generator.h b/Source/cmLocalVisualStudio10Generator.h
index 4becfee..1ed57ec 100644
--- a/Source/cmLocalVisualStudio10Generator.h
+++ b/Source/cmLocalVisualStudio10Generator.h
@@ -3,8 +3,15 @@
 #ifndef cmLocalVisualStudio10Generator_h
 #define cmLocalVisualStudio10Generator_h
 
+#include <cmConfigure.h>
+
+#include <string>
+
 #include "cmLocalVisualStudio7Generator.h"
 
+class cmGlobalGenerator;
+class cmMakefile;
+
 /** \class cmLocalVisualStudio10Generator
  * \brief Write Visual Studio 10 project files.
  *
diff --git a/Source/cmLocalVisualStudio7Generator.cxx b/Source/cmLocalVisualStudio7Generator.cxx
index a4b28b5..38dda04 100644
--- a/Source/cmLocalVisualStudio7Generator.cxx
+++ b/Source/cmLocalVisualStudio7Generator.cxx
@@ -64,7 +64,7 @@ void cmLocalVisualStudio7Generator::AddHelperCommands()
   std::vector<cmGeneratorTarget*> tgts = this->GetGeneratorTargets();
   for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
        l != tgts.end(); ++l) {
-    if ((*l)->GetType() == cmState::INTERFACE_LIBRARY) {
+    if ((*l)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     const char* path = (*l)->GetProperty("EXTERNAL_MSPROJECT");
@@ -93,7 +93,7 @@ void cmLocalVisualStudio7Generator::AddCMakeListsRules()
       std::vector<cmGeneratorTarget*> tgts = this->GetGeneratorTargets();
       for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
            l != tgts.end(); ++l) {
-        if ((*l)->GetType() == cmState::GLOBAL_TARGET) {
+        if ((*l)->GetType() == cmStateEnums::GLOBAL_TARGET) {
           continue;
         }
         if ((*l)->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
@@ -112,7 +112,7 @@ void cmLocalVisualStudio7Generator::FixGlobalTargets()
   std::vector<cmGeneratorTarget*> tgts = this->GetGeneratorTargets();
   for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
        l != tgts.end(); l++) {
-    if ((*l)->GetType() == cmState::GLOBAL_TARGET) {
+    if ((*l)->GetType() == cmStateEnums::GLOBAL_TARGET) {
       std::vector<std::string> no_depends;
       cmCustomCommandLine force_command;
       force_command.push_back("cd");
@@ -154,7 +154,7 @@ void cmLocalVisualStudio7Generator::WriteProjectFiles()
   // Create the project file for each target.
   for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
        l != tgts.end(); l++) {
-    if ((*l)->GetType() == cmState::INTERFACE_LIBRARY) {
+    if ((*l)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     // INCLUDE_EXTERNAL_MSPROJECT command only affects the workspace
@@ -260,9 +260,7 @@ cmSourceFile* cmLocalVisualStudio7Generator::CreateVCProjBuildRule()
   args += this->GetBinaryDirectory();
   commandLine.push_back(args);
   commandLine.push_back("--check-stamp-file");
-  std::string stampFilename = this->ConvertToOutputFormat(
-    cmSystemTools::CollapseFullPath(stampName), cmOutputConverter::SHELL);
-  commandLine.push_back(stampFilename.c_str());
+  commandLine.push_back(stampName);
 
   std::vector<std::string> const& listFiles = this->Makefile->GetListFiles();
 
@@ -273,7 +271,7 @@ cmSourceFile* cmLocalVisualStudio7Generator::CreateVCProjBuildRule()
     cmSystemTools::CollapseFullPath(stampName.c_str());
   this->Makefile->AddCustomCommandToOutput(
     fullpathStampName.c_str(), listFiles, makefileIn.c_str(), commandLines,
-    comment.c_str(), no_working_directory, true);
+    comment.c_str(), no_working_directory, true, false);
   if (cmSourceFile* file = this->Makefile->GetSource(makefileIn.c_str())) {
     return file;
   } else {
@@ -615,22 +613,22 @@ void cmLocalVisualStudio7Generator::WriteConfiguration(
   bool targetBuilds = true;
 
   switch (target->GetType()) {
-    case cmState::OBJECT_LIBRARY:
+    case cmStateEnums::OBJECT_LIBRARY:
       targetBuilds = false; // no manifest tool for object library
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
       projectType = "typeStaticLibrary";
       configType = "4";
       break;
-    case cmState::SHARED_LIBRARY:
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       projectType = "typeDynamicLibrary";
       configType = "2";
       break;
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       configType = "1";
       break;
-    case cmState::UTILITY:
-    case cmState::GLOBAL_TARGET:
+    case cmStateEnums::UTILITY:
+    case cmStateEnums::GLOBAL_TARGET:
       configType = "10";
     default:
       targetBuilds = false;
@@ -725,8 +723,9 @@ void cmLocalVisualStudio7Generator::WriteConfiguration(
   intermediateDir += "/";
   intermediateDir += configName;
 
-  if (target->GetType() < cmState::UTILITY) {
-    std::string const& outDir = target->GetType() == cmState::OBJECT_LIBRARY
+  if (target->GetType() < cmStateEnums::UTILITY) {
+    std::string const& outDir =
+      target->GetType() == cmStateEnums::OBJECT_LIBRARY
       ? intermediateDir
       : target->GetDirectory(configName);
     /* clang-format off */
@@ -810,7 +809,7 @@ void cmLocalVisualStudio7Generator::WriteConfiguration(
   targetOptions.OutputFlagMap(fout, "\t\t\t\t");
   targetOptions.OutputPreprocessorDefinitions(fout, "\t\t\t\t", "\n", "CXX");
   fout << "\t\t\t\tObjectFile=\"$(IntDir)\\\"\n";
-  if (target->GetType() <= cmState::OBJECT_LIBRARY) {
+  if (target->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
     // Specify the compiler program database file if configured.
     std::string pdb = target->GetCompilePDBPath(configName);
     if (!pdb.empty()) {
@@ -959,19 +958,19 @@ void cmLocalVisualStudio7Generator::OutputBuildTool(
     static_cast<cmGlobalVisualStudio7Generator*>(this->GlobalGenerator);
   std::string temp;
   std::string extraLinkOptions;
-  if (target->GetType() == cmState::EXECUTABLE) {
+  if (target->GetType() == cmStateEnums::EXECUTABLE) {
     extraLinkOptions =
       this->Makefile->GetRequiredDefinition("CMAKE_EXE_LINKER_FLAGS") +
       std::string(" ") +
       GetBuildTypeLinkerFlags("CMAKE_EXE_LINKER_FLAGS", configName);
   }
-  if (target->GetType() == cmState::SHARED_LIBRARY) {
+  if (target->GetType() == cmStateEnums::SHARED_LIBRARY) {
     extraLinkOptions =
       this->Makefile->GetRequiredDefinition("CMAKE_SHARED_LINKER_FLAGS") +
       std::string(" ") +
       GetBuildTypeLinkerFlags("CMAKE_SHARED_LINKER_FLAGS", configName);
   }
-  if (target->GetType() == cmState::MODULE_LIBRARY) {
+  if (target->GetType() == cmStateEnums::MODULE_LIBRARY) {
     extraLinkOptions =
       this->Makefile->GetRequiredDefinition("CMAKE_MODULE_LINKER_FLAGS") +
       std::string(" ") +
@@ -1004,7 +1003,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool(
     linkOptions.AddFlag("ModuleDefinitionFile", defFile.c_str());
   }
 
-  if ((target->GetType() == cmState::SHARED_LIBRARY ||
+  if ((target->GetType() == cmStateEnums::SHARED_LIBRARY ||
        target->IsExecutableWithExports()) &&
       this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
     if (target->GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
@@ -1012,9 +1011,9 @@ void cmLocalVisualStudio7Generator::OutputBuildTool(
     }
   }
   switch (target->GetType()) {
-    case cmState::UNKNOWN_LIBRARY:
+    case cmStateEnums::UNKNOWN_LIBRARY:
       break;
-    case cmState::OBJECT_LIBRARY: {
+    case cmStateEnums::OBJECT_LIBRARY: {
       std::string libpath = this->GetTargetDirectory(target);
       libpath += "/";
       libpath += configName;
@@ -1029,7 +1028,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool(
            << this->ConvertToXMLOutputPathSingle(libpath.c_str()) << "\"/>\n";
       break;
     }
-    case cmState::STATIC_LIBRARY: {
+    case cmStateEnums::STATIC_LIBRARY: {
       std::string targetNameFull = target->GetFullName(configName);
       std::string libpath = target->GetDirectory(configName);
       libpath += "/";
@@ -1059,8 +1058,8 @@ void cmLocalVisualStudio7Generator::OutputBuildTool(
            << this->ConvertToXMLOutputPathSingle(libpath.c_str()) << "\"/>\n";
       break;
     }
-    case cmState::SHARED_LIBRARY:
-    case cmState::MODULE_LIBRARY: {
+    case cmStateEnums::SHARED_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY: {
       std::string targetName;
       std::string targetNameSO;
       std::string targetNameFull;
@@ -1145,7 +1144,7 @@ void cmLocalVisualStudio7Generator::OutputBuildTool(
       }
       fout << "/>\n";
     } break;
-    case cmState::EXECUTABLE: {
+    case cmStateEnums::EXECUTABLE: {
       std::string targetName;
       std::string targetNameFull;
       std::string targetNameImport;
@@ -1241,9 +1240,9 @@ void cmLocalVisualStudio7Generator::OutputBuildTool(
            << this->ConvertToXMLOutputPathSingle(temp.c_str()) << "\"/>\n";
       break;
     }
-    case cmState::UTILITY:
-    case cmState::GLOBAL_TARGET:
-    case cmState::INTERFACE_LIBRARY:
+    case cmStateEnums::UTILITY:
+    case cmStateEnums::GLOBAL_TARGET:
+    case cmStateEnums::INTERFACE_LIBRARY:
       break;
   }
 }
@@ -1296,7 +1295,7 @@ void cmLocalVisualStudio7GeneratorInternals::OutputLibraries(
         lg->ConvertToRelativePath(currentBinDir, l->Value.c_str());
       fout << lg->ConvertToXMLOutputPath(rel.c_str()) << " ";
     } else if (!l->Target ||
-               l->Target->GetType() != cmState::INTERFACE_LIBRARY) {
+               l->Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
       fout << l->Value << " ";
     }
   }
@@ -1463,7 +1462,9 @@ cmLocalVisualStudio7GeneratorFCInfo::cmLocalVisualStudio7GeneratorFCInfo(
       needfc = true;
     }
     if (const char* cflags = sf.GetProperty("COMPILE_FLAGS")) {
-      fc.CompileFlags = cflags;
+      cmGeneratorExpression ge;
+      CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(cflags);
+      fc.CompileFlags = cge->Evaluate(lg, *i);
       needfc = true;
     }
     if (lg->FortranProject) {
@@ -1607,8 +1608,8 @@ bool cmLocalVisualStudio7Generator::WriteGroup(
     std::string source = (*sf)->GetFullPath();
     FCInfo fcinfo(this, target, *(*sf), configs);
 
-    if (source != libName || target->GetType() == cmState::UTILITY ||
-        target->GetType() == cmState::GLOBAL_TARGET) {
+    if (source != libName || target->GetType() == cmStateEnums::UTILITY ||
+        target->GetType() == cmStateEnums::GLOBAL_TARGET) {
       fout << "\t\t\t<File\n";
       std::string d = this->ConvertToXMLOutputPathSingle(source.c_str());
       // Tell MS-Dev what the source is.  If the compiler knows how to
@@ -1812,7 +1813,7 @@ void cmLocalVisualStudio7Generator::OutputTargetRules(
   std::ostream& fout, const std::string& configName, cmGeneratorTarget* target,
   const std::string& /*libName*/)
 {
-  if (target->GetType() > cmState::GLOBAL_TARGET) {
+  if (target->GetType() > cmStateEnums::GLOBAL_TARGET) {
     return;
   }
   EventWriter event(this, configName, fout);
@@ -1828,7 +1829,7 @@ void cmLocalVisualStudio7Generator::OutputTargetRules(
   tool = this->FortranProject ? "VFPreLinkEventTool" : "VCPreLinkEventTool";
   event.Start(tool);
   bool addedPrelink = false;
-  if ((target->GetType() == cmState::SHARED_LIBRARY ||
+  if ((target->GetType() == cmStateEnums::SHARED_LIBRARY ||
        target->IsExecutableWithExports()) &&
       this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
     if (target->GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
@@ -1900,27 +1901,27 @@ void cmLocalVisualStudio7Generator::WriteProjectStartFortran(
   }
   const char* projectType = 0;
   switch (target->GetType()) {
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
       projectType = "typeStaticLibrary";
       if (keyword) {
         keyword = "Static Library";
       }
       break;
-    case cmState::SHARED_LIBRARY:
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       projectType = "typeDynamicLibrary";
       if (!keyword) {
         keyword = "Dll";
       }
       break;
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       if (!keyword) {
         keyword = "Console Application";
       }
       projectType = 0;
       break;
-    case cmState::UTILITY:
-    case cmState::GLOBAL_TARGET:
+    case cmStateEnums::UTILITY:
+    case cmStateEnums::GLOBAL_TARGET:
     default:
       break;
   }
@@ -2117,7 +2118,7 @@ void cmLocalVisualStudio7Generator::ReadAndStoreExternalGUID(
   // save the GUID in the cache
   this->GlobalGenerator->GetCMakeInstance()->AddCacheEntry(
     guidStoreName.c_str(), parser.GUID.c_str(), "Stored GUID",
-    cmState::INTERNAL);
+    cmStateEnums::INTERNAL);
 }
 
 std::string cmLocalVisualStudio7Generator::GetTargetDirectory(
diff --git a/Source/cmLocalVisualStudio7Generator.h b/Source/cmLocalVisualStudio7Generator.h
index 6665bb0..d69cce1 100644
--- a/Source/cmLocalVisualStudio7Generator.h
+++ b/Source/cmLocalVisualStudio7Generator.h
@@ -3,17 +3,23 @@
 #ifndef cmLocalVisualStudio7Generator_h
 #define cmLocalVisualStudio7Generator_h
 
-#include "cmLocalVisualStudioGenerator.h"
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <string>
+#include <vector>
 
+#include "cmLocalVisualStudioGenerator.h"
 #include "cmVisualStudioGeneratorOptions.h"
 
-class cmSourceFile;
 class cmCustomCommand;
-class cmSourceGroup;
-
-class cmLocalVisualStudio7GeneratorOptions;
+class cmGeneratorTarget;
+class cmGlobalGenerator;
 class cmLocalVisualStudio7GeneratorFCInfo;
 class cmLocalVisualStudio7GeneratorInternals;
+class cmMakefile;
+class cmSourceFile;
+class cmSourceGroup;
 
 /** \class cmLocalVisualStudio7Generator
  * \brief Write Visual Studio .NET project files.
@@ -119,6 +125,7 @@ private:
   friend class cmLocalVisualStudio7GeneratorInternals;
 
   class EventWriter;
+
   friend class EventWriter;
 
   std::string ModuleDefinitionFile;
diff --git a/Source/cmLocalVisualStudioGenerator.cxx b/Source/cmLocalVisualStudioGenerator.cxx
index e2b3cd2..e20fe50 100644
--- a/Source/cmLocalVisualStudioGenerator.cxx
+++ b/Source/cmLocalVisualStudioGenerator.cxx
@@ -76,8 +76,8 @@ cmLocalVisualStudioGenerator::MaybeCreateImplibDir(cmGeneratorTarget* target,
   // If an executable exports symbols then VS wants to create an
   // import library but forgets to create the output directory.
   // The Intel Fortran plugin always forgets to the directory.
-  if (target->GetType() != cmState::EXECUTABLE &&
-      !(isFortran && target->GetType() == cmState::SHARED_LIBRARY)) {
+  if (target->GetType() != cmStateEnums::EXECUTABLE &&
+      !(isFortran && target->GetType() == cmStateEnums::SHARED_LIBRARY)) {
     return pcc;
   }
   std::string outDir = target->GetDirectory(config, false);
diff --git a/Source/cmLocalVisualStudioGenerator.h b/Source/cmLocalVisualStudioGenerator.h
index 169ecaf..39188f9 100644
--- a/Source/cmLocalVisualStudioGenerator.h
+++ b/Source/cmLocalVisualStudioGenerator.h
@@ -3,16 +3,22 @@
 #ifndef cmLocalVisualStudioGenerator_h
 #define cmLocalVisualStudioGenerator_h
 
-#include "cmLocalGenerator.h"
+#include <cmConfigure.h>
 
-#include "cmGlobalVisualStudioGenerator.h"
+#include <map>
+#include <memory>
+#include <string>
 
-#include <cm_auto_ptr.hxx>
+#include "cmGlobalVisualStudioGenerator.h"
+#include "cmLocalGenerator.h"
+#include "cm_auto_ptr.hxx"
 
-class cmSourceFile;
-class cmSourceGroup;
 class cmCustomCommand;
 class cmCustomCommandGenerator;
+class cmGeneratorTarget;
+class cmGlobalGenerator;
+class cmMakefile;
+class cmSourceFile;
 
 /** \class cmLocalVisualStudioGenerator
  * \brief Base class for Visual Studio generators.
diff --git a/Source/cmLocalXCodeGenerator.cxx b/Source/cmLocalXCodeGenerator.cxx
index b596a8f..739ef43 100644
--- a/Source/cmLocalXCodeGenerator.cxx
+++ b/Source/cmLocalXCodeGenerator.cxx
@@ -4,9 +4,12 @@
 
 #include "cmGeneratorTarget.h"
 #include "cmGlobalXCodeGenerator.h"
-#include "cmMakefile.h"
 #include "cmSourceFile.h"
 
+class cmGeneratorTarget;
+class cmGlobalGenerator;
+class cmMakefile;
+
 cmLocalXCodeGenerator::cmLocalXCodeGenerator(cmGlobalGenerator* gg,
                                              cmMakefile* mf)
   : cmLocalGenerator(gg, mf)
diff --git a/Source/cmLocalXCodeGenerator.h b/Source/cmLocalXCodeGenerator.h
index 3756b61..b4a8c6c 100644
--- a/Source/cmLocalXCodeGenerator.h
+++ b/Source/cmLocalXCodeGenerator.h
@@ -3,8 +3,17 @@
 #ifndef cmLocalXCodeGenerator_h
 #define cmLocalXCodeGenerator_h
 
+#include <cmConfigure.h> // IWYU pragma: keep
+#include <map>
+#include <string>
+
 #include "cmLocalGenerator.h"
 
+class cmGeneratorTarget;
+class cmGlobalGenerator;
+class cmMakefile;
+class cmSourceFile;
+
 /** \class cmLocalXCodeGenerator
  * \brief Write a local Xcode project
  *
diff --git a/Source/cmLocale.h b/Source/cmLocale.h
index f35e528..cca7cf5 100644
--- a/Source/cmLocale.h
+++ b/Source/cmLocale.h
@@ -5,13 +5,12 @@
 
 #include <cmConfigure.h>
 
-#include "cmStandardIncludes.h"
-
 #include <locale.h>
+#include <string>
 
 class cmLocaleRAII
 {
-  const char* OldLocale;
+  std::string OldLocale;
 
 public:
   cmLocaleRAII()
@@ -19,7 +18,7 @@ public:
   {
     setlocale(LC_CTYPE, "");
   }
-  ~cmLocaleRAII() { setlocale(LC_CTYPE, this->OldLocale); }
+  ~cmLocaleRAII() { setlocale(LC_CTYPE, this->OldLocale.c_str()); }
 };
 
 #endif
diff --git a/Source/cmMSVC60LinkLineComputer.cxx b/Source/cmMSVC60LinkLineComputer.cxx
new file mode 100644
index 0000000..d761e7b
--- /dev/null
+++ b/Source/cmMSVC60LinkLineComputer.cxx
@@ -0,0 +1,42 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#include "cmMSVC60LinkLineComputer.h"
+
+#include "cmStateDirectory.h"
+
+#if defined(_WIN32) && !defined(__CYGWIN__)
+#include "cmSystemTools.h"
+#endif
+
+class cmOutputConverter;
+
+cmMSVC60LinkLineComputer::cmMSVC60LinkLineComputer(
+  cmOutputConverter* outputConverter, cmStateDirectory stateDir)
+  : cmLinkLineComputer(outputConverter, stateDir)
+{
+}
+
+std::string cmMSVC60LinkLineComputer::ConvertToLinkReference(
+  std::string const& lib) const
+{
+#if defined(_WIN32) && !defined(__CYGWIN__)
+  // Work-ardound command line parsing limitations in MSVC 6.0
+  // Search for the last space.
+  std::string::size_type pos = lib.rfind(' ');
+  if (pos != lib.npos) {
+    // Find the slash after the last space, if any.
+    pos = lib.find('/', pos);
+
+    // Convert the portion of the path with a space to a short path.
+    std::string sp;
+    if (cmSystemTools::GetShortPath(lib.substr(0, pos).c_str(), sp)) {
+      // Append the rest of the path with no space.
+      sp += lib.substr(pos);
+      return sp;
+    }
+  }
+#endif
+
+  return cmLinkLineComputer::ConvertToLinkReference(lib);
+}
diff --git a/Source/cmMSVC60LinkLineComputer.h b/Source/cmMSVC60LinkLineComputer.h
new file mode 100644
index 0000000..9a28dca
--- /dev/null
+++ b/Source/cmMSVC60LinkLineComputer.h
@@ -0,0 +1,26 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#ifndef cmMSVC60LinkLineComputer_h
+#define cmMSVC60LinkLineComputer_h
+
+#include <cmConfigure.h>
+
+#include <string>
+
+#include "cmLinkLineComputer.h"
+
+class cmOutputConverter;
+class cmStateDirectory;
+
+class cmMSVC60LinkLineComputer : public cmLinkLineComputer
+{
+public:
+  cmMSVC60LinkLineComputer(cmOutputConverter* outputConverter,
+                           cmStateDirectory stateDir);
+
+  std::string ConvertToLinkReference(std::string const& input) const
+    CM_OVERRIDE;
+};
+
+#endif
diff --git a/Source/cmMachO.cxx b/Source/cmMachO.cxx
index 95518f9..586e6c6 100644
--- a/Source/cmMachO.cxx
+++ b/Source/cmMachO.cxx
@@ -1,10 +1,12 @@
 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
    file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmStandardIncludes.h" // to get CMAKE_USE_MACH_PARSER first
-
 #include "cmMachO.h"
 
+#include <algorithm>
 #include <cmsys/FStream.hxx>
+#include <stddef.h>
+#include <string>
+#include <vector>
 
 // Include the Mach-O format information system header.
 #include <mach-o/fat.h>
diff --git a/Source/cmMachO.h b/Source/cmMachO.h
index a754c1f..901f17a 100644
--- a/Source/cmMachO.h
+++ b/Source/cmMachO.h
@@ -3,6 +3,11 @@
 #ifndef cmMachO_h
 #define cmMachO_h
 
+#include <cmConfigure.h>
+
+#include <iosfwd>
+#include <string>
+
 #if !defined(CMAKE_USE_MACH_PARSER)
 #error "This file may be included only if CMAKE_USE_MACH_PARSER is enabled."
 #endif
diff --git a/Source/cmMacroCommand.cxx b/Source/cmMacroCommand.cxx
index 9917394..583f801 100644
--- a/Source/cmMacroCommand.cxx
+++ b/Source/cmMacroCommand.cxx
@@ -2,8 +2,15 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMacroCommand.h"
 
+#include <sstream>
+#include <stdio.h>
+
 #include "cmAlgorithms.h"
-#include "cmake.h"
+#include "cmExecutionStatus.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
 
 // define the class for macro commands
 class cmMacroHelperCommand : public cmCommand
@@ -15,12 +22,9 @@ public:
   ~cmMacroHelperCommand() CM_OVERRIDE {}
 
   /**
-   * This is used to avoid including this command
-   * in documentation. This is mainly used by
-   * cmMacroHelperCommand and cmFunctionHelperCommand
-   * which cannot provide appropriate documentation.
+   * This determines if the command is defined in a cmake script.
    */
-  bool ShouldAppearInDocumentation() const CM_OVERRIDE { return false; }
+  bool IsUserDefined() const CM_OVERRIDE { return true; }
 
   /**
    * This is a virtual constructor for the command.
@@ -59,8 +63,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return this->Args[0]; }
 
-  cmTypeMacro(cmMacroHelperCommand, cmCommand);
-
   std::vector<std::string> Args;
   std::vector<cmListFileFunction> Functions;
   cmPolicies::PolicyMap Policies;
diff --git a/Source/cmMacroCommand.h b/Source/cmMacroCommand.h
index 362d272..acb4233 100644
--- a/Source/cmMacroCommand.h
+++ b/Source/cmMacroCommand.h
@@ -3,9 +3,16 @@
 #ifndef cmMacroCommand_h
 #define cmMacroCommand_h
 
-#include "cmCommand.h"
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
 
+#include "cmCommand.h"
 #include "cmFunctionBlocker.h"
+#include "cmListFileCache.h"
+
+class cmExecutionStatus;
+class cmMakefile;
 
 class cmMacroFunctionBlocker : public cmFunctionBlocker
 {
@@ -46,8 +53,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "macro"; }
-
-  cmTypeMacro(cmMacroCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmMakeDirectoryCommand.cxx b/Source/cmMakeDirectoryCommand.cxx
index e0011bd..06e295b 100644
--- a/Source/cmMakeDirectoryCommand.cxx
+++ b/Source/cmMakeDirectoryCommand.cxx
@@ -2,6 +2,11 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMakeDirectoryCommand.h"
 
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmMakeDirectoryCommand
 bool cmMakeDirectoryCommand::InitialPass(std::vector<std::string> const& args,
                                          cmExecutionStatus&)
diff --git a/Source/cmMakeDirectoryCommand.h b/Source/cmMakeDirectoryCommand.h
index 2117fae..d9cce6f 100644
--- a/Source/cmMakeDirectoryCommand.h
+++ b/Source/cmMakeDirectoryCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmMakeDirectoryCommand_h
 #define cmMakeDirectoryCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmMakeDirectoryCommand
  * \brief Specify auxiliary source code directories.
  *
@@ -38,8 +44,6 @@ public:
    * This determines if the command is invoked when in script mode.
    */
   bool IsScriptable() const CM_OVERRIDE { return true; }
-
-  cmTypeMacro(cmMakeDirectoryCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmMakefile.cxx b/Source/cmMakefile.cxx
index df993ce..1e995fb 100644
--- a/Source/cmMakefile.cxx
+++ b/Source/cmMakefile.cxx
@@ -2,6 +2,16 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMakefile.h"
 
+#include <algorithm>
+#include <assert.h>
+#include <cmsys/FStream.hxx>
+#include <cmsys/RegularExpression.hxx>
+#include <ctype.h>
+#include <sstream>
+#include <stdlib.h>
+#include <string.h>
+#include <utility>
+
 #include "cmAlgorithms.h"
 #include "cmCommand.h"
 #include "cmCommandArgumentParserHelper.h"
@@ -14,38 +24,30 @@
 #include "cmGeneratorExpression.h"
 #include "cmGeneratorExpressionEvaluationFile.h"
 #include "cmGlobalGenerator.h"
+#include "cmInstallGenerator.h" // IWYU pragma: keep
 #include "cmListFileCache.h"
 #include "cmSourceFile.h"
 #include "cmSourceFileLocation.h"
 #include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
+#include "cmTargetLinkLibraryType.h"
 #include "cmTest.h"
+#include "cmTestGenerator.h" // IWYU pragma: keep
 #include "cmVersion.h"
+#include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
-#include "cmInstallGenerator.h" // IWYU pragma: keep
-#include "cmTestGenerator.h"    // IWYU pragma: keep
-
 #ifdef CMAKE_BUILD_WITH_CMAKE
 #include "cmVariableWatch.h"
 #endif
 
-#include <algorithm>
-#include <assert.h>
-#include <cm_auto_ptr.hxx>
-#include <cmsys/FStream.hxx>
-#include <cmsys/RegularExpression.hxx>
-#include <ctype.h>
-#include <sstream>
-#include <stdlib.h>
-#include <string.h>
-#include <utility>
-
 class cmMessenger;
 
 // default is not to be building executables
 cmMakefile::cmMakefile(cmGlobalGenerator* globalGenerator,
-                       cmState::Snapshot const& snapshot)
+                       cmStateSnapshot const& snapshot)
   : GlobalGenerator(globalGenerator)
   , StateSnapshot(snapshot)
   , Backtrace(snapshot)
@@ -264,7 +266,7 @@ bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff,
     pcmd->SetMakefile(this);
 
     // Decide whether to invoke the command.
-    if (pcmd->GetEnabled() && !cmSystemTools::GetFatalErrorOccured() &&
+    if (!cmSystemTools::GetFatalErrorOccured() &&
         (this->GetCMakeInstance()->GetWorkingMode() != cmake::SCRIPT_MODE ||
          pcmd->IsScriptable()))
 
@@ -690,7 +692,7 @@ void cmMakefile::AddCustomCommandToTarget(
   const std::vector<std::string>& depends,
   const cmCustomCommandLines& commandLines, cmTarget::CustomCommandType type,
   const char* comment, const char* workingDir, bool escapeOldStyle,
-  bool uses_terminal, const std::string& depfile)
+  bool uses_terminal, const std::string& depfile, bool command_expand_lists)
 {
   // Find the target to which to add the custom command.
   cmTargets::iterator ti = this->Targets.find(target);
@@ -730,7 +732,7 @@ void cmMakefile::AddCustomCommandToTarget(
     return;
   }
 
-  if (ti->second.GetType() == cmState::OBJECT_LIBRARY) {
+  if (ti->second.GetType() == cmStateEnums::OBJECT_LIBRARY) {
     std::ostringstream e;
     e << "Target \"" << target
       << "\" is an OBJECT library "
@@ -738,7 +740,7 @@ void cmMakefile::AddCustomCommandToTarget(
     this->IssueMessage(cmake::FATAL_ERROR, e.str());
     return;
   }
-  if (ti->second.GetType() == cmState::INTERFACE_LIBRARY) {
+  if (ti->second.GetType() == cmStateEnums::INTERFACE_LIBRARY) {
     std::ostringstream e;
     e << "Target \"" << target
       << "\" is an INTERFACE library "
@@ -762,6 +764,7 @@ void cmMakefile::AddCustomCommandToTarget(
   cc.SetEscapeOldStyle(escapeOldStyle);
   cc.SetEscapeAllowMakeVars(true);
   cc.SetUsesTerminal(uses_terminal);
+  cc.SetCommandExpandLists(command_expand_lists);
   cc.SetDepfile(depfile);
   switch (type) {
     case cmTarget::PRE_BUILD:
@@ -782,7 +785,7 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput(
   const std::vector<std::string>& depends, const std::string& main_dependency,
   const cmCustomCommandLines& commandLines, const char* comment,
   const char* workingDir, bool replace, bool escapeOldStyle,
-  bool uses_terminal, const std::string& depfile)
+  bool uses_terminal, bool command_expand_lists, const std::string& depfile)
 {
   // Make sure there is at least one output.
   if (outputs.empty()) {
@@ -876,6 +879,7 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput(
     cc->SetEscapeOldStyle(escapeOldStyle);
     cc->SetEscapeAllowMakeVars(true);
     cc->SetUsesTerminal(uses_terminal);
+    cc->SetCommandExpandLists(command_expand_lists);
     cc->SetDepfile(depfile);
     file->SetCustomCommand(cc);
     this->UpdateOutputToSourceMap(outputs, file);
@@ -914,14 +918,16 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput(
   const std::string& output, const std::vector<std::string>& depends,
   const std::string& main_dependency, const cmCustomCommandLines& commandLines,
   const char* comment, const char* workingDir, bool replace,
-  bool escapeOldStyle, bool uses_terminal, const std::string& depfile)
+  bool escapeOldStyle, bool uses_terminal, bool command_expand_lists,
+  const std::string& depfile)
 {
   std::vector<std::string> outputs;
   outputs.push_back(output);
   std::vector<std::string> no_byproducts;
   return this->AddCustomCommandToOutput(
     outputs, no_byproducts, depends, main_dependency, commandLines, comment,
-    workingDir, replace, escapeOldStyle, uses_terminal, depfile);
+    workingDir, replace, escapeOldStyle, uses_terminal, command_expand_lists,
+    depfile);
 }
 
 void cmMakefile::AddCustomCommandOldStyle(
@@ -959,7 +965,7 @@ void cmMakefile::AddCustomCommandOldStyle(
                                           commandLines, comment, CM_NULLPTR);
     } else {
       // The source may not be a real file.  Do not use a main dependency.
-      std::string no_main_dependency = "";
+      std::string no_main_dependency;
       std::vector<std::string> depends2 = depends;
       depends2.push_back(source);
       sf = this->AddCustomCommandToOutput(output, depends2, no_main_dependency,
@@ -1016,12 +1022,13 @@ cmTarget* cmMakefile::AddUtilityCommand(
   const std::string& utilityName, bool excludeFromAll,
   const char* workingDirectory, const std::vector<std::string>& depends,
   const cmCustomCommandLines& commandLines, bool escapeOldStyle,
-  const char* comment, bool uses_terminal)
+  const char* comment, bool uses_terminal, bool command_expand_lists)
 {
   std::vector<std::string> no_byproducts;
   return this->AddUtilityCommand(utilityName, excludeFromAll, workingDirectory,
                                  no_byproducts, depends, commandLines,
-                                 escapeOldStyle, comment, uses_terminal);
+                                 escapeOldStyle, comment, uses_terminal,
+                                 command_expand_lists);
 }
 
 cmTarget* cmMakefile::AddUtilityCommand(
@@ -1029,10 +1036,10 @@ cmTarget* cmMakefile::AddUtilityCommand(
   const char* workingDirectory, const std::vector<std::string>& byproducts,
   const std::vector<std::string>& depends,
   const cmCustomCommandLines& commandLines, bool escapeOldStyle,
-  const char* comment, bool uses_terminal)
+  const char* comment, bool uses_terminal, bool command_expand_lists)
 {
   // Create a target instance for this utility.
-  cmTarget* target = this->AddNewTarget(cmState::UTILITY, utilityName);
+  cmTarget* target = this->AddNewTarget(cmStateEnums::UTILITY, utilityName);
   if (excludeFromAll) {
     target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
   }
@@ -1049,11 +1056,12 @@ cmTarget* cmMakefile::AddUtilityCommand(
     force += utilityName;
     std::vector<std::string> forced;
     forced.push_back(force);
-    std::string no_main_dependency = "";
+    std::string no_main_dependency;
     bool no_replace = false;
     this->AddCustomCommandToOutput(
       forced, byproducts, depends, no_main_dependency, commandLines, comment,
-      workingDirectory, no_replace, escapeOldStyle, uses_terminal);
+      workingDirectory, no_replace, escapeOldStyle, uses_terminal,
+      command_expand_lists);
     cmSourceFile* sf = target->AddSourceCMP0049(force);
 
     // The output is not actually created so mark it symbolic.
@@ -1207,71 +1215,6 @@ bool cmMakefile::ParseDefineFlag(std::string const& def, bool remove)
   return true;
 }
 
-void cmMakefile::AddLinkLibrary(const std::string& lib,
-                                cmTargetLinkLibraryType llt)
-{
-  cmTarget::LibraryID tmp;
-  tmp.first = lib;
-  tmp.second = llt;
-  this->LinkLibraries.push_back(tmp);
-}
-
-void cmMakefile::AddLinkLibraryForTarget(const std::string& target,
-                                         const std::string& lib,
-                                         cmTargetLinkLibraryType llt)
-{
-  cmTargets::iterator i = this->Targets.find(target);
-  if (i != this->Targets.end()) {
-    cmTarget* tgt = this->GetGlobalGenerator()->FindTarget(lib);
-    if (tgt) {
-      // if it is not a static or shared library then you can not link to it
-      if (!((tgt->GetType() == cmState::STATIC_LIBRARY) ||
-            (tgt->GetType() == cmState::SHARED_LIBRARY) ||
-            (tgt->GetType() == cmState::INTERFACE_LIBRARY) ||
-            tgt->IsExecutableWithExports())) {
-        std::ostringstream e;
-        e << "Target \"" << lib << "\" of type "
-          << cmState::GetTargetTypeName(tgt->GetType())
-          << " may not be linked into another target.  "
-          << "One may link only to STATIC or SHARED libraries, or "
-          << "to executables with the ENABLE_EXPORTS property set.";
-        this->IssueMessage(cmake::FATAL_ERROR, e.str());
-      }
-    }
-    i->second.AddLinkLibrary(*this, target, lib, llt);
-  } else {
-    std::ostringstream e;
-    e << "Attempt to add link library \"" << lib << "\" to target \"" << target
-      << "\" which is not built in this directory.";
-    this->IssueMessage(cmake::FATAL_ERROR, e.str());
-  }
-}
-
-void cmMakefile::AddLinkDirectoryForTarget(const std::string& target,
-                                           const std::string& d)
-{
-  cmTargets::iterator i = this->Targets.find(target);
-  if (i != this->Targets.end()) {
-    if (this->IsAlias(target)) {
-      std::ostringstream e;
-      e << "ALIAS target \"" << target << "\" "
-        << "may not be linked into another target.";
-      this->IssueMessage(cmake::FATAL_ERROR, e.str());
-      return;
-    }
-    i->second.AddLinkDirectory(d);
-  } else {
-    cmSystemTools::Error(
-      "Attempt to add link directories to non-existent target: ",
-      target.c_str(), " for directory ", d.c_str());
-  }
-}
-
-void cmMakefile::AddLinkLibrary(const std::string& lib)
-{
-  this->AddLinkLibrary(lib, GENERAL_LibraryType);
-}
-
 void cmMakefile::InitializeFromParent(cmMakefile* parent)
 {
   this->SystemIncludeDirectories = parent->SystemIncludeDirectories;
@@ -1303,7 +1246,7 @@ void cmMakefile::InitializeFromParent(cmMakefile* parent)
   }
 
   // link libraries
-  this->LinkLibraries = parent->LinkLibraries;
+  this->SetProperty("LINK_LIBRARIES", parent->GetProperty("LINK_LIBRARIES"));
 
   // link directories
   this->SetProperty("LINK_DIRECTORIES",
@@ -1421,7 +1364,7 @@ private:
   cmMakefile* Makefile;
   cmGlobalGenerator* GG;
   cmMakefile* CurrentMakefile;
-  cmState::Snapshot Snapshot;
+  cmStateSnapshot Snapshot;
   bool ReportError;
 };
 
@@ -1603,7 +1546,7 @@ void cmMakefile::AddSubDirectory(const std::string& srcPath,
     return;
   }
 
-  cmState::Snapshot newSnapshot =
+  cmStateSnapshot newSnapshot =
     this->GetState()->CreateBuildsystemDirectorySnapshot(this->StateSnapshot);
 
   newSnapshot.GetDirectory().SetCurrentSource(srcPath);
@@ -1708,20 +1651,21 @@ void cmMakefile::AddDefinition(const std::string& name, const char* value)
 
 void cmMakefile::AddCacheDefinition(const std::string& name, const char* value,
                                     const char* doc,
-                                    cmState::CacheEntryType type, bool force)
+                                    cmStateEnums::CacheEntryType type,
+                                    bool force)
 {
   const char* existingValue = this->GetState()->GetInitializedCacheValue(name);
   // must be outside the following if() to keep it alive long enough
   std::string nvalue;
 
-  if (existingValue &&
-      (this->GetState()->GetCacheEntryType(name) == cmState::UNINITIALIZED)) {
+  if (existingValue && (this->GetState()->GetCacheEntryType(name) ==
+                        cmStateEnums::UNINITIALIZED)) {
     // if this is not a force, then use the value from the cache
     // if it is a force, then use the value being passed in
     if (!force) {
       value = existingValue;
     }
-    if (type == cmState::PATH || type == cmState::FILEPATH) {
+    if (type == cmStateEnums::PATH || type == cmStateEnums::FILEPATH) {
       std::vector<std::string>::size_type cc;
       std::vector<std::string> files;
       nvalue = value ? value : "";
@@ -1835,14 +1779,13 @@ void cmMakefile::SetProjectName(std::string const& p)
   this->StateSnapshot.SetProjectName(p);
 }
 
-void cmMakefile::AddGlobalLinkInformation(const std::string& name,
-                                          cmTarget& target)
+void cmMakefile::AddGlobalLinkInformation(cmTarget& target)
 {
   // for these targets do not add anything
   switch (target.GetType()) {
-    case cmState::UTILITY:
-    case cmState::GLOBAL_TARGET:
-    case cmState::INTERFACE_LIBRARY:
+    case cmStateEnums::UTILITY:
+    case cmStateEnums::GLOBAL_TARGET:
+    case cmStateEnums::INTERFACE_LIBRARY:
       return;
     default:;
   }
@@ -1857,13 +1800,34 @@ void cmMakefile::AddGlobalLinkInformation(const std::string& name,
       if (*j->rbegin() == '/') {
         newdir = j->substr(0, j->size() - 1);
       }
-      if (std::find(this->LinkDirectories.begin(), this->LinkDirectories.end(),
-                    newdir) == this->LinkDirectories.end()) {
-        target.AddLinkDirectory(*j);
+      target.AddLinkDirectory(*j);
+    }
+  }
+
+  if (const char* linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
+    std::vector<std::string> linkLibs;
+    cmSystemTools::ExpandListArgument(linkLibsProp, linkLibs);
+
+    for (std::vector<std::string>::iterator j = linkLibs.begin();
+         j != linkLibs.end(); ++j) {
+      std::string libraryName = *j;
+      cmTargetLinkLibraryType libType = GENERAL_LibraryType;
+      if (libraryName == "optimized") {
+        libType = OPTIMIZED_LibraryType;
+        ++j;
+        libraryName = *j;
+      } else if (libraryName == "debug") {
+        libType = DEBUG_LibraryType;
+        ++j;
+        libraryName = *j;
       }
+      // This is equivalent to the target_link_libraries plain signature.
+      target.AddLinkLibrary(*this, libraryName, libType);
+      target.AppendProperty(
+        "INTERFACE_LINK_LIBRARIES",
+        target.GetDebugGeneratorExpressions(libraryName, libType).c_str());
     }
   }
-  target.MergeLinkLibraries(*this, name, this->LinkLibraries);
 }
 
 void cmMakefile::AddAlias(const std::string& lname, std::string const& tgtName)
@@ -1873,18 +1837,15 @@ void cmMakefile::AddAlias(const std::string& lname, std::string const& tgtName)
 }
 
 cmTarget* cmMakefile::AddLibrary(const std::string& lname,
-                                 cmState::TargetType type,
+                                 cmStateEnums::TargetType type,
                                  const std::vector<std::string>& srcs,
                                  bool excludeFromAll)
 {
-  // wrong type ? default to STATIC
-  if ((type != cmState::STATIC_LIBRARY) && (type != cmState::SHARED_LIBRARY) &&
-      (type != cmState::MODULE_LIBRARY) && (type != cmState::OBJECT_LIBRARY) &&
-      (type != cmState::INTERFACE_LIBRARY)) {
-    this->IssueMessage(cmake::INTERNAL_ERROR,
-                       "cmMakefile::AddLibrary given invalid target type.");
-    type = cmState::STATIC_LIBRARY;
-  }
+  assert(type == cmStateEnums::STATIC_LIBRARY ||
+         type == cmStateEnums::SHARED_LIBRARY ||
+         type == cmStateEnums::MODULE_LIBRARY ||
+         type == cmStateEnums::OBJECT_LIBRARY ||
+         type == cmStateEnums::INTERFACE_LIBRARY);
 
   cmTarget* target = this->AddNewTarget(type, lname);
   // Clear its dependencies. Otherwise, dependencies might persist
@@ -1895,7 +1856,7 @@ cmTarget* cmMakefile::AddLibrary(const std::string& lname,
     target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
   }
   target->AddSources(srcs);
-  this->AddGlobalLinkInformation(lname, *target);
+  this->AddGlobalLinkInformation(*target);
   return target;
 }
 
@@ -1903,16 +1864,16 @@ cmTarget* cmMakefile::AddExecutable(const char* exeName,
                                     const std::vector<std::string>& srcs,
                                     bool excludeFromAll)
 {
-  cmTarget* target = this->AddNewTarget(cmState::EXECUTABLE, exeName);
+  cmTarget* target = this->AddNewTarget(cmStateEnums::EXECUTABLE, exeName);
   if (excludeFromAll) {
     target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
   }
   target->AddSources(srcs);
-  this->AddGlobalLinkInformation(exeName, *target);
+  this->AddGlobalLinkInformation(*target);
   return target;
 }
 
-cmTarget* cmMakefile::AddNewTarget(cmState::TargetType type,
+cmTarget* cmMakefile::AddNewTarget(cmStateEnums::TargetType type,
                                    const std::string& name)
 {
   cmTargets::iterator it =
@@ -2090,8 +2051,8 @@ void cmMakefile::ExpandVariablesCMP0019()
   for (cmTargets::iterator l = this->Targets.begin(); l != this->Targets.end();
        ++l) {
     cmTarget& t = l->second;
-    if (t.GetType() == cmState::INTERFACE_LIBRARY ||
-        t.GetType() == cmState::GLOBAL_TARGET) {
+    if (t.GetType() == cmStateEnums::INTERFACE_LIBRARY ||
+        t.GetType() == cmStateEnums::GLOBAL_TARGET) {
       continue;
     }
     includeDirs = t.GetProperty("INCLUDE_DIRECTORIES");
@@ -2125,19 +2086,32 @@ void cmMakefile::ExpandVariablesCMP0019()
       }
     }
   }
-  for (cmTarget::LinkLibraryVectorType::iterator l =
-         this->LinkLibraries.begin();
-       l != this->LinkLibraries.end(); ++l) {
-    if (mightExpandVariablesCMP0019(l->first.c_str())) {
-      std::string orig = l->first;
-      this->ExpandVariablesInString(l->first, true, true);
-      if (pol == cmPolicies::WARN && l->first != orig) {
-        /* clang-format off */
+
+  if (const char* linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
+    std::vector<std::string> linkLibs;
+    cmSystemTools::ExpandListArgument(linkLibsProp, linkLibs);
+
+    for (std::vector<std::string>::iterator l = linkLibs.begin();
+         l != linkLibs.end(); ++l) {
+      std::string libName = *l;
+      if (libName == "optimized") {
+        ++l;
+        libName = *l;
+      } else if (libName == "debug") {
+        ++l;
+        libName = *l;
+      }
+      if (mightExpandVariablesCMP0019(libName.c_str())) {
+        std::string orig = libName;
+        this->ExpandVariablesInString(libName, true, true);
+        if (pol == cmPolicies::WARN && libName != orig) {
+          /* clang-format off */
         w << "Evaluated link library\n"
           << "  " << orig << "\n"
           << "as\n"
-          << "  " << l->first << "\n";
-        /* clang-format on */
+          << "  " << libName << "\n";
+          /* clang-format on */
+        }
       }
     }
   }
@@ -2247,7 +2221,7 @@ const char* cmMakefile::GetRequiredDefinition(const std::string& name) const
   const char* ret = this->GetDefinition(name);
   if (!ret) {
     cmSystemTools::Error("Error required internal CMake variable not "
-                         "set, cmake may be not be built correctly.\n",
+                         "set, cmake may not be built correctly.\n",
                          "Missing variable is:\n", name.c_str());
     return "";
   }
@@ -3190,8 +3164,10 @@ int cmMakefile::TryCompile(const std::string& srcdir,
   cmGlobalGenerator* gg =
     cm.CreateGlobalGenerator(this->GetGlobalGenerator()->GetName());
   if (!gg) {
-    cmSystemTools::Error(
-      "Internal CMake error, TryCompile bad GlobalGenerator");
+    this->IssueMessage(cmake::INTERNAL_ERROR, "Global generator '" +
+                         this->GetGlobalGenerator()->GetName() +
+                         "' could not be created.");
+    cmSystemTools::SetFatalErrorOccured();
     // return to the original directory
     cmSystemTools::ChangeDirectory(cwd);
     this->IsSourceFileTryCompile = false;
@@ -3212,7 +3188,7 @@ int cmMakefile::TryCompile(const std::string& srcdir,
       // Add this before the user-provided CMake arguments in case
       // one of the arguments is -DCMAKE_BUILD_TYPE=...
       cm.AddCacheEntry("CMAKE_BUILD_TYPE", config, "Build configuration",
-                       cmState::STRING);
+                       cmStateEnums::STRING);
     }
   }
   // if cmake args were provided then pass them in
@@ -3248,14 +3224,15 @@ int cmMakefile::TryCompile(const std::string& srcdir,
   gg->EnableLanguagesFromGenerator(this->GetGlobalGenerator(), this);
   if (this->IsOn("CMAKE_SUPPRESS_DEVELOPER_WARNINGS")) {
     cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "TRUE", "",
-                     cmState::INTERNAL);
+                     cmStateEnums::INTERNAL);
   } else {
     cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "FALSE", "",
-                     cmState::INTERNAL);
+                     cmStateEnums::INTERNAL);
   }
   if (cm.Configure() != 0) {
-    cmSystemTools::Error(
-      "Internal CMake error, TryCompile configure of cmake failed");
+    this->IssueMessage(cmake::FATAL_ERROR,
+                       "Failed to configure test project build system.");
+    cmSystemTools::SetFatalErrorOccured();
     // return to the original directory
     cmSystemTools::ChangeDirectory(cwd);
     this->IsSourceFileTryCompile = false;
@@ -3263,8 +3240,9 @@ int cmMakefile::TryCompile(const std::string& srcdir,
   }
 
   if (cm.Generate() != 0) {
-    cmSystemTools::Error(
-      "Internal CMake error, TryCompile generation of cmake failed");
+    this->IssueMessage(cmake::FATAL_ERROR,
+                       "Failed to generate test project build system.");
+    cmSystemTools::SetFatalErrorOccured();
     // return to the original directory
     cmSystemTools::ChangeDirectory(cwd);
     this->IsSourceFileTryCompile = false;
@@ -3384,7 +3362,7 @@ std::string cmMakefile::GetModulesFile(const char* filename) const
   if (!moduleInCMakeModulePath.empty() && !moduleInCMakeRoot.empty()) {
     const char* currentFile = this->GetDefinition("CMAKE_CURRENT_LIST_FILE");
     std::string mods = cmSystemTools::GetCMakeRoot() + "/Modules/";
-    if (currentFile && strncmp(currentFile, mods.c_str(), mods.size()) == 0) {
+    if (currentFile && cmSystemTools::IsSubDirectory(currentFile, mods)) {
       switch (this->GetPolicyStatus(cmPolicies::CMP0017)) {
         case cmPolicies::WARN: {
           std::ostringstream e;
@@ -3655,7 +3633,7 @@ void cmMakefile::AddCMakeDependFilesFromUser()
 std::string cmMakefile::FormatListFileStack() const
 {
   std::vector<std::string> listFiles;
-  cmState::Snapshot snp = this->StateSnapshot;
+  cmStateSnapshot snp = this->StateSnapshot;
   while (snp.IsValid()) {
     listFiles.push_back(snp.GetExecutionListFile());
     snp = snp.GetCallStackParent();
@@ -3718,7 +3696,8 @@ void cmMakefile::RaiseScope(const std::string& var, const char* varDef)
 }
 
 cmTarget* cmMakefile::AddImportedTarget(const std::string& name,
-                                        cmState::TargetType type, bool global)
+                                        cmStateEnums::TargetType type,
+                                        bool global)
 {
   // Create the target.
   CM_AUTO_PTR<cmTarget> target(
@@ -3804,7 +3783,7 @@ bool cmMakefile::EnforceUniqueName(std::string const& name, std::string& msg,
     // The conflict is with a non-imported target.
     // Allow this if the user has requested support.
     cmake* cm = this->GetCMakeInstance();
-    if (isCustom && existing->GetType() == cmState::UTILITY &&
+    if (isCustom && existing->GetType() == cmStateEnums::UTILITY &&
         this != existing->GetMakefile() &&
         cm->GetState()->GetGlobalPropertyAsBool(
           "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
@@ -3818,22 +3797,22 @@ bool cmMakefile::EnforceUniqueName(std::string const& name, std::string& msg,
       << "\" because another target with the same name already exists.  "
       << "The existing target is ";
     switch (existing->GetType()) {
-      case cmState::EXECUTABLE:
+      case cmStateEnums::EXECUTABLE:
         e << "an executable ";
         break;
-      case cmState::STATIC_LIBRARY:
+      case cmStateEnums::STATIC_LIBRARY:
         e << "a static library ";
         break;
-      case cmState::SHARED_LIBRARY:
+      case cmStateEnums::SHARED_LIBRARY:
         e << "a shared library ";
         break;
-      case cmState::MODULE_LIBRARY:
+      case cmStateEnums::MODULE_LIBRARY:
         e << "a module library ";
         break;
-      case cmState::UTILITY:
+      case cmStateEnums::UTILITY:
         e << "a custom target ";
         break;
-      case cmState::INTERFACE_LIBRARY:
+      case cmStateEnums::INTERFACE_LIBRARY:
         e << "an interface library ";
         break;
       default:
@@ -3951,7 +3930,7 @@ void cmMakefile::StoreMatches(cmsys::RegularExpression& re)
   this->MarkVariableAsUsed(nMatchesVariable);
 }
 
-cmState::Snapshot cmMakefile::GetStateSnapshot() const
+cmStateSnapshot cmMakefile::GetStateSnapshot() const
 {
   return this->StateSnapshot;
 }
@@ -3970,10 +3949,8 @@ cmPolicies::PolicyStatus cmMakefile::GetPolicyStatus(
 bool cmMakefile::PolicyOptionalWarningEnabled(std::string const& var)
 {
   // Check for an explicit CMAKE_POLICY_WARNING_CMP<NNNN> setting.
-  if (!var.empty()) {
-    if (const char* val = this->GetDefinition(var)) {
-      return cmSystemTools::IsOn(val);
-    }
+  if (const char* val = this->GetDefinition(var)) {
+    return cmSystemTools::IsOn(val);
   }
   // Enable optional policy warnings with --debug-output, --trace,
   // or --trace-expand.
@@ -4034,7 +4011,7 @@ void cmMakefile::PopPolicy()
 
 void cmMakefile::PopSnapshot(bool reportError)
 {
-  // cmState::Snapshot manages nested policy scopes within it.
+  // cmStateSnapshot manages nested policy scopes within it.
   // Since the scope corresponding to the snapshot is closing,
   // reject any still-open nested policy scopes with an error.
   while (!this->StateSnapshot.CanPopPolicyScope()) {
@@ -4097,7 +4074,7 @@ static const char* const CXX_FEATURES[] = { CM_NULLPTR FOR_EACH_CXX_FEATURE(
 #undef FEATURE_STRING
 
 static const char* const C_STANDARDS[] = { "90", "99", "11" };
-static const char* const CXX_STANDARDS[] = { "98", "11", "14" };
+static const char* const CXX_STANDARDS[] = { "98", "11", "14", "17" };
 
 bool cmMakefile::AddRequiredTargetFeature(cmTarget* target,
                                           const std::string& feature,
@@ -4330,7 +4307,9 @@ bool cmMakefile::HaveCxxStandardAvailable(cmTarget const* target,
   bool needCxx98 = false;
   bool needCxx11 = false;
   bool needCxx14 = false;
-  this->CheckNeededCxxLanguage(feature, needCxx98, needCxx11, needCxx14);
+  bool needCxx17 = false;
+  this->CheckNeededCxxLanguage(feature, needCxx98, needCxx11, needCxx14,
+                               needCxx17);
 
   const char* existingCxxStandard = target->GetProperty("CXX_STANDARD");
   if (!existingCxxStandard) {
@@ -4369,7 +4348,7 @@ bool cmMakefile::HaveCxxStandardAvailable(cmTarget const* target,
 
 void cmMakefile::CheckNeededCxxLanguage(const std::string& feature,
                                         bool& needCxx98, bool& needCxx11,
-                                        bool& needCxx14) const
+                                        bool& needCxx14, bool& needCxx17) const
 {
   if (const char* propCxx98 =
         this->GetDefinition("CMAKE_CXX98_COMPILE_FEATURES")) {
@@ -4389,6 +4368,12 @@ void cmMakefile::CheckNeededCxxLanguage(const std::string& feature,
     cmSystemTools::ExpandListArgument(propCxx14, props);
     needCxx14 = std::find(props.begin(), props.end(), feature) != props.end();
   }
+  if (const char* propCxx17 =
+        this->GetDefinition("CMAKE_CXX17_COMPILE_FEATURES")) {
+    std::vector<std::string> props;
+    cmSystemTools::ExpandListArgument(propCxx17, props);
+    needCxx17 = std::find(props.begin(), props.end(), feature) != props.end();
+  }
 }
 
 bool cmMakefile::AddRequiredTargetCxxFeature(cmTarget* target,
@@ -4398,8 +4383,10 @@ bool cmMakefile::AddRequiredTargetCxxFeature(cmTarget* target,
   bool needCxx98 = false;
   bool needCxx11 = false;
   bool needCxx14 = false;
+  bool needCxx17 = false;
 
-  this->CheckNeededCxxLanguage(feature, needCxx98, needCxx11, needCxx14);
+  this->CheckNeededCxxLanguage(feature, needCxx98, needCxx11, needCxx14,
+                               needCxx17);
 
   const char* existingCxxStandard = target->GetProperty("CXX_STANDARD");
   if (existingCxxStandard) {
@@ -4426,11 +4413,17 @@ bool cmMakefile::AddRequiredTargetCxxFeature(cmTarget* target,
   bool setCxx98 = needCxx98 && !existingCxxStandard;
   bool setCxx11 = needCxx11 && !existingCxxStandard;
   bool setCxx14 = needCxx14 && !existingCxxStandard;
+  bool setCxx17 = needCxx17 && !existingCxxStandard;
 
-  if (needCxx14 && existingCxxStandard &&
+  if (needCxx17 && existingCxxStandard &&
       existingCxxIt < std::find_if(cmArrayBegin(CXX_STANDARDS),
                                    cmArrayEnd(CXX_STANDARDS),
-                                   cmStrCmp("14"))) {
+                                   cmStrCmp("17"))) {
+    setCxx17 = true;
+  } else if (needCxx14 && existingCxxStandard &&
+             existingCxxIt < std::find_if(cmArrayBegin(CXX_STANDARDS),
+                                          cmArrayEnd(CXX_STANDARDS),
+                                          cmStrCmp("14"))) {
     setCxx14 = true;
   } else if (needCxx11 && existingCxxStandard &&
              existingCxxIt < std::find_if(cmArrayBegin(CXX_STANDARDS),
@@ -4444,12 +4437,18 @@ bool cmMakefile::AddRequiredTargetCxxFeature(cmTarget* target,
     setCxx98 = true;
   }
 
-  if (setCxx14) {
+  if (setCxx17) {
+    target->SetProperty("CXX_STANDARD", "17");
+    target->SetProperty("CUDA_STANDARD", "17");
+  } else if (setCxx14) {
     target->SetProperty("CXX_STANDARD", "14");
+    target->SetProperty("CUDA_STANDARD", "14");
   } else if (setCxx11) {
     target->SetProperty("CXX_STANDARD", "11");
+    target->SetProperty("CUDA_STANDARD", "11");
   } else if (setCxx98) {
     target->SetProperty("CXX_STANDARD", "98");
+    target->SetProperty("CUDA_STANDARD", "98");
   }
   return true;
 }
diff --git a/Source/cmMakefile.h b/Source/cmMakefile.h
index 40344ce..9d9e90a 100644
--- a/Source/cmMakefile.h
+++ b/Source/cmMakefile.h
@@ -5,36 +5,28 @@
 
 #include <cmConfigure.h>
 
+#include <cmsys/RegularExpression.hxx>
+#include <map>
+#include <set>
+#include <stack>
+#include <string>
+#include <vector>
+
 #include "cmAlgorithms.h"
 #include "cmListFileCache.h"
 #include "cmNewLineStyle.h"
 #include "cmPolicies.h"
-#include "cmState.h"
+#include "cmStateSnapshot.h"
+#include "cmStateTypes.h"
 #include "cmTarget.h"
-#include "cmTargetLinkLibraryType.h"
+#include "cm_auto_ptr.hxx"
+#include "cm_unordered_map.hxx"
 #include "cmake.h"
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
 #include "cmSourceGroup.h"
 #endif
 
-#include <cm_auto_ptr.hxx>
-#include <cmsys/RegularExpression.hxx>
-
-#include <map>
-#include <set>
-#include <stack>
-#include <string>
-#include <vector>
-
-#if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX_UNORDERED_MAP
-#include <unordered_map>
-#else
-#include <cmsys/hash_map.hxx>
-#endif
-#endif
-
 class cmCommand;
 class cmCompiledGeneratorExpression;
 class cmCustomCommandLines;
@@ -47,6 +39,7 @@ class cmGlobalGenerator;
 class cmInstallGenerator;
 class cmMessenger;
 class cmSourceFile;
+class cmState;
 class cmTest;
 class cmTestGenerator;
 class cmVariableWatch;
@@ -70,7 +63,7 @@ public:
    * Construct an empty makefile.
    */
   cmMakefile(cmGlobalGenerator* globalGenerator,
-             const cmState::Snapshot& snapshot);
+             const cmStateSnapshot& snapshot);
 
   /**
    * Destructor.
@@ -132,7 +125,8 @@ public:
     const std::vector<std::string>& depends,
     const cmCustomCommandLines& commandLines, cmTarget::CustomCommandType type,
     const char* comment, const char* workingDir, bool escapeOldStyle = true,
-    bool uses_terminal = false, const std::string& depfile = "");
+    bool uses_terminal = false, const std::string& depfile = "",
+    bool command_expand_lists = false);
   cmSourceFile* AddCustomCommandToOutput(
     const std::vector<std::string>& outputs,
     const std::vector<std::string>& byproducts,
@@ -140,13 +134,15 @@ public:
     const std::string& main_dependency,
     const cmCustomCommandLines& commandLines, const char* comment,
     const char* workingDir, bool replace = false, bool escapeOldStyle = true,
-    bool uses_terminal = false, const std::string& depfile = "");
+    bool uses_terminal = false, bool command_expand_lists = false,
+    const std::string& depfile = "");
   cmSourceFile* AddCustomCommandToOutput(
     const std::string& output, const std::vector<std::string>& depends,
     const std::string& main_dependency,
     const cmCustomCommandLines& commandLines, const char* comment,
     const char* workingDir, bool replace = false, bool escapeOldStyle = true,
-    bool uses_terminal = false, const std::string& depfile = "");
+    bool uses_terminal = false, bool command_expand_lists = false,
+    const std::string& depfile = "");
   void AddCustomCommandOldStyle(const std::string& target,
                                 const std::vector<std::string>& outputs,
                                 const std::vector<std::string>& depends,
@@ -163,9 +159,10 @@ public:
 
   /** Create a new imported target with the name and type given.  */
   cmTarget* AddImportedTarget(const std::string& name,
-                              cmState::TargetType type, bool global);
+                              cmStateEnums::TargetType type, bool global);
 
-  cmTarget* AddNewTarget(cmState::TargetType type, const std::string& name);
+  cmTarget* AddNewTarget(cmStateEnums::TargetType type,
+                         const std::string& name);
 
   /**
    * Add an executable to the build.
@@ -188,22 +185,15 @@ public:
     const std::string& utilityName, bool excludeFromAll,
     const char* workingDirectory, const std::vector<std::string>& depends,
     const cmCustomCommandLines& commandLines, bool escapeOldStyle = true,
-    const char* comment = CM_NULLPTR, bool uses_terminal = false);
+    const char* comment = CM_NULLPTR, bool uses_terminal = false,
+    bool command_expand_lists = false);
   cmTarget* AddUtilityCommand(
     const std::string& utilityName, bool excludeFromAll,
     const char* workingDirectory, const std::vector<std::string>& byproducts,
     const std::vector<std::string>& depends,
     const cmCustomCommandLines& commandLines, bool escapeOldStyle = true,
-    const char* comment = CM_NULLPTR, bool uses_terminal = false);
-
-  /**
-   * Add a link library to the build.
-   */
-  void AddLinkLibrary(const std::string&);
-  void AddLinkLibrary(const std::string&, cmTargetLinkLibraryType type);
-  void AddLinkLibraryForTarget(const std::string& tgt, const std::string&,
-                               cmTargetLinkLibraryType type);
-  void AddLinkDirectoryForTarget(const std::string& tgt, const std::string& d);
+    const char* comment = CM_NULLPTR, bool uses_terminal = false,
+    bool command_expand_lists = false);
 
   /**
    * Add a subdirectory to the build.
@@ -232,7 +222,7 @@ public:
   void AddDefinition(const std::string& name, const char* value);
   ///! Add a definition to this makefile and the global cmake cache.
   void AddCacheDefinition(const std::string& name, const char* value,
-                          const char* doc, cmState::CacheEntryType type,
+                          const char* doc, cmStateEnums::CacheEntryType type,
                           bool force = false);
 
   /**
@@ -260,7 +250,8 @@ public:
   /**
    * Set the name of the library.
    */
-  cmTarget* AddLibrary(const std::string& libname, cmState::TargetType type,
+  cmTarget* AddLibrary(const std::string& libname,
+                       cmStateEnums::TargetType type,
                        const std::vector<std::string>& srcs,
                        bool excludeFromAll = false);
   void AddAlias(const std::string& libname, const std::string& tgt);
@@ -447,7 +438,7 @@ public:
   /**
    * Get a list of preprocessor define flags.
    */
-  const char* GetDefineFlags() const { return this->DefineFlags.c_str(); }
+  std::string GetDefineFlags() const { return this->DefineFlags; }
 
   /**
    * Make sure CMake can write this file
@@ -760,7 +751,7 @@ public:
   void ClearMatches();
   void StoreMatches(cmsys::RegularExpression& re);
 
-  cmState::Snapshot GetStateSnapshot() const;
+  cmStateSnapshot GetStateSnapshot() const;
 
   const char* GetDefineFlagsCMP0059() const;
 
@@ -781,7 +772,7 @@ public:
 
 protected:
   // add link libraries and directories to the target
-  void AddGlobalLinkInformation(const std::string& name, cmTarget& target);
+  void AddGlobalLinkInformation(cmTarget& target);
 
   // Check for a an unused variable
   void LogUnused(const char* reason, const std::string& name) const;
@@ -790,24 +781,12 @@ protected:
 
   // libraries, classes, and executables
   mutable cmTargets Targets;
-#if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX_UNORDERED_MAP
-  typedef std::unordered_map<std::string, cmTarget*> TargetMap;
-#else
-  typedef cmsys::hash_map<std::string, cmTarget*> TargetMap;
-#endif
-#else
-  typedef std::map<std::string, cmTarget*> TargetMap;
-#endif
   std::map<std::string, std::string> AliasTargets;
   std::vector<cmSourceFile*> SourceFiles;
 
   // Tests
   std::map<std::string, cmTest*> Tests;
 
-  // The link-library paths.  Order matters, use std::vector (not std::set).
-  std::vector<std::string> LinkDirectories;
-
   // The set of include directories that are marked as system include
   // directories.
   std::set<std::string> SystemIncludeDirectories;
@@ -815,8 +794,6 @@ protected:
   std::vector<std::string> ListFiles;
   std::vector<std::string> OutputFiles;
 
-  cmTarget::LinkLibraryVectorType LinkLibraries;
-
   std::vector<cmInstallGenerator*> InstallGenerators;
   std::vector<cmTestGenerator*> TestGenerators;
 
@@ -841,7 +818,7 @@ private:
   cmMakefile(const cmMakefile& mf);
   cmMakefile& operator=(const cmMakefile& mf);
 
-  cmState::Snapshot StateSnapshot;
+  cmStateSnapshot StateSnapshot;
   cmListFileBacktrace Backtrace;
 
   void ReadListFile(cmListFile const& listFile,
@@ -875,6 +852,7 @@ private:
   friend class cmParseFileScope;
 
   std::vector<cmTarget*> ImportedTargetsOwned;
+  typedef CM_UNORDERED_MAP<std::string, cmTarget*> TargetMap;
   TargetMap ImportedTargets;
 
   // Internal policy stack management.
@@ -911,16 +889,8 @@ private:
    */
   cmSourceFile* LinearGetSourceFileWithOutput(const std::string& cname) const;
 
-// A map for fast output to input look up.
-#if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX_UNORDERED_MAP
-  typedef std::unordered_map<std::string, cmSourceFile*> OutputToSourceMap;
-#else
-  typedef cmsys::hash_map<std::string, cmSourceFile*> OutputToSourceMap;
-#endif
-#else
-  typedef std::map<std::string, cmSourceFile*> OutputToSourceMap;
-#endif
+  // A map for fast output to input look up.
+  typedef CM_UNORDERED_MAP<std::string, cmSourceFile*> OutputToSourceMap;
   OutputToSourceMap OutputToSource;
 
   void UpdateOutputToSourceMap(std::vector<std::string> const& outputs,
@@ -940,7 +910,8 @@ private:
   void CheckNeededCLanguage(const std::string& feature, bool& needC90,
                             bool& needC99, bool& needC11) const;
   void CheckNeededCxxLanguage(const std::string& feature, bool& needCxx98,
-                              bool& needCxx11, bool& needCxx14) const;
+                              bool& needCxx11, bool& needCxx14,
+                              bool& needCxx17) const;
 
   bool HaveCStandardAvailable(cmTarget const* target,
                               const std::string& feature) const;
diff --git a/Source/cmMakefileExecutableTargetGenerator.cxx b/Source/cmMakefileExecutableTargetGenerator.cxx
index 4a6990e..b76ddeb 100644
--- a/Source/cmMakefileExecutableTargetGenerator.cxx
+++ b/Source/cmMakefileExecutableTargetGenerator.cxx
@@ -2,21 +2,28 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMakefileExecutableTargetGenerator.h"
 
+#include <sstream>
+#include <string>
+#include <vector>
+
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalUnixMakefileGenerator3.h"
+#include "cmLinkLineComputer.h"
+#include "cmLinkLineDeviceComputer.h"
 #include "cmLocalGenerator.h"
 #include "cmLocalUnixMakefileGenerator3.h"
 #include "cmMakefile.h"
 #include "cmOSXBundleGenerator.h"
 #include "cmOutputConverter.h"
+#include "cmRulePlaceholderExpander.h"
+#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
 #include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
-#include <sstream>
-#include <string>
-#include <vector>
-
 cmMakefileExecutableTargetGenerator::cmMakefileExecutableTargetGenerator(
   cmGeneratorTarget* target)
   : cmMakefileTargetGenerator(target)
@@ -50,6 +57,9 @@ void cmMakefileExecutableTargetGenerator::WriteRuleFiles()
   // write in rules for object files and custom commands
   this->WriteTargetBuildRules();
 
+  // write the device link rules
+  this->WriteDeviceExecutableRule(false);
+
   // write the link rules
   this->WriteExecutableRule(false);
   if (this->GeneratorTarget->NeedRelinkBeforeInstall(this->ConfigName)) {
@@ -71,6 +81,217 @@ void cmMakefileExecutableTargetGenerator::WriteRuleFiles()
   this->CloseFileStreams();
 }
 
+void cmMakefileExecutableTargetGenerator::WriteDeviceExecutableRule(
+  bool relink)
+{
+#ifdef CMAKE_BUILD_WITH_CMAKE
+  const std::string cuda_lang("CUDA");
+  cmGeneratorTarget::LinkClosure const* closure =
+    this->GeneratorTarget->GetLinkClosure(this->ConfigName);
+
+  const bool hasCUDA =
+    (std::find(closure->Languages.begin(), closure->Languages.end(),
+               cuda_lang) != closure->Languages.end());
+  if (!hasCUDA) {
+    return;
+  }
+
+  std::vector<std::string> commands;
+
+  // Build list of dependencies.
+  std::vector<std::string> depends;
+  this->AppendLinkDepends(depends);
+
+  // Get the language to use for linking this library.
+  std::string linkLanguage = "CUDA";
+  std::string const objExt =
+    this->Makefile->GetSafeDefinition("CMAKE_CUDA_OUTPUT_EXTENSION");
+
+  // Get the name of the device object to generate.
+  std::string const targetOutputReal =
+    this->GeneratorTarget->ObjectDirectory + "cmake_device_link" + objExt;
+  this->DeviceLinkObject = targetOutputReal;
+
+  this->NumberOfProgressActions++;
+  if (!this->NoRuleMessages) {
+    cmLocalUnixMakefileGenerator3::EchoProgress progress;
+    this->MakeEchoProgress(progress);
+    // Add the link message.
+    std::string buildEcho = "Linking ";
+    buildEcho += linkLanguage;
+    buildEcho += " device code ";
+    buildEcho += targetOutputReal;
+    this->LocalGenerator->AppendEcho(
+      commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress);
+  }
+
+  // Build a list of compiler flags and linker flags.
+  std::string flags;
+  std::string linkFlags;
+
+  // Add flags to create an executable.
+  // Add symbol export flags if necessary.
+  if (this->GeneratorTarget->IsExecutableWithExports()) {
+    std::string export_flag_var = "CMAKE_EXE_EXPORTS_";
+    export_flag_var += linkLanguage;
+    export_flag_var += "_FLAG";
+    this->LocalGenerator->AppendFlags(
+      linkFlags, this->Makefile->GetDefinition(export_flag_var));
+  }
+
+  this->LocalGenerator->AppendFlags(linkFlags,
+                                    this->LocalGenerator->GetLinkLibsCMP0065(
+                                      linkLanguage, *this->GeneratorTarget));
+
+  // Add language feature flags.
+  this->AddFeatureFlags(flags, linkLanguage);
+
+  this->LocalGenerator->AddArchitectureFlags(flags, this->GeneratorTarget,
+                                             linkLanguage, this->ConfigName);
+
+  // Add target-specific linker flags.
+  this->LocalGenerator->AppendFlags(
+    linkFlags, this->GeneratorTarget->GetProperty("LINK_FLAGS"));
+  std::string linkFlagsConfig = "LINK_FLAGS_";
+  linkFlagsConfig += cmSystemTools::UpperCase(this->ConfigName);
+  this->LocalGenerator->AppendFlags(
+    linkFlags, this->GeneratorTarget->GetProperty(linkFlagsConfig));
+
+  // Construct a list of files associated with this executable that
+  // may need to be cleaned.
+  std::vector<std::string> exeCleanFiles;
+  exeCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
+    this->LocalGenerator->GetCurrentBinaryDirectory(), targetOutputReal));
+
+  // Determine whether a link script will be used.
+  bool useLinkScript = this->GlobalGenerator->GetUseLinkScript();
+
+  // Construct the main link rule.
+  std::vector<std::string> real_link_commands;
+  const std::string linkRuleVar = "CMAKE_CUDA_DEVICE_LINK_EXECUTABLE";
+  const std::string linkRule = this->GetLinkRule(linkRuleVar);
+  std::vector<std::string> commands1;
+  cmSystemTools::ExpandListArgument(linkRule, real_link_commands);
+
+  bool useResponseFileForObjects =
+    this->CheckUseResponseFileForObjects(linkLanguage);
+  bool const useResponseFileForLibs =
+    this->CheckUseResponseFileForLibraries(linkLanguage);
+
+  // Expand the rule variables.
+  {
+    bool useWatcomQuote =
+      this->Makefile->IsOn(linkRuleVar + "_USE_WATCOM_QUOTE");
+
+    // Set path conversion for link script shells.
+    this->LocalGenerator->SetLinkScriptShell(useLinkScript);
+
+    CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+      new cmLinkLineDeviceComputer(
+        this->LocalGenerator,
+        this->LocalGenerator->GetStateSnapshot().GetDirectory()));
+    linkLineComputer->SetForResponse(useResponseFileForLibs);
+    linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
+    linkLineComputer->SetRelink(relink);
+
+    // Collect up flags to link in needed libraries.
+    std::string linkLibs;
+    this->CreateLinkLibs(linkLineComputer.get(), linkLibs,
+                         useResponseFileForLibs, depends);
+
+    // Construct object file lists that may be needed to expand the
+    // rule.
+    std::string buildObjs;
+    this->CreateObjectLists(useLinkScript, false, useResponseFileForObjects,
+                            buildObjs, depends, useWatcomQuote);
+
+    cmRulePlaceholderExpander::RuleVariables vars;
+    std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
+
+    objectDir = this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->MaybeConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir),
+      cmOutputConverter::SHELL);
+
+    cmOutputConverter::OutputFormat output = (useWatcomQuote)
+      ? cmOutputConverter::WATCOMQUOTE
+      : cmOutputConverter::SHELL;
+    std::string target = this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->MaybeConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(), targetOutputReal),
+      output);
+
+    std::string targetFullPathCompilePDB = this->ComputeTargetCompilePDB();
+    std::string targetOutPathCompilePDB =
+      this->LocalGenerator->ConvertToOutputFormat(targetFullPathCompilePDB,
+                                                  cmOutputConverter::SHELL);
+
+    vars.Language = linkLanguage.c_str();
+    vars.Objects = buildObjs.c_str();
+    vars.ObjectDir = objectDir.c_str();
+    vars.Target = target.c_str();
+    vars.LinkLibraries = linkLibs.c_str();
+    vars.Flags = flags.c_str();
+    vars.LinkFlags = linkFlags.c_str();
+    vars.TargetCompilePDB = targetOutPathCompilePDB.c_str();
+
+    std::string launcher;
+
+    const char* val = this->LocalGenerator->GetRuleLauncher(
+      this->GeneratorTarget, "RULE_LAUNCH_LINK");
+    if (val && *val) {
+      launcher = val;
+      launcher += " ";
+    }
+
+    CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+      this->LocalGenerator->CreateRulePlaceholderExpander());
+
+    // Expand placeholders in the commands.
+    rulePlaceholderExpander->SetTargetImpLib(targetOutputReal);
+    for (std::vector<std::string>::iterator i = real_link_commands.begin();
+         i != real_link_commands.end(); ++i) {
+      *i = launcher + *i;
+      rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i,
+                                                   vars);
+    }
+
+    // Restore path conversion to normal shells.
+    this->LocalGenerator->SetLinkScriptShell(false);
+  }
+
+  // Optionally convert the build rule to use a script to avoid long
+  // command lines in the make shell.
+  if (useLinkScript) {
+    // Use a link script.
+    const char* name = (relink ? "drelink.txt" : "dlink.txt");
+    this->CreateLinkScript(name, real_link_commands, commands1, depends);
+  } else {
+    // No link script.  Just use the link rule directly.
+    commands1 = real_link_commands;
+  }
+  this->LocalGenerator->CreateCDCommand(
+    commands1, this->Makefile->GetCurrentBinaryDirectory(),
+    this->LocalGenerator->GetBinaryDirectory());
+  commands.insert(commands.end(), commands1.begin(), commands1.end());
+  commands1.clear();
+
+  // Write the build rule.
+  this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+                                      targetOutputReal, depends, commands,
+                                      false);
+
+  // Write the main driver rule to build everything in this target.
+  this->WriteTargetDriverRule(targetOutputReal, relink);
+
+  // Clean all the possible executable names and symlinks.
+  this->CleanFiles.insert(this->CleanFiles.end(), exeCleanFiles.begin(),
+                          exeCleanFiles.end());
+#else
+  static_cast<void>(relink);
+#endif
+}
+
 void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
 {
   std::vector<std::string> commands;
@@ -78,6 +299,9 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
   // Build list of dependencies.
   std::vector<std::string> depends;
   this->AppendLinkDepends(depends);
+  if (!this->DeviceLinkObject.empty()) {
+    depends.push_back(this->DeviceLinkObject);
+  }
 
   // Get the name of the executable to generate.
   std::string targetName;
@@ -130,16 +354,16 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
     targetFullPathPDB, cmOutputConverter::SHELL);
   // Convert to the output path to use in constructing commands.
   std::string targetOutPath = this->LocalGenerator->ConvertToOutputFormat(
-    this->LocalGenerator->ConvertToRelativePath(
+    this->LocalGenerator->MaybeConvertToRelativePath(
       this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPath),
     cmOutputConverter::SHELL);
   std::string targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat(
-    this->LocalGenerator->ConvertToRelativePath(
+    this->LocalGenerator->MaybeConvertToRelativePath(
       this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal),
     cmOutputConverter::SHELL);
   std::string targetOutPathImport =
     this->LocalGenerator->ConvertToOutputFormat(
-      this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->MaybeConvertToRelativePath(
         this->LocalGenerator->GetCurrentBinaryDirectory(),
         targetFullPathImport),
       cmOutputConverter::SHELL);
@@ -192,6 +416,11 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
     this->LocalGenerator->AppendFlags(
       linkFlags, this->Makefile->GetDefinition(export_flag_var));
   }
+
+  this->LocalGenerator->AppendFlags(linkFlags,
+                                    this->LocalGenerator->GetLinkLibsCMP0065(
+                                      linkLanguage, *this->GeneratorTarget));
+
   if (this->GeneratorTarget->GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
     this->LocalGenerator->AppendFlags(linkFlags, " -Wl,--no-as-needed");
   }
@@ -210,32 +439,39 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
   this->LocalGenerator->AppendFlags(
     linkFlags, this->GeneratorTarget->GetProperty(linkFlagsConfig));
 
-  this->AddModuleDefinitionFlag(linkFlags);
+  {
+    CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+      this->CreateLinkLineComputer(
+        this->LocalGenerator,
+        this->LocalGenerator->GetStateSnapshot().GetDirectory()));
+
+    this->AddModuleDefinitionFlag(linkLineComputer.get(), linkFlags);
+  }
 
   // Construct a list of files associated with this executable that
   // may need to be cleaned.
   std::vector<std::string> exeCleanFiles;
-  exeCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+  exeCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
     this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPath));
 #ifdef _WIN32
   // There may be a manifest file for this target.  Add it to the
   // clean set just in case.
-  exeCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+  exeCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
     this->LocalGenerator->GetCurrentBinaryDirectory(),
     (targetFullPath + ".manifest").c_str()));
 #endif
   if (targetNameReal != targetName) {
-    exeCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+    exeCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
       this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal));
   }
   if (!targetNameImport.empty()) {
-    exeCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+    exeCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
       this->LocalGenerator->GetCurrentBinaryDirectory(),
       targetFullPathImport));
     std::string implib;
     if (this->GeneratorTarget->GetImplibGNUtoMS(targetFullPathImport,
                                                 implib)) {
-      exeCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+      exeCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
         this->LocalGenerator->GetCurrentBinaryDirectory(), implib));
     }
   }
@@ -243,7 +479,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
   // List the PDB for cleaning only when the whole target is
   // cleaned.  We do not want to delete the .pdb file just before
   // linking the target.
-  this->CleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+  this->CleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
     this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathPDB));
 
   // Add the pre-build and pre-link rules building but not when relinking.
@@ -291,16 +527,32 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
     // Set path conversion for link script shells.
     this->LocalGenerator->SetLinkScriptShell(useLinkScript);
 
+    CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+      this->CreateLinkLineComputer(
+        this->LocalGenerator,
+        this->LocalGenerator->GetStateSnapshot().GetDirectory()));
+    linkLineComputer->SetForResponse(useResponseFileForLibs);
+    linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
+    linkLineComputer->SetRelink(relink);
+
     // Collect up flags to link in needed libraries.
     std::string linkLibs;
-    this->CreateLinkLibs(linkLibs, relink, useResponseFileForLibs, depends,
-                         useWatcomQuote);
+    this->CreateLinkLibs(linkLineComputer.get(), linkLibs,
+                         useResponseFileForLibs, depends);
 
     // Construct object file lists that may be needed to expand the
     // rule.
     std::string buildObjs;
     this->CreateObjectLists(useLinkScript, false, useResponseFileForObjects,
                             buildObjs, depends, useWatcomQuote);
+    if (!this->DeviceLinkObject.empty()) {
+      buildObjs += " " +
+        this->LocalGenerator->ConvertToOutputFormat(
+          this->LocalGenerator->MaybeConvertToRelativePath(
+            this->LocalGenerator->GetCurrentBinaryDirectory(),
+            this->DeviceLinkObject),
+          cmOutputConverter::SHELL);
+    }
 
     // maybe create .def file from list of objects
     if (this->GeneratorTarget->IsExecutableWithExports() &&
@@ -310,15 +562,16 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
 
     std::string manifests = this->GetManifests();
 
-    cmLocalGenerator::RuleVariables vars;
-    vars.RuleLauncher = "RULE_LAUNCH_LINK";
-    vars.CMTarget = this->GeneratorTarget;
+    cmRulePlaceholderExpander::RuleVariables vars;
+    vars.CMTargetName = this->GeneratorTarget->GetName().c_str();
+    vars.CMTargetType =
+      cmState::GetTargetTypeName(this->GeneratorTarget->GetType());
     vars.Language = linkLanguage.c_str();
     vars.Objects = buildObjs.c_str();
     std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
 
     objectDir = this->LocalGenerator->ConvertToOutputFormat(
-      this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->MaybeConvertToRelativePath(
         this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir),
       cmOutputConverter::SHELL);
     vars.ObjectDir = objectDir.c_str();
@@ -326,7 +579,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
       ? cmOutputConverter::WATCOMQUOTE
       : cmOutputConverter::SHELL;
     std::string target = this->LocalGenerator->ConvertToOutputFormat(
-      this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->MaybeConvertToRelativePath(
         this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal),
       output);
     vars.Target = target.c_str();
@@ -362,13 +615,26 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
       real_link_commands.push_back(cmakeCommand);
     }
 
+    std::string launcher;
+
+    const char* val = this->LocalGenerator->GetRuleLauncher(
+      this->GeneratorTarget, "RULE_LAUNCH_LINK");
+    if (val && *val) {
+      launcher = val;
+      launcher += " ";
+    }
+
+    CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+      this->LocalGenerator->CreateRulePlaceholderExpander());
+
     // Expand placeholders in the commands.
-    this->LocalGenerator->TargetImplib = targetOutPathImport;
+    rulePlaceholderExpander->SetTargetImpLib(targetOutPathImport);
     for (std::vector<std::string>::iterator i = real_link_commands.begin();
          i != real_link_commands.end(); ++i) {
-      this->LocalGenerator->ExpandRuleVariables(*i, vars);
+      *i = launcher + *i;
+      rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i,
+                                                   vars);
     }
-    this->LocalGenerator->TargetImplib = "";
 
     // Restore path conversion to normal shells.
     this->LocalGenerator->SetLinkScriptShell(false);
diff --git a/Source/cmMakefileExecutableTargetGenerator.h b/Source/cmMakefileExecutableTargetGenerator.h
index 36cfe40..642182b 100644
--- a/Source/cmMakefileExecutableTargetGenerator.h
+++ b/Source/cmMakefileExecutableTargetGenerator.h
@@ -21,6 +21,10 @@ public:
 
 protected:
   virtual void WriteExecutableRule(bool relink);
+  virtual void WriteDeviceExecutableRule(bool relink);
+
+private:
+  std::string DeviceLinkObject;
 };
 
 #endif
diff --git a/Source/cmMakefileLibraryTargetGenerator.cxx b/Source/cmMakefileLibraryTargetGenerator.cxx
index 2b1d7cc..ff8b604 100644
--- a/Source/cmMakefileLibraryTargetGenerator.cxx
+++ b/Source/cmMakefileLibraryTargetGenerator.cxx
@@ -2,27 +2,36 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMakefileLibraryTargetGenerator.h"
 
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <sstream>
+#include <vector>
+
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalUnixMakefileGenerator3.h"
+#include "cmLinkLineComputer.h"
+#include "cmLinkLineDeviceComputer.h"
 #include "cmLocalGenerator.h"
 #include "cmLocalUnixMakefileGenerator3.h"
 #include "cmMakefile.h"
 #include "cmOSXBundleGenerator.h"
 #include "cmOutputConverter.h"
+#include "cmRulePlaceholderExpander.h"
 #include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
-#include <sstream>
-#include <vector>
-
 cmMakefileLibraryTargetGenerator::cmMakefileLibraryTargetGenerator(
   cmGeneratorTarget* target)
   : cmMakefileTargetGenerator(target)
 {
   this->CustomCommandDriver = OnDepends;
-  if (this->GeneratorTarget->GetType() != cmState::INTERFACE_LIBRARY) {
+  if (this->GeneratorTarget->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
     this->GeneratorTarget->GetLibraryNames(
       this->TargetNameOut, this->TargetNameSO, this->TargetNameReal,
       this->TargetNameImport, this->TargetNamePDB, this->ConfigName);
@@ -55,24 +64,24 @@ void cmMakefileLibraryTargetGenerator::WriteRuleFiles()
   // write the link rules
   // Write the rule for this target type.
   switch (this->GeneratorTarget->GetType()) {
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
       this->WriteStaticLibraryRules();
       break;
-    case cmState::SHARED_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
       this->WriteSharedLibraryRules(false);
       if (this->GeneratorTarget->NeedRelinkBeforeInstall(this->ConfigName)) {
         // Write rules to link an installable version of the target.
         this->WriteSharedLibraryRules(true);
       }
       break;
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       this->WriteModuleLibraryRules(false);
       if (this->GeneratorTarget->NeedRelinkBeforeInstall(this->ConfigName)) {
         // Write rules to link an installable version of the target.
         this->WriteModuleLibraryRules(true);
       }
       break;
-    case cmState::OBJECT_LIBRARY:
+    case cmStateEnums::OBJECT_LIBRARY:
       this->WriteObjectLibraryRules();
       break;
     default:
@@ -143,6 +152,24 @@ void cmMakefileLibraryTargetGenerator::WriteSharedLibraryRules(bool relink)
     this->WriteFrameworkRules(relink);
     return;
   }
+
+  if (!relink) {
+    const std::string cuda_lang("CUDA");
+    cmGeneratorTarget::LinkClosure const* closure =
+      this->GeneratorTarget->GetLinkClosure(this->ConfigName);
+
+    const bool hasCUDA =
+      (std::find(closure->Languages.begin(), closure->Languages.end(),
+                 cuda_lang) != closure->Languages.end());
+    if (hasCUDA) {
+      std::string linkRuleVar = "CMAKE_CUDA_DEVICE_LINK_LIBRARY";
+      std::string extraFlags;
+      this->LocalGenerator->AppendFlags(
+        extraFlags, this->GeneratorTarget->GetProperty("LINK_FLAGS"));
+      this->WriteDeviceLibraryRules(linkRuleVar, extraFlags, relink);
+    }
+  }
+
   std::string linkLanguage =
     this->GeneratorTarget->GetLinkerLanguage(this->ConfigName);
   std::string linkRuleVar = "CMAKE_";
@@ -159,7 +186,13 @@ void cmMakefileLibraryTargetGenerator::WriteSharedLibraryRules(bool relink)
 
   this->LocalGenerator->AddConfigVariableFlags(
     extraFlags, "CMAKE_SHARED_LINKER_FLAGS", this->ConfigName);
-  this->AddModuleDefinitionFlag(extraFlags);
+
+  CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+    this->CreateLinkLineComputer(
+      this->LocalGenerator,
+      this->LocalGenerator->GetStateSnapshot().GetDirectory()));
+
+  this->AddModuleDefinitionFlag(linkLineComputer.get(), extraFlags);
 
   if (this->GeneratorTarget->GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
     this->LocalGenerator->AppendFlags(extraFlags, " -Wl,--no-as-needed");
@@ -169,6 +202,24 @@ void cmMakefileLibraryTargetGenerator::WriteSharedLibraryRules(bool relink)
 
 void cmMakefileLibraryTargetGenerator::WriteModuleLibraryRules(bool relink)
 {
+
+  if (!relink) {
+    const std::string cuda_lang("CUDA");
+    cmGeneratorTarget::LinkClosure const* closure =
+      this->GeneratorTarget->GetLinkClosure(this->ConfigName);
+
+    const bool hasCUDA =
+      (std::find(closure->Languages.begin(), closure->Languages.end(),
+                 cuda_lang) != closure->Languages.end());
+    if (hasCUDA) {
+      std::string linkRuleVar = "CMAKE_CUDA_DEVICE_LINK_LIBRARY";
+      std::string extraFlags;
+      this->LocalGenerator->AppendFlags(
+        extraFlags, this->GeneratorTarget->GetProperty("LINK_FLAGS"));
+      this->WriteDeviceLibraryRules(linkRuleVar, extraFlags, relink);
+    }
+  }
+
   std::string linkLanguage =
     this->GeneratorTarget->GetLinkerLanguage(this->ConfigName);
   std::string linkRuleVar = "CMAKE_";
@@ -184,7 +235,13 @@ void cmMakefileLibraryTargetGenerator::WriteModuleLibraryRules(bool relink)
     extraFlags, this->GeneratorTarget->GetProperty(linkFlagsConfig));
   this->LocalGenerator->AddConfigVariableFlags(
     extraFlags, "CMAKE_MODULE_LINKER_FLAGS", this->ConfigName);
-  this->AddModuleDefinitionFlag(extraFlags);
+
+  CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+    this->CreateLinkLineComputer(
+      this->LocalGenerator,
+      this->LocalGenerator->GetStateSnapshot().GetDirectory()));
+
+  this->AddModuleDefinitionFlag(linkLineComputer.get(), extraFlags);
 
   this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
 }
@@ -210,6 +267,188 @@ void cmMakefileLibraryTargetGenerator::WriteFrameworkRules(bool relink)
   this->WriteLibraryRules(linkRuleVar, extraFlags, relink);
 }
 
+void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules(
+  const std::string& linkRuleVar, const std::string& extraFlags, bool relink)
+{
+#ifdef CMAKE_BUILD_WITH_CMAKE
+  // TODO: Merge the methods that call this method to avoid
+  // code duplication.
+  std::vector<std::string> commands;
+
+  // Build list of dependencies.
+  std::vector<std::string> depends;
+  this->AppendLinkDepends(depends);
+
+  // Get the language to use for linking this library.
+  std::string linkLanguage = "CUDA";
+  std::string const objExt =
+    this->Makefile->GetSafeDefinition("CMAKE_CUDA_OUTPUT_EXTENSION");
+
+  // Create set of linking flags.
+  std::string linkFlags;
+  this->LocalGenerator->AppendFlags(linkFlags, extraFlags);
+
+  // Get the name of the device object to generate.
+  std::string const targetOutputReal =
+    this->GeneratorTarget->ObjectDirectory + "cmake_device_link" + objExt;
+  this->DeviceLinkObject = targetOutputReal;
+
+  this->NumberOfProgressActions++;
+  if (!this->NoRuleMessages) {
+    cmLocalUnixMakefileGenerator3::EchoProgress progress;
+    this->MakeEchoProgress(progress);
+    // Add the link message.
+    std::string buildEcho = "Linking " + linkLanguage + " device code";
+    buildEcho += targetOutputReal;
+    this->LocalGenerator->AppendEcho(
+      commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress);
+  }
+  // Clean files associated with this library.
+  std::vector<std::string> libCleanFiles;
+  libCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
+    this->LocalGenerator->GetCurrentBinaryDirectory(), targetOutputReal));
+
+  // Determine whether a link script will be used.
+  bool useLinkScript = this->GlobalGenerator->GetUseLinkScript();
+
+  bool useResponseFileForObjects =
+    this->CheckUseResponseFileForObjects(linkLanguage);
+  bool const useResponseFileForLibs =
+    this->CheckUseResponseFileForLibraries(linkLanguage);
+
+  cmRulePlaceholderExpander::RuleVariables vars;
+  vars.Language = linkLanguage.c_str();
+
+  // Expand the rule variables.
+  std::vector<std::string> real_link_commands;
+  {
+    bool useWatcomQuote =
+      this->Makefile->IsOn(linkRuleVar + "_USE_WATCOM_QUOTE");
+
+    // Set path conversion for link script shells.
+    this->LocalGenerator->SetLinkScriptShell(useLinkScript);
+
+    // Collect up flags to link in needed libraries.
+    std::string linkLibs;
+    if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
+
+      CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+        new cmLinkLineDeviceComputer(
+          this->LocalGenerator,
+          this->LocalGenerator->GetStateSnapshot().GetDirectory()));
+      linkLineComputer->SetForResponse(useResponseFileForLibs);
+      linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
+      linkLineComputer->SetRelink(relink);
+
+      this->CreateLinkLibs(linkLineComputer.get(), linkLibs,
+                           useResponseFileForLibs, depends);
+    }
+
+    // Construct object file lists that may be needed to expand the
+    // rule.
+    std::string buildObjs;
+    this->CreateObjectLists(useLinkScript, false, // useArchiveRules
+                            useResponseFileForObjects, buildObjs, depends,
+                            useWatcomQuote);
+
+    cmOutputConverter::OutputFormat output = (useWatcomQuote)
+      ? cmOutputConverter::WATCOMQUOTE
+      : cmOutputConverter::SHELL;
+
+    std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
+    objectDir = this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->MaybeConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir),
+      cmOutputConverter::SHELL);
+
+    std::string target = this->LocalGenerator->ConvertToOutputFormat(
+      this->LocalGenerator->MaybeConvertToRelativePath(
+        this->LocalGenerator->GetCurrentBinaryDirectory(), targetOutputReal),
+      output);
+
+    std::string targetFullPathCompilePDB = this->ComputeTargetCompilePDB();
+    std::string targetOutPathCompilePDB =
+      this->LocalGenerator->ConvertToOutputFormat(targetFullPathCompilePDB,
+                                                  cmOutputConverter::SHELL);
+
+    vars.Objects = buildObjs.c_str();
+    vars.ObjectDir = objectDir.c_str();
+    vars.Target = target.c_str();
+    vars.LinkLibraries = linkLibs.c_str();
+    vars.ObjectsQuoted = buildObjs.c_str();
+    vars.LinkFlags = linkFlags.c_str();
+    vars.TargetCompilePDB = targetOutPathCompilePDB.c_str();
+
+    // Add language feature flags.
+    std::string langFlags;
+    this->AddFeatureFlags(langFlags, linkLanguage);
+
+    vars.LanguageCompileFlags = langFlags.c_str();
+
+    std::string launcher;
+    const char* val = this->LocalGenerator->GetRuleLauncher(
+      this->GeneratorTarget, "RULE_LAUNCH_LINK");
+    if (val && *val) {
+      launcher = val;
+      launcher += " ";
+    }
+
+    CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+      this->LocalGenerator->CreateRulePlaceholderExpander());
+
+    // Construct the main link rule and expand placeholders.
+    rulePlaceholderExpander->SetTargetImpLib(targetOutputReal);
+    std::string linkRule = this->GetLinkRule(linkRuleVar);
+    cmSystemTools::ExpandListArgument(linkRule, real_link_commands);
+
+    // Expand placeholders.
+    for (std::vector<std::string>::iterator i = real_link_commands.begin();
+         i != real_link_commands.end(); ++i) {
+      *i = launcher + *i;
+      rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i,
+                                                   vars);
+    }
+    // Restore path conversion to normal shells.
+    this->LocalGenerator->SetLinkScriptShell(false);
+
+    // Clean all the possible library names and symlinks.
+    this->CleanFiles.insert(this->CleanFiles.end(), libCleanFiles.begin(),
+                            libCleanFiles.end());
+  }
+
+  std::vector<std::string> commands1;
+  // Optionally convert the build rule to use a script to avoid long
+  // command lines in the make shell.
+  if (useLinkScript) {
+    // Use a link script.
+    const char* name = (relink ? "drelink.txt" : "dlink.txt");
+    this->CreateLinkScript(name, real_link_commands, commands1, depends);
+  } else {
+    // No link script.  Just use the link rule directly.
+    commands1 = real_link_commands;
+  }
+  this->LocalGenerator->CreateCDCommand(
+    commands1, this->Makefile->GetCurrentBinaryDirectory(),
+    this->LocalGenerator->GetBinaryDirectory());
+  commands.insert(commands.end(), commands1.begin(), commands1.end());
+  commands1.clear();
+
+  // Compute the list of outputs.
+  std::vector<std::string> outputs(1, targetOutputReal);
+
+  // Write the build rule.
+  this->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR, outputs, depends,
+                      commands, false);
+
+  // Write the main driver rule to build everything in this target.
+  this->WriteTargetDriverRule(targetOutputReal, relink);
+#else
+  static_cast<void>(linkRuleVar);
+  static_cast<void>(extraFlags);
+  static_cast<void>(relink);
+#endif
+}
+
 void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
   const std::string& linkRuleVar, const std::string& extraFlags, bool relink)
 {
@@ -220,6 +459,9 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
   // Build list of dependencies.
   std::vector<std::string> depends;
   this->AppendLinkDepends(depends);
+  if (!this->DeviceLinkObject.empty()) {
+    depends.push_back(this->DeviceLinkObject);
+  }
 
   // Get the language to use for linking this library.
   std::string linkLanguage =
@@ -237,8 +479,8 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
   this->LocalGenerator->AppendFlags(linkFlags, extraFlags);
 
   // Add OSX version flags, if any.
-  if (this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY ||
-      this->GeneratorTarget->GetType() == cmState::MODULE_LIBRARY) {
+  if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
+      this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
     this->AppendOSXVerFlag(linkFlags, linkLanguage, "COMPATIBILITY", true);
     this->AppendOSXVerFlag(linkFlags, linkLanguage, "CURRENT", false);
   }
@@ -305,20 +547,20 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
     targetFullPathPDB, cmOutputConverter::SHELL);
 
   std::string targetOutPath = this->LocalGenerator->ConvertToOutputFormat(
-    this->LocalGenerator->ConvertToRelativePath(
+    this->LocalGenerator->MaybeConvertToRelativePath(
       this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPath),
     cmOutputConverter::SHELL);
   std::string targetOutPathSO = this->LocalGenerator->ConvertToOutputFormat(
-    this->LocalGenerator->ConvertToRelativePath(
+    this->LocalGenerator->MaybeConvertToRelativePath(
       this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathSO),
     cmOutputConverter::SHELL);
   std::string targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat(
-    this->LocalGenerator->ConvertToRelativePath(
+    this->LocalGenerator->MaybeConvertToRelativePath(
       this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal),
     cmOutputConverter::SHELL);
   std::string targetOutPathImport =
     this->LocalGenerator->ConvertToOutputFormat(
-      this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->MaybeConvertToRelativePath(
         this->LocalGenerator->GetCurrentBinaryDirectory(),
         targetFullPathImport),
       cmOutputConverter::SHELL);
@@ -331,13 +573,13 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
     std::string buildEcho = "Linking ";
     buildEcho += linkLanguage;
     switch (this->GeneratorTarget->GetType()) {
-      case cmState::STATIC_LIBRARY:
+      case cmStateEnums::STATIC_LIBRARY:
         buildEcho += " static library ";
         break;
-      case cmState::SHARED_LIBRARY:
+      case cmStateEnums::SHARED_LIBRARY:
         buildEcho += " shared library ";
         break;
-      case cmState::MODULE_LIBRARY:
+      case cmStateEnums::MODULE_LIBRARY:
         if (this->GeneratorTarget->IsCFBundleOnApple()) {
           buildEcho += " CFBundle";
         }
@@ -352,38 +594,40 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
       commands, buildEcho, cmLocalUnixMakefileGenerator3::EchoLink, &progress);
   }
 
-  const char* forbiddenFlagVar = CM_NULLPTR;
-  switch (this->GeneratorTarget->GetType()) {
-    case cmState::SHARED_LIBRARY:
-      forbiddenFlagVar = "_CREATE_SHARED_LIBRARY_FORBIDDEN_FLAGS";
-      break;
-    case cmState::MODULE_LIBRARY:
-      forbiddenFlagVar = "_CREATE_SHARED_MODULE_FORBIDDEN_FLAGS";
-      break;
-    default:
-      break;
-  }
-
   // Clean files associated with this library.
   std::vector<std::string> libCleanFiles;
-  libCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
-    this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPath));
-  if (targetNameReal != targetName) {
-    libCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
-      this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal));
+  libCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
+    this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal));
+
+  std::vector<std::string> commands1;
+  // Add a command to remove any existing files for this library.
+  // for static libs only
+  if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
+    this->LocalGenerator->AppendCleanCommand(commands1, libCleanFiles,
+                                             this->GeneratorTarget, "target");
+    this->LocalGenerator->CreateCDCommand(
+      commands1, this->Makefile->GetCurrentBinaryDirectory(),
+      this->LocalGenerator->GetBinaryDirectory());
+    commands.insert(commands.end(), commands1.begin(), commands1.end());
+    commands1.clear();
+  }
+
+  if (targetName != targetNameReal) {
+    libCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
+      this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPath));
   }
-  if (targetNameSO != targetName && targetNameSO != targetNameReal) {
-    libCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+  if (targetNameSO != targetNameReal && targetNameSO != targetName) {
+    libCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
       this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathSO));
   }
   if (!targetNameImport.empty()) {
-    libCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+    libCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
       this->LocalGenerator->GetCurrentBinaryDirectory(),
       targetFullPathImport));
     std::string implib;
     if (this->GeneratorTarget->GetImplibGNUtoMS(targetFullPathImport,
                                                 implib)) {
-      libCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+      libCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
         this->LocalGenerator->GetCurrentBinaryDirectory(), implib));
     }
   }
@@ -391,32 +635,19 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
   // List the PDB for cleaning only when the whole target is
   // cleaned.  We do not want to delete the .pdb file just before
   // linking the target.
-  this->CleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+  this->CleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
     this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathPDB));
 
 #ifdef _WIN32
   // There may be a manifest file for this target.  Add it to the
   // clean set just in case.
-  if (this->GeneratorTarget->GetType() != cmState::STATIC_LIBRARY) {
-    libCleanFiles.push_back(this->LocalGenerator->ConvertToRelativePath(
+  if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
+    libCleanFiles.push_back(this->LocalGenerator->MaybeConvertToRelativePath(
       this->LocalGenerator->GetCurrentBinaryDirectory(),
       (targetFullPath + ".manifest").c_str()));
   }
 #endif
 
-  std::vector<std::string> commands1;
-  // Add a command to remove any existing files for this library.
-  // for static libs only
-  if (this->GeneratorTarget->GetType() == cmState::STATIC_LIBRARY) {
-    this->LocalGenerator->AppendCleanCommand(commands1, libCleanFiles,
-                                             this->GeneratorTarget, "target");
-    this->LocalGenerator->CreateCDCommand(
-      commands1, this->Makefile->GetCurrentBinaryDirectory(),
-      this->LocalGenerator->GetBinaryDirectory());
-    commands.insert(commands.end(), commands1.begin(), commands1.end());
-    commands1.clear();
-  }
-
   // Add the pre-build and pre-link rules building but not when relinking.
   if (!relink) {
     this->LocalGenerator->AppendCustomCommands(
@@ -441,7 +672,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
   std::vector<std::string> archiveAppendCommands;
   std::vector<std::string> archiveFinishCommands;
   std::string::size_type archiveCommandLimit = std::string::npos;
-  if (this->GeneratorTarget->GetType() == cmState::STATIC_LIBRARY) {
+  if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
     haveStaticLibraryRule = this->Makefile->IsDefinitionSet(linkRuleVar);
     std::string arCreateVar = "CMAKE_";
     arCreateVar += linkLanguage;
@@ -490,9 +721,18 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
 
     // Collect up flags to link in needed libraries.
     std::string linkLibs;
-    if (this->GeneratorTarget->GetType() != cmState::STATIC_LIBRARY) {
-      this->CreateLinkLibs(linkLibs, relink, useResponseFileForLibs, depends,
-                           useWatcomQuote);
+    if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
+
+      CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+        this->CreateLinkLineComputer(
+          this->LocalGenerator,
+          this->LocalGenerator->GetStateSnapshot().GetDirectory()));
+      linkLineComputer->SetForResponse(useResponseFileForLibs);
+      linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
+      linkLineComputer->SetRelink(relink);
+
+      this->CreateLinkLibs(linkLineComputer.get(), linkLibs,
+                           useResponseFileForLibs, depends);
     }
 
     // Construct object file lists that may be needed to expand the
@@ -501,16 +741,24 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
     this->CreateObjectLists(useLinkScript, useArchiveRules,
                             useResponseFileForObjects, buildObjs, depends,
                             useWatcomQuote);
+    if (!this->DeviceLinkObject.empty()) {
+      buildObjs += " " +
+        this->LocalGenerator->ConvertToOutputFormat(
+          this->LocalGenerator->MaybeConvertToRelativePath(
+            this->LocalGenerator->GetCurrentBinaryDirectory(),
+            this->DeviceLinkObject),
+          cmOutputConverter::SHELL);
+    }
 
     // maybe create .def file from list of objects
-    if (this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY &&
+    if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY &&
         this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
       this->GenDefFile(real_link_commands, linkFlags);
     }
 
     std::string manifests = this->GetManifests();
 
-    cmLocalGenerator::RuleVariables vars;
+    cmRulePlaceholderExpander::RuleVariables vars;
     vars.TargetPDB = targetOutPathPDB.c_str();
 
     // Setup the target version.
@@ -530,14 +778,15 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
     vars.TargetVersionMajor = targetVersionMajor.c_str();
     vars.TargetVersionMinor = targetVersionMinor.c_str();
 
-    vars.RuleLauncher = "RULE_LAUNCH_LINK";
-    vars.CMTarget = this->GeneratorTarget;
+    vars.CMTargetName = this->GeneratorTarget->GetName().c_str();
+    vars.CMTargetType =
+      cmState::GetTargetTypeName(this->GeneratorTarget->GetType());
     vars.Language = linkLanguage.c_str();
     vars.Objects = buildObjs.c_str();
     std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
 
     objectDir = this->LocalGenerator->ConvertToOutputFormat(
-      this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->MaybeConvertToRelativePath(
         this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir),
       cmOutputConverter::SHELL);
 
@@ -546,7 +795,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
       ? cmOutputConverter::WATCOMQUOTE
       : cmOutputConverter::SHELL;
     std::string target = this->LocalGenerator->ConvertToOutputFormat(
-      this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->MaybeConvertToRelativePath(
         this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal),
       output);
     vars.Target = target.c_str();
@@ -562,7 +811,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
 
     // Compute the directory portion of the install_name setting.
     std::string install_name_dir;
-    if (this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY) {
+    if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY) {
       // Get the install_name directory for the build tree.
       install_name_dir =
         this->GeneratorTarget->GetInstallNameDirForBuildTree(this->ConfigName);
@@ -585,15 +834,20 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
     this->LocalGenerator->AddArchitectureFlags(
       langFlags, this->GeneratorTarget, linkLanguage, this->ConfigName);
 
-    // remove any language flags that might not work with the
-    // particular os
-    if (forbiddenFlagVar) {
-      this->RemoveForbiddenFlags(forbiddenFlagVar, linkLanguage, langFlags);
-    }
     vars.LanguageCompileFlags = langFlags.c_str();
 
+    std::string launcher;
+    const char* val = this->LocalGenerator->GetRuleLauncher(
+      this->GeneratorTarget, "RULE_LAUNCH_LINK");
+    if (val && *val) {
+      launcher = val;
+      launcher += " ";
+    }
+
+    CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+      this->LocalGenerator->CreateRulePlaceholderExpander());
     // Construct the main link rule and expand placeholders.
-    this->LocalGenerator->TargetImplib = targetOutPathImport;
+    rulePlaceholderExpander->SetTargetImpLib(targetOutPathImport);
     if (useArchiveRules) {
       // Construct the individual object list strings.
       std::vector<std::string> object_strings;
@@ -606,8 +860,9 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
         for (std::vector<std::string>::const_iterator i =
                archiveCreateCommands.begin();
              i != archiveCreateCommands.end(); ++i) {
-          std::string cmd = *i;
-          this->LocalGenerator->ExpandRuleVariables(cmd, vars);
+          std::string cmd = launcher + *i;
+          rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
+                                                       cmd, vars);
           real_link_commands.push_back(cmd);
         }
       }
@@ -617,8 +872,9 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
         for (std::vector<std::string>::const_iterator i =
                archiveAppendCommands.begin();
              i != archiveAppendCommands.end(); ++i) {
-          std::string cmd = *i;
-          this->LocalGenerator->ExpandRuleVariables(cmd, vars);
+          std::string cmd = launcher + *i;
+          rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
+                                                       cmd, vars);
           real_link_commands.push_back(cmd);
         }
       }
@@ -627,8 +883,9 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
       for (std::vector<std::string>::const_iterator i =
              archiveFinishCommands.begin();
            i != archiveFinishCommands.end(); ++i) {
-        std::string cmd = *i;
-        this->LocalGenerator->ExpandRuleVariables(cmd, vars);
+        std::string cmd = launcher + *i;
+        rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, cmd,
+                                                     vars);
         // If there is no ranlib the command will be ":".  Skip it.
         if (!cmd.empty() && cmd[0] != ':') {
           real_link_commands.push_back(cmd);
@@ -639,7 +896,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
       std::string linkRule = this->GetLinkRule(linkRuleVar);
       cmSystemTools::ExpandListArgument(linkRule, real_link_commands);
       if (this->GeneratorTarget->GetPropertyAsBool("LINK_WHAT_YOU_USE") &&
-          (this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY)) {
+          (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY)) {
         std::string cmakeCommand = this->LocalGenerator->ConvertToOutputFormat(
           cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
         cmakeCommand += " -E __run_iwyu --lwyu=";
@@ -650,10 +907,11 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
       // Expand placeholders.
       for (std::vector<std::string>::iterator i = real_link_commands.begin();
            i != real_link_commands.end(); ++i) {
-        this->LocalGenerator->ExpandRuleVariables(*i, vars);
+        *i = launcher + *i;
+        rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i,
+                                                     vars);
       }
     }
-    this->LocalGenerator->TargetImplib = "";
 
     // Restore path conversion to normal shells.
     this->LocalGenerator->SetLinkScriptShell(false);
diff --git a/Source/cmMakefileLibraryTargetGenerator.h b/Source/cmMakefileLibraryTargetGenerator.h
index dda41b8..93ce902 100644
--- a/Source/cmMakefileLibraryTargetGenerator.h
+++ b/Source/cmMakefileLibraryTargetGenerator.h
@@ -26,6 +26,9 @@ protected:
   void WriteStaticLibraryRules();
   void WriteSharedLibraryRules(bool relink);
   void WriteModuleLibraryRules(bool relink);
+
+  void WriteDeviceLibraryRules(const std::string& linkRule,
+                               const std::string& extraFlags, bool relink);
   void WriteLibraryRules(const std::string& linkRule,
                          const std::string& extraFlags, bool relink);
   // MacOSX Framework support methods
@@ -33,6 +36,9 @@ protected:
 
   // Store the computd framework version for OS X Frameworks.
   std::string FrameworkVersion;
+
+private:
+  std::string DeviceLinkObject;
 };
 
 #endif
diff --git a/Source/cmMakefileTargetGenerator.cxx b/Source/cmMakefileTargetGenerator.cxx
index e70f09e..54b3f36 100644
--- a/Source/cmMakefileTargetGenerator.cxx
+++ b/Source/cmMakefileTargetGenerator.cxx
@@ -2,6 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMakefileTargetGenerator.h"
 
+#include <sstream>
+#include <stdio.h>
+#include <utility>
+
 #include "cmAlgorithms.h"
 #include "cmComputeLinkInformation.h"
 #include "cmCustomCommand.h"
@@ -10,25 +14,22 @@
 #include "cmGeneratorExpression.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalUnixMakefileGenerator3.h"
-#include "cmLocalGenerator.h"
 #include "cmLocalUnixMakefileGenerator3.h"
 #include "cmMakefile.h"
 #include "cmMakefileExecutableTargetGenerator.h"
 #include "cmMakefileLibraryTargetGenerator.h"
 #include "cmMakefileUtilityTargetGenerator.h"
 #include "cmOutputConverter.h"
+#include "cmRulePlaceholderExpander.h"
 #include "cmSourceFile.h"
 #include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
-#include <algorithm>
-#include <ctype.h>
-#include <sstream>
-#include <stdio.h>
-#include <utility>
-
 #ifndef _WIN32
 #include <unistd.h>
 #endif
@@ -66,16 +67,16 @@ cmMakefileTargetGenerator* cmMakefileTargetGenerator::New(
   cmMakefileTargetGenerator* result = CM_NULLPTR;
 
   switch (tgt->GetType()) {
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       result = new cmMakefileExecutableTargetGenerator(tgt);
       break;
-    case cmState::STATIC_LIBRARY:
-    case cmState::SHARED_LIBRARY:
-    case cmState::MODULE_LIBRARY:
-    case cmState::OBJECT_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
+    case cmStateEnums::OBJECT_LIBRARY:
       result = new cmMakefileLibraryTargetGenerator(tgt);
       break;
-    case cmState::UTILITY:
+    case cmStateEnums::UTILITY:
       result = new cmMakefileUtilityTargetGenerator(tgt);
       break;
     default:
@@ -110,7 +111,8 @@ void cmMakefileTargetGenerator::CreateRuleFile()
   // Open the rule file.  This should be copy-if-different because the
   // rules may depend on this file itself.
   this->BuildFileStream =
-    new cmGeneratedFileStream(this->BuildFileNameFull.c_str());
+    new cmGeneratedFileStream(this->BuildFileNameFull.c_str(), false,
+                              this->GlobalGenerator->GetMakefileEncoding());
   this->BuildFileStream->SetCopyIfDifferent(true);
   if (!this->BuildFileStream) {
     return;
@@ -166,7 +168,7 @@ void cmMakefileTargetGenerator::WriteTargetBuildRules()
       for (std::vector<std::string>::const_iterator o = outputs.begin();
            o != outputs.end(); ++o) {
         this->CleanFiles.push_back(
-          this->LocalGenerator->ConvertToRelativePath(currentBinDir, *o));
+          this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir, *o));
       }
     }
   }
@@ -209,8 +211,8 @@ void cmMakefileTargetGenerator::WriteCommonCodeRules()
     << this->GlobalGenerator->IncludeDirective << " " << root
     << cmSystemTools::ConvertToOutputPath(
          this->LocalGenerator
-           ->ConvertToRelativePath(this->LocalGenerator->GetBinaryDirectory(),
-                                   dependFileNameFull)
+           ->MaybeConvertToRelativePath(
+             this->LocalGenerator->GetBinaryDirectory(), dependFileNameFull)
            .c_str())
     << "\n\n";
 
@@ -221,7 +223,7 @@ void cmMakefileTargetGenerator::WriteCommonCodeRules()
       << this->GlobalGenerator->IncludeDirective << " " << root
       << cmSystemTools::ConvertToOutputPath(
            this->LocalGenerator
-             ->ConvertToRelativePath(
+             ->MaybeConvertToRelativePath(
                this->LocalGenerator->GetBinaryDirectory(),
                this->ProgressFileNameFull)
              .c_str())
@@ -231,7 +233,9 @@ void cmMakefileTargetGenerator::WriteCommonCodeRules()
   // make sure the depend file exists
   if (!cmSystemTools::FileExists(dependFileNameFull.c_str())) {
     // Write an empty dependency file.
-    cmGeneratedFileStream depFileStream(dependFileNameFull.c_str());
+    cmGeneratedFileStream depFileStream(
+      dependFileNameFull.c_str(), false,
+      this->GlobalGenerator->GetMakefileEncoding());
     depFileStream << "# Empty dependencies file for "
                   << this->GeneratorTarget->GetName() << ".\n"
                   << "# This may be replaced when dependencies are built."
@@ -243,7 +247,8 @@ void cmMakefileTargetGenerator::WriteCommonCodeRules()
   this->FlagFileNameFull = this->TargetBuildDirectoryFull;
   this->FlagFileNameFull += "/flags.make";
   this->FlagFileStream =
-    new cmGeneratedFileStream(this->FlagFileNameFull.c_str());
+    new cmGeneratedFileStream(this->FlagFileNameFull.c_str(), false,
+                              this->GlobalGenerator->GetMakefileEncoding());
   this->FlagFileStream->SetCopyIfDifferent(true);
   if (!this->FlagFileStream) {
     return;
@@ -256,8 +261,9 @@ void cmMakefileTargetGenerator::WriteCommonCodeRules()
     << this->GlobalGenerator->IncludeDirective << " " << root
     << cmSystemTools::ConvertToOutputPath(
          this->LocalGenerator
-           ->ConvertToRelativePath(this->LocalGenerator->GetBinaryDirectory(),
-                                   this->FlagFileNameFull)
+           ->MaybeConvertToRelativePath(
+             this->LocalGenerator->GetBinaryDirectory(),
+             this->FlagFileNameFull)
            .c_str())
     << "\n\n";
 }
@@ -314,9 +320,9 @@ void cmMakefileTargetGenerator::MacOSXContentGeneratorType::operator()(
   output += "/";
   output += cmSystemTools::GetFilenameName(input);
   this->Generator->CleanFiles.push_back(
-    this->Generator->LocalGenerator->ConvertToRelativePath(
+    this->Generator->LocalGenerator->MaybeConvertToRelativePath(
       this->Generator->LocalGenerator->GetCurrentBinaryDirectory(), output));
-  output = this->Generator->LocalGenerator->ConvertToRelativePath(
+  output = this->Generator->LocalGenerator->MaybeConvertToRelativePath(
     this->Generator->LocalGenerator->GetBinaryDirectory(), output);
 
   // Create a rule to copy the content into the bundle.
@@ -429,8 +435,8 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
   langFlags += "_FLAGS)";
   this->LocalGenerator->AppendFlags(flags, langFlags);
 
-  std::string configUpper =
-    cmSystemTools::UpperCase(this->LocalGenerator->GetConfigName());
+  std::string config = this->LocalGenerator->GetConfigName();
+  std::string configUpper = cmSystemTools::UpperCase(config);
 
   // Add Fortran format flags.
   if (lang == "Fortran") {
@@ -438,12 +444,14 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
   }
 
   // Add flags from source file properties.
-  if (source.GetProperty("COMPILE_FLAGS")) {
-    this->LocalGenerator->AppendFlags(flags,
-                                      source.GetProperty("COMPILE_FLAGS"));
+  if (const char* cflags = source.GetProperty("COMPILE_FLAGS")) {
+    cmGeneratorExpression ge;
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(cflags);
+    const char* evaluatedFlags = cge->Evaluate(this->LocalGenerator, config,
+                                               false, this->GeneratorTarget);
+    this->LocalGenerator->AppendFlags(flags, evaluatedFlags);
     *this->FlagFileStream << "# Custom flags: " << relativeObj
-                          << "_FLAGS = " << source.GetProperty("COMPILE_FLAGS")
-                          << "\n"
+                          << "_FLAGS = " << evaluatedFlags << "\n"
                           << "\n";
   }
 
@@ -496,11 +504,11 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
   {
     std::string targetFullPathReal;
     std::string targetFullPathPDB;
-    std::string targetFullPathCompilePDB;
-    if (this->GeneratorTarget->GetType() == cmState::EXECUTABLE ||
-        this->GeneratorTarget->GetType() == cmState::STATIC_LIBRARY ||
-        this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY ||
-        this->GeneratorTarget->GetType() == cmState::MODULE_LIBRARY) {
+    std::string targetFullPathCompilePDB = this->ComputeTargetCompilePDB();
+    if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
+        this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
+        this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
+        this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
       targetFullPathReal =
         this->GeneratorTarget->GetFullPath(this->ConfigName, false, true);
       targetFullPathPDB =
@@ -508,23 +516,15 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
       targetFullPathPDB += "/";
       targetFullPathPDB += this->GeneratorTarget->GetPDBName(this->ConfigName);
     }
-    if (this->GeneratorTarget->GetType() <= cmState::OBJECT_LIBRARY) {
-      targetFullPathCompilePDB =
-        this->GeneratorTarget->GetCompilePDBPath(this->ConfigName);
-      if (targetFullPathCompilePDB.empty()) {
-        targetFullPathCompilePDB =
-          this->GeneratorTarget->GetSupportDirectory() + "/";
-      }
-    }
 
     targetOutPathReal = this->LocalGenerator->ConvertToOutputFormat(
-      this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->MaybeConvertToRelativePath(
         this->LocalGenerator->GetCurrentBinaryDirectory(), targetFullPathReal),
       cmOutputConverter::SHELL);
     targetOutPathPDB = this->LocalGenerator->ConvertToOutputFormat(
       targetFullPathPDB, cmOutputConverter::SHELL);
     targetOutPathCompilePDB = this->LocalGenerator->ConvertToOutputFormat(
-      this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->MaybeConvertToRelativePath(
         this->LocalGenerator->GetCurrentBinaryDirectory(),
         targetFullPathCompilePDB),
       cmOutputConverter::SHELL);
@@ -537,9 +537,10 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
       targetOutPathCompilePDB[targetOutPathCompilePDB.size() - 1] = '/';
     }
   }
-  cmLocalGenerator::RuleVariables vars;
-  vars.RuleLauncher = "RULE_LAUNCH_COMPILE";
-  vars.CMTarget = this->GeneratorTarget;
+  cmRulePlaceholderExpander::RuleVariables vars;
+  vars.CMTargetName = this->GeneratorTarget->GetName().c_str();
+  vars.CMTargetType =
+    cmState::GetTargetTypeName(this->GeneratorTarget->GetType());
   vars.Language = lang.c_str();
   vars.Target = targetOutPathReal.c_str();
   vars.TargetPDB = targetOutPathPDB.c_str();
@@ -550,13 +551,13 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
   vars.Object = shellObj.c_str();
   std::string objectDir = this->GeneratorTarget->GetSupportDirectory();
   objectDir = this->LocalGenerator->ConvertToOutputFormat(
-    this->LocalGenerator->ConvertToRelativePath(
+    this->LocalGenerator->MaybeConvertToRelativePath(
       this->LocalGenerator->GetCurrentBinaryDirectory(), objectDir),
     cmOutputConverter::SHELL);
   vars.ObjectDir = objectDir.c_str();
   std::string objectFileDir = cmSystemTools::GetFilenamePath(obj);
   objectFileDir = this->LocalGenerator->ConvertToOutputFormat(
-    this->LocalGenerator->ConvertToRelativePath(
+    this->LocalGenerator->MaybeConvertToRelativePath(
       this->LocalGenerator->GetCurrentBinaryDirectory(), objectFileDir),
     cmOutputConverter::SHELL);
   vars.ObjectFileDir = objectFileDir.c_str();
@@ -573,28 +574,44 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
   std::string const includesString = "$(" + lang + "_INCLUDES)";
   vars.Includes = includesString.c_str();
 
-  // At the moment, it is assumed that C, C++, and Fortran have both
+  // At the moment, it is assumed that C, C++, Fortran, and CUDA have both
   // assembly and preprocessor capabilities. The same is true for the
   // ability to export compile commands
-  bool lang_has_preprocessor =
-    ((lang == "C") || (lang == "CXX") || (lang == "Fortran"));
+  bool lang_has_preprocessor = ((lang == "C") || (lang == "CXX") ||
+                                (lang == "Fortran") || (lang == "CUDA"));
   bool const lang_has_assembly = lang_has_preprocessor;
   bool const lang_can_export_cmds = lang_has_preprocessor;
 
+  CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+    this->LocalGenerator->CreateRulePlaceholderExpander());
+
   // Construct the compile rules.
   {
-    std::string compileRuleVar = "CMAKE_";
-    compileRuleVar += lang;
-    compileRuleVar += "_COMPILE_OBJECT";
-    std::string compileRule =
-      this->Makefile->GetRequiredDefinition(compileRuleVar);
     std::vector<std::string> compileCommands;
-    cmSystemTools::ExpandListArgument(compileRule, compileCommands);
+    if (lang == "CUDA") {
+      std::string cmdVar;
+      if (this->GeneratorTarget->GetPropertyAsBool(
+            "CUDA_SEPARABLE_COMPILATION")) {
+        cmdVar = std::string("CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION");
+      } else {
+        cmdVar = std::string("CMAKE_CUDA_COMPILE_WHOLE_COMPILATION");
+      }
+      std::string compileRule = this->Makefile->GetRequiredDefinition(cmdVar);
+      cmSystemTools::ExpandListArgument(compileRule, compileCommands);
+    } else {
+      const std::string cmdVar =
+        std::string("CMAKE_") + lang + "_COMPILE_OBJECT";
+      std::string compileRule = this->Makefile->GetRequiredDefinition(cmdVar);
+      cmSystemTools::ExpandListArgument(compileRule, compileCommands);
+    }
 
     if (this->Makefile->IsOn("CMAKE_EXPORT_COMPILE_COMMANDS") &&
         lang_can_export_cmds && compileCommands.size() == 1) {
       std::string compileCommand = compileCommands[0];
-      this->LocalGenerator->ExpandRuleVariables(compileCommand, vars);
+
+      // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
+      rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
+                                                   compileCommand, vars);
       std::string workingDirectory = cmSystemTools::CollapseFullPath(
         this->LocalGenerator->GetCurrentBinaryDirectory());
       compileCommand.replace(compileCommand.find(langFlags), langFlags.size(),
@@ -615,7 +632,9 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
       const char* iwyu = this->GeneratorTarget->GetProperty(iwyu_prop);
       std::string const tidy_prop = lang + "_CLANG_TIDY";
       const char* tidy = this->GeneratorTarget->GetProperty(tidy_prop);
-      if ((iwyu && *iwyu) || (tidy && *tidy)) {
+      std::string const cpplint_prop = lang + "_CPPLINT";
+      const char* cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
+      if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint)) {
         std::string run_iwyu = "$(CMAKE_COMMAND) -E __run_iwyu";
         if (iwyu && *iwyu) {
           run_iwyu += " --iwyu=";
@@ -624,6 +643,12 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
         if (tidy && *tidy) {
           run_iwyu += " --tidy=";
           run_iwyu += this->LocalGenerator->EscapeForShell(tidy);
+        }
+        if (cpplint && *cpplint) {
+          run_iwyu += " --cpplint=";
+          run_iwyu += this->LocalGenerator->EscapeForShell(cpplint);
+        }
+        if ((tidy && *tidy) || (cpplint && *cpplint)) {
           run_iwyu += " --source=";
           run_iwyu += sourceFile;
         }
@@ -650,10 +675,22 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
       }
     }
 
+    std::string launcher;
+    {
+      const char* val = this->LocalGenerator->GetRuleLauncher(
+        this->GeneratorTarget, "RULE_LAUNCH_COMPILE");
+      if (val && *val) {
+        launcher = val;
+        launcher += " ";
+      }
+    }
+
     // Expand placeholders in the commands.
     for (std::vector<std::string>::iterator i = compileCommands.begin();
          i != compileCommands.end(); ++i) {
-      this->LocalGenerator->ExpandRuleVariables(*i, vars);
+      *i = launcher + *i;
+      rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i,
+                                                   vars);
     }
 
     // Change the command working directory to the local build tree.
@@ -716,7 +753,9 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
         // Expand placeholders in the commands.
         for (std::vector<std::string>::iterator i = preprocessCommands.begin();
              i != preprocessCommands.end(); ++i) {
-          this->LocalGenerator->ExpandRuleVariables(*i, vars);
+          // no launcher for preprocessor commands
+          rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
+                                                       *i, vars);
         }
 
         this->LocalGenerator->CreateCDCommand(
@@ -763,7 +802,9 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
         // Expand placeholders in the commands.
         for (std::vector<std::string>::iterator i = assemblyCommands.begin();
              i != assemblyCommands.end(); ++i) {
-          this->LocalGenerator->ExpandRuleVariables(*i, vars);
+          // no launcher for assembly commands
+          rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
+                                                       *i, vars);
         }
 
         this->LocalGenerator->CreateCDCommand(
@@ -904,7 +945,7 @@ bool cmMakefileTargetGenerator::WriteMakeRule(
     // Touch the extra output so "make" knows that it was updated,
     // but only if the output was acually created.
     std::string const out = this->LocalGenerator->ConvertToOutputFormat(
-      this->LocalGenerator->ConvertToRelativePath(binDir, *o),
+      this->LocalGenerator->MaybeConvertToRelativePath(binDir, *o),
       cmOutputConverter::SHELL);
     std::vector<std::string> output_commands;
 
@@ -1200,10 +1241,9 @@ void cmMakefileTargetGenerator::WriteObjectsVariable(
   for (std::vector<std::string>::const_iterator i =
          this->ExternalObjects.begin();
        i != this->ExternalObjects.end(); ++i) {
-    object = this->LocalGenerator->ConvertToRelativePath(currentBinDir, *i);
-    *this->BuildFileStream << " " << lineContinue << "\n"
-                           << this->Makefile->GetSafeDefinition(
-                                "CMAKE_OBJECT_NAME");
+    object =
+      this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir, *i);
+    *this->BuildFileStream << " " << lineContinue << "\n";
     *this->BuildFileStream << this->LocalGenerator->ConvertToQuotedOutputPath(
       i->c_str(), useWatcomQuote);
   }
@@ -1211,21 +1251,16 @@ void cmMakefileTargetGenerator::WriteObjectsVariable(
                          << "\n";
 }
 
-void cmMakefileTargetGenerator::WriteObjectsString(std::string& buildObjs)
-{
-  std::vector<std::string> objStrings;
-  this->WriteObjectsStrings(objStrings);
-  buildObjs = objStrings[0];
-}
-
 class cmMakefileTargetGeneratorObjectStrings
 {
 public:
   cmMakefileTargetGeneratorObjectStrings(std::vector<std::string>& strings,
-                                         cmLocalUnixMakefileGenerator3* lg,
+                                         cmOutputConverter* outputConverter,
+                                         cmStateDirectory stateDir,
                                          std::string::size_type limit)
     : Strings(strings)
-    , LocalGenerator(lg)
+    , OutputConverter(outputConverter)
+    , StateDir(stateDir)
     , LengthLimit(limit)
   {
     this->Space = "";
@@ -1233,10 +1268,8 @@ public:
   void Feed(std::string const& obj)
   {
     // Construct the name of the next object.
-    this->NextObject = this->LocalGenerator->ConvertToOutputFormat(
-      this->LocalGenerator->ConvertToRelativePath(
-        this->LocalGenerator->GetCurrentBinaryDirectory(), obj),
-      cmOutputConverter::RESPONSE);
+    this->NextObject = this->OutputConverter->ConvertToOutputFormat(
+      this->MaybeConvertToRelativePath(obj), cmOutputConverter::RESPONSE);
 
     // Roll over to next string if the limit will be exceeded.
     if (this->LengthLimit != std::string::npos &&
@@ -1256,8 +1289,19 @@ public:
   }
   void Done() { this->Strings.push_back(this->CurrentString); }
 private:
+  std::string MaybeConvertToRelativePath(std::string const& obj)
+  {
+    if (!cmOutputConverter::ContainedInDirectory(
+          this->StateDir.GetCurrentBinary(), obj, this->StateDir)) {
+      return obj;
+    }
+    return cmOutputConverter::ForceToRelativePath(
+      this->StateDir.GetCurrentBinary(), obj);
+  }
+
   std::vector<std::string>& Strings;
-  cmLocalUnixMakefileGenerator3* LocalGenerator;
+  cmOutputConverter* OutputConverter;
+  cmStateDirectory StateDir;
   std::string::size_type LengthLimit;
   std::string CurrentString;
   std::string NextObject;
@@ -1267,8 +1311,9 @@ private:
 void cmMakefileTargetGenerator::WriteObjectsStrings(
   std::vector<std::string>& objStrings, std::string::size_type limit)
 {
-  cmMakefileTargetGeneratorObjectStrings helper(objStrings,
-                                                this->LocalGenerator, limit);
+  cmMakefileTargetGeneratorObjectStrings helper(
+    objStrings, this->LocalGenerator,
+    this->LocalGenerator->GetStateSnapshot().GetDirectory(), limit);
   for (std::vector<std::string>::const_iterator i = this->Objects.begin();
        i != this->Objects.end(); ++i) {
     helper.Feed(*i);
@@ -1289,7 +1334,7 @@ void cmMakefileTargetGenerator::WriteTargetDriverRule(
     this->LocalGenerator->GetRelativeTargetDirectory(this->GeneratorTarget);
   std::string buildTargetRuleName = dir;
   buildTargetRuleName += relink ? "/preinstall" : "/build";
-  buildTargetRuleName = this->LocalGenerator->ConvertToRelativePath(
+  buildTargetRuleName = this->LocalGenerator->MaybeConvertToRelativePath(
     this->LocalGenerator->GetBinaryDirectory(), buildTargetRuleName);
 
   // Build the list of target outputs to drive.
@@ -1325,7 +1370,7 @@ void cmMakefileTargetGenerator::AppendTargetDepends(
   std::vector<std::string>& depends)
 {
   // Static libraries never depend on anything for linking.
-  if (this->GeneratorTarget->GetType() == cmState::STATIC_LIBRARY) {
+  if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
     return;
   }
 
@@ -1410,52 +1455,6 @@ void cmMakefileTargetGenerator::CloseFileStreams()
   delete this->FlagFileStream;
 }
 
-void cmMakefileTargetGenerator::RemoveForbiddenFlags(
-  const char* flagVar, const std::string& linkLang, std::string& linkFlags)
-{
-  // check for language flags that are not allowed at link time, and
-  // remove them, -w on darwin for gcc -w -dynamiclib sends -w to libtool
-  // which fails, there may be more]
-
-  std::string removeFlags = "CMAKE_";
-  removeFlags += linkLang;
-  removeFlags += flagVar;
-  std::string removeflags = this->Makefile->GetSafeDefinition(removeFlags);
-  std::vector<std::string> removeList;
-  cmSystemTools::ExpandListArgument(removeflags, removeList);
-
-  for (std::vector<std::string>::iterator i = removeList.begin();
-       i != removeList.end(); ++i) {
-    std::string tmp;
-    std::string::size_type lastPosition = 0;
-
-    for (;;) {
-      std::string::size_type position = linkFlags.find(*i, lastPosition);
-
-      if (position == std::string::npos) {
-        tmp += linkFlags.substr(lastPosition);
-        break;
-      } else {
-        std::string::size_type prefixLength = position - lastPosition;
-        tmp += linkFlags.substr(lastPosition, prefixLength);
-        lastPosition = position + i->length();
-
-        bool validFlagStart =
-          position == 0 || isspace(linkFlags[position - 1]);
-
-        bool validFlagEnd =
-          lastPosition == linkFlags.size() || isspace(linkFlags[lastPosition]);
-
-        if (!validFlagStart || !validFlagEnd) {
-          tmp += *i;
-        }
-      }
-    }
-
-    linkFlags = tmp;
-  }
-}
-
 void cmMakefileTargetGenerator::CreateLinkScript(
   const char* name, std::vector<std::string> const& link_commands,
   std::vector<std::string>& makefile_commands,
@@ -1479,7 +1478,7 @@ void cmMakefileTargetGenerator::CreateLinkScript(
   // Create the makefile command to invoke the link script.
   std::string link_command = "$(CMAKE_COMMAND) -E cmake_link_script ";
   link_command += this->LocalGenerator->ConvertToOutputFormat(
-    this->LocalGenerator->ConvertToRelativePath(
+    this->LocalGenerator->MaybeConvertToRelativePath(
       this->LocalGenerator->GetCurrentBinaryDirectory(), linkScriptName),
     cmOutputConverter::SHELL);
   link_command += " --verbose=$(VERBOSE)";
@@ -1577,15 +1576,28 @@ std::string cmMakefileTargetGenerator::CreateResponseFile(
   return responseFileName;
 }
 
+cmLinkLineComputer* cmMakefileTargetGenerator::CreateLinkLineComputer(
+  cmOutputConverter* outputConverter, cmStateDirectory stateDir)
+{
+  if (this->Makefile->IsOn("MSVC60")) {
+    return this->GlobalGenerator->CreateMSVC60LinkLineComputer(outputConverter,
+                                                               stateDir);
+  }
+  return this->GlobalGenerator->CreateLinkLineComputer(outputConverter,
+                                                       stateDir);
+}
+
 void cmMakefileTargetGenerator::CreateLinkLibs(
-  std::string& linkLibs, bool relink, bool useResponseFile,
-  std::vector<std::string>& makefile_depends, bool useWatcomQuote)
+  cmLinkLineComputer* linkLineComputer, std::string& linkLibs,
+  bool useResponseFile, std::vector<std::string>& makefile_depends)
 {
   std::string frameworkPath;
   std::string linkPath;
-  this->LocalGenerator->OutputLinkLibraries(linkLibs, frameworkPath, linkPath,
-                                            *this->GeneratorTarget, relink,
-                                            useResponseFile, useWatcomQuote);
+  std::string config = this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
+  cmComputeLinkInformation* pcli =
+    this->GeneratorTarget->GetLinkInformation(config);
+  this->LocalGenerator->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
+                                            frameworkPath, linkPath);
   linkLibs = frameworkPath + linkPath + linkLibs;
 
   if (useResponseFile && linkLibs.find_first_not_of(' ') != linkLibs.npos) {
@@ -1659,7 +1671,9 @@ void cmMakefileTargetGenerator::CreateObjectLists(
     }
   } else if (useLinkScript) {
     if (!useArchiveRules) {
-      this->WriteObjectsString(buildObjs);
+      std::vector<std::string> objStrings;
+      this->WriteObjectsStrings(objStrings);
+      buildObjs = objStrings[0];
     }
   } else {
     buildObjs = "$(";
@@ -1716,14 +1730,14 @@ void cmMakefileTargetGenerator::GenDefFile(
       cmd, cmOutputConverter::SHELL);
     cmd += " -E __create_def ";
     cmd += this->LocalGenerator->ConvertToOutputFormat(
-      this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->MaybeConvertToRelativePath(
         this->LocalGenerator->GetCurrentBinaryDirectory(), name_of_def_file),
       cmOutputConverter::SHELL);
     cmd += " ";
     std::string objlist_file = name_of_def_file;
     objlist_file += ".objs";
     cmd += this->LocalGenerator->ConvertToOutputFormat(
-      this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->MaybeConvertToRelativePath(
         this->LocalGenerator->GetCurrentBinaryDirectory(), objlist_file),
       cmOutputConverter::SHELL);
     real_link_commands.insert(real_link_commands.begin(), cmd);
@@ -1744,7 +1758,7 @@ void cmMakefileTargetGenerator::GenDefFile(
     linkFlags += " ";
     linkFlags += this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
     linkFlags += this->LocalGenerator->ConvertToOutputFormat(
-      this->LocalGenerator->ConvertToRelativePath(
+      this->LocalGenerator->MaybeConvertToRelativePath(
         this->LocalGenerator->GetCurrentBinaryDirectory(), name_of_def_file),
       cmOutputConverter::SHELL);
     linkFlags += " ";
diff --git a/Source/cmMakefileTargetGenerator.h b/Source/cmMakefileTargetGenerator.h
index df7b6aa..347f9f2 100644
--- a/Source/cmMakefileTargetGenerator.h
+++ b/Source/cmMakefileTargetGenerator.h
@@ -5,21 +5,24 @@
 
 #include <cmConfigure.h>
 
-#include "cmCommonTargetGenerator.h"
-#include "cmLocalUnixMakefileGenerator3.h"
-#include "cmOSXBundleGenerator.h"
-
 #include <iosfwd>
 #include <map>
 #include <set>
 #include <string>
 #include <vector>
 
+#include "cmCommonTargetGenerator.h"
+#include "cmLocalUnixMakefileGenerator3.h"
+#include "cmOSXBundleGenerator.h"
+
 class cmCustomCommandGenerator;
 class cmGeneratedFileStream;
 class cmGeneratorTarget;
 class cmGlobalUnixMakefileGenerator3;
+class cmLinkLineComputer;
+class cmOutputConverter;
 class cmSourceFile;
+class cmStateDirectory;
 
 /** \class cmMakefileTargetGenerator
  * \brief Support Routines for writing makefiles
@@ -112,7 +115,6 @@ protected:
   void WriteObjectsVariable(std::string& variableName,
                             std::string& variableNameExternal,
                             bool useWatcomQuote);
-  void WriteObjectsString(std::string& buildObjs);
   void WriteObjectsStrings(std::vector<std::string>& objStrings,
                            std::string::size_type limit = std::string::npos);
 
@@ -140,6 +142,9 @@ protected:
                         std::vector<std::string>& makefile_commands,
                         std::vector<std::string>& makefile_depends);
 
+  cmLinkLineComputer* CreateLinkLineComputer(
+    cmOutputConverter* outputConverter, cmStateDirectory stateDir);
+
   /** Create a response file with the given set of options.  Returns
       the relative path from the target build working directory to the
       response file name.  */
@@ -150,9 +155,9 @@ protected:
   bool CheckUseResponseFileForLibraries(std::string const& l) const;
 
   /** Create list of flags for link libraries. */
-  void CreateLinkLibs(std::string& linkLibs, bool relink, bool useResponseFile,
-                      std::vector<std::string>& makefile_depends,
-                      bool useWatcomQuote);
+  void CreateLinkLibs(cmLinkLineComputer* linkLineComputer,
+                      std::string& linkLibs, bool useResponseFile,
+                      std::vector<std::string>& makefile_depends);
 
   /** Create lists of object files for linking and cleaning.  */
   void CreateObjectLists(bool useLinkScript, bool useArchiveRules,
@@ -168,8 +173,6 @@ protected:
                        const std::string& lang) CM_OVERRIDE;
 
   virtual void CloseFileStreams();
-  void RemoveForbiddenFlags(const char* flagVar, const std::string& linkLang,
-                            std::string& linkFlags);
   cmLocalUnixMakefileGenerator3* LocalGenerator;
   cmGlobalUnixMakefileGenerator3* GlobalGenerator;
 
diff --git a/Source/cmMakefileUtilityTargetGenerator.cxx b/Source/cmMakefileUtilityTargetGenerator.cxx
index f40c8fa..a7c5d27 100644
--- a/Source/cmMakefileUtilityTargetGenerator.cxx
+++ b/Source/cmMakefileUtilityTargetGenerator.cxx
@@ -2,17 +2,17 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMakefileUtilityTargetGenerator.h"
 
+#include <ostream>
+#include <string>
+#include <vector>
+
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalUnixMakefileGenerator3.h"
 #include "cmLocalUnixMakefileGenerator3.h"
 #include "cmMakefile.h"
 #include "cmOSXBundleGenerator.h"
-#include "cmOutputConverter.h"
-
-#include <ostream>
-#include <string>
-#include <vector>
+#include "cmSystemTools.h"
 
 cmMakefileUtilityTargetGenerator::cmMakefileUtilityTargetGenerator(
   cmGeneratorTarget* target)
@@ -46,7 +46,7 @@ void cmMakefileUtilityTargetGenerator::WriteRuleFiles()
       << this->GlobalGenerator->IncludeDirective << " " << root
       << cmSystemTools::ConvertToOutputPath(
            this->LocalGenerator
-             ->ConvertToRelativePath(
+             ->MaybeConvertToRelativePath(
                this->LocalGenerator->GetBinaryDirectory(),
                this->ProgressFileNameFull)
              .c_str())
diff --git a/Source/cmMarkAsAdvancedCommand.cxx b/Source/cmMarkAsAdvancedCommand.cxx
index 5ec1620..b2f0d22 100644
--- a/Source/cmMarkAsAdvancedCommand.cxx
+++ b/Source/cmMarkAsAdvancedCommand.cxx
@@ -2,6 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMarkAsAdvancedCommand.h"
 
+#include "cmMakefile.h"
+#include "cmState.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
+
 // cmMarkAsAdvancedCommand
 bool cmMarkAsAdvancedCommand::InitialPass(std::vector<std::string> const& args,
                                           cmExecutionStatus&)
@@ -26,7 +34,7 @@ bool cmMarkAsAdvancedCommand::InitialPass(std::vector<std::string> const& args,
     cmState* state = this->Makefile->GetState();
     if (!state->GetCacheEntryValue(variable)) {
       this->Makefile->GetCMakeInstance()->AddCacheEntry(
-        variable, CM_NULLPTR, CM_NULLPTR, cmState::UNINITIALIZED);
+        variable, CM_NULLPTR, CM_NULLPTR, cmStateEnums::UNINITIALIZED);
       overwrite = true;
     }
     if (!state->GetCacheEntryValue(variable)) {
diff --git a/Source/cmMarkAsAdvancedCommand.h b/Source/cmMarkAsAdvancedCommand.h
index 54fa78a..26caa66 100644
--- a/Source/cmMarkAsAdvancedCommand.h
+++ b/Source/cmMarkAsAdvancedCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmMarkAsAdvancedCommand_h
 #define cmMarkAsAdvancedCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmMarkAsAdvancedCommand
  * \brief mark_as_advanced command
  *
@@ -37,8 +43,6 @@ public:
    * FindUnixMake.cmake used by the CTEST_BUILD command.
   */
   bool IsScriptable() const CM_OVERRIDE { return true; }
-
-  cmTypeMacro(cmMarkAsAdvancedCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmMathCommand.cxx b/Source/cmMathCommand.cxx
index 42e6b90..c1cd1b6 100644
--- a/Source/cmMathCommand.cxx
+++ b/Source/cmMathCommand.cxx
@@ -2,7 +2,12 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMathCommand.h"
 
+#include <stdio.h>
+
 #include "cmExprParserHelper.h"
+#include "cmMakefile.h"
+
+class cmExecutionStatus;
 
 bool cmMathCommand::InitialPass(std::vector<std::string> const& args,
                                 cmExecutionStatus&)
diff --git a/Source/cmMathCommand.h b/Source/cmMathCommand.h
index 6fa7389..9b49b21 100644
--- a/Source/cmMathCommand.h
+++ b/Source/cmMathCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmMathCommand_h
 #define cmMathCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /// Mathematical expressions: math(EXPR ...) command.
 class cmMathCommand : public cmCommand
 {
@@ -31,8 +37,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "math"; }
 
-  cmTypeMacro(cmMathCommand, cmCommand);
-
 protected:
   bool HandleExprCommand(std::vector<std::string> const& args);
 };
diff --git a/Source/cmMessageCommand.cxx b/Source/cmMessageCommand.cxx
index 9a83cd9..43fb5f5 100644
--- a/Source/cmMessageCommand.cxx
+++ b/Source/cmMessageCommand.cxx
@@ -2,7 +2,13 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmMessageCommand.h"
 
+#include "cmAlgorithms.h"
+#include "cmMakefile.h"
 #include "cmMessenger.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 // cmLibraryCommand
 bool cmMessageCommand::InitialPass(std::vector<std::string> const& args,
diff --git a/Source/cmMessageCommand.h b/Source/cmMessageCommand.h
index a67d52b..a565635 100644
--- a/Source/cmMessageCommand.h
+++ b/Source/cmMessageCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmMessageCommand_h
 #define cmMessageCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmMessageCommand
  * \brief Displays a message to the user
  *
@@ -33,8 +39,6 @@ public:
    * This determines if the command is invoked when in script mode.
    */
   bool IsScriptable() const CM_OVERRIDE { return true; }
-
-  cmTypeMacro(cmMessageCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmNinjaLinkLineComputer.cxx b/Source/cmNinjaLinkLineComputer.cxx
new file mode 100644
index 0000000..2546b55
--- /dev/null
+++ b/Source/cmNinjaLinkLineComputer.cxx
@@ -0,0 +1,23 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#include "cmNinjaLinkLineComputer.h"
+
+#include "cmGlobalNinjaGenerator.h"
+#include "cmStateDirectory.h"
+
+class cmOutputConverter;
+
+cmNinjaLinkLineComputer::cmNinjaLinkLineComputer(
+  cmOutputConverter* outputConverter, cmStateDirectory stateDir,
+  cmGlobalNinjaGenerator const* gg)
+  : cmLinkLineComputer(outputConverter, stateDir)
+  , GG(gg)
+{
+}
+
+std::string cmNinjaLinkLineComputer::ConvertToLinkReference(
+  std::string const& lib) const
+{
+  return GG->ConvertToNinjaPath(lib);
+}
diff --git a/Source/cmNinjaLinkLineComputer.h b/Source/cmNinjaLinkLineComputer.h
new file mode 100644
index 0000000..ff0771b
--- /dev/null
+++ b/Source/cmNinjaLinkLineComputer.h
@@ -0,0 +1,31 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#ifndef cmNinjaLinkLineComputer_h
+#define cmNinjaLinkLineComputer_h
+
+#include <cmConfigure.h>
+
+#include <string>
+
+#include "cmLinkLineComputer.h"
+
+class cmGlobalNinjaGenerator;
+class cmOutputConverter;
+class cmStateDirectory;
+
+class cmNinjaLinkLineComputer : public cmLinkLineComputer
+{
+public:
+  cmNinjaLinkLineComputer(cmOutputConverter* outputConverter,
+                          cmStateDirectory stateDir,
+                          cmGlobalNinjaGenerator const* gg);
+
+  std::string ConvertToLinkReference(std::string const& input) const
+    CM_OVERRIDE;
+
+private:
+  cmGlobalNinjaGenerator const* GG;
+};
+
+#endif
diff --git a/Source/cmNinjaNormalTargetGenerator.cxx b/Source/cmNinjaNormalTargetGenerator.cxx
index cd6dd1a..b1374c2 100644
--- a/Source/cmNinjaNormalTargetGenerator.cxx
+++ b/Source/cmNinjaNormalTargetGenerator.cxx
@@ -2,32 +2,39 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmNinjaNormalTargetGenerator.h"
 
+#include <algorithm>
+#include <assert.h>
+#include <iterator>
+#include <limits>
+#include <map>
+#include <set>
+#include <sstream>
+#include <stddef.h>
+
 #include "cmAlgorithms.h"
 #include "cmCustomCommand.h"
 #include "cmCustomCommandGenerator.h"
 #include "cmGeneratedFileStream.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalNinjaGenerator.h"
+#include "cmLinkLineComputer.h"
+#include "cmLinkLineDeviceComputer.h"
 #include "cmLocalGenerator.h"
 #include "cmLocalNinjaGenerator.h"
 #include "cmMakefile.h"
 #include "cmNinjaTypes.h"
 #include "cmOSXBundleGenerator.h"
 #include "cmOutputConverter.h"
+#include "cmRulePlaceholderExpander.h"
 #include "cmSourceFile.h"
 #include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
-#include <algorithm>
-#include <assert.h>
-#include <iterator>
-#include <limits>
-#include <map>
-#include <set>
-#include <sstream>
-#include <stddef.h>
-
 #ifndef _WIN32
 #include <unistd.h>
 #endif
@@ -41,9 +48,10 @@ cmNinjaNormalTargetGenerator::cmNinjaNormalTargetGenerator(
   , TargetNameImport()
   , TargetNamePDB()
   , TargetLinkLanguage("")
+  , DeviceLinkObject()
 {
   this->TargetLinkLanguage = target->GetLinkerLanguage(this->GetConfigName());
-  if (target->GetType() == cmState::EXECUTABLE) {
+  if (target->GetType() == cmStateEnums::EXECUTABLE) {
     this->GetGeneratorTarget()->GetExecutableNames(
       this->TargetNameOut, this->TargetNameReal, this->TargetNameImport,
       this->TargetNamePDB, GetLocalGenerator()->GetConfigName());
@@ -54,7 +62,7 @@ cmNinjaNormalTargetGenerator::cmNinjaNormalTargetGenerator(
       GetLocalGenerator()->GetConfigName());
   }
 
-  if (target->GetType() != cmState::OBJECT_LIBRARY) {
+  if (target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
     // on Windows the output dir is already needed at compile time
     // ensure the directory exists (OutDir test)
     EnsureDirectoryExists(target->GetDirectory(this->GetConfigName()));
@@ -85,9 +93,12 @@ void cmNinjaNormalTargetGenerator::Generate()
   // Write the build statements
   this->WriteObjectBuildStatements();
 
-  if (this->GetGeneratorTarget()->GetType() == cmState::OBJECT_LIBRARY) {
+  if (this->GetGeneratorTarget()->GetType() == cmStateEnums::OBJECT_LIBRARY) {
     this->WriteObjectLibStatement();
   } else {
+    // If this target has cuda language link inputs, and we need to do
+    // device linking
+    this->WriteDeviceLinkStatement();
     this->WriteLinkStatement();
   }
 }
@@ -104,10 +115,11 @@ void cmNinjaNormalTargetGenerator::WriteLanguagesRules()
 
   // Write rules for languages compiled in this target.
   std::set<std::string> languages;
-  std::vector<cmSourceFile*> sourceFiles;
-  this->GetGeneratorTarget()->GetSourceFiles(
+  std::vector<cmSourceFile const*> sourceFiles;
+  this->GetGeneratorTarget()->GetObjectSources(
     sourceFiles, this->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE"));
-  for (std::vector<cmSourceFile*>::const_iterator i = sourceFiles.begin();
+  for (std::vector<cmSourceFile const*>::const_iterator i =
+         sourceFiles.begin();
        i != sourceFiles.end(); ++i) {
     const std::string& lang = (*i)->GetLanguage();
     if (!lang.empty()) {
@@ -123,17 +135,17 @@ void cmNinjaNormalTargetGenerator::WriteLanguagesRules()
 const char* cmNinjaNormalTargetGenerator::GetVisibleTypeName() const
 {
   switch (this->GetGeneratorTarget()->GetType()) {
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
       return "static library";
-    case cmState::SHARED_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
       return "shared library";
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       if (this->GetGeneratorTarget()->IsCFBundleOnApple()) {
         return "CFBundle shared module";
       } else {
         return "shared module";
       }
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       return "executable";
     default:
       return CM_NULLPTR;
@@ -148,6 +160,14 @@ std::string cmNinjaNormalTargetGenerator::LanguageLinkerRule() const
                     this->GetGeneratorTarget()->GetName());
 }
 
+std::string cmNinjaNormalTargetGenerator::LanguageLinkerDeviceRule() const
+{
+  return this->TargetLinkLanguage + "_" +
+    cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()) +
+    "_DEVICE_LINKER__" + cmGlobalNinjaGenerator::EncodeRuleName(
+                           this->GetGeneratorTarget()->GetName());
+}
+
 struct cmNinjaRemoveNoOpCommands
 {
   bool operator()(std::string const& cmd)
@@ -156,9 +176,119 @@ struct cmNinjaRemoveNoOpCommands
   }
 };
 
+void cmNinjaNormalTargetGenerator::WriteDeviceLinkRule(bool useResponseFile)
+{
+  cmStateEnums::TargetType targetType = this->GetGeneratorTarget()->GetType();
+  std::string ruleName = this->LanguageLinkerDeviceRule();
+  // Select whether to use a response file for objects.
+  std::string rspfile;
+  std::string rspcontent;
+
+  if (!this->GetGlobalGenerator()->HasRule(ruleName)) {
+    cmRulePlaceholderExpander::RuleVariables vars;
+    vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
+    vars.CMTargetType =
+      cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType());
+
+    vars.Language = "CUDA";
+
+    std::string responseFlag;
+    if (!useResponseFile) {
+      vars.Objects = "$in";
+      vars.LinkLibraries = "$LINK_LIBRARIES";
+    } else {
+      std::string cmakeVarLang = "CMAKE_";
+      cmakeVarLang += this->TargetLinkLanguage;
+
+      // build response file name
+      std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
+      const char* flag = GetMakefile()->GetDefinition(cmakeLinkVar);
+      if (flag) {
+        responseFlag = flag;
+      } else {
+        responseFlag = "@";
+      }
+      rspfile = "$RSP_FILE";
+      responseFlag += rspfile;
+
+      // build response file content
+      if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
+        rspcontent = "$in";
+      } else {
+        rspcontent = "$in_newline";
+      }
+      rspcontent += " $LINK_LIBRARIES";
+      vars.Objects = responseFlag.c_str();
+      vars.LinkLibraries = "";
+    }
+
+    vars.ObjectDir = "$OBJECT_DIR";
+
+    vars.Target = "$TARGET_FILE";
+
+    vars.SONameFlag = "$SONAME_FLAG";
+    vars.TargetSOName = "$SONAME";
+    vars.TargetPDB = "$TARGET_PDB";
+    vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
+
+    vars.Flags = "$FLAGS";
+    vars.LinkFlags = "$LINK_FLAGS";
+    vars.Manifests = "$MANIFESTS";
+
+    std::string langFlags;
+    if (targetType != cmStateEnums::EXECUTABLE) {
+      langFlags += "$LANGUAGE_COMPILE_FLAGS $ARCH_FLAGS";
+      vars.LanguageCompileFlags = langFlags.c_str();
+    }
+
+    std::string launcher;
+    const char* val = this->GetLocalGenerator()->GetRuleLauncher(
+      this->GetGeneratorTarget(), "RULE_LAUNCH_LINK");
+    if (val && *val) {
+      launcher = val;
+      launcher += " ";
+    }
+
+    CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+      this->GetLocalGenerator()->CreateRulePlaceholderExpander());
+
+    // Rule for linking library/executable.
+    std::vector<std::string> linkCmds = this->ComputeDeviceLinkCmd();
+    for (std::vector<std::string>::iterator i = linkCmds.begin();
+         i != linkCmds.end(); ++i) {
+      *i = launcher + *i;
+      rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
+                                                   *i, vars);
+    }
+    {
+      // If there is no ranlib the command will be ":".  Skip it.
+      std::vector<std::string>::iterator newEnd = std::remove_if(
+        linkCmds.begin(), linkCmds.end(), cmNinjaRemoveNoOpCommands());
+      linkCmds.erase(newEnd, linkCmds.end());
+    }
+
+    std::string linkCmd =
+      this->GetLocalGenerator()->BuildCommandLine(linkCmds);
+
+    // Write the linker rule with response file if needed.
+    std::ostringstream comment;
+    comment << "Rule for linking " << this->TargetLinkLanguage << " "
+            << this->GetVisibleTypeName() << ".";
+    std::ostringstream description;
+    description << "Linking " << this->TargetLinkLanguage << " "
+                << this->GetVisibleTypeName() << " $TARGET_FILE";
+    this->GetGlobalGenerator()->AddRule(ruleName, linkCmd, description.str(),
+                                        comment.str(),
+                                        /*depfile*/ "",
+                                        /*deptype*/ "", rspfile, rspcontent,
+                                        /*restat*/ "$RESTAT",
+                                        /*generator*/ false);
+  }
+}
+
 void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
 {
-  cmState::TargetType targetType = this->GetGeneratorTarget()->GetType();
+  cmStateEnums::TargetType targetType = this->GetGeneratorTarget()->GetType();
   std::string ruleName = this->LanguageLinkerRule();
 
   // Select whether to use a response file for objects.
@@ -166,9 +296,11 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
   std::string rspcontent;
 
   if (!this->GetGlobalGenerator()->HasRule(ruleName)) {
-    cmLocalGenerator::RuleVariables vars;
-    vars.RuleLauncher = "RULE_LAUNCH_LINK";
-    vars.CMTarget = this->GetGeneratorTarget();
+    cmRulePlaceholderExpander::RuleVariables vars;
+    vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
+    vars.CMTargetType =
+      cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType());
+
     vars.Language = this->TargetLinkLanguage.c_str();
 
     std::string responseFlag;
@@ -232,16 +364,29 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
     vars.Manifests = "$MANIFESTS";
 
     std::string langFlags;
-    if (targetType != cmState::EXECUTABLE) {
+    if (targetType != cmStateEnums::EXECUTABLE) {
       langFlags += "$LANGUAGE_COMPILE_FLAGS $ARCH_FLAGS";
       vars.LanguageCompileFlags = langFlags.c_str();
     }
 
+    std::string launcher;
+    const char* val = this->GetLocalGenerator()->GetRuleLauncher(
+      this->GetGeneratorTarget(), "RULE_LAUNCH_LINK");
+    if (val && *val) {
+      launcher = val;
+      launcher += " ";
+    }
+
+    CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+      this->GetLocalGenerator()->CreateRulePlaceholderExpander());
+
     // Rule for linking library/executable.
     std::vector<std::string> linkCmds = this->ComputeLinkCmd();
     for (std::vector<std::string>::iterator i = linkCmds.begin();
          i != linkCmds.end(); ++i) {
-      this->GetLocalGenerator()->ExpandRuleVariables(*i, vars);
+      *i = launcher + *i;
+      rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
+                                                   *i, vars);
     }
     {
       // If there is no ranlib the command will be ":".  Skip it.
@@ -275,7 +420,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
     std::string cmakeCommand =
       this->GetLocalGenerator()->ConvertToOutputFormat(
         cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
-    if (targetType == cmState::EXECUTABLE) {
+    if (targetType == cmStateEnums::EXECUTABLE) {
       this->GetGlobalGenerator()->AddRule(
         "CMAKE_SYMLINK_EXECUTABLE",
         cmakeCommand + " -E cmake_symlink_executable"
@@ -305,11 +450,40 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
   }
 }
 
+std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeDeviceLinkCmd()
+{
+  std::vector<std::string> linkCmds;
+
+  // this target requires separable cuda compilation
+  // now build the correct command depending on if the target is
+  // an executable or a dynamic library.
+  std::string linkCmd;
+  switch (this->GetGeneratorTarget()->GetType()) {
+    case cmStateEnums::SHARED_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY: {
+      const std::string cudaLinkCmd(
+        this->GetMakefile()->GetDefinition("CMAKE_CUDA_DEVICE_LINK_LIBRARY"));
+      cmSystemTools::ExpandListArgument(cudaLinkCmd, linkCmds);
+    } break;
+    case cmStateEnums::EXECUTABLE: {
+      const std::string cudaLinkCmd(this->GetMakefile()->GetDefinition(
+        "CMAKE_CUDA_DEVICE_LINK_EXECUTABLE"));
+      cmSystemTools::ExpandListArgument(cudaLinkCmd, linkCmds);
+    } break;
+    default:
+      break;
+  }
+  return linkCmds;
+}
+
 std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd()
 {
   std::vector<std::string> linkCmds;
   cmMakefile* mf = this->GetMakefile();
   {
+    // If we have a rule variable prefer it. In the case of static libraries
+    // this occurs when things like IPO is enabled, and we need to use the
+    // CMAKE_<lang>_CREATE_STATIC_LIBRARY_IPO define instead.
     std::string linkCmdVar = this->GetGeneratorTarget()->GetCreateRuleVariable(
       this->TargetLinkLanguage, this->GetConfigName());
     const char* linkCmd = mf->GetDefinition(linkCmdVar);
@@ -335,7 +509,7 @@ std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd()
     }
   }
   switch (this->GetGeneratorTarget()->GetType()) {
-    case cmState::STATIC_LIBRARY: {
+    case cmStateEnums::STATIC_LIBRARY: {
       // We have archive link commands set. First, delete the existing archive.
       {
         std::string cmakeCommand =
@@ -360,12 +534,12 @@ std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd()
       }
       return linkCmds;
     }
-    case cmState::SHARED_LIBRARY:
-    case cmState::MODULE_LIBRARY:
-    case cmState::EXECUTABLE:
+    case cmStateEnums::SHARED_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
+    case cmStateEnums::EXECUTABLE:
       break;
     default:
-      assert(0 && "Unexpected target type");
+      assert(false && "Unexpected target type");
   }
   return std::vector<std::string>();
 }
@@ -376,10 +550,6 @@ static int calculateCommandLineLengthLimit(int linkRuleLength)
 #ifdef _WIN32
     8000,
 #endif
-#if defined(_SC_ARG_MAX)
-    // for instance ARG_MAX is 2096152 on Ubuntu or 262144 on Mac
-    ((int)sysconf(_SC_ARG_MAX)) - 1000,
-#endif
 #if defined(__linux)
     // #define MAX_ARG_STRLEN (PAGE_SIZE * 32) in Linux's binfmts.h
     ((int)sysconf(_SC_PAGESIZE) * 32) - 1000,
@@ -388,7 +558,15 @@ static int calculateCommandLineLengthLimit(int linkRuleLength)
   };
 
   size_t const arrSz = cmArraySize(limits);
-  int const sz = *std::min_element(limits, limits + arrSz);
+  int sz = *std::min_element(limits, limits + arrSz);
+#if defined(_SC_ARG_MAX)
+  // for instance ARG_MAX is 2096152 on Ubuntu or 262144 on Mac
+  int const szArgMax = static_cast<int>(sysconf(_SC_ARG_MAX));
+  // a return value of -1 signifies an unrestricted value
+  if (szArgMax != -1) {
+    sz = std::min(sz, szArgMax - 1000);
+  }
+#endif
   if (sz == std::numeric_limits<int>::max()) {
     return 0;
   }
@@ -396,6 +574,213 @@ static int calculateCommandLineLengthLimit(int linkRuleLength)
   return sz - linkRuleLength;
 }
 
+void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatement()
+{
+  cmGeneratorTarget& genTarget = *this->GetGeneratorTarget();
+
+  // determine if we need to do any device linking for this target
+  const std::string cuda_lang("CUDA");
+  cmGeneratorTarget::LinkClosure const* closure =
+    genTarget.GetLinkClosure(this->GetConfigName());
+
+  const bool hasCUDA =
+    (std::find(closure->Languages.begin(), closure->Languages.end(),
+               cuda_lang) != closure->Languages.end());
+
+  bool shouldHaveDeviceLinking = false;
+  switch (genTarget.GetType()) {
+    case cmStateEnums::SHARED_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
+    case cmStateEnums::EXECUTABLE:
+      shouldHaveDeviceLinking = true;
+      break;
+    default:
+      break;
+  }
+
+  if (!shouldHaveDeviceLinking || !hasCUDA) {
+    return;
+  }
+
+  // Now we can do device linking
+
+  // First and very important step is to make sure while inside this
+  // step our link language is set to CUDA
+  std::string cudaLinkLanguage = "CUDA";
+  std::string const objExt =
+    this->Makefile->GetSafeDefinition("CMAKE_CUDA_OUTPUT_EXTENSION");
+
+  std::string const cfgName = this->GetConfigName();
+  std::string const targetOutputReal = ConvertToNinjaPath(
+    genTarget.ObjectDirectory + "cmake_device_link" + objExt);
+
+  std::string const targetOutputImplib =
+    ConvertToNinjaPath(genTarget.GetFullPath(cfgName,
+                                             /*implib=*/true));
+
+  this->DeviceLinkObject = targetOutputReal;
+
+  // Write comments.
+  cmGlobalNinjaGenerator::WriteDivider(this->GetBuildFileStream());
+  const cmStateEnums::TargetType targetType = genTarget.GetType();
+  this->GetBuildFileStream() << "# Device Link build statements for "
+                             << cmState::GetTargetTypeName(targetType)
+                             << " target " << this->GetTargetName() << "\n\n";
+
+  // Compute the comment.
+  std::ostringstream comment;
+  comment << "Link the " << this->GetVisibleTypeName() << " "
+          << targetOutputReal;
+
+  cmNinjaDeps emptyDeps;
+  cmNinjaVars vars;
+
+  // Compute outputs.
+  cmNinjaDeps outputs;
+  outputs.push_back(targetOutputReal);
+  // Compute specific libraries to link with.
+  cmNinjaDeps explicitDeps = this->GetObjects();
+  cmNinjaDeps implicitDeps = this->ComputeLinkDeps();
+
+  std::string frameworkPath;
+  std::string linkPath;
+
+  std::string createRule = genTarget.GetCreateRuleVariable(
+    this->TargetLinkLanguage, this->GetConfigName());
+  const bool useWatcomQuote =
+    this->GetMakefile()->IsOn(createRule + "_USE_WATCOM_QUOTE");
+  cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
+
+  vars["TARGET_FILE"] =
+    localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
+
+  CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+    new cmNinjaLinkLineDeviceComputer(
+      this->GetLocalGenerator(),
+      this->GetLocalGenerator()->GetStateSnapshot().GetDirectory(),
+      this->GetGlobalGenerator()));
+  linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
+
+  localGen.GetTargetFlags(
+    linkLineComputer.get(), this->GetConfigName(), vars["LINK_LIBRARIES"],
+    vars["FLAGS"], vars["LINK_FLAGS"], frameworkPath, linkPath, &genTarget);
+
+  this->addPoolNinjaVariable("JOB_POOL_LINK", &genTarget, vars);
+
+  vars["LINK_FLAGS"] =
+    cmGlobalNinjaGenerator::EncodeLiteral(vars["LINK_FLAGS"]);
+
+  vars["MANIFESTS"] = this->GetManifests();
+
+  vars["LINK_PATH"] = frameworkPath + linkPath;
+
+  // Compute architecture specific link flags.  Yes, these go into a different
+  // variable for executables, probably due to a mistake made when duplicating
+  // code between the Makefile executable and library generators.
+  if (targetType == cmStateEnums::EXECUTABLE) {
+    std::string t = vars["FLAGS"];
+    localGen.AddArchitectureFlags(t, &genTarget, cudaLinkLanguage, cfgName);
+    vars["FLAGS"] = t;
+  } else {
+    std::string t = vars["ARCH_FLAGS"];
+    localGen.AddArchitectureFlags(t, &genTarget, cudaLinkLanguage, cfgName);
+    vars["ARCH_FLAGS"] = t;
+    t = "";
+    localGen.AddLanguageFlags(t, cudaLinkLanguage, cfgName);
+    vars["LANGUAGE_COMPILE_FLAGS"] = t;
+  }
+  if (this->GetGeneratorTarget()->HasSOName(cfgName)) {
+    vars["SONAME_FLAG"] =
+      this->GetMakefile()->GetSONameFlag(this->TargetLinkLanguage);
+    vars["SONAME"] = this->TargetNameSO;
+    if (targetType == cmStateEnums::SHARED_LIBRARY) {
+      std::string install_dir =
+        this->GetGeneratorTarget()->GetInstallNameDirForBuildTree(cfgName);
+      if (!install_dir.empty()) {
+        vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
+          install_dir, cmOutputConverter::SHELL);
+      }
+    }
+  }
+
+  cmNinjaDeps byproducts;
+
+  if (!this->TargetNameImport.empty()) {
+    const std::string impLibPath = localGen.ConvertToOutputFormat(
+      targetOutputImplib, cmOutputConverter::SHELL);
+    vars["TARGET_IMPLIB"] = impLibPath;
+    EnsureParentDirectoryExists(impLibPath);
+    if (genTarget.HasImportLibrary()) {
+      byproducts.push_back(targetOutputImplib);
+    }
+  }
+
+  const std::string objPath = GetGeneratorTarget()->GetSupportDirectory();
+  vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
+    this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
+  EnsureDirectoryExists(objPath);
+
+  this->SetMsvcTargetPdbVariable(vars);
+
+  if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
+    // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
+    std::string& linkLibraries = vars["LINK_LIBRARIES"];
+    std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
+    std::string& link_path = vars["LINK_PATH"];
+    std::replace(link_path.begin(), link_path.end(), '\\', '/');
+  }
+
+  const std::vector<cmCustomCommand>* cmdLists[3] = {
+    &genTarget.GetPreBuildCommands(), &genTarget.GetPreLinkCommands(),
+    &genTarget.GetPostBuildCommands()
+  };
+
+  std::vector<std::string> preLinkCmdLines, postBuildCmdLines;
+  vars["PRE_LINK"] = localGen.BuildCommandLine(preLinkCmdLines);
+  vars["POST_BUILD"] = localGen.BuildCommandLine(postBuildCmdLines);
+
+  std::vector<std::string>* cmdLineLists[3] = { &preLinkCmdLines,
+                                                &preLinkCmdLines,
+                                                &postBuildCmdLines };
+
+  for (unsigned i = 0; i != 3; ++i) {
+    for (std::vector<cmCustomCommand>::const_iterator ci =
+           cmdLists[i]->begin();
+         ci != cmdLists[i]->end(); ++ci) {
+      cmCustomCommandGenerator ccg(*ci, cfgName, this->GetLocalGenerator());
+      localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
+      std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
+      std::transform(ccByproducts.begin(), ccByproducts.end(),
+                     std::back_inserter(byproducts), MapToNinjaPath());
+    }
+  }
+
+  cmGlobalNinjaGenerator& globalGen = *this->GetGlobalGenerator();
+
+  // Device linking currently doesn't support response files so
+  // do not check if the user has explicitly forced a response file.
+  int const commandLineLengthLimit = calculateCommandLineLengthLimit(
+    globalGen.GetRuleCmdLength(this->LanguageLinkerDeviceRule()));
+
+  const std::string rspfile =
+    std::string(cmake::GetCMakeFilesDirectoryPostSlash()) +
+    genTarget.GetName() + ".rsp";
+
+  // Gather order-only dependencies.
+  cmNinjaDeps orderOnlyDeps;
+  this->GetLocalGenerator()->AppendTargetDepends(this->GetGeneratorTarget(),
+                                                 orderOnlyDeps);
+
+  // Write the build statement for this target.
+  bool usedResponseFile = false;
+  globalGen.WriteBuild(this->GetBuildFileStream(), comment.str(),
+                       this->LanguageLinkerDeviceRule(), outputs,
+                       /*implicitOuts=*/cmNinjaDeps(), explicitDeps,
+                       implicitDeps, orderOnlyDeps, vars, rspfile,
+                       commandLineLengthLimit, &usedResponseFile);
+  this->WriteDeviceLinkRule(usedResponseFile);
+}
+
 void cmNinjaNormalTargetGenerator::WriteLinkStatement()
 {
   cmGeneratorTarget& gt = *this->GetGeneratorTarget();
@@ -435,7 +820,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
 
   // Write comments.
   cmGlobalNinjaGenerator::WriteDivider(this->GetBuildFileStream());
-  const cmState::TargetType targetType = gt.GetType();
+  const cmStateEnums::TargetType targetType = gt.GetType();
   this->GetBuildFileStream() << "# Link build statements for "
                              << cmState::GetTargetTypeName(targetType)
                              << " target " << this->GetTargetName() << "\n\n";
@@ -456,6 +841,10 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
   cmNinjaDeps explicitDeps = this->GetObjects();
   cmNinjaDeps implicitDeps = this->ComputeLinkDeps();
 
+  if (!this->DeviceLinkObject.empty()) {
+    explicitDeps.push_back(this->DeviceLinkObject);
+  }
+
   cmMakefile* mf = this->GetMakefile();
 
   std::string frameworkPath;
@@ -470,11 +859,18 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
   vars["TARGET_FILE"] =
     localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
 
-  localGen.GetTargetFlags(this->GetConfigName(), vars["LINK_LIBRARIES"],
-                          vars["FLAGS"], vars["LINK_FLAGS"], frameworkPath,
-                          linkPath, &genTarget, useWatcomQuote);
+  CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+    this->GetGlobalGenerator()->CreateLinkLineComputer(
+      this->GetLocalGenerator(),
+      this->GetLocalGenerator()->GetStateSnapshot().GetDirectory()));
+  linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
+
+  localGen.GetTargetFlags(
+    linkLineComputer.get(), this->GetConfigName(), vars["LINK_LIBRARIES"],
+    vars["FLAGS"], vars["LINK_FLAGS"], frameworkPath, linkPath, &genTarget);
+
   if (this->GetMakefile()->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") &&
-      (gt.GetType() == cmState::SHARED_LIBRARY ||
+      (gt.GetType() == cmStateEnums::SHARED_LIBRARY ||
        gt.IsExecutableWithExports())) {
     if (gt.GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
       std::string name_of_def_file = gt.GetSupportDirectory();
@@ -487,8 +883,8 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
   }
 
   // Add OS X version flags, if any.
-  if (this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY ||
-      this->GeneratorTarget->GetType() == cmState::MODULE_LIBRARY) {
+  if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
+      this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
     this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
                            "COMPATIBILITY", true);
     this->AppendOSXVerFlag(vars["LINK_FLAGS"], this->TargetLinkLanguage,
@@ -497,7 +893,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
 
   this->addPoolNinjaVariable("JOB_POOL_LINK", &gt, vars);
 
-  this->AddModuleDefinitionFlag(vars["LINK_FLAGS"]);
+  this->AddModuleDefinitionFlag(linkLineComputer.get(), vars["LINK_FLAGS"]);
   vars["LINK_FLAGS"] =
     cmGlobalNinjaGenerator::EncodeLiteral(vars["LINK_FLAGS"]);
 
@@ -512,7 +908,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
   // Compute architecture specific link flags.  Yes, these go into a different
   // variable for executables, probably due to a mistake made when duplicating
   // code between the Makefile executable and library generators.
-  if (targetType == cmState::EXECUTABLE) {
+  if (targetType == cmStateEnums::EXECUTABLE) {
     std::string t = vars["FLAGS"];
     localGen.AddArchitectureFlags(t, &genTarget, TargetLinkLanguage, cfgName);
     t += lwyuFlags;
@@ -529,7 +925,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
   if (this->GetGeneratorTarget()->HasSOName(cfgName)) {
     vars["SONAME_FLAG"] = mf->GetSONameFlag(this->TargetLinkLanguage);
     vars["SONAME"] = this->TargetNameSO;
-    if (targetType == cmState::SHARED_LIBRARY) {
+    if (targetType == cmStateEnums::SHARED_LIBRARY) {
       std::string install_dir =
         this->GetGeneratorTarget()->GetInstallNameDirForBuildTree(cfgName);
       if (!install_dir.empty()) {
@@ -602,7 +998,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
   }
 
   // maybe create .def file from list of objects
-  if ((gt.GetType() == cmState::SHARED_LIBRARY ||
+  if ((gt.GetType() == cmStateEnums::SHARED_LIBRARY ||
        gt.IsExecutableWithExports()) &&
       this->GetMakefile()->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
     if (gt.GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS")) {
@@ -650,13 +1046,15 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
   if (!symlinkNeeded) {
     vars["POST_BUILD"] = postBuildCmdLine;
   } else {
-    vars["POST_BUILD"] = ":";
+    vars["POST_BUILD"] = cmGlobalNinjaGenerator::SHELL_NOOP;
     symlinkVars["POST_BUILD"] = postBuildCmdLine;
   }
   cmGlobalNinjaGenerator& globalGen = *this->GetGlobalGenerator();
 
+  bool const lang_supports_response =
+    !(this->TargetLinkLanguage == "RC" || this->TargetLinkLanguage == "CUDA");
   int commandLineLengthLimit = -1;
-  if (!this->ForceResponseFile()) {
+  if (!lang_supports_response || !this->ForceResponseFile()) {
     commandLineLengthLimit = calculateCommandLineLengthLimit(
       globalGen.GetRuleCmdLength(this->LanguageLinkerRule()));
   }
@@ -690,7 +1088,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
   this->WriteLinkRule(usedResponseFile);
 
   if (symlinkNeeded) {
-    if (targetType == cmState::EXECUTABLE) {
+    if (targetType == cmStateEnums::EXECUTABLE) {
       globalGen.WriteBuild(
         this->GetBuildFileStream(),
         "Create executable symlink " + targetOutput,
diff --git a/Source/cmNinjaNormalTargetGenerator.h b/Source/cmNinjaNormalTargetGenerator.h
index 5bd906f..e5595ea 100644
--- a/Source/cmNinjaNormalTargetGenerator.h
+++ b/Source/cmNinjaNormalTargetGenerator.h
@@ -22,12 +22,21 @@ public:
 
 private:
   std::string LanguageLinkerRule() const;
+  std::string LanguageLinkerDeviceRule() const;
+
   const char* GetVisibleTypeName() const;
   void WriteLanguagesRules();
+
   void WriteLinkRule(bool useResponseFile);
+  void WriteDeviceLinkRule(bool useResponseFile);
+
   void WriteLinkStatement();
+  void WriteDeviceLinkStatement();
+
   void WriteObjectLibStatement();
+
   std::vector<std::string> ComputeLinkCmd();
+  std::vector<std::string> ComputeDeviceLinkCmd();
 
 private:
   // Target name info.
@@ -37,6 +46,7 @@ private:
   std::string TargetNameImport;
   std::string TargetNamePDB;
   std::string TargetLinkLanguage;
+  std::string DeviceLinkObject;
 };
 
 #endif // ! cmNinjaNormalTargetGenerator_h
diff --git a/Source/cmNinjaTargetGenerator.cxx b/Source/cmNinjaTargetGenerator.cxx
index 46a6161..d57b8f7 100644
--- a/Source/cmNinjaTargetGenerator.cxx
+++ b/Source/cmNinjaTargetGenerator.cxx
@@ -2,10 +2,20 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmNinjaTargetGenerator.h"
 
+#include <algorithm>
+#include <assert.h>
+#include <cm_jsoncpp_value.h>
+#include <cm_jsoncpp_writer.h>
+#include <iterator>
+#include <map>
+#include <sstream>
+#include <string.h>
+
 #include "cmAlgorithms.h"
 #include "cmComputeLinkInformation.h"
 #include "cmCustomCommandGenerator.h"
 #include "cmGeneratedFileStream.h"
+#include "cmGeneratorExpression.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalNinjaGenerator.h"
 #include "cmLocalGenerator.h"
@@ -14,31 +24,26 @@
 #include "cmNinjaNormalTargetGenerator.h"
 #include "cmNinjaUtilityTargetGenerator.h"
 #include "cmOutputConverter.h"
+#include "cmRulePlaceholderExpander.h"
 #include "cmSourceFile.h"
 #include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
 #include "cmake.h"
 
-#include "cm_jsoncpp_writer.h"
-
-#include <algorithm>
-#include <iterator>
-#include <map>
-#include <sstream>
-#include <string.h>
-
 cmNinjaTargetGenerator* cmNinjaTargetGenerator::New(cmGeneratorTarget* target)
 {
   switch (target->GetType()) {
-    case cmState::EXECUTABLE:
-    case cmState::SHARED_LIBRARY:
-    case cmState::STATIC_LIBRARY:
-    case cmState::MODULE_LIBRARY:
-    case cmState::OBJECT_LIBRARY:
+    case cmStateEnums::EXECUTABLE:
+    case cmStateEnums::SHARED_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
+    case cmStateEnums::OBJECT_LIBRARY:
       return new cmNinjaNormalTargetGenerator(target);
 
-    case cmState::UTILITY:
-    case cmState::GLOBAL_TARGET:
+    case cmStateEnums::UTILITY:
+    case cmStateEnums::GLOBAL_TARGET:
       return new cmNinjaUtilityTargetGenerator(target);
 
     default:
@@ -130,8 +135,14 @@ std::string cmNinjaTargetGenerator::ComputeFlagsForObject(
   }
 
   // Add source file specific flags.
-  this->LocalGenerator->AppendFlags(flags,
-                                    source->GetProperty("COMPILE_FLAGS"));
+  if (const char* cflags = source->GetProperty("COMPILE_FLAGS")) {
+    std::string config = this->LocalGenerator->GetConfigName();
+    cmGeneratorExpression ge;
+    CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(cflags);
+    const char* evaluatedFlags = cge->Evaluate(this->LocalGenerator, config,
+                                               false, this->GeneratorTarget);
+    this->LocalGenerator->AppendFlags(flags, evaluatedFlags);
+  }
 
   return flags;
 }
@@ -185,8 +196,8 @@ std::string cmNinjaTargetGenerator::ComputeDefines(cmSourceFile const* source,
 cmNinjaDeps cmNinjaTargetGenerator::ComputeLinkDeps() const
 {
   // Static libraries never depend on other targets for linking.
-  if (this->GeneratorTarget->GetType() == cmState::STATIC_LIBRARY ||
-      this->GeneratorTarget->GetType() == cmState::OBJECT_LIBRARY) {
+  if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
+      this->GeneratorTarget->GetType() == cmStateEnums::OBJECT_LIBRARY) {
     return cmNinjaDeps();
   }
 
@@ -273,8 +284,9 @@ std::string cmNinjaTargetGenerator::GetPreprocessedFilePath(
     objName.substr(0, objName.size() - objExt.size()) + "-pp." + ppExt;
 
   std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
-  if (!path.empty())
+  if (!path.empty()) {
     path += "/";
+  }
   path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
   path += "/";
   path += ppName;
@@ -285,8 +297,9 @@ std::string cmNinjaTargetGenerator::GetDyndepFilePath(
   std::string const& lang) const
 {
   std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
-  if (!path.empty())
+  if (!path.empty()) {
     path += "/";
+  }
   path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
   path += "/";
   path += lang;
@@ -331,24 +344,18 @@ bool cmNinjaTargetGenerator::SetMsvcTargetPdbVariable(cmNinjaVars& vars) const
 {
   cmMakefile* mf = this->GetMakefile();
   if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
-      mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID")) {
+      mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
+      mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
     std::string pdbPath;
-    std::string compilePdbPath;
-    if (this->GeneratorTarget->GetType() == cmState::EXECUTABLE ||
-        this->GeneratorTarget->GetType() == cmState::STATIC_LIBRARY ||
-        this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY ||
-        this->GeneratorTarget->GetType() == cmState::MODULE_LIBRARY) {
+    std::string compilePdbPath = this->ComputeTargetCompilePDB();
+    if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
+        this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
+        this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
+        this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
       pdbPath = this->GeneratorTarget->GetPDBDirectory(this->GetConfigName());
       pdbPath += "/";
       pdbPath += this->GeneratorTarget->GetPDBName(this->GetConfigName());
     }
-    if (this->GeneratorTarget->GetType() <= cmState::OBJECT_LIBRARY) {
-      compilePdbPath =
-        this->GeneratorTarget->GetCompilePDBPath(this->GetConfigName());
-      if (compilePdbPath.empty()) {
-        compilePdbPath = this->GeneratorTarget->GetSupportDirectory() + "/";
-      }
-    }
 
     vars["TARGET_PDB"] = this->GetLocalGenerator()->ConvertToOutputFormat(
       ConvertToNinjaPath(pdbPath), cmOutputConverter::SHELL);
@@ -373,11 +380,12 @@ void cmNinjaTargetGenerator::WriteLanguageRules(const std::string& language)
 
 void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
 {
-  cmLocalGenerator::RuleVariables vars;
-  vars.RuleLauncher = "RULE_LAUNCH_COMPILE";
-  vars.CMTarget = this->GetGeneratorTarget();
+  cmRulePlaceholderExpander::RuleVariables vars;
+  vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
+  vars.CMTargetType =
+    cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType());
   vars.Language = lang.c_str();
-  vars.Source = "$IN_ABS";
+  vars.Source = "$in";
   vars.Object = "$out";
   vars.Defines = "$DEFINES";
   vars.Includes = "$INCLUDES";
@@ -397,7 +405,8 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
   std::string rspcontent;
   std::string responseFlag;
 
-  if (lang != "RC" && this->ForceResponseFile()) {
+  bool const lang_supports_response = !(lang == "RC" || lang == "CUDA");
+  if (lang_supports_response && this->ForceResponseFile()) {
     rspfile = "$RSP_FILE";
     responseFlag = "@" + rspfile;
     rspcontent = " $DEFINES $INCLUDES $FLAGS";
@@ -452,10 +461,21 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
   vars.Flags = flags.c_str();
   vars.DependencyFile = depfile.c_str();
 
+  CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+    this->GetLocalGenerator()->CreateRulePlaceholderExpander());
+
   std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat(
     ConvertToNinjaPath(this->GetTargetDependInfoPath(lang)),
     cmLocalGenerator::SHELL);
 
+  std::string launcher;
+  const char* val = this->GetLocalGenerator()->GetRuleLauncher(
+    this->GetGeneratorTarget(), "RULE_LAUNCH_COMPILE");
+  if (val && *val) {
+    launcher = val;
+    launcher += " ";
+  }
+
   if (explicitPP) {
     // Lookup the explicit preprocessing rule.
     std::string const ppVar = "CMAKE_" + lang + "_PREPROCESS_SOURCE";
@@ -463,12 +483,12 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
       this->GetMakefile()->GetRequiredDefinition(ppVar);
 
     // Explicit preprocessing always uses a depfile.
-    std::string const ppDeptype = ""; // no deps= for multiple outputs
+    std::string const ppDeptype; // no deps= for multiple outputs
     std::string const ppDepfile = "$DEP_FILE";
 
-    cmLocalGenerator::RuleVariables ppVars;
-    ppVars.RuleLauncher = vars.RuleLauncher;
-    ppVars.CMTarget = vars.CMTarget;
+    cmRulePlaceholderExpander::RuleVariables ppVars;
+    ppVars.CMTargetName = vars.CMTargetName;
+    ppVars.CMTargetType = vars.CMTargetType;
     ppVars.Language = vars.Language;
     ppVars.Object = "$out"; // for RULE_LAUNCH_COMPILE
     ppVars.PreprocessedSource = "$out";
@@ -496,7 +516,9 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
 
     for (std::vector<std::string>::iterator i = ppCmds.begin();
          i != ppCmds.end(); ++i) {
-      this->GetLocalGenerator()->ExpandRuleVariables(*i, ppVars);
+      *i = launcher + *i;
+      rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
+                                                   *i, ppVars);
     }
 
     // Run CMake dependency scanner on preprocessed output.
@@ -556,10 +578,23 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
   }
 
   // Rule for compiling object file.
-  const std::string cmdVar = std::string("CMAKE_") + lang + "_COMPILE_OBJECT";
-  std::string compileCmd = mf->GetRequiredDefinition(cmdVar);
   std::vector<std::string> compileCmds;
-  cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
+  if (lang == "CUDA") {
+    std::string cmdVar;
+    if (this->GeneratorTarget->GetPropertyAsBool(
+          "CUDA_SEPARABLE_COMPILATION")) {
+      cmdVar = std::string("CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION");
+    } else {
+      cmdVar = std::string("CMAKE_CUDA_COMPILE_WHOLE_COMPILATION");
+    }
+    std::string compileCmd = mf->GetRequiredDefinition(cmdVar);
+    cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
+  } else {
+    const std::string cmdVar =
+      std::string("CMAKE_") + lang + "_COMPILE_OBJECT";
+    std::string compileCmd = mf->GetRequiredDefinition(cmdVar);
+    cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
+  }
 
   // Maybe insert an include-what-you-use runner.
   if (!compileCmds.empty() && (lang == "C" || lang == "CXX")) {
@@ -567,7 +602,9 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
     const char* iwyu = this->GeneratorTarget->GetProperty(iwyu_prop);
     std::string const tidy_prop = lang + "_CLANG_TIDY";
     const char* tidy = this->GeneratorTarget->GetProperty(tidy_prop);
-    if ((iwyu && *iwyu) || (tidy && *tidy)) {
+    std::string const cpplint_prop = lang + "_CPPLINT";
+    const char* cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
+    if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint)) {
       std::string run_iwyu = this->GetLocalGenerator()->ConvertToOutputFormat(
         cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
       run_iwyu += " -E __run_iwyu";
@@ -578,6 +615,12 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
       if (tidy && *tidy) {
         run_iwyu += " --tidy=";
         run_iwyu += this->GetLocalGenerator()->EscapeForShell(tidy);
+      }
+      if (cpplint && *cpplint) {
+        run_iwyu += " --cpplint=";
+        run_iwyu += this->GetLocalGenerator()->EscapeForShell(cpplint);
+      }
+      if ((tidy && *tidy) || (cpplint && *cpplint)) {
         run_iwyu += " --source=$in";
       }
       run_iwyu += " -- ";
@@ -608,7 +651,9 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
 
   for (std::vector<std::string>::iterator i = compileCmds.begin();
        i != compileCmds.end(); ++i) {
-    this->GetLocalGenerator()->ExpandRuleVariables(*i, vars);
+    *i = launcher + *i;
+    rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), *i,
+                                                 vars);
   }
 
   std::string cmdLine =
@@ -729,7 +774,8 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement(
   cmSourceFile const* source, bool writeOrderDependsTargetForTarget)
 {
   std::string const language = source->GetLanguage();
-  std::string const sourceFileName = this->GetSourceFilePath(source);
+  std::string const sourceFileName =
+    language == "RC" ? source->GetFullPath() : this->GetSourceFilePath(source);
   std::string const objectDir =
     this->ConvertToNinjaPath(this->GeneratorTarget->GetSupportDirectory());
   std::string const objectFileName =
@@ -738,8 +784,6 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement(
     cmSystemTools::GetFilenamePath(objectFileName);
 
   cmNinjaVars vars;
-  vars["IN_ABS"] = this->GetLocalGenerator()->ConvertToOutputFormat(
-    source->GetFullPath(), cmOutputConverter::SHELL);
   vars["FLAGS"] = this->ComputeFlagsForObject(source, language);
   vars["DEFINES"] = this->ComputeDefines(source, language);
   vars["INCLUDES"] = this->GetIncludes(language);
@@ -887,9 +931,10 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement(
 
   this->SetMsvcTargetPdbVariable(vars);
 
-  bool const isRC = (language == "RC");
+  bool const lang_supports_response =
+    !(language == "RC" || language == "CUDA");
   int const commandLineLengthLimit =
-    ((!isRC && this->ForceResponseFile())) ? -1 : 0;
+    ((lang_supports_response && this->ForceResponseFile())) ? -1 : 0;
   std::string const rspfile = objectFileName + ".rsp";
 
   this->GetGlobalGenerator()->WriteBuild(
@@ -935,7 +980,9 @@ void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang)
                                               lang, this->GetConfigName());
   for (std::vector<std::string>::iterator i = includes.begin();
        i != includes.end(); ++i) {
-    tdi_include_dirs.append(*i);
+    // Convert the include directories the same way we do for -I flags.
+    // See upstream ninja issue 1251.
+    tdi_include_dirs.append(this->ConvertToNinjaPath(*i));
   }
 
   Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
@@ -961,7 +1008,7 @@ void cmNinjaTargetGenerator::ExportObjectCompileCommand(
     return;
   }
 
-  cmLocalGenerator::RuleVariables compileObjectVars;
+  cmRulePlaceholderExpander::RuleVariables compileObjectVars;
   compileObjectVars.Language = language.c_str();
 
   std::string escapedSourceFileName = sourceFileName;
@@ -993,9 +1040,14 @@ void cmNinjaTargetGenerator::ExportObjectCompileCommand(
   std::vector<std::string> compileCmds;
   cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
 
+  CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+    this->GetLocalGenerator()->CreateRulePlaceholderExpander());
+
   for (std::vector<std::string>::iterator i = compileCmds.begin();
        i != compileCmds.end(); ++i) {
-    this->GetLocalGenerator()->ExpandRuleVariables(*i, compileObjectVars);
+    // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
+    rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), *i,
+                                                 compileObjectVars);
   }
 
   std::string cmdLine =
diff --git a/Source/cmNinjaTypes.h b/Source/cmNinjaTypes.h
index b4eaa59..3fd536a 100644
--- a/Source/cmNinjaTypes.h
+++ b/Source/cmNinjaTypes.h
@@ -3,9 +3,11 @@
 #ifndef cmNinjaTypes_h
 #define cmNinjaTypes_h
 
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmStandardIncludes.h"
+#include <map>
+#include <string>
+#include <vector>
 
 typedef std::vector<std::string> cmNinjaDeps;
 typedef std::map<std::string, std::string> cmNinjaVars;
diff --git a/Source/cmNinjaUtilityTargetGenerator.cxx b/Source/cmNinjaUtilityTargetGenerator.cxx
index 17e35e5..500ff4a 100644
--- a/Source/cmNinjaUtilityTargetGenerator.cxx
+++ b/Source/cmNinjaUtilityTargetGenerator.cxx
@@ -12,7 +12,7 @@
 #include "cmNinjaTypes.h"
 #include "cmOutputConverter.h"
 #include "cmSourceFile.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmake.h"
 
@@ -151,7 +151,7 @@ void cmNinjaUtilityTargetGenerator::Generate()
   // Add an alias for the logical target name regardless of what directory
   // contains it.  Skip this for GLOBAL_TARGET because they are meant to
   // be per-directory and have one at the top-level anyway.
-  if (this->GetGeneratorTarget()->GetType() != cmState::GLOBAL_TARGET) {
+  if (this->GetGeneratorTarget()->GetType() != cmStateEnums::GLOBAL_TARGET) {
     this->GetGlobalGenerator()->AddTargetAlias(this->GetTargetName(),
                                                this->GetGeneratorTarget());
   }
diff --git a/Source/cmObject.h b/Source/cmObject.h
deleted file mode 100644
index 621a06f..0000000
--- a/Source/cmObject.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#ifndef cmObject_h
-#define cmObject_h
-
-#include <cmConfigure.h>
-
-#include "cmStandardIncludes.h"
-
-/** \class cmObject
- * \brief Superclass for all commands and other classes in CMake.
- *
- * cmObject is the base class for all classes in CMake. It defines some
- * methods such as GetNameOfClass, IsA, SafeDownCast.
- */
-class cmObject
-{
-public:
-  /**
-   * Need virtual destructor to destroy real command type.
-   */
-  virtual ~cmObject() {}
-
-  /**
-   * The class name of the command.
-   */
-  virtual const char* GetNameOfClass() = 0;
-
-  /**
-   * Returns true if this class is the given class, or a subclass of it.
-   */
-  static bool IsTypeOf(const char* type) { return !strcmp("cmObject", type); }
-
-  /**
-   * Returns true if this object is an instance of the given class or
-   * a subclass of it.
-   */
-  virtual bool IsA(const char* type) { return cmObject::IsTypeOf(type); }
-};
-
-#endif
diff --git a/Source/cmOptionCommand.cxx b/Source/cmOptionCommand.cxx
index 946a543..00a2d2b 100644
--- a/Source/cmOptionCommand.cxx
+++ b/Source/cmOptionCommand.cxx
@@ -2,6 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmOptionCommand.h"
 
+#include "cmAlgorithms.h"
+#include "cmMakefile.h"
+#include "cmState.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmOptionCommand
 bool cmOptionCommand::InitialPass(std::vector<std::string> const& args,
                                   cmExecutionStatus&)
@@ -32,7 +40,7 @@ bool cmOptionCommand::InitialPass(std::vector<std::string> const& args,
   cmState* state = this->Makefile->GetState();
   const char* existingValue = state->GetCacheEntryValue(args[0]);
   if (existingValue) {
-    if (state->GetCacheEntryType(args[0]) != cmState::UNINITIALIZED) {
+    if (state->GetCacheEntryType(args[0]) != cmStateEnums::UNINITIALIZED) {
       state->SetCacheEntryProperty(args[0], "HELPSTRING", args[1]);
       return true;
     }
@@ -43,6 +51,6 @@ bool cmOptionCommand::InitialPass(std::vector<std::string> const& args,
   }
   bool init = cmSystemTools::IsOn(initialValue.c_str());
   this->Makefile->AddCacheDefinition(args[0], init ? "ON" : "OFF",
-                                     args[1].c_str(), cmState::BOOL);
+                                     args[1].c_str(), cmStateEnums::BOOL);
   return true;
 }
diff --git a/Source/cmOptionCommand.h b/Source/cmOptionCommand.h
index 3ca62d7..09567ff 100644
--- a/Source/cmOptionCommand.h
+++ b/Source/cmOptionCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmOptionCommand_h
 #define cmOptionCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmOptionCommand
  * \brief Provide an option to the user
  *
@@ -34,8 +40,6 @@ public:
    * This determines if the command is invoked when in script mode.
    */
   bool IsScriptable() const CM_OVERRIDE { return true; }
-
-  cmTypeMacro(cmOptionCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmOrderDirectories.cxx b/Source/cmOrderDirectories.cxx
index 7744a5a..d48eb53 100644
--- a/Source/cmOrderDirectories.cxx
+++ b/Source/cmOrderDirectories.cxx
@@ -287,8 +287,7 @@ void cmOrderDirectories::AddRuntimeLibrary(std::string const& fullPath,
         }
       }
 
-      if (this->ImplicitDirectories.find(dir) !=
-          this->ImplicitDirectories.end()) {
+      if (this->IsImplicitDirectory(dir)) {
         this->ImplicitDirEntries.push_back(
           new cmOrderDirectoriesConstraintSOName(this, fullPath, soname));
         return;
@@ -316,8 +315,7 @@ void cmOrderDirectories::AddLinkLibrary(std::string const& fullPath)
     // Implicit link directories need special handling.
     if (!this->ImplicitDirectories.empty()) {
       std::string dir = cmSystemTools::GetFilenamePath(fullPath);
-      if (this->ImplicitDirectories.find(dir) !=
-          this->ImplicitDirectories.end()) {
+      if (this->IsImplicitDirectory(dir)) {
         this->ImplicitDirEntries.push_back(
           new cmOrderDirectoriesConstraintLibrary(this, fullPath));
         return;
@@ -347,7 +345,18 @@ void cmOrderDirectories::AddLanguageDirectories(
 void cmOrderDirectories::SetImplicitDirectories(
   std::set<std::string> const& implicitDirs)
 {
-  this->ImplicitDirectories = implicitDirs;
+  this->ImplicitDirectories.clear();
+  for (std::set<std::string>::const_iterator i = implicitDirs.begin();
+       i != implicitDirs.end(); ++i) {
+    this->ImplicitDirectories.insert(this->GetRealPath(*i));
+  }
+}
+
+bool cmOrderDirectories::IsImplicitDirectory(std::string const& dir)
+{
+  std::string const& real = this->GetRealPath(dir);
+  return this->ImplicitDirectories.find(real) !=
+    this->ImplicitDirectories.end();
 }
 
 void cmOrderDirectories::SetLinkExtensionInfo(
@@ -394,8 +403,7 @@ void cmOrderDirectories::AddOriginalDirectories(
   for (std::vector<std::string>::const_iterator di = dirs.begin();
        di != dirs.end(); ++di) {
     // We never explicitly specify implicit link directories.
-    if (this->ImplicitDirectories.find(*di) !=
-        this->ImplicitDirectories.end()) {
+    if (this->IsImplicitDirectory(*di)) {
       continue;
     }
 
diff --git a/Source/cmOrderDirectories.h b/Source/cmOrderDirectories.h
index 90a67e7..d9e0126 100644
--- a/Source/cmOrderDirectories.h
+++ b/Source/cmOrderDirectories.h
@@ -82,6 +82,8 @@ private:
   // Compare directories after resolving symlinks.
   bool IsSameDirectory(std::string const& l, std::string const& r);
 
+  bool IsImplicitDirectory(std::string const& dir);
+
   std::string const& GetRealPath(std::string const& dir);
   std::map<std::string, std::string> RealPaths;
 
diff --git a/Source/cmOutputConverter.cxx b/Source/cmOutputConverter.cxx
index 2ef603b..d6864a6 100644
--- a/Source/cmOutputConverter.cxx
+++ b/Source/cmOutputConverter.cxx
@@ -2,16 +2,19 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmOutputConverter.h"
 
-#include "cmAlgorithms.h"
-#include "cmSystemTools.h"
-
 #include <algorithm>
 #include <assert.h>
 #include <ctype.h>
 #include <set>
 #include <sstream>
+#include <vector>
 
-cmOutputConverter::cmOutputConverter(cmState::Snapshot snapshot)
+#include "cmAlgorithms.h"
+#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmSystemTools.h"
+
+cmOutputConverter::cmOutputConverter(cmStateSnapshot snapshot)
   : StateSnapshot(snapshot)
   , LinkScriptShell(false)
 {
@@ -76,44 +79,35 @@ static bool cmOutputConverterNotAbove(const char* a, const char* b)
           cmSystemTools::IsSubDirectory(a, b));
 }
 
-std::string cmOutputConverter::ConvertToRelativePath(
-  const std::vector<std::string>& local, const std::string& in_remote,
-  bool force) const
+bool cmOutputConverter::ContainedInDirectory(std::string const& local_path,
+                                             std::string const& remote_path,
+                                             cmStateDirectory directory)
 {
-  std::string local_path = cmSystemTools::JoinPath(local);
-  return force ? this->ForceToRelativePath(local_path, in_remote)
-               : this->ConvertToRelativePath(local_path, in_remote);
+  const std::string relativePathTopBinary =
+    directory.GetRelativePathTopBinary();
+  const std::string relativePathTopSource =
+    directory.GetRelativePathTopSource();
+
+  const bool bothInBinary =
+    cmOutputConverterNotAbove(local_path.c_str(),
+                              relativePathTopBinary.c_str()) &&
+    cmOutputConverterNotAbove(remote_path.c_str(),
+                              relativePathTopBinary.c_str());
+
+  const bool bothInSource =
+    cmOutputConverterNotAbove(local_path.c_str(),
+                              relativePathTopSource.c_str()) &&
+    cmOutputConverterNotAbove(remote_path.c_str(),
+                              relativePathTopSource.c_str());
+
+  return bothInSource || bothInBinary;
 }
 
 std::string cmOutputConverter::ConvertToRelativePath(
   std::string const& local_path, std::string const& remote_path) const
 {
-  // The paths should never be quoted.
-  assert(local_path[0] != '\"');
-  assert(remote_path[0] != '\"');
-
-  // The local path should never have a trailing slash.
-  assert(local_path.empty() || local_path[local_path.size() - 1] != '/');
-
-  // If the path is already relative then just return the path.
-  if (!cmSystemTools::FileIsFullPath(remote_path.c_str())) {
-    return remote_path;
-  }
-
-  // Skip conversion if the path and local are not both in the source
-  // or both in the binary tree.
-  if (!((cmOutputConverterNotAbove(
-           local_path.c_str(),
-           this->StateSnapshot.GetDirectory().GetRelativePathTopBinary()) &&
-         cmOutputConverterNotAbove(
-           remote_path.c_str(),
-           this->StateSnapshot.GetDirectory().GetRelativePathTopBinary())) ||
-        (cmOutputConverterNotAbove(
-           local_path.c_str(),
-           this->StateSnapshot.GetDirectory().GetRelativePathTopSource()) &&
-         cmOutputConverterNotAbove(
-           remote_path.c_str(),
-           this->StateSnapshot.GetDirectory().GetRelativePathTopSource())))) {
+  if (!ContainedInDirectory(local_path, remote_path,
+                            this->StateSnapshot.GetDirectory())) {
     return remote_path;
   }
 
@@ -248,10 +242,11 @@ std::string cmOutputConverter::EscapeForShell(const std::string& str,
   if (this->GetState()->UseNMake()) {
     flags |= Shell_Flag_NMake;
   }
+  if (!this->GetState()->UseWindowsShell()) {
+    flags |= Shell_Flag_IsUnix;
+  }
 
-  return this->GetState()->UseWindowsShell()
-    ? Shell_GetArgumentForWindows(str.c_str(), flags)
-    : Shell_GetArgumentForUnix(str.c_str(), flags);
+  return Shell__GetArgument(str.c_str(), flags);
 }
 
 std::string cmOutputConverter::EscapeForCMake(const std::string& str)
@@ -280,7 +275,7 @@ std::string cmOutputConverter::EscapeForCMake(const std::string& str)
 std::string cmOutputConverter::EscapeWindowsShellArgument(const char* arg,
                                                           int shell_flags)
 {
-  return Shell_GetArgumentForWindows(arg, shell_flags);
+  return Shell__GetArgument(arg, shell_flags);
 }
 
 cmOutputConverter::FortranFormat cmOutputConverter::GetFortranFormat(
@@ -366,10 +361,10 @@ int cmOutputConverter::Shell__CharNeedsQuotesOnWindows(char c)
           (c == '>') || (c == '|') || (c == '^'));
 }
 
-int cmOutputConverter::Shell__CharNeedsQuotes(char c, int isUnix, int flags)
+int cmOutputConverter::Shell__CharNeedsQuotes(char c, int flags)
 {
   /* On Windows the built-in command shell echo never needs quotes.  */
-  if (!isUnix && (flags & Shell_Flag_EchoWindows)) {
+  if (!(flags & Shell_Flag_IsUnix) && (flags & Shell_Flag_EchoWindows)) {
     return 0;
   }
 
@@ -378,7 +373,7 @@ int cmOutputConverter::Shell__CharNeedsQuotes(char c, int isUnix, int flags)
     return 1;
   }
 
-  if (isUnix) {
+  if (flags & Shell_Flag_IsUnix) {
     /* On UNIX several special characters need quotes to preserve them.  */
     if (Shell__CharNeedsQuotesOnUnix(c)) {
       return 1;
@@ -436,8 +431,7 @@ flag later when we understand applications of this better.
 */
 #define KWSYS_SYSTEM_SHELL_QUOTE_MAKE_VARIABLES 0
 
-int cmOutputConverter::Shell__ArgumentNeedsQuotes(const char* in, int isUnix,
-                                                  int flags)
+int cmOutputConverter::Shell__ArgumentNeedsQuotes(const char* in, int flags)
 {
   /* The empty string needs quotes.  */
   if (!*in) {
@@ -469,14 +463,14 @@ int cmOutputConverter::Shell__ArgumentNeedsQuotes(const char* in, int isUnix,
       }
 
       /* Check whether this character needs quotes.  */
-      if (Shell__CharNeedsQuotes(*c, isUnix, flags)) {
+      if (Shell__CharNeedsQuotes(*c, flags)) {
         return 1;
       }
     }
   }
 
   /* On Windows some single character arguments need quotes.  */
-  if (!isUnix && *in && !*(in + 1)) {
+  if (flags & Shell_Flag_IsUnix && *in && !*(in + 1)) {
     char c = *in;
     if ((c == '?') || (c == '&') || (c == '^') || (c == '|') || (c == '#')) {
       return 1;
@@ -486,8 +480,7 @@ int cmOutputConverter::Shell__ArgumentNeedsQuotes(const char* in, int isUnix,
   return 0;
 }
 
-std::string cmOutputConverter::Shell__GetArgument(const char* in, int isUnix,
-                                                  int flags)
+std::string cmOutputConverter::Shell__GetArgument(const char* in, int flags)
 {
   std::ostringstream out;
 
@@ -498,11 +491,11 @@ std::string cmOutputConverter::Shell__GetArgument(const char* in, int isUnix,
   int windows_backslashes = 0;
 
   /* Whether the argument must be quoted.  */
-  int needQuotes = Shell__ArgumentNeedsQuotes(in, isUnix, flags);
+  int needQuotes = Shell__ArgumentNeedsQuotes(in, flags);
   if (needQuotes) {
     /* Add the opening quote for this argument.  */
     if (flags & Shell_Flag_WatcomQuote) {
-      if (isUnix) {
+      if (flags & Shell_Flag_IsUnix) {
         out << '"';
       }
       out << '\'';
@@ -534,7 +527,7 @@ std::string cmOutputConverter::Shell__GetArgument(const char* in, int isUnix,
     }
 
     /* Check whether this character needs escaping for the shell.  */
-    if (isUnix) {
+    if (flags & Shell_Flag_IsUnix) {
       /* On Unix a few special characters need escaping even inside a
          quoted argument.  */
       if (*c == '\\' || *c == '"' || *c == '`' || *c == '$') {
@@ -631,7 +624,7 @@ std::string cmOutputConverter::Shell__GetArgument(const char* in, int isUnix,
     /* Add the closing quote for this argument.  */
     if (flags & Shell_Flag_WatcomQuote) {
       out << '\'';
-      if (isUnix) {
+      if (flags & Shell_Flag_IsUnix) {
         out << '"';
       }
     } else {
@@ -641,15 +634,3 @@ std::string cmOutputConverter::Shell__GetArgument(const char* in, int isUnix,
 
   return out.str();
 }
-
-std::string cmOutputConverter::Shell_GetArgumentForWindows(const char* in,
-                                                           int flags)
-{
-  return Shell__GetArgument(in, 0, flags);
-}
-
-std::string cmOutputConverter::Shell_GetArgumentForUnix(const char* in,
-                                                        int flags)
-{
-  return Shell__GetArgument(in, 1, flags);
-}
diff --git a/Source/cmOutputConverter.h b/Source/cmOutputConverter.h
index 5979eaa..a3da4cd 100644
--- a/Source/cmOutputConverter.h
+++ b/Source/cmOutputConverter.h
@@ -5,15 +5,17 @@
 
 #include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmState.h"
-
 #include <string>
-#include <vector>
+
+#include "cmStateSnapshot.h"
+
+class cmState;
+class cmStateDirectory;
 
 class cmOutputConverter
 {
 public:
-  cmOutputConverter(cmState::Snapshot snapshot);
+  cmOutputConverter(cmStateSnapshot snapshot);
 
   enum OutputFormat
   {
@@ -33,8 +35,7 @@ public:
   void SetLinkScriptShell(bool linkScriptShell);
 
   /**
-   * Flags to pass to Shell_GetArgumentForWindows or
-   * Shell_GetArgumentForUnix.  These modify the generated
+   * Flags to pass to Shell_GetArgument.  These modify the generated
    * quoting and escape sequences to work under alternative
    * environments.
    */
@@ -67,18 +68,10 @@ public:
     Shell_Flag_AllowMakeVariables = (1 << 6),
 
     /** The target shell quoting uses extra single Quotes for Watcom tools.  */
-    Shell_Flag_WatcomQuote = (1 << 7)
-  };
+    Shell_Flag_WatcomQuote = (1 << 7),
 
-  /**
-   * Transform the given command line argument for use in a Windows or
-   * Unix shell.  Returns a pointer to the end of the command line
-   * argument in the provided output buffer.  Flags may be passed to
-   * modify the generated quoting and escape sequences to work under
-   * alternative environments.
-   */
-  static std::string Shell_GetArgumentForWindows(const char* in, int flags);
-  static std::string Shell_GetArgumentForUnix(const char* in, int flags);
+    Shell_Flag_IsUnix = (1 << 8)
+  };
 
   std::string EscapeForShell(const std::string& str, bool makeVars = false,
                              bool forEcho = false,
@@ -99,16 +92,9 @@ public:
   };
   static FortranFormat GetFortranFormat(const char* value);
 
-  /**
-   * Convert the given remote path to a relative path with respect to
-   * the given local path.  The local path must be given in component
-   * form (see SystemTools::SplitPath) without a trailing slash.  The
-   * remote path must use forward slashes and not already be escaped
-   * or quoted.
-   */
-  std::string ConvertToRelativePath(const std::vector<std::string>& local,
-                                    const std::string& in_remote,
-                                    bool force = false) const;
+  static bool ContainedInDirectory(std::string const& local_path,
+                                   std::string const& remote_path,
+                                   cmStateDirectory directory);
 
   /**
    * Convert the given remote path to a relative path with respect to
@@ -134,14 +120,14 @@ private:
   static int Shell__CharIsWhitespace(char c);
   static int Shell__CharNeedsQuotesOnUnix(char c);
   static int Shell__CharNeedsQuotesOnWindows(char c);
-  static int Shell__CharNeedsQuotes(char c, int isUnix, int flags);
+  static int Shell__CharNeedsQuotes(char c, int flags);
   static int Shell__CharIsMakeVariableName(char c);
   static const char* Shell__SkipMakeVariables(const char* c);
-  static int Shell__ArgumentNeedsQuotes(const char* in, int isUnix, int flags);
-  static std::string Shell__GetArgument(const char* in, int isUnix, int flags);
+  static int Shell__ArgumentNeedsQuotes(const char* in, int flags);
+  static std::string Shell__GetArgument(const char* in, int flags);
 
 private:
-  cmState::Snapshot StateSnapshot;
+  cmStateSnapshot StateSnapshot;
 
   bool LinkScriptShell;
 };
diff --git a/Source/cmOutputRequiredFilesCommand.cxx b/Source/cmOutputRequiredFilesCommand.cxx
index 8b629fe..7a17f2c 100644
--- a/Source/cmOutputRequiredFilesCommand.cxx
+++ b/Source/cmOutputRequiredFilesCommand.cxx
@@ -2,8 +2,21 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmOutputRequiredFilesCommand.h"
 
-#include "cmAlgorithms.h"
 #include <cmsys/FStream.hxx>
+#include <cmsys/RegularExpression.hxx>
+#include <map>
+#include <utility>
+
+#include "cmAlgorithms.h"
+#include "cmGeneratorExpression.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmSourceFile.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cm_unordered_map.hxx"
+
+class cmExecutionStatus;
 
 /** \class cmDependInformation
  * \brief Store dependency information for a single source file.
@@ -167,33 +180,30 @@ protected:
     while (cmSystemTools::GetLineFromStream(fin, line)) {
       if (cmHasLiteralPrefix(line.c_str(), "#include")) {
         // if it is an include line then create a string class
-        std::string currentline = line;
-        size_t qstart = currentline.find('\"', 8);
+        size_t qstart = line.find('\"', 8);
         size_t qend;
         // if a quote is not found look for a <
         if (qstart == std::string::npos) {
-          qstart = currentline.find('<', 8);
+          qstart = line.find('<', 8);
           // if a < is not found then move on
           if (qstart == std::string::npos) {
-            cmSystemTools::Error("unknown include directive ",
-                                 currentline.c_str());
+            cmSystemTools::Error("unknown include directive ", line.c_str());
             continue;
           } else {
-            qend = currentline.find('>', qstart + 1);
+            qend = line.find('>', qstart + 1);
           }
         } else {
-          qend = currentline.find('\"', qstart + 1);
+          qend = line.find('\"', qstart + 1);
         }
         // extract the file being included
-        std::string includeFile =
-          currentline.substr(qstart + 1, qend - qstart - 1);
+        std::string includeFile = line.substr(qstart + 1, qend - qstart - 1);
         // see if the include matches the regular expression
         if (!this->IncludeFileRegularExpression.find(includeFile)) {
           if (this->Verbose) {
             std::string message = "Skipping ";
             message += includeFile;
             message += " for file ";
-            message += info->FullPath.c_str();
+            message += info->FullPath;
             cmSystemTools::Error(message.c_str(), CM_NULLPTR);
           }
           continue;
@@ -507,7 +517,7 @@ bool cmOutputRequiredFilesCommand::InitialPass(
   const cmDependInformation* info = md.FindDependencies(this->File.c_str());
   if (info) {
     // write them out
-    FILE* fout = cmsys::SystemTools::Fopen(this->OutputFile.c_str(), "w");
+    FILE* fout = cmsys::SystemTools::Fopen(this->OutputFile, "w");
     if (!fout) {
       std::string err = "Can not open output file: ";
       err += this->OutputFile;
diff --git a/Source/cmOutputRequiredFilesCommand.h b/Source/cmOutputRequiredFilesCommand.h
index 7a81a76..c4ce680 100644
--- a/Source/cmOutputRequiredFilesCommand.h
+++ b/Source/cmOutputRequiredFilesCommand.h
@@ -3,14 +3,20 @@
 #ifndef cmOutputRequiredFilesCommand_h
 #define cmOutputRequiredFilesCommand_h
 
+#include <cmConfigure.h>
+#include <set>
+#include <stdio.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
 class cmDependInformation;
+class cmExecutionStatus;
 
 class cmOutputRequiredFilesCommand : public cmCommand
 {
 public:
-  cmTypeMacro(cmOutputRequiredFilesCommand, cmCommand);
   cmCommand* Clone() CM_OVERRIDE { return new cmOutputRequiredFilesCommand; }
   bool InitialPass(std::vector<std::string> const& args,
                    cmExecutionStatus& status) CM_OVERRIDE;
diff --git a/Source/cmParseArgumentsCommand.cxx b/Source/cmParseArgumentsCommand.cxx
index 55d71ea..d75ee8e 100644
--- a/Source/cmParseArgumentsCommand.cxx
+++ b/Source/cmParseArgumentsCommand.cxx
@@ -2,7 +2,18 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmParseArgumentsCommand.h"
 
+#include <map>
+#include <set>
+#include <sstream>
+#include <stddef.h>
+#include <utility>
+
 #include "cmAlgorithms.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 static std::string escape_arg(const std::string& arg)
 {
diff --git a/Source/cmParseArgumentsCommand.h b/Source/cmParseArgumentsCommand.h
index fbeb3df..079eadb 100644
--- a/Source/cmParseArgumentsCommand.h
+++ b/Source/cmParseArgumentsCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmParseArgumentsCommand_h
 #define cmParseArgumentsCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmParseArgumentsCommand
  *
  */
@@ -32,8 +38,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "cmake_parse_arguments"; }
-
-  cmTypeMacro(cmParseArgumentsCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmPathLabel.cxx b/Source/cmPathLabel.cxx
index 19e6820..30ba081 100644
--- a/Source/cmPathLabel.cxx
+++ b/Source/cmPathLabel.cxx
@@ -2,6 +2,8 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmPathLabel.h"
 
+#include <stddef.h>
+
 cmPathLabel::cmPathLabel(const std::string& label)
   : Label(label)
   , Hash(0)
diff --git a/Source/cmPathLabel.h b/Source/cmPathLabel.h
index 5e9e423..cd9743c 100644
--- a/Source/cmPathLabel.h
+++ b/Source/cmPathLabel.h
@@ -3,9 +3,9 @@
 #ifndef cmPathLabel_h
 #define cmPathLabel_h
 
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmStandardIncludes.h"
+#include <string>
 
 /** \class cmPathLabel
  * \brief Helper class for text based labels
diff --git a/Source/cmPolicies.cxx b/Source/cmPolicies.cxx
index 3402191..6339e11 100644
--- a/Source/cmPolicies.cxx
+++ b/Source/cmPolicies.cxx
@@ -3,6 +3,7 @@
 #include "cmAlgorithms.h"
 #include "cmMakefile.h"
 #include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmVersion.h"
 #include "cmake.h"
@@ -233,7 +234,7 @@ bool cmPolicies::ApplyPolicyVersion(cmMakefile* mf, const char* version)
               "For backwards compatibility, what version of CMake "
               "commands and "
               "syntax should this version of CMake try to support.",
-              cmState::STRING);
+              cmStateEnums::STRING);
           }
         }
       }
diff --git a/Source/cmPolicies.h b/Source/cmPolicies.h
index 9b86435..62e67c7 100644
--- a/Source/cmPolicies.h
+++ b/Source/cmPolicies.h
@@ -197,7 +197,10 @@ class cmMakefile;
          3, 4, 0, cmPolicies::WARN)                                           \
   SELECT(POLICY, CMP0066,                                                     \
          "Honor per-config flags in try_compile() source-file signature.", 3, \
-         7, 0, cmPolicies::WARN)
+         7, 0, cmPolicies::WARN)                                              \
+  SELECT(POLICY, CMP0067,                                                     \
+         "Honor language standard in try_compile() source-file signature.",   \
+         3, 8, 0, cmPolicies::WARN)
 
 #define CM_SELECT_ID(F, A1, A2, A3, A4, A5, A6) F(A1)
 #define CM_FOR_EACH_POLICY_ID(POLICY)                                         \
diff --git a/Source/cmProcessOutput.cxx b/Source/cmProcessOutput.cxx
new file mode 100644
index 0000000..617e1ca
--- /dev/null
+++ b/Source/cmProcessOutput.cxx
@@ -0,0 +1,173 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#include "cmProcessOutput.h"
+
+#if defined(_WIN32)
+#include <windows.h>
+unsigned int cmProcessOutput::defaultCodepage =
+  KWSYS_ENCODING_DEFAULT_CODEPAGE;
+#endif
+
+cmProcessOutput::Encoding cmProcessOutput::FindEncoding(
+  std::string const& name)
+{
+  Encoding encoding = Auto;
+  if (name == "UTF8") {
+    encoding = UTF8;
+  } else if (name == "NONE") {
+    encoding = None;
+  } else if (name == "ANSI") {
+    encoding = ANSI;
+  } else if (name == "OEM") {
+    encoding = OEM;
+  }
+  return encoding;
+}
+
+cmProcessOutput::cmProcessOutput(Encoding encoding, unsigned int maxSize)
+{
+#if defined(_WIN32)
+  codepage = 0;
+  bufferSize = maxSize;
+  if (encoding == None) {
+    codepage = defaultCodepage;
+  } else if (encoding == Auto) {
+    codepage = GetConsoleCP();
+  } else if (encoding == UTF8) {
+    codepage = CP_UTF8;
+  } else if (encoding == OEM) {
+    codepage = GetOEMCP();
+  }
+  if (!codepage || encoding == ANSI) {
+    codepage = GetACP();
+  }
+#else
+  static_cast<void>(encoding);
+  static_cast<void>(maxSize);
+#endif
+}
+
+cmProcessOutput::~cmProcessOutput()
+{
+}
+
+bool cmProcessOutput::DecodeText(std::string raw, std::string& decoded,
+                                 size_t id)
+{
+#if !defined(_WIN32)
+  static_cast<void>(id);
+  decoded.swap(raw);
+  return true;
+#else
+  bool success = true;
+  decoded = raw;
+  if (id > 0) {
+    if (rawparts.size() < id) {
+      rawparts.reserve(id);
+      while (rawparts.size() < id)
+        rawparts.push_back(std::string());
+    }
+    raw = rawparts[id - 1] + raw;
+    rawparts[id - 1].clear();
+    decoded = raw;
+  }
+  if (raw.size() > 0 && codepage != defaultCodepage) {
+    success = false;
+    CPINFOEXW cpinfo;
+    if (id > 0 && bufferSize > 0 && raw.size() == bufferSize &&
+        GetCPInfoExW(codepage, 0, &cpinfo) == 1 && cpinfo.MaxCharSize > 1) {
+      if (cpinfo.MaxCharSize == 2 && cpinfo.LeadByte[0] != 0) {
+        LPSTR prevChar =
+          CharPrevExA(codepage, raw.c_str(), raw.c_str() + raw.size(), 0);
+        bool isLeadByte =
+          (*(prevChar + 1) == 0) && IsDBCSLeadByteEx(codepage, *prevChar);
+        if (isLeadByte) {
+          rawparts[id - 1] += *(raw.end() - 1);
+          raw.resize(raw.size() - 1);
+        }
+        success = DoDecodeText(raw, decoded, NULL);
+      } else {
+        bool restoreDecoded = false;
+        std::string firstDecoded = decoded;
+        wchar_t lastChar = 0;
+        for (UINT i = 0; i < cpinfo.MaxCharSize; i++) {
+          success = DoDecodeText(raw, decoded, &lastChar);
+          if (success && lastChar != 0) {
+            if (i == 0) {
+              firstDecoded = decoded;
+            }
+            if (lastChar == cpinfo.UnicodeDefaultChar) {
+              restoreDecoded = true;
+              rawparts[id - 1] = *(raw.end() - 1) + rawparts[id - 1];
+              raw.resize(raw.size() - 1);
+            } else {
+              restoreDecoded = false;
+              break;
+            }
+          } else {
+            break;
+          }
+        }
+        if (restoreDecoded) {
+          decoded = firstDecoded;
+          rawparts[id - 1].clear();
+        }
+      }
+    } else {
+      success = DoDecodeText(raw, decoded, NULL);
+    }
+  }
+  return success;
+#endif
+}
+
+bool cmProcessOutput::DecodeText(const char* data, size_t length,
+                                 std::string& decoded, size_t id)
+{
+  return DecodeText(std::string(data, length), decoded, id);
+}
+
+bool cmProcessOutput::DecodeText(std::vector<char> raw,
+                                 std::vector<char>& decoded, size_t id)
+{
+  std::string str;
+  const bool success =
+    DecodeText(std::string(raw.begin(), raw.end()), str, id);
+  decoded.assign(str.begin(), str.end());
+  return success;
+}
+
+#if defined(_WIN32)
+bool cmProcessOutput::DoDecodeText(std::string raw, std::string& decoded,
+                                   wchar_t* lastChar)
+{
+  bool success = false;
+  const int wlength =
+    MultiByteToWideChar(codepage, 0, raw.c_str(), int(raw.size()), NULL, 0);
+  wchar_t* wdata = new wchar_t[wlength];
+  int r = MultiByteToWideChar(codepage, 0, raw.c_str(), int(raw.size()), wdata,
+                              wlength);
+  if (r > 0) {
+    if (lastChar) {
+      *lastChar = 0;
+      if ((wlength >= 2 && wdata[wlength - 2] != wdata[wlength - 1]) ||
+          wlength >= 1) {
+        *lastChar = wdata[wlength - 1];
+      }
+    }
+    int length = WideCharToMultiByte(defaultCodepage, 0, wdata, wlength, NULL,
+                                     0, NULL, NULL);
+    char* data = new char[length];
+    r = WideCharToMultiByte(defaultCodepage, 0, wdata, wlength, data, length,
+                            NULL, NULL);
+    if (r > 0) {
+      decoded = std::string(data, length);
+      success = true;
+    }
+    delete[] data;
+  }
+  delete[] wdata;
+  return success;
+}
+#endif
diff --git a/Source/cmProcessOutput.h b/Source/cmProcessOutput.h
new file mode 100644
index 0000000..d2e631f
--- /dev/null
+++ b/Source/cmProcessOutput.h
@@ -0,0 +1,88 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef cmProcessOutput_h
+#define cmProcessOutput_h
+
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <stddef.h>
+#include <string>
+#include <vector>
+
+/** \class cmProcessOutput
+ * \brief Decode text data to internal encoding.
+ *
+ * cmProcessOutput is used to decode text output from external process
+ * using external encoding to our internal encoding.
+ */
+class cmProcessOutput
+{
+public:
+  enum Encoding
+  {
+    None,
+    Auto,
+    UTF8,
+    ANSI,
+    OEM
+  };
+
+  /**
+  * Find encoding enum value for given encoding \a name.
+  * \param name a encoding name.
+  * \return encoding enum value or Auto if \a name was not found.
+  */
+  static Encoding FindEncoding(std::string const& name);
+
+  /// The code page that is used as internal encoding to which we will encode.
+  static unsigned int defaultCodepage;
+
+  /**
+   * A class constructor.
+   * \param encoding external process encoding from which we will decode.
+   * \param maxSize a maximal size for process output buffer. It should match
+   * to KWSYSPE_PIPE_BUFFER_SIZE. If text we decode is same size as \a maxSize
+   * then we will check for incomplete character at end of buffer and
+   * we will not return last incomplete character. This character will be
+   * returned with next DecodeText() call. To disable this behavior specify
+   * 0 as \a maxSize.
+   */
+  cmProcessOutput(Encoding encoding = Auto, unsigned int maxSize = 1024);
+  ~cmProcessOutput();
+  /**
+   * Decode \a raw string using external encoding to internal
+   * encoding in \a decoded.
+   * \a id specifies which internal buffer to use. This is important when we
+   * are decoding both stdout and stderr from process output and we need to
+   * keep incomplete characters in separate buffers for each stream.
+   * \return true if successfully decoded \a raw to \a decoded or false if not.
+   */
+  bool DecodeText(std::string raw, std::string& decoded, size_t id = 0);
+  /**
+   * Decode \a data with \a length from external encoding to internal
+   * encoding in \a decoded.
+   * \param data a pointer to process output text data.
+   * \param length a size of data buffer.
+   * \param decoded a string which will contain decoded text.
+   * \param id an internal buffer id to use.
+   * \return true if successfully decoded \a data to \a decoded or false if
+   * not.
+   */
+  bool DecodeText(const char* data, size_t length, std::string& decoded,
+                  size_t id = 0);
+  /**
+   * \overload
+   */
+  bool DecodeText(std::vector<char> raw, std::vector<char>& decoded,
+                  size_t id = 0);
+
+private:
+#if defined(_WIN32)
+  unsigned int codepage;
+  unsigned int bufferSize;
+  std::vector<std::string> rawparts;
+  bool DoDecodeText(std::string raw, std::string& decoded, wchar_t* lastChar);
+#endif
+};
+
+#endif
diff --git a/Source/cmProcessTools.cxx b/Source/cmProcessTools.cxx
index e7b6051..b756650 100644
--- a/Source/cmProcessTools.cxx
+++ b/Source/cmProcessTools.cxx
@@ -1,29 +1,46 @@
 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmProcessTools.h"
+#include "cmProcessOutput.h"
 
 #include <cmsys/Process.h>
 #include <ostream>
 
 void cmProcessTools::RunProcess(struct cmsysProcess_s* cp, OutputParser* out,
-                                OutputParser* err)
+                                OutputParser* err, Encoding encoding)
 {
   cmsysProcess_Execute(cp);
   char* data = CM_NULLPTR;
   int length = 0;
   int p;
+  cmProcessOutput processOutput(encoding);
+  std::string strdata;
   while ((out || err) &&
          (p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR), p)) {
     if (out && p == cmsysProcess_Pipe_STDOUT) {
-      if (!out->Process(data, length)) {
+      processOutput.DecodeText(data, length, strdata, 1);
+      if (!out->Process(strdata.c_str(), int(strdata.size()))) {
         out = CM_NULLPTR;
       }
     } else if (err && p == cmsysProcess_Pipe_STDERR) {
-      if (!err->Process(data, length)) {
+      processOutput.DecodeText(data, length, strdata, 2);
+      if (!err->Process(strdata.c_str(), int(strdata.size()))) {
         err = CM_NULLPTR;
       }
     }
   }
+  if (out) {
+    processOutput.DecodeText(std::string(), strdata, 1);
+    if (!strdata.empty()) {
+      out->Process(strdata.c_str(), int(strdata.size()));
+    }
+  }
+  if (err) {
+    processOutput.DecodeText(std::string(), strdata, 2);
+    if (!strdata.empty()) {
+      out->Process(strdata.c_str(), int(strdata.size()));
+    }
+  }
   cmsysProcess_WaitForExit(cp, CM_NULLPTR);
 }
 
diff --git a/Source/cmProcessTools.h b/Source/cmProcessTools.h
index e5a3fe9..df131b9 100644
--- a/Source/cmProcessTools.h
+++ b/Source/cmProcessTools.h
@@ -3,6 +3,7 @@
 #ifndef cmProcessTools_h
 #define cmProcessTools_h
 
+#include "cmProcessOutput.h"
 #include <cmConfigure.h>
 
 #include <iosfwd>
@@ -16,6 +17,7 @@
 class cmProcessTools
 {
 public:
+  typedef cmProcessOutput::Encoding Encoding;
   /** Abstract interface for process output parsers.  */
   class OutputParser
   {
@@ -79,7 +81,8 @@ public:
 
   /** Run a process and send output to given parsers.  */
   static void RunProcess(struct cmsysProcess_s* cp, OutputParser* out,
-                         OutputParser* err = CM_NULLPTR);
+                         OutputParser* err = CM_NULLPTR,
+                         Encoding encoding = cmProcessOutput::Auto);
 };
 
 #endif
diff --git a/Source/cmProjectCommand.cxx b/Source/cmProjectCommand.cxx
index c34a94b..4e0fa57 100644
--- a/Source/cmProjectCommand.cxx
+++ b/Source/cmProjectCommand.cxx
@@ -2,6 +2,18 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmProjectCommand.h"
 
+#include <cmsys/RegularExpression.hxx>
+#include <sstream>
+#include <stdio.h>
+
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
+
 // cmProjectCommand
 bool cmProjectCommand::InitialPass(std::vector<std::string> const& args,
                                    cmExecutionStatus&)
@@ -19,10 +31,10 @@ bool cmProjectCommand::InitialPass(std::vector<std::string> const& args,
 
   this->Makefile->AddCacheDefinition(
     bindir, this->Makefile->GetCurrentBinaryDirectory(),
-    "Value Computed by CMake", cmState::STATIC);
+    "Value Computed by CMake", cmStateEnums::STATIC);
   this->Makefile->AddCacheDefinition(
     srcdir, this->Makefile->GetCurrentSourceDirectory(),
-    "Value Computed by CMake", cmState::STATIC);
+    "Value Computed by CMake", cmStateEnums::STATIC);
 
   bindir = "PROJECT_BINARY_DIR";
   srcdir = "PROJECT_SOURCE_DIR";
@@ -45,7 +57,7 @@ bool cmProjectCommand::InitialPass(std::vector<std::string> const& args,
     this->Makefile->AddDefinition("CMAKE_PROJECT_NAME", args[0].c_str());
     this->Makefile->AddCacheDefinition("CMAKE_PROJECT_NAME", args[0].c_str(),
                                        "Value Computed by CMake",
-                                       cmState::STATIC);
+                                       cmStateEnums::STATIC);
   }
 
   bool haveVersion = false;
diff --git a/Source/cmProjectCommand.h b/Source/cmProjectCommand.h
index c9c2549..cd92176 100644
--- a/Source/cmProjectCommand.h
+++ b/Source/cmProjectCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmProjectCommand_h
 #define cmProjectCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmProjectCommand
  * \brief Specify the name for this build project.
  *
@@ -32,8 +38,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "project"; }
-
-  cmTypeMacro(cmProjectCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmQTWrapCPPCommand.cxx b/Source/cmQTWrapCPPCommand.cxx
index 3a721da..de9e545 100644
--- a/Source/cmQTWrapCPPCommand.cxx
+++ b/Source/cmQTWrapCPPCommand.cxx
@@ -2,6 +2,13 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmQTWrapCPPCommand.h"
 
+#include "cmCustomCommandLines.h"
+#include "cmMakefile.h"
+#include "cmSourceFile.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmQTWrapCPPCommand
 bool cmQTWrapCPPCommand::InitialPass(std::vector<std::string> const& args,
                                      cmExecutionStatus&)
@@ -70,7 +77,7 @@ bool cmQTWrapCPPCommand::InitialPass(std::vector<std::string> const& args,
       depends.push_back(moc_exe);
       depends.push_back(hname);
 
-      std::string no_main_dependency = "";
+      std::string no_main_dependency;
       const char* no_working_dir = CM_NULLPTR;
       this->Makefile->AddCustomCommandToOutput(
         newName, depends, no_main_dependency, commandLines, "Qt Wrapped File",
diff --git a/Source/cmQTWrapCPPCommand.h b/Source/cmQTWrapCPPCommand.h
index 3567fb6..8eb5ff9 100644
--- a/Source/cmQTWrapCPPCommand.h
+++ b/Source/cmQTWrapCPPCommand.h
@@ -3,9 +3,13 @@
 #ifndef cmQTWrapCPPCommand_h
 #define cmQTWrapCPPCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
-#include "cmSourceFile.h"
+class cmExecutionStatus;
 
 /** \class cmQTWrapCPPCommand
  * \brief Create moc file rules for Qt classes
@@ -16,8 +20,6 @@
 class cmQTWrapCPPCommand : public cmCommand
 {
 public:
-  cmTypeMacro(cmQTWrapCPPCommand, cmCommand);
-
   /**
    * This is a virtual constructor for the command.
    */
diff --git a/Source/cmQTWrapUICommand.cxx b/Source/cmQTWrapUICommand.cxx
index 3b0f083..d3c6631 100644
--- a/Source/cmQTWrapUICommand.cxx
+++ b/Source/cmQTWrapUICommand.cxx
@@ -2,6 +2,13 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmQTWrapUICommand.h"
 
+#include "cmCustomCommandLines.h"
+#include "cmMakefile.h"
+#include "cmSourceFile.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmQTWrapUICommand
 bool cmQTWrapUICommand::InitialPass(std::vector<std::string> const& args,
                                     cmExecutionStatus&)
@@ -101,7 +108,7 @@ bool cmQTWrapUICommand::InitialPass(std::vector<std::string> const& args,
 
       std::vector<std::string> depends;
       depends.push_back(uiName);
-      std::string no_main_dependency = "";
+      std::string no_main_dependency;
       const char* no_comment = CM_NULLPTR;
       const char* no_working_dir = CM_NULLPTR;
       this->Makefile->AddCustomCommandToOutput(
diff --git a/Source/cmQTWrapUICommand.h b/Source/cmQTWrapUICommand.h
index 84b88a8..876ddd5 100644
--- a/Source/cmQTWrapUICommand.h
+++ b/Source/cmQTWrapUICommand.h
@@ -3,9 +3,13 @@
 #ifndef cmQTWrapUICommand_h
 #define cmQTWrapUICommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
-#include "cmSourceFile.h"
+class cmExecutionStatus;
 
 /** \class cmQTWrapUICommand
  * \brief Create .h and .cxx files rules for Qt user interfaces files
@@ -15,7 +19,6 @@
 class cmQTWrapUICommand : public cmCommand
 {
 public:
-  cmTypeMacro(cmQTWrapUICommand, cmCommand);
   /**
    * This is a virtual constructor for the command.
    */
diff --git a/Source/cmQtAutoGeneratorInitializer.cxx b/Source/cmQtAutoGeneratorInitializer.cxx
index 5246a67..825eba0 100644
--- a/Source/cmQtAutoGeneratorInitializer.cxx
+++ b/Source/cmQtAutoGeneratorInitializer.cxx
@@ -4,7 +4,7 @@
 
 #include "cmAlgorithms.h"
 #include "cmCustomCommandLines.h"
-#include "cmFilePathUuid.h"
+#include "cmFilePathChecksum.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
 #include "cmLocalGenerator.h"
@@ -26,7 +26,6 @@
 #include <cmConfigure.h>
 #include <cmsys/FStream.hxx>
 #include <cmsys/RegularExpression.hxx>
-#include <iostream>
 #include <map>
 #include <set>
 #include <sstream>
@@ -36,14 +35,34 @@
 #include <utility>
 #include <vector>
 
+static void utilCopyTargetProperty(cmTarget* destinationTarget,
+                                   cmTarget* sourceTarget,
+                                   const std::string& propertyName)
+{
+  const char* propertyValue = sourceTarget->GetProperty(propertyName);
+  if (propertyValue) {
+    destinationTarget->SetProperty(propertyName, propertyValue);
+  }
+}
+
+static std::string utilStripCR(std::string const& line)
+{
+  // Strip CR characters rcc may have printed (possibly more than one!).
+  std::string::size_type cr = line.find('\r');
+  if (cr != line.npos) {
+    return line.substr(0, cr);
+  }
+  return line;
+}
+
 static std::string GetAutogenTargetName(cmGeneratorTarget const* target)
 {
   std::string autogenTargetName = target->GetName();
-  autogenTargetName += "_automoc";
+  autogenTargetName += "_autogen";
   return autogenTargetName;
 }
 
-static std::string GetAutogenTargetDir(cmGeneratorTarget const* target)
+static std::string GetAutogenTargetFilesDir(cmGeneratorTarget const* target)
 {
   cmMakefile* makefile = target->Target->GetMakefile();
   std::string targetDir = makefile->GetCurrentBinaryDirectory();
@@ -60,73 +79,87 @@ static std::string GetAutogenTargetBuildDir(cmGeneratorTarget const* target)
   std::string targetDir = makefile->GetCurrentBinaryDirectory();
   targetDir += "/";
   targetDir += GetAutogenTargetName(target);
-  targetDir += ".dir/";
+  targetDir += "/";
   return targetDir;
 }
 
+static std::string GetQtMajorVersion(cmGeneratorTarget const* target)
+{
+  cmMakefile* makefile = target->Target->GetMakefile();
+  std::string qtMajorVersion = makefile->GetSafeDefinition("QT_VERSION_MAJOR");
+  if (qtMajorVersion.empty()) {
+    qtMajorVersion = makefile->GetSafeDefinition("Qt5Core_VERSION_MAJOR");
+  }
+  const char* targetQtVersion =
+    target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION", "");
+  if (targetQtVersion != CM_NULLPTR) {
+    qtMajorVersion = targetQtVersion;
+  }
+  return qtMajorVersion;
+}
+
 static void SetupSourceFiles(cmGeneratorTarget const* target,
-                             std::vector<std::string>& skipMoc,
-                             std::vector<std::string>& mocSources,
-                             std::vector<std::string>& mocHeaders,
-                             std::vector<std::string>& skipUic)
+                             std::vector<std::string>& mocUicSources,
+                             std::vector<std::string>& mocUicHeaders,
+                             std::vector<std::string>& skipMocList,
+                             std::vector<std::string>& skipUicList)
 {
   cmMakefile* makefile = target->Target->GetMakefile();
 
   std::vector<cmSourceFile*> srcFiles;
   target->GetConfigCommonSourceFiles(srcFiles);
 
-  std::vector<std::string> newRccFiles;
+  const bool targetMoc = target->GetPropertyAsBool("AUTOMOC");
+  const bool targetUic = target->GetPropertyAsBool("AUTOUIC");
 
-  cmFilePathUuid fpathUuid(makefile);
+  cmFilePathChecksum fpathCheckSum(makefile);
   for (std::vector<cmSourceFile*>::const_iterator fileIt = srcFiles.begin();
        fileIt != srcFiles.end(); ++fileIt) {
     cmSourceFile* sf = *fileIt;
-    std::string absFile = cmsys::SystemTools::GetRealPath(sf->GetFullPath());
-    bool skipFileForMoc =
-      cmSystemTools::IsOn(sf->GetPropertyForUser("SKIP_AUTOMOC"));
-    bool generated = cmSystemTools::IsOn(sf->GetPropertyForUser("GENERATED"));
+    const cmSystemTools::FileFormat fileType =
+      cmSystemTools::GetFileFormat(sf->GetExtension().c_str());
 
-    if (cmSystemTools::IsOn(sf->GetPropertyForUser("SKIP_AUTOUIC"))) {
-      skipUic.push_back(absFile);
+    if (!(fileType == cmSystemTools::CXX_FILE_FORMAT) &&
+        !(fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
+      continue;
     }
-
-    std::string ext = sf->GetExtension();
-
-    if (target->GetPropertyAsBool("AUTORCC")) {
-      if (ext == "qrc" &&
-          !cmSystemTools::IsOn(sf->GetPropertyForUser("SKIP_AUTORCC"))) {
-
-        std::string rcc_output_file = GetAutogenTargetBuildDir(target);
-        // Create output directory
-        cmSystemTools::MakeDirectory(rcc_output_file.c_str());
-        rcc_output_file += fpathUuid.get(absFile, "qrc_", ".cpp");
-
-        makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES",
-                                 rcc_output_file.c_str(), false);
-        makefile->GetOrCreateSource(rcc_output_file, true);
-        newRccFiles.push_back(rcc_output_file);
-      }
+    if (cmSystemTools::IsOn(sf->GetPropertyForUser("GENERATED"))) {
+      continue;
+    }
+    const std::string absFile =
+      cmsys::SystemTools::GetRealPath(sf->GetFullPath());
+    // Skip flags
+    const bool skipAll =
+      cmSystemTools::IsOn(sf->GetPropertyForUser("SKIP_AUTOGEN"));
+    const bool skipMoc =
+      skipAll || cmSystemTools::IsOn(sf->GetPropertyForUser("SKIP_AUTOMOC"));
+    const bool skipUic =
+      skipAll || cmSystemTools::IsOn(sf->GetPropertyForUser("SKIP_AUTOUIC"));
+    // Add file name to skip lists.
+    // Do this even when the file is not added to the sources/headers lists
+    // because the file name may be extracted from an other file when
+    // processing
+    if (skipMoc) {
+      skipMocList.push_back(absFile);
+    }
+    if (skipUic) {
+      skipUicList.push_back(absFile);
     }
 
-    if (!generated) {
-      if (skipFileForMoc) {
-        skipMoc.push_back(absFile);
-      } else {
-        cmSystemTools::FileFormat fileType =
-          cmSystemTools::GetFileFormat(ext.c_str());
-        if (fileType == cmSystemTools::CXX_FILE_FORMAT) {
-          mocSources.push_back(absFile);
-        } else if (fileType == cmSystemTools::HEADER_FILE_FORMAT) {
-          mocHeaders.push_back(absFile);
-        }
+    if ((targetMoc && !skipMoc) || (targetUic && !skipUic)) {
+      // Add file name to sources or headers list
+      switch (fileType) {
+        case cmSystemTools::CXX_FILE_FORMAT:
+          mocUicSources.push_back(absFile);
+          break;
+        case cmSystemTools::HEADER_FILE_FORMAT:
+          mocUicHeaders.push_back(absFile);
+          break;
+        default:
+          break;
       }
     }
   }
-
-  for (std::vector<std::string>::const_iterator fileIt = newRccFiles.begin();
-       fileIt != newRccFiles.end(); ++fileIt) {
-    const_cast<cmGeneratorTarget*>(target)->AddSource(*fileIt);
-  }
 }
 
 static void GetCompileDefinitionsAndDirectories(
@@ -147,10 +180,9 @@ static void GetCompileDefinitionsAndDirectories(
   defs += cmJoin(defines, ";");
 }
 
-static void SetupAutoMocTarget(
+static void MocSetupAutoTarget(
   cmGeneratorTarget const* target, const std::string& autogenTargetName,
   std::vector<std::string> const& skipMoc,
-  std::vector<std::string> const& mocHeaders,
   std::map<std::string, std::string>& configIncludes,
   std::map<std::string, std::string>& configDefines)
 {
@@ -164,9 +196,6 @@ static void SetupAutoMocTarget(
   makefile->AddDefinition(
     "_skip_moc",
     cmOutputConverter::EscapeForCMake(cmJoin(skipMoc, ";")).c_str());
-  makefile->AddDefinition(
-    "_moc_headers",
-    cmOutputConverter::EscapeForCMake(cmJoin(mocHeaders, ";")).c_str());
   bool relaxedMode = makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE");
   makefile->AddDefinition("_moc_relaxed_mode", relaxedMode ? "TRUE" : "FALSE");
 
@@ -230,7 +259,7 @@ static void SetupAutoMocTarget(
   }
 }
 
-static void GetUicOpts(cmGeneratorTarget const* target,
+static void UicGetOpts(cmGeneratorTarget const* target,
                        const std::string& config, std::string& optString)
 {
   std::vector<std::string> opts;
@@ -238,7 +267,7 @@ static void GetUicOpts(cmGeneratorTarget const* target,
   optString = cmJoin(opts, ";");
 }
 
-static void SetupAutoUicTarget(
+static void UicSetupAutoTarget(
   cmGeneratorTarget const* target, std::vector<std::string> const& skipUic,
   std::map<std::string, std::string>& configUicOptions)
 {
@@ -260,7 +289,7 @@ static void SetupAutoUicTarget(
   std::string _uic_opts;
   std::vector<std::string> configs;
   const std::string& config = makefile->GetConfigurations(configs);
-  GetUicOpts(target, config, _uic_opts);
+  UicGetOpts(target, config, _uic_opts);
 
   if (!_uic_opts.empty()) {
     _uic_opts = cmOutputConverter::EscapeForCMake(_uic_opts);
@@ -269,7 +298,7 @@ static void SetupAutoUicTarget(
   for (std::vector<std::string>::const_iterator li = configs.begin();
        li != configs.end(); ++li) {
     std::string config_uic_opts;
-    GetUicOpts(target, *li, config_uic_opts);
+    UicGetOpts(target, *li, config_uic_opts);
     if (config_uic_opts != _uic_opts) {
       configUicOptions[*li] =
         cmOutputConverter::EscapeForCMake(config_uic_opts);
@@ -332,25 +361,13 @@ static void SetupAutoUicTarget(
   }
 }
 
-static std::string GetRccExecutable(cmGeneratorTarget const* target)
+static std::string RccGetExecutable(cmGeneratorTarget const* target,
+                                    const std::string& qtMajorVersion)
 {
   cmLocalGenerator* lg = target->GetLocalGenerator();
-  cmMakefile* makefile = target->Target->GetMakefile();
-  const char* qtVersion = makefile->GetDefinition("_target_qt_version");
-  if (!qtVersion) {
-    qtVersion = makefile->GetDefinition("Qt5Core_VERSION_MAJOR");
-    if (!qtVersion) {
-      qtVersion = makefile->GetDefinition("QT_VERSION_MAJOR");
-    }
-    if (const char* targetQtVersion =
-          target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
-                                                          "")) {
-      qtVersion = targetQtVersion;
-    }
-  }
 
-  std::string targetName = target->GetName();
-  if (strcmp(qtVersion, "5") == 0) {
+  std::string const& targetName = target->GetName();
+  if (qtMajorVersion == "5") {
     cmGeneratorTarget* qt5Rcc = lg->FindGeneratorTargetToUse("Qt5::rcc");
     if (!qt5Rcc) {
       cmSystemTools::Error("Qt5::rcc target not found ", targetName.c_str());
@@ -358,7 +375,7 @@ static std::string GetRccExecutable(cmGeneratorTarget const* target)
     }
     return qt5Rcc->ImportedGetLocation("");
   }
-  if (strcmp(qtVersion, "4") == 0) {
+  if (qtMajorVersion == "4") {
     cmGeneratorTarget* qt4Rcc = lg->FindGeneratorTargetToUse("Qt4::rcc");
     if (!qt4Rcc) {
       cmSystemTools::Error("Qt4::rcc target not found ", targetName.c_str());
@@ -373,7 +390,7 @@ static std::string GetRccExecutable(cmGeneratorTarget const* target)
   return std::string();
 }
 
-static void MergeRccOptions(std::vector<std::string>& opts,
+static void RccMergeOptions(std::vector<std::string>& opts,
                             const std::vector<std::string>& fileOpts,
                             bool isQt5)
 {
@@ -405,41 +422,16 @@ static void MergeRccOptions(std::vector<std::string>& opts,
   opts.insert(opts.end(), extraOpts.begin(), extraOpts.end());
 }
 
-static void copyTargetProperty(cmTarget* destinationTarget,
-                               cmTarget* sourceTarget,
-                               const std::string& propertyName)
-{
-  const char* propertyValue = sourceTarget->GetProperty(propertyName);
-  if (propertyValue) {
-    destinationTarget->SetProperty(propertyName, propertyValue);
-  }
-}
-
-static std::string cmQtAutoGeneratorsStripCR(std::string const& line)
-{
-  // Strip CR characters rcc may have printed (possibly more than one!).
-  std::string::size_type cr = line.find('\r');
-  if (cr != line.npos) {
-    return line.substr(0, cr);
-  }
-  return line;
-}
-
-static std::string ReadAll(const std::string& filename)
-{
-  cmsys::ifstream file(filename.c_str());
-  std::ostringstream stream;
-  stream << file.rdbuf();
-  file.close();
-  return stream.str();
-}
-
 /// @brief Reads the resource files list from from a .qrc file - Qt5 version
 /// @return True if the .qrc file was successfully parsed
-static bool ListQt5RccInputs(cmSourceFile* sf, cmGeneratorTarget const* target,
+static bool RccListInputsQt5(cmSourceFile* sf, cmGeneratorTarget const* target,
                              std::vector<std::string>& depends)
 {
-  std::string rccCommand = GetRccExecutable(target);
+  const std::string rccCommand = RccGetExecutable(target, "5");
+  if (rccCommand.empty()) {
+    cmSystemTools::Error("AUTOGEN: error: rcc executable not available\n");
+    return false;
+  }
 
   bool hasDashDashList = false;
   // Read rcc features
@@ -487,7 +479,7 @@ static bool ListQt5RccInputs(cmSourceFile* sf, cmGeneratorTarget const* target,
     std::istringstream ostr(rccStdOut);
     std::string oline;
     while (std::getline(ostr, oline)) {
-      oline = cmQtAutoGeneratorsStripCR(oline);
+      oline = utilStripCR(oline);
       if (!oline.empty()) {
         depends.push_back(oline);
       }
@@ -498,7 +490,7 @@ static bool ListQt5RccInputs(cmSourceFile* sf, cmGeneratorTarget const* target,
     std::istringstream estr(rccStdErr);
     std::string eline;
     while (std::getline(estr, eline)) {
-      eline = cmQtAutoGeneratorsStripCR(eline);
+      eline = utilStripCR(eline);
       if (cmHasLiteralPrefix(eline, "RCC: Error in")) {
         static std::string searchString = "Cannot find file '";
 
@@ -522,10 +514,16 @@ static bool ListQt5RccInputs(cmSourceFile* sf, cmGeneratorTarget const* target,
 
 /// @brief Reads the resource files list from from a .qrc file - Qt4 version
 /// @return True if the .qrc file was successfully parsed
-static bool ListQt4RccInputs(cmSourceFile* sf,
+static bool RccListInputsQt4(cmSourceFile* sf,
                              std::vector<std::string>& depends)
 {
-  const std::string qrcContents = ReadAll(sf->GetFullPath());
+  // Read file into string
+  std::string qrcContents;
+  {
+    std::ostringstream stream;
+    stream << cmsys::ifstream(sf->GetFullPath().c_str()).rdbuf();
+    qrcContents = stream.str();
+  }
 
   cmsys::RegularExpression fileMatchRegex("(<file[^<]+)");
 
@@ -552,17 +550,18 @@ static bool ListQt4RccInputs(cmSourceFile* sf,
 
 /// @brief Reads the resource files list from from a .qrc file
 /// @return True if the rcc file was successfully parsed
-static bool ListQtRccInputs(const std::string& qtMajorVersion,
-                            cmSourceFile* sf, cmGeneratorTarget const* target,
-                            std::vector<std::string>& depends)
+static bool RccListInputs(const std::string& qtMajorVersion, cmSourceFile* sf,
+                          cmGeneratorTarget const* target,
+                          std::vector<std::string>& depends)
 {
   if (qtMajorVersion == "5") {
-    return ListQt5RccInputs(sf, target, depends);
+    return RccListInputsQt5(sf, target, depends);
   }
-  return ListQt4RccInputs(sf, depends);
+  return RccListInputsQt4(sf, depends);
 }
 
-static void SetupAutoRccTarget(cmGeneratorTarget const* target)
+static void RccSetupAutoTarget(cmGeneratorTarget const* target,
+                               const std::string& qtMajorVersion)
 {
   std::string _rcc_files;
   const char* sepRccFiles = "";
@@ -578,16 +577,12 @@ static void SetupAutoRccTarget(cmGeneratorTarget const* target)
   std::string rccFileOptions;
   const char* optionSep = "";
 
-  const char* qtVersion = makefile->GetDefinition("_target_qt_version");
+  const bool qtMajorVersion5 = (qtMajorVersion == "5");
 
   std::vector<std::string> rccOptions;
   if (const char* opts = target->GetProperty("AUTORCC_OPTIONS")) {
     cmSystemTools::ExpandListArgument(opts, rccOptions);
   }
-  std::string qtMajorVersion = makefile->GetSafeDefinition("QT_VERSION_MAJOR");
-  if (qtMajorVersion == "") {
-    qtMajorVersion = makefile->GetSafeDefinition("Qt5Core_VERSION_MAJOR");
-  }
 
   for (std::vector<cmSourceFile*>::const_iterator fileIt = srcFiles.begin();
        fileIt != srcFiles.end(); ++fileIt) {
@@ -595,7 +590,9 @@ static void SetupAutoRccTarget(cmGeneratorTarget const* target)
     std::string ext = sf->GetExtension();
     if (ext == "qrc") {
       std::string absFile = cmsys::SystemTools::GetRealPath(sf->GetFullPath());
-      bool skip = cmSystemTools::IsOn(sf->GetPropertyForUser("SKIP_AUTORCC"));
+      const bool skip =
+        cmSystemTools::IsOn(sf->GetPropertyForUser("SKIP_AUTOGEN")) ||
+        cmSystemTools::IsOn(sf->GetPropertyForUser("SKIP_AUTORCC"));
 
       if (!skip) {
         _rcc_files += sepRccFiles;
@@ -605,7 +602,7 @@ static void SetupAutoRccTarget(cmGeneratorTarget const* target)
         if (const char* prop = sf->GetProperty("AUTORCC_OPTIONS")) {
           std::vector<std::string> optsVec;
           cmSystemTools::ExpandListArgument(prop, optsVec);
-          MergeRccOptions(rccOptions, optsVec, strcmp(qtVersion, "5") == 0);
+          RccMergeOptions(rccOptions, optsVec, qtMajorVersion5);
         }
 
         if (!rccOptions.empty()) {
@@ -625,7 +622,7 @@ static void SetupAutoRccTarget(cmGeneratorTarget const* target)
         std::string entriesList;
         if (!cmSystemTools::IsOn(sf->GetPropertyForUser("GENERATED"))) {
           std::vector<std::string> depends;
-          if (ListQtRccInputs(qtMajorVersion, sf, target, depends)) {
+          if (RccListInputs(qtMajorVersion, sf, target, depends)) {
             entriesList = cmJoin(depends, "@list_sep@");
           } else {
             return;
@@ -638,38 +635,28 @@ static void SetupAutoRccTarget(cmGeneratorTarget const* target)
     }
   }
   makefile->AddDefinition(
-    "_qt_rcc_inputs_" + target->GetName(),
-    cmOutputConverter::EscapeForCMake(qrcInputs).c_str());
-
+    "_rcc_inputs", cmOutputConverter::EscapeForCMake(qrcInputs).c_str());
   makefile->AddDefinition(
     "_rcc_files", cmOutputConverter::EscapeForCMake(_rcc_files).c_str());
-
   makefile->AddDefinition(
-    "_qt_rcc_options_files",
+    "_rcc_options_files",
     cmOutputConverter::EscapeForCMake(rccFileFiles).c_str());
   makefile->AddDefinition(
-    "_qt_rcc_options_options",
+    "_rcc_options_options",
     cmOutputConverter::EscapeForCMake(rccFileOptions).c_str());
-
   makefile->AddDefinition("_qt_rcc_executable",
-                          GetRccExecutable(target).c_str());
+                          RccGetExecutable(target, qtMajorVersion).c_str());
 }
 
 void cmQtAutoGeneratorInitializer::InitializeAutogenSources(
   cmGeneratorTarget* target)
 {
-  cmMakefile* makefile = target->Target->GetMakefile();
-
   if (target->GetPropertyAsBool("AUTOMOC")) {
-    std::string automocTargetName = GetAutogenTargetName(target);
-    std::string mocCppFile = makefile->GetCurrentBinaryDirectory();
-    mocCppFile += "/";
-    mocCppFile += automocTargetName;
-    mocCppFile += ".cpp";
-    makefile->GetOrCreateSource(mocCppFile, true);
-    makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES", mocCppFile.c_str(),
-                             false);
-
+    cmMakefile* makefile = target->Target->GetMakefile();
+    const std::string mocCppFile =
+      GetAutogenTargetBuildDir(target) + "moc_compilation.cpp";
+    cmSourceFile* gf = makefile->GetOrCreateSource(mocCppFile, true);
+    gf->SetProperty("SKIP_AUTOGEN", "On");
     target->AddSource(mocCppFile);
   }
 }
@@ -679,56 +666,85 @@ void cmQtAutoGeneratorInitializer::InitializeAutogenTarget(
 {
   cmMakefile* makefile = target->Target->GetMakefile();
 
-  std::string qtMajorVersion = makefile->GetSafeDefinition("QT_VERSION_MAJOR");
-  if (qtMajorVersion == "") {
-    qtMajorVersion = makefile->GetSafeDefinition("Qt5Core_VERSION_MAJOR");
-  }
-
-  // create a custom target for running generators at buildtime:
-  std::string autogenTargetName = GetAutogenTargetName(target);
+  // Create a custom target for running generators at buildtime
+  const std::string autogenTargetName = GetAutogenTargetName(target);
+  const std::string autogenBuildDir = GetAutogenTargetBuildDir(target);
+  const std::string workingDirectory =
+    cmSystemTools::CollapseFullPath("", makefile->GetCurrentBinaryDirectory());
+  const std::string qtMajorVersion = GetQtMajorVersion(target);
+  std::vector<std::string> autogenOutputFiles;
 
-  std::string targetDir = GetAutogenTargetDir(target);
+  // Remove old settings on cleanup
+  {
+    std::string fname = GetAutogenTargetFilesDir(target);
+    fname += "/AutogenOldSettings.cmake";
+    makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES", fname.c_str(),
+                             false);
+  }
 
-  cmCustomCommandLine currentLine;
-  currentLine.push_back(cmSystemTools::GetCMakeCommand());
-  currentLine.push_back("-E");
-  currentLine.push_back("cmake_autogen");
-  currentLine.push_back(targetDir);
-  currentLine.push_back("$<CONFIGURATION>");
+  // Create autogen target build directory and add it to the clean files
+  cmSystemTools::MakeDirectory(autogenBuildDir);
+  makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES",
+                           autogenBuildDir.c_str(), false);
 
-  cmCustomCommandLines commandLines;
-  commandLines.push_back(currentLine);
+  if (target->GetPropertyAsBool("AUTOMOC") ||
+      target->GetPropertyAsBool("AUTOUIC")) {
+    // Create autogen target includes directory and
+    // add it to the origin target INCLUDE_DIRECTORIES
+    const std::string incsDir = autogenBuildDir + "include";
+    cmSystemTools::MakeDirectory(incsDir);
+    target->AddIncludeDirectory(incsDir, true);
+  }
 
-  std::string workingDirectory =
-    cmSystemTools::CollapseFullPath("", makefile->GetCurrentBinaryDirectory());
+  if (target->GetPropertyAsBool("AUTOMOC")) {
+    // Register moc compilation file as generated
+    autogenOutputFiles.push_back(autogenBuildDir + "moc_compilation.cpp");
+  }
 
+  // Initialize autogen target dependencies
   std::vector<std::string> depends;
   if (const char* autogenDepends =
         target->GetProperty("AUTOGEN_TARGET_DEPENDS")) {
     cmSystemTools::ExpandListArgument(autogenDepends, depends);
   }
-  std::vector<std::string> toolNames;
-  if (target->GetPropertyAsBool("AUTOMOC")) {
-    toolNames.push_back("moc");
-  }
-  if (target->GetPropertyAsBool("AUTOUIC")) {
-    toolNames.push_back("uic");
-  }
-  if (target->GetPropertyAsBool("AUTORCC")) {
-    toolNames.push_back("rcc");
+
+  // Compose command lines
+  cmCustomCommandLines commandLines;
+  {
+    cmCustomCommandLine currentLine;
+    currentLine.push_back(cmSystemTools::GetCMakeCommand());
+    currentLine.push_back("-E");
+    currentLine.push_back("cmake_autogen");
+    currentLine.push_back(GetAutogenTargetFilesDir(target));
+    currentLine.push_back("$<CONFIGURATION>");
+    commandLines.push_back(currentLine);
   }
 
-  std::string tools = toolNames[0];
-  toolNames.erase(toolNames.begin());
-  while (toolNames.size() > 1) {
-    tools += ", " + toolNames[0];
+  // Compose target comment
+  std::string autogenComment;
+  {
+    std::vector<std::string> toolNames;
+    if (target->GetPropertyAsBool("AUTOMOC")) {
+      toolNames.push_back("MOC");
+    }
+    if (target->GetPropertyAsBool("AUTOUIC")) {
+      toolNames.push_back("UIC");
+    }
+    if (target->GetPropertyAsBool("AUTORCC")) {
+      toolNames.push_back("RCC");
+    }
+
+    std::string tools = toolNames[0];
     toolNames.erase(toolNames.begin());
+    while (toolNames.size() > 1) {
+      tools += ", " + toolNames[0];
+      toolNames.erase(toolNames.begin());
+    }
+    if (toolNames.size() == 1) {
+      tools += " and " + toolNames[0];
+    }
+    autogenComment = "Automatic " + tools + " for target " + target->GetName();
   }
-  if (toolNames.size() == 1) {
-    tools += " and " + toolNames[0];
-  }
-  std::string autogenComment = "Automatic " + tools + " for target ";
-  autogenComment += target->GetName();
 
 #if defined(_WIN32) && !defined(__CYGWIN__)
   bool usePRE_BUILD = false;
@@ -742,6 +758,8 @@ void cmQtAutoGeneratorInitializer::InitializeAutogenTarget(
     //  https://connect.microsoft.com/VisualStudio/feedback/details/769495
     usePRE_BUILD = vsgg->GetVersion() >= cmGlobalVisualStudioGenerator::VS7;
     if (usePRE_BUILD) {
+      // If the autogen target depends on an other target
+      // don't use PRE_BUILD
       for (std::vector<std::string>::iterator it = depends.begin();
            it != depends.end(); ++it) {
         if (!makefile->FindTargetToUse(it->c_str())) {
@@ -753,35 +771,44 @@ void cmQtAutoGeneratorInitializer::InitializeAutogenTarget(
   }
 #endif
 
-  std::vector<std::string> rcc_output;
-  bool const isNinja = lg->GetGlobalGenerator()->GetName() == "Ninja";
-  if (isNinja
-#if defined(_WIN32) && !defined(__CYGWIN__)
-      || usePRE_BUILD
-#endif
-      ) {
+  if (target->GetPropertyAsBool("AUTORCC")) {
+    cmFilePathChecksum fpathCheckSum(makefile);
     std::vector<cmSourceFile*> srcFiles;
     target->GetConfigCommonSourceFiles(srcFiles);
-    cmFilePathUuid fpathUuid(makefile);
     for (std::vector<cmSourceFile*>::const_iterator fileIt = srcFiles.begin();
          fileIt != srcFiles.end(); ++fileIt) {
       cmSourceFile* sf = *fileIt;
-      std::string absFile = cmsys::SystemTools::GetRealPath(sf->GetFullPath());
-
-      std::string ext = sf->GetExtension();
-
-      if (target->GetPropertyAsBool("AUTORCC")) {
-        if (ext == "qrc" &&
-            !cmSystemTools::IsOn(sf->GetPropertyForUser("SKIP_AUTORCC"))) {
-          {
-            std::string rcc_output_file = GetAutogenTargetBuildDir(target);
-            // Create output directory
-            cmSystemTools::MakeDirectory(rcc_output_file.c_str());
-            rcc_output_file += fpathUuid.get(absFile, "qrc_", ".cpp");
-            rcc_output.push_back(rcc_output_file);
-          }
+      if (sf->GetExtension() == "qrc" &&
+          !cmSystemTools::IsOn(sf->GetPropertyForUser("SKIP_AUTOGEN")) &&
+          !cmSystemTools::IsOn(sf->GetPropertyForUser("SKIP_AUTORCC"))) {
+        {
+          const std::string absFile =
+            cmsys::SystemTools::GetRealPath(sf->GetFullPath());
+
+          // Run cmake again when .qrc file changes
+          makefile->AddCMakeDependFile(absFile);
+
+          std::string rccOutputFile = autogenBuildDir;
+          rccOutputFile += fpathCheckSum.getPart(absFile);
+          rccOutputFile += "/qrc_";
+          rccOutputFile +=
+            cmsys::SystemTools::GetFilenameWithoutLastExtension(absFile);
+          rccOutputFile += ".cpp";
+
+          // Add rcc output file to origin target sources
+          cmSourceFile* gf = makefile->GetOrCreateSource(rccOutputFile, true);
+          gf->SetProperty("SKIP_AUTOGEN", "On");
+          target->AddSource(rccOutputFile);
+          // Register rcc output file as generated
+          autogenOutputFiles.push_back(rccOutputFile);
+        }
+        if (lg->GetGlobalGenerator()->GetName() == "Ninja"
+#if defined(_WIN32) && !defined(__CYGWIN__)
+            || usePRE_BUILD
+#endif
+            ) {
           if (!cmSystemTools::IsOn(sf->GetPropertyForUser("GENERATED"))) {
-            ListQtRccInputs(qtMajorVersion, sf, target, depends);
+            RccListInputs(qtMajorVersion, sf, target, depends);
 #if defined(_WIN32) && !defined(__CYGWIN__)
             // Cannot use PRE_BUILD because the resource files themselves
             // may not be sources within the target so VS may not know the
@@ -812,7 +839,7 @@ void cmQtAutoGeneratorInitializer::InitializeAutogenTarget(
   {
     cmTarget* autogenTarget = makefile->AddUtilityCommand(
       autogenTargetName, true, workingDirectory.c_str(),
-      /*byproducts=*/rcc_output, depends, commandLines, false,
+      /*byproducts=*/autogenOutputFiles, depends, commandLines, false,
       autogenComment.c_str());
 
     cmGeneratorTarget* gt = new cmGeneratorTarget(autogenTarget, lg);
@@ -829,7 +856,7 @@ void cmQtAutoGeneratorInitializer::InitializeAutogenTarget(
       autogenTarget->SetProperty("FOLDER", autogenFolder);
     } else {
       // inherit FOLDER property from target (#13688)
-      copyTargetProperty(gt->Target, target->Target, "FOLDER");
+      utilCopyTargetProperty(gt->Target, target->Target, "FOLDER");
     }
 
     target->Target->AddUtility(autogenTargetName);
@@ -846,7 +873,8 @@ void cmQtAutoGeneratorInitializer::SetupAutoGenerateTarget(
   static_cast<void>(varScope);
 
   // create a custom target for running generators at buildtime:
-  std::string autogenTargetName = GetAutogenTargetName(target);
+  const std::string autogenTargetName = GetAutogenTargetName(target);
+  const std::string qtMajorVersion = GetQtMajorVersion(target);
 
   makefile->AddDefinition(
     "_moc_target_name",
@@ -854,72 +882,64 @@ void cmQtAutoGeneratorInitializer::SetupAutoGenerateTarget(
   makefile->AddDefinition(
     "_origin_target_name",
     cmOutputConverter::EscapeForCMake(target->GetName()).c_str());
+  makefile->AddDefinition("_target_qt_version", qtMajorVersion.c_str());
 
-  std::string targetDir = GetAutogenTargetDir(target);
-
-  const char* qtVersion = makefile->GetDefinition("Qt5Core_VERSION_MAJOR");
-  if (!qtVersion) {
-    qtVersion = makefile->GetDefinition("QT_VERSION_MAJOR");
-  }
-  if (const char* targetQtVersion =
-        target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
-                                                        "")) {
-    qtVersion = targetQtVersion;
-  }
-  if (qtVersion) {
-    makefile->AddDefinition("_target_qt_version", qtVersion);
-  }
-
-  std::vector<std::string> skipUic;
+  std::vector<std::string> mocUicSources;
+  std::vector<std::string> mocUicHeaders;
   std::vector<std::string> skipMoc;
-  std::vector<std::string> mocSources;
-  std::vector<std::string> mocHeaders;
-  std::map<std::string, std::string> configIncludes;
-  std::map<std::string, std::string> configDefines;
+  std::vector<std::string> skipUic;
+  std::map<std::string, std::string> configMocIncludes;
+  std::map<std::string, std::string> configMocDefines;
   std::map<std::string, std::string> configUicOptions;
 
   if (target->GetPropertyAsBool("AUTOMOC") ||
       target->GetPropertyAsBool("AUTOUIC") ||
       target->GetPropertyAsBool("AUTORCC")) {
-    SetupSourceFiles(target, skipMoc, mocSources, mocHeaders, skipUic);
+    SetupSourceFiles(target, mocUicSources, mocUicHeaders, skipMoc, skipUic);
   }
   makefile->AddDefinition(
-    "_cpp_files",
-    cmOutputConverter::EscapeForCMake(cmJoin(mocSources, ";")).c_str());
+    "_moc_uic_sources",
+    cmOutputConverter::EscapeForCMake(cmJoin(mocUicSources, ";")).c_str());
+  makefile->AddDefinition(
+    "_moc_uic_headers",
+    cmOutputConverter::EscapeForCMake(cmJoin(mocUicHeaders, ";")).c_str());
+
   if (target->GetPropertyAsBool("AUTOMOC")) {
-    SetupAutoMocTarget(target, autogenTargetName, skipMoc, mocHeaders,
-                       configIncludes, configDefines);
+    MocSetupAutoTarget(target, autogenTargetName, skipMoc, configMocIncludes,
+                       configMocDefines);
   }
   if (target->GetPropertyAsBool("AUTOUIC")) {
-    SetupAutoUicTarget(target, skipUic, configUicOptions);
+    UicSetupAutoTarget(target, skipUic, configUicOptions);
   }
   if (target->GetPropertyAsBool("AUTORCC")) {
-    SetupAutoRccTarget(target);
+    RccSetupAutoTarget(target, qtMajorVersion);
   }
 
+  // Generate config file
   std::string inputFile = cmSystemTools::GetCMakeRoot();
   inputFile += "/Modules/AutogenInfo.cmake.in";
-  std::string outputFile = targetDir;
+  std::string outputFile = GetAutogenTargetFilesDir(target);
   outputFile += "/AutogenInfo.cmake";
-  makefile->AddDefinition(
-    "_qt_rcc_inputs",
-    makefile->GetDefinition("_qt_rcc_inputs_" + target->GetName()));
+
   makefile->ConfigureFile(inputFile.c_str(), outputFile.c_str(), false, true,
                           false);
 
-  // Ensure we have write permission in case .in was read-only.
-  mode_t perm = 0;
+  // Append custom definitions to config file
+  if (!configMocDefines.empty() || !configMocIncludes.empty() ||
+      !configUicOptions.empty()) {
+
+    // Ensure we have write permission in case .in was read-only.
+    mode_t perm = 0;
 #if defined(_WIN32) && !defined(__CYGWIN__)
-  mode_t mode_write = S_IWRITE;
+    mode_t mode_write = S_IWRITE;
 #else
-  mode_t mode_write = S_IWUSR;
+    mode_t mode_write = S_IWUSR;
 #endif
-  cmSystemTools::GetPermissions(outputFile, perm);
-  if (!(perm & mode_write)) {
-    cmSystemTools::SetPermissions(outputFile, perm | mode_write);
-  }
-  if (!configDefines.empty() || !configIncludes.empty() ||
-      !configUicOptions.empty()) {
+    cmSystemTools::GetPermissions(outputFile, perm);
+    if (!(perm & mode_write)) {
+      cmSystemTools::SetPermissions(outputFile, perm | mode_write);
+    }
+
     cmsys::ofstream infoFile(outputFile.c_str(), std::ios::app);
     if (!infoFile) {
       std::string error = "Internal CMake error when trying to open file: ";
@@ -928,19 +948,19 @@ void cmQtAutoGeneratorInitializer::SetupAutoGenerateTarget(
       cmSystemTools::Error(error.c_str());
       return;
     }
-    if (!configDefines.empty()) {
+    if (!configMocDefines.empty()) {
       for (std::map<std::string, std::string>::iterator
-             it = configDefines.begin(),
-             end = configDefines.end();
+             it = configMocDefines.begin(),
+             end = configMocDefines.end();
            it != end; ++it) {
         infoFile << "set(AM_MOC_COMPILE_DEFINITIONS_" << it->first << " "
                  << it->second << ")\n";
       }
     }
-    if (!configIncludes.empty()) {
+    if (!configMocIncludes.empty()) {
       for (std::map<std::string, std::string>::iterator
-             it = configIncludes.begin(),
-             end = configIncludes.end();
+             it = configMocIncludes.begin(),
+             end = configMocIncludes.end();
            it != end; ++it) {
         infoFile << "set(AM_MOC_INCLUDES_" << it->first << " " << it->second
                  << ")\n";
diff --git a/Source/cmQtAutoGenerators.cxx b/Source/cmQtAutoGenerators.cxx
index 84d00ea..1d6972b 100644
--- a/Source/cmQtAutoGenerators.cxx
+++ b/Source/cmQtAutoGenerators.cxx
@@ -2,21 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmQtAutoGenerators.h"
 
-#include "cmAlgorithms.h"
-#include "cmFilePathUuid.h"
-#include "cmGlobalGenerator.h"
-#include "cmMakefile.h"
-#include "cmOutputConverter.h"
-#include "cmState.h"
-#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
-#include "cmake.h"
-
 #include <algorithm>
 #include <assert.h>
 #include <cmConfigure.h>
 #include <cmsys/FStream.hxx>
-#include <cmsys/RegularExpression.hxx>
 #include <cmsys/Terminal.h>
 #include <iostream>
 #include <sstream>
@@ -24,32 +13,53 @@
 #include <string.h>
 #include <utility>
 
+#include "cmAlgorithms.h"
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmOutputConverter.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
+#include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
+
 #if defined(__APPLE__)
 #include <unistd.h>
 #endif
 
-static bool requiresMocing(const std::string& text, std::string& macroName)
-{
-  // this simple check is much much faster than the regexp
-  if (strstr(text.c_str(), "Q_OBJECT") == CM_NULLPTR &&
-      strstr(text.c_str(), "Q_GADGET") == CM_NULLPTR) {
-    return false;
-  }
+// -- Static variables
 
-  cmsys::RegularExpression qObjectRegExp("[\n][ \t]*Q_OBJECT[^a-zA-Z0-9_]");
-  if (qObjectRegExp.find(text)) {
-    macroName = "Q_OBJECT";
-    return true;
+static const char* MocOldSettingsKey = "AM_MOC_OLD_SETTINGS";
+static const char* UicOldSettingsKey = "AM_UIC_OLD_SETTINGS";
+static const char* RccOldSettingsKey = "AM_RCC_OLD_SETTINGS";
+
+// -- Static functions
+
+static std::string GetConfigDefinition(cmMakefile* makefile,
+                                       const std::string& key,
+                                       const std::string& config)
+{
+  std::string keyConf = key;
+  if (!config.empty()) {
+    keyConf += "_";
+    keyConf += config;
   }
-  cmsys::RegularExpression qGadgetRegExp("[\n][ \t]*Q_GADGET[^a-zA-Z0-9_]");
-  if (qGadgetRegExp.find(text)) {
-    macroName = "Q_GADGET";
-    return true;
+  const char* valueConf = makefile->GetDefinition(keyConf);
+  if (valueConf != CM_NULLPTR) {
+    return valueConf;
   }
-  return false;
+  return makefile->GetSafeDefinition(key);
 }
 
-static std::string findMatchingHeader(
+static std::string OldSettingsFile(const std::string& targetDirectory)
+{
+  std::string filename(cmSystemTools::CollapseFullPath(targetDirectory));
+  cmSystemTools::ConvertToUnixSlashes(filename);
+  filename += "/AutogenOldSettings.cmake";
+  return filename;
+}
+
+static std::string FindMatchingHeader(
   const std::string& absPath, const std::string& mocSubDir,
   const std::string& basename,
   const std::vector<std::string>& headerExtensions)
@@ -62,6 +72,7 @@ static std::string findMatchingHeader(
       header = sourceFilePath;
       break;
     }
+    // Try subdirectory instead
     if (!mocSubDir.empty()) {
       sourceFilePath = mocSubDir + basename + "." + (*ext);
       if (cmsys::SystemTools::FileExists(sourceFilePath.c_str())) {
@@ -74,7 +85,7 @@ static std::string findMatchingHeader(
   return header;
 }
 
-static std::string extractSubDir(const std::string& absPath,
+static std::string ExtractSubDir(const std::string& absPath,
                                  const std::string& currentMoc)
 {
   std::string subDir;
@@ -101,29 +112,69 @@ static bool FileNameIsUnique(const std::string& filePath,
   return true;
 }
 
-cmQtAutoGenerators::cmQtAutoGenerators()
-  : Verbose(cmsys::SystemTools::HasEnv("VERBOSE"))
-  , ColorOutput(true)
-  , RunMocFailed(false)
-  , RunUicFailed(false)
-  , RunRccFailed(false)
-  , GenerateAll(false)
+static std::string ReadAll(const std::string& filename)
 {
+  cmsys::ifstream file(filename.c_str());
+  std::ostringstream stream;
+  stream << file.rdbuf();
+  file.close();
+  return stream.str();
+}
 
-  std::string colorEnv = "";
-  cmsys::SystemTools::GetEnv("COLOR", colorEnv);
-  if (!colorEnv.empty()) {
-    if (cmSystemTools::IsOn(colorEnv.c_str())) {
-      this->ColorOutput = true;
-    } else {
-      this->ColorOutput = false;
+/**
+ * @brief Tests if buildFile doesn't exist or is older than sourceFile
+ * @return True if buildFile doesn't exist or is older than sourceFile
+ */
+static bool FileAbsentOrOlder(const std::string& buildFile,
+                              const std::string& sourceFile)
+{
+  int result = 0;
+  bool success =
+    cmsys::SystemTools::FileTimeCompare(buildFile, sourceFile, &result);
+  return (!success || (result <= 0));
+}
+
+static bool ListContains(const std::vector<std::string>& list,
+                         const std::string& entry)
+{
+  return (std::find(list.begin(), list.end(), entry) != list.end());
+}
+
+static std::string JoinOptions(const std::map<std::string, std::string>& opts)
+{
+  std::string result;
+  for (std::map<std::string, std::string>::const_iterator it = opts.begin();
+       it != opts.end(); ++it) {
+    if (it != opts.begin()) {
+      result += "%%%";
+    }
+    result += it->first;
+    result += "===";
+    result += it->second;
+  }
+  return result;
+}
+
+static std::string JoinExts(const std::vector<std::string>& lst)
+{
+  std::string result;
+  if (!lst.empty()) {
+    const std::string separator = ",";
+    for (std::vector<std::string>::const_iterator it = lst.begin();
+         it != lst.end(); ++it) {
+      if (it != lst.begin()) {
+        result += separator;
+      }
+      result += '.';
+      result += *it;
     }
   }
+  return result;
 }
 
-void cmQtAutoGenerators::MergeUicOptions(
-  std::vector<std::string>& opts, const std::vector<std::string>& fileOpts,
-  bool isQt5)
+static void UicMergeOptions(std::vector<std::string>& opts,
+                            const std::vector<std::string>& fileOpts,
+                            bool isQt5)
 {
   static const char* valueOptions[] = { "tr",      "translate",
                                         "postfix", "generator",
@@ -155,35 +206,72 @@ void cmQtAutoGenerators::MergeUicOptions(
   opts.insert(opts.end(), extraOpts.begin(), extraOpts.end());
 }
 
+// -- Class methods
+
+cmQtAutoGenerators::cmQtAutoGenerators()
+  : Verbose(cmsys::SystemTools::HasEnv("VERBOSE"))
+  , ColorOutput(true)
+  , RunMocFailed(false)
+  , RunUicFailed(false)
+  , RunRccFailed(false)
+  , GenerateMocAll(false)
+  , GenerateUicAll(false)
+  , GenerateRccAll(false)
+{
+
+  std::string colorEnv;
+  cmsys::SystemTools::GetEnv("COLOR", colorEnv);
+  if (!colorEnv.empty()) {
+    if (cmSystemTools::IsOn(colorEnv.c_str())) {
+      this->ColorOutput = true;
+    } else {
+      this->ColorOutput = false;
+    }
+  }
+
+  // Precompile regular expressions
+  this->RegExpQObject.compile("[\n][ \t]*Q_OBJECT[^a-zA-Z0-9_]");
+  this->RegExpQGadget.compile("[\n][ \t]*Q_GADGET[^a-zA-Z0-9_]");
+  this->RegExpMocInclude.compile(
+    "[\n][ \t]*#[ \t]*include[ \t]+"
+    "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
+  this->RegExpUicInclude.compile("[\n][ \t]*#[ \t]*include[ \t]+"
+                                 "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]");
+}
+
 bool cmQtAutoGenerators::Run(const std::string& targetDirectory,
                              const std::string& config)
 {
-  bool success = true;
   cmake cm;
   cm.SetHomeOutputDirectory(targetDirectory);
   cm.SetHomeDirectory(targetDirectory);
   cm.GetCurrentSnapshot().SetDefaultDefinitions();
   cmGlobalGenerator gg(&cm);
 
-  cmState::Snapshot snapshot = cm.GetCurrentSnapshot();
+  cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
   snapshot.GetDirectory().SetCurrentBinary(targetDirectory);
   snapshot.GetDirectory().SetCurrentSource(targetDirectory);
 
   CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, snapshot));
   gg.SetCurrentMakefile(mf.get());
 
-  this->ReadAutogenInfoFile(mf.get(), targetDirectory, config);
-  this->ReadOldMocDefinitionsFile(mf.get(), targetDirectory);
-
+  if (!this->ReadAutogenInfoFile(mf.get(), targetDirectory, config)) {
+    return false;
+  }
+  // Read old settings
+  this->OldSettingsReadFile(mf.get(), targetDirectory);
+  // Init and run
   this->Init();
-
   if (this->QtMajorVersion == "4" || this->QtMajorVersion == "5") {
-    success = this->RunAutogen(mf.get());
+    if (!this->RunAutogen(mf.get())) {
+      return false;
+    }
   }
-
-  this->WriteOldMocDefinitionsFile(targetDirectory);
-
-  return success;
+  // Write latest settings
+  if (!this->OldSettingsWriteFile(targetDirectory)) {
+    return false;
+  }
+  return true;
 }
 
 bool cmQtAutoGenerators::ReadAutogenInfoFile(
@@ -195,81 +283,68 @@ bool cmQtAutoGenerators::ReadAutogenInfoFile(
   filename += "/AutogenInfo.cmake";
 
   if (!makefile->ReadListFile(filename.c_str())) {
-    cmSystemTools::Error("Error processing file: ", filename.c_str());
+    std::ostringstream err;
+    err << "AutoGen: error processing file: " << filename << std::endl;
+    this->LogError(err.str());
     return false;
   }
 
+  // - Target names
+  this->OriginTargetName =
+    makefile->GetSafeDefinition("AM_ORIGIN_TARGET_NAME");
+  this->AutogenTargetName = makefile->GetSafeDefinition("AM_TARGET_NAME");
+
+  // - Directories
+  this->ProjectSourceDir = makefile->GetSafeDefinition("AM_CMAKE_SOURCE_DIR");
+  this->ProjectBinaryDir = makefile->GetSafeDefinition("AM_CMAKE_BINARY_DIR");
+  this->CurrentSourceDir =
+    makefile->GetSafeDefinition("AM_CMAKE_CURRENT_SOURCE_DIR");
+  this->CurrentBinaryDir =
+    makefile->GetSafeDefinition("AM_CMAKE_CURRENT_BINARY_DIR");
+
+  // - Qt environment
   this->QtMajorVersion = makefile->GetSafeDefinition("AM_QT_VERSION_MAJOR");
   if (this->QtMajorVersion == "") {
     this->QtMajorVersion =
       makefile->GetSafeDefinition("AM_Qt5Core_VERSION_MAJOR");
   }
-  this->Sources = makefile->GetSafeDefinition("AM_SOURCES");
-  {
-    std::string rccSources = makefile->GetSafeDefinition("AM_RCC_SOURCES");
-    cmSystemTools::ExpandListArgument(rccSources, this->RccSources);
-  }
-  this->SkipMoc = makefile->GetSafeDefinition("AM_SKIP_MOC");
-  this->SkipUic = makefile->GetSafeDefinition("AM_SKIP_UIC");
-  this->Headers = makefile->GetSafeDefinition("AM_HEADERS");
-  this->IncludeProjectDirsBefore =
-    makefile->IsOn("AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE");
-  this->Srcdir = makefile->GetSafeDefinition("AM_CMAKE_CURRENT_SOURCE_DIR");
-  this->Builddir = makefile->GetSafeDefinition("AM_CMAKE_CURRENT_BINARY_DIR");
   this->MocExecutable = makefile->GetSafeDefinition("AM_QT_MOC_EXECUTABLE");
   this->UicExecutable = makefile->GetSafeDefinition("AM_QT_UIC_EXECUTABLE");
   this->RccExecutable = makefile->GetSafeDefinition("AM_QT_RCC_EXECUTABLE");
-  {
-    std::string compileDefsPropOrig = "AM_MOC_COMPILE_DEFINITIONS";
-    std::string compileDefsProp = compileDefsPropOrig;
-    if (!config.empty()) {
-      compileDefsProp += "_";
-      compileDefsProp += config;
-    }
-    const char* compileDefs = makefile->GetDefinition(compileDefsProp);
-    this->MocCompileDefinitionsStr = compileDefs
-      ? compileDefs
-      : makefile->GetSafeDefinition(compileDefsPropOrig);
-  }
-  {
-    std::string includesPropOrig = "AM_MOC_INCLUDES";
-    std::string includesProp = includesPropOrig;
-    if (!config.empty()) {
-      includesProp += "_";
-      includesProp += config;
-    }
-    const char* includes = makefile->GetDefinition(includesProp);
-    this->MocIncludesStr =
-      includes ? includes : makefile->GetSafeDefinition(includesPropOrig);
-  }
+
+  // - File Lists
+  cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition("AM_SOURCES"),
+                                    this->Sources);
+  cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition("AM_HEADERS"),
+                                    this->Headers);
+
+  // - Moc
+  cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition("AM_SKIP_MOC"),
+                                    this->SkipMoc);
+  this->MocCompileDefinitionsStr =
+    GetConfigDefinition(makefile, "AM_MOC_COMPILE_DEFINITIONS", config);
+  this->MocIncludesStr =
+    GetConfigDefinition(makefile, "AM_MOC_INCLUDES", config);
   this->MocOptionsStr = makefile->GetSafeDefinition("AM_MOC_OPTIONS");
-  this->ProjectBinaryDir = makefile->GetSafeDefinition("AM_CMAKE_BINARY_DIR");
-  this->ProjectSourceDir = makefile->GetSafeDefinition("AM_CMAKE_SOURCE_DIR");
-  this->TargetName = makefile->GetSafeDefinition("AM_TARGET_NAME");
-  this->OriginTargetName =
-    makefile->GetSafeDefinition("AM_ORIGIN_TARGET_NAME");
 
+  // - Uic
+  cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition("AM_SKIP_UIC"),
+                                    this->SkipUic);
+  cmSystemTools::ExpandListArgument(
+    GetConfigDefinition(makefile, "AM_UIC_TARGET_OPTIONS", config),
+    this->UicTargetOptions);
   {
-    const char* uicOptionsFiles =
-      makefile->GetSafeDefinition("AM_UIC_OPTIONS_FILES");
-    std::string uicOptionsPropOrig = "AM_UIC_TARGET_OPTIONS";
-    std::string uicOptionsProp = uicOptionsPropOrig;
-    if (!config.empty()) {
-      uicOptionsProp += "_";
-      uicOptionsProp += config;
-    }
-    const char* uicTargetOptions = makefile->GetSafeDefinition(uicOptionsProp);
-    cmSystemTools::ExpandListArgument(
-      uicTargetOptions ? uicTargetOptions
-                       : makefile->GetSafeDefinition(uicOptionsPropOrig),
-      this->UicTargetOptions);
-    const char* uicOptionsOptions =
-      makefile->GetSafeDefinition("AM_UIC_OPTIONS_OPTIONS");
     std::vector<std::string> uicFilesVec;
-    cmSystemTools::ExpandListArgument(uicOptionsFiles, uicFilesVec);
     std::vector<std::string> uicOptionsVec;
-    cmSystemTools::ExpandListArgument(uicOptionsOptions, uicOptionsVec);
+    cmSystemTools::ExpandListArgument(
+      makefile->GetSafeDefinition("AM_UIC_OPTIONS_FILES"), uicFilesVec);
+    cmSystemTools::ExpandListArgument(
+      makefile->GetSafeDefinition("AM_UIC_OPTIONS_OPTIONS"), uicOptionsVec);
     if (uicFilesVec.size() != uicOptionsVec.size()) {
+      std::ostringstream err;
+      err << "AutoGen: Error: Uic files/options lists size missmatch in: "
+          << filename << std::endl;
+      this->LogError(err.str());
       return false;
     }
     for (std::vector<std::string>::iterator fileIt = uicFilesVec.begin(),
@@ -279,16 +354,22 @@ bool cmQtAutoGenerators::ReadAutogenInfoFile(
       this->UicOptions[*fileIt] = *optionIt;
     }
   }
+
+  // - Rcc
+  cmSystemTools::ExpandListArgument(
+    makefile->GetSafeDefinition("AM_RCC_SOURCES"), this->RccSources);
   {
-    const char* rccOptionsFiles =
-      makefile->GetSafeDefinition("AM_RCC_OPTIONS_FILES");
-    const char* rccOptionsOptions =
-      makefile->GetSafeDefinition("AM_RCC_OPTIONS_OPTIONS");
     std::vector<std::string> rccFilesVec;
-    cmSystemTools::ExpandListArgument(rccOptionsFiles, rccFilesVec);
     std::vector<std::string> rccOptionsVec;
-    cmSystemTools::ExpandListArgument(rccOptionsOptions, rccOptionsVec);
+    cmSystemTools::ExpandListArgument(
+      makefile->GetSafeDefinition("AM_RCC_OPTIONS_FILES"), rccFilesVec);
+    cmSystemTools::ExpandListArgument(
+      makefile->GetSafeDefinition("AM_RCC_OPTIONS_OPTIONS"), rccOptionsVec);
     if (rccFilesVec.size() != rccOptionsVec.size()) {
+      std::ostringstream err;
+      err << "AutoGen: Error: RCC files/options lists size missmatch in: "
+          << filename << std::endl;
+      this->LogError(err.str());
       return false;
     }
     for (std::vector<std::string>::iterator fileIt = rccFilesVec.begin(),
@@ -297,88 +378,177 @@ bool cmQtAutoGenerators::ReadAutogenInfoFile(
       cmSystemTools::ReplaceString(*optionIt, "@list_sep@", ";");
       this->RccOptions[*fileIt] = *optionIt;
     }
-
-    const char* rccInputs = makefile->GetSafeDefinition("AM_RCC_INPUTS");
+  }
+  {
     std::vector<std::string> rccInputLists;
-    cmSystemTools::ExpandListArgument(rccInputs, rccInputLists);
+    cmSystemTools::ExpandListArgument(
+      makefile->GetSafeDefinition("AM_RCC_INPUTS"), rccInputLists);
 
+    // qrc files in the end of the list may have been empty
+    if (rccInputLists.size() < this->RccSources.size()) {
+      rccInputLists.resize(this->RccSources.size());
+    }
     if (this->RccSources.size() != rccInputLists.size()) {
-      cmSystemTools::Error("Error processing file: ", filename.c_str());
+      std::ostringstream err;
+      err << "AutoGen: Error: RCC sources/inputs lists size missmatch in: "
+          << filename << std::endl;
+      this->LogError(err.str());
       return false;
     }
-
     for (std::vector<std::string>::iterator fileIt = this->RccSources.begin(),
                                             inputIt = rccInputLists.begin();
          fileIt != this->RccSources.end(); ++fileIt, ++inputIt) {
       cmSystemTools::ReplaceString(*inputIt, "@list_sep@", ";");
       std::vector<std::string> rccInputFiles;
       cmSystemTools::ExpandListArgument(*inputIt, rccInputFiles);
-
       this->RccInputs[*fileIt] = rccInputFiles;
     }
   }
-  this->CurrentCompileSettingsStr = this->MakeCompileSettingsString(makefile);
 
-  this->RelaxedMode = makefile->IsOn("AM_RELAXED_MODE");
+  // - Flags
+  this->IncludeProjectDirsBefore =
+    makefile->IsOn("AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE");
+  this->MocRelaxedMode = makefile->IsOn("AM_MOC_RELAXED_MODE");
 
   return true;
 }
 
-std::string cmQtAutoGenerators::MakeCompileSettingsString(cmMakefile* makefile)
+std::string cmQtAutoGenerators::MocSettingsStringCompose()
 {
-  std::string s;
-  s += makefile->GetSafeDefinition("AM_MOC_COMPILE_DEFINITIONS");
-  s += " ~~~ ";
-  s += makefile->GetSafeDefinition("AM_MOC_INCLUDES");
-  s += " ~~~ ";
-  s += makefile->GetSafeDefinition("AM_MOC_OPTIONS");
-  s += " ~~~ ";
-  s += makefile->IsOn("AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE") ? "TRUE"
-                                                                     : "FALSE";
-  s += " ~~~ ";
-
-  return s;
+  std::string res;
+  res += this->MocCompileDefinitionsStr;
+  res += " ~~~ ";
+  res += this->MocIncludesStr;
+  res += " ~~~ ";
+  res += this->MocOptionsStr;
+  res += " ~~~ ";
+  res += this->IncludeProjectDirsBefore ? "TRUE" : "FALSE";
+  res += " ~~~ ";
+  return res;
 }
 
-bool cmQtAutoGenerators::ReadOldMocDefinitionsFile(
-  cmMakefile* makefile, const std::string& targetDirectory)
+std::string cmQtAutoGenerators::UicSettingsStringCompose()
 {
-  std::string filename(cmSystemTools::CollapseFullPath(targetDirectory));
-  cmSystemTools::ConvertToUnixSlashes(filename);
-  filename += "/AutomocOldMocDefinitions.cmake";
+  std::string res;
+  res += cmJoin(this->UicTargetOptions, "@osep@");
+  res += " ~~~ ";
+  res += JoinOptions(this->UicOptions);
+  res += " ~~~ ";
+  return res;
+}
+
+std::string cmQtAutoGenerators::RccSettingsStringCompose()
+{
+  std::string res;
+  res += JoinOptions(this->RccOptions);
+  res += " ~~~ ";
+  return res;
+}
 
-  if (makefile->ReadListFile(filename.c_str())) {
-    this->OldCompileSettingsStr =
-      makefile->GetSafeDefinition("AM_OLD_COMPILE_SETTINGS");
+void cmQtAutoGenerators::OldSettingsReadFile(
+  cmMakefile* makefile, const std::string& targetDirectory)
+{
+  if (!this->MocExecutable.empty() || !this->UicExecutable.empty() ||
+      !this->RccExecutable.empty()) {
+    // Compose current settings strings
+    this->MocSettingsString = this->MocSettingsStringCompose();
+    this->UicSettingsString = this->UicSettingsStringCompose();
+    this->RccSettingsString = this->RccSettingsStringCompose();
+
+    // Read old settings
+    const std::string filename = OldSettingsFile(targetDirectory);
+    if (makefile->ReadListFile(filename.c_str())) {
+      if (!this->MocExecutable.empty()) {
+        const std::string sol = makefile->GetSafeDefinition(MocOldSettingsKey);
+        if (sol != this->MocSettingsString) {
+          this->GenerateMocAll = true;
+        }
+      }
+      if (!this->UicExecutable.empty()) {
+        const std::string sol = makefile->GetSafeDefinition(UicOldSettingsKey);
+        if (sol != this->UicSettingsString) {
+          this->GenerateUicAll = true;
+        }
+      }
+      if (!this->RccExecutable.empty()) {
+        const std::string sol = makefile->GetSafeDefinition(RccOldSettingsKey);
+        if (sol != this->RccSettingsString) {
+          this->GenerateRccAll = true;
+        }
+      }
+      // In case any setting changed remove the old settings file.
+      // This triggers a full rebuild on the next run if the current
+      // build is aborted before writing the current settings in the end.
+      if (this->GenerateMocAll || this->GenerateUicAll ||
+          this->GenerateRccAll) {
+        cmSystemTools::RemoveFile(filename);
+      }
+    } else {
+      // If the file could not be read re-generate everythiung.
+      this->GenerateMocAll = true;
+      this->GenerateUicAll = true;
+      this->GenerateRccAll = true;
+    }
   }
-  return true;
 }
 
-void cmQtAutoGenerators::WriteOldMocDefinitionsFile(
+bool cmQtAutoGenerators::OldSettingsWriteFile(
   const std::string& targetDirectory)
 {
-  std::string filename(cmSystemTools::CollapseFullPath(targetDirectory));
-  cmSystemTools::ConvertToUnixSlashes(filename);
-  filename += "/AutomocOldMocDefinitions.cmake";
-
-  cmsys::ofstream outfile;
-  outfile.open(filename.c_str(), std::ios::trunc);
-  outfile << "set(AM_OLD_COMPILE_SETTINGS "
-          << cmOutputConverter::EscapeForCMake(this->CurrentCompileSettingsStr)
-          << ")\n";
-
-  outfile.close();
+  bool success = true;
+  // Only write if any setting changed
+  if (this->GenerateMocAll || this->GenerateUicAll || this->GenerateRccAll) {
+    const std::string filename = OldSettingsFile(targetDirectory);
+    cmsys::ofstream outfile;
+    outfile.open(filename.c_str(), std::ios::trunc);
+    if (outfile) {
+      if (!this->MocExecutable.empty()) {
+        outfile << "set(" << MocOldSettingsKey << " "
+                << cmOutputConverter::EscapeForCMake(this->MocSettingsString)
+                << ")\n";
+      }
+      if (!this->UicExecutable.empty()) {
+        outfile << "set(" << UicOldSettingsKey << " "
+                << cmOutputConverter::EscapeForCMake(this->UicSettingsString)
+                << ")\n";
+      }
+      if (!this->RccExecutable.empty()) {
+        outfile << "set(" << RccOldSettingsKey << " "
+                << cmOutputConverter::EscapeForCMake(this->RccSettingsString)
+                << ")\n";
+      }
+      success = outfile.good();
+      outfile.close();
+    } else {
+      success = false;
+      // Remove old settings file to trigger full rebuild on next run
+      cmSystemTools::RemoveFile(filename);
+      {
+        std::ostringstream err;
+        err << "AutoGen: Error: Writing old settings file failed: " << filename
+            << std::endl;
+        this->LogError(err.str());
+      }
+    }
+  }
+  return success;
 }
 
 void cmQtAutoGenerators::Init()
 {
-  this->TargetBuildSubDir = this->TargetName;
-  this->TargetBuildSubDir += ".dir/";
+  this->AutogenBuildSubDir = this->AutogenTargetName;
+  this->AutogenBuildSubDir += "/";
+
+  this->OutMocCppFilenameRel = this->AutogenBuildSubDir;
+  this->OutMocCppFilenameRel += "moc_compilation.cpp";
 
-  this->OutMocCppFilenameRel = this->TargetName;
-  this->OutMocCppFilenameRel += ".cpp";
+  this->OutMocCppFilenameAbs =
+    this->CurrentBinaryDir + this->OutMocCppFilenameRel;
 
-  this->OutMocCppFilenameAbs = this->Builddir + this->OutMocCppFilenameRel;
+  // Init file path checksum generator
+  fpathCheckSum.setupParentDirs(this->CurrentSourceDir, this->CurrentBinaryDir,
+                                this->ProjectSourceDir,
+                                this->ProjectBinaryDir);
 
   std::vector<std::string> cdefList;
   cmSystemTools::ExpandListArgument(this->MocCompileDefinitionsStr, cdefList);
@@ -415,7 +585,6 @@ void cmQtAutoGenerators::Init()
 
   if (this->IncludeProjectDirsBefore) {
     const std::string binDir = "-I" + this->ProjectBinaryDir;
-
     const std::string srcDir = "-I" + this->ProjectSourceDir;
 
     std::list<std::string> sortedMocIncludes;
@@ -444,540 +613,468 @@ void cmQtAutoGenerators::Init()
   }
 }
 
-static std::string ReadAll(const std::string& filename)
-{
-  cmsys::ifstream file(filename.c_str());
-  std::ostringstream stream;
-  stream << file.rdbuf();
-  file.close();
-  return stream.str();
-}
-
 bool cmQtAutoGenerators::RunAutogen(cmMakefile* makefile)
 {
-  // If settings changed everything needs to be re-generated.
-  if (this->OldCompileSettingsStr != this->CurrentCompileSettingsStr) {
-    this->GenerateAll = true;
-  }
-
   // the program goes through all .cpp files to see which moc files are
   // included. It is not really interesting how the moc file is named, but
   // what file the moc is created from. Once a moc is included the same moc
-  // may not be included in the _automoc.cpp file anymore. OTOH if there's a
-  // header containing Q_OBJECT where no corresponding moc file is included
-  // anywhere a moc_<filename>.cpp file is created and included in
-  // the _automoc.cpp file.
+  // may not be included in the moc_compilation.cpp file anymore. OTOH if
+  // there's a header containing Q_OBJECT where no corresponding moc file
+  // is included anywhere a moc_<filename>.cpp file is created and included in
+  // the moc_compilation.cpp file.
 
   // key = moc source filepath, value = moc output filepath
   std::map<std::string, std::string> includedMocs;
-  // collect all headers which may need to be mocced
-  std::set<std::string> headerFiles;
-
-  std::vector<std::string> sourceFiles;
-  cmSystemTools::ExpandListArgument(this->Sources, sourceFiles);
-
-  const std::vector<std::string>& headerExtensions =
-    makefile->GetCMakeInstance()->GetHeaderExtensions();
-
+  std::map<std::string, std::string> notIncludedMocs;
   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);
-
-  for (std::vector<std::string>::const_iterator it = sourceFiles.begin();
-       it != sourceFiles.end(); ++it) {
-    const bool skipUic =
-      std::find(uicSkipped.begin(), uicSkipped.end(), *it) != uicSkipped.end();
-    std::map<std::string, std::vector<std::string> >& uiFiles =
-      skipUic ? skippedUis : includedUis;
-    const std::string& absFilename = *it;
-    if (this->Verbose) {
-      std::ostringstream err;
-      err << "AUTOGEN: Checking " << absFilename << std::endl;
-      this->LogInfo(err.str());
-    }
-    if (this->RelaxedMode) {
-      this->ParseCppFile(absFilename, headerExtensions, includedMocs, uiFiles);
-    } else {
-      this->StrictParseCppFile(absFilename, headerExtensions, includedMocs,
-                               uiFiles);
-    }
-    this->SearchHeadersForCppFile(absFilename, headerExtensions, headerFiles);
-  }
+  // collects all headers which may need to be mocced
+  std::set<std::string> headerFilesMoc;
+  std::set<std::string> headerFilesUic;
 
+  // Parse sources
   {
-    std::vector<std::string> mocSkipped;
-    cmSystemTools::ExpandListArgument(this->SkipMoc, mocSkipped);
-    for (std::vector<std::string>::const_iterator it = mocSkipped.begin();
-         it != mocSkipped.end(); ++it) {
-      if (std::find(uicSkipped.begin(), uicSkipped.end(), *it) !=
-          uicSkipped.end()) {
-        const std::string& absFilename = *it;
-        if (this->Verbose) {
-          std::ostringstream err;
-          err << "AUTOGEN: Checking " << absFilename << std::endl;
-          this->LogInfo(err.str());
-        }
-        this->ParseForUic(absFilename, includedUis);
+    const std::vector<std::string>& headerExtensions =
+      makefile->GetCMakeInstance()->GetHeaderExtensions();
+
+    for (std::vector<std::string>::const_iterator it = this->Sources.begin();
+         it != this->Sources.end(); ++it) {
+      const std::string& absFilename = *it;
+      // Parse source file for MOC/UIC
+      if (!this->ParseSourceFile(absFilename, headerExtensions, includedMocs,
+                                 includedUis, this->MocRelaxedMode)) {
+        return false;
       }
+      // Find additional headers
+      this->SearchHeadersForSourceFile(absFilename, headerExtensions,
+                                       headerFilesMoc, headerFilesUic);
     }
   }
 
-  std::vector<std::string> headerFilesVec;
-  cmSystemTools::ExpandListArgument(this->Headers, headerFilesVec);
-  headerFiles.insert(headerFilesVec.begin(), headerFilesVec.end());
-
-  // key = moc source filepath, value = moc output filename
-  std::map<std::string, std::string> notIncludedMocs;
-  this->ParseHeaders(headerFiles, includedMocs, notIncludedMocs, includedUis);
-
-  if (!this->MocExecutable.empty()) {
-    this->GenerateMocFiles(includedMocs, notIncludedMocs);
-  }
-  if (!this->UicExecutable.empty()) {
-    this->GenerateUiFiles(includedUis);
-  }
-  if (!this->RccExecutable.empty()) {
-    this->GenerateQrcFiles();
+  // Parse headers
+  for (std::vector<std::string>::const_iterator it = this->Headers.begin();
+       it != this->Headers.end(); ++it) {
+    const std::string& headerName = *it;
+    if (!this->MocSkipTest(headerName)) {
+      headerFilesMoc.insert(headerName);
+    }
+    if (!this->UicSkipTest(headerName)) {
+      headerFilesUic.insert(headerName);
+    }
   }
+  this->ParseHeaders(headerFilesMoc, headerFilesUic, includedMocs,
+                     notIncludedMocs, includedUis);
 
-  if (this->RunMocFailed) {
-    std::ostringstream err;
-    err << "moc failed..." << std::endl;
-    this->LogError(err.str());
+  // Generate files
+  if (!this->MocGenerateAll(includedMocs, notIncludedMocs)) {
     return false;
   }
-  if (this->RunUicFailed) {
-    std::ostringstream err;
-    err << "uic failed..." << std::endl;
-    this->LogError(err.str());
+  if (!this->UicGenerateAll(includedUis)) {
     return false;
   }
-  if (this->RunRccFailed) {
-    std::ostringstream err;
-    err << "rcc failed..." << std::endl;
-    this->LogError(err.str());
+  if (!this->QrcGenerateAll()) {
     return false;
   }
 
   return true;
 }
 
-void cmQtAutoGenerators::ParseCppFile(
+/**
+ * @brief Tests if the C++ content requires moc processing
+ * @return True if moc is required
+ */
+bool cmQtAutoGenerators::MocRequired(const std::string& text,
+                                     std::string& macroName)
+{
+  // Run a simple check before an expensive regular expression check
+  if (strstr(text.c_str(), "Q_OBJECT") != CM_NULLPTR) {
+    if (this->RegExpQObject.find(text)) {
+      macroName = "Q_OBJECT";
+      return true;
+    }
+  }
+  if (strstr(text.c_str(), "Q_GADGET") != CM_NULLPTR) {
+    if (this->RegExpQGadget.find(text)) {
+      macroName = "Q_GADGET";
+      return true;
+    }
+  }
+  return false;
+}
+
+/**
+ * @brief Tests if the file should be ignored for moc scanning
+ * @return True if the file should be ignored
+ */
+bool cmQtAutoGenerators::MocSkipTest(const std::string& absFilename)
+{
+  // Test if moc scanning is enabled
+  if (!this->MocExecutable.empty()) {
+    // Test if the file name is on the skip list
+    if (!ListContains(this->SkipMoc, absFilename)) {
+      return false;
+    }
+  }
+  return true;
+}
+
+/**
+ * @brief Tests if the file name is in the skip list
+ */
+bool cmQtAutoGenerators::UicSkipTest(const std::string& absFilename)
+{
+  // Test if uic scanning is enabled
+  if (!this->UicExecutable.empty()) {
+    // Test if the file name is on the skip list
+    if (!ListContains(this->SkipUic, absFilename)) {
+      return false;
+    }
+  }
+  return true;
+}
+
+/**
+ * @return True on success
+ */
+bool cmQtAutoGenerators::ParseSourceFile(
   const std::string& absFilename,
   const std::vector<std::string>& headerExtensions,
   std::map<std::string, std::string>& includedMocs,
-  std::map<std::string, std::vector<std::string> >& includedUis)
+  std::map<std::string, std::vector<std::string> >& includedUis, bool relaxed)
 {
-  cmsys::RegularExpression mocIncludeRegExp(
-    "[\n][ \t]*#[ \t]*include[ \t]+"
-    "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
-
+  bool success = true;
   const std::string contentsString = ReadAll(absFilename);
   if (contentsString.empty()) {
     std::ostringstream err;
-    err << "AUTOGEN: warning: " << absFilename << ": file is empty\n"
-        << std::endl;
-    this->LogError(err.str());
-    return;
-  }
-  this->ParseForUic(absFilename, contentsString, includedUis);
-  if (this->MocExecutable.empty()) {
-    return;
+    err << "AutoGen: Warning: " << absFilename << "\n"
+        << "The file is empty\n";
+    this->LogWarning(err.str());
+  } else {
+    // Parse source contents for MOC
+    if (success && !this->MocSkipTest(absFilename)) {
+      success = this->ParseContentForMoc(
+        absFilename, contentsString, headerExtensions, includedMocs, relaxed);
+    }
+    // Parse source contents for UIC
+    if (success && !this->UicSkipTest(absFilename)) {
+      this->ParseContentForUic(absFilename, contentsString, includedUis);
+    }
   }
+  return success;
+}
 
-  const std::string absPath = cmsys::SystemTools::GetFilenamePath(
-                                cmsys::SystemTools::GetRealPath(absFilename)) +
-    '/';
-  const std::string scannedFileBasename =
-    cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename);
-  std::string macroName;
-  const bool requiresMoc = requiresMocing(contentsString, macroName);
-  bool dotMocIncluded = false;
-  bool mocUnderscoreIncluded = false;
-  std::string ownMocUnderscoreFile;
-  std::string ownDotMocFile;
-  std::string ownMocHeaderFile;
-
-  std::string::size_type matchOffset = 0;
-  // first a simple string check for "moc" is *much* faster than the regexp,
-  // and if the string search already fails, we don't have to try the
-  // expensive regexp
-  if ((strstr(contentsString.c_str(), "moc") != CM_NULLPTR) &&
-      (mocIncludeRegExp.find(contentsString))) {
-    // for every moc include in the file
-    do {
-      const std::string currentMoc = mocIncludeRegExp.match(1);
-
-      std::string basename =
-        cmsys::SystemTools::GetFilenameWithoutLastExtension(currentMoc);
-      const bool moc_style = cmHasLiteralPrefix(basename, "moc_");
-
-      // If the moc include is of the moc_foo.cpp style we expect
-      // the Q_OBJECT class declaration in a header file.
-      // If the moc include is of the foo.moc style we need to look for
-      // a Q_OBJECT macro in the current source file, if it contains the
-      // macro we generate the moc file from the source file.
-      // Q_OBJECT
-      if (moc_style) {
-        // basename should be the part of the moc filename used for
-        // finding the correct header, so we need to remove the moc_ part
-        basename = basename.substr(4);
-        std::string mocSubDir = extractSubDir(absPath, currentMoc);
-        std::string headerToMoc =
-          findMatchingHeader(absPath, mocSubDir, basename, headerExtensions);
-
-        if (!headerToMoc.empty()) {
-          includedMocs[headerToMoc] = currentMoc;
-          if (basename == scannedFileBasename) {
-            mocUnderscoreIncluded = true;
-            ownMocUnderscoreFile = currentMoc;
-            ownMocHeaderFile = headerToMoc;
-          }
-        } else {
-          std::ostringstream err;
-          err << "AUTOGEN: error: " << absFilename << ": The file "
-              << "includes the moc file \"" << currentMoc << "\", "
-              << "but could not find header \"" << basename << '{'
-              << this->JoinExts(headerExtensions) << "}\" ";
-          if (mocSubDir.empty()) {
-            err << "in " << absPath << "\n" << std::endl;
-          } else {
-            err << "neither in " << absPath << " nor in " << mocSubDir << "\n"
-                << std::endl;
-          }
-          this->LogError(err.str());
-          ::exit(EXIT_FAILURE);
-        }
-      } else {
-        std::string fileToMoc = absFilename;
-        if (!requiresMoc || basename != scannedFileBasename) {
-          std::string mocSubDir = extractSubDir(absPath, currentMoc);
-          std::string headerToMoc =
-            findMatchingHeader(absPath, mocSubDir, basename, headerExtensions);
-          if (!headerToMoc.empty()) {
-            // this is for KDE4 compatibility:
-            fileToMoc = headerToMoc;
-            if (!requiresMoc && basename == scannedFileBasename) {
-              std::ostringstream err;
-              err << "AUTOGEN: warning: " << absFilename
-                  << ": The file "
-                     "includes the moc file \""
-                  << currentMoc << "\", but does not contain a " << macroName
-                  << " macro. Running moc on "
-                  << "\"" << headerToMoc << "\" ! Include \"moc_" << basename
-                  << ".cpp\" for a compatibility with "
-                     "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n"
-                  << std::endl;
-              this->LogError(err.str());
-            } else {
-              std::ostringstream err;
-              err << "AUTOGEN: warning: " << absFilename
-                  << ": The file "
-                     "includes the moc file \""
-                  << currentMoc << "\" instead of \"moc_" << basename
-                  << ".cpp\". "
-                     "Running moc on "
-                  << "\"" << headerToMoc << "\" ! Include \"moc_" << basename
-                  << ".cpp\" for compatibility with "
-                     "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n"
-                  << std::endl;
-              this->LogError(err.str());
-            }
-          } else {
-            std::ostringstream err;
-            err << "AUTOGEN: error: " << absFilename
-                << ": The file "
-                   "includes the moc file \""
-                << currentMoc
-                << "\", which seems to be the moc file from a different "
-                   "source file. CMake also could not find a matching "
-                   "header.\n"
-                << std::endl;
-            this->LogError(err.str());
-            ::exit(EXIT_FAILURE);
-          }
-        } else {
-          dotMocIncluded = true;
-          ownDotMocFile = currentMoc;
-        }
-        includedMocs[fileToMoc] = currentMoc;
-      }
-      matchOffset += mocIncludeRegExp.end();
-    } while (mocIncludeRegExp.find(contentsString.c_str() + matchOffset));
+void cmQtAutoGenerators::ParseContentForUic(
+  const std::string& absFilename, const std::string& contentsString,
+  std::map<std::string, std::vector<std::string> >& includedUis)
+{
+  // Process
+  if (this->Verbose) {
+    std::ostringstream err;
+    err << "AutoUic: Checking " << absFilename << "\n";
+    this->LogInfo(err.str());
   }
 
-  // In this case, check whether the scanned file itself contains a Q_OBJECT.
-  // If this is the case, the moc_foo.cpp should probably be generated from
-  // foo.cpp instead of foo.h, because otherwise it won't build.
-  // But warn, since this is not how it is supposed to be used.
-  if (!dotMocIncluded && requiresMoc) {
-    if (mocUnderscoreIncluded) {
-      // this is for KDE4 compatibility:
-      std::ostringstream err;
-      err << "AUTOGEN: warning: " << absFilename << ": The file "
-          << "contains a " << macroName << " macro, but does not "
-                                           "include "
-          << "\"" << scannedFileBasename << ".moc\", but instead "
-                                            "includes "
-          << "\"" << ownMocUnderscoreFile << "\". Running moc on "
-          << "\"" << absFilename << "\" ! Better include \""
-          << scannedFileBasename
-          << ".moc\" for compatibility with "
-             "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n"
-          << std::endl;
-      this->LogError(err.str());
-
-      includedMocs[absFilename] = ownMocUnderscoreFile;
-      includedMocs.erase(ownMocHeaderFile);
-    } else {
-      // otherwise always error out since it will not compile:
-      std::ostringstream err;
-      err << "AUTOGEN: error: " << absFilename << ": The file "
-          << "contains a " << macroName << " macro, but does not "
-                                           "include "
-          << "\"" << scannedFileBasename << ".moc\" !\n"
-          << std::endl;
-      this->LogError(err.str());
-
-      ::exit(EXIT_FAILURE);
+  const std::string realName = cmsys::SystemTools::GetRealPath(absFilename);
+  const char* contentChars = contentsString.c_str();
+  if (strstr(contentChars, "ui_") != CM_NULLPTR) {
+    while (this->RegExpUicInclude.find(contentChars)) {
+      const std::string currentUi = this->RegExpUicInclude.match(1);
+      const std::string basename =
+        cmsys::SystemTools::GetFilenameWithoutLastExtension(currentUi);
+      // basename should be the part of the ui filename used for
+      // finding the correct header, so we need to remove the ui_ part
+      includedUis[realName].push_back(basename.substr(3));
+      contentChars += this->RegExpUicInclude.end();
     }
   }
 }
 
-void cmQtAutoGenerators::StrictParseCppFile(
-  const std::string& absFilename,
+/**
+ * @return True on success
+ */
+bool cmQtAutoGenerators::ParseContentForMoc(
+  const std::string& absFilename, const std::string& contentsString,
   const std::vector<std::string>& headerExtensions,
-  std::map<std::string, std::string>& includedMocs,
-  std::map<std::string, std::vector<std::string> >& includedUis)
+  std::map<std::string, std::string>& includedMocs, bool relaxed)
 {
-  cmsys::RegularExpression mocIncludeRegExp(
-    "[\n][ \t]*#[ \t]*include[ \t]+"
-    "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
-
-  const std::string contentsString = ReadAll(absFilename);
-  if (contentsString.empty()) {
+  // Process
+  if (this->Verbose) {
     std::ostringstream err;
-    err << "AUTOGEN: warning: " << absFilename << ": file is empty\n"
-        << std::endl;
-    this->LogError(err.str());
-    return;
-  }
-  this->ParseForUic(absFilename, contentsString, includedUis);
-  if (this->MocExecutable.empty()) {
-    return;
+    err << "AutoMoc: Checking " << absFilename << "\n";
+    this->LogInfo(err.str());
   }
 
-  const std::string absPath = cmsys::SystemTools::GetFilenamePath(
-                                cmsys::SystemTools::GetRealPath(absFilename)) +
+  const std::string scannedFileAbsPath =
+    cmsys::SystemTools::GetFilenamePath(
+      cmsys::SystemTools::GetRealPath(absFilename)) +
     '/';
   const std::string scannedFileBasename =
     cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename);
 
-  bool dotMocIncluded = false;
+  std::string macroName;
+  const bool requiresMoc = this->MocRequired(contentsString, macroName);
+  bool ownDotMocIncluded = false;
+  bool ownMocUnderscoreIncluded = false;
+  std::string ownMocUnderscoreFile;
+  std::string ownMocHeaderFile;
 
-  std::string::size_type matchOffset = 0;
   // first a simple string check for "moc" is *much* faster than the regexp,
   // and if the string search already fails, we don't have to try the
   // expensive regexp
-  if ((strstr(contentsString.c_str(), "moc") != CM_NULLPTR) &&
-      (mocIncludeRegExp.find(contentsString))) {
-    // for every moc include in the file
-    do {
-      const std::string currentMoc = mocIncludeRegExp.match(1);
-
+  const char* contentChars = contentsString.c_str();
+  if (strstr(contentChars, "moc") != CM_NULLPTR) {
+    // Iterate over all included moc files
+    while (this->RegExpMocInclude.find(contentChars)) {
+      const std::string currentMoc = this->RegExpMocInclude.match(1);
+      // Basename of the current moc include
       std::string basename =
         cmsys::SystemTools::GetFilenameWithoutLastExtension(currentMoc);
-      const bool mocUnderscoreStyle = cmHasLiteralPrefix(basename, "moc_");
 
       // If the moc include is of the moc_foo.cpp style we expect
       // the Q_OBJECT class declaration in a header file.
       // If the moc include is of the foo.moc style we need to look for
       // a Q_OBJECT macro in the current source file, if it contains the
       // macro we generate the moc file from the source file.
-      if (mocUnderscoreStyle) {
+      if (cmHasLiteralPrefix(basename, "moc_")) {
+        // Include: moc_FOO.cxx
         // basename should be the part of the moc filename used for
         // finding the correct header, so we need to remove the moc_ part
         basename = basename.substr(4);
-        std::string mocSubDir = extractSubDir(absPath, currentMoc);
-        std::string headerToMoc =
-          findMatchingHeader(absPath, mocSubDir, basename, headerExtensions);
+        const std::string mocSubDir =
+          ExtractSubDir(scannedFileAbsPath, currentMoc);
+        const std::string headerToMoc = FindMatchingHeader(
+          scannedFileAbsPath, mocSubDir, basename, headerExtensions);
 
         if (!headerToMoc.empty()) {
           includedMocs[headerToMoc] = currentMoc;
+          if (relaxed && (basename == scannedFileBasename)) {
+            ownMocUnderscoreIncluded = true;
+            ownMocUnderscoreFile = currentMoc;
+            ownMocHeaderFile = headerToMoc;
+          }
         } else {
           std::ostringstream err;
-          err << "AUTOGEN: error: " << absFilename << " The file "
-              << "includes the moc file \"" << currentMoc << "\", "
-              << "but could not find header \"" << basename << '{'
-              << this->JoinExts(headerExtensions) << "}\" ";
+          err << "AutoMoc: Error: " << absFilename << "\n"
+              << "The file includes the moc file \"" << currentMoc
+              << "\", but could not find header \"" << basename << '{'
+              << JoinExts(headerExtensions) << "}\" ";
           if (mocSubDir.empty()) {
-            err << "in " << absPath << "\n" << std::endl;
+            err << "in " << scannedFileAbsPath << "\n";
           } else {
-            err << "neither in " << absPath << " nor in " << mocSubDir << "\n"
-                << std::endl;
+            err << "neither in " << scannedFileAbsPath << " nor in "
+                << mocSubDir << "\n";
           }
           this->LogError(err.str());
-          ::exit(EXIT_FAILURE);
+          return false;
         }
       } else {
-        if (basename != scannedFileBasename) {
-          std::ostringstream err;
-          err << "AUTOGEN: error: " << absFilename
-              << ": The file "
-                 "includes the moc file \""
-              << currentMoc
-              << "\", which seems to be the moc file from a different "
-                 "source file. This is not supported. "
-                 "Include \""
-              << scannedFileBasename << ".moc\" to run "
-                                        "moc on this source file.\n"
-              << std::endl;
-          this->LogError(err.str());
-          ::exit(EXIT_FAILURE);
+        // Include: FOO.moc
+        std::string fileToMoc;
+        if (relaxed) {
+          // Mode: Relaxed
+          if (!requiresMoc || basename != scannedFileBasename) {
+            const std::string mocSubDir =
+              ExtractSubDir(scannedFileAbsPath, currentMoc);
+            const std::string headerToMoc = FindMatchingHeader(
+              scannedFileAbsPath, mocSubDir, basename, headerExtensions);
+            if (!headerToMoc.empty()) {
+              // This is for KDE4 compatibility:
+              fileToMoc = headerToMoc;
+              if (!requiresMoc && basename == scannedFileBasename) {
+                std::ostringstream err;
+                err << "AutoMoc: Warning: " << absFilename << "\n"
+                    << "The file includes the moc file \"" << currentMoc
+                    << "\", but does not contain a " << macroName
+                    << " macro. Running moc on "
+                    << "\"" << headerToMoc << "\" ! Include \"moc_" << basename
+                    << ".cpp\" for a compatibility with "
+                       "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n";
+                this->LogWarning(err.str());
+              } else {
+                std::ostringstream err;
+                err << "AutoMoc: Warning: " << absFilename << "\n"
+                    << "The file includes the moc file \"" << currentMoc
+                    << "\" instead of \"moc_" << basename
+                    << ".cpp\". Running moc on "
+                    << "\"" << headerToMoc << "\" ! Include \"moc_" << basename
+                    << ".cpp\" for compatibility with "
+                       "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n";
+                this->LogWarning(err.str());
+              }
+            } else {
+              std::ostringstream err;
+              err << "AutoMoc: Error: " << absFilename << "\n"
+                  << "The file includes the moc file \"" << currentMoc
+                  << "\", which seems to be the moc file from a different "
+                     "source file. CMake also could not find a matching "
+                     "header.\n";
+              this->LogError(err.str());
+              return false;
+            }
+          } else {
+            // Include self
+            fileToMoc = absFilename;
+            ownDotMocIncluded = true;
+          }
+        } else {
+          // Mode: Strict
+          if (basename == scannedFileBasename) {
+            // Include self
+            fileToMoc = absFilename;
+            ownDotMocIncluded = true;
+          } else {
+            // Don't allow FOO.moc include other than self in strict mode
+            std::ostringstream err;
+            err << "AutoMoc: Error: " << absFilename << "\n"
+                << "The file includes the moc file \"" << currentMoc
+                << "\", which seems to be the moc file from a different "
+                   "source file. This is not supported. Include \""
+                << scannedFileBasename
+                << ".moc\" to run moc on this source file.\n";
+            this->LogError(err.str());
+            return false;
+          }
+        }
+        if (!fileToMoc.empty()) {
+          includedMocs[fileToMoc] = currentMoc;
         }
-        dotMocIncluded = true;
-        includedMocs[absFilename] = currentMoc;
       }
-      matchOffset += mocIncludeRegExp.end();
-    } while (mocIncludeRegExp.find(contentsString.c_str() + matchOffset));
+      // Forward content pointer
+      contentChars += this->RegExpMocInclude.end();
+    }
   }
 
   // In this case, check whether the scanned file itself contains a Q_OBJECT.
   // If this is the case, the moc_foo.cpp should probably be generated from
   // foo.cpp instead of foo.h, because otherwise it won't build.
   // But warn, since this is not how it is supposed to be used.
-  std::string macroName;
-  if (!dotMocIncluded && requiresMocing(contentsString, macroName)) {
-    // otherwise always error out since it will not compile:
-    std::ostringstream err;
-    err << "AUTOGEN: error: " << absFilename << ": The file "
-        << "contains a " << macroName << " macro, but does not include "
-        << "\"" << scannedFileBasename << ".moc\" !\n"
-        << std::endl;
-    this->LogError(err.str());
-    ::exit(EXIT_FAILURE);
-  }
-}
-
-void cmQtAutoGenerators::ParseForUic(
-  const std::string& absFilename,
-  std::map<std::string, std::vector<std::string> >& includedUis)
-{
-  if (this->UicExecutable.empty()) {
-    return;
-  }
-  const std::string contentsString = ReadAll(absFilename);
-  if (contentsString.empty()) {
-    std::ostringstream err;
-    err << "AUTOGEN: warning: " << absFilename << ": file is empty\n"
-        << std::endl;
-    this->LogError(err.str());
-    return;
-  }
-  this->ParseForUic(absFilename, contentsString, includedUis);
-}
+  if (requiresMoc && !ownDotMocIncluded) {
+    if (relaxed && ownMocUnderscoreIncluded) {
+      // This is for KDE4 compatibility:
+      std::ostringstream err;
+      err << "AutoMoc: Warning: " << absFilename << "\n"
+          << "The file contains a " << macroName
+          << " macro, but does not include "
+          << "\"" << scannedFileBasename << ".moc\", but instead includes "
+          << "\"" << ownMocUnderscoreFile << "\". Running moc on "
+          << "\"" << absFilename << "\" ! Better include \""
+          << scannedFileBasename
+          << ".moc\" for compatibility with "
+             "strict mode (see CMAKE_AUTOMOC_RELAXED_MODE).\n";
+      this->LogWarning(err.str());
 
-void cmQtAutoGenerators::ParseForUic(
-  const std::string& absFilename, const std::string& contentsString,
-  std::map<std::string, std::vector<std::string> >& includedUis)
-{
-  if (this->UicExecutable.empty()) {
-    return;
+      // Use scanned source file instead of scanned header file as moc source
+      includedMocs[absFilename] = ownMocUnderscoreFile;
+      includedMocs.erase(ownMocHeaderFile);
+    } else {
+      // Otherwise always error out since it will not compile:
+      std::ostringstream err;
+      err << "AutoMoc: Error: " << absFilename << "\n"
+          << "The file contains a " << macroName
+          << " macro, but does not include "
+          << "\"" << scannedFileBasename << ".moc\" !\n";
+      this->LogError(err.str());
+      return false;
+    }
   }
-  cmsys::RegularExpression uiIncludeRegExp(
-    "[\n][ \t]*#[ \t]*include[ \t]+"
-    "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]");
-
-  std::string::size_type matchOffset = 0;
-
-  const std::string realName = cmsys::SystemTools::GetRealPath(absFilename);
-
-  matchOffset = 0;
-  if ((strstr(contentsString.c_str(), "ui_") != CM_NULLPTR) &&
-      (uiIncludeRegExp.find(contentsString))) {
-    do {
-      const std::string currentUi = uiIncludeRegExp.match(1);
-
-      std::string basename =
-        cmsys::SystemTools::GetFilenameWithoutLastExtension(currentUi);
-
-      // basename should be the part of the ui filename used for
-      // finding the correct header, so we need to remove the ui_ part
-      basename = basename.substr(3);
-
-      includedUis[realName].push_back(basename);
 
-      matchOffset += uiIncludeRegExp.end();
-    } while (uiIncludeRegExp.find(contentsString.c_str() + matchOffset));
-  }
+  return true;
 }
 
-void cmQtAutoGenerators::SearchHeadersForCppFile(
+void cmQtAutoGenerators::SearchHeadersForSourceFile(
   const std::string& absFilename,
   const std::vector<std::string>& headerExtensions,
-  std::set<std::string>& absHeaders)
+  std::set<std::string>& absHeadersMoc, std::set<std::string>& absHeadersUic)
 {
   // search for header files and private header files we may need to moc:
-  const std::string basename =
-    cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename);
-  const std::string absPath = cmsys::SystemTools::GetFilenamePath(
-                                cmsys::SystemTools::GetRealPath(absFilename)) +
-    '/';
+  std::string basepath = cmsys::SystemTools::GetFilenamePath(
+    cmsys::SystemTools::GetRealPath(absFilename));
+  basepath += '/';
+  basepath += cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename);
 
+  // Search for regular header
   for (std::vector<std::string>::const_iterator ext = headerExtensions.begin();
        ext != headerExtensions.end(); ++ext) {
-    const std::string headerName = absPath + basename + "." + (*ext);
+    const std::string headerName = basepath + "." + (*ext);
     if (cmsys::SystemTools::FileExists(headerName.c_str())) {
-      absHeaders.insert(headerName);
+      // Moc headers
+      if (!this->MocSkipTest(absFilename) && !this->MocSkipTest(headerName)) {
+        absHeadersMoc.insert(headerName);
+      }
+      // Uic headers
+      if (!this->UicSkipTest(absFilename) && !this->UicSkipTest(headerName)) {
+        absHeadersUic.insert(headerName);
+      }
       break;
     }
   }
+  // Search for private header
   for (std::vector<std::string>::const_iterator ext = headerExtensions.begin();
        ext != headerExtensions.end(); ++ext) {
-    const std::string privateHeaderName = absPath + basename + "_p." + (*ext);
-    if (cmsys::SystemTools::FileExists(privateHeaderName.c_str())) {
-      absHeaders.insert(privateHeaderName);
+    const std::string headerName = basepath + "_p." + (*ext);
+    if (cmsys::SystemTools::FileExists(headerName.c_str())) {
+      // Moc headers
+      if (!this->MocSkipTest(absFilename) && !this->MocSkipTest(headerName)) {
+        absHeadersMoc.insert(headerName);
+      }
+      // Uic headers
+      if (!this->UicSkipTest(absFilename) && !this->UicSkipTest(headerName)) {
+        absHeadersUic.insert(headerName);
+      }
       break;
     }
   }
 }
 
 void cmQtAutoGenerators::ParseHeaders(
-  const std::set<std::string>& absHeaders,
+  const std::set<std::string>& absHeadersMoc,
+  const std::set<std::string>& absHeadersUic,
   const std::map<std::string, std::string>& includedMocs,
   std::map<std::string, std::string>& notIncludedMocs,
   std::map<std::string, std::vector<std::string> >& includedUis)
 {
-  cmFilePathUuid fpathUuid(this->Srcdir, this->Builddir,
-                           this->ProjectSourceDir, this->ProjectBinaryDir);
-  for (std::set<std::string>::const_iterator hIt = absHeaders.begin();
-       hIt != absHeaders.end(); ++hIt) {
+  // Merged header files list to read files only once
+  std::set<std::string> headerFiles;
+  headerFiles.insert(absHeadersMoc.begin(), absHeadersMoc.end());
+  headerFiles.insert(absHeadersUic.begin(), absHeadersUic.end());
+
+  for (std::set<std::string>::const_iterator hIt = headerFiles.begin();
+       hIt != headerFiles.end(); ++hIt) {
     const std::string& headerName = *hIt;
     const std::string contents = ReadAll(headerName);
 
-    if (!this->MocExecutable.empty() &&
-        includedMocs.find(headerName) == includedMocs.end()) {
+    // Parse header content for MOC
+    if ((absHeadersMoc.find(headerName) != absHeadersMoc.end()) &&
+        (includedMocs.find(headerName) == includedMocs.end())) {
+      // Process
       if (this->Verbose) {
         std::ostringstream err;
-        err << "AUTOGEN: Checking " << headerName << std::endl;
+        err << "AutoMoc: Checking " << headerName << "\n";
         this->LogInfo(err.str());
       }
-
       std::string macroName;
-      if (requiresMocing(contents, macroName)) {
-        notIncludedMocs[headerName] =
-          this->TargetBuildSubDir + fpathUuid.get(headerName, "moc_", ".cpp");
+      if (this->MocRequired(contents, macroName)) {
+        notIncludedMocs[headerName] = fpathCheckSum.getPart(headerName) +
+          "/moc_" +
+          cmsys::SystemTools::GetFilenameWithoutLastExtension(headerName) +
+          ".cpp";
       }
     }
-    this->ParseForUic(headerName, contents, includedUis);
+
+    // Parse header content for UIC
+    if (absHeadersUic.find(headerName) != absHeadersUic.end()) {
+      this->ParseContentForUic(headerName, contents, includedUis);
+    }
   }
 }
 
-bool cmQtAutoGenerators::GenerateMocFiles(
+bool cmQtAutoGenerators::MocGenerateAll(
   const std::map<std::string, std::string>& includedMocs,
   const std::map<std::string, std::string>& notIncludedMocs)
 {
+  if (this->MocExecutable.empty()) {
+    return true;
+  }
+
   // look for name collisions
   {
     std::multimap<std::string, std::string> collisions;
@@ -986,51 +1083,59 @@ bool cmQtAutoGenerators::GenerateMocFiles(
     mergedMocs.insert(notIncludedMocs.begin(), notIncludedMocs.end());
     if (this->NameCollisionTest(mergedMocs, collisions)) {
       std::ostringstream err;
-      err << "AUTOGEN: error: "
+      err << "AutoMoc: Error: "
              "The same moc file will be generated "
              "from different sources."
           << std::endl
           << "To avoid this error either" << std::endl
           << "- rename the source files or" << std::endl
           << "- do not include the (moc_NAME.cpp|NAME.moc) file" << std::endl;
-      this->NameCollisionLog(err.str(), collisions);
-      ::exit(EXIT_FAILURE);
+      this->LogErrorNameCollision(err.str(), collisions);
+      return false;
     }
   }
 
   // generate moc files that are included by source files.
-  for (std::map<std::string, std::string>::const_iterator it =
-         includedMocs.begin();
-       it != includedMocs.end(); ++it) {
-    if (!this->GenerateMoc(it->first, it->second)) {
-      if (this->RunMocFailed) {
-        return false;
+  {
+    const std::string subDirPrefix = "include/";
+    for (std::map<std::string, std::string>::const_iterator it =
+           includedMocs.begin();
+         it != includedMocs.end(); ++it) {
+      if (!this->MocGenerateFile(it->first, it->second, subDirPrefix)) {
+        if (this->RunMocFailed) {
+          return false;
+        }
       }
     }
   }
 
   // generate moc files that are _not_ included by source files.
   bool automocCppChanged = false;
-  for (std::map<std::string, std::string>::const_iterator it =
-         notIncludedMocs.begin();
-       it != notIncludedMocs.end(); ++it) {
-    if (this->GenerateMoc(it->first, it->second)) {
-      automocCppChanged = true;
-    } else {
-      if (this->RunMocFailed) {
-        return false;
+  {
+    const std::string subDirPrefix;
+    for (std::map<std::string, std::string>::const_iterator it =
+           notIncludedMocs.begin();
+         it != notIncludedMocs.end(); ++it) {
+      if (this->MocGenerateFile(it->first, it->second, subDirPrefix)) {
+        automocCppChanged = true;
+      } else {
+        if (this->RunMocFailed) {
+          return false;
+        }
       }
     }
   }
 
-  // compose _automoc.cpp content
+  // Compose moc_compilation.cpp content
   std::string automocSource;
   {
     std::ostringstream outStream;
     outStream << "/* This file is autogenerated, do not edit*/\n";
     if (notIncludedMocs.empty()) {
+      // Dummy content
       outStream << "enum some_compilers { need_more_than_nothing };\n";
     } else {
+      // Valid content
       for (std::map<std::string, std::string>::const_iterator it =
              notIncludedMocs.begin();
            it != notIncludedMocs.end(); ++it) {
@@ -1041,15 +1146,15 @@ bool cmQtAutoGenerators::GenerateMocFiles(
     automocSource = outStream.str();
   }
 
-  // check if we even need to update _automoc.cpp
+  // Check if we even need to update moc_compilation.cpp
   if (!automocCppChanged) {
-    // compare contents of the _automoc.cpp file
+    // compare contents of the moc_compilation.cpp file
     const std::string oldContents = ReadAll(this->OutMocCppFilenameAbs);
     if (oldContents == automocSource) {
-      // nothing changed: don't touch the _automoc.cpp file
+      // nothing changed: don't touch the moc_compilation.cpp file
       if (this->Verbose) {
         std::ostringstream err;
-        err << "AUTOGEN: " << this->OutMocCppFilenameRel << " still up to date"
+        err << "AutoMoc: " << this->OutMocCppFilenameRel << " still up to date"
             << std::endl;
         this->LogInfo(err.str());
       }
@@ -1057,43 +1162,61 @@ bool cmQtAutoGenerators::GenerateMocFiles(
     }
   }
 
-  // actually write _automoc.cpp
+  // Actually write moc_compilation.cpp
   {
-    std::string msg = "Generating moc compilation ";
+    std::string msg = "Generating MOC compilation ";
     msg += this->OutMocCppFilenameRel;
-    cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundBlue |
-                                       cmsysTerminal_Color_ForegroundBold,
-                                     msg.c_str(), true, this->ColorOutput);
+    this->LogBold(msg);
   }
-  {
+  // Make sure the parent directory exists
+  bool success = this->MakeParentDirectory(this->OutMocCppFilenameAbs);
+  if (success) {
     cmsys::ofstream outfile;
     outfile.open(this->OutMocCppFilenameAbs.c_str(), std::ios::trunc);
-    outfile << automocSource;
-    outfile.close();
+    if (!outfile) {
+      success = false;
+      std::ostringstream err;
+      err << "AutoMoc: error opening " << this->OutMocCppFilenameAbs << "\n";
+      this->LogError(err.str());
+    } else {
+      outfile << automocSource;
+      // Check for write errors
+      if (!outfile.good()) {
+        success = false;
+        std::ostringstream err;
+        err << "AutoMoc: error writing " << this->OutMocCppFilenameAbs << "\n";
+        this->LogError(err.str());
+      }
+    }
   }
-
-  return true;
+  return success;
 }
 
-bool cmQtAutoGenerators::GenerateMoc(const std::string& sourceFile,
-                                     const std::string& mocFileName)
+/**
+ * @return True if a moc file was created. False may indicate an error.
+ */
+bool cmQtAutoGenerators::MocGenerateFile(const std::string& sourceFile,
+                                         const std::string& mocFileName,
+                                         const std::string& subDirPrefix)
 {
-  const std::string mocFilePath = this->Builddir + mocFileName;
-  int sourceNewerThanMoc = 0;
-  bool success = cmsys::SystemTools::FileTimeCompare(sourceFile, mocFilePath,
-                                                     &sourceNewerThanMoc);
-  if (this->GenerateAll || !success || sourceNewerThanMoc >= 0) {
-    // make sure the directory for the resulting moc file exists
-    std::string mocDir = mocFilePath.substr(0, mocFilePath.rfind('/'));
-    if (!cmsys::SystemTools::FileExists(mocDir.c_str(), false)) {
-      cmsys::SystemTools::MakeDirectory(mocDir.c_str());
-    }
-
-    std::string msg = "Generating moc source ";
-    msg += mocFileName;
-    cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundBlue |
-                                       cmsysTerminal_Color_ForegroundBold,
-                                     msg.c_str(), true, this->ColorOutput);
+  const std::string mocFileRel =
+    this->AutogenBuildSubDir + subDirPrefix + mocFileName;
+  const std::string mocFileAbs = this->CurrentBinaryDir + mocFileRel;
+
+  bool generateMoc = this->GenerateMocAll;
+  // Test if the source file is newer that the build file
+  if (!generateMoc) {
+    generateMoc = FileAbsentOrOlder(mocFileAbs, sourceFile);
+  }
+  if (generateMoc) {
+    // Log
+    this->LogBold("Generating MOC source " + mocFileRel);
+
+    // Make sure the parent directory exists
+    if (!this->MakeParentDirectory(mocFileAbs)) {
+      this->RunMocFailed = true;
+      return false;
+    }
 
     std::vector<std::string> command;
     command.push_back(this->MocExecutable);
@@ -1107,7 +1230,7 @@ bool cmQtAutoGenerators::GenerateMoc(const std::string& sourceFile,
     command.push_back("-DWIN32");
 #endif
     command.push_back("-o");
-    command.push_back(mocFilePath);
+    command.push_back(mocFileAbs);
     command.push_back(sourceFile);
 
     if (this->Verbose) {
@@ -1119,21 +1242,28 @@ bool cmQtAutoGenerators::GenerateMoc(const std::string& sourceFile,
     bool result =
       cmSystemTools::RunSingleCommand(command, &output, &output, &retVal);
     if (!result || retVal) {
-      std::ostringstream err;
-      err << "AUTOGEN: error: process for " << mocFilePath << " failed:\n"
-          << output << std::endl;
-      this->LogError(err.str());
+      {
+        std::ostringstream err;
+        err << "AutoMoc: Error: moc process for " << mocFileRel << " failed:\n"
+            << output << std::endl;
+        this->LogError(err.str());
+      }
+      cmSystemTools::RemoveFile(mocFileAbs);
       this->RunMocFailed = true;
-      cmSystemTools::RemoveFile(mocFilePath);
+      return false;
     }
     return true;
   }
   return false;
 }
 
-bool cmQtAutoGenerators::GenerateUiFiles(
+bool cmQtAutoGenerators::UicGenerateAll(
   const std::map<std::string, std::vector<std::string> >& includedUis)
 {
+  if (this->UicExecutable.empty()) {
+    return true;
+  }
+
   // single map with input / output names
   std::map<std::string, std::map<std::string, std::string> > uiGenMap;
   std::map<std::string, std::string> testMap;
@@ -1161,12 +1291,12 @@ bool cmQtAutoGenerators::GenerateUiFiles(
     std::multimap<std::string, std::string> collisions;
     if (this->NameCollisionTest(testMap, collisions)) {
       std::ostringstream err;
-      err << "AUTOGEN: error: The same ui_NAME.h file will be generated "
+      err << "AutoUic: Error: The same ui_NAME.h file will be generated "
              "from different sources."
           << std::endl
           << "To avoid this error rename the source files." << std::endl;
-      this->NameCollisionLog(err.str(), collisions);
-      ::exit(EXIT_FAILURE);
+      this->LogErrorNameCollision(err.str(), collisions);
+      return false;
     }
   }
   testMap.clear();
@@ -1179,7 +1309,7 @@ bool cmQtAutoGenerators::GenerateUiFiles(
     for (std::map<std::string, std::string>::const_iterator sit =
            it->second.begin();
          sit != it->second.end(); ++sit) {
-      if (!this->GenerateUi(it->first, sit->first, sit->second)) {
+      if (!this->UicGenerateFile(it->first, sit->first, sit->second)) {
         if (this->RunUicFailed) {
           return false;
         }
@@ -1190,25 +1320,31 @@ bool cmQtAutoGenerators::GenerateUiFiles(
   return true;
 }
 
-bool cmQtAutoGenerators::GenerateUi(const std::string& realName,
-                                    const std::string& uiInputFile,
-                                    const std::string& uiOutputFile)
+/**
+ * @return True if a uic file was created. False may indicate an error.
+ */
+bool cmQtAutoGenerators::UicGenerateFile(const std::string& realName,
+                                         const std::string& uiInputFile,
+                                         const std::string& uiOutputFile)
 {
-  if (!cmsys::SystemTools::FileExists(this->Builddir.c_str(), false)) {
-    cmsys::SystemTools::MakeDirectory(this->Builddir.c_str());
-  }
+  const std::string uicFileRel =
+    this->AutogenBuildSubDir + "include/" + uiOutputFile;
+  const std::string uicFileAbs = this->CurrentBinaryDir + uicFileRel;
 
-  const std::string uiBuildFile = this->Builddir + uiOutputFile;
+  bool generateUic = this->GenerateUicAll;
+  // Test if the source file is newer that the build file
+  if (!generateUic) {
+    generateUic = FileAbsentOrOlder(uicFileAbs, uiInputFile);
+  }
+  if (generateUic) {
+    // Log
+    this->LogBold("Generating UIC header " + uicFileRel);
 
-  int sourceNewerThanUi = 0;
-  bool success = cmsys::SystemTools::FileTimeCompare(uiInputFile, uiBuildFile,
-                                                     &sourceNewerThanUi);
-  if (this->GenerateAll || !success || sourceNewerThanUi >= 0) {
-    std::string msg = "Generating ui header ";
-    msg += uiOutputFile;
-    cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundBlue |
-                                       cmsysTerminal_Color_ForegroundBold,
-                                     msg.c_str(), true, this->ColorOutput);
+    // Make sure the parent directory exists
+    if (!this->MakeParentDirectory(uicFileAbs)) {
+      this->RunUicFailed = true;
+      return false;
+    }
 
     std::vector<std::string> command;
     command.push_back(this->UicExecutable);
@@ -1219,13 +1355,12 @@ bool cmQtAutoGenerators::GenerateUi(const std::string& realName,
     if (optionIt != this->UicOptions.end()) {
       std::vector<std::string> fileOpts;
       cmSystemTools::ExpandListArgument(optionIt->second, fileOpts);
-      cmQtAutoGenerators::MergeUicOptions(opts, fileOpts,
-                                          this->QtMajorVersion == "5");
+      UicMergeOptions(opts, fileOpts, this->QtMajorVersion == "5");
     }
     command.insert(command.end(), opts.begin(), opts.end());
 
     command.push_back("-o");
-    command.push_back(uiBuildFile);
+    command.push_back(uicFileAbs);
     command.push_back(uiInputFile);
 
     if (this->Verbose) {
@@ -1236,13 +1371,15 @@ bool cmQtAutoGenerators::GenerateUi(const std::string& realName,
     bool result =
       cmSystemTools::RunSingleCommand(command, &output, &output, &retVal);
     if (!result || retVal) {
-      std::ostringstream err;
-      err << "AUTOUIC: error: process for " << uiOutputFile
-          << " needed by\n \"" << realName << "\"\nfailed:\n"
-          << output << std::endl;
-      this->LogError(err.str());
+      {
+        std::ostringstream err;
+        err << "AutoUic: Error: uic process for " << uicFileRel
+            << " needed by\n \"" << realName << "\"\nfailed:\n"
+            << output << std::endl;
+        this->LogError(err.str());
+      }
+      cmSystemTools::RemoveFile(uicFileAbs);
       this->RunUicFailed = true;
-      cmSystemTools::RemoveFile(uiOutputFile);
       return false;
     }
     return true;
@@ -1250,38 +1387,21 @@ bool cmQtAutoGenerators::GenerateUi(const std::string& realName,
   return false;
 }
 
-bool cmQtAutoGenerators::InputFilesNewerThanQrc(const std::string& qrcFile,
-                                                const std::string& rccOutput)
+bool cmQtAutoGenerators::QrcGenerateAll()
 {
-  std::vector<std::string> const& files = this->RccInputs[qrcFile];
-  for (std::vector<std::string>::const_iterator it = files.begin();
-       it != files.end(); ++it) {
-    int inputNewerThanQrc = 0;
-    bool success =
-      cmsys::SystemTools::FileTimeCompare(*it, rccOutput, &inputNewerThanQrc);
-    if (!success || inputNewerThanQrc >= 0) {
-      return true;
-    }
+  if (this->RccExecutable.empty()) {
+    return true;
   }
-  return false;
-}
 
-bool cmQtAutoGenerators::GenerateQrcFiles()
-{
   // generate single map with input / output names
   std::map<std::string, std::string> qrcGenMap;
-  {
-    cmFilePathUuid fpathUuid(this->Srcdir, this->Builddir,
-                             this->ProjectSourceDir, this->ProjectBinaryDir);
-    for (std::vector<std::string>::const_iterator si =
-           this->RccSources.begin();
-         si != this->RccSources.end(); ++si) {
-      const std::string ext =
-        cmsys::SystemTools::GetFilenameLastExtension(*si);
-      if (ext == ".qrc") {
-        qrcGenMap[*si] =
-          (this->TargetBuildSubDir + fpathUuid.get(*si, "qrc_", ".cpp"));
-      }
+  for (std::vector<std::string>::const_iterator si = this->RccSources.begin();
+       si != this->RccSources.end(); ++si) {
+    const std::string ext = cmsys::SystemTools::GetFilenameLastExtension(*si);
+    if (ext == ".qrc") {
+      qrcGenMap[*si] = this->AutogenBuildSubDir + fpathCheckSum.getPart(*si) +
+        "/qrc_" + cmsys::SystemTools::GetFilenameWithoutLastExtension(*si) +
+        ".cpp";
     }
   }
 
@@ -1290,12 +1410,12 @@ bool cmQtAutoGenerators::GenerateQrcFiles()
     std::multimap<std::string, std::string> collisions;
     if (this->NameCollisionTest(qrcGenMap, collisions)) {
       std::ostringstream err;
-      err << "AUTOGEN: error: The same qrc_NAME.cpp file"
+      err << "AutoRcc: Error: The same qrc_NAME.cpp file"
              " will be generated from different sources."
           << std::endl
           << "To avoid this error rename the source .qrc files." << std::endl;
-      this->NameCollisionLog(err.str(), collisions);
-      ::exit(EXIT_FAILURE);
+      this->LogErrorNameCollision(err.str(), collisions);
+      return false;
     }
   }
 
@@ -1304,7 +1424,7 @@ bool cmQtAutoGenerators::GenerateQrcFiles()
          qrcGenMap.begin();
        si != qrcGenMap.end(); ++si) {
     bool unique = FileNameIsUnique(si->first, qrcGenMap);
-    if (!this->GenerateQrc(si->first, si->second, unique)) {
+    if (!this->QrcGenerateFile(si->first, si->second, unique)) {
       if (this->RunRccFailed) {
         return false;
       }
@@ -1313,49 +1433,63 @@ bool cmQtAutoGenerators::GenerateQrcFiles()
   return true;
 }
 
-bool cmQtAutoGenerators::GenerateQrc(const std::string& qrcInputFile,
-                                     const std::string& qrcOutputFile,
-                                     bool unique_n)
+/**
+ * @return True if a rcc file was created. False may indicate an error.
+ */
+bool cmQtAutoGenerators::QrcGenerateFile(const std::string& qrcInputFile,
+                                         const std::string& qrcOutputFile,
+                                         bool unique_n)
 {
-  std::string symbolName;
-  if (unique_n) {
-    symbolName =
-      cmsys::SystemTools::GetFilenameWithoutLastExtension(qrcInputFile);
-  } else {
-    symbolName =
-      cmsys::SystemTools::GetFilenameWithoutLastExtension(qrcOutputFile);
-    // Remove "qrc_" at string begin
-    symbolName.erase(0, 4);
+  std::string symbolName =
+    cmsys::SystemTools::GetFilenameWithoutLastExtension(qrcInputFile);
+  if (!unique_n) {
+    symbolName += "_";
+    symbolName += fpathCheckSum.getPart(qrcInputFile);
   }
   // Replace '-' with '_'. The former is valid for
   // file names but not for symbol names.
   std::replace(symbolName.begin(), symbolName.end(), '-', '_');
 
-  const std::string qrcBuildFile = this->Builddir + qrcOutputFile;
+  const std::string qrcBuildFile = this->CurrentBinaryDir + qrcOutputFile;
 
-  int sourceNewerThanQrc = 0;
-  bool generateQrc = !cmsys::SystemTools::FileTimeCompare(
-    qrcInputFile, qrcBuildFile, &sourceNewerThanQrc);
-  generateQrc = generateQrc || (sourceNewerThanQrc >= 0);
-  generateQrc =
-    generateQrc || this->InputFilesNewerThanQrc(qrcInputFile, qrcBuildFile);
+  bool generateQrc = this->GenerateRccAll;
+  // Test if the resources list file is newer than build file
+  if (!generateQrc) {
+    generateQrc = FileAbsentOrOlder(qrcBuildFile, qrcInputFile);
+  }
+  // Test if any resource file is newer than the build file
+  if (!generateQrc) {
+    const std::vector<std::string>& files = this->RccInputs[qrcInputFile];
+    for (std::vector<std::string>::const_iterator it = files.begin();
+         it != files.end(); ++it) {
+      if (FileAbsentOrOlder(qrcBuildFile, *it)) {
+        generateQrc = true;
+        break;
+      }
+    }
+  }
+  if (generateQrc) {
+    {
+      std::string msg = "Generating RCC source ";
+      msg += qrcOutputFile;
+      this->LogBold(msg);
+    }
 
-  if (this->GenerateAll || generateQrc) {
-    std::string msg = "Generating qrc source ";
-    msg += qrcOutputFile;
-    cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundBlue |
-                                       cmsysTerminal_Color_ForegroundBold,
-                                     msg.c_str(), true, this->ColorOutput);
+    // Make sure the parent directory exists
+    if (!this->MakeParentDirectory(qrcOutputFile)) {
+      this->RunRccFailed = true;
+      return false;
+    }
 
     std::vector<std::string> command;
     command.push_back(this->RccExecutable);
-
-    std::map<std::string, std::string>::const_iterator optionIt =
-      this->RccOptions.find(qrcInputFile);
-    if (optionIt != this->RccOptions.end()) {
-      cmSystemTools::ExpandListArgument(optionIt->second, command);
+    {
+      std::map<std::string, std::string>::const_iterator optionIt =
+        this->RccOptions.find(qrcInputFile);
+      if (optionIt != this->RccOptions.end()) {
+        cmSystemTools::ExpandListArgument(optionIt->second, command);
+      }
     }
-
     command.push_back("-name");
     command.push_back(symbolName);
     command.push_back("-o");
@@ -1370,49 +1504,23 @@ bool cmQtAutoGenerators::GenerateQrc(const std::string& qrcInputFile,
     bool result =
       cmSystemTools::RunSingleCommand(command, &output, &output, &retVal);
     if (!result || retVal) {
-      std::ostringstream err;
-      err << "AUTORCC: error: process for " << qrcOutputFile << " failed:\n"
-          << output << std::endl;
-      this->LogError(err.str());
-      this->RunRccFailed = true;
+      {
+        std::ostringstream err;
+        err << "AutoRcc: Error: rcc process for " << qrcOutputFile
+            << " failed:\n"
+            << output << std::endl;
+        this->LogError(err.str());
+      }
       cmSystemTools::RemoveFile(qrcBuildFile);
+      this->RunRccFailed = true;
       return false;
     }
+    return true;
   }
-  return true;
-}
-
-/**
- * @brief Collects name collisions as output/input pairs
- * @return True if there were collisions
- */
-bool cmQtAutoGenerators::NameCollisionTest(
-  const std::map<std::string, std::string>& genFiles,
-  std::multimap<std::string, std::string>& collisions)
-{
-  typedef std::map<std::string, std::string>::const_iterator Iter;
-  typedef std::map<std::string, std::string>::value_type VType;
-  for (Iter ait = genFiles.begin(); ait != genFiles.end(); ++ait) {
-    bool first_match(true);
-    for (Iter bit = (++Iter(ait)); bit != genFiles.end(); ++bit) {
-      if (ait->second == bit->second) {
-        if (first_match) {
-          if (collisions.find(ait->second) != collisions.end()) {
-            // We already know of this collision from before
-            break;
-          }
-          collisions.insert(VType(ait->second, ait->first));
-          first_match = false;
-        }
-        collisions.insert(VType(bit->second, bit->first));
-      }
-    }
-  }
-
-  return !collisions.empty();
+  return false;
 }
 
-void cmQtAutoGenerators::NameCollisionLog(
+void cmQtAutoGenerators::LogErrorNameCollision(
   const std::string& message,
   const std::multimap<std::string, std::string>& collisions)
 {
@@ -1428,14 +1536,30 @@ void cmQtAutoGenerators::NameCollisionLog(
   this->LogError(err.str());
 }
 
+void cmQtAutoGenerators::LogBold(const std::string& message)
+{
+  cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundBlue |
+                                     cmsysTerminal_Color_ForegroundBold,
+                                   message.c_str(), true, this->ColorOutput);
+}
+
 void cmQtAutoGenerators::LogInfo(const std::string& message)
 {
-  std::cout << message;
+  std::cout << message.c_str();
+}
+
+void cmQtAutoGenerators::LogWarning(const std::string& message)
+{
+  std::ostringstream ostr;
+  ostr << message << "\n";
+  std::cout << message.c_str();
 }
 
 void cmQtAutoGenerators::LogError(const std::string& message)
 {
-  std::cerr << message;
+  std::ostringstream ostr;
+  ostr << message << "\n\n";
+  std::cerr << ostr.str();
 }
 
 void cmQtAutoGenerators::LogCommand(const std::vector<std::string>& command)
@@ -1454,21 +1578,51 @@ void cmQtAutoGenerators::LogCommand(const std::vector<std::string>& command)
   }
 }
 
-std::string cmQtAutoGenerators::JoinExts(const std::vector<std::string>& lst)
+/**
+ * @brief Collects name collisions as output/input pairs
+ * @return True if there were collisions
+ */
+bool cmQtAutoGenerators::NameCollisionTest(
+  const std::map<std::string, std::string>& genFiles,
+  std::multimap<std::string, std::string>& collisions)
 {
-  if (lst.empty()) {
-    return "";
+  typedef std::map<std::string, std::string>::const_iterator Iter;
+  typedef std::map<std::string, std::string>::value_type VType;
+  for (Iter ait = genFiles.begin(); ait != genFiles.end(); ++ait) {
+    bool first_match(true);
+    for (Iter bit = (++Iter(ait)); bit != genFiles.end(); ++bit) {
+      if (ait->second == bit->second) {
+        if (first_match) {
+          if (collisions.find(ait->second) != collisions.end()) {
+            // We already know of this collision from before
+            break;
+          }
+          collisions.insert(VType(ait->second, ait->first));
+          first_match = false;
+        }
+        collisions.insert(VType(bit->second, bit->first));
+      }
+    }
   }
 
-  std::string result;
-  std::string separator = ",";
-  for (std::vector<std::string>::const_iterator it = lst.begin();
-       it != lst.end(); ++it) {
-    if (it != lst.begin()) {
-      result += separator;
+  return !collisions.empty();
+}
+
+/**
+ * @brief Generates the parent directory of the given file on demand
+ * @return True on success
+ */
+bool cmQtAutoGenerators::MakeParentDirectory(const std::string& filename)
+{
+  bool success = true;
+  const std::string dirName = cmSystemTools::GetFilenamePath(filename);
+  if (!dirName.empty()) {
+    success = cmsys::SystemTools::MakeDirectory(dirName);
+    if (!success) {
+      std::ostringstream err;
+      err << "AutoGen: Directory creation failed: " << dirName << std::endl;
+      this->LogError(err.str());
     }
-    result += '.' + (*it);
   }
-  result.erase(result.end() - 1);
-  return result;
+  return success;
 }
diff --git a/Source/cmQtAutoGenerators.h b/Source/cmQtAutoGenerators.h
index 08d7e03..7891eb9 100644
--- a/Source/cmQtAutoGenerators.h
+++ b/Source/cmQtAutoGenerators.h
@@ -4,6 +4,8 @@
 #define cmQtAutoGenerators_h
 
 #include <cmConfigure.h> // IWYU pragma: keep
+#include <cmFilePathChecksum.h>
+#include <cmsys/RegularExpression.hxx>
 
 #include <list>
 #include <map>
@@ -20,119 +22,147 @@ public:
   bool Run(const std::string& targetDirectory, const std::string& config);
 
 private:
+  // - Configuration
   bool ReadAutogenInfoFile(cmMakefile* makefile,
                            const std::string& targetDirectory,
                            const std::string& config);
-  bool ReadOldMocDefinitionsFile(cmMakefile* makefile,
-                                 const std::string& targetDirectory);
-  void WriteOldMocDefinitionsFile(const std::string& targetDirectory);
 
-  std::string MakeCompileSettingsString(cmMakefile* makefile);
+  std::string MocSettingsStringCompose();
+  std::string UicSettingsStringCompose();
+  std::string RccSettingsStringCompose();
+  void OldSettingsReadFile(cmMakefile* makefile,
+                           const std::string& targetDirectory);
+  bool OldSettingsWriteFile(const std::string& targetDirectory);
 
+  // - Init and run
+  void Init();
   bool RunAutogen(cmMakefile* makefile);
-  bool GenerateMocFiles(
-    const std::map<std::string, std::string>& includedMocs,
-    const std::map<std::string, std::string>& notIncludedMocs);
-  bool GenerateMoc(const std::string& sourceFile,
-                   const std::string& mocFileName);
-  bool GenerateUiFiles(
-    const std::map<std::string, std::vector<std::string> >& includedUis);
-  bool GenerateUi(const std::string& realName, const std::string& uiInputFile,
-                  const std::string& uiOutputFile);
-  bool GenerateQrcFiles();
-  bool GenerateQrc(const std::string& qrcInputFile,
-                   const std::string& qrcOutputFile, bool unique_n);
 
-  void ParseCppFile(
-    const std::string& absFilename,
-    const std::vector<std::string>& headerExtensions,
-    std::map<std::string, std::string>& includedMocs,
-    std::map<std::string, std::vector<std::string> >& includedUis);
-  void StrictParseCppFile(
+  // - Content analysis
+  bool MocRequired(const std::string& text, std::string& macroName);
+  bool MocSkipTest(const std::string& absFilename);
+  bool UicSkipTest(const std::string& absFilename);
+
+  bool ParseSourceFile(
     const std::string& absFilename,
     const std::vector<std::string>& headerExtensions,
     std::map<std::string, std::string>& includedMocs,
-    std::map<std::string, std::vector<std::string> >& includedUis);
-  void SearchHeadersForCppFile(
+    std::map<std::string, std::vector<std::string> >& includedUis,
+    bool relaxed);
+
+  void SearchHeadersForSourceFile(
     const std::string& absFilename,
     const std::vector<std::string>& headerExtensions,
-    std::set<std::string>& absHeaders);
+    std::set<std::string>& absHeadersMoc,
+    std::set<std::string>& absHeadersUic);
 
   void ParseHeaders(
-    const std::set<std::string>& absHeaders,
+    const std::set<std::string>& absHeadersMoc,
+    const std::set<std::string>& absHeadersUic,
     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(
+  void ParseContentForUic(
     const std::string& fileName, const std::string& contentsString,
     std::map<std::string, std::vector<std::string> >& includedUis);
 
-  void ParseForUic(
-    const std::string& fileName,
-    std::map<std::string, std::vector<std::string> >& includedUis);
+  bool ParseContentForMoc(const std::string& absFilename,
+                          const std::string& contentsString,
+                          const std::vector<std::string>& headerExtensions,
+                          std::map<std::string, std::string>& includedMocs,
+                          bool relaxed);
 
-  void Init();
+  // - Moc file generation
+  bool MocGenerateAll(
+    const std::map<std::string, std::string>& includedMocs,
+    const std::map<std::string, std::string>& notIncludedMocs);
+  bool MocGenerateFile(const std::string& sourceFile,
+                       const std::string& mocFileName,
+                       const std::string& subDirPrefix);
 
-  bool NameCollisionTest(const std::map<std::string, std::string>& genFiles,
-                         std::multimap<std::string, std::string>& collisions);
-  void NameCollisionLog(
+  // - Uic file generation
+  bool UicGenerateAll(
+    const std::map<std::string, std::vector<std::string> >& includedUis);
+  bool UicGenerateFile(const std::string& realName,
+                       const std::string& uiInputFile,
+                       const std::string& uiOutputFile);
+
+  // - Qrc file generation
+  bool QrcGenerateAll();
+  bool QrcGenerateFile(const std::string& qrcInputFile,
+                       const std::string& qrcOutputFile, bool unique_n);
+
+  // - Logging
+  void LogErrorNameCollision(
     const std::string& message,
     const std::multimap<std::string, std::string>& collisions);
-
+  void LogBold(const std::string& message);
   void LogInfo(const std::string& message);
+  void LogWarning(const std::string& message);
   void LogError(const std::string& message);
   void LogCommand(const std::vector<std::string>& command);
-  std::string JoinExts(const std::vector<std::string>& lst);
 
-  static void MergeUicOptions(std::vector<std::string>& opts,
-                              const std::vector<std::string>& fileOpts,
-                              bool isQt5);
-
-  bool InputFilesNewerThanQrc(const std::string& qrcFile,
-                              const std::string& rccOutput);
+  // - Utility
+  bool NameCollisionTest(const std::map<std::string, std::string>& genFiles,
+                         std::multimap<std::string, std::string>& collisions);
+  bool MakeParentDirectory(const std::string& filename);
 
+  // - Target names
+  std::string OriginTargetName;
+  std::string AutogenTargetName;
+  // - Directories
+  std::string ProjectSourceDir;
+  std::string ProjectBinaryDir;
+  std::string CurrentSourceDir;
+  std::string CurrentBinaryDir;
+  std::string AutogenBuildSubDir;
+  // - Qt environment
   std::string QtMajorVersion;
-  std::string Sources;
-  std::vector<std::string> RccSources;
-  std::string SkipMoc;
-  std::string SkipUic;
-  std::string Headers;
-  std::string Srcdir;
-  std::string Builddir;
   std::string MocExecutable;
   std::string UicExecutable;
   std::string RccExecutable;
+  // - File lists
+  std::vector<std::string> Sources;
+  std::vector<std::string> Headers;
+  // - Moc
+  std::vector<std::string> SkipMoc;
   std::string MocCompileDefinitionsStr;
   std::string MocIncludesStr;
   std::string MocOptionsStr;
-  std::string ProjectBinaryDir;
-  std::string ProjectSourceDir;
-  std::string TargetName;
-  std::string OriginTargetName;
-
-  std::string CurrentCompileSettingsStr;
-  std::string OldCompileSettingsStr;
-
-  std::string TargetBuildSubDir;
   std::string OutMocCppFilenameRel;
   std::string OutMocCppFilenameAbs;
   std::list<std::string> MocIncludes;
   std::list<std::string> MocDefinitions;
   std::vector<std::string> MocOptions;
+  std::string MocSettingsString;
+  // - Uic
+  std::vector<std::string> SkipUic;
   std::vector<std::string> UicTargetOptions;
   std::map<std::string, std::string> UicOptions;
+  std::string UicSettingsString;
+  // - Rcc
+  std::vector<std::string> RccSources;
   std::map<std::string, std::string> RccOptions;
   std::map<std::string, std::vector<std::string> > RccInputs;
-
+  std::string RccSettingsString;
+  // - Utility
+  cmFilePathChecksum fpathCheckSum;
+  cmsys::RegularExpression RegExpQObject;
+  cmsys::RegularExpression RegExpQGadget;
+  cmsys::RegularExpression RegExpMocInclude;
+  cmsys::RegularExpression RegExpUicInclude;
+  // - Flags
   bool IncludeProjectDirsBefore;
   bool Verbose;
   bool ColorOutput;
   bool RunMocFailed;
   bool RunUicFailed;
   bool RunRccFailed;
-  bool GenerateAll;
-  bool RelaxedMode;
+  bool GenerateMocAll;
+  bool GenerateUicAll;
+  bool GenerateRccAll;
+  bool MocRelaxedMode;
 };
 
 #endif
diff --git a/Source/cmRemoveCommand.cxx b/Source/cmRemoveCommand.cxx
index 540f37f..5a52927 100644
--- a/Source/cmRemoveCommand.cxx
+++ b/Source/cmRemoveCommand.cxx
@@ -2,6 +2,11 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmRemoveCommand.h"
 
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmRemoveCommand
 bool cmRemoveCommand::InitialPass(std::vector<std::string> const& args,
                                   cmExecutionStatus&)
diff --git a/Source/cmRemoveCommand.h b/Source/cmRemoveCommand.h
index bf33de0..c935f28 100644
--- a/Source/cmRemoveCommand.h
+++ b/Source/cmRemoveCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmRemoveCommand_h
 #define cmRemoveCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmRemoveCommand
  * \brief remove command
  *
@@ -34,8 +40,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "remove"; }
-
-  cmTypeMacro(cmRemoveCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmRemoveDefinitionsCommand.cxx b/Source/cmRemoveDefinitionsCommand.cxx
index cae5072..f5fe2df 100644
--- a/Source/cmRemoveDefinitionsCommand.cxx
+++ b/Source/cmRemoveDefinitionsCommand.cxx
@@ -2,6 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmRemoveDefinitionsCommand.h"
 
+#include "cmMakefile.h"
+
+class cmExecutionStatus;
+
 // cmRemoveDefinitionsCommand
 bool cmRemoveDefinitionsCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
diff --git a/Source/cmRemoveDefinitionsCommand.h b/Source/cmRemoveDefinitionsCommand.h
index 016f5fd..2bcc12d 100644
--- a/Source/cmRemoveDefinitionsCommand.h
+++ b/Source/cmRemoveDefinitionsCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmRemoveDefinitionsCommand_h
 #define cmRemoveDefinitionsCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmRemoveDefinitionsCommand
  * \brief Specify a list of compiler defines
  *
@@ -31,8 +37,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "remove_definitions"; }
-
-  cmTypeMacro(cmRemoveDefinitionsCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmReturnCommand.cxx b/Source/cmReturnCommand.cxx
index aa056c3..f8b3129 100644
--- a/Source/cmReturnCommand.cxx
+++ b/Source/cmReturnCommand.cxx
@@ -2,6 +2,8 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmReturnCommand.h"
 
+#include "cmExecutionStatus.h"
+
 // cmReturnCommand
 bool cmReturnCommand::InitialPass(std::vector<std::string> const&,
                                   cmExecutionStatus& status)
diff --git a/Source/cmReturnCommand.h b/Source/cmReturnCommand.h
index 1159e78..9496d67 100644
--- a/Source/cmReturnCommand.h
+++ b/Source/cmReturnCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmReturnCommand_h
 #define cmReturnCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmReturnCommand
  * \brief Return from a directory or function
  *
@@ -34,8 +40,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "return"; }
-
-  cmTypeMacro(cmReturnCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmRulePlaceholderExpander.cxx b/Source/cmRulePlaceholderExpander.cxx
new file mode 100644
index 0000000..f190a5c
--- /dev/null
+++ b/Source/cmRulePlaceholderExpander.cxx
@@ -0,0 +1,308 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmRulePlaceholderExpander.h"
+
+#include <ctype.h>
+#include <string.h>
+#include <utility>
+
+#include "cmOutputConverter.h"
+#include "cmSystemTools.h"
+
+cmRulePlaceholderExpander::cmRulePlaceholderExpander(
+  std::map<std::string, std::string> const& compilers,
+  std::map<std::string, std::string> const& variableMappings,
+  std::string const& compilerSysroot)
+  : Compilers(compilers)
+  , VariableMappings(variableMappings)
+  , CompilerSysroot(compilerSysroot)
+{
+}
+
+cmRulePlaceholderExpander::RuleVariables::RuleVariables()
+{
+  memset(this, 0, sizeof(*this));
+}
+
+std::string cmRulePlaceholderExpander::ExpandRuleVariable(
+  cmOutputConverter* outputConverter, std::string const& variable,
+  const RuleVariables& replaceValues)
+{
+  if (replaceValues.LinkFlags) {
+    if (variable == "LINK_FLAGS") {
+      return replaceValues.LinkFlags;
+    }
+  }
+  if (replaceValues.Manifests) {
+    if (variable == "MANIFESTS") {
+      return replaceValues.Manifests;
+    }
+  }
+  if (replaceValues.Flags) {
+    if (variable == "FLAGS") {
+      return replaceValues.Flags;
+    }
+  }
+
+  if (replaceValues.Source) {
+    if (variable == "SOURCE") {
+      return replaceValues.Source;
+    }
+  }
+  if (replaceValues.PreprocessedSource) {
+    if (variable == "PREPROCESSED_SOURCE") {
+      return replaceValues.PreprocessedSource;
+    }
+  }
+  if (replaceValues.AssemblySource) {
+    if (variable == "ASSEMBLY_SOURCE") {
+      return replaceValues.AssemblySource;
+    }
+  }
+  if (replaceValues.Object) {
+    if (variable == "OBJECT") {
+      return replaceValues.Object;
+    }
+  }
+  if (replaceValues.ObjectDir) {
+    if (variable == "OBJECT_DIR") {
+      return replaceValues.ObjectDir;
+    }
+  }
+  if (replaceValues.ObjectFileDir) {
+    if (variable == "OBJECT_FILE_DIR") {
+      return replaceValues.ObjectFileDir;
+    }
+  }
+  if (replaceValues.Objects) {
+    if (variable == "OBJECTS") {
+      return replaceValues.Objects;
+    }
+  }
+  if (replaceValues.ObjectsQuoted) {
+    if (variable == "OBJECTS_QUOTED") {
+      return replaceValues.ObjectsQuoted;
+    }
+  }
+  if (replaceValues.Defines && variable == "DEFINES") {
+    return replaceValues.Defines;
+  }
+  if (replaceValues.Includes && variable == "INCLUDES") {
+    return replaceValues.Includes;
+  }
+  if (replaceValues.TargetPDB) {
+    if (variable == "TARGET_PDB") {
+      return replaceValues.TargetPDB;
+    }
+  }
+  if (replaceValues.TargetCompilePDB) {
+    if (variable == "TARGET_COMPILE_PDB") {
+      return replaceValues.TargetCompilePDB;
+    }
+  }
+  if (replaceValues.DependencyFile) {
+    if (variable == "DEP_FILE") {
+      return replaceValues.DependencyFile;
+    }
+  }
+
+  if (replaceValues.Target) {
+    if (variable == "TARGET_QUOTED") {
+      std::string targetQuoted = replaceValues.Target;
+      if (!targetQuoted.empty() && targetQuoted[0] != '\"') {
+        targetQuoted = '\"';
+        targetQuoted += replaceValues.Target;
+        targetQuoted += '\"';
+      }
+      return targetQuoted;
+    }
+    if (variable == "TARGET_UNQUOTED") {
+      std::string unquoted = replaceValues.Target;
+      std::string::size_type sz = unquoted.size();
+      if (sz > 2 && unquoted[0] == '\"' && unquoted[sz - 1] == '\"') {
+        unquoted = unquoted.substr(1, sz - 2);
+      }
+      return unquoted;
+    }
+    if (replaceValues.LanguageCompileFlags) {
+      if (variable == "LANGUAGE_COMPILE_FLAGS") {
+        return replaceValues.LanguageCompileFlags;
+      }
+    }
+    if (replaceValues.Target) {
+      if (variable == "TARGET") {
+        return replaceValues.Target;
+      }
+    }
+    if (variable == "TARGET_IMPLIB") {
+      return this->TargetImpLib;
+    }
+    if (variable == "TARGET_VERSION_MAJOR") {
+      if (replaceValues.TargetVersionMajor) {
+        return replaceValues.TargetVersionMajor;
+      }
+      return "0";
+    }
+    if (variable == "TARGET_VERSION_MINOR") {
+      if (replaceValues.TargetVersionMinor) {
+        return replaceValues.TargetVersionMinor;
+      }
+      return "0";
+    }
+    if (replaceValues.Target) {
+      if (variable == "TARGET_BASE") {
+        // Strip the last extension off the target name.
+        std::string targetBase = replaceValues.Target;
+        std::string::size_type pos = targetBase.rfind('.');
+        if (pos != targetBase.npos) {
+          return targetBase.substr(0, pos);
+        }
+        return targetBase;
+      }
+    }
+  }
+  if (variable == "TARGET_SONAME" || variable == "SONAME_FLAG" ||
+      variable == "TARGET_INSTALLNAME_DIR") {
+    // All these variables depend on TargetSOName
+    if (replaceValues.TargetSOName) {
+      if (variable == "TARGET_SONAME") {
+        return replaceValues.TargetSOName;
+      }
+      if (variable == "SONAME_FLAG" && replaceValues.SONameFlag) {
+        return replaceValues.SONameFlag;
+      }
+      if (replaceValues.TargetInstallNameDir &&
+          variable == "TARGET_INSTALLNAME_DIR") {
+        return replaceValues.TargetInstallNameDir;
+      }
+    }
+    return "";
+  }
+  if (replaceValues.LinkLibraries) {
+    if (variable == "LINK_LIBRARIES") {
+      return replaceValues.LinkLibraries;
+    }
+  }
+  if (replaceValues.Language) {
+    if (variable == "LANGUAGE") {
+      return replaceValues.Language;
+    }
+  }
+  if (replaceValues.CMTargetName) {
+    if (variable == "TARGET_NAME") {
+      return replaceValues.CMTargetName;
+    }
+  }
+  if (replaceValues.CMTargetType) {
+    if (variable == "TARGET_TYPE") {
+      return replaceValues.CMTargetType;
+    }
+  }
+  if (replaceValues.Output) {
+    if (variable == "OUTPUT") {
+      return replaceValues.Output;
+    }
+  }
+  if (variable == "CMAKE_COMMAND") {
+    return outputConverter->ConvertToOutputFormat(
+      cmSystemTools::CollapseFullPath(cmSystemTools::GetCMakeCommand()),
+      cmOutputConverter::SHELL);
+  }
+
+  std::map<std::string, std::string>::iterator compIt =
+    this->Compilers.find(variable);
+
+  if (compIt != this->Compilers.end()) {
+    std::string ret = outputConverter->ConvertToOutputForExisting(
+      this->VariableMappings["CMAKE_" + compIt->second + "_COMPILER"]);
+    std::string const& compilerArg1 =
+      this->VariableMappings["CMAKE_" + compIt->second + "_COMPILER_ARG1"];
+    std::string const& compilerTarget =
+      this->VariableMappings["CMAKE_" + compIt->second + "_COMPILER_TARGET"];
+    std::string const& compilerOptionTarget =
+      this->VariableMappings["CMAKE_" + compIt->second +
+                             "_COMPILE_OPTIONS_TARGET"];
+    std::string const& compilerExternalToolchain =
+      this->VariableMappings["CMAKE_" + compIt->second +
+                             "_COMPILER_EXTERNAL_TOOLCHAIN"];
+    std::string const& compilerOptionExternalToolchain =
+      this->VariableMappings["CMAKE_" + compIt->second +
+                             "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN"];
+    std::string const& compilerOptionSysroot =
+      this->VariableMappings["CMAKE_" + compIt->second +
+                             "_COMPILE_OPTIONS_SYSROOT"];
+
+    // if there is a required first argument to the compiler add it
+    // to the compiler string
+    if (!compilerArg1.empty()) {
+      ret += " ";
+      ret += compilerArg1;
+    }
+    if (!compilerTarget.empty() && !compilerOptionTarget.empty()) {
+      ret += " ";
+      ret += compilerOptionTarget;
+      ret += compilerTarget;
+    }
+    if (!compilerExternalToolchain.empty() &&
+        !compilerOptionExternalToolchain.empty()) {
+      ret += " ";
+      ret += compilerOptionExternalToolchain;
+      ret += outputConverter->EscapeForShell(compilerExternalToolchain, true);
+    }
+    if (!this->CompilerSysroot.empty() && !compilerOptionSysroot.empty()) {
+      ret += " ";
+      ret += compilerOptionSysroot;
+      ret += outputConverter->EscapeForShell(this->CompilerSysroot, true);
+    }
+    return ret;
+  }
+
+  std::map<std::string, std::string>::iterator mapIt =
+    this->VariableMappings.find(variable);
+  if (mapIt != this->VariableMappings.end()) {
+    if (variable.find("_FLAG") == variable.npos) {
+      return outputConverter->ConvertToOutputForExisting(mapIt->second);
+    }
+    return mapIt->second;
+  }
+  return variable;
+}
+
+void cmRulePlaceholderExpander::ExpandRuleVariables(
+  cmOutputConverter* outputConverter, std::string& s,
+  const RuleVariables& replaceValues)
+{
+  std::string::size_type start = s.find('<');
+  // no variables to expand
+  if (start == s.npos) {
+    return;
+  }
+  std::string::size_type pos = 0;
+  std::string expandedInput;
+  while (start != s.npos && start < s.size() - 2) {
+    std::string::size_type end = s.find('>', start);
+    // if we find a < with no > we are done
+    if (end == s.npos) {
+      return;
+    }
+    char c = s[start + 1];
+    // if the next char after the < is not A-Za-z then
+    // skip it and try to find the next < in the string
+    if (!isalpha(c)) {
+      start = s.find('<', start + 1);
+    } else {
+      // extract the var
+      std::string var = s.substr(start + 1, end - start - 1);
+      std::string replace =
+        this->ExpandRuleVariable(outputConverter, var, replaceValues);
+      expandedInput += s.substr(pos, start - pos);
+      expandedInput += replace;
+      // move to next one
+      start = s.find('<', start + var.size() + 2);
+      pos = end + 1;
+    }
+  }
+  // add the rest of the input
+  expandedInput += s.substr(pos, s.size() - pos);
+  s = expandedInput;
+}
diff --git a/Source/cmRulePlaceholderExpander.h b/Source/cmRulePlaceholderExpander.h
new file mode 100644
index 0000000..8329166
--- /dev/null
+++ b/Source/cmRulePlaceholderExpander.h
@@ -0,0 +1,81 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#ifndef cmRulePlaceholderExpander_h
+#define cmRulePlaceholderExpander_h
+
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <map>
+#include <string>
+
+class cmOutputConverter;
+
+class cmRulePlaceholderExpander
+{
+public:
+  cmRulePlaceholderExpander(
+    std::map<std::string, std::string> const& compilers,
+    std::map<std::string, std::string> const& variableMappings,
+    std::string const& compilerSysroot);
+
+  void SetTargetImpLib(std::string const& targetImpLib)
+  {
+    this->TargetImpLib = targetImpLib;
+  }
+
+  // Create a struct to hold the varibles passed into
+  // ExpandRuleVariables
+  struct RuleVariables
+  {
+    RuleVariables();
+    const char* CMTargetName;
+    const char* CMTargetType;
+    const char* TargetPDB;
+    const char* TargetCompilePDB;
+    const char* TargetVersionMajor;
+    const char* TargetVersionMinor;
+    const char* Language;
+    const char* Objects;
+    const char* Target;
+    const char* LinkLibraries;
+    const char* Source;
+    const char* AssemblySource;
+    const char* PreprocessedSource;
+    const char* Output;
+    const char* Object;
+    const char* ObjectDir;
+    const char* ObjectFileDir;
+    const char* Flags;
+    const char* ObjectsQuoted;
+    const char* SONameFlag;
+    const char* TargetSOName;
+    const char* TargetInstallNameDir;
+    const char* LinkFlags;
+    const char* Manifests;
+    const char* LanguageCompileFlags;
+    const char* Defines;
+    const char* Includes;
+    const char* DependencyFile;
+    const char* FilterPrefix;
+  };
+
+  // Expand rule variables in CMake of the type found in language rules
+  void ExpandRuleVariables(cmOutputConverter* outputConverter,
+                           std::string& string,
+                           const RuleVariables& replaceValues);
+
+  // Expand rule variables in a single string
+  std::string ExpandRuleVariable(cmOutputConverter* outputConverter,
+                                 std::string const& variable,
+                                 const RuleVariables& replaceValues);
+
+private:
+  std::string TargetImpLib;
+
+  std::map<std::string, std::string> Compilers;
+  std::map<std::string, std::string> VariableMappings;
+  std::string CompilerSysroot;
+};
+
+#endif
diff --git a/Source/cmSearchPath.cxx b/Source/cmSearchPath.cxx
index c34028e..0df6e0c 100644
--- a/Source/cmSearchPath.cxx
+++ b/Source/cmSearchPath.cxx
@@ -2,8 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSearchPath.h"
 
+#include <algorithm>
+#include <cassert>
+#include <utility>
+
 #include "cmAlgorithms.h"
 #include "cmFindCommon.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
 
 cmSearchPath::cmSearchPath(cmFindCommon* findCmd)
   : FC(findCmd)
diff --git a/Source/cmSearchPath.h b/Source/cmSearchPath.h
index 80815ed..9ffa871 100644
--- a/Source/cmSearchPath.h
+++ b/Source/cmSearchPath.h
@@ -5,7 +5,9 @@
 
 #include <cmConfigure.h>
 
-#include "cmStandardIncludes.h"
+#include <set>
+#include <string>
+#include <vector>
 
 class cmFindCommon;
 
diff --git a/Source/cmSeparateArgumentsCommand.cxx b/Source/cmSeparateArgumentsCommand.cxx
index b5c3186..b27d227 100644
--- a/Source/cmSeparateArgumentsCommand.cxx
+++ b/Source/cmSeparateArgumentsCommand.cxx
@@ -2,6 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSeparateArgumentsCommand.h"
 
+#include <algorithm>
+#include <sstream>
+
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmSeparateArgumentsCommand
 bool cmSeparateArgumentsCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
diff --git a/Source/cmSeparateArgumentsCommand.h b/Source/cmSeparateArgumentsCommand.h
index 66fbef7..1cbf56e 100644
--- a/Source/cmSeparateArgumentsCommand.h
+++ b/Source/cmSeparateArgumentsCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmSeparateArgumentsCommand_h
 #define cmSeparateArgumentsCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmSeparateArgumentsCommand
  * \brief separate_arguments command
  *
@@ -34,8 +40,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "separate_arguments"; }
-
-  cmTypeMacro(cmSeparateArgumentsCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmServer.cxx b/Source/cmServer.cxx
index 51a363f..5a71dc0 100644
--- a/Source/cmServer.cxx
+++ b/Source/cmServer.cxx
@@ -14,6 +14,7 @@
 #include "cm_jsoncpp_value.h"
 #endif
 
+#include <algorithm>
 #include <fstream>
 #include <iostream>
 #include <memory>
diff --git a/Source/cmServerConnection.cxx b/Source/cmServerConnection.cxx
index b4af52b..008052b 100644
--- a/Source/cmServerConnection.cxx
+++ b/Source/cmServerConnection.cxx
@@ -8,6 +8,7 @@
 #include "cmServer.h"
 
 #include <assert.h>
+#include <string.h>
 
 namespace {
 
diff --git a/Source/cmServerProtocol.cxx b/Source/cmServerProtocol.cxx
index 895337f..a5c1a23 100644
--- a/Source/cmServerProtocol.cxx
+++ b/Source/cmServerProtocol.cxx
@@ -2,11 +2,11 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmServerProtocol.h"
 
-#include "cmCacheManager.h"
 #include "cmExternalMakefileProjectGenerator.h"
 #include "cmFileMonitor.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
+#include "cmLinkLineComputer.h"
 #include "cmListFileCache.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
@@ -32,7 +32,7 @@
 
 namespace {
 
-static std::vector<std::string> getConfigurations(const cmake* cm)
+std::vector<std::string> getConfigurations(const cmake* cm)
 {
   std::vector<std::string> configurations;
   auto makefiles = cm->GetGlobalGenerator()->GetMakefiles();
@@ -41,12 +41,13 @@ static std::vector<std::string> getConfigurations(const cmake* cm)
   }
 
   makefiles[0]->GetConfigurations(configurations);
-  if (configurations.empty())
+  if (configurations.empty()) {
     configurations.push_back("");
+  }
   return configurations;
 }
 
-static bool hasString(const Json::Value& v, const std::string& s)
+bool hasString(const Json::Value& v, const std::string& s)
 {
   return !v.isNull() &&
     std::find_if(v.begin(), v.end(), [s](const Json::Value& i) {
@@ -55,7 +56,7 @@ static bool hasString(const Json::Value& v, const std::string& s)
 }
 
 template <class T>
-static Json::Value fromStringList(const T& in)
+Json::Value fromStringList(const T& in)
 {
   Json::Value result = Json::arrayValue;
   for (const std::string& i : in) {
@@ -64,7 +65,7 @@ static Json::Value fromStringList(const T& in)
   return result;
 }
 
-static std::vector<std::string> toStringList(const Json::Value& in)
+std::vector<std::string> toStringList(const Json::Value& in)
 {
   std::vector<std::string> result;
   for (const auto& it : in) {
@@ -73,15 +74,14 @@ static std::vector<std::string> toStringList(const Json::Value& in)
   return result;
 }
 
-static void getCMakeInputs(const cmGlobalGenerator* gg,
-                           const std::string& sourceDir,
-                           const std::string& buildDir,
-                           std::vector<std::string>* internalFiles,
-                           std::vector<std::string>* explicitFiles,
-                           std::vector<std::string>* tmpFiles)
+void getCMakeInputs(const cmGlobalGenerator* gg, const std::string& sourceDir,
+                    const std::string& buildDir,
+                    std::vector<std::string>* internalFiles,
+                    std::vector<std::string>* explicitFiles,
+                    std::vector<std::string>* tmpFiles)
 {
   const std::string cmakeRootDir = cmSystemTools::GetCMakeRoot() + '/';
-  const std::vector<cmMakefile*> makefiles = gg->GetMakefiles();
+  std::vector<cmMakefile*> const& makefiles = gg->GetMakefiles();
   for (auto it = makefiles.begin(); it != makefiles.end(); ++it) {
     const std::vector<std::string> listFiles = (*it)->GetListFiles();
 
@@ -95,20 +95,24 @@ static void getCMakeInputs(const cmGlobalGenerator* gg,
       if (!sourceDir.empty()) {
         const std::string& relative =
           cmSystemTools::RelativePath(sourceDir.c_str(), jt->c_str());
-        if (toAdd.size() > relative.size())
+        if (toAdd.size() > relative.size()) {
           toAdd = relative;
+        }
       }
 
       if (isInternal) {
-        if (internalFiles)
+        if (internalFiles) {
           internalFiles->push_back(toAdd);
+        }
       } else {
         if (isTemporary) {
-          if (tmpFiles)
+          if (tmpFiles) {
             tmpFiles->push_back(toAdd);
+          }
         } else {
-          if (explicitFiles)
+          if (explicitFiles) {
             explicitFiles->push_back(toAdd);
+          }
         }
       }
     }
@@ -251,6 +255,27 @@ static void setErrorMessage(std::string* errorMessage, const std::string& text)
   }
 }
 
+static bool testHomeDirectory(cmState* state, std::string& value,
+                              std::string* errorMessage)
+{
+  const std::string cachedValue =
+    std::string(state->GetCacheEntryValue("CMAKE_HOME_DIRECTORY"));
+  const std::string suffix = "/CMakeLists.txt";
+  const std::string cachedValueCML = cachedValue + suffix;
+  const std::string valueCML = value + suffix;
+  if (!cmSystemTools::SameFile(valueCML, cachedValueCML)) {
+    setErrorMessage(errorMessage,
+                    std::string("\"CMAKE_HOME_DIRECTORY\" is set but "
+                                "incompatible with configured "
+                                "source directory value."));
+    return false;
+  }
+  if (value.empty()) {
+    value = cachedValue;
+  }
+  return true;
+}
+
 static bool testValue(cmState* state, const std::string& key,
                       std::string& value, const std::string& keyDescription,
                       std::string* errorMessage)
@@ -310,8 +335,7 @@ bool cmServerProtocol1_0::DoActivate(const cmServerRequest& request,
       }
 
       // check sourcedir:
-      if (!testValue(state, "CMAKE_HOME_DIRECTORY", sourceDirectory,
-                     "source directory", errorMessage)) {
+      if (!testHomeDirectory(state, sourceDirectory, errorMessage)) {
         return false;
       }
 
@@ -665,7 +689,13 @@ static Json::Value DumpSourceFilesList(
       cmLocalGenerator* lg = target->GetLocalGenerator();
 
       std::string compileFlags = ld.Flags;
-      lg->AppendFlags(compileFlags, file->GetProperty("COMPILE_FLAGS"));
+      if (const char* cflags = file->GetProperty("COMPILE_FLAGS")) {
+        cmGeneratorExpression ge;
+        auto cge = ge.Parse(cflags);
+        const char* processed =
+          cge->Evaluate(target->GetLocalGenerator(), config);
+        lg->AppendFlags(compileFlags, processed);
+      }
       fileData.Flags = compileFlags;
 
       fileData.IncludePathList = ld.IncludePathList;
@@ -689,8 +719,9 @@ static Json::Value DumpSourceFilesList(
   Json::Value result = Json::arrayValue;
   for (auto it = fileGroups.begin(); it != fileGroups.end(); ++it) {
     Json::Value group = DumpSourceFileGroup(it->first, it->second, baseDir);
-    if (!group.isNull())
+    if (!group.isNull()) {
       result.append(group);
+    }
   }
 
   return result;
@@ -702,7 +733,7 @@ static Json::Value DumpTarget(cmGeneratorTarget* target,
   cmLocalGenerator* lg = target->GetLocalGenerator();
   const cmState* state = lg->GetState();
 
-  const cmState::TargetType type = target->GetType();
+  const cmStateEnums::TargetType type = target->GetType();
   const std::string typeName = state->GetTargetTypeName(type);
 
   Json::Value ttl = Json::arrayValue;
@@ -724,7 +755,7 @@ static Json::Value DumpTarget(cmGeneratorTarget* target,
   result[kSOURCE_DIRECTORY_KEY] = lg->GetCurrentSourceDirectory();
   result[kBUILD_DIRECTORY_KEY] = lg->GetCurrentBinaryDirectory();
 
-  if (type == cmState::INTERFACE_LIBRARY) {
+  if (type == cmStateEnums::INTERFACE_LIBRARY) {
     return result;
   }
 
@@ -750,8 +781,10 @@ static Json::Value DumpTarget(cmGeneratorTarget* target,
     std::string linkLanguageFlags;
     std::string frameworkPath;
     std::string linkPath;
-    lg->GetTargetFlags(config, linkLibs, linkLanguageFlags, linkFlags,
-                       frameworkPath, linkPath, target, false);
+    cmLinkLineComputer linkLineComputer(lg,
+                                        lg->GetStateSnapshot().GetDirectory());
+    lg->GetTargetFlags(&linkLineComputer, config, linkLibs, linkLanguageFlags,
+                       linkFlags, frameworkPath, linkPath, target);
 
     linkLibs = cmSystemTools::TrimWhitespace(linkLibs);
     linkFlags = cmSystemTools::TrimWhitespace(linkFlags);
@@ -830,7 +863,7 @@ static Json::Value DumpTargetsList(
   return result;
 }
 
-static Json::Value DumpProjectList(const cmake* cm, const std::string config)
+static Json::Value DumpProjectList(const cmake* cm, std::string const& config)
 {
   Json::Value result = Json::arrayValue;
 
@@ -840,8 +873,8 @@ static Json::Value DumpProjectList(const cmake* cm, const std::string config)
     Json::Value pObj = Json::objectValue;
     pObj[kNAME_KEY] = projectIt.first;
 
-    assert(projectIt.second.size() >
-           0); // All Projects must have at least one local generator
+    // All Projects must have at least one local generator
+    assert(!projectIt.second.empty());
     const cmLocalGenerator* lg = projectIt.second.at(0);
 
     // Project structure information:
@@ -1044,7 +1077,7 @@ cmServerResponse cmServerProtocol1_0::ProcessGlobalSettings(
 }
 
 static void setBool(const cmServerRequest& request, const std::string& key,
-                    std::function<void(bool)> setter)
+                    std::function<void(bool)> const& setter)
 {
   if (request.Data[key].isNull()) {
     return;
diff --git a/Source/cmSetCommand.cxx b/Source/cmSetCommand.cxx
index 8ce0b18..820e7f6 100644
--- a/Source/cmSetCommand.cxx
+++ b/Source/cmSetCommand.cxx
@@ -2,6 +2,16 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSetCommand.h"
 
+#include <string.h>
+
+#include "cmAlgorithms.h"
+#include "cmMakefile.h"
+#include "cmState.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmSetCommand
 bool cmSetCommand::InitialPass(std::vector<std::string> const& args,
                                cmExecutionStatus&)
@@ -64,8 +74,9 @@ bool cmSetCommand::InitialPass(std::vector<std::string> const& args,
   bool cache = false; // optional
   bool force = false; // optional
   bool parentScope = false;
-  cmState::CacheEntryType type = cmState::STRING; // required if cache
-  const char* docstring = CM_NULLPTR;             // required if cache
+  cmStateEnums::CacheEntryType type =
+    cmStateEnums::STRING;             // required if cache
+  const char* docstring = CM_NULLPTR; // required if cache
 
   unsigned int ignoreLastArgs = 0;
   // look for PARENT_SCOPE argument
@@ -115,12 +126,12 @@ bool cmSetCommand::InitialPass(std::vector<std::string> const& args,
   cmState* state = this->Makefile->GetState();
   const char* existingValue = state->GetCacheEntryValue(variable);
   if (existingValue &&
-      (state->GetCacheEntryType(variable) != cmState::UNINITIALIZED)) {
+      (state->GetCacheEntryType(variable) != cmStateEnums::UNINITIALIZED)) {
     // if the set is trying to CACHE the value but the value
     // is already in the cache and the type is not internal
     // then leave now without setting any definitions in the cache
     // or the makefile
-    if (cache && type != cmState::INTERNAL && !force) {
+    if (cache && type != cmStateEnums::INTERNAL && !force) {
       return true;
     }
   }
diff --git a/Source/cmSetCommand.h b/Source/cmSetCommand.h
index 94f7cf0..190092a 100644
--- a/Source/cmSetCommand.h
+++ b/Source/cmSetCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmSetCommand_h
 #define cmSetCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmSetCommand
  * \brief Set a CMAKE variable
  *
@@ -34,8 +40,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "set"; }
-
-  cmTypeMacro(cmSetCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmSetDirectoryPropertiesCommand.cxx b/Source/cmSetDirectoryPropertiesCommand.cxx
index b0de021..8d3961a 100644
--- a/Source/cmSetDirectoryPropertiesCommand.cxx
+++ b/Source/cmSetDirectoryPropertiesCommand.cxx
@@ -2,7 +2,9 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSetDirectoryPropertiesCommand.h"
 
-#include "cmake.h"
+#include "cmMakefile.h"
+
+class cmExecutionStatus;
 
 // cmSetDirectoryPropertiesCommand
 bool cmSetDirectoryPropertiesCommand::InitialPass(
diff --git a/Source/cmSetDirectoryPropertiesCommand.h b/Source/cmSetDirectoryPropertiesCommand.h
index 9abefda..854ad43 100644
--- a/Source/cmSetDirectoryPropertiesCommand.h
+++ b/Source/cmSetDirectoryPropertiesCommand.h
@@ -3,8 +3,15 @@
 #ifndef cmSetDirectoryPropertiesCommand_h
 #define cmSetDirectoryPropertiesCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+class cmMakefile;
+
 class cmSetDirectoryPropertiesCommand : public cmCommand
 {
 public:
@@ -40,8 +47,6 @@ public:
                          std::vector<std::string>::const_iterator ait,
                          std::vector<std::string>::const_iterator aitend,
                          std::string& errors);
-
-  cmTypeMacro(cmSetDirectoryPropertiesCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmSetPropertyCommand.cxx b/Source/cmSetPropertyCommand.cxx
index 2a4101f..60c198a 100644
--- a/Source/cmSetPropertyCommand.cxx
+++ b/Source/cmSetPropertyCommand.cxx
@@ -2,9 +2,20 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSetPropertyCommand.h"
 
-#include "cmSetSourceFilesPropertiesCommand.h"
-#include "cmSetTargetPropertiesCommand.h"
-#include "cmSetTestsPropertiesCommand.h"
+#include <sstream>
+
+#include "cmGlobalGenerator.h"
+#include "cmInstalledFile.h"
+#include "cmMakefile.h"
+#include "cmProperty.h"
+#include "cmSourceFile.h"
+#include "cmState.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmTest.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 cmSetPropertyCommand::cmSetPropertyCommand()
 {
@@ -331,7 +342,7 @@ bool cmSetPropertyCommand::HandleCacheMode()
       return false;
     }
   } else if (this->PropertyName == "TYPE") {
-    if (!cmState::IsCacheEntryType(this->PropertyValue.c_str())) {
+    if (!cmState::IsCacheEntryType(this->PropertyValue)) {
       std::ostringstream e;
       e << "given invalid CACHE entry TYPE \"" << this->PropertyValue << "\"";
       this->SetError(e.str());
diff --git a/Source/cmSetPropertyCommand.h b/Source/cmSetPropertyCommand.h
index 01295c1..fd7c922 100644
--- a/Source/cmSetPropertyCommand.h
+++ b/Source/cmSetPropertyCommand.h
@@ -3,8 +3,19 @@
 #ifndef cmSetsPropertiesCommand_h
 #define cmSetsPropertiesCommand_h
 
+#include <cmConfigure.h>
+#include <set>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+class cmInstalledFile;
+class cmSourceFile;
+class cmTarget;
+class cmTest;
+
 class cmSetPropertyCommand : public cmCommand
 {
 public:
@@ -29,8 +40,6 @@ public:
    */
   bool IsScriptable() const CM_OVERRIDE { return true; }
 
-  cmTypeMacro(cmSetPropertyCommand, cmCommand);
-
 private:
   std::set<std::string> Names;
   std::string PropertyName;
diff --git a/Source/cmSetSourceFilesPropertiesCommand.cxx b/Source/cmSetSourceFilesPropertiesCommand.cxx
index 0021589..33e1b2e 100644
--- a/Source/cmSetSourceFilesPropertiesCommand.cxx
+++ b/Source/cmSetSourceFilesPropertiesCommand.cxx
@@ -2,7 +2,11 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSetSourceFilesPropertiesCommand.h"
 
+#include "cmMakefile.h"
 #include "cmSourceFile.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
 
 // cmSetSourceFilesPropertiesCommand
 bool cmSetSourceFilesPropertiesCommand::InitialPass(
diff --git a/Source/cmSetSourceFilesPropertiesCommand.h b/Source/cmSetSourceFilesPropertiesCommand.h
index c683ac0..8fa12c7 100644
--- a/Source/cmSetSourceFilesPropertiesCommand.h
+++ b/Source/cmSetSourceFilesPropertiesCommand.h
@@ -3,8 +3,15 @@
 #ifndef cmSetSourceFilesPropertiesCommand_h
 #define cmSetSourceFilesPropertiesCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+class cmMakefile;
+
 class cmSetSourceFilesPropertiesCommand : public cmCommand
 {
 public:
@@ -28,8 +35,6 @@ public:
     return "set_source_files_properties";
   }
 
-  cmTypeMacro(cmSetSourceFilesPropertiesCommand, cmCommand);
-
   static bool RunCommand(cmMakefile* mf,
                          std::vector<std::string>::const_iterator filebeg,
                          std::vector<std::string>::const_iterator fileend,
diff --git a/Source/cmSetTargetPropertiesCommand.cxx b/Source/cmSetTargetPropertiesCommand.cxx
index 200b42d..da26972 100644
--- a/Source/cmSetTargetPropertiesCommand.cxx
+++ b/Source/cmSetTargetPropertiesCommand.cxx
@@ -2,7 +2,12 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSetTargetPropertiesCommand.h"
 
-#include "cmGlobalGenerator.h"
+#include <iterator>
+
+#include "cmMakefile.h"
+#include "cmTarget.h"
+
+class cmExecutionStatus;
 
 // cmSetTargetPropertiesCommand
 bool cmSetTargetPropertiesCommand::InitialPass(
diff --git a/Source/cmSetTargetPropertiesCommand.h b/Source/cmSetTargetPropertiesCommand.h
index 6e2a242..c3c0d06 100644
--- a/Source/cmSetTargetPropertiesCommand.h
+++ b/Source/cmSetTargetPropertiesCommand.h
@@ -3,8 +3,15 @@
 #ifndef cmSetTargetsPropertiesCommand_h
 #define cmSetTargetsPropertiesCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+class cmMakefile;
+
 class cmSetTargetPropertiesCommand : public cmCommand
 {
 public:
@@ -28,8 +35,6 @@ public:
   static bool SetOneTarget(const std::string& tname,
                            std::vector<std::string>& propertyPairs,
                            cmMakefile* mf);
-
-  cmTypeMacro(cmSetTargetPropertiesCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmSetTestsPropertiesCommand.cxx b/Source/cmSetTestsPropertiesCommand.cxx
index 5abb84e..4fd379f 100644
--- a/Source/cmSetTestsPropertiesCommand.cxx
+++ b/Source/cmSetTestsPropertiesCommand.cxx
@@ -2,8 +2,12 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSetTestsPropertiesCommand.h"
 
+#include <iterator>
+
+#include "cmMakefile.h"
 #include "cmTest.h"
-#include "cmake.h"
+
+class cmExecutionStatus;
 
 // cmSetTestsPropertiesCommand
 bool cmSetTestsPropertiesCommand::InitialPass(
diff --git a/Source/cmSetTestsPropertiesCommand.h b/Source/cmSetTestsPropertiesCommand.h
index 3f5ce21..45aed79 100644
--- a/Source/cmSetTestsPropertiesCommand.h
+++ b/Source/cmSetTestsPropertiesCommand.h
@@ -3,8 +3,15 @@
 #ifndef cmSetTestsPropertiesCommand_h
 #define cmSetTestsPropertiesCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+class cmMakefile;
+
 class cmSetTestsPropertiesCommand : public cmCommand
 {
 public:
@@ -22,8 +29,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "set_tests_properties"; }
 
-  cmTypeMacro(cmSetTestsPropertiesCommand, cmCommand);
-
   static bool SetOneTest(const std::string& tname,
                          std::vector<std::string>& propertyPairs,
                          cmMakefile* mf, std::string& errors);
diff --git a/Source/cmSiteNameCommand.cxx b/Source/cmSiteNameCommand.cxx
index dbd3ed9..4322a6d 100644
--- a/Source/cmSiteNameCommand.cxx
+++ b/Source/cmSiteNameCommand.cxx
@@ -4,6 +4,12 @@
 
 #include <cmsys/RegularExpression.hxx>
 
+#include "cmMakefile.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmSiteNameCommand
 bool cmSiteNameCommand::InitialPass(std::vector<std::string> const& args,
                                     cmExecutionStatus&)
@@ -68,7 +74,8 @@ bool cmSiteNameCommand::InitialPass(std::vector<std::string> const& args,
 #endif
   this->Makefile->AddCacheDefinition(
     args[0], siteName.c_str(),
-    "Name of the computer/site where compile is being run", cmState::STRING);
+    "Name of the computer/site where compile is being run",
+    cmStateEnums::STRING);
 
   return true;
 }
diff --git a/Source/cmSiteNameCommand.h b/Source/cmSiteNameCommand.h
index 5578b03..01023b9 100644
--- a/Source/cmSiteNameCommand.h
+++ b/Source/cmSiteNameCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmSiteNameCommand_h
 #define cmSiteNameCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmSiteNameCommand
  * \brief site_name command
  *
@@ -34,8 +40,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "site_name"; }
-
-  cmTypeMacro(cmSiteNameCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmSourceFile.cxx b/Source/cmSourceFile.cxx
index 5d37578..5c4f18b 100644
--- a/Source/cmSourceFile.cxx
+++ b/Source/cmSourceFile.cxx
@@ -2,6 +2,8 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSourceFile.h"
 
+#include <sstream>
+
 #include "cmCustomCommand.h"
 #include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
@@ -10,8 +12,6 @@
 #include "cmSystemTools.h"
 #include "cmake.h"
 
-#include <sstream>
-
 cmSourceFile::cmSourceFile(cmMakefile* mf, const std::string& name)
   : Location(mf, name)
 {
diff --git a/Source/cmSourceFile.h b/Source/cmSourceFile.h
index b193f65..bbcc300 100644
--- a/Source/cmSourceFile.h
+++ b/Source/cmSourceFile.h
@@ -86,6 +86,7 @@ public:
 
   // Get the properties
   cmPropertyMap& GetProperties() { return this->Properties; }
+  const cmPropertyMap& GetProperties() const { return this->Properties; }
 
   /**
    * Check whether the given source file location could refer to this
diff --git a/Source/cmSourceGroupCommand.cxx b/Source/cmSourceGroupCommand.cxx
index 2b176b5..5555199 100644
--- a/Source/cmSourceGroupCommand.cxx
+++ b/Source/cmSourceGroupCommand.cxx
@@ -2,6 +2,107 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSourceGroupCommand.h"
 
+#include <sstream>
+
+#include "cmMakefile.h"
+#include "cmSourceGroup.h"
+#include "cmSystemTools.h"
+
+namespace {
+const size_t RootIndex = 1;
+const size_t FilesWithoutPrefixKeywordIndex = 2;
+const size_t FilesWithPrefixKeywordIndex = 4;
+const size_t PrefixKeywordIdex = 2;
+
+std::vector<std::string> tokenizePath(const std::string& path)
+{
+  return cmSystemTools::tokenize(path, "\\/");
+}
+
+std::string getFullFilePath(const std::string& currentPath,
+                            const std::string& path)
+{
+  std::string fullPath = path;
+
+  if (!cmSystemTools::FileIsFullPath(path.c_str())) {
+    fullPath = currentPath;
+    fullPath += "/";
+    fullPath += path;
+  }
+
+  return cmSystemTools::CollapseFullPath(fullPath);
+}
+
+std::set<std::string> getSourceGroupFilesPaths(
+  const std::string& currentPath, const std::string& root,
+  const std::vector<std::string>& files)
+{
+  std::set<std::string> ret;
+  const std::string::size_type rootLength = root.length();
+
+  for (size_t i = 0; i < files.size(); ++i) {
+    const std::string fullPath = getFullFilePath(currentPath, files[i]);
+
+    ret.insert(fullPath.substr(rootLength + 1)); // +1 to also omnit last '/'
+  }
+
+  return ret;
+}
+
+cmSourceGroup* addSourceGroup(const std::vector<std::string>& tokenizedPath,
+                              cmMakefile& makefile)
+{
+  cmSourceGroup* sg;
+
+  sg = makefile.GetSourceGroup(tokenizedPath);
+  if (!sg) {
+    makefile.AddSourceGroup(tokenizedPath);
+    sg = makefile.GetSourceGroup(tokenizedPath);
+    if (!sg) {
+      return CM_NULLPTR;
+    }
+  }
+
+  return sg;
+}
+
+bool addFilesToItsSourceGroups(const std::set<std::string>& sgFilesPaths,
+                               const std::string& prefix, cmMakefile& makefile,
+                               std::string& errorMsg)
+{
+  cmSourceGroup* sg;
+
+  for (std::set<std::string>::const_iterator it = sgFilesPaths.begin();
+       it != sgFilesPaths.end(); ++it) {
+
+    std::vector<std::string> tokenizedPath;
+    if (!prefix.empty()) {
+      tokenizedPath = tokenizePath(prefix + '/' + *it);
+    } else {
+      tokenizedPath = tokenizePath(*it);
+    }
+
+    if (tokenizedPath.size() > 1) {
+      tokenizedPath.pop_back();
+
+      sg = addSourceGroup(tokenizedPath, makefile);
+
+      if (!sg) {
+        errorMsg = "Could not create source group for file: " + *it;
+        return false;
+      }
+      const std::string fullPath =
+        getFullFilePath(makefile.GetCurrentSourceDirectory(), *it);
+      sg->AddGroupFile(fullPath);
+    }
+  }
+
+  return true;
+}
+}
+
+class cmExecutionStatus;
+
 // cmSourceGroupCommand
 bool cmSourceGroupCommand::InitialPass(std::vector<std::string> const& args,
                                        cmExecutionStatus&)
@@ -11,6 +112,17 @@ bool cmSourceGroupCommand::InitialPass(std::vector<std::string> const& args,
     return false;
   }
 
+  if (args[0] == "TREE") {
+    std::string error;
+
+    if (!processTree(args, error)) {
+      this->SetError(error);
+      return false;
+    }
+
+    return true;
+  }
+
   std::string delimiter = "\\";
   if (this->Makefile->GetDefinition("SOURCE_GROUP_DELIMITER")) {
     delimiter = this->Makefile->GetDefinition("SOURCE_GROUP_DELIMITER");
@@ -61,7 +173,7 @@ bool cmSourceGroupCommand::InitialPass(std::vector<std::string> const& args,
         src += "/";
         src += args[i];
       }
-      src = cmSystemTools::CollapseFullPath(src.c_str());
+      src = cmSystemTools::CollapseFullPath(src);
       sg->AddGroupFile(src);
     } else {
       std::ostringstream err;
@@ -74,3 +186,64 @@ bool cmSourceGroupCommand::InitialPass(std::vector<std::string> const& args,
 
   return true;
 }
+
+bool cmSourceGroupCommand::checkTreeArgumentsPreconditions(
+  const std::vector<std::string>& args, std::string& errorMsg) const
+{
+  if (args.size() == 1) {
+    errorMsg = "TREE argument given without a root.";
+    return false;
+  }
+
+  if (args.size() < 3) {
+    errorMsg = "Missing FILES arguments.";
+    return false;
+  }
+
+  if (args[FilesWithoutPrefixKeywordIndex] != "FILES" &&
+      args[PrefixKeywordIdex] != "PREFIX") {
+    errorMsg = "Unknown argument \"" + args[2] +
+      "\". Perhaps the FILES keyword is missing.\n";
+    return false;
+  }
+
+  if (args[PrefixKeywordIdex] == "PREFIX" &&
+      (args.size() < 5 || args[FilesWithPrefixKeywordIndex] != "FILES")) {
+    errorMsg = "Missing FILES arguments.";
+    return false;
+  }
+
+  return true;
+}
+
+bool cmSourceGroupCommand::processTree(const std::vector<std::string>& args,
+                                       std::string& errorMsg)
+{
+  if (!checkTreeArgumentsPreconditions(args, errorMsg)) {
+    return false;
+  }
+
+  const std::string root = cmSystemTools::CollapseFullPath(args[RootIndex]);
+  std::string prefix;
+  size_t filesBegin = FilesWithoutPrefixKeywordIndex + 1;
+  if (args[PrefixKeywordIdex] == "PREFIX") {
+    prefix = args[PrefixKeywordIdex + 1];
+    filesBegin = FilesWithPrefixKeywordIndex + 1;
+  }
+
+  const std::vector<std::string> filesVector(args.begin() + filesBegin,
+                                             args.end());
+
+  std::set<std::string> sourceGroupPaths = getSourceGroupFilesPaths(
+    this->Makefile->GetCurrentSourceDirectory(), root, filesVector);
+
+  addFilesToItsSourceGroups(sourceGroupPaths, prefix, *(this->Makefile),
+                            errorMsg);
+
+  if (!errorMsg.empty()) {
+    this->SetError(errorMsg);
+    return false;
+  }
+
+  return true;
+}
diff --git a/Source/cmSourceGroupCommand.h b/Source/cmSourceGroupCommand.h
index e3639df..5549096 100644
--- a/Source/cmSourceGroupCommand.h
+++ b/Source/cmSourceGroupCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmSourceGroupCommand_h
 #define cmSourceGroupCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmSourceGroupCommand
  * \brief Adds a cmSourceGroup to the cmMakefile.
  *
@@ -31,7 +37,11 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "source_group"; }
 
-  cmTypeMacro(cmSourceGroupCommand, cmCommand);
+private:
+  bool processTree(const std::vector<std::string>& args,
+                   std::string& errorMsg);
+  bool checkTreeArgumentsPreconditions(const std::vector<std::string>& args,
+                                       std::string& errorMsg) const;
 };
 
 #endif
diff --git a/Source/cmStandardIncludes.h b/Source/cmStandardIncludes.h
index 0aab6d9..a2047af 100644
--- a/Source/cmStandardIncludes.h
+++ b/Source/cmStandardIncludes.h
@@ -49,6 +49,5 @@ extern void operator<<(std::ostream&, const std::ostringstream&);
 #include "cmCustomCommandLines.h"
 #include "cmDocumentationEntry.h"
 #include "cmTargetLinkLibraryType.h"
-#include "cmTypeMacro.h"
 
 #endif
diff --git a/Source/cmStandardLexer.h b/Source/cmStandardLexer.h
index 234aef5..b9adee5 100644
--- a/Source/cmStandardLexer.h
+++ b/Source/cmStandardLexer.h
@@ -3,8 +3,11 @@
 #ifndef cmStandardLexer_h
 #define cmStandardLexer_h
 
+#include <cmConfigure.h> // IWYU pragma: keep
+
 /* Disable some warnings.  */
 #if defined(_MSC_VER)
+#pragma warning(disable : 4018)
 #pragma warning(disable : 4127)
 #pragma warning(disable : 4131)
 #pragma warning(disable : 4244)
@@ -16,13 +19,24 @@
 #pragma warning(disable : 4786)
 #endif
 
-/* Define isatty on windows.  */
+#if defined(__GNUC__) && !defined(__INTEL_COMPILER)
+#if ((__GNUC__ * 100) + __GNUC_MINOR__) >= 402
+#pragma GCC diagnostic ignored "-Wconversion"
+#pragma GCC diagnostic ignored "-Wsign-compare"
+#endif
+#if ((__GNUC__ * 100) + __GNUC_MINOR__) >= 403
+#pragma GCC diagnostic ignored "-Wsign-conversion"
+#endif
+#endif
+
+/* Make sure isatty is available. */
 #if defined(_WIN32) && !defined(__CYGWIN__)
 #include <io.h>
 #if defined(_MSC_VER)
 #define isatty _isatty
 #endif
-#define YY_NO_UNISTD_H 1
+#else
+#include <unistd.h> // IWYU pragma: export
 #endif
 
 /* Make sure malloc and free are available on QNX.  */
@@ -36,4 +50,12 @@
 #define YY_NO_UNPUT 1
 #define ECHO
 
+#include <cm_kwiml.h>
+typedef KWIML_INT_int8_t flex_int8_t;
+typedef KWIML_INT_uint8_t flex_uint8_t;
+typedef KWIML_INT_int16_t flex_int16_t;
+typedef KWIML_INT_uint16_t flex_uint16_t;
+typedef KWIML_INT_int32_t flex_int32_t;
+typedef KWIML_INT_uint32_t flex_uint32_t;
+
 #endif
diff --git a/Source/cmState.cxx b/Source/cmState.cxx
index 0e73879..18d5ea1 100644
--- a/Source/cmState.cxx
+++ b/Source/cmState.cxx
@@ -2,103 +2,22 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmState.h"
 
+#include <algorithm>
+#include <assert.h>
+#include <cmsys/RegularExpression.hxx>
+#include <string.h>
+#include <utility>
+
 #include "cmAlgorithms.h"
 #include "cmCacheManager.h"
 #include "cmCommand.h"
 #include "cmDefinitions.h"
 #include "cmListFileCache.h"
+#include "cmStatePrivate.h"
+#include "cmStateSnapshot.h"
 #include "cmSystemTools.h"
-#include "cmTypeMacro.h"
-#include "cmVersion.h"
 #include "cmake.h"
 
-#include <algorithm>
-#include <assert.h>
-#include <cmsys/RegularExpression.hxx>
-#include <iterator>
-#include <stdio.h>
-#include <string.h>
-#include <utility>
-
-static std::string const kBINARY_DIR = "BINARY_DIR";
-static std::string const kBUILDSYSTEM_TARGETS = "BUILDSYSTEM_TARGETS";
-static std::string const kSOURCE_DIR = "SOURCE_DIR";
-static std::string const kSUBDIRECTORIES = "SUBDIRECTORIES";
-
-struct cmState::SnapshotDataType
-{
-  cmState::PositionType ScopeParent;
-  cmState::PositionType DirectoryParent;
-  cmLinkedTree<cmState::PolicyStackEntry>::iterator Policies;
-  cmLinkedTree<cmState::PolicyStackEntry>::iterator PolicyRoot;
-  cmLinkedTree<cmState::PolicyStackEntry>::iterator PolicyScope;
-  cmState::SnapshotType SnapshotType;
-  bool Keep;
-  cmLinkedTree<std::string>::iterator ExecutionListFile;
-  cmLinkedTree<cmState::BuildsystemDirectoryStateType>::iterator
-    BuildSystemDirectory;
-  cmLinkedTree<cmDefinitions>::iterator Vars;
-  cmLinkedTree<cmDefinitions>::iterator Root;
-  cmLinkedTree<cmDefinitions>::iterator Parent;
-  std::vector<std::string>::size_type IncludeDirectoryPosition;
-  std::vector<std::string>::size_type CompileDefinitionsPosition;
-  std::vector<std::string>::size_type CompileOptionsPosition;
-};
-
-struct cmState::PolicyStackEntry : public cmPolicies::PolicyMap
-{
-  typedef cmPolicies::PolicyMap derived;
-  PolicyStackEntry(bool w = false)
-    : derived()
-    , Weak(w)
-  {
-  }
-  PolicyStackEntry(derived const& d, bool w)
-    : derived(d)
-    , Weak(w)
-  {
-  }
-  PolicyStackEntry(PolicyStackEntry const& r)
-    : derived(r)
-    , Weak(r.Weak)
-  {
-  }
-  bool Weak;
-};
-
-struct cmState::BuildsystemDirectoryStateType
-{
-  cmState::PositionType DirectoryEnd;
-
-  std::string Location;
-  std::string OutputLocation;
-
-  // The top-most directories for relative path conversion.  Both the
-  // source and destination location of a relative path conversion
-  // must be underneath one of these directories (both under source or
-  // both under binary) in order for the relative path to be evaluated
-  // safely by the build tools.
-  std::string RelativePathTopSource;
-  std::string RelativePathTopBinary;
-
-  std::vector<std::string> IncludeDirectories;
-  std::vector<cmListFileBacktrace> IncludeDirectoryBacktraces;
-
-  std::vector<std::string> CompileDefinitions;
-  std::vector<cmListFileBacktrace> CompileDefinitionsBacktraces;
-
-  std::vector<std::string> CompileOptions;
-  std::vector<cmListFileBacktrace> CompileOptionsBacktraces;
-
-  std::vector<std::string> NormalTargetNames;
-
-  std::string ProjectName;
-
-  cmPropertyMap Properties;
-
-  std::vector<cmState::Snapshot> Children;
-};
-
 cmState::cmState()
   : IsInTryCompile(false)
   , WindowsShell(false)
@@ -117,29 +36,29 @@ cmState::~cmState()
   cmDeleteAll(this->Commands);
 }
 
-const char* cmState::GetTargetTypeName(cmState::TargetType targetType)
+const char* cmState::GetTargetTypeName(cmStateEnums::TargetType targetType)
 {
   switch (targetType) {
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
       return "STATIC_LIBRARY";
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       return "MODULE_LIBRARY";
-    case cmState::SHARED_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
       return "SHARED_LIBRARY";
-    case cmState::OBJECT_LIBRARY:
+    case cmStateEnums::OBJECT_LIBRARY:
       return "OBJECT_LIBRARY";
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       return "EXECUTABLE";
-    case cmState::UTILITY:
+    case cmStateEnums::UTILITY:
       return "UTILITY";
-    case cmState::GLOBAL_TARGET:
+    case cmStateEnums::GLOBAL_TARGET:
       return "GLOBAL_TARGET";
-    case cmState::INTERFACE_LIBRARY:
+    case cmStateEnums::INTERFACE_LIBRARY:
       return "INTERFACE_LIBRARY";
-    case cmState::UNKNOWN_LIBRARY:
+    case cmStateEnums::UNKNOWN_LIBRARY:
       return "UNKNOWN_LIBRARY";
   }
-  assert(0 && "Unexpected target type");
+  assert(false && "Unexpected target type");
   return CM_NULLPTR;
 }
 
@@ -147,7 +66,7 @@ const char* cmCacheEntryTypes[] = { "BOOL",          "PATH",     "FILEPATH",
                                     "STRING",        "INTERNAL", "STATIC",
                                     "UNINITIALIZED", CM_NULLPTR };
 
-const char* cmState::CacheEntryTypeToString(cmState::CacheEntryType type)
+const char* cmState::CacheEntryTypeToString(cmStateEnums::CacheEntryType type)
 {
   if (type > 6) {
     return cmCacheEntryTypes[6];
@@ -155,16 +74,16 @@ const char* cmState::CacheEntryTypeToString(cmState::CacheEntryType type)
   return cmCacheEntryTypes[type];
 }
 
-cmState::CacheEntryType cmState::StringToCacheEntryType(const char* s)
+cmStateEnums::CacheEntryType cmState::StringToCacheEntryType(const char* s)
 {
   int i = 0;
   while (cmCacheEntryTypes[i]) {
     if (strcmp(s, cmCacheEntryTypes[i]) == 0) {
-      return static_cast<cmState::CacheEntryType>(i);
+      return static_cast<cmStateEnums::CacheEntryType>(i);
     }
     ++i;
   }
-  return STRING;
+  return cmStateEnums::STRING;
 }
 
 bool cmState::IsCacheEntryType(std::string const& key)
@@ -219,7 +138,7 @@ const char* cmState::GetInitializedCacheValue(std::string const& key) const
   return this->CacheManager->GetInitializedCacheValue(key);
 }
 
-cmState::CacheEntryType cmState::GetCacheEntryType(
+cmStateEnums::CacheEntryType cmState::GetCacheEntryType(
   std::string const& key) const
 {
   cmCacheManager::CacheIterator it =
@@ -279,7 +198,7 @@ bool cmState::GetCacheEntryPropertyAsBool(std::string const& key,
 
 void cmState::AddCacheEntry(const std::string& key, const char* value,
                             const char* helpString,
-                            cmState::CacheEntryType type)
+                            cmStateEnums::CacheEntryType type)
 {
   this->CacheManager->AddCacheEntry(key, value, helpString, type);
 }
@@ -304,16 +223,16 @@ void cmState::RemoveCacheEntryProperty(std::string const& key,
     .SetProperty(propertyName, (void*)CM_NULLPTR);
 }
 
-cmState::Snapshot cmState::Reset()
+cmStateSnapshot cmState::Reset()
 {
   this->GlobalProperties.clear();
   this->PropertyDefinitions.clear();
 
-  PositionType pos = this->SnapshotData.Truncate();
+  cmStateDetail::PositionType pos = this->SnapshotData.Truncate();
   this->ExecutionListFiles.Truncate();
 
   {
-    cmLinkedTree<BuildsystemDirectoryStateType>::iterator it =
+    cmLinkedTree<cmStateDetail::BuildsystemDirectoryStateType>::iterator it =
       this->BuildsystemDirectory.Truncate();
     it->IncludeDirectories.clear();
     it->IncludeDirectoryBacktraces.clear();
@@ -360,7 +279,7 @@ cmState::Snapshot cmState::Reset()
   this->DefineProperty("RULE_LAUNCH_LINK", cmProperty::TARGET, "", "", true);
   this->DefineProperty("RULE_LAUNCH_CUSTOM", cmProperty::TARGET, "", "", true);
 
-  return Snapshot(this, pos);
+  return cmStateSnapshot(this, pos);
 }
 
 void cmState::DefineProperty(const std::string& name,
@@ -524,8 +443,7 @@ void cmState::RemoveUserDefinedCommands()
   std::vector<cmCommand*> renamedCommands;
   for (std::map<std::string, cmCommand*>::iterator j = this->Commands.begin();
        j != this->Commands.end();) {
-    if (j->second->IsA("cmMacroHelperCommand") ||
-        j->second->IsA("cmFunctionHelperCommand")) {
+    if (j->second->IsUserDefined()) {
       delete j->second;
       this->Commands.erase(j++);
     } else if (j->first != j->second->GetName()) {
@@ -676,78 +594,13 @@ const char* cmState::GetBinaryDirectory() const
   return this->BinaryDirectory.c_str();
 }
 
-void cmState::Directory::ComputeRelativePathTopSource()
+cmStateSnapshot cmState::CreateBaseSnapshot()
 {
-  // Relative path conversion inside the source tree is not used to
-  // construct relative paths passed to build tools so it is safe to use
-  // even when the source is a network path.
-
-  cmState::Snapshot snapshot = this->Snapshot_;
-  std::vector<cmState::Snapshot> snapshots;
-  snapshots.push_back(snapshot);
-  while (true) {
-    snapshot = snapshot.GetBuildsystemDirectoryParent();
-    if (snapshot.IsValid()) {
-      snapshots.push_back(snapshot);
-    } else {
-      break;
-    }
-  }
-
-  std::string result = snapshots.front().GetDirectory().GetCurrentSource();
-
-  for (std::vector<cmState::Snapshot>::const_iterator it =
-         snapshots.begin() + 1;
-       it != snapshots.end(); ++it) {
-    std::string currentSource = it->GetDirectory().GetCurrentSource();
-    if (cmSystemTools::IsSubDirectory(result, currentSource)) {
-      result = currentSource;
-    }
-  }
-  this->DirectoryState->RelativePathTopSource = result;
-}
-
-void cmState::Directory::ComputeRelativePathTopBinary()
-{
-  cmState::Snapshot snapshot = this->Snapshot_;
-  std::vector<cmState::Snapshot> snapshots;
-  snapshots.push_back(snapshot);
-  while (true) {
-    snapshot = snapshot.GetBuildsystemDirectoryParent();
-    if (snapshot.IsValid()) {
-      snapshots.push_back(snapshot);
-    } else {
-      break;
-    }
-  }
-
-  std::string result = snapshots.front().GetDirectory().GetCurrentBinary();
-
-  for (std::vector<cmState::Snapshot>::const_iterator it =
-         snapshots.begin() + 1;
-       it != snapshots.end(); ++it) {
-    std::string currentBinary = it->GetDirectory().GetCurrentBinary();
-    if (cmSystemTools::IsSubDirectory(result, currentBinary)) {
-      result = currentBinary;
-    }
-  }
-
-  // The current working directory on Windows cannot be a network
-  // path.  Therefore relative paths cannot work when the binary tree
-  // is a network path.
-  if (result.size() < 2 || result.substr(0, 2) != "//") {
-    this->DirectoryState->RelativePathTopBinary = result;
-  } else {
-    this->DirectoryState->RelativePathTopBinary = "";
-  }
-}
-
-cmState::Snapshot cmState::CreateBaseSnapshot()
-{
-  PositionType pos = this->SnapshotData.Push(this->SnapshotData.Root());
+  cmStateDetail::PositionType pos =
+    this->SnapshotData.Push(this->SnapshotData.Root());
   pos->DirectoryParent = this->SnapshotData.Root();
   pos->ScopeParent = this->SnapshotData.Root();
-  pos->SnapshotType = BaseType;
+  pos->SnapshotType = cmStateEnums::BaseType;
   pos->Keep = true;
   pos->BuildSystemDirectory =
     this->BuildsystemDirectory.Push(this->BuildsystemDirectory.Root());
@@ -766,17 +619,18 @@ cmState::Snapshot cmState::CreateBaseSnapshot()
   assert(pos->Vars.IsValid());
   pos->Parent = this->VarTree.Root();
   pos->Root = this->VarTree.Root();
-  return cmState::Snapshot(this, pos);
+  return cmStateSnapshot(this, pos);
 }
 
-cmState::Snapshot cmState::CreateBuildsystemDirectorySnapshot(
-  Snapshot originSnapshot)
+cmStateSnapshot cmState::CreateBuildsystemDirectorySnapshot(
+  cmStateSnapshot originSnapshot)
 {
   assert(originSnapshot.IsValid());
-  PositionType pos = this->SnapshotData.Push(originSnapshot.Position);
+  cmStateDetail::PositionType pos =
+    this->SnapshotData.Push(originSnapshot.Position);
   pos->DirectoryParent = originSnapshot.Position;
   pos->ScopeParent = originSnapshot.Position;
-  pos->SnapshotType = BuildsystemDirectoryType;
+  pos->SnapshotType = cmStateEnums::BuildsystemDirectoryType;
   pos->Keep = true;
   pos->BuildSystemDirectory = this->BuildsystemDirectory.Push(
     originSnapshot.Position->BuildSystemDirectory);
@@ -794,7 +648,7 @@ cmState::Snapshot cmState::CreateBuildsystemDirectorySnapshot(
   pos->Root = origin;
   pos->Vars = this->VarTree.Push(origin);
 
-  cmState::Snapshot snapshot = cmState::Snapshot(this, pos);
+  cmStateSnapshot snapshot = cmStateSnapshot(this, pos);
   originSnapshot.Position->BuildSystemDirectory->Children.push_back(snapshot);
   snapshot.SetDefaultDefinitions();
   snapshot.InitializeFromParent();
@@ -802,13 +656,13 @@ cmState::Snapshot cmState::CreateBuildsystemDirectorySnapshot(
   return snapshot;
 }
 
-cmState::Snapshot cmState::CreateFunctionCallSnapshot(
-  cmState::Snapshot originSnapshot, std::string const& fileName)
+cmStateSnapshot cmState::CreateFunctionCallSnapshot(
+  cmStateSnapshot originSnapshot, std::string const& fileName)
 {
-  PositionType pos =
+  cmStateDetail::PositionType pos =
     this->SnapshotData.Push(originSnapshot.Position, *originSnapshot.Position);
   pos->ScopeParent = originSnapshot.Position;
-  pos->SnapshotType = FunctionCallType;
+  pos->SnapshotType = cmStateEnums::FunctionCallType;
   pos->Keep = false;
   pos->ExecutionListFile = this->ExecutionListFiles.Push(
     originSnapshot.Position->ExecutionListFile, fileName);
@@ -818,46 +672,46 @@ cmState::Snapshot cmState::CreateFunctionCallSnapshot(
   cmLinkedTree<cmDefinitions>::iterator origin = originSnapshot.Position->Vars;
   pos->Parent = origin;
   pos->Vars = this->VarTree.Push(origin);
-  return cmState::Snapshot(this, pos);
+  return cmStateSnapshot(this, pos);
 }
 
-cmState::Snapshot cmState::CreateMacroCallSnapshot(
-  cmState::Snapshot originSnapshot, std::string const& fileName)
+cmStateSnapshot cmState::CreateMacroCallSnapshot(
+  cmStateSnapshot originSnapshot, std::string const& fileName)
 {
-  PositionType pos =
+  cmStateDetail::PositionType pos =
     this->SnapshotData.Push(originSnapshot.Position, *originSnapshot.Position);
-  pos->SnapshotType = MacroCallType;
+  pos->SnapshotType = cmStateEnums::MacroCallType;
   pos->Keep = false;
   pos->ExecutionListFile = this->ExecutionListFiles.Push(
     originSnapshot.Position->ExecutionListFile, fileName);
   assert(originSnapshot.Position->Vars.IsValid());
   pos->BuildSystemDirectory->DirectoryEnd = pos;
   pos->PolicyScope = originSnapshot.Position->Policies;
-  return cmState::Snapshot(this, pos);
+  return cmStateSnapshot(this, pos);
 }
 
-cmState::Snapshot cmState::CreateIncludeFileSnapshot(
-  cmState::Snapshot originSnapshot, const std::string& fileName)
+cmStateSnapshot cmState::CreateIncludeFileSnapshot(
+  cmStateSnapshot originSnapshot, const std::string& fileName)
 {
-  PositionType pos =
+  cmStateDetail::PositionType pos =
     this->SnapshotData.Push(originSnapshot.Position, *originSnapshot.Position);
-  pos->SnapshotType = IncludeFileType;
+  pos->SnapshotType = cmStateEnums::IncludeFileType;
   pos->Keep = true;
   pos->ExecutionListFile = this->ExecutionListFiles.Push(
     originSnapshot.Position->ExecutionListFile, fileName);
   assert(originSnapshot.Position->Vars.IsValid());
   pos->BuildSystemDirectory->DirectoryEnd = pos;
   pos->PolicyScope = originSnapshot.Position->Policies;
-  return cmState::Snapshot(this, pos);
+  return cmStateSnapshot(this, pos);
 }
 
-cmState::Snapshot cmState::CreateVariableScopeSnapshot(
-  cmState::Snapshot originSnapshot)
+cmStateSnapshot cmState::CreateVariableScopeSnapshot(
+  cmStateSnapshot originSnapshot)
 {
-  PositionType pos =
+  cmStateDetail::PositionType pos =
     this->SnapshotData.Push(originSnapshot.Position, *originSnapshot.Position);
   pos->ScopeParent = originSnapshot.Position;
-  pos->SnapshotType = VariableScopeType;
+  pos->SnapshotType = cmStateEnums::VariableScopeType;
   pos->Keep = false;
   pos->PolicyScope = originSnapshot.Position->Policies;
   assert(originSnapshot.Position->Vars.IsValid());
@@ -866,39 +720,39 @@ cmState::Snapshot cmState::CreateVariableScopeSnapshot(
   pos->Parent = origin;
   pos->Vars = this->VarTree.Push(origin);
   assert(pos->Vars.IsValid());
-  return cmState::Snapshot(this, pos);
+  return cmStateSnapshot(this, pos);
 }
 
-cmState::Snapshot cmState::CreateInlineListFileSnapshot(
-  cmState::Snapshot originSnapshot, const std::string& fileName)
+cmStateSnapshot cmState::CreateInlineListFileSnapshot(
+  cmStateSnapshot originSnapshot, const std::string& fileName)
 {
-  PositionType pos =
+  cmStateDetail::PositionType pos =
     this->SnapshotData.Push(originSnapshot.Position, *originSnapshot.Position);
-  pos->SnapshotType = InlineListFileType;
+  pos->SnapshotType = cmStateEnums::InlineListFileType;
   pos->Keep = true;
   pos->ExecutionListFile = this->ExecutionListFiles.Push(
     originSnapshot.Position->ExecutionListFile, fileName);
   pos->BuildSystemDirectory->DirectoryEnd = pos;
   pos->PolicyScope = originSnapshot.Position->Policies;
-  return cmState::Snapshot(this, pos);
+  return cmStateSnapshot(this, pos);
 }
 
-cmState::Snapshot cmState::CreatePolicyScopeSnapshot(
-  cmState::Snapshot originSnapshot)
+cmStateSnapshot cmState::CreatePolicyScopeSnapshot(
+  cmStateSnapshot originSnapshot)
 {
-  PositionType pos =
+  cmStateDetail::PositionType pos =
     this->SnapshotData.Push(originSnapshot.Position, *originSnapshot.Position);
-  pos->SnapshotType = PolicyScopeType;
+  pos->SnapshotType = cmStateEnums::PolicyScopeType;
   pos->Keep = false;
   pos->BuildSystemDirectory->DirectoryEnd = pos;
   pos->PolicyScope = originSnapshot.Position->Policies;
-  return cmState::Snapshot(this, pos);
+  return cmStateSnapshot(this, pos);
 }
 
-cmState::Snapshot cmState::Pop(cmState::Snapshot originSnapshot)
+cmStateSnapshot cmState::Pop(cmStateSnapshot originSnapshot)
 {
-  PositionType pos = originSnapshot.Position;
-  PositionType prevPos = pos;
+  cmStateDetail::PositionType pos = originSnapshot.Position;
+  cmStateDetail::PositionType prevPos = pos;
   ++prevPos;
   prevPos->IncludeDirectoryPosition =
     prevPos->BuildSystemDirectory->IncludeDirectories.size();
@@ -920,855 +774,7 @@ cmState::Snapshot cmState::Pop(cmState::Snapshot originSnapshot)
     this->SnapshotData.Pop(pos);
   }
 
-  return Snapshot(this, prevPos);
-}
-
-cmState::Snapshot::Snapshot(cmState* state)
-  : State(state)
-  , Position()
-{
-}
-
-std::vector<cmState::Snapshot> cmState::Snapshot::GetChildren()
-{
-  return this->Position->BuildSystemDirectory->Children;
-}
-
-cmState::Snapshot::Snapshot(cmState* state, PositionType position)
-  : State(state)
-  , Position(position)
-{
-}
-
-cmState::SnapshotType cmState::Snapshot::GetType() const
-{
-  return this->Position->SnapshotType;
-}
-
-const char* cmState::Directory::GetCurrentSource() const
-{
-  return this->DirectoryState->Location.c_str();
-}
-
-void cmState::Directory::SetCurrentSource(std::string const& dir)
-{
-  std::string& loc = this->DirectoryState->Location;
-  loc = dir;
-  cmSystemTools::ConvertToUnixSlashes(loc);
-  loc = cmSystemTools::CollapseFullPath(loc);
-
-  this->ComputeRelativePathTopSource();
-
-  this->Snapshot_.SetDefinition("CMAKE_CURRENT_SOURCE_DIR", loc);
-}
-
-const char* cmState::Directory::GetCurrentBinary() const
-{
-  return this->DirectoryState->OutputLocation.c_str();
-}
-
-void cmState::Directory::SetCurrentBinary(std::string const& dir)
-{
-  std::string& loc = this->DirectoryState->OutputLocation;
-  loc = dir;
-  cmSystemTools::ConvertToUnixSlashes(loc);
-  loc = cmSystemTools::CollapseFullPath(loc);
-
-  this->ComputeRelativePathTopBinary();
-
-  this->Snapshot_.SetDefinition("CMAKE_CURRENT_BINARY_DIR", loc);
-}
-
-void cmState::Snapshot::SetListFile(const std::string& listfile)
-{
-  *this->Position->ExecutionListFile = listfile;
-}
-
-const char* cmState::Directory::GetRelativePathTopSource() const
-{
-  return this->DirectoryState->RelativePathTopSource.c_str();
-}
-
-const char* cmState::Directory::GetRelativePathTopBinary() const
-{
-  return this->DirectoryState->RelativePathTopBinary.c_str();
-}
-
-void cmState::Directory::SetRelativePathTopSource(const char* dir)
-{
-  this->DirectoryState->RelativePathTopSource = dir;
-}
-
-void cmState::Directory::SetRelativePathTopBinary(const char* dir)
-{
-  this->DirectoryState->RelativePathTopBinary = dir;
-}
-
-std::string cmState::Snapshot::GetExecutionListFile() const
-{
-  return *this->Position->ExecutionListFile;
-}
-
-bool cmState::Snapshot::IsValid() const
-{
-  return this->State && this->Position.IsValid()
-    ? this->Position != this->State->SnapshotData.Root()
-    : false;
-}
-
-cmState::Snapshot cmState::Snapshot::GetBuildsystemDirectoryParent() const
-{
-  Snapshot snapshot;
-  if (!this->State || this->Position == this->State->SnapshotData.Root()) {
-    return snapshot;
-  }
-  PositionType parentPos = this->Position->DirectoryParent;
-  if (parentPos != this->State->SnapshotData.Root()) {
-    snapshot =
-      Snapshot(this->State, parentPos->BuildSystemDirectory->DirectoryEnd);
-  }
-
-  return snapshot;
-}
-
-cmState::Snapshot cmState::Snapshot::GetCallStackParent() const
-{
-  assert(this->State);
-  assert(this->Position != this->State->SnapshotData.Root());
-
-  Snapshot snapshot;
-  PositionType parentPos = this->Position;
-  while (parentPos->SnapshotType == cmState::PolicyScopeType ||
-         parentPos->SnapshotType == cmState::VariableScopeType) {
-    ++parentPos;
-  }
-  if (parentPos->SnapshotType == cmState::BuildsystemDirectoryType ||
-      parentPos->SnapshotType == cmState::BaseType) {
-    return snapshot;
-  }
-
-  ++parentPos;
-  while (parentPos->SnapshotType == cmState::PolicyScopeType ||
-         parentPos->SnapshotType == cmState::VariableScopeType) {
-    ++parentPos;
-  }
-
-  if (parentPos == this->State->SnapshotData.Root()) {
-    return snapshot;
-  }
-
-  snapshot = Snapshot(this->State, parentPos);
-  return snapshot;
-}
-
-cmState::Snapshot cmState::Snapshot::GetCallStackBottom() const
-{
-  assert(this->State);
-  assert(this->Position != this->State->SnapshotData.Root());
-
-  PositionType pos = this->Position;
-  while (pos->SnapshotType != cmState::BaseType &&
-         pos->SnapshotType != cmState::BuildsystemDirectoryType &&
-         pos != this->State->SnapshotData.Root()) {
-    ++pos;
-  }
-  return Snapshot(this->State, pos);
-}
-
-void cmState::Snapshot::PushPolicy(cmPolicies::PolicyMap entry, bool weak)
-{
-  PositionType pos = this->Position;
-  pos->Policies = this->State->PolicyStack.Push(pos->Policies,
-                                                PolicyStackEntry(entry, weak));
-}
-
-bool cmState::Snapshot::PopPolicy()
-{
-  PositionType pos = this->Position;
-  if (pos->Policies == pos->PolicyScope) {
-    return false;
-  }
-  pos->Policies = this->State->PolicyStack.Pop(pos->Policies);
-  return true;
-}
-
-bool cmState::Snapshot::CanPopPolicyScope()
-{
-  return this->Position->Policies == this->Position->PolicyScope;
-}
-
-void cmState::Snapshot::SetPolicy(cmPolicies::PolicyID id,
-                                  cmPolicies::PolicyStatus status)
-{
-  // Update the policy stack from the top to the top-most strong entry.
-  bool previous_was_weak = true;
-  for (cmLinkedTree<PolicyStackEntry>::iterator psi = this->Position->Policies;
-       previous_was_weak && psi != this->Position->PolicyRoot; ++psi) {
-    psi->Set(id, status);
-    previous_was_weak = psi->Weak;
-  }
-}
-
-cmPolicies::PolicyStatus cmState::Snapshot::GetPolicy(
-  cmPolicies::PolicyID id) const
-{
-  cmPolicies::PolicyStatus status = cmPolicies::GetPolicyStatus(id);
-
-  if (status == cmPolicies::REQUIRED_ALWAYS ||
-      status == cmPolicies::REQUIRED_IF_USED) {
-    return status;
-  }
-
-  cmLinkedTree<BuildsystemDirectoryStateType>::iterator dir =
-    this->Position->BuildSystemDirectory;
-
-  while (true) {
-    assert(dir.IsValid());
-    cmLinkedTree<PolicyStackEntry>::iterator leaf =
-      dir->DirectoryEnd->Policies;
-    cmLinkedTree<PolicyStackEntry>::iterator root =
-      dir->DirectoryEnd->PolicyRoot;
-    for (; leaf != root; ++leaf) {
-      if (leaf->IsDefined(id)) {
-        status = leaf->Get(id);
-        return status;
-      }
-    }
-    cmState::PositionType e = dir->DirectoryEnd;
-    cmState::PositionType p = e->DirectoryParent;
-    if (p == this->State->SnapshotData.Root()) {
-      break;
-    }
-    dir = p->BuildSystemDirectory;
-  }
-  return status;
-}
-
-bool cmState::Snapshot::HasDefinedPolicyCMP0011()
-{
-  return !this->Position->Policies->IsEmpty();
-}
-
-const char* cmState::Snapshot::GetDefinition(std::string const& name) const
-{
-  assert(this->Position->Vars.IsValid());
-  return cmDefinitions::Get(name, this->Position->Vars, this->Position->Root);
-}
-
-bool cmState::Snapshot::IsInitialized(std::string const& name) const
-{
-  return cmDefinitions::HasKey(name, this->Position->Vars,
-                               this->Position->Root);
-}
-
-void cmState::Snapshot::SetDefinition(std::string const& name,
-                                      std::string const& value)
-{
-  this->Position->Vars->Set(name, value.c_str());
-}
-
-void cmState::Snapshot::RemoveDefinition(std::string const& name)
-{
-  this->Position->Vars->Set(name, CM_NULLPTR);
-}
-
-std::vector<std::string> cmState::Snapshot::UnusedKeys() const
-{
-  return this->Position->Vars->UnusedKeys();
-}
-
-std::vector<std::string> cmState::Snapshot::ClosureKeys() const
-{
-  return cmDefinitions::ClosureKeys(this->Position->Vars,
-                                    this->Position->Root);
-}
-
-bool cmState::Snapshot::RaiseScope(std::string const& var, const char* varDef)
-{
-  if (this->Position->ScopeParent == this->Position->DirectoryParent) {
-    Snapshot parentDir = this->GetBuildsystemDirectoryParent();
-    if (!parentDir.IsValid()) {
-      return false;
-    }
-    // Update the definition in the parent directory top scope.  This
-    // directory's scope was initialized by the closure of the parent
-    // scope, so we do not need to localize the definition first.
-    if (varDef) {
-      parentDir.SetDefinition(var, varDef);
-    } else {
-      parentDir.RemoveDefinition(var);
-    }
-    return true;
-  }
-  // First localize the definition in the current scope.
-  cmDefinitions::Raise(var, this->Position->Vars, this->Position->Root);
-
-  // Now update the definition in the parent scope.
-  this->Position->Parent->Set(var, varDef);
-  return true;
-}
-
-static const std::string cmPropertySentinal = std::string();
-
-template <typename T, typename U, typename V>
-void InitializeContentFromParent(T& parentContent, T& thisContent,
-                                 U& parentBacktraces, U& thisBacktraces,
-                                 V& contentEndPosition)
-{
-  std::vector<std::string>::const_iterator parentBegin = parentContent.begin();
-  std::vector<std::string>::const_iterator parentEnd = parentContent.end();
-
-  std::vector<std::string>::const_reverse_iterator parentRbegin =
-    cmMakeReverseIterator(parentEnd);
-  std::vector<std::string>::const_reverse_iterator parentRend =
-    parentContent.rend();
-  parentRbegin = std::find(parentRbegin, parentRend, cmPropertySentinal);
-  std::vector<std::string>::const_iterator parentIt = parentRbegin.base();
-
-  thisContent = std::vector<std::string>(parentIt, parentEnd);
-
-  std::vector<cmListFileBacktrace>::const_iterator btIt =
-    parentBacktraces.begin() + std::distance(parentBegin, parentIt);
-  std::vector<cmListFileBacktrace>::const_iterator btEnd =
-    parentBacktraces.end();
-
-  thisBacktraces = std::vector<cmListFileBacktrace>(btIt, btEnd);
-
-  contentEndPosition = thisContent.size();
-}
-
-void cmState::Snapshot::SetDefaultDefinitions()
-{
-/* Up to CMake 2.4 here only WIN32, UNIX and APPLE were set.
-  With CMake must separate between target and host platform. In most cases
-  the tests for WIN32, UNIX and APPLE will be for the target system, so an
-  additional set of variables for the host system is required ->
-  CMAKE_HOST_WIN32, CMAKE_HOST_UNIX, CMAKE_HOST_APPLE.
-  WIN32, UNIX and APPLE are now set in the platform files in
-  Modules/Platforms/.
-  To keep cmake scripts (-P) and custom language and compiler modules
-  working, these variables are still also set here in this place, but they
-  will be reset in CMakeSystemSpecificInformation.cmake before the platform
-  files are executed. */
-#if defined(_WIN32)
-  this->SetDefinition("WIN32", "1");
-  this->SetDefinition("CMAKE_HOST_WIN32", "1");
-#else
-  this->SetDefinition("UNIX", "1");
-  this->SetDefinition("CMAKE_HOST_UNIX", "1");
-#endif
-#if defined(__CYGWIN__)
-  std::string legacy;
-  if (cmSystemTools::GetEnv("CMAKE_LEGACY_CYGWIN_WIN32", legacy) &&
-      cmSystemTools::IsOn(legacy.c_str())) {
-    this->SetDefinition("WIN32", "1");
-    this->SetDefinition("CMAKE_HOST_WIN32", "1");
-  }
-#endif
-#if defined(__APPLE__)
-  this->SetDefinition("APPLE", "1");
-  this->SetDefinition("CMAKE_HOST_APPLE", "1");
-#endif
-#if defined(__sun__)
-  this->SetDefinition("CMAKE_HOST_SOLARIS", "1");
-#endif
-
-  char temp[1024];
-  sprintf(temp, "%d", cmVersion::GetMinorVersion());
-  this->SetDefinition("CMAKE_MINOR_VERSION", temp);
-  sprintf(temp, "%d", cmVersion::GetMajorVersion());
-  this->SetDefinition("CMAKE_MAJOR_VERSION", temp);
-  sprintf(temp, "%d", cmVersion::GetPatchVersion());
-  this->SetDefinition("CMAKE_PATCH_VERSION", temp);
-  sprintf(temp, "%d", cmVersion::GetTweakVersion());
-  this->SetDefinition("CMAKE_TWEAK_VERSION", temp);
-  this->SetDefinition("CMAKE_VERSION", cmVersion::GetCMakeVersion());
-
-  this->SetDefinition("CMAKE_FILES_DIRECTORY",
-                      cmake::GetCMakeFilesDirectory());
-
-  // Setup the default include file regular expression (match everything).
-  this->Position->BuildSystemDirectory->Properties.SetProperty(
-    "INCLUDE_REGULAR_EXPRESSION", "^.*$");
-}
-
-void cmState::Snapshot::SetDirectoryDefinitions()
-{
-  this->SetDefinition("CMAKE_SOURCE_DIR", this->State->GetSourceDirectory());
-  this->SetDefinition("CMAKE_CURRENT_SOURCE_DIR",
-                      this->State->GetSourceDirectory());
-  this->SetDefinition("CMAKE_BINARY_DIR", this->State->GetBinaryDirectory());
-  this->SetDefinition("CMAKE_CURRENT_BINARY_DIR",
-                      this->State->GetBinaryDirectory());
-}
-
-void cmState::Snapshot::InitializeFromParent()
-{
-  PositionType parent = this->Position->DirectoryParent;
-  assert(this->Position->Vars.IsValid());
-  assert(parent->Vars.IsValid());
-
-  *this->Position->Vars =
-    cmDefinitions::MakeClosure(parent->Vars, parent->Root);
-
-  InitializeContentFromParent(
-    parent->BuildSystemDirectory->IncludeDirectories,
-    this->Position->BuildSystemDirectory->IncludeDirectories,
-    parent->BuildSystemDirectory->IncludeDirectoryBacktraces,
-    this->Position->BuildSystemDirectory->IncludeDirectoryBacktraces,
-    this->Position->IncludeDirectoryPosition);
-
-  InitializeContentFromParent(
-    parent->BuildSystemDirectory->CompileDefinitions,
-    this->Position->BuildSystemDirectory->CompileDefinitions,
-    parent->BuildSystemDirectory->CompileDefinitionsBacktraces,
-    this->Position->BuildSystemDirectory->CompileDefinitionsBacktraces,
-    this->Position->CompileDefinitionsPosition);
-
-  InitializeContentFromParent(
-    parent->BuildSystemDirectory->CompileOptions,
-    this->Position->BuildSystemDirectory->CompileOptions,
-    parent->BuildSystemDirectory->CompileOptionsBacktraces,
-    this->Position->BuildSystemDirectory->CompileOptionsBacktraces,
-    this->Position->CompileOptionsPosition);
-}
-
-cmState* cmState::Snapshot::GetState() const
-{
-  return this->State;
-}
-
-cmState::Directory cmState::Snapshot::GetDirectory() const
-{
-  return Directory(this->Position->BuildSystemDirectory, *this);
-}
-
-void cmState::Snapshot::SetProjectName(const std::string& name)
-{
-  this->Position->BuildSystemDirectory->ProjectName = name;
-}
-
-std::string cmState::Snapshot::GetProjectName() const
-{
-  return this->Position->BuildSystemDirectory->ProjectName;
-}
-
-void cmState::Snapshot::InitializeFromParent_ForSubdirsCommand()
-{
-  std::string currentSrcDir = this->GetDefinition("CMAKE_CURRENT_SOURCE_DIR");
-  std::string currentBinDir = this->GetDefinition("CMAKE_CURRENT_BINARY_DIR");
-  this->InitializeFromParent();
-  this->SetDefinition("CMAKE_SOURCE_DIR", this->State->GetSourceDirectory());
-  this->SetDefinition("CMAKE_BINARY_DIR", this->State->GetBinaryDirectory());
-
-  this->SetDefinition("CMAKE_CURRENT_SOURCE_DIR", currentSrcDir);
-  this->SetDefinition("CMAKE_CURRENT_BINARY_DIR", currentBinDir);
-}
-
-cmState::Directory::Directory(
-  cmLinkedTree<BuildsystemDirectoryStateType>::iterator iter,
-  const cmState::Snapshot& snapshot)
-  : DirectoryState(iter)
-  , Snapshot_(snapshot)
-{
-}
-
-template <typename T, typename U>
-cmStringRange GetPropertyContent(T const& content, U contentEndPosition)
-{
-  std::vector<std::string>::const_iterator end =
-    content.begin() + contentEndPosition;
-
-  std::vector<std::string>::const_reverse_iterator rbegin =
-    cmMakeReverseIterator(end);
-  rbegin = std::find(rbegin, content.rend(), cmPropertySentinal);
-
-  return cmMakeRange(rbegin.base(), end);
-}
-
-template <typename T, typename U, typename V>
-cmBacktraceRange GetPropertyBacktraces(T const& content, U const& backtraces,
-                                       V contentEndPosition)
-{
-  std::vector<std::string>::const_iterator entryEnd =
-    content.begin() + contentEndPosition;
-
-  std::vector<std::string>::const_reverse_iterator rbegin =
-    cmMakeReverseIterator(entryEnd);
-  rbegin = std::find(rbegin, content.rend(), cmPropertySentinal);
-
-  std::vector<cmListFileBacktrace>::const_iterator it =
-    backtraces.begin() + std::distance(content.begin(), rbegin.base());
-
-  std::vector<cmListFileBacktrace>::const_iterator end = backtraces.end();
-  return cmMakeRange(it, end);
-}
-
-template <typename T, typename U, typename V>
-void AppendEntry(T& content, U& backtraces, V& endContentPosition,
-                 const std::string& value, const cmListFileBacktrace& lfbt)
-{
-  if (value.empty()) {
-    return;
-  }
-
-  assert(endContentPosition == content.size());
-
-  content.push_back(value);
-  backtraces.push_back(lfbt);
-
-  endContentPosition = content.size();
-}
-
-template <typename T, typename U, typename V>
-void SetContent(T& content, U& backtraces, V& endContentPosition,
-                const std::string& vec, const cmListFileBacktrace& lfbt)
-{
-  assert(endContentPosition == content.size());
-
-  content.resize(content.size() + 2);
-  backtraces.resize(backtraces.size() + 2);
-
-  content.back() = vec;
-  backtraces.back() = lfbt;
-
-  endContentPosition = content.size();
-}
-
-template <typename T, typename U, typename V>
-void ClearContent(T& content, U& backtraces, V& endContentPosition)
-{
-  assert(endContentPosition == content.size());
-
-  content.resize(content.size() + 1);
-  backtraces.resize(backtraces.size() + 1);
-
-  endContentPosition = content.size();
-}
-
-cmStringRange cmState::Directory::GetIncludeDirectoriesEntries() const
-{
-  return GetPropertyContent(
-    this->DirectoryState->IncludeDirectories,
-    this->Snapshot_.Position->IncludeDirectoryPosition);
-}
-
-cmBacktraceRange cmState::Directory::GetIncludeDirectoriesEntryBacktraces()
-  const
-{
-  return GetPropertyBacktraces(
-    this->DirectoryState->IncludeDirectories,
-    this->DirectoryState->IncludeDirectoryBacktraces,
-    this->Snapshot_.Position->IncludeDirectoryPosition);
-}
-
-void cmState::Directory::AppendIncludeDirectoriesEntry(
-  const std::string& vec, const cmListFileBacktrace& lfbt)
-{
-  AppendEntry(this->DirectoryState->IncludeDirectories,
-              this->DirectoryState->IncludeDirectoryBacktraces,
-              this->Snapshot_.Position->IncludeDirectoryPosition, vec, lfbt);
-}
-
-void cmState::Directory::PrependIncludeDirectoriesEntry(
-  const std::string& vec, const cmListFileBacktrace& lfbt)
-{
-  std::vector<std::string>::iterator entryEnd =
-    this->DirectoryState->IncludeDirectories.begin() +
-    this->Snapshot_.Position->IncludeDirectoryPosition;
-
-  std::vector<std::string>::reverse_iterator rend =
-    this->DirectoryState->IncludeDirectories.rend();
-  std::vector<std::string>::reverse_iterator rbegin =
-    cmMakeReverseIterator(entryEnd);
-  rbegin = std::find(rbegin, rend, cmPropertySentinal);
-
-  std::vector<std::string>::iterator entryIt = rbegin.base();
-  std::vector<std::string>::iterator entryBegin =
-    this->DirectoryState->IncludeDirectories.begin();
-
-  std::vector<cmListFileBacktrace>::iterator btIt =
-    this->DirectoryState->IncludeDirectoryBacktraces.begin() +
-    std::distance(entryBegin, entryIt);
-
-  this->DirectoryState->IncludeDirectories.insert(entryIt, vec);
-  this->DirectoryState->IncludeDirectoryBacktraces.insert(btIt, lfbt);
-
-  this->Snapshot_.Position->IncludeDirectoryPosition =
-    this->DirectoryState->IncludeDirectories.size();
-}
-
-void cmState::Directory::SetIncludeDirectories(const std::string& vec,
-                                               const cmListFileBacktrace& lfbt)
-{
-  SetContent(this->DirectoryState->IncludeDirectories,
-             this->DirectoryState->IncludeDirectoryBacktraces,
-             this->Snapshot_.Position->IncludeDirectoryPosition, vec, lfbt);
-}
-
-void cmState::Directory::ClearIncludeDirectories()
-{
-  ClearContent(this->DirectoryState->IncludeDirectories,
-               this->DirectoryState->IncludeDirectoryBacktraces,
-               this->Snapshot_.Position->IncludeDirectoryPosition);
-}
-
-cmStringRange cmState::Directory::GetCompileDefinitionsEntries() const
-{
-  return GetPropertyContent(
-    this->DirectoryState->CompileDefinitions,
-    this->Snapshot_.Position->CompileDefinitionsPosition);
-}
-
-cmBacktraceRange cmState::Directory::GetCompileDefinitionsEntryBacktraces()
-  const
-{
-  return GetPropertyBacktraces(
-    this->DirectoryState->CompileDefinitions,
-    this->DirectoryState->CompileDefinitionsBacktraces,
-    this->Snapshot_.Position->CompileDefinitionsPosition);
-}
-
-void cmState::Directory::AppendCompileDefinitionsEntry(
-  const std::string& vec, const cmListFileBacktrace& lfbt)
-{
-  AppendEntry(this->DirectoryState->CompileDefinitions,
-              this->DirectoryState->CompileDefinitionsBacktraces,
-              this->Snapshot_.Position->CompileDefinitionsPosition, vec, lfbt);
-}
-
-void cmState::Directory::SetCompileDefinitions(const std::string& vec,
-                                               const cmListFileBacktrace& lfbt)
-{
-  SetContent(this->DirectoryState->CompileDefinitions,
-             this->DirectoryState->CompileDefinitionsBacktraces,
-             this->Snapshot_.Position->CompileDefinitionsPosition, vec, lfbt);
-}
-
-void cmState::Directory::ClearCompileDefinitions()
-{
-  ClearContent(this->DirectoryState->CompileDefinitions,
-               this->DirectoryState->CompileDefinitionsBacktraces,
-               this->Snapshot_.Position->CompileDefinitionsPosition);
-}
-
-cmStringRange cmState::Directory::GetCompileOptionsEntries() const
-{
-  return GetPropertyContent(this->DirectoryState->CompileOptions,
-                            this->Snapshot_.Position->CompileOptionsPosition);
-}
-
-cmBacktraceRange cmState::Directory::GetCompileOptionsEntryBacktraces() const
-{
-  return GetPropertyBacktraces(
-    this->DirectoryState->CompileOptions,
-    this->DirectoryState->CompileOptionsBacktraces,
-    this->Snapshot_.Position->CompileOptionsPosition);
-}
-
-void cmState::Directory::AppendCompileOptionsEntry(
-  const std::string& vec, const cmListFileBacktrace& lfbt)
-{
-  AppendEntry(this->DirectoryState->CompileOptions,
-              this->DirectoryState->CompileOptionsBacktraces,
-              this->Snapshot_.Position->CompileOptionsPosition, vec, lfbt);
-}
-
-void cmState::Directory::SetCompileOptions(const std::string& vec,
-                                           const cmListFileBacktrace& lfbt)
-{
-  SetContent(this->DirectoryState->CompileOptions,
-             this->DirectoryState->CompileOptionsBacktraces,
-             this->Snapshot_.Position->CompileOptionsPosition, vec, lfbt);
-}
-
-void cmState::Directory::ClearCompileOptions()
-{
-  ClearContent(this->DirectoryState->CompileOptions,
-               this->DirectoryState->CompileOptionsBacktraces,
-               this->Snapshot_.Position->CompileOptionsPosition);
-}
-
-bool cmState::Snapshot::StrictWeakOrder::operator()(
-  const cmState::Snapshot& lhs, const cmState::Snapshot& rhs) const
-{
-  return lhs.Position.StrictWeakOrdered(rhs.Position);
-}
-
-void cmState::Directory::SetProperty(const std::string& prop,
-                                     const char* value,
-                                     cmListFileBacktrace const& lfbt)
-{
-  if (prop == "INCLUDE_DIRECTORIES") {
-    if (!value) {
-      this->ClearIncludeDirectories();
-      return;
-    }
-    this->SetIncludeDirectories(value, lfbt);
-    return;
-  }
-  if (prop == "COMPILE_OPTIONS") {
-    if (!value) {
-      this->ClearCompileOptions();
-      return;
-    }
-    this->SetCompileOptions(value, lfbt);
-    return;
-  }
-  if (prop == "COMPILE_DEFINITIONS") {
-    if (!value) {
-      this->ClearCompileDefinitions();
-      return;
-    }
-    this->SetCompileDefinitions(value, lfbt);
-    return;
-  }
-
-  this->DirectoryState->Properties.SetProperty(prop, value);
-}
-
-void cmState::Directory::AppendProperty(const std::string& prop,
-                                        const char* value, bool asString,
-                                        cmListFileBacktrace const& lfbt)
-{
-  if (prop == "INCLUDE_DIRECTORIES") {
-    this->AppendIncludeDirectoriesEntry(value, lfbt);
-    return;
-  }
-  if (prop == "COMPILE_OPTIONS") {
-    this->AppendCompileOptionsEntry(value, lfbt);
-    return;
-  }
-  if (prop == "COMPILE_DEFINITIONS") {
-    this->AppendCompileDefinitionsEntry(value, lfbt);
-    return;
-  }
-
-  this->DirectoryState->Properties.AppendProperty(prop, value, asString);
-}
-
-const char* cmState::Directory::GetProperty(const std::string& prop) const
-{
-  const bool chain =
-    this->Snapshot_.State->IsPropertyChained(prop, cmProperty::DIRECTORY);
-  return this->GetProperty(prop, chain);
-}
-
-const char* cmState::Directory::GetProperty(const std::string& prop,
-                                            bool chain) const
-{
-  static std::string output;
-  output = "";
-  if (prop == "PARENT_DIRECTORY") {
-    cmState::Snapshot parent = this->Snapshot_.GetBuildsystemDirectoryParent();
-    if (parent.IsValid()) {
-      return parent.GetDirectory().GetCurrentSource();
-    }
-    return "";
-  }
-  if (prop == kBINARY_DIR) {
-    output = this->GetCurrentBinary();
-    return output.c_str();
-  }
-  if (prop == kSOURCE_DIR) {
-    output = this->GetCurrentSource();
-    return output.c_str();
-  }
-  if (prop == kSUBDIRECTORIES) {
-    std::vector<std::string> child_dirs;
-    std::vector<cmState::Snapshot> const& children =
-      this->DirectoryState->Children;
-    for (std::vector<cmState::Snapshot>::const_iterator ci = children.begin();
-         ci != children.end(); ++ci) {
-      child_dirs.push_back(ci->GetDirectory().GetCurrentSource());
-    }
-    output = cmJoin(child_dirs, ";");
-    return output.c_str();
-  }
-  if (prop == kBUILDSYSTEM_TARGETS) {
-    output = cmJoin(this->DirectoryState->NormalTargetNames, ";");
-    return output.c_str();
-  }
-
-  if (prop == "LISTFILE_STACK") {
-    std::vector<std::string> listFiles;
-    cmState::Snapshot snp = this->Snapshot_;
-    while (snp.IsValid()) {
-      listFiles.push_back(snp.GetExecutionListFile());
-      snp = snp.GetCallStackParent();
-    }
-    std::reverse(listFiles.begin(), listFiles.end());
-    output = cmJoin(listFiles, ";");
-    return output.c_str();
-  }
-  if (prop == "CACHE_VARIABLES") {
-    output = cmJoin(this->Snapshot_.State->GetCacheEntryKeys(), ";");
-    return output.c_str();
-  }
-  if (prop == "VARIABLES") {
-    std::vector<std::string> res = this->Snapshot_.ClosureKeys();
-    std::vector<std::string> cacheKeys =
-      this->Snapshot_.State->GetCacheEntryKeys();
-    res.insert(res.end(), cacheKeys.begin(), cacheKeys.end());
-    std::sort(res.begin(), res.end());
-    output = cmJoin(res, ";");
-    return output.c_str();
-  }
-  if (prop == "INCLUDE_DIRECTORIES") {
-    output = cmJoin(this->GetIncludeDirectoriesEntries(), ";");
-    return output.c_str();
-  }
-  if (prop == "COMPILE_OPTIONS") {
-    output = cmJoin(this->GetCompileOptionsEntries(), ";");
-    return output.c_str();
-  }
-  if (prop == "COMPILE_DEFINITIONS") {
-    output = cmJoin(this->GetCompileDefinitionsEntries(), ";");
-    return output.c_str();
-  }
-
-  const char* retVal = this->DirectoryState->Properties.GetPropertyValue(prop);
-  if (!retVal && chain) {
-    Snapshot parentSnapshot = this->Snapshot_.GetBuildsystemDirectoryParent();
-    if (parentSnapshot.IsValid()) {
-      return parentSnapshot.GetDirectory().GetProperty(prop, chain);
-    }
-    return this->Snapshot_.State->GetGlobalProperty(prop);
-  }
-
-  return retVal;
-}
-
-bool cmState::Directory::GetPropertyAsBool(const std::string& prop) const
-{
-  return cmSystemTools::IsOn(this->GetProperty(prop));
-}
-
-std::vector<std::string> cmState::Directory::GetPropertyKeys() const
-{
-  std::vector<std::string> keys;
-  keys.reserve(this->DirectoryState->Properties.size());
-  for (cmPropertyMap::const_iterator it =
-         this->DirectoryState->Properties.begin();
-       it != this->DirectoryState->Properties.end(); ++it) {
-    keys.push_back(it->first);
-  }
-  return keys;
-}
-
-void cmState::Directory::AddNormalTargetName(std::string const& name)
-{
-  this->DirectoryState->NormalTargetNames.push_back(name);
-}
-
-bool operator==(const cmState::Snapshot& lhs, const cmState::Snapshot& rhs)
-{
-  return lhs.Position == rhs.Position;
-}
-
-bool operator!=(const cmState::Snapshot& lhs, const cmState::Snapshot& rhs)
-{
-  return lhs.Position != rhs.Position;
+  return cmStateSnapshot(this, prevPos);
 }
 
 static bool ParseEntryWithoutType(const std::string& entry, std::string& var,
@@ -1802,7 +808,8 @@ static bool ParseEntryWithoutType(const std::string& entry, std::string& var,
 }
 
 bool cmState::ParseCacheEntry(const std::string& entry, std::string& var,
-                              std::string& value, CacheEntryType& type)
+                              std::string& value,
+                              cmStateEnums::CacheEntryType& type)
 {
   // input line is:         key:type=value
   static cmsys::RegularExpression reg(
diff --git a/Source/cmState.h b/Source/cmState.h
index feed1c7..41ffcdc 100644
--- a/Source/cmState.h
+++ b/Source/cmState.h
@@ -5,220 +5,51 @@
 
 #include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmAlgorithms.h"
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
 #include "cmDefinitions.h"
 #include "cmLinkedTree.h"
-#include "cmPolicies.h"
 #include "cmProperty.h"
 #include "cmPropertyDefinitionMap.h"
 #include "cmPropertyMap.h"
-
-#include <map>
-#include <set>
-#include <string>
-#include <vector>
+#include "cmStatePrivate.h"
+#include "cmStateTypes.h"
 
 class cmCacheManager;
 class cmCommand;
-class cmListFileBacktrace;
 class cmPropertyDefinition;
+class cmStateSnapshot;
 
 class cmState
 {
-  struct SnapshotDataType;
-  struct PolicyStackEntry;
-  struct BuildsystemDirectoryStateType;
-  typedef cmLinkedTree<SnapshotDataType>::iterator PositionType;
-  friend class Snapshot;
+  friend class cmStateSnapshot;
 
 public:
   cmState();
   ~cmState();
 
-  enum SnapshotType
-  {
-    BaseType,
-    BuildsystemDirectoryType,
-    FunctionCallType,
-    MacroCallType,
-    IncludeFileType,
-    InlineListFileType,
-    PolicyScopeType,
-    VariableScopeType
-  };
-
-  class Directory;
-
-  class Snapshot
-  {
-  public:
-    Snapshot(cmState* state = CM_NULLPTR);
-    Snapshot(cmState* state, PositionType position);
-
-    const char* GetDefinition(std::string const& name) const;
-    bool IsInitialized(std::string const& name) const;
-    void SetDefinition(std::string const& name, std::string const& value);
-    void RemoveDefinition(std::string const& name);
-    std::vector<std::string> UnusedKeys() const;
-    std::vector<std::string> ClosureKeys() const;
-    bool RaiseScope(std::string const& var, const char* varDef);
-
-    void SetListFile(std::string const& listfile);
-
-    std::string GetExecutionListFile() const;
-
-    std::vector<Snapshot> GetChildren();
-
-    bool IsValid() const;
-    Snapshot GetBuildsystemDirectoryParent() const;
-    Snapshot GetCallStackParent() const;
-    Snapshot GetCallStackBottom() const;
-    SnapshotType GetType() const;
-
-    void SetPolicy(cmPolicies::PolicyID id, cmPolicies::PolicyStatus status);
-    cmPolicies::PolicyStatus GetPolicy(cmPolicies::PolicyID id) const;
-    bool HasDefinedPolicyCMP0011();
-    void PushPolicy(cmPolicies::PolicyMap entry, bool weak);
-    bool PopPolicy();
-    bool CanPopPolicyScope();
-
-    cmState* GetState() const;
-
-    Directory GetDirectory() const;
-
-    void SetProjectName(std::string const& name);
-    std::string GetProjectName() const;
-
-    void InitializeFromParent_ForSubdirsCommand();
-
-    struct StrictWeakOrder
-    {
-      bool operator()(const cmState::Snapshot& lhs,
-                      const cmState::Snapshot& rhs) const;
-    };
-
-    void SetDirectoryDefinitions();
-    void SetDefaultDefinitions();
-
-  private:
-    friend bool operator==(const cmState::Snapshot& lhs,
-                           const cmState::Snapshot& rhs);
-    friend bool operator!=(const cmState::Snapshot& lhs,
-                           const cmState::Snapshot& rhs);
-    friend class cmState;
-    friend class Directory;
-    friend struct StrictWeakOrder;
-
-    void InitializeFromParent();
-
-    cmState* State;
-    cmState::PositionType Position;
-  };
-
-  class Directory
-  {
-    Directory(cmLinkedTree<BuildsystemDirectoryStateType>::iterator iter,
-              Snapshot const& snapshot);
-
-  public:
-    const char* GetCurrentSource() const;
-    void SetCurrentSource(std::string const& dir);
-    const char* GetCurrentBinary() const;
-    void SetCurrentBinary(std::string const& dir);
-
-    const char* GetRelativePathTopSource() const;
-    const char* GetRelativePathTopBinary() const;
-    void SetRelativePathTopSource(const char* dir);
-    void SetRelativePathTopBinary(const char* dir);
-
-    cmStringRange GetIncludeDirectoriesEntries() const;
-    cmBacktraceRange GetIncludeDirectoriesEntryBacktraces() const;
-    void AppendIncludeDirectoriesEntry(std::string const& vec,
-                                       cmListFileBacktrace const& lfbt);
-    void PrependIncludeDirectoriesEntry(std::string const& vec,
-                                        cmListFileBacktrace const& lfbt);
-    void SetIncludeDirectories(std::string const& vec,
-                               cmListFileBacktrace const& lfbt);
-    void ClearIncludeDirectories();
-
-    cmStringRange GetCompileDefinitionsEntries() const;
-    cmBacktraceRange GetCompileDefinitionsEntryBacktraces() const;
-    void AppendCompileDefinitionsEntry(std::string const& vec,
-                                       cmListFileBacktrace const& lfbt);
-    void SetCompileDefinitions(std::string const& vec,
-                               cmListFileBacktrace const& lfbt);
-    void ClearCompileDefinitions();
-
-    cmStringRange GetCompileOptionsEntries() const;
-    cmBacktraceRange GetCompileOptionsEntryBacktraces() const;
-    void AppendCompileOptionsEntry(std::string const& vec,
-                                   cmListFileBacktrace const& lfbt);
-    void SetCompileOptions(std::string const& vec,
-                           cmListFileBacktrace const& lfbt);
-    void ClearCompileOptions();
-
-    void SetProperty(const std::string& prop, const char* value,
-                     cmListFileBacktrace const& lfbt);
-    void AppendProperty(const std::string& prop, const char* value,
-                        bool asString, cmListFileBacktrace const& lfbt);
-    const char* GetProperty(const std::string& prop) const;
-    const char* GetProperty(const std::string& prop, bool chain) const;
-    bool GetPropertyAsBool(const std::string& prop) const;
-    std::vector<std::string> GetPropertyKeys() const;
-
-    void AddNormalTargetName(std::string const& name);
-
-  private:
-    void ComputeRelativePathTopSource();
-    void ComputeRelativePathTopBinary();
-
-  private:
-    cmLinkedTree<BuildsystemDirectoryStateType>::iterator DirectoryState;
-    Snapshot Snapshot_;
-    friend class Snapshot;
-  };
-
-  enum TargetType
-  {
-    EXECUTABLE,
-    STATIC_LIBRARY,
-    SHARED_LIBRARY,
-    MODULE_LIBRARY,
-    OBJECT_LIBRARY,
-    UTILITY,
-    GLOBAL_TARGET,
-    INTERFACE_LIBRARY,
-    UNKNOWN_LIBRARY
-  };
-
-  static const char* GetTargetTypeName(cmState::TargetType targetType);
-
-  Snapshot CreateBaseSnapshot();
-  Snapshot CreateBuildsystemDirectorySnapshot(Snapshot originSnapshot);
-  Snapshot CreateFunctionCallSnapshot(Snapshot originSnapshot,
-                                      std::string const& fileName);
-  Snapshot CreateMacroCallSnapshot(Snapshot originSnapshot,
-                                   std::string const& fileName);
-  Snapshot CreateIncludeFileSnapshot(Snapshot originSnapshot,
-                                     std::string const& fileName);
-  Snapshot CreateVariableScopeSnapshot(Snapshot originSnapshot);
-  Snapshot CreateInlineListFileSnapshot(Snapshot originSnapshot,
-                                        std::string const& fileName);
-  Snapshot CreatePolicyScopeSnapshot(Snapshot originSnapshot);
-  Snapshot Pop(Snapshot originSnapshot);
-
-  enum CacheEntryType
-  {
-    BOOL = 0,
-    PATH,
-    FILEPATH,
-    STRING,
-    INTERNAL,
-    STATIC,
-    UNINITIALIZED
-  };
-  static CacheEntryType StringToCacheEntryType(const char*);
-  static const char* CacheEntryTypeToString(CacheEntryType);
+  static const char* GetTargetTypeName(cmStateEnums::TargetType targetType);
+
+  cmStateSnapshot CreateBaseSnapshot();
+  cmStateSnapshot CreateBuildsystemDirectorySnapshot(
+    cmStateSnapshot originSnapshot);
+  cmStateSnapshot CreateFunctionCallSnapshot(cmStateSnapshot originSnapshot,
+                                             std::string const& fileName);
+  cmStateSnapshot CreateMacroCallSnapshot(cmStateSnapshot originSnapshot,
+                                          std::string const& fileName);
+  cmStateSnapshot CreateIncludeFileSnapshot(cmStateSnapshot originSnapshot,
+                                            std::string const& fileName);
+  cmStateSnapshot CreateVariableScopeSnapshot(cmStateSnapshot originSnapshot);
+  cmStateSnapshot CreateInlineListFileSnapshot(cmStateSnapshot originSnapshot,
+                                               std::string const& fileName);
+  cmStateSnapshot CreatePolicyScopeSnapshot(cmStateSnapshot originSnapshot);
+  cmStateSnapshot Pop(cmStateSnapshot originSnapshot);
+
+  static cmStateEnums::CacheEntryType StringToCacheEntryType(const char*);
+  static const char* CacheEntryTypeToString(cmStateEnums::CacheEntryType);
   static bool IsCacheEntryType(std::string const& key);
 
   bool LoadCache(const std::string& path, bool internal,
@@ -232,7 +63,7 @@ public:
   std::vector<std::string> GetCacheEntryKeys() const;
   const char* GetCacheEntryValue(std::string const& key) const;
   const char* GetInitializedCacheValue(std::string const& key) const;
-  CacheEntryType GetCacheEntryType(std::string const& key) const;
+  cmStateEnums::CacheEntryType GetCacheEntryType(std::string const& key) const;
   void SetCacheEntryValue(std::string const& key, std::string const& value);
   void SetCacheValue(std::string const& key, std::string const& value);
 
@@ -257,9 +88,10 @@ public:
 
   ///! Break up a line like VAR:type="value" into var, type and value
   static bool ParseCacheEntry(const std::string& entry, std::string& var,
-                              std::string& value, CacheEntryType& type);
+                              std::string& value,
+                              cmStateEnums::CacheEntryType& type);
 
-  Snapshot Reset();
+  cmStateSnapshot Reset();
   // Define a property
   void DefineProperty(const std::string& name, cmProperty::ScopeType scope,
                       const char* ShortDescription,
@@ -321,7 +153,8 @@ public:
 private:
   friend class cmake;
   void AddCacheEntry(const std::string& key, const char* value,
-                     const char* helpString, CacheEntryType type);
+                     const char* helpString,
+                     cmStateEnums::CacheEntryType type);
 
   std::map<cmProperty::ScopeType, cmPropertyDefinitionMap> PropertyDefinitions;
   std::vector<std::string> EnabledLanguages;
@@ -329,12 +162,13 @@ private:
   cmPropertyMap GlobalProperties;
   cmCacheManager* CacheManager;
 
-  cmLinkedTree<BuildsystemDirectoryStateType> BuildsystemDirectory;
+  cmLinkedTree<cmStateDetail::BuildsystemDirectoryStateType>
+    BuildsystemDirectory;
 
   cmLinkedTree<std::string> ExecutionListFiles;
 
-  cmLinkedTree<PolicyStackEntry> PolicyStack;
-  cmLinkedTree<SnapshotDataType> SnapshotData;
+  cmLinkedTree<cmStateDetail::PolicyStackEntry> PolicyStack;
+  cmLinkedTree<cmStateDetail::SnapshotDataType> SnapshotData;
   cmLinkedTree<cmDefinitions> VarTree;
 
   std::string SourceDirectory;
@@ -348,7 +182,4 @@ private:
   bool MSYSShell;
 };
 
-bool operator==(const cmState::Snapshot& lhs, const cmState::Snapshot& rhs);
-bool operator!=(const cmState::Snapshot& lhs, const cmState::Snapshot& rhs);
-
 #endif
diff --git a/Source/cmStateDirectory.cxx b/Source/cmStateDirectory.cxx
new file mode 100644
index 0000000..46a1858
--- /dev/null
+++ b/Source/cmStateDirectory.cxx
@@ -0,0 +1,528 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#include "cmStateDirectory.h"
+
+#include <algorithm>
+#include <assert.h>
+#include <iterator>
+#include <map>
+#include <utility>
+
+#include "cmProperty.h"
+#include "cmPropertyMap.h"
+#include "cmState.h"
+#include "cmStatePrivate.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+
+static std::string const kBINARY_DIR = "BINARY_DIR";
+static std::string const kBUILDSYSTEM_TARGETS = "BUILDSYSTEM_TARGETS";
+static std::string const kSOURCE_DIR = "SOURCE_DIR";
+static std::string const kSUBDIRECTORIES = "SUBDIRECTORIES";
+
+void cmStateDirectory::ComputeRelativePathTopSource()
+{
+  // Relative path conversion inside the source tree is not used to
+  // construct relative paths passed to build tools so it is safe to use
+  // even when the source is a network path.
+
+  cmStateSnapshot snapshot = this->Snapshot_;
+  std::vector<cmStateSnapshot> snapshots;
+  snapshots.push_back(snapshot);
+  while (true) {
+    snapshot = snapshot.GetBuildsystemDirectoryParent();
+    if (snapshot.IsValid()) {
+      snapshots.push_back(snapshot);
+    } else {
+      break;
+    }
+  }
+
+  std::string result = snapshots.front().GetDirectory().GetCurrentSource();
+
+  for (std::vector<cmStateSnapshot>::const_iterator it = snapshots.begin() + 1;
+       it != snapshots.end(); ++it) {
+    std::string currentSource = it->GetDirectory().GetCurrentSource();
+    if (cmSystemTools::IsSubDirectory(result, currentSource)) {
+      result = currentSource;
+    }
+  }
+  this->DirectoryState->RelativePathTopSource = result;
+}
+
+void cmStateDirectory::ComputeRelativePathTopBinary()
+{
+  cmStateSnapshot snapshot = this->Snapshot_;
+  std::vector<cmStateSnapshot> snapshots;
+  snapshots.push_back(snapshot);
+  while (true) {
+    snapshot = snapshot.GetBuildsystemDirectoryParent();
+    if (snapshot.IsValid()) {
+      snapshots.push_back(snapshot);
+    } else {
+      break;
+    }
+  }
+
+  std::string result = snapshots.front().GetDirectory().GetCurrentBinary();
+
+  for (std::vector<cmStateSnapshot>::const_iterator it = snapshots.begin() + 1;
+       it != snapshots.end(); ++it) {
+    std::string currentBinary = it->GetDirectory().GetCurrentBinary();
+    if (cmSystemTools::IsSubDirectory(result, currentBinary)) {
+      result = currentBinary;
+    }
+  }
+
+  // The current working directory on Windows cannot be a network
+  // path.  Therefore relative paths cannot work when the binary tree
+  // is a network path.
+  if (result.size() < 2 || result.substr(0, 2) != "//") {
+    this->DirectoryState->RelativePathTopBinary = result;
+  } else {
+    this->DirectoryState->RelativePathTopBinary = "";
+  }
+}
+
+const char* cmStateDirectory::GetCurrentSource() const
+{
+  return this->DirectoryState->Location.c_str();
+}
+
+void cmStateDirectory::SetCurrentSource(std::string const& dir)
+{
+  std::string& loc = this->DirectoryState->Location;
+  loc = dir;
+  cmSystemTools::ConvertToUnixSlashes(loc);
+  loc = cmSystemTools::CollapseFullPath(loc);
+
+  this->ComputeRelativePathTopSource();
+
+  this->Snapshot_.SetDefinition("CMAKE_CURRENT_SOURCE_DIR", loc);
+}
+
+const char* cmStateDirectory::GetCurrentBinary() const
+{
+  return this->DirectoryState->OutputLocation.c_str();
+}
+
+void cmStateDirectory::SetCurrentBinary(std::string const& dir)
+{
+  std::string& loc = this->DirectoryState->OutputLocation;
+  loc = dir;
+  cmSystemTools::ConvertToUnixSlashes(loc);
+  loc = cmSystemTools::CollapseFullPath(loc);
+
+  this->ComputeRelativePathTopBinary();
+
+  this->Snapshot_.SetDefinition("CMAKE_CURRENT_BINARY_DIR", loc);
+}
+
+const char* cmStateDirectory::GetRelativePathTopSource() const
+{
+  return this->DirectoryState->RelativePathTopSource.c_str();
+}
+
+const char* cmStateDirectory::GetRelativePathTopBinary() const
+{
+  return this->DirectoryState->RelativePathTopBinary.c_str();
+}
+
+void cmStateDirectory::SetRelativePathTopSource(const char* dir)
+{
+  this->DirectoryState->RelativePathTopSource = dir;
+}
+
+void cmStateDirectory::SetRelativePathTopBinary(const char* dir)
+{
+  this->DirectoryState->RelativePathTopBinary = dir;
+}
+
+cmStateDirectory::cmStateDirectory(
+  cmLinkedTree<cmStateDetail::BuildsystemDirectoryStateType>::iterator iter,
+  const cmStateSnapshot& snapshot)
+  : DirectoryState(iter)
+  , Snapshot_(snapshot)
+{
+}
+
+template <typename T, typename U>
+cmStringRange GetPropertyContent(T const& content, U contentEndPosition)
+{
+  std::vector<std::string>::const_iterator end =
+    content.begin() + contentEndPosition;
+
+  std::vector<std::string>::const_reverse_iterator rbegin =
+    cmMakeReverseIterator(end);
+  rbegin = std::find(rbegin, content.rend(), cmPropertySentinal);
+
+  return cmMakeRange(rbegin.base(), end);
+}
+
+template <typename T, typename U, typename V>
+cmBacktraceRange GetPropertyBacktraces(T const& content, U const& backtraces,
+                                       V contentEndPosition)
+{
+  std::vector<std::string>::const_iterator entryEnd =
+    content.begin() + contentEndPosition;
+
+  std::vector<std::string>::const_reverse_iterator rbegin =
+    cmMakeReverseIterator(entryEnd);
+  rbegin = std::find(rbegin, content.rend(), cmPropertySentinal);
+
+  std::vector<cmListFileBacktrace>::const_iterator it =
+    backtraces.begin() + std::distance(content.begin(), rbegin.base());
+
+  std::vector<cmListFileBacktrace>::const_iterator end = backtraces.end();
+  return cmMakeRange(it, end);
+}
+
+template <typename T, typename U, typename V>
+void AppendEntry(T& content, U& backtraces, V& endContentPosition,
+                 const std::string& value, const cmListFileBacktrace& lfbt)
+{
+  if (value.empty()) {
+    return;
+  }
+
+  assert(endContentPosition == content.size());
+
+  content.push_back(value);
+  backtraces.push_back(lfbt);
+
+  endContentPosition = content.size();
+}
+
+template <typename T, typename U, typename V>
+void SetContent(T& content, U& backtraces, V& endContentPosition,
+                const std::string& vec, const cmListFileBacktrace& lfbt)
+{
+  assert(endContentPosition == content.size());
+
+  content.resize(content.size() + 2);
+  backtraces.resize(backtraces.size() + 2);
+
+  content.back() = vec;
+  backtraces.back() = lfbt;
+
+  endContentPosition = content.size();
+}
+
+template <typename T, typename U, typename V>
+void ClearContent(T& content, U& backtraces, V& endContentPosition)
+{
+  assert(endContentPosition == content.size());
+
+  content.resize(content.size() + 1);
+  backtraces.resize(backtraces.size() + 1);
+
+  endContentPosition = content.size();
+}
+
+cmStringRange cmStateDirectory::GetIncludeDirectoriesEntries() const
+{
+  return GetPropertyContent(
+    this->DirectoryState->IncludeDirectories,
+    this->Snapshot_.Position->IncludeDirectoryPosition);
+}
+
+cmBacktraceRange cmStateDirectory::GetIncludeDirectoriesEntryBacktraces() const
+{
+  return GetPropertyBacktraces(
+    this->DirectoryState->IncludeDirectories,
+    this->DirectoryState->IncludeDirectoryBacktraces,
+    this->Snapshot_.Position->IncludeDirectoryPosition);
+}
+
+void cmStateDirectory::AppendIncludeDirectoriesEntry(
+  const std::string& vec, const cmListFileBacktrace& lfbt)
+{
+  AppendEntry(this->DirectoryState->IncludeDirectories,
+              this->DirectoryState->IncludeDirectoryBacktraces,
+              this->Snapshot_.Position->IncludeDirectoryPosition, vec, lfbt);
+}
+
+void cmStateDirectory::PrependIncludeDirectoriesEntry(
+  const std::string& vec, const cmListFileBacktrace& lfbt)
+{
+  std::vector<std::string>::iterator entryEnd =
+    this->DirectoryState->IncludeDirectories.begin() +
+    this->Snapshot_.Position->IncludeDirectoryPosition;
+
+  std::vector<std::string>::reverse_iterator rend =
+    this->DirectoryState->IncludeDirectories.rend();
+  std::vector<std::string>::reverse_iterator rbegin =
+    cmMakeReverseIterator(entryEnd);
+  rbegin = std::find(rbegin, rend, cmPropertySentinal);
+
+  std::vector<std::string>::iterator entryIt = rbegin.base();
+  std::vector<std::string>::iterator entryBegin =
+    this->DirectoryState->IncludeDirectories.begin();
+
+  std::vector<cmListFileBacktrace>::iterator btIt =
+    this->DirectoryState->IncludeDirectoryBacktraces.begin() +
+    std::distance(entryBegin, entryIt);
+
+  this->DirectoryState->IncludeDirectories.insert(entryIt, vec);
+  this->DirectoryState->IncludeDirectoryBacktraces.insert(btIt, lfbt);
+
+  this->Snapshot_.Position->IncludeDirectoryPosition =
+    this->DirectoryState->IncludeDirectories.size();
+}
+
+void cmStateDirectory::SetIncludeDirectories(const std::string& vec,
+                                             const cmListFileBacktrace& lfbt)
+{
+  SetContent(this->DirectoryState->IncludeDirectories,
+             this->DirectoryState->IncludeDirectoryBacktraces,
+             this->Snapshot_.Position->IncludeDirectoryPosition, vec, lfbt);
+}
+
+void cmStateDirectory::ClearIncludeDirectories()
+{
+  ClearContent(this->DirectoryState->IncludeDirectories,
+               this->DirectoryState->IncludeDirectoryBacktraces,
+               this->Snapshot_.Position->IncludeDirectoryPosition);
+}
+
+cmStringRange cmStateDirectory::GetCompileDefinitionsEntries() const
+{
+  return GetPropertyContent(
+    this->DirectoryState->CompileDefinitions,
+    this->Snapshot_.Position->CompileDefinitionsPosition);
+}
+
+cmBacktraceRange cmStateDirectory::GetCompileDefinitionsEntryBacktraces() const
+{
+  return GetPropertyBacktraces(
+    this->DirectoryState->CompileDefinitions,
+    this->DirectoryState->CompileDefinitionsBacktraces,
+    this->Snapshot_.Position->CompileDefinitionsPosition);
+}
+
+void cmStateDirectory::AppendCompileDefinitionsEntry(
+  const std::string& vec, const cmListFileBacktrace& lfbt)
+{
+  AppendEntry(this->DirectoryState->CompileDefinitions,
+              this->DirectoryState->CompileDefinitionsBacktraces,
+              this->Snapshot_.Position->CompileDefinitionsPosition, vec, lfbt);
+}
+
+void cmStateDirectory::SetCompileDefinitions(const std::string& vec,
+                                             const cmListFileBacktrace& lfbt)
+{
+  SetContent(this->DirectoryState->CompileDefinitions,
+             this->DirectoryState->CompileDefinitionsBacktraces,
+             this->Snapshot_.Position->CompileDefinitionsPosition, vec, lfbt);
+}
+
+void cmStateDirectory::ClearCompileDefinitions()
+{
+  ClearContent(this->DirectoryState->CompileDefinitions,
+               this->DirectoryState->CompileDefinitionsBacktraces,
+               this->Snapshot_.Position->CompileDefinitionsPosition);
+}
+
+cmStringRange cmStateDirectory::GetCompileOptionsEntries() const
+{
+  return GetPropertyContent(this->DirectoryState->CompileOptions,
+                            this->Snapshot_.Position->CompileOptionsPosition);
+}
+
+cmBacktraceRange cmStateDirectory::GetCompileOptionsEntryBacktraces() const
+{
+  return GetPropertyBacktraces(
+    this->DirectoryState->CompileOptions,
+    this->DirectoryState->CompileOptionsBacktraces,
+    this->Snapshot_.Position->CompileOptionsPosition);
+}
+
+void cmStateDirectory::AppendCompileOptionsEntry(
+  const std::string& vec, const cmListFileBacktrace& lfbt)
+{
+  AppendEntry(this->DirectoryState->CompileOptions,
+              this->DirectoryState->CompileOptionsBacktraces,
+              this->Snapshot_.Position->CompileOptionsPosition, vec, lfbt);
+}
+
+void cmStateDirectory::SetCompileOptions(const std::string& vec,
+                                         const cmListFileBacktrace& lfbt)
+{
+  SetContent(this->DirectoryState->CompileOptions,
+             this->DirectoryState->CompileOptionsBacktraces,
+             this->Snapshot_.Position->CompileOptionsPosition, vec, lfbt);
+}
+
+void cmStateDirectory::ClearCompileOptions()
+{
+  ClearContent(this->DirectoryState->CompileOptions,
+               this->DirectoryState->CompileOptionsBacktraces,
+               this->Snapshot_.Position->CompileOptionsPosition);
+}
+
+void cmStateDirectory::SetProperty(const std::string& prop, const char* value,
+                                   cmListFileBacktrace const& lfbt)
+{
+  if (prop == "INCLUDE_DIRECTORIES") {
+    if (!value) {
+      this->ClearIncludeDirectories();
+      return;
+    }
+    this->SetIncludeDirectories(value, lfbt);
+    return;
+  }
+  if (prop == "COMPILE_OPTIONS") {
+    if (!value) {
+      this->ClearCompileOptions();
+      return;
+    }
+    this->SetCompileOptions(value, lfbt);
+    return;
+  }
+  if (prop == "COMPILE_DEFINITIONS") {
+    if (!value) {
+      this->ClearCompileDefinitions();
+      return;
+    }
+    this->SetCompileDefinitions(value, lfbt);
+    return;
+  }
+
+  this->DirectoryState->Properties.SetProperty(prop, value);
+}
+
+void cmStateDirectory::AppendProperty(const std::string& prop,
+                                      const char* value, bool asString,
+                                      cmListFileBacktrace const& lfbt)
+{
+  if (prop == "INCLUDE_DIRECTORIES") {
+    this->AppendIncludeDirectoriesEntry(value, lfbt);
+    return;
+  }
+  if (prop == "COMPILE_OPTIONS") {
+    this->AppendCompileOptionsEntry(value, lfbt);
+    return;
+  }
+  if (prop == "COMPILE_DEFINITIONS") {
+    this->AppendCompileDefinitionsEntry(value, lfbt);
+    return;
+  }
+
+  this->DirectoryState->Properties.AppendProperty(prop, value, asString);
+}
+
+const char* cmStateDirectory::GetProperty(const std::string& prop) const
+{
+  const bool chain =
+    this->Snapshot_.State->IsPropertyChained(prop, cmProperty::DIRECTORY);
+  return this->GetProperty(prop, chain);
+}
+
+const char* cmStateDirectory::GetProperty(const std::string& prop,
+                                          bool chain) const
+{
+  static std::string output;
+  output = "";
+  if (prop == "PARENT_DIRECTORY") {
+    cmStateSnapshot parent = this->Snapshot_.GetBuildsystemDirectoryParent();
+    if (parent.IsValid()) {
+      return parent.GetDirectory().GetCurrentSource();
+    }
+    return "";
+  }
+  if (prop == kBINARY_DIR) {
+    output = this->GetCurrentBinary();
+    return output.c_str();
+  }
+  if (prop == kSOURCE_DIR) {
+    output = this->GetCurrentSource();
+    return output.c_str();
+  }
+  if (prop == kSUBDIRECTORIES) {
+    std::vector<std::string> child_dirs;
+    std::vector<cmStateSnapshot> const& children =
+      this->DirectoryState->Children;
+    for (std::vector<cmStateSnapshot>::const_iterator ci = children.begin();
+         ci != children.end(); ++ci) {
+      child_dirs.push_back(ci->GetDirectory().GetCurrentSource());
+    }
+    output = cmJoin(child_dirs, ";");
+    return output.c_str();
+  }
+  if (prop == kBUILDSYSTEM_TARGETS) {
+    output = cmJoin(this->DirectoryState->NormalTargetNames, ";");
+    return output.c_str();
+  }
+
+  if (prop == "LISTFILE_STACK") {
+    std::vector<std::string> listFiles;
+    cmStateSnapshot snp = this->Snapshot_;
+    while (snp.IsValid()) {
+      listFiles.push_back(snp.GetExecutionListFile());
+      snp = snp.GetCallStackParent();
+    }
+    std::reverse(listFiles.begin(), listFiles.end());
+    output = cmJoin(listFiles, ";");
+    return output.c_str();
+  }
+  if (prop == "CACHE_VARIABLES") {
+    output = cmJoin(this->Snapshot_.State->GetCacheEntryKeys(), ";");
+    return output.c_str();
+  }
+  if (prop == "VARIABLES") {
+    std::vector<std::string> res = this->Snapshot_.ClosureKeys();
+    std::vector<std::string> cacheKeys =
+      this->Snapshot_.State->GetCacheEntryKeys();
+    res.insert(res.end(), cacheKeys.begin(), cacheKeys.end());
+    std::sort(res.begin(), res.end());
+    output = cmJoin(res, ";");
+    return output.c_str();
+  }
+  if (prop == "INCLUDE_DIRECTORIES") {
+    output = cmJoin(this->GetIncludeDirectoriesEntries(), ";");
+    return output.c_str();
+  }
+  if (prop == "COMPILE_OPTIONS") {
+    output = cmJoin(this->GetCompileOptionsEntries(), ";");
+    return output.c_str();
+  }
+  if (prop == "COMPILE_DEFINITIONS") {
+    output = cmJoin(this->GetCompileDefinitionsEntries(), ";");
+    return output.c_str();
+  }
+
+  const char* retVal = this->DirectoryState->Properties.GetPropertyValue(prop);
+  if (!retVal && chain) {
+    cmStateSnapshot parentSnapshot =
+      this->Snapshot_.GetBuildsystemDirectoryParent();
+    if (parentSnapshot.IsValid()) {
+      return parentSnapshot.GetDirectory().GetProperty(prop, chain);
+    }
+    return this->Snapshot_.State->GetGlobalProperty(prop);
+  }
+
+  return retVal;
+}
+
+bool cmStateDirectory::GetPropertyAsBool(const std::string& prop) const
+{
+  return cmSystemTools::IsOn(this->GetProperty(prop));
+}
+
+std::vector<std::string> cmStateDirectory::GetPropertyKeys() const
+{
+  std::vector<std::string> keys;
+  keys.reserve(this->DirectoryState->Properties.size());
+  for (cmPropertyMap::const_iterator it =
+         this->DirectoryState->Properties.begin();
+       it != this->DirectoryState->Properties.end(); ++it) {
+    keys.push_back(it->first);
+  }
+  return keys;
+}
+
+void cmStateDirectory::AddNormalTargetName(std::string const& name)
+{
+  this->DirectoryState->NormalTargetNames.push_back(name);
+}
diff --git a/Source/cmStateDirectory.h b/Source/cmStateDirectory.h
new file mode 100644
index 0000000..8accc8e
--- /dev/null
+++ b/Source/cmStateDirectory.h
@@ -0,0 +1,83 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#ifndef cmStateDirectory_h
+#define cmStateDirectory_h
+
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
+#include "cmAlgorithms.h"
+#include "cmLinkedTree.h"
+#include "cmListFileCache.h"
+#include "cmStatePrivate.h"
+#include "cmStateSnapshot.h"
+
+class cmStateDirectory
+{
+  cmStateDirectory(
+    cmLinkedTree<cmStateDetail::BuildsystemDirectoryStateType>::iterator iter,
+    cmStateSnapshot const& snapshot);
+
+public:
+  const char* GetCurrentSource() const;
+  void SetCurrentSource(std::string const& dir);
+  const char* GetCurrentBinary() const;
+  void SetCurrentBinary(std::string const& dir);
+
+  const char* GetRelativePathTopSource() const;
+  const char* GetRelativePathTopBinary() const;
+  void SetRelativePathTopSource(const char* dir);
+  void SetRelativePathTopBinary(const char* dir);
+
+  cmStringRange GetIncludeDirectoriesEntries() const;
+  cmBacktraceRange GetIncludeDirectoriesEntryBacktraces() const;
+  void AppendIncludeDirectoriesEntry(std::string const& vec,
+                                     cmListFileBacktrace const& lfbt);
+  void PrependIncludeDirectoriesEntry(std::string const& vec,
+                                      cmListFileBacktrace const& lfbt);
+  void SetIncludeDirectories(std::string const& vec,
+                             cmListFileBacktrace const& lfbt);
+  void ClearIncludeDirectories();
+
+  cmStringRange GetCompileDefinitionsEntries() const;
+  cmBacktraceRange GetCompileDefinitionsEntryBacktraces() const;
+  void AppendCompileDefinitionsEntry(std::string const& vec,
+                                     cmListFileBacktrace const& lfbt);
+  void SetCompileDefinitions(std::string const& vec,
+                             cmListFileBacktrace const& lfbt);
+  void ClearCompileDefinitions();
+
+  cmStringRange GetCompileOptionsEntries() const;
+  cmBacktraceRange GetCompileOptionsEntryBacktraces() const;
+  void AppendCompileOptionsEntry(std::string const& vec,
+                                 cmListFileBacktrace const& lfbt);
+  void SetCompileOptions(std::string const& vec,
+                         cmListFileBacktrace const& lfbt);
+  void ClearCompileOptions();
+
+  void SetProperty(const std::string& prop, const char* value,
+                   cmListFileBacktrace const& lfbt);
+  void AppendProperty(const std::string& prop, const char* value,
+                      bool asString, cmListFileBacktrace const& lfbt);
+  const char* GetProperty(const std::string& prop) const;
+  const char* GetProperty(const std::string& prop, bool chain) const;
+  bool GetPropertyAsBool(const std::string& prop) const;
+  std::vector<std::string> GetPropertyKeys() const;
+
+  void AddNormalTargetName(std::string const& name);
+
+private:
+  void ComputeRelativePathTopSource();
+  void ComputeRelativePathTopBinary();
+
+private:
+  cmLinkedTree<cmStateDetail::BuildsystemDirectoryStateType>::iterator
+    DirectoryState;
+  cmStateSnapshot Snapshot_;
+  friend class cmStateSnapshot;
+};
+
+#endif
diff --git a/Source/cmStatePrivate.h b/Source/cmStatePrivate.h
new file mode 100644
index 0000000..20700f2
--- /dev/null
+++ b/Source/cmStatePrivate.h
@@ -0,0 +1,101 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#ifndef cmStatePrivate_h
+#define cmStatePrivate_h
+
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
+#include "cmDefinitions.h"
+#include "cmLinkedTree.h"
+#include "cmListFileCache.h"
+#include "cmPolicies.h"
+#include "cmPropertyMap.h"
+#include "cmStateSnapshot.h"
+#include "cmStateTypes.h"
+
+namespace cmStateDetail {
+struct BuildsystemDirectoryStateType;
+struct PolicyStackEntry;
+} // namespace cmStateDetail
+
+static const std::string cmPropertySentinal = std::string();
+
+struct cmStateDetail::SnapshotDataType
+{
+  cmStateDetail::PositionType ScopeParent;
+  cmStateDetail::PositionType DirectoryParent;
+  cmLinkedTree<cmStateDetail::PolicyStackEntry>::iterator Policies;
+  cmLinkedTree<cmStateDetail::PolicyStackEntry>::iterator PolicyRoot;
+  cmLinkedTree<cmStateDetail::PolicyStackEntry>::iterator PolicyScope;
+  cmStateEnums::SnapshotType SnapshotType;
+  bool Keep;
+  cmLinkedTree<std::string>::iterator ExecutionListFile;
+  cmLinkedTree<cmStateDetail::BuildsystemDirectoryStateType>::iterator
+    BuildSystemDirectory;
+  cmLinkedTree<cmDefinitions>::iterator Vars;
+  cmLinkedTree<cmDefinitions>::iterator Root;
+  cmLinkedTree<cmDefinitions>::iterator Parent;
+  std::vector<std::string>::size_type IncludeDirectoryPosition;
+  std::vector<std::string>::size_type CompileDefinitionsPosition;
+  std::vector<std::string>::size_type CompileOptionsPosition;
+};
+
+struct cmStateDetail::PolicyStackEntry : public cmPolicies::PolicyMap
+{
+  typedef cmPolicies::PolicyMap derived;
+  PolicyStackEntry(bool w = false)
+    : derived()
+    , Weak(w)
+  {
+  }
+  PolicyStackEntry(derived const& d, bool w)
+    : derived(d)
+    , Weak(w)
+  {
+  }
+  PolicyStackEntry(PolicyStackEntry const& r)
+    : derived(r)
+    , Weak(r.Weak)
+  {
+  }
+  bool Weak;
+};
+
+struct cmStateDetail::BuildsystemDirectoryStateType
+{
+  cmStateDetail::PositionType DirectoryEnd;
+
+  std::string Location;
+  std::string OutputLocation;
+
+  // The top-most directories for relative path conversion.  Both the
+  // source and destination location of a relative path conversion
+  // must be underneath one of these directories (both under source or
+  // both under binary) in order for the relative path to be evaluated
+  // safely by the build tools.
+  std::string RelativePathTopSource;
+  std::string RelativePathTopBinary;
+
+  std::vector<std::string> IncludeDirectories;
+  std::vector<cmListFileBacktrace> IncludeDirectoryBacktraces;
+
+  std::vector<std::string> CompileDefinitions;
+  std::vector<cmListFileBacktrace> CompileDefinitionsBacktraces;
+
+  std::vector<std::string> CompileOptions;
+  std::vector<cmListFileBacktrace> CompileOptionsBacktraces;
+
+  std::vector<std::string> NormalTargetNames;
+
+  std::string ProjectName;
+
+  cmPropertyMap Properties;
+
+  std::vector<cmStateSnapshot> Children;
+};
+
+#endif
diff --git a/Source/cmStateSnapshot.cxx b/Source/cmStateSnapshot.cxx
new file mode 100644
index 0000000..c6288a5
--- /dev/null
+++ b/Source/cmStateSnapshot.cxx
@@ -0,0 +1,427 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#include "cmStateSnapshot.h"
+
+#include <algorithm>
+#include <assert.h>
+#include <iterator>
+#include <stdio.h>
+
+#include "cmAlgorithms.h"
+#include "cmDefinitions.h"
+#include "cmListFileCache.h"
+#include "cmPropertyMap.h"
+#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStatePrivate.h"
+#include "cmVersion.h"
+#include "cmake.h"
+
+#if defined(__CYGWIN__)
+#include "cmSystemTools.h"
+#endif
+
+cmStateSnapshot::cmStateSnapshot(cmState* state)
+  : State(state)
+  , Position()
+{
+}
+
+std::vector<cmStateSnapshot> cmStateSnapshot::GetChildren()
+{
+  return this->Position->BuildSystemDirectory->Children;
+}
+
+cmStateSnapshot::cmStateSnapshot(cmState* state,
+                                 cmStateDetail::PositionType position)
+  : State(state)
+  , Position(position)
+{
+}
+
+cmStateEnums::SnapshotType cmStateSnapshot::GetType() const
+{
+  return this->Position->SnapshotType;
+}
+
+void cmStateSnapshot::SetListFile(const std::string& listfile)
+{
+  *this->Position->ExecutionListFile = listfile;
+}
+
+std::string cmStateSnapshot::GetExecutionListFile() const
+{
+  return *this->Position->ExecutionListFile;
+}
+
+bool cmStateSnapshot::IsValid() const
+{
+  return this->State && this->Position.IsValid()
+    ? this->Position != this->State->SnapshotData.Root()
+    : false;
+}
+
+cmStateSnapshot cmStateSnapshot::GetBuildsystemDirectoryParent() const
+{
+  cmStateSnapshot snapshot;
+  if (!this->State || this->Position == this->State->SnapshotData.Root()) {
+    return snapshot;
+  }
+  cmStateDetail::PositionType parentPos = this->Position->DirectoryParent;
+  if (parentPos != this->State->SnapshotData.Root()) {
+    snapshot = cmStateSnapshot(this->State,
+                               parentPos->BuildSystemDirectory->DirectoryEnd);
+  }
+
+  return snapshot;
+}
+
+cmStateSnapshot cmStateSnapshot::GetCallStackParent() const
+{
+  assert(this->State);
+  assert(this->Position != this->State->SnapshotData.Root());
+
+  cmStateSnapshot snapshot;
+  cmStateDetail::PositionType parentPos = this->Position;
+  while (parentPos->SnapshotType == cmStateEnums::PolicyScopeType ||
+         parentPos->SnapshotType == cmStateEnums::VariableScopeType) {
+    ++parentPos;
+  }
+  if (parentPos->SnapshotType == cmStateEnums::BuildsystemDirectoryType ||
+      parentPos->SnapshotType == cmStateEnums::BaseType) {
+    return snapshot;
+  }
+
+  ++parentPos;
+  while (parentPos->SnapshotType == cmStateEnums::PolicyScopeType ||
+         parentPos->SnapshotType == cmStateEnums::VariableScopeType) {
+    ++parentPos;
+  }
+
+  if (parentPos == this->State->SnapshotData.Root()) {
+    return snapshot;
+  }
+
+  snapshot = cmStateSnapshot(this->State, parentPos);
+  return snapshot;
+}
+
+cmStateSnapshot cmStateSnapshot::GetCallStackBottom() const
+{
+  assert(this->State);
+  assert(this->Position != this->State->SnapshotData.Root());
+
+  cmStateDetail::PositionType pos = this->Position;
+  while (pos->SnapshotType != cmStateEnums::BaseType &&
+         pos->SnapshotType != cmStateEnums::BuildsystemDirectoryType &&
+         pos != this->State->SnapshotData.Root()) {
+    ++pos;
+  }
+  return cmStateSnapshot(this->State, pos);
+}
+
+void cmStateSnapshot::PushPolicy(cmPolicies::PolicyMap entry, bool weak)
+{
+  cmStateDetail::PositionType pos = this->Position;
+  pos->Policies = this->State->PolicyStack.Push(
+    pos->Policies, cmStateDetail::PolicyStackEntry(entry, weak));
+}
+
+bool cmStateSnapshot::PopPolicy()
+{
+  cmStateDetail::PositionType pos = this->Position;
+  if (pos->Policies == pos->PolicyScope) {
+    return false;
+  }
+  pos->Policies = this->State->PolicyStack.Pop(pos->Policies);
+  return true;
+}
+
+bool cmStateSnapshot::CanPopPolicyScope()
+{
+  return this->Position->Policies == this->Position->PolicyScope;
+}
+
+void cmStateSnapshot::SetPolicy(cmPolicies::PolicyID id,
+                                cmPolicies::PolicyStatus status)
+{
+  // Update the policy stack from the top to the top-most strong entry.
+  bool previous_was_weak = true;
+  for (cmLinkedTree<cmStateDetail::PolicyStackEntry>::iterator psi =
+         this->Position->Policies;
+       previous_was_weak && psi != this->Position->PolicyRoot; ++psi) {
+    psi->Set(id, status);
+    previous_was_weak = psi->Weak;
+  }
+}
+
+cmPolicies::PolicyStatus cmStateSnapshot::GetPolicy(
+  cmPolicies::PolicyID id) const
+{
+  cmPolicies::PolicyStatus status = cmPolicies::GetPolicyStatus(id);
+
+  if (status == cmPolicies::REQUIRED_ALWAYS ||
+      status == cmPolicies::REQUIRED_IF_USED) {
+    return status;
+  }
+
+  cmLinkedTree<cmStateDetail::BuildsystemDirectoryStateType>::iterator dir =
+    this->Position->BuildSystemDirectory;
+
+  while (true) {
+    assert(dir.IsValid());
+    cmLinkedTree<cmStateDetail::PolicyStackEntry>::iterator leaf =
+      dir->DirectoryEnd->Policies;
+    cmLinkedTree<cmStateDetail::PolicyStackEntry>::iterator root =
+      dir->DirectoryEnd->PolicyRoot;
+    for (; leaf != root; ++leaf) {
+      if (leaf->IsDefined(id)) {
+        status = leaf->Get(id);
+        return status;
+      }
+    }
+    cmStateDetail::PositionType e = dir->DirectoryEnd;
+    cmStateDetail::PositionType p = e->DirectoryParent;
+    if (p == this->State->SnapshotData.Root()) {
+      break;
+    }
+    dir = p->BuildSystemDirectory;
+  }
+  return status;
+}
+
+bool cmStateSnapshot::HasDefinedPolicyCMP0011()
+{
+  return !this->Position->Policies->IsEmpty();
+}
+
+const char* cmStateSnapshot::GetDefinition(std::string const& name) const
+{
+  assert(this->Position->Vars.IsValid());
+  return cmDefinitions::Get(name, this->Position->Vars, this->Position->Root);
+}
+
+bool cmStateSnapshot::IsInitialized(std::string const& name) const
+{
+  return cmDefinitions::HasKey(name, this->Position->Vars,
+                               this->Position->Root);
+}
+
+void cmStateSnapshot::SetDefinition(std::string const& name,
+                                    std::string const& value)
+{
+  this->Position->Vars->Set(name, value.c_str());
+}
+
+void cmStateSnapshot::RemoveDefinition(std::string const& name)
+{
+  this->Position->Vars->Set(name, CM_NULLPTR);
+}
+
+std::vector<std::string> cmStateSnapshot::UnusedKeys() const
+{
+  return this->Position->Vars->UnusedKeys();
+}
+
+std::vector<std::string> cmStateSnapshot::ClosureKeys() const
+{
+  return cmDefinitions::ClosureKeys(this->Position->Vars,
+                                    this->Position->Root);
+}
+
+bool cmStateSnapshot::RaiseScope(std::string const& var, const char* varDef)
+{
+  if (this->Position->ScopeParent == this->Position->DirectoryParent) {
+    cmStateSnapshot parentDir = this->GetBuildsystemDirectoryParent();
+    if (!parentDir.IsValid()) {
+      return false;
+    }
+    // Update the definition in the parent directory top scope.  This
+    // directory's scope was initialized by the closure of the parent
+    // scope, so we do not need to localize the definition first.
+    if (varDef) {
+      parentDir.SetDefinition(var, varDef);
+    } else {
+      parentDir.RemoveDefinition(var);
+    }
+    return true;
+  }
+  // First localize the definition in the current scope.
+  cmDefinitions::Raise(var, this->Position->Vars, this->Position->Root);
+
+  // Now update the definition in the parent scope.
+  this->Position->Parent->Set(var, varDef);
+  return true;
+}
+
+template <typename T, typename U, typename V>
+void InitializeContentFromParent(T& parentContent, T& thisContent,
+                                 U& parentBacktraces, U& thisBacktraces,
+                                 V& contentEndPosition)
+{
+  std::vector<std::string>::const_iterator parentBegin = parentContent.begin();
+  std::vector<std::string>::const_iterator parentEnd = parentContent.end();
+
+  std::vector<std::string>::const_reverse_iterator parentRbegin =
+    cmMakeReverseIterator(parentEnd);
+  std::vector<std::string>::const_reverse_iterator parentRend =
+    parentContent.rend();
+  parentRbegin = std::find(parentRbegin, parentRend, cmPropertySentinal);
+  std::vector<std::string>::const_iterator parentIt = parentRbegin.base();
+
+  thisContent = std::vector<std::string>(parentIt, parentEnd);
+
+  std::vector<cmListFileBacktrace>::const_iterator btIt =
+    parentBacktraces.begin() + std::distance(parentBegin, parentIt);
+  std::vector<cmListFileBacktrace>::const_iterator btEnd =
+    parentBacktraces.end();
+
+  thisBacktraces = std::vector<cmListFileBacktrace>(btIt, btEnd);
+
+  contentEndPosition = thisContent.size();
+}
+
+void cmStateSnapshot::SetDefaultDefinitions()
+{
+/* Up to CMake 2.4 here only WIN32, UNIX and APPLE were set.
+  With CMake must separate between target and host platform. In most cases
+  the tests for WIN32, UNIX and APPLE will be for the target system, so an
+  additional set of variables for the host system is required ->
+  CMAKE_HOST_WIN32, CMAKE_HOST_UNIX, CMAKE_HOST_APPLE.
+  WIN32, UNIX and APPLE are now set in the platform files in
+  Modules/Platforms/.
+  To keep cmake scripts (-P) and custom language and compiler modules
+  working, these variables are still also set here in this place, but they
+  will be reset in CMakeSystemSpecificInformation.cmake before the platform
+  files are executed. */
+#if defined(_WIN32)
+  this->SetDefinition("WIN32", "1");
+  this->SetDefinition("CMAKE_HOST_WIN32", "1");
+#else
+  this->SetDefinition("UNIX", "1");
+  this->SetDefinition("CMAKE_HOST_UNIX", "1");
+#endif
+#if defined(__CYGWIN__)
+  std::string legacy;
+  if (cmSystemTools::GetEnv("CMAKE_LEGACY_CYGWIN_WIN32", legacy) &&
+      cmSystemTools::IsOn(legacy.c_str())) {
+    this->SetDefinition("WIN32", "1");
+    this->SetDefinition("CMAKE_HOST_WIN32", "1");
+  }
+#endif
+#if defined(__APPLE__)
+  this->SetDefinition("APPLE", "1");
+  this->SetDefinition("CMAKE_HOST_APPLE", "1");
+#endif
+#if defined(__sun__)
+  this->SetDefinition("CMAKE_HOST_SOLARIS", "1");
+#endif
+
+  char temp[1024];
+  sprintf(temp, "%d", cmVersion::GetMinorVersion());
+  this->SetDefinition("CMAKE_MINOR_VERSION", temp);
+  sprintf(temp, "%d", cmVersion::GetMajorVersion());
+  this->SetDefinition("CMAKE_MAJOR_VERSION", temp);
+  sprintf(temp, "%d", cmVersion::GetPatchVersion());
+  this->SetDefinition("CMAKE_PATCH_VERSION", temp);
+  sprintf(temp, "%d", cmVersion::GetTweakVersion());
+  this->SetDefinition("CMAKE_TWEAK_VERSION", temp);
+  this->SetDefinition("CMAKE_VERSION", cmVersion::GetCMakeVersion());
+
+  this->SetDefinition("CMAKE_FILES_DIRECTORY",
+                      cmake::GetCMakeFilesDirectory());
+
+  // Setup the default include file regular expression (match everything).
+  this->Position->BuildSystemDirectory->Properties.SetProperty(
+    "INCLUDE_REGULAR_EXPRESSION", "^.*$");
+}
+
+void cmStateSnapshot::SetDirectoryDefinitions()
+{
+  this->SetDefinition("CMAKE_SOURCE_DIR", this->State->GetSourceDirectory());
+  this->SetDefinition("CMAKE_CURRENT_SOURCE_DIR",
+                      this->State->GetSourceDirectory());
+  this->SetDefinition("CMAKE_BINARY_DIR", this->State->GetBinaryDirectory());
+  this->SetDefinition("CMAKE_CURRENT_BINARY_DIR",
+                      this->State->GetBinaryDirectory());
+}
+
+void cmStateSnapshot::InitializeFromParent()
+{
+  cmStateDetail::PositionType parent = this->Position->DirectoryParent;
+  assert(this->Position->Vars.IsValid());
+  assert(parent->Vars.IsValid());
+
+  *this->Position->Vars =
+    cmDefinitions::MakeClosure(parent->Vars, parent->Root);
+
+  InitializeContentFromParent(
+    parent->BuildSystemDirectory->IncludeDirectories,
+    this->Position->BuildSystemDirectory->IncludeDirectories,
+    parent->BuildSystemDirectory->IncludeDirectoryBacktraces,
+    this->Position->BuildSystemDirectory->IncludeDirectoryBacktraces,
+    this->Position->IncludeDirectoryPosition);
+
+  InitializeContentFromParent(
+    parent->BuildSystemDirectory->CompileDefinitions,
+    this->Position->BuildSystemDirectory->CompileDefinitions,
+    parent->BuildSystemDirectory->CompileDefinitionsBacktraces,
+    this->Position->BuildSystemDirectory->CompileDefinitionsBacktraces,
+    this->Position->CompileDefinitionsPosition);
+
+  InitializeContentFromParent(
+    parent->BuildSystemDirectory->CompileOptions,
+    this->Position->BuildSystemDirectory->CompileOptions,
+    parent->BuildSystemDirectory->CompileOptionsBacktraces,
+    this->Position->BuildSystemDirectory->CompileOptionsBacktraces,
+    this->Position->CompileOptionsPosition);
+}
+
+cmState* cmStateSnapshot::GetState() const
+{
+  return this->State;
+}
+
+cmStateDirectory cmStateSnapshot::GetDirectory() const
+{
+  return cmStateDirectory(this->Position->BuildSystemDirectory, *this);
+}
+
+void cmStateSnapshot::SetProjectName(const std::string& name)
+{
+  this->Position->BuildSystemDirectory->ProjectName = name;
+}
+
+std::string cmStateSnapshot::GetProjectName() const
+{
+  return this->Position->BuildSystemDirectory->ProjectName;
+}
+
+void cmStateSnapshot::InitializeFromParent_ForSubdirsCommand()
+{
+  std::string currentSrcDir = this->GetDefinition("CMAKE_CURRENT_SOURCE_DIR");
+  std::string currentBinDir = this->GetDefinition("CMAKE_CURRENT_BINARY_DIR");
+  this->InitializeFromParent();
+  this->SetDefinition("CMAKE_SOURCE_DIR", this->State->GetSourceDirectory());
+  this->SetDefinition("CMAKE_BINARY_DIR", this->State->GetBinaryDirectory());
+
+  this->SetDefinition("CMAKE_CURRENT_SOURCE_DIR", currentSrcDir);
+  this->SetDefinition("CMAKE_CURRENT_BINARY_DIR", currentBinDir);
+}
+
+bool cmStateSnapshot::StrictWeakOrder::operator()(
+  const cmStateSnapshot& lhs, const cmStateSnapshot& rhs) const
+{
+  return lhs.Position.StrictWeakOrdered(rhs.Position);
+}
+
+bool operator==(const cmStateSnapshot& lhs, const cmStateSnapshot& rhs)
+{
+  return lhs.Position == rhs.Position;
+}
+
+bool operator!=(const cmStateSnapshot& lhs, const cmStateSnapshot& rhs)
+{
+  return lhs.Position != rhs.Position;
+}
diff --git a/Source/cmStateSnapshot.h b/Source/cmStateSnapshot.h
new file mode 100644
index 0000000..72d0349
--- /dev/null
+++ b/Source/cmStateSnapshot.h
@@ -0,0 +1,88 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#ifndef cmStateSnapshot_h
+#define cmStateSnapshot_h
+
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
+#include "cmLinkedTree.h"
+#include "cmPolicies.h"
+#include "cmStateTypes.h"
+
+class cmState;
+class cmStateDirectory;
+
+class cmStateSnapshot
+{
+public:
+  cmStateSnapshot(cmState* state = CM_NULLPTR);
+  cmStateSnapshot(cmState* state, cmStateDetail::PositionType position);
+
+  const char* GetDefinition(std::string const& name) const;
+  bool IsInitialized(std::string const& name) const;
+  void SetDefinition(std::string const& name, std::string const& value);
+  void RemoveDefinition(std::string const& name);
+  std::vector<std::string> UnusedKeys() const;
+  std::vector<std::string> ClosureKeys() const;
+  bool RaiseScope(std::string const& var, const char* varDef);
+
+  void SetListFile(std::string const& listfile);
+
+  std::string GetExecutionListFile() const;
+
+  std::vector<cmStateSnapshot> GetChildren();
+
+  bool IsValid() const;
+  cmStateSnapshot GetBuildsystemDirectoryParent() const;
+  cmStateSnapshot GetCallStackParent() const;
+  cmStateSnapshot GetCallStackBottom() const;
+  cmStateEnums::SnapshotType GetType() const;
+
+  void SetPolicy(cmPolicies::PolicyID id, cmPolicies::PolicyStatus status);
+  cmPolicies::PolicyStatus GetPolicy(cmPolicies::PolicyID id) const;
+  bool HasDefinedPolicyCMP0011();
+  void PushPolicy(cmPolicies::PolicyMap entry, bool weak);
+  bool PopPolicy();
+  bool CanPopPolicyScope();
+
+  cmState* GetState() const;
+
+  cmStateDirectory GetDirectory() const;
+
+  void SetProjectName(std::string const& name);
+  std::string GetProjectName() const;
+
+  void InitializeFromParent_ForSubdirsCommand();
+
+  struct StrictWeakOrder
+  {
+    bool operator()(const cmStateSnapshot& lhs,
+                    const cmStateSnapshot& rhs) const;
+  };
+
+  void SetDirectoryDefinitions();
+  void SetDefaultDefinitions();
+
+private:
+  friend bool operator==(const cmStateSnapshot& lhs,
+                         const cmStateSnapshot& rhs);
+  friend bool operator!=(const cmStateSnapshot& lhs,
+                         const cmStateSnapshot& rhs);
+  friend class cmState;
+  friend class cmStateDirectory;
+  friend struct StrictWeakOrder;
+
+  void InitializeFromParent();
+
+  cmState* State;
+  cmStateDetail::PositionType Position;
+};
+
+bool operator==(const cmStateSnapshot& lhs, const cmStateSnapshot& rhs);
+bool operator!=(const cmStateSnapshot& lhs, const cmStateSnapshot& rhs);
+
+#endif
diff --git a/Source/cmStateTypes.h b/Source/cmStateTypes.h
new file mode 100644
index 0000000..2c974c1
--- /dev/null
+++ b/Source/cmStateTypes.h
@@ -0,0 +1,55 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#ifndef cmStateTypes_h
+#define cmStateTypes_h
+
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include "cmLinkedTree.h"
+
+namespace cmStateDetail {
+struct SnapshotDataType;
+typedef cmLinkedTree<cmStateDetail::SnapshotDataType>::iterator PositionType;
+}
+
+namespace cmStateEnums {
+
+enum SnapshotType
+{
+  BaseType,
+  BuildsystemDirectoryType,
+  FunctionCallType,
+  MacroCallType,
+  IncludeFileType,
+  InlineListFileType,
+  PolicyScopeType,
+  VariableScopeType
+};
+
+enum TargetType
+{
+  EXECUTABLE,
+  STATIC_LIBRARY,
+  SHARED_LIBRARY,
+  MODULE_LIBRARY,
+  OBJECT_LIBRARY,
+  UTILITY,
+  GLOBAL_TARGET,
+  INTERFACE_LIBRARY,
+  UNKNOWN_LIBRARY
+};
+
+enum CacheEntryType
+{
+  BOOL = 0,
+  PATH,
+  FILEPATH,
+  STRING,
+  INTERNAL,
+  STATIC,
+  UNINITIALIZED
+};
+}
+
+#endif
diff --git a/Source/cmStringCommand.cxx b/Source/cmStringCommand.cxx
index c73025a..eb94080 100644
--- a/Source/cmStringCommand.cxx
+++ b/Source/cmStringCommand.cxx
@@ -2,17 +2,22 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmStringCommand.h"
 
-#include "cmCryptoHash.h"
-
 #include <cmsys/RegularExpression.hxx>
-#include <cmsys/SystemTools.hxx>
-
 #include <ctype.h>
-#include <stdlib.h> // required for atoi
-#include <time.h>
+#include <sstream>
+#include <stdio.h>
+#include <stdlib.h>
 
-#include <cmTimestamp.h>
-#include <cmUuid.h>
+#include "cmAlgorithms.h"
+#include "cmCryptoHash.h"
+#include "cmGeneratorExpression.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cmTimestamp.h"
+#include "cmUuid.h"
+#include "cm_auto_ptr.hxx"
+
+class cmExecutionStatus;
 
 bool cmStringCommand::InitialPass(std::vector<std::string> const& args,
                                   cmExecutionStatus&)
@@ -31,7 +36,9 @@ bool cmStringCommand::InitialPass(std::vector<std::string> const& args,
   }
   if (subCommand == "MD5" || subCommand == "SHA1" || subCommand == "SHA224" ||
       subCommand == "SHA256" || subCommand == "SHA384" ||
-      subCommand == "SHA512") {
+      subCommand == "SHA512" || subCommand == "SHA3_224" ||
+      subCommand == "SHA3_256" || subCommand == "SHA3_384" ||
+      subCommand == "SHA3_512") {
     return this->HandleHashCommand(args);
   }
   if (subCommand == "TOLOWER") {
@@ -143,7 +150,7 @@ bool cmStringCommand::HandleAsciiCommand(std::vector<std::string> const& args)
   }
   std::string::size_type cc;
   std::string outvar = args[args.size() - 1];
-  std::string output = "";
+  std::string output;
   for (cc = 1; cc < args.size() - 1; cc++) {
     int ch = atoi(args[cc].c_str());
     if (ch > 0 && ch < 256) {
@@ -335,7 +342,7 @@ bool cmStringCommand::RegexReplace(std::vector<std::string> const& args)
   std::vector<RegexReplacement> replacement;
   std::string::size_type l = 0;
   while (l < replace.length()) {
-    std::string::size_type r = replace.find("\\", l);
+    std::string::size_type r = replace.find('\\', l);
     if (r == std::string::npos) {
       r = replace.length();
       replacement.push_back(replace.substr(l, r - l));
diff --git a/Source/cmStringCommand.h b/Source/cmStringCommand.h
index edb138d..c63bc3f 100644
--- a/Source/cmStringCommand.h
+++ b/Source/cmStringCommand.h
@@ -3,12 +3,13 @@
 #ifndef cmStringCommand_h
 #define cmStringCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
-class cmMakefile;
-namespace cmsys {
-class RegularExpression;
-}
+class cmExecutionStatus;
 
 /** \class cmStringCommand
  * \brief Common string operations
@@ -39,8 +40,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "string"; }
 
-  cmTypeMacro(cmStringCommand, cmCommand);
-
 protected:
   bool HandleConfigureCommand(std::vector<std::string> const& args);
   bool HandleAsciiCommand(std::vector<std::string> const& args);
diff --git a/Source/cmSubdirCommand.cxx b/Source/cmSubdirCommand.cxx
index fe7f659..3727dfa 100644
--- a/Source/cmSubdirCommand.cxx
+++ b/Source/cmSubdirCommand.cxx
@@ -2,6 +2,11 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSubdirCommand.h"
 
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmSubdirCommand
 bool cmSubdirCommand::InitialPass(std::vector<std::string> const& args,
                                   cmExecutionStatus&)
@@ -26,12 +31,10 @@ bool cmSubdirCommand::InitialPass(std::vector<std::string> const& args,
 
     // if they specified a relative path then compute the full
     std::string srcPath =
-      std::string(this->Makefile->GetCurrentSourceDirectory()) + "/" +
-      i->c_str();
+      std::string(this->Makefile->GetCurrentSourceDirectory()) + "/" + *i;
     if (cmSystemTools::FileIsDirectory(srcPath)) {
       std::string binPath =
-        std::string(this->Makefile->GetCurrentBinaryDirectory()) + "/" +
-        i->c_str();
+        std::string(this->Makefile->GetCurrentBinaryDirectory()) + "/" + *i;
       this->Makefile->AddSubDirectory(srcPath, binPath, excludeFromAll, false);
     }
     // otherwise it is a full path
diff --git a/Source/cmSubdirCommand.h b/Source/cmSubdirCommand.h
index c425852..ce1f876 100644
--- a/Source/cmSubdirCommand.h
+++ b/Source/cmSubdirCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmSubdirCommand_h
 #define cmSubdirCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmSubdirCommand
  * \brief Specify a list of subdirectories to build.
  *
@@ -31,8 +37,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "subdirs"; }
-
-  cmTypeMacro(cmSubdirCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmSubdirDependsCommand.cxx b/Source/cmSubdirDependsCommand.cxx
index b5b4148..9259836 100644
--- a/Source/cmSubdirDependsCommand.cxx
+++ b/Source/cmSubdirDependsCommand.cxx
@@ -2,6 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmSubdirDependsCommand.h"
 
+#include "cmPolicies.h"
+
+class cmExecutionStatus;
+
 bool cmSubdirDependsCommand::InitialPass(std::vector<std::string> const&,
                                          cmExecutionStatus&)
 {
diff --git a/Source/cmSubdirDependsCommand.h b/Source/cmSubdirDependsCommand.h
index 0f3deb6..80ff24f 100644
--- a/Source/cmSubdirDependsCommand.h
+++ b/Source/cmSubdirDependsCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmSubdirDependsCommand_h
 #define cmSubdirDependsCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 class cmSubdirDependsCommand : public cmCommand
 {
 public:
@@ -12,7 +18,6 @@ public:
   bool InitialPass(std::vector<std::string> const& args,
                    cmExecutionStatus& status) CM_OVERRIDE;
   std::string GetName() const CM_OVERRIDE { return "subdir_depends"; }
-  cmTypeMacro(cmSubdirDependsCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmSystemTools.cxx b/Source/cmSystemTools.cxx
index 3d8fdf5..9efc13b 100644
--- a/Source/cmSystemTools.cxx
+++ b/Source/cmSystemTools.cxx
@@ -3,6 +3,7 @@
 #include "cmSystemTools.h"
 
 #include "cmAlgorithms.h"
+#include "cmProcessOutput.h"
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
 #include "cmArchiveWrite.h"
@@ -573,7 +574,7 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
                                      std::string* captureStdOut,
                                      std::string* captureStdErr, int* retVal,
                                      const char* dir, OutputOption outputflag,
-                                     double timeout)
+                                     double timeout, Encoding encoding)
 {
   std::vector<const char*> argv;
   for (std::vector<std::string>::const_iterator a = command.begin();
@@ -609,6 +610,8 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
   char* data;
   int length;
   int pipe;
+  cmProcessOutput processOutput(encoding);
+  std::string strdata;
   if (outputflag != OUTPUT_PASSTHROUGH &&
       (captureStdOut || captureStdErr || outputflag != OUTPUT_NONE)) {
     while ((pipe = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) >
@@ -624,28 +627,44 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
 
       if (pipe == cmsysProcess_Pipe_STDOUT) {
         if (outputflag != OUTPUT_NONE) {
-          cmSystemTools::Stdout(data, length);
+          processOutput.DecodeText(data, length, strdata, 1);
+          cmSystemTools::Stdout(strdata.c_str(), strdata.size());
         }
         if (captureStdOut) {
           tempStdOut.insert(tempStdOut.end(), data, data + length);
         }
       } else if (pipe == cmsysProcess_Pipe_STDERR) {
         if (outputflag != OUTPUT_NONE) {
-          cmSystemTools::Stderr(data, length);
+          processOutput.DecodeText(data, length, strdata, 2);
+          cmSystemTools::Stderr(strdata.c_str(), strdata.size());
         }
         if (captureStdErr) {
           tempStdErr.insert(tempStdErr.end(), data, data + length);
         }
       }
     }
+
+    if (outputflag != OUTPUT_NONE) {
+      processOutput.DecodeText(std::string(), strdata, 1);
+      if (!strdata.empty()) {
+        cmSystemTools::Stdout(strdata.c_str(), strdata.size());
+      }
+      processOutput.DecodeText(std::string(), strdata, 2);
+      if (!strdata.empty()) {
+        cmSystemTools::Stderr(strdata.c_str(), strdata.size());
+      }
+    }
   }
 
   cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+
   if (captureStdOut) {
     captureStdOut->assign(tempStdOut.begin(), tempStdOut.end());
+    processOutput.DecodeText(*captureStdOut, *captureStdOut);
   }
   if (captureStdErr) {
     captureStdErr->assign(tempStdErr.begin(), tempStdErr.end());
+    processOutput.DecodeText(*captureStdErr, *captureStdErr);
   }
 
   bool result = true;
@@ -847,8 +866,8 @@ bool cmSystemTools::RenameFile(const char* oldname, const char* newname)
 bool cmSystemTools::ComputeFileMD5(const std::string& source, char* md5out)
 {
 #if defined(CMAKE_BUILD_WITH_CMAKE)
-  cmCryptoHashMD5 md5;
-  std::string str = md5.HashFile(source);
+  cmCryptoHash md5(cmCryptoHash::AlgoMD5);
+  std::string const str = md5.HashFile(source);
   strncpy(md5out, str.c_str(), 32);
   return !str.empty();
 #else
@@ -863,7 +882,7 @@ bool cmSystemTools::ComputeFileMD5(const std::string& source, char* md5out)
 std::string cmSystemTools::ComputeStringMD5(const std::string& input)
 {
 #if defined(CMAKE_BUILD_WITH_CMAKE)
-  cmCryptoHashMD5 md5;
+  cmCryptoHash md5(cmCryptoHash::AlgoMD5);
   return md5.HashString(input);
 #else
   (void)input;
@@ -1499,6 +1518,7 @@ void list_item_verbose(FILE* out, struct archive_entry* entry)
   {
     fprintf(out, " -> %s", archive_entry_symlink(entry));
   }
+  fflush(out);
 }
 
 long copy_data(struct archive* ar, struct archive* aw)
@@ -1642,7 +1662,9 @@ int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
   line = "";
   std::vector<char>::iterator outiter = out.begin();
   std::vector<char>::iterator erriter = err.begin();
-  while (1) {
+  cmProcessOutput processOutput;
+  std::string strdata;
+  while (true) {
     // Check for a newline in stdout.
     for (; outiter != out.end(); ++outiter) {
       if ((*outiter == '\r') && ((outiter + 1) == out.end())) {
@@ -1686,17 +1708,31 @@ int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
       return pipe;
     }
     if (pipe == cmsysProcess_Pipe_STDOUT) {
+      processOutput.DecodeText(data, length, strdata, 1);
       // Append to the stdout buffer.
       std::vector<char>::size_type size = out.size();
-      out.insert(out.end(), data, data + length);
+      out.insert(out.end(), strdata.begin(), strdata.end());
       outiter = out.begin() + size;
     } else if (pipe == cmsysProcess_Pipe_STDERR) {
+      processOutput.DecodeText(data, length, strdata, 2);
       // Append to the stderr buffer.
       std::vector<char>::size_type size = err.size();
-      err.insert(err.end(), data, data + length);
+      err.insert(err.end(), strdata.begin(), strdata.end());
       erriter = err.begin() + size;
     } else if (pipe == cmsysProcess_Pipe_None) {
       // Both stdout and stderr pipes have broken.  Return leftover data.
+      processOutput.DecodeText(std::string(), strdata, 1);
+      if (!strdata.empty()) {
+        std::vector<char>::size_type size = out.size();
+        out.insert(out.end(), strdata.begin(), strdata.end());
+        outiter = out.begin() + size;
+      }
+      processOutput.DecodeText(std::string(), strdata, 2);
+      if (!strdata.empty()) {
+        std::vector<char>::size_type size = err.size();
+        err.insert(err.end(), strdata.begin(), strdata.end());
+        erriter = err.begin() + size;
+      }
       if (!out.empty()) {
         line.append(&out[0], outiter - out.begin());
         out.erase(out.begin(), out.end());
@@ -1979,7 +2015,8 @@ void cmSystemTools::FindCMakeResources(const char* argv0)
   // Install tree has
   // - "<prefix><CMAKE_BIN_DIR>/cmake"
   // - "<prefix><CMAKE_DATA_DIR>"
-  if (cmHasSuffix(exe_dir, CMAKE_BIN_DIR)) {
+  const std::string actual_case = cmSystemTools::GetActualCaseForPath(exe_dir);
+  if (cmHasSuffix(actual_case, CMAKE_BIN_DIR)) {
     std::string const prefix =
       exe_dir.substr(0, exe_dir.size() - strlen(CMAKE_BIN_DIR));
     cmSystemToolsCMakeRoot = prefix + CMAKE_DATA_DIR;
@@ -2518,9 +2555,9 @@ bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
       std::swap(se[0], se[1]);
     }
 
-    // Get the size of the dynamic section header.
-    unsigned int count = elf.GetDynamicEntryCount();
-    if (count == 0) {
+    // Obtain a copy of the dynamic entries
+    cmELF::DynamicEntryList dentries = elf.GetDynamicEntries();
+    if (dentries.empty()) {
       // This should happen only for invalid ELF files where a DT_NULL
       // appears before the end of the table.
       if (emsg) {
@@ -2536,40 +2573,46 @@ bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
       zeroSize[i] = se[i]->Size;
     }
 
-    // Get the range of file positions corresponding to each entry and
-    // the rest of the table after them.
-    unsigned long entryBegin[3] = { 0, 0, 0 };
-    unsigned long entryEnd[2] = { 0, 0 };
-    for (int i = 0; i < se_count; ++i) {
-      entryBegin[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection);
-      entryEnd[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection + 1);
-    }
-    entryBegin[se_count] = elf.GetDynamicEntryPosition(count);
-
-    // The data are to be written over the old table entries starting at
-    // the first one being removed.
-    bytesBegin = entryBegin[0];
-    unsigned long bytesEnd = entryBegin[se_count];
-
-    // Allocate a buffer to hold the part of the file to be written.
-    // Initialize it with zeros.
-    bytes.resize(bytesEnd - bytesBegin, 0);
+    // Get size of one DYNAMIC entry
+    unsigned long const sizeof_dentry =
+      elf.GetDynamicEntryPosition(1) - elf.GetDynamicEntryPosition(0);
 
-    // Read the part of the DYNAMIC section header that will move.
-    // The remainder of the buffer will be left with zeros which
-    // represent a DT_NULL entry.
-    char* data = &bytes[0];
-    for (int i = 0; i < se_count; ++i) {
-      // Read data between the entries being removed.
-      unsigned long sz = entryBegin[i + 1] - entryEnd[i];
-      if (sz > 0 && !elf.ReadBytes(entryEnd[i], sz, data)) {
-        if (emsg) {
-          *emsg = "Failed to read DYNAMIC section header.";
+    // Adjust the entry list as necessary to remove the run path
+    unsigned long entriesErased = 0;
+    for (cmELF::DynamicEntryList::iterator it = dentries.begin();
+         it != dentries.end();) {
+      if (it->first == cmELF::TagRPath || it->first == cmELF::TagRunPath) {
+        it = dentries.erase(it);
+        entriesErased++;
+        continue;
+      } else {
+        if (cmELF::TagMipsRldMapRel != 0 &&
+            it->first == cmELF::TagMipsRldMapRel) {
+          // Background: debuggers need to know the "linker map" which contains
+          // the addresses each dynamic object is loaded at. Most arches use
+          // the DT_DEBUG tag which the dynamic linker writes to (directly) and
+          // contain the location of the linker map, however on MIPS the
+          // .dynamic section is always read-only so this is not possible. MIPS
+          // objects instead contain a DT_MIPS_RLD_MAP tag which contains the
+          // address where the dyanmic linker will write to (an indirect
+          // version of DT_DEBUG). Since this doesn't work when using PIE, a
+          // relative equivalent was created - DT_MIPS_RLD_MAP_REL. Since this
+          // version contains a relative offset, moving it changes the
+          // calculated address. This may cause the dyanmic linker to write
+          // into memory it should not be changing.
+          //
+          // To fix this, we adjust the value of DT_MIPS_RLD_MAP_REL here. If
+          // we move it up by n bytes, we add n bytes to the value of this tag.
+          it->second += entriesErased * sizeof_dentry;
         }
-        return false;
+
+        it++;
       }
-      data += sz;
     }
+
+    // Encode new entries list
+    bytes = elf.EncodeDynamicEntries(dentries);
+    bytesBegin = elf.GetDynamicEntryPosition(0);
   }
 
   // Open the file for update.
diff --git a/Source/cmSystemTools.h b/Source/cmSystemTools.h
index 9817a3c..10e8280 100644
--- a/Source/cmSystemTools.h
+++ b/Source/cmSystemTools.h
@@ -5,12 +5,19 @@
 
 #include <cmConfigure.h> // IWYU pragma: keep
 
+#include <cmProcessOutput.h>
 #include <cmsys/Process.h>
 #include <cmsys/SystemTools.hxx>
 #include <stddef.h>
 #include <string>
 #include <vector>
 
+#if defined(_MSC_VER)
+typedef unsigned short mode_t;
+#else
+#include <sys/types.h>
+#endif
+
 class cmSystemToolsFileTime;
 
 /** \class cmSystemTools
@@ -23,6 +30,7 @@ class cmSystemTools : public cmsys::SystemTools
 {
 public:
   typedef cmsys::SystemTools Superclass;
+  typedef cmProcessOutput::Encoding Encoding;
 
   /** Expand out any arguments in the vector that have ; separated
    *  strings into multiple arguments.  A new vector is created
@@ -233,7 +241,8 @@ public:
                                int* retVal = CM_NULLPTR,
                                const char* dir = CM_NULLPTR,
                                OutputOption outputflag = OUTPUT_MERGE,
-                               double timeout = 0.0);
+                               double timeout = 0.0,
+                               Encoding encoding = cmProcessOutput::Auto);
 
   static std::string PrintSingleCommand(std::vector<std::string> const&);
 
diff --git a/Source/cmTarget.cxx b/Source/cmTarget.cxx
index 54e0bea..fe3472d 100644
--- a/Source/cmTarget.cxx
+++ b/Source/cmTarget.cxx
@@ -2,36 +2,160 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTarget.h"
 
+#include <algorithm>
+#include <assert.h>
+#include <cmsys/RegularExpression.hxx>
+#include <map>
+#include <set>
+#include <sstream>
+#include <string.h>
+
 #include "cmAlgorithms.h"
 #include "cmGeneratorExpression.h"
 #include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
 #include "cmListFileCache.h"
 #include "cmMakefile.h"
+#include "cmMessenger.h"
 #include "cmOutputConverter.h"
 #include "cmProperty.h"
 #include "cmSourceFile.h"
 #include "cmSourceFileLocation.h"
+#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
 #include "cmSystemTools.h"
+#include "cmTargetPropertyComputer.h"
+#include "cm_unordered_set.hxx"
 #include "cmake.h"
 
-#include <algorithm>
-#include <assert.h>
-#include <cmsys/RegularExpression.hxx>
-#include <map>
-#include <set>
-#include <sstream>
-#include <string.h>
+template <>
+const char* cmTargetPropertyComputer::ComputeLocationForBuild<cmTarget>(
+  cmTarget const* tgt)
+{
+  static std::string loc;
+  if (tgt->IsImported()) {
+    loc = tgt->ImportedGetFullPath("", false);
+    return loc.c_str();
+  }
+
+  cmGlobalGenerator* gg = tgt->GetGlobalGenerator();
+  if (!gg->GetConfigureDoneCMP0026()) {
+    gg->CreateGenerationObjects();
+  }
+  cmGeneratorTarget* gt = gg->FindGeneratorTarget(tgt->GetName());
+  loc = gt->GetLocationForBuild();
+  return loc.c_str();
+}
+
+template <>
+const char* cmTargetPropertyComputer::ComputeLocation<cmTarget>(
+  cmTarget const* tgt, const std::string& config)
+{
+  static std::string loc;
+  if (tgt->IsImported()) {
+    loc = tgt->ImportedGetFullPath(config, false);
+    return loc.c_str();
+  }
 
-#if defined(CMake_HAVE_CXX_UNORDERED_SET)
-#include <unordered_set>
-#define UNORDERED_SET std::unordered_set
-#elif defined(CMAKE_BUILD_WITH_CMAKE)
-#include <cmsys/hash_set.hxx>
-#define UNORDERED_SET cmsys::hash_set
-#else
-#define UNORDERED_SET std::set
-#endif
+  cmGlobalGenerator* gg = tgt->GetGlobalGenerator();
+  if (!gg->GetConfigureDoneCMP0026()) {
+    gg->CreateGenerationObjects();
+  }
+  cmGeneratorTarget* gt = gg->FindGeneratorTarget(tgt->GetName());
+  loc = gt->GetFullPath(config, false);
+  return loc.c_str();
+}
+
+template <>
+const char* cmTargetPropertyComputer::GetSources<cmTarget>(
+  cmTarget const* tgt, cmMessenger* messenger,
+  cmListFileBacktrace const& context)
+{
+  cmStringRange entries = tgt->GetSourceEntries();
+  if (entries.empty()) {
+    return CM_NULLPTR;
+  }
+
+  std::ostringstream ss;
+  const char* sep = "";
+  for (std::vector<std::string>::const_iterator i = entries.begin();
+       i != entries.end(); ++i) {
+    std::string const& entry = *i;
+
+    std::vector<std::string> files;
+    cmSystemTools::ExpandListArgument(entry, files);
+    for (std::vector<std::string>::const_iterator li = files.begin();
+         li != files.end(); ++li) {
+      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;
+        }
+
+        bool addContent = false;
+        bool noMessage = true;
+        std::ostringstream e;
+        cmake::MessageType messageType = cmake::AUTHOR_WARNING;
+        switch (context.GetBottom().GetPolicy(cmPolicies::CMP0051)) {
+          case cmPolicies::WARN:
+            e << cmPolicies::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 \"" << tgt->GetName()
+            << "\" 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.";
+          messenger->IssueMessage(messageType, e.str(), context);
+        }
+        if (addContent) {
+          ss << sep;
+          sep = ";";
+          ss << *li;
+        }
+      } else if (cmGeneratorExpression::Find(*li) == std::string::npos) {
+        ss << sep;
+        sep = ";";
+        ss << *li;
+      } else {
+        cmSourceFile* sf = tgt->GetMakefile()->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;
+      }
+    }
+  }
+  static std::string srcs;
+  srcs = ss.str();
+  return srcs.c_str();
+}
 
 class cmTargetInternals
 {
@@ -50,7 +174,7 @@ public:
   std::vector<cmListFileBacktrace> LinkImplementationPropertyBacktraces;
 };
 
-cmTarget::cmTarget(std::string const& name, cmState::TargetType type,
+cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
                    Visibility vis, cmMakefile* mf)
 {
   assert(mf);
@@ -66,8 +190,8 @@ cmTarget::cmTarget(std::string const& name, cmState::TargetType type,
   this->BuildInterfaceIncludesAppended = false;
 
   // only add dependency information for library targets
-  if (this->TargetTypeValue >= cmState::STATIC_LIBRARY &&
-      this->TargetTypeValue <= cmState::MODULE_LIBRARY) {
+  if (this->TargetTypeValue >= cmStateEnums::STATIC_LIBRARY &&
+      this->TargetTypeValue <= cmStateEnums::MODULE_LIBRARY) {
     this->RecordDependencies = true;
   } else {
     this->RecordDependencies = false;
@@ -84,8 +208,8 @@ cmTarget::cmTarget(std::string const& name, cmState::TargetType type,
            "Android") == 0;
 
   // Setup default property values.
-  if (this->GetType() != cmState::INTERFACE_LIBRARY &&
-      this->GetType() != cmState::UTILITY) {
+  if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
+      this->GetType() != cmStateEnums::UTILITY) {
     this->SetPropertyDefault("ANDROID_API", CM_NULLPTR);
     this->SetPropertyDefault("ANDROID_API_MIN", CM_NULLPTR);
     this->SetPropertyDefault("ANDROID_ARCH", CM_NULLPTR);
@@ -102,6 +226,7 @@ cmTarget::cmTarget(std::string const& name, cmState::TargetType type,
     this->SetPropertyDefault("ANDROID_JAR_DEPENDENCIES", CM_NULLPTR);
     this->SetPropertyDefault("ANDROID_ASSETS_DIRECTORIES", CM_NULLPTR);
     this->SetPropertyDefault("ANDROID_ANT_ADDITIONAL_OPTIONS", CM_NULLPTR);
+    this->SetPropertyDefault("BUILD_RPATH", CM_NULLPTR);
     this->SetPropertyDefault("INSTALL_NAME_DIR", CM_NULLPTR);
     this->SetPropertyDefault("INSTALL_RPATH", "");
     this->SetPropertyDefault("INSTALL_RPATH_USE_LINK_PATH", "OFF");
@@ -128,9 +253,9 @@ cmTarget::cmTarget(std::string const& name, cmState::TargetType type,
     this->SetPropertyDefault("WIN32_EXECUTABLE", CM_NULLPTR);
     this->SetPropertyDefault("MACOSX_BUNDLE", CM_NULLPTR);
     this->SetPropertyDefault("MACOSX_RPATH", CM_NULLPTR);
-    this->SetPropertyDefault("NO_SYSTEM_FROM_IMPORTED", CM_NULLPTR);
     this->SetPropertyDefault("C_CLANG_TIDY", CM_NULLPTR);
     this->SetPropertyDefault("C_COMPILER_LAUNCHER", CM_NULLPTR);
+    this->SetPropertyDefault("C_CPPLINT", CM_NULLPTR);
     this->SetPropertyDefault("C_INCLUDE_WHAT_YOU_USE", CM_NULLPTR);
     this->SetPropertyDefault("LINK_WHAT_YOU_USE", CM_NULLPTR);
     this->SetPropertyDefault("C_STANDARD", CM_NULLPTR);
@@ -138,20 +263,28 @@ cmTarget::cmTarget(std::string const& name, cmState::TargetType type,
     this->SetPropertyDefault("C_EXTENSIONS", CM_NULLPTR);
     this->SetPropertyDefault("CXX_CLANG_TIDY", CM_NULLPTR);
     this->SetPropertyDefault("CXX_COMPILER_LAUNCHER", CM_NULLPTR);
+    this->SetPropertyDefault("CXX_CPPLINT", CM_NULLPTR);
     this->SetPropertyDefault("CXX_INCLUDE_WHAT_YOU_USE", CM_NULLPTR);
     this->SetPropertyDefault("CXX_STANDARD", CM_NULLPTR);
     this->SetPropertyDefault("CXX_STANDARD_REQUIRED", CM_NULLPTR);
     this->SetPropertyDefault("CXX_EXTENSIONS", CM_NULLPTR);
+    this->SetPropertyDefault("CUDA_STANDARD", CM_NULLPTR);
+    this->SetPropertyDefault("CUDA_STANDARD_REQUIRED", CM_NULLPTR);
+    this->SetPropertyDefault("CUDA_EXTENSIONS", CM_NULLPTR);
     this->SetPropertyDefault("LINK_SEARCH_START_STATIC", CM_NULLPTR);
     this->SetPropertyDefault("LINK_SEARCH_END_STATIC", CM_NULLPTR);
   }
 
+  if (this->GetType() != cmStateEnums::UTILITY) {
+    this->SetPropertyDefault("NO_SYSTEM_FROM_IMPORTED", CM_NULLPTR);
+  }
+
   // Collect the set of configuration types.
   std::vector<std::string> configNames;
   mf->GetConfigurations(configNames);
 
   // Setup per-configuration property default values.
-  if (this->GetType() != cmState::UTILITY) {
+  if (this->GetType() != cmStateEnums::UTILITY) {
     const char* configProps[] = {
       /* clang-format needs this comment to break after the opening brace */
       "ARCHIVE_OUTPUT_DIRECTORY_",
@@ -166,7 +299,9 @@ cmTarget::cmTarget(std::string const& name, cmState::TargetType type,
          ci != configNames.end(); ++ci) {
       std::string configUpper = cmSystemTools::UpperCase(*ci);
       for (const char** p = configProps; *p; ++p) {
-        if (this->TargetTypeValue == cmState::INTERFACE_LIBRARY &&
+        // Interface libraries have no output locations, so honor only
+        // the configuration map.
+        if (this->TargetTypeValue == cmStateEnums::INTERFACE_LIBRARY &&
             strcmp(*p, "MAP_IMPORTED_CONFIG_") != 0) {
           continue;
         }
@@ -180,8 +315,8 @@ cmTarget::cmTarget(std::string const& name, cmState::TargetType type,
       // compatibility with previous CMake versions in which executables
       // did not support this variable.  Projects may still specify the
       // property directly.
-      if (this->TargetTypeValue != cmState::EXECUTABLE &&
-          this->TargetTypeValue != cmState::INTERFACE_LIBRARY) {
+      if (this->TargetTypeValue != cmStateEnums::EXECUTABLE &&
+          this->TargetTypeValue != cmStateEnums::INTERFACE_LIBRARY) {
         std::string property = cmSystemTools::UpperCase(*ci);
         property += "_POSTFIX";
         this->SetPropertyDefault(property, CM_NULLPTR);
@@ -226,49 +361,56 @@ cmTarget::cmTarget(std::string const& name, cmState::TargetType type,
       parentOptionsBts.end());
   }
 
-  if (this->GetType() != cmState::INTERFACE_LIBRARY &&
-      this->GetType() != cmState::UTILITY) {
+  if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
+      this->GetType() != cmStateEnums::UTILITY) {
     this->SetPropertyDefault("C_VISIBILITY_PRESET", CM_NULLPTR);
     this->SetPropertyDefault("CXX_VISIBILITY_PRESET", CM_NULLPTR);
+    this->SetPropertyDefault("CUDA_VISIBILITY_PRESET", CM_NULLPTR);
     this->SetPropertyDefault("VISIBILITY_INLINES_HIDDEN", CM_NULLPTR);
   }
 
-  if (this->TargetTypeValue == cmState::EXECUTABLE) {
+  if (this->TargetTypeValue == cmStateEnums::EXECUTABLE) {
     this->SetPropertyDefault("ANDROID_GUI", CM_NULLPTR);
     this->SetPropertyDefault("CROSSCOMPILING_EMULATOR", CM_NULLPTR);
     this->SetPropertyDefault("ENABLE_EXPORTS", CM_NULLPTR);
   }
-  if (this->TargetTypeValue == cmState::SHARED_LIBRARY ||
-      this->TargetTypeValue == cmState::MODULE_LIBRARY) {
+  if (this->TargetTypeValue == cmStateEnums::SHARED_LIBRARY ||
+      this->TargetTypeValue == cmStateEnums::MODULE_LIBRARY) {
     this->SetProperty("POSITION_INDEPENDENT_CODE", "True");
   }
-  if (this->TargetTypeValue == cmState::SHARED_LIBRARY ||
-      this->TargetTypeValue == cmState::EXECUTABLE) {
+  if (this->TargetTypeValue == cmStateEnums::SHARED_LIBRARY ||
+      this->TargetTypeValue == cmStateEnums::EXECUTABLE) {
     this->SetPropertyDefault("WINDOWS_EXPORT_ALL_SYMBOLS", CM_NULLPTR);
   }
 
-  if (this->GetType() != cmState::INTERFACE_LIBRARY &&
-      this->GetType() != cmState::UTILITY) {
+  if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
+      this->GetType() != cmStateEnums::UTILITY) {
     this->SetPropertyDefault("POSITION_INDEPENDENT_CODE", CM_NULLPTR);
   }
 
   // Record current policies for later use.
   this->Makefile->RecordPolicies(this->PolicyMap);
 
-  if (this->TargetTypeValue == cmState::INTERFACE_LIBRARY) {
+  if (this->TargetTypeValue == cmStateEnums::INTERFACE_LIBRARY) {
     // This policy is checked in a few conditions. The properties relevant
-    // to the policy are always ignored for cmState::INTERFACE_LIBRARY targets,
+    // to the policy are always ignored for cmStateEnums::INTERFACE_LIBRARY
+    // targets,
     // so ensure that the conditions don't lead to nonsense.
     this->PolicyMap.Set(cmPolicies::CMP0022, cmPolicies::NEW);
   }
 
-  if (this->GetType() != cmState::INTERFACE_LIBRARY &&
-      this->GetType() != cmState::UTILITY) {
+  if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
+      this->GetType() != cmStateEnums::UTILITY) {
     this->SetPropertyDefault("JOB_POOL_COMPILE", CM_NULLPTR);
     this->SetPropertyDefault("JOB_POOL_LINK", CM_NULLPTR);
   }
 }
 
+cmGlobalGenerator* cmTarget::GetGlobalGenerator() const
+{
+  return this->GetMakefile()->GetGlobalGenerator();
+}
+
 void cmTarget::AddUtility(const std::string& u, cmMakefile* makefile)
 {
   if (this->Utilities.insert(u).second && makefile) {
@@ -296,26 +438,28 @@ cmListFileBacktrace const& cmTarget::GetBacktrace() const
 
 bool cmTarget::IsExecutableWithExports() const
 {
-  return (this->GetType() == cmState::EXECUTABLE &&
+  return (this->GetType() == cmStateEnums::EXECUTABLE &&
           this->GetPropertyAsBool("ENABLE_EXPORTS"));
 }
 
 bool cmTarget::HasImportLibrary() const
 {
-  return (this->DLLPlatform && (this->GetType() == cmState::SHARED_LIBRARY ||
-                                this->IsExecutableWithExports()));
+  return (this->DLLPlatform &&
+          (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
+           this->IsExecutableWithExports()));
 }
 
 bool cmTarget::IsFrameworkOnApple() const
 {
-  return (this->GetType() == cmState::SHARED_LIBRARY &&
+  return ((this->GetType() == cmStateEnums::SHARED_LIBRARY ||
+           this->GetType() == cmStateEnums::STATIC_LIBRARY) &&
           this->Makefile->IsOn("APPLE") &&
           this->GetPropertyAsBool("FRAMEWORK"));
 }
 
 bool cmTarget::IsAppBundleOnApple() const
 {
-  return (this->GetType() == cmState::EXECUTABLE &&
+  return (this->GetType() == cmStateEnums::EXECUTABLE &&
           this->Makefile->IsOn("APPLE") &&
           this->GetPropertyAsBool("MACOSX_BUNDLE"));
 }
@@ -475,23 +619,6 @@ cmSourceFile* cmTarget::AddSource(const std::string& src)
   return this->Makefile->GetOrCreateSource(src);
 }
 
-void cmTarget::MergeLinkLibraries(cmMakefile& mf, const std::string& selfname,
-                                  const LinkLibraryVectorType& libs)
-{
-  // Only add on libraries we haven't added on before.
-  // Assumption: the global link libraries could only grow, never shrink
-  LinkLibraryVectorType::const_iterator i = libs.begin();
-  i += this->PrevLinkedLibraries.size();
-  for (; i != libs.end(); ++i) {
-    // This is equivalent to the target_link_libraries plain signature.
-    this->AddLinkLibrary(mf, selfname, i->first, i->second);
-    this->AppendProperty(
-      "INTERFACE_LINK_LIBRARIES",
-      this->GetDebugGeneratorExpressions(i->first, i->second).c_str());
-  }
-  this->PrevLinkedLibraries = libs;
-}
-
 void cmTarget::AddLinkDirectory(const std::string& d)
 {
   // Make sure we don't add unnecessary search directories.
@@ -514,7 +641,7 @@ void cmTarget::ClearDependencyInformation(cmMakefile& mf,
   depname += "_LIB_DEPENDS";
   if (this->RecordDependencies) {
     mf.AddCacheDefinition(depname, "", "Dependencies for target",
-                          cmState::STATIC);
+                          cmStateEnums::STATIC);
   } else {
     if (mf.GetDefinition(depname)) {
       std::string message = "Target ";
@@ -594,8 +721,7 @@ void cmTarget::GetTllSignatureTraces(std::ostream& s, TLLSignature sig) const
   }
 }
 
-void cmTarget::AddLinkLibrary(cmMakefile& mf, const std::string& target,
-                              const std::string& lib,
+void cmTarget::AddLinkLibrary(cmMakefile& mf, const std::string& lib,
                               cmTargetLinkLibraryType llt)
 {
   cmTarget* tgt = this->Makefile->FindTargetToUse(lib);
@@ -612,8 +738,8 @@ void cmTarget::AddLinkLibrary(cmMakefile& mf, const std::string& target,
   }
 
   if (cmGeneratorExpression::Find(lib) != std::string::npos ||
-      (tgt && tgt->GetType() == cmState::INTERFACE_LIBRARY) ||
-      (target == lib)) {
+      (tgt && tgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) ||
+      (this->Name == lib)) {
     return;
   }
 
@@ -631,7 +757,7 @@ void cmTarget::AddLinkLibrary(cmMakefile& mf, const std::string& target,
   // and we removing one instance will break the link line. Duplicates
   // will be appropriately eliminated at emit time.
   if (this->RecordDependencies) {
-    std::string targetEntry = target;
+    std::string targetEntry = this->Name;
     targetEntry += "_LIB_DEPENDS";
     std::string dependencies;
     const char* old_val = mf.GetDefinition(targetEntry);
@@ -653,7 +779,7 @@ void cmTarget::AddLinkLibrary(cmMakefile& mf, const std::string& target,
     dependencies += lib;
     dependencies += ";";
     mf.AddCacheDefinition(targetEntry, dependencies.c_str(),
-                          "Dependencies for the target", cmState::STATIC);
+                          "Dependencies for the target", cmStateEnums::STATIC);
   }
 }
 
@@ -722,51 +848,46 @@ cmBacktraceRange cmTarget::GetLinkImplementationBacktraces() const
   return cmMakeRange(this->Internal->LinkImplementationPropertyBacktraces);
 }
 
-static bool whiteListedInterfaceProperty(const std::string& prop)
+void cmTarget::SetProperty(const std::string& prop, const char* value)
 {
-  if (cmHasLiteralPrefix(prop, "INTERFACE_")) {
-    return true;
+  if (!cmTargetPropertyComputer::PassesWhitelist(
+        this->GetType(), prop, this->Makefile->GetMessenger(),
+        this->Makefile->GetBacktrace())) {
+    return;
   }
-  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 (prop == "MANUALLY_ADDED_DEPENDENCIES") {
+    std::ostringstream e;
+    e << "MANUALLY_ADDED_DEPENDENCIES property is read-only\n";
+    this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
+    return;
   }
-
-  if (builtIns.count(prop)) {
-    return true;
+  if (prop == "NAME") {
+    std::ostringstream e;
+    e << "NAME property is read-only\n";
+    this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
+    return;
   }
-
-  if (cmHasLiteralPrefix(prop, "MAP_IMPORTED_CONFIG_")) {
-    return true;
+  if (prop == "TYPE") {
+    std::ostringstream e;
+    e << "TYPE property is read-only\n";
+    this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
+    return;
   }
-
-  return false;
-}
-
-void cmTarget::SetProperty(const std::string& prop, const char* value)
-{
-  if (this->GetType() == cmState::INTERFACE_LIBRARY &&
-      !whiteListedInterfaceProperty(prop)) {
+  if (prop == "EXPORT_NAME" && this->IsImported()) {
     std::ostringstream e;
-    e << "INTERFACE_LIBRARY targets may only have whitelisted properties.  "
-         "The property \""
-      << prop << "\" is not allowed.";
+    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 == "NAME") {
+  if (prop == "SOURCES" && this->IsImported()) {
     std::ostringstream e;
-    e << "NAME property is read-only\n";
+    e << "SOURCES property can't be set on imported targets (\"" << this->Name
+      << "\")\n";
     this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
     return;
   }
+
   if (prop == "INCLUDE_DIRECTORIES") {
     this->Internal->IncludeDirectoriesEntries.clear();
     this->Internal->IncludeDirectoriesBacktraces.clear();
@@ -799,11 +920,6 @@ void cmTarget::SetProperty(const std::string& prop, const char* value)
       cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
       this->Internal->CompileDefinitionsBacktraces.push_back(lfbt);
     }
-  } else if (prop == "EXPORT_NAME" && this->IsImported()) {
-    std::ostringstream e;
-    e << "EXPORT_NAME property can't be set on imported targets (\""
-      << this->Name << "\")\n";
-    this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
   } else if (prop == "LINK_LIBRARIES") {
     this->Internal->LinkImplementationPropertyEntries.clear();
     this->Internal->LinkImplementationPropertyBacktraces.clear();
@@ -813,14 +929,6 @@ void cmTarget::SetProperty(const std::string& prop, const char* value)
       this->Internal->LinkImplementationPropertyBacktraces.push_back(lfbt);
     }
   } else if (prop == "SOURCES") {
-    if (this->IsImported()) {
-      std::ostringstream e;
-      e << "SOURCES property can't be set on imported targets (\""
-        << this->Name << "\")\n";
-      this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
-      return;
-    }
-
     this->Internal->SourceEntries.clear();
     this->Internal->SourceBacktraces.clear();
     if (value) {
@@ -828,6 +936,9 @@ void cmTarget::SetProperty(const std::string& prop, const char* value)
       this->Internal->SourceEntries.push_back(value);
       this->Internal->SourceBacktraces.push_back(lfbt);
     }
+  } else if (cmHasLiteralPrefix(prop, "IMPORTED_LIBNAME") &&
+             !this->CheckImportedLibName(prop, value ? value : "")) {
+    /* error was reported by check method */
   } else {
     this->Properties.SetProperty(prop, value);
   }
@@ -836,13 +947,9 @@ void cmTarget::SetProperty(const std::string& prop, const char* value)
 void cmTarget::AppendProperty(const std::string& prop, const char* value,
                               bool asString)
 {
-  if (this->GetType() == cmState::INTERFACE_LIBRARY &&
-      !whiteListedInterfaceProperty(prop)) {
-    std::ostringstream e;
-    e << "INTERFACE_LIBRARY targets may only have whitelisted properties.  "
-         "The property \""
-      << prop << "\" is not allowed.";
-    this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
+  if (!cmTargetPropertyComputer::PassesWhitelist(
+        this->GetType(), prop, this->Makefile->GetMessenger(),
+        this->Makefile->GetBacktrace())) {
     return;
   }
   if (prop == "NAME") {
@@ -851,6 +958,20 @@ void cmTarget::AppendProperty(const std::string& prop, const char* value,
     this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
     return;
   }
+  if (prop == "EXPORT_NAME" && this->IsImported()) {
+    std::ostringstream 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 == "SOURCES" && this->IsImported()) {
+    std::ostringstream e;
+    e << "SOURCES property can't be set on imported targets (\"" << this->Name
+      << "\")\n";
+    this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
+    return;
+  }
   if (prop == "INCLUDE_DIRECTORIES") {
     if (value && *value) {
       this->Internal->IncludeDirectoriesEntries.push_back(value);
@@ -875,11 +996,6 @@ void cmTarget::AppendProperty(const std::string& prop, const char* value,
       cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
       this->Internal->CompileDefinitionsBacktraces.push_back(lfbt);
     }
-  } else if (prop == "EXPORT_NAME" && this->IsImported()) {
-    std::ostringstream e;
-    e << "EXPORT_NAME property can't be set on imported targets (\""
-      << this->Name << "\")\n";
-    this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
   } else if (prop == "LINK_LIBRARIES") {
     if (value && *value) {
       cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
@@ -887,16 +1003,12 @@ void cmTarget::AppendProperty(const std::string& prop, const char* value,
       this->Internal->LinkImplementationPropertyBacktraces.push_back(lfbt);
     }
   } else if (prop == "SOURCES") {
-    if (this->IsImported()) {
-      std::ostringstream e;
-      e << "SOURCES property can't be set on imported targets (\""
-        << this->Name << "\")\n";
-      this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
-      return;
-    }
     cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
     this->Internal->SourceEntries.push_back(value);
     this->Internal->SourceBacktraces.push_back(lfbt);
+  } else if (cmHasLiteralPrefix(prop, "IMPORTED_LIBNAME")) {
+    this->Makefile->IssueMessage(cmake::FATAL_ERROR,
+                                 prop + " property may not be APPENDed.");
   } else {
     this->Properties.AppendProperty(prop, value, asString);
   }
@@ -904,10 +1016,10 @@ void cmTarget::AppendProperty(const std::string& prop, const char* value,
 
 void cmTarget::AppendBuildInterfaceIncludes()
 {
-  if (this->GetType() != cmState::SHARED_LIBRARY &&
-      this->GetType() != cmState::STATIC_LIBRARY &&
-      this->GetType() != cmState::MODULE_LIBRARY &&
-      this->GetType() != cmState::INTERFACE_LIBRARY &&
+  if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
+      this->GetType() != cmStateEnums::STATIC_LIBRARY &&
+      this->GetType() != cmStateEnums::MODULE_LIBRARY &&
+      this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
       !this->IsExecutableWithExports()) {
     return;
   }
@@ -1047,137 +1159,16 @@ void cmTarget::CheckProperty(const std::string& prop,
   }
 }
 
-bool cmTarget::HandleLocationPropertyPolicy(cmMakefile* context) const
+const char* cmTarget::GetComputedProperty(
+  const std::string& prop, cmMessenger* messenger,
+  cmListFileBacktrace const& context) const
 {
-  if (this->IsImported()) {
-    return true;
-  }
-  std::ostringstream e;
-  const char* modal = CM_NULLPTR;
-  cmake::MessageType messageType = cmake::AUTHOR_WARNING;
-  switch (context->GetPolicyStatus(cmPolicies::CMP0026)) {
-    case cmPolicies::WARN:
-      e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0026) << "\n";
-      modal = "should";
-    case cmPolicies::OLD:
-      break;
-    case cmPolicies::REQUIRED_ALWAYS:
-    case cmPolicies::REQUIRED_IF_USED:
-    case cmPolicies::NEW:
-      modal = "may";
-      messageType = cmake::FATAL_ERROR;
-  }
-
-  if (modal) {
-    e << "The LOCATION property " << modal << " not be read from target \""
-      << this->GetName()
-      << "\".  Use the target name directly with "
-         "add_custom_command, or use the generator expression $<TARGET_FILE>, "
-         "as appropriate.\n";
-    context->IssueMessage(messageType, e.str());
-  }
-
-  return messageType != cmake::FATAL_ERROR;
+  return cmTargetPropertyComputer::GetProperty(this, prop, messenger, context);
 }
 
 const char* cmTarget::GetProperty(const std::string& prop) const
 {
-  return this->GetProperty(prop, this->Makefile);
-}
-
-const char* cmTarget::GetProperty(const std::string& prop,
-                                  cmMakefile* context) const
-{
-  if (this->GetType() == cmState::INTERFACE_LIBRARY &&
-      !whiteListedInterfaceProperty(prop)) {
-    std::ostringstream e;
-    e << "INTERFACE_LIBRARY targets may only have whitelisted properties.  "
-         "The property \""
-      << prop << "\" is not allowed.";
-    context->IssueMessage(cmake::FATAL_ERROR, e.str());
-    return CM_NULLPTR;
-  }
-
-  // Watch for special "computed" properties that are dependent on
-  // other properties or variables.  Always recompute them.
-  if (this->GetType() == cmState::EXECUTABLE ||
-      this->GetType() == cmState::STATIC_LIBRARY ||
-      this->GetType() == cmState::SHARED_LIBRARY ||
-      this->GetType() == cmState::MODULE_LIBRARY ||
-      this->GetType() == cmState::UNKNOWN_LIBRARY) {
-    static const std::string propLOCATION = "LOCATION";
-    if (prop == propLOCATION) {
-      if (!this->HandleLocationPropertyPolicy(context)) {
-        return CM_NULLPTR;
-      }
-
-      // Set the LOCATION property of the target.
-      //
-      // For an imported target this is the location of an arbitrary
-      // available configuration.
-      //
-      if (this->IsImported()) {
-        this->Properties.SetProperty(
-          propLOCATION, this->ImportedGetFullPath("", false).c_str());
-      } else {
-        // For a non-imported target this is deprecated because it
-        // cannot take into account the per-configuration name of the
-        // target because the configuration type may not be known at
-        // CMake time.
-        cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator();
-        if (!gg->GetConfigureDoneCMP0026()) {
-          gg->CreateGenerationObjects();
-        }
-        cmGeneratorTarget* gt = gg->FindGeneratorTarget(this->GetName());
-        this->Properties.SetProperty(propLOCATION, gt->GetLocationForBuild());
-      }
-
-    }
-
-    // Support "LOCATION_<CONFIG>".
-    else if (cmHasLiteralPrefix(prop, "LOCATION_")) {
-      if (!this->HandleLocationPropertyPolicy(context)) {
-        return CM_NULLPTR;
-      }
-      const char* configName = prop.c_str() + 9;
-
-      if (this->IsImported()) {
-        this->Properties.SetProperty(
-          prop, this->ImportedGetFullPath(configName, false).c_str());
-      } else {
-        cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator();
-        if (!gg->GetConfigureDoneCMP0026()) {
-          gg->CreateGenerationObjects();
-        }
-        cmGeneratorTarget* gt = gg->FindGeneratorTarget(this->GetName());
-        this->Properties.SetProperty(
-          prop, gt->GetFullPath(configName, false).c_str());
-      }
-    }
-    // Support "<CONFIG>_LOCATION".
-    else if (cmHasLiteralSuffix(prop, "_LOCATION") &&
-             !cmHasLiteralPrefix(prop, "XCODE_ATTRIBUTE_")) {
-      std::string configName(prop.c_str(), prop.size() - 9);
-      if (configName != "IMPORTED") {
-        if (!this->HandleLocationPropertyPolicy(context)) {
-          return CM_NULLPTR;
-        }
-        if (this->IsImported()) {
-          this->Properties.SetProperty(
-            prop, this->ImportedGetFullPath(configName, false).c_str());
-        } else {
-          cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator();
-          if (!gg->GetConfigureDoneCMP0026()) {
-            gg->CreateGenerationObjects();
-          }
-          cmGeneratorTarget* gt = gg->FindGeneratorTarget(this->GetName());
-          this->Properties.SetProperty(
-            prop, gt->GetFullPath(configName, false).c_str());
-        }
-      }
-    }
-  }
-  static UNORDERED_SET<std::string> specialProps;
+  static CM_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);
@@ -1186,6 +1177,7 @@ const char* cmTarget::GetProperty(const std::string& prop,
   MAKE_STATIC_PROP(COMPILE_OPTIONS);
   MAKE_STATIC_PROP(COMPILE_DEFINITIONS);
   MAKE_STATIC_PROP(IMPORTED);
+  MAKE_STATIC_PROP(MANUALLY_ADDED_DEPENDENCIES);
   MAKE_STATIC_PROP(NAME);
   MAKE_STATIC_PROP(BINARY_DIR);
   MAKE_STATIC_PROP(SOURCE_DIR);
@@ -1199,6 +1191,7 @@ const char* cmTarget::GetProperty(const std::string& prop,
     specialProps.insert(propCOMPILE_OPTIONS);
     specialProps.insert(propCOMPILE_DEFINITIONS);
     specialProps.insert(propIMPORTED);
+    specialProps.insert(propMANUALLY_ADDED_DEPENDENCIES);
     specialProps.insert(propNAME);
     specialProps.insert(propBINARY_DIR);
     specialProps.insert(propSOURCE_DIR);
@@ -1254,6 +1247,15 @@ const char* cmTarget::GetProperty(const std::string& prop,
       output = cmJoin(this->Internal->CompileDefinitionsEntries, ";");
       return output.c_str();
     }
+    if (prop == propMANUALLY_ADDED_DEPENDENCIES) {
+      if (this->Utilities.empty()) {
+        return CM_NULLPTR;
+      }
+
+      static std::string output;
+      output = cmJoin(this->Utilities, ";");
+      return output.c_str();
+    }
     if (prop == propIMPORTED) {
       return this->IsImported() ? "TRUE" : "FALSE";
     }
@@ -1261,93 +1263,16 @@ const char* cmTarget::GetProperty(const std::string& prop,
       return this->GetName().c_str();
     }
     if (prop == propBINARY_DIR) {
-      return this->GetMakefile()->GetCurrentBinaryDirectory();
+      return this->GetMakefile()
+        ->GetStateSnapshot()
+        .GetDirectory()
+        .GetCurrentBinary();
     }
     if (prop == propSOURCE_DIR) {
-      return this->GetMakefile()->GetCurrentSourceDirectory();
-    }
-    if (prop == propSOURCES) {
-      if (this->Internal->SourceEntries.empty()) {
-        return CM_NULLPTR;
-      }
-
-      std::ostringstream ss;
-      const char* sep = "";
-      for (std::vector<std::string>::const_iterator i =
-             this->Internal->SourceEntries.begin();
-           i != this->Internal->SourceEntries.end(); ++i) {
-        std::string const& entry = *i;
-
-        std::vector<std::string> files;
-        cmSystemTools::ExpandListArgument(entry, files);
-        for (std::vector<std::string>::const_iterator li = files.begin();
-             li != files.end(); ++li) {
-          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;
-            }
-
-            bool addContent = false;
-            bool noMessage = true;
-            std::ostringstream e;
-            cmake::MessageType messageType = cmake::AUTHOR_WARNING;
-            switch (context->GetPolicyStatus(cmPolicies::CMP0051)) {
-              case cmPolicies::WARN:
-                e << cmPolicies::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;
-            }
-          } 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()) {
-              sname += "/";
-            }
-            sname += location.GetName();
-
-            ss << sep;
-            sep = ";";
-            // Append this list entry.
-            ss << sname;
-          }
-        }
-      }
-      this->Properties.SetProperty("SOURCES", ss.str().c_str());
+      return this->GetMakefile()
+        ->GetStateSnapshot()
+        .GetDirectory()
+        .GetCurrentSource();
     }
   }
 
@@ -1356,7 +1281,8 @@ const char* cmTarget::GetProperty(const std::string& prop,
     const bool chain = this->GetMakefile()->GetState()->IsPropertyChained(
       prop, cmProperty::TARGET);
     if (chain) {
-      return this->Makefile->GetProperty(prop, chain);
+      return this->Makefile->GetStateSnapshot().GetDirectory().GetProperty(
+        prop, chain);
     }
   }
   return retVal;
@@ -1370,15 +1296,15 @@ bool cmTarget::GetPropertyAsBool(const std::string& prop) const
 const char* cmTarget::GetSuffixVariableInternal(bool implib) const
 {
   switch (this->GetType()) {
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
       return "CMAKE_STATIC_LIBRARY_SUFFIX";
-    case cmState::SHARED_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
       return (implib ? "CMAKE_IMPORT_LIBRARY_SUFFIX"
                      : "CMAKE_SHARED_LIBRARY_SUFFIX");
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       return (implib ? "CMAKE_IMPORT_LIBRARY_SUFFIX"
                      : "CMAKE_SHARED_MODULE_SUFFIX");
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       return (implib
                 ? "CMAKE_IMPORT_LIBRARY_SUFFIX"
                 // Android GUI application packages store the native
@@ -1395,15 +1321,15 @@ const char* cmTarget::GetSuffixVariableInternal(bool implib) const
 const char* cmTarget::GetPrefixVariableInternal(bool implib) const
 {
   switch (this->GetType()) {
-    case cmState::STATIC_LIBRARY:
+    case cmStateEnums::STATIC_LIBRARY:
       return "CMAKE_STATIC_LIBRARY_PREFIX";
-    case cmState::SHARED_LIBRARY:
+    case cmStateEnums::SHARED_LIBRARY:
       return (implib ? "CMAKE_IMPORT_LIBRARY_PREFIX"
                      : "CMAKE_SHARED_LIBRARY_PREFIX");
-    case cmState::MODULE_LIBRARY:
+    case cmStateEnums::MODULE_LIBRARY:
       return (implib ? "CMAKE_IMPORT_LIBRARY_PREFIX"
                      : "CMAKE_SHARED_MODULE_PREFIX");
-    case cmState::EXECUTABLE:
+    case cmStateEnums::EXECUTABLE:
       return (implib
                 ? "CMAKE_IMPORT_LIBRARY_PREFIX"
                 // Android GUI application packages store the native
@@ -1437,7 +1363,7 @@ std::string cmTarget::ImportedGetFullPath(const std::string& config,
   const char* imp = CM_NULLPTR;
   std::string suffix;
 
-  if (this->GetType() != cmState::INTERFACE_LIBRARY &&
+  if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
       this->GetMappedConfig(config_upper, &loc, &imp, suffix)) {
     if (!pimplib) {
       if (loc) {
@@ -1455,7 +1381,7 @@ std::string cmTarget::ImportedGetFullPath(const std::string& config,
     } else {
       if (imp) {
         result = imp;
-      } else if (this->GetType() == cmState::SHARED_LIBRARY ||
+      } else if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
                  this->IsExecutableWithExports()) {
         std::string impProp = "IMPORTED_IMPLIB";
         impProp += suffix;
@@ -1489,17 +1415,41 @@ void cmTarget::SetPropertyDefault(const std::string& property,
   }
 }
 
+bool cmTarget::CheckImportedLibName(std::string const& prop,
+                                    std::string const& value) const
+{
+  if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY ||
+      !this->IsImported()) {
+    this->Makefile->IssueMessage(
+      cmake::FATAL_ERROR, prop +
+        " property may be set only on imported INTERFACE library targets.");
+    return false;
+  }
+  if (!value.empty()) {
+    if (value[0] == '-') {
+      this->Makefile->IssueMessage(cmake::FATAL_ERROR, prop +
+                                     " property value\n  " + value +
+                                     "\nmay not start with '-'.");
+      return false;
+    }
+    std::string::size_type bad = value.find_first_of(":/\\;");
+    if (bad != value.npos) {
+      this->Makefile->IssueMessage(
+        cmake::FATAL_ERROR, prop + " property value\n  " + value +
+          "\nmay not contain '" + value.substr(bad, 1) + "'.");
+      return false;
+    }
+  }
+  return true;
+}
+
 bool cmTarget::GetMappedConfig(std::string const& desired_config,
                                const char** loc, const char** imp,
                                std::string& suffix) const
 {
-  if (this->GetType() == cmState::INTERFACE_LIBRARY) {
-    // This method attempts to find a config-specific LOCATION for the
-    // IMPORTED library. In the case of cmState::INTERFACE_LIBRARY, there is no
-    // LOCATION at all, so leaving *loc and *imp unchanged is the appropriate
-    // and valid response.
-    return true;
-  }
+  std::string const locPropBase =
+    this->GetType() == cmStateEnums::INTERFACE_LIBRARY ? "IMPORTED_LIBNAME"
+                                                       : "IMPORTED_LOCATION";
 
   // Track the configuration-specific property suffix.
   suffix = "_";
@@ -1510,7 +1460,7 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config,
     std::string mapProp = "MAP_IMPORTED_CONFIG_";
     mapProp += desired_config;
     if (const char* mapValue = this->GetProperty(mapProp)) {
-      cmSystemTools::ExpandListArgument(mapValue, mappedConfigs);
+      cmSystemTools::ExpandListArgument(mapValue, mappedConfigs, true);
     }
   }
 
@@ -1523,34 +1473,49 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config,
   for (std::vector<std::string>::const_iterator mci = mappedConfigs.begin();
        !*loc && !*imp && mci != mappedConfigs.end(); ++mci) {
     // Look for this configuration.
-    std::string mcUpper = cmSystemTools::UpperCase(*mci);
-    std::string locProp = "IMPORTED_LOCATION_";
-    locProp += mcUpper;
-    *loc = this->GetProperty(locProp);
-    if (allowImp) {
-      std::string impProp = "IMPORTED_IMPLIB_";
-      impProp += mcUpper;
-      *imp = this->GetProperty(impProp);
-    }
+    if (mci->empty()) {
+      // An empty string in the mapping has a special meaning:
+      // look up the config-less properties.
+      *loc = this->GetProperty(locPropBase);
+      if (allowImp) {
+        *imp = this->GetProperty("IMPORTED_IMPLIB");
+      }
+      // If it was found, set the suffix.
+      if (*loc || *imp) {
+        suffix = "";
+      }
+    } else {
+      std::string mcUpper = cmSystemTools::UpperCase(*mci);
+      std::string locProp = locPropBase + "_";
+      locProp += mcUpper;
+      *loc = this->GetProperty(locProp);
+      if (allowImp) {
+        std::string impProp = "IMPORTED_IMPLIB_";
+        impProp += mcUpper;
+        *imp = this->GetProperty(impProp);
+      }
 
-    // If it was found, use it for all properties below.
-    if (*loc || *imp) {
-      suffix = "_";
-      suffix += mcUpper;
+      // If it was found, use it for all properties below.
+      if (*loc || *imp) {
+        suffix = "_";
+        suffix += mcUpper;
+      }
     }
   }
 
   // If we needed to find one of the mapped configurations but did not
-  // then the target is not found.  The project does not want any
-  // other configuration.
+  // then the target location is not found.  The project does not want
+  // any other configuration.
   if (!mappedConfigs.empty() && !*loc && !*imp) {
-    return false;
+    // Interface libraries are always available because their
+    // library name is optional so it is okay to leave *loc empty.
+    return this->GetType() == cmStateEnums::INTERFACE_LIBRARY;
   }
 
   // If we have not yet found it then there are no mapped
   // configurations.  Look for an exact-match.
   if (!*loc && !*imp) {
-    std::string locProp = "IMPORTED_LOCATION";
+    std::string locProp = locPropBase;
     locProp += suffix;
     *loc = this->GetProperty(locProp);
     if (allowImp) {
@@ -1568,7 +1533,7 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config,
 
     // Look for a configuration-less location.  This may be set by
     // manually-written code.
-    *loc = this->GetProperty("IMPORTED_LOCATION");
+    *loc = this->GetProperty(locPropBase);
     if (allowImp) {
       *imp = this->GetProperty("IMPORTED_IMPLIB");
     }
@@ -1586,7 +1551,7 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config,
          !*loc && !*imp && aci != availableConfigs.end(); ++aci) {
       suffix = "_";
       suffix += cmSystemTools::UpperCase(*aci);
-      std::string locProp = "IMPORTED_LOCATION";
+      std::string locProp = locPropBase;
       locProp += suffix;
       *loc = this->GetProperty(locProp);
       if (allowImp) {
@@ -1596,9 +1561,11 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config,
       }
     }
   }
-  // If we have not yet found it then the target is not available.
+  // If we have not yet found it then the target location is not available.
   if (!*loc && !*imp) {
-    return false;
+    // Interface libraries are always available because their
+    // library name is optional so it is okay to leave *loc empty.
+    return this->GetType() == cmStateEnums::INTERFACE_LIBRARY;
   }
 
   return true;
diff --git a/Source/cmTarget.h b/Source/cmTarget.h
index dd9097a..1d40d20 100644
--- a/Source/cmTarget.h
+++ b/Source/cmTarget.h
@@ -5,14 +5,6 @@
 
 #include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmAlgorithms.h"
-#include "cmCustomCommand.h"
-#include "cmListFileCache.h"
-#include "cmPolicies.h"
-#include "cmPropertyMap.h"
-#include "cmState.h"
-#include "cmTargetLinkLibraryType.h"
-
 #include <iosfwd>
 #include <map>
 #include <set>
@@ -20,15 +12,18 @@
 #include <utility>
 #include <vector>
 
-#if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX_UNORDERED_MAP
-#include <unordered_map>
-#else
-#include <cmsys/hash_map.hxx>
-#endif
-#endif
+#include "cmAlgorithms.h"
+#include "cmCustomCommand.h"
+#include "cmListFileCache.h"
+#include "cmPolicies.h"
+#include "cmPropertyMap.h"
+#include "cmStateTypes.h"
+#include "cmTargetLinkLibraryType.h"
+#include "cm_unordered_map.hxx"
 
+class cmGlobalGenerator;
 class cmMakefile;
+class cmMessenger;
 class cmSourceFile;
 class cmTargetInternals;
 
@@ -61,8 +56,8 @@ public:
     VisibilityImportedGlobally
   };
 
-  cmTarget(std::string const& name, cmState::TargetType type, Visibility vis,
-           cmMakefile* mf);
+  cmTarget(std::string const& name, cmStateEnums::TargetType type,
+           Visibility vis, cmMakefile* mf);
 
   enum CustomCommandType
   {
@@ -74,7 +69,9 @@ public:
   /**
    * Return the type of target.
    */
-  cmState::TargetType GetType() const { return this->TargetTypeValue; }
+  cmStateEnums::TargetType GetType() const { return this->TargetTypeValue; }
+
+  cmGlobalGenerator* GetGlobalGenerator() const;
 
   ///! Set/Get the name of the target
   const std::string& GetName() const { return this->Name; }
@@ -142,8 +139,8 @@ public:
    */
   void ClearDependencyInformation(cmMakefile& mf, const std::string& target);
 
-  void AddLinkLibrary(cmMakefile& mf, const std::string& target,
-                      const std::string& lib, cmTargetLinkLibraryType llt);
+  void AddLinkLibrary(cmMakefile& mf, const std::string& lib,
+                      cmTargetLinkLibraryType llt);
   enum TLLSignature
   {
     KeywordTLLSignature,
@@ -153,9 +150,6 @@ public:
                            cmListFileContext const& lfc);
   void GetTllSignatureTraces(std::ostream& s, TLLSignature sig) const;
 
-  void MergeLinkLibraries(cmMakefile& mf, const std::string& selfname,
-                          const LinkLibraryVectorType& libs);
-
   const std::vector<std::string>& GetLinkDirectories() const;
 
   void AddLinkDirectory(const std::string& d);
@@ -200,9 +194,11 @@ public:
   void AppendProperty(const std::string& prop, const char* value,
                       bool asString = false);
   const char* GetProperty(const std::string& prop) const;
-  const char* GetProperty(const std::string& prop, cmMakefile* context) const;
   bool GetPropertyAsBool(const std::string& prop) const;
   void CheckProperty(const std::string& prop, cmMakefile* context) const;
+  const char* GetComputedProperty(const std::string& prop,
+                                  cmMessenger* messenger,
+                                  cmListFileBacktrace const& context) const;
 
   bool IsImported() const { return this->IsImportedTarget; }
   bool IsImportedGloballyVisible() const
@@ -211,7 +207,7 @@ public:
   }
 
   // Get the properties
-  cmPropertyMap& GetProperties() const { return this->Properties; }
+  cmPropertyMap const& GetProperties() const { return this->Properties; }
 
   bool GetMappedConfig(std::string const& desired_config, const char** loc,
                        const char** imp, std::string& suffix) const;
@@ -270,9 +266,10 @@ public:
     bool operator()(cmTarget const* t1, cmTarget const* t2) const;
   };
 
-private:
-  bool HandleLocationPropertyPolicy(cmMakefile* context) const;
+  std::string ImportedGetFullPath(const std::string& config,
+                                  bool implib) const;
 
+private:
   const char* GetSuffixVariableInternal(bool implib) const;
   const char* GetPrefixVariableInternal(bool implib) const;
 
@@ -281,11 +278,11 @@ private:
   void SetPropertyDefault(const std::string& property,
                           const char* default_value);
 
-  std::string ImportedGetFullPath(const std::string& config,
-                                  bool implib) const;
+  bool CheckImportedLibName(std::string const& prop,
+                            std::string const& value) const;
 
 private:
-  mutable cmPropertyMap Properties;
+  cmPropertyMap Properties;
   std::set<std::string> SystemIncludeDirectories;
   std::set<std::string> LinkDirectoriesEmmitted;
   std::set<std::string> Utilities;
@@ -299,11 +296,10 @@ private:
   std::vector<cmCustomCommand> PreLinkCommands;
   std::vector<cmCustomCommand> PostBuildCommands;
   std::vector<std::pair<TLLSignature, cmListFileContext> > TLLCommands;
-  LinkLibraryVectorType PrevLinkedLibraries;
   LinkLibraryVectorType OriginalLinkLibraries;
   cmMakefile* Makefile;
   cmTargetInternalPointer Internal;
-  cmState::TargetType TargetTypeValue;
+  cmStateEnums::TargetType TargetTypeValue;
   bool HaveInstallRule;
   bool RecordDependencies;
   bool DLLPlatform;
@@ -325,15 +321,7 @@ private:
   cmListFileBacktrace Backtrace;
 };
 
-#ifdef CMAKE_BUILD_WITH_CMAKE
-#ifdef CMake_HAVE_CXX_UNORDERED_MAP
-typedef std::unordered_map<std::string, cmTarget> cmTargets;
-#else
-typedef cmsys::hash_map<std::string, cmTarget> cmTargets;
-#endif
-#else
-typedef std::map<std::string, cmTarget> cmTargets;
-#endif
+typedef CM_UNORDERED_MAP<std::string, cmTarget> cmTargets;
 
 class cmTargetSet : public std::set<std::string>
 {
diff --git a/Source/cmTargetCompileDefinitionsCommand.cxx b/Source/cmTargetCompileDefinitionsCommand.cxx
index 9f08ba7..008d1a2 100644
--- a/Source/cmTargetCompileDefinitionsCommand.cxx
+++ b/Source/cmTargetCompileDefinitionsCommand.cxx
@@ -2,7 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTargetCompileDefinitionsCommand.h"
 
+#include <sstream>
+
 #include "cmAlgorithms.h"
+#include "cmMakefile.h"
+#include "cmTarget.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 bool cmTargetCompileDefinitionsCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
diff --git a/Source/cmTargetCompileDefinitionsCommand.h b/Source/cmTargetCompileDefinitionsCommand.h
index b49f616..caaf23b 100644
--- a/Source/cmTargetCompileDefinitionsCommand.h
+++ b/Source/cmTargetCompileDefinitionsCommand.h
@@ -3,8 +3,16 @@
 #ifndef cmTargetCompileDefinitionsCommand_h
 #define cmTargetCompileDefinitionsCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmTargetPropCommandBase.h"
 
+class cmCommand;
+class cmExecutionStatus;
+class cmTarget;
+
 class cmTargetCompileDefinitionsCommand : public cmTargetPropCommandBase
 {
 public:
@@ -31,8 +39,6 @@ public:
     return "target_compile_definitions";
   }
 
-  cmTypeMacro(cmTargetCompileDefinitionsCommand, cmTargetPropCommandBase);
-
 private:
   void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE;
   void HandleMissingTarget(const std::string& name) CM_OVERRIDE;
diff --git a/Source/cmTargetCompileFeaturesCommand.cxx b/Source/cmTargetCompileFeaturesCommand.cxx
index 7636347..1b6c008 100644
--- a/Source/cmTargetCompileFeaturesCommand.cxx
+++ b/Source/cmTargetCompileFeaturesCommand.cxx
@@ -2,7 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTargetCompileFeaturesCommand.h"
 
+#include <sstream>
+
 #include "cmAlgorithms.h"
+#include "cmMakefile.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
+class cmTarget;
 
 bool cmTargetCompileFeaturesCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
diff --git a/Source/cmTargetCompileFeaturesCommand.h b/Source/cmTargetCompileFeaturesCommand.h
index 8273e02..01f2938 100644
--- a/Source/cmTargetCompileFeaturesCommand.h
+++ b/Source/cmTargetCompileFeaturesCommand.h
@@ -3,8 +3,16 @@
 #ifndef cmTargetCompileFeaturesCommand_h
 #define cmTargetCompileFeaturesCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmTargetPropCommandBase.h"
 
+class cmCommand;
+class cmExecutionStatus;
+class cmTarget;
+
 class cmTargetCompileFeaturesCommand : public cmTargetPropCommandBase
 {
   cmCommand* Clone() CM_OVERRIDE { return new cmTargetCompileFeaturesCommand; }
@@ -14,8 +22,6 @@ class cmTargetCompileFeaturesCommand : public cmTargetPropCommandBase
 
   std::string GetName() const CM_OVERRIDE { return "target_compile_features"; }
 
-  cmTypeMacro(cmTargetCompileFeaturesCommand, cmTargetPropCommandBase);
-
 private:
   void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE;
   void HandleMissingTarget(const std::string& name) CM_OVERRIDE;
diff --git a/Source/cmTargetCompileOptionsCommand.cxx b/Source/cmTargetCompileOptionsCommand.cxx
index eb66dd3..1b4056d 100644
--- a/Source/cmTargetCompileOptionsCommand.cxx
+++ b/Source/cmTargetCompileOptionsCommand.cxx
@@ -2,7 +2,15 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTargetCompileOptionsCommand.h"
 
+#include <sstream>
+
 #include "cmAlgorithms.h"
+#include "cmListFileCache.h"
+#include "cmMakefile.h"
+#include "cmTarget.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 bool cmTargetCompileOptionsCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
diff --git a/Source/cmTargetCompileOptionsCommand.h b/Source/cmTargetCompileOptionsCommand.h
index f5b4c70..179013b 100644
--- a/Source/cmTargetCompileOptionsCommand.h
+++ b/Source/cmTargetCompileOptionsCommand.h
@@ -3,8 +3,16 @@
 #ifndef cmTargetCompileOptionsCommand_h
 #define cmTargetCompileOptionsCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmTargetPropCommandBase.h"
 
+class cmCommand;
+class cmExecutionStatus;
+class cmTarget;
+
 class cmTargetCompileOptionsCommand : public cmTargetPropCommandBase
 {
 public:
@@ -25,8 +33,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "target_compile_options"; }
 
-  cmTypeMacro(cmTargetCompileOptionsCommand, cmTargetPropCommandBase);
-
 private:
   void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE;
   void HandleMissingTarget(const std::string& name) CM_OVERRIDE;
diff --git a/Source/cmTargetDepend.h b/Source/cmTargetDepend.h
index acea6ea..a953efb 100644
--- a/Source/cmTargetDepend.h
+++ b/Source/cmTargetDepend.h
@@ -3,9 +3,9 @@
 #ifndef cmTargetDepend_h
 #define cmTargetDepend_h
 
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmStandardIncludes.h"
+#include <set>
 
 class cmGeneratorTarget;
 
diff --git a/Source/cmTargetExport.h b/Source/cmTargetExport.h
index 634148b..b08ede2 100644
--- a/Source/cmTargetExport.h
+++ b/Source/cmTargetExport.h
@@ -3,13 +3,13 @@
 #ifndef cmTargetExport_h
 #define cmTargetExport_h
 
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmStandardIncludes.h"
+#include <string>
 
 class cmGeneratorTarget;
-class cmInstallTargetGenerator;
 class cmInstallFilesGenerator;
+class cmInstallTargetGenerator;
 
 /** \brief A member of an ExportSet
  *
diff --git a/Source/cmTargetIncludeDirectoriesCommand.cxx b/Source/cmTargetIncludeDirectoriesCommand.cxx
index 37b9598..65a3149 100644
--- a/Source/cmTargetIncludeDirectoriesCommand.cxx
+++ b/Source/cmTargetIncludeDirectoriesCommand.cxx
@@ -2,7 +2,17 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTargetIncludeDirectoriesCommand.h"
 
+#include <set>
+#include <sstream>
+
 #include "cmGeneratorExpression.h"
+#include "cmListFileCache.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 bool cmTargetIncludeDirectoriesCommand::InitialPass(
   std::vector<std::string> const& args, cmExecutionStatus&)
diff --git a/Source/cmTargetIncludeDirectoriesCommand.h b/Source/cmTargetIncludeDirectoriesCommand.h
index 671627a..bc6cf0d 100644
--- a/Source/cmTargetIncludeDirectoriesCommand.h
+++ b/Source/cmTargetIncludeDirectoriesCommand.h
@@ -3,8 +3,16 @@
 #ifndef cmTargetIncludeDirectoriesCommand_h
 #define cmTargetIncludeDirectoriesCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmTargetPropCommandBase.h"
 
+class cmCommand;
+class cmExecutionStatus;
+class cmTarget;
+
 class cmTargetIncludeDirectoriesCommand : public cmTargetPropCommandBase
 {
 public:
@@ -31,8 +39,6 @@ public:
     return "target_include_directories";
   }
 
-  cmTypeMacro(cmTargetIncludeDirectoriesCommand, cmTargetPropCommandBase);
-
 private:
   void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE;
   void HandleMissingTarget(const std::string& name) CM_OVERRIDE;
diff --git a/Source/cmTargetLinkLibrariesCommand.cxx b/Source/cmTargetLinkLibrariesCommand.cxx
index e714309..e173036 100644
--- a/Source/cmTargetLinkLibrariesCommand.cxx
+++ b/Source/cmTargetLinkLibrariesCommand.cxx
@@ -2,7 +2,20 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTargetLinkLibrariesCommand.h"
 
+#include <sstream>
+#include <string.h>
+
 #include "cmGeneratorExpression.h"
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmState.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 const char* cmTargetLinkLibrariesCommand::LinkLibraryTypeNames[3] = {
   "general", "debug", "optimized"
@@ -71,7 +84,7 @@ bool cmTargetLinkLibrariesCommand::InitialPass(
     return true;
   }
 
-  if (this->Target->GetType() == cmState::OBJECT_LIBRARY) {
+  if (this->Target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
     std::ostringstream e;
     e << "Object library target \"" << args[0] << "\" "
       << "may not link to anything.";
@@ -80,7 +93,7 @@ bool cmTargetLinkLibrariesCommand::InitialPass(
     return true;
   }
 
-  if (this->Target->GetType() == cmState::UTILITY) {
+  if (this->Target->GetType() == cmStateEnums::UTILITY) {
     std::ostringstream e;
     const char* modal = CM_NULLPTR;
     cmake::MessageType messageType = cmake::AUTHOR_WARNING;
@@ -278,7 +291,7 @@ void cmTargetLinkLibrariesCommand::LinkLibraryTypeSpecifierWarning(int left,
 bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib,
                                                  cmTargetLinkLibraryType llt)
 {
-  if (this->Target->GetType() == cmState::INTERFACE_LIBRARY &&
+  if (this->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY &&
       this->CurrentProcessingState != ProcessingKeywordLinkInterface) {
     this->Makefile->IssueMessage(
       cmake::FATAL_ERROR,
@@ -338,7 +351,35 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib,
   // Handle normal case first.
   if (this->CurrentProcessingState != ProcessingKeywordLinkInterface &&
       this->CurrentProcessingState != ProcessingPlainLinkInterface) {
-    this->Makefile->AddLinkLibraryForTarget(this->Target->GetName(), lib, llt);
+
+    cmTarget* t =
+      this->Makefile->FindLocalNonAliasTarget(this->Target->GetName());
+    if (!t) {
+      std::ostringstream e;
+      e << "Attempt to add link library \"" << lib << "\" to target \""
+        << this->Target->GetName()
+        << "\" which is not built in this directory.";
+      this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
+    } else {
+
+      cmTarget* tgt = this->Makefile->GetGlobalGenerator()->FindTarget(lib);
+
+      if (tgt && (tgt->GetType() != cmStateEnums::STATIC_LIBRARY) &&
+          (tgt->GetType() != cmStateEnums::SHARED_LIBRARY) &&
+          (tgt->GetType() != cmStateEnums::INTERFACE_LIBRARY) &&
+          !tgt->IsExecutableWithExports()) {
+        std::ostringstream e;
+        e << "Target \"" << lib << "\" of type "
+          << cmState::GetTargetTypeName(tgt->GetType())
+          << " may not be linked into another target.  "
+          << "One may link only to STATIC or SHARED libraries, or "
+          << "to executables with the ENABLE_EXPORTS property set.";
+        this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
+      }
+
+      this->Target->AddLinkLibrary(*this->Makefile, lib, llt);
+    }
+
     if (this->CurrentProcessingState == ProcessingLinkLibraries) {
       this->Target->AppendProperty(
         "INTERFACE_LINK_LIBRARIES",
@@ -347,7 +388,7 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib,
     }
     if (this->CurrentProcessingState != ProcessingKeywordPublicInterface &&
         this->CurrentProcessingState != ProcessingPlainPublicInterface) {
-      if (this->Target->GetType() == cmState::STATIC_LIBRARY) {
+      if (this->Target->GetType() == cmStateEnums::STATIC_LIBRARY) {
         std::string configLib =
           this->Target->GetDebugGeneratorExpressions(lib, llt);
         if (cmGeneratorExpression::IsValidTargetName(lib) ||
@@ -375,7 +416,7 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib,
     return true;
   }
 
-  if (this->Target->GetType() == cmState::INTERFACE_LIBRARY) {
+  if (this->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
     return true;
   }
 
diff --git a/Source/cmTargetLinkLibrariesCommand.h b/Source/cmTargetLinkLibrariesCommand.h
index 85888f9..762b48f 100644
--- a/Source/cmTargetLinkLibrariesCommand.h
+++ b/Source/cmTargetLinkLibrariesCommand.h
@@ -3,7 +3,15 @@
 #ifndef cmTargetLinkLibrariesCommand_h
 #define cmTargetLinkLibrariesCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
+#include "cmTargetLinkLibraryType.h"
+
+class cmExecutionStatus;
+class cmTarget;
 
 /** \class cmTargetLinkLibrariesCommand
  * \brief Specify a list of libraries to link into executables.
@@ -32,8 +40,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "target_link_libraries"; }
 
-  cmTypeMacro(cmTargetLinkLibrariesCommand, cmCommand);
-
 private:
   void LinkLibraryTypeSpecifierWarning(int left, int right);
   static const char* LinkLibraryTypeNames[3];
diff --git a/Source/cmTargetPropCommandBase.cxx b/Source/cmTargetPropCommandBase.cxx
index a00360b..9a5c1da 100644
--- a/Source/cmTargetPropCommandBase.cxx
+++ b/Source/cmTargetPropCommandBase.cxx
@@ -3,6 +3,10 @@
 #include "cmTargetPropCommandBase.h"
 
 #include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmStateTypes.h"
+#include "cmTarget.h"
+#include "cmake.h"
 
 bool cmTargetPropCommandBase::HandleArguments(
   std::vector<std::string> const& args, const std::string& prop,
@@ -28,12 +32,12 @@ bool cmTargetPropCommandBase::HandleArguments(
     this->HandleMissingTarget(args[0]);
     return false;
   }
-  if ((this->Target->GetType() != cmState::SHARED_LIBRARY) &&
-      (this->Target->GetType() != cmState::STATIC_LIBRARY) &&
-      (this->Target->GetType() != cmState::OBJECT_LIBRARY) &&
-      (this->Target->GetType() != cmState::MODULE_LIBRARY) &&
-      (this->Target->GetType() != cmState::INTERFACE_LIBRARY) &&
-      (this->Target->GetType() != cmState::EXECUTABLE)) {
+  if ((this->Target->GetType() != cmStateEnums::SHARED_LIBRARY) &&
+      (this->Target->GetType() != cmStateEnums::STATIC_LIBRARY) &&
+      (this->Target->GetType() != cmStateEnums::OBJECT_LIBRARY) &&
+      (this->Target->GetType() != cmStateEnums::MODULE_LIBRARY) &&
+      (this->Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) &&
+      (this->Target->GetType() != cmStateEnums::EXECUTABLE)) {
     this->SetError("called with non-compilable target type");
     return false;
   }
@@ -86,7 +90,7 @@ bool cmTargetPropCommandBase::ProcessContentArgs(
     return false;
   }
 
-  if (this->Target->GetType() == cmState::INTERFACE_LIBRARY &&
+  if (this->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY &&
       scope != "INTERFACE") {
     this->SetError("may only be set INTERFACE properties on INTERFACE "
                    "targets");
diff --git a/Source/cmTargetPropCommandBase.h b/Source/cmTargetPropCommandBase.h
index de0a7d3..8b49653 100644
--- a/Source/cmTargetPropCommandBase.h
+++ b/Source/cmTargetPropCommandBase.h
@@ -3,6 +3,11 @@
 #ifndef cmTargetPropCommandBase_h
 #define cmTargetPropCommandBase_h
 
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
 class cmTarget;
@@ -21,8 +26,6 @@ public:
                        const std::string& prop,
                        ArgumentFlags flags = NO_FLAGS);
 
-  cmTypeMacro(cmTargetPropCommandBase, cmCommand);
-
 protected:
   std::string Property;
   cmTarget* Target;
diff --git a/Source/cmTargetPropertyComputer.cxx b/Source/cmTargetPropertyComputer.cxx
new file mode 100644
index 0000000..a57bc5a
--- /dev/null
+++ b/Source/cmTargetPropertyComputer.cxx
@@ -0,0 +1,92 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+
+#include "cmTargetPropertyComputer.h"
+
+#include <sstream>
+
+#include "cmMessenger.h"
+#include "cmPolicies.h"
+#include "cmStateSnapshot.h"
+#include "cm_unordered_set.hxx"
+#include "cmake.h"
+
+bool cmTargetPropertyComputer::HandleLocationPropertyPolicy(
+  std::string const& tgtName, cmMessenger* messenger,
+  cmListFileBacktrace const& context)
+{
+  std::ostringstream e;
+  const char* modal = CM_NULLPTR;
+  cmake::MessageType messageType = cmake::AUTHOR_WARNING;
+  switch (context.GetBottom().GetPolicy(cmPolicies::CMP0026)) {
+    case cmPolicies::WARN:
+      e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0026) << "\n";
+      modal = "should";
+    case cmPolicies::OLD:
+      break;
+    case cmPolicies::REQUIRED_ALWAYS:
+    case cmPolicies::REQUIRED_IF_USED:
+    case cmPolicies::NEW:
+      modal = "may";
+      messageType = cmake::FATAL_ERROR;
+  }
+
+  if (modal) {
+    e << "The LOCATION property " << modal << " not be read from target \""
+      << tgtName
+      << "\".  Use the target name directly with "
+         "add_custom_command, or use the generator expression $<TARGET_FILE>, "
+         "as appropriate.\n";
+    messenger->IssueMessage(messageType, e.str(), context);
+  }
+
+  return messageType != cmake::FATAL_ERROR;
+}
+
+bool cmTargetPropertyComputer::WhiteListedInterfaceProperty(
+  const std::string& prop)
+{
+  if (cmHasLiteralPrefix(prop, "INTERFACE_")) {
+    return true;
+  }
+  static CM_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 (builtIns.count(prop)) {
+    return true;
+  }
+
+  if (prop == "IMPORTED_CONFIGURATIONS" || prop == "IMPORTED_LIBNAME" ||
+      prop == "NO_SYSTEM_FROM_IMPORTED" ||
+      cmHasLiteralPrefix(prop, "IMPORTED_LIBNAME_") ||
+      cmHasLiteralPrefix(prop, "MAP_IMPORTED_CONFIG_")) {
+    return true;
+  }
+
+  return false;
+}
+
+bool cmTargetPropertyComputer::PassesWhitelist(
+  cmStateEnums::TargetType tgtType, std::string const& prop,
+  cmMessenger* messenger, cmListFileBacktrace const& context)
+{
+  if (tgtType == cmStateEnums::INTERFACE_LIBRARY &&
+      !WhiteListedInterfaceProperty(prop)) {
+    std::ostringstream e;
+    e << "INTERFACE_LIBRARY targets may only have whitelisted properties.  "
+         "The property \""
+      << prop << "\" is not allowed.";
+    messenger->IssueMessage(cmake::FATAL_ERROR, e.str(), context);
+    return false;
+  }
+  return true;
+}
diff --git a/Source/cmTargetPropertyComputer.h b/Source/cmTargetPropertyComputer.h
new file mode 100644
index 0000000..45d31be
--- /dev/null
+++ b/Source/cmTargetPropertyComputer.h
@@ -0,0 +1,110 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef cmTargetPropertyComputer_h
+#define cmTargetPropertyComputer_h
+
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <string>
+
+#include "cmAlgorithms.h"
+#include "cmListFileCache.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+
+class cmMessenger;
+
+class cmTargetPropertyComputer
+{
+public:
+  template <typename Target>
+  static const char* GetProperty(Target const* tgt, const std::string& prop,
+                                 cmMessenger* messenger,
+                                 cmListFileBacktrace const& context)
+  {
+    if (const char* loc = GetLocation(tgt, prop, messenger, context)) {
+      return loc;
+    }
+    if (cmSystemTools::GetFatalErrorOccured()) {
+      return CM_NULLPTR;
+    }
+    if (prop == "SOURCES") {
+      return GetSources(tgt, messenger, context);
+    }
+    return CM_NULLPTR;
+  }
+
+  static bool WhiteListedInterfaceProperty(const std::string& prop);
+
+  static bool PassesWhitelist(cmStateEnums::TargetType tgtType,
+                              std::string const& prop, cmMessenger* messenger,
+                              cmListFileBacktrace const& context);
+
+private:
+  static bool HandleLocationPropertyPolicy(std::string const& tgtName,
+                                           cmMessenger* messenger,
+                                           cmListFileBacktrace const& context);
+
+  template <typename Target>
+  static const char* ComputeLocationForBuild(Target const* tgt);
+  template <typename Target>
+  static const char* ComputeLocation(Target const* tgt,
+                                     std::string const& config);
+
+  template <typename Target>
+  static const char* GetLocation(Target const* tgt, std::string const& prop,
+                                 cmMessenger* messenger,
+                                 cmListFileBacktrace const& context)
+
+  {
+    // Watch for special "computed" properties that are dependent on
+    // other properties or variables.  Always recompute them.
+    if (tgt->GetType() == cmStateEnums::EXECUTABLE ||
+        tgt->GetType() == cmStateEnums::STATIC_LIBRARY ||
+        tgt->GetType() == cmStateEnums::SHARED_LIBRARY ||
+        tgt->GetType() == cmStateEnums::MODULE_LIBRARY ||
+        tgt->GetType() == cmStateEnums::UNKNOWN_LIBRARY) {
+      static const std::string propLOCATION = "LOCATION";
+      if (prop == propLOCATION) {
+        if (!tgt->IsImported() &&
+            !HandleLocationPropertyPolicy(tgt->GetName(), messenger,
+                                          context)) {
+          return CM_NULLPTR;
+        }
+        return ComputeLocationForBuild(tgt);
+      }
+
+      // Support "LOCATION_<CONFIG>".
+      if (cmHasLiteralPrefix(prop, "LOCATION_")) {
+        if (!tgt->IsImported() &&
+            !HandleLocationPropertyPolicy(tgt->GetName(), messenger,
+                                          context)) {
+          return CM_NULLPTR;
+        }
+        const char* configName = prop.c_str() + 9;
+        return ComputeLocation(tgt, configName);
+      }
+
+      // Support "<CONFIG>_LOCATION".
+      if (cmHasLiteralSuffix(prop, "_LOCATION") &&
+          !cmHasLiteralPrefix(prop, "XCODE_ATTRIBUTE_")) {
+        std::string configName(prop.c_str(), prop.size() - 9);
+        if (configName != "IMPORTED") {
+          if (!tgt->IsImported() &&
+              !HandleLocationPropertyPolicy(tgt->GetName(), messenger,
+                                            context)) {
+            return CM_NULLPTR;
+          }
+          return ComputeLocation(tgt, configName);
+        }
+      }
+    }
+    return CM_NULLPTR;
+  }
+
+  template <typename Target>
+  static const char* GetSources(Target const* tgt, cmMessenger* messenger,
+                                cmListFileBacktrace const& context);
+};
+
+#endif
diff --git a/Source/cmTargetSourcesCommand.cxx b/Source/cmTargetSourcesCommand.cxx
index 2170247..058659a 100644
--- a/Source/cmTargetSourcesCommand.cxx
+++ b/Source/cmTargetSourcesCommand.cxx
@@ -2,7 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTargetSourcesCommand.h"
 
-#include "cmGeneratorExpression.h"
+#include <sstream>
+
+#include "cmAlgorithms.h"
+#include "cmMakefile.h"
+#include "cmTarget.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 bool cmTargetSourcesCommand::InitialPass(std::vector<std::string> const& args,
                                          cmExecutionStatus&)
diff --git a/Source/cmTargetSourcesCommand.h b/Source/cmTargetSourcesCommand.h
index 8f88b25..b1afac2 100644
--- a/Source/cmTargetSourcesCommand.h
+++ b/Source/cmTargetSourcesCommand.h
@@ -3,8 +3,16 @@
 #ifndef cmTargetSourcesCommand_h
 #define cmTargetSourcesCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmTargetPropCommandBase.h"
 
+class cmCommand;
+class cmExecutionStatus;
+class cmTarget;
+
 class cmTargetSourcesCommand : public cmTargetPropCommandBase
 {
 public:
@@ -25,8 +33,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "target_sources"; }
 
-  cmTypeMacro(cmTargetSourcesCommand, cmTargetPropCommandBase);
-
 private:
   void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE;
   void HandleMissingTarget(const std::string& name) CM_OVERRIDE;
diff --git a/Source/cmTestGenerator.cxx b/Source/cmTestGenerator.cxx
index 3ea59cb..4164f3a 100644
--- a/Source/cmTestGenerator.cxx
+++ b/Source/cmTestGenerator.cxx
@@ -2,20 +2,19 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTestGenerator.h"
 
+#include <map>
+#include <ostream>
+#include <utility>
+
 #include "cmGeneratorExpression.h"
 #include "cmGeneratorTarget.h"
 #include "cmLocalGenerator.h"
 #include "cmOutputConverter.h"
 #include "cmProperty.h"
 #include "cmPropertyMap.h"
-#include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmTest.h"
-#include "cm_auto_ptr.hxx"
-
-#include <map>
-#include <ostream>
-#include <utility>
 
 cmTestGenerator::cmTestGenerator(
   cmTest* test, std::vector<std::string> const& configurations)
@@ -77,7 +76,7 @@ void cmTestGenerator::GenerateScriptForConfig(std::ostream& os,
   // be translated.
   std::string exe = command[0];
   cmGeneratorTarget* target = this->LG->FindGeneratorTargetToUse(exe);
-  if (target && target->GetType() == cmState::EXECUTABLE) {
+  if (target && target->GetType() == cmStateEnums::EXECUTABLE) {
     // Use the target file on disk.
     exe = target->GetFullPath(config);
 
diff --git a/Source/cmTimestamp.cxx b/Source/cmTimestamp.cxx
index 6a8c9c6..3d42e26 100644
--- a/Source/cmTimestamp.cxx
+++ b/Source/cmTimestamp.cxx
@@ -2,18 +2,27 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTimestamp.h"
 
-#include <cstdlib>
+#include <cmConfigure.h>
 #include <cstring>
 #include <sstream>
+#include <stdlib.h>
 
-#include <sys/types.h>
-// include sys/stat.h after sys/types.h
-#include <sys/stat.h>
+#include "cmSystemTools.h"
 
 std::string cmTimestamp::CurrentTime(const std::string& formatString,
                                      bool utcFlag)
 {
   time_t currentTimeT = time(CM_NULLPTR);
+  std::string source_date_epoch;
+  cmSystemTools::GetEnv("SOURCE_DATE_EPOCH", source_date_epoch);
+  if (!source_date_epoch.empty()) {
+    std::istringstream iss(source_date_epoch);
+    iss >> currentTimeT;
+    if (iss.fail() || !iss.eof()) {
+      cmSystemTools::Error("Cannot parse SOURCE_DATE_EPOCH as integer");
+      exit(27);
+    }
+  }
   if (currentTimeT == time_t(-1)) {
     return std::string();
   }
@@ -84,7 +93,7 @@ time_t cmTimestamp::CreateUtcTimeTFromTm(struct tm& tm) const
 #else
   // From Linux timegm() manpage.
 
-  std::string tz_old = "";
+  std::string tz_old;
   cmSystemTools::GetEnv("TZ", tz_old);
   tz_old = "TZ=" + tz_old;
 
@@ -127,6 +136,7 @@ std::string cmTimestamp::AddTimestampComponent(char flag,
     case 'w':
     case 'y':
     case 'Y':
+    case '%':
       break;
     case 's': // Seconds since UNIX epoch (midnight 1-jan-1970)
     {
diff --git a/Source/cmTimestamp.h b/Source/cmTimestamp.h
index 44e397b..fdee564 100644
--- a/Source/cmTimestamp.h
+++ b/Source/cmTimestamp.h
@@ -3,9 +3,7 @@
 #ifndef cmTimestamp_h
 #define cmTimestamp_h
 
-#include <cmConfigure.h>
-
-#include "cmStandardIncludes.h"
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <string>
 #include <time.h>
diff --git a/Source/cmTryCompileCommand.cxx b/Source/cmTryCompileCommand.cxx
index 933818e..b6bfbfa 100644
--- a/Source/cmTryCompileCommand.cxx
+++ b/Source/cmTryCompileCommand.cxx
@@ -2,6 +2,11 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTryCompileCommand.h"
 
+#include "cmMakefile.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
+
 // cmTryCompileCommand
 bool cmTryCompileCommand::InitialPass(std::vector<std::string> const& argv,
                                       cmExecutionStatus&)
diff --git a/Source/cmTryCompileCommand.h b/Source/cmTryCompileCommand.h
index 45d92df..52a0345 100644
--- a/Source/cmTryCompileCommand.h
+++ b/Source/cmTryCompileCommand.h
@@ -3,8 +3,15 @@
 #ifndef cmTryCompileCommand_h
 #define cmTryCompileCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCoreTryCompile.h"
 
+class cmCommand;
+class cmExecutionStatus;
+
 /** \class cmTryCompileCommand
  * \brief Specifies where to install some files
  *
@@ -29,8 +36,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "try_compile"; }
-
-  cmTypeMacro(cmTryCompileCommand, cmCoreTryCompile);
 };
 
 #endif
diff --git a/Source/cmTryRunCommand.cxx b/Source/cmTryRunCommand.cxx
index 5c9e41a..c4fc94e 100644
--- a/Source/cmTryRunCommand.cxx
+++ b/Source/cmTryRunCommand.cxx
@@ -2,8 +2,17 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmTryRunCommand.h"
 
-#include "cmTryCompileCommand.h"
 #include <cmsys/FStream.hxx>
+#include <stdio.h>
+#include <string.h>
+
+#include "cmMakefile.h"
+#include "cmState.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+class cmExecutionStatus;
 
 // cmTryRunCommand
 bool cmTryRunCommand::InitialPass(std::vector<std::string> const& argv,
@@ -77,8 +86,9 @@ bool cmTryRunCommand::InitialPass(std::vector<std::string> const& argv,
 
   // although they could be used together, don't allow it, because
   // using OUTPUT_VARIABLE makes crosscompiling harder
-  if (this->OutputVariable.size() && (!this->RunOutputVariable.empty() ||
-                                      !this->CompileOutputVariable.empty())) {
+  if (!this->OutputVariable.empty() &&
+      (!this->RunOutputVariable.empty() ||
+       !this->CompileOutputVariable.empty())) {
     cmSystemTools::Error(
       "You cannot use OUTPUT_VARIABLE together with COMPILE_OUTPUT_VARIABLE "
       "or RUN_OUTPUT_VARIABLE. Please use only COMPILE_OUTPUT_VARIABLE and/or "
@@ -189,7 +199,8 @@ void cmTryRunCommand::RunExecutable(const std::string& runArgs,
     strcpy(retChar, "FAILED_TO_RUN");
   }
   this->Makefile->AddCacheDefinition(this->RunResultVariable, retChar,
-                                     "Result of TRY_RUN", cmState::INTERNAL);
+                                     "Result of TRY_RUN",
+                                     cmStateEnums::INTERNAL);
 }
 
 /* This is only used when cross compiling. Instead of running the
@@ -231,7 +242,7 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
     comment += detailsString;
     this->Makefile->AddCacheDefinition(this->RunResultVariable,
                                        "PLEASE_FILL_OUT-FAILED_TO_RUN",
-                                       comment.c_str(), cmState::STRING);
+                                       comment.c_str(), cmStateEnums::STRING);
 
     cmState* state = this->Makefile->GetState();
     const char* existingValue =
@@ -254,9 +265,9 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
         "would have printed on stdout and stderr on its target platform.\n";
       comment += detailsString;
 
-      this->Makefile->AddCacheDefinition(internalRunOutputName,
-                                         "PLEASE_FILL_OUT-NOTFOUND",
-                                         comment.c_str(), cmState::STRING);
+      this->Makefile->AddCacheDefinition(
+        internalRunOutputName, "PLEASE_FILL_OUT-NOTFOUND", comment.c_str(),
+        cmStateEnums::STRING);
       cmState* state = this->Makefile->GetState();
       const char* existing = state->GetCacheEntryValue(internalRunOutputName);
       if (existing) {
diff --git a/Source/cmTryRunCommand.h b/Source/cmTryRunCommand.h
index b569b0b..8b44ac5 100644
--- a/Source/cmTryRunCommand.h
+++ b/Source/cmTryRunCommand.h
@@ -3,8 +3,15 @@
 #ifndef cmTryRunCommand_h
 #define cmTryRunCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCoreTryCompile.h"
 
+class cmCommand;
+class cmExecutionStatus;
+
 /** \class cmTryRunCommand
  * \brief Specifies where to install some files
  *
@@ -30,8 +37,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "try_run"; }
 
-  cmTypeMacro(cmTryRunCommand, cmCoreTryCompile);
-
 private:
   void RunExecutable(const std::string& runArgs,
                      std::string* runOutputContents);
diff --git a/Source/cmTypeMacro.h b/Source/cmTypeMacro.h
deleted file mode 100644
index b302ff1..0000000
--- a/Source/cmTypeMacro.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#ifndef cmTypeMacro_h
-#define cmTypeMacro_h
-
-// All subclasses of cmCommand or cmCTestGenericHandler should
-// invoke this macro.
-#define cmTypeMacro(thisClass, superclass)                                    \
-  const char* GetNameOfClass() CM_OVERRIDE { return #thisClass; }             \
-  typedef superclass Superclass;                                              \
-  static bool IsTypeOf(const char* type)                                      \
-  {                                                                           \
-    if (!strcmp(#thisClass, type)) {                                          \
-      return true;                                                            \
-    }                                                                         \
-    return Superclass::IsTypeOf(type);                                        \
-  }                                                                           \
-  bool IsA(const char* type) CM_OVERRIDE                                      \
-  {                                                                           \
-    return thisClass::IsTypeOf(type);                                         \
-  }                                                                           \
-  static thisClass* SafeDownCast(cmObject* c)                                 \
-  {                                                                           \
-    if (c && c->IsA(#thisClass)) {                                            \
-      return static_cast<thisClass*>(c);                                      \
-    }                                                                         \
-    return 0;                                                                 \
-  }                                                                           \
-  class cmTypeMacro_UseTrailingSemicolon
-
-#endif
diff --git a/Source/cmUnexpectedCommand.cxx b/Source/cmUnexpectedCommand.cxx
new file mode 100644
index 0000000..a8de9e6
--- /dev/null
+++ b/Source/cmUnexpectedCommand.cxx
@@ -0,0 +1,22 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmUnexpectedCommand.h"
+
+#include <stdlib.h>
+
+#include "cmMakefile.h"
+
+class cmExecutionStatus;
+
+bool cmUnexpectedCommand::InitialPass(std::vector<std::string> const&,
+                                      cmExecutionStatus&)
+{
+  const char* versionValue =
+    this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION");
+  if (this->Name == "endif" && (!versionValue || atof(versionValue) <= 1.4)) {
+    return true;
+  }
+
+  this->SetError(this->Error);
+  return false;
+}
diff --git a/Source/cmUnexpectedCommand.h b/Source/cmUnexpectedCommand.h
new file mode 100644
index 0000000..897dfb6
--- /dev/null
+++ b/Source/cmUnexpectedCommand.h
@@ -0,0 +1,40 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef cmUnexpectedCommand_h
+#define cmUnexpectedCommand_h
+
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
+#include "cmCommand.h"
+
+class cmExecutionStatus;
+
+class cmUnexpectedCommand : public cmCommand
+{
+public:
+  cmUnexpectedCommand(std::string const& name, const char* error)
+    : Name(name)
+    , Error(error)
+  {
+  }
+
+  cmCommand* Clone() CM_OVERRIDE
+  {
+    return new cmUnexpectedCommand(this->Name, this->Error);
+  }
+
+  bool InitialPass(std::vector<std::string> const& args,
+                   cmExecutionStatus& status) CM_OVERRIDE;
+
+  bool IsScriptable() const CM_OVERRIDE { return true; }
+
+  std::string GetName() const CM_OVERRIDE { return this->Name; }
+
+private:
+  std::string Name;
+  const char* Error;
+};
+
+#endif
diff --git a/Source/cmUnsetCommand.cxx b/Source/cmUnsetCommand.cxx
index 746c435..31525ba 100644
--- a/Source/cmUnsetCommand.cxx
+++ b/Source/cmUnsetCommand.cxx
@@ -2,6 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmUnsetCommand.h"
 
+#include <string.h>
+
+#include "cmAlgorithms.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmUnsetCommand
 bool cmUnsetCommand::InitialPass(std::vector<std::string> const& args,
                                  cmExecutionStatus&)
diff --git a/Source/cmUnsetCommand.h b/Source/cmUnsetCommand.h
index b3f045a..5b07202 100644
--- a/Source/cmUnsetCommand.h
+++ b/Source/cmUnsetCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmUnsetCommand_h
 #define cmUnsetCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmUnsetCommand
  * \brief Unset a CMAKE variable
  *
@@ -34,8 +40,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "unset"; }
-
-  cmTypeMacro(cmUnsetCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmUseMangledMesaCommand.cxx b/Source/cmUseMangledMesaCommand.cxx
index e2b6b1a..3e72d75 100644
--- a/Source/cmUseMangledMesaCommand.cxx
+++ b/Source/cmUseMangledMesaCommand.cxx
@@ -2,11 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmUseMangledMesaCommand.h"
 
-#include "cmSystemTools.h"
-
 #include <cmsys/FStream.hxx>
 #include <cmsys/RegularExpression.hxx>
 
+#include "cmPolicies.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 bool cmUseMangledMesaCommand::InitialPass(std::vector<std::string> const& args,
                                           cmExecutionStatus&)
 {
@@ -105,5 +108,5 @@ void cmUseMangledMesaCommand::CopyAndFullPathMesaHeader(const char* source,
   fin.close();
   fout.close();
   cmSystemTools::CopyFileIfDifferent(tempOutputFile.c_str(), outFile.c_str());
-  cmSystemTools::RemoveFile(tempOutputFile.c_str());
+  cmSystemTools::RemoveFile(tempOutputFile);
 }
diff --git a/Source/cmUseMangledMesaCommand.h b/Source/cmUseMangledMesaCommand.h
index a5fa146..9a49f94 100644
--- a/Source/cmUseMangledMesaCommand.h
+++ b/Source/cmUseMangledMesaCommand.h
@@ -3,12 +3,17 @@
 #ifndef cmUseMangledMesaCommand_h
 #define cmUseMangledMesaCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 class cmUseMangledMesaCommand : public cmCommand
 {
 public:
-  cmTypeMacro(cmUseMangledMesaCommand, cmCommand);
   cmCommand* Clone() CM_OVERRIDE { return new cmUseMangledMesaCommand; }
   bool InitialPass(std::vector<std::string> const& args,
                    cmExecutionStatus& status) CM_OVERRIDE;
diff --git a/Source/cmUtilitySourceCommand.cxx b/Source/cmUtilitySourceCommand.cxx
index 08ea21e..3b78abe 100644
--- a/Source/cmUtilitySourceCommand.cxx
+++ b/Source/cmUtilitySourceCommand.cxx
@@ -2,6 +2,16 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmUtilitySourceCommand.h"
 
+#include <string.h>
+
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmState.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmUtilitySourceCommand
 bool cmUtilitySourceCommand::InitialPass(std::vector<std::string> const& args,
                                          cmExecutionStatus&)
@@ -98,13 +108,13 @@ bool cmUtilitySourceCommand::InitialPass(std::vector<std::string> const& args,
   // Enter the value into the cache.
   this->Makefile->AddCacheDefinition(cacheEntry, utilityExecutable.c_str(),
                                      "Path to an internal program.",
-                                     cmState::FILEPATH);
+                                     cmStateEnums::FILEPATH);
   // add a value into the cache that maps from the
   // full path to the name of the project
   cmSystemTools::ConvertToUnixSlashes(utilityExecutable);
   this->Makefile->AddCacheDefinition(utilityExecutable, utilityName.c_str(),
                                      "Executable to project name.",
-                                     cmState::INTERNAL);
+                                     cmStateEnums::INTERNAL);
 
   return true;
 }
diff --git a/Source/cmUtilitySourceCommand.h b/Source/cmUtilitySourceCommand.h
index 6ee5f3e..849b966 100644
--- a/Source/cmUtilitySourceCommand.h
+++ b/Source/cmUtilitySourceCommand.h
@@ -3,12 +3,17 @@
 #ifndef cmUtilitySourceCommand_h
 #define cmUtilitySourceCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 class cmUtilitySourceCommand : public cmCommand
 {
 public:
-  cmTypeMacro(cmUtilitySourceCommand, cmCommand);
   cmCommand* Clone() CM_OVERRIDE { return new cmUtilitySourceCommand; }
   bool InitialPass(std::vector<std::string> const& args,
                    cmExecutionStatus& status) CM_OVERRIDE;
diff --git a/Source/cmUuid.cxx b/Source/cmUuid.cxx
index 904bcbb..201e1cc 100644
--- a/Source/cmUuid.cxx
+++ b/Source/cmUuid.cxx
@@ -2,9 +2,8 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmUuid.h"
 
-#include "cm_sha2.h"
+#include "cmCryptoHash.h"
 
-#include <cmsys/MD5.h>
 #include <string.h>
 
 cmUuid::cmUuid()
@@ -22,16 +21,12 @@ std::string cmUuid::FromMd5(std::vector<unsigned char> const& uuidNamespace,
   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()));
+  cmCryptoHash md5(cmCryptoHash::AlgoMD5);
+  md5.Initialize();
+  md5.Append(&hashInput[0], hashInput.size());
+  std::vector<unsigned char> digest = md5.Finalize();
 
-  unsigned char digest[16] = { 0 };
-  cmsysMD5_Finalize(md5, digest);
-
-  cmsysMD5_Delete(md5);
-
-  return this->FromDigest(digest, 3);
+  return this->FromDigest(&digest[0], 3);
 }
 
 std::string cmUuid::FromSha1(std::vector<unsigned char> const& uuidNamespace,
@@ -40,16 +35,12 @@ std::string cmUuid::FromSha1(std::vector<unsigned char> const& uuidNamespace,
   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;
+  cmCryptoHash sha1(cmCryptoHash::AlgoSHA1);
+  sha1.Initialize();
+  sha1.Append(&hashInput[0], hashInput.size());
+  std::vector<unsigned char> digest = sha1.Finalize();
 
-  return this->FromDigest(digest, 5);
+  return this->FromDigest(&digest[0], 5);
 }
 
 void cmUuid::CreateHashInput(std::vector<unsigned char> const& uuidNamespace,
diff --git a/Source/cmVS10CSharpFlagTable.h b/Source/cmVS10CSharpFlagTable.h
new file mode 100644
index 0000000..493ec2b
--- /dev/null
+++ b/Source/cmVS10CSharpFlagTable.h
@@ -0,0 +1,120 @@
+static cmVS7FlagTable cmVS10CSharpFlagTable[] = {
+  { "ProjectName", "out:", "", "", cmIDEFlagTable::UserValueRequired },
+
+  { "OutputType", "target:exe", "", "Exe", 0 },
+  { "OutputType", "target:winexe", "", "Winexe", 0 },
+  { "OutputType", "target:library", "", "Library", 0 },
+  { "OutputType", "target:module", "", "Module", 0 },
+
+  { "DocumentationFile", "doc", "", "", cmIDEFlagTable::UserValueRequired },
+
+  { "Platform", "platform:x86", "", "x86", 0 },
+  { "Platform", "platform:Itanium", "", "Itanium", 0 },
+  { "Platform", "platform:x64", "", "x64", 0 },
+  { "Platform", "platform:arm", "", "arm", 0 },
+  { "Platform", "platform:anycpu32bitpreferred", "", "anycpu32bitpreferred",
+    0 },
+  { "Platform", "platform:anycpu", "", "anycpu", 0 },
+
+  { "References", "reference:", "mit alias", "", 0 },
+  { "References", "reference:", "dateiliste", "", 0 },
+  { "AddModules", "addmodule:", "", "", cmIDEFlagTable::SemicolonAppendable },
+  { "", "link", "", "", 0 },
+
+  { "Win32Resource", "win32res", "", "", cmIDEFlagTable::UserValueRequired },
+  { "ApplicationIcon", "win32icon", "", "",
+    cmIDEFlagTable::UserValueRequired },
+
+  { "Win32Manifest", "win32manifest:", "", "true", 0 },
+
+  { "NoWin32Manifest", "nowin32manifest", "", "true", 0 },
+
+  { "DefineDebug", "debug", "", "true", cmIDEFlagTable::Continue },
+
+  { "DebugSymbols", "debug", "", "true", 0 },
+  { "DebugSymbols", "debug-", "", "false", 0 },
+  { "DebugSymbols", "debug+", "", "true", 0 },
+
+  { "DebugType", "debug:none", "", "none", 0 },
+  { "DebugType", "debug:full", "", "full", 0 },
+  { "DebugType", "debug:pdbonly", "", "pdbonly", 0 },
+
+  { "Optimize", "optimize", "", "true", 0 },
+  { "Optimize", "optimize-", "", "false", 0 },
+  { "Optimize", "optimize+", "", "true", 0 },
+
+  { "TreatWarningsAsErrors", "warnaserror", "", "true", 0 },
+  { "TreatWarningsAsErrors", "warnaserror-", "", "false", 0 },
+  { "TreatWarningsAsErrors", "warnaserror+", "", "true", 0 },
+
+  { "WarningsAsErrors", "warnaserror", "", "", 0 },
+  { "WarningsAsErrors", "warnaserror-", "", "", 0 },
+  { "WarningsAsErrors", "warnaserror+", "", "", 0 },
+
+  { "WarningLevel", "warn:0", "", "0", 0 },
+  { "WarningLevel", "warn:1", "", "1", 0 },
+  { "WarningLevel", "warn:2", "", "2", 0 },
+  { "WarningLevel", "warn:3", "", "3", 0 },
+  { "WarningLevel", "warn:4", "", "4", 0 },
+  { "DisabledWarnings", "nowarn", "", "", 0 },
+
+  { "CheckForOverflowUnderflow", "checked", "", "true", 0 },
+  { "CheckForOverflowUnderflow", "checked-", "", "false", 0 },
+  { "CheckForOverflowUnderflow", "checked+", "", "true", 0 },
+
+  { "AllowUnsafeBlocks", "unsafe", "", "true", 0 },
+  { "AllowUnsafeBlocks", "unsafe-", "", "false", 0 },
+  { "AllowUnsafeBlocks", "unsafe+", "", "true", 0 },
+
+  { "DefineConstants", "define:", "", "",
+    cmIDEFlagTable::SemicolonAppendable | cmIDEFlagTable::UserValue },
+
+  { "LangVersion", "langversion:ISO-1", "", "ISO-1", 0 },
+  { "LangVersion", "langversion:ISO-2", "", "ISO-2", 0 },
+  { "LangVersion", "langversion:3", "", "3", 0 },
+  { "LangVersion", "langversion:4", "", "4", 0 },
+  { "LangVersion", "langversion:5", "", "5", 0 },
+  { "LangVersion", "langversion:6", "", "6", 0 },
+  { "LangVersion", "langversion:default", "", "default", 0 },
+
+  { "DelaySign", "delaysign", "", "true", 0 },
+  { "DelaySign", "delaysign-", "", "false", 0 },
+  { "DelaySign", "delaysign+", "", "true", 0 },
+
+  { "AssemblyOriginatorKeyFile", "keyfile", "", "", 0 },
+
+  { "KeyContainerName", "keycontainer", "", "", 0 },
+
+  { "NoLogo", "nologo", "", "", 0 },
+
+  { "NoConfig", "noconfig", "", "true", 0 },
+
+  { "BaseAddress", "baseaddress:", "", "", 0 },
+
+  { "CodePage", "codepage", "", "", 0 },
+
+  { "Utf8Output", "utf8output", "", "", 0 },
+
+  { "MainEntryPoint", "main:", "", "", 0 },
+
+  { "GenerateFullPaths", "fullpaths", "", "true", 0 },
+
+  { "FileAlignment", "filealign", "", "", 0 },
+
+  { "PdbFile", "pdb:", "", "", 0 },
+
+  { "NoStandardLib", "nostdlib", "", "true", 0 },
+  { "NoStandardLib", "nostdlib-", "", "false", 0 },
+  { "NoStandardLib", "nostdlib+", "", "true", 0 },
+
+  { "SubsystemVersion", "subsystemversion", "", "", 0 },
+
+  { "AdditionalLibPaths", "lib:", "", "", 0 },
+
+  { "ErrorReport", "errorreport:none", "Do Not Send Report", "none", 0 },
+  { "ErrorReport", "errorreport:prompt", "Prompt Immediately", "prompt", 0 },
+  { "ErrorReport", "errorreport:queue", "Queue For Next Login", "queue", 0 },
+  { "ErrorReport", "errorreport:send", "Send Automatically", "send", 0 },
+
+  { 0, 0, 0, 0, 0 },
+};
diff --git a/Source/cmVS11CSharpFlagTable.h b/Source/cmVS11CSharpFlagTable.h
new file mode 100644
index 0000000..71870b6
--- /dev/null
+++ b/Source/cmVS11CSharpFlagTable.h
@@ -0,0 +1,120 @@
+static cmVS7FlagTable cmVS11CSharpFlagTable[] = {
+  { "ProjectName", "out:", "", "", cmIDEFlagTable::UserValueRequired },
+
+  { "OutputType", "target:exe", "", "Exe", 0 },
+  { "OutputType", "target:winexe", "", "Winexe", 0 },
+  { "OutputType", "target:library", "", "Library", 0 },
+  { "OutputType", "target:module", "", "Module", 0 },
+
+  { "DocumentationFile", "doc", "", "", cmIDEFlagTable::UserValueRequired },
+
+  { "Platform", "platform:x86", "", "x86", 0 },
+  { "Platform", "platform:Itanium", "", "Itanium", 0 },
+  { "Platform", "platform:x64", "", "x64", 0 },
+  { "Platform", "platform:arm", "", "arm", 0 },
+  { "Platform", "platform:anycpu32bitpreferred", "", "anycpu32bitpreferred",
+    0 },
+  { "Platform", "platform:anycpu", "", "anycpu", 0 },
+
+  { "References", "reference:", "mit alias", "", 0 },
+  { "References", "reference:", "dateiliste", "", 0 },
+  { "AddModules", "addmodule:", "", "", cmIDEFlagTable::SemicolonAppendable },
+  { "", "link", "", "", 0 },
+
+  { "Win32Resource", "win32res", "", "", cmIDEFlagTable::UserValueRequired },
+  { "ApplicationIcon", "win32icon", "", "",
+    cmIDEFlagTable::UserValueRequired },
+
+  { "Win32Manifest", "win32manifest:", "", "true", 0 },
+
+  { "NoWin32Manifest", "nowin32manifest", "", "true", 0 },
+
+  { "DefineDebug", "debug", "", "true", cmIDEFlagTable::Continue },
+
+  { "DebugSymbols", "debug", "", "true", 0 },
+  { "DebugSymbols", "debug-", "", "false", 0 },
+  { "DebugSymbols", "debug+", "", "true", 0 },
+
+  { "DebugType", "debug:none", "", "none", 0 },
+  { "DebugType", "debug:full", "", "full", 0 },
+  { "DebugType", "debug:pdbonly", "", "pdbonly", 0 },
+
+  { "Optimize", "optimize", "", "true", 0 },
+  { "Optimize", "optimize-", "", "false", 0 },
+  { "Optimize", "optimize+", "", "true", 0 },
+
+  { "TreatWarningsAsErrors", "warnaserror", "", "true", 0 },
+  { "TreatWarningsAsErrors", "warnaserror-", "", "false", 0 },
+  { "TreatWarningsAsErrors", "warnaserror+", "", "true", 0 },
+
+  { "WarningsAsErrors", "warnaserror", "", "", 0 },
+  { "WarningsAsErrors", "warnaserror-", "", "", 0 },
+  { "WarningsAsErrors", "warnaserror+", "", "", 0 },
+
+  { "WarningLevel", "warn:0", "", "0", 0 },
+  { "WarningLevel", "warn:1", "", "1", 0 },
+  { "WarningLevel", "warn:2", "", "2", 0 },
+  { "WarningLevel", "warn:3", "", "3", 0 },
+  { "WarningLevel", "warn:4", "", "4", 0 },
+  { "DisabledWarnings", "nowarn", "", "", 0 },
+
+  { "CheckForOverflowUnderflow", "checked", "", "true", 0 },
+  { "CheckForOverflowUnderflow", "checked-", "", "false", 0 },
+  { "CheckForOverflowUnderflow", "checked+", "", "true", 0 },
+
+  { "AllowUnsafeBlocks", "unsafe", "", "true", 0 },
+  { "AllowUnsafeBlocks", "unsafe-", "", "false", 0 },
+  { "AllowUnsafeBlocks", "unsafe+", "", "true", 0 },
+
+  { "DefineConstants", "define:", "", "",
+    cmIDEFlagTable::SemicolonAppendable | cmIDEFlagTable::UserValue },
+
+  { "LangVersion", "langversion:ISO-1", "", "ISO-1", 0 },
+  { "LangVersion", "langversion:ISO-2", "", "ISO-2", 0 },
+  { "LangVersion", "langversion:3", "", "3", 0 },
+  { "LangVersion", "langversion:4", "", "4", 0 },
+  { "LangVersion", "langversion:5", "", "5", 0 },
+  { "LangVersion", "langversion:6", "", "6", 0 },
+  { "LangVersion", "langversion:default", "", "default", 0 },
+
+  { "DelaySign", "delaysign", "", "true", 0 },
+  { "DelaySign", "delaysign-", "", "false", 0 },
+  { "DelaySign", "delaysign+", "", "true", 0 },
+
+  { "AssemblyOriginatorKeyFile", "keyfile", "", "", 0 },
+
+  { "KeyContainerName", "keycontainer", "", "", 0 },
+
+  { "NoLogo", "nologo", "", "", 0 },
+
+  { "NoConfig", "noconfig", "", "true", 0 },
+
+  { "BaseAddress", "baseaddress:", "", "", 0 },
+
+  { "CodePage", "codepage", "", "", 0 },
+
+  { "Utf8Output", "utf8output", "", "", 0 },
+
+  { "MainEntryPoint", "main:", "", "", 0 },
+
+  { "GenerateFullPaths", "fullpaths", "", "true", 0 },
+
+  { "FileAlignment", "filealign", "", "", 0 },
+
+  { "PdbFile", "pdb:", "", "", 0 },
+
+  { "NoStandardLib", "nostdlib", "", "true", 0 },
+  { "NoStandardLib", "nostdlib-", "", "false", 0 },
+  { "NoStandardLib", "nostdlib+", "", "true", 0 },
+
+  { "SubsystemVersion", "subsystemversion", "", "", 0 },
+
+  { "AdditionalLibPaths", "lib:", "", "", 0 },
+
+  { "ErrorReport", "errorreport:none", "Do Not Send Report", "none", 0 },
+  { "ErrorReport", "errorreport:prompt", "Prompt Immediately", "prompt", 0 },
+  { "ErrorReport", "errorreport:queue", "Queue For Next Login", "queue", 0 },
+  { "ErrorReport", "errorreport:send", "Send Automatically", "send", 0 },
+
+  { 0, 0, 0, 0, 0 },
+};
diff --git a/Source/cmVS12CSharpFlagTable.h b/Source/cmVS12CSharpFlagTable.h
new file mode 100644
index 0000000..f98b184
--- /dev/null
+++ b/Source/cmVS12CSharpFlagTable.h
@@ -0,0 +1,120 @@
+static cmVS7FlagTable cmVS12CSharpFlagTable[] = {
+  { "ProjectName", "out:", "", "", cmIDEFlagTable::UserValueRequired },
+
+  { "OutputType", "target:exe", "", "Exe", 0 },
+  { "OutputType", "target:winexe", "", "Winexe", 0 },
+  { "OutputType", "target:library", "", "Library", 0 },
+  { "OutputType", "target:module", "", "Module", 0 },
+
+  { "DocumentationFile", "doc", "", "", cmIDEFlagTable::UserValueRequired },
+
+  { "Platform", "platform:x86", "", "x86", 0 },
+  { "Platform", "platform:Itanium", "", "Itanium", 0 },
+  { "Platform", "platform:x64", "", "x64", 0 },
+  { "Platform", "platform:arm", "", "arm", 0 },
+  { "Platform", "platform:anycpu32bitpreferred", "", "anycpu32bitpreferred",
+    0 },
+  { "Platform", "platform:anycpu", "", "anycpu", 0 },
+
+  { "References", "reference:", "mit alias", "", 0 },
+  { "References", "reference:", "dateiliste", "", 0 },
+  { "AddModules", "addmodule:", "", "", cmIDEFlagTable::SemicolonAppendable },
+  { "", "link", "", "", 0 },
+
+  { "Win32Resource", "win32res", "", "", cmIDEFlagTable::UserValueRequired },
+  { "ApplicationIcon", "win32icon", "", "",
+    cmIDEFlagTable::UserValueRequired },
+
+  { "Win32Manifest", "win32manifest:", "", "true", 0 },
+
+  { "NoWin32Manifest", "nowin32manifest", "", "true", 0 },
+
+  { "DefineDebug", "debug", "", "true", cmIDEFlagTable::Continue },
+
+  { "DebugSymbols", "debug", "", "true", 0 },
+  { "DebugSymbols", "debug-", "", "false", 0 },
+  { "DebugSymbols", "debug+", "", "true", 0 },
+
+  { "DebugType", "debug:none", "", "none", 0 },
+  { "DebugType", "debug:full", "", "full", 0 },
+  { "DebugType", "debug:pdbonly", "", "pdbonly", 0 },
+
+  { "Optimize", "optimize", "", "true", 0 },
+  { "Optimize", "optimize-", "", "false", 0 },
+  { "Optimize", "optimize+", "", "true", 0 },
+
+  { "TreatWarningsAsErrors", "warnaserror", "", "true", 0 },
+  { "TreatWarningsAsErrors", "warnaserror-", "", "false", 0 },
+  { "TreatWarningsAsErrors", "warnaserror+", "", "true", 0 },
+
+  { "WarningsAsErrors", "warnaserror", "", "", 0 },
+  { "WarningsAsErrors", "warnaserror-", "", "", 0 },
+  { "WarningsAsErrors", "warnaserror+", "", "", 0 },
+
+  { "WarningLevel", "warn:0", "", "0", 0 },
+  { "WarningLevel", "warn:1", "", "1", 0 },
+  { "WarningLevel", "warn:2", "", "2", 0 },
+  { "WarningLevel", "warn:3", "", "3", 0 },
+  { "WarningLevel", "warn:4", "", "4", 0 },
+  { "DisabledWarnings", "nowarn", "", "", 0 },
+
+  { "CheckForOverflowUnderflow", "checked", "", "true", 0 },
+  { "CheckForOverflowUnderflow", "checked-", "", "false", 0 },
+  { "CheckForOverflowUnderflow", "checked+", "", "true", 0 },
+
+  { "AllowUnsafeBlocks", "unsafe", "", "true", 0 },
+  { "AllowUnsafeBlocks", "unsafe-", "", "false", 0 },
+  { "AllowUnsafeBlocks", "unsafe+", "", "true", 0 },
+
+  { "DefineConstants", "define:", "", "",
+    cmIDEFlagTable::SemicolonAppendable | cmIDEFlagTable::UserValue },
+
+  { "LangVersion", "langversion:ISO-1", "", "ISO-1", 0 },
+  { "LangVersion", "langversion:ISO-2", "", "ISO-2", 0 },
+  { "LangVersion", "langversion:3", "", "3", 0 },
+  { "LangVersion", "langversion:4", "", "4", 0 },
+  { "LangVersion", "langversion:5", "", "5", 0 },
+  { "LangVersion", "langversion:6", "", "6", 0 },
+  { "LangVersion", "langversion:default", "", "default", 0 },
+
+  { "DelaySign", "delaysign", "", "true", 0 },
+  { "DelaySign", "delaysign-", "", "false", 0 },
+  { "DelaySign", "delaysign+", "", "true", 0 },
+
+  { "AssemblyOriginatorKeyFile", "keyfile", "", "", 0 },
+
+  { "KeyContainerName", "keycontainer", "", "", 0 },
+
+  { "NoLogo", "nologo", "", "", 0 },
+
+  { "NoConfig", "noconfig", "", "true", 0 },
+
+  { "BaseAddress", "baseaddress:", "", "", 0 },
+
+  { "CodePage", "codepage", "", "", 0 },
+
+  { "Utf8Output", "utf8output", "", "", 0 },
+
+  { "MainEntryPoint", "main:", "", "", 0 },
+
+  { "GenerateFullPaths", "fullpaths", "", "true", 0 },
+
+  { "FileAlignment", "filealign", "", "", 0 },
+
+  { "PdbFile", "pdb:", "", "", 0 },
+
+  { "NoStandardLib", "nostdlib", "", "true", 0 },
+  { "NoStandardLib", "nostdlib-", "", "false", 0 },
+  { "NoStandardLib", "nostdlib+", "", "true", 0 },
+
+  { "SubsystemVersion", "subsystemversion", "", "", 0 },
+
+  { "AdditionalLibPaths", "lib:", "", "", 0 },
+
+  { "ErrorReport", "errorreport:none", "Do Not Send Report", "none", 0 },
+  { "ErrorReport", "errorreport:prompt", "Prompt Immediately", "prompt", 0 },
+  { "ErrorReport", "errorreport:queue", "Queue For Next Login", "queue", 0 },
+  { "ErrorReport", "errorreport:send", "Send Automatically", "send", 0 },
+
+  { 0, 0, 0, 0, 0 },
+};
diff --git a/Source/cmVS140CSharpFlagTable.h b/Source/cmVS140CSharpFlagTable.h
new file mode 100644
index 0000000..256c35f
--- /dev/null
+++ b/Source/cmVS140CSharpFlagTable.h
@@ -0,0 +1,120 @@
+static cmVS7FlagTable cmVS140CSharpFlagTable[] = {
+  { "ProjectName", "out:", "", "", cmIDEFlagTable::UserValueRequired },
+
+  { "OutputType", "target:exe", "", "Exe", 0 },
+  { "OutputType", "target:winexe", "", "Winexe", 0 },
+  { "OutputType", "target:library", "", "Library", 0 },
+  { "OutputType", "target:module", "", "Module", 0 },
+
+  { "DocumentationFile", "doc", "", "", cmIDEFlagTable::UserValueRequired },
+
+  { "Platform", "platform:x86", "", "x86", 0 },
+  { "Platform", "platform:Itanium", "", "Itanium", 0 },
+  { "Platform", "platform:x64", "", "x64", 0 },
+  { "Platform", "platform:arm", "", "arm", 0 },
+  { "Platform", "platform:anycpu32bitpreferred", "", "anycpu32bitpreferred",
+    0 },
+  { "Platform", "platform:anycpu", "", "anycpu", 0 },
+
+  { "References", "reference:", "mit alias", "", 0 },
+  { "References", "reference:", "dateiliste", "", 0 },
+  { "AddModules", "addmodule:", "", "", cmIDEFlagTable::SemicolonAppendable },
+  { "", "link", "", "", 0 },
+
+  { "Win32Resource", "win32res", "", "", cmIDEFlagTable::UserValueRequired },
+  { "ApplicationIcon", "win32icon", "", "",
+    cmIDEFlagTable::UserValueRequired },
+
+  { "Win32Manifest", "win32manifest:", "", "true", 0 },
+
+  { "NoWin32Manifest", "nowin32manifest", "", "true", 0 },
+
+  { "DefineDebug", "debug", "", "true", cmIDEFlagTable::Continue },
+
+  { "DebugSymbols", "debug", "", "true", 0 },
+  { "DebugSymbols", "debug-", "", "false", 0 },
+  { "DebugSymbols", "debug+", "", "true", 0 },
+
+  { "DebugType", "debug:none", "", "none", 0 },
+  { "DebugType", "debug:full", "", "full", 0 },
+  { "DebugType", "debug:pdbonly", "", "pdbonly", 0 },
+
+  { "Optimize", "optimize", "", "true", 0 },
+  { "Optimize", "optimize-", "", "false", 0 },
+  { "Optimize", "optimize+", "", "true", 0 },
+
+  { "TreatWarningsAsErrors", "warnaserror", "", "true", 0 },
+  { "TreatWarningsAsErrors", "warnaserror-", "", "false", 0 },
+  { "TreatWarningsAsErrors", "warnaserror+", "", "true", 0 },
+
+  { "WarningsAsErrors", "warnaserror", "", "", 0 },
+  { "WarningsAsErrors", "warnaserror-", "", "", 0 },
+  { "WarningsAsErrors", "warnaserror+", "", "", 0 },
+
+  { "WarningLevel", "warn:0", "", "0", 0 },
+  { "WarningLevel", "warn:1", "", "1", 0 },
+  { "WarningLevel", "warn:2", "", "2", 0 },
+  { "WarningLevel", "warn:3", "", "3", 0 },
+  { "WarningLevel", "warn:4", "", "4", 0 },
+  { "DisabledWarnings", "nowarn", "", "", 0 },
+
+  { "CheckForOverflowUnderflow", "checked", "", "true", 0 },
+  { "CheckForOverflowUnderflow", "checked-", "", "false", 0 },
+  { "CheckForOverflowUnderflow", "checked+", "", "true", 0 },
+
+  { "AllowUnsafeBlocks", "unsafe", "", "true", 0 },
+  { "AllowUnsafeBlocks", "unsafe-", "", "false", 0 },
+  { "AllowUnsafeBlocks", "unsafe+", "", "true", 0 },
+
+  { "DefineConstants", "define:", "", "",
+    cmIDEFlagTable::SemicolonAppendable | cmIDEFlagTable::UserValue },
+
+  { "LangVersion", "langversion:ISO-1", "", "ISO-1", 0 },
+  { "LangVersion", "langversion:ISO-2", "", "ISO-2", 0 },
+  { "LangVersion", "langversion:3", "", "3", 0 },
+  { "LangVersion", "langversion:4", "", "4", 0 },
+  { "LangVersion", "langversion:5", "", "5", 0 },
+  { "LangVersion", "langversion:6", "", "6", 0 },
+  { "LangVersion", "langversion:default", "", "default", 0 },
+
+  { "DelaySign", "delaysign", "", "true", 0 },
+  { "DelaySign", "delaysign-", "", "false", 0 },
+  { "DelaySign", "delaysign+", "", "true", 0 },
+
+  { "AssemblyOriginatorKeyFile", "keyfile", "", "", 0 },
+
+  { "KeyContainerName", "keycontainer", "", "", 0 },
+
+  { "NoLogo", "nologo", "", "", 0 },
+
+  { "NoConfig", "noconfig", "", "true", 0 },
+
+  { "BaseAddress", "baseaddress:", "", "", 0 },
+
+  { "CodePage", "codepage", "", "", 0 },
+
+  { "Utf8Output", "utf8output", "", "", 0 },
+
+  { "MainEntryPoint", "main:", "", "", 0 },
+
+  { "GenerateFullPaths", "fullpaths", "", "true", 0 },
+
+  { "FileAlignment", "filealign", "", "", 0 },
+
+  { "PdbFile", "pdb:", "", "", 0 },
+
+  { "NoStandardLib", "nostdlib", "", "true", 0 },
+  { "NoStandardLib", "nostdlib-", "", "false", 0 },
+  { "NoStandardLib", "nostdlib+", "", "true", 0 },
+
+  { "SubsystemVersion", "subsystemversion", "", "", 0 },
+
+  { "AdditionalLibPaths", "lib:", "", "", 0 },
+
+  { "ErrorReport", "errorreport:none", "Do Not Send Report", "none", 0 },
+  { "ErrorReport", "errorreport:prompt", "Prompt Immediately", "prompt", 0 },
+  { "ErrorReport", "errorreport:queue", "Queue For Next Login", "queue", 0 },
+  { "ErrorReport", "errorreport:send", "Send Automatically", "send", 0 },
+
+  { 0, 0, 0, 0, 0 },
+};
diff --git a/Source/cmVS141CSharpFlagTable.h b/Source/cmVS141CSharpFlagTable.h
new file mode 100644
index 0000000..8508581
--- /dev/null
+++ b/Source/cmVS141CSharpFlagTable.h
@@ -0,0 +1,120 @@
+static cmVS7FlagTable cmVS141CSharpFlagTable[] = {
+  { "ProjectName", "out:", "", "", cmIDEFlagTable::UserValueRequired },
+
+  { "OutputType", "target:exe", "", "Exe", 0 },
+  { "OutputType", "target:winexe", "", "Winexe", 0 },
+  { "OutputType", "target:library", "", "Library", 0 },
+  { "OutputType", "target:module", "", "Module", 0 },
+
+  { "DocumentationFile", "doc", "", "", cmIDEFlagTable::UserValueRequired },
+
+  { "Platform", "platform:x86", "", "x86", 0 },
+  { "Platform", "platform:Itanium", "", "Itanium", 0 },
+  { "Platform", "platform:x64", "", "x64", 0 },
+  { "Platform", "platform:arm", "", "arm", 0 },
+  { "Platform", "platform:anycpu32bitpreferred", "", "anycpu32bitpreferred",
+    0 },
+  { "Platform", "platform:anycpu", "", "anycpu", 0 },
+
+  { "References", "reference:", "mit alias", "", 0 },
+  { "References", "reference:", "dateiliste", "", 0 },
+  { "AddModules", "addmodule:", "", "", cmIDEFlagTable::SemicolonAppendable },
+  { "", "link", "", "", 0 },
+
+  { "Win32Resource", "win32res", "", "", cmIDEFlagTable::UserValueRequired },
+  { "ApplicationIcon", "win32icon", "", "",
+    cmIDEFlagTable::UserValueRequired },
+
+  { "Win32Manifest", "win32manifest:", "", "true", 0 },
+
+  { "NoWin32Manifest", "nowin32manifest", "", "true", 0 },
+
+  { "DefineDebug", "debug", "", "true", cmIDEFlagTable::Continue },
+
+  { "DebugSymbols", "debug", "", "true", 0 },
+  { "DebugSymbols", "debug-", "", "false", 0 },
+  { "DebugSymbols", "debug+", "", "true", 0 },
+
+  { "DebugType", "debug:none", "", "none", 0 },
+  { "DebugType", "debug:full", "", "full", 0 },
+  { "DebugType", "debug:pdbonly", "", "pdbonly", 0 },
+
+  { "Optimize", "optimize", "", "true", 0 },
+  { "Optimize", "optimize-", "", "false", 0 },
+  { "Optimize", "optimize+", "", "true", 0 },
+
+  { "TreatWarningsAsErrors", "warnaserror", "", "true", 0 },
+  { "TreatWarningsAsErrors", "warnaserror-", "", "false", 0 },
+  { "TreatWarningsAsErrors", "warnaserror+", "", "true", 0 },
+
+  { "WarningsAsErrors", "warnaserror", "", "", 0 },
+  { "WarningsAsErrors", "warnaserror-", "", "", 0 },
+  { "WarningsAsErrors", "warnaserror+", "", "", 0 },
+
+  { "WarningLevel", "warn:0", "", "0", 0 },
+  { "WarningLevel", "warn:1", "", "1", 0 },
+  { "WarningLevel", "warn:2", "", "2", 0 },
+  { "WarningLevel", "warn:3", "", "3", 0 },
+  { "WarningLevel", "warn:4", "", "4", 0 },
+  { "DisabledWarnings", "nowarn", "", "", 0 },
+
+  { "CheckForOverflowUnderflow", "checked", "", "true", 0 },
+  { "CheckForOverflowUnderflow", "checked-", "", "false", 0 },
+  { "CheckForOverflowUnderflow", "checked+", "", "true", 0 },
+
+  { "AllowUnsafeBlocks", "unsafe", "", "true", 0 },
+  { "AllowUnsafeBlocks", "unsafe-", "", "false", 0 },
+  { "AllowUnsafeBlocks", "unsafe+", "", "true", 0 },
+
+  { "DefineConstants", "define:", "", "",
+    cmIDEFlagTable::SemicolonAppendable | cmIDEFlagTable::UserValue },
+
+  { "LangVersion", "langversion:ISO-1", "", "ISO-1", 0 },
+  { "LangVersion", "langversion:ISO-2", "", "ISO-2", 0 },
+  { "LangVersion", "langversion:3", "", "3", 0 },
+  { "LangVersion", "langversion:4", "", "4", 0 },
+  { "LangVersion", "langversion:5", "", "5", 0 },
+  { "LangVersion", "langversion:6", "", "6", 0 },
+  { "LangVersion", "langversion:default", "", "default", 0 },
+
+  { "DelaySign", "delaysign", "", "true", 0 },
+  { "DelaySign", "delaysign-", "", "false", 0 },
+  { "DelaySign", "delaysign+", "", "true", 0 },
+
+  { "AssemblyOriginatorKeyFile", "keyfile", "", "", 0 },
+
+  { "KeyContainerName", "keycontainer", "", "", 0 },
+
+  { "NoLogo", "nologo", "", "", 0 },
+
+  { "NoConfig", "noconfig", "", "true", 0 },
+
+  { "BaseAddress", "baseaddress:", "", "", 0 },
+
+  { "CodePage", "codepage", "", "", 0 },
+
+  { "Utf8Output", "utf8output", "", "", 0 },
+
+  { "MainEntryPoint", "main:", "", "", 0 },
+
+  { "GenerateFullPaths", "fullpaths", "", "true", 0 },
+
+  { "FileAlignment", "filealign", "", "", 0 },
+
+  { "PdbFile", "pdb:", "", "", 0 },
+
+  { "NoStandardLib", "nostdlib", "", "true", 0 },
+  { "NoStandardLib", "nostdlib-", "", "false", 0 },
+  { "NoStandardLib", "nostdlib+", "", "true", 0 },
+
+  { "SubsystemVersion", "subsystemversion", "", "", 0 },
+
+  { "AdditionalLibPaths", "lib:", "", "", 0 },
+
+  { "ErrorReport", "errorreport:none", "Do Not Send Report", "none", 0 },
+  { "ErrorReport", "errorreport:prompt", "Prompt Immediately", "prompt", 0 },
+  { "ErrorReport", "errorreport:queue", "Queue For Next Login", "queue", 0 },
+  { "ErrorReport", "errorreport:send", "Send Automatically", "send", 0 },
+
+  { 0, 0, 0, 0, 0 },
+};
diff --git a/Source/cmVSSetupHelper.cxx b/Source/cmVSSetupHelper.cxx
new file mode 100644
index 0000000..c2ff664
--- /dev/null
+++ b/Source/cmVSSetupHelper.cxx
@@ -0,0 +1,366 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmVSSetupHelper.h"
+
+#ifndef VSSetupConstants
+#define VSSetupConstants
+/* clang-format off */
+const IID IID_ISetupConfiguration = {
+  0x42843719, 0xDB4C, 0x46C2,
+  { 0x8E, 0x7C, 0x64, 0xF1, 0x81, 0x6E, 0xFD, 0x5B }
+};
+const IID IID_ISetupConfiguration2 = {
+  0x26AAB78C, 0x4A60, 0x49D6,
+  { 0xAF, 0x3B, 0x3C, 0x35, 0xBC, 0x93, 0x36, 0x5D }
+};
+const IID IID_ISetupPackageReference = {
+  0xda8d8a16, 0xb2b6, 0x4487,
+  { 0xa2, 0xf1, 0x59, 0x4c, 0xcc, 0xcd, 0x6b, 0xf5 }
+};
+const IID IID_ISetupHelper = {
+  0x42b21b78, 0x6192, 0x463e,
+  { 0x87, 0xbf, 0xd5, 0x77, 0x83, 0x8f, 0x1d, 0x5c }
+};
+const IID IID_IEnumSetupInstances = {
+  0x6380BCFF, 0x41D3, 0x4B2E,
+  { 0x8B, 0x2E, 0xBF, 0x8A, 0x68, 0x10, 0xC8, 0x48 }
+};
+const IID IID_ISetupInstance2 = {
+  0x89143C9A, 0x05AF, 0x49B0,
+  { 0xB7, 0x17, 0x72, 0xE2, 0x18, 0xA2, 0x18, 0x5C }
+};
+const IID IID_ISetupInstance = {
+  0xB41463C3, 0x8866, 0x43B5,
+  { 0xBC, 0x33, 0x2B, 0x06, 0x76, 0xF7, 0xF4, 0x2E }
+};
+const CLSID CLSID_SetupConfiguration = {
+  0x177F0C4A, 0x1CD3, 0x4DE7,
+  { 0xA3, 0x2C, 0x71, 0xDB, 0xBB, 0x9F, 0xA3, 0x6D }
+};
+/* clang-format on */
+#endif
+
+const WCHAR* VCToolsetComponent =
+  L"Microsoft.VisualStudio.Component.VC.Tools.x86.x64";
+const WCHAR* Win10SDKComponent =
+  L"Microsoft.VisualStudio.Component.Windows10SDK";
+const WCHAR* Win81SDKComponent =
+  L"Microsoft.VisualStudio.Component.Windows81SDK";
+const WCHAR* ComponentType = L"Component";
+
+cmVSSetupAPIHelper::cmVSSetupAPIHelper()
+  : setupConfig(NULL)
+  , setupConfig2(NULL)
+  , setupHelper(NULL)
+  , initializationFailure(false)
+{
+  comInitialized = CoInitializeEx(NULL, 0);
+  if (SUCCEEDED(comInitialized)) {
+    Initialize();
+  } else {
+    initializationFailure = true;
+  }
+}
+
+cmVSSetupAPIHelper::~cmVSSetupAPIHelper()
+{
+  setupHelper = NULL;
+  setupConfig2 = NULL;
+  setupConfig = NULL;
+  if (SUCCEEDED(comInitialized))
+    CoUninitialize();
+}
+
+bool cmVSSetupAPIHelper::IsVS2017Installed()
+{
+  return this->EnumerateAndChooseVSInstance();
+}
+
+bool cmVSSetupAPIHelper::IsWin10SDKInstalled()
+{
+  return (this->EnumerateAndChooseVSInstance() &&
+          chosenInstanceInfo.IsWin10SDKInstalled);
+}
+
+bool cmVSSetupAPIHelper::IsWin81SDKInstalled()
+{
+  return (this->EnumerateAndChooseVSInstance() &&
+          chosenInstanceInfo.IsWin81SDKInstalled);
+}
+
+bool cmVSSetupAPIHelper::CheckInstalledComponent(
+  SmartCOMPtr<ISetupPackageReference> package, bool& bVCToolset,
+  bool& bWin10SDK, bool& bWin81SDK)
+{
+  bool ret = false;
+  bVCToolset = bWin10SDK = bWin81SDK = false;
+  SmartBSTR bstrId;
+  if (FAILED(package->GetId(&bstrId))) {
+    return ret;
+  }
+
+  SmartBSTR bstrType;
+  if (FAILED(package->GetType(&bstrType))) {
+    return ret;
+  }
+
+  std::wstring id = std::wstring(bstrId);
+  std::wstring type = std::wstring(bstrType);
+  if (id.compare(VCToolsetComponent) == 0 &&
+      type.compare(ComponentType) == 0) {
+    bVCToolset = true;
+    ret = true;
+  }
+
+  // Checks for any version of Win10 SDK. The version is appended at the end of
+  // the
+  // component name ex: Microsoft.VisualStudio.Component.Windows10SDK.10240
+  if (id.find(Win10SDKComponent) != std::wstring::npos &&
+      type.compare(ComponentType) == 0) {
+    bWin10SDK = true;
+    ret = true;
+  }
+
+  if (id.compare(Win81SDKComponent) == 0 && type.compare(ComponentType) == 0) {
+    bWin81SDK = true;
+    ret = true;
+  }
+
+  return ret;
+}
+
+// Gather additional info such as if VCToolset, WinSDKs are installed, location
+// of VS and version information.
+bool cmVSSetupAPIHelper::GetVSInstanceInfo(
+  SmartCOMPtr<ISetupInstance2> pInstance, VSInstanceInfo& vsInstanceInfo)
+{
+  bool isVCToolSetInstalled = false;
+  if (pInstance == NULL)
+    return false;
+
+  SmartBSTR bstrId;
+  if (SUCCEEDED(pInstance->GetInstanceId(&bstrId))) {
+    vsInstanceInfo.InstanceId = std::wstring(bstrId);
+  } else {
+    return false;
+  }
+
+  InstanceState state;
+  if (FAILED(pInstance->GetState(&state))) {
+    return false;
+  }
+
+  ULONGLONG ullVersion = 0;
+  SmartBSTR bstrVersion;
+  if (FAILED(pInstance->GetInstallationVersion(&bstrVersion))) {
+    return false;
+  } else {
+    vsInstanceInfo.Version = std::wstring(bstrVersion);
+    if (FAILED(setupHelper->ParseVersion(bstrVersion, &ullVersion))) {
+      vsInstanceInfo.ullVersion = 0;
+    } else {
+      vsInstanceInfo.ullVersion = ullVersion;
+    }
+  }
+
+  // Reboot may have been required before the installation path was created.
+  SmartBSTR bstrInstallationPath;
+  if ((eLocal & state) == eLocal) {
+    if (FAILED(pInstance->GetInstallationPath(&bstrInstallationPath))) {
+      return false;
+    } else {
+      vsInstanceInfo.VSInstallLocation = std::wstring(bstrInstallationPath);
+    }
+  }
+
+  // Reboot may have been required before the product package was registered
+  // (last).
+  if ((eRegistered & state) == eRegistered) {
+    SmartCOMPtr<ISetupPackageReference> product;
+    if (FAILED(pInstance->GetProduct(&product)) || !product) {
+      return false;
+    }
+
+    LPSAFEARRAY lpsaPackages;
+    if (FAILED(pInstance->GetPackages(&lpsaPackages)) ||
+        lpsaPackages == NULL) {
+      return false;
+    }
+
+    int lower = lpsaPackages->rgsabound[0].lLbound;
+    int upper = lpsaPackages->rgsabound[0].cElements + lower;
+
+    IUnknown** ppData = (IUnknown**)lpsaPackages->pvData;
+    for (int i = lower; i < upper; i++) {
+      SmartCOMPtr<ISetupPackageReference> package = NULL;
+      if (FAILED(ppData[i]->QueryInterface(IID_ISetupPackageReference,
+                                           (void**)&package)) ||
+          package == NULL)
+        continue;
+
+      bool vcToolsetInstalled = false, win10SDKInstalled = false,
+           win81SDkInstalled = false;
+      bool ret = CheckInstalledComponent(package, vcToolsetInstalled,
+                                         win10SDKInstalled, win81SDkInstalled);
+      if (ret) {
+        isVCToolSetInstalled |= vcToolsetInstalled;
+        vsInstanceInfo.IsWin10SDKInstalled |= win10SDKInstalled;
+        vsInstanceInfo.IsWin81SDKInstalled |= win81SDkInstalled;
+      }
+    }
+
+    SafeArrayDestroy(lpsaPackages);
+  }
+
+  return isVCToolSetInstalled;
+}
+
+bool cmVSSetupAPIHelper::GetVSInstanceInfo(std::string& vsInstallLocation)
+{
+  vsInstallLocation = "";
+  bool isInstalled = this->EnumerateAndChooseVSInstance();
+
+  if (isInstalled) {
+    std::string str(chosenInstanceInfo.VSInstallLocation.begin(),
+                    chosenInstanceInfo.VSInstallLocation.end());
+    vsInstallLocation = str;
+  }
+
+  return isInstalled;
+}
+
+bool cmVSSetupAPIHelper::EnumerateAndChooseVSInstance()
+{
+  bool isVSInstanceExists = false;
+  if (chosenInstanceInfo.VSInstallLocation.compare(L"") != 0) {
+    return true;
+  }
+
+  if (initializationFailure || setupConfig == NULL || setupConfig2 == NULL ||
+      setupHelper == NULL)
+    return false;
+
+  std::vector<VSInstanceInfo> vecVSInstances;
+  SmartCOMPtr<IEnumSetupInstances> enumInstances = NULL;
+  if (FAILED(
+        setupConfig2->EnumInstances((IEnumSetupInstances**)&enumInstances)) ||
+      !enumInstances) {
+    return false;
+  }
+
+  SmartCOMPtr<ISetupInstance> instance;
+  while (SUCCEEDED(enumInstances->Next(1, &instance, NULL)) && instance) {
+    SmartCOMPtr<ISetupInstance2> instance2 = NULL;
+    if (FAILED(
+          instance->QueryInterface(IID_ISetupInstance2, (void**)&instance2)) ||
+        !instance2) {
+      instance = NULL;
+      continue;
+    }
+
+    VSInstanceInfo instanceInfo;
+    bool isInstalled = GetVSInstanceInfo(instance2, instanceInfo);
+    instance = instance2 = NULL;
+
+    if (isInstalled) {
+      vecVSInstances.push_back(instanceInfo);
+    }
+  }
+
+  if (vecVSInstances.size() > 0) {
+    isVSInstanceExists = true;
+    int index = ChooseVSInstance(vecVSInstances);
+    chosenInstanceInfo = vecVSInstances[index];
+  }
+
+  return isVSInstanceExists;
+}
+
+int cmVSSetupAPIHelper::ChooseVSInstance(
+  const std::vector<VSInstanceInfo>& vecVSInstances)
+{
+  if (vecVSInstances.size() == 0)
+    return -1;
+
+  if (vecVSInstances.size() == 1)
+    return 0;
+
+  unsigned int chosenIndex = 0;
+  for (unsigned int i = 1; i < vecVSInstances.size(); i++) {
+    // If the current has Win10 SDK but not the chosen one, then choose the
+    // current VS instance
+    if (!vecVSInstances[chosenIndex].IsWin10SDKInstalled &&
+        vecVSInstances[i].IsWin10SDKInstalled) {
+      chosenIndex = i;
+      continue;
+    }
+
+    // If the chosen one has Win10 SDK but the current one is not, then look at
+    // the next VS instance even the current
+    // instance version may be higher
+    if (vecVSInstances[chosenIndex].IsWin10SDKInstalled &&
+        !vecVSInstances[i].IsWin10SDKInstalled) {
+      continue;
+    }
+
+    // If both chosen one and current one doesn't have Win10 SDK but the
+    // current one has Win8.1 SDK installed,
+    // then choose the current one
+    if (!vecVSInstances[chosenIndex].IsWin10SDKInstalled &&
+        !vecVSInstances[i].IsWin10SDKInstalled &&
+        !vecVSInstances[chosenIndex].IsWin81SDKInstalled &&
+        vecVSInstances[i].IsWin81SDKInstalled) {
+      chosenIndex = i;
+      continue;
+    }
+
+    // If there is no difference in WinSDKs then look for the highest version
+    // of installed VS
+    if ((vecVSInstances[chosenIndex].IsWin10SDKInstalled ==
+         vecVSInstances[i].IsWin10SDKInstalled) &&
+        (vecVSInstances[chosenIndex].IsWin81SDKInstalled ==
+         vecVSInstances[i].IsWin81SDKInstalled) &&
+        vecVSInstances[chosenIndex].Version < vecVSInstances[i].Version) {
+      chosenIndex = i;
+      continue;
+    }
+  }
+
+  return chosenIndex;
+}
+
+bool cmVSSetupAPIHelper::Initialize()
+{
+  if (initializationFailure)
+    return false;
+
+  if (FAILED(comInitialized)) {
+    initializationFailure = true;
+    return false;
+  }
+
+  if (FAILED(setupConfig.CoCreateInstance(CLSID_SetupConfiguration, NULL,
+                                          IID_ISetupConfiguration,
+                                          CLSCTX_INPROC_SERVER)) ||
+      setupConfig == NULL) {
+    initializationFailure = true;
+    return false;
+  }
+
+  if (FAILED(setupConfig.QueryInterface(IID_ISetupConfiguration2,
+                                        (void**)&setupConfig2)) ||
+      setupConfig2 == NULL) {
+    initializationFailure = true;
+    return false;
+  }
+
+  if (FAILED(
+        setupConfig.QueryInterface(IID_ISetupHelper, (void**)&setupHelper)) ||
+      setupHelper == NULL) {
+    initializationFailure = true;
+    return false;
+  }
+
+  initializationFailure = false;
+  return true;
+}
diff --git a/Source/cmVSSetupHelper.h b/Source/cmVSSetupHelper.h
new file mode 100644
index 0000000..d2f514c
--- /dev/null
+++ b/Source/cmVSSetupHelper.h
@@ -0,0 +1,154 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef cmVSSetupHelper_h
+#define cmVSSetupHelper_h
+
+#ifndef NOMINMAX
+#define NOMINMAX // Undefine min and max defined by windows.h
+#endif
+
+// Published by Visual Studio Setup team
+#include "cmvssetup/Setup.Configuration.h"
+
+#include <string>
+#include <vector>
+
+#include <windows.h>
+
+template <class T>
+class SmartCOMPtr
+{
+public:
+  SmartCOMPtr() { ptr = NULL; }
+  SmartCOMPtr(T* p)
+  {
+    ptr = p;
+    if (ptr != NULL)
+      ptr->AddRef();
+  }
+  SmartCOMPtr(const SmartCOMPtr<T>& sptr)
+  {
+    ptr = sptr.ptr;
+    if (ptr != NULL)
+      ptr->AddRef();
+  }
+  T** operator&() { return &ptr; }
+  T* operator->() { return ptr; }
+  T* operator=(T* p)
+  {
+    if (*this != p) {
+      ptr = p;
+      if (ptr != NULL)
+        ptr->AddRef();
+    }
+    return *this;
+  }
+  operator T*() const { return ptr; }
+  template <class I>
+  HRESULT QueryInterface(REFCLSID rclsid, I** pp)
+  {
+    if (pp != NULL) {
+      return ptr->QueryInterface(rclsid, (void**)pp);
+    } else {
+      return E_FAIL;
+    }
+  }
+  HRESULT CoCreateInstance(REFCLSID clsid, IUnknown* pUnknown,
+                           REFIID interfaceId, DWORD dwClsContext = CLSCTX_ALL)
+  {
+    HRESULT hr = ::CoCreateInstance(clsid, pUnknown, dwClsContext, interfaceId,
+                                    (void**)&ptr);
+    return hr;
+  }
+  ~SmartCOMPtr()
+  {
+    if (ptr != NULL)
+      ptr->Release();
+  }
+
+private:
+  T* ptr;
+};
+
+class SmartBSTR
+{
+public:
+  SmartBSTR() { str = NULL; }
+  SmartBSTR(const SmartBSTR& src)
+  {
+    if (src.str != NULL) {
+      str = ::SysAllocStringByteLen((char*)str, ::SysStringByteLen(str));
+    } else {
+      str = ::SysAllocStringByteLen(NULL, 0);
+    }
+  }
+  SmartBSTR& operator=(const SmartBSTR& src)
+  {
+    if (str != src.str) {
+      ::SysFreeString(str);
+      if (src.str != NULL) {
+        str = ::SysAllocStringByteLen((char*)str, ::SysStringByteLen(str));
+      } else {
+        str = ::SysAllocStringByteLen(NULL, 0);
+      }
+    }
+    return *this;
+  }
+  operator BSTR() const { return str; }
+  BSTR* operator&() throw() { return &str; }
+  ~SmartBSTR() throw() { ::SysFreeString(str); }
+private:
+  BSTR str;
+};
+
+struct VSInstanceInfo
+{
+  std::wstring InstanceId;
+  std::wstring VSInstallLocation;
+  std::wstring Version;
+  ULONGLONG ullVersion;
+  bool IsWin10SDKInstalled;
+  bool IsWin81SDKInstalled;
+
+  VSInstanceInfo()
+  {
+    InstanceId = VSInstallLocation = Version = L"";
+    ullVersion = 0;
+    IsWin10SDKInstalled = IsWin81SDKInstalled = false;
+  }
+};
+
+class cmVSSetupAPIHelper
+{
+public:
+  cmVSSetupAPIHelper();
+  ~cmVSSetupAPIHelper();
+
+  bool IsVS2017Installed();
+  bool GetVSInstanceInfo(std::string& vsInstallLocation);
+  bool IsWin10SDKInstalled();
+  bool IsWin81SDKInstalled();
+
+private:
+  bool Initialize();
+  bool GetVSInstanceInfo(SmartCOMPtr<ISetupInstance2> instance2,
+                         VSInstanceInfo& vsInstanceInfo);
+  bool CheckInstalledComponent(SmartCOMPtr<ISetupPackageReference> package,
+                               bool& bVCToolset, bool& bWin10SDK,
+                               bool& bWin81SDK);
+  int ChooseVSInstance(const std::vector<VSInstanceInfo>& vecVSInstances);
+  bool EnumerateAndChooseVSInstance();
+
+  // COM ptrs to query about VS instances
+  SmartCOMPtr<ISetupConfiguration> setupConfig;
+  SmartCOMPtr<ISetupConfiguration2> setupConfig2;
+  SmartCOMPtr<ISetupHelper> setupHelper;
+  // used to indicate failure in Initialize(), so we don't have to call again
+  bool initializationFailure;
+  // indicated if COM initialization is successful
+  HRESULT comInitialized;
+  // current best instance of VS selected
+  VSInstanceInfo chosenInstanceInfo;
+};
+
+#endif
diff --git a/Source/cmVariableRequiresCommand.cxx b/Source/cmVariableRequiresCommand.cxx
index 7599551..1eb1f20 100644
--- a/Source/cmVariableRequiresCommand.cxx
+++ b/Source/cmVariableRequiresCommand.cxx
@@ -2,7 +2,12 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmVariableRequiresCommand.h"
 
+#include "cmMakefile.h"
+#include "cmPolicies.h"
 #include "cmState.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
 
 // cmLibraryCommand
 bool cmVariableRequiresCommand::InitialPass(
diff --git a/Source/cmVariableRequiresCommand.h b/Source/cmVariableRequiresCommand.h
index e40151b..baf717c 100644
--- a/Source/cmVariableRequiresCommand.h
+++ b/Source/cmVariableRequiresCommand.h
@@ -3,12 +3,17 @@
 #ifndef cmVariableRequiresCommand_h
 #define cmVariableRequiresCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 class cmVariableRequiresCommand : public cmCommand
 {
 public:
-  cmTypeMacro(cmVariableRequiresCommand, cmCommand);
   cmCommand* Clone() CM_OVERRIDE { return new cmVariableRequiresCommand; }
   bool InitialPass(std::vector<std::string> const& args,
                    cmExecutionStatus& status) CM_OVERRIDE;
diff --git a/Source/cmVariableWatchCommand.cxx b/Source/cmVariableWatchCommand.cxx
index 5c1e00a..90b0b28 100644
--- a/Source/cmVariableWatchCommand.cxx
+++ b/Source/cmVariableWatchCommand.cxx
@@ -2,7 +2,14 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmVariableWatchCommand.h"
 
+#include <sstream>
+
+#include "cmExecutionStatus.h"
+#include "cmListFileCache.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
 #include "cmVariableWatch.h"
+#include "cmake.h"
 
 struct cmVariableWatchCallbackData
 {
diff --git a/Source/cmVariableWatchCommand.h b/Source/cmVariableWatchCommand.h
index b1862f0..919bac4 100644
--- a/Source/cmVariableWatchCommand.h
+++ b/Source/cmVariableWatchCommand.h
@@ -3,8 +3,15 @@
 #ifndef cmVariableWatchCommand_h
 #define cmVariableWatchCommand_h
 
+#include <cmConfigure.h>
+#include <set>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmVariableWatchCommand
  * \brief Watch when the variable changes and invoke command
  *
@@ -44,8 +51,6 @@ public:
    */
   std::string GetName() const CM_OVERRIDE { return "variable_watch"; }
 
-  cmTypeMacro(cmVariableWatchCommand, cmCommand);
-
 protected:
   std::set<std::string> WatchedVariables;
 };
diff --git a/Source/cmVisualStudio10TargetGenerator.cxx b/Source/cmVisualStudio10TargetGenerator.cxx
index 82f4b99..902fe03 100644
--- a/Source/cmVisualStudio10TargetGenerator.cxx
+++ b/Source/cmVisualStudio10TargetGenerator.cxx
@@ -10,27 +10,6 @@
 #include "cmLocalVisualStudio7Generator.h"
 #include "cmMakefile.h"
 #include "cmSourceFile.h"
-#include "cmVS10CLFlagTable.h"
-#include "cmVS10LibFlagTable.h"
-#include "cmVS10LinkFlagTable.h"
-#include "cmVS10MASMFlagTable.h"
-#include "cmVS10RCFlagTable.h"
-#include "cmVS11CLFlagTable.h"
-#include "cmVS11LibFlagTable.h"
-#include "cmVS11LinkFlagTable.h"
-#include "cmVS11MASMFlagTable.h"
-#include "cmVS11RCFlagTable.h"
-#include "cmVS12CLFlagTable.h"
-#include "cmVS12LibFlagTable.h"
-#include "cmVS12LinkFlagTable.h"
-#include "cmVS12MASMFlagTable.h"
-#include "cmVS12RCFlagTable.h"
-#include "cmVS140CLFlagTable.h"
-#include "cmVS141CLFlagTable.h"
-#include "cmVS14LibFlagTable.h"
-#include "cmVS14LinkFlagTable.h"
-#include "cmVS14MASMFlagTable.h"
-#include "cmVS14RCFlagTable.h"
 #include "cmVisualStudioGeneratorOptions.h"
 #include "windows.h"
 
@@ -38,102 +17,6 @@
 
 static std::string const kWINDOWS_7_1_SDK = "Windows7.1SDK";
 
-cmIDEFlagTable const* cmVisualStudio10TargetGenerator::GetClFlagTable() const
-{
-  if (this->MSTools) {
-    cmGlobalVisualStudioGenerator::VSVersion v =
-      this->LocalGenerator->GetVersion();
-    if (v >= cmGlobalVisualStudioGenerator::VS14) {
-      // FIXME: All flag table selection should be based on the toolset name.
-      // See issue #16153.  For now, treat VS 15's toolset as a special case.
-      const char* toolset = this->GlobalGenerator->GetPlatformToolset();
-      if (toolset && cmHasLiteralPrefix(toolset, "v141")) {
-        return cmVS141CLFlagTable;
-      }
-      return cmVS140CLFlagTable;
-    } else if (v >= cmGlobalVisualStudioGenerator::VS12) {
-      return cmVS12CLFlagTable;
-    } else if (v == cmGlobalVisualStudioGenerator::VS11) {
-      return cmVS11CLFlagTable;
-    } else {
-      return cmVS10CLFlagTable;
-    }
-  }
-  return 0;
-}
-
-cmIDEFlagTable const* cmVisualStudio10TargetGenerator::GetRcFlagTable() const
-{
-  if (this->MSTools) {
-    cmGlobalVisualStudioGenerator::VSVersion v =
-      this->LocalGenerator->GetVersion();
-    if (v >= cmGlobalVisualStudioGenerator::VS14) {
-      return cmVS14RCFlagTable;
-    } else if (v >= cmGlobalVisualStudioGenerator::VS12) {
-      return cmVS12RCFlagTable;
-    } else if (v == cmGlobalVisualStudioGenerator::VS11) {
-      return cmVS11RCFlagTable;
-    } else {
-      return cmVS10RCFlagTable;
-    }
-  }
-  return 0;
-}
-
-cmIDEFlagTable const* cmVisualStudio10TargetGenerator::GetLibFlagTable() const
-{
-  if (this->MSTools) {
-    cmGlobalVisualStudioGenerator::VSVersion v =
-      this->LocalGenerator->GetVersion();
-    if (v >= cmGlobalVisualStudioGenerator::VS14) {
-      return cmVS14LibFlagTable;
-    } else if (v >= cmGlobalVisualStudioGenerator::VS12) {
-      return cmVS12LibFlagTable;
-    } else if (v == cmGlobalVisualStudioGenerator::VS11) {
-      return cmVS11LibFlagTable;
-    } else {
-      return cmVS10LibFlagTable;
-    }
-  }
-  return 0;
-}
-
-cmIDEFlagTable const* cmVisualStudio10TargetGenerator::GetLinkFlagTable() const
-{
-  if (this->MSTools) {
-    cmGlobalVisualStudioGenerator::VSVersion v =
-      this->LocalGenerator->GetVersion();
-    if (v >= cmGlobalVisualStudioGenerator::VS14) {
-      return cmVS14LinkFlagTable;
-    } else if (v >= cmGlobalVisualStudioGenerator::VS12) {
-      return cmVS12LinkFlagTable;
-    } else if (v == cmGlobalVisualStudioGenerator::VS11) {
-      return cmVS11LinkFlagTable;
-    } else {
-      return cmVS10LinkFlagTable;
-    }
-  }
-  return 0;
-}
-
-cmIDEFlagTable const* cmVisualStudio10TargetGenerator::GetMasmFlagTable() const
-{
-  if (this->MSTools) {
-    cmGlobalVisualStudioGenerator::VSVersion v =
-      this->LocalGenerator->GetVersion();
-    if (v >= cmGlobalVisualStudioGenerator::VS14) {
-      return cmVS14MASMFlagTable;
-    } else if (v >= cmGlobalVisualStudioGenerator::VS12) {
-      return cmVS12MASMFlagTable;
-    } else if (v == cmGlobalVisualStudioGenerator::VS11) {
-      return cmVS11MASMFlagTable;
-    } else {
-      return cmVS10MASMFlagTable;
-    }
-  }
-  return 0;
-}
-
 static std::string cmVS10EscapeXML(std::string arg)
 {
   cmSystemTools::ReplaceString(arg, "&", "&");
@@ -170,6 +53,22 @@ static std::string cmVS10EscapeComment(std::string comment)
   return echoable;
 }
 
+static bool cmVS10IsTargetsFile(std::string const& path)
+{
+  std::string const ext = cmSystemTools::GetFilenameLastExtension(path);
+  return cmSystemTools::Strucmp(ext.c_str(), ".targets") == 0;
+}
+
+static std::string computeProjectFileExtension(cmGeneratorTarget const* t)
+{
+  std::string res;
+  res = ".vcxproj";
+  if (cmGlobalVisualStudioGenerator::TargetIsCSharpOnly(t)) {
+    res = ".csproj";
+  }
+  return res;
+}
+
 cmVisualStudio10TargetGenerator::cmVisualStudio10TargetGenerator(
   cmGeneratorTarget* target, cmGlobalVisualStudio10Generator* gg)
 {
@@ -190,12 +89,16 @@ cmVisualStudio10TargetGenerator::cmVisualStudio10TargetGenerator(
          &this->NsightTegraVersion[0], &this->NsightTegraVersion[1],
          &this->NsightTegraVersion[2], &this->NsightTegraVersion[3]);
   this->MSTools = !this->NsightTegra;
+  this->Managed = false;
   this->TargetCompileAsWinRT = false;
   this->BuildFileStream = 0;
   this->IsMissingFiles = false;
   this->DefaultArtifactDir =
     this->LocalGenerator->GetCurrentBinaryDirectory() + std::string("/") +
     this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
+  this->InSourceBuild =
+    (strcmp(this->Makefile->GetCurrentSourceDirectory(),
+            this->Makefile->GetCurrentBinaryDirectory()) == 0);
 }
 
 cmVisualStudio10TargetGenerator::~cmVisualStudio10TargetGenerator()
@@ -212,7 +115,7 @@ cmVisualStudio10TargetGenerator::~cmVisualStudio10TargetGenerator()
     return;
   }
   if (this->BuildFileStream->Close()) {
-    this->GlobalGenerator->FileReplacedDuringGenerate(this->PathToVcxproj);
+    this->GlobalGenerator->FileReplacedDuringGenerate(this->PathToProjectFile);
   }
   delete this->BuildFileStream;
 }
@@ -227,9 +130,19 @@ void cmVisualStudio10TargetGenerator::WritePlatformConfigTag(
   }
   stream->fill(' ');
   stream->width(indentLevel * 2);
-  (*stream) << "";
-  (*stream) << "<" << tag << " Condition=\"'$(Configuration)|$(Platform)'=='";
-  (*stream) << config << "|" << this->Platform << "'\"";
+  (*stream) << ""; // applies indentation
+  (*stream) << "<" << tag << " Condition=\"";
+  (*stream) << "'$(Configuration)|$(Platform)'=='";
+  (*stream) << config << "|" << this->Platform;
+  (*stream) << "'";
+  // handle special case for 32 bit C# targets
+  if (csproj == this->ProjectType && this->Platform == "Win32") {
+    (*stream) << " Or ";
+    (*stream) << "'$(Configuration)|$(Platform)'=='";
+    (*stream) << config << "|x86";
+    (*stream) << "'";
+  }
+  (*stream) << "\"";
   if (attribute) {
     (*stream) << attribute;
   }
@@ -250,21 +163,42 @@ void cmVisualStudio10TargetGenerator::WriteString(const char* line,
   (*this->BuildFileStream) << line;
 }
 
-#define VS10_USER_PROPS "$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props"
+#define VS10_CXX_DEFAULT_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.Default.props"
+#define VS10_CXX_PROPS "$(VCTargetsPath)\\Microsoft.Cpp.props"
+#define VS10_CXX_USER_PROPS                                                   \
+  "$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props"
+#define VS10_CXX_TARGETS "$(VCTargetsPath)\\Microsoft.Cpp.targets"
+
+#define VS10_CSharp_DEFAULT_PROPS                                             \
+  "$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props"
+// This does not seem to exist by default, it's just provided for consistency
+// in case users want to have default custom props for C# targets
+#define VS10_CSharp_USER_PROPS                                                \
+  "$(UserRootDir)\\Microsoft.CSharp.$(Platform).user.props"
+#define VS10_CSharp_TARGETS "$(MSBuildToolsPath)\\Microsoft.CSharp.targets"
 
 void cmVisualStudio10TargetGenerator::Generate()
 {
   // do not generate external ms projects
-  if (this->GeneratorTarget->GetType() == cmState::INTERFACE_LIBRARY ||
+  if (this->GeneratorTarget->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
       this->GeneratorTarget->GetProperty("EXTERNAL_MSPROJECT")) {
     return;
   }
+  this->ProjectFileExtension =
+    computeProjectFileExtension(this->GeneratorTarget);
+  if (this->ProjectFileExtension == ".vcxproj") {
+    this->ProjectType = vcxproj;
+    this->Managed = false;
+  } else if (this->ProjectFileExtension == ".csproj") {
+    this->ProjectType = csproj;
+    this->Managed = true;
+  }
   // Tell the global generator the name of the project file
   this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME",
                                              this->Name.c_str());
-  this->GeneratorTarget->Target->SetProperty("GENERATOR_FILE_NAME_EXT",
-                                             ".vcxproj");
-  if (this->GeneratorTarget->GetType() <= cmState::OBJECT_LIBRARY) {
+  this->GeneratorTarget->Target->SetProperty(
+    "GENERATOR_FILE_NAME_EXT", this->ProjectFileExtension.c_str());
+  if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
     if (!this->ComputeClOptions()) {
       return;
     }
@@ -277,13 +211,16 @@ void cmVisualStudio10TargetGenerator::Generate()
     if (!this->ComputeLinkOptions()) {
       return;
     }
+    if (!this->ComputeLibOptions()) {
+      return;
+    }
   }
   std::string path = this->LocalGenerator->GetCurrentBinaryDirectory();
   path += "/";
   path += this->Name;
-  path += ".vcxproj";
+  path += this->ProjectFileExtension;
   this->BuildFileStream = new cmGeneratedFileStream(path.c_str());
-  this->PathToVcxproj = path;
+  this->PathToProjectFile = path;
   this->BuildFileStream->SetCopyIfDifferent(true);
 
   // Write the encoding header into the file
@@ -329,13 +266,24 @@ void cmVisualStudio10TargetGenerator::Generate()
     this->WriteString("</PropertyGroup>\n", 1);
   }
 
-  this->WriteProjectConfigurations();
+  if (const char* hostArch =
+        this->GlobalGenerator->GetPlatformToolsetHostArchitecture()) {
+    this->WriteString("<PropertyGroup>\n", 1);
+    this->WriteString("<PreferredToolArchitecture>", 2);
+    (*this->BuildFileStream) << cmVS10EscapeXML(hostArch)
+                             << "</PreferredToolArchitecture>\n";
+    this->WriteString("</PropertyGroup>\n", 1);
+  }
+
+  if (csproj != this->ProjectType) {
+    this->WriteProjectConfigurations();
+  }
   this->WriteString("<PropertyGroup Label=\"Globals\">\n", 1);
   this->WriteString("<ProjectGUID>", 2);
   (*this->BuildFileStream) << "{" << this->GUID << "}</ProjectGUID>\n";
 
   if (this->MSTools &&
-      this->GeneratorTarget->GetType() <= cmState::GLOBAL_TARGET) {
+      this->GeneratorTarget->GetType() <= cmStateEnums::GLOBAL_TARGET) {
     this->WriteApplicationTypeSettings();
     this->VerifyNecessaryFiles();
   }
@@ -343,9 +291,14 @@ void cmVisualStudio10TargetGenerator::Generate()
   const char* vsProjectTypes =
     this->GeneratorTarget->GetProperty("VS_GLOBAL_PROJECT_TYPES");
   if (vsProjectTypes) {
-    this->WriteString("<ProjectTypes>", 2);
-    (*this->BuildFileStream) << cmVS10EscapeXML(vsProjectTypes)
-                             << "</ProjectTypes>\n";
+    std::string tagName = "ProjectTypes";
+    if (csproj == this->ProjectType) {
+      tagName = "ProjectTypeGuids";
+    }
+    this->WriteString("", 2);
+    (*this->BuildFileStream) << "<" << tagName << ">"
+                             << cmVS10EscapeXML(vsProjectTypes) << "</"
+                             << tagName << ">\n";
   }
 
   const char* vsProjectName =
@@ -413,6 +366,16 @@ void cmVisualStudio10TargetGenerator::Generate()
                              << "</TargetFrameworkVersion>\n";
   }
 
+  // Disable the project upgrade prompt that is displayed the first time a
+  // project using an older toolset version is opened in a newer version of
+  // the IDE (respected by VS 2013 and above).
+  if (this->GlobalGenerator->GetVersion() >=
+      cmGlobalVisualStudioGenerator::VS12) {
+    this->WriteString("<VCProjectUpgraderObjectName>NoUpgrade"
+                      "</VCProjectUpgraderObjectName>\n",
+                      2);
+  }
+
   std::vector<std::string> keys = this->GeneratorTarget->GetPropertyKeys();
   for (std::vector<std::string>::const_iterator keyIt = keys.begin();
        keyIt != keys.end(); ++keyIt) {
@@ -433,13 +396,59 @@ void cmVisualStudio10TargetGenerator::Generate()
                              << "</" << globalKey << ">\n";
   }
 
+  if (this->Managed) {
+    std::string outputType = "<OutputType>";
+    switch (this->GeneratorTarget->GetType()) {
+      case cmStateEnums::OBJECT_LIBRARY:
+      case cmStateEnums::STATIC_LIBRARY:
+      case cmStateEnums::SHARED_LIBRARY:
+        outputType += "Library";
+        break;
+      case cmStateEnums::MODULE_LIBRARY:
+        outputType += "Module";
+        break;
+      case cmStateEnums::EXECUTABLE:
+        if (this->GeneratorTarget->Target->GetPropertyAsBool(
+              "WIN32_EXECUTABLE")) {
+          outputType += "WinExe";
+        } else {
+          outputType += "Exe";
+        }
+        break;
+      case cmStateEnums::UTILITY:
+      case cmStateEnums::GLOBAL_TARGET:
+        outputType += "Utility";
+        break;
+      case cmStateEnums::UNKNOWN_LIBRARY:
+      case cmStateEnums::INTERFACE_LIBRARY:
+        break;
+    }
+    outputType += "</OutputType>\n";
+    this->WriteString(outputType.c_str(), 2);
+    this->WriteString("<AppDesignerFolder>Properties</AppDesignerFolder>\n",
+                      2);
+  }
+
   this->WriteString("</PropertyGroup>\n", 1);
-  this->WriteString("<Import Project="
-                    "\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\n",
-                    1);
+
+  switch (this->ProjectType) {
+    case vcxproj:
+      this->WriteString("<Import Project=\"" VS10_CXX_DEFAULT_PROPS "\" />\n",
+                        1);
+      break;
+    case csproj:
+      this->WriteString("<Import Project=\"" VS10_CSharp_DEFAULT_PROPS "\" "
+                        "Condition=\"Exists('" VS10_CSharp_DEFAULT_PROPS "')\""
+                        "/>\n",
+                        1);
+      break;
+  }
+
   this->WriteProjectConfigurationValues();
-  this->WriteString(
-    "<Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\n", 1);
+
+  if (vcxproj == this->ProjectType) {
+    this->WriteString("<Import Project=\"" VS10_CXX_PROPS "\" />\n", 1);
+  }
   this->WriteString("<ImportGroup Label=\"ExtensionSettings\">\n", 1);
   if (this->GlobalGenerator->IsMasmEnabled()) {
     this->WriteString("<Import Project=\"$(VCTargetsPath)\\"
@@ -448,10 +457,28 @@ void cmVisualStudio10TargetGenerator::Generate()
   }
   this->WriteString("</ImportGroup>\n", 1);
   this->WriteString("<ImportGroup Label=\"PropertySheets\">\n", 1);
-  this->WriteString("<Import Project=\"" VS10_USER_PROPS "\""
-                    " Condition=\"exists('" VS10_USER_PROPS "')\""
-                    " Label=\"LocalAppDataPlatform\" />\n",
-                    2);
+  {
+    std::string props;
+    switch (this->ProjectType) {
+      case vcxproj:
+        props = VS10_CXX_USER_PROPS;
+        break;
+      case csproj:
+        props = VS10_CSharp_USER_PROPS;
+        break;
+    }
+    if (const char* p = this->GeneratorTarget->GetProperty("VS_USER_PROPS")) {
+      props = p;
+    }
+    if (!props.empty()) {
+      this->ConvertToWindowsSlash(props);
+      this->WriteString("", 2);
+      (*this->BuildFileStream)
+        << "<Import Project=\"" << cmVS10EscapeXML(props) << "\""
+        << " Condition=\"exists('" << cmVS10EscapeXML(props) << "')\""
+        << " Label=\"LocalAppDataPlatform\" />\n";
+    }
+  }
   this->WritePlatformExtensions();
   this->WriteString("</ImportGroup>\n", 1);
   this->WriteString("<PropertyGroup Label=\"UserMacros\" />\n", 1);
@@ -466,18 +493,35 @@ void cmVisualStudio10TargetGenerator::Generate()
   this->WriteWinRTReferences();
   this->WriteProjectReferences();
   this->WriteSDKReferences();
-  this->WriteString(
-    "<Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\""
-    " />\n",
-    1);
+  switch (this->ProjectType) {
+    case vcxproj:
+      this->WriteString("<Import Project=\"" VS10_CXX_TARGETS "\" />\n", 1);
+      break;
+    case csproj:
+      this->WriteString("<Import Project=\"" VS10_CSharp_TARGETS "\" />\n", 1);
+      break;
+  }
+
   this->WriteTargetSpecificReferences();
   this->WriteString("<ImportGroup Label=\"ExtensionTargets\">\n", 1);
+  this->WriteTargetsFileReferences();
   if (this->GlobalGenerator->IsMasmEnabled()) {
     this->WriteString("<Import Project=\"$(VCTargetsPath)\\"
                       "BuildCustomizations\\masm.targets\" />\n",
                       2);
   }
   this->WriteString("</ImportGroup>\n", 1);
+  if (csproj == this->ProjectType) {
+    for (std::vector<std::string>::const_iterator i =
+           this->Configurations.begin();
+         i != this->Configurations.end(); ++i) {
+      this->WriteString("<PropertyGroup Condition=\"'$(Configuration)' == '",
+                        1);
+      (*this->BuildFileStream) << *i << "'\">\n";
+      this->WriteEvents(*i);
+      this->WriteString("</PropertyGroup>\n", 1);
+    }
+  }
   this->WriteString("</Project>", 0);
   // The groups are stored in a separate file for VS 10
   this->WriteGroups();
@@ -486,58 +530,192 @@ void cmVisualStudio10TargetGenerator::Generate()
 void cmVisualStudio10TargetGenerator::WriteDotNetReferences()
 {
   std::vector<std::string> references;
+  typedef std::pair<std::string, std::string> HintReference;
+  std::vector<HintReference> hintReferences;
   if (const char* vsDotNetReferences =
         this->GeneratorTarget->GetProperty("VS_DOTNET_REFERENCES")) {
     cmSystemTools::ExpandListArgument(vsDotNetReferences, references);
   }
-  if (!references.empty()) {
+  cmPropertyMap const& props = this->GeneratorTarget->Target->GetProperties();
+  for (cmPropertyMap::const_iterator i = props.begin(); i != props.end();
+       ++i) {
+    if (i->first.find("VS_DOTNET_REFERENCE_") == 0) {
+      std::string name = i->first.substr(20);
+      if (name != "") {
+        std::string path = i->second.GetValue();
+        if (!cmsys::SystemTools::FileIsFullPath(path)) {
+          path = std::string(this->GeneratorTarget->Target->GetMakefile()
+                               ->GetCurrentSourceDirectory()) +
+            "/" + path;
+        }
+        this->ConvertToWindowsSlash(path);
+        hintReferences.push_back(HintReference(name, path));
+      }
+    }
+  }
+  if (!references.empty() || !hintReferences.empty()) {
     this->WriteString("<ItemGroup>\n", 1);
     for (std::vector<std::string>::iterator ri = references.begin();
          ri != references.end(); ++ri) {
-      this->WriteString("<Reference Include=\"", 2);
-      (*this->BuildFileStream) << cmVS10EscapeXML(*ri) << "\">\n";
-      this->WriteString("<CopyLocalSatelliteAssemblies>true"
-                        "</CopyLocalSatelliteAssemblies>\n",
-                        3);
-      this->WriteString("<ReferenceOutputAssembly>true"
-                        "</ReferenceOutputAssembly>\n",
-                        3);
-      this->WriteString("</Reference>\n", 2);
+      // if the entry from VS_DOTNET_REFERENCES is an existing file, generate
+      // a new hint-reference and name it from the filename
+      if (cmsys::SystemTools::FileExists(*ri, true)) {
+        std::string name =
+          cmsys::SystemTools::GetFilenameWithoutExtension(*ri);
+        std::string path = *ri;
+        this->ConvertToWindowsSlash(path);
+        hintReferences.push_back(HintReference(name, path));
+      } else {
+        this->WriteDotNetReference(*ri, "");
+      }
+    }
+    for (std::vector<std::pair<std::string, std::string> >::const_iterator i =
+           hintReferences.begin();
+         i != hintReferences.end(); ++i) {
+      this->WriteDotNetReference(i->first, i->second);
     }
     this->WriteString("</ItemGroup>\n", 1);
   }
 }
 
+void cmVisualStudio10TargetGenerator::WriteDotNetReference(
+  std::string const& ref, std::string const& hint)
+{
+  this->WriteString("<Reference Include=\"", 2);
+  (*this->BuildFileStream) << cmVS10EscapeXML(ref) << "\">\n";
+  this->WriteString("<CopyLocalSatelliteAssemblies>true"
+                    "</CopyLocalSatelliteAssemblies>\n",
+                    3);
+  this->WriteString("<ReferenceOutputAssembly>true"
+                    "</ReferenceOutputAssembly>\n",
+                    3);
+  if (!hint.empty()) {
+    const char* privateReference = "True";
+    if (const char* value = this->GeneratorTarget->GetProperty(
+          "VS_DOTNET_REFERENCES_COPY_LOCAL")) {
+      if (cmSystemTools::IsOff(value)) {
+        privateReference = "False";
+      }
+    }
+    this->WriteString("<Private>", 3);
+    (*this->BuildFileStream) << privateReference << "</Private>\n";
+    this->WriteString("<HintPath>", 3);
+    (*this->BuildFileStream) << hint << "</HintPath>\n";
+  }
+  this->WriteString("</Reference>\n", 2);
+}
+
 void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup()
 {
   std::vector<cmSourceFile const*> resxObjs;
   this->GeneratorTarget->GetResxSources(resxObjs, "");
   if (!resxObjs.empty()) {
     this->WriteString("<ItemGroup>\n", 1);
+    std::string srcDir = this->Makefile->GetCurrentSourceDirectory();
+    this->ConvertToWindowsSlash(srcDir);
     for (std::vector<cmSourceFile const*>::const_iterator oi =
            resxObjs.begin();
          oi != resxObjs.end(); ++oi) {
       std::string obj = (*oi)->GetFullPath();
       this->WriteString("<EmbeddedResource Include=\"", 2);
       this->ConvertToWindowsSlash(obj);
+      bool useRelativePath = false;
+      if (csproj == this->ProjectType && this->InSourceBuild) {
+        // If we do an in-source build and the resource file is in a
+        // subdirectory
+        // of the .csproj file, we have to use relative pathnames, otherwise
+        // visual studio does not show the file in the IDE. Sorry.
+        if (obj.find(srcDir) == 0) {
+          obj = this->ConvertPath(obj, true);
+          this->ConvertToWindowsSlash(obj);
+          useRelativePath = true;
+        }
+      }
       (*this->BuildFileStream) << obj << "\">\n";
 
-      this->WriteString("<DependentUpon>", 3);
-      std::string hFileName = obj.substr(0, obj.find_last_of(".")) + ".h";
-      (*this->BuildFileStream) << hFileName << "</DependentUpon>\n";
-
-      for (std::vector<std::string>::const_iterator i =
-             this->Configurations.begin();
-           i != this->Configurations.end(); ++i) {
-        this->WritePlatformConfigTag("LogicalName", i->c_str(), 3);
-        if (this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE") ||
-            // Handle variant of VS_GLOBAL_<variable> for RootNamespace.
-            this->GeneratorTarget->GetProperty("VS_GLOBAL_RootNamespace")) {
-          (*this->BuildFileStream) << "$(RootNamespace).";
+      if (csproj != this->ProjectType) {
+        this->WriteString("<DependentUpon>", 3);
+        std::string hFileName = obj.substr(0, obj.find_last_of(".")) + ".h";
+        (*this->BuildFileStream) << hFileName << "</DependentUpon>\n";
+
+        for (std::vector<std::string>::const_iterator i =
+               this->Configurations.begin();
+             i != this->Configurations.end(); ++i) {
+          this->WritePlatformConfigTag("LogicalName", i->c_str(), 3);
+          if (this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE") ||
+              // Handle variant of VS_GLOBAL_<variable> for RootNamespace.
+              this->GeneratorTarget->GetProperty("VS_GLOBAL_RootNamespace")) {
+            (*this->BuildFileStream) << "$(RootNamespace).";
+          }
+          (*this->BuildFileStream) << "%(Filename)";
+          (*this->BuildFileStream) << ".resources";
+          (*this->BuildFileStream) << "</LogicalName>\n";
+        }
+      } else {
+        std::string binDir = this->Makefile->GetCurrentBinaryDirectory();
+        this->ConvertToWindowsSlash(binDir);
+        // If the resource was NOT added using a relative path (which should
+        // be the default), we have to provide a link here
+        if (!useRelativePath) {
+          std::string link;
+          if (obj.find(srcDir) == 0) {
+            link = obj.substr(srcDir.length() + 1);
+          } else if (obj.find(binDir) == 0) {
+            link = obj.substr(binDir.length() + 1);
+          } else {
+            link = cmsys::SystemTools::GetFilenameName(obj);
+          }
+          if (!link.empty()) {
+            this->WriteString("<Link>", 3);
+            (*this->BuildFileStream) << link << "</Link>\n";
+          }
+        }
+        // Determine if this is a generated resource from a .Designer.cs file
+        std::string designerResource =
+          cmSystemTools::GetFilenamePath((*oi)->GetFullPath()) + "/" +
+          cmSystemTools::GetFilenameWithoutLastExtension(
+            (*oi)->GetFullPath()) +
+          ".Designer.cs";
+        if (cmsys::SystemTools::FileExists(designerResource)) {
+          std::string generator = "PublicResXFileCodeGenerator";
+          if (const char* g = (*oi)->GetProperty("VS_RESOURCE_GENERATOR")) {
+            generator = g;
+          }
+          if (!generator.empty()) {
+            this->WriteString("<Generator>", 3);
+            (*this->BuildFileStream) << cmVS10EscapeXML(generator)
+                                     << "</Generator>\n";
+            if (designerResource.find(srcDir) == 0) {
+              designerResource = designerResource.substr(srcDir.length() + 1);
+            } else if (designerResource.find(binDir) == 0) {
+              designerResource = designerResource.substr(binDir.length() + 1);
+            } else {
+              designerResource =
+                cmsys::SystemTools::GetFilenameName(designerResource);
+            }
+            this->ConvertToWindowsSlash(designerResource);
+            this->WriteString("<LastGenOutput>", 3);
+            (*this->BuildFileStream) << designerResource
+                                     << "</LastGenOutput>\n";
+          }
+        }
+        const cmPropertyMap& props = (*oi)->GetProperties();
+        for (cmPropertyMap::const_iterator p = props.begin(); p != props.end();
+             ++p) {
+          static const std::string propNamePrefix = "VS_CSHARP_";
+          if (p->first.find(propNamePrefix.c_str()) == 0) {
+            std::string tagName = p->first.substr(propNamePrefix.length());
+            if (!tagName.empty()) {
+              std::string value = props.GetPropertyValue(p->first);
+              if (!value.empty()) {
+                this->WriteString("<", 3);
+                (*this->BuildFileStream) << tagName << ">";
+                (*this->BuildFileStream) << cmVS10EscapeXML(value);
+                (*this->BuildFileStream) << "</" << tagName << ">\n";
+              }
+            }
+          }
         }
-        (*this->BuildFileStream) << "%(Filename)";
-        (*this->BuildFileStream) << ".resources";
-        (*this->BuildFileStream) << "</LogicalName>\n";
       }
 
       this->WriteString("</EmbeddedResource>\n", 2);
@@ -565,6 +743,24 @@ void cmVisualStudio10TargetGenerator::WriteXamlFilesGroup()
       }
 
       this->WriteSource(xamlType, *oi, ">\n");
+      if (csproj == this->ProjectType && !this->InSourceBuild) {
+        // add <Link> tag to written XAML source if necessary
+        const std::string srcDir = this->Makefile->GetCurrentSourceDirectory();
+        const std::string binDir = this->Makefile->GetCurrentBinaryDirectory();
+        std::string link;
+        if (obj.find(srcDir) == 0) {
+          link = obj.substr(srcDir.length() + 1);
+        } else if (obj.find(binDir) == 0) {
+          link = obj.substr(binDir.length() + 1);
+        } else {
+          link = cmsys::SystemTools::GetFilenameName(obj);
+        }
+        if (!link.empty()) {
+          this->ConvertToWindowsSlash(link);
+          this->WriteString("<Link>", 3);
+          (*this->BuildFileStream) << link << "</Link>\n";
+        }
+      }
       this->WriteString("<SubType>Designer</SubType>\n", 3);
       this->WriteString("</", 2);
       (*this->BuildFileStream) << xamlType << ">\n";
@@ -587,6 +783,31 @@ void cmVisualStudio10TargetGenerator::WriteTargetSpecificReferences()
   }
 }
 
+void cmVisualStudio10TargetGenerator::WriteTargetsFileReferences()
+{
+  for (std::vector<TargetsFileAndConfigs>::iterator i =
+         this->TargetsFileAndConfigsVec.begin();
+       i != this->TargetsFileAndConfigsVec.end(); ++i) {
+    TargetsFileAndConfigs const& tac = *i;
+    this->WriteString("<Import Project=\"", 3);
+    (*this->BuildFileStream) << tac.File << "\" ";
+    (*this->BuildFileStream) << "Condition=\"";
+    (*this->BuildFileStream) << "Exists('" << tac.File << "')";
+    if (!tac.Configs.empty()) {
+      (*this->BuildFileStream) << " And (";
+      for (size_t j = 0; j < tac.Configs.size(); ++j) {
+        if (j > 0) {
+          (*this->BuildFileStream) << " Or ";
+        }
+        (*this->BuildFileStream) << "'$(Configuration)'=='" << tac.Configs[j]
+                                 << "'";
+      }
+      (*this->BuildFileStream) << ")";
+    }
+    (*this->BuildFileStream) << "\" />\n";
+  }
+}
+
 void cmVisualStudio10TargetGenerator::WriteWinRTReferences()
 {
   std::vector<std::string> references;
@@ -640,48 +861,55 @@ void cmVisualStudio10TargetGenerator::WriteProjectConfigurationValues()
        i != this->Configurations.end(); ++i) {
     this->WritePlatformConfigTag("PropertyGroup", i->c_str(), 1,
                                  " Label=\"Configuration\"", "\n");
-    std::string configType = "<ConfigurationType>";
-    if (const char* vsConfigurationType =
-          this->GeneratorTarget->GetProperty("VS_CONFIGURATION_TYPE")) {
-      configType += cmVS10EscapeXML(vsConfigurationType);
-    } else {
-      switch (this->GeneratorTarget->GetType()) {
-        case cmState::SHARED_LIBRARY:
-        case cmState::MODULE_LIBRARY:
-          configType += "DynamicLibrary";
-          break;
-        case cmState::OBJECT_LIBRARY:
-        case cmState::STATIC_LIBRARY:
-          configType += "StaticLibrary";
-          break;
-        case cmState::EXECUTABLE:
-          if (this->NsightTegra &&
-              !this->GeneratorTarget->GetPropertyAsBool("ANDROID_GUI")) {
-            // Android executables are .so too.
+
+    if (csproj != this->ProjectType) {
+      std::string configType = "<ConfigurationType>";
+      if (const char* vsConfigurationType =
+            this->GeneratorTarget->GetProperty("VS_CONFIGURATION_TYPE")) {
+        configType += cmVS10EscapeXML(vsConfigurationType);
+      } else {
+        switch (this->GeneratorTarget->GetType()) {
+          case cmStateEnums::SHARED_LIBRARY:
+          case cmStateEnums::MODULE_LIBRARY:
             configType += "DynamicLibrary";
-          } else {
-            configType += "Application";
-          }
-          break;
-        case cmState::UTILITY:
-        case cmState::GLOBAL_TARGET:
-          if (this->NsightTegra) {
-            // Tegra-Android platform does not understand "Utility".
+            break;
+          case cmStateEnums::OBJECT_LIBRARY:
+          case cmStateEnums::STATIC_LIBRARY:
             configType += "StaticLibrary";
-          } else {
-            configType += "Utility";
-          }
-          break;
-        case cmState::UNKNOWN_LIBRARY:
-        case cmState::INTERFACE_LIBRARY:
-          break;
+            break;
+          case cmStateEnums::EXECUTABLE:
+            if (this->NsightTegra &&
+                !this->GeneratorTarget->GetPropertyAsBool("ANDROID_GUI")) {
+              // Android executables are .so too.
+              configType += "DynamicLibrary";
+            } else {
+              configType += "Application";
+            }
+            break;
+          case cmStateEnums::UTILITY:
+          case cmStateEnums::GLOBAL_TARGET:
+            if (this->NsightTegra) {
+              // Tegra-Android platform does not understand "Utility".
+              configType += "StaticLibrary";
+            } else {
+              configType += "Utility";
+            }
+            break;
+          case cmStateEnums::UNKNOWN_LIBRARY:
+          case cmStateEnums::INTERFACE_LIBRARY:
+            break;
+        }
       }
+      configType += "</ConfigurationType>\n";
+      this->WriteString(configType.c_str(), 2);
     }
-    configType += "</ConfigurationType>\n";
-    this->WriteString(configType.c_str(), 2);
 
     if (this->MSTools) {
-      this->WriteMSToolConfigurationValues(*i);
+      if (!this->Managed) {
+        this->WriteMSToolConfigurationValues(*i);
+      } else {
+        this->WriteMSToolConfigurationValuesManaged(*i);
+      }
     } else if (this->NsightTegra) {
       this->WriteNsightTegraConfigurationValues(*i);
     }
@@ -701,7 +929,7 @@ void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValues(
   std::string mfcFlagValue = mfcFlag ? mfcFlag : "0";
 
   std::string useOfMfcValue = "false";
-  if (this->GeneratorTarget->GetType() <= cmState::OBJECT_LIBRARY) {
+  if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
     if (mfcFlagValue == "1") {
       useOfMfcValue = "Static";
     } else if (mfcFlagValue == "2") {
@@ -712,14 +940,15 @@ void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValues(
   mfcLine += useOfMfcValue + "</UseOfMfc>\n";
   this->WriteString(mfcLine.c_str(), 2);
 
-  if ((this->GeneratorTarget->GetType() <= cmState::OBJECT_LIBRARY &&
+  if ((this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY &&
        this->ClOptions[config]->UsingUnicode()) ||
       this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") ||
       this->GlobalGenerator->TargetsWindowsPhone() ||
       this->GlobalGenerator->TargetsWindowsStore() ||
       this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_EXTENSIONS")) {
     this->WriteString("<CharacterSet>Unicode</CharacterSet>\n", 2);
-  } else if (this->GeneratorTarget->GetType() <= cmState::MODULE_LIBRARY &&
+  } else if (this->GeneratorTarget->GetType() <=
+               cmStateEnums::MODULE_LIBRARY &&
              this->ClOptions[config]->UsingSBCS()) {
     this->WriteString("<CharacterSet>NotSet</CharacterSet>\n", 2);
   } else {
@@ -739,6 +968,61 @@ void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValues(
   }
 }
 
+void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValuesManaged(
+  std::string const& config)
+{
+  cmGlobalVisualStudio10Generator* gg =
+    static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
+
+  Options& o = *(this->ClOptions[config]);
+
+  if (o.IsDebug()) {
+    this->WriteString("<DebugSymbols>true</DebugSymbols>\n", 2);
+    this->WriteString("<DefineDebug>true</DefineDebug>\n", 2);
+  }
+
+  std::string outDir =
+    this->GeneratorTarget->GetDirectory(config.c_str()) + "/";
+  this->ConvertToWindowsSlash(outDir);
+  this->WriteString("<OutputPath>", 2);
+  (*this->BuildFileStream) << cmVS10EscapeXML(outDir) << "</OutputPath>\n";
+
+  if (o.HasFlag("Platform")) {
+    this->WriteString("<PlatformTarget>", 2);
+    (*this->BuildFileStream) << cmVS10EscapeXML(o.GetFlag("Platform"))
+                             << "</PlatformTarget>\n";
+    o.RemoveFlag("Platform");
+  }
+
+  if (const char* toolset = gg->GetPlatformToolset()) {
+    this->WriteString("<PlatformToolset>", 2);
+    (*this->BuildFileStream) << cmVS10EscapeXML(toolset)
+                             << "</PlatformToolset>\n";
+  }
+
+  std::string postfixName = cmSystemTools::UpperCase(config);
+  postfixName += "_POSTFIX";
+  std::string assemblyName =
+    this->GeneratorTarget->GetOutputName(config, false);
+  if (const char* postfix = this->GeneratorTarget->GetProperty(postfixName)) {
+    assemblyName += postfix;
+  }
+  this->WriteString("<AssemblyName>", 2);
+  (*this->BuildFileStream) << cmVS10EscapeXML(assemblyName)
+                           << "</AssemblyName>\n";
+
+  if (cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType()) {
+    this->WriteString("<StartAction>Program</StartAction>\n", 2);
+    this->WriteString("<StartProgram>", 2);
+    (*this->BuildFileStream) << cmVS10EscapeXML(outDir)
+                             << cmVS10EscapeXML(assemblyName)
+                             << ".exe</StartProgram>\n";
+  }
+
+  o.OutputFlagMap(*this->BuildFileStream, "    ");
+}
+
+//----------------------------------------------------------------------------
 void cmVisualStudio10TargetGenerator::WriteNsightTegraConfigurationValues(
   std::string const&)
 {
@@ -902,6 +1186,10 @@ void cmVisualStudio10TargetGenerator::ConvertToWindowsSlash(std::string& s)
 }
 void cmVisualStudio10TargetGenerator::WriteGroups()
 {
+  if (csproj == this->ProjectType) {
+    return;
+  }
+
   // collect up group information
   std::vector<cmSourceGroup> sourceGroups = this->Makefile->GetSourceGroups();
   std::vector<cmSourceFile*> classes;
@@ -925,7 +1213,8 @@ void cmVisualStudio10TargetGenerator::WriteGroups()
   std::string path = this->LocalGenerator->GetCurrentBinaryDirectory();
   path += "/";
   path += this->Name;
-  path += ".vcxproj.filters";
+  path += computeProjectFileExtension(this->GeneratorTarget);
+  path += ".filters";
   cmGeneratedFileStream fout(path.c_str());
   fout.SetCopyIfDifferent(true);
   char magic[] = { char(0xEF), char(0xBB), char(0xBF) };
@@ -1159,7 +1448,38 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
   std::string shaderEntryPoint;
   std::string shaderModel;
   std::string shaderAdditionalFlags;
+  std::string settingsGenerator;
+  std::string settingsLastGenOutput;
+  std::string sourceLink;
+  std::string subType;
+  std::string copyToOutDir;
+  std::string includeInVsix;
   std::string ext = cmSystemTools::LowerCase(sf->GetExtension());
+  if (csproj == this->ProjectType) {
+    // EVERY extra source file must have a <Link>, otherwise it might not
+    // be visible in Visual Studio at all. The path relative to current
+    // source- or binary-dir is used within the link, if the file is
+    // in none of these paths, it is added with the plain filename without
+    // any path. This means the file will show up at root-level of the csproj
+    // (where CMakeLists.txt etc. are).
+    if (!this->InSourceBuild) {
+      toolHasSettings = true;
+      std::string fullFileName = sf->GetFullPath();
+      std::string srcDir = this->Makefile->GetCurrentSourceDirectory();
+      std::string binDir = this->Makefile->GetCurrentBinaryDirectory();
+      if (fullFileName.find(binDir) != std::string::npos) {
+        sourceLink = "";
+      } else if (fullFileName.find(srcDir) != std::string::npos) {
+        sourceLink = fullFileName.substr(srcDir.length() + 1);
+      } else {
+        // fallback: add plain filename without any path
+        sourceLink = cmsys::SystemTools::GetFilenameName(fullFileName);
+      }
+      if (!sourceLink.empty()) {
+        this->ConvertToWindowsSlash(sourceLink);
+      }
+    }
+  }
   if (ext == "hlsl") {
     tool = "FXCompile";
     // Figure out the type of shader compiler to use.
@@ -1190,6 +1510,28 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
     tool = "XML";
   } else if (ext == "natvis") {
     tool = "Natvis";
+  } else if (ext == "settings") {
+    // remove path to current source dir (if files are in current source dir)
+    if (!sourceLink.empty()) {
+      settingsLastGenOutput = sourceLink;
+    } else {
+      settingsLastGenOutput = sf->GetFullPath();
+    }
+    std::size_t pos = settingsLastGenOutput.find(".settings");
+    settingsLastGenOutput.replace(pos, 9, ".Designer.cs");
+    settingsGenerator = "SettingsSingleFileGenerator";
+    toolHasSettings = true;
+  } else if (ext == "vsixmanifest") {
+    subType = "Designer";
+  }
+  if (const char* c = sf->GetProperty("VS_COPY_TO_OUT_DIR")) {
+    copyToOutDir = c;
+    toolHasSettings = true;
+  }
+  if (sf->GetPropertyAsBool("VS_INCLUDE_IN_VSIX")) {
+    includeInVsix = "True";
+    tool = "Content";
+    toolHasSettings = true;
   }
 
   if (this->NsightTegra) {
@@ -1280,6 +1622,35 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
       (*this->BuildFileStream) << cmVS10EscapeXML(shaderAdditionalFlags)
                                << "</AdditionalOptions>\n";
     }
+    if (!settingsGenerator.empty()) {
+      this->WriteString("<Generator>", 3);
+      (*this->BuildFileStream) << cmVS10EscapeXML(settingsGenerator)
+                               << "</Generator>\n";
+    }
+    if (!settingsLastGenOutput.empty()) {
+      this->WriteString("<LastGenOutput>", 3);
+      (*this->BuildFileStream) << cmVS10EscapeXML(settingsLastGenOutput)
+                               << "</LastGenOutput>\n";
+    }
+    if (!sourceLink.empty()) {
+      this->WriteString("<Link>", 3);
+      (*this->BuildFileStream) << cmVS10EscapeXML(sourceLink) << "</Link>\n";
+    }
+    if (!subType.empty()) {
+      this->WriteString("<SubType>", 3);
+      (*this->BuildFileStream) << cmVS10EscapeXML(subType) << "</SubType>\n";
+    }
+    if (!copyToOutDir.empty()) {
+      this->WriteString("<CopyToOutputDirectory>", 3);
+      (*this->BuildFileStream) << cmVS10EscapeXML(copyToOutDir)
+                               << "</CopyToOutputDirectory>\n";
+    }
+    if (!includeInVsix.empty()) {
+      this->WriteString("<IncludeInVSIX>", 3);
+      (*this->BuildFileStream) << cmVS10EscapeXML(includeInVsix)
+                               << "</IncludeInVSIX>\n";
+    }
+
     this->WriteString("</", 2);
     (*this->BuildFileStream) << tool << ">\n";
   } else {
@@ -1342,7 +1713,7 @@ void cmVisualStudio10TargetGenerator::WriteSources(
 
 void cmVisualStudio10TargetGenerator::WriteAllSources()
 {
-  if (this->GeneratorTarget->GetType() > cmState::UTILITY) {
+  if (this->GeneratorTarget->GetType() > cmStateEnums::UTILITY) {
     return;
   }
   this->WriteString("<ItemGroup>\n", 1);
@@ -1371,6 +1742,8 @@ void cmVisualStudio10TargetGenerator::WriteAllSources()
       tool = "MASM";
     } else if (lang == "RC") {
       tool = "ResourceCompile";
+    } else if (lang == "CSharp") {
+      tool = "Compile";
     }
 
     if (!tool.empty()) {
@@ -1462,8 +1835,13 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags(
     objectName = this->GeneratorTarget->GetObjectName(&sf);
   }
   std::string flags;
+  bool configDependentFlags = false;
   std::string defines;
   if (const char* cflags = sf.GetProperty("COMPILE_FLAGS")) {
+
+    if (cmGeneratorExpression::Find(cflags) != std::string::npos) {
+      configDependentFlags = true;
+    }
     flags += cflags;
   }
   if (const char* cdefs = sf.GetProperty("COMPILE_DEFINITIONS")) {
@@ -1519,20 +1897,31 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags(
     }
     // if we have flags or defines for this config then
     // use them
-    if (!flags.empty() || !configDefines.empty() || compileAs || noWinRT) {
+    if (!flags.empty() || configDependentFlags || !configDefines.empty() ||
+        compileAs || noWinRT) {
       (*this->BuildFileStream) << firstString;
       firstString = ""; // only do firstString once
       hasFlags = true;
+      cmGlobalVisualStudio10Generator* gg =
+        static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
       cmVisualStudioGeneratorOptions clOptions(
         this->LocalGenerator, cmVisualStudioGeneratorOptions::Compiler,
-        this->GetClFlagTable(), 0, this);
+        gg->GetClFlagTable(), 0, this);
       if (compileAs) {
         clOptions.AddFlag("CompileAs", compileAs);
       }
       if (noWinRT) {
         clOptions.AddFlag("CompileAsWinRT", "false");
       }
-      clOptions.Parse(flags.c_str());
+      if (configDependentFlags) {
+        cmGeneratorExpression ge;
+        CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(flags);
+        std::string evaluatedFlags =
+          cge->Evaluate(this->LocalGenerator, *config);
+        clOptions.Parse(evaluatedFlags.c_str());
+      } else {
+        clOptions.Parse(flags.c_str());
+      }
       if (clOptions.HasFlag("AdditionalIncludeDirectories")) {
         clOptions.AppendFlag("AdditionalIncludeDirectories",
                              "%(AdditionalIncludeDirectories)");
@@ -1558,14 +1947,61 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags(
     std::string xamlFileName = fileName.substr(0, fileName.find_last_of("."));
     (*this->BuildFileStream) << xamlFileName << "</DependentUpon>\n";
   }
+  if (csproj == this->ProjectType) {
+    std::string f = source->GetFullPath();
+    typedef std::map<std::string, std::string> CsPropMap;
+    CsPropMap sourceFileTags;
+    // set <Link> tag if necessary
+    if (!this->InSourceBuild) {
+      const std::string stripFromPath =
+        this->Makefile->GetCurrentSourceDirectory();
+      if (f.find(stripFromPath) != std::string::npos) {
+        std::string link = f.substr(stripFromPath.length() + 1);
+        this->ConvertToWindowsSlash(link);
+        sourceFileTags["Link"] = link;
+      }
+    }
+    const cmPropertyMap& props = sf.GetProperties();
+    for (cmPropertyMap::const_iterator p = props.begin(); p != props.end();
+         ++p) {
+      static const std::string propNamePrefix = "VS_CSHARP_";
+      if (p->first.find(propNamePrefix.c_str()) == 0) {
+        std::string tagName = p->first.substr(propNamePrefix.length());
+        if (!tagName.empty()) {
+          const std::string val = props.GetPropertyValue(p->first);
+          if (!val.empty()) {
+            sourceFileTags[tagName] = val;
+          } else {
+            sourceFileTags.erase(tagName);
+          }
+        }
+      }
+    }
+    // write source file specific tags
+    if (!sourceFileTags.empty()) {
+      hasFlags = true;
+      (*this->BuildFileStream) << firstString;
+      firstString = "";
+      for (CsPropMap::const_iterator i = sourceFileTags.begin();
+           i != sourceFileTags.end(); ++i) {
+        this->WriteString("<", 3);
+        (*this->BuildFileStream)
+          << i->first << ">" << cmVS10EscapeXML(i->second) << "</" << i->first
+          << ">\n";
+      }
+    }
+  }
 
   return hasFlags;
 }
 
 void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions()
 {
-  cmState::TargetType ttype = this->GeneratorTarget->GetType();
-  if (ttype > cmState::GLOBAL_TARGET) {
+  cmStateEnums::TargetType ttype = this->GeneratorTarget->GetType();
+  if (ttype > cmStateEnums::GLOBAL_TARGET) {
+    return;
+  }
+  if (csproj == this->ProjectType) {
     return;
   }
 
@@ -1576,7 +2012,7 @@ void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions()
   for (std::vector<std::string>::const_iterator config =
          this->Configurations.begin();
        config != this->Configurations.end(); ++config) {
-    if (ttype >= cmState::UTILITY) {
+    if (ttype >= cmStateEnums::UTILITY) {
       this->WritePlatformConfigTag("IntDir", config->c_str(), 3);
       *this->BuildFileStream
         << "$(Platform)\\$(Configuration)\\$(ProjectName)\\"
@@ -1589,7 +2025,7 @@ void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions()
       intermediateDir += "/";
       std::string outDir;
       std::string targetNameFull;
-      if (ttype == cmState::OBJECT_LIBRARY) {
+      if (ttype == cmStateEnums::OBJECT_LIBRARY) {
         outDir = intermediateDir;
         targetNameFull = this->GeneratorTarget->GetName();
         targetNameFull += ".lib";
@@ -1607,6 +2043,14 @@ void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions()
       *this->BuildFileStream << cmVS10EscapeXML(intermediateDir)
                              << "</IntDir>\n";
 
+      if (const char* workingDir = this->GeneratorTarget->GetProperty(
+            "VS_DEBUGGER_WORKING_DIRECTORY")) {
+        this->WritePlatformConfigTag("LocalDebuggerWorkingDirectory",
+                                     config->c_str(), 3);
+        *this->BuildFileStream << cmVS10EscapeXML(workingDir)
+                               << "</LocalDebuggerWorkingDirectory>\n";
+      }
+
       std::string name =
         cmSystemTools::GetFilenameWithoutLastExtension(targetNameFull);
       this->WritePlatformConfigTag("TargetName", config->c_str(), 3);
@@ -1634,10 +2078,13 @@ void cmVisualStudio10TargetGenerator::OutputLinkIncremental(
   if (!this->MSTools) {
     return;
   }
+  if (csproj == this->ProjectType) {
+    return;
+  }
   // static libraries and things greater than modules do not need
   // to set this option
-  if (this->GeneratorTarget->GetType() == cmState::STATIC_LIBRARY ||
-      this->GeneratorTarget->GetType() > cmState::MODULE_LIBRARY) {
+  if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
+      this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
     return;
   }
   Options& linkOptions = *(this->LinkOptions[configName]);
@@ -1686,8 +2133,20 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions(
   // copied from cmLocalVisualStudio7Generator.cxx 805
   // TODO: Integrate code below with cmLocalVisualStudio7Generator.
 
-  CM_AUTO_PTR<Options> pOptions(new Options(
-    this->LocalGenerator, Options::Compiler, this->GetClFlagTable()));
+  cmGlobalVisualStudio10Generator* gg =
+    static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
+  CM_AUTO_PTR<Options> pOptions;
+  switch (this->ProjectType) {
+    case vcxproj:
+      pOptions = CM_AUTO_PTR<Options>(new Options(
+        this->LocalGenerator, Options::Compiler, gg->GetClFlagTable()));
+      break;
+    case csproj:
+      pOptions = CM_AUTO_PTR<Options>(new Options(this->LocalGenerator,
+                                                  Options::CSharpCompiler,
+                                                  gg->GetCSharpFlagTable()));
+      break;
+  }
   Options& clOptions = *pOptions;
 
   std::string flags;
@@ -1700,7 +2159,7 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions(
     return false;
   }
   if (linkLanguage == "C" || linkLanguage == "CXX" ||
-      linkLanguage == "Fortran") {
+      linkLanguage == "Fortran" || linkLanguage == "CSharp") {
     std::string baseFlagVar = "CMAKE_";
     baseFlagVar += linkLanguage;
     baseFlagVar += "_FLAGS";
@@ -1728,16 +2187,26 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions(
   std::string defineFlags =
     this->GeneratorTarget->Target->GetMakefile()->GetDefineFlags();
   if (this->MSTools) {
-    clOptions.FixExceptionHandlingDefault();
-    clOptions.AddFlag("PrecompiledHeader", "NotUsing");
-    std::string asmLocation = configName + "/";
-    clOptions.AddFlag("AssemblerListingLocation", asmLocation.c_str());
+    if (vcxproj == this->ProjectType) {
+      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->GeneratorTarget->GetCompileDefinitions(targetDefines,
-                                               configName.c_str(), "CXX");
+  switch (this->ProjectType) {
+    case vcxproj:
+      this->GeneratorTarget->GetCompileDefinitions(targetDefines,
+                                                   configName.c_str(), "CXX");
+      break;
+    case csproj:
+      this->GeneratorTarget->GetCompileDefinitions(
+        targetDefines, configName.c_str(), "CSharp");
+      break;
+  }
   clOptions.AddDefines(targetDefines);
   if (this->MSTools) {
     clOptions.SetVerboseMakefile(
@@ -1758,8 +2227,8 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions(
     if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT")) {
       clOptions.AddFlag("CompileAsWinRT", "true");
       // For WinRT components, add the _WINRT_DLL define to produce a lib
-      if (this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY ||
-          this->GeneratorTarget->GetType() == cmState::MODULE_LIBRARY) {
+      if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
+          this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
         clOptions.AddDefine("_WINRT_DLL");
       }
     } else if (this->GlobalGenerator->TargetsWindowsStore() ||
@@ -1775,6 +2244,15 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions(
     }
   }
 
+  if (csproj != this->ProjectType && clOptions.IsManaged()) {
+    this->Managed = true;
+    std::string managedType = clOptions.GetFlag("CompileAsManaged");
+    if (managedType == "Safe") {
+      // force empty calling convention if safe clr is used
+      clOptions.AddFlag("CallingConvention", "");
+    }
+  }
+
   this->ClOptions[configName] = pOptions.release();
   return true;
 }
@@ -1783,6 +2261,9 @@ void cmVisualStudio10TargetGenerator::WriteClOptions(
   std::string const& configName, std::vector<std::string> const& includes)
 {
   Options& clOptions = *(this->ClOptions[configName]);
+  if (this->ProjectType == csproj) {
+    return;
+  }
   this->WriteString("<ClCompile>\n", 2);
   clOptions.OutputAdditionalOptions(*this->BuildFileStream, "      ", "");
   clOptions.AppendFlag("AdditionalIncludeDirectories", includes);
@@ -1851,8 +2332,10 @@ bool cmVisualStudio10TargetGenerator::ComputeRcOptions()
 bool cmVisualStudio10TargetGenerator::ComputeRcOptions(
   std::string const& configName)
 {
+  cmGlobalVisualStudio10Generator* gg =
+    static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
   CM_AUTO_PTR<Options> pOptions(new Options(
-    this->LocalGenerator, Options::ResourceCompiler, this->GetRcFlagTable()));
+    this->LocalGenerator, Options::ResourceCompiler, gg->GetRcFlagTable()));
   Options& rcOptions = *pOptions;
 
   std::string CONFIG = cmSystemTools::UpperCase(configName);
@@ -1863,6 +2346,11 @@ bool cmVisualStudio10TargetGenerator::ComputeRcOptions(
     std::string(this->Makefile->GetSafeDefinition(rcConfigFlagsVar));
 
   rcOptions.Parse(flags.c_str());
+
+  // For historical reasons, add the C preprocessor defines to RC.
+  Options& clOptions = *(this->ClOptions[configName]);
+  rcOptions.AddDefines(clOptions.GetDefines());
+
   this->RcOptions[configName] = pOptions.release();
   return true;
 }
@@ -1875,12 +2363,9 @@ void cmVisualStudio10TargetGenerator::WriteRCOptions(
   }
   this->WriteString("<ResourceCompile>\n", 2);
 
-  // Preprocessor definitions and includes are shared with clOptions.
-  Options& clOptions = *(this->ClOptions[configName]);
-  clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, "      ",
-                                          "\n", "RC");
-
   Options& rcOptions = *(this->RcOptions[configName]);
+  rcOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, "      ",
+                                          "\n", "RC");
   rcOptions.AppendFlag("AdditionalIncludeDirectories", includes);
   rcOptions.AppendFlag("AdditionalIncludeDirectories",
                        "%(AdditionalIncludeDirectories)");
@@ -1908,8 +2393,10 @@ bool cmVisualStudio10TargetGenerator::ComputeMasmOptions()
 bool cmVisualStudio10TargetGenerator::ComputeMasmOptions(
   std::string const& configName)
 {
+  cmGlobalVisualStudio10Generator* gg =
+    static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
   CM_AUTO_PTR<Options> pOptions(new Options(
-    this->LocalGenerator, Options::MasmCompiler, this->GetMasmFlagTable()));
+    this->LocalGenerator, Options::MasmCompiler, gg->GetMasmFlagTable()));
   Options& masmOptions = *pOptions;
 
   std::string CONFIG = cmSystemTools::UpperCase(configName);
@@ -1949,8 +2436,8 @@ void cmVisualStudio10TargetGenerator::WriteMasmOptions(
 void cmVisualStudio10TargetGenerator::WriteLibOptions(
   std::string const& config)
 {
-  if (this->GeneratorTarget->GetType() != cmState::STATIC_LIBRARY &&
-      this->GeneratorTarget->GetType() != cmState::OBJECT_LIBRARY) {
+  if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY &&
+      this->GeneratorTarget->GetType() != cmStateEnums::OBJECT_LIBRARY) {
     return;
   }
   std::string libflags;
@@ -1958,9 +2445,11 @@ void cmVisualStudio10TargetGenerator::WriteLibOptions(
     libflags, cmSystemTools::UpperCase(config), this->GeneratorTarget);
   if (!libflags.empty()) {
     this->WriteString("<Lib>\n", 2);
+    cmGlobalVisualStudio10Generator* gg =
+      static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
     cmVisualStudioGeneratorOptions libOptions(
       this->LocalGenerator, cmVisualStudioGeneratorOptions::Linker,
-      this->GetLibFlagTable(), 0, this);
+      gg->GetLibFlagTable(), 0, this);
     libOptions.Parse(libflags.c_str());
     libOptions.OutputAdditionalOptions(*this->BuildFileStream, "      ", "");
     libOptions.OutputFlagMap(*this->BuildFileStream, "      ");
@@ -1983,9 +2472,9 @@ void cmVisualStudio10TargetGenerator::WriteLibOptions(
 void cmVisualStudio10TargetGenerator::WriteManifestOptions(
   std::string const& config)
 {
-  if (this->GeneratorTarget->GetType() != cmState::EXECUTABLE &&
-      this->GeneratorTarget->GetType() != cmState::SHARED_LIBRARY &&
-      this->GeneratorTarget->GetType() != cmState::MODULE_LIBRARY) {
+  if (this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE &&
+      this->GeneratorTarget->GetType() != cmStateEnums::SHARED_LIBRARY &&
+      this->GeneratorTarget->GetType() != cmStateEnums::MODULE_LIBRARY) {
     return;
   }
 
@@ -2136,9 +2625,9 @@ void cmVisualStudio10TargetGenerator::WriteAntBuildOptions(
 
 bool cmVisualStudio10TargetGenerator::ComputeLinkOptions()
 {
-  if (this->GeneratorTarget->GetType() == cmState::EXECUTABLE ||
-      this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY ||
-      this->GeneratorTarget->GetType() == cmState::MODULE_LIBRARY) {
+  if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
+      this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
+      this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
     for (std::vector<std::string>::const_iterator i =
            this->Configurations.begin();
          i != this->Configurations.end(); ++i) {
@@ -2153,8 +2642,10 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions()
 bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
   std::string const& config)
 {
+  cmGlobalVisualStudio10Generator* gg =
+    static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
   CM_AUTO_PTR<Options> pOptions(new Options(
-    this->LocalGenerator, Options::Linker, this->GetLinkFlagTable(), 0, this));
+    this->LocalGenerator, Options::Linker, gg->GetLinkFlagTable(), 0, this));
   Options& linkOptions = *pOptions;
 
   const std::string& linkLanguage =
@@ -2169,10 +2660,10 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
   std::string CONFIG = cmSystemTools::UpperCase(config);
 
   const char* linkType = "SHARED";
-  if (this->GeneratorTarget->GetType() == cmState::MODULE_LIBRARY) {
+  if (this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
     linkType = "MODULE";
   }
-  if (this->GeneratorTarget->GetType() == cmState::EXECUTABLE) {
+  if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
     linkType = "EXE";
   }
   std::string flags;
@@ -2229,9 +2720,16 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
   }
   // add the libraries for the target to libs string
   cmComputeLinkInformation& cli = *pcli;
-  this->AddLibraries(cli, libVec);
+  std::vector<std::string> vsTargetVec;
+  this->AddLibraries(cli, libVec, vsTargetVec);
   linkOptions.AddFlag("AdditionalDependencies", libVec);
 
+  // Populate TargetsFileAndConfigsVec
+  for (std::vector<std::string>::iterator ti = vsTargetVec.begin();
+       ti != vsTargetVec.end(); ++ti) {
+    this->AddTargetsFileAndConfigPair(*ti, config);
+  }
+
   std::vector<std::string> const& ldirs = cli.GetDirectories();
   std::vector<std::string> linkDirs;
   for (std::vector<std::string>::const_iterator d = ldirs.begin();
@@ -2249,7 +2747,7 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
   std::string targetNameFull;
   std::string targetNameImport;
   std::string targetNamePDB;
-  if (this->GeneratorTarget->GetType() == cmState::EXECUTABLE) {
+  if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
     this->GeneratorTarget->GetExecutableNames(targetName, targetNameFull,
                                               targetNameImport, targetNamePDB,
                                               config.c_str());
@@ -2265,7 +2763,7 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
     if (this->GeneratorTarget->GetPropertyAsBool("WIN32_EXECUTABLE")) {
       if (this->GlobalGenerator->TargetsWindowsCE()) {
         linkOptions.AddFlag("SubSystem", "WindowsCE");
-        if (this->GeneratorTarget->GetType() == cmState::EXECUTABLE) {
+        if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
           if (this->ClOptions[config]->UsingUnicode()) {
             linkOptions.AddFlag("EntryPointSymbol", "wWinMainCRTStartup");
           } else {
@@ -2278,7 +2776,7 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
     } else {
       if (this->GlobalGenerator->TargetsWindowsCE()) {
         linkOptions.AddFlag("SubSystem", "WindowsCE");
-        if (this->GeneratorTarget->GetType() == cmState::EXECUTABLE) {
+        if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
           if (this->ClOptions[config]->UsingUnicode()) {
             linkOptions.AddFlag("EntryPointSymbol", "mainWCRTStartup");
           } else {
@@ -2316,7 +2814,7 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
     // A Windows Runtime component uses internal .NET metadata,
     // so does not have an import library.
     if (this->GeneratorTarget->GetPropertyAsBool("VS_WINRT_COMPONENT") &&
-        this->GeneratorTarget->GetType() != cmState::EXECUTABLE) {
+        this->GeneratorTarget->GetType() != cmStateEnums::EXECUTABLE) {
       linkOptions.AddFlag("GenerateWindowsMetadata", "true");
     } else if (this->GlobalGenerator->TargetsWindowsPhone() ||
                this->GlobalGenerator->TargetsWindowsStore()) {
@@ -2347,7 +2845,7 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
                            "%(IgnoreSpecificDefaultLibraries)");
   }
 
-  if ((this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY ||
+  if ((this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
        this->GeneratorTarget->IsExecutableWithExports()) &&
       this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
     if (this->GeneratorTarget->GetPropertyAsBool(
@@ -2386,11 +2884,57 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
   return true;
 }
 
+bool cmVisualStudio10TargetGenerator::ComputeLibOptions()
+{
+  if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY) {
+    for (std::vector<std::string>::const_iterator i =
+           this->Configurations.begin();
+         i != this->Configurations.end(); ++i) {
+      if (!this->ComputeLibOptions(*i)) {
+        return false;
+      }
+    }
+  }
+  return true;
+}
+
+bool cmVisualStudio10TargetGenerator::ComputeLibOptions(
+  std::string const& config)
+{
+  cmComputeLinkInformation* pcli =
+    this->GeneratorTarget->GetLinkInformation(config.c_str());
+  if (!pcli) {
+    cmSystemTools::Error(
+      "CMake can not compute cmComputeLinkInformation for target: ",
+      this->Name.c_str());
+    return false;
+  }
+
+  cmComputeLinkInformation& cli = *pcli;
+  typedef cmComputeLinkInformation::ItemVector ItemVector;
+  const ItemVector& libs = cli.GetItems();
+  std::string currentBinDir =
+    this->LocalGenerator->GetCurrentBinaryDirectory();
+  for (ItemVector::const_iterator l = libs.begin(); l != libs.end(); ++l) {
+    if (l->IsPath && cmVS10IsTargetsFile(l->Value)) {
+      std::string path = this->LocalGenerator->ConvertToRelativePath(
+        currentBinDir, l->Value.c_str());
+      this->ConvertToWindowsSlash(path);
+      this->AddTargetsFileAndConfigPair(path, config);
+    }
+  }
+
+  return true;
+}
+
 void cmVisualStudio10TargetGenerator::WriteLinkOptions(
   std::string const& config)
 {
-  if (this->GeneratorTarget->GetType() == cmState::STATIC_LIBRARY ||
-      this->GeneratorTarget->GetType() > cmState::MODULE_LIBRARY) {
+  if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
+      this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
+    return;
+  }
+  if (csproj == this->ProjectType) {
     return;
   }
   Options& linkOptions = *(this->LinkOptions[config]);
@@ -2410,10 +2954,11 @@ void cmVisualStudio10TargetGenerator::WriteLinkOptions(
 }
 
 void cmVisualStudio10TargetGenerator::AddLibraries(
-  cmComputeLinkInformation& cli, std::vector<std::string>& libVec)
+  cmComputeLinkInformation& cli, std::vector<std::string>& libVec,
+  std::vector<std::string>& vsTargetVec)
 {
   typedef cmComputeLinkInformation::ItemVector ItemVector;
-  ItemVector libs = cli.GetItems();
+  ItemVector const& libs = cli.GetItems();
   std::string currentBinDir =
     this->LocalGenerator->GetCurrentBinaryDirectory();
   for (ItemVector::const_iterator l = libs.begin(); l != libs.end(); ++l) {
@@ -2421,20 +2966,47 @@ void cmVisualStudio10TargetGenerator::AddLibraries(
       std::string path = this->LocalGenerator->ConvertToRelativePath(
         currentBinDir, l->Value.c_str());
       this->ConvertToWindowsSlash(path);
-      libVec.push_back(path);
+      if (cmVS10IsTargetsFile(l->Value)) {
+        vsTargetVec.push_back(path);
+      } else {
+        libVec.push_back(path);
+      }
     } else if (!l->Target ||
-               l->Target->GetType() != cmState::INTERFACE_LIBRARY) {
+               l->Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
       libVec.push_back(l->Value);
     }
   }
 }
 
+void cmVisualStudio10TargetGenerator::AddTargetsFileAndConfigPair(
+  std::string const& targetsFile, std::string const& config)
+{
+  for (std::vector<TargetsFileAndConfigs>::iterator i =
+         this->TargetsFileAndConfigsVec.begin();
+       i != this->TargetsFileAndConfigsVec.end(); ++i) {
+    if (cmSystemTools::ComparePath(targetsFile, i->File)) {
+      if (std::find(i->Configs.begin(), i->Configs.end(), config) ==
+          i->Configs.end()) {
+        i->Configs.push_back(config);
+      }
+      return;
+    }
+  }
+  TargetsFileAndConfigs entry;
+  entry.File = targetsFile;
+  entry.Configs.push_back(config);
+  this->TargetsFileAndConfigsVec.push_back(entry);
+}
+
 void cmVisualStudio10TargetGenerator::WriteMidlOptions(
   std::string const& /*config*/, std::vector<std::string> const& includes)
 {
   if (!this->MSTools) {
     return;
   }
+  if (csproj == this->ProjectType) {
+    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
@@ -2487,7 +3059,7 @@ void cmVisualStudio10TargetGenerator::WriteItemDefinitionGroups()
     this->WritePlatformConfigTag("ItemDefinitionGroup", i->c_str(), 1);
     *this->BuildFileStream << "\n";
     //    output cl compile flags <ClCompile></ClCompile>
-    if (this->GeneratorTarget->GetType() <= cmState::OBJECT_LIBRARY) {
+    if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
       this->WriteClOptions(*i, includes);
       //    output rc compile flags <ResourceCompile></ResourceCompile>
       this->WriteRCOptions(*i, includes);
@@ -2496,7 +3068,9 @@ void cmVisualStudio10TargetGenerator::WriteItemDefinitionGroups()
     //    output midl flags       <Midl></Midl>
     this->WriteMidlOptions(*i, includes);
     // write events
-    this->WriteEvents(*i);
+    if (csproj != this->ProjectType) {
+      this->WriteEvents(*i);
+    }
     //    output link flags       <Link></Link>
     this->WriteLinkOptions(*i);
     //    output lib flags       <Lib></Lib>
@@ -2504,7 +3078,7 @@ void cmVisualStudio10TargetGenerator::WriteItemDefinitionGroups()
     //    output manifest flags  <Manifest></Manifest>
     this->WriteManifestOptions(*i);
     if (this->NsightTegra &&
-        this->GeneratorTarget->GetType() == cmState::EXECUTABLE &&
+        this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE &&
         this->GeneratorTarget->GetPropertyAsBool("ANDROID_GUI")) {
       this->WriteAntBuildOptions(*i);
     }
@@ -2516,7 +3090,7 @@ void cmVisualStudio10TargetGenerator::WriteEvents(
   std::string const& configName)
 {
   bool addedPrelink = false;
-  if ((this->GeneratorTarget->GetType() == cmState::SHARED_LIBRARY ||
+  if ((this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
        this->GeneratorTarget->IsExecutableWithExports()) &&
       this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS")) {
     if (this->GeneratorTarget->GetPropertyAsBool(
@@ -2562,12 +3136,20 @@ void cmVisualStudio10TargetGenerator::WriteEvent(
     script += cmVS10EscapeXML(lg->ConstructScript(ccg));
   }
   comment = cmVS10EscapeComment(comment);
-  this->WriteString("<Message>", 3);
-  (*this->BuildFileStream) << cmVS10EscapeXML(comment) << "</Message>\n";
-  this->WriteString("<Command>", 3);
+  if (csproj != this->ProjectType) {
+    this->WriteString("<Message>", 3);
+    (*this->BuildFileStream) << cmVS10EscapeXML(comment) << "</Message>\n";
+    this->WriteString("<Command>", 3);
+  } else {
+    if (!comment.empty()) {
+      (*this->BuildFileStream) << "echo " << cmVS10EscapeXML(comment) << "\n";
+    }
+  }
   (*this->BuildFileStream) << script;
-  (*this->BuildFileStream) << "</Command>"
-                           << "\n";
+  if (csproj != this->ProjectType) {
+    (*this->BuildFileStream) << "</Command>";
+  }
+  (*this->BuildFileStream) << "\n";
   this->WriteString("</", 2);
   (*this->BuildFileStream) << name << ">\n";
 }
@@ -2583,7 +3165,7 @@ void cmVisualStudio10TargetGenerator::WriteProjectReferences()
   for (OrderedTargetDependSet::const_iterator i = depends.begin();
        i != depends.end(); ++i) {
     cmGeneratorTarget const* dt = *i;
-    if (dt->GetType() == cmState::INTERFACE_LIBRARY) {
+    if (dt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
       continue;
     }
     // skip fortran targets as they can not be processed by MSBuild
@@ -2592,6 +3174,10 @@ void cmVisualStudio10TargetGenerator::WriteProjectReferences()
           ->TargetIsFortranOnly(dt)) {
       continue;
     }
+    if (csproj == this->ProjectType &&
+        !this->GlobalGenerator->TargetIsCSharpOnly(dt)) {
+      continue;
+    }
     this->WriteString("<ProjectReference Include=\"", 2);
     cmLocalGenerator* lg = dt->GetLocalGenerator();
     std::string name = dt->GetName();
@@ -2603,12 +3189,21 @@ void cmVisualStudio10TargetGenerator::WriteProjectReferences()
       path = lg->GetCurrentBinaryDirectory();
       path += "/";
       path += dt->GetName();
-      path += ".vcxproj";
+      path += computeProjectFileExtension(dt);
     }
+    this->ConvertToWindowsSlash(path);
     (*this->BuildFileStream) << cmVS10EscapeXML(path) << "\">\n";
     this->WriteString("<Project>", 3);
-    (*this->BuildFileStream) << this->GlobalGenerator->GetGUID(name.c_str())
-                             << "</Project>\n";
+    if (csproj == this->ProjectType) {
+      (*this->BuildFileStream) << "{";
+    }
+    (*this->BuildFileStream) << this->GlobalGenerator->GetGUID(name.c_str());
+    if (csproj == this->ProjectType) {
+      (*this->BuildFileStream) << "}";
+    }
+    (*this->BuildFileStream) << "</Project>\n";
+    this->WriteString("<Name>", 3);
+    (*this->BuildFileStream) << name << "</Name>\n";
     this->WriteString("</ProjectReference>\n", 2);
   }
   this->WriteString("</ItemGroup>\n", 1);
@@ -2719,7 +3314,7 @@ void cmVisualStudio10TargetGenerator::WriteWinRTPackageCertificateKeyFile()
 {
   if ((this->GlobalGenerator->TargetsWindowsStore() ||
        this->GlobalGenerator->TargetsWindowsPhone()) &&
-      (cmState::EXECUTABLE == this->GeneratorTarget->GetType())) {
+      (cmStateEnums::EXECUTABLE == this->GeneratorTarget->GetType())) {
     std::string pfxFile;
     std::vector<cmSourceFile const*> certificates;
     this->GeneratorTarget->GetCertificates(certificates, "");
@@ -2844,7 +3439,7 @@ void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings()
                         "</MinimumVisualStudioVersion>\n",
                         2);
 
-      if (this->GeneratorTarget->GetType() < cmState::UTILITY) {
+      if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
         isAppContainer = true;
       }
     } else if (v == "8.1") {
@@ -2856,7 +3451,7 @@ void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings()
                         "</MinimumVisualStudioVersion>\n",
                         2);
 
-      if (this->GeneratorTarget->GetType() < cmState::UTILITY) {
+      if (this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
         isAppContainer = true;
       }
     } else if (v == "8.0") {
@@ -2869,10 +3464,11 @@ void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings()
                         2);
 
       if (isWindowsStore &&
-          this->GeneratorTarget->GetType() < cmState::UTILITY) {
+          this->GeneratorTarget->GetType() < cmStateEnums::UTILITY) {
         isAppContainer = true;
       } else if (isWindowsPhone &&
-                 this->GeneratorTarget->GetType() == cmState::EXECUTABLE) {
+                 this->GeneratorTarget->GetType() ==
+                   cmStateEnums::EXECUTABLE) {
         this->WriteString("<XapOutputs>true</XapOutputs>\n", 2);
         this->WriteString("<XapFilename>", 2);
         (*this->BuildFileStream)
@@ -2922,7 +3518,7 @@ 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->GeneratorTarget->GetType() == cmState::EXECUTABLE) {
+  if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
     std::vector<cmSourceFile const*> manifestSources;
     this->GeneratorTarget->GetAppManifest(manifestSources, "");
     {
diff --git a/Source/cmVisualStudio10TargetGenerator.h b/Source/cmVisualStudio10TargetGenerator.h
index c62be7e..45464c0 100644
--- a/Source/cmVisualStudio10TargetGenerator.h
+++ b/Source/cmVisualStudio10TargetGenerator.h
@@ -5,19 +5,22 @@
 
 #include <cmConfigure.h>
 
-#include "cmStandardIncludes.h"
+#include <iosfwd>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
 
-class cmMakefile;
-class cmGeneratorTarget;
+class cmComputeLinkInformation;
+class cmCustomCommand;
 class cmGeneratedFileStream;
+class cmGeneratorTarget;
 class cmGlobalVisualStudio10Generator;
-class cmSourceFile;
-class cmCustomCommand;
 class cmLocalVisualStudio7Generator;
-class cmComputeLinkInformation;
+class cmMakefile;
+class cmSourceFile;
+class cmSourceGroup;
 class cmVisualStudioGeneratorOptions;
-struct cmIDEFlagTable;
-#include "cmSourceGroup.h"
 
 class cmVisualStudio10TargetGenerator
 {
@@ -41,12 +44,19 @@ private:
   {
   };
 
+  struct TargetsFileAndConfigs
+  {
+    std::string File;
+    std::vector<std::string> Configs;
+  };
+
   std::string ConvertPath(std::string const& path, bool forceRelative);
   void ConvertToWindowsSlash(std::string& s);
   void WriteString(const char* line, int indentLevel);
   void WriteProjectConfigurations();
   void WriteProjectConfigurationValues();
   void WriteMSToolConfigurationValues(std::string const& config);
+  void WriteMSToolConfigurationValuesManaged(std::string const& config);
   void WriteHeaderSource(cmSourceFile const* sf);
   void WriteExtraSource(cmSourceFile const* sf);
   void WriteNsightTegraConfigurationValues(std::string const& config);
@@ -56,6 +66,7 @@ private:
                     std::vector<cmSourceFile const*> const&);
   void WriteAllSources();
   void WriteDotNetReferences();
+  void WriteDotNetReference(std::string const& ref, std::string const& hint);
   void WriteEmbeddedResourceGroup();
   void WriteWinRTReferences();
   void WriteWinRTPackageCertificateKeyFile();
@@ -77,6 +88,7 @@ private:
                                std::string const& version);
   void WriteCommonMissingFiles(const std::string& manifestFile);
   void WriteTargetSpecificReferences();
+  void WriteTargetsFileReferences();
 
   bool ComputeClOptions();
   bool ComputeClOptions(std::string const& configName);
@@ -92,6 +104,8 @@ private:
                         std::vector<std::string> const& includes);
   bool ComputeLinkOptions();
   bool ComputeLinkOptions(std::string const& config);
+  bool ComputeLibOptions();
+  bool ComputeLibOptions(std::string const& config);
   void WriteLinkOptions(std::string const& config);
   void WriteMidlOptions(std::string const& config,
                         std::vector<std::string> const& includes);
@@ -106,7 +120,10 @@ private:
   void WriteApplicationTypeSettings();
   bool OutputSourceSpecificFlags(cmSourceFile const* source);
   void AddLibraries(cmComputeLinkInformation& cli,
-                    std::vector<std::string>& libVec);
+                    std::vector<std::string>& libVec,
+                    std::vector<std::string>& vsTargetVec);
+  void AddTargetsFileAndConfigPair(std::string const& targetsFile,
+                                   std::string const& config);
   void WriteLibOptions(std::string const& config);
   void WriteManifestOptions(std::string const& config);
   void WriteEvents(std::string const& configName);
@@ -121,12 +138,6 @@ private:
   bool IsXamlHeader(const std::string& headerFile);
   bool IsXamlSource(const std::string& headerFile);
 
-  cmIDEFlagTable const* GetClFlagTable() const;
-  cmIDEFlagTable const* GetRcFlagTable() const;
-  cmIDEFlagTable const* GetLibFlagTable() const;
-  cmIDEFlagTable const* GetLinkFlagTable() const;
-  cmIDEFlagTable const* GetMasmFlagTable() const;
-
   bool ForceOld(const std::string& source) const;
 
 private:
@@ -136,14 +147,23 @@ private:
   OptionsMap RcOptions;
   OptionsMap MasmOptions;
   OptionsMap LinkOptions;
-  std::string PathToVcxproj;
+  std::string PathToProjectFile;
+  std::string ProjectFileExtension;
+  enum VsProjectType
+  {
+    vcxproj,
+    csproj
+  } ProjectType;
+  bool InSourceBuild;
   std::vector<std::string> Configurations;
+  std::vector<TargetsFileAndConfigs> TargetsFileAndConfigsVec;
   cmGeneratorTarget* GeneratorTarget;
   cmMakefile* Makefile;
   std::string Platform;
   std::string GUID;
   std::string Name;
   bool MSTools;
+  bool Managed;
   bool NsightTegra;
   int NsightTegraVersion[4];
   bool TargetCompileAsWinRT;
diff --git a/Source/cmVisualStudio10ToolsetOptions.cxx b/Source/cmVisualStudio10ToolsetOptions.cxx
new file mode 100644
index 0000000..afca216
--- /dev/null
+++ b/Source/cmVisualStudio10ToolsetOptions.cxx
@@ -0,0 +1,159 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cmVisualStudio10ToolsetOptions.h"
+
+#include "cmAlgorithms.h"
+#include "cmIDEFlagTable.h"
+#include "cmVisualStudioGeneratorOptions.h"
+
+#include "cmVS10CLFlagTable.h"
+#include "cmVS10CSharpFlagTable.h"
+#include "cmVS10LibFlagTable.h"
+#include "cmVS10LinkFlagTable.h"
+#include "cmVS10MASMFlagTable.h"
+#include "cmVS10RCFlagTable.h"
+#include "cmVS11CLFlagTable.h"
+#include "cmVS11CSharpFlagTable.h"
+#include "cmVS11LibFlagTable.h"
+#include "cmVS11LinkFlagTable.h"
+#include "cmVS11MASMFlagTable.h"
+#include "cmVS11RCFlagTable.h"
+#include "cmVS12CLFlagTable.h"
+#include "cmVS12CSharpFlagTable.h"
+#include "cmVS12LibFlagTable.h"
+#include "cmVS12LinkFlagTable.h"
+#include "cmVS12MASMFlagTable.h"
+#include "cmVS12RCFlagTable.h"
+#include "cmVS140CLFlagTable.h"
+#include "cmVS140CSharpFlagTable.h"
+#include "cmVS141CLFlagTable.h"
+#include "cmVS141CSharpFlagTable.h"
+#include "cmVS14LibFlagTable.h"
+#include "cmVS14LinkFlagTable.h"
+#include "cmVS14MASMFlagTable.h"
+#include "cmVS14RCFlagTable.h"
+
+cmIDEFlagTable const* cmVisualStudio10ToolsetOptions::GetClFlagTable(
+  std::string const& name, std::string const& toolset) const
+{
+  std::string const useToolset = this->GetToolsetName(name, toolset);
+
+  if (toolset == "v141") {
+    return cmVS141CLFlagTable;
+  } else if (useToolset == "v140") {
+    return cmVS140CLFlagTable;
+  } else if (useToolset == "v120") {
+    return cmVS12CLFlagTable;
+  } else if (useToolset == "v110") {
+    return cmVS11CLFlagTable;
+  } else if (useToolset == "v100") {
+    return cmVS10CLFlagTable;
+  } else {
+    return 0;
+  }
+}
+
+cmIDEFlagTable const* cmVisualStudio10ToolsetOptions::GetCSharpFlagTable(
+  std::string const& name, std::string const& toolset) const
+{
+  std::string const useToolset = this->GetToolsetName(name, toolset);
+
+  if ((useToolset == "v141")) {
+    return cmVS141CSharpFlagTable;
+  } else if (useToolset == "v140") {
+    return cmVS140CSharpFlagTable;
+  } else if (useToolset == "v120") {
+    return cmVS12CSharpFlagTable;
+  } else if (useToolset == "v110") {
+    return cmVS11CSharpFlagTable;
+  } else if (useToolset == "v100") {
+    return cmVS10CSharpFlagTable;
+  } else {
+    return 0;
+  }
+}
+
+cmIDEFlagTable const* cmVisualStudio10ToolsetOptions::GetRcFlagTable(
+  std::string const& name, std::string const& toolset) const
+{
+  std::string const useToolset = this->GetToolsetName(name, toolset);
+
+  if ((useToolset == "v140") || (useToolset == "v141")) {
+    return cmVS14RCFlagTable;
+  } else if (useToolset == "v120") {
+    return cmVS12RCFlagTable;
+  } else if (useToolset == "v110") {
+    return cmVS11RCFlagTable;
+  } else if (useToolset == "v100") {
+    return cmVS10RCFlagTable;
+  } else {
+    return 0;
+  }
+}
+
+cmIDEFlagTable const* cmVisualStudio10ToolsetOptions::GetLibFlagTable(
+  std::string const& name, std::string const& toolset) const
+{
+  std::string const useToolset = this->GetToolsetName(name, toolset);
+
+  if ((useToolset == "v140") || (useToolset == "v141")) {
+    return cmVS14LibFlagTable;
+  } else if (useToolset == "v120") {
+    return cmVS12LibFlagTable;
+  } else if (useToolset == "v110") {
+    return cmVS11LibFlagTable;
+  } else if (useToolset == "v100") {
+    return cmVS10LibFlagTable;
+  } else {
+    return 0;
+  }
+}
+
+cmIDEFlagTable const* cmVisualStudio10ToolsetOptions::GetLinkFlagTable(
+  std::string const& name, std::string const& toolset) const
+{
+  std::string const useToolset = this->GetToolsetName(name, toolset);
+
+  if ((useToolset == "v140") || (useToolset == "v141")) {
+    return cmVS14LinkFlagTable;
+  } else if (useToolset == "v120") {
+    return cmVS12LinkFlagTable;
+  } else if (useToolset == "v110") {
+    return cmVS11LinkFlagTable;
+  } else if (useToolset == "v100") {
+    return cmVS10LinkFlagTable;
+  } else {
+    return 0;
+  }
+}
+
+cmIDEFlagTable const* cmVisualStudio10ToolsetOptions::GetMasmFlagTable(
+  std::string const& name, std::string const& toolset) const
+{
+  std::string const useToolset = this->GetToolsetName(name, toolset);
+
+  if ((useToolset == "v140") || (useToolset == "v141")) {
+    return cmVS14MASMFlagTable;
+  } else if (useToolset == "v120") {
+    return cmVS12MASMFlagTable;
+  } else if (useToolset == "v110") {
+    return cmVS11MASMFlagTable;
+  } else if (useToolset == "v100") {
+    return cmVS10MASMFlagTable;
+  } else {
+    return 0;
+  }
+}
+
+std::string cmVisualStudio10ToolsetOptions::GetToolsetName(
+  std::string const& name, std::string const& toolset) const
+{
+  static_cast<void>(name);
+  std::size_t length = toolset.length();
+
+  if (cmHasLiteralSuffix(toolset, "_xp")) {
+    length -= 3;
+  }
+
+  return toolset.substr(0, length);
+}
diff --git a/Source/cmVisualStudio10ToolsetOptions.h b/Source/cmVisualStudio10ToolsetOptions.h
new file mode 100644
index 0000000..2459f5e
--- /dev/null
+++ b/Source/cmVisualStudio10ToolsetOptions.h
@@ -0,0 +1,37 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef cmVisualStudio10ToolsetOptions_h
+#define cmVisualStudio10ToolsetOptions_h
+
+#include <cmConfigure.h>
+
+#include <string>
+
+struct cmIDEFlagTable;
+
+/** \class cmVisualStudio10ToolsetOptions
+ * \brief Retrieves toolset options for MSBuild.
+ *
+ * cmVisualStudio10ToolsetOptions manages toolsets within MSBuild
+ */
+class cmVisualStudio10ToolsetOptions
+{
+public:
+  cmIDEFlagTable const* GetClFlagTable(std::string const& name,
+                                       std::string const& toolset) const;
+  cmIDEFlagTable const* GetCSharpFlagTable(std::string const& name,
+                                           std::string const& toolset) const;
+  cmIDEFlagTable const* GetRcFlagTable(std::string const& name,
+                                       std::string const& toolset) const;
+  cmIDEFlagTable const* GetLibFlagTable(std::string const& name,
+                                        std::string const& toolset) const;
+  cmIDEFlagTable const* GetLinkFlagTable(std::string const& name,
+                                         std::string const& toolset) const;
+  cmIDEFlagTable const* GetMasmFlagTable(std::string const& name,
+                                         std::string const& toolset) const;
+
+private:
+  std::string GetToolsetName(std::string const& name,
+                             std::string const& toolset) const;
+};
+#endif
diff --git a/Source/cmVisualStudioGeneratorOptions.cxx b/Source/cmVisualStudioGeneratorOptions.cxx
index 9badda6..da6f9a7 100644
--- a/Source/cmVisualStudioGeneratorOptions.cxx
+++ b/Source/cmVisualStudioGeneratorOptions.cxx
@@ -1,5 +1,7 @@
 #include "cmVisualStudioGeneratorOptions.h"
 
+#include "cmAlgorithms.h"
+#include "cmLocalVisualStudioGenerator.h"
 #include "cmOutputConverter.h"
 #include "cmSystemTools.h"
 #include "cmVisualStudio10TargetGenerator.h"
@@ -129,7 +131,17 @@ void cmVisualStudioGeneratorOptions::SetVerboseMakefile(bool verbose)
 
 bool cmVisualStudioGeneratorOptions::IsDebug() const
 {
-  return this->FlagMap.find("DebugInformationFormat") != this->FlagMap.end();
+  if (this->CurrentTool != CSharpCompiler) {
+    return this->FlagMap.find("DebugInformationFormat") != this->FlagMap.end();
+  }
+  std::map<std::string, FlagValue>::const_iterator i =
+    this->FlagMap.find("DebugType");
+  if (i != this->FlagMap.end()) {
+    if (i->second.size() == 1) {
+      return i->second[0] != "none";
+    }
+  }
+  return false;
 }
 
 bool cmVisualStudioGeneratorOptions::IsWinRt() const
@@ -137,6 +149,11 @@ bool cmVisualStudioGeneratorOptions::IsWinRt() const
   return this->FlagMap.find("CompileAsWinRT") != this->FlagMap.end();
 }
 
+bool cmVisualStudioGeneratorOptions::IsManaged() const
+{
+  return this->FlagMap.find("CompileAsManaged") != this->FlagMap.end();
+}
+
 bool cmVisualStudioGeneratorOptions::UsingUnicode() const
 {
   // Look for the a _UNICODE definition.
@@ -251,8 +268,10 @@ void cmVisualStudioGeneratorOptions::OutputPreprocessorDefinitions(
     fout << prefix << "PreprocessorDefinitions=\"";
   }
   const char* sep = "";
+  std::vector<std::string>::const_iterator de =
+    cmRemoveDuplicates(this->Defines);
   for (std::vector<std::string>::const_iterator di = this->Defines.begin();
-       di != this->Defines.end(); ++di) {
+       di != de; ++di) {
     // Escape the definition for the compiler.
     std::string define;
     if (this->Version < cmGlobalVisualStudioGenerator::VS10) {
@@ -329,8 +348,9 @@ void cmVisualStudioGeneratorOptions::OutputAdditionalOptions(
       } else {
         fout << "<AdditionalOptions>";
       }
-      fout << cmVisualStudio10GeneratorOptionsEscapeForXML(this->FlagString)
-           << " %(AdditionalOptions)</AdditionalOptions>\n";
+      fout << "%(AdditionalOptions) "
+           << cmVisualStudio10GeneratorOptionsEscapeForXML(this->FlagString)
+           << "</AdditionalOptions>\n";
     } else {
       fout << prefix << "AdditionalOptions=\"";
       fout << cmVisualStudioGeneratorOptionsEscapeForXML(this->FlagString);
diff --git a/Source/cmVisualStudioGeneratorOptions.h b/Source/cmVisualStudioGeneratorOptions.h
index 4eeae3d..ab6b8cc 100644
--- a/Source/cmVisualStudioGeneratorOptions.h
+++ b/Source/cmVisualStudioGeneratorOptions.h
@@ -3,9 +3,17 @@
 #ifndef cmVisualStudioGeneratorOptions_h
 #define cmVisualStudioGeneratorOptions_h
 
-#include "cmLocalVisualStudioGenerator.h"
+#include <cmConfigure.h>
 
+#include <iosfwd>
+#include <string>
+
+#include "cmGlobalVisualStudioGenerator.h"
+#include "cmIDEFlagTable.h"
 #include "cmIDEOptions.h"
+
+class cmLocalVisualStudioGenerator;
+
 typedef cmIDEFlagTable cmVS7FlagTable;
 
 class cmVisualStudio10TargetGenerator;
@@ -20,7 +28,8 @@ public:
     ResourceCompiler,
     MasmCompiler,
     Linker,
-    FortranCompiler
+    FortranCompiler,
+    CSharpCompiler
   };
   cmVisualStudioGeneratorOptions(cmLocalVisualStudioGenerator* lg, Tool tool,
                                  cmVS7FlagTable const* table,
@@ -49,6 +58,7 @@ public:
 
   bool IsDebug() const;
   bool IsWinRt() const;
+  bool IsManaged() const;
   // Write options to output.
   void OutputPreprocessorDefinitions(std::ostream& fout, const char* prefix,
                                      const char* suffix,
diff --git a/Source/cmVisualStudioSlnData.h b/Source/cmVisualStudioSlnData.h
index 9f5ccb7..b2f8db9 100644
--- a/Source/cmVisualStudioSlnData.h
+++ b/Source/cmVisualStudioSlnData.h
@@ -5,7 +5,9 @@
 
 #include <cmConfigure.h>
 
-#include "cmStandardIncludes.h"
+#include <map>
+#include <string>
+#include <vector>
 
 class cmSlnProjectEntry
 {
diff --git a/Source/cmVisualStudioSlnParser.h b/Source/cmVisualStudioSlnParser.h
index 8939ab5..a3391a6 100644
--- a/Source/cmVisualStudioSlnParser.h
+++ b/Source/cmVisualStudioSlnParser.h
@@ -5,9 +5,10 @@
 
 #include <cmConfigure.h>
 
-#include "cmStandardIncludes.h"
-
 #include <bitset>
+#include <iosfwd>
+#include <stddef.h>
+#include <string>
 
 class cmSlnData;
 
@@ -65,6 +66,7 @@ public:
 
 protected:
   class State;
+
   friend class State;
   class ParsedLine;
 
diff --git a/Source/cmVisualStudioWCEPlatformParser.h b/Source/cmVisualStudioWCEPlatformParser.h
index 25f1a18..8ed6083 100644
--- a/Source/cmVisualStudioWCEPlatformParser.h
+++ b/Source/cmVisualStudioWCEPlatformParser.h
@@ -5,7 +5,10 @@
 
 #include <cmConfigure.h>
 
-#include "cmStandardIncludes.h"
+#include <map>
+#include <stddef.h>
+#include <string>
+#include <vector>
 
 #include "cmXMLParser.h"
 
diff --git a/Source/cmWhileCommand.cxx b/Source/cmWhileCommand.cxx
index c52ea40..38ea637 100644
--- a/Source/cmWhileCommand.cxx
+++ b/Source/cmWhileCommand.cxx
@@ -3,6 +3,12 @@
 #include "cmWhileCommand.h"
 
 #include "cmConditionEvaluator.h"
+#include "cmExecutionStatus.h"
+#include "cmExpandedCommandArgument.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cm_auto_ptr.hxx"
+#include "cmake.h"
 
 cmWhileFunctionBlocker::cmWhileFunctionBlocker(cmMakefile* mf)
   : Makefile(mf)
diff --git a/Source/cmWhileCommand.h b/Source/cmWhileCommand.h
index 9c70ca2..abd36b3 100644
--- a/Source/cmWhileCommand.h
+++ b/Source/cmWhileCommand.h
@@ -3,11 +3,17 @@
 #ifndef cmWhileCommand_h
 #define cmWhileCommand_h
 
-#include "cmCommand.h"
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
 
+#include "cmCommand.h"
 #include "cmFunctionBlocker.h"
 #include "cmListFileCache.h"
 
+class cmExecutionStatus;
+class cmMakefile;
+
 class cmWhileFunctionBlocker : public cmFunctionBlocker
 {
 public:
@@ -60,8 +66,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "while"; }
-
-  cmTypeMacro(cmWhileCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmWriteFileCommand.cxx b/Source/cmWriteFileCommand.cxx
index 0bdef0f..96c8e27 100644
--- a/Source/cmWriteFileCommand.cxx
+++ b/Source/cmWriteFileCommand.cxx
@@ -8,6 +8,11 @@
 // include sys/stat.h after sys/types.h
 #include <sys/stat.h>
 
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+class cmExecutionStatus;
+
 // cmLibraryCommand
 bool cmWriteFileCommand::InitialPass(std::vector<std::string> const& args,
                                      cmExecutionStatus&)
@@ -60,7 +65,7 @@ bool cmWriteFileCommand::InitialPass(std::vector<std::string> const& args,
                        overwrite ? std::ios::out : std::ios::app);
   if (!file) {
     std::string error = "Internal CMake error when trying to open file: ";
-    error += fileName.c_str();
+    error += fileName;
     error += " for writing.";
     this->SetError(error);
     return false;
diff --git a/Source/cmWriteFileCommand.h b/Source/cmWriteFileCommand.h
index dbadf84..73e6e22 100644
--- a/Source/cmWriteFileCommand.h
+++ b/Source/cmWriteFileCommand.h
@@ -3,8 +3,14 @@
 #ifndef cmWriteFileCommand_h
 #define cmWriteFileCommand_h
 
+#include <cmConfigure.h>
+#include <string>
+#include <vector>
+
 #include "cmCommand.h"
 
+class cmExecutionStatus;
+
 /** \class cmWriteFileCommand
  * \brief Writes a message to a file
  *
@@ -33,8 +39,6 @@ public:
    * The name of the command as specified in CMakeList.txt.
    */
   std::string GetName() const CM_OVERRIDE { return "write_file"; }
-
-  cmTypeMacro(cmWriteFileCommand, cmCommand);
 };
 
 #endif
diff --git a/Source/cmXCode21Object.cxx b/Source/cmXCode21Object.cxx
index a783c70..719e627 100644
--- a/Source/cmXCode21Object.cxx
+++ b/Source/cmXCode21Object.cxx
@@ -2,6 +2,9 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmXCode21Object.h"
 
+#include <ostream>
+#include <string>
+
 #include "cmSystemTools.h"
 
 cmXCode21Object::cmXCode21Object(PBXType ptype, Type type)
diff --git a/Source/cmXCode21Object.h b/Source/cmXCode21Object.h
index 0db20e6..083d229 100644
--- a/Source/cmXCode21Object.h
+++ b/Source/cmXCode21Object.h
@@ -3,6 +3,11 @@
 #ifndef cmXCode21Object_h
 #define cmXCode21Object_h
 
+#include <cmConfigure.h> // IWYU pragma: keep
+
+#include <iosfwd>
+#include <vector>
+
 #include "cmXCodeObject.h"
 
 class cmXCode21Object : public cmXCodeObject
diff --git a/Source/cmXCodeObject.cxx b/Source/cmXCodeObject.cxx
index b1dc7ea..3689ac4 100644
--- a/Source/cmXCodeObject.cxx
+++ b/Source/cmXCodeObject.cxx
@@ -2,9 +2,10 @@
    file Copyright.txt or https://cmake.org/licensing for details.  */
 #include "cmXCodeObject.h"
 
-#include "cmSystemTools.h"
+#include <CoreFoundation/CoreFoundation.h>
+#include <ostream>
 
-#include <CoreFoundation/CoreFoundation.h> // CFUUIDCreate
+#include "cmSystemTools.h"
 
 const char* cmXCodeObject::PBXTypeNames[] = {
   /* clang-format needs this comment to break after the opening brace */
diff --git a/Source/cmXCodeObject.h b/Source/cmXCodeObject.h
index d495130..3bfecdf 100644
--- a/Source/cmXCodeObject.h
+++ b/Source/cmXCodeObject.h
@@ -3,9 +3,14 @@
 #ifndef cmXCodeObject_h
 #define cmXCodeObject_h
 
-#include <cmConfigure.h>
+#include <cmConfigure.h> // IWYU pragma: keep
 
-#include "cmStandardIncludes.h"
+#include <algorithm>
+#include <iosfwd>
+#include <map>
+#include <string>
+#include <utility>
+#include <vector>
 
 class cmGeneratorTarget;
 
diff --git a/Source/cm_codecvt.cxx b/Source/cm_codecvt.cxx
new file mode 100644
index 0000000..869dd32
--- /dev/null
+++ b/Source/cm_codecvt.cxx
@@ -0,0 +1,215 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#include "cm_codecvt.hxx"
+#include <limits>
+
+#if defined(_WIN32)
+#include <windows.h>
+#undef max
+#include <cmsys/Encoding.hxx>
+#endif
+
+codecvt::codecvt(Encoding e)
+  : m_lastState(0)
+#if defined(_WIN32)
+  , m_codepage(0)
+#endif
+{
+  switch (e) {
+    case codecvt::ANSI:
+#if defined(_WIN32)
+      m_noconv = false;
+      m_codepage = CP_ACP;
+      break;
+#endif
+    // We don't know which ANSI encoding to use for other platforms than
+    // Windows so we don't do any conversion there
+    case codecvt::UTF8:
+    // Assume internal encoding is UTF-8
+    case codecvt::None:
+    // No encoding
+    default:
+      m_noconv = true;
+  }
+}
+
+codecvt::~codecvt(){};
+
+bool codecvt::do_always_noconv() const throw()
+{
+  return m_noconv;
+};
+
+std::codecvt_base::result codecvt::do_out(mbstate_t& state, const char* from,
+                                          const char* from_end,
+                                          const char*& from_next, char* to,
+                                          char* to_end, char*& to_next) const
+{
+  if (m_noconv) {
+    return noconv;
+  }
+  std::codecvt_base::result res = error;
+#if defined(_WIN32)
+  from_next = from;
+  to_next = to;
+  bool convert = true;
+  size_t count = from_end - from;
+  const char* data = from;
+  unsigned int& stateId = reinterpret_cast<unsigned int&>(state);
+  if (count == 0) {
+    return codecvt::ok;
+  } else if (count == 1) {
+    if (stateId == 0) {
+      // decode first byte for UTF-8
+      if ((*from & 0xF8) == 0xF0 || // 1111 0xxx; 4 bytes for codepoint
+          (*from & 0xF0) == 0xE0 || // 1110 xxxx; 3 bytes for codepoint
+          (*from & 0xE0) == 0xC0)   // 110x xxxx; 2 bytes for codepoint
+      {
+        stateId = findStateId();
+        codecvt::State& s = m_states.at(stateId - 1);
+        s.bytes[0] = *from;
+        convert = false;
+        if ((*from & 0xF8) == 0xF0) {
+          s.totalBytes = 4;
+        } else if ((*from & 0xF0) == 0xE0) {
+          s.totalBytes = 3;
+        } else if ((*from & 0xE0) == 0xC0) {
+          s.totalBytes = 2;
+        }
+        s.bytesLeft = s.totalBytes - 1;
+      };
+      // else 1 byte for codepoint
+    } else {
+      codecvt::State& s = m_states.at(stateId - 1);
+      s.bytes[s.totalBytes - s.bytesLeft] = *from;
+      s.bytesLeft--;
+      data = s.bytes;
+      count = s.totalBytes - s.bytesLeft;
+      if ((*from & 0xC0) == 0x80) { // 10xx xxxx
+        convert = s.bytesLeft == 0;
+      } else {
+        // invalid multi-byte
+        convert = true;
+      }
+      if (convert) {
+        s.used = false;
+        if (stateId == m_lastState) {
+          m_lastState--;
+        }
+        stateId = 0;
+      }
+    }
+    if (convert) {
+      std::wstring wide = cmsys::Encoding::ToWide(std::string(data, count));
+      int r = WideCharToMultiByte(m_codepage, 0, wide.c_str(),
+                                  static_cast<int>(wide.size()), to,
+                                  to_end - to, NULL, NULL);
+      if (r > 0) {
+        from_next = from_end;
+        to_next = to + r;
+        res = ok;
+      }
+    } else {
+      res = partial;
+      from_next = from_end;
+      to_next = to;
+    }
+  }
+#else
+  static_cast<void>(state);
+  static_cast<void>(from);
+  static_cast<void>(from_end);
+  static_cast<void>(from_next);
+  static_cast<void>(to);
+  static_cast<void>(to_end);
+  static_cast<void>(to_next);
+  res = codecvt::noconv;
+#endif
+  return res;
+};
+
+std::codecvt_base::result codecvt::do_unshift(mbstate_t& state, char* to,
+                                              char* to_end,
+                                              char*& to_next) const
+{
+  std::codecvt_base::result res = error;
+  to_next = to;
+#if defined(_WIN32)
+  unsigned int& stateId = reinterpret_cast<unsigned int&>(state);
+  if (stateId > 0) {
+    codecvt::State& s = m_states.at(stateId - 1);
+    s.used = false;
+    if (stateId == m_lastState) {
+      m_lastState--;
+    }
+    stateId = 0;
+    std::wstring wide = cmsys::Encoding::ToWide(
+      std::string(s.bytes, s.totalBytes - s.bytesLeft));
+    int r = WideCharToMultiByte(m_codepage, 0, wide.c_str(),
+                                static_cast<int>(wide.size()), to, to_end - to,
+                                NULL, NULL);
+    if (r > 0) {
+      to_next = to + r;
+      res = ok;
+    }
+  } else {
+    res = ok;
+  }
+#else
+  static_cast<void>(state);
+  static_cast<void>(to_end);
+  res = ok;
+#endif
+  return res;
+};
+
+int codecvt::do_max_length() const throw()
+{
+  return 4;
+};
+
+int codecvt::do_encoding() const throw()
+{
+  return 0;
+};
+
+unsigned int codecvt::findStateId() const
+{
+  unsigned int stateId = 0;
+  bool add = false;
+  const unsigned int maxSize = std::numeric_limits<unsigned int>::max();
+  if (m_lastState >= maxSize) {
+    m_lastState = 0;
+  }
+  if (m_states.size() <= m_lastState) {
+    add = true;
+  } else {
+    unsigned int i = m_lastState;
+    while (i < maxSize) {
+      codecvt::State& s = m_states.at(i);
+      i++;
+      if (!s.used) {
+        m_lastState = i;
+        stateId = m_lastState;
+        s.used = true;
+        s.totalBytes = 0;
+        s.bytesLeft = 0;
+        break;
+      }
+      if (i >= m_states.size()) {
+        i = 0;
+      }
+      if (i == m_lastState) {
+        add = true;
+        break;
+      }
+    }
+  };
+  if (add) {
+    codecvt::State s = { true, 0, 0, { 0, 0, 0, 0 } };
+    m_states.push_back(s);
+    m_lastState = (unsigned int)m_states.size();
+    stateId = m_lastState;
+  }
+  return stateId;
+};
diff --git a/Source/cm_codecvt.hxx b/Source/cm_codecvt.hxx
new file mode 100644
index 0000000..fcd9954
--- /dev/null
+++ b/Source/cm_codecvt.hxx
@@ -0,0 +1,58 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef cm_codecvt_hxx
+#define cm_codecvt_hxx
+
+#include <cmConfigure.h>
+
+#include <locale>
+#include <vector>
+#include <wchar.h>
+
+class codecvt : public std::codecvt<char, char, mbstate_t>
+{
+public:
+  enum Encoding
+  {
+    None,
+    UTF8,
+    ANSI
+  };
+
+#ifdef CMAKE_BUILD_WITH_CMAKE
+
+  codecvt(Encoding e);
+
+protected:
+  ~codecvt() CM_OVERRIDE;
+  bool do_always_noconv() const throw() CM_OVERRIDE;
+  result do_out(mbstate_t& state, const char* from, const char* from_end,
+                const char*& from_next, char* to, char* to_end,
+                char*& to_next) const CM_OVERRIDE;
+  result do_unshift(mbstate_t& state, char* to, char*,
+                    char*& to_next) const CM_OVERRIDE;
+  int do_max_length() const throw() CM_OVERRIDE;
+  int do_encoding() const throw() CM_OVERRIDE;
+
+private:
+  typedef struct
+  {
+    bool used;
+    unsigned char totalBytes;
+    unsigned char bytesLeft;
+    char bytes[4];
+  } State;
+
+  unsigned int findStateId() const;
+
+  bool m_noconv;
+  mutable std::vector<State> m_states;
+  mutable unsigned int m_lastState;
+#if defined(_WIN32)
+  unsigned int m_codepage;
+#endif
+
+#endif
+};
+
+#endif
diff --git a/Source/cm_sha2.c b/Source/cm_sha2.c
deleted file mode 100644
index 649c39a..0000000
--- a/Source/cm_sha2.c
+++ /dev/null
@@ -1,1613 +0,0 @@
-/*
- * FILE:	sha2.c
- * AUTHOR:	Aaron D. Gifford
- *		http://www.aarongifford.com/computers/sha.html
- *
- * Copyright (c) 2000-2003, Aaron D. Gifford
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the copyright holder nor the names of contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * $Id: sha2.c,v 1.4 2004/01/07 22:58:18 adg Exp $
- */
-
-#include <string.h>	/* memcpy()/memset() or bcopy()/bzero() */
-#include <assert.h>	/* assert() */
-#include "cm_sha2.h"	/* "sha2.h" -> "cm_sha2.h" renamed for CMake */
-
-/*
- * ASSERT NOTE:
- * Some sanity checking code is included using assert().  On my FreeBSD
- * system, this additional code can be removed by compiling with NDEBUG
- * defined.  Check your own systems manpage on assert() to see how to
- * compile WITHOUT the sanity checking code on your system.
- *
- * UNROLLED TRANSFORM LOOP NOTE:
- * You can define SHA2_UNROLL_TRANSFORM to use the unrolled transform
- * loop version for the hash transform rounds (defined using macros
- * later in this file).  Either define on the command line, for example:
- *
- *   cc -DSHA2_UNROLL_TRANSFORM -o sha2 sha2.c sha2prog.c
- *
- * or define below:
- *
- *   #define SHA2_UNROLL_TRANSFORM
- *
- */
-
-
-/*** SHA-224/256/384/512 Machine Architecture Definitions *************/
-/*
- * BYTE_ORDER NOTE:
- *
- * Please make sure that your system defines BYTE_ORDER.  If your
- * architecture is little-endian, make sure it also defines
- * LITTLE_ENDIAN and that the two (BYTE_ORDER and LITTLE_ENDIAN) are
- * equivilent.
- *
- * If your system does not define the above, then you can do so by
- * hand like this:
- *
- *   #define LITTLE_ENDIAN 1234
- *   #define BIG_ENDIAN    4321
- *
- * And for little-endian machines, add:
- *
- *   #define BYTE_ORDER LITTLE_ENDIAN
- *
- * Or for big-endian machines:
- *
- *   #define BYTE_ORDER BIG_ENDIAN
- *
- * The FreeBSD machine this was written on defines BYTE_ORDER
- * appropriately by including <sys/types.h> (which in turn includes
- * <machine/endian.h> where the appropriate definitions are actually
- * made).
- */
-#if !defined(BYTE_ORDER) || (BYTE_ORDER != LITTLE_ENDIAN && BYTE_ORDER != BIG_ENDIAN)
-/* CMake modification: use byte order from KWIML.  */
-# undef BYTE_ORDER
-# undef BIG_ENDIAN
-# undef LITTLE_ENDIAN
-# define BYTE_ORDER    KWIML_ABI_ENDIAN_ID
-# define BIG_ENDIAN    KWIML_ABI_ENDIAN_ID_BIG
-# define LITTLE_ENDIAN KWIML_ABI_ENDIAN_ID_LITTLE
-#endif
-
-/* CMake modification: use types computed in header.  */
-typedef cm_sha2_uint8_t  sha_byte;	/* Exactly 1 byte */
-typedef cm_sha2_uint32_t sha_word32;	/* Exactly 4 bytes */
-typedef cm_sha2_uint64_t sha_word64;	/* Exactly 8 bytes */
-#define SHA_UINT32_C(x) KWIML_INT_UINT32_C(x)
-#define SHA_UINT64_C(x) KWIML_INT_UINT64_C(x)
-#if defined(__clang__)
-# pragma clang diagnostic ignored "-Wcast-align"
-#endif
-
-/*** ENDIAN REVERSAL MACROS *******************************************/
-#if BYTE_ORDER == LITTLE_ENDIAN
-#define REVERSE32(w,x)	{ \
-	sha_word32 tmp = (w); \
-	tmp = (tmp >> 16) | (tmp << 16); \
-	(x) = ((tmp & SHA_UINT32_C(0xff00ff00)) >> 8) | \
-	      ((tmp & SHA_UINT32_C(0x00ff00ff)) << 8); \
-}
-#define REVERSE64(w,x)	{ \
-	sha_word64 tmp = (w); \
-	tmp = (tmp >> 32) | (tmp << 32); \
-	tmp = ((tmp & SHA_UINT64_C(0xff00ff00ff00ff00)) >> 8) | \
-	      ((tmp & SHA_UINT64_C(0x00ff00ff00ff00ff)) << 8); \
-	(x) = ((tmp & SHA_UINT64_C(0xffff0000ffff0000)) >> 16) | \
-	      ((tmp & SHA_UINT64_C(0x0000ffff0000ffff)) << 16); \
-}
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
-
-/*
- * Macro for incrementally adding the unsigned 64-bit integer n to the
- * unsigned 128-bit integer (represented using a two-element array of
- * 64-bit words):
- */
-#define ADDINC128(w,n)	{ \
-	(w)[0] += (sha_word64)(n); \
-	if ((w)[0] < (n)) { \
-		(w)[1]++; \
-	} \
-}
-
-/*
- * Macros for copying blocks of memory and for zeroing out ranges
- * of memory.  Using these macros makes it easy to switch from
- * using memset()/memcpy() and using bzero()/bcopy().
- *
- * Please define either SHA2_USE_MEMSET_MEMCPY or define
- * SHA2_USE_BZERO_BCOPY depending on which function set you
- * choose to use:
- */
-#if !defined(SHA2_USE_MEMSET_MEMCPY) && !defined(SHA2_USE_BZERO_BCOPY)
-/* Default to memset()/memcpy() if no option is specified */
-#define	SHA2_USE_MEMSET_MEMCPY	1
-#endif
-#if defined(SHA2_USE_MEMSET_MEMCPY) && defined(SHA2_USE_BZERO_BCOPY)
-/* Abort with an error if BOTH options are defined */
-#error Define either SHA2_USE_MEMSET_MEMCPY or SHA2_USE_BZERO_BCOPY, not both!
-#endif
-
-#ifdef SHA2_USE_MEMSET_MEMCPY
-#define MEMSET_BZERO(p,l)	memset((p), 0, (l))
-#define MEMCPY_BCOPY(d,s,l)	memcpy((d), (s), (l))
-#endif
-#ifdef SHA2_USE_BZERO_BCOPY
-#define MEMSET_BZERO(p,l)	bzero((p), (l))
-#define MEMCPY_BCOPY(d,s,l)	bcopy((s), (d), (l))
-#endif
-
-
-/*** THE SIX LOGICAL FUNCTIONS ****************************************/
-/*
- * Bit shifting and rotation (used by the six SHA-XYZ logical functions:
- *
- *   NOTE:  In the original SHA-256/384/512 document, the shift-right
- *   function was named R and the rotate-right function was called S.
- *   (See: http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf on the
- *   web.)
- *
- *   The newer NIST FIPS 180-2 document uses a much clearer naming
- *   scheme, SHR for shift-right, ROTR for rotate-right, and ROTL for
- *   rotate-left.  (See:
- *   http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
- *   on the web.)
- *
- *   WARNING: These macros must be used cautiously, since they reference
- *   supplied parameters sometimes more than once, and thus could have
- *   unexpected side-effects if used without taking this into account.
- */
-/* Shift-right (used in SHA-256, SHA-384, and SHA-512): */
-#define SHR(b,x) 		((x) >> (b))
-/* 32-bit Rotate-right (used in SHA-256): */
-#define ROTR32(b,x)	(((x) >> (b)) | ((x) << (32 - (b))))
-/* 64-bit Rotate-right (used in SHA-384 and SHA-512): */
-#define ROTR64(b,x)	(((x) >> (b)) | ((x) << (64 - (b))))
-/* 32-bit Rotate-left (used in SHA-1): */
-#define ROTL32(b,x)	(((x) << (b)) | ((x) >> (32 - (b))))
-
-/* Two logical functions used in SHA-1, SHA-254, SHA-256, SHA-384, and SHA-512: */
-#define Ch(x,y,z)	(((x) & (y)) ^ ((~(x)) & (z)))
-#define Maj(x,y,z)	(((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
-
-/* Function used in SHA-1: */
-#define Parity(x,y,z)	((x) ^ (y) ^ (z))
-
-/* Four logical functions used in SHA-256: */
-#define Sigma0_256(x)	(ROTR32(2,  (x)) ^ ROTR32(13, (x)) ^ ROTR32(22, (x)))
-#define Sigma1_256(x)	(ROTR32(6,  (x)) ^ ROTR32(11, (x)) ^ ROTR32(25, (x)))
-#define sigma0_256(x)	(ROTR32(7,  (x)) ^ ROTR32(18, (x)) ^ SHR(   3 , (x)))
-#define sigma1_256(x)	(ROTR32(17, (x)) ^ ROTR32(19, (x)) ^ SHR(   10, (x)))
-
-/* Four of six logical functions used in SHA-384 and SHA-512: */
-#define Sigma0_512(x)	(ROTR64(28, (x)) ^ ROTR64(34, (x)) ^ ROTR64(39, (x)))
-#define Sigma1_512(x)	(ROTR64(14, (x)) ^ ROTR64(18, (x)) ^ ROTR64(41, (x)))
-#define sigma0_512(x)	(ROTR64( 1, (x)) ^ ROTR64( 8, (x)) ^ SHR(    7, (x)))
-#define sigma1_512(x)	(ROTR64(19, (x)) ^ ROTR64(61, (x)) ^ SHR(    6, (x)))
-
-/*** INTERNAL FUNCTION PROTOTYPES *************************************/
-
-/* SHA-224 and SHA-256: */
-void SHA256_Internal_Init(SHA_CTX*, const sha_word32*);
-void SHA256_Internal_Last(SHA_CTX*);
-void SHA256_Internal_Transform(SHA_CTX*, const sha_word32*);
-
-/* SHA-384 and SHA-512: */
-void SHA512_Internal_Init(SHA_CTX*, const sha_word64*);
-void SHA512_Internal_Last(SHA_CTX*);
-void SHA512_Internal_Transform(SHA_CTX*, const sha_word64*);
-
-
-/*** SHA2 INITIAL HASH VALUES AND CONSTANTS ***************************/
-
-/* Hash constant words K for SHA-1: */
-#define K1_0_TO_19	SHA_UINT32_C(0x5a827999)
-#define K1_20_TO_39	SHA_UINT32_C(0x6ed9eba1)
-#define K1_40_TO_59	SHA_UINT32_C(0x8f1bbcdc)
-#define K1_60_TO_79	SHA_UINT32_C(0xca62c1d6)
-
-/* Initial hash value H for SHA-1: */
-static const sha_word32 sha1_initial_hash_value[5] = {
-	SHA_UINT32_C(0x67452301),
-	SHA_UINT32_C(0xefcdab89),
-	SHA_UINT32_C(0x98badcfe),
-	SHA_UINT32_C(0x10325476),
-	SHA_UINT32_C(0xc3d2e1f0)
-};
-
-/* Hash constant words K for SHA-224 and SHA-256: */
-static const sha_word32 K256[64] = {
-	SHA_UINT32_C(0x428a2f98), SHA_UINT32_C(0x71374491),
-	SHA_UINT32_C(0xb5c0fbcf), SHA_UINT32_C(0xe9b5dba5),
-	SHA_UINT32_C(0x3956c25b), SHA_UINT32_C(0x59f111f1),
-	SHA_UINT32_C(0x923f82a4), SHA_UINT32_C(0xab1c5ed5),
-	SHA_UINT32_C(0xd807aa98), SHA_UINT32_C(0x12835b01),
-	SHA_UINT32_C(0x243185be), SHA_UINT32_C(0x550c7dc3),
-	SHA_UINT32_C(0x72be5d74), SHA_UINT32_C(0x80deb1fe),
-	SHA_UINT32_C(0x9bdc06a7), SHA_UINT32_C(0xc19bf174),
-	SHA_UINT32_C(0xe49b69c1), SHA_UINT32_C(0xefbe4786),
-	SHA_UINT32_C(0x0fc19dc6), SHA_UINT32_C(0x240ca1cc),
-	SHA_UINT32_C(0x2de92c6f), SHA_UINT32_C(0x4a7484aa),
-	SHA_UINT32_C(0x5cb0a9dc), SHA_UINT32_C(0x76f988da),
-	SHA_UINT32_C(0x983e5152), SHA_UINT32_C(0xa831c66d),
-	SHA_UINT32_C(0xb00327c8), SHA_UINT32_C(0xbf597fc7),
-	SHA_UINT32_C(0xc6e00bf3), SHA_UINT32_C(0xd5a79147),
-	SHA_UINT32_C(0x06ca6351), SHA_UINT32_C(0x14292967),
-	SHA_UINT32_C(0x27b70a85), SHA_UINT32_C(0x2e1b2138),
-	SHA_UINT32_C(0x4d2c6dfc), SHA_UINT32_C(0x53380d13),
-	SHA_UINT32_C(0x650a7354), SHA_UINT32_C(0x766a0abb),
-	SHA_UINT32_C(0x81c2c92e), SHA_UINT32_C(0x92722c85),
-	SHA_UINT32_C(0xa2bfe8a1), SHA_UINT32_C(0xa81a664b),
-	SHA_UINT32_C(0xc24b8b70), SHA_UINT32_C(0xc76c51a3),
-	SHA_UINT32_C(0xd192e819), SHA_UINT32_C(0xd6990624),
-	SHA_UINT32_C(0xf40e3585), SHA_UINT32_C(0x106aa070),
-	SHA_UINT32_C(0x19a4c116), SHA_UINT32_C(0x1e376c08),
-	SHA_UINT32_C(0x2748774c), SHA_UINT32_C(0x34b0bcb5),
-	SHA_UINT32_C(0x391c0cb3), SHA_UINT32_C(0x4ed8aa4a),
-	SHA_UINT32_C(0x5b9cca4f), SHA_UINT32_C(0x682e6ff3),
-	SHA_UINT32_C(0x748f82ee), SHA_UINT32_C(0x78a5636f),
-	SHA_UINT32_C(0x84c87814), SHA_UINT32_C(0x8cc70208),
-	SHA_UINT32_C(0x90befffa), SHA_UINT32_C(0xa4506ceb),
-	SHA_UINT32_C(0xbef9a3f7), SHA_UINT32_C(0xc67178f2)
-};
-
-/* Initial hash value H for SHA-224: */
-static const sha_word32 sha224_initial_hash_value[8] = {
-	SHA_UINT32_C(0xc1059ed8),
-	SHA_UINT32_C(0x367cd507),
-	SHA_UINT32_C(0x3070dd17),
-	SHA_UINT32_C(0xf70e5939),
-	SHA_UINT32_C(0xffc00b31),
-	SHA_UINT32_C(0x68581511),
-	SHA_UINT32_C(0x64f98fa7),
-	SHA_UINT32_C(0xbefa4fa4)
-};
-
-/* Initial hash value H for SHA-256: */
-static const sha_word32 sha256_initial_hash_value[8] = {
-	SHA_UINT32_C(0x6a09e667),
-	SHA_UINT32_C(0xbb67ae85),
-	SHA_UINT32_C(0x3c6ef372),
-	SHA_UINT32_C(0xa54ff53a),
-	SHA_UINT32_C(0x510e527f),
-	SHA_UINT32_C(0x9b05688c),
-	SHA_UINT32_C(0x1f83d9ab),
-	SHA_UINT32_C(0x5be0cd19)
-};
-
-/* Hash constant words K for SHA-384 and SHA-512: */
-static const sha_word64 K512[80] = {
-	SHA_UINT64_C(0x428a2f98d728ae22), SHA_UINT64_C(0x7137449123ef65cd),
-	SHA_UINT64_C(0xb5c0fbcfec4d3b2f), SHA_UINT64_C(0xe9b5dba58189dbbc),
-	SHA_UINT64_C(0x3956c25bf348b538), SHA_UINT64_C(0x59f111f1b605d019),
-	SHA_UINT64_C(0x923f82a4af194f9b), SHA_UINT64_C(0xab1c5ed5da6d8118),
-	SHA_UINT64_C(0xd807aa98a3030242), SHA_UINT64_C(0x12835b0145706fbe),
-	SHA_UINT64_C(0x243185be4ee4b28c), SHA_UINT64_C(0x550c7dc3d5ffb4e2),
-	SHA_UINT64_C(0x72be5d74f27b896f), SHA_UINT64_C(0x80deb1fe3b1696b1),
-	SHA_UINT64_C(0x9bdc06a725c71235), SHA_UINT64_C(0xc19bf174cf692694),
-	SHA_UINT64_C(0xe49b69c19ef14ad2), SHA_UINT64_C(0xefbe4786384f25e3),
-	SHA_UINT64_C(0x0fc19dc68b8cd5b5), SHA_UINT64_C(0x240ca1cc77ac9c65),
-	SHA_UINT64_C(0x2de92c6f592b0275), SHA_UINT64_C(0x4a7484aa6ea6e483),
-	SHA_UINT64_C(0x5cb0a9dcbd41fbd4), SHA_UINT64_C(0x76f988da831153b5),
-	SHA_UINT64_C(0x983e5152ee66dfab), SHA_UINT64_C(0xa831c66d2db43210),
-	SHA_UINT64_C(0xb00327c898fb213f), SHA_UINT64_C(0xbf597fc7beef0ee4),
-	SHA_UINT64_C(0xc6e00bf33da88fc2), SHA_UINT64_C(0xd5a79147930aa725),
-	SHA_UINT64_C(0x06ca6351e003826f), SHA_UINT64_C(0x142929670a0e6e70),
-	SHA_UINT64_C(0x27b70a8546d22ffc), SHA_UINT64_C(0x2e1b21385c26c926),
-	SHA_UINT64_C(0x4d2c6dfc5ac42aed), SHA_UINT64_C(0x53380d139d95b3df),
-	SHA_UINT64_C(0x650a73548baf63de), SHA_UINT64_C(0x766a0abb3c77b2a8),
-	SHA_UINT64_C(0x81c2c92e47edaee6), SHA_UINT64_C(0x92722c851482353b),
-	SHA_UINT64_C(0xa2bfe8a14cf10364), SHA_UINT64_C(0xa81a664bbc423001),
-	SHA_UINT64_C(0xc24b8b70d0f89791), SHA_UINT64_C(0xc76c51a30654be30),
-	SHA_UINT64_C(0xd192e819d6ef5218), SHA_UINT64_C(0xd69906245565a910),
-	SHA_UINT64_C(0xf40e35855771202a), SHA_UINT64_C(0x106aa07032bbd1b8),
-	SHA_UINT64_C(0x19a4c116b8d2d0c8), SHA_UINT64_C(0x1e376c085141ab53),
-	SHA_UINT64_C(0x2748774cdf8eeb99), SHA_UINT64_C(0x34b0bcb5e19b48a8),
-	SHA_UINT64_C(0x391c0cb3c5c95a63), SHA_UINT64_C(0x4ed8aa4ae3418acb),
-	SHA_UINT64_C(0x5b9cca4f7763e373), SHA_UINT64_C(0x682e6ff3d6b2b8a3),
-	SHA_UINT64_C(0x748f82ee5defb2fc), SHA_UINT64_C(0x78a5636f43172f60),
-	SHA_UINT64_C(0x84c87814a1f0ab72), SHA_UINT64_C(0x8cc702081a6439ec),
-	SHA_UINT64_C(0x90befffa23631e28), SHA_UINT64_C(0xa4506cebde82bde9),
-	SHA_UINT64_C(0xbef9a3f7b2c67915), SHA_UINT64_C(0xc67178f2e372532b),
-	SHA_UINT64_C(0xca273eceea26619c), SHA_UINT64_C(0xd186b8c721c0c207),
-	SHA_UINT64_C(0xeada7dd6cde0eb1e), SHA_UINT64_C(0xf57d4f7fee6ed178),
-	SHA_UINT64_C(0x06f067aa72176fba), SHA_UINT64_C(0x0a637dc5a2c898a6),
-	SHA_UINT64_C(0x113f9804bef90dae), SHA_UINT64_C(0x1b710b35131c471b),
-	SHA_UINT64_C(0x28db77f523047d84), SHA_UINT64_C(0x32caab7b40c72493),
-	SHA_UINT64_C(0x3c9ebe0a15c9bebc), SHA_UINT64_C(0x431d67c49c100d4c),
-	SHA_UINT64_C(0x4cc5d4becb3e42b6), SHA_UINT64_C(0x597f299cfc657e2a),
-	SHA_UINT64_C(0x5fcb6fab3ad6faec), SHA_UINT64_C(0x6c44198c4a475817)
-};
-
-/* Initial hash value H for SHA-384 */
-static const sha_word64 sha384_initial_hash_value[8] = {
-	SHA_UINT64_C(0xcbbb9d5dc1059ed8),
-	SHA_UINT64_C(0x629a292a367cd507),
-	SHA_UINT64_C(0x9159015a3070dd17),
-	SHA_UINT64_C(0x152fecd8f70e5939),
-	SHA_UINT64_C(0x67332667ffc00b31),
-	SHA_UINT64_C(0x8eb44a8768581511),
-	SHA_UINT64_C(0xdb0c2e0d64f98fa7),
-	SHA_UINT64_C(0x47b5481dbefa4fa4)
-};
-
-/* Initial hash value H for SHA-512 */
-static const sha_word64 sha512_initial_hash_value[8] = {
-	SHA_UINT64_C(0x6a09e667f3bcc908),
-	SHA_UINT64_C(0xbb67ae8584caa73b),
-	SHA_UINT64_C(0x3c6ef372fe94f82b),
-	SHA_UINT64_C(0xa54ff53a5f1d36f1),
-	SHA_UINT64_C(0x510e527fade682d1),
-	SHA_UINT64_C(0x9b05688c2b3e6c1f),
-	SHA_UINT64_C(0x1f83d9abfb41bd6b),
-	SHA_UINT64_C(0x5be0cd19137e2179)
-};
-
-/*
- * Constant used by SHA224/256/384/512_End() functions for converting the
- * digest to a readable hexadecimal character string:
- */
-static const char *sha_hex_digits = "0123456789abcdef";
-
-
-/*** SHA-1: ***********************************************************/
-void SHA1_Init(SHA_CTX* context) {
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0);
-
-	MEMCPY_BCOPY(context->s1.state, sha1_initial_hash_value, sizeof(sha_word32) * 5);
-	MEMSET_BZERO(context->s1.buffer, 64);
-	context->s1.bitcount = 0;
-}
-
-#ifdef SHA2_UNROLL_TRANSFORM
-
-/* Unrolled SHA-1 round macros: */
-
-#if BYTE_ORDER == LITTLE_ENDIAN
-
-#define ROUND1_0_TO_15(a,b,c,d,e)				\
-	REVERSE32(*data++, W1[j]);				\
-	(e) = ROTL32(5, (a)) + Ch((b), (c), (d)) + (e) +	\
-	     K1_0_TO_19 + W1[j];	\
-	(b) = ROTL32(30, (b));		\
-	j++;
-
-#else /* BYTE_ORDER == LITTLE_ENDIAN */
-
-#define ROUND1_0_TO_15(a,b,c,d,e)				\
-	(e) = ROTL32(5, (a)) + Ch((b), (c), (d)) + (e) +	\
-	     K1_0_TO_19 + ( W1[j] = *data++ );		\
-	(b) = ROTL32(30, (b));	\
-	j++;
-
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
-
-#define ROUND1_16_TO_19(a,b,c,d,e)	\
-	T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];	\
-	(e) = ROTL32(5, a) + Ch(b,c,d) + e + K1_0_TO_19 + ( W1[j&0x0f] = ROTL32(1, T1) );	\
-	(b) = ROTL32(30, b);	\
-	j++;
-
-#define ROUND1_20_TO_39(a,b,c,d,e)	\
-	T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];	\
-	(e) = ROTL32(5, a) + Parity(b,c,d) + e + K1_20_TO_39 + ( W1[j&0x0f] = ROTL32(1, T1) );	\
-	(b) = ROTL32(30, b);	\
-	j++;
-
-#define ROUND1_40_TO_59(a,b,c,d,e)	\
-	T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];	\
-	(e) = ROTL32(5, a) + Maj(b,c,d) + e + K1_40_TO_59 + ( W1[j&0x0f] = ROTL32(1, T1) );	\
-	(b) = ROTL32(30, b);	\
-	j++;
-
-#define ROUND1_60_TO_79(a,b,c,d,e)	\
-	T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];	\
-	(e) = ROTL32(5, a) + Parity(b,c,d) + e + K1_60_TO_79 + ( W1[j&0x0f] = ROTL32(1, T1) );	\
-	(b) = ROTL32(30, b);	\
-	j++;
-
-void SHA1_Internal_Transform(SHA_CTX* context, const sha_word32* data) {
-	sha_word32	a, b, c, d, e;
-	sha_word32	T1, *W1;
-	int		j;
-
-	W1 = (sha_word32*)context->s1.buffer;
-
-	/* Initialize registers with the prev. intermediate value */
-	a = context->s1.state[0];
-	b = context->s1.state[1];
-	c = context->s1.state[2];
-	d = context->s1.state[3];
-	e = context->s1.state[4];
-
-	j = 0;
-
-	/* Rounds 0 to 15 unrolled: */
-	ROUND1_0_TO_15(a,b,c,d,e);
-	ROUND1_0_TO_15(e,a,b,c,d);
-	ROUND1_0_TO_15(d,e,a,b,c);
-	ROUND1_0_TO_15(c,d,e,a,b);
-	ROUND1_0_TO_15(b,c,d,e,a);
-	ROUND1_0_TO_15(a,b,c,d,e);
-	ROUND1_0_TO_15(e,a,b,c,d);
-	ROUND1_0_TO_15(d,e,a,b,c);
-	ROUND1_0_TO_15(c,d,e,a,b);
-	ROUND1_0_TO_15(b,c,d,e,a);
-	ROUND1_0_TO_15(a,b,c,d,e);
-	ROUND1_0_TO_15(e,a,b,c,d);
-	ROUND1_0_TO_15(d,e,a,b,c);
-	ROUND1_0_TO_15(c,d,e,a,b);
-	ROUND1_0_TO_15(b,c,d,e,a);
-	ROUND1_0_TO_15(a,b,c,d,e);
-
-	/* Rounds 16 to 19 unrolled: */
-	ROUND1_16_TO_19(e,a,b,c,d);
-	ROUND1_16_TO_19(d,e,a,b,c);
-	ROUND1_16_TO_19(c,d,e,a,b);
-	ROUND1_16_TO_19(b,c,d,e,a);
-
-	/* Rounds 20 to 39 unrolled: */
-	ROUND1_20_TO_39(a,b,c,d,e);
-	ROUND1_20_TO_39(e,a,b,c,d);
-	ROUND1_20_TO_39(d,e,a,b,c);
-	ROUND1_20_TO_39(c,d,e,a,b);
-	ROUND1_20_TO_39(b,c,d,e,a);
-	ROUND1_20_TO_39(a,b,c,d,e);
-	ROUND1_20_TO_39(e,a,b,c,d);
-	ROUND1_20_TO_39(d,e,a,b,c);
-	ROUND1_20_TO_39(c,d,e,a,b);
-	ROUND1_20_TO_39(b,c,d,e,a);
-	ROUND1_20_TO_39(a,b,c,d,e);
-	ROUND1_20_TO_39(e,a,b,c,d);
-	ROUND1_20_TO_39(d,e,a,b,c);
-	ROUND1_20_TO_39(c,d,e,a,b);
-	ROUND1_20_TO_39(b,c,d,e,a);
-	ROUND1_20_TO_39(a,b,c,d,e);
-	ROUND1_20_TO_39(e,a,b,c,d);
-	ROUND1_20_TO_39(d,e,a,b,c);
-	ROUND1_20_TO_39(c,d,e,a,b);
-	ROUND1_20_TO_39(b,c,d,e,a);
-
-	/* Rounds 40 to 59 unrolled: */
-	ROUND1_40_TO_59(a,b,c,d,e);
-	ROUND1_40_TO_59(e,a,b,c,d);
-	ROUND1_40_TO_59(d,e,a,b,c);
-	ROUND1_40_TO_59(c,d,e,a,b);
-	ROUND1_40_TO_59(b,c,d,e,a);
-	ROUND1_40_TO_59(a,b,c,d,e);
-	ROUND1_40_TO_59(e,a,b,c,d);
-	ROUND1_40_TO_59(d,e,a,b,c);
-	ROUND1_40_TO_59(c,d,e,a,b);
-	ROUND1_40_TO_59(b,c,d,e,a);
-	ROUND1_40_TO_59(a,b,c,d,e);
-	ROUND1_40_TO_59(e,a,b,c,d);
-	ROUND1_40_TO_59(d,e,a,b,c);
-	ROUND1_40_TO_59(c,d,e,a,b);
-	ROUND1_40_TO_59(b,c,d,e,a);
-	ROUND1_40_TO_59(a,b,c,d,e);
-	ROUND1_40_TO_59(e,a,b,c,d);
-	ROUND1_40_TO_59(d,e,a,b,c);
-	ROUND1_40_TO_59(c,d,e,a,b);
-	ROUND1_40_TO_59(b,c,d,e,a);
-
-	/* Rounds 60 to 79 unrolled: */
-	ROUND1_60_TO_79(a,b,c,d,e);
-	ROUND1_60_TO_79(e,a,b,c,d);
-	ROUND1_60_TO_79(d,e,a,b,c);
-	ROUND1_60_TO_79(c,d,e,a,b);
-	ROUND1_60_TO_79(b,c,d,e,a);
-	ROUND1_60_TO_79(a,b,c,d,e);
-	ROUND1_60_TO_79(e,a,b,c,d);
-	ROUND1_60_TO_79(d,e,a,b,c);
-	ROUND1_60_TO_79(c,d,e,a,b);
-	ROUND1_60_TO_79(b,c,d,e,a);
-	ROUND1_60_TO_79(a,b,c,d,e);
-	ROUND1_60_TO_79(e,a,b,c,d);
-	ROUND1_60_TO_79(d,e,a,b,c);
-	ROUND1_60_TO_79(c,d,e,a,b);
-	ROUND1_60_TO_79(b,c,d,e,a);
-	ROUND1_60_TO_79(a,b,c,d,e);
-	ROUND1_60_TO_79(e,a,b,c,d);
-	ROUND1_60_TO_79(d,e,a,b,c);
-	ROUND1_60_TO_79(c,d,e,a,b);
-	ROUND1_60_TO_79(b,c,d,e,a);
-
-	/* Compute the current intermediate hash value */
-	context->s1.state[0] += a;
-	context->s1.state[1] += b;
-	context->s1.state[2] += c;
-	context->s1.state[3] += d;
-	context->s1.state[4] += e;
-
-	/* Clean up */
-	a = b = c = d = e = T1 = 0;
-}
-
-#else  /* SHA2_UNROLL_TRANSFORM */
-
-void SHA1_Internal_Transform(SHA_CTX* context, const sha_word32* data) {
-	sha_word32	a, b, c, d, e;
-	sha_word32	T1, *W1;
-	int		j;
-
-	W1 = (sha_word32*)context->s1.buffer;
-
-	/* Initialize registers with the prev. intermediate value */
-	a = context->s1.state[0];
-	b = context->s1.state[1];
-	c = context->s1.state[2];
-	d = context->s1.state[3];
-	e = context->s1.state[4];
-	j = 0;
-	do {
-#if BYTE_ORDER == LITTLE_ENDIAN
-		T1 = data[j];
-		/* Copy data while converting to host byte order */
-		REVERSE32(*data++, W1[j]);
-		T1 = ROTL32(5, a) + Ch(b, c, d) + e + K1_0_TO_19 + W1[j];
-#else /* BYTE_ORDER == LITTLE_ENDIAN */
-		T1 = ROTL32(5, a) + Ch(b, c, d) + e + K1_0_TO_19 + (W1[j] = *data++);
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
-		e = d;
-		d = c;
-		c = ROTL32(30, b);
-		b = a;
-		a = T1;
-		j++;
-	} while (j < 16);
-
-	do {
-		T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];
-		T1 = ROTL32(5, a) + Ch(b,c,d) + e + K1_0_TO_19 + (W1[j&0x0f] = ROTL32(1, T1));
-		e = d;
-		d = c;
-		c = ROTL32(30, b);
-		b = a;
-		a = T1;
-		j++;
-	} while (j < 20);
-
-	do {
-		T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];
-		T1 = ROTL32(5, a) + Parity(b,c,d) + e + K1_20_TO_39 + (W1[j&0x0f] = ROTL32(1, T1));
-		e = d;
-		d = c;
-		c = ROTL32(30, b);
-		b = a;
-		a = T1;
-		j++;
-	} while (j < 40);
-
-	do {
-		T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];
-		T1 = ROTL32(5, a) + Maj(b,c,d) + e + K1_40_TO_59 + (W1[j&0x0f] = ROTL32(1, T1));
-		e = d;
-		d = c;
-		c = ROTL32(30, b);
-		b = a;
-		a = T1;
-		j++;
-	} while (j < 60);
-
-	do {
-		T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];
-		T1 = ROTL32(5, a) + Parity(b,c,d) + e + K1_60_TO_79 + (W1[j&0x0f] = ROTL32(1, T1));
-		e = d;
-		d = c;
-		c = ROTL32(30, b);
-		b = a;
-		a = T1;
-		j++;
-	} while (j < 80);
-
-
-	/* Compute the current intermediate hash value */
-	context->s1.state[0] += a;
-	context->s1.state[1] += b;
-	context->s1.state[2] += c;
-	context->s1.state[3] += d;
-	context->s1.state[4] += e;
-
-	/* Clean up */
-	a = b = c = d = e = T1 = 0;
-}
-
-#endif /* SHA2_UNROLL_TRANSFORM */
-
-void SHA1_Update(SHA_CTX* context, const sha_byte *data, size_t len) {
-	unsigned int	freespace, usedspace;
-	if (len == 0) {
-		/* Calling with no data is valid - we do nothing */
-		return;
-	}
-
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0 && data != (sha_byte*)0);
-
-	usedspace = (unsigned int)((context->s1.bitcount >> 3) % 64);
-	if (usedspace > 0) {
-		/* Calculate how much free space is available in the buffer */
-		freespace = 64 - usedspace;
-
-		if (len >= freespace) {
-			/* Fill the buffer completely and process it */
-			MEMCPY_BCOPY(&context->s1.buffer[usedspace], data, freespace);
-			context->s1.bitcount += freespace << 3;
-			len -= freespace;
-			data += freespace;
-			SHA1_Internal_Transform(context, (const sha_word32*)context->s1.buffer);
-		} else {
-			/* The buffer is not yet full */
-			MEMCPY_BCOPY(&context->s1.buffer[usedspace], data, len);
-			context->s1.bitcount += len << 3;
-			/* Clean up: */
-			usedspace = freespace = 0;
-			return;
-		}
-	}
-	while (len >= 64) {
-		/* Process as many complete blocks as we can */
-		SHA1_Internal_Transform(context, (const sha_word32*)data);
-		context->s1.bitcount += 512;
-		len -= 64;
-		data += 64;
-	}
-	if (len > 0) {
-		/* There's left-overs, so save 'em */
-		MEMCPY_BCOPY(context->s1.buffer, data, len);
-		context->s1.bitcount += len << 3;
-	}
-	/* Clean up: */
-	usedspace = freespace = 0;
-}
-
-void SHA1_Final(sha_byte digest[], SHA_CTX* context) {
-	sha_word32	*d = (sha_word32*)digest;
-	unsigned int	usedspace;
-
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0);
-
-	if (digest == (sha_byte*)0) {
-		/*
-		 * No digest buffer, so we can do nothing
-		 * except clean up and go home
-		 */
-		MEMSET_BZERO(context, sizeof(*context));
-		return;
-	}
-
-	usedspace = (unsigned int)((context->s1.bitcount >> 3) % 64);
-	if (usedspace == 0) {
-		/* Set-up for the last transform: */
-		MEMSET_BZERO(context->s1.buffer, 56);
-
-		/* Begin padding with a 1 bit: */
-		*context->s1.buffer = 0x80;
-	} else {
-		/* Begin padding with a 1 bit: */
-		context->s1.buffer[usedspace++] = 0x80;
-
-		if (usedspace <= 56) {
-			/* Set-up for the last transform: */
-			MEMSET_BZERO(&context->s1.buffer[usedspace], 56 - usedspace);
-		} else {
-			if (usedspace < 64) {
-				MEMSET_BZERO(&context->s1.buffer[usedspace], 64 - usedspace);
-			}
-			/* Do second-to-last transform: */
-			SHA1_Internal_Transform(context, (const sha_word32*)context->s1.buffer);
-
-			/* And set-up for the last transform: */
-			MEMSET_BZERO(context->s1.buffer, 56);
-		}
-		/* Clean up: */
-		usedspace = 0;
-	}
-	/* Set the bit count: */
-#if BYTE_ORDER == LITTLE_ENDIAN
-	/* Convert FROM host byte order */
-	REVERSE64(context->s1.bitcount,context->s1.bitcount);
-#endif
-	MEMCPY_BCOPY(&context->s1.buffer[56], &context->s1.bitcount,
-		     sizeof(sha_word64));
-
-	/* Final transform: */
-	SHA1_Internal_Transform(context, (const sha_word32*)context->s1.buffer);
-
-	/* Save the hash data for output: */
-#if BYTE_ORDER == LITTLE_ENDIAN
-	{
-		/* Convert TO host byte order */
-		int	j;
-		for (j = 0; j < (SHA1_DIGEST_LENGTH >> 2); j++) {
-			REVERSE32(context->s1.state[j],context->s1.state[j]);
-			*d++ = context->s1.state[j];
-		}
-	}
-#else
-	MEMCPY_BCOPY(d, context->s1.state, SHA1_DIGEST_LENGTH);
-#endif
-
-	/* Clean up: */
-	MEMSET_BZERO(context, sizeof(*context));
-}
-
-char *SHA1_End(SHA_CTX* context, char buffer[]) {
-	sha_byte	digest[SHA1_DIGEST_LENGTH], *d = digest;
-	int		i;
-
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0);
-
-	if (buffer != (char*)0) {
-		SHA1_Final(digest, context);
-
-		for (i = 0; i < SHA1_DIGEST_LENGTH; i++) {
-			*buffer++ = sha_hex_digits[(*d & 0xf0) >> 4];
-			*buffer++ = sha_hex_digits[*d & 0x0f];
-			d++;
-		}
-		*buffer = (char)0;
-	} else {
-		MEMSET_BZERO(context, sizeof(*context));
-	}
-	MEMSET_BZERO(digest, SHA1_DIGEST_LENGTH);
-	return buffer;
-}
-
-char* SHA1_Data(const sha_byte* data, size_t len, char digest[SHA1_DIGEST_STRING_LENGTH]) {
-	SHA_CTX	context;
-
-	SHA1_Init(&context);
-	SHA1_Update(&context, data, len);
-	return SHA1_End(&context, digest);
-}
-
-
-/*** SHA-256: *********************************************************/
-void SHA256_Internal_Init(SHA_CTX* context, const sha_word32* ihv) {
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0);
-
-	MEMCPY_BCOPY(context->s256.state, ihv, sizeof(sha_word32) * 8);
-	MEMSET_BZERO(context->s256.buffer, 64);
-	context->s256.bitcount = 0;
-}
-
-void SHA256_Init(SHA_CTX* context) {
-	SHA256_Internal_Init(context, sha256_initial_hash_value);
-}
-
-#ifdef SHA2_UNROLL_TRANSFORM
-
-/* Unrolled SHA-256 round macros: */
-
-#if BYTE_ORDER == LITTLE_ENDIAN
-
-#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h)	\
-	REVERSE32(*data++, W256[j]); \
-	T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \
-	     K256[j] + W256[j]; \
-	(d) += T1; \
-	(h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
-	j++
-
-
-#else /* BYTE_ORDER == LITTLE_ENDIAN */
-
-#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h)	\
-	T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \
-	     K256[j] + (W256[j] = *data++); \
-	(d) += T1; \
-	(h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
-	j++
-
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
-
-#define ROUND256(a,b,c,d,e,f,g,h)	\
-	s0 = W256[(j+1)&0x0f]; \
-	s0 = sigma0_256(s0); \
-	s1 = W256[(j+14)&0x0f]; \
-	s1 = sigma1_256(s1); \
-	T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + \
-	     (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \
-	(d) += T1; \
-	(h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
-	j++
-
-void SHA256_Internal_Transform(SHA_CTX* context, const sha_word32* data) {
-	sha_word32	a, b, c, d, e, f, g, h, s0, s1;
-	sha_word32	T1, *W256;
-	int		j;
-
-	W256 = (sha_word32*)context->s256.buffer;
-
-	/* Initialize registers with the prev. intermediate value */
-	a = context->s256.state[0];
-	b = context->s256.state[1];
-	c = context->s256.state[2];
-	d = context->s256.state[3];
-	e = context->s256.state[4];
-	f = context->s256.state[5];
-	g = context->s256.state[6];
-	h = context->s256.state[7];
-
-	j = 0;
-	do {
-		/* Rounds 0 to 15 (unrolled): */
-		ROUND256_0_TO_15(a,b,c,d,e,f,g,h);
-		ROUND256_0_TO_15(h,a,b,c,d,e,f,g);
-		ROUND256_0_TO_15(g,h,a,b,c,d,e,f);
-		ROUND256_0_TO_15(f,g,h,a,b,c,d,e);
-		ROUND256_0_TO_15(e,f,g,h,a,b,c,d);
-		ROUND256_0_TO_15(d,e,f,g,h,a,b,c);
-		ROUND256_0_TO_15(c,d,e,f,g,h,a,b);
-		ROUND256_0_TO_15(b,c,d,e,f,g,h,a);
-	} while (j < 16);
-
-	/* Now for the remaining rounds to 64: */
-	do {
-		ROUND256(a,b,c,d,e,f,g,h);
-		ROUND256(h,a,b,c,d,e,f,g);
-		ROUND256(g,h,a,b,c,d,e,f);
-		ROUND256(f,g,h,a,b,c,d,e);
-		ROUND256(e,f,g,h,a,b,c,d);
-		ROUND256(d,e,f,g,h,a,b,c);
-		ROUND256(c,d,e,f,g,h,a,b);
-		ROUND256(b,c,d,e,f,g,h,a);
-	} while (j < 64);
-
-	/* Compute the current intermediate hash value */
-	context->s256.state[0] += a;
-	context->s256.state[1] += b;
-	context->s256.state[2] += c;
-	context->s256.state[3] += d;
-	context->s256.state[4] += e;
-	context->s256.state[5] += f;
-	context->s256.state[6] += g;
-	context->s256.state[7] += h;
-
-	/* Clean up */
-	a = b = c = d = e = f = g = h = T1 = 0;
-}
-
-#else /* SHA2_UNROLL_TRANSFORM */
-
-void SHA256_Internal_Transform(SHA_CTX* context, const sha_word32* data) {
-	sha_word32	a, b, c, d, e, f, g, h, s0, s1;
-	sha_word32	T1, T2, *W256;
-	int		j;
-
-	W256 = (sha_word32*)context->s256.buffer;
-
-	/* Initialize registers with the prev. intermediate value */
-	a = context->s256.state[0];
-	b = context->s256.state[1];
-	c = context->s256.state[2];
-	d = context->s256.state[3];
-	e = context->s256.state[4];
-	f = context->s256.state[5];
-	g = context->s256.state[6];
-	h = context->s256.state[7];
-
-	j = 0;
-	do {
-#if BYTE_ORDER == LITTLE_ENDIAN
-		/* Copy data while converting to host byte order */
-		REVERSE32(*data++,W256[j]);
-		/* Apply the SHA-256 compression function to update a..h */
-		T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j];
-#else /* BYTE_ORDER == LITTLE_ENDIAN */
-		/* Apply the SHA-256 compression function to update a..h with copy */
-		T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j] = *data++);
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
-		T2 = Sigma0_256(a) + Maj(a, b, c);
-		h = g;
-		g = f;
-		f = e;
-		e = d + T1;
-		d = c;
-		c = b;
-		b = a;
-		a = T1 + T2;
-
-		j++;
-	} while (j < 16);
-
-	do {
-		/* Part of the message block expansion: */
-		s0 = W256[(j+1)&0x0f];
-		s0 = sigma0_256(s0);
-		s1 = W256[(j+14)&0x0f];
-		s1 = sigma1_256(s1);
-
-		/* Apply the SHA-256 compression function to update a..h */
-		T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] +
-		     (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0);
-		T2 = Sigma0_256(a) + Maj(a, b, c);
-		h = g;
-		g = f;
-		f = e;
-		e = d + T1;
-		d = c;
-		c = b;
-		b = a;
-		a = T1 + T2;
-
-		j++;
-	} while (j < 64);
-
-	/* Compute the current intermediate hash value */
-	context->s256.state[0] += a;
-	context->s256.state[1] += b;
-	context->s256.state[2] += c;
-	context->s256.state[3] += d;
-	context->s256.state[4] += e;
-	context->s256.state[5] += f;
-	context->s256.state[6] += g;
-	context->s256.state[7] += h;
-
-	/* Clean up */
-	a = b = c = d = e = f = g = h = T1 = T2 = 0;
-}
-
-#endif /* SHA2_UNROLL_TRANSFORM */
-
-void SHA256_Update(SHA_CTX* context, const sha_byte *data, size_t len) {
-	unsigned int	freespace, usedspace;
-
-	if (len == 0) {
-		/* Calling with no data is valid - we do nothing */
-		return;
-	}
-
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0 && data != (sha_byte*)0);
-
-	usedspace = (unsigned int)((context->s256.bitcount >> 3) % 64);
-	if (usedspace > 0) {
-		/* Calculate how much free space is available in the buffer */
-		freespace = 64 - usedspace;
-
-		if (len >= freespace) {
-			/* Fill the buffer completely and process it */
-			MEMCPY_BCOPY(&context->s256.buffer[usedspace], data, freespace);
-			context->s256.bitcount += freespace << 3;
-			len -= freespace;
-			data += freespace;
-			SHA256_Internal_Transform(context, (const sha_word32*)context->s256.buffer);
-		} else {
-			/* The buffer is not yet full */
-			MEMCPY_BCOPY(&context->s256.buffer[usedspace], data, len);
-			context->s256.bitcount += len << 3;
-			/* Clean up: */
-			usedspace = freespace = 0;
-			return;
-		}
-	}
-	while (len >= 64) {
-		/* Process as many complete blocks as we can */
-		SHA256_Internal_Transform(context, (const sha_word32*)data);
-		context->s256.bitcount += 512;
-		len -= 64;
-		data += 64;
-	}
-	if (len > 0) {
-		/* There's left-overs, so save 'em */
-		MEMCPY_BCOPY(context->s256.buffer, data, len);
-		context->s256.bitcount += len << 3;
-	}
-	/* Clean up: */
-	usedspace = freespace = 0;
-}
-
-void SHA256_Internal_Last(SHA_CTX* context) {
-	unsigned int	usedspace;
-
-	usedspace = (unsigned int)((context->s256.bitcount >> 3) % 64);
-#if BYTE_ORDER == LITTLE_ENDIAN
-	/* Convert FROM host byte order */
-	REVERSE64(context->s256.bitcount,context->s256.bitcount);
-#endif
-	if (usedspace > 0) {
-		/* Begin padding with a 1 bit: */
-		context->s256.buffer[usedspace++] = 0x80;
-
-		if (usedspace <= 56) {
-			/* Set-up for the last transform: */
-			MEMSET_BZERO(&context->s256.buffer[usedspace], 56 - usedspace);
-		} else {
-			if (usedspace < 64) {
-				MEMSET_BZERO(&context->s256.buffer[usedspace], 64 - usedspace);
-			}
-			/* Do second-to-last transform: */
-			SHA256_Internal_Transform(context, (const sha_word32*)context->s256.buffer);
-
-			/* And set-up for the last transform: */
-			MEMSET_BZERO(context->s256.buffer, 56);
-		}
-		/* Clean up: */
-		usedspace = 0;
-	} else {
-		/* Set-up for the last transform: */
-		MEMSET_BZERO(context->s256.buffer, 56);
-
-		/* Begin padding with a 1 bit: */
-		*context->s256.buffer = 0x80;
-	}
-	/* Set the bit count: */
-	MEMCPY_BCOPY(&context->s256.buffer[56], &context->s256.bitcount,
-		     sizeof(sha_word64));
-
-	/* Final transform: */
-	SHA256_Internal_Transform(context, (const sha_word32*)context->s256.buffer);
-}
-
-void SHA256_Final(sha_byte digest[], SHA_CTX* context) {
-	sha_word32	*d = (sha_word32*)digest;
-
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0);
-
-	/* If no digest buffer is passed, we don't bother doing this: */
-	if (digest != (sha_byte*)0) {
-		SHA256_Internal_Last(context);
-
-		/* Save the hash data for output: */
-#if BYTE_ORDER == LITTLE_ENDIAN
-		{
-			/* Convert TO host byte order */
-			int	j;
-			for (j = 0; j < (SHA256_DIGEST_LENGTH >> 2); j++) {
-				REVERSE32(context->s256.state[j],context->s256.state[j]);
-				*d++ = context->s256.state[j];
-			}
-		}
-#else
-		MEMCPY_BCOPY(d, context->s256.state, SHA256_DIGEST_LENGTH);
-#endif
-	}
-
-	/* Clean up state data: */
-	MEMSET_BZERO(context, sizeof(*context));
-}
-
-char *SHA256_End(SHA_CTX* context, char buffer[]) {
-	sha_byte	digest[SHA256_DIGEST_LENGTH], *d = digest;
-	int		i;
-
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0);
-
-	if (buffer != (char*)0) {
-		SHA256_Final(digest, context);
-
-		for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
-			*buffer++ = sha_hex_digits[(*d & 0xf0) >> 4];
-			*buffer++ = sha_hex_digits[*d & 0x0f];
-			d++;
-		}
-		*buffer = (char)0;
-	} else {
-		MEMSET_BZERO(context, sizeof(*context));
-	}
-	MEMSET_BZERO(digest, SHA256_DIGEST_LENGTH);
-	return buffer;
-}
-
-char* SHA256_Data(const sha_byte* data, size_t len, char digest[SHA256_DIGEST_STRING_LENGTH]) {
-	SHA_CTX	context;
-
-	SHA256_Init(&context);
-	SHA256_Update(&context, data, len);
-	return SHA256_End(&context, digest);
-}
-
-
-/*** SHA-224: *********************************************************/
-void SHA224_Init(SHA_CTX* context) {
-	SHA256_Internal_Init(context, sha224_initial_hash_value);
-}
-
-void SHA224_Internal_Transform(SHA_CTX* context, const sha_word32* data) {
-	SHA256_Internal_Transform(context, data);
-}
-
-void SHA224_Update(SHA_CTX* context, const sha_byte *data, size_t len) {
-	SHA256_Update(context, data, len);
-}
-
-void SHA224_Final(sha_byte digest[], SHA_CTX* context) {
-	sha_word32	*d = (sha_word32*)digest;
-
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0);
-
-	/* If no digest buffer is passed, we don't bother doing this: */
-	if (digest != (sha_byte*)0) {
-		SHA256_Internal_Last(context);
-
-		/* Save the hash data for output: */
-#if BYTE_ORDER == LITTLE_ENDIAN
-		{
-			/* Convert TO host byte order */
-			int	j;
-			for (j = 0; j < (SHA224_DIGEST_LENGTH >> 2); j++) {
-				REVERSE32(context->s256.state[j],context->s256.state[j]);
-				*d++ = context->s256.state[j];
-			}
-		}
-#else
-		MEMCPY_BCOPY(d, context->s256.state, SHA224_DIGEST_LENGTH);
-#endif
-	}
-
-	/* Clean up state data: */
-	MEMSET_BZERO(context, sizeof(*context));
-}
-
-char *SHA224_End(SHA_CTX* context, char buffer[]) {
-	sha_byte	digest[SHA224_DIGEST_LENGTH], *d = digest;
-	int		i;
-
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0);
-
-	if (buffer != (char*)0) {
-		SHA224_Final(digest, context);
-
-		for (i = 0; i < SHA224_DIGEST_LENGTH; i++) {
-			*buffer++ = sha_hex_digits[(*d & 0xf0) >> 4];
-			*buffer++ = sha_hex_digits[*d & 0x0f];
-			d++;
-		}
-		*buffer = (char)0;
-	} else {
-		MEMSET_BZERO(context, sizeof(*context));
-	}
-	MEMSET_BZERO(digest, SHA224_DIGEST_LENGTH);
-	return buffer;
-}
-
-char* SHA224_Data(const sha_byte* data, size_t len, char digest[SHA224_DIGEST_STRING_LENGTH]) {
-	SHA_CTX	context;
-
-	SHA224_Init(&context);
-	SHA224_Update(&context, data, len);
-	return SHA224_End(&context, digest);
-}
-
-
-/*** SHA-512: *********************************************************/
-void SHA512_Internal_Init(SHA_CTX* context, const sha_word64* ihv) {
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0);
-
-	MEMCPY_BCOPY(context->s512.state, ihv, sizeof(sha_word64) * 8);
-	MEMSET_BZERO(context->s512.buffer, 128);
-	context->s512.bitcount[0] = context->s512.bitcount[1] =  0;
-}
-
-void SHA512_Init(SHA_CTX* context) {
-	SHA512_Internal_Init(context, sha512_initial_hash_value);
-}
-
-#ifdef SHA2_UNROLL_TRANSFORM
-
-/* Unrolled SHA-512 round macros: */
-#if BYTE_ORDER == LITTLE_ENDIAN
-
-#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h)	\
-	REVERSE64(*data++, W512[j]); \
-	T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \
-	     K512[j] + W512[j]; \
-	(d) += T1, \
-	(h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)), \
-	j++
-
-
-#else /* BYTE_ORDER == LITTLE_ENDIAN */
-
-#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h)	\
-	T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \
-	     K512[j] + (W512[j] = *data++); \
-	(d) += T1; \
-	(h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \
-	j++
-
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
-
-#define ROUND512(a,b,c,d,e,f,g,h)	\
-	s0 = W512[(j+1)&0x0f]; \
-	s0 = sigma0_512(s0); \
-	s1 = W512[(j+14)&0x0f]; \
-	s1 = sigma1_512(s1); \
-	T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] + \
-	     (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); \
-	(d) += T1; \
-	(h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \
-	j++
-
-void SHA512_Internal_Transform(SHA_CTX* context, const sha_word64* data) {
-	sha_word64	a, b, c, d, e, f, g, h, s0, s1;
-	sha_word64	T1, *W512 = (sha_word64*)context->s512.buffer;
-	int		j;
-
-	/* Initialize registers with the prev. intermediate value */
-	a = context->s512.state[0];
-	b = context->s512.state[1];
-	c = context->s512.state[2];
-	d = context->s512.state[3];
-	e = context->s512.state[4];
-	f = context->s512.state[5];
-	g = context->s512.state[6];
-	h = context->s512.state[7];
-
-	j = 0;
-	do {
-		ROUND512_0_TO_15(a,b,c,d,e,f,g,h);
-		ROUND512_0_TO_15(h,a,b,c,d,e,f,g);
-		ROUND512_0_TO_15(g,h,a,b,c,d,e,f);
-		ROUND512_0_TO_15(f,g,h,a,b,c,d,e);
-		ROUND512_0_TO_15(e,f,g,h,a,b,c,d);
-		ROUND512_0_TO_15(d,e,f,g,h,a,b,c);
-		ROUND512_0_TO_15(c,d,e,f,g,h,a,b);
-		ROUND512_0_TO_15(b,c,d,e,f,g,h,a);
-	} while (j < 16);
-
-	/* Now for the remaining rounds up to 79: */
-	do {
-		ROUND512(a,b,c,d,e,f,g,h);
-		ROUND512(h,a,b,c,d,e,f,g);
-		ROUND512(g,h,a,b,c,d,e,f);
-		ROUND512(f,g,h,a,b,c,d,e);
-		ROUND512(e,f,g,h,a,b,c,d);
-		ROUND512(d,e,f,g,h,a,b,c);
-		ROUND512(c,d,e,f,g,h,a,b);
-		ROUND512(b,c,d,e,f,g,h,a);
-	} while (j < 80);
-
-	/* Compute the current intermediate hash value */
-	context->s512.state[0] += a;
-	context->s512.state[1] += b;
-	context->s512.state[2] += c;
-	context->s512.state[3] += d;
-	context->s512.state[4] += e;
-	context->s512.state[5] += f;
-	context->s512.state[6] += g;
-	context->s512.state[7] += h;
-
-	/* Clean up */
-	a = b = c = d = e = f = g = h = T1 = 0;
-}
-
-#else /* SHA2_UNROLL_TRANSFORM */
-
-void SHA512_Internal_Transform(SHA_CTX* context, const sha_word64* data) {
-	sha_word64	a, b, c, d, e, f, g, h, s0, s1;
-	sha_word64	T1, T2, *W512 = (sha_word64*)context->s512.buffer;
-	int		j;
-
-	/* Initialize registers with the prev. intermediate value */
-	a = context->s512.state[0];
-	b = context->s512.state[1];
-	c = context->s512.state[2];
-	d = context->s512.state[3];
-	e = context->s512.state[4];
-	f = context->s512.state[5];
-	g = context->s512.state[6];
-	h = context->s512.state[7];
-
-	j = 0;
-	do {
-#if BYTE_ORDER == LITTLE_ENDIAN
-		/* Convert TO host byte order */
-		REVERSE64(*data++, W512[j]);
-		/* Apply the SHA-512 compression function to update a..h */
-		T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j];
-#else /* BYTE_ORDER == LITTLE_ENDIAN */
-		/* Apply the SHA-512 compression function to update a..h with copy */
-		T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j] = *data++);
-#endif /* BYTE_ORDER == LITTLE_ENDIAN */
-		T2 = Sigma0_512(a) + Maj(a, b, c);
-		h = g;
-		g = f;
-		f = e;
-		e = d + T1;
-		d = c;
-		c = b;
-		b = a;
-		a = T1 + T2;
-
-		j++;
-	} while (j < 16);
-
-	do {
-		/* Part of the message block expansion: */
-		s0 = W512[(j+1)&0x0f];
-		s0 = sigma0_512(s0);
-		s1 = W512[(j+14)&0x0f];
-		s1 =  sigma1_512(s1);
-
-		/* Apply the SHA-512 compression function to update a..h */
-		T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] +
-		     (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0);
-		T2 = Sigma0_512(a) + Maj(a, b, c);
-		h = g;
-		g = f;
-		f = e;
-		e = d + T1;
-		d = c;
-		c = b;
-		b = a;
-		a = T1 + T2;
-
-		j++;
-	} while (j < 80);
-
-	/* Compute the current intermediate hash value */
-	context->s512.state[0] += a;
-	context->s512.state[1] += b;
-	context->s512.state[2] += c;
-	context->s512.state[3] += d;
-	context->s512.state[4] += e;
-	context->s512.state[5] += f;
-	context->s512.state[6] += g;
-	context->s512.state[7] += h;
-
-	/* Clean up */
-	a = b = c = d = e = f = g = h = T1 = T2 = 0;
-}
-
-#endif /* SHA2_UNROLL_TRANSFORM */
-
-void SHA512_Update(SHA_CTX* context, const sha_byte *data, size_t len) {
-	unsigned int	freespace, usedspace;
-
-	if (len == 0) {
-		/* Calling with no data is valid - we do nothing */
-		return;
-	}
-
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0 && data != (sha_byte*)0);
-
-	usedspace = (unsigned int)((context->s512.bitcount[0] >> 3) % 128);
-	if (usedspace > 0) {
-		/* Calculate how much free space is available in the buffer */
-		freespace = 128 - usedspace;
-
-		if (len >= freespace) {
-			/* Fill the buffer completely and process it */
-			MEMCPY_BCOPY(&context->s512.buffer[usedspace], data, freespace);
-			ADDINC128(context->s512.bitcount, freespace << 3);
-			len -= freespace;
-			data += freespace;
-			SHA512_Internal_Transform(context, (const sha_word64*)context->s512.buffer);
-		} else {
-			/* The buffer is not yet full */
-			MEMCPY_BCOPY(&context->s512.buffer[usedspace], data, len);
-			ADDINC128(context->s512.bitcount, len << 3);
-			/* Clean up: */
-			usedspace = freespace = 0;
-			return;
-		}
-	}
-	while (len >= 128) {
-		/* Process as many complete blocks as we can */
-		SHA512_Internal_Transform(context, (const sha_word64*)data);
-		ADDINC128(context->s512.bitcount, 1024);
-		len -= 128;
-		data += 128;
-	}
-	if (len > 0) {
-		/* There's left-overs, so save 'em */
-		MEMCPY_BCOPY(context->s512.buffer, data, len);
-		ADDINC128(context->s512.bitcount, len << 3);
-	}
-	/* Clean up: */
-	usedspace = freespace = 0;
-}
-
-void SHA512_Internal_Last(SHA_CTX* context) {
-	unsigned int	usedspace;
-
-	usedspace = (unsigned int)((context->s512.bitcount[0] >> 3) % 128);
-#if BYTE_ORDER == LITTLE_ENDIAN
-	/* Convert FROM host byte order */
-	REVERSE64(context->s512.bitcount[0],context->s512.bitcount[0]);
-	REVERSE64(context->s512.bitcount[1],context->s512.bitcount[1]);
-#endif
-	if (usedspace > 0) {
-		/* Begin padding with a 1 bit: */
-		context->s512.buffer[usedspace++] = 0x80;
-
-		if (usedspace <= 112) {
-			/* Set-up for the last transform: */
-			MEMSET_BZERO(&context->s512.buffer[usedspace], 112 - usedspace);
-		} else {
-			if (usedspace < 128) {
-				MEMSET_BZERO(&context->s512.buffer[usedspace], 128 - usedspace);
-			}
-			/* Do second-to-last transform: */
-			SHA512_Internal_Transform(context, (const sha_word64*)context->s512.buffer);
-
-			/* And set-up for the last transform: */
-			MEMSET_BZERO(context->s512.buffer, 112);
-		}
-		/* Clean up: */
-		usedspace = 0;
-	} else {
-		/* Prepare for final transform: */
-		MEMSET_BZERO(context->s512.buffer, 112);
-
-		/* Begin padding with a 1 bit: */
-		*context->s512.buffer = 0x80;
-	}
-	/* Store the length of input data (in bits): */
-	MEMCPY_BCOPY(&context->s512.buffer[112], &context->s512.bitcount[1],
-		     sizeof(sha_word64));
-	MEMCPY_BCOPY(&context->s512.buffer[120], &context->s512.bitcount[0],
-		     sizeof(sha_word64));
-
-	/* Final transform: */
-	SHA512_Internal_Transform(context, (const sha_word64*)context->s512.buffer);
-}
-
-void SHA512_Final(sha_byte digest[], SHA_CTX* context) {
-	sha_word64	*d = (sha_word64*)digest;
-
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0);
-
-	/* If no digest buffer is passed, we don't bother doing this: */
-	if (digest != (sha_byte*)0) {
-		SHA512_Internal_Last(context);
-
-		/* Save the hash data for output: */
-#if BYTE_ORDER == LITTLE_ENDIAN
-		{
-			/* Convert TO host byte order */
-			int	j;
-			for (j = 0; j < (SHA512_DIGEST_LENGTH >> 3); j++) {
-				REVERSE64(context->s512.state[j],context->s512.state[j]);
-				*d++ = context->s512.state[j];
-			}
-		}
-#else
-		MEMCPY_BCOPY(d, context->s512.state, SHA512_DIGEST_LENGTH);
-#endif
-	}
-
-	/* Zero out state data */
-	MEMSET_BZERO(context, sizeof(*context));
-}
-
-char *SHA512_End(SHA_CTX* context, char buffer[]) {
-	sha_byte	digest[SHA512_DIGEST_LENGTH], *d = digest;
-	int		i;
-
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0);
-
-	if (buffer != (char*)0) {
-		SHA512_Final(digest, context);
-
-		for (i = 0; i < SHA512_DIGEST_LENGTH; i++) {
-			*buffer++ = sha_hex_digits[(*d & 0xf0) >> 4];
-			*buffer++ = sha_hex_digits[*d & 0x0f];
-			d++;
-		}
-		*buffer = (char)0;
-	} else {
-		MEMSET_BZERO(context, sizeof(*context));
-	}
-	MEMSET_BZERO(digest, SHA512_DIGEST_LENGTH);
-	return buffer;
-}
-
-char* SHA512_Data(const sha_byte* data, size_t len, char digest[SHA512_DIGEST_STRING_LENGTH]) {
-	SHA_CTX	context;
-
-	SHA512_Init(&context);
-	SHA512_Update(&context, data, len);
-	return SHA512_End(&context, digest);
-}
-
-
-/*** SHA-384: *********************************************************/
-void SHA384_Init(SHA_CTX* context) {
-	SHA512_Internal_Init(context, sha384_initial_hash_value);
-}
-
-void SHA384_Update(SHA_CTX* context, const sha_byte* data, size_t len) {
-	SHA512_Update(context, data, len);
-}
-
-void SHA384_Final(sha_byte digest[], SHA_CTX* context) {
-	sha_word64	*d = (sha_word64*)digest;
-
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0);
-
-	/* If no digest buffer is passed, we don't bother doing this: */
-	if (digest != (sha_byte*)0) {
-		SHA512_Internal_Last(context);
-
-		/* Save the hash data for output: */
-#if BYTE_ORDER == LITTLE_ENDIAN
-		{
-			/* Convert TO host byte order */
-			int	j;
-			for (j = 0; j < (SHA384_DIGEST_LENGTH >> 3); j++) {
-				REVERSE64(context->s512.state[j],context->s512.state[j]);
-				*d++ = context->s512.state[j];
-			}
-		}
-#else
-		MEMCPY_BCOPY(d, context->s512.state, SHA384_DIGEST_LENGTH);
-#endif
-	}
-
-	/* Zero out state data */
-	MEMSET_BZERO(context, sizeof(*context));
-}
-
-char *SHA384_End(SHA_CTX* context, char buffer[]) {
-	sha_byte	digest[SHA384_DIGEST_LENGTH], *d = digest;
-	int		i;
-
-	/* Sanity check: */
-	assert(context != (SHA_CTX*)0);
-
-	if (buffer != (char*)0) {
-		SHA384_Final(digest, context);
-
-		for (i = 0; i < SHA384_DIGEST_LENGTH; i++) {
-			*buffer++ = sha_hex_digits[(*d & 0xf0) >> 4];
-			*buffer++ = sha_hex_digits[*d & 0x0f];
-			d++;
-		}
-		*buffer = (char)0;
-	} else {
-		MEMSET_BZERO(context, sizeof(*context));
-	}
-	MEMSET_BZERO(digest, SHA384_DIGEST_LENGTH);
-	return buffer;
-}
-
-char* SHA384_Data(const sha_byte* data, size_t len, char digest[SHA384_DIGEST_STRING_LENGTH]) {
-	SHA_CTX	context;
-
-	SHA384_Init(&context);
-	SHA384_Update(&context, data, len);
-	return SHA384_End(&context, digest);
-}
diff --git a/Source/cm_sha2.h b/Source/cm_sha2.h
deleted file mode 100644
index f151031..0000000
--- a/Source/cm_sha2.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * FILE:    sha2.h
- * AUTHOR:  Aaron D. Gifford
- *          http://www.aarongifford.com/computers/sha.html
- *
- * Copyright (c) 2000-2003, Aaron D. Gifford
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the copyright holder nor the names of contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * $Id: sha2.h,v 1.4 2004/01/07 19:06:18 adg Exp $
- */
-
-#ifndef __SHA2_H__
-#define __SHA2_H__
-
-#include "cm_sha2_mangle.h"
-
-/* CMake modification: use integer types from KWIML.  */
-#include <cm_kwiml.h>
-typedef KWIML_INT_uint8_t cm_sha2_uint8_t;
-typedef KWIML_INT_uint32_t cm_sha2_uint32_t;
-typedef KWIML_INT_uint64_t cm_sha2_uint64_t;
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/*
- * Import u_intXX_t size_t type definitions from system headers.  You
- * may need to change this, or define these things yourself in this
- * file.
- */
-#include <sys/types.h>
-
-/*** SHA-224/256/384/512 Various Length Definitions *******************/
-
-/* Digest lengths for SHA-1/224/256/384/512 */
-#define   SHA1_DIGEST_LENGTH          20
-#define   SHA1_DIGEST_STRING_LENGTH  (SHA1_DIGEST_LENGTH   * 2 + 1)
-#define SHA224_DIGEST_LENGTH          28
-#define SHA224_DIGEST_STRING_LENGTH  (SHA224_DIGEST_LENGTH * 2 + 1)
-#define SHA256_DIGEST_LENGTH          32
-#define SHA256_DIGEST_STRING_LENGTH  (SHA256_DIGEST_LENGTH * 2 + 1)
-#define SHA384_DIGEST_LENGTH          48
-#define SHA384_DIGEST_STRING_LENGTH  (SHA384_DIGEST_LENGTH * 2 + 1)
-#define SHA512_DIGEST_LENGTH          64
-#define SHA512_DIGEST_STRING_LENGTH  (SHA512_DIGEST_LENGTH * 2 + 1)
-
-
-/*** SHA-224/256/384/512 Context Structures ***************************/
-
-typedef union _SHA_CTX {
-    /* SHA-1 uses this part of the union: */
-    struct {
-	cm_sha2_uint32_t state[5];
-	cm_sha2_uint64_t bitcount;
-	cm_sha2_uint8_t  buffer[64];
-    } s1;
-
-    /* SHA-224 and SHA-256 use this part of the union: */
-    struct {
-	cm_sha2_uint32_t state[8];
-	cm_sha2_uint64_t bitcount;
-	cm_sha2_uint8_t  buffer[64];
-    } s256;
-
-    /* SHA-384 and SHA-512 use this part of the union: */
-    struct {
-	cm_sha2_uint64_t state[8];
-	cm_sha2_uint64_t bitcount[2];
-	cm_sha2_uint8_t  buffer[128];
-    } s512;
-} SHA_CTX;
-
-/*** SHA-256/384/512 Function Prototypes ******************************/
-
-void SHA1_Init(SHA_CTX*);
-void SHA1_Update(SHA_CTX*, const cm_sha2_uint8_t*, size_t);
-void SHA1_Final(cm_sha2_uint8_t[SHA1_DIGEST_LENGTH], SHA_CTX*);
-char* SHA1_End(SHA_CTX*, char[SHA1_DIGEST_STRING_LENGTH]);
-char* SHA1_Data(const cm_sha2_uint8_t*, size_t,
-		char[SHA1_DIGEST_STRING_LENGTH]);
-
-void SHA224_Init(SHA_CTX*);
-void SHA224_Update(SHA_CTX*, const cm_sha2_uint8_t*, size_t);
-void SHA224_Final(cm_sha2_uint8_t[SHA224_DIGEST_LENGTH], SHA_CTX*);
-char* SHA224_End(SHA_CTX*, char[SHA224_DIGEST_STRING_LENGTH]);
-char* SHA224_Data(const cm_sha2_uint8_t*, size_t,
-		  char[SHA224_DIGEST_STRING_LENGTH]);
-
-void SHA256_Init(SHA_CTX*);
-void SHA256_Update(SHA_CTX*, const cm_sha2_uint8_t*, size_t);
-void SHA256_Final(cm_sha2_uint8_t[SHA256_DIGEST_LENGTH], SHA_CTX*);
-char* SHA256_End(SHA_CTX*, char[SHA256_DIGEST_STRING_LENGTH]);
-char* SHA256_Data(const cm_sha2_uint8_t*, size_t,
-		  char[SHA256_DIGEST_STRING_LENGTH]);
-
-void SHA384_Init(SHA_CTX*);
-void SHA384_Update(SHA_CTX*, const cm_sha2_uint8_t*, size_t);
-void SHA384_Final(cm_sha2_uint8_t[SHA384_DIGEST_LENGTH], SHA_CTX*);
-char* SHA384_End(SHA_CTX*, char[SHA384_DIGEST_STRING_LENGTH]);
-char* SHA384_Data(const cm_sha2_uint8_t*, size_t,
-		  char[SHA384_DIGEST_STRING_LENGTH]);
-
-void SHA512_Init(SHA_CTX*);
-void SHA512_Update(SHA_CTX*, const cm_sha2_uint8_t*, size_t);
-void SHA512_Final(cm_sha2_uint8_t[SHA512_DIGEST_LENGTH], SHA_CTX*);
-char* SHA512_End(SHA_CTX*, char[SHA512_DIGEST_STRING_LENGTH]);
-char* SHA512_Data(const cm_sha2_uint8_t*, size_t,
-		  char[SHA512_DIGEST_STRING_LENGTH]);
-
-#ifdef    __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* __SHA2_H__ */
diff --git a/Source/cm_sha2_mangle.h b/Source/cm_sha2_mangle.h
deleted file mode 100644
index 3dce819..0000000
--- a/Source/cm_sha2_mangle.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-   file Copyright.txt or https://cmake.org/licensing for details.  */
-#ifndef cm_sha2_mangle_h
-#define cm_sha2_mangle_h
-
-/* Mangle sha2 symbol names to avoid possible conflict with
-   implementations in other libraries to which CMake links.  */
-#define SHA1_Data                  cmSHA1_Data
-#define SHA1_End                   cmSHA1_End
-#define SHA1_Final                 cmSHA1_Final
-#define SHA1_Init                  cmSHA1_Init
-#define SHA1_Internal_Transform    cmSHA1_Internal_Transform
-#define SHA1_Update                cmSHA1_Update
-#define SHA224_Data                cmSHA224_Data
-#define SHA224_End                 cmSHA224_End
-#define SHA224_Final               cmSHA224_Final
-#define SHA224_Init                cmSHA224_Init
-#define SHA224_Internal_Transform  cmSHA224_Internal_Transform
-#define SHA224_Update              cmSHA224_Update
-#define SHA256_Data                cmSHA256_Data
-#define SHA256_End                 cmSHA256_End
-#define SHA256_Final               cmSHA256_Final
-#define SHA256_Init                cmSHA256_Init
-#define SHA256_Internal_Init       cmSHA256_Internal_Init
-#define SHA256_Internal_Last       cmSHA256_Internal_Last
-#define SHA256_Internal_Transform  cmSHA256_Internal_Transform
-#define SHA256_Update              cmSHA256_Update
-#define SHA384_Data                cmSHA384_Data
-#define SHA384_End                 cmSHA384_End
-#define SHA384_Final               cmSHA384_Final
-#define SHA384_Init                cmSHA384_Init
-#define SHA384_Update              cmSHA384_Update
-#define SHA512_Data                cmSHA512_Data
-#define SHA512_End                 cmSHA512_End
-#define SHA512_Final               cmSHA512_Final
-#define SHA512_Init                cmSHA512_Init
-#define SHA512_Internal_Init       cmSHA512_Internal_Init
-#define SHA512_Internal_Last       cmSHA512_Internal_Last
-#define SHA512_Internal_Transform  cmSHA512_Internal_Transform
-#define SHA512_Update              cmSHA512_Update
-
-#endif
diff --git a/Source/cm_unordered_map.hxx b/Source/cm_unordered_map.hxx
new file mode 100644
index 0000000..dc8ca35
--- /dev/null
+++ b/Source/cm_unordered_map.hxx
@@ -0,0 +1,25 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef CM_UNORDERED_MAP_HXX
+#define CM_UNORDERED_MAP_HXX
+
+#include <cmConfigure.h>
+
+#if defined(CMake_HAVE_CXX_UNORDERED_MAP)
+
+#include <unordered_map>
+#define CM_UNORDERED_MAP std::unordered_map
+
+#elif defined(CMAKE_BUILD_WITH_CMAKE)
+
+#include <cmsys/hash_map.hxx>
+#define CM_UNORDERED_MAP cmsys::hash_map
+
+#else
+
+#include <map>
+#define CM_UNORDERED_MAP std::map
+
+#endif
+
+#endif
diff --git a/Source/cm_unordered_set.hxx b/Source/cm_unordered_set.hxx
new file mode 100644
index 0000000..ce58dbf
--- /dev/null
+++ b/Source/cm_unordered_set.hxx
@@ -0,0 +1,25 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef CM_UNORDERED_SET_HXX
+#define CM_UNORDERED_SET_HXX
+
+#include <cmConfigure.h>
+
+#if defined(CMake_HAVE_CXX_UNORDERED_SET)
+
+#include <unordered_set>
+#define CM_UNORDERED_SET std::unordered_set
+
+#elif defined(CMAKE_BUILD_WITH_CMAKE)
+
+#include <cmsys/hash_set.hxx>
+#define CM_UNORDERED_SET cmsys::hash_set
+
+#else
+
+#include <set>
+#define CM_UNORDERED_SET std::set
+
+#endif
+
+#endif
diff --git a/Source/cmake.cxx b/Source/cmake.cxx
index f0caf0d..6141f50 100644
--- a/Source/cmake.cxx
+++ b/Source/cmake.cxx
@@ -12,10 +12,12 @@
 #include "cmGeneratorTarget.h"
 #include "cmGlobalGenerator.h"
 #include "cmGlobalGeneratorFactory.h"
+#include "cmLinkLineComputer.h"
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmMessenger.h"
 #include "cmState.h"
+#include "cmStateDirectory.h"
 #include "cmSystemTools.h"
 #include "cmTarget.h"
 #include "cmTargetLinkLibraryType.h"
@@ -24,10 +26,11 @@
 #include "cm_auto_ptr.hxx"
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
+#include <cm_jsoncpp_writer.h>
+
 #include "cmGraphVizWriter.h"
 #include "cmVariableWatch.h"
-
-#include <cm_jsoncpp_writer.h>
+#include "cm_unordered_map.hxx"
 #endif
 
 // only build kdevelop generator on non-windows platforms
@@ -61,6 +64,7 @@
 #include "cmGlobalVisualStudio71Generator.h"
 #include "cmGlobalVisualStudio8Generator.h"
 #include "cmGlobalVisualStudio9Generator.h"
+#include "cmVSSetupHelper.h"
 
 #define CMAKE_HAVE_VS_GENERATORS
 #endif
@@ -121,17 +125,13 @@ class cmCommand;
 namespace {
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
-#ifdef CMake_HAVE_CXX_UNORDERED_MAP
-typedef std::unordered_map<std::string, Json::Value> JsonValueMapType;
-#else
-typedef cmsys::hash_map<std::string, Json::Value> JsonValueMapType;
-#endif
+typedef CM_UNORDERED_MAP<std::string, Json::Value> JsonValueMapType;
 #endif
 
 } // namespace
 
-static bool cmakeCheckStampFile(const char* stampName);
-static bool cmakeCheckStampList(const char* stampName);
+static bool cmakeCheckStampFile(const char* stampName, bool verbose = true);
+static bool cmakeCheckStampList(const char* stampList, bool verbose = true);
 
 void cmWarnUnusedCliWarning(const std::string& variable, int /*unused*/,
                             void* ctx, const char* /*unused*/,
@@ -314,7 +314,7 @@ bool cmake::SetCacheArgs(const std::vector<std::string>& args)
         }
       }
       std::string var, value;
-      cmState::CacheEntryType type = cmState::UNINITIALIZED;
+      cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
       if (cmState::ParseCacheEntry(entry, var, value, type)) {
         // 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
@@ -409,8 +409,8 @@ bool cmake::SetCacheArgs(const std::vector<std::string>& args)
       std::vector<std::string> cacheKeys = this->State->GetCacheEntryKeys();
       for (std::vector<std::string>::const_iterator it = cacheKeys.begin();
            it != cacheKeys.end(); ++it) {
-        cmState::CacheEntryType t = this->State->GetCacheEntryType(*it);
-        if (t != cmState::STATIC) {
+        cmStateEnums::CacheEntryType t = this->State->GetCacheEntryType(*it);
+        if (t != cmStateEnums::STATIC) {
           if (regex.find(it->c_str())) {
             entriesToDelete.push_back(*it);
           }
@@ -480,7 +480,7 @@ void cmake::ReadListFile(const std::vector<std::string>& args,
     std::string homeOutputDir = this->GetHomeOutputDirectory();
     this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
     this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
-    cmState::Snapshot snapshot = this->GetCurrentSnapshot();
+    cmStateSnapshot snapshot = this->GetCurrentSnapshot();
     snapshot.GetDirectory().SetCurrentBinary(
       cmSystemTools::GetCurrentWorkingDirectory());
     snapshot.GetDirectory().SetCurrentSource(
@@ -516,7 +516,7 @@ bool cmake::FindPackage(const std::vector<std::string>& args)
   cmGlobalGenerator* gg = new cmGlobalGenerator(this);
   this->SetGlobalGenerator(gg);
 
-  cmState::Snapshot snapshot = this->GetCurrentSnapshot();
+  cmStateSnapshot snapshot = this->GetCurrentSnapshot();
   snapshot.GetDirectory().SetCurrentBinary(
     cmSystemTools::GetCurrentWorkingDirectory());
   snapshot.GetDirectory().SetCurrentSource(
@@ -568,7 +568,7 @@ bool cmake::FindPackage(const std::vector<std::string>& args)
     cmSystemTools::ExpandListArgument(libs, libList);
     for (std::vector<std::string>::const_iterator libIt = libList.begin();
          libIt != libList.end(); ++libIt) {
-      mf->AddLinkLibraryForTarget(targetName, *libIt, GENERAL_LibraryType);
+      tgt->AddLinkLibrary(*mf, *libIt, GENERAL_LibraryType);
     }
 
     std::string buildType = mf->GetSafeDefinition("CMAKE_BUILD_TYPE");
@@ -582,8 +582,10 @@ bool cmake::FindPackage(const std::vector<std::string>& args)
     gg->CreateGenerationObjects();
     cmGeneratorTarget* gtgt = gg->FindGeneratorTarget(tgt->GetName());
     cmLocalGenerator* lg = gtgt->GetLocalGenerator();
-    lg->GetTargetFlags(buildType, linkLibs, flags, linkFlags, frameworkPath,
-                       linkPath, gtgt, false);
+    cmLinkLineComputer linkLineComputer(lg,
+                                        lg->GetStateSnapshot().GetDirectory());
+    lg->GetTargetFlags(&linkLineComputer, buildType, linkLibs, flags,
+                       linkFlags, frameworkPath, linkPath, gtgt);
     linkLibs = frameworkPath + linkPath + linkLibs;
 
     printf("%s\n", linkLibs.c_str());
@@ -856,14 +858,14 @@ int cmake::AddCMakePaths()
   // Save the value in the cache
   this->AddCacheEntry("CMAKE_COMMAND",
                       cmSystemTools::GetCMakeCommand().c_str(),
-                      "Path to CMake executable.", cmState::INTERNAL);
+                      "Path to CMake executable.", cmStateEnums::INTERNAL);
 #ifdef CMAKE_BUILD_WITH_CMAKE
-  this->AddCacheEntry("CMAKE_CTEST_COMMAND",
-                      cmSystemTools::GetCTestCommand().c_str(),
-                      "Path to ctest program executable.", cmState::INTERNAL);
-  this->AddCacheEntry("CMAKE_CPACK_COMMAND",
-                      cmSystemTools::GetCPackCommand().c_str(),
-                      "Path to cpack program executable.", cmState::INTERNAL);
+  this->AddCacheEntry(
+    "CMAKE_CTEST_COMMAND", cmSystemTools::GetCTestCommand().c_str(),
+    "Path to ctest program executable.", cmStateEnums::INTERNAL);
+  this->AddCacheEntry(
+    "CMAKE_CPACK_COMMAND", cmSystemTools::GetCPackCommand().c_str(),
+    "Path to cpack program executable.", cmStateEnums::INTERNAL);
 #endif
   if (!cmSystemTools::FileExists(
         (cmSystemTools::GetCMakeRoot() + "/Modules/CMake.cmake").c_str())) {
@@ -876,7 +878,7 @@ int cmake::AddCMakePaths()
     return 0;
   }
   this->AddCacheEntry("CMAKE_ROOT", cmSystemTools::GetCMakeRoot().c_str(),
-                      "Path to CMake installation.", cmState::INTERNAL);
+                      "Path to CMake installation.", cmStateEnums::INTERNAL);
 
   return 1;
 }
@@ -1144,7 +1146,7 @@ struct SaveCacheEntry
   std::string key;
   std::string value;
   std::string help;
-  cmState::CacheEntryType type;
+  cmStateEnums::CacheEntryType type;
 };
 
 int cmake::HandleDeleteCacheVariables(const std::string& var)
@@ -1288,7 +1290,7 @@ int cmake::ActualConfigure()
       "CMAKE_HOME_DIRECTORY", this->GetHomeDirectory(),
       "Source directory with the top level CMakeLists.txt file for this "
       "project",
-      cmState::INTERNAL);
+      cmStateEnums::INTERNAL);
   }
 
   // no generator specified on the command line
@@ -1310,54 +1312,7 @@ int cmake::ActualConfigure()
       cmSystemTools::SetForceUnixPaths(
         this->GlobalGenerator->GetForceUnixPaths());
     } else {
-#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
-      std::string installedCompiler;
-      // Try to find the newest VS installed on the computer and
-      // use that as a default if -G is not specified
-      const std::string vsregBase =
-        "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\";
-      std::vector<std::string> vsVerions;
-      vsVerions.push_back("VisualStudio\\");
-      vsVerions.push_back("VCExpress\\");
-      vsVerions.push_back("WDExpress\\");
-      struct VSRegistryEntryName
-      {
-        const char* MSVersion;
-        const char* GeneratorName;
-      };
-      VSRegistryEntryName version[] = {
-        /* clang-format needs this comment to break after the opening brace */
-        { "7.1", "Visual Studio 7 .NET 2003" },
-        { "8.0", "Visual Studio 8 2005" },
-        { "9.0", "Visual Studio 9 2008" },
-        { "10.0", "Visual Studio 10 2010" },
-        { "11.0", "Visual Studio 11 2012" },
-        { "12.0", "Visual Studio 12 2013" },
-        { "14.0", "Visual Studio 14 2015" },
-        { "15.0", "Visual Studio 15 2017" },
-        { 0, 0 }
-      };
-      for (int i = 0; version[i].MSVersion != 0; i++) {
-        for (size_t b = 0; b < vsVerions.size(); b++) {
-          std::string reg = vsregBase + vsVerions[b] + version[i].MSVersion;
-          reg += ";InstallDir]";
-          cmSystemTools::ExpandRegistryValues(reg, cmSystemTools::KeyWOW64_32);
-          if (!(reg == "/registry")) {
-            installedCompiler = version[i].GeneratorName;
-            break;
-          }
-        }
-      }
-      cmGlobalGenerator* gen =
-        this->CreateGlobalGenerator(installedCompiler.c_str());
-      if (!gen) {
-        gen = new cmGlobalNMakeMakefileGenerator(this);
-      }
-      this->SetGlobalGenerator(gen);
-      std::cout << "-- Building for: " << gen->GetName() << "\n";
-#else
-      this->SetGlobalGenerator(new cmGlobalUnixMakefileGenerator3(this));
-#endif
+      this->CreateDefaultGlobalGenerator();
     }
     if (!this->GlobalGenerator) {
       cmSystemTools::Error("Could not create generator");
@@ -1382,11 +1337,11 @@ int cmake::ActualConfigure()
   if (!this->State->GetInitializedCacheValue("CMAKE_GENERATOR")) {
     this->AddCacheEntry("CMAKE_GENERATOR",
                         this->GlobalGenerator->GetName().c_str(),
-                        "Name of generator.", cmState::INTERNAL);
+                        "Name of generator.", cmStateEnums::INTERNAL);
     this->AddCacheEntry("CMAKE_EXTRA_GENERATOR",
                         this->GlobalGenerator->GetExtraGeneratorName().c_str(),
                         "Name of external makefile project generator.",
-                        cmState::INTERNAL);
+                        cmStateEnums::INTERNAL);
   }
 
   if (const char* platformName =
@@ -1406,7 +1361,7 @@ int cmake::ActualConfigure()
   } else {
     this->AddCacheEntry("CMAKE_GENERATOR_PLATFORM",
                         this->GeneratorPlatform.c_str(),
-                        "Name of generator platform.", cmState::INTERNAL);
+                        "Name of generator platform.", cmStateEnums::INTERNAL);
   }
 
   if (const char* tsName =
@@ -1426,7 +1381,7 @@ int cmake::ActualConfigure()
   } else {
     this->AddCacheEntry("CMAKE_GENERATOR_TOOLSET",
                         this->GeneratorToolset.c_str(),
-                        "Name of generator toolset.", cmState::INTERNAL);
+                        "Name of generator toolset.", cmStateEnums::INTERNAL);
   }
 
   // reset any system configuration information, except for when we are
@@ -1455,13 +1410,14 @@ int cmake::ActualConfigure()
     if (!this->State->GetInitializedCacheValue("LIBRARY_OUTPUT_PATH")) {
       this->AddCacheEntry(
         "LIBRARY_OUTPUT_PATH", "",
-        "Single output directory for building all libraries.", cmState::PATH);
+        "Single output directory for building all libraries.",
+        cmStateEnums::PATH);
     }
     if (!this->State->GetInitializedCacheValue("EXECUTABLE_OUTPUT_PATH")) {
       this->AddCacheEntry(
         "EXECUTABLE_OUTPUT_PATH", "",
         "Single output directory for building all executables.",
-        cmState::PATH);
+        cmStateEnums::PATH);
     }
   }
 
@@ -1485,6 +1441,68 @@ int cmake::ActualConfigure()
   return 0;
 }
 
+void cmake::CreateDefaultGlobalGenerator()
+{
+#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
+  std::string found;
+  // Try to find the newest VS installed on the computer and
+  // use that as a default if -G is not specified
+  const std::string vsregBase = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\";
+  static const char* const vsVariants[] = {
+    /* clang-format needs this comment to break after the opening brace */
+    "VisualStudio\\", "VCExpress\\", "WDExpress\\"
+  };
+  struct VSVersionedGenerator
+  {
+    const char* MSVersion;
+    const char* GeneratorName;
+  };
+  static VSVersionedGenerator const vsGenerators[] = {
+    { "15.0", "Visual Studio 15 2017" }, //
+    { "14.0", "Visual Studio 14 2015" }, //
+    { "12.0", "Visual Studio 12 2013" }, //
+    { "11.0", "Visual Studio 11 2012" }, //
+    { "10.0", "Visual Studio 10 2010" }, //
+    { "9.0", "Visual Studio 9 2008" },   //
+    { "8.0", "Visual Studio 8 2005" },   //
+    { "7.1", "Visual Studio 7 .NET 2003" }
+  };
+  static const char* const vsEntries[] = {
+    "\\Setup\\VC;ProductDir", //
+    ";InstallDir"             //
+  };
+  cmVSSetupAPIHelper vsSetupAPIHelper;
+  if (vsSetupAPIHelper.IsVS2017Installed()) {
+    found = "Visual Studio 15 2017";
+  } else {
+    for (VSVersionedGenerator const* g = cmArrayBegin(vsGenerators);
+         found.empty() && g != cmArrayEnd(vsGenerators); ++g) {
+      for (const char* const* v = cmArrayBegin(vsVariants);
+           found.empty() && v != cmArrayEnd(vsVariants); ++v) {
+        for (const char* const* e = cmArrayBegin(vsEntries);
+             found.empty() && e != cmArrayEnd(vsEntries); ++e) {
+          std::string const reg = vsregBase + *v + g->MSVersion + *e;
+          std::string dir;
+          if (cmSystemTools::ReadRegistryValue(reg, dir,
+                                               cmSystemTools::KeyWOW64_32) &&
+              cmSystemTools::PathExists(dir)) {
+            found = g->GeneratorName;
+          }
+        }
+      }
+    }
+  }
+  cmGlobalGenerator* gen = this->CreateGlobalGenerator(found);
+  if (!gen) {
+    gen = new cmGlobalNMakeMakefileGenerator(this);
+  }
+  this->SetGlobalGenerator(gen);
+  std::cout << "-- Building for: " << gen->GetName() << "\n";
+#else
+  this->SetGlobalGenerator(new cmGlobalUnixMakefileGenerator3(this));
+#endif
+}
+
 void cmake::PreLoadCMakeFiles()
 {
   std::vector<std::string> args;
@@ -1627,7 +1645,7 @@ void cmake::AddCacheEntry(const std::string& key, const char* value,
                           const char* helpString, int type)
 {
   this->State->AddCacheEntry(key, value, helpString,
-                             cmState::CacheEntryType(type));
+                             cmStateEnums::CacheEntryType(type));
   this->UnwatchUnusedCli(key);
 }
 
@@ -1638,11 +1656,8 @@ const char* cmake::GetCacheDefinition(const std::string& name) const
 
 void cmake::AddDefaultCommands()
 {
-  std::vector<cmCommand*> commands;
-  GetBootstrapCommands1(commands);
-  GetBootstrapCommands2(commands);
-  GetPredefinedCommands(commands);
-  for (std::vector<cmCommand*>::iterator i = commands.begin();
+  std::vector<cmCommand*> const commands = GetPredefinedCommands();
+  for (std::vector<cmCommand*>::const_iterator i = commands.begin();
        i != commands.end(); ++i) {
     this->State->AddCommand(*i);
   }
@@ -1681,7 +1696,8 @@ void cmake::AddDefaultGenerators()
 }
 
 bool cmake::ParseCacheEntry(const std::string& entry, std::string& var,
-                            std::string& value, cmState::CacheEntryType& type)
+                            std::string& value,
+                            cmStateEnums::CacheEntryType& type)
 {
   return cmState::ParseCacheEntry(entry, var, value, type);
 }
@@ -2223,7 +2239,7 @@ int cmake::GetSystemInformation(std::vector<std::string>& args)
   return 0;
 }
 
-static bool cmakeCheckStampFile(const char* stampName)
+static bool cmakeCheckStampFile(const char* stampName, bool verbose)
 {
   // The stamp file does not exist.  Use the stamp dependencies to
   // determine whether it is really out of date.  This works in
@@ -2277,11 +2293,13 @@ static bool cmakeCheckStampFile(const char* stampName)
     stamp << "# CMake generation timestamp file for this directory.\n";
   }
   if (cmSystemTools::RenameFile(stampTemp, stampName)) {
-    // Notify the user why CMake is not re-running.  It is safe to
-    // just print to stdout here because this code is only reachable
-    // through an undocumented flag used by the VS generator.
-    std::cout << "CMake does not need to re-run because " << stampName
-              << " is up-to-date.\n";
+    if (verbose) {
+      // Notify the user why CMake is not re-running.  It is safe to
+      // just print to stdout here because this code is only reachable
+      // through an undocumented flag used by the VS generator.
+      std::cout << "CMake does not need to re-run because " << stampName
+                << " is up-to-date.\n";
+    }
     return true;
   }
   cmSystemTools::RemoveFile(stampTemp);
@@ -2289,7 +2307,7 @@ static bool cmakeCheckStampFile(const char* stampName)
   return false;
 }
 
-static bool cmakeCheckStampList(const char* stampList)
+static bool cmakeCheckStampList(const char* stampList, bool verbose)
 {
   // If the stamp list does not exist CMake must rerun to generate it.
   if (!cmSystemTools::FileExists(stampList)) {
@@ -2307,7 +2325,7 @@ static bool cmakeCheckStampList(const char* stampList)
   // Check each stamp.
   std::string stampName;
   while (cmSystemTools::GetLineFromStream(fin, stampName)) {
-    if (!cmakeCheckStampFile(stampName.c_str())) {
+    if (!cmakeCheckStampFile(stampName.c_str(), verbose)) {
       return false;
     }
   }
@@ -2387,6 +2405,48 @@ int cmake::Build(const std::string& dir, const std::string& target,
   if (cachedVerbose) {
     verbose = cmSystemTools::IsOn(cachedVerbose);
   }
+
+#ifdef CMAKE_HAVE_VS_GENERATORS
+  // For VS generators, explicitly check if regeneration is necessary before
+  // actually starting the build. If not done separately from the build
+  // itself, there is the risk of building an out-of-date solution file due
+  // to limitations of the underlying build system.
+  std::string const stampList = cachePath + "/" +
+    GetCMakeFilesDirectoryPostSlash() +
+    cmGlobalVisualStudio8Generator::GetGenerateStampList();
+
+  // Note that the stampList file only exists for VS generators.
+  if (cmSystemTools::FileExists(stampList.c_str()) &&
+      !cmakeCheckStampList(stampList.c_str(), false)) {
+
+    // Correctly initialize the home (=source) and home output (=binary)
+    // directories, which is required for running the generation step.
+    std::string homeOrig = this->GetHomeDirectory();
+    std::string homeOutputOrig = this->GetHomeOutputDirectory();
+    this->SetDirectoriesFromFile(cachePath.c_str());
+
+    int ret = this->Configure();
+    if (ret) {
+      cmSystemTools::Message("CMake Configure step failed.  "
+                             "Build files cannot be regenerated correctly.");
+      return ret;
+    }
+    ret = this->Generate();
+    if (ret) {
+      cmSystemTools::Message("CMake Generate step failed.  "
+                             "Build files cannot be regenerated correctly.");
+      return ret;
+    }
+    std::string message = "Build files have been written to: ";
+    message += this->GetHomeOutputDirectory();
+    this->UpdateProgress(message.c_str(), -1);
+
+    // Restore the previously set directories to their original value.
+    this->SetHomeDirectory(homeOrig);
+    this->SetHomeOutputDirectory(homeOutputOrig);
+  }
+#endif
+
   return gen->Build("", dir, projName, target, output, "", config, clean,
                     false, verbose, 0, cmSystemTools::OUTPUT_PASSTHROUGH,
                     nativeOptions);
@@ -2451,7 +2511,7 @@ void cmake::SetSuppressDevWarnings(bool b)
   this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", value.c_str(),
                       "Suppress Warnings that are meant for"
                       " the author of the CMakeLists.txt files.",
-                      cmState::INTERNAL);
+                      cmStateEnums::INTERNAL);
 }
 
 bool cmake::GetSuppressDeprecatedWarnings() const
@@ -2475,7 +2535,7 @@ void cmake::SetSuppressDeprecatedWarnings(bool b)
   this->AddCacheEntry("CMAKE_WARN_DEPRECATED", value.c_str(),
                       "Whether to issue warnings for deprecated "
                       "functionality.",
-                      cmState::INTERNAL);
+                      cmStateEnums::INTERNAL);
 }
 
 bool cmake::GetDevWarningsAsErrors() const
@@ -2499,7 +2559,7 @@ void cmake::SetDevWarningsAsErrors(bool b)
   this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_ERRORS", value.c_str(),
                       "Suppress errors that are meant for"
                       " the author of the CMakeLists.txt files.",
-                      cmState::INTERNAL);
+                      cmStateEnums::INTERNAL);
 }
 
 bool cmake::GetDeprecatedWarningsAsErrors() const
@@ -2523,5 +2583,5 @@ void cmake::SetDeprecatedWarningsAsErrors(bool b)
   this->AddCacheEntry("CMAKE_ERROR_DEPRECATED", value.c_str(),
                       "Whether to issue deprecation errors for macros"
                       " and functions.",
-                      cmState::INTERNAL);
+                      cmStateEnums::INTERNAL);
 }
diff --git a/Source/cmake.h b/Source/cmake.h
index ae1a502..5347745 100644
--- a/Source/cmake.h
+++ b/Source/cmake.h
@@ -5,17 +5,18 @@
 
 #include <cmConfigure.h>
 
-#include "cmInstalledFile.h"
-#include "cmListFileCache.h"
-#include "cmState.h"
-
 #include <map>
 #include <set>
 #include <string>
 #include <vector>
 
+#include "cmInstalledFile.h"
+#include "cmListFileCache.h"
+#include "cmStateSnapshot.h"
+#include "cmStateTypes.h"
+
 #if defined(CMAKE_BUILD_WITH_CMAKE)
-#include "cm_jsoncpp_value.h"
+#include <cm_jsoncpp_value.h>
 #endif
 
 class cmExternalMakefileProjectGeneratorFactory;
@@ -24,6 +25,7 @@ class cmGlobalGenerator;
 class cmGlobalGeneratorFactory;
 class cmMakefile;
 class cmMessenger;
+class cmState;
 class cmVariableWatch;
 struct cmDocumentationEntry;
 
@@ -161,7 +163,7 @@ public:
   ///! Break up a line like VAR:type="value" into var, type and value
   static bool ParseCacheEntry(const std::string& entry, std::string& var,
                               std::string& value,
-                              cmState::CacheEntryType& type);
+                              cmStateEnums::CacheEntryType& type);
 
   int LoadCache();
   bool LoadCache(const std::string& path);
@@ -407,14 +409,11 @@ public:
   void WatchUnusedCli(const std::string& var);
 
   cmState* GetState() const { return this->State; }
-  void SetCurrentSnapshot(cmState::Snapshot snapshot)
+  void SetCurrentSnapshot(cmStateSnapshot snapshot)
   {
     this->CurrentSnapshot = snapshot;
   }
-  cmState::Snapshot GetCurrentSnapshot() const
-  {
-    return this->CurrentSnapshot;
-  }
+  cmStateSnapshot GetCurrentSnapshot() const { return this->CurrentSnapshot; }
 
 protected:
   void RunCheckForUnusedVariables();
@@ -490,7 +489,7 @@ private:
   InstalledFilesMap InstalledFiles;
 
   cmState* State;
-  cmState::Snapshot CurrentSnapshot;
+  cmStateSnapshot CurrentSnapshot;
   cmMessenger* Messenger;
 
   std::vector<std::string> TraceOnlyThisSources;
@@ -500,6 +499,8 @@ private:
   // Print a list of valid generators to stderr.
   void PrintGeneratorList();
 
+  void CreateDefaultGlobalGenerator();
+
   /**
    * Convert a message type between a warning and an error, based on the state
    * of the error output CMake variables, in the cache.
@@ -536,12 +537,19 @@ private:
   }
 
 #define FOR_EACH_C_FEATURE(F)                                                 \
+  F(c_std_90)                                                                 \
+  F(c_std_99)                                                                 \
+  F(c_std_11)                                                                 \
   F(c_function_prototypes)                                                    \
   F(c_restrict)                                                               \
   F(c_static_assert)                                                          \
   F(c_variadic_macros)
 
 #define FOR_EACH_CXX_FEATURE(F)                                               \
+  F(cxx_std_98)                                                               \
+  F(cxx_std_11)                                                               \
+  F(cxx_std_14)                                                               \
+  F(cxx_std_17)                                                               \
   F(cxx_aggregate_default_initializers)                                       \
   F(cxx_alias_templates)                                                      \
   F(cxx_alignas)                                                              \
diff --git a/Source/cmakemain.cxx b/Source/cmakemain.cxx
index 0d1f1ce..b8e227f 100644
--- a/Source/cmakemain.cxx
+++ b/Source/cmakemain.cxx
@@ -12,12 +12,16 @@
 #include "cmGlobalGenerator.h"
 #include "cmMakefile.h"
 #include "cmState.h"
+#include "cmStateTypes.h"
 #include "cmSystemTools.h"
 #include "cmake.h"
 #include "cmcmd.h"
 
 #include <cmConfigure.h>
 #include <cmsys/Encoding.hxx>
+#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
+#include <cmsys/ConsoleBuf.hxx>
+#endif
 #include <iostream>
 #include <string.h>
 #include <string>
@@ -153,6 +157,13 @@ static void cmakemainProgressCallback(const char* m, float prog,
 
 int main(int ac, char const* const* av)
 {
+#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
+  // Replace streambuf so we can output Unicode to console
+  cmsys::ConsoleBuf::Manager consoleOut(std::cout);
+  consoleOut.SetUTF8Pipes();
+  cmsys::ConsoleBuf::Manager consoleErr(std::cerr, true);
+  consoleErr.SetUTF8Pipes();
+#endif
   cmsys::Encoding::CommandLineArguments args =
     cmsys::Encoding::CommandLineArguments::Main(ac, av);
   ac = args.argc();
@@ -292,9 +303,9 @@ int do_cmake(int ac, char const* const* av)
     std::vector<std::string> keys = cm.GetState()->GetCacheEntryKeys();
     for (std::vector<std::string>::const_iterator it = keys.begin();
          it != keys.end(); ++it) {
-      cmState::CacheEntryType t = cm.GetState()->GetCacheEntryType(*it);
-      if (t != cmState::INTERNAL && t != cmState::STATIC &&
-          t != cmState::UNINITIALIZED) {
+      cmStateEnums::CacheEntryType t = cm.GetState()->GetCacheEntryType(*it);
+      if (t != cmStateEnums::INTERNAL && t != cmStateEnums::STATIC &&
+          t != cmStateEnums::UNINITIALIZED) {
         const char* advancedProp =
           cm.GetState()->GetCacheEntryProperty(*it, "ADVANCED");
         if (list_all_cached || !advancedProp) {
@@ -398,6 +409,8 @@ static int do_build(int ac, char const* const* av)
   }
 
   cmake cm;
+  cmSystemTools::SetMessageCallback(cmakemainMessageCallback, (void*)&cm);
+  cm.SetProgressCallback(cmakemainProgressCallback, (void*)&cm);
   return cm.Build(dir, target, config, nativeOptions, clean);
 #endif
 }
diff --git a/Source/cmakexbuild.cxx b/Source/cmakexbuild.cxx
index 82db012..e166bee 100644
--- a/Source/cmakexbuild.cxx
+++ b/Source/cmakexbuild.cxx
@@ -1,9 +1,14 @@
 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
    file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmStandardIncludes.h"
 
-#include "cmSystemTools.h"
+#include <cmConfigure.h> // IWYU pragma: keep
+
 #include <cmsys/Process.h>
+#include <iostream>
+#include <string>
+#include <vector>
+
+#include "cmSystemTools.h"
 
 // This is a wrapper program for xcodebuild
 // it calls xcodebuild, and does two things
diff --git a/Source/cmcldeps.cxx b/Source/cmcldeps.cxx
index 167d60a..b86ad6e 100644
--- a/Source/cmcldeps.cxx
+++ b/Source/cmcldeps.cxx
@@ -205,7 +205,7 @@ static int process(const std::string& srcfilename, const std::string& dfile,
   std::vector<std::string> command;
   for (std::vector<std::string>::iterator i = args.begin(); i != args.end();
        ++i) {
-    command.push_back(i->c_str());
+    command.push_back(*i);
   }
   // run the command
   int exit_code = 0;
@@ -258,7 +258,7 @@ int main()
   // needed to suppress filename output of msvc tools
   std::string srcfilename;
   {
-    std::string::size_type pos = srcfile.rfind("\\");
+    std::string::size_type pos = srcfile.rfind('\\');
     if (pos == std::string::npos) {
       srcfilename = srcfile;
     } else {
@@ -279,12 +279,7 @@ int main()
     clrest = replace(clrest, "/fo", "/out:");
     clrest = replace(clrest, objfile, objfile + ".dep.obj ");
 
-    // rc: src\x\x.rc  ->  cl: /Tc src\x\x.rc
-    if (srcfile.find(" ") != std::string::npos)
-      srcfile = "\"" + srcfile + "\"";
-    clrest = replace(clrest, srcfile, "/Tc " + srcfile);
-
-    cl = "\"" + cl + "\" /P /DRC_INVOKED ";
+    cl = "\"" + cl + "\" /P /DRC_INVOKED /TC ";
 
     // call cl in object dir so the .i is generated there
     std::string objdir;
diff --git a/Source/cmcmd.cxx b/Source/cmcmd.cxx
index 4387bf6..823b38f 100644
--- a/Source/cmcmd.cxx
+++ b/Source/cmcmd.cxx
@@ -7,7 +7,8 @@
 #include "cmLocalGenerator.h"
 #include "cmMakefile.h"
 #include "cmQtAutoGenerators.h"
-#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
 #include "cmSystemTools.h"
 #include "cmUtils.hxx"
 #include "cmVersion.h"
@@ -168,13 +169,13 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
         return 1;
       }
       // If error occurs we want to continue copying next files.
-      bool return_value = 0;
+      bool return_value = false;
       for (std::string::size_type cc = 2; cc < args.size() - 1; cc++) {
         if (!cmSystemTools::cmCopyFile(args[cc].c_str(),
                                        args[args.size() - 1].c_str())) {
           std::cerr << "Error copying file \"" << args[cc] << "\" to \""
                     << args[args.size() - 1] << "\".\n";
-          return_value = 1;
+          return_value = true;
         }
       }
       return return_value;
@@ -191,13 +192,13 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
         return 1;
       }
       // If error occurs we want to continue copying next files.
-      bool return_value = 0;
+      bool return_value = false;
       for (std::string::size_type cc = 2; cc < args.size() - 1; cc++) {
         if (!cmSystemTools::CopyFileIfDifferent(
               args[cc].c_str(), args[args.size() - 1].c_str())) {
           std::cerr << "Error copying file (if different) from \"" << args[cc]
                     << "\" to \"" << args[args.size() - 1] << "\".\n";
-          return_value = 1;
+          return_value = true;
         }
       }
       return return_value;
@@ -206,12 +207,12 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
     // Copy directory content
     if (args[1] == "copy_directory" && args.size() > 3) {
       // If error occurs we want to continue copying next files.
-      bool return_value = 0;
+      bool return_value = false;
       for (std::string::size_type cc = 2; cc < args.size() - 1; cc++) {
         if (!cmSystemTools::CopyADirectory(args[cc], args[args.size() - 1])) {
           std::cerr << "Error copying directory from \"" << args[cc]
                     << "\" to \"" << args[args.size() - 1] << "\".\n";
-          return_value = 1;
+          return_value = true;
         }
       }
       return return_value;
@@ -275,7 +276,8 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
     if (args[1] == "__run_iwyu") {
       if (args.size() < 3) {
         std::cerr << "__run_iwyu Usage: -E __run_iwyu [--iwyu=/path/iwyu]"
-                     " [--tidy=/path/tidy] -- compile command\n";
+                     " [--cpplint=/path/cpplint] [--tidy=/path/tidy]"
+                     " -- compile command\n";
         return 1;
       }
       bool doing_options = true;
@@ -284,6 +286,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
       std::string tidy;
       std::string sourceFile;
       std::string lwyu;
+      std::string cpplint;
       for (std::string::size_type cc = 2; cc < args.size(); cc++) {
         std::string const& arg = args[cc];
         if (arg == "--") {
@@ -296,6 +299,8 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
           sourceFile = arg.substr(9);
         } else if (doing_options && cmHasLiteralPrefix(arg, "--lwyu=")) {
           lwyu = arg.substr(7);
+        } else if (doing_options && cmHasLiteralPrefix(arg, "--cpplint=")) {
+          cpplint = arg.substr(10);
         } else if (doing_options) {
           std::cerr << "__run_iwyu given unknown argument: " << arg << "\n";
           return 1;
@@ -303,12 +308,14 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
           orig_cmd.push_back(arg);
         }
       }
-      if (tidy.empty() && iwyu.empty() && lwyu.empty()) {
-        std::cerr << "__run_iwyu missing --tidy= or --iwyu=\n";
+      if (tidy.empty() && iwyu.empty() && lwyu.empty() && cpplint.empty()) {
+        std::cerr << "__run_iwyu missing --cpplint=, --iwyu=, --lwyu=, and/or"
+                     " --tidy=\n";
         return 1;
       }
-      if (!tidy.empty() && sourceFile.empty()) {
-        std::cerr << "__run_iwyu --tidy= requires --source=\n";
+      if ((!cpplint.empty() || !tidy.empty()) && sourceFile.empty()) {
+        std::cerr << "__run_iwyu --cpplint= and/or __run_iwyu --tidy="
+                     " require --source=\n";
         return 1;
       }
       if (orig_cmd.empty() && lwyu.empty()) {
@@ -326,6 +333,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
         iwyu_cmd.insert(iwyu_cmd.end(), orig_cmd.begin() + 1, orig_cmd.end());
 
         // Run the iwyu command line.  Capture its stderr and hide its stdout.
+        // Ignore its return code because the tool always returns non-zero.
         std::string stdErr;
         if (!cmSystemTools::RunSingleCommand(iwyu_cmd, CM_NULLPTR, &stdErr,
                                              &ret, CM_NULLPTR,
@@ -356,14 +364,21 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
 
         // Run the tidy command line.  Capture its stdout and hide its stderr.
         std::string stdOut;
-        if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, CM_NULLPTR,
-                                             &ret, CM_NULLPTR,
+        std::string stdErr;
+        if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, &stdErr, &ret,
+                                             CM_NULLPTR,
                                              cmSystemTools::OUTPUT_NONE)) {
-          std::cerr << "Error running '" << tidy_cmd[0] << "'\n";
+          std::cerr << "Error running '" << tidy_cmd[0] << "': " << stdErr
+                    << "\n";
           return 1;
         }
         // Output the stdout from clang-tidy to stderr
         std::cerr << stdOut;
+        // If clang-tidy exited with an error do the same.
+        if (ret != 0) {
+          std::cerr << stdErr;
+          return ret;
+        }
       }
       if (!lwyu.empty()) {
         // Construct the ldd -r -u (link what you use lwyu) command line
@@ -376,11 +391,15 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
 
         // Run the ldd -u -r command line.
         // Capture its stdout and hide its stderr.
+        // Ignore its return code because the tool always returns non-zero
+        // if there are any warnings, but we just want to warn.
         std::string stdOut;
-        if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, CM_NULLPTR,
-                                             &ret, CM_NULLPTR,
+        std::string stdErr;
+        if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, &stdErr, &ret,
+                                             CM_NULLPTR,
                                              cmSystemTools::OUTPUT_NONE)) {
-          std::cerr << "Error running '" << lwyu_cmd[0] << "'\n";
+          std::cerr << "Error running '" << lwyu_cmd[0] << "': " << stdErr
+                    << "\n";
           return 1;
         }
 
@@ -390,6 +409,32 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
           std::cerr << "Warning: " << stdOut;
         }
       }
+
+      if (!cpplint.empty()) {
+        // Construct the cpplint command line.
+        std::vector<std::string> cpplint_cmd;
+        cmSystemTools::ExpandListArgument(cpplint, cpplint_cmd, true);
+        cpplint_cmd.push_back(sourceFile);
+
+        // Run the cpplint command line.  Capture its output.
+        std::string stdOut;
+        if (!cmSystemTools::RunSingleCommand(cpplint_cmd, &stdOut, &stdOut,
+                                             &ret, CM_NULLPTR,
+                                             cmSystemTools::OUTPUT_NONE)) {
+          std::cerr << "Error running '" << cpplint_cmd[0] << "': " << stdOut
+                    << "\n";
+          return 1;
+        }
+
+        // Output the output from cpplint to stderr
+        std::cerr << stdOut;
+
+        // If cpplint exited with an error do the same.
+        if (ret != 0) {
+          return ret;
+        }
+      }
+
       ret = 0;
       // Now run the real compiler command and return its result value.
       if (lwyu.empty() &&
@@ -414,7 +459,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
       return 0;
     }
 
-    else if (args[1] == "env") {
+    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) {
@@ -454,7 +499,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
     }
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
-    else if (args[1] == "environment") {
+    if (args[1] == "environment") {
       std::vector<std::string> env = cmSystemTools::GetEnvironmentVariables();
       std::vector<std::string>::iterator it;
       for (it = env.begin(); it != env.end(); ++it) {
@@ -464,19 +509,19 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
     }
 #endif
 
-    else if (args[1] == "make_directory" && args.size() > 2) {
+    if (args[1] == "make_directory" && args.size() > 2) {
       // If error occurs we want to continue copying next files.
-      bool return_value = 0;
+      bool return_value = false;
       for (std::string::size_type cc = 2; cc < args.size(); cc++) {
         if (!cmSystemTools::MakeDirectory(args[cc].c_str())) {
           std::cerr << "Error creating directory \"" << args[cc] << "\".\n";
-          return_value = 1;
+          return_value = true;
         }
       }
       return return_value;
     }
 
-    else if (args[1] == "remove_directory" && args.size() == 3) {
+    if (args[1] == "remove_directory" && args.size() == 3) {
       if (cmSystemTools::FileIsDirectory(args[2]) &&
           !cmSystemTools::RemoveADirectory(args[2])) {
         std::cerr << "Error removing directory \"" << args[2] << "\".\n";
@@ -486,7 +531,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
     }
 
     // Remove file
-    else if (args[1] == "remove" && args.size() > 2) {
+    if (args[1] == "remove" && args.size() > 2) {
       bool force = false;
       for (std::string::size_type cc = 2; cc < args.size(); cc++) {
         if (args[cc] == "\\-f" || args[cc] == "-f") {
@@ -502,8 +547,9 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
       }
       return 0;
     }
+
     // Touch file
-    else if (args[1] == "touch" && args.size() > 2) {
+    if (args[1] == "touch" && args.size() > 2) {
       for (std::string::size_type cc = 2; cc < args.size(); cc++) {
         if (!cmSystemTools::Touch(args[cc], true)) {
           return 1;
@@ -511,8 +557,9 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
       }
       return 0;
     }
+
     // Touch file
-    else if (args[1] == "touch_nocreate" && args.size() > 2) {
+    if (args[1] == "touch_nocreate" && args.size() > 2) {
       for (std::string::size_type cc = 2; cc < args.size(); cc++) {
         // Complain if the file could not be removed, still exists,
         // and the -f option was not given.
@@ -522,8 +569,9 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
       }
       return 0;
     }
+
     // capabilities
-    else if (args[1] == "capabilities") {
+    if (args[1] == "capabilities") {
       if (args.size() > 2) {
         std::cerr << "-E capabilities accepts no additional arguments\n";
         return 1;
@@ -538,7 +586,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
     }
 
     // Sleep command
-    else if (args[1] == "sleep" && args.size() > 2) {
+    if (args[1] == "sleep" && args.size() > 2) {
       double total = 0;
       for (size_t i = 2; i < args.size(); ++i) {
         double num = 0.0;
@@ -559,7 +607,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
     }
 
     // Clock command
-    else if (args[1] == "time" && args.size() > 2) {
+    if (args[1] == "time" && args.size() > 2) {
       std::vector<std::string> command(args.begin() + 2, args.end());
 
       clock_t clock_start, clock_finish;
@@ -583,8 +631,9 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
                 << "\n";
       return ret;
     }
+
     // Command to calculate the md5sum of a file
-    else if (args[1] == "md5sum" && args.size() >= 3) {
+    if (args[1] == "md5sum" && args.size() >= 3) {
       char md5out[32];
       int retval = 0;
       for (std::string::size_type cc = 2; cc < args.size(); cc++) {
@@ -606,7 +655,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
     }
 
     // Command to change directory and run a program.
-    else if (args[1] == "chdir" && args.size() >= 4) {
+    if (args[1] == "chdir" && args.size() >= 4) {
       std::string directory = args[2];
       if (!cmSystemTools::FileExists(directory.c_str())) {
         cmSystemTools::Error("Directory does not exist for chdir command: ",
@@ -628,7 +677,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
     }
 
     // Command to start progress for a build
-    else if (args[1] == "cmake_progress_start" && args.size() == 4) {
+    if (args[1] == "cmake_progress_start" && args.size() == 4) {
       // basically remove the directory
       std::string dirName = args[2];
       dirName += "/Progress";
@@ -660,7 +709,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
     }
 
     // Command to report progress for a build
-    else if (args[1] == "cmake_progress_report" && args.size() >= 3) {
+    if (args[1] == "cmake_progress_report" && args.size() >= 3) {
       // This has been superseded by cmake_echo_color --progress-*
       // options.  We leave it here to avoid errors if somehow this
       // is invoked by an existing makefile without regenerating.
@@ -669,7 +718,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
 
     // Command to create a symbolic link.  Fails on platforms not
     // supporting them.
-    else if (args[1] == "create_symlink" && args.size() == 4) {
+    if (args[1] == "create_symlink" && args.size() == 4) {
       const char* destinationFileName = args[3].c_str();
       if ((cmSystemTools::FileExists(destinationFileName) ||
            cmSystemTools::FileIsSymlink(destinationFileName)) &&
@@ -690,16 +739,17 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
     }
 
     // Internal CMake shared library support.
-    else if (args[1] == "cmake_symlink_library" && args.size() == 5) {
+    if (args[1] == "cmake_symlink_library" && args.size() == 5) {
       return cmcmd::SymlinkLibrary(args);
     }
+
     // Internal CMake versioned executable support.
-    else if (args[1] == "cmake_symlink_executable" && args.size() == 4) {
+    if (args[1] == "cmake_symlink_executable" && args.size() == 4) {
       return cmcmd::SymlinkExecutable(args);
     }
 
     // Internal CMake dependency scanning support.
-    else if (args[1] == "cmake_depends" && args.size() >= 6) {
+    if (args[1] == "cmake_depends" && args.size() >= 6) {
       const bool verbose = isCMakeVerbose();
 
       // Create a cmake object instance to process dependencies.
@@ -760,7 +810,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
       cm.GetCurrentSnapshot().SetDefaultDefinitions();
       if (cmGlobalGenerator* ggd = cm.CreateGlobalGenerator(gen)) {
         cm.SetGlobalGenerator(ggd);
-        cmState::Snapshot snapshot = cm.GetCurrentSnapshot();
+        cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
         snapshot.GetDirectory().SetCurrentBinary(startOutDir);
         snapshot.GetDirectory().SetCurrentSource(startDir);
         CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(ggd, snapshot));
@@ -774,41 +824,47 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
     }
 
     // Internal CMake link script support.
-    else if (args[1] == "cmake_link_script" && args.size() >= 3) {
+    if (args[1] == "cmake_link_script" && args.size() >= 3) {
       return cmcmd::ExecuteLinkScript(args);
     }
 
 #ifdef CMAKE_BUILD_WITH_CMAKE
     // Internal CMake ninja dependency scanning support.
-    else if (args[1] == "cmake_ninja_depends") {
+    if (args[1] == "cmake_ninja_depends") {
       return cmcmd_cmake_ninja_depends(args.begin() + 2, args.end());
     }
 
     // Internal CMake ninja dyndep support.
-    else if (args[1] == "cmake_ninja_dyndep") {
+    if (args[1] == "cmake_ninja_dyndep") {
       return cmcmd_cmake_ninja_dyndep(args.begin() + 2, args.end());
     }
 #endif
 
     // Internal CMake unimplemented feature notification.
-    else if (args[1] == "cmake_unimplemented_variable") {
+    if (args[1] == "cmake_unimplemented_variable") {
       std::cerr << "Feature not implemented for this platform.";
       if (args.size() == 3) {
         std::cerr << "  Variable " << args[2] << " is not set.";
       }
       std::cerr << std::endl;
       return 1;
-    } else if (args[1] == "vs_link_exe") {
+    }
+
+    if (args[1] == "vs_link_exe") {
       return cmcmd::VisualStudioLink(args, 1);
-    } else if (args[1] == "vs_link_dll") {
+    }
+
+    if (args[1] == "vs_link_dll") {
       return cmcmd::VisualStudioLink(args, 2);
     }
+
     // Internal CMake color makefile support.
-    else if (args[1] == "cmake_echo_color") {
+    if (args[1] == "cmake_echo_color") {
       return cmcmd::ExecuteEchoColor(args);
     }
+
 #ifdef CMAKE_BUILD_WITH_CMAKE
-    else if (args[1] == "cmake_autogen" && args.size() >= 4) {
+    if (args[1] == "cmake_autogen" && args.size() >= 4) {
       cmQtAutoGenerators autogen;
       std::string const& config = args[3];
       bool autogenSuccess = autogen.Run(args[2], config);
@@ -817,7 +873,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
 #endif
 
     // Tar files
-    else if (args[1] == "tar" && args.size() > 3) {
+    if (args[1] == "tar" && args.size() > 3) {
       const char* knownFormats[] = { "7zip", "gnutar", "pax", "paxr", "zip" };
 
       std::string flags = args[2];
@@ -921,7 +977,9 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
 #endif
       }
       return 0;
-    } else if (args[1] == "server") {
+    }
+
+    if (args[1] == "server") {
       const std::string pipePrefix = "--pipe=";
       bool supportExperimental = false;
       bool isDebug = false;
@@ -958,28 +1016,26 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
       std::string errorMessage;
       if (server.Serve(&errorMessage)) {
         return 0;
-      } else {
-        cmSystemTools::Error(errorMessage.c_str());
-        return 1;
       }
+      cmSystemTools::Error(errorMessage.c_str());
 #else
       static_cast<void>(supportExperimental);
       static_cast<void>(isDebug);
       cmSystemTools::Error("CMake was not built with server mode enabled");
-      return 1;
 #endif
+      return 1;
     }
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
     // Internal CMake Fortran module support.
-    else if (args[1] == "cmake_copy_f90_mod" && args.size() >= 4) {
+    if (args[1] == "cmake_copy_f90_mod" && args.size() >= 4) {
       return cmDependsFortran::CopyModule(args) ? 0 : 1;
     }
 #endif
 
 #if defined(_WIN32) && !defined(__CYGWIN__)
     // Write registry value
-    else if (args[1] == "write_regv" && args.size() > 3) {
+    if (args[1] == "write_regv" && args.size() > 3) {
       return cmSystemTools::WriteRegistryValue(args[2].c_str(),
                                                args[3].c_str())
         ? 0
@@ -987,16 +1043,21 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
     }
 
     // Delete registry value
-    else if (args[1] == "delete_regv" && args.size() > 2) {
+    if (args[1] == "delete_regv" && args.size() > 2) {
       return cmSystemTools::DeleteRegistryValue(args[2].c_str()) ? 0 : 1;
     }
+
     // Remove file
-    else if (args[1] == "comspec" && args.size() > 2) {
+    if (args[1] == "comspec" && args.size() > 2) {
       std::cerr << "Win9x helper \"cmake -E comspec\" no longer supported\n";
       return 1;
-    } else if (args[1] == "env_vs8_wince" && args.size() == 3) {
+    }
+
+    if (args[1] == "env_vs8_wince" && args.size() == 3) {
       return cmcmd::WindowsCEEnvironment("8.0", args[2]);
-    } else if (args[1] == "env_vs9_wince" && args.size() == 3) {
+    }
+
+    if (args[1] == "env_vs9_wince" && args.size() == 3) {
       return cmcmd::WindowsCEEnvironment("9.0", args[2]);
     }
 #endif
diff --git a/Source/ctest.cxx b/Source/ctest.cxx
index 1fb39ff..1cf75c8 100644
--- a/Source/ctest.cxx
+++ b/Source/ctest.cxx
@@ -10,6 +10,9 @@
 #include "cmake.h"
 
 #include <cmsys/Encoding.hxx>
+#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
+#include <cmsys/ConsoleBuf.hxx>
+#endif
 #include <iostream>
 #include <string.h>
 #include <string>
@@ -110,6 +113,13 @@ static const char* cmDocumentationOptions[][2] = {
 // this is a test driver program for cmCTest.
 int main(int argc, char const* const* argv)
 {
+#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
+  // Replace streambuf so we can output Unicode to console
+  cmsys::ConsoleBuf::Manager consoleOut(std::cout);
+  consoleOut.SetUTF8Pipes();
+  cmsys::ConsoleBuf::Manager consoleErr(std::cerr, true);
+  consoleErr.SetUTF8Pipes();
+#endif
   cmsys::Encoding::CommandLineArguments encoding_args =
     cmsys::Encoding::CommandLineArguments::Main(argc, argv);
   argc = encoding_args.argc();
@@ -163,11 +173,7 @@ int main(int argc, char const* const* argv)
       doc.SetSection("Name", cmDocumentationName);
       doc.SetSection("Usage", cmDocumentationUsage);
       doc.PrependSection("Options", cmDocumentationOptions);
-#ifdef cout
-#undef cout
-#endif
       return doc.PrintRequestedDocumentation(std::cout) ? 0 : 1;
-#define cout no_cout_use_cmCTestLog
     }
   }
 
diff --git a/Source/kwsys/.gitattributes b/Source/kwsys/.gitattributes
index a9c4e77..a121ad1 100644
--- a/Source/kwsys/.gitattributes
+++ b/Source/kwsys/.gitattributes
@@ -1,7 +1,5 @@
 .git*            export-ignore
 
-/CONTRIBUTING.rst conflict-marker-size=78
-
 *.c              whitespace=tab-in-indent,no-lf-at-eof
 *.h              whitespace=tab-in-indent,no-lf-at-eof
 *.h.in           whitespace=tab-in-indent,no-lf-at-eof
@@ -10,3 +8,5 @@
 *.hxx.in         whitespace=tab-in-indent,no-lf-at-eof
 *.txt            whitespace=tab-in-indent,no-lf-at-eof
 *.cmake          whitespace=tab-in-indent,no-lf-at-eof
+
+*.rst            whitespace=tab-in-indent conflict-marker-size=79
diff --git a/Source/kwsys/Base64.c b/Source/kwsys/Base64.c
index 4b8ede2..37c3b8c 100644
--- a/Source/kwsys/Base64.c
+++ b/Source/kwsys/Base64.c
@@ -1,65 +1,43 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(Base64.h)
 
 /* Work-around CMake dependency scanning limitation.  This must
    duplicate the above list of headers.  */
 #if 0
-# include "Base64.h.in"
+#include "Base64.h.in"
 #endif
 
 /*--------------------------------------------------------------------------*/
 static const unsigned char kwsysBase64EncodeTable[65] =
-"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
-"abcdefghijklmnopqrstuvwxyz"
-"0123456789+/";
+  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+  "abcdefghijklmnopqrstuvwxyz"
+  "0123456789+/";
 
 /*--------------------------------------------------------------------------*/
-static const unsigned char kwsysBase64DecodeTable[256] =
-{
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0x3E,0xFF,0xFF,0xFF,0x3F,
-  0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,
-  0x3C,0x3D,0xFF,0xFF,0xFF,0x00,0xFF,0xFF,
-  0xFF,0x00,0x01,0x02,0x03,0x04,0x05,0x06,
-  0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,
-  0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16,
-  0x17,0x18,0x19,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20,
-  0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,
-  0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F,0x30,
-  0x31,0x32,0x33,0xFF,0xFF,0xFF,0xFF,0xFF,
+static const unsigned char kwsysBase64DecodeTable[256] = {
+  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+  0xFF, 0xFF, 0xFF, 0xFF, 0x3E, 0xFF, 0xFF, 0xFF, 0x3F, 0x34, 0x35, 0x36, 0x37,
+  0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF,
+  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
+  0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
+  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20,
+  0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D,
+  0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
   /*------------------------------------*/
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
-  0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF
+  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
 };
 
 /*--------------------------------------------------------------------------*/
@@ -76,27 +54,30 @@ static unsigned char kwsysBase64DecodeChar(unsigned char c)
 
 /*--------------------------------------------------------------------------*/
 /* Encode 3 bytes into a 4 byte string. */
-void kwsysBase64_Encode3(const unsigned char *src, unsigned char *dest)
+void kwsysBase64_Encode3(const unsigned char* src, unsigned char* dest)
 {
   dest[0] = kwsysBase64EncodeChar((src[0] >> 2) & 0x3F);
-  dest[1] = kwsysBase64EncodeChar(((src[0] << 4) & 0x30)|((src[1] >> 4) & 0x0F));
-  dest[2] = kwsysBase64EncodeChar(((src[1] << 2) & 0x3C)|((src[2] >> 6) & 0x03));
+  dest[1] =
+    kwsysBase64EncodeChar(((src[0] << 4) & 0x30) | ((src[1] >> 4) & 0x0F));
+  dest[2] =
+    kwsysBase64EncodeChar(((src[1] << 2) & 0x3C) | ((src[2] >> 6) & 0x03));
   dest[3] = kwsysBase64EncodeChar(src[2] & 0x3F);
 }
 
 /*--------------------------------------------------------------------------*/
 /* Encode 2 bytes into a 4 byte string. */
-void kwsysBase64_Encode2(const unsigned char *src, unsigned char *dest)
+void kwsysBase64_Encode2(const unsigned char* src, unsigned char* dest)
 {
   dest[0] = kwsysBase64EncodeChar((src[0] >> 2) & 0x3F);
-  dest[1] = kwsysBase64EncodeChar(((src[0] << 4) & 0x30)|((src[1] >> 4) & 0x0F));
+  dest[1] =
+    kwsysBase64EncodeChar(((src[0] << 4) & 0x30) | ((src[1] >> 4) & 0x0F));
   dest[2] = kwsysBase64EncodeChar(((src[1] << 2) & 0x3C));
   dest[3] = '=';
 }
 
 /*--------------------------------------------------------------------------*/
 /* Encode 1 bytes into a 4 byte string. */
-void kwsysBase64_Encode1(const unsigned char *src, unsigned char *dest)
+void kwsysBase64_Encode1(const unsigned char* src, unsigned char* dest)
 {
   dest[0] = kwsysBase64EncodeChar((src[0] >> 2) & 0x3F);
   dest[1] = kwsysBase64EncodeChar(((src[0] << 4) & 0x30));
@@ -115,54 +96,48 @@ void kwsysBase64_Encode1(const unsigned char *src, unsigned char *dest)
    actually knowing how much data to expect (if the input is not a multiple of
    3 bytes then the extra padding needed to complete the encode 4 bytes will
    stop the decoding anyway).  */
-size_t kwsysBase64_Encode(const unsigned char *input,
-                          size_t length,
-                          unsigned char *output,
-                          int mark_end)
+size_t kwsysBase64_Encode(const unsigned char* input, size_t length,
+                          unsigned char* output, int mark_end)
 {
-  const unsigned char *ptr = input;
-  const unsigned char *end = input + length;
-  unsigned char *optr = output;
+  const unsigned char* ptr = input;
+  const unsigned char* end = input + length;
+  unsigned char* optr = output;
 
   /* Encode complete triplet */
 
-  while ((end - ptr) >= 3)
-    {
+  while ((end - ptr) >= 3) {
     kwsysBase64_Encode3(ptr, optr);
     ptr += 3;
     optr += 4;
-    }
+  }
 
   /* Encodes a 2-byte ending into 3 bytes and 1 pad byte and writes. */
 
-  if (end - ptr == 2)
-    {
+  if (end - ptr == 2) {
     kwsysBase64_Encode2(ptr, optr);
     optr += 4;
-    }
+  }
 
   /* Encodes a 1-byte ending into 2 bytes and 2 pad bytes */
-  
-  else if (end - ptr == 1)
-    {
+
+  else if (end - ptr == 1) {
     kwsysBase64_Encode1(ptr, optr);
     optr += 4;
-    }
+  }
 
   /* Do we need to mark the end */
 
-  else if (mark_end)
-    {
+  else if (mark_end) {
     optr[0] = optr[1] = optr[2] = optr[3] = '=';
     optr += 4;
-    }
+  }
 
   return (size_t)(optr - output);
 }
 
 /*--------------------------------------------------------------------------*/
 /* Decode 4 bytes into a 3 byte string. */
-int kwsysBase64_Decode3(const unsigned char *src, unsigned char *dest)
+int kwsysBase64_Decode3(const unsigned char* src, unsigned char* dest)
 {
   unsigned char d0, d1, d2, d3;
 
@@ -170,35 +145,32 @@ int kwsysBase64_Decode3(const unsigned char *src, unsigned char *dest)
   d1 = kwsysBase64DecodeChar(src[1]);
   d2 = kwsysBase64DecodeChar(src[2]);
   d3 = kwsysBase64DecodeChar(src[3]);
-  
+
   /* Make sure all characters were valid */
 
-  if (d0 == 0xFF || d1 == 0xFF || d2 == 0xFF || d3 == 0xFF)
-    { 
-    return 0; 
-    }
-  
+  if (d0 == 0xFF || d1 == 0xFF || d2 == 0xFF || d3 == 0xFF) {
+    return 0;
+  }
+
   /* Decode the 3 bytes */
 
   dest[0] = (unsigned char)(((d0 << 2) & 0xFC) | ((d1 >> 4) & 0x03));
   dest[1] = (unsigned char)(((d1 << 4) & 0xF0) | ((d2 >> 2) & 0x0F));
   dest[2] = (unsigned char)(((d2 << 6) & 0xC0) | ((d3 >> 0) & 0x3F));
-  
+
   /* Return the number of bytes actually decoded */
 
-  if (src[2] == '=') 
-    { 
-    return 1; 
-    }
-  if (src[3] == '=') 
-    { 
-    return 2; 
-    }
+  if (src[2] == '=') {
+    return 1;
+  }
+  if (src[3] == '=') {
+    return 2;
+  }
   return 3;
 }
 
 /*--------------------------------------------------------------------------*/
-/* Decode bytes from the input buffer and store the decoded stream 
+/* Decode bytes from the input buffer and store the decoded stream
    into the output buffer until 'length' bytes have been decoded.  Return the
    real length of the decoded stream (which should be equal to 'length'). Note
    that the output buffer must be allocated by the caller.  If
@@ -207,73 +179,57 @@ int kwsysBase64_Decode3(const unsigned char *src, unsigned char *dest)
    'length' parameter is ignored. This enables the caller to decode a stream
    without actually knowing how much decoded data to expect (of course, the
    buffer must be large enough). */
-size_t kwsysBase64_Decode(const unsigned char *input,
-                          size_t length,
-                          unsigned char *output,
-                          size_t max_input_length)
+size_t kwsysBase64_Decode(const unsigned char* input, size_t length,
+                          unsigned char* output, size_t max_input_length)
 {
-  const unsigned char *ptr = input;
-  unsigned char *optr = output;
+  const unsigned char* ptr = input;
+  unsigned char* optr = output;
 
   /* Decode complete triplet */
 
-  if (max_input_length)
-    {
-    const unsigned char *end = input + max_input_length;
-    while (ptr < end)
-      {
+  if (max_input_length) {
+    const unsigned char* end = input + max_input_length;
+    while (ptr < end) {
       int len = kwsysBase64_Decode3(ptr, optr);
       optr += len;
-      if(len < 3)
-        {
+      if (len < 3) {
         return (size_t)(optr - output);
-        }
-      ptr += 4;
       }
-    } 
-  else 
-    {
-    unsigned char *oend = output + length;
-    while ((oend - optr) >= 3)
-      {
+      ptr += 4;
+    }
+  } else {
+    unsigned char* oend = output + length;
+    while ((oend - optr) >= 3) {
       int len = kwsysBase64_Decode3(ptr, optr);
       optr += len;
-      if(len < 3)
-        {
+      if (len < 3) {
         return (size_t)(optr - output);
-        }
-      ptr += 4;
       }
+      ptr += 4;
+    }
 
     /* Decode the last triplet */
-  
-    if (oend - optr == 2)
-      {
+
+    if (oend - optr == 2) {
       unsigned char temp[3];
       int len = kwsysBase64_Decode3(ptr, temp);
-      if(len >= 2)
-        {
+      if (len >= 2) {
         optr[0] = temp[0];
         optr[1] = temp[1];
         optr += 2;
-        }
-      else if(len > 0)
-        {
+      } else if (len > 0) {
         optr[0] = temp[0];
         optr += 1;
-        }
       }
-    else if (oend - optr == 1)
-      {
+    } else if (oend - optr == 1) {
       unsigned char temp[3];
       int len = kwsysBase64_Decode3(ptr, temp);
-      if(len > 0)
-        {
+      if (len > 0) {
         optr[0] = temp[0];
         optr += 1;
-        }
       }
     }
+  }
 
   return (size_t)(optr - output);
 }
diff --git a/Source/kwsys/Base64.h.in b/Source/kwsys/Base64.h.in
index 36ed3cc..3536757 100644
--- a/Source/kwsys/Base64.h.in
+++ b/Source/kwsys/Base64.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _Base64_h
 #define @KWSYS_NAMESPACE at _Base64_h
 
@@ -21,41 +12,40 @@
    not visible to user code.  Use kwsysHeaderDump.pl to reproduce
    these macros after making changes to the interface.  */
 #if !defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
 #endif
 #if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-# define kwsysBase64          kwsys_ns(Base64)
-# define kwsysBase64_Decode   kwsys_ns(Base64_Decode)
-# define kwsysBase64_Decode3  kwsys_ns(Base64_Decode3)
-# define kwsysBase64_Encode   kwsys_ns(Base64_Encode)
-# define kwsysBase64_Encode1  kwsys_ns(Base64_Encode1)
-# define kwsysBase64_Encode2  kwsys_ns(Base64_Encode2)
-# define kwsysBase64_Encode3  kwsys_ns(Base64_Encode3)
+#define kwsysBase64 kwsys_ns(Base64)
+#define kwsysBase64_Decode kwsys_ns(Base64_Decode)
+#define kwsysBase64_Decode3 kwsys_ns(Base64_Decode3)
+#define kwsysBase64_Encode kwsys_ns(Base64_Encode)
+#define kwsysBase64_Encode1 kwsys_ns(Base64_Encode1)
+#define kwsysBase64_Encode2 kwsys_ns(Base64_Encode2)
+#define kwsysBase64_Encode3 kwsys_ns(Base64_Encode3)
 #endif
 
 #if defined(__cplusplus)
-extern "C"
-{
+extern "C" {
 #endif
 
 /**
  * Encode 3 bytes into a 4 byte string.
  */
-kwsysEXPORT void kwsysBase64_Encode3(const unsigned char *src,
-                                     unsigned char *dest);
+kwsysEXPORT void kwsysBase64_Encode3(const unsigned char* src,
+                                     unsigned char* dest);
 
 /**
  * Encode 2 bytes into a 4 byte string.
  */
-kwsysEXPORT void kwsysBase64_Encode2(const unsigned char *src,
-                                     unsigned char *dest);
+kwsysEXPORT void kwsysBase64_Encode2(const unsigned char* src,
+                                     unsigned char* dest);
 
 /**
  * Encode 1 bytes into a 4 byte string.
  */
-kwsysEXPORT void kwsysBase64_Encode1(const unsigned char *src,
-                                     unsigned char *dest);
+kwsysEXPORT void kwsysBase64_Encode1(const unsigned char* src,
+                                     unsigned char* dest);
 
 /**
  * Encode 'length' bytes from the input buffer and store the encoded
@@ -70,17 +60,16 @@ kwsysEXPORT void kwsysBase64_Encode1(const unsigned char *src,
  * the extra padding needed to complete the encode 4 bytes will stop
  * the decoding anyway).
  */
-kwsysEXPORT size_t kwsysBase64_Encode(const unsigned char *input,
-                                      size_t length,
-                                      unsigned char *output,
+kwsysEXPORT size_t kwsysBase64_Encode(const unsigned char* input,
+                                      size_t length, unsigned char* output,
                                       int mark_end);
 
 /**
  * Decode 4 bytes into a 3 byte string.  Returns the number of bytes
  * actually decoded.
  */
-kwsysEXPORT int kwsysBase64_Decode3(const unsigned char *src,
-                                    unsigned char *dest);
+kwsysEXPORT int kwsysBase64_Decode3(const unsigned char* src,
+                                    unsigned char* dest);
 
 /**
  * Decode bytes from the input buffer and store the decoded stream
@@ -94,9 +83,8 @@ kwsysEXPORT int kwsysBase64_Decode3(const unsigned char *src,
  * much decoded data to expect (of course, the buffer must be large
  * enough).
  */
-kwsysEXPORT size_t kwsysBase64_Decode(const unsigned char *input,
-                                      size_t length,
-                                      unsigned char *output,
+kwsysEXPORT size_t kwsysBase64_Decode(const unsigned char* input,
+                                      size_t length, unsigned char* output,
                                       size_t max_input_length);
 
 #if defined(__cplusplus)
@@ -106,17 +94,17 @@ kwsysEXPORT size_t kwsysBase64_Decode(const unsigned char *input,
 /* If we are building a kwsys .c or .cxx file, let it use these macros.
    Otherwise, undefine them to keep the namespace clean.  */
 #if !defined(KWSYS_NAMESPACE)
-# undef kwsys_ns
-# undef kwsysEXPORT
-# if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-#  undef kwsysBase64
-#  undef kwsysBase64_Decode
-#  undef kwsysBase64_Decode3
-#  undef kwsysBase64_Encode
-#  undef kwsysBase64_Encode1
-#  undef kwsysBase64_Encode2
-#  undef kwsysBase64_Encode3
-# endif
+#undef kwsys_ns
+#undef kwsysEXPORT
+#if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
+#undef kwsysBase64
+#undef kwsysBase64_Decode
+#undef kwsysBase64_Decode3
+#undef kwsysBase64_Encode
+#undef kwsysBase64_Encode1
+#undef kwsysBase64_Encode2
+#undef kwsysBase64_Encode3
+#endif
 #endif
 
 #endif
diff --git a/Source/kwsys/CMakeLists.txt b/Source/kwsys/CMakeLists.txt
index c4fe5e8..d4fe8a7 100644
--- a/Source/kwsys/CMakeLists.txt
+++ b/Source/kwsys/CMakeLists.txt
@@ -1,14 +1,5 @@
-#=============================================================================
-# KWSys - Kitware System Library
-# Copyright 2000-2011 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.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing#kwsys for details.
 
 # The Kitware System Library is intended to be included in other
 # projects.  It is completely configurable in that the library's
@@ -76,12 +67,15 @@
 # written.
 
 CMAKE_MINIMUM_REQUIRED(VERSION 2.6.3 FATAL_ERROR)
-IF(POLICY CMP0025)
-  CMAKE_POLICY(SET CMP0025 NEW)
-ENDIF()
-IF(POLICY CMP0056)
-  CMAKE_POLICY(SET CMP0056 NEW)
-ENDIF()
+FOREACH(p
+    CMP0025 # CMake 3.0, Compiler id for Apple Clang is now AppleClang.
+    CMP0056 # CMake 3.2, Honor link flags in try_compile() source-file signature.
+    CMP0063 # CMake 3.3, Honor visibility properties for all target types.
+    )
+  IF(POLICY ${p})
+    CMAKE_POLICY(SET ${p} NEW)
+  ENDIF()
+ENDFOREACH()
 SET(CMAKE_LEGACY_CYGWIN_WIN32 0)
 
 #-----------------------------------------------------------------------------
@@ -435,6 +429,17 @@ SET_SOURCE_FILES_PROPERTIES(ProcessUNIX.c System.c PROPERTIES
   COMPILE_FLAGS "-DKWSYS_C_HAS_PTRDIFF_T=${KWSYS_C_HAS_PTRDIFF_T} -DKWSYS_C_HAS_SSIZE_T=${KWSYS_C_HAS_SSIZE_T}"
   )
 
+IF(KWSYS_USE_DynamicLoader)
+  GET_PROPERTY(KWSYS_SUPPORTS_SHARED_LIBS GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS)
+  IF(KWSYS_SUPPORTS_SHARED_LIBS)
+    SET(KWSYS_SUPPORTS_SHARED_LIBS 1)
+  ELSE()
+    SET(KWSYS_SUPPORTS_SHARED_LIBS 0)
+  ENDIF()
+  SET_PROPERTY(SOURCE DynamicLoader.cxx APPEND PROPERTY COMPILE_DEFINITIONS
+    KWSYS_SUPPORTS_SHARED_LIBS=${KWSYS_SUPPORTS_SHARED_LIBS})
+ENDIF()
+
 IF(KWSYS_USE_SystemTools)
   KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_SETENV
     "Checking whether CXX compiler has setenv" DIRECT)
@@ -813,6 +818,9 @@ IF(KWSYS_C_SRCS OR KWSYS_CXX_SRCS)
         # for symbol lookup using dladdr
         TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE} ${CMAKE_DL_LIBS})
       ENDIF()
+      IF (CMAKE_SYSTEM_NAME STREQUAL "SunOS")
+        TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE} socket)
+      ENDIF()
     ENDIF()
   ENDIF()
 
@@ -874,7 +882,7 @@ ENDIF()
 
 IF(KWSYS_USE_Encoding)
   # Set default 8 bit encoding in "EndcodingC.c".
-  SET_PROPERTY(SOURCE EncodingC.c APPEND PROPERTY COMPILE_DEFINITIONS
+  SET_PROPERTY(SOURCE EncodingC.c EncodingCXX.cxx APPEND PROPERTY COMPILE_DEFINITIONS
     KWSYS_ENCODING_DEFAULT_CODEPAGE=${KWSYS_ENCODING_DEFAULT_CODEPAGE})
 ENDIF()
 
diff --git a/Source/kwsys/CONTRIBUTING.rst b/Source/kwsys/CONTRIBUTING.rst
index 960eea4..d71832a 100644
--- a/Source/kwsys/CONTRIBUTING.rst
+++ b/Source/kwsys/CONTRIBUTING.rst
@@ -1,28 +1,40 @@
 Contributing to KWSys
 *********************
 
-Overview
-========
+Patches
+=======
 
 KWSys is kept in its own Git repository and shared by several projects
 via copies in their source trees.  Changes to KWSys should not be made
 directly in a host project, except perhaps in maintenance branches.
 
-Please visit
+KWSys uses `Kitware's GitLab Instance`_ to manage development and code review.
+To contribute patches:
+
+#. Fork the upstream `KWSys Repository`_ into a personal account.
+#. Base all new work on the upstream ``master`` branch.
+#. Run ``./SetupForDevelopment.sh`` in new local work trees.
+#. Create commits making incremental, distinct, logically complete changes.
+#. Push a topic branch to a personal repository fork on GitLab.
+#. Create a GitLab Merge Request targeting the upstream ``master`` branch.
+
+Once changes are reviewed, tested, and integrated to KWSys upstream then
+copies of KWSys within dependent projects can be updated to get the changes.
 
-  http://public.kitware.com/Wiki/KWSys/Git
+.. _`Kitware's GitLab Instance`: https://gitlab.kitware.com
+.. _`KWSys Repository`: https://gitlab.kitware.com/utils/kwsys
 
-to contribute changes directly to KWSys upstream.  Once changes are
-reviewed, tested, and integrated there then the copies of KWSys within
-dependent projects can be updated to get the changes.
+Code Style
+==========
 
-Issues
-======
+We use `clang-format`_ to define our style for C++ code in the KWSys source
+tree.  See the `.clang-format`_ configuration file for our style settings.
+Use ``clang-format`` version 3.8 or higher to format source files.
+See also the `clang-format.bash`_ script.
 
-KWSys has no independent issue tracker.  After encountering an issue
-(bug) please try to submit a patch using the above instructions.
-Otherwise please report the issue to the tracker for the project that
-hosts the copy of KWSys in which the problem was found.
+.. _`clang-format`: http://clang.llvm.org/docs/ClangFormat.html
+.. _`.clang-format`: .clang-format
+.. _`clang-format.bash`: clang-format.bash
 
 License
 =======
diff --git a/Source/kwsys/CTestConfig.cmake b/Source/kwsys/CTestConfig.cmake
index d977b47..33ea84c 100644
--- a/Source/kwsys/CTestConfig.cmake
+++ b/Source/kwsys/CTestConfig.cmake
@@ -1,14 +1,6 @@
-#=============================================================================
-# KWSys - Kitware System Library
-# Copyright 2000-2012 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.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing#kwsys for details.
+
 set(CTEST_PROJECT_NAME "KWSys")
 set(CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set(CTEST_DROP_METHOD "http")
diff --git a/Source/kwsys/CommandLineArguments.cxx b/Source/kwsys/CommandLineArguments.cxx
index f713294..226263c 100644
--- a/Source/kwsys/CommandLineArguments.cxx
+++ b/Source/kwsys/CommandLineArguments.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(CommandLineArguments.hxx)
 
@@ -18,38 +9,37 @@
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "CommandLineArguments.hxx.in"
-# include "Configure.hxx.in"
-# include "String.hxx.in"
+#include "CommandLineArguments.hxx.in"
+#include "Configure.hxx.in"
+#include "String.hxx.in"
 #endif
 
-#include <vector>
+#include <iostream>
 #include <map>
 #include <set>
 #include <sstream>
-#include <iostream>
+#include <vector>
 
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
 #ifdef _MSC_VER
-# pragma warning (disable: 4786)
+#pragma warning(disable : 4786)
 #endif
 
 #if defined(__sgi) && !defined(__GNUC__)
-# pragma set woff 1375 /* base class destructor not virtual */
+#pragma set woff 1375 /* base class destructor not virtual */
 #endif
 
 #if 0
-#  define CommandLineArguments_DEBUG(x) \
+#define CommandLineArguments_DEBUG(x)                                         \
   std::cout << __LINE__ << " CLA: " << x << std::endl
 #else
-#  define CommandLineArguments_DEBUG(x)
+#define CommandLineArguments_DEBUG(x)
 #endif
 
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
 
 //----------------------------------------------------------------------------
 //============================================================================
@@ -63,24 +53,27 @@ struct CommandLineArgumentsCallbackStructure
   int VariableType;
   const char* Help;
 };
- 
-class CommandLineArgumentsVectorOfStrings : 
-  public std::vector<kwsys::String> {};
-class CommandLineArgumentsSetOfStrings :
-  public std::set<kwsys::String> {};
-class CommandLineArgumentsMapOfStrucs : 
-  public std::map<kwsys::String,
-    CommandLineArgumentsCallbackStructure> {};
+
+class CommandLineArgumentsVectorOfStrings : public std::vector<kwsys::String>
+{
+};
+class CommandLineArgumentsSetOfStrings : public std::set<kwsys::String>
+{
+};
+class CommandLineArgumentsMapOfStrucs
+  : public std::map<kwsys::String, CommandLineArgumentsCallbackStructure>
+{
+};
 
 class CommandLineArgumentsInternal
 {
 public:
   CommandLineArgumentsInternal()
-    {
+  {
     this->UnknownArgumentCallback = 0;
     this->ClientData = 0;
     this->LastArgument = 0;
-    }
+  }
 
   typedef CommandLineArgumentsVectorOfStrings VectorOfStrings;
   typedef CommandLineArgumentsMapOfStrucs CallbacksMap;
@@ -92,7 +85,7 @@ public:
   CallbacksMap Callbacks;
 
   CommandLineArguments::ErrorCallbackType UnknownArgumentCallback;
-  void*             ClientData;
+  void* ClientData;
 
   VectorOfStrings::size_type LastArgument;
 
@@ -123,10 +116,9 @@ void CommandLineArguments::Initialize(int argc, const char* const argv[])
 
   this->Initialize();
   this->Internals->Argv0 = argv[0];
-  for ( cc = 1; cc < argc; cc ++ )
-    {
+  for (cc = 1; cc < argc; cc++) {
     this->ProcessArgument(argv[cc]);
-    }
+  }
 }
 
 //----------------------------------------------------------------------------
@@ -150,32 +142,25 @@ void CommandLineArguments::ProcessArgument(const char* arg)
 
 //----------------------------------------------------------------------------
 bool CommandLineArguments::GetMatchedArguments(
-  std::vector<std::string>* matches,
-  const std::string& arg)
+  std::vector<std::string>* matches, const std::string& arg)
 {
   matches->clear();
   CommandLineArguments::Internal::CallbacksMap::iterator it;
 
   // Does the argument match to any we know about?
-  for ( it = this->Internals->Callbacks.begin();
-    it != this->Internals->Callbacks.end();
-    it ++ )
-    {
+  for (it = this->Internals->Callbacks.begin();
+       it != this->Internals->Callbacks.end(); it++) {
     const CommandLineArguments::Internal::String& parg = it->first;
-    CommandLineArgumentsCallbackStructure *cs = &it->second;
+    CommandLineArgumentsCallbackStructure* cs = &it->second;
     if (cs->ArgumentType == CommandLineArguments::NO_ARGUMENT ||
-      cs->ArgumentType == CommandLineArguments::SPACE_ARGUMENT) 
-      {
-      if ( arg == parg )
-        {
+        cs->ArgumentType == CommandLineArguments::SPACE_ARGUMENT) {
+      if (arg == parg) {
         matches->push_back(parg);
-        }
       }
-    else if ( arg.find( parg ) == 0 )
-      {
+    } else if (arg.find(parg) == 0) {
       matches->push_back(parg);
-      }
     }
+  }
   return !matches->empty();
 }
 
@@ -184,163 +169,143 @@ int CommandLineArguments::Parse()
 {
   std::vector<std::string>::size_type cc;
   std::vector<std::string> matches;
-  if ( this->StoreUnusedArgumentsFlag )
-    {
+  if (this->StoreUnusedArgumentsFlag) {
     this->Internals->UnusedArguments.clear();
-    }
-  for ( cc = 0; cc < this->Internals->Argv.size(); cc ++ )
-    {
+  }
+  for (cc = 0; cc < this->Internals->Argv.size(); cc++) {
     const std::string& arg = this->Internals->Argv[cc];
     CommandLineArguments_DEBUG("Process argument: " << arg);
     this->Internals->LastArgument = cc;
-    if ( this->GetMatchedArguments(&matches, arg) )
-      {
+    if (this->GetMatchedArguments(&matches, arg)) {
       // Ok, we found one or more arguments that match what user specified.
       // Let's find the longest one.
       CommandLineArguments::Internal::VectorOfStrings::size_type kk;
       CommandLineArguments::Internal::VectorOfStrings::size_type maxidx = 0;
       CommandLineArguments::Internal::String::size_type maxlen = 0;
-      for ( kk = 0; kk < matches.size(); kk ++ )
-        {
-        if ( matches[kk].size() > maxlen )
-          {
+      for (kk = 0; kk < matches.size(); kk++) {
+        if (matches[kk].size() > maxlen) {
           maxlen = matches[kk].size();
           maxidx = kk;
-          }
         }
+      }
       // So, the longest one is probably the right one. Now see if it has any
       // additional value
-      CommandLineArgumentsCallbackStructure *cs 
-        = &this->Internals->Callbacks[matches[maxidx]];
+      CommandLineArgumentsCallbackStructure* cs =
+        &this->Internals->Callbacks[matches[maxidx]];
       const std::string& sarg = matches[maxidx];
-      if ( cs->Argument != sarg )
-        {
+      if (cs->Argument != sarg) {
         abort();
-        }
-      switch ( cs->ArgumentType )
-        {
-      case NO_ARGUMENT:
-        // No value
-        if ( !this->PopulateVariable(cs, 0) )
-          {
-          return 0;
+      }
+      switch (cs->ArgumentType) {
+        case NO_ARGUMENT:
+          // No value
+          if (!this->PopulateVariable(cs, 0)) {
+            return 0;
           }
-        break;
-      case SPACE_ARGUMENT:
-        if ( cc == this->Internals->Argv.size()-1 )
-          {
-          this->Internals->LastArgument --;
-          return 0;
+          break;
+        case SPACE_ARGUMENT:
+          if (cc == this->Internals->Argv.size() - 1) {
+            this->Internals->LastArgument--;
+            return 0;
           }
-        CommandLineArguments_DEBUG("This is a space argument: " << arg
-          << " value: " << this->Internals->Argv[cc+1]);
-        // Value is the next argument
-        if ( !this->PopulateVariable(cs, this->Internals->Argv[cc+1].c_str()) )
-          {
-          return 0;
+          CommandLineArguments_DEBUG("This is a space argument: "
+                                     << arg << " value: "
+                                     << this->Internals->Argv[cc + 1]);
+          // Value is the next argument
+          if (!this->PopulateVariable(cs,
+                                      this->Internals->Argv[cc + 1].c_str())) {
+            return 0;
           }
-        cc ++;
-        break;
-      case EQUAL_ARGUMENT:
-        if ( arg.size() == sarg.size() || arg.at(sarg.size()) != '=' )
-          {
-          this->Internals->LastArgument --;
-          return 0;
+          cc++;
+          break;
+        case EQUAL_ARGUMENT:
+          if (arg.size() == sarg.size() || arg.at(sarg.size()) != '=') {
+            this->Internals->LastArgument--;
+            return 0;
           }
-        // Value is everythng followed the '=' sign
-        if ( !this->PopulateVariable(cs, arg.c_str() + sarg.size() + 1) )
-          {
-          return 0;
+          // Value is everythng followed the '=' sign
+          if (!this->PopulateVariable(cs, arg.c_str() + sarg.size() + 1)) {
+            return 0;
           }
-        break;
-      case CONCAT_ARGUMENT:
-        // Value is whatever follows the argument
-        if ( !this->PopulateVariable(cs, arg.c_str() + sarg.size()) )
-          {
-          return 0;
+          break;
+        case CONCAT_ARGUMENT:
+          // Value is whatever follows the argument
+          if (!this->PopulateVariable(cs, arg.c_str() + sarg.size())) {
+            return 0;
           }
-        break;
-      case MULTI_ARGUMENT:
-        // Suck in all the rest of the arguments
-        CommandLineArguments_DEBUG("This is a multi argument: " << arg);
-        for (cc++; cc < this->Internals->Argv.size(); ++ cc )
-          {
-          const std::string& marg = this->Internals->Argv[cc];
-          CommandLineArguments_DEBUG(" check multi argument value: " << marg);
-          if ( this->GetMatchedArguments(&matches, marg) )
-            {
-            CommandLineArguments_DEBUG("End of multi argument " << arg << " with value: " << marg);
-            break;
+          break;
+        case MULTI_ARGUMENT:
+          // Suck in all the rest of the arguments
+          CommandLineArguments_DEBUG("This is a multi argument: " << arg);
+          for (cc++; cc < this->Internals->Argv.size(); ++cc) {
+            const std::string& marg = this->Internals->Argv[cc];
+            CommandLineArguments_DEBUG(
+              " check multi argument value: " << marg);
+            if (this->GetMatchedArguments(&matches, marg)) {
+              CommandLineArguments_DEBUG("End of multi argument "
+                                         << arg << " with value: " << marg);
+              break;
             }
-          CommandLineArguments_DEBUG(" populate multi argument value: " << marg);
-          if ( !this->PopulateVariable(cs, marg.c_str()) )
-            {
-            return 0;
+            CommandLineArguments_DEBUG(
+              " populate multi argument value: " << marg);
+            if (!this->PopulateVariable(cs, marg.c_str())) {
+              return 0;
             }
           }
-        if ( cc != this->Internals->Argv.size() )
-          {
-          CommandLineArguments_DEBUG("Again End of multi argument " << arg);
-          cc--;
-          continue;
+          if (cc != this->Internals->Argv.size()) {
+            CommandLineArguments_DEBUG("Again End of multi argument " << arg);
+            cc--;
+            continue;
           }
-        break;
-      default:
-        std::cerr << "Got unknown argument type: \"" << cs->ArgumentType << "\"" << std::endl;
-        this->Internals->LastArgument --;
-        return 0;
-        }
+          break;
+        default:
+          std::cerr << "Got unknown argument type: \"" << cs->ArgumentType
+                    << "\"" << std::endl;
+          this->Internals->LastArgument--;
+          return 0;
       }
-    else
-      {
+    } else {
       // Handle unknown arguments
-      if ( this->Internals->UnknownArgumentCallback )
-        {
-        if ( !this->Internals->UnknownArgumentCallback(arg.c_str(), 
-            this->Internals->ClientData) )
-          {
-          this->Internals->LastArgument --;
+      if (this->Internals->UnknownArgumentCallback) {
+        if (!this->Internals->UnknownArgumentCallback(
+              arg.c_str(), this->Internals->ClientData)) {
+          this->Internals->LastArgument--;
           return 0;
-          }
-        return 1;
         }
-      else if ( this->StoreUnusedArgumentsFlag )
-        {
+        return 1;
+      } else if (this->StoreUnusedArgumentsFlag) {
         CommandLineArguments_DEBUG("Store unused argument " << arg);
         this->Internals->UnusedArguments.push_back(arg);
-        }
-      else
-        {
+      } else {
         std::cerr << "Got unknown argument: \"" << arg << "\"" << std::endl;
-        this->Internals->LastArgument --;
+        this->Internals->LastArgument--;
         return 0;
-        }
       }
     }
+  }
   return 1;
 }
 
 //----------------------------------------------------------------------------
 void CommandLineArguments::GetRemainingArguments(int* argc, char*** argv)
 {
-  CommandLineArguments::Internal::VectorOfStrings::size_type size 
-    = this->Internals->Argv.size() - this->Internals->LastArgument + 1;
+  CommandLineArguments::Internal::VectorOfStrings::size_type size =
+    this->Internals->Argv.size() - this->Internals->LastArgument + 1;
   CommandLineArguments::Internal::VectorOfStrings::size_type cc;
 
   // Copy Argv0 as the first argument
-  char** args = new char*[ size ];
-  args[0] = new char[ this->Internals->Argv0.size() + 1 ];
+  char** args = new char*[size];
+  args[0] = new char[this->Internals->Argv0.size() + 1];
   strcpy(args[0], this->Internals->Argv0.c_str());
   int cnt = 1;
 
   // Copy everything after the LastArgument, since that was not parsed.
-  for ( cc = this->Internals->LastArgument+1; 
-    cc < this->Internals->Argv.size(); cc ++ )
-    {
-    args[cnt] = new char[ this->Internals->Argv[cc].size() + 1];
+  for (cc = this->Internals->LastArgument + 1;
+       cc < this->Internals->Argv.size(); cc++) {
+    args[cnt] = new char[this->Internals->Argv[cc].size() + 1];
     strcpy(args[cnt], this->Internals->Argv[cc].c_str());
-    cnt ++;
-    }
+    cnt++;
+  }
   *argc = cnt;
   *argv = args;
 }
@@ -348,25 +313,23 @@ void CommandLineArguments::GetRemainingArguments(int* argc, char*** argv)
 //----------------------------------------------------------------------------
 void CommandLineArguments::GetUnusedArguments(int* argc, char*** argv)
 {
-  CommandLineArguments::Internal::VectorOfStrings::size_type size 
-    = this->Internals->UnusedArguments.size() + 1;
+  CommandLineArguments::Internal::VectorOfStrings::size_type size =
+    this->Internals->UnusedArguments.size() + 1;
   CommandLineArguments::Internal::VectorOfStrings::size_type cc;
 
   // Copy Argv0 as the first argument
-  char** args = new char*[ size ];
-  args[0] = new char[ this->Internals->Argv0.size() + 1 ];
+  char** args = new char*[size];
+  args[0] = new char[this->Internals->Argv0.size() + 1];
   strcpy(args[0], this->Internals->Argv0.c_str());
   int cnt = 1;
 
   // Copy everything after the LastArgument, since that was not parsed.
-  for ( cc = 0;
-    cc < this->Internals->UnusedArguments.size(); cc ++ )
-    {
-    kwsys::String &str = this->Internals->UnusedArguments[cc];
-    args[cnt] = new char[ str.size() + 1];
+  for (cc = 0; cc < this->Internals->UnusedArguments.size(); cc++) {
+    kwsys::String& str = this->Internals->UnusedArguments[cc];
+    args[cnt] = new char[str.size() + 1];
     strcpy(args[cnt], str.c_str());
-    cnt ++;
-    }
+    cnt++;
+  }
   *argc = cnt;
   *argv = args;
 }
@@ -375,84 +338,95 @@ void CommandLineArguments::GetUnusedArguments(int* argc, char*** argv)
 void CommandLineArguments::DeleteRemainingArguments(int argc, char*** argv)
 {
   int cc;
-  for ( cc = 0; cc < argc; ++ cc )
-    {
-    delete [] (*argv)[cc];
-    }
-  delete [] *argv;
+  for (cc = 0; cc < argc; ++cc) {
+    delete[](*argv)[cc];
+  }
+  delete[] * argv;
 }
 
 //----------------------------------------------------------------------------
-void CommandLineArguments::AddCallback(const char* argument, ArgumentTypeEnum type, 
-  CallbackType callback, void* call_data, const char* help)
+void CommandLineArguments::AddCallback(const char* argument,
+                                       ArgumentTypeEnum type,
+                                       CallbackType callback, void* call_data,
+                                       const char* help)
 {
   CommandLineArgumentsCallbackStructure s;
-  s.Argument     = argument;
+  s.Argument = argument;
   s.ArgumentType = type;
-  s.Callback     = callback;
-  s.CallData     = call_data;
+  s.Callback = callback;
+  s.CallData = call_data;
   s.VariableType = CommandLineArguments::NO_VARIABLE_TYPE;
-  s.Variable     = 0;
-  s.Help         = help;
+  s.Variable = 0;
+  s.Help = help;
 
   this->Internals->Callbacks[argument] = s;
   this->GenerateHelp();
 }
 
 //----------------------------------------------------------------------------
-void CommandLineArguments::AddArgument(const char* argument, ArgumentTypeEnum type,
-  VariableTypeEnum vtype, void* variable, const char* help)
+void CommandLineArguments::AddArgument(const char* argument,
+                                       ArgumentTypeEnum type,
+                                       VariableTypeEnum vtype, void* variable,
+                                       const char* help)
 {
   CommandLineArgumentsCallbackStructure s;
-  s.Argument     = argument;
+  s.Argument = argument;
   s.ArgumentType = type;
-  s.Callback     = 0;
-  s.CallData     = 0;
+  s.Callback = 0;
+  s.CallData = 0;
   s.VariableType = vtype;
-  s.Variable     = variable;
-  s.Help         = help;
+  s.Variable = variable;
+  s.Help = help;
 
   this->Internals->Callbacks[argument] = s;
   this->GenerateHelp();
 }
 
 //----------------------------------------------------------------------------
-#define CommandLineArgumentsAddArgumentMacro(type, ctype) \
-  void CommandLineArguments::AddArgument(const char* argument, ArgumentTypeEnum type, \
-    ctype* variable, const char* help) \
-  { \
-    this->AddArgument(argument, type, CommandLineArguments::type##_TYPE, variable, help); \
+#define CommandLineArgumentsAddArgumentMacro(type, ctype)                     \
+  void CommandLineArguments::AddArgument(const char* argument,                \
+                                         ArgumentTypeEnum type,               \
+                                         ctype* variable, const char* help)   \
+  {                                                                           \
+    this->AddArgument(argument, type, CommandLineArguments::type##_TYPE,      \
+                      variable, help);                                        \
   }
 
-CommandLineArgumentsAddArgumentMacro(BOOL,       bool)
-CommandLineArgumentsAddArgumentMacro(INT,        int)
-CommandLineArgumentsAddArgumentMacro(DOUBLE,     double)
-CommandLineArgumentsAddArgumentMacro(STRING,     char*)
-CommandLineArgumentsAddArgumentMacro(STL_STRING, std::string)
-
-CommandLineArgumentsAddArgumentMacro(VECTOR_BOOL,       std::vector<bool>)
-CommandLineArgumentsAddArgumentMacro(VECTOR_INT,        std::vector<int>)
-CommandLineArgumentsAddArgumentMacro(VECTOR_DOUBLE,     std::vector<double>)
-CommandLineArgumentsAddArgumentMacro(VECTOR_STRING,     std::vector<char*>)
-CommandLineArgumentsAddArgumentMacro(VECTOR_STL_STRING, std::vector<std::string>)
-
-//----------------------------------------------------------------------------
-#define CommandLineArgumentsAddBooleanArgumentMacro(type, ctype) \
-  void CommandLineArguments::AddBooleanArgument(const char* argument, \
-    ctype* variable, const char* help) \
-  { \
-    this->AddArgument(argument, CommandLineArguments::NO_ARGUMENT, \
-      CommandLineArguments::type##_TYPE, variable, help); \
+CommandLineArgumentsAddArgumentMacro(BOOL, bool)
+  CommandLineArgumentsAddArgumentMacro(INT, int)
+    CommandLineArgumentsAddArgumentMacro(DOUBLE, double)
+      CommandLineArgumentsAddArgumentMacro(STRING, char*)
+        CommandLineArgumentsAddArgumentMacro(STL_STRING, std::string)
+
+          CommandLineArgumentsAddArgumentMacro(VECTOR_BOOL, std::vector<bool>)
+            CommandLineArgumentsAddArgumentMacro(VECTOR_INT, std::vector<int>)
+              CommandLineArgumentsAddArgumentMacro(VECTOR_DOUBLE,
+                                                   std::vector<double>)
+                CommandLineArgumentsAddArgumentMacro(VECTOR_STRING,
+                                                     std::vector<char*>)
+                  CommandLineArgumentsAddArgumentMacro(
+                    VECTOR_STL_STRING, std::vector<std::string>)
+
+//----------------------------------------------------------------------------
+#define CommandLineArgumentsAddBooleanArgumentMacro(type, ctype)              \
+  void CommandLineArguments::AddBooleanArgument(                              \
+    const char* argument, ctype* variable, const char* help)                  \
+  {                                                                           \
+    this->AddArgument(argument, CommandLineArguments::NO_ARGUMENT,            \
+                      CommandLineArguments::type##_TYPE, variable, help);     \
   }
 
-CommandLineArgumentsAddBooleanArgumentMacro(BOOL,       bool)
-CommandLineArgumentsAddBooleanArgumentMacro(INT,        int)
-CommandLineArgumentsAddBooleanArgumentMacro(DOUBLE,     double)
-CommandLineArgumentsAddBooleanArgumentMacro(STRING,     char*)
-CommandLineArgumentsAddBooleanArgumentMacro(STL_STRING, std::string)
+                    CommandLineArgumentsAddBooleanArgumentMacro(BOOL, bool)
+                      CommandLineArgumentsAddBooleanArgumentMacro(INT, int)
+                        CommandLineArgumentsAddBooleanArgumentMacro(DOUBLE,
+                                                                    double)
+                          CommandLineArgumentsAddBooleanArgumentMacro(STRING,
+                                                                      char*)
+                            CommandLineArgumentsAddBooleanArgumentMacro(
+                              STL_STRING, std::string)
 
-//----------------------------------------------------------------------------
-void CommandLineArguments::SetClientData(void* client_data)
+  //----------------------------------------------------------------------------
+  void CommandLineArguments::SetClientData(void* client_data)
 {
   this->Internals->ClientData = client_data;
 }
@@ -467,36 +441,32 @@ void CommandLineArguments::SetUnknownArgumentCallback(
 //----------------------------------------------------------------------------
 const char* CommandLineArguments::GetHelp(const char* arg)
 {
-  CommandLineArguments::Internal::CallbacksMap::iterator it 
-    = this->Internals->Callbacks.find(arg);
-  if ( it == this->Internals->Callbacks.end() )
-    {
+  CommandLineArguments::Internal::CallbacksMap::iterator it =
+    this->Internals->Callbacks.find(arg);
+  if (it == this->Internals->Callbacks.end()) {
     return 0;
-    }
+  }
 
   // Since several arguments may point to the same argument, find the one this
   // one point to if this one is pointing to another argument.
-  CommandLineArgumentsCallbackStructure *cs = &(it->second);
-  for(;;)
-    {
-    CommandLineArguments::Internal::CallbacksMap::iterator hit 
-      = this->Internals->Callbacks.find(cs->Help);
-    if ( hit == this->Internals->Callbacks.end() )
-      {
+  CommandLineArgumentsCallbackStructure* cs = &(it->second);
+  for (;;) {
+    CommandLineArguments::Internal::CallbacksMap::iterator hit =
+      this->Internals->Callbacks.find(cs->Help);
+    if (hit == this->Internals->Callbacks.end()) {
       break;
-      }
-    cs = &(hit->second);
     }
+    cs = &(hit->second);
+  }
   return cs->Help;
 }
 
 //----------------------------------------------------------------------------
 void CommandLineArguments::SetLineLength(unsigned int ll)
 {
-  if ( ll < 9 || ll > 1000 )
-    {
+  if (ll < 9 || ll > 1000) {
     return;
-    }
+  }
   this->LineLength = ll;
   this->GenerateHelp();
 }
@@ -517,76 +487,68 @@ unsigned int CommandLineArguments::GetLastArgument()
 void CommandLineArguments::GenerateHelp()
 {
   std::ostringstream str;
-  
+
   // Collapse all arguments into the map of vectors of all arguments that do
   // the same thing.
   CommandLineArguments::Internal::CallbacksMap::iterator it;
   typedef std::map<CommandLineArguments::Internal::String,
-     CommandLineArguments::Internal::SetOfStrings > MapArgs;
+                   CommandLineArguments::Internal::SetOfStrings>
+    MapArgs;
   MapArgs mp;
   MapArgs::iterator mpit, smpit;
-  for ( it = this->Internals->Callbacks.begin();
-    it != this->Internals->Callbacks.end();
-    it ++ )
-    {
-    CommandLineArgumentsCallbackStructure *cs = &(it->second);
+  for (it = this->Internals->Callbacks.begin();
+       it != this->Internals->Callbacks.end(); it++) {
+    CommandLineArgumentsCallbackStructure* cs = &(it->second);
     mpit = mp.find(cs->Help);
-    if ( mpit != mp.end() )
-      {
+    if (mpit != mp.end()) {
       mpit->second.insert(it->first);
       mp[it->first].insert(it->first);
-      }
-    else
-      {
+    } else {
       mp[it->first].insert(it->first);
-      }
     }
-  for ( it = this->Internals->Callbacks.begin();
-    it != this->Internals->Callbacks.end();
-    it ++ )
-    {
-    CommandLineArgumentsCallbackStructure *cs = &(it->second);
+  }
+  for (it = this->Internals->Callbacks.begin();
+       it != this->Internals->Callbacks.end(); it++) {
+    CommandLineArgumentsCallbackStructure* cs = &(it->second);
     mpit = mp.find(cs->Help);
-    if ( mpit != mp.end() )
-      {
+    if (mpit != mp.end()) {
       mpit->second.insert(it->first);
       smpit = mp.find(it->first);
       CommandLineArguments::Internal::SetOfStrings::iterator sit;
-      for ( sit = smpit->second.begin(); sit != smpit->second.end(); sit++ )
-        {
+      for (sit = smpit->second.begin(); sit != smpit->second.end(); sit++) {
         mpit->second.insert(*sit);
-        }
-      mp.erase(smpit);
       }
-    else
-      {
+      mp.erase(smpit);
+    } else {
       mp[it->first].insert(it->first);
-      }
     }
- 
+  }
+
   // Find the length of the longest string
   CommandLineArguments::Internal::String::size_type maxlen = 0;
-  for ( mpit = mp.begin();
-    mpit != mp.end();
-    mpit ++ )
-    {
+  for (mpit = mp.begin(); mpit != mp.end(); mpit++) {
     CommandLineArguments::Internal::SetOfStrings::iterator sit;
-    for ( sit = mpit->second.begin(); sit != mpit->second.end(); sit++ )
-      {
+    for (sit = mpit->second.begin(); sit != mpit->second.end(); sit++) {
       CommandLineArguments::Internal::String::size_type clen = sit->size();
-      switch ( this->Internals->Callbacks[*sit].ArgumentType )
-        {
-        case CommandLineArguments::NO_ARGUMENT:     clen += 0; break;
-        case CommandLineArguments::CONCAT_ARGUMENT: clen += 3; break;
-        case CommandLineArguments::SPACE_ARGUMENT:  clen += 4; break;
-        case CommandLineArguments::EQUAL_ARGUMENT:  clen += 4; break;
-        }
-      if ( clen > maxlen )
-        {
+      switch (this->Internals->Callbacks[*sit].ArgumentType) {
+        case CommandLineArguments::NO_ARGUMENT:
+          clen += 0;
+          break;
+        case CommandLineArguments::CONCAT_ARGUMENT:
+          clen += 3;
+          break;
+        case CommandLineArguments::SPACE_ARGUMENT:
+          clen += 4;
+          break;
+        case CommandLineArguments::EQUAL_ARGUMENT:
+          clen += 4;
+          break;
+      }
+      if (clen > maxlen) {
         maxlen = clen;
-        }
       }
     }
+  }
 
   // Create format for that string
   char format[80];
@@ -595,74 +557,69 @@ void CommandLineArguments::GenerateHelp()
   maxlen += 4; // For the space before and after the option
 
   // Print help for each option
-  for ( mpit = mp.begin();
-    mpit != mp.end();
-    mpit ++ )
-    {
+  for (mpit = mp.begin(); mpit != mp.end(); mpit++) {
     CommandLineArguments::Internal::SetOfStrings::iterator sit;
-    for ( sit = mpit->second.begin(); sit != mpit->second.end(); sit++ )
-      {
+    for (sit = mpit->second.begin(); sit != mpit->second.end(); sit++) {
       str << std::endl;
       char argument[100];
       sprintf(argument, "%s", sit->c_str());
-      switch ( this->Internals->Callbacks[*sit].ArgumentType )
-        {
-        case CommandLineArguments::NO_ARGUMENT: break;
-        case CommandLineArguments::CONCAT_ARGUMENT: strcat(argument, "opt"); break;
-        case CommandLineArguments::SPACE_ARGUMENT:  strcat(argument, " opt"); break;
-        case CommandLineArguments::EQUAL_ARGUMENT:  strcat(argument, "=opt"); break;
-        case CommandLineArguments::MULTI_ARGUMENT:  strcat(argument, " opt opt ..."); break;
-        }
+      switch (this->Internals->Callbacks[*sit].ArgumentType) {
+        case CommandLineArguments::NO_ARGUMENT:
+          break;
+        case CommandLineArguments::CONCAT_ARGUMENT:
+          strcat(argument, "opt");
+          break;
+        case CommandLineArguments::SPACE_ARGUMENT:
+          strcat(argument, " opt");
+          break;
+        case CommandLineArguments::EQUAL_ARGUMENT:
+          strcat(argument, "=opt");
+          break;
+        case CommandLineArguments::MULTI_ARGUMENT:
+          strcat(argument, " opt opt ...");
+          break;
+      }
       char buffer[80];
       sprintf(buffer, format, argument);
       str << buffer;
-      }
+    }
     const char* ptr = this->Internals->Callbacks[mpit->first].Help;
     size_t len = strlen(ptr);
     int cnt = 0;
-    while ( len > 0)
-      {
+    while (len > 0) {
       // If argument with help is longer than line length, split it on previous
       // space (or tab) and continue on the next line
       CommandLineArguments::Internal::String::size_type cc;
-      for ( cc = 0; ptr[cc]; cc ++ )
-        {
-        if ( *ptr == ' ' || *ptr == '\t' )
-          {
-          ptr ++;
-          len --;
-          }
+      for (cc = 0; ptr[cc]; cc++) {
+        if (*ptr == ' ' || *ptr == '\t') {
+          ptr++;
+          len--;
         }
-      if ( cnt > 0 )
-        {
-        for ( cc = 0; cc < maxlen; cc ++ )
-          {
+      }
+      if (cnt > 0) {
+        for (cc = 0; cc < maxlen; cc++) {
           str << " ";
-          }
         }
+      }
       CommandLineArguments::Internal::String::size_type skip = len;
-      if ( skip > this->LineLength - maxlen )
-        {
+      if (skip > this->LineLength - maxlen) {
         skip = this->LineLength - maxlen;
-        for ( cc = skip-1; cc > 0; cc -- )
-          {
-          if ( ptr[cc] == ' ' || ptr[cc] == '\t' )
-            {
+        for (cc = skip - 1; cc > 0; cc--) {
+          if (ptr[cc] == ' ' || ptr[cc] == '\t') {
             break;
-            }
           }
-        if ( cc != 0 )
-          {
+        }
+        if (cc != 0) {
           skip = cc;
-          }
         }
+      }
       str.write(ptr, static_cast<std::streamsize>(skip));
       str << std::endl;
       ptr += skip;
       len -= skip;
-      cnt ++;
-      }
+      cnt++;
     }
+  }
   /*
   // This can help debugging help string
   str << endl;
@@ -677,181 +634,176 @@ void CommandLineArguments::GenerateHelp()
 }
 
 //----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
-  bool* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(bool* variable,
+                                            const std::string& value)
 {
-  if ( value == "1" || value == "ON" || value == "on" || value == "On" ||
-    value == "TRUE" || value == "true" || value == "True" ||
-    value == "yes" || value == "Yes" || value == "YES" )
-    {
+  if (value == "1" || value == "ON" || value == "on" || value == "On" ||
+      value == "TRUE" || value == "true" || value == "True" ||
+      value == "yes" || value == "Yes" || value == "YES") {
     *variable = true;
-    }
-  else
-    {
+  } else {
     *variable = false;
-    }
+  }
 }
 
 //----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
-  int* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(int* variable,
+                                            const std::string& value)
 {
   char* res = 0;
   *variable = static_cast<int>(strtol(value.c_str(), &res, 10));
-  //if ( res && *res )
+  // if ( res && *res )
   //  {
   //  Can handle non-int
   //  }
 }
 
 //----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
-  double* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(double* variable,
+                                            const std::string& value)
 {
   char* res = 0;
   *variable = strtod(value.c_str(), &res);
-  //if ( res && *res )
+  // if ( res && *res )
   //  {
   //  Can handle non-double
   //  }
 }
 
 //----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
-  char** variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(char** variable,
+                                            const std::string& value)
 {
-  if ( *variable )
-    {
-    delete [] *variable;
+  if (*variable) {
+    delete[] * variable;
     *variable = 0;
-    }
-  *variable = new char[ value.size() + 1 ];
+  }
+  *variable = new char[value.size() + 1];
   strcpy(*variable, value.c_str());
 }
 
 //----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
-  std::string* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(std::string* variable,
+                                            const std::string& value)
 {
   *variable = value;
 }
 
 //----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
-  std::vector<bool>* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(std::vector<bool>* variable,
+                                            const std::string& value)
 {
   bool val = false;
-  if ( value == "1" || value == "ON" || value == "on" || value == "On" ||
-    value == "TRUE" || value == "true" || value == "True" ||
-    value == "yes" || value == "Yes" || value == "YES" )
-    {
+  if (value == "1" || value == "ON" || value == "on" || value == "On" ||
+      value == "TRUE" || value == "true" || value == "True" ||
+      value == "yes" || value == "Yes" || value == "YES") {
     val = true;
-    }
+  }
   variable->push_back(val);
 }
 
 //----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
-  std::vector<int>* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(std::vector<int>* variable,
+                                            const std::string& value)
 {
   char* res = 0;
   variable->push_back(static_cast<int>(strtol(value.c_str(), &res, 10)));
-  //if ( res && *res )
+  // if ( res && *res )
   //  {
   //  Can handle non-int
   //  }
 }
 
 //----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
-  std::vector<double>* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(std::vector<double>* variable,
+                                            const std::string& value)
 {
   char* res = 0;
   variable->push_back(strtod(value.c_str(), &res));
-  //if ( res && *res )
+  // if ( res && *res )
   //  {
   //  Can handle non-int
   //  }
 }
 
 //----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
-  std::vector<char*>* variable, const std::string& value)
+void CommandLineArguments::PopulateVariable(std::vector<char*>* variable,
+                                            const std::string& value)
 {
-  char* var = new char[ value.size() + 1 ];
+  char* var = new char[value.size() + 1];
   strcpy(var, value.c_str());
   variable->push_back(var);
 }
 
 //----------------------------------------------------------------------------
-void CommandLineArguments::PopulateVariable(
-  std::vector<std::string>* variable,
-  const std::string& value)
+void CommandLineArguments::PopulateVariable(std::vector<std::string>* variable,
+                                            const std::string& value)
 {
   variable->push_back(value);
 }
 
 //----------------------------------------------------------------------------
-bool CommandLineArguments::PopulateVariable(CommandLineArgumentsCallbackStructure* cs,
-  const char* value)
+bool CommandLineArguments::PopulateVariable(
+  CommandLineArgumentsCallbackStructure* cs, const char* value)
 {
   // Call the callback
-  if ( cs->Callback )
-    {
-    if ( !cs->Callback(cs->Argument, value, cs->CallData) )
-      {
-      this->Internals->LastArgument --;
+  if (cs->Callback) {
+    if (!cs->Callback(cs->Argument, value, cs->CallData)) {
+      this->Internals->LastArgument--;
       return 0;
-      }
     }
-  CommandLineArguments_DEBUG("Set argument: " << cs->Argument << " to " << value);
-  if ( cs->Variable )
-    {
+  }
+  CommandLineArguments_DEBUG("Set argument: " << cs->Argument << " to "
+                                              << value);
+  if (cs->Variable) {
     std::string var = "1";
-    if ( value )
-      {
+    if (value) {
       var = value;
-      }
-    switch ( cs->VariableType )
-      {
-    case CommandLineArguments::INT_TYPE:
-      this->PopulateVariable(static_cast<int*>(cs->Variable), var);
-      break;
-    case CommandLineArguments::DOUBLE_TYPE:
-      this->PopulateVariable(static_cast<double*>(cs->Variable), var);
-      break;
-    case CommandLineArguments::STRING_TYPE:
-      this->PopulateVariable(static_cast<char**>(cs->Variable), var);
-      break;
-    case CommandLineArguments::STL_STRING_TYPE:
-      this->PopulateVariable(static_cast<std::string*>(cs->Variable), var);
-      break;
-    case CommandLineArguments::BOOL_TYPE:
-      this->PopulateVariable(static_cast<bool*>(cs->Variable), var);
-      break;
-    case CommandLineArguments::VECTOR_BOOL_TYPE:
-      this->PopulateVariable(static_cast<std::vector<bool>*>(cs->Variable), var);
-      break;
-    case CommandLineArguments::VECTOR_INT_TYPE:
-      this->PopulateVariable(static_cast<std::vector<int>*>(cs->Variable), var);
-      break;
-    case CommandLineArguments::VECTOR_DOUBLE_TYPE:
-      this->PopulateVariable(static_cast<std::vector<double>*>(cs->Variable), var);
-      break;
-    case CommandLineArguments::VECTOR_STRING_TYPE:
-      this->PopulateVariable(static_cast<std::vector<char*>*>(cs->Variable), var);
-      break;
-    case CommandLineArguments::VECTOR_STL_STRING_TYPE:
-      this->PopulateVariable(static_cast<std::vector<std::string>*>(cs->Variable), var);
-      break;
-    default:
-      std::cerr << "Got unknown variable type: \"" << cs->VariableType << "\"" << std::endl;
-      this->Internals->LastArgument --;
-      return 0;
-      }
     }
+    switch (cs->VariableType) {
+      case CommandLineArguments::INT_TYPE:
+        this->PopulateVariable(static_cast<int*>(cs->Variable), var);
+        break;
+      case CommandLineArguments::DOUBLE_TYPE:
+        this->PopulateVariable(static_cast<double*>(cs->Variable), var);
+        break;
+      case CommandLineArguments::STRING_TYPE:
+        this->PopulateVariable(static_cast<char**>(cs->Variable), var);
+        break;
+      case CommandLineArguments::STL_STRING_TYPE:
+        this->PopulateVariable(static_cast<std::string*>(cs->Variable), var);
+        break;
+      case CommandLineArguments::BOOL_TYPE:
+        this->PopulateVariable(static_cast<bool*>(cs->Variable), var);
+        break;
+      case CommandLineArguments::VECTOR_BOOL_TYPE:
+        this->PopulateVariable(static_cast<std::vector<bool>*>(cs->Variable),
+                               var);
+        break;
+      case CommandLineArguments::VECTOR_INT_TYPE:
+        this->PopulateVariable(static_cast<std::vector<int>*>(cs->Variable),
+                               var);
+        break;
+      case CommandLineArguments::VECTOR_DOUBLE_TYPE:
+        this->PopulateVariable(static_cast<std::vector<double>*>(cs->Variable),
+                               var);
+        break;
+      case CommandLineArguments::VECTOR_STRING_TYPE:
+        this->PopulateVariable(static_cast<std::vector<char*>*>(cs->Variable),
+                               var);
+        break;
+      case CommandLineArguments::VECTOR_STL_STRING_TYPE:
+        this->PopulateVariable(
+          static_cast<std::vector<std::string>*>(cs->Variable), var);
+        break;
+      default:
+        std::cerr << "Got unknown variable type: \"" << cs->VariableType
+                  << "\"" << std::endl;
+        this->Internals->LastArgument--;
+        return 0;
+    }
+  }
   return 1;
 }
 
-
 } // namespace KWSYS_NAMESPACE
diff --git a/Source/kwsys/CommandLineArguments.hxx.in b/Source/kwsys/CommandLineArguments.hxx.in
index e4f6d02..31115e5 100644
--- a/Source/kwsys/CommandLineArguments.hxx.in
+++ b/Source/kwsys/CommandLineArguments.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _CommandLineArguments_hxx
 #define @KWSYS_NAMESPACE at _CommandLineArguments_hxx
 
@@ -18,8 +9,7 @@
 #include <string>
 #include <vector>
 
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 
 class CommandLineArgumentsInternal;
 struct CommandLineArgumentsCallbackStructure;
@@ -41,28 +31,29 @@ struct CommandLineArgumentsCallbackStructure;
  * the argument is specified, the variable is set to the specified value casted
  * to the appropriate type. For boolean (NO_ARGUMENT), the value is "1".
  *
- * Both interfaces can be used at the same time. 
+ * Both interfaces can be used at the same time.
  *
  * Possible argument types are:
  *   NO_ARGUMENT     - The argument takes no value             : --A
  *   CONCAT_ARGUMENT - The argument takes value after no space : --Aval
- *   SPACE_ARGUMENT  - The argument takes value after space    : --A val 
+ *   SPACE_ARGUMENT  - The argument takes value after space    : --A val
  *   EQUAL_ARGUMENT  - The argument takes value after equal    : --A=val
- *   MULTI_ARGUMENT  - The argument takes values after space   : --A val1 val2 val3 ...
+ *   MULTI_ARGUMENT  - The argument takes values after space   : --A val1 val2
+ * val3 ...
  *
  * Example use:
  *
  * kwsys::CommandLineArguments arg;
  * arg.Initialize(argc, argv);
  * typedef kwsys::CommandLineArguments argT;
- * arg.AddArgument("--something", argT::EQUAL_ARGUMENT, &some_variable, 
+ * arg.AddArgument("--something", argT::EQUAL_ARGUMENT, &some_variable,
  *                 "This is help string for --something");
  * if ( !arg.Parse() )
  *   {
  *   std::cerr << "Problem parsing arguments" << std::endl;
  *   res = 1;
  *   }
- * 
+ *
  */
 
 class @KWSYS_NAMESPACE at _EXPORT CommandLineArguments
@@ -74,7 +65,8 @@ public:
   /**
    * Various argument types.
    */
-  enum ArgumentTypeEnum { 
+  enum ArgumentTypeEnum
+  {
     NO_ARGUMENT,
     CONCAT_ARGUMENT,
     SPACE_ARGUMENT,
@@ -86,27 +78,28 @@ public:
    * Various variable types. When using the variable interface, this specifies
    * what type the variable is.
    */
-  enum VariableTypeEnum {
-    NO_VARIABLE_TYPE = 0, // The variable is not specified
-    INT_TYPE,             // The variable is integer (int)
-    BOOL_TYPE,            // The variable is boolean (bool)
-    DOUBLE_TYPE,          // The variable is float (double)
-    STRING_TYPE,          // The variable is string (char*)
-    STL_STRING_TYPE,      // The variable is string (char*)
-    VECTOR_INT_TYPE,             // The variable is integer (int)
-    VECTOR_BOOL_TYPE,            // The variable is boolean (bool)
-    VECTOR_DOUBLE_TYPE,          // The variable is float (double)
-    VECTOR_STRING_TYPE,          // The variable is string (char*)
-    VECTOR_STL_STRING_TYPE,      // The variable is string (char*)
+  enum VariableTypeEnum
+  {
+    NO_VARIABLE_TYPE = 0,   // The variable is not specified
+    INT_TYPE,               // The variable is integer (int)
+    BOOL_TYPE,              // The variable is boolean (bool)
+    DOUBLE_TYPE,            // The variable is float (double)
+    STRING_TYPE,            // The variable is string (char*)
+    STL_STRING_TYPE,        // The variable is string (char*)
+    VECTOR_INT_TYPE,        // The variable is integer (int)
+    VECTOR_BOOL_TYPE,       // The variable is boolean (bool)
+    VECTOR_DOUBLE_TYPE,     // The variable is float (double)
+    VECTOR_STRING_TYPE,     // The variable is string (char*)
+    VECTOR_STL_STRING_TYPE, // The variable is string (char*)
     LAST_VARIABLE_TYPE
   };
 
   /**
    * Prototypes for callbacks for callback interface.
    */
-  typedef int(*CallbackType)(const char* argument, const char* value, 
-    void* call_data);
-  typedef int(*ErrorCallbackType)(const char* argument, void* client_data);
+  typedef int (*CallbackType)(const char* argument, const char* value,
+                              void* call_data);
+  typedef int (*ErrorCallbackType)(const char* argument, void* client_data);
 
   /**
    * Initialize internal data structures. This should be called before parsing.
@@ -133,24 +126,24 @@ public:
    * argument help specifies the help string used with this option. The
    * callback and call_data can be skipped.
    */
-  void AddCallback(const char* argument, ArgumentTypeEnum type, 
-    CallbackType callback, void* call_data, const char* help);
+  void AddCallback(const char* argument, ArgumentTypeEnum type,
+                   CallbackType callback, void* call_data, const char* help);
 
   /**
    * Add handler for argument which is going to set the variable to the
    * specified value. If the argument is specified, the option is casted to the
    * appropriate type.
    */
+  void AddArgument(const char* argument, ArgumentTypeEnum type, bool* variable,
+                   const char* help);
+  void AddArgument(const char* argument, ArgumentTypeEnum type, int* variable,
+                   const char* help);
   void AddArgument(const char* argument, ArgumentTypeEnum type,
-    bool* variable, const char* help);
+                   double* variable, const char* help);
   void AddArgument(const char* argument, ArgumentTypeEnum type,
-    int* variable, const char* help);
-  void AddArgument(const char* argument, ArgumentTypeEnum type, 
-    double* variable, const char* help);
-  void AddArgument(const char* argument, ArgumentTypeEnum type, 
-    char** variable, const char* help);
+                   char** variable, const char* help);
   void AddArgument(const char* argument, ArgumentTypeEnum type,
-    std::string* variable, const char* help);
+                   std::string* variable, const char* help);
 
   /**
    * Add handler for argument which is going to set the variable to the
@@ -158,31 +151,31 @@ public:
    * appropriate type. This will handle the multi argument values.
    */
   void AddArgument(const char* argument, ArgumentTypeEnum type,
-    std::vector<bool>* variable, const char* help);
+                   std::vector<bool>* variable, const char* help);
+  void AddArgument(const char* argument, ArgumentTypeEnum type,
+                   std::vector<int>* variable, const char* help);
+  void AddArgument(const char* argument, ArgumentTypeEnum type,
+                   std::vector<double>* variable, const char* help);
   void AddArgument(const char* argument, ArgumentTypeEnum type,
-    std::vector<int>* variable, const char* help);
-  void AddArgument(const char* argument, ArgumentTypeEnum type, 
-    std::vector<double>* variable, const char* help);
-  void AddArgument(const char* argument, ArgumentTypeEnum type, 
-    std::vector<char*>* variable, const char* help);
+                   std::vector<char*>* variable, const char* help);
   void AddArgument(const char* argument, ArgumentTypeEnum type,
-    std::vector<std::string>* variable, const char* help);
+                   std::vector<std::string>* variable, const char* help);
 
   /**
    * Add handler for boolean argument. The argument does not take any option
    * and if it is specified, the value of the variable is true/1, otherwise it
    * is false/0.
    */
-  void AddBooleanArgument(const char* argument,
-    bool* variable, const char* help);
-  void AddBooleanArgument(const char* argument,
-    int* variable, const char* help);
-  void AddBooleanArgument(const char* argument,
-    double* variable, const char* help);
-  void AddBooleanArgument(const char* argument,
-    char** variable, const char* help);
-  void AddBooleanArgument(const char* argument,
-    std::string* variable, const char* help);
+  void AddBooleanArgument(const char* argument, bool* variable,
+                          const char* help);
+  void AddBooleanArgument(const char* argument, int* variable,
+                          const char* help);
+  void AddBooleanArgument(const char* argument, double* variable,
+                          const char* help);
+  void AddBooleanArgument(const char* argument, char** variable,
+                          const char* help);
+  void AddBooleanArgument(const char* argument, std::string* variable,
+                          const char* help);
 
   /**
    * Set the callbacks for error handling.
@@ -236,14 +229,14 @@ protected:
 
   //! This is internal method that registers variable with argument
   void AddArgument(const char* argument, ArgumentTypeEnum type,
-    VariableTypeEnum vtype, void* variable, const char* help);
+                   VariableTypeEnum vtype, void* variable, const char* help);
 
   bool GetMatchedArguments(std::vector<std::string>* matches,
-    const std::string& arg);
+                           const std::string& arg);
 
   //! Populate individual variables
   bool PopulateVariable(CommandLineArgumentsCallbackStructure* cs,
-    const char* value);
+                        const char* value);
 
   //! Populate individual variables of type ...
   void PopulateVariable(bool* variable, const std::string& value);
@@ -253,9 +246,12 @@ protected:
   void PopulateVariable(std::string* variable, const std::string& value);
   void PopulateVariable(std::vector<bool>* variable, const std::string& value);
   void PopulateVariable(std::vector<int>* variable, const std::string& value);
-  void PopulateVariable(std::vector<double>* variable, const std::string& value);
-  void PopulateVariable(std::vector<char*>* variable, const std::string& value);
-  void PopulateVariable(std::vector<std::string>* variable, const std::string& value);
+  void PopulateVariable(std::vector<double>* variable,
+                        const std::string& value);
+  void PopulateVariable(std::vector<char*>* variable,
+                        const std::string& value);
+  void PopulateVariable(std::vector<std::string>* variable,
+                        const std::string& value);
 
   typedef CommandLineArgumentsInternal Internal;
   Internal* Internals;
@@ -269,8 +265,3 @@ protected:
 } // namespace @KWSYS_NAMESPACE@
 
 #endif
-
-
-
-
-
diff --git a/Source/kwsys/Configure.h.in b/Source/kwsys/Configure.h.in
index cd2d965..0afcae7 100644
--- a/Source/kwsys/Configure.h.in
+++ b/Source/kwsys/Configure.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _Configure_h
 #define @KWSYS_NAMESPACE at _Configure_h
 
@@ -16,22 +7,22 @@
    namespace.  When not building a kwsys source file these macros are
    temporarily defined inside the headers that use them.  */
 #if defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
 #endif
 
 /* Disable some warnings inside kwsys source files.  */
 #if defined(KWSYS_NAMESPACE)
-# if defined(__BORLANDC__)
-#  pragma warn -8027 /* function not inlined.  */
-# endif
-# if defined(__INTEL_COMPILER)
-#  pragma warning (disable: 1572) /* floating-point equality test */
-# endif
-# if defined(__sgi) && !defined(__GNUC__)
-#  pragma set woff 3970 /* pointer to int conversion */
-#  pragma set woff 3968 /* 64 bit conversion */
-# endif
+#if defined(__BORLANDC__)
+#pragma warn - 8027 /* function not inlined.  */
+#endif
+#if defined(__INTEL_COMPILER)
+#pragma warning(disable : 1572) /* floating-point equality test */
+#endif
+#if defined(__sgi) && !defined(__GNUC__)
+#pragma set woff 3970 /* pointer to int conversion */
+#pragma set woff 3968 /* 64 bit conversion */
+#endif
 #endif
 
 /* Whether kwsys namespace is "kwsys".  */
@@ -42,84 +33,84 @@
 
 /* Whether Large File Support is available.  */
 #if @KWSYS_NAMESPACE at _LFS_REQUESTED
-# define @KWSYS_NAMESPACE at _LFS_AVAILABLE @KWSYS_LFS_AVAILABLE@
+#define @KWSYS_NAMESPACE at _LFS_AVAILABLE @KWSYS_LFS_AVAILABLE@
 #endif
 
 /* Setup Large File Support if requested.  */
 #if @KWSYS_NAMESPACE at _LFS_REQUESTED
-  /* Since LFS is requested this header must be included before system
-     headers whether or not LFS is available. */
-# if 0 && (defined(_SYS_TYPES_H) || defined(_SYS_TYPES_INCLUDED))
-#  error "@KWSYS_NAMESPACE@/Configure.h must be included before sys/types.h"
-# endif
-  /* Enable the large file API if it is available.  */
-# if @KWSYS_NAMESPACE at _LFS_AVAILABLE && \
-     !defined(@KWSYS_NAMESPACE at _LFS_NO_DEFINES)
-#  if !defined(_LARGEFILE_SOURCE) && \
-      !defined(@KWSYS_NAMESPACE at _LFS_NO_DEFINE_LARGEFILE_SOURCE)
-#   define _LARGEFILE_SOURCE
-#  endif
-#  if !defined(_LARGEFILE64_SOURCE) && \
-      !defined(@KWSYS_NAMESPACE at _LFS_NO_DEFINE_LARGEFILE64_SOURCE)
-#   define _LARGEFILE64_SOURCE
-#  endif
-#  if !defined(_LARGE_FILES) && \
-      !defined(@KWSYS_NAMESPACE at _LFS_NO_DEFINE_LARGE_FILES)
-#   define _LARGE_FILES
-#  endif
-#  if !defined(_FILE_OFFSET_BITS) && \
-      !defined(@KWSYS_NAMESPACE at _LFS_NO_DEFINE_FILE_OFFSET_BITS)
-#   define _FILE_OFFSET_BITS 64
-#  endif
-#  if 0 && (defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS < 64)
-#   error "_FILE_OFFSET_BITS must be defined to at least 64"
-#  endif
-# endif
+/* Since LFS is requested this header must be included before system
+   headers whether or not LFS is available. */
+#if 0 && (defined(_SYS_TYPES_H) || defined(_SYS_TYPES_INCLUDED))
+#error "@KWSYS_NAMESPACE@/Configure.h must be included before sys/types.h"
+#endif
+/* Enable the large file API if it is available.  */
+#if @KWSYS_NAMESPACE at _LFS_AVAILABLE &&                                        \
+  !defined(@KWSYS_NAMESPACE at _LFS_NO_DEFINES)
+#if !defined(_LARGEFILE_SOURCE) &&                                            \
+  !defined(@KWSYS_NAMESPACE at _LFS_NO_DEFINE_LARGEFILE_SOURCE)
+#define _LARGEFILE_SOURCE
+#endif
+#if !defined(_LARGEFILE64_SOURCE) &&                                          \
+  !defined(@KWSYS_NAMESPACE at _LFS_NO_DEFINE_LARGEFILE64_SOURCE)
+#define _LARGEFILE64_SOURCE
+#endif
+#if !defined(_LARGE_FILES) &&                                                 \
+  !defined(@KWSYS_NAMESPACE at _LFS_NO_DEFINE_LARGE_FILES)
+#define _LARGE_FILES
+#endif
+#if !defined(_FILE_OFFSET_BITS) &&                                            \
+  !defined(@KWSYS_NAMESPACE at _LFS_NO_DEFINE_FILE_OFFSET_BITS)
+#define _FILE_OFFSET_BITS 64
+#endif
+#if 0 && (defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS < 64)
+#error "_FILE_OFFSET_BITS must be defined to at least 64"
+#endif
+#endif
 #endif
 
 /* Setup the export macro.  */
 #if @KWSYS_BUILD_SHARED@
-# if defined(_WIN32) || defined(__CYGWIN__)
-#  if defined(@KWSYS_NAMESPACE at _EXPORTS)
-#   define @KWSYS_NAMESPACE at _EXPORT __declspec(dllexport)
-#  else
-#   define @KWSYS_NAMESPACE at _EXPORT __declspec(dllimport)
-#  endif
-# elif __GNUC__ >= 4
-#  define @KWSYS_NAMESPACE at _EXPORT __attribute__ ((visibility("default")))
-# else
-#  define @KWSYS_NAMESPACE at _EXPORT
-# endif
+#if defined(_WIN32) || defined(__CYGWIN__)
+#if defined(@KWSYS_NAMESPACE at _EXPORTS)
+#define @KWSYS_NAMESPACE at _EXPORT __declspec(dllexport)
+#else
+#define @KWSYS_NAMESPACE at _EXPORT __declspec(dllimport)
+#endif
+#elif __GNUC__ >= 4
+#define @KWSYS_NAMESPACE at _EXPORT __attribute__((visibility("default")))
+#else
+#define @KWSYS_NAMESPACE at _EXPORT
+#endif
 #else
-# define @KWSYS_NAMESPACE at _EXPORT
+#define @KWSYS_NAMESPACE at _EXPORT
 #endif
 
 /* Enable warnings that are off by default but are useful.  */
 #if !defined(@KWSYS_NAMESPACE at _NO_WARNING_ENABLE)
-# if defined(_MSC_VER)
-#  pragma warning ( default : 4263 ) /* no override, call convention differs */
-# endif
+#if defined(_MSC_VER)
+#pragma warning(default : 4263) /* no override, call convention differs */
+#endif
 #endif
 
 /* Disable warnings that are on by default but occur in valid code.  */
 #if !defined(@KWSYS_NAMESPACE at _NO_WARNING_DISABLE)
-# if defined(_MSC_VER)
-#  pragma warning (disable: 4097) /* typedef is synonym for class */
-#  pragma warning (disable: 4127) /* conditional expression is constant */
-#  pragma warning (disable: 4244) /* possible loss in conversion */
-#  pragma warning (disable: 4251) /* missing DLL-interface */
-#  pragma warning (disable: 4305) /* truncation from type1 to type2 */
-#  pragma warning (disable: 4309) /* truncation of constant value */
-#  pragma warning (disable: 4514) /* unreferenced inline function */
-#  pragma warning (disable: 4706) /* assignment in conditional expression */
-#  pragma warning (disable: 4710) /* function not inlined */
-#  pragma warning (disable: 4786) /* identifier truncated in debug info */
-# endif
-# if defined(__BORLANDC__) && !defined(__cplusplus)
-   /* Code has no effect; raised by winnt.h in C (not C++) when ignoring an
-      unused parameter using "(param)" syntax (i.e. no cast to void).  */
-#  pragma warn -8019
-# endif
+#if defined(_MSC_VER)
+#pragma warning(disable : 4097) /* typedef is synonym for class */
+#pragma warning(disable : 4127) /* conditional expression is constant */
+#pragma warning(disable : 4244) /* possible loss in conversion */
+#pragma warning(disable : 4251) /* missing DLL-interface */
+#pragma warning(disable : 4305) /* truncation from type1 to type2 */
+#pragma warning(disable : 4309) /* truncation of constant value */
+#pragma warning(disable : 4514) /* unreferenced inline function */
+#pragma warning(disable : 4706) /* assignment in conditional expression */
+#pragma warning(disable : 4710) /* function not inlined */
+#pragma warning(disable : 4786) /* identifier truncated in debug info */
+#endif
+#if defined(__BORLANDC__) && !defined(__cplusplus)
+/* Code has no effect; raised by winnt.h in C (not C++) when ignoring an
+   unused parameter using "(param)" syntax (i.e. no cast to void).  */
+#pragma warn - 8019
+#endif
 #endif
 
 /* MSVC 6.0 in release mode will warn about code it produces with its
@@ -127,10 +118,10 @@
    configuration.  Real warnings will be revealed by a debug build or
    by other compilers.  */
 #if !defined(@KWSYS_NAMESPACE at _NO_WARNING_DISABLE_BOGUS)
-# if defined(_MSC_VER) && (_MSC_VER < 1300) && defined(NDEBUG)
-#  pragma warning ( disable : 4701 ) /* Variable may be used uninitialized.  */
-#  pragma warning ( disable : 4702 ) /* Unreachable code.  */
-# endif
+#if defined(_MSC_VER) && (_MSC_VER < 1300) && defined(NDEBUG)
+#pragma warning(disable : 4701) /* Variable may be used uninitialized.  */
+#pragma warning(disable : 4702) /* Unreachable code.  */
+#endif
 #endif
 
 #endif
diff --git a/Source/kwsys/Configure.hxx.in b/Source/kwsys/Configure.hxx.in
index 4ce680d..1c07a4e 100644
--- a/Source/kwsys/Configure.hxx.in
+++ b/Source/kwsys/Configure.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _Configure_hxx
 #define @KWSYS_NAMESPACE at _Configure_hxx
 
@@ -18,17 +9,19 @@
 /* Whether wstring is available.  */
 #define @KWSYS_NAMESPACE at _STL_HAS_WSTRING @KWSYS_STL_HAS_WSTRING@
 /* Whether <ext/stdio_filebuf.h> is available. */
-#define @KWSYS_NAMESPACE at _CXX_HAS_EXT_STDIO_FILEBUF_H @KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H@
+#define @KWSYS_NAMESPACE at _CXX_HAS_EXT_STDIO_FILEBUF_H                         \
+  @KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H@
 
 /* If building a C++ file in kwsys itself, give the source file
    access to the macros without a configured namespace.  */
 #if defined(KWSYS_NAMESPACE)
-# if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-#  define kwsys     @KWSYS_NAMESPACE@
-# endif
-# define KWSYS_NAME_IS_KWSYS               @KWSYS_NAMESPACE at _NAME_IS_KWSYS
-# define KWSYS_STL_HAS_WSTRING             @KWSYS_NAMESPACE at _STL_HAS_WSTRING
-# define KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H @KWSYS_NAMESPACE at _CXX_HAS_EXT_STDIO_FILEBUF_H
+#if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
+#define kwsys @KWSYS_NAMESPACE@
+#endif
+#define KWSYS_NAME_IS_KWSYS @KWSYS_NAMESPACE at _NAME_IS_KWSYS
+#define KWSYS_STL_HAS_WSTRING @KWSYS_NAMESPACE at _STL_HAS_WSTRING
+#define KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H                                     \
+  @KWSYS_NAMESPACE at _CXX_HAS_EXT_STDIO_FILEBUF_H
 #endif
 
 #endif
diff --git a/Source/kwsys/ConsoleBuf.hxx.in b/Source/kwsys/ConsoleBuf.hxx.in
index 8aeeda1..cb58865 100644
--- a/Source/kwsys/ConsoleBuf.hxx.in
+++ b/Source/kwsys/ConsoleBuf.hxx.in
@@ -1,346 +1,392 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  Copyright 2000-2016 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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _ConsoleBuf_hxx
 #define @KWSYS_NAMESPACE at _ConsoleBuf_hxx
 
 #include <@KWSYS_NAMESPACE@/Configure.hxx>
+
 #include <@KWSYS_NAMESPACE@/Encoding.hxx>
-#include <string>
+
 #include <cstring>
-#include <sstream>
-#include <streambuf>
 #include <iostream>
+#include <sstream>
 #include <stdexcept>
+#include <streambuf>
+#include <string>
 
 #if defined(_WIN32)
-#  include <windows.h>
-#  if __cplusplus >= 201103L
-#    include <system_error>
-#  endif
+#include <windows.h>
+#if __cplusplus >= 201103L
+#include <system_error>
+#endif
 #endif
 
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 #if defined(_WIN32)
 
-  template<class CharT, class Traits = std::char_traits<CharT> >
-  class @KWSYS_NAMESPACE at _EXPORT BasicConsoleBuf :
-      public std::basic_streambuf<CharT, Traits> {
-    public:
-      typedef typename Traits::int_type int_type;
-      typedef typename Traits::char_type char_type;
-
-      class Manager {
-        public:
-          Manager(std::basic_ios<CharT, Traits> &ios, const bool err = false)
-            : m_consolebuf(0)
-          {
-            m_ios = &ios;
-            try {
-              m_consolebuf = new BasicConsoleBuf<CharT, Traits>(err);
-              m_streambuf = m_ios->rdbuf(m_consolebuf);
-            } catch (const std::runtime_error& ex) {
-              std::cerr << "Failed to create ConsoleBuf!" << std::endl
-                        << ex.what() << std::endl;
-            };
-          }
-
-          ~Manager()
-          {
-            if (m_consolebuf) {
-              delete m_consolebuf;
-              m_ios->rdbuf(m_streambuf);
-            }
-          }
+template <class CharT, class Traits = std::char_traits<CharT> >
+class @KWSYS_NAMESPACE at _EXPORT BasicConsoleBuf
+  : public std::basic_streambuf<CharT, Traits>
+{
+public:
+  typedef typename Traits::int_type int_type;
+  typedef typename Traits::char_type char_type;
 
-        private:
-          std::basic_ios<CharT, Traits> *m_ios;
-          std::basic_streambuf<CharT, Traits> *m_streambuf;
-          BasicConsoleBuf<CharT, Traits> *m_consolebuf;
+  class Manager
+  {
+  public:
+    Manager(std::basic_ios<CharT, Traits>& ios, const bool err = false)
+      : m_consolebuf(0)
+    {
+      m_ios = &ios;
+      try {
+        m_consolebuf = new BasicConsoleBuf<CharT, Traits>(err);
+        m_streambuf = m_ios->rdbuf(m_consolebuf);
+      } catch (const std::runtime_error& ex) {
+        std::cerr << "Failed to create ConsoleBuf!" << std::endl
+                  << ex.what() << std::endl;
       };
+    }
 
-      BasicConsoleBuf(const bool err = false) :
-        flush_on_newline(true),
-        input_pipe_codepage(0),
-        output_pipe_codepage(0),
-        input_file_codepage(CP_UTF8),
-        output_file_codepage(CP_UTF8),
-        m_consolesCodepage(0)
-      {
-        m_hInput = ::GetStdHandle(STD_INPUT_HANDLE);
-        checkHandle(true, "STD_INPUT_HANDLE");
-        if (!setActiveInputCodepage()) {
-          throw std::runtime_error("setActiveInputCodepage failed!");
-        }
-        m_hOutput = err ? ::GetStdHandle(STD_ERROR_HANDLE) :
-                          ::GetStdHandle(STD_OUTPUT_HANDLE);
-        checkHandle(false, err ? "STD_ERROR_HANDLE" : "STD_OUTPUT_HANDLE");
-        if (!setActiveOutputCodepage()) {
-          throw std::runtime_error("setActiveOutputCodepage failed!");
-        }
-        _setg();
-        _setp();
-      }
+    BasicConsoleBuf<CharT, Traits>* GetConsoleBuf() { return m_consolebuf; }
 
-      ~BasicConsoleBuf() throw()
-      {
-        sync();
+    void SetUTF8Pipes()
+    {
+      if (m_consolebuf) {
+        m_consolebuf->input_pipe_codepage = CP_UTF8;
+        m_consolebuf->output_pipe_codepage = CP_UTF8;
+        m_consolebuf->activateCodepageChange();
       }
+    }
 
-      bool activateCodepageChange()
-      {
-        return setActiveInputCodepage() && setActiveOutputCodepage();
+    ~Manager()
+    {
+      if (m_consolebuf) {
+        delete m_consolebuf;
+        m_ios->rdbuf(m_streambuf);
       }
+    }
 
-    protected:
-      virtual int sync() {
-        bool success = true;
-        if (m_hInput && m_isConsoleInput &&
-            ::FlushConsoleInputBuffer(m_hInput) == 0) {
-          success = false;
-        }
-        if (m_hOutput && !m_obuffer.empty()) {
-          const std::wstring wbuffer = getBuffer(m_obuffer);
-          if (m_isConsoleOutput) {
-            DWORD charsWritten;
-            success = ::WriteConsoleW(m_hOutput, wbuffer.c_str(),
-                                      (DWORD)wbuffer.size(), &charsWritten,
-                                      NULL) == 0 ? false : true;
-          } else {
-            DWORD bytesWritten;
-            std::string buffer;
-            success = encodeOutputBuffer(wbuffer, buffer);
-            if (success) {
-              success = ::WriteFile(m_hOutput, buffer.c_str(),
-                                    (DWORD)buffer.size(), &bytesWritten,
-                                     NULL) == 0 ? false : true;
-            }
-          }
+  private:
+    std::basic_ios<CharT, Traits>* m_ios;
+    std::basic_streambuf<CharT, Traits>* m_streambuf;
+    BasicConsoleBuf<CharT, Traits>* m_consolebuf;
+  };
+
+  BasicConsoleBuf(const bool err = false)
+    : flush_on_newline(true)
+    , input_pipe_codepage(0)
+    , output_pipe_codepage(0)
+    , input_file_codepage(CP_UTF8)
+    , output_file_codepage(CP_UTF8)
+    , m_consolesCodepage(0)
+  {
+    m_hInput = ::GetStdHandle(STD_INPUT_HANDLE);
+    checkHandle(true, "STD_INPUT_HANDLE");
+    if (!setActiveInputCodepage()) {
+      throw std::runtime_error("setActiveInputCodepage failed!");
+    }
+    m_hOutput = err ? ::GetStdHandle(STD_ERROR_HANDLE)
+                    : ::GetStdHandle(STD_OUTPUT_HANDLE);
+    checkHandle(false, err ? "STD_ERROR_HANDLE" : "STD_OUTPUT_HANDLE");
+    if (!setActiveOutputCodepage()) {
+      throw std::runtime_error("setActiveOutputCodepage failed!");
+    }
+    _setg();
+    _setp();
+  }
+
+  ~BasicConsoleBuf() throw() { sync(); }
+
+  bool activateCodepageChange()
+  {
+    return setActiveInputCodepage() && setActiveOutputCodepage();
+  }
+
+protected:
+  virtual int sync()
+  {
+    bool success = true;
+    if (m_hInput && m_isConsoleInput &&
+        ::FlushConsoleInputBuffer(m_hInput) == 0) {
+      success = false;
+    }
+    if (m_hOutput && !m_obuffer.empty()) {
+      const std::wstring wbuffer = getBuffer(m_obuffer);
+      if (m_isConsoleOutput) {
+        DWORD charsWritten;
+        success =
+          ::WriteConsoleW(m_hOutput, wbuffer.c_str(), (DWORD)wbuffer.size(),
+                          &charsWritten, NULL) == 0
+          ? false
+          : true;
+      } else {
+        DWORD bytesWritten;
+        std::string buffer;
+        success = encodeOutputBuffer(wbuffer, buffer);
+        if (success) {
+          success = ::WriteFile(m_hOutput, buffer.c_str(),
+                                (DWORD)buffer.size(), &bytesWritten, NULL) == 0
+            ? false
+            : true;
         }
-        m_ibuffer.clear();
-        m_obuffer.clear();
-        _setg();
-        _setp();
-        return success ? 0 : -1;
       }
+    }
+    m_ibuffer.clear();
+    m_obuffer.clear();
+    _setg();
+    _setp();
+    return success ? 0 : -1;
+  }
 
-      virtual int_type underflow() {
-        if (this->gptr() >= this->egptr()) {
-          if (!m_hInput) {
-            _setg(true);
-            return Traits::eof();
-          }
-          if (m_isConsoleInput) {
-            wchar_t wbuffer[128];
-            DWORD charsRead;
-            if (::ReadConsoleW(m_hInput, wbuffer, (sizeof(wbuffer) / sizeof(wbuffer[0])) - 1,
-                               &charsRead, NULL) == 0 || charsRead == 0) {
-              _setg(true);
-              return Traits::eof();
-            }
-            wbuffer[charsRead] = L'\0';
-            setBuffer(wbuffer, m_ibuffer);
-          } else {
-            std::wstring totalBuffer;
-            std::wstring wbuffer;
-            char buffer[128];
-            DWORD bytesRead;
-            while (::ReadFile(m_hInput, buffer, (sizeof(buffer) / sizeof(buffer[0])) - 1,
-                              &bytesRead, NULL) == 0) {
-              if (::GetLastError() == ERROR_MORE_DATA) {
-                buffer[bytesRead] = '\0';
-                if (decodeInputBuffer(buffer, wbuffer)) {
-                  totalBuffer += wbuffer;
-                  continue;
-                }
-              }
-              _setg(true);
-              return Traits::eof();
-            }
-            buffer[bytesRead] = '\0';
-            if (!decodeInputBuffer(buffer, wbuffer)) {
-              _setg(true);
-              return Traits::eof();
-            }
-            totalBuffer += wbuffer;
-            setBuffer(totalBuffer, m_ibuffer);
+  virtual int_type underflow()
+  {
+    if (this->gptr() >= this->egptr()) {
+      if (!m_hInput) {
+        _setg(true);
+        return Traits::eof();
+      }
+      if (m_isConsoleInput) {
+        // ReadConsole doesn't tell if there's more input available
+        // don't support reading more characters than this
+        wchar_t wbuffer[8192];
+        DWORD charsRead;
+        if (ReadConsoleW(m_hInput, wbuffer,
+                         (sizeof(wbuffer) / sizeof(wbuffer[0])), &charsRead,
+                         NULL) == 0 ||
+            charsRead == 0) {
+          _setg(true);
+          return Traits::eof();
+        }
+        setBuffer(std::wstring(wbuffer, charsRead), m_ibuffer);
+      } else {
+        std::wstring wbuffer;
+        std::string strbuffer;
+        DWORD bytesRead;
+        LARGE_INTEGER size;
+        if (GetFileSizeEx(m_hInput, &size) == 0) {
+          _setg(true);
+          return Traits::eof();
+        }
+        char* buffer = new char[size.LowPart];
+        while (ReadFile(m_hInput, buffer, size.LowPart, &bytesRead, NULL) ==
+               0) {
+          if (GetLastError() == ERROR_MORE_DATA) {
+            strbuffer += std::string(buffer, bytesRead);
+            continue;
           }
-          _setg();
+          _setg(true);
+          delete[] buffer;
+          return Traits::eof();
+        }
+        if (bytesRead > 0) {
+          strbuffer += std::string(buffer, bytesRead);
+        }
+        delete[] buffer;
+        if (!decodeInputBuffer(strbuffer, wbuffer)) {
+          _setg(true);
+          return Traits::eof();
         }
-        return Traits::to_int_type(*this->gptr());
+        setBuffer(wbuffer, m_ibuffer);
       }
+      _setg();
+    }
+    return Traits::to_int_type(*this->gptr());
+  }
 
-      virtual int_type overflow(int_type ch = Traits::eof()) {
-        if (!Traits::eq_int_type(ch, Traits::eof())) {
-          char_type chr = Traits::to_char_type(ch);
-          m_obuffer += chr;
-          if ((flush_on_newline && Traits::eq(chr, '\n')) ||
-              Traits::eq_int_type(ch, 0x00)) {
-            sync();
-          }
-          return ch;
-        }
+  virtual int_type overflow(int_type ch = Traits::eof())
+  {
+    if (!Traits::eq_int_type(ch, Traits::eof())) {
+      char_type chr = Traits::to_char_type(ch);
+      m_obuffer += chr;
+      if ((flush_on_newline && Traits::eq(chr, '\n')) ||
+          Traits::eq_int_type(ch, 0x00)) {
         sync();
-        return Traits::eof();
       }
+      return ch;
+    }
+    sync();
+    return Traits::eof();
+  }
 
-    public:
-      bool flush_on_newline;
-      UINT input_pipe_codepage;
-      UINT output_pipe_codepage;
-      UINT input_file_codepage;
-      UINT output_file_codepage;
+public:
+  bool flush_on_newline;
+  UINT input_pipe_codepage;
+  UINT output_pipe_codepage;
+  UINT input_file_codepage;
+  UINT output_file_codepage;
 
-    private:
-      HANDLE m_hInput;
-      HANDLE m_hOutput;
-      std::basic_string<char_type> m_ibuffer;
-      std::basic_string<char_type> m_obuffer;
-      bool m_isConsoleInput;
-      bool m_isConsoleOutput;
-      UINT m_activeInputCodepage;
-      UINT m_activeOutputCodepage;
-      UINT m_consolesCodepage;
-      void checkHandle(bool input, std::string handleName) {
-        if ((input && m_hInput == INVALID_HANDLE_VALUE) ||
-            (!input && m_hOutput == INVALID_HANDLE_VALUE)) {
-          std::string errmsg = "GetStdHandle(" + handleName +
-                               ") returned INVALID_HANDLE_VALUE";
+private:
+  HANDLE m_hInput;
+  HANDLE m_hOutput;
+  std::basic_string<char_type> m_ibuffer;
+  std::basic_string<char_type> m_obuffer;
+  bool m_isConsoleInput;
+  bool m_isConsoleOutput;
+  UINT m_activeInputCodepage;
+  UINT m_activeOutputCodepage;
+  UINT m_consolesCodepage;
+  void checkHandle(bool input, std::string handleName)
+  {
+    if ((input && m_hInput == INVALID_HANDLE_VALUE) ||
+        (!input && m_hOutput == INVALID_HANDLE_VALUE)) {
+      std::string errmsg =
+        "GetStdHandle(" + handleName + ") returned INVALID_HANDLE_VALUE";
 #if __cplusplus >= 201103L
-          throw std::system_error(::GetLastError(),
-                                  std::system_category(), errmsg);
+      throw std::system_error(::GetLastError(), std::system_category(),
+                              errmsg);
 #else
-          throw std::runtime_error(errmsg);
+      throw std::runtime_error(errmsg);
 #endif
-        }
-      }
-      UINT getConsolesCodepage() {
-        if (!m_consolesCodepage) {
-          m_consolesCodepage = GetConsoleCP();
-          if (!m_consolesCodepage) {
-            m_consolesCodepage = GetACP();
-          }
-        }
-        return m_consolesCodepage;
+    }
+  }
+  UINT getConsolesCodepage()
+  {
+    if (!m_consolesCodepage) {
+      m_consolesCodepage = GetConsoleCP();
+      if (!m_consolesCodepage) {
+        m_consolesCodepage = GetACP();
       }
-      bool setActiveInputCodepage() {
-        m_isConsoleInput = false;
-        switch (GetFileType(m_hInput)) {
-          case FILE_TYPE_DISK:
-            m_activeInputCodepage = input_file_codepage;
-            break;
-          case FILE_TYPE_CHAR:
-            m_isConsoleInput = true;
-            break;
-          case FILE_TYPE_PIPE:
-            m_activeInputCodepage = input_pipe_codepage;
-            break;
-          default:
-            return false;
+    }
+    return m_consolesCodepage;
+  }
+  bool setActiveInputCodepage()
+  {
+    m_isConsoleInput = false;
+    switch (GetFileType(m_hInput)) {
+      case FILE_TYPE_DISK:
+        m_activeInputCodepage = input_file_codepage;
+        break;
+      case FILE_TYPE_CHAR:
+        // Check for actual console.
+        DWORD consoleMode;
+        m_isConsoleInput =
+          GetConsoleMode(m_hInput, &consoleMode) == 0 ? false : true;
+        if (m_isConsoleInput) {
+          break;
         }
-        if (!m_isConsoleInput && m_activeInputCodepage == 0) {
-          m_activeInputCodepage = getConsolesCodepage();
+      case FILE_TYPE_PIPE:
+        m_activeInputCodepage = input_pipe_codepage;
+        break;
+      default:
+        return false;
+    }
+    if (!m_isConsoleInput && m_activeInputCodepage == 0) {
+      m_activeInputCodepage = getConsolesCodepage();
+    }
+    return true;
+  }
+  bool setActiveOutputCodepage()
+  {
+    m_isConsoleOutput = false;
+    switch (GetFileType(m_hOutput)) {
+      case FILE_TYPE_DISK:
+        m_activeOutputCodepage = output_file_codepage;
+        break;
+      case FILE_TYPE_CHAR:
+        // Check for actual console.
+        DWORD consoleMode;
+        m_isConsoleOutput =
+          GetConsoleMode(m_hOutput, &consoleMode) == 0 ? false : true;
+        if (m_isConsoleOutput) {
+          break;
         }
-        return true;
-      }
-      bool setActiveOutputCodepage() {
-        m_isConsoleOutput = false;
-        switch (GetFileType(m_hOutput)) {
-          case FILE_TYPE_DISK:
-            m_activeOutputCodepage = output_file_codepage;
-            break;
-          case FILE_TYPE_CHAR:
-            m_isConsoleOutput = true;
-            break;
-          case FILE_TYPE_PIPE:
-            m_activeOutputCodepage = output_pipe_codepage;
-            break;
-          default:
-            return false;
-        }
-        if (!m_isConsoleOutput && m_activeOutputCodepage == 0) {
-           m_activeOutputCodepage = getConsolesCodepage();
-        }
-        return true;
-      }
-      void _setg(bool empty = false) {
-        if (!empty) {
-          this->setg((char_type *)m_ibuffer.data(),
-                     (char_type *)m_ibuffer.data(),
-                     (char_type *)m_ibuffer.data() + m_ibuffer.size());
-        } else {
-          this->setg((char_type *)m_ibuffer.data(),
-                     (char_type *)m_ibuffer.data() + m_ibuffer.size(),
-                     (char_type *)m_ibuffer.data() + m_ibuffer.size());
-        }
-      }
-      void _setp() {
-        this->setp((char_type *)m_obuffer.data(),
-                   (char_type *)m_obuffer.data() + m_obuffer.size());
-      }
-      bool encodeOutputBuffer(const std::wstring wbuffer,
-                              std::string &buffer) {
-        const int length = WideCharToMultiByte(m_activeOutputCodepage, 0,
-                                               wbuffer.c_str(),
-                                               (int)wbuffer.size(), NULL, 0,
-                                               NULL, NULL);
-        char *buf = new char[length + 1];
-        const bool success = WideCharToMultiByte(m_activeOutputCodepage, 0,
-                                                 wbuffer.c_str(),
-                                                 (int)wbuffer.size(), buf,
-                                                 length, NULL, NULL) > 0
-                             ? true : false;
-        buf[length] = '\0';
-        buffer = buf;
-        delete[] buf;
-        return success;
-      }
-      bool decodeInputBuffer(const char *buffer, std::wstring &wbuffer) {
-        int actualCodepage = m_activeInputCodepage;
-        const char BOM_UTF8[] = { char(0xEF), char(0xBB), char(0xBF) };
-        if (std::memcmp(buffer, BOM_UTF8, sizeof(BOM_UTF8)) == 0) {
-          // PowerShell uses UTF-8 with BOM for pipes
-          actualCodepage = CP_UTF8;
-          buffer += sizeof(BOM_UTF8);
-        }
-        const int wlength = MultiByteToWideChar(actualCodepage, 0, buffer,
-                                                -1, NULL, 0);
-        wchar_t *wbuf = new wchar_t[wlength];
-        const bool success = MultiByteToWideChar(actualCodepage, 0, buffer,
-                                                 -1, wbuf, wlength) > 0
-                             ? true : false;
-        wbuffer = wbuf;
-        delete[] wbuf;
-        return success;
-      }
-      std::wstring getBuffer(const std::basic_string<char> buffer) {
-        return Encoding::ToWide(buffer);
-      }
-      std::wstring getBuffer(const std::basic_string<wchar_t> buffer) {
-        return buffer;
-      }
-      void setBuffer(const std::wstring wbuffer,
-                     std::basic_string<char> &target) {
-        target = Encoding::ToNarrow(wbuffer);
-      }
-      void setBuffer(const std::wstring wbuffer,
-                     std::basic_string<wchar_t> &target) {
-        target = wbuffer;
-      }
+      case FILE_TYPE_PIPE:
+        m_activeOutputCodepage = output_pipe_codepage;
+        break;
+      default:
+        return false;
+    }
+    if (!m_isConsoleOutput && m_activeOutputCodepage == 0) {
+      m_activeOutputCodepage = getConsolesCodepage();
+    }
+    return true;
+  }
+  void _setg(bool empty = false)
+  {
+    if (!empty) {
+      this->setg((char_type*)m_ibuffer.data(), (char_type*)m_ibuffer.data(),
+                 (char_type*)m_ibuffer.data() + m_ibuffer.size());
+    } else {
+      this->setg((char_type*)m_ibuffer.data(),
+                 (char_type*)m_ibuffer.data() + m_ibuffer.size(),
+                 (char_type*)m_ibuffer.data() + m_ibuffer.size());
+    }
+  }
+  void _setp()
+  {
+    this->setp((char_type*)m_obuffer.data(),
+               (char_type*)m_obuffer.data() + m_obuffer.size());
+  }
+  bool encodeOutputBuffer(const std::wstring wbuffer, std::string& buffer)
+  {
+    if (wbuffer.size() == 0) {
+      buffer = std::string();
+      return true;
+    }
+    const int length =
+      WideCharToMultiByte(m_activeOutputCodepage, 0, wbuffer.c_str(),
+                          (int)wbuffer.size(), NULL, 0, NULL, NULL);
+    char* buf = new char[length];
+    const bool success =
+      WideCharToMultiByte(m_activeOutputCodepage, 0, wbuffer.c_str(),
+                          (int)wbuffer.size(), buf, length, NULL, NULL) > 0
+      ? true
+      : false;
+    buffer = std::string(buf, length);
+    delete[] buf;
+    return success;
+  }
+  bool decodeInputBuffer(const std::string buffer, std::wstring& wbuffer)
+  {
+    int length = int(buffer.length());
+    if (length == 0) {
+      wbuffer = std::wstring();
+      return true;
+    }
+    int actualCodepage = m_activeInputCodepage;
+    const char BOM_UTF8[] = { char(0xEF), char(0xBB), char(0xBF) };
+    const char* data = buffer.data();
+    const size_t BOMsize = sizeof(BOM_UTF8);
+    if (length >= BOMsize && std::memcmp(data, BOM_UTF8, BOMsize) == 0) {
+      // PowerShell uses UTF-8 with BOM for pipes
+      actualCodepage = CP_UTF8;
+      data += BOMsize;
+      length -= BOMsize;
+    }
+    const int wlength =
+      MultiByteToWideChar(actualCodepage, 0, data, length, NULL, 0);
+    wchar_t* wbuf = new wchar_t[wlength];
+    const bool success =
+      MultiByteToWideChar(actualCodepage, 0, data, length, wbuf, wlength) > 0
+      ? true
+      : false;
+    wbuffer = std::wstring(wbuf, wlength);
+    delete[] wbuf;
+    return success;
+  }
+  std::wstring getBuffer(const std::basic_string<char> buffer)
+  {
+    return Encoding::ToWide(buffer);
+  }
+  std::wstring getBuffer(const std::basic_string<wchar_t> buffer)
+  {
+    return buffer;
+  }
+  void setBuffer(const std::wstring wbuffer, std::basic_string<char>& target)
+  {
+    target = Encoding::ToNarrow(wbuffer);
+  }
+  void setBuffer(const std::wstring wbuffer,
+                 std::basic_string<wchar_t>& target)
+  {
+    target = wbuffer;
+  }
 
-  }; // BasicConsoleBuf class
+}; // BasicConsoleBuf class
 
-  typedef BasicConsoleBuf<char>    ConsoleBuf;
-  typedef BasicConsoleBuf<wchar_t> WConsoleBuf;
+typedef BasicConsoleBuf<char> ConsoleBuf;
+typedef BasicConsoleBuf<wchar_t> WConsoleBuf;
 
 #endif
 } // KWSYS_NAMESPACE
diff --git a/Source/kwsys/Copyright.txt b/Source/kwsys/Copyright.txt
index 1549a7d..33d7fb4 100644
--- a/Source/kwsys/Copyright.txt
+++ b/Source/kwsys/Copyright.txt
@@ -1,5 +1,5 @@
 KWSys - Kitware System Library
-Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+Copyright 2000-2016 Kitware, Inc. and Contributors
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
@@ -13,10 +13,9 @@ are met:
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
 
-* Neither the names of Kitware, Inc., the Insight Software Consortium,
-  nor the names of their contributors may be used to endorse or promote
-  products derived from this software without specific prior written
-  permission.
+* Neither the name of Kitware, Inc. nor the names of Contributors
+  may be used to endorse or promote products derived from this
+  software without specific prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -29,3 +28,11 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------------------------------------------------------------------------------
+
+The following individuals and institutions are among the Contributors:
+
+* Insight Software Consortium <insightsoftwareconsortium.org>
+
+See version control history for details of individual contributions.
diff --git a/Source/kwsys/Directory.cxx b/Source/kwsys/Directory.cxx
index 15480e1..3c31b49 100644
--- a/Source/kwsys/Directory.cxx
+++ b/Source/kwsys/Directory.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(Directory.hxx)
 
@@ -19,16 +10,15 @@
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "Directory.hxx.in"
-# include "Configure.hxx.in"
-# include "Encoding.hxx.in"
+#include "Configure.hxx.in"
+#include "Directory.hxx.in"
+#include "Encoding.hxx.in"
 #endif
 
 #include <string>
 #include <vector>
 
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
 
 //----------------------------------------------------------------------------
 class DirectoryInternals
@@ -62,10 +52,9 @@ unsigned long Directory::GetNumberOfFiles() const
 //----------------------------------------------------------------------------
 const char* Directory::GetFile(unsigned long dindex) const
 {
-  if ( dindex >= this->Internal->Files.size() )
-    {
+  if (dindex >= this->Internal->Files.size()) {
     return 0;
-    }
+  }
   return this->Internal->Files[dindex].c_str();
 }
 
@@ -88,9 +77,10 @@ void Directory::Clear()
 
 #if defined(_WIN32) && !defined(__CYGWIN__)
 #include <windows.h>
-#include <io.h>
+
 #include <ctype.h>
 #include <fcntl.h>
+#include <io.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -99,15 +89,14 @@ void Directory::Clear()
 
 // Wide function names can vary depending on compiler:
 #ifdef __BORLANDC__
-# define _wfindfirst_func __wfindfirst
-# define _wfindnext_func __wfindnext
+#define _wfindfirst_func __wfindfirst
+#define _wfindnext_func __wfindnext
 #else
-# define _wfindfirst_func _wfindfirst
-# define _wfindnext_func _wfindnext
+#define _wfindfirst_func _wfindfirst
+#define _wfindnext_func _wfindnext
 #endif
 
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
 
 bool Directory::Load(const std::string& name)
 {
@@ -120,42 +109,34 @@ bool Directory::Load(const std::string& name)
 #endif
   char* buf;
   size_t n = name.size();
-  if ( *name.rbegin() == '/' || *name.rbegin() == '\\' )
-    {
+  if (*name.rbegin() == '/' || *name.rbegin() == '\\') {
     buf = new char[n + 1 + 1];
     sprintf(buf, "%s*", name.c_str());
-    }
-  else
-    {
+  } else {
     // Make sure the slashes in the wildcard suffix are consistent with the
     // rest of the path
     buf = new char[n + 2 + 1];
-    if ( name.find('\\') != name.npos )
-      {
+    if (name.find('\\') != name.npos) {
       sprintf(buf, "%s\\*", name.c_str());
-      }
-    else
-      {
+    } else {
       sprintf(buf, "%s/*", name.c_str());
-      }
     }
-  struct _wfinddata_t data;      // data of current file
+  }
+  struct _wfinddata_t data; // data of current file
 
   // Now put them into the file array
-  srchHandle = _wfindfirst_func((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
-  delete [] buf;
+  srchHandle =
+    _wfindfirst_func((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
+  delete[] buf;
 
-  if ( srchHandle == -1 )
-    {
+  if (srchHandle == -1) {
     return 0;
-    }
+  }
 
   // Loop through names
-  do
-    {
+  do {
     this->Internal->Files.push_back(Encoding::ToNarrow(data.name));
-    }
-  while ( _wfindnext_func(srchHandle, &data) != -1 );
+  } while (_wfindnext_func(srchHandle, &data) != -1);
   this->Internal->Path = name;
   return _findclose(srchHandle) != -1;
 }
@@ -170,34 +151,29 @@ unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name)
 #endif
   char* buf;
   size_t n = name.size();
-  if ( *name.rbegin() == '/' )
-    {
+  if (*name.rbegin() == '/') {
     buf = new char[n + 1 + 1];
     sprintf(buf, "%s*", name.c_str());
-    }
-  else
-    {
+  } else {
     buf = new char[n + 2 + 1];
     sprintf(buf, "%s/*", name.c_str());
-    }
-  struct _wfinddata_t data;      // data of current file
+  }
+  struct _wfinddata_t data; // data of current file
 
   // Now put them into the file array
-  srchHandle = _wfindfirst_func((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
-  delete [] buf;
+  srchHandle =
+    _wfindfirst_func((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
+  delete[] buf;
 
-  if ( srchHandle == -1 )
-    {
+  if (srchHandle == -1) {
     return 0;
-    }
+  }
 
   // Loop through names
   unsigned long count = 0;
-  do
-    {
+  do {
     count++;
-    }
-  while ( _wfindnext_func(srchHandle, &data) != -1 );
+  } while (_wfindnext_func(srchHandle, &data) != -1);
   _findclose(srchHandle);
   return count;
 }
@@ -209,6 +185,7 @@ unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name)
 // Now the POSIX style directory access
 
 #include <sys/types.h>
+
 #include <dirent.h>
 
 // PGI with glibc has trouble with dirent and large file support:
@@ -216,33 +193,30 @@ unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name)
 //  p=1992&sid=f16167f51964f1a68fe5041b8eb213b6
 // Work around the problem by mapping dirent the same way as readdir.
 #if defined(__PGI) && defined(__GLIBC__)
-# define kwsys_dirent_readdir dirent
-# define kwsys_dirent_readdir64 dirent64
-# define kwsys_dirent kwsys_dirent_lookup(readdir)
-# define kwsys_dirent_lookup(x) kwsys_dirent_lookup_delay(x)
-# define kwsys_dirent_lookup_delay(x) kwsys_dirent_##x
+#define kwsys_dirent_readdir dirent
+#define kwsys_dirent_readdir64 dirent64
+#define kwsys_dirent kwsys_dirent_lookup(readdir)
+#define kwsys_dirent_lookup(x) kwsys_dirent_lookup_delay(x)
+#define kwsys_dirent_lookup_delay(x) kwsys_dirent_##x
 #else
-# define kwsys_dirent dirent
+#define kwsys_dirent dirent
 #endif
 
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
 
 bool Directory::Load(const std::string& name)
 {
   this->Clear();
-   
+
   DIR* dir = opendir(name.c_str());
 
-  if (!dir)
-    {
+  if (!dir) {
     return 0;
-    }
+  }
 
-  for (kwsys_dirent* d = readdir(dir); d; d = readdir(dir) )
-    {
+  for (kwsys_dirent* d = readdir(dir); d; d = readdir(dir)) {
     this->Internal->Files.push_back(d->d_name);
-    }
+  }
   this->Internal->Path = name;
   closedir(dir);
   return 1;
@@ -252,16 +226,14 @@ unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name)
 {
   DIR* dir = opendir(name.c_str());
 
-  if (!dir)
-    {
+  if (!dir) {
     return 0;
-    }
+  }
 
   unsigned long count = 0;
-  for (kwsys_dirent* d = readdir(dir); d; d = readdir(dir) )
-    {
+  for (kwsys_dirent* d = readdir(dir); d; d = readdir(dir)) {
     count++;
-    }
+  }
   closedir(dir);
   return count;
 }
diff --git a/Source/kwsys/Directory.hxx.in b/Source/kwsys/Directory.hxx.in
index e68f337..ad8c51b 100644
--- a/Source/kwsys/Directory.hxx.in
+++ b/Source/kwsys/Directory.hxx.in
@@ -1,22 +1,13 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _Directory_hxx
 #define @KWSYS_NAMESPACE at _Directory_hxx
 
 #include <@KWSYS_NAMESPACE@/Configure.h>
+
 #include <string>
 
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 
 class DirectoryInternals;
 
@@ -72,9 +63,9 @@ private:
   // Private implementation details.
   DirectoryInternals* Internal;
 
-  Directory(const Directory&);  // Not implemented.
-  void operator=(const Directory&);  // Not implemented.
-}; // End Class: Directory
+  Directory(const Directory&);      // Not implemented.
+  void operator=(const Directory&); // Not implemented.
+};                                  // End Class: Directory
 
 } // namespace @KWSYS_NAMESPACE@
 
diff --git a/Source/kwsys/DynamicLoader.cxx b/Source/kwsys/DynamicLoader.cxx
index 1941d96..e494db6 100644
--- a/Source/kwsys/DynamicLoader.cxx
+++ b/Source/kwsys/DynamicLoader.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(DynamicLoader.hxx)
 
@@ -17,30 +8,73 @@
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "DynamicLoader.hxx.in"
-# include "Configure.hxx.in"
+#include "Configure.hxx.in"
+#include "DynamicLoader.hxx.in"
 #endif
 
-// This file is actually 3 different implementations.
-// 1. HP machines which uses shl_load
-// 2. Mac OS X 10.2.x and earlier which uses NSLinkModule
-// 3. Windows which uses LoadLibrary
-// 4. Most unix systems (including Mac OS X 10.3 and later) which use dlopen
-// (default) Each part of the ifdef contains a complete implementation for
+// This file actually contains several different implementations:
+// * NOOP for environments without dynamic libs
+// * HP machines which uses shl_load
+// * Mac OS X 10.2.x and earlier which uses NSLinkModule
+// * Windows which uses LoadLibrary
+// * BeOS / Haiku
+// * FreeMiNT for Atari
+// * Default implementation for *NIX systems (including Mac OS X 10.3 and
+//   later) which use dlopen
+//
+// Each part of the ifdef contains a complete implementation for
 // the static methods of DynamicLoader.
 
-// ---------------------------------------------------------------
-// 1. Implementation for HPUX  machines
-#ifdef __hpux
-#include <errno.h>
-#include <dl.h>
-#define DYNAMICLOADER_DEFINED 1
+#if !KWSYS_SUPPORTS_SHARED_LIBS
+//----------------------------------------------------------------------------
+// Implementation for environments without dynamic libs
+#include <string.h> // for strerror()
+
+namespace KWSYS_NAMESPACE {
+
+//----------------------------------------------------------------------------
+DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(
+  const std::string& libname)
+{
+  return 0;
+}
+
+//----------------------------------------------------------------------------
+int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
+{
+  if (!lib) {
+    return 0;
+  }
+
+  return 1;
+}
 
-namespace KWSYS_NAMESPACE
+//----------------------------------------------------------------------------
+DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
+  DynamicLoader::LibraryHandle lib, const std::string& sym)
 {
+  return 0;
+}
 
 //----------------------------------------------------------------------------
-DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libname )
+const char* DynamicLoader::LastError()
+{
+  return "General error";
+}
+
+} // namespace KWSYS_NAMESPACE
+
+#elif defined(__hpux)
+//----------------------------------------------------------------------------
+// Implementation for HPUX  machines
+#include <dl.h>
+#include <errno.h>
+
+namespace KWSYS_NAMESPACE {
+
+//----------------------------------------------------------------------------
+DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(
+  const std::string& libname)
 {
   return shl_load(libname.c_str(), BIND_DEFERRED | DYNAMIC_PATH, 0L);
 }
@@ -48,25 +82,25 @@ DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libna
 //----------------------------------------------------------------------------
 int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
 {
-  if (!lib)
-    {
+  if (!lib) {
     return 0;
-    }
+  }
   return !shl_unload(lib);
 }
 
 //----------------------------------------------------------------------------
-DynamicLoader::SymbolPointer
-DynamicLoader::GetSymbolAddress(DynamicLoader::LibraryHandle lib, const std::string& sym)
+DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
+  DynamicLoader::LibraryHandle lib, const std::string& sym)
 {
   void* addr;
   int status;
 
   /* TYPE_PROCEDURE Look for a function or procedure. (This used to be default)
-   * TYPE_DATA      Look for a symbol in the data segment (for example, variables).
+   * TYPE_DATA      Look for a symbol in the data segment (for example,
+   * variables).
    * TYPE_UNDEFINED Look for any symbol.
    */
-  status = shl_findsym (&lib, sym.c_str(), TYPE_UNDEFINED, &addr);
+  status = shl_findsym(&lib, sym.c_str(), TYPE_UNDEFINED, &addr);
   void* result = (status < 0) ? (void*)0 : addr;
 
   // Hack to cast pointer-to-data to pointer-to-function.
@@ -88,52 +122,44 @@ const char* DynamicLoader::LastError()
    * The specified handle is invalid.
    */
 
-  if(  errno == ENOEXEC
-    || errno == ENOSYM
-    || errno == EINVAL )
-    {
+  if (errno == ENOEXEC || errno == ENOSYM || errno == EINVAL) {
     return strerror(errno);
-    }
+  }
   // else
   return 0;
 }
 
 } // namespace KWSYS_NAMESPACE
 
-#endif //__hpux
-
-
-// ---------------------------------------------------------------
-// 2. Implementation for Mac OS X 10.2.x and earlier
-#ifdef __APPLE__
-#if MAC_OS_X_VERSION_MAX_ALLOWED < 1030
-#include <string.h> // for strlen
+#elif defined(__APPLE__) && (MAC_OS_X_VERSION_MAX_ALLOWED < 1030)
+//----------------------------------------------------------------------------
+// Implementation for Mac OS X 10.2.x and earlier
 #include <mach-o/dyld.h>
-#define DYNAMICLOADER_DEFINED 1
+#include <string.h> // for strlen
 
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
 
 //----------------------------------------------------------------------------
-DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libname )
+DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(
+  const std::string& libname)
 {
   NSObjectFileImageReturnCode rc;
   NSObjectFileImage image = 0;
 
   rc = NSCreateObjectFileImageFromFile(libname.c_str(), &image);
   // rc == NSObjectFileImageInappropriateFile when trying to load a dylib file
-  if( rc != NSObjectFileImageSuccess )
-    {
+  if (rc != NSObjectFileImageSuccess) {
     return 0;
-    }
-  NSModule handle = NSLinkModule(image, libname.c_str(),
-    NSLINKMODULE_OPTION_BINDNOW|NSLINKMODULE_OPTION_RETURN_ON_ERROR);
+  }
+  NSModule handle =
+    NSLinkModule(image, libname.c_str(), NSLINKMODULE_OPTION_BINDNOW |
+                   NSLINKMODULE_OPTION_RETURN_ON_ERROR);
   NSDestroyObjectFileImage(image);
   return handle;
 }
 
 //----------------------------------------------------------------------------
-int DynamicLoader::CloseLibrary( DynamicLoader::LibraryHandle lib)
+int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
 {
   // NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED
   // With  this  option  the memory for the module is not deallocated
@@ -148,18 +174,17 @@ int DynamicLoader::CloseLibrary( DynamicLoader::LibraryHandle lib)
 DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
   DynamicLoader::LibraryHandle lib, const std::string& sym)
 {
-  void *result=0;
+  void* result = 0;
   // Need to prepend symbols with '_' on Apple-gcc compilers
   size_t len = sym.size();
-  char *rsym = new char[len + 1 + 1];
+  char* rsym = new char[len + 1 + 1];
   strcpy(rsym, "_");
-  strcat(rsym+1, sym.c_str());
+  strcat(rsym + 1, sym.c_str());
 
   NSSymbol symbol = NSLookupSymbolInModule(lib, rsym);
-  if(symbol)
-    {
+  if (symbol) {
     result = NSAddressOfSymbol(symbol);
-    }
+  }
 
   delete[] rsym;
   // Hack to cast pointer-to-data to pointer-to-function.
@@ -174,28 +199,24 @@ const char* DynamicLoader::LastError()
 
 } // namespace KWSYS_NAMESPACE
 
-#endif // MAC_OS_X_VERSION_MAX_ALLOWED < 1030
-#endif // __APPLE__
-
-// ---------------------------------------------------------------
-// 3. Implementation for Windows win32 code but not cygwin
-#if defined(_WIN32) && !defined(__CYGWIN__)
+#elif defined(_WIN32) && !defined(__CYGWIN__)
+//----------------------------------------------------------------------------
+// Implementation for Windows win32 code but not cygwin
 #include <windows.h>
-#define DYNAMICLOADER_DEFINED 1
 
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
 
 //----------------------------------------------------------------------------
-DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libname)
+DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(
+  const std::string& libname)
 {
   DynamicLoader::LibraryHandle lh;
   int length = MultiByteToWideChar(CP_UTF8, 0, libname.c_str(), -1, NULL, 0);
-  wchar_t* wchars = new wchar_t[length+1];
+  wchar_t* wchars = new wchar_t[length + 1];
   wchars[0] = '\0';
   MultiByteToWideChar(CP_UTF8, 0, libname.c_str(), -1, wchars, length);
   lh = LoadLibraryW(wchars);
-  delete [] wchars;
+  delete[] wchars;
   return lh;
 }
 
@@ -231,21 +252,21 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
   //
   // Note that the "@X" part of the name above is the total size (in
   // bytes) of the arguments on the stack.
-  void *result;
+  void* result;
 #if defined(__BORLANDC__) || defined(__WATCOMC__)
   // Need to prepend symbols with '_'
   size_t len = sym.size();
-  char *rsym = new char[len + 1 + 1];
+  char* rsym = new char[len + 1 + 1];
   strcpy(rsym, "_");
   strcat(rsym, sym.c_str());
 #else
-  const char *rsym = sym.c_str();
+  const char* rsym = sym.c_str();
 #endif
   result = (void*)GetProcAddress(lib, rsym);
 #if defined(__BORLANDC__) || defined(__WATCOMC__)
   delete[] rsym;
 #endif
-  // Hack to cast pointer-to-data to pointer-to-function.
+// Hack to cast pointer-to-data to pointer-to-function.
 #ifdef __WATCOMC__
   return *(DynamicLoader::SymbolPointer*)(&result);
 #else
@@ -256,84 +277,68 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
 //----------------------------------------------------------------------------
 const char* DynamicLoader::LastError()
 {
-  LPVOID lpMsgBuf=NULL;
-
-  FormatMessage(
-    FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
-    NULL,
-    GetLastError(),
-    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
-    (LPTSTR) &lpMsgBuf,
-    0,
-    NULL
-    );
-
-  if(!lpMsgBuf)
-    {
+  LPVOID lpMsgBuf = NULL;
+
+  FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
+                NULL, GetLastError(),
+                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
+                (LPTSTR)&lpMsgBuf, 0, NULL);
+
+  if (!lpMsgBuf) {
     return NULL;
-    }
+  }
 
   static char* str = 0;
-  delete [] str;
-  str = strcpy(new char[strlen((char*)lpMsgBuf)+1], (char*)lpMsgBuf);
+  delete[] str;
+  str = strcpy(new char[strlen((char*)lpMsgBuf) + 1], (char*)lpMsgBuf);
   // Free the buffer.
-  LocalFree( lpMsgBuf );
+  LocalFree(lpMsgBuf);
   return str;
 }
 
 } // namespace KWSYS_NAMESPACE
 
-#endif //_WIN32
-
-// ---------------------------------------------------------------
-// 4. Implementation for BeOS
-#if defined __BEOS__
-
+#elif defined(__BEOS__)
+//----------------------------------------------------------------------------
+// Implementation for BeOS / Haiku
 #include <string.h> // for strerror()
 
 #include <be/kernel/image.h>
 #include <be/support/Errors.h>
 
-#define DYNAMICLOADER_DEFINED 1
-
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
 
 static image_id last_dynamic_err = B_OK;
 
 //----------------------------------------------------------------------------
-DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libname )
+DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(
+  const std::string& libname)
 {
   // image_id's are integers, errors are negative. Add one just in case we
   //  get a valid image_id of zero (is that even possible?).
   image_id rc = load_add_on(libname.c_str());
-  if (rc < 0)
-    {
+  if (rc < 0) {
     last_dynamic_err = rc;
     return 0;
-    }
+  }
 
-  return rc+1;
+  return rc + 1;
 }
 
 //----------------------------------------------------------------------------
 int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
 {
-  if (!lib)
-    {
-      last_dynamic_err = B_BAD_VALUE;
-      return 0;
-    }
-  else
-    {
+  if (!lib) {
+    last_dynamic_err = B_BAD_VALUE;
+    return 0;
+  } else {
     // The function dlclose() returns 0 on success, and non-zero on error.
-    status_t rc = unload_add_on(lib-1);
-    if (rc != B_OK)
-      {
+    status_t rc = unload_add_on(lib - 1);
+    if (rc != B_OK) {
       last_dynamic_err = rc;
       return 0;
-      }
     }
+  }
 
   return 1;
 }
@@ -343,7 +348,7 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
   DynamicLoader::LibraryHandle lib, const std::string& sym)
 {
   // Hack to cast pointer-to-data to pointer-to-function.
-  union 
+  union
   {
     void* pvoid;
     DynamicLoader::SymbolPointer psym;
@@ -351,105 +356,58 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
 
   result.psym = NULL;
 
-  if (!lib)
-    {
-      last_dynamic_err = B_BAD_VALUE;
-    }
-  else
-    {
+  if (!lib) {
+    last_dynamic_err = B_BAD_VALUE;
+  } else {
     // !!! FIXME: BeOS can do function-only lookups...does this ever
     // !!! FIXME:  actually _want_ a data symbol lookup, or was this union
     // !!! FIXME:  a leftover of dlsym()? (s/ANY/TEXT for functions only).
-    status_t rc = get_image_symbol(lib-1,sym.c_str(),B_SYMBOL_TYPE_ANY,&result.pvoid);
-    if (rc != B_OK)
-      {
+    status_t rc =
+      get_image_symbol(lib - 1, sym.c_str(), B_SYMBOL_TYPE_ANY, &result.pvoid);
+    if (rc != B_OK) {
       last_dynamic_err = rc;
       result.psym = NULL;
-      }
     }
+  }
   return result.psym;
 }
 
 //----------------------------------------------------------------------------
 const char* DynamicLoader::LastError()
 {
-  const char *retval = strerror(last_dynamic_err);
+  const char* retval = strerror(last_dynamic_err);
   last_dynamic_err = B_OK;
   return retval;
 }
 
 } // namespace KWSYS_NAMESPACE
-#endif
-
-// ---------------------------------------------------------------
-// 5. Implementation for systems without dynamic libs
-// __gnu_blrts__ is IBM BlueGene/L
-// __LIBCATAMOUNT__ is defined on Catamount on Cray compute nodes
-#if defined(__gnu_blrts__) || defined(__LIBCATAMOUNT__) || defined(__CRAYXT_COMPUTE_LINUX_TARGET)
-#include <string.h> // for strerror()
-#define DYNAMICLOADER_DEFINED 1
-
-namespace KWSYS_NAMESPACE
-{
-
-//----------------------------------------------------------------------------
-DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libname )
-{
-  return 0;
-}
 
+#elif defined(__MINT__)
 //----------------------------------------------------------------------------
-int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
-{
-  if (!lib)
-    {
-    return 0;
-    }
-
-  return 1;
-}
-
-//----------------------------------------------------------------------------
-DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
-    DynamicLoader::LibraryHandle lib, const std::string& sym)
-{
-  return 0;
-}
-
-//----------------------------------------------------------------------------
-const char* DynamicLoader::LastError()
-  {
-  return "General error";
-  }
-
-} // namespace KWSYS_NAMESPACE
-#endif
-
-#ifdef __MINT__
-#define DYNAMICLOADER_DEFINED 1
+// Implementation for FreeMiNT on Atari
 #define _GNU_SOURCE /* for program_invocation_name */
-#include <string.h>
-#include <malloc.h>
-#include <errno.h>
 #include <dld.h>
+#include <errno.h>
+#include <malloc.h>
+#include <string.h>
 
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
 
 //----------------------------------------------------------------------------
-DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libname )
+DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(
+  const std::string& libname)
 {
-  char *name = (char *)calloc(1, libname.size() + 1);
+  char* name = (char*)calloc(1, libname.size() + 1);
   dld_init(program_invocation_name);
   strncpy(name, libname.c_str(), libname.size());
   dld_link(libname.c_str());
-  return (void *)name;
+  return (void*)name;
 }
 
 //----------------------------------------------------------------------------
 int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
 {
-  dld_unlink_by_file((char *)lib, 0);
+  dld_unlink_by_file((char*)lib, 0);
   free(lib);
   return 0;
 }
@@ -475,21 +433,18 @@ const char* DynamicLoader::LastError()
 }
 
 } // namespace KWSYS_NAMESPACE
-#endif
 
-// ---------------------------------------------------------------
-// 6. Implementation for default UNIX machines.
-// if nothing has been defined then use this
-#ifndef DYNAMICLOADER_DEFINED
-#define DYNAMICLOADER_DEFINED 1
-// Setup for most unix machines
+#else
+//----------------------------------------------------------------------------
+// Default implementation for *NIX systems (including Mac OS X 10.3 and
+// later) which use dlopen
 #include <dlfcn.h>
 
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
 
 //----------------------------------------------------------------------------
-DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libname )
+DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(
+  const std::string& libname)
 {
   return dlopen(libname.c_str(), RTLD_LAZY);
 }
@@ -497,11 +452,10 @@ DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const std::string& libna
 //----------------------------------------------------------------------------
 int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
 {
-  if (lib)
-    {
+  if (lib) {
     // The function dlclose() returns 0 on success, and non-zero on error.
     return !dlclose(lib);
-    }
+  }
   // else
   return 0;
 }
@@ -511,7 +465,7 @@ DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
   DynamicLoader::LibraryHandle lib, const std::string& sym)
 {
   // Hack to cast pointer-to-data to pointer-to-function.
-  union 
+  union
   {
     void* pvoid;
     DynamicLoader::SymbolPointer psym;
@@ -527,5 +481,4 @@ const char* DynamicLoader::LastError()
 }
 
 } // namespace KWSYS_NAMESPACE
-
 #endif
diff --git a/Source/kwsys/DynamicLoader.hxx.in b/Source/kwsys/DynamicLoader.hxx.in
index 1e4a912..7e71a45 100644
--- a/Source/kwsys/DynamicLoader.hxx.in
+++ b/Source/kwsys/DynamicLoader.hxx.in
@@ -1,35 +1,26 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _DynamicLoader_hxx
 #define @KWSYS_NAMESPACE at _DynamicLoader_hxx
 
 #include <@KWSYS_NAMESPACE@/Configure.hxx>
+
 #include <string>
 
 #if defined(__hpux)
-  #include <dl.h>
+#include <dl.h>
 #elif defined(_WIN32) && !defined(__CYGWIN__)
-  #include <windows.h>
+#include <windows.h>
 #elif defined(__APPLE__)
-  #include <AvailabilityMacros.h>
-  #if MAC_OS_X_VERSION_MAX_ALLOWED < 1030
-    #include <mach-o/dyld.h>
-  #endif
+#include <AvailabilityMacros.h>
+#if MAC_OS_X_VERSION_MAX_ALLOWED < 1030
+#include <mach-o/dyld.h>
+#endif
 #elif defined(__BEOS__)
-  #include <be/kernel/image.h>
+#include <be/kernel/image.h>
 #endif
 
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 /** \class DynamicLoader
  * \brief Portable loading of dynamic libraries or dll's.
  *
@@ -61,14 +52,14 @@ public:
 #elif defined(_WIN32) && !defined(__CYGWIN__)
   typedef HMODULE LibraryHandle;
 #elif defined(__APPLE__)
-  #if MAC_OS_X_VERSION_MAX_ALLOWED < 1030
-    typedef NSModule LibraryHandle;
-  #else
-    typedef void* LibraryHandle;
-  #endif
+#if MAC_OS_X_VERSION_MAX_ALLOWED < 1030
+  typedef NSModule LibraryHandle;
+#else
+  typedef void* LibraryHandle;
+#endif
 #elif defined(__BEOS__)
   typedef image_id LibraryHandle;
-#else  // POSIX
+#else // POSIX
   typedef void* LibraryHandle;
 #endif
 
diff --git a/Source/kwsys/Encoding.h.in b/Source/kwsys/Encoding.h.in
index 591c5a8..7b6ed10 100644
--- a/Source/kwsys/Encoding.h.in
+++ b/Source/kwsys/Encoding.h.in
@@ -1,18 +1,10 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _Encoding_h
 #define @KWSYS_NAMESPACE at _Encoding_h
 
 #include <@KWSYS_NAMESPACE@/Configure.h>
+
 #include <wchar.h>
 
 /* Redefine all public interface symbol names to be in the proper
@@ -20,44 +12,42 @@
    not visible to user code.  Use kwsysHeaderDump.pl to reproduce
    these macros after making changes to the interface.  */
 #if !defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
 #endif
 #if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-# define kwsysEncoding         kwsys_ns(Encoding)
-# define kwsysEncoding_mbstowcs  kwsys_ns(Encoding_mbstowcs)
-# define kwsysEncoding_DupToWide  kwsys_ns(Encoding_DupToWide)
-# define kwsysEncoding_wcstombs  kwsys_ns(Encoding_wcstombs)
-# define kwsysEncoding_DupToNarrow kwsys_ns(Encoding_DupToNarrow)
+#define kwsysEncoding kwsys_ns(Encoding)
+#define kwsysEncoding_mbstowcs kwsys_ns(Encoding_mbstowcs)
+#define kwsysEncoding_DupToWide kwsys_ns(Encoding_DupToWide)
+#define kwsysEncoding_wcstombs kwsys_ns(Encoding_wcstombs)
+#define kwsysEncoding_DupToNarrow kwsys_ns(Encoding_DupToNarrow)
 #endif
 
 #if defined(__cplusplus)
-extern "C"
-{
+extern "C" {
 #endif
 
-
 /* Convert a narrow string to a wide string.
    On Windows, UTF-8 is assumed, and on other platforms,
    the current locale is assumed.
    */
-kwsysEXPORT size_t kwsysEncoding_mbstowcs(wchar_t* dest, const char* src, size_t n);
+kwsysEXPORT size_t kwsysEncoding_mbstowcs(wchar_t* dest, const char* src,
+                                          size_t n);
 
 /* Convert a narrow string to a wide string.
    This can return NULL if the conversion fails. */
 kwsysEXPORT wchar_t* kwsysEncoding_DupToWide(const char* src);
 
-
 /* Convert a wide string to a narrow string.
    On Windows, UTF-8 is assumed, and on other platforms,
    the current locale is assumed. */
-kwsysEXPORT size_t kwsysEncoding_wcstombs(char* dest, const wchar_t* src, size_t n);
+kwsysEXPORT size_t kwsysEncoding_wcstombs(char* dest, const wchar_t* src,
+                                          size_t n);
 
 /* Convert a wide string to a narrow string.
    This can return NULL if the conversion fails. */
 kwsysEXPORT char* kwsysEncoding_DupToNarrow(const wchar_t* str);
 
-
 #if defined(__cplusplus)
 } /* extern "C" */
 #endif
@@ -65,15 +55,15 @@ kwsysEXPORT char* kwsysEncoding_DupToNarrow(const wchar_t* str);
 /* If we are building a kwsys .c or .cxx file, let it use these macros.
    Otherwise, undefine them to keep the namespace clean.  */
 #if !defined(KWSYS_NAMESPACE)
-# undef kwsys_ns
-# undef kwsysEXPORT
-# if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-#  undef kwsysEncoding
-#  undef kwsysEncoding_mbstowcs
-#  undef kwsysEncoding_DupToWide
-#  undef kwsysEncoding_wcstombs
-#  undef kwsysEncoding_DupToNarrow
-# endif
+#undef kwsys_ns
+#undef kwsysEXPORT
+#if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
+#undef kwsysEncoding
+#undef kwsysEncoding_mbstowcs
+#undef kwsysEncoding_DupToWide
+#undef kwsysEncoding_wcstombs
+#undef kwsysEncoding_DupToNarrow
+#endif
 #endif
 
 #endif
diff --git a/Source/kwsys/Encoding.hxx.in b/Source/kwsys/Encoding.hxx.in
index 87b1c21..6639efd 100644
--- a/Source/kwsys/Encoding.hxx.in
+++ b/Source/kwsys/Encoding.hxx.in
@@ -1,59 +1,49 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _Encoding_hxx
 #define @KWSYS_NAMESPACE at _Encoding_hxx
 
 #include <@KWSYS_NAMESPACE@/Configure.hxx>
+
 #include <string>
 #include <vector>
 
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 class @KWSYS_NAMESPACE at _EXPORT Encoding
 {
 public:
-
   // Container class for argc/argv.
   class CommandLineArguments
   {
-    public:
-      // On Windows, get the program command line arguments
-      // in this Encoding module's 8 bit encoding.
-      // On other platforms the given argc/argv is used, and
-      // to be consistent, should be the argc/argv from main().
-      static CommandLineArguments Main(int argc, char const* const* argv);
-
-      // Construct CommandLineArguments with the given
-      // argc/argv.  It is assumed that the string is already
-      // in the encoding used by this module.
-      CommandLineArguments(int argc, char const* const* argv);
-
-      // Construct CommandLineArguments with the given
-      // argc and wide argv.  This is useful if wmain() is used.
-      CommandLineArguments(int argc, wchar_t const* const* argv);
-      ~CommandLineArguments();
-      CommandLineArguments(const CommandLineArguments&);
-      CommandLineArguments& operator=(const CommandLineArguments&);
-
-      int argc() const;
-      char const* const* argv() const;
-
-    protected:
-      std::vector<char*> argv_;
+  public:
+    // On Windows, get the program command line arguments
+    // in this Encoding module's 8 bit encoding.
+    // On other platforms the given argc/argv is used, and
+    // to be consistent, should be the argc/argv from main().
+    static CommandLineArguments Main(int argc, char const* const* argv);
+
+    // Construct CommandLineArguments with the given
+    // argc/argv.  It is assumed that the string is already
+    // in the encoding used by this module.
+    CommandLineArguments(int argc, char const* const* argv);
+
+    // Construct CommandLineArguments with the given
+    // argc and wide argv.  This is useful if wmain() is used.
+    CommandLineArguments(int argc, wchar_t const* const* argv);
+    ~CommandLineArguments();
+    CommandLineArguments(const CommandLineArguments&);
+    CommandLineArguments& operator=(const CommandLineArguments&);
+
+    int argc() const;
+    char const* const* argv() const;
+
+  protected:
+    std::vector<char*> argv_;
   };
 
-  /**
-   * Convert between char and wchar_t
-   */
+/**
+ * Convert between char and wchar_t
+ */
 
 #if @KWSYS_NAMESPACE at _STL_HAS_WSTRING
 
diff --git a/Source/kwsys/EncodingC.c b/Source/kwsys/EncodingC.c
index 32b9bff..c1315b2 100644
--- a/Source/kwsys/EncodingC.c
+++ b/Source/kwsys/EncodingC.c
@@ -1,21 +1,12 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(Encoding.h)
 
 /* Work-around CMake dependency scanning limitation.  This must
    duplicate the above list of headers.  */
 #if 0
-# include "Encoding.h.in"
+#include "Encoding.h.in"
 #endif
 
 #include <stdlib.h>
@@ -26,13 +17,13 @@
 
 size_t kwsysEncoding_mbstowcs(wchar_t* dest, const char* str, size_t n)
 {
-  if(str == 0)
-    {
+  if (str == 0) {
     return (size_t)-1;
-    }
+  }
 #ifdef _WIN32
-  return MultiByteToWideChar(KWSYS_ENCODING_DEFAULT_CODEPAGE, 0,
-                             str, -1, dest, (int)n) - 1;
+  return MultiByteToWideChar(KWSYS_ENCODING_DEFAULT_CODEPAGE, 0, str, -1, dest,
+                             (int)n) -
+    1;
 #else
   return mbstowcs(dest, str, n);
 #endif
@@ -42,27 +33,25 @@ wchar_t* kwsysEncoding_DupToWide(const char* str)
 {
   wchar_t* ret = NULL;
   size_t length = kwsysEncoding_mbstowcs(NULL, str, 0) + 1;
-  if(length > 0)
-    {
-    ret = (wchar_t*)malloc((length)*sizeof(wchar_t));
-    if(ret)
-      {
+  if (length > 0) {
+    ret = (wchar_t*)malloc((length) * sizeof(wchar_t));
+    if (ret) {
       ret[0] = 0;
       kwsysEncoding_mbstowcs(ret, str, length);
-      }
     }
+  }
   return ret;
 }
 
 size_t kwsysEncoding_wcstombs(char* dest, const wchar_t* str, size_t n)
 {
-  if(str == 0)
-    {
+  if (str == 0) {
     return (size_t)-1;
-    }
+  }
 #ifdef _WIN32
-  return WideCharToMultiByte(KWSYS_ENCODING_DEFAULT_CODEPAGE, 0, str, -1,
-                             dest, (int)n, NULL, NULL) - 1;
+  return WideCharToMultiByte(KWSYS_ENCODING_DEFAULT_CODEPAGE, 0, str, -1, dest,
+                             (int)n, NULL, NULL) -
+    1;
 #else
   return wcstombs(dest, str, n);
 #endif
@@ -72,14 +61,12 @@ char* kwsysEncoding_DupToNarrow(const wchar_t* str)
 {
   char* ret = NULL;
   size_t length = kwsysEncoding_wcstombs(0, str, 0) + 1;
-  if(length > 0)
-    {
+  if (length > 0) {
     ret = (char*)malloc(length);
-    if(ret)
-      {
+    if (ret) {
       ret[0] = 0;
       kwsysEncoding_wcstombs(ret, str, length);
-      }
     }
+  }
   return ret;
 }
diff --git a/Source/kwsys/EncodingCXX.cxx b/Source/kwsys/EncodingCXX.cxx
index 597d4bd..e904c1a 100644
--- a/Source/kwsys/EncodingCXX.cxx
+++ b/Source/kwsys/EncodingCXX.cxx
@@ -1,19 +1,9 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifdef __osf__
-#  define _OSF_SOURCE
-#  define _POSIX_C_SOURCE 199506L
-#  define _XOPEN_SOURCE_EXTENDED
+#define _OSF_SOURCE
+#define _POSIX_C_SOURCE 199506L
+#define _XOPEN_SOURCE_EXTENDED
 #endif
 
 #include "kwsysPrivate.h"
@@ -23,44 +13,43 @@
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "Encoding.hxx.in"
-# include "Encoding.h.in"
+#include "Encoding.h.in"
+#include "Encoding.hxx.in"
 #endif
 
-#include <vector>
 #include <stdlib.h>
 #include <string.h>
+#include <vector>
 
 #ifdef _MSC_VER
-# pragma warning (disable: 4786)
+#pragma warning(disable : 4786)
 #endif
 
 // Windows API.
 #if defined(_WIN32)
-# include <windows.h>
-# include <shellapi.h>
+#include <windows.h>
+
+#include <shellapi.h>
 #endif
 
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
 
-Encoding::CommandLineArguments
-Encoding::CommandLineArguments::Main(int argc, char const* const* argv)
+Encoding::CommandLineArguments Encoding::CommandLineArguments::Main(
+  int argc, char const* const* argv)
 {
 #ifdef _WIN32
-  (void) argc;
-  (void) argv;
+  (void)argc;
+  (void)argv;
 
   int ac;
   LPWSTR* w_av = CommandLineToArgvW(GetCommandLineW(), &ac);
 
   std::vector<std::string> av1(ac);
   std::vector<char const*> av2(ac);
-  for(int i=0; i<ac; i++)
-    {
+  for (int i = 0; i < ac; i++) {
     av1[i] = ToNarrow(w_av[i]);
     av2[i] = av1[i].c_str();
-    }
+  }
   LocalFree(w_av);
   return CommandLineArguments(ac, &av2[0]);
 #else
@@ -71,60 +60,53 @@ Encoding::CommandLineArguments::Main(int argc, char const* const* argv)
 Encoding::CommandLineArguments::CommandLineArguments(int ac,
                                                      char const* const* av)
 {
-  this->argv_.resize(ac+1);
-  for(int i=0; i<ac; i++)
-    {
+  this->argv_.resize(ac + 1);
+  for (int i = 0; i < ac; i++) {
     this->argv_[i] = strdup(av[i]);
-    }
+  }
   this->argv_[ac] = 0;
 }
 
 Encoding::CommandLineArguments::CommandLineArguments(int ac,
                                                      wchar_t const* const* av)
 {
-  this->argv_.resize(ac+1);
-  for(int i=0; i<ac; i++)
-    {
+  this->argv_.resize(ac + 1);
+  for (int i = 0; i < ac; i++) {
     this->argv_[i] = kwsysEncoding_DupToNarrow(av[i]);
-    }
+  }
   this->argv_[ac] = 0;
 }
 
 Encoding::CommandLineArguments::~CommandLineArguments()
 {
-  for(size_t i=0; i<this->argv_.size(); i++)
-    {
+  for (size_t i = 0; i < this->argv_.size(); i++) {
     free(argv_[i]);
-    }
+  }
 }
 
-Encoding::CommandLineArguments::
-  CommandLineArguments(const CommandLineArguments& other)
+Encoding::CommandLineArguments::CommandLineArguments(
+  const CommandLineArguments& other)
 {
   this->argv_.resize(other.argv_.size());
-  for(size_t i=0; i<this->argv_.size(); i++)
-    {
+  for (size_t i = 0; i < this->argv_.size(); i++) {
     this->argv_[i] = other.argv_[i] ? strdup(other.argv_[i]) : 0;
-    }
+  }
 }
 
-Encoding::CommandLineArguments&
-Encoding::CommandLineArguments::operator=(const CommandLineArguments& other)
+Encoding::CommandLineArguments& Encoding::CommandLineArguments::operator=(
+  const CommandLineArguments& other)
 {
-  if(this != &other)
-    {
+  if (this != &other) {
     size_t i;
-    for(i=0; i<this->argv_.size(); i++)
-      {
+    for (i = 0; i < this->argv_.size(); i++) {
       free(this->argv_[i]);
-      }
+    }
 
     this->argv_.resize(other.argv_.size());
-    for(i=0; i<this->argv_.size(); i++)
-      {
+    for (i = 0; i < this->argv_.size(); i++) {
       this->argv_[i] = other.argv_[i] ? strdup(other.argv_[i]) : 0;
-      }
     }
+  }
 
   return *this;
 }
@@ -143,26 +125,80 @@ char const* const* Encoding::CommandLineArguments::argv() const
 
 std::wstring Encoding::ToWide(const std::string& str)
 {
-  return ToWide(str.c_str());
+  std::wstring wstr;
+#if defined(_WIN32)
+  const int wlength = MultiByteToWideChar(
+    KWSYS_ENCODING_DEFAULT_CODEPAGE, 0, str.data(), int(str.size()), NULL, 0);
+  if (wlength > 0) {
+    wchar_t* wdata = new wchar_t[wlength];
+    int r = MultiByteToWideChar(KWSYS_ENCODING_DEFAULT_CODEPAGE, 0, str.data(),
+                                int(str.size()), wdata, wlength);
+    if (r > 0) {
+      wstr = std::wstring(wdata, wlength);
+    }
+    delete[] wdata;
+  }
+#else
+  size_t pos = 0;
+  size_t nullPos = 0;
+  do {
+    if (pos < str.size() && str.at(pos) != '\0') {
+      wstr += ToWide(str.c_str() + pos);
+    }
+    nullPos = str.find('\0', pos);
+    if (nullPos != str.npos) {
+      pos = nullPos + 1;
+      wstr += wchar_t('\0');
+    }
+  } while (nullPos != str.npos);
+#endif
+  return wstr;
 }
 
 std::string Encoding::ToNarrow(const std::wstring& str)
 {
-  return ToNarrow(str.c_str());
+  std::string nstr;
+#if defined(_WIN32)
+  int length =
+    WideCharToMultiByte(KWSYS_ENCODING_DEFAULT_CODEPAGE, 0, str.c_str(),
+                        int(str.size()), NULL, 0, NULL, NULL);
+  if (length > 0) {
+    char* data = new char[length];
+    int r =
+      WideCharToMultiByte(KWSYS_ENCODING_DEFAULT_CODEPAGE, 0, str.c_str(),
+                          int(str.size()), data, length, NULL, NULL);
+    if (r > 0) {
+      nstr = std::string(data, length);
+    }
+    delete[] data;
+  }
+#else
+  size_t pos = 0;
+  size_t nullPos = 0;
+  do {
+    if (pos < str.size() && str.at(pos) != '\0') {
+      nstr += ToNarrow(str.c_str() + pos);
+    }
+    nullPos = str.find(wchar_t('\0'), pos);
+    if (nullPos != str.npos) {
+      pos = nullPos + 1;
+      nstr += '\0';
+    }
+  } while (nullPos != str.npos);
+#endif
+  return nstr;
 }
 
 std::wstring Encoding::ToWide(const char* cstr)
 {
   std::wstring wstr;
   size_t length = kwsysEncoding_mbstowcs(0, cstr, 0) + 1;
-  if(length > 0)
-    {
+  if (length > 0) {
     std::vector<wchar_t> wchars(length);
-    if(kwsysEncoding_mbstowcs(&wchars[0], cstr, length) > 0)
-      {
+    if (kwsysEncoding_mbstowcs(&wchars[0], cstr, length) > 0) {
       wstr = &wchars[0];
-      }
     }
+  }
   return wstr;
 }
 
@@ -170,14 +206,12 @@ std::string Encoding::ToNarrow(const wchar_t* wcstr)
 {
   std::string str;
   size_t length = kwsysEncoding_wcstombs(0, wcstr, 0) + 1;
-  if(length > 0)
-    {
+  if (length > 0) {
     std::vector<char> chars(length);
-    if(kwsysEncoding_wcstombs(&chars[0], wcstr, length) > 0)
-      {
+    if (kwsysEncoding_wcstombs(&chars[0], wcstr, length) > 0) {
       str = &chars[0];
-      }
     }
+  }
   return str;
 }
 #endif // KWSYS_STL_HAS_WSTRING
diff --git a/Source/kwsys/FStream.cxx b/Source/kwsys/FStream.cxx
index 5a30997..3c44a6f 100644
--- a/Source/kwsys/FStream.cxx
+++ b/Source/kwsys/FStream.cxx
@@ -1,78 +1,55 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(FStream.hxx)
 
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "FStream.hxx.in"
+#include "FStream.hxx.in"
 #endif
 
-namespace KWSYS_NAMESPACE
-{
-namespace FStream
-{
+namespace KWSYS_NAMESPACE {
+namespace FStream {
 
 BOM ReadBOM(std::istream& in)
 {
-  if(!in.good())
-    {
+  if (!in.good()) {
     return BOM_None;
-    }
+  }
   unsigned long orig = in.tellg();
   unsigned char bom[4];
   in.read(reinterpret_cast<char*>(bom), 2);
-  if(!in.good())
-    {
+  if (!in.good()) {
     in.clear();
     in.seekg(orig);
     return BOM_None;
-    }
-  if(bom[0] == 0xEF && bom[1] == 0xBB)
-    {
-    in.read(reinterpret_cast<char*>(bom+2), 1);
-    if(in.good() && bom[2] == 0xBF)
-      {
+  }
+  if (bom[0] == 0xEF && bom[1] == 0xBB) {
+    in.read(reinterpret_cast<char*>(bom + 2), 1);
+    if (in.good() && bom[2] == 0xBF) {
       return BOM_UTF8;
-      }
     }
-  else if(bom[0] == 0xFE && bom[1] == 0xFF)
-    {
+  } else if (bom[0] == 0xFE && bom[1] == 0xFF) {
     return BOM_UTF16BE;
-    }
-  else if(bom[0] == 0x00 && bom[1] == 0x00)
-    {
-    in.read(reinterpret_cast<char*>(bom+2), 2);
-    if(in.good() && bom[2] == 0xFE && bom[3] == 0xFF)
-      {
+  } else if (bom[0] == 0x00 && bom[1] == 0x00) {
+    in.read(reinterpret_cast<char*>(bom + 2), 2);
+    if (in.good() && bom[2] == 0xFE && bom[3] == 0xFF) {
       return BOM_UTF32BE;
-      }
     }
-  else if(bom[0] == 0xFF && bom[1] == 0xFE)
-    {
+  } else if (bom[0] == 0xFF && bom[1] == 0xFE) {
     unsigned long p = in.tellg();
-    in.read(reinterpret_cast<char*>(bom+2), 2);
-    if(in.good() && bom[2] == 0x00 && bom[3] == 0x00)
-      {
+    in.read(reinterpret_cast<char*>(bom + 2), 2);
+    if (in.good() && bom[2] == 0x00 && bom[3] == 0x00) {
       return BOM_UTF32LE;
-      }
+    }
     in.seekg(p);
     return BOM_UTF16LE;
-    }
+  }
   in.clear();
   in.seekg(orig);
   return BOM_None;
 }
 
 } // FStream namespace
-} //KWSYS_NAMESPACE
+} // KWSYS_NAMESPACE
diff --git a/Source/kwsys/FStream.hxx.in b/Source/kwsys/FStream.hxx.in
index 5471247..736214f 100644
--- a/Source/kwsys/FStream.hxx.in
+++ b/Source/kwsys/FStream.hxx.in
@@ -1,288 +1,276 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _FStream_hxx
 #define @KWSYS_NAMESPACE at _FStream_hxx
 
 #include <@KWSYS_NAMESPACE@/Configure.hxx>
+
 #include <@KWSYS_NAMESPACE@/Encoding.hxx>
+
 #include <fstream>
 #if defined(_WIN32)
-# if !defined(_MSC_VER) && @KWSYS_NAMESPACE at _CXX_HAS_EXT_STDIO_FILEBUF_H
-#  include <ext/stdio_filebuf.h>
-# endif
+#if !defined(_MSC_VER) && @KWSYS_NAMESPACE at _CXX_HAS_EXT_STDIO_FILEBUF_H
+#include <ext/stdio_filebuf.h>
+#endif
 #endif
 
-namespace @KWSYS_NAMESPACE@
-{
-#if defined(_WIN32) && (defined(_MSC_VER) || @KWSYS_NAMESPACE at _CXX_HAS_EXT_STDIO_FILEBUF_H)
-# if defined(_NOEXCEPT)
-#  define @KWSYS_NAMESPACE at _FStream_NOEXCEPT _NOEXCEPT
-# else
-#  define @KWSYS_NAMESPACE at _FStream_NOEXCEPT
-# endif
+namespace @KWSYS_NAMESPACE@ {
+#if defined(_WIN32) &&                                                        \
+  (defined(_MSC_VER) || @KWSYS_NAMESPACE at _CXX_HAS_EXT_STDIO_FILEBUF_H)
+#if defined(_NOEXCEPT)
+#define @KWSYS_NAMESPACE at _FStream_NOEXCEPT _NOEXCEPT
+#else
+#define @KWSYS_NAMESPACE at _FStream_NOEXCEPT
+#endif
 
 #if defined(_MSC_VER)
 
-  template<typename CharType,typename Traits>
-  class basic_filebuf : public std::basic_filebuf<CharType,Traits>
+template <typename CharType, typename Traits>
+class basic_filebuf : public std::basic_filebuf<CharType, Traits>
+{
+#if _MSC_VER >= 1400
+public:
+  typedef std::basic_filebuf<CharType, Traits> my_base_type;
+  basic_filebuf* open(char const* s, std::ios_base::openmode mode)
   {
-# if _MSC_VER >= 1400
-    public:
-      typedef std::basic_filebuf<CharType,Traits> my_base_type;
-      basic_filebuf *open(char const *s,std::ios_base::openmode mode)
-      {
-        const std::wstring wstr = Encoding::ToWide(s);
-        return static_cast<basic_filebuf*>(
-          my_base_type::open(wstr.c_str(), mode)
-          );
-      }
-# endif
-  };
+    const std::wstring wstr = Encoding::ToWide(s);
+    return static_cast<basic_filebuf*>(my_base_type::open(wstr.c_str(), mode));
+  }
+#endif
+};
 
 #else
 
-  inline std::wstring getcmode(const std::ios_base::openmode mode) {
-    std::wstring cmode;
-    bool plus = false;
-    if (mode & std::ios_base::app) {
-      cmode += L"a";
-      plus = mode & std::ios_base::in ? true : false;
-    } else if (mode & std::ios_base::trunc ||
-                (mode & std::ios_base::out && (mode & std::ios_base::in) == 0)) {
-      cmode += L"w";
-      plus = mode & std::ios_base::in ? true : false;
-    } else {
-      cmode += L"r";
-      plus = mode & std::ios_base::out ? true : false;
-    }
-    if (plus) {
-      cmode += L"+";
-    }
-    if (mode & std::ios_base::binary) {
-      cmode += L"b";
-    } else {
-      cmode += L"t";
-    }
-    return cmode;
-  };
+inline std::wstring getcmode(const std::ios_base::openmode mode)
+{
+  std::wstring cmode;
+  bool plus = false;
+  if (mode & std::ios_base::app) {
+    cmode += L"a";
+    plus = mode & std::ios_base::in ? true : false;
+  } else if (mode & std::ios_base::trunc ||
+             (mode & std::ios_base::out && (mode & std::ios_base::in) == 0)) {
+    cmode += L"w";
+    plus = mode & std::ios_base::in ? true : false;
+  } else {
+    cmode += L"r";
+    plus = mode & std::ios_base::out ? true : false;
+  }
+  if (plus) {
+    cmode += L"+";
+  }
+  if (mode & std::ios_base::binary) {
+    cmode += L"b";
+  } else {
+    cmode += L"t";
+  }
+  return cmode;
+};
 
 #endif
 
-  template<typename CharType,typename Traits = std::char_traits<CharType> >
-  class basic_efilebuf
-  {
-    public:
+template <typename CharType, typename Traits = std::char_traits<CharType> >
+class basic_efilebuf
+{
+public:
 #if defined(_MSC_VER)
-      typedef basic_filebuf<CharType,Traits> internal_buffer_type;
+  typedef basic_filebuf<CharType, Traits> internal_buffer_type;
 #else
-      typedef __gnu_cxx::stdio_filebuf<CharType,Traits> internal_buffer_type;
+  typedef __gnu_cxx::stdio_filebuf<CharType, Traits> internal_buffer_type;
 #endif
 
-      basic_efilebuf() : file_(0)
-      {
-        buf_ = 0;
-      }
+  basic_efilebuf()
+    : file_(0)
+  {
+    buf_ = 0;
+  }
 
-      bool _open(char const *file_name,std::ios_base::openmode mode)
-      {
-        if (is_open() || file_) {
-          return false;
-        }
+  bool _open(char const* file_name, std::ios_base::openmode mode)
+  {
+    if (is_open() || file_) {
+      return false;
+    }
 #if defined(_MSC_VER)
-        const bool success = buf_->open(file_name,mode) != 0;
+    const bool success = buf_->open(file_name, mode) != 0;
 #else
-        const std::wstring wstr = Encoding::ToWide(file_name);
-        bool success = false;
-        std::wstring cmode = getcmode(mode);
-        file_ = _wfopen(wstr.c_str(), cmode.c_str());
-        if (file_) {
-          if (buf_) {
-            delete buf_;
-          }
-          buf_ = new internal_buffer_type(file_, mode);
-          success = true;
-        }
-#endif
-        return success;
+    const std::wstring wstr = Encoding::ToWide(file_name);
+    bool success = false;
+    std::wstring cmode = getcmode(mode);
+    file_ = _wfopen(wstr.c_str(), cmode.c_str());
+    if (file_) {
+      if (buf_) {
+        delete buf_;
       }
+      buf_ = new internal_buffer_type(file_, mode);
+      success = true;
+    }
+#endif
+    return success;
+  }
 
-      bool is_open()
-      {
-        if (!buf_) {
-          return false;
-        }
-        return buf_->is_open();
-      }
+  bool is_open()
+  {
+    if (!buf_) {
+      return false;
+    }
+    return buf_->is_open();
+  }
 
-      bool is_open() const
-      {
-        if (!buf_) {
-          return false;
-        }
-        return buf_->is_open();
-      }
+  bool is_open() const
+  {
+    if (!buf_) {
+      return false;
+    }
+    return buf_->is_open();
+  }
 
-      bool _close()
-      {
-        bool success = false;
-        if (buf_) {
-          success = buf_->close() != 0;
+  bool _close()
+  {
+    bool success = false;
+    if (buf_) {
+      success = buf_->close() != 0;
 #if !defined(_MSC_VER)
-          if (file_) {
-            success = fclose(file_) == 0 ? success : false;
-            file_ = 0;
-          }
-#endif
-        }
-        return success;
+      if (file_) {
+        success = fclose(file_) == 0 ? success : false;
+        file_ = 0;
       }
+#endif
+    }
+    return success;
+  }
 
-      static void _set_state(bool success, std::basic_ios<CharType,Traits> *ios, basic_efilebuf* efilebuf)
-      {
+  static void _set_state(bool success, std::basic_ios<CharType, Traits>* ios,
+                         basic_efilebuf* efilebuf)
+  {
 #if !defined(_MSC_VER)
-        ios->rdbuf(efilebuf->buf_);
+    ios->rdbuf(efilebuf->buf_);
+#else
+    static_cast<void>(efilebuf);
 #endif
-        if (!success) {
-          ios->setstate(std::ios_base::failbit);
-        } else {
-          ios->clear();
-        }
-      }
+    if (!success) {
+      ios->setstate(std::ios_base::failbit);
+    } else {
+      ios->clear();
+    }
+  }
 
-      ~basic_efilebuf()
-     {
-       if (buf_) {
-         delete buf_;
-       }
-     }
-
-    protected:
-      internal_buffer_type* buf_;
-      FILE *file_;
-  };
-
-template<typename CharType,typename Traits = std::char_traits<CharType> >
-class basic_ifstream : public std::basic_istream<CharType,Traits>,
-                       public basic_efilebuf<CharType,Traits>
+  ~basic_efilebuf()
+  {
+    if (buf_) {
+      delete buf_;
+    }
+  }
+
+protected:
+  internal_buffer_type* buf_;
+  FILE* file_;
+};
+
+template <typename CharType, typename Traits = std::char_traits<CharType> >
+class basic_ifstream : public std::basic_istream<CharType, Traits>,
+                       public basic_efilebuf<CharType, Traits>
 {
-  using basic_efilebuf<CharType,Traits>::is_open;
+  using basic_efilebuf<CharType, Traits>::is_open;
 
-  public:
-    typedef typename basic_efilebuf<CharType, Traits>::internal_buffer_type internal_buffer_type;
-    typedef std::basic_istream<CharType,Traits> internal_stream_type;
+public:
+  typedef typename basic_efilebuf<CharType, Traits>::internal_buffer_type
+    internal_buffer_type;
+  typedef std::basic_istream<CharType, Traits> internal_stream_type;
 
-    basic_ifstream() : internal_stream_type(new internal_buffer_type())
-    {
-      this->buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
-    }
-    explicit basic_ifstream(char const *file_name,
-                            std::ios_base::openmode mode = std::ios_base::in)
-      : internal_stream_type(new internal_buffer_type())
-    {
-      this->buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
-      open(file_name,mode);
-    }
+  basic_ifstream()
+    : internal_stream_type(new internal_buffer_type())
+  {
+    this->buf_ =
+      static_cast<internal_buffer_type*>(internal_stream_type::rdbuf());
+  }
+  explicit basic_ifstream(char const* file_name,
+                          std::ios_base::openmode mode = std::ios_base::in)
+    : internal_stream_type(new internal_buffer_type())
+  {
+    this->buf_ =
+      static_cast<internal_buffer_type*>(internal_stream_type::rdbuf());
+    open(file_name, mode);
+  }
 
-    void open(char const *file_name,std::ios_base::openmode mode = std::ios_base::in)
-    {
-      mode = mode | std::ios_base::in;
-      this->_set_state(this->_open(file_name, mode), this, this);
-    }
+  void open(char const* file_name,
+            std::ios_base::openmode mode = std::ios_base::in)
+  {
+    mode = mode | std::ios_base::in;
+    this->_set_state(this->_open(file_name, mode), this, this);
+  }
 
-    void close()
-    {
-      this->_set_state(this->_close(), this, this);
-    }
+  void close() { this->_set_state(this->_close(), this, this); }
 
-    internal_buffer_type *rdbuf() const
-    {
-      return this->buf_;
-    }
+  internal_buffer_type* rdbuf() const { return this->buf_; }
 
-    ~basic_ifstream() @KWSYS_NAMESPACE at _FStream_NOEXCEPT
-    {
-      close();
-    }
+  ~basic_ifstream() @KWSYS_NAMESPACE at _FStream_NOEXCEPT { close(); }
 };
 
-template<typename CharType,typename Traits = std::char_traits<CharType> >
-class basic_ofstream : public std::basic_ostream<CharType,Traits>,
-                       public basic_efilebuf<CharType,Traits>
+template <typename CharType, typename Traits = std::char_traits<CharType> >
+class basic_ofstream : public std::basic_ostream<CharType, Traits>,
+                       public basic_efilebuf<CharType, Traits>
 {
-  using basic_efilebuf<CharType,Traits>::is_open;
+  using basic_efilebuf<CharType, Traits>::is_open;
 
-  public:
-  typedef typename basic_efilebuf<CharType, Traits>::internal_buffer_type internal_buffer_type;
-  typedef std::basic_ostream<CharType,Traits> internal_stream_type;
+public:
+  typedef typename basic_efilebuf<CharType, Traits>::internal_buffer_type
+    internal_buffer_type;
+  typedef std::basic_ostream<CharType, Traits> internal_stream_type;
 
-  basic_ofstream() : internal_stream_type(new internal_buffer_type())
+  basic_ofstream()
+    : internal_stream_type(new internal_buffer_type())
   {
-    this->buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
+    this->buf_ =
+      static_cast<internal_buffer_type*>(internal_stream_type::rdbuf());
   }
-  explicit basic_ofstream(char const *file_name,std::ios_base::openmode mode = std::ios_base::out) :
-  internal_stream_type(new internal_buffer_type())
+  explicit basic_ofstream(char const* file_name,
+                          std::ios_base::openmode mode = std::ios_base::out)
+    : internal_stream_type(new internal_buffer_type())
   {
-    this->buf_ = static_cast<internal_buffer_type *>(internal_stream_type::rdbuf());
-    open(file_name,mode);
+    this->buf_ =
+      static_cast<internal_buffer_type*>(internal_stream_type::rdbuf());
+    open(file_name, mode);
   }
-  void open(char const *file_name,std::ios_base::openmode mode = std::ios_base::out)
+  void open(char const* file_name,
+            std::ios_base::openmode mode = std::ios_base::out)
   {
     mode = mode | std::ios_base::out;
     this->_set_state(this->_open(file_name, mode), this, this);
   }
 
-  void close()
-  {
-    this->_set_state(this->_close(), this, this);
-  }
+  void close() { this->_set_state(this->_close(), this, this); }
 
-  internal_buffer_type *rdbuf() const
-  {
-    return this->buf_;
-  }
+  internal_buffer_type* rdbuf() const { return this->buf_; }
 
-  ~basic_ofstream() @KWSYS_NAMESPACE at _FStream_NOEXCEPT
-  {
-    close();
-  }
+  ~basic_ofstream() @KWSYS_NAMESPACE at _FStream_NOEXCEPT { close(); }
 };
 
-  typedef basic_ifstream<char> ifstream;
-  typedef basic_ofstream<char> ofstream;
+typedef basic_ifstream<char> ifstream;
+typedef basic_ofstream<char> ofstream;
 
-# undef @KWSYS_NAMESPACE at _FStream_NOEXCEPT
+#undef @KWSYS_NAMESPACE at _FStream_NOEXCEPT
 #else
-  using std::ofstream;
-  using std::ifstream;
+using std::ofstream;
+using std::ifstream;
 #endif
 
-  namespace FStream
-  {
-    enum BOM
-    {
-      BOM_None,
-      BOM_UTF8,
-      BOM_UTF16BE,
-      BOM_UTF16LE,
-      BOM_UTF32BE,
-      BOM_UTF32LE
-    };
-
-    // Read a BOM, if one exists.
-    // If a BOM exists, the stream is advanced to after the BOM.
-    // This function requires a seekable stream (but not a relative
-    // seekable stream).
-    BOM ReadBOM(std::istream& in);
-  }
+namespace FStream {
+enum BOM
+{
+  BOM_None,
+  BOM_UTF8,
+  BOM_UTF16BE,
+  BOM_UTF16LE,
+  BOM_UTF32BE,
+  BOM_UTF32LE
+};
+
+// Read a BOM, if one exists.
+// If a BOM exists, the stream is advanced to after the BOM.
+// This function requires a seekable stream (but not a relative
+// seekable stream).
+BOM ReadBOM(std::istream& in);
+}
 }
 
 #endif
diff --git a/Source/kwsys/Glob.cxx b/Source/kwsys/Glob.cxx
index 9d63459..fa8760d 100644
--- a/Source/kwsys/Glob.cxx
+++ b/Source/kwsys/Glob.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(Glob.hxx)
 
@@ -21,30 +12,29 @@
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "Glob.hxx.in"
-# include "Directory.hxx.in"
-# include "Configure.hxx.in"
-# include "RegularExpression.hxx.in"
-# include "SystemTools.hxx.in"
+#include "Configure.hxx.in"
+#include "Directory.hxx.in"
+#include "Glob.hxx.in"
+#include "RegularExpression.hxx.in"
+#include "SystemTools.hxx.in"
 #endif
 
+#include <algorithm>
 #include <string>
 #include <vector>
-#include <algorithm>
 
 #include <ctype.h>
 #include <stdio.h>
 #include <string.h>
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
 #if defined(_WIN32) || defined(__APPLE__) || defined(__CYGWIN__)
 // On Windows and apple, no difference between lower and upper case
-# define KWSYS_GLOB_CASE_INDEPENDENT
+#define KWSYS_GLOB_CASE_INDEPENDENT
 #endif
 
 #if defined(_WIN32) || defined(__CYGWIN__)
 // Handle network paths
-# define KWSYS_GLOB_SUPPORT_NETWORK_PATHS
+#define KWSYS_GLOB_SUPPORT_NETWORK_PATHS
 #endif
 
 //----------------------------------------------------------------------------
@@ -63,8 +53,8 @@ Glob::Glob()
   this->Relative = "";
 
   this->RecurseThroughSymlinks = true;
-    // RecurseThroughSymlinks is true by default for backwards compatibility,
-    // not because it's a good idea...
+  // RecurseThroughSymlinks is true by default for backwards compatibility,
+  // not because it's a good idea...
   this->FollowedSymlinkCount = 0;
 
   // Keep separate variables for directory listing for back compatibility
@@ -86,69 +76,55 @@ std::vector<std::string>& Glob::GetFiles()
 
 //----------------------------------------------------------------------------
 std::string Glob::PatternToRegex(const std::string& pattern,
-                                       bool require_whole_string,
-                                       bool preserve_case)
+                                 bool require_whole_string, bool preserve_case)
 {
   // Incrementally build the regular expression from the pattern.
-  std::string regex = require_whole_string? "^" : "";
+  std::string regex = require_whole_string ? "^" : "";
   std::string::const_iterator pattern_first = pattern.begin();
   std::string::const_iterator pattern_last = pattern.end();
-  for(std::string::const_iterator i = pattern_first;
-      i != pattern_last; ++i)
-    {
+  for (std::string::const_iterator i = pattern_first; i != pattern_last; ++i) {
     int c = *i;
-    if(c == '*')
-      {
+    if (c == '*') {
       // A '*' (not between brackets) matches any string.
       // We modify this to not match slashes since the orignal glob
       // pattern documentation was meant for matching file name
       // components separated by slashes.
       regex += "[^/]*";
-      }
-    else if(c == '?')
-      {
+    } else if (c == '?') {
       // A '?' (not between brackets) matches any single character.
       // We modify this to not match slashes since the orignal glob
       // pattern documentation was meant for matching file name
       // components separated by slashes.
       regex += "[^/]";
-      }
-    else if(c == '[')
-      {
+    } else if (c == '[') {
       // Parse out the bracket expression.  It begins just after the
       // opening character.
-      std::string::const_iterator bracket_first = i+1;
+      std::string::const_iterator bracket_first = i + 1;
       std::string::const_iterator bracket_last = bracket_first;
 
       // The first character may be complementation '!' or '^'.
-      if(bracket_last != pattern_last &&
-         (*bracket_last == '!' || *bracket_last == '^'))
-        {
+      if (bracket_last != pattern_last &&
+          (*bracket_last == '!' || *bracket_last == '^')) {
         ++bracket_last;
-        }
+      }
 
       // If the next character is a ']' it is included in the brackets
       // because the bracket string may not be empty.
-      if(bracket_last != pattern_last && *bracket_last == ']')
-        {
+      if (bracket_last != pattern_last && *bracket_last == ']') {
         ++bracket_last;
-        }
+      }
 
       // Search for the closing ']'.
-      while(bracket_last != pattern_last && *bracket_last != ']')
-        {
+      while (bracket_last != pattern_last && *bracket_last != ']') {
         ++bracket_last;
-        }
+      }
 
       // Check whether we have a complete bracket string.
-      if(bracket_last == pattern_last)
-        {
+      if (bracket_last == pattern_last) {
         // The bracket string did not end, so it was opened simply by
         // a '[' that is supposed to be matched literally.
         regex += "\\[";
-        }
-      else
-        {
+      } else {
         // Convert the bracket string to its regex equivalent.
         std::string::const_iterator k = bracket_first;
 
@@ -156,97 +132,81 @@ std::string Glob::PatternToRegex(const std::string& pattern,
         regex += "[";
 
         // A regex range complement uses '^' instead of '!'.
-        if(k != bracket_last && *k == '!')
-          {
+        if (k != bracket_last && *k == '!') {
           regex += "^";
           ++k;
-          }
+        }
 
         // Convert the remaining characters.
-        for(; k != bracket_last; ++k)
-          {
+        for (; k != bracket_last; ++k) {
           // Backslashes must be escaped.
-          if(*k == '\\')
-            {
+          if (*k == '\\') {
             regex += "\\";
-            }
+          }
 
           // Store this character.
           regex += *k;
-          }
+        }
 
         // Close the regex block.
         regex += "]";
 
         // Jump to the end of the bracket string.
         i = bracket_last;
-        }
       }
-    else
-      {
+    } else {
       // A single character matches itself.
       int ch = c;
-      if(!(('a' <= ch && ch <= 'z') ||
-           ('A' <= ch && ch <= 'Z') ||
-           ('0' <= ch && ch <= '9')))
-        {
+      if (!(('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
+            ('0' <= ch && ch <= '9'))) {
         // Escape the non-alphanumeric character.
         regex += "\\";
-        }
+      }
 #if defined(KWSYS_GLOB_CASE_INDEPENDENT)
-      else
-        {
+      else {
         // On case-insensitive systems file names are converted to lower
         // case before matching.
-        if(!preserve_case)
-          {
+        if (!preserve_case) {
           ch = tolower(ch);
-          }
         }
+      }
 #endif
       (void)preserve_case;
       // Store the character.
       regex.append(1, static_cast<char>(ch));
-      }
     }
+  }
 
-  if(require_whole_string)
-    {
+  if (require_whole_string) {
     regex += "$";
-    }
+  }
   return regex;
 }
 
 //----------------------------------------------------------------------------
 bool Glob::RecurseDirectory(std::string::size_type start,
-  const std::string& dir, GlobMessages* messages)
+                            const std::string& dir, GlobMessages* messages)
 {
   kwsys::Directory d;
-  if ( !d.Load(dir) )
-    {
+  if (!d.Load(dir)) {
     return true;
-    }
+  }
   unsigned long cc;
   std::string realname;
   std::string fname;
-  for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )
-    {
+  for (cc = 0; cc < d.GetNumberOfFiles(); cc++) {
     fname = d.GetFile(cc);
-    if ( fname == "." || fname == ".." )
-      {
+    if (fname == "." || fname == "..") {
       continue;
-      }
+    }
 
-    if ( start == 0 )
-      {
+    if (start == 0) {
       realname = dir + fname;
-      }
-    else
-      {
+    } else {
       realname = dir + "/" + fname;
-      }
+    }
 
-#if defined( KWSYS_GLOB_CASE_INDEPENDENT )
+#if defined(KWSYS_GLOB_CASE_INDEPENDENT)
     // On Windows and apple, no difference between lower and upper case
     fname = kwsys::SystemTools::LowerCase(fname);
 #endif
@@ -254,157 +214,127 @@ bool Glob::RecurseDirectory(std::string::size_type start,
     bool isDir = kwsys::SystemTools::FileIsDirectory(realname);
     bool isSymLink = kwsys::SystemTools::FileIsSymlink(realname);
 
-    if ( isDir && (!isSymLink || this->RecurseThroughSymlinks) )
-      {
-      if (isSymLink)
-        {
+    if (isDir && (!isSymLink || this->RecurseThroughSymlinks)) {
+      if (isSymLink) {
         ++this->FollowedSymlinkCount;
         std::string realPathErrorMessage;
-        std::string canonicalPath(SystemTools::GetRealPath(dir,
-            &realPathErrorMessage));
+        std::string canonicalPath(
+          SystemTools::GetRealPath(dir, &realPathErrorMessage));
 
-        if(!realPathErrorMessage.empty())
-          {
-          if(messages)
-            {
+        if (!realPathErrorMessage.empty()) {
+          if (messages) {
             messages->push_back(Message(
-                Glob::error, "Canonical path generation from path '"
-                + dir + "' failed! Reason: '" + realPathErrorMessage + "'"));
-            }
-          return false;
+              Glob::error, "Canonical path generation from path '" + dir +
+                "' failed! Reason: '" + realPathErrorMessage + "'"));
           }
+          return false;
+        }
 
-        if(std::find(this->VisitedSymlinks.begin(),
-            this->VisitedSymlinks.end(),
-            canonicalPath) == this->VisitedSymlinks.end())
-          {
-          if(this->RecurseListDirs)
-            {
+        if (std::find(this->VisitedSymlinks.begin(),
+                      this->VisitedSymlinks.end(),
+                      canonicalPath) == this->VisitedSymlinks.end()) {
+          if (this->RecurseListDirs) {
             // symlinks are treated as directories
             this->AddFile(this->Internals->Files, realname);
-            }
+          }
 
           this->VisitedSymlinks.push_back(canonicalPath);
-          if(!this->RecurseDirectory(start+1, realname, messages))
-            {
+          if (!this->RecurseDirectory(start + 1, realname, messages)) {
             this->VisitedSymlinks.pop_back();
 
             return false;
-            }
-          this->VisitedSymlinks.pop_back();
           }
+          this->VisitedSymlinks.pop_back();
+        }
         // else we have already visited this symlink - prevent cyclic recursion
-        else if(messages)
-          {
+        else if (messages) {
           std::string message;
-          for(std::vector<std::string>::const_iterator
-                pathIt = std::find(this->VisitedSymlinks.begin(),
-                                         this->VisitedSymlinks.end(),
-                                         canonicalPath);
-              pathIt != this->VisitedSymlinks.end(); ++pathIt)
-            {
+          for (std::vector<std::string>::const_iterator pathIt =
+                 std::find(this->VisitedSymlinks.begin(),
+                           this->VisitedSymlinks.end(), canonicalPath);
+               pathIt != this->VisitedSymlinks.end(); ++pathIt) {
             message += *pathIt + "\n";
-            }
+          }
           message += canonicalPath + "/" + fname;
           messages->push_back(Message(Glob::cyclicRecursion, message));
-          }
         }
-      else
-        {
-        if(this->RecurseListDirs)
-          {
+      } else {
+        if (this->RecurseListDirs) {
           this->AddFile(this->Internals->Files, realname);
-          }
-        if(!this->RecurseDirectory(start+1, realname, messages))
-          {
+        }
+        if (!this->RecurseDirectory(start + 1, realname, messages)) {
           return false;
-          }
         }
       }
-    else
-      {
-      if ( !this->Internals->Expressions.empty() &&
-           this->Internals->Expressions.rbegin()->find(fname) )
-        {
+    } else {
+      if (!this->Internals->Expressions.empty() &&
+          this->Internals->Expressions.rbegin()->find(fname)) {
         this->AddFile(this->Internals->Files, realname);
-        }
       }
     }
+  }
 
   return true;
 }
 
 //----------------------------------------------------------------------------
 void Glob::ProcessDirectory(std::string::size_type start,
-  const std::string& dir, GlobMessages* messages)
+                            const std::string& dir, GlobMessages* messages)
 {
-  //std::cout << "ProcessDirectory: " << dir << std::endl;
-  bool last = ( start == this->Internals->Expressions.size()-1 );
-  if ( last && this->Recurse )
-    {
+  // std::cout << "ProcessDirectory: " << dir << std::endl;
+  bool last = (start == this->Internals->Expressions.size() - 1);
+  if (last && this->Recurse) {
     this->RecurseDirectory(start, dir, messages);
     return;
-    }
+  }
 
-  if ( start >= this->Internals->Expressions.size() )
-    {
+  if (start >= this->Internals->Expressions.size()) {
     return;
-    }
+  }
 
   kwsys::Directory d;
-  if ( !d.Load(dir) )
-    {
+  if (!d.Load(dir)) {
     return;
-    }
+  }
   unsigned long cc;
   std::string realname;
   std::string fname;
-  for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )
-    {
+  for (cc = 0; cc < d.GetNumberOfFiles(); cc++) {
     fname = d.GetFile(cc);
-    if ( fname == "." || fname == ".." )
-      {
+    if (fname == "." || fname == "..") {
       continue;
-      }
+    }
 
-    if ( start == 0 )
-      {
+    if (start == 0) {
       realname = dir + fname;
-      }
-    else
-      {
+    } else {
       realname = dir + "/" + fname;
-      }
+    }
 
 #if defined(KWSYS_GLOB_CASE_INDEPENDENT)
     // On case-insensitive file systems convert to lower case for matching.
     fname = kwsys::SystemTools::LowerCase(fname);
 #endif
 
-    //std::cout << "Look at file: " << fname << std::endl;
-    //std::cout << "Match: "
+    // std::cout << "Look at file: " << fname << std::endl;
+    // std::cout << "Match: "
     // << this->Internals->TextExpressions[start].c_str() << std::endl;
-    //std::cout << "Real name: " << realname << std::endl;
+    // std::cout << "Real name: " << realname << std::endl;
 
-    if( (!last && !kwsys::SystemTools::FileIsDirectory(realname))
-      || (!this->ListDirs && last &&
-          kwsys::SystemTools::FileIsDirectory(realname)) )
-      {
+    if ((!last && !kwsys::SystemTools::FileIsDirectory(realname)) ||
+        (!this->ListDirs && last &&
+         kwsys::SystemTools::FileIsDirectory(realname))) {
       continue;
-      }
+    }
 
-    if ( this->Internals->Expressions[start].find(fname) )
-      {
-      if ( last )
-        {
+    if (this->Internals->Expressions[start].find(fname)) {
+      if (last) {
         this->AddFile(this->Internals->Files, realname);
-        }
-      else
-        {
-        this->ProcessDirectory(start+1, realname, messages);
-        }
+      } else {
+        this->ProcessDirectory(start + 1, realname, messages);
       }
     }
+  }
 }
 
 //----------------------------------------------------------------------------
@@ -417,99 +347,76 @@ bool Glob::FindFiles(const std::string& inexpr, GlobMessages* messages)
   this->Internals->Expressions.clear();
   this->Internals->Files.clear();
 
-  if ( !kwsys::SystemTools::FileIsFullPath(expr) )
-    {
+  if (!kwsys::SystemTools::FileIsFullPath(expr)) {
     expr = kwsys::SystemTools::GetCurrentWorkingDirectory();
     expr += "/" + inexpr;
-    }
+  }
   std::string fexpr = expr;
 
   std::string::size_type skip = 0;
   std::string::size_type last_slash = 0;
-  for ( cc = 0; cc < expr.size(); cc ++ )
-    {
-    if ( cc > 0 && expr[cc] == '/' && expr[cc-1] != '\\' )
-      {
+  for (cc = 0; cc < expr.size(); cc++) {
+    if (cc > 0 && expr[cc] == '/' && expr[cc - 1] != '\\') {
       last_slash = cc;
-      }
-    if ( cc > 0 &&
-      (expr[cc] == '[' || expr[cc] == '?' || expr[cc] == '*') &&
-      expr[cc-1] != '\\' )
-      {
+    }
+    if (cc > 0 && (expr[cc] == '[' || expr[cc] == '?' || expr[cc] == '*') &&
+        expr[cc - 1] != '\\') {
       break;
-      }
     }
-  if ( last_slash > 0 )
-    {
-    //std::cout << "I can skip: " << fexpr.substr(0, last_slash)
+  }
+  if (last_slash > 0) {
+    // std::cout << "I can skip: " << fexpr.substr(0, last_slash)
     // << std::endl;
     skip = last_slash;
-    }
-  if ( skip == 0 )
-    {
-#if defined( KWSYS_GLOB_SUPPORT_NETWORK_PATHS )
+  }
+  if (skip == 0) {
+#if defined(KWSYS_GLOB_SUPPORT_NETWORK_PATHS)
     // Handle network paths
-    if ( expr[0] == '/' && expr[1] == '/' )
-      {
+    if (expr[0] == '/' && expr[1] == '/') {
       int cnt = 0;
-      for ( cc = 2; cc < expr.size(); cc ++ )
-        {
-        if ( expr[cc] == '/' )
-          {
-          cnt ++;
-          if ( cnt == 2 )
-            {
+      for (cc = 2; cc < expr.size(); cc++) {
+        if (expr[cc] == '/') {
+          cnt++;
+          if (cnt == 2) {
             break;
-            }
           }
         }
-      skip = int(cc + 1);
       }
-    else
+      skip = int(cc + 1);
+    } else
 #endif
       // Handle drive letters on Windows
-      if ( expr[1] == ':' && expr[0] != '/' )
-        {
-        skip = 2;
-        }
+      if (expr[1] == ':' && expr[0] != '/') {
+      skip = 2;
     }
+  }
 
-  if ( skip > 0 )
-    {
+  if (skip > 0) {
     expr = expr.substr(skip);
-    }
+  }
 
   cexpr = "";
-  for ( cc = 0; cc < expr.size(); cc ++ )
-    {
+  for (cc = 0; cc < expr.size(); cc++) {
     int ch = expr[cc];
-    if ( ch == '/' )
-      {
-      if ( !cexpr.empty() )
-        {
+    if (ch == '/') {
+      if (!cexpr.empty()) {
         this->AddExpression(cexpr);
-        }
-      cexpr = "";
       }
-    else
-      {
+      cexpr = "";
+    } else {
       cexpr.append(1, static_cast<char>(ch));
-      }
     }
-  if ( !cexpr.empty() )
-    {
+  }
+  if (!cexpr.empty()) {
     this->AddExpression(cexpr);
-    }
+  }
 
   // Handle network paths
-  if ( skip > 0 )
-    {
+  if (skip > 0) {
     this->ProcessDirectory(0, fexpr.substr(0, skip) + "/", messages);
-    }
-  else
-    {
+  } else {
     this->ProcessDirectory(0, "/", messages);
-    }
+  }
   return true;
 }
 
@@ -517,43 +424,36 @@ bool Glob::FindFiles(const std::string& inexpr, GlobMessages* messages)
 void Glob::AddExpression(const std::string& expr)
 {
   this->Internals->Expressions.push_back(
-    kwsys::RegularExpression(
-      this->PatternToRegex(expr)));
+    kwsys::RegularExpression(this->PatternToRegex(expr)));
 }
 
 //----------------------------------------------------------------------------
 void Glob::SetRelative(const char* dir)
 {
-  if ( !dir )
-    {
+  if (!dir) {
     this->Relative = "";
     return;
-    }
+  }
   this->Relative = dir;
 }
 
 //----------------------------------------------------------------------------
 const char* Glob::GetRelative()
 {
-  if ( this->Relative.empty() )
-    {
+  if (this->Relative.empty()) {
     return 0;
-    }
+  }
   return this->Relative.c_str();
 }
 
 //----------------------------------------------------------------------------
 void Glob::AddFile(std::vector<std::string>& files, const std::string& file)
 {
-  if ( !this->Relative.empty() )
-    {
+  if (!this->Relative.empty()) {
     files.push_back(kwsys::SystemTools::RelativePath(this->Relative, file));
-    }
-  else
-    {
+  } else {
     files.push_back(file);
-    }
+  }
 }
 
 } // namespace KWSYS_NAMESPACE
-
diff --git a/Source/kwsys/Glob.hxx.in b/Source/kwsys/Glob.hxx.in
index ffee9ca..bd4a176 100644
--- a/Source/kwsys/Glob.hxx.in
+++ b/Source/kwsys/Glob.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _Glob_hxx
 #define @KWSYS_NAMESPACE at _Glob_hxx
 
@@ -18,8 +9,7 @@
 #include <string>
 #include <vector>
 
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 
 class GlobInternals;
 
@@ -46,31 +36,33 @@ public:
     MessageType type;
     std::string content;
 
-    Message(MessageType t, const std::string& c) :
-      type(t),
-      content(c)
-    {}
-    Message(const Message& msg) :
-      type(msg.type),
-      content(msg.content)
-    {}
+    Message(MessageType t, const std::string& c)
+      : type(t)
+      , content(c)
+    {
+    }
+    Message(const Message& msg)
+      : type(msg.type)
+      , content(msg.content)
+    {
+    }
     Message& operator=(Message const& msg)
-      {
+    {
       this->type = msg.type;
       this->content = msg.content;
       return *this;
-      }
+    }
   };
 
   typedef std::vector<Message> GlobMessages;
   typedef std::vector<Message>::iterator GlobMessagesIterator;
+
 public:
   Glob();
   ~Glob();
 
   //! Find all files that match the pattern.
-  bool FindFiles(const std::string& inexpr,
-    GlobMessages* messages = 0);
+  bool FindFiles(const std::string& inexpr, GlobMessages* messages = 0);
 
   //! Return the list of files that matched.
   std::vector<std::string>& GetFiles();
@@ -103,29 +95,27 @@ public:
       whole strings, but may be disabled to support concatenating
       expressions more easily (regex1|regex2|etc).  */
   static std::string PatternToRegex(const std::string& pattern,
-                                          bool require_whole_string = true,
-                                          bool preserve_case = false);
+                                    bool require_whole_string = true,
+                                    bool preserve_case = false);
 
   /** Getters and setters for enabling and disabling directory
       listing in recursive and non recursive globbing mode.
       If listing is enabled in recursive mode it also lists
       directory symbolic links even if follow symlinks is enabled. */
-  void SetListDirs(bool list) { this->ListDirs=list; }
+  void SetListDirs(bool list) { this->ListDirs = list; }
   bool GetListDirs() const { return this->ListDirs; }
-  void SetRecurseListDirs(bool list) { this->RecurseListDirs=list; }
+  void SetRecurseListDirs(bool list) { this->RecurseListDirs = list; }
   bool GetRecurseListDirs() const { return this->RecurseListDirs; }
 
 protected:
   //! Process directory
-  void ProcessDirectory(std::string::size_type start,
-    const std::string& dir,
-    GlobMessages* messages);
+  void ProcessDirectory(std::string::size_type start, const std::string& dir,
+                        GlobMessages* messages);
 
   //! Process last directory, but only when recurse flags is on. That is
   // effectively like saying: /path/to/file/**/file
-  bool RecurseDirectory(std::string::size_type start,
-    const std::string& dir,
-    GlobMessages* messages);
+  bool RecurseDirectory(std::string::size_type start, const std::string& dir,
+                        GlobMessages* messages);
 
   //! Add regular expression
   void AddExpression(const std::string& expr);
@@ -143,8 +133,8 @@ protected:
   bool RecurseListDirs;
 
 private:
-  Glob(const Glob&);  // Not implemented.
-  void operator=(const Glob&);  // Not implemented.
+  Glob(const Glob&);           // Not implemented.
+  void operator=(const Glob&); // Not implemented.
 };
 
 } // namespace @KWSYS_NAMESPACE@
diff --git a/Source/kwsys/IOStream.cxx b/Source/kwsys/IOStream.cxx
index 81c6a73..01ada1f 100644
--- a/Source/kwsys/IOStream.cxx
+++ b/Source/kwsys/IOStream.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(Configure.hxx)
 
@@ -19,24 +10,23 @@
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "Configure.hxx.in"
-# include "IOStream.hxx.in"
+#include "Configure.hxx.in"
+#include "IOStream.hxx.in"
 #endif
 
 // Implement the rest of this file only if it is needed.
 #if KWSYS_IOS_NEED_OPERATORS_LL
 
-# include <stdio.h>  // sscanf, sprintf
-# include <string.h> // memchr
+#include <stdio.h>  // sscanf, sprintf
+#include <string.h> // memchr
 
-# if defined(_MAX_INT_DIG)
-#  define KWSYS_IOS_INT64_MAX_DIG _MAX_INT_DIG
-# else
-#  define KWSYS_IOS_INT64_MAX_DIG 32
-# endif
+#if defined(_MAX_INT_DIG)
+#define KWSYS_IOS_INT64_MAX_DIG _MAX_INT_DIG
+#else
+#define KWSYS_IOS_INT64_MAX_DIG 32
+#endif
 
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
 
 // Scan an input stream for an integer value.
 static int IOStreamScanStream(std::istream& is, char* buffer)
@@ -46,74 +36,68 @@ static int IOStreamScanStream(std::istream& is, char* buffer)
   char* end = buffer + KWSYS_IOS_INT64_MAX_DIG - 1;
 
   // Look for leading sign.
-  if(is.peek() == '+') { *out++ = '+'; is.ignore(); }
-  else if(is.peek() == '-') { *out++ = '-'; is.ignore(); }
+  if (is.peek() == '+') {
+    *out++ = '+';
+    is.ignore();
+  } else if (is.peek() == '-') {
+    *out++ = '-';
+    is.ignore();
+  }
 
   // Determine the base.  If not specified in the stream, try to
   // detect it from the input.  A leading 0x means hex, and a leading
   // 0 alone means octal.
   int base = 0;
   int flags = is.flags() & std::ios_base::basefield;
-  if(flags == std::ios_base::oct) { base = 8; }
-  else if(flags == std::ios_base::dec) { base = 10; }
-  else if(flags == std::ios_base::hex) { base = 16; }
+  if (flags == std::ios_base::oct) {
+    base = 8;
+  } else if (flags == std::ios_base::dec) {
+    base = 10;
+  } else if (flags == std::ios_base::hex) {
+    base = 16;
+  }
   bool foundDigit = false;
   bool foundNonZero = false;
-  if(is.peek() == '0')
-    {
+  if (is.peek() == '0') {
     foundDigit = true;
     is.ignore();
-    if((is.peek() == 'x' || is.peek() == 'X') && (base == 0 || base == 16))
-      {
+    if ((is.peek() == 'x' || is.peek() == 'X') && (base == 0 || base == 16)) {
       base = 16;
       foundDigit = false;
       is.ignore();
-      }
-    else if (base == 0)
-      {
+    } else if (base == 0) {
       base = 8;
-      }
     }
+  }
 
   // Determine the range of digits allowed for this number.
   const char* digits = "0123456789abcdefABCDEF";
   int maxDigitIndex = 10;
-  if(base == 8)
-    {
+  if (base == 8) {
     maxDigitIndex = 8;
-    }
-  else if(base == 16)
-    {
-    maxDigitIndex = 10+6+6;
-    }
+  } else if (base == 16) {
+    maxDigitIndex = 10 + 6 + 6;
+  }
 
   // Scan until an invalid digit is found.
-  for(;is.peek() != EOF; is.ignore())
-    {
-    if(memchr(digits, *out = (char)is.peek(), maxDigitIndex) != 0)
-      {
-      if((foundNonZero || *out != '0') && out < end)
-        {
+  for (; is.peek() != EOF; is.ignore()) {
+    if (memchr(digits, *out = (char)is.peek(), maxDigitIndex) != 0) {
+      if ((foundNonZero || *out != '0') && out < end) {
         ++out;
         foundNonZero = true;
-        }
-      foundDigit = true;
       }
-    else
-      {
+      foundDigit = true;
+    } else {
       break;
-      }
     }
+  }
 
   // Correct the buffer contents for degenerate cases.
-  if(foundDigit && !foundNonZero)
-    {
+  if (foundDigit && !foundNonZero) {
     *out++ = '0';
-    }
-  else if (!foundDigit)
-    {
+  } else if (!foundDigit) {
     out = buffer;
-    }
+  }
 
   // Terminate the string in the buffer.
   *out = '\0';
@@ -123,44 +107,54 @@ static int IOStreamScanStream(std::istream& is, char* buffer)
 
 // Read an integer value from an input stream.
 template <class T>
-std::istream&
-IOStreamScanTemplate(std::istream& is, T& value, char type)
+std::istream& IOStreamScanTemplate(std::istream& is, T& value, char type)
 {
   int state = std::ios_base::goodbit;
 
   // Skip leading whitespace.
   std::istream::sentry okay(is);
 
-  if(okay)
-    {
+  if (okay) {
     try {
-    // Copy the string to a buffer and construct the format string.
-    char buffer[KWSYS_IOS_INT64_MAX_DIG];
-#   if defined(_MSC_VER)
-    char format[] = "%I64_";
-    const int typeIndex = 4;
-#   else
-    char format[] = "%ll_";
-    const int typeIndex = 3;
-#   endif
-    switch(IOStreamScanStream(is, buffer))
-      {
-      case 8: format[typeIndex] = 'o'; break;
-      case 0: // Default to decimal if not told otherwise.
-      case 10: format[typeIndex] = type; break;
-      case 16: format[typeIndex] = 'x'; break;
+      // Copy the string to a buffer and construct the format string.
+      char buffer[KWSYS_IOS_INT64_MAX_DIG];
+#if defined(_MSC_VER)
+      char format[] = "%I64_";
+      const int typeIndex = 4;
+#else
+      char format[] = "%ll_";
+      const int typeIndex = 3;
+#endif
+      switch (IOStreamScanStream(is, buffer)) {
+        case 8:
+          format[typeIndex] = 'o';
+          break;
+        case 0: // Default to decimal if not told otherwise.
+        case 10:
+          format[typeIndex] = type;
+          break;
+        case 16:
+          format[typeIndex] = 'x';
+          break;
       };
 
-    // Use sscanf to parse the number from the buffer.
-    T result;
-    int success = (sscanf(buffer, format, &result) == 1)?1:0;
+      // Use sscanf to parse the number from the buffer.
+      T result;
+      int success = (sscanf(buffer, format, &result) == 1) ? 1 : 0;
 
-    // Set flags for resulting state.
-    if(is.peek() == EOF) { state |= std::ios_base::eofbit; }
-    if(!success) { state |= std::ios_base::failbit; }
-    else { value = result; }
-    } catch(...) { state |= std::ios_base::badbit; }
+      // Set flags for resulting state.
+      if (is.peek() == EOF) {
+        state |= std::ios_base::eofbit;
+      }
+      if (!success) {
+        state |= std::ios_base::failbit;
+      } else {
+        value = result;
+      }
+    } catch (...) {
+      state |= std::ios_base::badbit;
     }
+  }
 
   is.setstate(std::ios_base::iostate(state));
   return is;
@@ -168,42 +162,54 @@ IOStreamScanTemplate(std::istream& is, T& value, char type)
 
 // Print an integer value to an output stream.
 template <class T>
-std::ostream&
-IOStreamPrintTemplate(std::ostream& os, T value, char type)
+std::ostream& IOStreamPrintTemplate(std::ostream& os, T value, char type)
 {
   std::ostream::sentry okay(os);
-  if(okay)
-    {
+  if (okay) {
     try {
-    // Construct the format string.
-    char format[8];
-    char* f = format;
-    *f++ = '%';
-    if(os.flags() & std::ios_base::showpos) { *f++ = '+'; }
-    if(os.flags() & std::ios_base::showbase) { *f++ = '#'; }
-#   if defined(_MSC_VER)
-    *f++ = 'I'; *f++ = '6'; *f++ = '4';
-#   else
-    *f++ = 'l'; *f++ = 'l';
-#   endif
-    long bflags = os.flags() & std::ios_base::basefield;
-    if(bflags == std::ios_base::oct) { *f++ = 'o'; }
-    else if(bflags != std::ios_base::hex) { *f++ = type; }
-    else if(os.flags() & std::ios_base::uppercase) { *f++ = 'X'; }
-    else { *f++ = 'x'; }
-    *f = '\0';
-
-    // Use sprintf to print to a buffer and then write the
-    // buffer to the stream.
-    char buffer[2*KWSYS_IOS_INT64_MAX_DIG];
-    sprintf(buffer, format, value);
-    os << buffer;
-    } catch(...) { os.clear(os.rdstate() | std::ios_base::badbit); }
+      // Construct the format string.
+      char format[8];
+      char* f = format;
+      *f++ = '%';
+      if (os.flags() & std::ios_base::showpos) {
+        *f++ = '+';
+      }
+      if (os.flags() & std::ios_base::showbase) {
+        *f++ = '#';
+      }
+#if defined(_MSC_VER)
+      *f++ = 'I';
+      *f++ = '6';
+      *f++ = '4';
+#else
+      *f++ = 'l';
+      *f++ = 'l';
+#endif
+      long bflags = os.flags() & std::ios_base::basefield;
+      if (bflags == std::ios_base::oct) {
+        *f++ = 'o';
+      } else if (bflags != std::ios_base::hex) {
+        *f++ = type;
+      } else if (os.flags() & std::ios_base::uppercase) {
+        *f++ = 'X';
+      } else {
+        *f++ = 'x';
+      }
+      *f = '\0';
+
+      // Use sprintf to print to a buffer and then write the
+      // buffer to the stream.
+      char buffer[2 * KWSYS_IOS_INT64_MAX_DIG];
+      sprintf(buffer, format, value);
+      os << buffer;
+    } catch (...) {
+      os.clear(os.rdstate() | std::ios_base::badbit);
     }
+  }
   return os;
 }
 
-# if !KWSYS_IOS_HAS_ISTREAM_LONG_LONG
+#if !KWSYS_IOS_HAS_ISTREAM_LONG_LONG
 // Implement input stream operator for IOStreamSLL.
 std::istream& IOStreamScan(std::istream& is, IOStreamSLL& value)
 {
@@ -215,9 +221,9 @@ std::istream& IOStreamScan(std::istream& is, IOStreamULL& value)
 {
   return IOStreamScanTemplate(is, value, 'u');
 }
-# endif
+#endif
 
-# if !KWSYS_IOS_HAS_OSTREAM_LONG_LONG
+#if !KWSYS_IOS_HAS_OSTREAM_LONG_LONG
 // Implement output stream operator for IOStreamSLL.
 std::ostream& IOStreamPrint(std::ostream& os, IOStreamSLL value)
 {
@@ -229,14 +235,13 @@ std::ostream& IOStreamPrint(std::ostream& os, IOStreamULL value)
 {
   return IOStreamPrintTemplate(os, value, 'u');
 }
-# endif
+#endif
 
 } // namespace KWSYS_NAMESPACE
 
 #else
 
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
 
 // Create one public symbol in this object file to avoid warnings from
 // archivers.
diff --git a/Source/kwsys/IOStream.hxx.in b/Source/kwsys/IOStream.hxx.in
index c101909..de3a2e6 100644
--- a/Source/kwsys/IOStream.hxx.in
+++ b/Source/kwsys/IOStream.hxx.in
@@ -1,136 +1,126 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _IOStream_hxx
 #define @KWSYS_NAMESPACE at _IOStream_hxx
 
 #include <iosfwd>
 
 /* Define these macros temporarily to keep the code readable.  */
-#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-# define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
+#if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
+#define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
 #endif
 
 /* Whether istream supports long long.  */
-#define @KWSYS_NAMESPACE at _IOS_HAS_ISTREAM_LONG_LONG @KWSYS_IOS_HAS_ISTREAM_LONG_LONG@
+#define @KWSYS_NAMESPACE at _IOS_HAS_ISTREAM_LONG_LONG                           \
+  @KWSYS_IOS_HAS_ISTREAM_LONG_LONG@
 
 /* Whether ostream supports long long.  */
-#define @KWSYS_NAMESPACE at _IOS_HAS_OSTREAM_LONG_LONG @KWSYS_IOS_HAS_OSTREAM_LONG_LONG@
+#define @KWSYS_NAMESPACE at _IOS_HAS_OSTREAM_LONG_LONG                           \
+  @KWSYS_IOS_HAS_OSTREAM_LONG_LONG@
 
 /* Determine whether we need to define the streaming operators for
    long long or __int64.  */
 #if @KWSYS_USE_LONG_LONG@
-# if !@KWSYS_NAMESPACE at _IOS_HAS_ISTREAM_LONG_LONG || \
-     !@KWSYS_NAMESPACE at _IOS_HAS_OSTREAM_LONG_LONG
-# define @KWSYS_NAMESPACE at _IOS_NEED_OPERATORS_LL 1
-  namespace @KWSYS_NAMESPACE@
-  {
-    typedef long long IOStreamSLL;
-    typedef unsigned long long IOStreamULL;
-  }
-# endif
+#if !@KWSYS_NAMESPACE at _IOS_HAS_ISTREAM_LONG_LONG ||                           \
+  !@KWSYS_NAMESPACE at _IOS_HAS_OSTREAM_LONG_LONG
+#define @KWSYS_NAMESPACE at _IOS_NEED_OPERATORS_LL 1
+namespace @KWSYS_NAMESPACE@ {
+typedef long long IOStreamSLL;
+typedef unsigned long long IOStreamULL;
+}
+#endif
 #elif defined(_MSC_VER) && _MSC_VER < 1300
-# define @KWSYS_NAMESPACE at _IOS_NEED_OPERATORS_LL 1
-  namespace @KWSYS_NAMESPACE@
-  {
-    typedef __int64 IOStreamSLL;
-    typedef unsigned __int64 IOStreamULL;
-  }
+#define @KWSYS_NAMESPACE at _IOS_NEED_OPERATORS_LL 1
+namespace @KWSYS_NAMESPACE@ {
+typedef __int64 IOStreamSLL;
+typedef unsigned __int64 IOStreamULL;
+}
 #endif
 #if !defined(@KWSYS_NAMESPACE at _IOS_NEED_OPERATORS_LL)
-# define @KWSYS_NAMESPACE at _IOS_NEED_OPERATORS_LL 0
+#define @KWSYS_NAMESPACE at _IOS_NEED_OPERATORS_LL 0
 #endif
 
 #if @KWSYS_NAMESPACE at _IOS_NEED_OPERATORS_LL
-# if !@KWSYS_NAMESPACE at _IOS_HAS_ISTREAM_LONG_LONG
+#if !@KWSYS_NAMESPACE at _IOS_HAS_ISTREAM_LONG_LONG
 
 /* Input stream operator implementation functions.  */
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 kwsysEXPORT std::istream& IOStreamScan(std::istream&, IOStreamSLL&);
 kwsysEXPORT std::istream& IOStreamScan(std::istream&, IOStreamULL&);
 }
 
 /* Provide input stream operator for long long.  */
-#  if !defined(@KWSYS_NAMESPACE at _IOS_NO_ISTREAM_LONG_LONG) && \
-      !defined(KWSYS_IOS_ISTREAM_LONG_LONG_DEFINED)
-#   define KWSYS_IOS_ISTREAM_LONG_LONG_DEFINED
-#   define @KWSYS_NAMESPACE at _IOS_ISTREAM_LONG_LONG_DEFINED
-inline std::istream&
-operator>>(std::istream& is, @KWSYS_NAMESPACE@::IOStreamSLL& value)
+#if !defined(@KWSYS_NAMESPACE at _IOS_NO_ISTREAM_LONG_LONG) &&                   \
+  !defined(KWSYS_IOS_ISTREAM_LONG_LONG_DEFINED)
+#define KWSYS_IOS_ISTREAM_LONG_LONG_DEFINED
+#define @KWSYS_NAMESPACE at _IOS_ISTREAM_LONG_LONG_DEFINED
+inline std::istream& operator>>(std::istream& is,
+                                @KWSYS_NAMESPACE@::IOStreamSLL& value)
 {
   return @KWSYS_NAMESPACE@::IOStreamScan(is, value);
 }
-#  endif
+#endif
 
 /* Provide input stream operator for unsigned long long.  */
-#  if !defined(@KWSYS_NAMESPACE at _IOS_NO_ISTREAM_UNSIGNED_LONG_LONG) && \
-      !defined(KWSYS_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED)
-#   define KWSYS_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED
-#   define @KWSYS_NAMESPACE at _IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED
-inline std::istream&
-operator>>(std::istream& is, @KWSYS_NAMESPACE@::IOStreamULL& value)
+#if !defined(@KWSYS_NAMESPACE at _IOS_NO_ISTREAM_UNSIGNED_LONG_LONG) &&          \
+  !defined(KWSYS_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED)
+#define KWSYS_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED
+#define @KWSYS_NAMESPACE at _IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED
+inline std::istream& operator>>(std::istream& is,
+                                @KWSYS_NAMESPACE@::IOStreamULL& value)
 {
   return @KWSYS_NAMESPACE@::IOStreamScan(is, value);
 }
-#  endif
-# endif /* !@KWSYS_NAMESPACE at _IOS_HAS_ISTREAM_LONG_LONG */
+#endif
+#endif /* !@KWSYS_NAMESPACE at _IOS_HAS_ISTREAM_LONG_LONG */
 
-# if !@KWSYS_NAMESPACE at _IOS_HAS_OSTREAM_LONG_LONG
+#if !@KWSYS_NAMESPACE at _IOS_HAS_OSTREAM_LONG_LONG
 
 /* Output stream operator implementation functions.  */
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 kwsysEXPORT std::ostream& IOStreamPrint(std::ostream&, IOStreamSLL);
 kwsysEXPORT std::ostream& IOStreamPrint(std::ostream&, IOStreamULL);
 }
 
 /* Provide output stream operator for long long.  */
-#  if !defined(@KWSYS_NAMESPACE at _IOS_NO_OSTREAM_LONG_LONG) && \
-      !defined(KWSYS_IOS_OSTREAM_LONG_LONG_DEFINED)
-#   define KWSYS_IOS_OSTREAM_LONG_LONG_DEFINED
-#   define @KWSYS_NAMESPACE at _IOS_OSTREAM_LONG_LONG_DEFINED
-inline std::ostream&
-operator<<(std::ostream& os, @KWSYS_NAMESPACE@::IOStreamSLL value)
+#if !defined(@KWSYS_NAMESPACE at _IOS_NO_OSTREAM_LONG_LONG) &&                   \
+  !defined(KWSYS_IOS_OSTREAM_LONG_LONG_DEFINED)
+#define KWSYS_IOS_OSTREAM_LONG_LONG_DEFINED
+#define @KWSYS_NAMESPACE at _IOS_OSTREAM_LONG_LONG_DEFINED
+inline std::ostream& operator<<(std::ostream& os,
+                                @KWSYS_NAMESPACE@::IOStreamSLL value)
 {
   return @KWSYS_NAMESPACE@::IOStreamPrint(os, value);
 }
-#  endif
+#endif
 
 /* Provide output stream operator for unsigned long long.  */
-#  if !defined(@KWSYS_NAMESPACE at _IOS_NO_OSTREAM_UNSIGNED_LONG_LONG) && \
-      !defined(KWSYS_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED)
-#   define KWSYS_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED
-#   define @KWSYS_NAMESPACE at _IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED
-inline std::ostream&
-operator<<(std::ostream& os, @KWSYS_NAMESPACE@::IOStreamULL value)
+#if !defined(@KWSYS_NAMESPACE at _IOS_NO_OSTREAM_UNSIGNED_LONG_LONG) &&          \
+  !defined(KWSYS_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED)
+#define KWSYS_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED
+#define @KWSYS_NAMESPACE at _IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED
+inline std::ostream& operator<<(std::ostream& os,
+                                @KWSYS_NAMESPACE@::IOStreamULL value)
 {
   return @KWSYS_NAMESPACE@::IOStreamPrint(os, value);
 }
-#  endif
-# endif /* !@KWSYS_NAMESPACE at _IOS_HAS_OSTREAM_LONG_LONG */
+#endif
+#endif /* !@KWSYS_NAMESPACE at _IOS_HAS_OSTREAM_LONG_LONG */
 #endif /* @KWSYS_NAMESPACE at _IOS_NEED_OPERATORS_LL */
 
 /* Undefine temporary macros.  */
-#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-# undef kwsysEXPORT
+#if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
+#undef kwsysEXPORT
 #endif
 
 /* If building a C++ file in kwsys itself, give the source file
    access to the macros without a configured namespace.  */
 #if defined(KWSYS_NAMESPACE)
-# define KWSYS_IOS_HAS_ISTREAM_LONG_LONG @KWSYS_NAMESPACE at _IOS_HAS_ISTREAM_LONG_LONG
-# define KWSYS_IOS_HAS_OSTREAM_LONG_LONG @KWSYS_NAMESPACE at _IOS_HAS_OSTREAM_LONG_LONG
-# define KWSYS_IOS_NEED_OPERATORS_LL     @KWSYS_NAMESPACE at _IOS_NEED_OPERATORS_LL
+#define KWSYS_IOS_HAS_ISTREAM_LONG_LONG                                       \
+  @KWSYS_NAMESPACE at _IOS_HAS_ISTREAM_LONG_LONG
+#define KWSYS_IOS_HAS_OSTREAM_LONG_LONG                                       \
+  @KWSYS_NAMESPACE at _IOS_HAS_OSTREAM_LONG_LONG
+#define KWSYS_IOS_NEED_OPERATORS_LL @KWSYS_NAMESPACE at _IOS_NEED_OPERATORS_LL
 #endif
 
 #endif
-
diff --git a/Source/kwsys/MD5.c b/Source/kwsys/MD5.c
index b75acb2..1310c64 100644
--- a/Source/kwsys/MD5.c
+++ b/Source/kwsys/MD5.c
@@ -1,26 +1,17 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(MD5.h)
 
 /* Work-around CMake dependency scanning limitation.  This must
    duplicate the above list of headers.  */
 #if 0
-# include "MD5.h.in"
+#include "MD5.h.in"
 #endif
 
-#include <stddef.h>    /* size_t */
-#include <stdlib.h>    /* malloc, free */
-#include <string.h>    /* memcpy, strlen */
+#include <stddef.h> /* size_t */
+#include <stdlib.h> /* malloc, free */
+#include <string.h> /* memcpy, strlen */
 
 /*--------------------------------------------------------------------------*/
 
@@ -30,8 +21,8 @@
    implementation file.  */
 
 #if defined(__clang__) && !defined(__INTEL_COMPILER)
-# pragma clang diagnostic push
-# pragma clang diagnostic ignored "-Wcast-align"
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wcast-align"
 #endif
 
 /*
@@ -97,344 +88,341 @@
  */
 
 typedef unsigned char md5_byte_t; /* 8-bit byte */
-typedef unsigned int md5_word_t; /* 32-bit word */
+typedef unsigned int md5_word_t;  /* 32-bit word */
 
 /* Define the state of the MD5 Algorithm. */
-typedef struct md5_state_s {
-    md5_word_t count[2];        /* message length in bits, lsw first */
-    md5_word_t abcd[4];         /* digest buffer */
-    md5_byte_t buf[64];         /* accumulate block */
+typedef struct md5_state_s
+{
+  md5_word_t count[2]; /* message length in bits, lsw first */
+  md5_word_t abcd[4];  /* digest buffer */
+  md5_byte_t buf[64];  /* accumulate block */
 } md5_state_t;
 
-#undef BYTE_ORDER       /* 1 = big-endian, -1 = little-endian, 0 = unknown */
+#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */
 #ifdef ARCH_IS_BIG_ENDIAN
-#  define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
+#define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
 #else
-#  define BYTE_ORDER 0
+#define BYTE_ORDER 0
 #endif
 
 #define T_MASK ((md5_word_t)~0)
 #define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87)
 #define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9)
-#define T3    0x242070db
+#define T3 0x242070db
 #define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111)
 #define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050)
-#define T6    0x4787c62a
+#define T6 0x4787c62a
 #define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec)
 #define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe)
-#define T9    0x698098d8
+#define T9 0x698098d8
 #define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850)
 #define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e)
 #define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841)
-#define T13    0x6b901122
+#define T13 0x6b901122
 #define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c)
 #define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71)
-#define T16    0x49b40821
+#define T16 0x49b40821
 #define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d)
 #define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf)
-#define T19    0x265e5a51
+#define T19 0x265e5a51
 #define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855)
 #define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2)
-#define T22    0x02441453
+#define T22 0x02441453
 #define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e)
 #define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437)
-#define T25    0x21e1cde6
+#define T25 0x21e1cde6
 #define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829)
 #define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278)
-#define T28    0x455a14ed
+#define T28 0x455a14ed
 #define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa)
 #define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07)
-#define T31    0x676f02d9
+#define T31 0x676f02d9
 #define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375)
 #define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd)
 #define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e)
-#define T35    0x6d9d6122
+#define T35 0x6d9d6122
 #define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3)
 #define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb)
-#define T38    0x4bdecfa9
+#define T38 0x4bdecfa9
 #define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f)
 #define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f)
-#define T41    0x289b7ec6
+#define T41 0x289b7ec6
 #define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805)
 #define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a)
-#define T44    0x04881d05
+#define T44 0x04881d05
 #define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6)
 #define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a)
-#define T47    0x1fa27cf8
+#define T47 0x1fa27cf8
 #define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a)
 #define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb)
-#define T50    0x432aff97
+#define T50 0x432aff97
 #define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58)
 #define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6)
-#define T53    0x655b59c3
+#define T53 0x655b59c3
 #define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d)
 #define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82)
 #define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e)
-#define T57    0x6fa87e4f
+#define T57 0x6fa87e4f
 #define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f)
 #define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb)
-#define T60    0x4e0811a1
+#define T60 0x4e0811a1
 #define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d)
 #define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca)
-#define T63    0x2ad7d2bb
+#define T63 0x2ad7d2bb
 #define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e)
 
-
-static void
-md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
+static void md5_process(md5_state_t* pms, const md5_byte_t* data /*[64]*/)
 {
-    md5_word_t
-        a = pms->abcd[0], b = pms->abcd[1],
-        c = pms->abcd[2], d = pms->abcd[3];
-    md5_word_t t;
+  md5_word_t a = pms->abcd[0], b = pms->abcd[1], c = pms->abcd[2],
+             d = pms->abcd[3];
+  md5_word_t t;
 #if BYTE_ORDER > 0
-    /* Define storage only for big-endian CPUs. */
-    md5_word_t X[16];
+  /* Define storage only for big-endian CPUs. */
+  md5_word_t X[16];
 #else
-    /* Define storage for little-endian or both types of CPUs. */
-    md5_word_t xbuf[16];
-    const md5_word_t *X;
+  /* Define storage for little-endian or both types of CPUs. */
+  md5_word_t xbuf[16];
+  const md5_word_t* X;
 #endif
 
-    {
+  {
 #if BYTE_ORDER == 0
-        /*
-         * Determine dynamically whether this is a big-endian or
-         * little-endian machine, since we can use a more efficient
-         * algorithm on the latter.
-         */
-        static const int w = 1;
-
-        if (*((const md5_byte_t *)&w)) /* dynamic little-endian */
+    /*
+     * Determine dynamically whether this is a big-endian or
+     * little-endian machine, since we can use a more efficient
+     * algorithm on the latter.
+     */
+    static const int w = 1;
+
+    if (*((const md5_byte_t*)&w)) /* dynamic little-endian */
 #endif
-#if BYTE_ORDER <= 0             /* little-endian */
-        {
-            /*
-             * On little-endian machines, we can process properly aligned
-             * data without copying it.
-             */
-            if (!((data - (const md5_byte_t *)0) & 3)) {
-                /* data are properly aligned */
-                X = (const md5_word_t *)data;
-            } else {
-                /* not aligned */
-                memcpy(xbuf, data, 64);
-                X = xbuf;
-            }
-        }
+#if BYTE_ORDER <= 0 /* little-endian */
+    {
+      /*
+       * On little-endian machines, we can process properly aligned
+       * data without copying it.
+       */
+      if (!((data - (const md5_byte_t*)0) & 3)) {
+        /* data are properly aligned */
+        X = (const md5_word_t*)data;
+      } else {
+        /* not aligned */
+        memcpy(xbuf, data, 64);
+        X = xbuf;
+      }
+    }
 #endif
 #if BYTE_ORDER == 0
-        else                    /* dynamic big-endian */
+    else /* dynamic big-endian */
 #endif
-#if BYTE_ORDER >= 0             /* big-endian */
-        {
-            /*
-             * On big-endian machines, we must arrange the bytes in the
-             * right order.
-             */
-            const md5_byte_t *xp = data;
-            int i;
-
-#  if BYTE_ORDER == 0
-            X = xbuf;           /* (dynamic only) */
-#  else
-#    define xbuf X              /* (static only) */
-#  endif
-            for (i = 0; i < 16; ++i, xp += 4)
-              xbuf[i] = (md5_word_t)(xp[0] + (xp[1] << 8) +
-                                     (xp[2] << 16) + (xp[3] << 24));
-        }
+#if BYTE_ORDER >= 0 /* big-endian */
+    {
+      /*
+       * On big-endian machines, we must arrange the bytes in the
+       * right order.
+       */
+      const md5_byte_t* xp = data;
+      int i;
+
+#if BYTE_ORDER == 0
+      X = xbuf; /* (dynamic only) */
+#else
+#define xbuf X /* (static only) */
 #endif
+      for (i = 0; i < 16; ++i, xp += 4)
+        xbuf[i] =
+          (md5_word_t)(xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24));
     }
+#endif
+  }
 
 #define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
 
-    /* Round 1. */
-    /* Let [abcd k s i] denote the operation
-       a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
+/* Round 1. */
+/* Let [abcd k s i] denote the operation
+   a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
 #define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
-#define SET(a, b, c, d, k, s, Ti)\
-  t = a + F(b,c,d) + X[k] + (Ti);\
+#define SET(a, b, c, d, k, s, Ti)                                             \
+  t = a + F(b, c, d) + X[k] + (Ti);                                           \
   a = ROTATE_LEFT(t, s) + b
-    /* Do the following 16 operations. */
-    SET(a, b, c, d,  0,  7,  T1);
-    SET(d, a, b, c,  1, 12,  T2);
-    SET(c, d, a, b,  2, 17,  T3);
-    SET(b, c, d, a,  3, 22,  T4);
-    SET(a, b, c, d,  4,  7,  T5);
-    SET(d, a, b, c,  5, 12,  T6);
-    SET(c, d, a, b,  6, 17,  T7);
-    SET(b, c, d, a,  7, 22,  T8);
-    SET(a, b, c, d,  8,  7,  T9);
-    SET(d, a, b, c,  9, 12, T10);
-    SET(c, d, a, b, 10, 17, T11);
-    SET(b, c, d, a, 11, 22, T12);
-    SET(a, b, c, d, 12,  7, T13);
-    SET(d, a, b, c, 13, 12, T14);
-    SET(c, d, a, b, 14, 17, T15);
-    SET(b, c, d, a, 15, 22, T16);
+  /* Do the following 16 operations. */
+  SET(a, b, c, d, 0, 7, T1);
+  SET(d, a, b, c, 1, 12, T2);
+  SET(c, d, a, b, 2, 17, T3);
+  SET(b, c, d, a, 3, 22, T4);
+  SET(a, b, c, d, 4, 7, T5);
+  SET(d, a, b, c, 5, 12, T6);
+  SET(c, d, a, b, 6, 17, T7);
+  SET(b, c, d, a, 7, 22, T8);
+  SET(a, b, c, d, 8, 7, T9);
+  SET(d, a, b, c, 9, 12, T10);
+  SET(c, d, a, b, 10, 17, T11);
+  SET(b, c, d, a, 11, 22, T12);
+  SET(a, b, c, d, 12, 7, T13);
+  SET(d, a, b, c, 13, 12, T14);
+  SET(c, d, a, b, 14, 17, T15);
+  SET(b, c, d, a, 15, 22, T16);
 #undef SET
 
-     /* Round 2. */
-     /* Let [abcd k s i] denote the operation
-          a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
+/* Round 2. */
+/* Let [abcd k s i] denote the operation
+     a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
 #define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
-#define SET(a, b, c, d, k, s, Ti)\
-  t = a + G(b,c,d) + X[k] + (Ti);\
+#define SET(a, b, c, d, k, s, Ti)                                             \
+  t = a + G(b, c, d) + X[k] + (Ti);                                           \
   a = ROTATE_LEFT(t, s) + b
-     /* Do the following 16 operations. */
-    SET(a, b, c, d,  1,  5, T17);
-    SET(d, a, b, c,  6,  9, T18);
-    SET(c, d, a, b, 11, 14, T19);
-    SET(b, c, d, a,  0, 20, T20);
-    SET(a, b, c, d,  5,  5, T21);
-    SET(d, a, b, c, 10,  9, T22);
-    SET(c, d, a, b, 15, 14, T23);
-    SET(b, c, d, a,  4, 20, T24);
-    SET(a, b, c, d,  9,  5, T25);
-    SET(d, a, b, c, 14,  9, T26);
-    SET(c, d, a, b,  3, 14, T27);
-    SET(b, c, d, a,  8, 20, T28);
-    SET(a, b, c, d, 13,  5, T29);
-    SET(d, a, b, c,  2,  9, T30);
-    SET(c, d, a, b,  7, 14, T31);
-    SET(b, c, d, a, 12, 20, T32);
+  /* Do the following 16 operations. */
+  SET(a, b, c, d, 1, 5, T17);
+  SET(d, a, b, c, 6, 9, T18);
+  SET(c, d, a, b, 11, 14, T19);
+  SET(b, c, d, a, 0, 20, T20);
+  SET(a, b, c, d, 5, 5, T21);
+  SET(d, a, b, c, 10, 9, T22);
+  SET(c, d, a, b, 15, 14, T23);
+  SET(b, c, d, a, 4, 20, T24);
+  SET(a, b, c, d, 9, 5, T25);
+  SET(d, a, b, c, 14, 9, T26);
+  SET(c, d, a, b, 3, 14, T27);
+  SET(b, c, d, a, 8, 20, T28);
+  SET(a, b, c, d, 13, 5, T29);
+  SET(d, a, b, c, 2, 9, T30);
+  SET(c, d, a, b, 7, 14, T31);
+  SET(b, c, d, a, 12, 20, T32);
 #undef SET
 
-     /* Round 3. */
-     /* Let [abcd k s t] denote the operation
-          a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
+/* Round 3. */
+/* Let [abcd k s t] denote the operation
+     a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
 #define H(x, y, z) ((x) ^ (y) ^ (z))
-#define SET(a, b, c, d, k, s, Ti)\
-  t = a + H(b,c,d) + X[k] + (Ti);\
+#define SET(a, b, c, d, k, s, Ti)                                             \
+  t = a + H(b, c, d) + X[k] + (Ti);                                           \
   a = ROTATE_LEFT(t, s) + b
-     /* Do the following 16 operations. */
-    SET(a, b, c, d,  5,  4, T33);
-    SET(d, a, b, c,  8, 11, T34);
-    SET(c, d, a, b, 11, 16, T35);
-    SET(b, c, d, a, 14, 23, T36);
-    SET(a, b, c, d,  1,  4, T37);
-    SET(d, a, b, c,  4, 11, T38);
-    SET(c, d, a, b,  7, 16, T39);
-    SET(b, c, d, a, 10, 23, T40);
-    SET(a, b, c, d, 13,  4, T41);
-    SET(d, a, b, c,  0, 11, T42);
-    SET(c, d, a, b,  3, 16, T43);
-    SET(b, c, d, a,  6, 23, T44);
-    SET(a, b, c, d,  9,  4, T45);
-    SET(d, a, b, c, 12, 11, T46);
-    SET(c, d, a, b, 15, 16, T47);
-    SET(b, c, d, a,  2, 23, T48);
+  /* Do the following 16 operations. */
+  SET(a, b, c, d, 5, 4, T33);
+  SET(d, a, b, c, 8, 11, T34);
+  SET(c, d, a, b, 11, 16, T35);
+  SET(b, c, d, a, 14, 23, T36);
+  SET(a, b, c, d, 1, 4, T37);
+  SET(d, a, b, c, 4, 11, T38);
+  SET(c, d, a, b, 7, 16, T39);
+  SET(b, c, d, a, 10, 23, T40);
+  SET(a, b, c, d, 13, 4, T41);
+  SET(d, a, b, c, 0, 11, T42);
+  SET(c, d, a, b, 3, 16, T43);
+  SET(b, c, d, a, 6, 23, T44);
+  SET(a, b, c, d, 9, 4, T45);
+  SET(d, a, b, c, 12, 11, T46);
+  SET(c, d, a, b, 15, 16, T47);
+  SET(b, c, d, a, 2, 23, T48);
 #undef SET
 
-     /* Round 4. */
-     /* Let [abcd k s t] denote the operation
-          a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
+/* Round 4. */
+/* Let [abcd k s t] denote the operation
+     a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
 #define I(x, y, z) ((y) ^ ((x) | ~(z)))
-#define SET(a, b, c, d, k, s, Ti)\
-  t = a + I(b,c,d) + X[k] + (Ti);\
+#define SET(a, b, c, d, k, s, Ti)                                             \
+  t = a + I(b, c, d) + X[k] + (Ti);                                           \
   a = ROTATE_LEFT(t, s) + b
-     /* Do the following 16 operations. */
-    SET(a, b, c, d,  0,  6, T49);
-    SET(d, a, b, c,  7, 10, T50);
-    SET(c, d, a, b, 14, 15, T51);
-    SET(b, c, d, a,  5, 21, T52);
-    SET(a, b, c, d, 12,  6, T53);
-    SET(d, a, b, c,  3, 10, T54);
-    SET(c, d, a, b, 10, 15, T55);
-    SET(b, c, d, a,  1, 21, T56);
-    SET(a, b, c, d,  8,  6, T57);
-    SET(d, a, b, c, 15, 10, T58);
-    SET(c, d, a, b,  6, 15, T59);
-    SET(b, c, d, a, 13, 21, T60);
-    SET(a, b, c, d,  4,  6, T61);
-    SET(d, a, b, c, 11, 10, T62);
-    SET(c, d, a, b,  2, 15, T63);
-    SET(b, c, d, a,  9, 21, T64);
+  /* Do the following 16 operations. */
+  SET(a, b, c, d, 0, 6, T49);
+  SET(d, a, b, c, 7, 10, T50);
+  SET(c, d, a, b, 14, 15, T51);
+  SET(b, c, d, a, 5, 21, T52);
+  SET(a, b, c, d, 12, 6, T53);
+  SET(d, a, b, c, 3, 10, T54);
+  SET(c, d, a, b, 10, 15, T55);
+  SET(b, c, d, a, 1, 21, T56);
+  SET(a, b, c, d, 8, 6, T57);
+  SET(d, a, b, c, 15, 10, T58);
+  SET(c, d, a, b, 6, 15, T59);
+  SET(b, c, d, a, 13, 21, T60);
+  SET(a, b, c, d, 4, 6, T61);
+  SET(d, a, b, c, 11, 10, T62);
+  SET(c, d, a, b, 2, 15, T63);
+  SET(b, c, d, a, 9, 21, T64);
 #undef SET
 
-     /* Then perform the following additions. (That is increment each
-        of the four registers by the value it had before this block
-        was started.) */
-    pms->abcd[0] += a;
-    pms->abcd[1] += b;
-    pms->abcd[2] += c;
-    pms->abcd[3] += d;
+  /* Then perform the following additions. (That is increment each
+     of the four registers by the value it had before this block
+     was started.) */
+  pms->abcd[0] += a;
+  pms->abcd[1] += b;
+  pms->abcd[2] += c;
+  pms->abcd[3] += d;
 }
 
 /* Initialize the algorithm. */
-static void md5_init(md5_state_t *pms)
+static void md5_init(md5_state_t* pms)
 {
-    pms->count[0] = pms->count[1] = 0;
-    pms->abcd[0] = 0x67452301;
-    pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
-    pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
-    pms->abcd[3] = 0x10325476;
+  pms->count[0] = pms->count[1] = 0;
+  pms->abcd[0] = 0x67452301;
+  pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
+  pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
+  pms->abcd[3] = 0x10325476;
 }
 
 /* Append a string to the message. */
-static void md5_append(md5_state_t *pms, const md5_byte_t *data, size_t nbytes)
+static void md5_append(md5_state_t* pms, const md5_byte_t* data, size_t nbytes)
 {
-    const md5_byte_t *p = data;
-    size_t left = nbytes;
-    size_t offset = (pms->count[0] >> 3) & 63;
-    md5_word_t nbits = (md5_word_t)(nbytes << 3);
-
-    if (nbytes <= 0)
-        return;
-
-    /* Update the message length. */
-    pms->count[1] += (md5_word_t)(nbytes >> 29);
-    pms->count[0] += nbits;
-    if (pms->count[0] < nbits)
-        pms->count[1]++;
-
-    /* Process an initial partial block. */
-    if (offset) {
-        size_t copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
-
-        memcpy(pms->buf + offset, p, copy);
-        if (offset + copy < 64)
-            return;
-        p += copy;
-        left -= copy;
-        md5_process(pms, pms->buf);
-    }
+  const md5_byte_t* p = data;
+  size_t left = nbytes;
+  size_t offset = (pms->count[0] >> 3) & 63;
+  md5_word_t nbits = (md5_word_t)(nbytes << 3);
 
-    /* Process full blocks. */
-    for (; left >= 64; p += 64, left -= 64)
-        md5_process(pms, p);
+  if (nbytes <= 0)
+    return;
 
-    /* Process a final partial block. */
-    if (left)
-        memcpy(pms->buf, p, left);
+  /* Update the message length. */
+  pms->count[1] += (md5_word_t)(nbytes >> 29);
+  pms->count[0] += nbits;
+  if (pms->count[0] < nbits)
+    pms->count[1]++;
+
+  /* Process an initial partial block. */
+  if (offset) {
+    size_t copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
+
+    memcpy(pms->buf + offset, p, copy);
+    if (offset + copy < 64)
+      return;
+    p += copy;
+    left -= copy;
+    md5_process(pms, pms->buf);
+  }
+
+  /* Process full blocks. */
+  for (; left >= 64; p += 64, left -= 64)
+    md5_process(pms, p);
+
+  /* Process a final partial block. */
+  if (left)
+    memcpy(pms->buf, p, left);
 }
 
 /* Finish the message and return the digest. */
-static void md5_finish(md5_state_t *pms, md5_byte_t digest[16])
+static void md5_finish(md5_state_t* pms, md5_byte_t digest[16])
 {
-    static const md5_byte_t pad[64] = {
-        0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
-    };
-    md5_byte_t data[8];
-    int i;
-
-    /* Save the length before padding. */
-    for (i = 0; i < 8; ++i)
-        data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
-    /* Pad to 56 bytes mod 64. */
-    md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
-    /* Append the length. */
-    md5_append(pms, data, 8);
-    for (i = 0; i < 16; ++i)
-        digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
+  static const md5_byte_t pad[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                                      0,    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                                      0,    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                                      0,    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                                      0,    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+  md5_byte_t data[8];
+  int i;
+
+  /* Save the length before padding. */
+  for (i = 0; i < 8; ++i)
+    data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
+  /* Pad to 56 bytes mod 64. */
+  md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
+  /* Append the length. */
+  md5_append(pms, data, 8);
+  for (i = 0; i < 16; ++i)
+    digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
 }
 
 #if defined(__clang__) && !defined(__INTEL_COMPILER)
-# pragma clang diagnostic pop
+#pragma clang diagnostic pop
 #endif
 
 /*--------------------------------------------------------------------------*/
@@ -449,10 +437,9 @@ kwsysMD5* kwsysMD5_New(void)
 {
   /* Allocate a process control structure.  */
   kwsysMD5* md5 = (kwsysMD5*)malloc(sizeof(kwsysMD5));
-  if(!md5)
-    {
+  if (!md5) {
     return 0;
-    }
+  }
   return md5;
 }
 
@@ -460,10 +447,9 @@ kwsysMD5* kwsysMD5_New(void)
 void kwsysMD5_Delete(kwsysMD5* md5)
 {
   /* Make sure we have an instance.  */
-  if(!md5)
-    {
+  if (!md5) {
     return;
-    }
+  }
 
   /* Free memory.  */
   free(md5);
@@ -479,14 +465,11 @@ void kwsysMD5_Initialize(kwsysMD5* md5)
 void kwsysMD5_Append(kwsysMD5* md5, unsigned char const* data, int length)
 {
   size_t dlen;
-  if(length < 0)
-    {
+  if (length < 0) {
     dlen = strlen((char const*)data);
-    }
-  else
-    {
+  } else {
     dlen = (size_t)length;
-    }
+  }
   md5_append(&md5->md5_state, (md5_byte_t const*)data, dlen);
 }
 
@@ -508,16 +491,14 @@ void kwsysMD5_FinalizeHex(kwsysMD5* md5, char buffer[32])
 void kwsysMD5_DigestToHex(unsigned char const digest[16], char buffer[32])
 {
   /* Map from 4-bit index to hexadecimal representation.  */
-  static char const hex[16] =
-    {'0', '1', '2', '3', '4', '5', '6', '7',
-     '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
+  static char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
+                                '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
 
   /* Map each 4-bit block separately.  */
   char* out = buffer;
   int i;
-  for(i=0; i < 16; ++i)
-    {
+  for (i = 0; i < 16; ++i) {
     *out++ = hex[digest[i] >> 4];
     *out++ = hex[digest[i] & 0xF];
-    }
+  }
 }
diff --git a/Source/kwsys/MD5.h.in b/Source/kwsys/MD5.h.in
index 3334431..c257f7f 100644
--- a/Source/kwsys/MD5.h.in
+++ b/Source/kwsys/MD5.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _MD5_h
 #define @KWSYS_NAMESPACE at _MD5_h
 
@@ -19,24 +10,23 @@
    not visible to user code.  Use kwsysHeaderDump.pl to reproduce
    these macros after making changes to the interface.  */
 #if !defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
 #endif
 #if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-# define kwsysMD5                 kwsys_ns(MD5)
-# define kwsysMD5_s               kwsys_ns(MD5_s)
-# define kwsysMD5_New             kwsys_ns(MD5_New)
-# define kwsysMD5_Delete          kwsys_ns(MD5_Delete)
-# define kwsysMD5_Initialize      kwsys_ns(MD5_Initialize)
-# define kwsysMD5_Append          kwsys_ns(MD5_Append)
-# define kwsysMD5_Finalize        kwsys_ns(MD5_Finalize)
-# define kwsysMD5_FinalizeHex     kwsys_ns(MD5_FinalizeHex)
-# define kwsysMD5_DigestToHex     kwsys_ns(MD5_DigestToHex)
+#define kwsysMD5 kwsys_ns(MD5)
+#define kwsysMD5_s kwsys_ns(MD5_s)
+#define kwsysMD5_New kwsys_ns(MD5_New)
+#define kwsysMD5_Delete kwsys_ns(MD5_Delete)
+#define kwsysMD5_Initialize kwsys_ns(MD5_Initialize)
+#define kwsysMD5_Append kwsys_ns(MD5_Append)
+#define kwsysMD5_Finalize kwsys_ns(MD5_Finalize)
+#define kwsysMD5_FinalizeHex kwsys_ns(MD5_FinalizeHex)
+#define kwsysMD5_DigestToHex kwsys_ns(MD5_DigestToHex)
 #endif
 
 #if defined(__cplusplus)
-extern "C"
-{
+extern "C" {
 #endif
 
 /**
@@ -89,19 +79,19 @@ kwsysEXPORT void kwsysMD5_DigestToHex(unsigned char const digest[16],
 /* If we are building a kwsys .c or .cxx file, let it use these macros.
    Otherwise, undefine them to keep the namespace clean.  */
 #if !defined(KWSYS_NAMESPACE)
-# undef kwsys_ns
-# undef kwsysEXPORT
-# if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-#  undef kwsysMD5
-#  undef kwsysMD5_s
-#  undef kwsysMD5_New
-#  undef kwsysMD5_Delete
-#  undef kwsysMD5_Initialize
-#  undef kwsysMD5_Append
-#  undef kwsysMD5_Finalize
-#  undef kwsysMD5_FinalizeHex
-#  undef kwsysMD5_DigestToHex
-# endif
+#undef kwsys_ns
+#undef kwsysEXPORT
+#if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
+#undef kwsysMD5
+#undef kwsysMD5_s
+#undef kwsysMD5_New
+#undef kwsysMD5_Delete
+#undef kwsysMD5_Initialize
+#undef kwsysMD5_Append
+#undef kwsysMD5_Finalize
+#undef kwsysMD5_FinalizeHex
+#undef kwsysMD5_DigestToHex
+#endif
 #endif
 
 #endif
diff --git a/Source/kwsys/Process.h.in b/Source/kwsys/Process.h.in
index 96563a2..b8349a6 100644
--- a/Source/kwsys/Process.h.in
+++ b/Source/kwsys/Process.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _Process_h
 #define @KWSYS_NAMESPACE at _Process_h
 
@@ -19,70 +10,70 @@
    not visible to user code.  Use kwsysHeaderDump.pl to reproduce
    these macros after making changes to the interface.  */
 #if !defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
 #endif
 #if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-# define kwsysProcess                           kwsys_ns(Process)
-# define kwsysProcess_s                         kwsys_ns(Process_s)
-# define kwsysProcess_New                       kwsys_ns(Process_New)
-# define kwsysProcess_Delete                    kwsys_ns(Process_Delete)
-# define kwsysProcess_SetCommand                kwsys_ns(Process_SetCommand)
-# define kwsysProcess_AddCommand                kwsys_ns(Process_AddCommand)
-# define kwsysProcess_SetTimeout                kwsys_ns(Process_SetTimeout)
-# define kwsysProcess_SetWorkingDirectory       kwsys_ns(Process_SetWorkingDirectory)
-# define kwsysProcess_SetPipeFile               kwsys_ns(Process_SetPipeFile)
-# define kwsysProcess_SetPipeNative             kwsys_ns(Process_SetPipeNative)
-# define kwsysProcess_SetPipeShared             kwsys_ns(Process_SetPipeShared)
-# define kwsysProcess_Option_Detach             kwsys_ns(Process_Option_Detach)
-# define kwsysProcess_Option_HideWindow         kwsys_ns(Process_Option_HideWindow)
-# define kwsysProcess_Option_MergeOutput        kwsys_ns(Process_Option_MergeOutput)
-# define kwsysProcess_Option_Verbatim           kwsys_ns(Process_Option_Verbatim)
-# define kwsysProcess_Option_CreateProcessGroup kwsys_ns(Process_Option_CreateProcessGroup)
-# define kwsysProcess_GetOption                 kwsys_ns(Process_GetOption)
-# define kwsysProcess_SetOption                 kwsys_ns(Process_SetOption)
-# define kwsysProcess_Option_e                  kwsys_ns(Process_Option_e)
-# define kwsysProcess_State_Starting            kwsys_ns(Process_State_Starting)
-# define kwsysProcess_State_Error               kwsys_ns(Process_State_Error)
-# define kwsysProcess_State_Exception           kwsys_ns(Process_State_Exception)
-# define kwsysProcess_State_Executing           kwsys_ns(Process_State_Executing)
-# define kwsysProcess_State_Exited              kwsys_ns(Process_State_Exited)
-# define kwsysProcess_State_Expired             kwsys_ns(Process_State_Expired)
-# define kwsysProcess_State_Killed              kwsys_ns(Process_State_Killed)
-# define kwsysProcess_State_Disowned            kwsys_ns(Process_State_Disowned)
-# define kwsysProcess_GetState                  kwsys_ns(Process_GetState)
-# define kwsysProcess_State_e                   kwsys_ns(Process_State_e)
-# define kwsysProcess_Exception_None            kwsys_ns(Process_Exception_None)
-# define kwsysProcess_Exception_Fault           kwsys_ns(Process_Exception_Fault)
-# define kwsysProcess_Exception_Illegal         kwsys_ns(Process_Exception_Illegal)
-# define kwsysProcess_Exception_Interrupt       kwsys_ns(Process_Exception_Interrupt)
-# define kwsysProcess_Exception_Numerical       kwsys_ns(Process_Exception_Numerical)
-# define kwsysProcess_Exception_Other           kwsys_ns(Process_Exception_Other)
-# define kwsysProcess_GetExitException          kwsys_ns(Process_GetExitException)
-# define kwsysProcess_Exception_e               kwsys_ns(Process_Exception_e)
-# define kwsysProcess_GetExitCode               kwsys_ns(Process_GetExitCode)
-# define kwsysProcess_GetExitValue              kwsys_ns(Process_GetExitValue)
-# define kwsysProcess_GetErrorString            kwsys_ns(Process_GetErrorString)
-# define kwsysProcess_GetExceptionString        kwsys_ns(Process_GetExceptionString)
-# define kwsysProcess_Execute                   kwsys_ns(Process_Execute)
-# define kwsysProcess_Disown                    kwsys_ns(Process_Disown)
-# define kwsysProcess_WaitForData               kwsys_ns(Process_WaitForData)
-# define kwsysProcess_Pipes_e                   kwsys_ns(Process_Pipes_e)
-# define kwsysProcess_Pipe_None                 kwsys_ns(Process_Pipe_None)
-# define kwsysProcess_Pipe_STDIN                kwsys_ns(Process_Pipe_STDIN)
-# define kwsysProcess_Pipe_STDOUT               kwsys_ns(Process_Pipe_STDOUT)
-# define kwsysProcess_Pipe_STDERR               kwsys_ns(Process_Pipe_STDERR)
-# define kwsysProcess_Pipe_Timeout              kwsys_ns(Process_Pipe_Timeout)
-# define kwsysProcess_Pipe_Handle               kwsys_ns(Process_Pipe_Handle)
-# define kwsysProcess_WaitForExit               kwsys_ns(Process_WaitForExit)
-# define kwsysProcess_Interrupt                 kwsys_ns(Process_Interrupt)
-# define kwsysProcess_Kill                      kwsys_ns(Process_Kill)
-# define kwsysProcess_ResetStartTime            kwsys_ns(Process_ResetStartTime)
+#define kwsysProcess kwsys_ns(Process)
+#define kwsysProcess_s kwsys_ns(Process_s)
+#define kwsysProcess_New kwsys_ns(Process_New)
+#define kwsysProcess_Delete kwsys_ns(Process_Delete)
+#define kwsysProcess_SetCommand kwsys_ns(Process_SetCommand)
+#define kwsysProcess_AddCommand kwsys_ns(Process_AddCommand)
+#define kwsysProcess_SetTimeout kwsys_ns(Process_SetTimeout)
+#define kwsysProcess_SetWorkingDirectory kwsys_ns(Process_SetWorkingDirectory)
+#define kwsysProcess_SetPipeFile kwsys_ns(Process_SetPipeFile)
+#define kwsysProcess_SetPipeNative kwsys_ns(Process_SetPipeNative)
+#define kwsysProcess_SetPipeShared kwsys_ns(Process_SetPipeShared)
+#define kwsysProcess_Option_Detach kwsys_ns(Process_Option_Detach)
+#define kwsysProcess_Option_HideWindow kwsys_ns(Process_Option_HideWindow)
+#define kwsysProcess_Option_MergeOutput kwsys_ns(Process_Option_MergeOutput)
+#define kwsysProcess_Option_Verbatim kwsys_ns(Process_Option_Verbatim)
+#define kwsysProcess_Option_CreateProcessGroup                                \
+  kwsys_ns(Process_Option_CreateProcessGroup)
+#define kwsysProcess_GetOption kwsys_ns(Process_GetOption)
+#define kwsysProcess_SetOption kwsys_ns(Process_SetOption)
+#define kwsysProcess_Option_e kwsys_ns(Process_Option_e)
+#define kwsysProcess_State_Starting kwsys_ns(Process_State_Starting)
+#define kwsysProcess_State_Error kwsys_ns(Process_State_Error)
+#define kwsysProcess_State_Exception kwsys_ns(Process_State_Exception)
+#define kwsysProcess_State_Executing kwsys_ns(Process_State_Executing)
+#define kwsysProcess_State_Exited kwsys_ns(Process_State_Exited)
+#define kwsysProcess_State_Expired kwsys_ns(Process_State_Expired)
+#define kwsysProcess_State_Killed kwsys_ns(Process_State_Killed)
+#define kwsysProcess_State_Disowned kwsys_ns(Process_State_Disowned)
+#define kwsysProcess_GetState kwsys_ns(Process_GetState)
+#define kwsysProcess_State_e kwsys_ns(Process_State_e)
+#define kwsysProcess_Exception_None kwsys_ns(Process_Exception_None)
+#define kwsysProcess_Exception_Fault kwsys_ns(Process_Exception_Fault)
+#define kwsysProcess_Exception_Illegal kwsys_ns(Process_Exception_Illegal)
+#define kwsysProcess_Exception_Interrupt kwsys_ns(Process_Exception_Interrupt)
+#define kwsysProcess_Exception_Numerical kwsys_ns(Process_Exception_Numerical)
+#define kwsysProcess_Exception_Other kwsys_ns(Process_Exception_Other)
+#define kwsysProcess_GetExitException kwsys_ns(Process_GetExitException)
+#define kwsysProcess_Exception_e kwsys_ns(Process_Exception_e)
+#define kwsysProcess_GetExitCode kwsys_ns(Process_GetExitCode)
+#define kwsysProcess_GetExitValue kwsys_ns(Process_GetExitValue)
+#define kwsysProcess_GetErrorString kwsys_ns(Process_GetErrorString)
+#define kwsysProcess_GetExceptionString kwsys_ns(Process_GetExceptionString)
+#define kwsysProcess_Execute kwsys_ns(Process_Execute)
+#define kwsysProcess_Disown kwsys_ns(Process_Disown)
+#define kwsysProcess_WaitForData kwsys_ns(Process_WaitForData)
+#define kwsysProcess_Pipes_e kwsys_ns(Process_Pipes_e)
+#define kwsysProcess_Pipe_None kwsys_ns(Process_Pipe_None)
+#define kwsysProcess_Pipe_STDIN kwsys_ns(Process_Pipe_STDIN)
+#define kwsysProcess_Pipe_STDOUT kwsys_ns(Process_Pipe_STDOUT)
+#define kwsysProcess_Pipe_STDERR kwsys_ns(Process_Pipe_STDERR)
+#define kwsysProcess_Pipe_Timeout kwsys_ns(Process_Pipe_Timeout)
+#define kwsysProcess_Pipe_Handle kwsys_ns(Process_Pipe_Handle)
+#define kwsysProcess_WaitForExit kwsys_ns(Process_WaitForExit)
+#define kwsysProcess_Interrupt kwsys_ns(Process_Interrupt)
+#define kwsysProcess_Kill kwsys_ns(Process_Kill)
+#define kwsysProcess_ResetStartTime kwsys_ns(Process_ResetStartTime)
 #endif
 
 #if defined(__cplusplus)
-extern "C"
-{
+extern "C" {
 #endif
 
 /**
@@ -256,9 +247,12 @@ enum kwsysProcess_State_e
  *
  *  kwsysProcess_Exception_None      = No exceptional behavior occurred.
  *  kwsysProcess_Exception_Fault     = Child crashed with a memory fault.
- *  kwsysProcess_Exception_Illegal   = Child crashed with an illegal instruction.
- *  kwsysProcess_Exception_Interrupt = Child was interrupted by user (Cntl-C/Break).
- *  kwsysProcess_Exception_Numerical = Child crashed with a numerical exception.
+ *  kwsysProcess_Exception_Illegal   = Child crashed with an illegal
+ * instruction.
+ *  kwsysProcess_Exception_Interrupt = Child was interrupted by user
+ * (Cntl-C/Break).
+ *  kwsysProcess_Exception_Numerical = Child crashed with a numerical
+ * exception.
  *  kwsysProcess_Exception_Other     = Child terminated for another reason.
  */
 kwsysEXPORT int kwsysProcess_GetExitException(kwsysProcess* cp);
@@ -352,7 +346,7 @@ enum kwsysProcess_Pipes_e
   kwsysProcess_Pipe_STDIN,
   kwsysProcess_Pipe_STDOUT,
   kwsysProcess_Pipe_STDERR,
-  kwsysProcess_Pipe_Timeout=255
+  kwsysProcess_Pipe_Timeout = 255
 };
 
 /**
@@ -405,65 +399,65 @@ kwsysEXPORT void kwsysProcess_ResetStartTime(kwsysProcess* cp);
 /* If we are building a kwsys .c or .cxx file, let it use these macros.
    Otherwise, undefine them to keep the namespace clean.  */
 #if !defined(KWSYS_NAMESPACE)
-# undef kwsys_ns
-# undef kwsysEXPORT
-# if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-#  undef kwsysProcess
-#  undef kwsysProcess_s
-#  undef kwsysProcess_New
-#  undef kwsysProcess_Delete
-#  undef kwsysProcess_SetCommand
-#  undef kwsysProcess_AddCommand
-#  undef kwsysProcess_SetTimeout
-#  undef kwsysProcess_SetWorkingDirectory
-#  undef kwsysProcess_SetPipeFile
-#  undef kwsysProcess_SetPipeNative
-#  undef kwsysProcess_SetPipeShared
-#  undef kwsysProcess_Option_Detach
-#  undef kwsysProcess_Option_HideWindow
-#  undef kwsysProcess_Option_MergeOutput
-#  undef kwsysProcess_Option_Verbatim
-#  undef kwsysProcess_Option_CreateProcessGroup
-#  undef kwsysProcess_GetOption
-#  undef kwsysProcess_SetOption
-#  undef kwsysProcess_Option_e
-#  undef kwsysProcess_State_Starting
-#  undef kwsysProcess_State_Error
-#  undef kwsysProcess_State_Exception
-#  undef kwsysProcess_State_Executing
-#  undef kwsysProcess_State_Exited
-#  undef kwsysProcess_State_Expired
-#  undef kwsysProcess_State_Killed
-#  undef kwsysProcess_State_Disowned
-#  undef kwsysProcess_GetState
-#  undef kwsysProcess_State_e
-#  undef kwsysProcess_Exception_None
-#  undef kwsysProcess_Exception_Fault
-#  undef kwsysProcess_Exception_Illegal
-#  undef kwsysProcess_Exception_Interrupt
-#  undef kwsysProcess_Exception_Numerical
-#  undef kwsysProcess_Exception_Other
-#  undef kwsysProcess_GetExitException
-#  undef kwsysProcess_Exception_e
-#  undef kwsysProcess_GetExitCode
-#  undef kwsysProcess_GetExitValue
-#  undef kwsysProcess_GetErrorString
-#  undef kwsysProcess_GetExceptionString
-#  undef kwsysProcess_Execute
-#  undef kwsysProcess_Disown
-#  undef kwsysProcess_WaitForData
-#  undef kwsysProcess_Pipes_e
-#  undef kwsysProcess_Pipe_None
-#  undef kwsysProcess_Pipe_STDIN
-#  undef kwsysProcess_Pipe_STDOUT
-#  undef kwsysProcess_Pipe_STDERR
-#  undef kwsysProcess_Pipe_Timeout
-#  undef kwsysProcess_Pipe_Handle
-#  undef kwsysProcess_WaitForExit
-#  undef kwsysProcess_Interrupt
-#  undef kwsysProcess_Kill
-#  undef kwsysProcess_ResetStartTime
-# endif
+#undef kwsys_ns
+#undef kwsysEXPORT
+#if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
+#undef kwsysProcess
+#undef kwsysProcess_s
+#undef kwsysProcess_New
+#undef kwsysProcess_Delete
+#undef kwsysProcess_SetCommand
+#undef kwsysProcess_AddCommand
+#undef kwsysProcess_SetTimeout
+#undef kwsysProcess_SetWorkingDirectory
+#undef kwsysProcess_SetPipeFile
+#undef kwsysProcess_SetPipeNative
+#undef kwsysProcess_SetPipeShared
+#undef kwsysProcess_Option_Detach
+#undef kwsysProcess_Option_HideWindow
+#undef kwsysProcess_Option_MergeOutput
+#undef kwsysProcess_Option_Verbatim
+#undef kwsysProcess_Option_CreateProcessGroup
+#undef kwsysProcess_GetOption
+#undef kwsysProcess_SetOption
+#undef kwsysProcess_Option_e
+#undef kwsysProcess_State_Starting
+#undef kwsysProcess_State_Error
+#undef kwsysProcess_State_Exception
+#undef kwsysProcess_State_Executing
+#undef kwsysProcess_State_Exited
+#undef kwsysProcess_State_Expired
+#undef kwsysProcess_State_Killed
+#undef kwsysProcess_State_Disowned
+#undef kwsysProcess_GetState
+#undef kwsysProcess_State_e
+#undef kwsysProcess_Exception_None
+#undef kwsysProcess_Exception_Fault
+#undef kwsysProcess_Exception_Illegal
+#undef kwsysProcess_Exception_Interrupt
+#undef kwsysProcess_Exception_Numerical
+#undef kwsysProcess_Exception_Other
+#undef kwsysProcess_GetExitException
+#undef kwsysProcess_Exception_e
+#undef kwsysProcess_GetExitCode
+#undef kwsysProcess_GetExitValue
+#undef kwsysProcess_GetErrorString
+#undef kwsysProcess_GetExceptionString
+#undef kwsysProcess_Execute
+#undef kwsysProcess_Disown
+#undef kwsysProcess_WaitForData
+#undef kwsysProcess_Pipes_e
+#undef kwsysProcess_Pipe_None
+#undef kwsysProcess_Pipe_STDIN
+#undef kwsysProcess_Pipe_STDOUT
+#undef kwsysProcess_Pipe_STDERR
+#undef kwsysProcess_Pipe_Timeout
+#undef kwsysProcess_Pipe_Handle
+#undef kwsysProcess_WaitForExit
+#undef kwsysProcess_Interrupt
+#undef kwsysProcess_Kill
+#undef kwsysProcess_ResetStartTime
+#endif
 #endif
 
 #endif
diff --git a/Source/kwsys/ProcessUNIX.c b/Source/kwsys/ProcessUNIX.c
index b577982..ed09095 100644
--- a/Source/kwsys/ProcessUNIX.c
+++ b/Source/kwsys/ProcessUNIX.c
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(Process.h)
 #include KWSYS_HEADER(System.h)
@@ -16,8 +7,8 @@
 /* Work-around CMake dependency scanning limitation.  This must
    duplicate the above list of headers.  */
 #if 0
-# include "Process.h.in"
-# include "System.h.in"
+#include "Process.h.in"
+#include "System.h.in"
 #endif
 
 /*
@@ -35,7 +26,6 @@ races.
 
 */
 
-
 /*
 
 TODO:
@@ -50,30 +40,30 @@ do.
 #if defined(__CYGWIN__)
 /* Increase the file descriptor limit for select() before including
    related system headers. (Default: 64) */
-# define FD_SETSIZE 16384
+#define FD_SETSIZE 16384
 #endif
 
+#include <assert.h>    /* assert */
+#include <ctype.h>     /* isspace */
+#include <dirent.h>    /* DIR, dirent */
+#include <errno.h>     /* errno */
+#include <fcntl.h>     /* fcntl */
+#include <signal.h>    /* sigaction */
 #include <stddef.h>    /* ptrdiff_t */
 #include <stdio.h>     /* snprintf */
 #include <stdlib.h>    /* malloc, free */
 #include <string.h>    /* strdup, strerror, memset */
+#include <sys/stat.h>  /* open mode */
 #include <sys/time.h>  /* struct timeval */
 #include <sys/types.h> /* pid_t, fd_set */
 #include <sys/wait.h>  /* waitpid */
-#include <sys/stat.h>  /* open mode */
-#include <unistd.h>    /* pipe, close, fork, execvp, select, _exit */
-#include <fcntl.h>     /* fcntl */
-#include <errno.h>     /* errno */
 #include <time.h>      /* gettimeofday */
-#include <signal.h>    /* sigaction */
-#include <dirent.h>    /* DIR, dirent */
-#include <ctype.h>     /* isspace */
-#include <assert.h>    /* assert */
+#include <unistd.h>    /* pipe, close, fork, execvp, select, _exit */
 
 #if defined(__VMS)
-# define KWSYSPE_VMS_NONBLOCK , O_NONBLOCK
+#define KWSYSPE_VMS_NONBLOCK , O_NONBLOCK
 #else
-# define KWSYSPE_VMS_NONBLOCK
+#define KWSYSPE_VMS_NONBLOCK
 #endif
 
 #if defined(KWSYS_C_HAS_PTRDIFF_T) && KWSYS_C_HAS_PTRDIFF_T
@@ -90,13 +80,13 @@ typedef int kwsysProcess_ssize_t;
 
 #if defined(__BEOS__) && !defined(__ZETA__)
 /* BeOS 5 doesn't have usleep(), but it has snooze(), which is identical. */
-# include <be/kernel/OS.h>
+#include <be/kernel/OS.h>
 static inline void kwsysProcess_usleep(unsigned int msec)
 {
   snooze(msec);
 }
 #else
-# define kwsysProcess_usleep usleep
+#define kwsysProcess_usleep usleep
 #endif
 
 /*
@@ -110,12 +100,12 @@ static inline void kwsysProcess_usleep(unsigned int msec)
  * without select().
  */
 #if !defined(__BEOS__) && !defined(__VMS) && !defined(__MINT__)
-# define KWSYSPE_USE_SELECT 1
+#define KWSYSPE_USE_SELECT 1
 #endif
 
 /* Some platforms do not have siginfo on their signal handlers.  */
 #if defined(SA_SIGINFO) && !defined(__BEOS__)
-# define KWSYSPE_USE_SIGINFO 1
+#define KWSYSPE_USE_SIGINFO 1
 #endif
 
 /* The number of pipes for the child's output.  The standard stdout
@@ -172,8 +162,10 @@ static kwsysProcessTime kwsysProcessTimeGetCurrent(void);
 static double kwsysProcessTimeToDouble(kwsysProcessTime t);
 static kwsysProcessTime kwsysProcessTimeFromDouble(double d);
 static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2);
-static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2);
-static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2);
+static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1,
+                                            kwsysProcessTime in2);
+static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1,
+                                                 kwsysProcessTime in2);
 static void kwsysProcessSetExitException(kwsysProcess* cp, int sig);
 static void kwsysProcessChildErrorExit(int errorPipe);
 static void kwsysProcessRestoreDefaultSignalHandlers(void);
@@ -281,10 +273,10 @@ struct kwsysProcess_s
   volatile sig_atomic_t Killed;
 
   /* Buffer for error message in case of failure.  */
-  char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE+1];
+  char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE + 1];
 
   /* Description for the ExitException.  */
-  char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE+1];
+  char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE + 1];
 
   /* The exit codes of each child process in the pipeline.  */
   int* CommandExitCodes;
@@ -314,10 +306,9 @@ kwsysProcess* kwsysProcess_New(void)
 {
   /* Allocate a process control structure.  */
   kwsysProcess* cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
-  if(!cp)
-    {
+  if (!cp) {
     return 0;
-    }
+  }
   memset(cp, 0, sizeof(kwsysProcess));
 
   /* Share stdin with the parent process by default.  */
@@ -341,23 +332,18 @@ kwsysProcess* kwsysProcess_New(void)
 void kwsysProcess_Delete(kwsysProcess* cp)
 {
   /* Make sure we have an instance.  */
-  if(!cp)
-    {
+  if (!cp) {
     return;
-    }
+  }
 
   /* If the process is executing, wait for it to finish.  */
-  if(cp->State == kwsysProcess_State_Executing)
-    {
-    if(cp->Detached)
-      {
+  if (cp->State == kwsysProcess_State_Executing) {
+    if (cp->Detached) {
       kwsysProcess_Disown(cp);
-      }
-    else
-      {
+    } else {
       kwsysProcess_WaitForExit(cp, 0);
-      }
     }
+  }
 
   /* Free memory.  */
   kwsysProcess_SetCommand(cp, 0);
@@ -365,10 +351,9 @@ void kwsysProcess_Delete(kwsysProcess* cp)
   kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDIN, 0);
   kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDOUT, 0);
   kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDERR, 0);
-  if(cp->CommandExitCodes)
-    {
+  if (cp->CommandExitCodes) {
     free(cp->CommandExitCodes);
-    }
+  }
   free(cp);
 }
 
@@ -376,29 +361,24 @@ void kwsysProcess_Delete(kwsysProcess* cp)
 int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
 {
   int i;
-  if(!cp)
-    {
+  if (!cp) {
     return 0;
-    }
-  for(i=0; i < cp->NumberOfCommands; ++i)
-    {
+  }
+  for (i = 0; i < cp->NumberOfCommands; ++i) {
     char** c = cp->Commands[i];
-    while(*c)
-      {
+    while (*c) {
       free(*c++);
-      }
-    free(cp->Commands[i]);
     }
+    free(cp->Commands[i]);
+  }
   cp->NumberOfCommands = 0;
-  if(cp->Commands)
-    {
+  if (cp->Commands) {
     free(cp->Commands);
     cp->Commands = 0;
-    }
-  if(command)
-    {
+  }
+  if (command) {
     return kwsysProcess_AddCommand(cp, command);
-    }
+  }
   return 1;
 }
 
@@ -409,81 +389,70 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
   char*** newCommands;
 
   /* Make sure we have a command to add.  */
-  if(!cp || !command || !*command)
-    {
+  if (!cp || !command || !*command) {
     return 0;
-    }
+  }
 
   /* Allocate a new array for command pointers.  */
   newNumberOfCommands = cp->NumberOfCommands + 1;
-  if(!(newCommands =
-       (char***)malloc(sizeof(char**) *(size_t)(newNumberOfCommands))))
-    {
+  if (!(newCommands =
+          (char***)malloc(sizeof(char**) * (size_t)(newNumberOfCommands)))) {
     /* Out of memory.  */
     return 0;
-    }
+  }
 
   /* Copy any existing commands into the new array.  */
   {
-  int i;
-  for(i=0; i < cp->NumberOfCommands; ++i)
-    {
-    newCommands[i] = cp->Commands[i];
+    int i;
+    for (i = 0; i < cp->NumberOfCommands; ++i) {
+      newCommands[i] = cp->Commands[i];
     }
   }
 
   /* Add the new command.  */
-  if(cp->Verbatim)
-    {
+  if (cp->Verbatim) {
     /* In order to run the given command line verbatim we need to
        parse it.  */
     newCommands[cp->NumberOfCommands] =
       kwsysSystem_Parse_CommandForUnix(*command, 0);
-    if(!newCommands[cp->NumberOfCommands] ||
-       !newCommands[cp->NumberOfCommands][0])
-      {
+    if (!newCommands[cp->NumberOfCommands] ||
+        !newCommands[cp->NumberOfCommands][0]) {
       /* Out of memory or no command parsed.  */
       free(newCommands);
       return 0;
-      }
     }
-  else
-    {
+  } else {
     /* Copy each argument string individually.  */
     char const* const* c = command;
     kwsysProcess_ptrdiff_t n = 0;
     kwsysProcess_ptrdiff_t i = 0;
-    while(*c++);
+    while (*c++)
+      ;
     n = c - command - 1;
     newCommands[cp->NumberOfCommands] =
-      (char**)malloc((size_t)(n+1)*sizeof(char*));
-    if(!newCommands[cp->NumberOfCommands])
-      {
+      (char**)malloc((size_t)(n + 1) * sizeof(char*));
+    if (!newCommands[cp->NumberOfCommands]) {
       /* Out of memory.  */
       free(newCommands);
       return 0;
-      }
-    for(i=0; i < n; ++i)
-      {
+    }
+    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])
-        {
+      if (!newCommands[cp->NumberOfCommands][i]) {
         break;
-        }
       }
-    if(i < n)
-      {
+    }
+    if (i < n) {
       /* Out of memory.  */
-      for(;i > 0; --i)
-        {
-        free(newCommands[cp->NumberOfCommands][i-1]);
-        }
+      for (; i > 0; --i) {
+        free(newCommands[cp->NumberOfCommands][i - 1]);
+      }
       free(newCommands);
       return 0;
-      }
-    newCommands[cp->NumberOfCommands][n] = 0;
     }
+    newCommands[cp->NumberOfCommands][n] = 0;
+  }
 
   /* Successfully allocated new command array.  Free the old array. */
   free(cp->Commands);
@@ -496,15 +465,13 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
 /*--------------------------------------------------------------------------*/
 void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return;
-    }
+  }
   cp->Timeout = timeout;
-  if(cp->Timeout < 0)
-    {
+  if (cp->Timeout < 0) {
     cp->Timeout = 0;
-    }
+  }
   // Force recomputation of TimeoutTime.
   cp->TimeoutTime.tv_sec = -1;
 }
@@ -512,32 +479,26 @@ void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
 /*--------------------------------------------------------------------------*/
 int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return 0;
-    }
-  if(cp->WorkingDirectory == dir)
-    {
+  }
+  if (cp->WorkingDirectory == dir) {
     return 1;
-    }
-  if(cp->WorkingDirectory && dir && strcmp(cp->WorkingDirectory, dir) == 0)
-    {
+  }
+  if (cp->WorkingDirectory && dir && strcmp(cp->WorkingDirectory, dir) == 0) {
     return 1;
-    }
-  if(cp->WorkingDirectory)
-    {
+  }
+  if (cp->WorkingDirectory) {
     free(cp->WorkingDirectory);
     cp->WorkingDirectory = 0;
-    }
-  if(dir)
-    {
+  }
+  if (dir) {
     cp->WorkingDirectory = (char*)malloc(strlen(dir) + 1);
-    if(!cp->WorkingDirectory)
-      {
+    if (!cp->WorkingDirectory) {
       return 0;
-      }
-    strcpy(cp->WorkingDirectory, dir);
     }
+    strcpy(cp->WorkingDirectory, dir);
+  }
   return 1;
 }
 
@@ -545,65 +506,70 @@ int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
 int kwsysProcess_SetPipeFile(kwsysProcess* cp, int prPipe, const char* file)
 {
   char** pfile;
-  if(!cp)
-    {
+  if (!cp) {
     return 0;
-    }
-  switch(prPipe)
-    {
-    case kwsysProcess_Pipe_STDIN: pfile = &cp->PipeFileSTDIN; break;
-    case kwsysProcess_Pipe_STDOUT: pfile = &cp->PipeFileSTDOUT; break;
-    case kwsysProcess_Pipe_STDERR: pfile = &cp->PipeFileSTDERR; break;
-    default: return 0;
-    }
-  if(*pfile)
-    {
+  }
+  switch (prPipe) {
+    case kwsysProcess_Pipe_STDIN:
+      pfile = &cp->PipeFileSTDIN;
+      break;
+    case kwsysProcess_Pipe_STDOUT:
+      pfile = &cp->PipeFileSTDOUT;
+      break;
+    case kwsysProcess_Pipe_STDERR:
+      pfile = &cp->PipeFileSTDERR;
+      break;
+    default:
+      return 0;
+  }
+  if (*pfile) {
     free(*pfile);
     *pfile = 0;
-    }
-  if(file)
-    {
-    *pfile = (char*)malloc(strlen(file)+1);
-    if(!*pfile)
-      {
+  }
+  if (file) {
+    *pfile = (char*)malloc(strlen(file) + 1);
+    if (!*pfile) {
       return 0;
-      }
-    strcpy(*pfile, file);
     }
+    strcpy(*pfile, file);
+  }
 
   /* If we are redirecting the pipe, do not share it or use a native
      pipe.  */
-  if(*pfile)
-    {
+  if (*pfile) {
     kwsysProcess_SetPipeNative(cp, prPipe, 0);
     kwsysProcess_SetPipeShared(cp, prPipe, 0);
-    }
+  }
   return 1;
 }
 
 /*--------------------------------------------------------------------------*/
 void kwsysProcess_SetPipeShared(kwsysProcess* cp, int prPipe, int shared)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return;
-    }
+  }
 
-  switch(prPipe)
-    {
-    case kwsysProcess_Pipe_STDIN: cp->PipeSharedSTDIN = shared?1:0; break;
-    case kwsysProcess_Pipe_STDOUT: cp->PipeSharedSTDOUT = shared?1:0; break;
-    case kwsysProcess_Pipe_STDERR: cp->PipeSharedSTDERR = shared?1:0; break;
-    default: return;
-    }
+  switch (prPipe) {
+    case kwsysProcess_Pipe_STDIN:
+      cp->PipeSharedSTDIN = shared ? 1 : 0;
+      break;
+    case kwsysProcess_Pipe_STDOUT:
+      cp->PipeSharedSTDOUT = shared ? 1 : 0;
+      break;
+    case kwsysProcess_Pipe_STDERR:
+      cp->PipeSharedSTDERR = shared ? 1 : 0;
+      break;
+    default:
+      return;
+  }
 
   /* If we are sharing the pipe, do not redirect it to a file or use a
      native pipe.  */
-  if(shared)
-    {
+  if (shared) {
     kwsysProcess_SetPipeFile(cp, prPipe, 0);
     kwsysProcess_SetPipeNative(cp, prPipe, 0);
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -611,127 +577,130 @@ void kwsysProcess_SetPipeNative(kwsysProcess* cp, int prPipe, int p[2])
 {
   int* pPipeNative = 0;
 
-  if(!cp)
-    {
+  if (!cp) {
     return;
-    }
+  }
 
-  switch(prPipe)
-    {
-    case kwsysProcess_Pipe_STDIN: pPipeNative = cp->PipeNativeSTDIN; break;
-    case kwsysProcess_Pipe_STDOUT: pPipeNative = cp->PipeNativeSTDOUT; break;
-    case kwsysProcess_Pipe_STDERR: pPipeNative = cp->PipeNativeSTDERR; break;
-    default: return;
-    }
+  switch (prPipe) {
+    case kwsysProcess_Pipe_STDIN:
+      pPipeNative = cp->PipeNativeSTDIN;
+      break;
+    case kwsysProcess_Pipe_STDOUT:
+      pPipeNative = cp->PipeNativeSTDOUT;
+      break;
+    case kwsysProcess_Pipe_STDERR:
+      pPipeNative = cp->PipeNativeSTDERR;
+      break;
+    default:
+      return;
+  }
 
   /* Copy the native pipe descriptors provided.  */
-  if(p)
-    {
+  if (p) {
     pPipeNative[0] = p[0];
     pPipeNative[1] = p[1];
-    }
-  else
-    {
+  } else {
     pPipeNative[0] = -1;
     pPipeNative[1] = -1;
-    }
+  }
 
   /* If we are using a native pipe, do not share it or redirect it to
      a file.  */
-  if(p)
-    {
+  if (p) {
     kwsysProcess_SetPipeFile(cp, prPipe, 0);
     kwsysProcess_SetPipeShared(cp, prPipe, 0);
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
 int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return 0;
-    }
+  }
 
-  switch(optionId)
-    {
-    case kwsysProcess_Option_Detach: return cp->OptionDetach;
-    case kwsysProcess_Option_MergeOutput: return cp->MergeOutput;
-    case kwsysProcess_Option_Verbatim: return cp->Verbatim;
+  switch (optionId) {
+    case kwsysProcess_Option_Detach:
+      return cp->OptionDetach;
+    case kwsysProcess_Option_MergeOutput:
+      return cp->MergeOutput;
+    case kwsysProcess_Option_Verbatim:
+      return cp->Verbatim;
     case kwsysProcess_Option_CreateProcessGroup:
       return cp->CreateProcessGroup;
-    default: return 0;
-    }
+    default:
+      return 0;
+  }
 }
 
 /*--------------------------------------------------------------------------*/
 void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return;
-    }
+  }
 
-  switch(optionId)
-    {
-    case kwsysProcess_Option_Detach: cp->OptionDetach = value; break;
-    case kwsysProcess_Option_MergeOutput: cp->MergeOutput = value; break;
-    case kwsysProcess_Option_Verbatim: cp->Verbatim = value; break;
+  switch (optionId) {
+    case kwsysProcess_Option_Detach:
+      cp->OptionDetach = value;
+      break;
+    case kwsysProcess_Option_MergeOutput:
+      cp->MergeOutput = value;
+      break;
+    case kwsysProcess_Option_Verbatim:
+      cp->Verbatim = value;
+      break;
     case kwsysProcess_Option_CreateProcessGroup:
-      cp->CreateProcessGroup = value; break;
-    default: break;
-    }
+      cp->CreateProcessGroup = value;
+      break;
+    default:
+      break;
+  }
 }
 
 /*--------------------------------------------------------------------------*/
 int kwsysProcess_GetState(kwsysProcess* cp)
 {
-  return cp? cp->State : kwsysProcess_State_Error;
+  return cp ? cp->State : kwsysProcess_State_Error;
 }
 
 /*--------------------------------------------------------------------------*/
 int kwsysProcess_GetExitException(kwsysProcess* cp)
 {
-  return cp? cp->ExitException : kwsysProcess_Exception_Other;
+  return cp ? cp->ExitException : kwsysProcess_Exception_Other;
 }
 
 /*--------------------------------------------------------------------------*/
 int kwsysProcess_GetExitCode(kwsysProcess* cp)
 {
-  return cp? cp->ExitCode : 0;
+  return cp ? cp->ExitCode : 0;
 }
 
 /*--------------------------------------------------------------------------*/
 int kwsysProcess_GetExitValue(kwsysProcess* cp)
 {
-  return cp? cp->ExitValue : -1;
+  return cp ? cp->ExitValue : -1;
 }
 
 /*--------------------------------------------------------------------------*/
 const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return "Process management structure could not be allocated";
-    }
-  else if(cp->State == kwsysProcess_State_Error)
-    {
+  } else if (cp->State == kwsysProcess_State_Error) {
     return cp->ErrorMessage;
-    }
+  }
   return "Success";
 }
 
 /*--------------------------------------------------------------------------*/
 const char* kwsysProcess_GetExceptionString(kwsysProcess* cp)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return "GetExceptionString called with NULL process management structure";
-    }
-  else if(cp->State == kwsysProcess_State_Exception)
-    {
+  } else if (cp->State == kwsysProcess_State_Exception) {
     return cp->ExitExceptionString;
-    }
+  }
   return "No exception";
 }
 
@@ -741,231 +710,193 @@ void kwsysProcess_Execute(kwsysProcess* cp)
   int i;
 
   /* Do not execute a second copy simultaneously.  */
-  if(!cp || cp->State == kwsysProcess_State_Executing)
-    {
+  if (!cp || cp->State == kwsysProcess_State_Executing) {
     return;
-    }
+  }
 
   /* Make sure we have something to run.  */
-  if(cp->NumberOfCommands < 1)
-    {
+  if (cp->NumberOfCommands < 1) {
     strcpy(cp->ErrorMessage, "No command");
     cp->State = kwsysProcess_State_Error;
     return;
-    }
+  }
 
   /* Initialize the control structure for a new process.  */
-  if(!kwsysProcessInitialize(cp))
-    {
+  if (!kwsysProcessInitialize(cp)) {
     strcpy(cp->ErrorMessage, "Out of memory");
     cp->State = kwsysProcess_State_Error;
     return;
-    }
+  }
 
 #if defined(__VMS)
   /* Make sure pipes behave like streams on VMS.  */
-  if(!kwsysProcessSetVMSFeature("DECC$STREAM_PIPE", 1))
-    {
+  if (!kwsysProcessSetVMSFeature("DECC$STREAM_PIPE", 1)) {
     kwsysProcessCleanup(cp, 1);
     return;
-    }
+  }
 #endif
 
   /* Save the real working directory of this process and change to
      the working directory for the child processes.  This is needed
      to make pipe file paths evaluate correctly.  */
-  if(cp->WorkingDirectory)
-    {
+  if (cp->WorkingDirectory) {
     int r;
-    if(!getcwd(cp->RealWorkingDirectory,
-               (size_t)(cp->RealWorkingDirectoryLength)))
-      {
+    if (!getcwd(cp->RealWorkingDirectory,
+                (size_t)(cp->RealWorkingDirectoryLength))) {
       kwsysProcessCleanup(cp, 1);
       return;
-      }
+    }
 
     /* Some platforms specify that the chdir call may be
        interrupted.  Repeat the call until it finishes.  */
-    while(((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR));
-    if(r < 0)
-      {
+    while (((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR))
+      ;
+    if (r < 0) {
       kwsysProcessCleanup(cp, 1);
       return;
-      }
     }
+  }
 
   /* If not running a detached child, add this object to the global
      set of process objects that wish to be notified when a child
      exits.  */
-  if(!cp->OptionDetach)
-    {
-    if(!kwsysProcessesAdd(cp))
-      {
+  if (!cp->OptionDetach) {
+    if (!kwsysProcessesAdd(cp)) {
       kwsysProcessCleanup(cp, 1);
       return;
-      }
     }
+  }
 
   /* Setup the stdin pipe for the first process.  */
-  if(cp->PipeFileSTDIN)
-    {
+  if (cp->PipeFileSTDIN) {
     /* Open a file for the child's stdin to read.  */
     cp->PipeChildStd[0] = open(cp->PipeFileSTDIN, O_RDONLY);
-    if(cp->PipeChildStd[0] < 0)
-      {
+    if (cp->PipeChildStd[0] < 0) {
       kwsysProcessCleanup(cp, 1);
       return;
-      }
+    }
 
     /* Set close-on-exec flag on the pipe's end.  */
-    if(fcntl(cp->PipeChildStd[0], F_SETFD, FD_CLOEXEC) < 0)
-      {
+    if (fcntl(cp->PipeChildStd[0], F_SETFD, FD_CLOEXEC) < 0) {
       kwsysProcessCleanup(cp, 1);
       return;
-      }
     }
-  else if(cp->PipeSharedSTDIN)
-    {
+  } else if (cp->PipeSharedSTDIN) {
     cp->PipeChildStd[0] = 0;
-    }
-  else if(cp->PipeNativeSTDIN[0] >= 0)
-    {
+  } else if (cp->PipeNativeSTDIN[0] >= 0) {
     cp->PipeChildStd[0] = cp->PipeNativeSTDIN[0];
 
     /* Set close-on-exec flag on the pipe's ends.  The read end will
        be dup2-ed into the stdin descriptor after the fork but before
        the exec.  */
-    if((fcntl(cp->PipeNativeSTDIN[0], F_SETFD, FD_CLOEXEC) < 0) ||
-       (fcntl(cp->PipeNativeSTDIN[1], F_SETFD, FD_CLOEXEC) < 0))
-      {
+    if ((fcntl(cp->PipeNativeSTDIN[0], F_SETFD, FD_CLOEXEC) < 0) ||
+        (fcntl(cp->PipeNativeSTDIN[1], F_SETFD, FD_CLOEXEC) < 0)) {
       kwsysProcessCleanup(cp, 1);
       return;
-      }
     }
-  else
-    {
+  } else {
     cp->PipeChildStd[0] = -1;
-    }
+  }
 
   /* Create the output pipe for the last process.
      We always create this so the pipe can be passed to select even if
      it will report closed immediately.  */
   {
-  /* Create the pipe.  */
-  int p[2];
-  if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
-    {
-    kwsysProcessCleanup(cp, 1);
-    return;
+    /* Create the pipe.  */
+    int p[2];
+    if (pipe(p KWSYSPE_VMS_NONBLOCK) < 0) {
+      kwsysProcessCleanup(cp, 1);
+      return;
     }
 
-  /* Store the pipe.  */
-  cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = p[0];
-  cp->PipeChildStd[1] = p[1];
+    /* Store the pipe.  */
+    cp->PipeReadEnds[KWSYSPE_PIPE_STDOUT] = p[0];
+    cp->PipeChildStd[1] = p[1];
 
-  /* Set close-on-exec flag on the pipe's ends.  */
-  if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
-     (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
-    {
-    kwsysProcessCleanup(cp, 1);
-    return;
+    /* Set close-on-exec flag on the pipe's ends.  */
+    if ((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
+        (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0)) {
+      kwsysProcessCleanup(cp, 1);
+      return;
     }
 
-  /* Set to non-blocking in case select lies, or for the polling
-     implementation.  */
-  if(!kwsysProcessSetNonBlocking(p[0]))
-    {
-    kwsysProcessCleanup(cp, 1);
-    return;
+    /* Set to non-blocking in case select lies, or for the polling
+       implementation.  */
+    if (!kwsysProcessSetNonBlocking(p[0])) {
+      kwsysProcessCleanup(cp, 1);
+      return;
     }
   }
 
-  if (cp->PipeFileSTDOUT)
-    {
+  if (cp->PipeFileSTDOUT) {
     /* Use a file for stdout.  */
-    if(!kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[1],
-                                        cp->PipeFileSTDOUT))
-      {
+    if (!kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[1],
+                                         cp->PipeFileSTDOUT)) {
       kwsysProcessCleanup(cp, 1);
       return;
-      }
     }
-  else if (cp->PipeSharedSTDOUT)
-    {
+  } else if (cp->PipeSharedSTDOUT) {
     /* Use the parent stdout.  */
     kwsysProcessCleanupDescriptor(&cp->PipeChildStd[1]);
     cp->PipeChildStd[1] = 1;
-    }
-  else if (cp->PipeNativeSTDOUT[1] >= 0)
-    {
+  } else if (cp->PipeNativeSTDOUT[1] >= 0) {
     /* Use the given descriptor for stdout.  */
-    if(!kwsysProcessSetupOutputPipeNative(&cp->PipeChildStd[1],
-                                          cp->PipeNativeSTDOUT))
-      {
+    if (!kwsysProcessSetupOutputPipeNative(&cp->PipeChildStd[1],
+                                           cp->PipeNativeSTDOUT)) {
       kwsysProcessCleanup(cp, 1);
       return;
-      }
     }
+  }
 
   /* Create stderr pipe to be shared by all processes in the pipeline.
      We always create this so the pipe can be passed to select even if
      it will report closed immediately.  */
   {
-  /* Create the pipe.  */
-  int p[2];
-  if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
-    {
-    kwsysProcessCleanup(cp, 1);
-    return;
+    /* Create the pipe.  */
+    int p[2];
+    if (pipe(p KWSYSPE_VMS_NONBLOCK) < 0) {
+      kwsysProcessCleanup(cp, 1);
+      return;
     }
 
-  /* Store the pipe.  */
-  cp->PipeReadEnds[KWSYSPE_PIPE_STDERR] = p[0];
-  cp->PipeChildStd[2] = p[1];
+    /* Store the pipe.  */
+    cp->PipeReadEnds[KWSYSPE_PIPE_STDERR] = p[0];
+    cp->PipeChildStd[2] = p[1];
 
-  /* Set close-on-exec flag on the pipe's ends.  */
-  if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
-     (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
-    {
-    kwsysProcessCleanup(cp, 1);
-    return;
+    /* Set close-on-exec flag on the pipe's ends.  */
+    if ((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
+        (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0)) {
+      kwsysProcessCleanup(cp, 1);
+      return;
     }
 
-  /* Set to non-blocking in case select lies, or for the polling
-     implementation.  */
-  if(!kwsysProcessSetNonBlocking(p[0]))
-    {
-    kwsysProcessCleanup(cp, 1);
-    return;
+    /* Set to non-blocking in case select lies, or for the polling
+       implementation.  */
+    if (!kwsysProcessSetNonBlocking(p[0])) {
+      kwsysProcessCleanup(cp, 1);
+      return;
     }
   }
 
-  if (cp->PipeFileSTDERR)
-    {
+  if (cp->PipeFileSTDERR) {
     /* Use a file for stderr.  */
-    if(!kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[2],
-                                        cp->PipeFileSTDERR))
-      {
+    if (!kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[2],
+                                         cp->PipeFileSTDERR)) {
       kwsysProcessCleanup(cp, 1);
       return;
-      }
     }
-  else if (cp->PipeSharedSTDERR)
-    {
+  } else if (cp->PipeSharedSTDERR) {
     /* Use the parent stderr.  */
     kwsysProcessCleanupDescriptor(&cp->PipeChildStd[2]);
     cp->PipeChildStd[2] = 2;
-    }
-  else if (cp->PipeNativeSTDERR[1] >= 0)
-    {
+  } else if (cp->PipeNativeSTDERR[1] >= 0) {
     /* Use the given handle for stderr.  */
-    if(!kwsysProcessSetupOutputPipeNative(&cp->PipeChildStd[2],
-                                          cp->PipeNativeSTDERR))
-      {
+    if (!kwsysProcessSetupOutputPipeNative(&cp->PipeChildStd[2],
+                                           cp->PipeNativeSTDERR)) {
       kwsysProcessCleanup(cp, 1);
       return;
-      }
     }
+  }
 
   /* The timeout period starts now.  */
   cp->StartTime = kwsysProcessTimeGetCurrent();
@@ -974,96 +905,82 @@ void kwsysProcess_Execute(kwsysProcess* cp)
 
   /* Create the pipeline of processes.  */
   {
-  kwsysProcessCreateInformation si = {-1, -1, -1, {-1, -1}};
-  int nextStdIn = cp->PipeChildStd[0];
-  for(i=0; i < cp->NumberOfCommands; ++i)
-    {
-    /* Setup the process's pipes.  */
-    si.StdIn = nextStdIn;
-    if (i == cp->NumberOfCommands-1)
-      {
-      nextStdIn = -1;
-      si.StdOut = cp->PipeChildStd[1];
-      }
-    else
-      {
-      /* Create a pipe to sit between the children.  */
-      int p[2] = {-1,-1};
-      if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
-        {
-        if (nextStdIn != cp->PipeChildStd[0])
-          {
-          kwsysProcessCleanupDescriptor(&nextStdIn);
+    kwsysProcessCreateInformation si = { -1, -1, -1, { -1, -1 } };
+    int nextStdIn = cp->PipeChildStd[0];
+    for (i = 0; i < cp->NumberOfCommands; ++i) {
+      /* Setup the process's pipes.  */
+      si.StdIn = nextStdIn;
+      if (i == cp->NumberOfCommands - 1) {
+        nextStdIn = -1;
+        si.StdOut = cp->PipeChildStd[1];
+      } else {
+        /* Create a pipe to sit between the children.  */
+        int p[2] = { -1, -1 };
+        if (pipe(p KWSYSPE_VMS_NONBLOCK) < 0) {
+          if (nextStdIn != cp->PipeChildStd[0]) {
+            kwsysProcessCleanupDescriptor(&nextStdIn);
           }
-        kwsysProcessCleanup(cp, 1);
-        return;
+          kwsysProcessCleanup(cp, 1);
+          return;
         }
 
-      /* Set close-on-exec flag on the pipe's ends.  */
-      if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
-         (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
-        {
-        close(p[0]);
-        close(p[1]);
-        if (nextStdIn != cp->PipeChildStd[0])
-          {
-          kwsysProcessCleanupDescriptor(&nextStdIn);
+        /* Set close-on-exec flag on the pipe's ends.  */
+        if ((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
+            (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0)) {
+          close(p[0]);
+          close(p[1]);
+          if (nextStdIn != cp->PipeChildStd[0]) {
+            kwsysProcessCleanupDescriptor(&nextStdIn);
           }
-        kwsysProcessCleanup(cp, 1);
-        return;
+          kwsysProcessCleanup(cp, 1);
+          return;
         }
-      nextStdIn = p[0];
-      si.StdOut = p[1];
+        nextStdIn = p[0];
+        si.StdOut = p[1];
       }
-    si.StdErr = cp->MergeOutput? cp->PipeChildStd[1] : cp->PipeChildStd[2];
+      si.StdErr = cp->MergeOutput ? cp->PipeChildStd[1] : cp->PipeChildStd[2];
 
-    {
-    int res = kwsysProcessCreate(cp, i, &si);
-
-    /* Close our copies of pipes used between children.  */
-    if (si.StdIn != cp->PipeChildStd[0])
-      {
-      kwsysProcessCleanupDescriptor(&si.StdIn);
-      }
-    if (si.StdOut != cp->PipeChildStd[1])
-      {
-      kwsysProcessCleanupDescriptor(&si.StdOut);
-      }
-    if (si.StdErr != cp->PipeChildStd[2] && !cp->MergeOutput)
       {
-      kwsysProcessCleanupDescriptor(&si.StdErr);
-      }
+        int res = kwsysProcessCreate(cp, i, &si);
 
-    if(!res)
-      {
-      kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
-      kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
-      if (nextStdIn != cp->PipeChildStd[0])
-        {
-        kwsysProcessCleanupDescriptor(&nextStdIn);
+        /* Close our copies of pipes used between children.  */
+        if (si.StdIn != cp->PipeChildStd[0]) {
+          kwsysProcessCleanupDescriptor(&si.StdIn);
+        }
+        if (si.StdOut != cp->PipeChildStd[1]) {
+          kwsysProcessCleanupDescriptor(&si.StdOut);
+        }
+        if (si.StdErr != cp->PipeChildStd[2] && !cp->MergeOutput) {
+          kwsysProcessCleanupDescriptor(&si.StdErr);
+        }
+
+        if (!res) {
+          kwsysProcessCleanupDescriptor(&si.ErrorPipe[0]);
+          kwsysProcessCleanupDescriptor(&si.ErrorPipe[1]);
+          if (nextStdIn != cp->PipeChildStd[0]) {
+            kwsysProcessCleanupDescriptor(&nextStdIn);
+          }
+          kwsysProcessCleanup(cp, 1);
+          return;
         }
-      kwsysProcessCleanup(cp, 1);
-      return;
       }
     }
-    }
   }
 
   /* The parent process does not need the child's pipe ends.  */
-  for (i=0; i < 3; ++i)
-    {
+  for (i = 0; i < 3; ++i) {
     kwsysProcessCleanupDescriptor(&cp->PipeChildStd[i]);
-    }
+  }
 
   /* Restore the working directory. */
-  if(cp->RealWorkingDirectory)
-    {
+  if (cp->RealWorkingDirectory) {
     /* Some platforms specify that the chdir call may be
        interrupted.  Repeat the call until it finishes.  */
-    while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
+    while ((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR))
+      ;
     free(cp->RealWorkingDirectory);
     cp->RealWorkingDirectory = 0;
-    }
+  }
 
   /* All the pipes are now open.  */
   cp->PipesLeft = KWSYSPE_PIPE_COUNT;
@@ -1077,11 +994,10 @@ void kwsysProcess_Execute(kwsysProcess* cp)
 kwsysEXPORT void kwsysProcess_Disown(kwsysProcess* cp)
 {
   /* Make sure a detached child process is running.  */
-  if(!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
-     cp->TimeoutExpired || cp->Killed)
-    {
+  if (!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
+      cp->TimeoutExpired || cp->Killed) {
     return;
-    }
+  }
 
   /* Close all the pipes safely.  */
   kwsysProcessClosePipes(cp);
@@ -1109,81 +1025,62 @@ static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
 int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
                              double* userTimeout)
 {
-  kwsysProcessTime userStartTime = {0, 0};
-  kwsysProcessWaitData wd =
-    {
-      0,
-      kwsysProcess_Pipe_None,
-      0,
-      0,
-      {0, 0}
-    };
+  kwsysProcessTime userStartTime = { 0, 0 };
+  kwsysProcessWaitData wd = { 0, kwsysProcess_Pipe_None, 0, 0, { 0, 0 } };
   wd.UserTimeout = userTimeout;
   /* Make sure we are executing a process.  */
-  if(!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
-     cp->TimeoutExpired)
-    {
+  if (!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
+      cp->TimeoutExpired) {
     return kwsysProcess_Pipe_None;
-    }
+  }
 
   /* Record the time at which user timeout period starts.  */
-  if(userTimeout)
-    {
+  if (userTimeout) {
     userStartTime = kwsysProcessTimeGetCurrent();
-    }
+  }
 
   /* Calculate the time at which a timeout will expire, and whether it
      is the user or process timeout.  */
-  wd.User = kwsysProcessGetTimeoutTime(cp, userTimeout,
-                                       &wd.TimeoutTime);
+  wd.User = kwsysProcessGetTimeoutTime(cp, userTimeout, &wd.TimeoutTime);
 
   /* Data can only be available when pipes are open.  If the process
      is not running, cp->PipesLeft will be 0.  */
-  while(cp->PipesLeft > 0 &&
-        !kwsysProcessWaitForPipe(cp, data, length, &wd)) {}
+  while (cp->PipesLeft > 0 &&
+         !kwsysProcessWaitForPipe(cp, data, length, &wd)) {
+  }
 
   /* Update the user timeout.  */
-  if(userTimeout)
-    {
+  if (userTimeout) {
     kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent();
-    kwsysProcessTime difference = kwsysProcessTimeSubtract(userEndTime,
-                                                           userStartTime);
+    kwsysProcessTime difference =
+      kwsysProcessTimeSubtract(userEndTime, userStartTime);
     double d = kwsysProcessTimeToDouble(difference);
     *userTimeout -= d;
-    if(*userTimeout < 0)
-      {
+    if (*userTimeout < 0) {
       *userTimeout = 0;
-      }
     }
+  }
 
   /* Check what happened.  */
-  if(wd.PipeId)
-    {
+  if (wd.PipeId) {
     /* Data are ready on a pipe.  */
     return wd.PipeId;
-    }
-  else if(wd.Expired)
-    {
+  } else if (wd.Expired) {
     /* A timeout has expired.  */
-    if(wd.User)
-      {
+    if (wd.User) {
       /* The user timeout has expired.  It has no time left.  */
       return kwsysProcess_Pipe_Timeout;
-      }
-    else
-      {
+    } else {
       /* The process timeout has expired.  Kill the children now.  */
       kwsysProcess_Kill(cp);
       cp->Killed = 0;
       cp->TimeoutExpired = 1;
       return kwsysProcess_Pipe_None;
-      }
     }
-  else
-    {
+  } else {
     /* No pipes are left open.  */
     return kwsysProcess_Pipe_None;
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -1202,11 +1099,9 @@ static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
      call to select.  According to "man select_tut" we must deal
      with all descriptors reported by a call to select before
      passing them to another select call.  */
-  for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
-    {
-    if(cp->PipeReadEnds[i] >= 0 &&
-       FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
-      {
+  for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
+    if (cp->PipeReadEnds[i] >= 0 &&
+        FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet)) {
       kwsysProcess_ssize_t n;
 
       /* We are handling this pipe now.  Remove it from the set.  */
@@ -1214,108 +1109,91 @@ static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
 
       /* The pipe is ready to read without blocking.  Keep trying to
          read until the operation is not interrupted.  */
-      while(((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
-                       KWSYSPE_PIPE_BUFFER_SIZE)) < 0) && (errno == EINTR));
-      if(n > 0)
-        {
+      while (((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
+                        KWSYSPE_PIPE_BUFFER_SIZE)) < 0) &&
+             (errno == EINTR))
+        ;
+      if (n > 0) {
         /* We have data on this pipe.  */
-        if(i == KWSYSPE_PIPE_SIGNAL)
-          {
+        if (i == KWSYSPE_PIPE_SIGNAL) {
           /* A child process has terminated.  */
           kwsysProcessDestroy(cp);
-          }
-        else if(data && length)
-          {
+        } else if (data && length) {
           /* Report this data.  */
           *data = cp->PipeBuffer;
           *length = (int)(n);
-          switch(i)
-            {
+          switch (i) {
             case KWSYSPE_PIPE_STDOUT:
-              wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
+              wd->PipeId = kwsysProcess_Pipe_STDOUT;
+              break;
             case KWSYSPE_PIPE_STDERR:
-              wd->PipeId = kwsysProcess_Pipe_STDERR; break;
-            };
+              wd->PipeId = kwsysProcess_Pipe_STDERR;
+              break;
+          };
           return 1;
-          }
         }
-      else if(n < 0 && errno == EAGAIN)
-        {
+      } else if (n < 0 && errno == EAGAIN) {
         /* No data are really ready.  The select call lied.  See the
            "man select" page on Linux for cases when this occurs.  */
-        }
-      else
-        {
+      } else {
         /* We are done reading from this pipe.  */
         kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
         --cp->PipesLeft;
-        }
       }
     }
+  }
 
   /* If we have data, break early.  */
-  if(wd->PipeId)
-    {
+  if (wd->PipeId) {
     return 1;
-    }
+  }
 
   /* Make sure the set is empty (it should always be empty here
      anyway).  */
   FD_ZERO(&cp->PipeSet);
 
   /* Setup a timeout if required.  */
-  if(wd->TimeoutTime.tv_sec < 0)
-    {
+  if (wd->TimeoutTime.tv_sec < 0) {
     timeout = 0;
-    }
-  else
-    {
+  } else {
     timeout = &timeoutLength;
-    }
-  if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime,
-                                wd->User?wd->UserTimeout:0,
-                                &timeoutLength, 0))
-    {
+  }
+  if (kwsysProcessGetTimeoutLeft(
+        &wd->TimeoutTime, wd->User ? wd->UserTimeout : 0, &timeoutLength, 0)) {
     /* Timeout has already expired.  */
     wd->Expired = 1;
     return 1;
-    }
+  }
 
   /* Add the pipe reading ends that are still open.  */
   max = -1;
-  for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
-    {
-    if(cp->PipeReadEnds[i] >= 0)
-      {
+  for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
+    if (cp->PipeReadEnds[i] >= 0) {
       FD_SET(cp->PipeReadEnds[i], &cp->PipeSet);
-      if(cp->PipeReadEnds[i] > max)
-        {
+      if (cp->PipeReadEnds[i] > max) {
         max = cp->PipeReadEnds[i];
-        }
       }
     }
+  }
 
   /* Make sure we have a non-empty set.  */
-  if(max < 0)
-    {
+  if (max < 0) {
     /* All pipes have closed.  Child has terminated.  */
     return 1;
-    }
+  }
 
   /* Run select to block until data are available.  Repeat call
      until it is not interrupted.  */
-  while(((numReady = select(max+1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
-        (errno == EINTR));
+  while (((numReady = select(max + 1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
+         (errno == EINTR))
+    ;
 
   /* Check result of select.  */
-  if(numReady == 0)
-    {
+  if (numReady == 0) {
     /* Select's timeout expired.  */
     wd->Expired = 1;
     return 1;
-    }
-  else if(numReady < 0)
-    {
+  } else if (numReady < 0) {
     /* Select returned an error.  Leave the error description in the
        pipe buffer.  */
     strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
@@ -1324,98 +1202,84 @@ static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
     kwsysProcess_Kill(cp);
     cp->Killed = 0;
     cp->SelectError = 1;
-    }
+  }
 
   return 0;
 #else
   /* Poll pipes for data since we do not have select.  */
-  for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
-    {
-    if(cp->PipeReadEnds[i] >= 0)
-      {
+  for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
+    if (cp->PipeReadEnds[i] >= 0) {
       const int fd = cp->PipeReadEnds[i];
       int n = read(fd, cp->PipeBuffer, KWSYSPE_PIPE_BUFFER_SIZE);
-      if(n > 0)
-        {
+      if (n > 0) {
         /* We have data on this pipe.  */
-        if(i == KWSYSPE_PIPE_SIGNAL)
-          {
+        if (i == KWSYSPE_PIPE_SIGNAL) {
           /* A child process has terminated.  */
           kwsysProcessDestroy(cp);
-          }
-        else if(data && length)
-          {
+        } else if (data && length) {
           /* Report this data.  */
           *data = cp->PipeBuffer;
           *length = n;
-          switch(i)
-            {
+          switch (i) {
             case KWSYSPE_PIPE_STDOUT:
-              wd->PipeId = kwsysProcess_Pipe_STDOUT; break;
+              wd->PipeId = kwsysProcess_Pipe_STDOUT;
+              break;
             case KWSYSPE_PIPE_STDERR:
-              wd->PipeId = kwsysProcess_Pipe_STDERR; break;
-            };
-          }
-        return 1;
+              wd->PipeId = kwsysProcess_Pipe_STDERR;
+              break;
+          };
         }
-      else if (n == 0)  /* EOF */
-        {
-        /* We are done reading from this pipe.  */
+        return 1;
+      } else if (n == 0) /* EOF */
+      {
+/* We are done reading from this pipe.  */
 #if defined(__VMS)
-        if(!cp->CommandsLeft)
+        if (!cp->CommandsLeft)
 #endif
-          {
+        {
           kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
           --cp->PipesLeft;
-          }
         }
-      else if (n < 0)  /* error */
-        {
+      } else if (n < 0) /* error */
+      {
 #if defined(__VMS)
-        if(!cp->CommandsLeft)
-          {
+        if (!cp->CommandsLeft) {
           kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
           --cp->PipesLeft;
-          }
-        else
+        } else
 #endif
-        if((errno != EINTR) && (errno != EAGAIN))
-          {
-          strncpy(cp->ErrorMessage,strerror(errno),
-                  KWSYSPE_PIPE_BUFFER_SIZE);
+          if ((errno != EINTR) && (errno != EAGAIN)) {
+          strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
           /* Kill the children now.  */
           kwsysProcess_Kill(cp);
           cp->Killed = 0;
           cp->SelectError = 1;
           return 1;
-          }
         }
       }
     }
+  }
 
   /* If we have data, break early.  */
-  if(wd->PipeId)
-    {
+  if (wd->PipeId) {
     return 1;
-    }
+  }
 
-  if(kwsysProcessGetTimeoutLeft(&wd->TimeoutTime, wd->User?wd->UserTimeout:0,
-                                &timeoutLength, 1))
-    {
+  if (kwsysProcessGetTimeoutLeft(
+        &wd->TimeoutTime, wd->User ? wd->UserTimeout : 0, &timeoutLength, 1)) {
     /* Timeout has already expired.  */
     wd->Expired = 1;
     return 1;
-    }
+  }
 
   /* Sleep a little, try again. */
   {
-  unsigned int msec = ((timeoutLength.tv_sec * 1000) +
-                       (timeoutLength.tv_usec / 1000));
-  if (msec > 100000)
-    {
-    msec = 100000;  /* do not sleep more than 100 milliseconds at a time */
+    unsigned int msec =
+      ((timeoutLength.tv_sec * 1000) + (timeoutLength.tv_usec / 1000));
+    if (msec > 100000) {
+      msec = 100000; /* do not sleep more than 100 milliseconds at a time */
     }
-  kwsysProcess_usleep(msec);
+    kwsysProcess_usleep(msec);
   }
   return 0;
 #endif
@@ -1428,74 +1292,60 @@ int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
   int prPipe = 0;
 
   /* Make sure we are executing a process.  */
-  if(!cp || cp->State != kwsysProcess_State_Executing)
-    {
+  if (!cp || cp->State != kwsysProcess_State_Executing) {
     return 1;
-    }
+  }
 
   /* Wait for all the pipes to close.  Ignore all data.  */
-  while((prPipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0)
-    {
-    if(prPipe == kwsysProcess_Pipe_Timeout)
-      {
+  while ((prPipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0) {
+    if (prPipe == kwsysProcess_Pipe_Timeout) {
       return 0;
-      }
     }
+  }
 
   /* Check if there was an error in one of the waitpid calls.  */
-  if(cp->State == kwsysProcess_State_Error)
-    {
+  if (cp->State == kwsysProcess_State_Error) {
     /* The error message is already in its buffer.  Tell
        kwsysProcessCleanup to not create it.  */
     kwsysProcessCleanup(cp, 0);
     return 1;
-    }
+  }
 
   /* Check whether the child reported an error invoking the process.  */
-  if(cp->SelectError)
-    {
+  if (cp->SelectError) {
     /* The error message is already in its buffer.  Tell
        kwsysProcessCleanup to not create it.  */
     kwsysProcessCleanup(cp, 0);
     cp->State = kwsysProcess_State_Error;
     return 1;
-    }
+  }
 
   /* Use the status of the last process in the pipeline.  */
-  status = cp->CommandExitCodes[cp->NumberOfCommands-1];
+  status = cp->CommandExitCodes[cp->NumberOfCommands - 1];
 
   /* Determine the outcome.  */
-  if(cp->Killed)
-    {
+  if (cp->Killed) {
     /* We killed the child.  */
     cp->State = kwsysProcess_State_Killed;
-    }
-  else if(cp->TimeoutExpired)
-    {
+  } else if (cp->TimeoutExpired) {
     /* The timeout expired.  */
     cp->State = kwsysProcess_State_Expired;
-    }
-  else if(WIFEXITED(status))
-    {
+  } else if (WIFEXITED(status)) {
     /* The child exited normally.  */
     cp->State = kwsysProcess_State_Exited;
     cp->ExitException = kwsysProcess_Exception_None;
     cp->ExitCode = status;
     cp->ExitValue = (int)WEXITSTATUS(status);
-    }
-  else if(WIFSIGNALED(status))
-    {
+  } else if (WIFSIGNALED(status)) {
     /* The child received an unhandled signal.  */
     cp->State = kwsysProcess_State_Exception;
     cp->ExitCode = status;
     kwsysProcessSetExitException(cp, (int)WTERMSIG(status));
-    }
-  else
-    {
+  } else {
     /* Error getting the child return code.  */
     strcpy(cp->ErrorMessage, "Error getting child return code.");
     cp->State = kwsysProcess_State_Error;
-    }
+  }
 
   /* Normal cleanup.  */
   kwsysProcessCleanup(cp, 0);
@@ -1507,38 +1357,31 @@ void kwsysProcess_Interrupt(kwsysProcess* cp)
 {
   int i;
   /* Make sure we are executing a process.  */
-  if(!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired ||
-     cp->Killed)
-    {
+  if (!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired ||
+      cp->Killed) {
     return;
-    }
+  }
 
   /* Interrupt the children.  */
-  if (cp->CreateProcessGroup)
-    {
-    if(cp->ForkPIDs)
-      {
-      for(i=0; i < cp->NumberOfCommands; ++i)
-        {
+  if (cp->CreateProcessGroup) {
+    if (cp->ForkPIDs) {
+      for (i = 0; i < cp->NumberOfCommands; ++i) {
         /* Make sure the PID is still valid. */
-        if(cp->ForkPIDs[i])
-          {
+        if (cp->ForkPIDs[i]) {
           /* The user created a process group for this process.  The group ID
              is the process ID for the original process in the group.  */
           kill(-cp->ForkPIDs[i], SIGINT);
-          }
         }
       }
     }
-  else
-    {
+  } else {
     /* No process group was created.  Kill our own process group.
        NOTE:  While one could argue that we could call kill(cp->ForkPIDs[i],
        SIGINT) as a way to still interrupt the process even though it's not in
        a special group, this is not an option on Windows.  Therefore, we kill
        the current process group for consistency with Windows.  */
     kill(0, SIGINT);
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -1547,10 +1390,9 @@ void kwsysProcess_Kill(kwsysProcess* cp)
   int i;
 
   /* Make sure we are executing a process.  */
-  if(!cp || cp->State != kwsysProcess_State_Executing)
-    {
+  if (!cp || cp->State != kwsysProcess_State_Executing) {
     return;
-    }
+  }
 
   /* First close the child exit report pipe write end to avoid causing a
      SIGPIPE when the child terminates and our signal handler tries to
@@ -1566,19 +1408,18 @@ void kwsysProcess_Kill(kwsysProcess* cp)
 
   /* Kill the children.  */
   cp->Killed = 1;
-  for(i=0; i < cp->NumberOfCommands; ++i)
-    {
+  for (i = 0; i < cp->NumberOfCommands; ++i) {
     int status;
-    if(cp->ForkPIDs[i])
-      {
+    if (cp->ForkPIDs[i]) {
       /* Kill the child.  */
       kwsysProcessKill(cp->ForkPIDs[i]);
 
       /* Reap the child.  Keep trying until the call is not
          interrupted.  */
-      while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) && (errno == EINTR));
-      }
+      while ((waitpid(cp->ForkPIDs[i], &status, 0) < 0) && (errno == EINTR))
+        ;
     }
+  }
 
 #if defined(__APPLE__)
   /* Close all the pipe read ends.  Do this after killing the
@@ -1595,15 +1436,15 @@ void kwsysProcess_Kill(kwsysProcess* cp)
    compiler warnings.  */
 static void kwsysProcessVolatileFree(volatile void* p)
 {
-  /* clang has made it impossible to free memory that points to volatile
-     without first using special pragmas to disable a warning...  */
+/* clang has made it impossible to free memory that points to volatile
+   without first using special pragmas to disable a warning...  */
 #if defined(__clang__) && !defined(__INTEL_COMPILER)
-# pragma clang diagnostic push
-# pragma clang diagnostic ignored "-Wcast-qual"
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wcast-qual"
 #endif
   free((void*)p); /* The cast will silence most compilers, but not clang.  */
 #if defined(__clang__) && !defined(__INTEL_COMPILER)
-# pragma clang diagnostic pop
+#pragma clang diagnostic pop
 #endif
 }
 
@@ -1613,14 +1454,12 @@ static int kwsysProcessInitialize(kwsysProcess* cp)
 {
   int i;
   volatile pid_t* oldForkPIDs;
-  for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
-    {
+  for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
     cp->PipeReadEnds[i] = -1;
-    }
-  for(i=0; i < 3; ++i)
-    {
+  }
+  for (i = 0; i < 3; ++i) {
     cp->PipeChildStd[i] = -1;
-    }
+  }
   cp->SignalPipe = -1;
   cp->SelectError = 0;
   cp->StartTime.tv_sec = -1;
@@ -1642,36 +1481,31 @@ static int kwsysProcessInitialize(kwsysProcess* cp)
   strcpy(cp->ExitExceptionString, "No exception");
 
   oldForkPIDs = cp->ForkPIDs;
-  cp->ForkPIDs = (volatile pid_t*)malloc(
-    sizeof(volatile pid_t)*(size_t)(cp->NumberOfCommands));
-  if(oldForkPIDs)
-    {
+  cp->ForkPIDs = (volatile pid_t*)malloc(sizeof(volatile pid_t) *
+                                         (size_t)(cp->NumberOfCommands));
+  if (oldForkPIDs) {
     kwsysProcessVolatileFree(oldForkPIDs);
-    }
-  if(!cp->ForkPIDs)
-    {
+  }
+  if (!cp->ForkPIDs) {
     return 0;
-    }
-  for(i=0; i < cp->NumberOfCommands; ++i)
-    {
+  }
+  for (i = 0; i < cp->NumberOfCommands; ++i) {
     cp->ForkPIDs[i] = 0; /* can't use memset due to volatile */
-    }
+  }
 
-  if(cp->CommandExitCodes)
-    {
+  if (cp->CommandExitCodes) {
     free(cp->CommandExitCodes);
-    }
-  cp->CommandExitCodes = (int*)malloc(sizeof(int)*
-                                      (size_t)(cp->NumberOfCommands));
-  if(!cp->CommandExitCodes)
-    {
+  }
+  cp->CommandExitCodes =
+    (int*)malloc(sizeof(int) * (size_t)(cp->NumberOfCommands));
+  if (!cp->CommandExitCodes) {
     return 0;
-    }
-  memset(cp->CommandExitCodes, 0, sizeof(int)*(size_t)(cp->NumberOfCommands));
+  }
+  memset(cp->CommandExitCodes, 0,
+         sizeof(int) * (size_t)(cp->NumberOfCommands));
 
   /* Allocate memory to save the real working directory.  */
-  if ( cp->WorkingDirectory )
-    {
+  if (cp->WorkingDirectory) {
 #if defined(MAXPATHLEN)
     cp->RealWorkingDirectoryLength = MAXPATHLEN;
 #elif defined(PATH_MAX)
@@ -1681,11 +1515,10 @@ static int kwsysProcessInitialize(kwsysProcess* cp)
 #endif
     cp->RealWorkingDirectory =
       (char*)malloc((size_t)(cp->RealWorkingDirectoryLength));
-    if(!cp->RealWorkingDirectory)
-      {
+    if (!cp->RealWorkingDirectory) {
       return 0;
-      }
     }
+  }
 
   return 1;
 }
@@ -1697,86 +1530,77 @@ static void kwsysProcessCleanup(kwsysProcess* cp, int error)
 {
   int i;
 
-  if(error)
-    {
+  if (error) {
     /* We are cleaning up due to an error.  Report the error message
        if one has not been provided already.  */
-    if(cp->ErrorMessage[0] == 0)
-      {
+    if (cp->ErrorMessage[0] == 0) {
       strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
-      }
+    }
 
     /* Set the error state.  */
     cp->State = kwsysProcess_State_Error;
 
     /* Kill any children already started.  */
-    if(cp->ForkPIDs)
-      {
+    if (cp->ForkPIDs) {
       int status;
-      for(i=0; i < cp->NumberOfCommands; ++i)
-        {
-        if(cp->ForkPIDs[i])
-          {
+      for (i = 0; i < cp->NumberOfCommands; ++i) {
+        if (cp->ForkPIDs[i]) {
           /* Kill the child.  */
           kwsysProcessKill(cp->ForkPIDs[i]);
 
           /* Reap the child.  Keep trying until the call is not
              interrupted.  */
-          while((waitpid(cp->ForkPIDs[i], &status, 0) < 0) &&
-                (errno == EINTR));
-          }
+          while ((waitpid(cp->ForkPIDs[i], &status, 0) < 0) &&
+                 (errno == EINTR))
+            ;
         }
       }
+    }
 
     /* Restore the working directory.  */
-    if(cp->RealWorkingDirectory)
-      {
-      while((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR));
-      }
+    if (cp->RealWorkingDirectory) {
+      while ((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR))
+        ;
     }
+  }
 
   /* If not creating a detached child, remove this object from the
      global set of process objects that wish to be notified when a
      child exits.  */
-  if(!cp->OptionDetach)
-    {
+  if (!cp->OptionDetach) {
     kwsysProcessesRemove(cp);
-    }
+  }
 
   /* Free memory.  */
-  if(cp->ForkPIDs)
-    {
+  if (cp->ForkPIDs) {
     kwsysProcessVolatileFree(cp->ForkPIDs);
     cp->ForkPIDs = 0;
-    }
-  if(cp->RealWorkingDirectory)
-    {
+  }
+  if (cp->RealWorkingDirectory) {
     free(cp->RealWorkingDirectory);
     cp->RealWorkingDirectory = 0;
-    }
+  }
 
   /* Close pipe handles.  */
-  for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
-    {
+  for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
     kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
-    }
-  for(i=0; i < 3; ++i)
-    {
+  }
+  for (i = 0; i < 3; ++i) {
     kwsysProcessCleanupDescriptor(&cp->PipeChildStd[i]);
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
 /* Close the given file descriptor if it is open.  Reset its value to -1.  */
 static void kwsysProcessCleanupDescriptor(int* pfd)
 {
-  if(pfd && *pfd > 2)
-    {
+  if (pfd && *pfd > 2) {
     /* Keep trying to close until it is not interrupted by a
      * signal.  */
-    while((close(*pfd) < 0) && (errno == EINTR));
+    while ((close(*pfd) < 0) && (errno == EINTR))
+      ;
     *pfd = -1;
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -1785,42 +1609,40 @@ static void kwsysProcessClosePipes(kwsysProcess* cp)
   int i;
 
   /* Close any pipes that are still open.  */
-  for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
-    {
-    if(cp->PipeReadEnds[i] >= 0)
-      {
+  for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
+    if (cp->PipeReadEnds[i] >= 0) {
 #if KWSYSPE_USE_SELECT
       /* If the pipe was reported by the last call to select, we must
          read from it.  This is needed to satisfy the suggestions from
          "man select_tut" and is not needed for the polling
          implementation.  Ignore the data.  */
-      if(FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet))
-        {
+      if (FD_ISSET(cp->PipeReadEnds[i], &cp->PipeSet)) {
         /* We are handling this pipe now.  Remove it from the set.  */
         FD_CLR(cp->PipeReadEnds[i], &cp->PipeSet);
 
         /* The pipe is ready to read without blocking.  Keep trying to
            read until the operation is not interrupted.  */
-        while((read(cp->PipeReadEnds[i], cp->PipeBuffer,
-                    KWSYSPE_PIPE_BUFFER_SIZE) < 0) && (errno == EINTR));
-        }
+        while ((read(cp->PipeReadEnds[i], cp->PipeBuffer,
+                     KWSYSPE_PIPE_BUFFER_SIZE) < 0) &&
+               (errno == EINTR))
+          ;
+      }
 #endif
 
       /* We are done reading from this pipe.  */
       kwsysProcessCleanupDescriptor(&cp->PipeReadEnds[i]);
       --cp->PipesLeft;
-      }
     }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
 static int kwsysProcessSetNonBlocking(int fd)
 {
   int flags = fcntl(fd, F_GETFL);
-  if(flags >= 0)
-    {
+  if (flags >= 0) {
     flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
-    }
+  }
   return flags >= 0;
 }
 
@@ -1839,30 +1661,27 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
   ssize_t readRes;
 
   /* Create the error reporting pipe.  */
-  if(pipe(si->ErrorPipe) < 0)
-    {
+  if (pipe(si->ErrorPipe) < 0) {
     return 0;
-    }
+  }
 
   /* Create a pipe for detecting that the child process has created a process
      group and session.  */
-  if(pipe(pgidPipe) < 0)
-    {
+  if (pipe(pgidPipe) < 0) {
     kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
     kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
     return 0;
-    }
+  }
 
   /* Set close-on-exec flag on the pipe's write end.  */
-  if(fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0 ||
-     fcntl(pgidPipe[1], F_SETFD, FD_CLOEXEC) < 0)
-    {
+  if (fcntl(si->ErrorPipe[1], F_SETFD, FD_CLOEXEC) < 0 ||
+      fcntl(pgidPipe[1], F_SETFD, FD_CLOEXEC) < 0) {
     kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
     kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
     kwsysProcessCleanupDescriptor(&pgidPipe[0]);
     kwsysProcessCleanupDescriptor(&pgidPipe[1]);
     return 0;
-    }
+  }
 
   /* Block SIGINT / SIGTERM while we start.  The purpose is so that our signal
      handler doesn't get called from the child process after the fork and
@@ -1870,16 +1689,15 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
   sigemptyset(&mask);
   sigaddset(&mask, SIGINT);
   sigaddset(&mask, SIGTERM);
-  if(sigprocmask(SIG_BLOCK, &mask, &old_mask) < 0)
-    {
+  if (sigprocmask(SIG_BLOCK, &mask, &old_mask) < 0) {
     kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
     kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
     kwsysProcessCleanupDescriptor(&pgidPipe[0]);
     kwsysProcessCleanupDescriptor(&pgidPipe[1]);
     return 0;
-    }
+  }
 
-  /* Fork off a child process.  */
+/* Fork off a child process.  */
 #if defined(__VMS)
   /* VMS needs vfork and execvp to be in the same function because
      they use setjmp/longjmp to run the child startup code in the
@@ -1889,18 +1707,16 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
 #else
   cp->ForkPIDs[prIndex] = kwsysProcessFork(cp, si);
 #endif
-  if(cp->ForkPIDs[prIndex] < 0)
-    {
+  if (cp->ForkPIDs[prIndex] < 0) {
     sigprocmask(SIG_SETMASK, &old_mask, 0);
     kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
     kwsysProcessCleanupDescriptor(&si->ErrorPipe[1]);
     kwsysProcessCleanupDescriptor(&pgidPipe[0]);
     kwsysProcessCleanupDescriptor(&pgidPipe[1]);
     return 0;
-    }
+  }
 
-  if(cp->ForkPIDs[prIndex] == 0)
-    {
+  if (cp->ForkPIDs[prIndex] == 0) {
 #if defined(__VMS)
     /* Specify standard pipes for child process.  */
     decc$set_child_standard_streams(si->StdIn, si->StdOut, si->StdErr);
@@ -1911,22 +1727,17 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
     close(pgidPipe[0]);
 
     /* Setup the stdin, stdout, and stderr pipes.  */
-    if(si->StdIn > 0)
-      {
+    if (si->StdIn > 0) {
       dup2(si->StdIn, 0);
-      }
-    else if(si->StdIn < 0)
-      {
+    } else if (si->StdIn < 0) {
       close(0);
-      }
-    if(si->StdOut != 1)
-      {
+    }
+    if (si->StdOut != 1) {
       dup2(si->StdOut, 1);
-      }
-    if(si->StdErr != 2)
-      {
+    }
+    if (si->StdErr != 2) {
       dup2(si->StdErr, 2);
-      }
+    }
 
     /* Clear the close-on-exec flag for stdin, stdout, and stderr.
        All other pipe handles will be closed when exec succeeds.  */
@@ -1945,10 +1756,9 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
        the child getting hung up on signals like SIGTTOU.  (In the real world,
        this has been observed where "git svn" ends up calling the "resize"
        program which opens /dev/tty.  */
-    if(cp->CreateProcessGroup && setsid() < 0)
-      {
+    if (cp->CreateProcessGroup && setsid() < 0) {
       kwsysProcessChildErrorExit(si->ErrorPipe[1]);
-      }
+    }
 #endif
 
     /* Execute the real process.  If successful, this does not return.  */
@@ -1958,7 +1768,7 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
 
     /* Failure.  Report error to parent and terminate.  */
     kwsysProcessChildErrorExit(si->ErrorPipe[1]);
-    }
+  }
 
 #if defined(__VMS)
   /* Restore the standard pipes of this process.  */
@@ -1973,22 +1783,21 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
   /* Make sure the child is in the process group before we proceed.  This
      avoids race conditions with calls to the kill function that we make for
      signalling process groups.  */
-  while((readRes = read(pgidPipe[0], &tmp, 1)) > 0);
-  if(readRes < 0)
-    {
+  while ((readRes = read(pgidPipe[0], &tmp, 1)) > 0)
+    ;
+  if (readRes < 0) {
     sigprocmask(SIG_SETMASK, &old_mask, 0);
     kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
     kwsysProcessCleanupDescriptor(&pgidPipe[0]);
     return 0;
-    }
+  }
   kwsysProcessCleanupDescriptor(&pgidPipe[0]);
 
   /* Unmask signals.  */
-  if(sigprocmask(SIG_SETMASK, &old_mask, 0) < 0)
-    {
+  if (sigprocmask(SIG_SETMASK, &old_mask, 0) < 0) {
     kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
     return 0;
-    }
+  }
 
   /* A child has been created.  */
   ++cp->CommandsLeft;
@@ -1996,28 +1805,26 @@ static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
   /* Block until the child's exec call succeeds and closes the error
      pipe or writes data to the pipe to report an error.  */
   {
-  kwsysProcess_ssize_t total = 0;
-  kwsysProcess_ssize_t n = 1;
-  /* Read the entire error message up to the length of our buffer.  */
-  while(total < KWSYSPE_PIPE_BUFFER_SIZE && n > 0)
-    {
-    /* Keep trying to read until the operation is not interrupted.  */
-    while(((n = read(si->ErrorPipe[0], cp->ErrorMessage+total,
-                     (size_t)(KWSYSPE_PIPE_BUFFER_SIZE-total))) < 0) &&
-          (errno == EINTR));
-    if(n > 0)
-      {
-      total += n;
+    kwsysProcess_ssize_t total = 0;
+    kwsysProcess_ssize_t n = 1;
+    /* Read the entire error message up to the length of our buffer.  */
+    while (total < KWSYSPE_PIPE_BUFFER_SIZE && n > 0) {
+      /* Keep trying to read until the operation is not interrupted.  */
+      while (((n = read(si->ErrorPipe[0], cp->ErrorMessage + total,
+                        (size_t)(KWSYSPE_PIPE_BUFFER_SIZE - total))) < 0) &&
+             (errno == EINTR))
+        ;
+      if (n > 0) {
+        total += n;
       }
     }
 
-  /* We are done with the error reporting pipe read end.  */
-  kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
+    /* We are done with the error reporting pipe read end.  */
+    kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
 
-  if(total > 0)
-    {
-    /* The child failed to execute the process.  */
-    return 0;
+    if (total > 0) {
+      /* The child failed to execute the process.  */
+      return 0;
     }
   }
 
@@ -2036,25 +1843,21 @@ static void kwsysProcessDestroy(kwsysProcess* cp)
   sigemptyset(&mask);
   sigaddset(&mask, SIGINT);
   sigaddset(&mask, SIGTERM);
-  if(sigprocmask(SIG_BLOCK, &mask, &old_mask) < 0)
-    {
+  if (sigprocmask(SIG_BLOCK, &mask, &old_mask) < 0) {
     return;
-    }
+  }
 
-  for(i=0; i < cp->NumberOfCommands; ++i)
-    {
-    if(cp->ForkPIDs[i])
-      {
+  for (i = 0; i < cp->NumberOfCommands; ++i) {
+    if (cp->ForkPIDs[i]) {
       int result;
-      while(((result = waitpid(cp->ForkPIDs[i],
-                               &cp->CommandExitCodes[i], WNOHANG)) < 0) &&
-            (errno == EINTR));
-      if(result > 0)
-        {
+      while (((result = waitpid(cp->ForkPIDs[i], &cp->CommandExitCodes[i],
+                                WNOHANG)) < 0) &&
+             (errno == EINTR))
+        ;
+      if (result > 0) {
         /* This child has termianted.  */
         cp->ForkPIDs[i] = 0;
-        if(--cp->CommandsLeft == 0)
-          {
+        if (--cp->CommandsLeft == 0) {
           /* All children have terminated.  Close the signal pipe
              write end so that no more notifications are sent to this
              object.  */
@@ -2064,16 +1867,14 @@ static void kwsysProcessDestroy(kwsysProcess* cp)
              WaitForData to use a non-blocking read to get the
              rest of the data from the pipe.  This is needed when
              grandchildren keep the output pipes open.  */
-          }
         }
-      else if(result < 0 && cp->State != kwsysProcess_State_Error)
-        {
+      } else if (result < 0 && cp->State != kwsysProcess_State_Error) {
         /* Unexpected error.  Report the first time this happens.  */
         strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
         cp->State = kwsysProcess_State_Error;
-        }
       }
     }
+  }
 
   /* Re-enable signals.  */
   sigprocmask(SIG_SETMASK, &old_mask, 0);
@@ -2083,25 +1884,22 @@ static void kwsysProcessDestroy(kwsysProcess* cp)
 static int kwsysProcessSetupOutputPipeFile(int* p, const char* name)
 {
   int fout;
-  if(!name)
-    {
+  if (!name) {
     return 1;
-    }
+  }
 
   /* Close the existing descriptor.  */
   kwsysProcessCleanupDescriptor(p);
 
   /* Open a file for the pipe to write.  */
-  if((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0)
-    {
+  if ((fout = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0) {
     return 0;
-    }
+  }
 
   /* Set close-on-exec flag on the pipe's end.  */
-  if(fcntl(fout, F_SETFD, FD_CLOEXEC) < 0)
-    {
+  if (fcntl(fout, F_SETFD, FD_CLOEXEC) < 0) {
     return 0;
-    }
+  }
 
   /* Assign the replacement descriptor.  */
   *p = fout;
@@ -2117,11 +1915,10 @@ static int kwsysProcessSetupOutputPipeNative(int* p, int des[2])
   /* Set close-on-exec flag on the pipe's ends.  The proper end will
      be dup2-ed into the standard descriptor number after fork but
      before exec.  */
-  if((fcntl(des[0], F_SETFD, FD_CLOEXEC) < 0) ||
-     (fcntl(des[1], F_SETFD, FD_CLOEXEC) < 0))
-    {
+  if ((fcntl(des[0], F_SETFD, FD_CLOEXEC) < 0) ||
+      (fcntl(des[1], F_SETFD, FD_CLOEXEC) < 0)) {
     return 0;
-    }
+  }
 
   /* Assign the replacement descriptor.  */
   *p = des[1];
@@ -2136,29 +1933,27 @@ static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
 {
   /* The first time this is called, we need to calculate the time at
      which the child will timeout.  */
-  if(cp->Timeout > 0 && cp->TimeoutTime.tv_sec < 0)
-    {
+  if (cp->Timeout > 0 && cp->TimeoutTime.tv_sec < 0) {
     kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout);
     cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length);
-    }
+  }
 
   /* Start with process timeout.  */
   *timeoutTime = cp->TimeoutTime;
 
   /* Check if the user timeout is earlier.  */
-  if(userTimeout)
-    {
+  if (userTimeout) {
     kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
-    kwsysProcessTime userTimeoutLength = kwsysProcessTimeFromDouble(*userTimeout);
-    kwsysProcessTime userTimeoutTime = kwsysProcessTimeAdd(currentTime,
-                                                           userTimeoutLength);
-    if(timeoutTime->tv_sec < 0 ||
-       kwsysProcessTimeLess(userTimeoutTime, *timeoutTime))
-      {
+    kwsysProcessTime userTimeoutLength =
+      kwsysProcessTimeFromDouble(*userTimeout);
+    kwsysProcessTime userTimeoutTime =
+      kwsysProcessTimeAdd(currentTime, userTimeoutLength);
+    if (timeoutTime->tv_sec < 0 ||
+        kwsysProcessTimeLess(userTimeoutTime, *timeoutTime)) {
       *timeoutTime = userTimeoutTime;
       return 1;
-      }
     }
+  }
   return 0;
 }
 
@@ -2170,38 +1965,31 @@ static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
                                       kwsysProcessTimeNative* timeoutLength,
                                       int zeroIsExpired)
 {
-  if(timeoutTime->tv_sec < 0)
-    {
+  if (timeoutTime->tv_sec < 0) {
     /* No timeout time has been requested.  */
     return 0;
-    }
-  else
-    {
+  } else {
     /* Calculate the remaining time.  */
     kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
-    kwsysProcessTime timeLeft = kwsysProcessTimeSubtract(*timeoutTime,
-                                                         currentTime);
-    if(timeLeft.tv_sec < 0 && userTimeout && *userTimeout <= 0)
-      {
+    kwsysProcessTime timeLeft =
+      kwsysProcessTimeSubtract(*timeoutTime, currentTime);
+    if (timeLeft.tv_sec < 0 && userTimeout && *userTimeout <= 0) {
       /* Caller has explicitly requested a zero timeout.  */
       timeLeft.tv_sec = 0;
       timeLeft.tv_usec = 0;
-      }
+    }
 
-    if(timeLeft.tv_sec < 0 ||
-       (timeLeft.tv_sec == 0 && timeLeft.tv_usec == 0 && zeroIsExpired))
-      {
+    if (timeLeft.tv_sec < 0 ||
+        (timeLeft.tv_sec == 0 && timeLeft.tv_usec == 0 && zeroIsExpired)) {
       /* Timeout has already expired.  */
       return 1;
-      }
-    else
-      {
+    } else {
       /* There is some time left.  */
       timeoutLength->tv_sec = timeLeft.tv_sec;
       timeoutLength->tv_usec = timeLeft.tv_usec;
       return 0;
-      }
     }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -2218,7 +2006,7 @@ static kwsysProcessTime kwsysProcessTimeGetCurrent(void)
 /*--------------------------------------------------------------------------*/
 static double kwsysProcessTimeToDouble(kwsysProcessTime t)
 {
-  return (double)t.tv_sec + (double)(t.tv_usec)*0.000001;
+  return (double)t.tv_sec + (double)(t.tv_usec) * 0.000001;
 }
 
 /*--------------------------------------------------------------------------*/
@@ -2226,7 +2014,7 @@ static kwsysProcessTime kwsysProcessTimeFromDouble(double d)
 {
   kwsysProcessTime t;
   t.tv_sec = (long)d;
-  t.tv_usec = (long)((d-(double)(t.tv_sec))*1000000);
+  t.tv_usec = (long)((d - (double)(t.tv_sec)) * 1000000);
   return t;
 }
 
@@ -2238,158 +2026,227 @@ static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2)
 }
 
 /*--------------------------------------------------------------------------*/
-static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
+static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1,
+                                            kwsysProcessTime in2)
 {
   kwsysProcessTime out;
   out.tv_sec = in1.tv_sec + in2.tv_sec;
   out.tv_usec = in1.tv_usec + in2.tv_usec;
-  if(out.tv_usec >= 1000000)
-    {
+  if (out.tv_usec >= 1000000) {
     out.tv_usec -= 1000000;
     out.tv_sec += 1;
-    }
+  }
   return out;
 }
 
 /*--------------------------------------------------------------------------*/
-static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2)
+static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1,
+                                                 kwsysProcessTime in2)
 {
   kwsysProcessTime out;
   out.tv_sec = in1.tv_sec - in2.tv_sec;
   out.tv_usec = in1.tv_usec - in2.tv_usec;
-  if(out.tv_usec < 0)
-    {
+  if (out.tv_usec < 0) {
     out.tv_usec += 1000000;
     out.tv_sec -= 1;
-    }
+  }
   return out;
 }
 
 /*--------------------------------------------------------------------------*/
-#define KWSYSPE_CASE(type, str) \
-  cp->ExitException = kwsysProcess_Exception_##type; \
+#define KWSYSPE_CASE(type, str)                                               \
+  cp->ExitException = kwsysProcess_Exception_##type;                          \
   strcpy(cp->ExitExceptionString, str)
 static void kwsysProcessSetExitException(kwsysProcess* cp, int sig)
 {
-  switch (sig)
-    {
+  switch (sig) {
 #ifdef SIGSEGV
-    case SIGSEGV: KWSYSPE_CASE(Fault, "Segmentation fault"); break;
+    case SIGSEGV:
+      KWSYSPE_CASE(Fault, "Segmentation fault");
+      break;
 #endif
 #ifdef SIGBUS
-# if !defined(SIGSEGV) || SIGBUS != SIGSEGV
-    case SIGBUS: KWSYSPE_CASE(Fault, "Bus error"); break;
-# endif
+#if !defined(SIGSEGV) || SIGBUS != SIGSEGV
+    case SIGBUS:
+      KWSYSPE_CASE(Fault, "Bus error");
+      break;
+#endif
 #endif
 #ifdef SIGFPE
-    case SIGFPE: KWSYSPE_CASE(Numerical, "Floating-point exception"); break;
+    case SIGFPE:
+      KWSYSPE_CASE(Numerical, "Floating-point exception");
+      break;
 #endif
 #ifdef SIGILL
-    case SIGILL: KWSYSPE_CASE(Illegal, "Illegal instruction"); break;
+    case SIGILL:
+      KWSYSPE_CASE(Illegal, "Illegal instruction");
+      break;
 #endif
 #ifdef SIGINT
-    case SIGINT: KWSYSPE_CASE(Interrupt, "User interrupt"); break;
+    case SIGINT:
+      KWSYSPE_CASE(Interrupt, "User interrupt");
+      break;
 #endif
 #ifdef SIGABRT
-    case SIGABRT: KWSYSPE_CASE(Other, "Child aborted"); break;
+    case SIGABRT:
+      KWSYSPE_CASE(Other, "Child aborted");
+      break;
 #endif
 #ifdef SIGKILL
-    case SIGKILL: KWSYSPE_CASE(Other, "Child killed"); break;
+    case SIGKILL:
+      KWSYSPE_CASE(Other, "Child killed");
+      break;
 #endif
 #ifdef SIGTERM
-    case SIGTERM: KWSYSPE_CASE(Other, "Child terminated"); break;
+    case SIGTERM:
+      KWSYSPE_CASE(Other, "Child terminated");
+      break;
 #endif
 #ifdef SIGHUP
-    case SIGHUP: KWSYSPE_CASE(Other, "SIGHUP"); break;
+    case SIGHUP:
+      KWSYSPE_CASE(Other, "SIGHUP");
+      break;
 #endif
 #ifdef SIGQUIT
-    case SIGQUIT: KWSYSPE_CASE(Other, "SIGQUIT"); break;
+    case SIGQUIT:
+      KWSYSPE_CASE(Other, "SIGQUIT");
+      break;
 #endif
 #ifdef SIGTRAP
-    case SIGTRAP: KWSYSPE_CASE(Other, "SIGTRAP"); break;
+    case SIGTRAP:
+      KWSYSPE_CASE(Other, "SIGTRAP");
+      break;
 #endif
 #ifdef SIGIOT
-# if !defined(SIGABRT) || SIGIOT != SIGABRT
-    case SIGIOT: KWSYSPE_CASE(Other, "SIGIOT"); break;
-# endif
+#if !defined(SIGABRT) || SIGIOT != SIGABRT
+    case SIGIOT:
+      KWSYSPE_CASE(Other, "SIGIOT");
+      break;
+#endif
 #endif
 #ifdef SIGUSR1
-    case SIGUSR1: KWSYSPE_CASE(Other, "SIGUSR1"); break;
+    case SIGUSR1:
+      KWSYSPE_CASE(Other, "SIGUSR1");
+      break;
 #endif
 #ifdef SIGUSR2
-    case SIGUSR2: KWSYSPE_CASE(Other, "SIGUSR2"); break;
+    case SIGUSR2:
+      KWSYSPE_CASE(Other, "SIGUSR2");
+      break;
 #endif
 #ifdef SIGPIPE
-    case SIGPIPE: KWSYSPE_CASE(Other, "SIGPIPE"); break;
+    case SIGPIPE:
+      KWSYSPE_CASE(Other, "SIGPIPE");
+      break;
 #endif
 #ifdef SIGALRM
-    case SIGALRM: KWSYSPE_CASE(Other, "SIGALRM"); break;
+    case SIGALRM:
+      KWSYSPE_CASE(Other, "SIGALRM");
+      break;
 #endif
 #ifdef SIGSTKFLT
-    case SIGSTKFLT: KWSYSPE_CASE(Other, "SIGSTKFLT"); break;
+    case SIGSTKFLT:
+      KWSYSPE_CASE(Other, "SIGSTKFLT");
+      break;
 #endif
 #ifdef SIGCHLD
-    case SIGCHLD: KWSYSPE_CASE(Other, "SIGCHLD"); break;
+    case SIGCHLD:
+      KWSYSPE_CASE(Other, "SIGCHLD");
+      break;
 #elif defined(SIGCLD)
-    case SIGCLD: KWSYSPE_CASE(Other, "SIGCLD"); break;
+    case SIGCLD:
+      KWSYSPE_CASE(Other, "SIGCLD");
+      break;
 #endif
 #ifdef SIGCONT
-    case SIGCONT: KWSYSPE_CASE(Other, "SIGCONT"); break;
+    case SIGCONT:
+      KWSYSPE_CASE(Other, "SIGCONT");
+      break;
 #endif
 #ifdef SIGSTOP
-    case SIGSTOP: KWSYSPE_CASE(Other, "SIGSTOP"); break;
+    case SIGSTOP:
+      KWSYSPE_CASE(Other, "SIGSTOP");
+      break;
 #endif
 #ifdef SIGTSTP
-    case SIGTSTP: KWSYSPE_CASE(Other, "SIGTSTP"); break;
+    case SIGTSTP:
+      KWSYSPE_CASE(Other, "SIGTSTP");
+      break;
 #endif
 #ifdef SIGTTIN
-    case SIGTTIN: KWSYSPE_CASE(Other, "SIGTTIN"); break;
+    case SIGTTIN:
+      KWSYSPE_CASE(Other, "SIGTTIN");
+      break;
 #endif
 #ifdef SIGTTOU
-    case SIGTTOU: KWSYSPE_CASE(Other, "SIGTTOU"); break;
+    case SIGTTOU:
+      KWSYSPE_CASE(Other, "SIGTTOU");
+      break;
 #endif
 #ifdef SIGURG
-    case SIGURG: KWSYSPE_CASE(Other, "SIGURG"); break;
+    case SIGURG:
+      KWSYSPE_CASE(Other, "SIGURG");
+      break;
 #endif
 #ifdef SIGXCPU
-    case SIGXCPU: KWSYSPE_CASE(Other, "SIGXCPU"); break;
+    case SIGXCPU:
+      KWSYSPE_CASE(Other, "SIGXCPU");
+      break;
 #endif
 #ifdef SIGXFSZ
-    case SIGXFSZ: KWSYSPE_CASE(Other, "SIGXFSZ"); break;
+    case SIGXFSZ:
+      KWSYSPE_CASE(Other, "SIGXFSZ");
+      break;
 #endif
 #ifdef SIGVTALRM
-    case SIGVTALRM: KWSYSPE_CASE(Other, "SIGVTALRM"); break;
+    case SIGVTALRM:
+      KWSYSPE_CASE(Other, "SIGVTALRM");
+      break;
 #endif
 #ifdef SIGPROF
-    case SIGPROF: KWSYSPE_CASE(Other, "SIGPROF"); break;
+    case SIGPROF:
+      KWSYSPE_CASE(Other, "SIGPROF");
+      break;
 #endif
 #ifdef SIGWINCH
-    case SIGWINCH: KWSYSPE_CASE(Other, "SIGWINCH"); break;
+    case SIGWINCH:
+      KWSYSPE_CASE(Other, "SIGWINCH");
+      break;
 #endif
 #ifdef SIGPOLL
-    case SIGPOLL: KWSYSPE_CASE(Other, "SIGPOLL"); break;
+    case SIGPOLL:
+      KWSYSPE_CASE(Other, "SIGPOLL");
+      break;
 #endif
 #ifdef SIGIO
-# if !defined(SIGPOLL) || SIGIO != SIGPOLL
-    case SIGIO: KWSYSPE_CASE(Other, "SIGIO"); break;
-# endif
+#if !defined(SIGPOLL) || SIGIO != SIGPOLL
+    case SIGIO:
+      KWSYSPE_CASE(Other, "SIGIO");
+      break;
+#endif
 #endif
 #ifdef SIGPWR
-    case SIGPWR: KWSYSPE_CASE(Other, "SIGPWR"); break;
+    case SIGPWR:
+      KWSYSPE_CASE(Other, "SIGPWR");
+      break;
 #endif
 #ifdef SIGSYS
-    case SIGSYS: KWSYSPE_CASE(Other, "SIGSYS"); break;
+    case SIGSYS:
+      KWSYSPE_CASE(Other, "SIGSYS");
+      break;
 #endif
 #ifdef SIGUNUSED
-# if !defined(SIGSYS) || SIGUNUSED != SIGSYS
-    case SIGUNUSED: KWSYSPE_CASE(Other, "SIGUNUSED"); break;
-# endif
+#if !defined(SIGSYS) || SIGUNUSED != SIGSYS
+    case SIGUNUSED:
+      KWSYSPE_CASE(Other, "SIGUNUSED");
+      break;
+#endif
 #endif
     default:
       cp->ExitException = kwsysProcess_Exception_Other;
       sprintf(cp->ExitExceptionString, "Signal %d", sig);
       break;
-    }
+  }
 }
 #undef KWSYSPE_CASE
 
@@ -2405,7 +2262,7 @@ static void kwsysProcessChildErrorExit(int errorPipe)
   strncpy(buffer, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
 
   /* Report the error to the parent through the special pipe.  */
-  result=write(errorPipe, buffer, strlen(buffer));
+  result = write(errorPipe, buffer, strlen(buffer));
   (void)result;
 
   /* Terminate without cleanup.  */
@@ -2532,55 +2389,47 @@ static pid_t kwsysProcessFork(kwsysProcess* cp,
                               kwsysProcessCreateInformation* si)
 {
   /* Create a detached process if requested.  */
-  if(cp->OptionDetach)
-    {
+  if (cp->OptionDetach) {
     /* Create an intermediate process.  */
     pid_t middle_pid = fork();
-    if(middle_pid < 0)
-      {
+    if (middle_pid < 0) {
       /* Fork failed.  Return as if we were not detaching.  */
       return middle_pid;
-      }
-    else if(middle_pid == 0)
-      {
+    } else if (middle_pid == 0) {
       /* This is the intermediate process.  Create the real child.  */
       pid_t child_pid = fork();
-      if(child_pid == 0)
-        {
+      if (child_pid == 0) {
         /* This is the real child process.  There is nothing to do here.  */
         return 0;
-        }
-      else
-        {
+      } else {
         /* Use the error pipe to report the pid to the real parent.  */
-        while((write(si->ErrorPipe[1], &child_pid, sizeof(child_pid)) < 0) &&
-              (errno == EINTR));
+        while ((write(si->ErrorPipe[1], &child_pid, sizeof(child_pid)) < 0) &&
+               (errno == EINTR))
+          ;
 
         /* Exit without cleanup.  The parent holds all resources.  */
         kwsysProcessExit();
         return 0; /* Never reached, but avoids SunCC warning.  */
-        }
       }
-    else
-      {
+    } else {
       /* This is the original parent process.  The intermediate
          process will use the error pipe to report the pid of the
          detached child.  */
       pid_t child_pid;
       int status;
-      while((read(si->ErrorPipe[0], &child_pid, sizeof(child_pid)) < 0) &&
-            (errno == EINTR));
+      while ((read(si->ErrorPipe[0], &child_pid, sizeof(child_pid)) < 0) &&
+             (errno == EINTR))
+        ;
 
       /* Wait for the intermediate process to exit and clean it up.  */
-      while((waitpid(middle_pid, &status, 0) < 0) && (errno == EINTR));
+      while ((waitpid(middle_pid, &status, 0) < 0) && (errno == EINTR))
+        ;
       return child_pid;
-      }
     }
-  else
-    {
+  } else {
     /* Not creating a detached process.  Use normal fork.  */
     return fork();
-    }
+  }
 }
 #endif
 
@@ -2589,23 +2438,23 @@ static pid_t kwsysProcessFork(kwsysProcess* cp,
    Here we define the command to call on each platform and the
    corresponding parsing format string.  The parsing format should
    have two integers to store: the pid and then the ppid.  */
-#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) \
-   || defined(__OpenBSD__) || defined(__GLIBC__) || defined(__GNU__)
-# define KWSYSPE_PS_COMMAND "ps axo pid,ppid"
-# define KWSYSPE_PS_FORMAT  "%d %d\n"
+#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) ||       \
+  defined(__OpenBSD__) || defined(__GLIBC__) || defined(__GNU__)
+#define KWSYSPE_PS_COMMAND "ps axo pid,ppid"
+#define KWSYSPE_PS_FORMAT "%d %d\n"
 #elif defined(__sun) && (defined(__SVR4) || defined(__svr4__)) /* Solaris */
-# define KWSYSPE_PS_COMMAND "ps -e -o pid,ppid"
-# define KWSYSPE_PS_FORMAT  "%d %d\n"
-#elif defined(__hpux) || defined(__sun__) || defined(__sgi) || defined(_AIX) \
-   || defined(__sparc)
-# define KWSYSPE_PS_COMMAND "ps -ef"
-# define KWSYSPE_PS_FORMAT  "%*s %d %d %*[^\n]\n"
+#define KWSYSPE_PS_COMMAND "ps -e -o pid,ppid"
+#define KWSYSPE_PS_FORMAT "%d %d\n"
+#elif defined(__hpux) || defined(__sun__) || defined(__sgi) ||                \
+  defined(_AIX) || defined(__sparc)
+#define KWSYSPE_PS_COMMAND "ps -ef"
+#define KWSYSPE_PS_FORMAT "%*s %d %d %*[^\n]\n"
 #elif defined(__QNX__)
-# define KWSYSPE_PS_COMMAND "ps -Af"
-# define KWSYSPE_PS_FORMAT  "%*d %d %d %*[^\n]\n"
+#define KWSYSPE_PS_COMMAND "ps -Af"
+#define KWSYSPE_PS_FORMAT "%*d %d %d %*[^\n]\n"
 #elif defined(__CYGWIN__)
-# define KWSYSPE_PS_COMMAND "ps aux"
-# define KWSYSPE_PS_FORMAT  "%d %d %*[^\n]\n"
+#define KWSYSPE_PS_COMMAND "ps aux"
+#define KWSYSPE_PS_FORMAT "%d %d %*[^\n]\n"
 #endif
 
 /*--------------------------------------------------------------------------*/
@@ -2624,11 +2473,10 @@ static void kwsysProcessKill(pid_t process_id)
   usleep(1);
 #endif
 
-  /* Kill all children if we can find them.  */
+/* Kill all children if we can find them.  */
 #if defined(__linux__) || defined(__CYGWIN__)
   /* First try using the /proc filesystem.  */
-  if((procdir = opendir("/proc")) != NULL)
-    {
+  if ((procdir = opendir("/proc")) != NULL) {
 #if defined(MAXPATHLEN)
     char fname[MAXPATHLEN];
 #elif defined(PATH_MAX)
@@ -2636,7 +2484,7 @@ static void kwsysProcessKill(pid_t process_id)
 #else
     char fname[4096];
 #endif
-    char buffer[KWSYSPE_PIPE_BUFFER_SIZE+1];
+    char buffer[KWSYSPE_PIPE_BUFFER_SIZE + 1];
     struct dirent* d;
 
     /* Each process has a directory in /proc whose name is the pid.
@@ -2647,69 +2495,57 @@ static void kwsysProcessKill(pid_t process_id)
 
        We want to get the ppid for all processes.  Those that have
        process_id as their parent should be recursively killed.  */
-    for(d = readdir(procdir); d; d = readdir(procdir))
-      {
+    for (d = readdir(procdir); d; d = readdir(procdir)) {
       int pid;
-      if(sscanf(d->d_name, "%d", &pid) == 1 && pid != 0)
-        {
+      if (sscanf(d->d_name, "%d", &pid) == 1 && pid != 0) {
         struct stat finfo;
         sprintf(fname, "/proc/%d/stat", pid);
-        if(stat(fname, &finfo) == 0)
-          {
+        if (stat(fname, &finfo) == 0) {
           FILE* f = fopen(fname, "r");
-          if(f)
-            {
+          if (f) {
             size_t nread = fread(buffer, 1, KWSYSPE_PIPE_BUFFER_SIZE, f);
             fclose(f);
             buffer[nread] = '\0';
-            if(nread > 0)
-              {
+            if (nread > 0) {
               const char* rparen = strrchr(buffer, ')');
               int ppid;
-              if(rparen && (sscanf(rparen+1, "%*s %d", &ppid) == 1))
-                {
-                if(ppid == process_id)
-                  {
+              if (rparen && (sscanf(rparen + 1, "%*s %d", &ppid) == 1)) {
+                if (ppid == process_id) {
                   /* Recursively kill this child and its children.  */
                   kwsysProcessKill(pid);
-                  }
                 }
               }
             }
           }
         }
       }
-    closedir(procdir);
     }
-  else
+    closedir(procdir);
+  } else
 #endif
-    {
+  {
 #if defined(KWSYSPE_PS_COMMAND)
     /* Try running "ps" to get the process information.  */
     FILE* ps = popen(KWSYSPE_PS_COMMAND, "r");
 
     /* Make sure the process started and provided a valid header.  */
-    if(ps && fscanf(ps, "%*[^\n]\n") != EOF)
-      {
+    if (ps && fscanf(ps, "%*[^\n]\n") != EOF) {
       /* Look for processes whose parent is the process being killed.  */
       int pid, ppid;
-      while(fscanf(ps, KWSYSPE_PS_FORMAT, &pid, &ppid) == 2)
-        {
-        if(ppid == process_id)
-          {
+      while (fscanf(ps, KWSYSPE_PS_FORMAT, &pid, &ppid) == 2) {
+        if (ppid == process_id) {
           /* Recursively kill this child and its children.  */
           kwsysProcessKill(pid);
-          }
         }
       }
+    }
 
     /* We are done with the ps process.  */
-    if(ps)
-      {
+    if (ps) {
       pclose(ps);
-      }
-#endif
     }
+#endif
+  }
 
   /* Kill the process.  */
   kill(process_id, SIGKILL);
@@ -2781,112 +2617,104 @@ static int kwsysProcessesAdd(kwsysProcess* cp)
   /* Create a pipe through which the signal handler can notify the
      given process object that a child has exited.  */
   {
-  /* Create the pipe.  */
-  int p[2];
-  if(pipe(p KWSYSPE_VMS_NONBLOCK) < 0)
-    {
-    return 0;
+    /* Create the pipe.  */
+    int p[2];
+    if (pipe(p KWSYSPE_VMS_NONBLOCK) < 0) {
+      return 0;
     }
 
-  /* Store the pipes now to be sure they are cleaned up later.  */
-  cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL] = p[0];
-  cp->SignalPipe = p[1];
+    /* Store the pipes now to be sure they are cleaned up later.  */
+    cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL] = p[0];
+    cp->SignalPipe = p[1];
 
-  /* Switch the pipe to non-blocking mode so that reading a byte can
-     be an atomic test-and-set.  */
-  if(!kwsysProcessSetNonBlocking(p[0]) ||
-     !kwsysProcessSetNonBlocking(p[1]))
-    {
-    return 0;
+    /* Switch the pipe to non-blocking mode so that reading a byte can
+       be an atomic test-and-set.  */
+    if (!kwsysProcessSetNonBlocking(p[0]) ||
+        !kwsysProcessSetNonBlocking(p[1])) {
+      return 0;
     }
 
-  /* The children do not need this pipe.  Set close-on-exec flag on
-     the pipe's ends.  */
-  if((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
-     (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0))
-    {
-    return 0;
+    /* The children do not need this pipe.  Set close-on-exec flag on
+       the pipe's ends.  */
+    if ((fcntl(p[0], F_SETFD, FD_CLOEXEC) < 0) ||
+        (fcntl(p[1], F_SETFD, FD_CLOEXEC) < 0)) {
+      return 0;
     }
   }
 
   /* Attempt to add the given signal pipe to the signal handler set.  */
   {
 
-  /* Make sure there is enough space for the new signal pipe.  */
-  kwsysProcessInstances oldProcesses = kwsysProcesses;
-  kwsysProcessInstances newProcesses = oldProcesses;
-  if(oldProcesses.Count == oldProcesses.Size)
-    {
-    /* Start with enough space for a small number of process instances
-       and double the size each time more is needed.  */
-    newProcesses.Size = oldProcesses.Size? oldProcesses.Size*2 : 4;
-
-    /* Try allocating the new block of memory.  */
-    if((newProcesses.Processes = ((kwsysProcess**)
-                                  malloc((size_t)(newProcesses.Size)*
-                                         sizeof(kwsysProcess*)))))
-      {
-      /* Copy the old pipe set to the new memory.  */
-      if(oldProcesses.Count > 0)
-        {
-        memcpy(newProcesses.Processes, oldProcesses.Processes,
-               ((size_t)(oldProcesses.Count) * sizeof(kwsysProcess*)));
+    /* Make sure there is enough space for the new signal pipe.  */
+    kwsysProcessInstances oldProcesses = kwsysProcesses;
+    kwsysProcessInstances newProcesses = oldProcesses;
+    if (oldProcesses.Count == oldProcesses.Size) {
+      /* Start with enough space for a small number of process instances
+         and double the size each time more is needed.  */
+      newProcesses.Size = oldProcesses.Size ? oldProcesses.Size * 2 : 4;
+
+      /* Try allocating the new block of memory.  */
+      if ((newProcesses.Processes = ((kwsysProcess**)malloc(
+             (size_t)(newProcesses.Size) * sizeof(kwsysProcess*))))) {
+        /* Copy the old pipe set to the new memory.  */
+        if (oldProcesses.Count > 0) {
+          memcpy(newProcesses.Processes, oldProcesses.Processes,
+                 ((size_t)(oldProcesses.Count) * sizeof(kwsysProcess*)));
         }
-      }
-    else
-      {
-      /* Failed to allocate memory for the new signal pipe set.  */
-      return 0;
+      } else {
+        /* Failed to allocate memory for the new signal pipe set.  */
+        return 0;
       }
     }
 
-  /* Append the new signal pipe to the set.  */
-  newProcesses.Processes[newProcesses.Count++] = cp;
+    /* Append the new signal pipe to the set.  */
+    newProcesses.Processes[newProcesses.Count++] = cp;
 
-  /* Store the new set in that seen by the signal handler.  */
-  kwsysProcessesUpdate(&newProcesses);
+    /* Store the new set in that seen by the signal handler.  */
+    kwsysProcessesUpdate(&newProcesses);
 
-  /* Free the original pipes if new ones were allocated.  */
-  if(newProcesses.Processes != oldProcesses.Processes)
-    {
-    free(oldProcesses.Processes);
+    /* Free the original pipes if new ones were allocated.  */
+    if (newProcesses.Processes != oldProcesses.Processes) {
+      free(oldProcesses.Processes);
     }
 
-  /* If this is the first process, enable the signal handler.  */
-  if(newProcesses.Count == 1)
-    {
-    /* Install our handler for SIGCHLD.  Repeat call until it is not
-       interrupted.  */
-    struct sigaction newSigAction;
-    memset(&newSigAction, 0, sizeof(struct sigaction));
+    /* If this is the first process, enable the signal handler.  */
+    if (newProcesses.Count == 1) {
+      /* Install our handler for SIGCHLD.  Repeat call until it is not
+         interrupted.  */
+      struct sigaction newSigAction;
+      memset(&newSigAction, 0, sizeof(struct sigaction));
 #if KWSYSPE_USE_SIGINFO
-    newSigAction.sa_sigaction = kwsysProcessesSignalHandler;
-    newSigAction.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
-# ifdef SA_RESTART
-    newSigAction.sa_flags |= SA_RESTART;
-# endif
-#else
-    newSigAction.sa_handler = kwsysProcessesSignalHandler;
-    newSigAction.sa_flags = SA_NOCLDSTOP;
+      newSigAction.sa_sigaction = kwsysProcessesSignalHandler;
+      newSigAction.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
+#ifdef SA_RESTART
+      newSigAction.sa_flags |= SA_RESTART;
 #endif
-    sigemptyset(&newSigAction.sa_mask);
-    while((sigaction(SIGCHLD, &newSigAction,
-                     &kwsysProcessesOldSigChldAction) < 0) &&
-          (errno == EINTR));
-
-    /* Install our handler for SIGINT / SIGTERM.  Repeat call until
-       it is not interrupted.  */
-    sigemptyset(&newSigAction.sa_mask);
-    sigaddset(&newSigAction.sa_mask, SIGTERM);
-    while((sigaction(SIGINT, &newSigAction,
-                     &kwsysProcessesOldSigIntAction) < 0) &&
-          (errno == EINTR));
+#else
+      newSigAction.sa_handler = kwsysProcessesSignalHandler;
+      newSigAction.sa_flags = SA_NOCLDSTOP;
+#endif
+      sigemptyset(&newSigAction.sa_mask);
+      while ((sigaction(SIGCHLD, &newSigAction,
+                        &kwsysProcessesOldSigChldAction) < 0) &&
+             (errno == EINTR))
+        ;
+
+      /* Install our handler for SIGINT / SIGTERM.  Repeat call until
+         it is not interrupted.  */
+      sigemptyset(&newSigAction.sa_mask);
+      sigaddset(&newSigAction.sa_mask, SIGTERM);
+      while ((sigaction(SIGINT, &newSigAction,
+                        &kwsysProcessesOldSigIntAction) < 0) &&
+             (errno == EINTR))
+        ;
 
-    sigemptyset(&newSigAction.sa_mask);
-    sigaddset(&newSigAction.sa_mask, SIGINT);
-    while((sigaction(SIGTERM, &newSigAction,
-                     &kwsysProcessesOldSigIntAction) < 0) &&
-          (errno == EINTR));
+      sigemptyset(&newSigAction.sa_mask);
+      sigaddset(&newSigAction.sa_mask, SIGINT);
+      while ((sigaction(SIGTERM, &newSigAction,
+                        &kwsysProcessesOldSigIntAction) < 0) &&
+             (errno == EINTR))
+        ;
     }
   }
 
@@ -2898,46 +2726,44 @@ static void kwsysProcessesRemove(kwsysProcess* cp)
 {
   /* Attempt to remove the given signal pipe from the signal handler set.  */
   {
-  /* Find the given process in the set.  */
-  kwsysProcessInstances newProcesses = kwsysProcesses;
-  int i;
-  for(i=0; i < newProcesses.Count; ++i)
-    {
-    if(newProcesses.Processes[i] == cp)
-      {
-      break;
+    /* Find the given process in the set.  */
+    kwsysProcessInstances newProcesses = kwsysProcesses;
+    int i;
+    for (i = 0; i < newProcesses.Count; ++i) {
+      if (newProcesses.Processes[i] == cp) {
+        break;
       }
     }
-  if(i < newProcesses.Count)
-    {
-    /* Remove the process from the set.  */
-    --newProcesses.Count;
-    for(; i < newProcesses.Count; ++i)
-      {
-      newProcesses.Processes[i] = newProcesses.Processes[i+1];
+    if (i < newProcesses.Count) {
+      /* Remove the process from the set.  */
+      --newProcesses.Count;
+      for (; i < newProcesses.Count; ++i) {
+        newProcesses.Processes[i] = newProcesses.Processes[i + 1];
       }
 
-    /* If this was the last process, disable the signal handler.  */
-    if(newProcesses.Count == 0)
-      {
-      /* Restore the signal handlers.  Repeat call until it is not
-         interrupted.  */
-      while((sigaction(SIGCHLD, &kwsysProcessesOldSigChldAction, 0) < 0) &&
-            (errno == EINTR));
-      while((sigaction(SIGINT, &kwsysProcessesOldSigIntAction, 0) < 0) &&
-            (errno == EINTR));
-      while((sigaction(SIGTERM, &kwsysProcessesOldSigTermAction, 0) < 0) &&
-            (errno == EINTR));
-
-      /* Free the table of process pointers since it is now empty.
-         This is safe because the signal handler has been removed.  */
-      newProcesses.Size = 0;
-      free(newProcesses.Processes);
-      newProcesses.Processes = 0;
+      /* If this was the last process, disable the signal handler.  */
+      if (newProcesses.Count == 0) {
+        /* Restore the signal handlers.  Repeat call until it is not
+           interrupted.  */
+        while ((sigaction(SIGCHLD, &kwsysProcessesOldSigChldAction, 0) < 0) &&
+               (errno == EINTR))
+          ;
+        while ((sigaction(SIGINT, &kwsysProcessesOldSigIntAction, 0) < 0) &&
+               (errno == EINTR))
+          ;
+        while ((sigaction(SIGTERM, &kwsysProcessesOldSigTermAction, 0) < 0) &&
+               (errno == EINTR))
+          ;
+
+        /* Free the table of process pointers since it is now empty.
+           This is safe because the signal handler has been removed.  */
+        newProcesses.Size = 0;
+        free(newProcesses.Processes);
+        newProcesses.Processes = 0;
       }
 
-    /* Store the new set in that seen by the signal handler.  */
-    kwsysProcessesUpdate(&newProcesses);
+      /* Store the new set in that seen by the signal handler.  */
+      kwsysProcessesUpdate(&newProcesses);
     }
   }
 
@@ -2949,9 +2775,10 @@ static void kwsysProcessesRemove(kwsysProcess* cp)
 /*--------------------------------------------------------------------------*/
 static void kwsysProcessesSignalHandler(int signum
 #if KWSYSPE_USE_SIGINFO
-                                        , siginfo_t* info, void* ucontext
+                                        ,
+                                        siginfo_t* info, void* ucontext
 #endif
-  )
+                                        )
 {
   int i, j, procStatus, old_errno = errno;
 #if KWSYSPE_USE_SIGINFO
@@ -2960,99 +2787,97 @@ static void kwsysProcessesSignalHandler(int signum
 #endif
 
   /* Signal all process objects that a child has terminated.  */
-  switch(signum)
-    {
+  switch (signum) {
     case SIGCHLD:
-      for(i=0; i < kwsysProcesses.Count; ++i)
-        {
+      for (i = 0; i < kwsysProcesses.Count; ++i) {
         /* Set the pipe in a signalled state.  */
         char buf = 1;
         kwsysProcess* cp = kwsysProcesses.Processes[i];
-        kwsysProcess_ssize_t pipeStatus=
+        kwsysProcess_ssize_t pipeStatus =
           read(cp->PipeReadEnds[KWSYSPE_PIPE_SIGNAL], &buf, 1);
         (void)pipeStatus;
-        pipeStatus=write(cp->SignalPipe, &buf, 1);
+        pipeStatus = write(cp->SignalPipe, &buf, 1);
         (void)pipeStatus;
-        }
+      }
       break;
     case SIGINT:
     case SIGTERM:
       /* Signal child processes that are running in new process groups.  */
-      for(i=0; i < kwsysProcesses.Count; ++i)
-        {
+      for (i = 0; i < kwsysProcesses.Count; ++i) {
         kwsysProcess* cp = kwsysProcesses.Processes[i];
         /* Check Killed to avoid data race condition when killing.
            Check State to avoid data race condition in kwsysProcessCleanup
            when there is an error (it leaves a reaped PID).  */
-        if(cp->CreateProcessGroup && !cp->Killed &&
-           cp->State != kwsysProcess_State_Error && cp->ForkPIDs)
-          {
-          for(j=0; j < cp->NumberOfCommands; ++j)
-            {
+        if (cp->CreateProcessGroup && !cp->Killed &&
+            cp->State != kwsysProcess_State_Error && cp->ForkPIDs) {
+          for (j = 0; j < cp->NumberOfCommands; ++j) {
             /* Make sure the PID is still valid. */
-            if(cp->ForkPIDs[j])
-              {
-              /* The user created a process group for this process.  The group ID
+            if (cp->ForkPIDs[j]) {
+              /* The user created a process group for this process.  The group
+                 ID
                  is the process ID for the original process in the group.  */
               kill(-cp->ForkPIDs[j], SIGINT);
-              }
             }
           }
         }
+      }
 
       /* Wait for all processes to terminate.  */
-      while(wait(&procStatus) >= 0 || errno != ECHILD)
-        {
-        }
+      while (wait(&procStatus) >= 0 || errno != ECHILD) {
+      }
 
       /* Terminate the process, which is now in an inconsistent state
          because we reaped all the PIDs that it may have been reaping
          or may have reaped in the future.  Reraise the signal so that
          the proper exit code is returned.  */
       {
-      /* Install default signal handler.  */
-      struct sigaction defSigAction;
-      sigset_t unblockSet;
-      memset(&defSigAction, 0, sizeof(defSigAction));
-      defSigAction.sa_handler = SIG_DFL;
-      sigemptyset(&defSigAction.sa_mask);
-      while((sigaction(signum, &defSigAction, 0) < 0) &&
-            (errno == EINTR));
-      /* Unmask the signal.  */
-      sigemptyset(&unblockSet);
-      sigaddset(&unblockSet, signum);
-      sigprocmask(SIG_UNBLOCK, &unblockSet, 0);
-      /* Raise the signal again.  */
-      raise(signum);
-      /* We shouldn't get here... but if we do... */
-      _exit(1);
+        /* Install default signal handler.  */
+        struct sigaction defSigAction;
+        sigset_t unblockSet;
+        memset(&defSigAction, 0, sizeof(defSigAction));
+        defSigAction.sa_handler = SIG_DFL;
+        sigemptyset(&defSigAction.sa_mask);
+        while ((sigaction(signum, &defSigAction, 0) < 0) && (errno == EINTR))
+          ;
+        /* Unmask the signal.  */
+        sigemptyset(&unblockSet);
+        sigaddset(&unblockSet, signum);
+        sigprocmask(SIG_UNBLOCK, &unblockSet, 0);
+        /* Raise the signal again.  */
+        raise(signum);
+        /* We shouldn't get here... but if we do... */
+        _exit(1);
       }
       /* break omitted to silence unreachable code clang compiler warning.  */
-    }
+  }
 
 #if !KWSYSPE_USE_SIGINFO
   /* Re-Install our handler.  Repeat call until it is not interrupted.  */
   {
-  struct sigaction newSigAction;
-  struct sigaction &oldSigAction;
-  memset(&newSigAction, 0, sizeof(struct sigaction));
-  newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
-  newSigChldAction.sa_flags = SA_NOCLDSTOP;
-  sigemptyset(&newSigAction.sa_mask);
-  switch(signum)
-    {
-    case SIGCHLD: oldSigAction = &kwsysProcessesOldSigChldAction; break;
-    case SIGINT:
-      sigaddset(&newSigAction.sa_mask, SIGTERM);
-      oldSigAction = &kwsysProcessesOldSigIntAction; break;
-    case SIGTERM:
-      sigaddset(&newSigAction.sa_mask, SIGINT);
-      oldSigAction = &kwsysProcessesOldSigTermAction; break;
-    default: return 0;
+    struct sigaction newSigAction;
+    struct sigaction& oldSigAction;
+    memset(&newSigAction, 0, sizeof(struct sigaction));
+    newSigChldAction.sa_handler = kwsysProcessesSignalHandler;
+    newSigChldAction.sa_flags = SA_NOCLDSTOP;
+    sigemptyset(&newSigAction.sa_mask);
+    switch (signum) {
+      case SIGCHLD:
+        oldSigAction = &kwsysProcessesOldSigChldAction;
+        break;
+      case SIGINT:
+        sigaddset(&newSigAction.sa_mask, SIGTERM);
+        oldSigAction = &kwsysProcessesOldSigIntAction;
+        break;
+      case SIGTERM:
+        sigaddset(&newSigAction.sa_mask, SIGINT);
+        oldSigAction = &kwsysProcessesOldSigTermAction;
+        break;
+      default:
+        return 0;
     }
-  while((sigaction(signum, &newSigAction,
-                   oldSigAction) < 0) &&
-        (errno == EINTR));
+    while ((sigaction(signum, &newSigAction, oldSigAction) < 0) &&
+           (errno == EINTR))
+      ;
   }
 #endif
 
@@ -3062,10 +2887,9 @@ static void kwsysProcessesSignalHandler(int signum
 /*--------------------------------------------------------------------------*/
 void kwsysProcess_ResetStartTime(kwsysProcess* cp)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return;
-    }
+  }
   /* Reset start time. */
   cp->StartTime = kwsysProcessTimeGetCurrent();
 }
diff --git a/Source/kwsys/ProcessWin32.c b/Source/kwsys/ProcessWin32.c
index 2b93e69..d10c733 100644
--- a/Source/kwsys/ProcessWin32.c
+++ b/Source/kwsys/ProcessWin32.c
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(Process.h)
 #include KWSYS_HEADER(Encoding.h)
@@ -16,8 +7,8 @@
 /* Work-around CMake dependency scanning limitation.  This must
    duplicate the above list of headers.  */
 #if 0
-# include "Process.h.in"
-# include "Encoding.h.in"
+#include "Encoding.h.in"
+#include "Process.h.in"
 #endif
 
 /*
@@ -31,15 +22,15 @@ a UNIX-style select system call.
 */
 
 #ifdef _MSC_VER
-#pragma warning (push, 1)
+#pragma warning(push, 1)
 #endif
 #include <windows.h> /* Windows API */
 #if defined(_MSC_VER) && _MSC_VER >= 1800
-# define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
+#define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
 #endif
-#include <string.h>  /* strlen, strdup */
-#include <stdio.h>   /* sprintf */
-#include <io.h>      /* _unlink */
+#include <io.h>     /* _unlink */
+#include <stdio.h>  /* sprintf */
+#include <string.h> /* strlen, strdup */
 #ifdef __WATCOMC__
 #define _unlink unlink
 #endif
@@ -52,14 +43,14 @@ a UNIX-style select system call.
 #endif
 
 #ifdef _MSC_VER
-#pragma warning (pop)
-#pragma warning (disable: 4514)
-#pragma warning (disable: 4706)
+#pragma warning(pop)
+#pragma warning(disable : 4514)
+#pragma warning(disable : 4706)
 #endif
 
 #if defined(__BORLANDC__)
-# pragma warn -8004 /* assigned a value that is never used  */
-# pragma warn -8060 /* Assignment inside if() condition.  */
+#pragma warn - 8004 /* assigned a value that is never used  */
+#pragma warn - 8060 /* Assignment inside if() condition.  */
 #endif
 
 /* There are pipes for the process pipeline's stdout and stderr.  */
@@ -72,18 +63,14 @@ a UNIX-style select system call.
 
 /* Debug output macro.  */
 #if 0
-# define KWSYSPE_DEBUG(x) \
-( \
-  (void*)cp == (void*)0x00226DE0? \
-  ( \
-    fprintf(stderr, "%d/%p/%d ", (int)GetCurrentProcessId(), cp, __LINE__), \
-    fprintf x, \
-    fflush(stderr), \
-    1 \
-  ) : (1) \
-)
+#define KWSYSPE_DEBUG(x)                                                      \
+  ((void*)cp == (void*)0x00226DE0                                             \
+     ? (fprintf(stderr, "%d/%p/%d ", (int)GetCurrentProcessId(), cp,          \
+                __LINE__),                                                    \
+        fprintf x, fflush(stderr), 1)                                         \
+     : (1))
 #else
-# define KWSYSPE_DEBUG(x) (void)1
+#define KWSYSPE_DEBUG(x) (void)1
 #endif
 
 typedef LARGE_INTEGER kwsysProcessTime;
@@ -99,7 +86,6 @@ typedef struct kwsysProcessCreateInformation_s
   HANDLE hStdError;
 } kwsysProcessCreateInformation;
 
-
 /*--------------------------------------------------------------------------*/
 typedef struct kwsysProcessPipeData_s kwsysProcessPipeData;
 static DWORD WINAPI kwsysProcessPipeThreadRead(LPVOID ptd);
@@ -112,8 +98,7 @@ static int kwsysProcessInitialize(kwsysProcess* cp);
 static DWORD kwsysProcessCreate(kwsysProcess* cp, int index,
                                 kwsysProcessCreateInformation* si);
 static void kwsysProcessDestroy(kwsysProcess* cp, int event);
-static DWORD kwsysProcessSetupOutputPipeFile(PHANDLE handle,
-                                             const char* name);
+static DWORD kwsysProcessSetupOutputPipeFile(PHANDLE handle, const char* name);
 static void kwsysProcessSetupSharedPipe(DWORD nStdHandle, PHANDLE handle);
 static void kwsysProcessSetupPipeNative(HANDLE native, PHANDLE handle);
 static void kwsysProcessCleanupHandle(PHANDLE h);
@@ -129,8 +114,10 @@ static DWORD kwsysProcessTimeToDWORD(kwsysProcessTime t);
 static double kwsysProcessTimeToDouble(kwsysProcessTime t);
 static kwsysProcessTime kwsysProcessTimeFromDouble(double d);
 static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2);
-static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2);
-static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2);
+static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1,
+                                            kwsysProcessTime in2);
+static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1,
+                                                 kwsysProcessTime in2);
 static void kwsysProcessSetExitException(kwsysProcess* cp, int code);
 static void kwsysProcessKillTree(int pid);
 static void kwsysProcessDisablePipeThreads(kwsysProcess* cp);
@@ -300,10 +287,10 @@ struct kwsysProcess_s
   int PipesLeft;
 
   /* Buffer for error messages.  */
-  char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE+1];
+  char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE + 1];
 
   /* Description for the ExitException.  */
-  char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE+1];
+  char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE + 1];
 
   /* Windows process information data.  */
   PROCESS_INFORMATION* ProcessInformation;
@@ -337,18 +324,16 @@ kwsysProcess* kwsysProcess_New(void)
      first process.  This prevents the risk of an orphaned process being
      started by the main thread while the default Ctrl handler is in
      progress.  */
-  if(!kwsysProcessesInitialize())
-    {
+  if (!kwsysProcessesInitialize()) {
     return 0;
-    }
+  }
 
   /* Allocate a process control structure.  */
   cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
-  if(!cp)
-    {
+  if (!cp) {
     /* Could not allocate memory for the control structure.  */
     return 0;
-    }
+  }
   ZeroMemory(cp, sizeof(*cp));
 
   /* Share stdin with the parent process by default.  */
@@ -362,42 +347,38 @@ kwsysProcess* kwsysProcess_New(void)
   ZeroMemory(&osv, sizeof(osv));
   osv.dwOSVersionInfoSize = sizeof(osv);
 #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (push)
-# ifdef __INTEL_COMPILER
-#  pragma warning (disable:1478)
-# else
-#  pragma warning (disable:4996)
-# endif
+#pragma warning(push)
+#ifdef __INTEL_COMPILER
+#pragma warning(disable : 1478)
+#else
+#pragma warning(disable : 4996)
+#endif
 #endif
   GetVersionEx(&osv);
 #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (pop)
+#pragma warning(pop)
 #endif
-  if(osv.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
-    {
+  if (osv.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
     /* Win9x no longer supported.  */
     kwsysProcess_Delete(cp);
     return 0;
-    }
+  }
 
   /* Initially no thread owns the mutex.  Initialize semaphore to 1.  */
-  if(!(cp->SharedIndexMutex = CreateSemaphore(0, 1, 1, 0)))
-    {
+  if (!(cp->SharedIndexMutex = CreateSemaphore(0, 1, 1, 0))) {
     kwsysProcess_Delete(cp);
     return 0;
-    }
+  }
 
   /* Initially no data are available.  Initialize semaphore to 0.  */
-  if(!(cp->Full = CreateSemaphore(0, 0, 1, 0)))
-    {
+  if (!(cp->Full = CreateSemaphore(0, 0, 1, 0))) {
     kwsysProcess_Delete(cp);
     return 0;
-    }
+  }
 
   /* Create the thread to read each pipe.  */
-  for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
-    {
-    DWORD dummy=0;
+  for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
+    DWORD dummy = 0;
 
     /* Assign the thread its index.  */
     cp->Pipe[i].Index = i;
@@ -406,73 +387,62 @@ kwsysProcess* kwsysProcess_New(void)
     cp->Pipe[i].Process = cp;
 
     /* No process is yet running.  Initialize semaphore to 0.  */
-    if(!(cp->Pipe[i].Reader.Ready = CreateSemaphore(0, 0, 1, 0)))
-      {
+    if (!(cp->Pipe[i].Reader.Ready = CreateSemaphore(0, 0, 1, 0))) {
       kwsysProcess_Delete(cp);
       return 0;
-      }
+    }
 
     /* The pipe is not yet reset.  Initialize semaphore to 0.  */
-    if(!(cp->Pipe[i].Reader.Reset = CreateSemaphore(0, 0, 1, 0)))
-      {
+    if (!(cp->Pipe[i].Reader.Reset = CreateSemaphore(0, 0, 1, 0))) {
       kwsysProcess_Delete(cp);
       return 0;
-      }
+    }
 
     /* The thread's buffer is initially empty.  Initialize semaphore to 1.  */
-    if(!(cp->Pipe[i].Reader.Go = CreateSemaphore(0, 1, 1, 0)))
-      {
+    if (!(cp->Pipe[i].Reader.Go = CreateSemaphore(0, 1, 1, 0))) {
       kwsysProcess_Delete(cp);
       return 0;
-      }
+    }
 
     /* Create the reading thread.  It will block immediately.  The
        thread will not make deeply nested calls, so we need only a
        small stack.  */
-    if(!(cp->Pipe[i].Reader.Thread = CreateThread(0, 1024,
-                                                  kwsysProcessPipeThreadRead,
-                                                  &cp->Pipe[i], 0, &dummy)))
-      {
+    if (!(cp->Pipe[i].Reader.Thread = CreateThread(
+            0, 1024, kwsysProcessPipeThreadRead, &cp->Pipe[i], 0, &dummy))) {
       kwsysProcess_Delete(cp);
       return 0;
-      }
+    }
 
     /* No process is yet running.  Initialize semaphore to 0.  */
-    if(!(cp->Pipe[i].Waker.Ready = CreateSemaphore(0, 0, 1, 0)))
-      {
+    if (!(cp->Pipe[i].Waker.Ready = CreateSemaphore(0, 0, 1, 0))) {
       kwsysProcess_Delete(cp);
       return 0;
-      }
+    }
 
     /* The pipe is not yet reset.  Initialize semaphore to 0.  */
-    if(!(cp->Pipe[i].Waker.Reset = CreateSemaphore(0, 0, 1, 0)))
-      {
+    if (!(cp->Pipe[i].Waker.Reset = CreateSemaphore(0, 0, 1, 0))) {
       kwsysProcess_Delete(cp);
       return 0;
-      }
+    }
 
     /* The waker should not wake immediately.  Initialize semaphore to 0.  */
-    if(!(cp->Pipe[i].Waker.Go = CreateSemaphore(0, 0, 1, 0)))
-      {
+    if (!(cp->Pipe[i].Waker.Go = CreateSemaphore(0, 0, 1, 0))) {
       kwsysProcess_Delete(cp);
       return 0;
-      }
+    }
 
     /* Create the waking thread.  It will block immediately.  The
        thread will not make deeply nested calls, so we need only a
        small stack.  */
-    if(!(cp->Pipe[i].Waker.Thread = CreateThread(0, 1024,
-                                                 kwsysProcessPipeThreadWake,
-                                                 &cp->Pipe[i], 0, &dummy)))
-      {
+    if (!(cp->Pipe[i].Waker.Thread = CreateThread(
+            0, 1024, kwsysProcessPipeThreadWake, &cp->Pipe[i], 0, &dummy))) {
       kwsysProcess_Delete(cp);
       return 0;
-      }
     }
-  for(i=0; i < 3; ++i)
-    {
+  }
+  for (i = 0; i < 3; ++i) {
     cp->PipeChildStd[i] = INVALID_HANDLE_VALUE;
-    }
+  }
 
   return cp;
 }
@@ -483,33 +453,26 @@ void kwsysProcess_Delete(kwsysProcess* cp)
   int i;
 
   /* Make sure we have an instance.  */
-  if(!cp)
-    {
+  if (!cp) {
     return;
-    }
+  }
 
   /* If the process is executing, wait for it to finish.  */
-  if(cp->State == kwsysProcess_State_Executing)
-    {
-    if(cp->Detached)
-      {
+  if (cp->State == kwsysProcess_State_Executing) {
+    if (cp->Detached) {
       kwsysProcess_Disown(cp);
-      }
-    else
-      {
+    } else {
       kwsysProcess_WaitForExit(cp, 0);
-      }
     }
+  }
 
   /* We are deleting the kwsysProcess instance.  */
   cp->Deleting = 1;
 
   /* Terminate each of the threads.  */
-  for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
-    {
+  for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
     /* Terminate this reading thread.  */
-    if(cp->Pipe[i].Reader.Thread)
-      {
+    if (cp->Pipe[i].Reader.Thread) {
       /* Signal the thread we are ready for it.  It will terminate
          immediately since Deleting is set.  */
       ReleaseSemaphore(cp->Pipe[i].Reader.Ready, 1, 0);
@@ -519,11 +482,10 @@ void kwsysProcess_Delete(kwsysProcess* cp)
 
       /* Close the handle to the thread. */
       kwsysProcessCleanupHandle(&cp->Pipe[i].Reader.Thread);
-      }
+    }
 
     /* Terminate this waking thread.  */
-    if(cp->Pipe[i].Waker.Thread)
-      {
+    if (cp->Pipe[i].Waker.Thread) {
       /* Signal the thread we are ready for it.  It will terminate
          immediately since Deleting is set.  */
       ReleaseSemaphore(cp->Pipe[i].Waker.Ready, 1, 0);
@@ -533,7 +495,7 @@ void kwsysProcess_Delete(kwsysProcess* cp)
 
       /* Close the handle to the thread. */
       kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Thread);
-      }
+    }
 
     /* Cleanup the pipe's semaphores.  */
     kwsysProcessCleanupHandle(&cp->Pipe[i].Reader.Ready);
@@ -542,7 +504,7 @@ void kwsysProcess_Delete(kwsysProcess* cp)
     kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Ready);
     kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Go);
     kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Reset);
-    }
+  }
 
   /* Close the shared semaphores.  */
   kwsysProcessCleanupHandle(&cp->SharedIndexMutex);
@@ -554,10 +516,9 @@ void kwsysProcess_Delete(kwsysProcess* cp)
   kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDIN, 0);
   kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDOUT, 0);
   kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDERR, 0);
-  if(cp->CommandExitCodes)
-    {
+  if (cp->CommandExitCodes) {
     free(cp->CommandExitCodes);
-    }
+  }
   free(cp);
 }
 
@@ -565,24 +526,20 @@ void kwsysProcess_Delete(kwsysProcess* cp)
 int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
 {
   int i;
-  if(!cp)
-    {
+  if (!cp) {
     return 0;
-    }
-  for(i=0; i < cp->NumberOfCommands; ++i)
-    {
+  }
+  for (i = 0; i < cp->NumberOfCommands; ++i) {
     free(cp->Commands[i]);
-    }
+  }
   cp->NumberOfCommands = 0;
-  if(cp->Commands)
-    {
+  if (cp->Commands) {
     free(cp->Commands);
     cp->Commands = 0;
-    }
-  if(command)
-    {
+  }
+  if (command) {
     return kwsysProcess_AddCommand(cp, command);
-    }
+  }
   return 1;
 }
 
@@ -593,91 +550,87 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
   wchar_t** newCommands;
 
   /* Make sure we have a command to add.  */
-  if(!cp || !command || !*command)
-    {
+  if (!cp || !command || !*command) {
     return 0;
-    }
-
+  }
 
   /* Allocate a new array for command pointers.  */
   newNumberOfCommands = cp->NumberOfCommands + 1;
-  if(!(newCommands = (wchar_t**)malloc(sizeof(wchar_t*) * newNumberOfCommands)))
-    {
+  if (!(newCommands =
+          (wchar_t**)malloc(sizeof(wchar_t*) * newNumberOfCommands))) {
     /* Out of memory.  */
     return 0;
-    }
+  }
 
   /* Copy any existing commands into the new array.  */
   {
-  int i;
-  for(i=0; i < cp->NumberOfCommands; ++i)
-    {
-    newCommands[i] = cp->Commands[i];
+    int i;
+    for (i = 0; i < cp->NumberOfCommands; ++i) {
+      newCommands[i] = cp->Commands[i];
     }
   }
 
-  if (cp->Verbatim)
-    {
+  if (cp->Verbatim) {
     /* Copy the verbatim command line into the buffer.  */
     newCommands[cp->NumberOfCommands] = kwsysEncoding_DupToWide(*command);
-    }
-  else
-    {
+  } else {
     /* Encode the arguments so CommandLineToArgvW can decode
        them from the command line string in the child.  */
     char buffer[32768]; /* CreateProcess max command-line length.  */
     char* end = buffer + sizeof(buffer);
     char* out = buffer;
     char const* const* a;
-    for (a = command; *a; ++a)
-      {
+    for (a = command; *a; ++a) {
       int quote = !**a; /* Quote the empty string.  */
       int slashes = 0;
       char const* c;
-      if (a != command && out != end) { *out++ = ' '; }
-      for (c = *a; !quote && *c; ++c)
-        { quote = (*c == ' ' || *c == '\t'); }
-      if (quote && out != end) { *out++ = '"'; }
-      for (c = *a; *c; ++c)
-        {
-        if (*c == '\\')
-          {
+      if (a != command && out != end) {
+        *out++ = ' ';
+      }
+      for (c = *a; !quote && *c; ++c) {
+        quote = (*c == ' ' || *c == '\t');
+      }
+      if (quote && out != end) {
+        *out++ = '"';
+      }
+      for (c = *a; *c; ++c) {
+        if (*c == '\\') {
           ++slashes;
-          }
-        else
-          {
-          if (*c == '"')
-            {
+        } else {
+          if (*c == '"') {
             // Add n+1 backslashes to total 2n+1 before internal '"'.
-            while(slashes-- >= 0 && out != end) { *out++ = '\\'; }
+            while (slashes-- >= 0 && out != end) {
+              *out++ = '\\';
             }
-          slashes = 0;
           }
-        if (out != end) { *out++ = *c; }
+          slashes = 0;
+        }
+        if (out != end) {
+          *out++ = *c;
         }
-      if (quote)
-        {
+      }
+      if (quote) {
         // Add n backslashes to total 2n before ending '"'.
-        while (slashes-- > 0 && out != end) { *out++ = '\\'; }
-        if (out != end) { *out++ = '"'; }
+        while (slashes-- > 0 && out != end) {
+          *out++ = '\\';
+        }
+        if (out != end) {
+          *out++ = '"';
         }
       }
-    if(out != end)
-      {
+    }
+    if (out != end) {
       *out = '\0';
       newCommands[cp->NumberOfCommands] = kwsysEncoding_DupToWide(buffer);
-      }
-    else
-      {
+    } else {
       newCommands[cp->NumberOfCommands] = 0;
-      }
     }
-  if (!newCommands[cp->NumberOfCommands])
-    {
+  }
+  if (!newCommands[cp->NumberOfCommands]) {
     /* Out of memory or command line too long.  */
     free(newCommands);
     return 0;
-    }
+  }
 
   /* Save the new array of commands.  */
   free(cp->Commands);
@@ -689,15 +642,13 @@ int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
 /*--------------------------------------------------------------------------*/
 void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return;
-    }
+  }
   cp->Timeout = timeout;
-  if(cp->Timeout < 0)
-    {
+  if (cp->Timeout < 0) {
     cp->Timeout = 0;
-    }
+  }
   // Force recomputation of TimeoutTime.
   cp->TimeoutTime.QuadPart = -1;
 }
@@ -705,38 +656,32 @@ void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
 /*--------------------------------------------------------------------------*/
 int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return 0;
-    }
-  if(cp->WorkingDirectory)
-    {
+  }
+  if (cp->WorkingDirectory) {
     free(cp->WorkingDirectory);
     cp->WorkingDirectory = 0;
-    }
-  if(dir && dir[0])
-    {
+  }
+  if (dir && dir[0]) {
     wchar_t* wdir = kwsysEncoding_DupToWide(dir);
     /* We must convert the working directory to a full path.  */
     DWORD length = GetFullPathNameW(wdir, 0, 0, 0);
-    if(length > 0)
-      {
-      wchar_t* work_dir = malloc(length*sizeof(wchar_t));
-      if(!work_dir)
-        {
+    if (length > 0) {
+      wchar_t* work_dir = malloc(length * sizeof(wchar_t));
+      if (!work_dir) {
         free(wdir);
         return 0;
-        }
-      if(!GetFullPathNameW(wdir, length, work_dir, 0))
-        {
+      }
+      if (!GetFullPathNameW(wdir, length, work_dir, 0)) {
         free(work_dir);
         free(wdir);
         return 0;
-        }
-      cp->WorkingDirectory = work_dir;
       }
-    free(wdir);
+      cp->WorkingDirectory = work_dir;
     }
+    free(wdir);
+  }
   return 1;
 }
 
@@ -744,39 +689,40 @@ int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
 int kwsysProcess_SetPipeFile(kwsysProcess* cp, int pipe, const char* file)
 {
   char** pfile;
-  if(!cp)
-    {
+  if (!cp) {
     return 0;
-    }
-  switch(pipe)
-    {
-    case kwsysProcess_Pipe_STDIN: pfile = &cp->PipeFileSTDIN; break;
-    case kwsysProcess_Pipe_STDOUT: pfile = &cp->PipeFileSTDOUT; break;
-    case kwsysProcess_Pipe_STDERR: pfile = &cp->PipeFileSTDERR; break;
-    default: return 0;
-    }
-  if(*pfile)
-    {
+  }
+  switch (pipe) {
+    case kwsysProcess_Pipe_STDIN:
+      pfile = &cp->PipeFileSTDIN;
+      break;
+    case kwsysProcess_Pipe_STDOUT:
+      pfile = &cp->PipeFileSTDOUT;
+      break;
+    case kwsysProcess_Pipe_STDERR:
+      pfile = &cp->PipeFileSTDERR;
+      break;
+    default:
+      return 0;
+  }
+  if (*pfile) {
     free(*pfile);
     *pfile = 0;
-    }
-  if(file)
-    {
-    *pfile = (char*)malloc(strlen(file)+1);
-    if(!*pfile)
-      {
+  }
+  if (file) {
+    *pfile = (char*)malloc(strlen(file) + 1);
+    if (!*pfile) {
       return 0;
-      }
-    strcpy(*pfile, file);
     }
+    strcpy(*pfile, file);
+  }
 
   /* If we are redirecting the pipe, do not share it or use a native
      pipe.  */
-  if(*pfile)
-    {
+  if (*pfile) {
     kwsysProcess_SetPipeNative(cp, pipe, 0);
     kwsysProcess_SetPipeShared(cp, pipe, 0);
-    }
+  }
 
   return 1;
 }
@@ -784,26 +730,30 @@ int kwsysProcess_SetPipeFile(kwsysProcess* cp, int pipe, const char* file)
 /*--------------------------------------------------------------------------*/
 void kwsysProcess_SetPipeShared(kwsysProcess* cp, int pipe, int shared)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return;
-    }
+  }
 
-  switch(pipe)
-    {
-    case kwsysProcess_Pipe_STDIN: cp->PipeSharedSTDIN = shared?1:0; break;
-    case kwsysProcess_Pipe_STDOUT: cp->PipeSharedSTDOUT = shared?1:0; break;
-    case kwsysProcess_Pipe_STDERR: cp->PipeSharedSTDERR = shared?1:0; break;
-    default: return;
-    }
+  switch (pipe) {
+    case kwsysProcess_Pipe_STDIN:
+      cp->PipeSharedSTDIN = shared ? 1 : 0;
+      break;
+    case kwsysProcess_Pipe_STDOUT:
+      cp->PipeSharedSTDOUT = shared ? 1 : 0;
+      break;
+    case kwsysProcess_Pipe_STDERR:
+      cp->PipeSharedSTDERR = shared ? 1 : 0;
+      break;
+    default:
+      return;
+  }
 
   /* If we are sharing the pipe, do not redirect it to a file or use a
      native pipe.  */
-  if(shared)
-    {
+  if (shared) {
     kwsysProcess_SetPipeFile(cp, pipe, 0);
     kwsysProcess_SetPipeNative(cp, pipe, 0);
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -811,129 +761,135 @@ void kwsysProcess_SetPipeNative(kwsysProcess* cp, int pipe, HANDLE p[2])
 {
   HANDLE* pPipeNative = 0;
 
-  if(!cp)
-    {
+  if (!cp) {
     return;
-    }
+  }
 
-  switch(pipe)
-    {
-    case kwsysProcess_Pipe_STDIN: pPipeNative = cp->PipeNativeSTDIN; break;
-    case kwsysProcess_Pipe_STDOUT: pPipeNative = cp->PipeNativeSTDOUT; break;
-    case kwsysProcess_Pipe_STDERR: pPipeNative = cp->PipeNativeSTDERR; break;
-    default: return;
-    }
+  switch (pipe) {
+    case kwsysProcess_Pipe_STDIN:
+      pPipeNative = cp->PipeNativeSTDIN;
+      break;
+    case kwsysProcess_Pipe_STDOUT:
+      pPipeNative = cp->PipeNativeSTDOUT;
+      break;
+    case kwsysProcess_Pipe_STDERR:
+      pPipeNative = cp->PipeNativeSTDERR;
+      break;
+    default:
+      return;
+  }
 
   /* Copy the native pipe handles provided.  */
-  if(p)
-    {
+  if (p) {
     pPipeNative[0] = p[0];
     pPipeNative[1] = p[1];
-    }
-  else
-    {
+  } else {
     pPipeNative[0] = 0;
     pPipeNative[1] = 0;
-    }
+  }
 
   /* If we are using a native pipe, do not share it or redirect it to
      a file.  */
-  if(p)
-    {
+  if (p) {
     kwsysProcess_SetPipeFile(cp, pipe, 0);
     kwsysProcess_SetPipeShared(cp, pipe, 0);
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
 int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return 0;
-    }
+  }
 
-  switch(optionId)
-    {
-    case kwsysProcess_Option_Detach: return cp->OptionDetach;
-    case kwsysProcess_Option_HideWindow: return cp->HideWindow;
-    case kwsysProcess_Option_MergeOutput: return cp->MergeOutput;
-    case kwsysProcess_Option_Verbatim: return cp->Verbatim;
+  switch (optionId) {
+    case kwsysProcess_Option_Detach:
+      return cp->OptionDetach;
+    case kwsysProcess_Option_HideWindow:
+      return cp->HideWindow;
+    case kwsysProcess_Option_MergeOutput:
+      return cp->MergeOutput;
+    case kwsysProcess_Option_Verbatim:
+      return cp->Verbatim;
     case kwsysProcess_Option_CreateProcessGroup:
       return cp->CreateProcessGroup;
-    default: return 0;
-    }
+    default:
+      return 0;
+  }
 }
 
 /*--------------------------------------------------------------------------*/
 void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return;
-    }
+  }
 
-  switch(optionId)
-    {
-    case kwsysProcess_Option_Detach: cp->OptionDetach = value; break;
-    case kwsysProcess_Option_HideWindow: cp->HideWindow = value; break;
-    case kwsysProcess_Option_MergeOutput: cp->MergeOutput = value; break;
-    case kwsysProcess_Option_Verbatim: cp->Verbatim = value; break;
+  switch (optionId) {
+    case kwsysProcess_Option_Detach:
+      cp->OptionDetach = value;
+      break;
+    case kwsysProcess_Option_HideWindow:
+      cp->HideWindow = value;
+      break;
+    case kwsysProcess_Option_MergeOutput:
+      cp->MergeOutput = value;
+      break;
+    case kwsysProcess_Option_Verbatim:
+      cp->Verbatim = value;
+      break;
     case kwsysProcess_Option_CreateProcessGroup:
-      cp->CreateProcessGroup = value; break;
-    default: break;
-    }
+      cp->CreateProcessGroup = value;
+      break;
+    default:
+      break;
+  }
 }
 
 /*--------------------------------------------------------------------------*/
 int kwsysProcess_GetState(kwsysProcess* cp)
 {
-  return cp? cp->State : kwsysProcess_State_Error;
+  return cp ? cp->State : kwsysProcess_State_Error;
 }
 
 /*--------------------------------------------------------------------------*/
 int kwsysProcess_GetExitException(kwsysProcess* cp)
 {
-  return cp? cp->ExitException : kwsysProcess_Exception_Other;
+  return cp ? cp->ExitException : kwsysProcess_Exception_Other;
 }
 
 /*--------------------------------------------------------------------------*/
 int kwsysProcess_GetExitValue(kwsysProcess* cp)
 {
-  return cp? cp->ExitValue : -1;
+  return cp ? cp->ExitValue : -1;
 }
 
 /*--------------------------------------------------------------------------*/
 int kwsysProcess_GetExitCode(kwsysProcess* cp)
 {
-  return cp? cp->ExitCode : 0;
+  return cp ? cp->ExitCode : 0;
 }
 
 /*--------------------------------------------------------------------------*/
 const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return "Process management structure could not be allocated";
-    }
-  else if(cp->State == kwsysProcess_State_Error)
-    {
+  } else if (cp->State == kwsysProcess_State_Error) {
     return cp->ErrorMessage;
-    }
+  }
   return "Success";
 }
 
 /*--------------------------------------------------------------------------*/
 const char* kwsysProcess_GetExceptionString(kwsysProcess* cp)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return "GetExceptionString called with NULL process management structure";
-    }
-  else if(cp->State == kwsysProcess_State_Exception)
-    {
+  } else if (cp->State == kwsysProcess_State_Exception) {
     return cp->ExitExceptionString;
-    }
+  }
   return "No exception";
 }
 
@@ -943,259 +899,210 @@ void kwsysProcess_Execute(kwsysProcess* cp)
   int i;
 
   /* Do not execute a second time.  */
-  if(!cp || cp->State == kwsysProcess_State_Executing)
-    {
+  if (!cp || cp->State == kwsysProcess_State_Executing) {
     return;
-    }
+  }
 
   /* Make sure we have something to run.  */
-  if(cp->NumberOfCommands < 1)
-    {
+  if (cp->NumberOfCommands < 1) {
     strcpy(cp->ErrorMessage, "No command");
     cp->State = kwsysProcess_State_Error;
     return;
-    }
+  }
 
   /* Initialize the control structure for a new process.  */
-  if(!kwsysProcessInitialize(cp))
-    {
+  if (!kwsysProcessInitialize(cp)) {
     strcpy(cp->ErrorMessage, "Out of memory");
     cp->State = kwsysProcess_State_Error;
     return;
-    }
+  }
 
   /* Save the real working directory of this process and change to
      the working directory for the child processes.  This is needed
      to make pipe file paths evaluate correctly.  */
-  if(cp->WorkingDirectory)
-    {
-    if(!GetCurrentDirectoryW(cp->RealWorkingDirectoryLength,
-                            cp->RealWorkingDirectory))
-      {
+  if (cp->WorkingDirectory) {
+    if (!GetCurrentDirectoryW(cp->RealWorkingDirectoryLength,
+                              cp->RealWorkingDirectory)) {
       kwsysProcessCleanup(cp, GetLastError());
       return;
-      }
-    SetCurrentDirectoryW(cp->WorkingDirectory);
     }
-
+    SetCurrentDirectoryW(cp->WorkingDirectory);
+  }
 
   /* Setup the stdin pipe for the first process.  */
-  if(cp->PipeFileSTDIN)
-    {
+  if (cp->PipeFileSTDIN) {
     /* Create a handle to read a file for stdin.  */
     wchar_t* wstdin = kwsysEncoding_DupToWide(cp->PipeFileSTDIN);
     DWORD error;
     cp->PipeChildStd[0] =
-      CreateFileW(wstdin, GENERIC_READ|GENERIC_WRITE,
-                  FILE_SHARE_READ|FILE_SHARE_WRITE,
-                  0, OPEN_EXISTING, 0, 0);
+      CreateFileW(wstdin, GENERIC_READ | GENERIC_WRITE,
+                  FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
     error = GetLastError(); /* Check now in case free changes this.  */
     free(wstdin);
-    if(cp->PipeChildStd[0] == INVALID_HANDLE_VALUE)
-      {
+    if (cp->PipeChildStd[0] == INVALID_HANDLE_VALUE) {
       kwsysProcessCleanup(cp, error);
       return;
-      }
     }
-  else if(cp->PipeSharedSTDIN)
-    {
+  } else if (cp->PipeSharedSTDIN) {
     /* Share this process's stdin with the child.  */
     kwsysProcessSetupSharedPipe(STD_INPUT_HANDLE, &cp->PipeChildStd[0]);
-    }
-  else if(cp->PipeNativeSTDIN[0])
-    {
+  } else if (cp->PipeNativeSTDIN[0]) {
     /* Use the provided native pipe.  */
     kwsysProcessSetupPipeNative(cp->PipeNativeSTDIN[0], &cp->PipeChildStd[0]);
-    }
-  else
-    {
+  } else {
     /* Explicitly give the child no stdin.  */
     cp->PipeChildStd[0] = INVALID_HANDLE_VALUE;
-    }
+  }
 
   /* Create the output pipe for the last process.
      We always create this so the pipe thread can run even if we
      do not end up giving the write end to the child below.  */
-  if(!CreatePipe(&cp->Pipe[KWSYSPE_PIPE_STDOUT].Read,
-                 &cp->Pipe[KWSYSPE_PIPE_STDOUT].Write, 0, 0))
-    {
+  if (!CreatePipe(&cp->Pipe[KWSYSPE_PIPE_STDOUT].Read,
+                  &cp->Pipe[KWSYSPE_PIPE_STDOUT].Write, 0, 0)) {
     kwsysProcessCleanup(cp, GetLastError());
     return;
-    }
+  }
 
-  if(cp->PipeFileSTDOUT)
-    {
+  if (cp->PipeFileSTDOUT) {
     /* Use a file for stdout.  */
     DWORD error = kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[1],
                                                   cp->PipeFileSTDOUT);
-    if(error)
-      {
+    if (error) {
       kwsysProcessCleanup(cp, error);
       return;
-      }
     }
-  else if(cp->PipeSharedSTDOUT)
-    {
+  } else if (cp->PipeSharedSTDOUT) {
     /* Use the parent stdout.  */
     kwsysProcessSetupSharedPipe(STD_OUTPUT_HANDLE, &cp->PipeChildStd[1]);
-    }
-  else if(cp->PipeNativeSTDOUT[1])
-    {
+  } else if (cp->PipeNativeSTDOUT[1]) {
     /* Use the given handle for stdout.  */
     kwsysProcessSetupPipeNative(cp->PipeNativeSTDOUT[1], &cp->PipeChildStd[1]);
-    }
-  else
-    {
+  } else {
     /* Use our pipe for stdout.  Duplicate the handle since our waker
        thread will use the original.  Do not make it inherited yet.  */
-    if(!DuplicateHandle(GetCurrentProcess(),
-                        cp->Pipe[KWSYSPE_PIPE_STDOUT].Write,
-                        GetCurrentProcess(), &cp->PipeChildStd[1],
-                        0, FALSE, DUPLICATE_SAME_ACCESS))
-      {
+    if (!DuplicateHandle(GetCurrentProcess(),
+                         cp->Pipe[KWSYSPE_PIPE_STDOUT].Write,
+                         GetCurrentProcess(), &cp->PipeChildStd[1], 0, FALSE,
+                         DUPLICATE_SAME_ACCESS)) {
       kwsysProcessCleanup(cp, GetLastError());
       return;
-      }
     }
+  }
 
   /* Create stderr pipe to be shared by all processes in the pipeline.
      We always create this so the pipe thread can run even if we do not
      end up giving the write end to the child below.  */
-  if(!CreatePipe(&cp->Pipe[KWSYSPE_PIPE_STDERR].Read,
-                 &cp->Pipe[KWSYSPE_PIPE_STDERR].Write, 0, 0))
-    {
+  if (!CreatePipe(&cp->Pipe[KWSYSPE_PIPE_STDERR].Read,
+                  &cp->Pipe[KWSYSPE_PIPE_STDERR].Write, 0, 0)) {
     kwsysProcessCleanup(cp, GetLastError());
     return;
-    }
+  }
 
-  if(cp->PipeFileSTDERR)
-    {
+  if (cp->PipeFileSTDERR) {
     /* Use a file for stderr.  */
     DWORD error = kwsysProcessSetupOutputPipeFile(&cp->PipeChildStd[2],
                                                   cp->PipeFileSTDERR);
-    if(error)
-      {
+    if (error) {
       kwsysProcessCleanup(cp, error);
       return;
-      }
     }
-  else if(cp->PipeSharedSTDERR)
-    {
+  } else if (cp->PipeSharedSTDERR) {
     /* Use the parent stderr.  */
     kwsysProcessSetupSharedPipe(STD_ERROR_HANDLE, &cp->PipeChildStd[2]);
-    }
-  else if(cp->PipeNativeSTDERR[1])
-    {
+  } else if (cp->PipeNativeSTDERR[1]) {
     /* Use the given handle for stderr.  */
     kwsysProcessSetupPipeNative(cp->PipeNativeSTDERR[1], &cp->PipeChildStd[2]);
-    }
-  else
-    {
+  } else {
     /* Use our pipe for stderr.  Duplicate the handle since our waker
        thread will use the original.  Do not make it inherited yet.  */
-    if(!DuplicateHandle(GetCurrentProcess(),
-                        cp->Pipe[KWSYSPE_PIPE_STDERR].Write,
-                        GetCurrentProcess(), &cp->PipeChildStd[2],
-                        0, FALSE, DUPLICATE_SAME_ACCESS))
-      {
+    if (!DuplicateHandle(GetCurrentProcess(),
+                         cp->Pipe[KWSYSPE_PIPE_STDERR].Write,
+                         GetCurrentProcess(), &cp->PipeChildStd[2], 0, FALSE,
+                         DUPLICATE_SAME_ACCESS)) {
       kwsysProcessCleanup(cp, GetLastError());
       return;
-      }
     }
+  }
 
   /* Create the pipeline of processes.  */
   {
-  /* Child startup control data.  */
-  kwsysProcessCreateInformation si;
-  HANDLE nextStdInput = cp->PipeChildStd[0];
-
-  /* Initialize startup info data.  */
-  ZeroMemory(&si, sizeof(si));
-  si.StartupInfo.cb = sizeof(si.StartupInfo);
-
-  /* Decide whether a child window should be shown.  */
-  si.StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
-  si.StartupInfo.wShowWindow =
-    (unsigned short)(cp->HideWindow?SW_HIDE:SW_SHOWDEFAULT);
-
-  /* Connect the child's output pipes to the threads.  */
-  si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
-
-  for(i=0; i < cp->NumberOfCommands; ++i)
-    {
-    /* Setup the process's pipes.  */
-    si.hStdInput = nextStdInput;
-    if (i == cp->NumberOfCommands-1)
-      {
-      /* The last child gets the overall stdout.  */
-      nextStdInput = INVALID_HANDLE_VALUE;
-      si.hStdOutput = cp->PipeChildStd[1];
-      }
-    else
-      {
-      /* Create a pipe to sit between the children.  */
-      HANDLE p[2] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
-      if (!CreatePipe(&p[0], &p[1], 0, 0))
-        {
-        DWORD error = GetLastError();
-        if (nextStdInput != cp->PipeChildStd[0])
-          {
-          kwsysProcessCleanupHandle(&nextStdInput);
+    /* Child startup control data.  */
+    kwsysProcessCreateInformation si;
+    HANDLE nextStdInput = cp->PipeChildStd[0];
+
+    /* Initialize startup info data.  */
+    ZeroMemory(&si, sizeof(si));
+    si.StartupInfo.cb = sizeof(si.StartupInfo);
+
+    /* Decide whether a child window should be shown.  */
+    si.StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
+    si.StartupInfo.wShowWindow =
+      (unsigned short)(cp->HideWindow ? SW_HIDE : SW_SHOWDEFAULT);
+
+    /* Connect the child's output pipes to the threads.  */
+    si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
+
+    for (i = 0; i < cp->NumberOfCommands; ++i) {
+      /* Setup the process's pipes.  */
+      si.hStdInput = nextStdInput;
+      if (i == cp->NumberOfCommands - 1) {
+        /* The last child gets the overall stdout.  */
+        nextStdInput = INVALID_HANDLE_VALUE;
+        si.hStdOutput = cp->PipeChildStd[1];
+      } else {
+        /* Create a pipe to sit between the children.  */
+        HANDLE p[2] = { INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE };
+        if (!CreatePipe(&p[0], &p[1], 0, 0)) {
+          DWORD error = GetLastError();
+          if (nextStdInput != cp->PipeChildStd[0]) {
+            kwsysProcessCleanupHandle(&nextStdInput);
           }
-        kwsysProcessCleanup(cp, error);
-        return;
+          kwsysProcessCleanup(cp, error);
+          return;
         }
-      nextStdInput = p[0];
-      si.hStdOutput = p[1];
+        nextStdInput = p[0];
+        si.hStdOutput = p[1];
       }
-    si.hStdError = cp->MergeOutput? cp->PipeChildStd[1] : cp->PipeChildStd[2];
+      si.hStdError =
+        cp->MergeOutput ? cp->PipeChildStd[1] : cp->PipeChildStd[2];
 
-    {
-    DWORD error = kwsysProcessCreate(cp, i, &si);
-
-    /* Close our copies of pipes used between children.  */
-    if (si.hStdInput != cp->PipeChildStd[0])
-      {
-      kwsysProcessCleanupHandle(&si.hStdInput);
-      }
-    if (si.hStdOutput != cp->PipeChildStd[1])
-      {
-      kwsysProcessCleanupHandle(&si.hStdOutput);
-      }
-    if (si.hStdError != cp->PipeChildStd[2] && !cp->MergeOutput)
-      {
-      kwsysProcessCleanupHandle(&si.hStdError);
-      }
-    if (!error)
-      {
-      cp->ProcessEvents[i+1] = cp->ProcessInformation[i].hProcess;
-      }
-    else
       {
-      if (nextStdInput != cp->PipeChildStd[0])
-        {
-        kwsysProcessCleanupHandle(&nextStdInput);
+        DWORD error = kwsysProcessCreate(cp, i, &si);
+
+        /* Close our copies of pipes used between children.  */
+        if (si.hStdInput != cp->PipeChildStd[0]) {
+          kwsysProcessCleanupHandle(&si.hStdInput);
+        }
+        if (si.hStdOutput != cp->PipeChildStd[1]) {
+          kwsysProcessCleanupHandle(&si.hStdOutput);
+        }
+        if (si.hStdError != cp->PipeChildStd[2] && !cp->MergeOutput) {
+          kwsysProcessCleanupHandle(&si.hStdError);
+        }
+        if (!error) {
+          cp->ProcessEvents[i + 1] = cp->ProcessInformation[i].hProcess;
+        } else {
+          if (nextStdInput != cp->PipeChildStd[0]) {
+            kwsysProcessCleanupHandle(&nextStdInput);
+          }
+          kwsysProcessCleanup(cp, error);
+          return;
         }
-      kwsysProcessCleanup(cp, error);
-      return;
       }
     }
-    }
   }
 
   /* The parent process does not need the child's pipe ends.  */
-  for (i=0; i < 3; ++i)
-    {
+  for (i = 0; i < 3; ++i) {
     kwsysProcessCleanupHandle(&cp->PipeChildStd[i]);
-    }
+  }
 
   /* Restore the working directory.  */
-  if(cp->RealWorkingDirectory)
-    {
+  if (cp->RealWorkingDirectory) {
     SetCurrentDirectoryW(cp->RealWorkingDirectory);
     free(cp->RealWorkingDirectory);
     cp->RealWorkingDirectory = 0;
-    }
+  }
 
   /* The timeout period starts now.  */
   cp->StartTime = kwsysProcessTimeGetCurrent();
@@ -1203,24 +1110,21 @@ void kwsysProcess_Execute(kwsysProcess* cp)
 
   /* All processes in the pipeline have been started in suspended
      mode.  Resume them all now.  */
-  for(i=0; i < cp->NumberOfCommands; ++i)
-    {
+  for (i = 0; i < cp->NumberOfCommands; ++i) {
     ResumeThread(cp->ProcessInformation[i].hThread);
-    }
+  }
 
   /* ---- It is no longer safe to call kwsysProcessCleanup. ----- */
   /* Tell the pipe threads that a process has started.  */
-  for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
-    {
+  for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
     ReleaseSemaphore(cp->Pipe[i].Reader.Ready, 1, 0);
     ReleaseSemaphore(cp->Pipe[i].Waker.Ready, 1, 0);
-    }
+  }
 
   /* We don't care about the children's main threads.  */
-  for(i=0; i < cp->NumberOfCommands; ++i)
-    {
+  for (i = 0; i < cp->NumberOfCommands; ++i) {
     kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hThread);
-    }
+  }
 
   /* No pipe has reported data.  */
   cp->CurrentIndex = KWSYSPE_PIPE_COUNT;
@@ -1237,21 +1141,19 @@ void kwsysProcess_Disown(kwsysProcess* cp)
   int i;
 
   /* Make sure we are executing a detached process.  */
-  if(!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
-     cp->TimeoutExpired || cp->Killed || cp->Terminated)
-    {
+  if (!cp || !cp->Detached || cp->State != kwsysProcess_State_Executing ||
+      cp->TimeoutExpired || cp->Killed || cp->Terminated) {
     return;
-    }
+  }
 
   /* Disable the reading threads.  */
   kwsysProcessDisablePipeThreads(cp);
 
   /* Wait for all pipe threads to reset.  */
-  for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
-    {
+  for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
     WaitForSingleObject(cp->Pipe[i].Reader.Reset, INFINITE);
     WaitForSingleObject(cp->Pipe[i].Waker.Reset, INFINITE);
-    }
+  }
 
   /* We will not wait for exit, so cleanup now.  */
   kwsysProcessCleanup(cp, 0);
@@ -1276,11 +1178,10 @@ int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
   DWORD w;
 
   /* Make sure we are executing a process.  */
-  if(!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
-     cp->TimeoutExpired)
-    {
+  if (!cp || cp->State != kwsysProcess_State_Executing || cp->Killed ||
+      cp->TimeoutExpired) {
     return kwsysProcess_Pipe_None;
-    }
+  }
 
   /* Record the time at which user timeout period starts.  */
   userStartTime = kwsysProcessTimeGetCurrent();
@@ -1290,125 +1191,102 @@ int kwsysProcess_WaitForData(kwsysProcess* cp, char** data, int* length,
   user = kwsysProcessGetTimeoutTime(cp, userTimeout, &timeoutTime);
 
   /* Loop until we have a reason to return.  */
-  while(!done && cp->PipesLeft > 0)
-    {
+  while (!done && cp->PipesLeft > 0) {
     /* If we previously got data from a thread, let it know we are
        done with the data.  */
-    if(cp->CurrentIndex < KWSYSPE_PIPE_COUNT)
-      {
+    if (cp->CurrentIndex < KWSYSPE_PIPE_COUNT) {
       KWSYSPE_DEBUG((stderr, "releasing reader %d\n", cp->CurrentIndex));
       ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Reader.Go, 1, 0);
       cp->CurrentIndex = KWSYSPE_PIPE_COUNT;
-      }
+    }
 
     /* Setup a timeout if required.  */
-    if(kwsysProcessGetTimeoutLeft(&timeoutTime, user?userTimeout:0,
-                                  &timeoutLength))
-      {
+    if (kwsysProcessGetTimeoutLeft(&timeoutTime, user ? userTimeout : 0,
+                                   &timeoutLength)) {
       /* Timeout has already expired.  */
       expired = 1;
       break;
-      }
-    if(timeoutTime.QuadPart < 0)
-      {
+    }
+    if (timeoutTime.QuadPart < 0) {
       timeout = INFINITE;
-      }
-    else
-      {
+    } else {
       timeout = kwsysProcessTimeToDWORD(timeoutLength);
-      }
+    }
 
     /* Wait for a pipe's thread to signal or a process to terminate.  */
-    w = WaitForMultipleObjects(cp->ProcessEventsLength, cp->ProcessEvents,
-                               0, timeout);
-    if(w == WAIT_TIMEOUT)
-      {
+    w = WaitForMultipleObjects(cp->ProcessEventsLength, cp->ProcessEvents, 0,
+                               timeout);
+    if (w == WAIT_TIMEOUT) {
       /* Timeout has expired.  */
       expired = 1;
       done = 1;
-      }
-    else if(w == WAIT_OBJECT_0)
-      {
+    } else if (w == WAIT_OBJECT_0) {
       /* Save the index of the reporting thread and release the mutex.
          The thread will block until we signal its Empty mutex.  */
       cp->CurrentIndex = cp->SharedIndex;
       ReleaseSemaphore(cp->SharedIndexMutex, 1, 0);
 
       /* Data are available or a pipe closed.  */
-      if(cp->Pipe[cp->CurrentIndex].Closed)
-        {
+      if (cp->Pipe[cp->CurrentIndex].Closed) {
         /* The pipe closed at the write end.  Close the read end and
            inform the wakeup thread it is done with this process.  */
         kwsysProcessCleanupHandle(&cp->Pipe[cp->CurrentIndex].Read);
         ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Waker.Go, 1, 0);
         KWSYSPE_DEBUG((stderr, "wakeup %d\n", cp->CurrentIndex));
         --cp->PipesLeft;
-        }
-      else if(data && length)
-        {
+      } else if (data && length) {
         /* Report this data.  */
         *data = cp->Pipe[cp->CurrentIndex].DataBuffer;
         *length = cp->Pipe[cp->CurrentIndex].DataLength;
-        switch(cp->CurrentIndex)
-          {
+        switch (cp->CurrentIndex) {
           case KWSYSPE_PIPE_STDOUT:
-            pipeId = kwsysProcess_Pipe_STDOUT; break;
+            pipeId = kwsysProcess_Pipe_STDOUT;
+            break;
           case KWSYSPE_PIPE_STDERR:
-            pipeId = kwsysProcess_Pipe_STDERR; break;
-          }
-        done = 1;
+            pipeId = kwsysProcess_Pipe_STDERR;
+            break;
         }
+        done = 1;
       }
-    else
-      {
+    } else {
       /* A process has terminated.  */
-      kwsysProcessDestroy(cp, w-WAIT_OBJECT_0);
-      }
+      kwsysProcessDestroy(cp, w - WAIT_OBJECT_0);
     }
+  }
 
   /* Update the user timeout.  */
-  if(userTimeout)
-    {
+  if (userTimeout) {
     kwsysProcessTime userEndTime = kwsysProcessTimeGetCurrent();
-    kwsysProcessTime difference = kwsysProcessTimeSubtract(userEndTime,
-                                                           userStartTime);
+    kwsysProcessTime difference =
+      kwsysProcessTimeSubtract(userEndTime, userStartTime);
     double d = kwsysProcessTimeToDouble(difference);
     *userTimeout -= d;
-    if(*userTimeout < 0)
-      {
+    if (*userTimeout < 0) {
       *userTimeout = 0;
-      }
     }
+  }
 
   /* Check what happened.  */
-  if(pipeId)
-    {
+  if (pipeId) {
     /* Data are ready on a pipe.  */
     return pipeId;
-    }
-  else if(expired)
-    {
+  } else if (expired) {
     /* A timeout has expired.  */
-    if(user)
-      {
+    if (user) {
       /* The user timeout has expired.  It has no time left.  */
       return kwsysProcess_Pipe_Timeout;
-      }
-    else
-      {
+    } else {
       /* The process timeout has expired.  Kill the child now.  */
       KWSYSPE_DEBUG((stderr, "killing child because timeout expired\n"));
       kwsysProcess_Kill(cp);
       cp->TimeoutExpired = 1;
       cp->Killed = 0;
       return kwsysProcess_Pipe_None;
-      }
     }
-  else
-    {
+  } else {
     /* The children have terminated and no more data are available.  */
     return kwsysProcess_Pipe_None;
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -1418,75 +1296,62 @@ int kwsysProcess_WaitForExit(kwsysProcess* cp, double* userTimeout)
   int pipe;
 
   /* Make sure we are executing a process.  */
-  if(!cp || cp->State != kwsysProcess_State_Executing)
-    {
+  if (!cp || cp->State != kwsysProcess_State_Executing) {
     return 1;
-    }
+  }
 
   /* Wait for the process to terminate.  Ignore all data.  */
-  while((pipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0)
-    {
-    if(pipe == kwsysProcess_Pipe_Timeout)
-      {
+  while ((pipe = kwsysProcess_WaitForData(cp, 0, 0, userTimeout)) > 0) {
+    if (pipe == kwsysProcess_Pipe_Timeout) {
       /* The user timeout has expired.  */
       return 0;
-      }
     }
+  }
 
   KWSYSPE_DEBUG((stderr, "no more data\n"));
 
   /* When the last pipe closes in WaitForData, the loop terminates
      without releasing the pipe's thread.  Release it now.  */
-  if(cp->CurrentIndex < KWSYSPE_PIPE_COUNT)
-    {
+  if (cp->CurrentIndex < KWSYSPE_PIPE_COUNT) {
     KWSYSPE_DEBUG((stderr, "releasing reader %d\n", cp->CurrentIndex));
     ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Reader.Go, 1, 0);
     cp->CurrentIndex = KWSYSPE_PIPE_COUNT;
-    }
+  }
 
   /* Wait for all pipe threads to reset.  */
-  for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
-    {
+  for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
     KWSYSPE_DEBUG((stderr, "waiting reader reset %d\n", i));
     WaitForSingleObject(cp->Pipe[i].Reader.Reset, INFINITE);
     KWSYSPE_DEBUG((stderr, "waiting waker reset %d\n", i));
     WaitForSingleObject(cp->Pipe[i].Waker.Reset, INFINITE);
-    }
+  }
 
   /* ---- It is now safe again to call kwsysProcessCleanup. ----- */
   /* Close all the pipes.  */
   kwsysProcessCleanup(cp, 0);
 
   /* Determine the outcome.  */
-  if(cp->Killed)
-    {
+  if (cp->Killed) {
     /* We killed the child.  */
     cp->State = kwsysProcess_State_Killed;
-    }
-  else if(cp->TimeoutExpired)
-    {
+  } else if (cp->TimeoutExpired) {
     /* The timeout expired.  */
     cp->State = kwsysProcess_State_Expired;
-    }
-  else
-    {
+  } else {
     /* The children exited.  Report the outcome of the last process.  */
-    cp->ExitCode = cp->CommandExitCodes[cp->NumberOfCommands-1];
-    if((cp->ExitCode & 0xF0000000) == 0xC0000000)
-      {
+    cp->ExitCode = cp->CommandExitCodes[cp->NumberOfCommands - 1];
+    if ((cp->ExitCode & 0xF0000000) == 0xC0000000) {
       /* Child terminated due to exceptional behavior.  */
       cp->State = kwsysProcess_State_Exception;
       cp->ExitValue = 1;
       kwsysProcessSetExitException(cp, cp->ExitCode);
-      }
-    else
-      {
+    } else {
       /* Child exited without exception.  */
       cp->State = kwsysProcess_State_Exited;
       cp->ExitException = kwsysProcess_Exception_None;
       cp->ExitValue = cp->ExitCode;
-      }
     }
+  }
 
   return 1;
 }
@@ -1496,45 +1361,37 @@ void kwsysProcess_Interrupt(kwsysProcess* cp)
 {
   int i;
   /* Make sure we are executing a process.  */
-  if(!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired ||
-     cp->Killed)
-    {
+  if (!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired ||
+      cp->Killed) {
     KWSYSPE_DEBUG((stderr, "interrupt: child not executing\n"));
     return;
-    }
+  }
 
   /* Skip actually interrupting the child if it has already terminated.  */
-  if(cp->Terminated)
-    {
+  if (cp->Terminated) {
     KWSYSPE_DEBUG((stderr, "interrupt: child already terminated\n"));
     return;
-    }
+  }
 
   /* Interrupt the children.  */
-  if (cp->CreateProcessGroup)
-    {
-    if(cp->ProcessInformation)
-      {
-      for(i=0; i < cp->NumberOfCommands; ++i)
-        {
+  if (cp->CreateProcessGroup) {
+    if (cp->ProcessInformation) {
+      for (i = 0; i < cp->NumberOfCommands; ++i) {
         /* Make sure the process handle isn't closed (e.g. from disowning). */
-        if(cp->ProcessInformation[i].hProcess)
-          {
+        if (cp->ProcessInformation[i].hProcess) {
           /* The user created a process group for this process.  The group ID
              is the process ID for the original process in the group.  Note
              that we have to use Ctrl+Break: Ctrl+C is not allowed for process
              groups.  */
           GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT,
                                    cp->ProcessInformation[i].dwProcessId);
-          }
         }
       }
     }
-  else
-    {
+  } else {
     /* No process group was created.  Kill our own process group...  */
     GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, 0);
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -1542,34 +1399,31 @@ void kwsysProcess_Kill(kwsysProcess* cp)
 {
   int i;
   /* Make sure we are executing a process.  */
-  if(!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired ||
-     cp->Killed)
-    {
+  if (!cp || cp->State != kwsysProcess_State_Executing || cp->TimeoutExpired ||
+      cp->Killed) {
     KWSYSPE_DEBUG((stderr, "kill: child not executing\n"));
     return;
-    }
+  }
 
   /* Disable the reading threads.  */
   KWSYSPE_DEBUG((stderr, "kill: disabling pipe threads\n"));
   kwsysProcessDisablePipeThreads(cp);
 
   /* Skip actually killing the child if it has already terminated.  */
-  if(cp->Terminated)
-    {
+  if (cp->Terminated) {
     KWSYSPE_DEBUG((stderr, "kill: child already terminated\n"));
     return;
-    }
+  }
 
   /* Kill the children.  */
   cp->Killed = 1;
-  for(i=0; i < cp->NumberOfCommands; ++i)
-    {
+  for (i = 0; i < cp->NumberOfCommands; ++i) {
     kwsysProcessKillTree(cp->ProcessInformation[i].dwProcessId);
     /* Remove from global list of processes and close handles.  */
     kwsysProcessesRemove(cp->ProcessInformation[i].hProcess);
     kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hThread);
     kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hProcess);
-    }
+  }
 
   /* We are killing the children and ignoring all data.  Do not wait
      for them to exit.  */
@@ -1587,14 +1441,13 @@ DWORD WINAPI kwsysProcessPipeThreadRead(LPVOID ptd)
   kwsysProcess* cp = td->Process;
 
   /* Wait for a process to be ready.  */
-  while((WaitForSingleObject(td->Reader.Ready, INFINITE), !cp->Deleting))
-    {
+  while ((WaitForSingleObject(td->Reader.Ready, INFINITE), !cp->Deleting)) {
     /* Read output from the process for this thread's pipe.  */
     kwsysProcessPipeThreadReadPipe(cp, td);
 
     /* Signal the main thread we have reset for a new process.  */
     ReleaseSemaphore(td->Reader.Reset, 1, 0);
-    }
+  }
   return 0;
 }
 
@@ -1607,24 +1460,21 @@ DWORD WINAPI kwsysProcessPipeThreadRead(LPVOID ptd)
 void kwsysProcessPipeThreadReadPipe(kwsysProcess* cp, kwsysProcessPipeData* td)
 {
   /* Wait for space in the thread's buffer. */
-  while((KWSYSPE_DEBUG((stderr, "wait for read %d\n", td->Index)),
-         WaitForSingleObject(td->Reader.Go, INFINITE), !td->Closed))
-    {
+  while ((KWSYSPE_DEBUG((stderr, "wait for read %d\n", td->Index)),
+          WaitForSingleObject(td->Reader.Go, INFINITE), !td->Closed)) {
     KWSYSPE_DEBUG((stderr, "reading %d\n", td->Index));
 
     /* Read data from the pipe.  This may block until data are available.  */
-    if(!ReadFile(td->Read, td->DataBuffer, KWSYSPE_PIPE_BUFFER_SIZE,
-                 &td->DataLength, 0))
-      {
-      if(GetLastError() != ERROR_BROKEN_PIPE)
-        {
+    if (!ReadFile(td->Read, td->DataBuffer, KWSYSPE_PIPE_BUFFER_SIZE,
+                  &td->DataLength, 0)) {
+      if (GetLastError() != ERROR_BROKEN_PIPE) {
         /* UNEXPECTED failure to read the pipe.  */
-        }
+      }
 
       /* The pipe closed.  There are no more data to read.  */
       td->Closed = 1;
       KWSYSPE_DEBUG((stderr, "read closed %d\n", td->Index));
-      }
+    }
 
     KWSYSPE_DEBUG((stderr, "read %d\n", td->Index));
 
@@ -1636,7 +1486,7 @@ void kwsysProcessPipeThreadReadPipe(kwsysProcess* cp, kwsysProcessPipeData* td)
     /* Tell the main thread we have something to report.  */
     cp->SharedIndex = td->Index;
     ReleaseSemaphore(cp->Full, 1, 0);
-    }
+  }
 
   /* We were signalled to exit with our buffer empty.  Reset the
      mutex for a new process.  */
@@ -1656,14 +1506,13 @@ DWORD WINAPI kwsysProcessPipeThreadWake(LPVOID ptd)
   kwsysProcess* cp = td->Process;
 
   /* Wait for a process to be ready.  */
-  while((WaitForSingleObject(td->Waker.Ready, INFINITE), !cp->Deleting))
-    {
+  while ((WaitForSingleObject(td->Waker.Ready, INFINITE), !cp->Deleting)) {
     /* Wait for a possible wakeup.  */
     kwsysProcessPipeThreadWakePipe(cp, td);
 
     /* Signal the main thread we have reset for a new process.  */
     ReleaseSemaphore(td->Waker.Reset, 1, 0);
-    }
+  }
   return 0;
 }
 
@@ -1683,13 +1532,12 @@ void kwsysProcessPipeThreadWakePipe(kwsysProcess* cp, kwsysProcessPipeData* td)
   KWSYSPE_DEBUG((stderr, "waking %d\n", td->Index));
 
   /* If the pipe is not closed, we need to wake up the reading thread.  */
-  if(!td->Closed)
-    {
+  if (!td->Closed) {
     DWORD dummy;
     KWSYSPE_DEBUG((stderr, "waker %d writing byte\n", td->Index));
     WriteFile(td->Write, "", 1, &dummy, 0);
     KWSYSPE_DEBUG((stderr, "waker %d wrote byte\n", td->Index));
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -1709,55 +1557,48 @@ int kwsysProcessInitialize(kwsysProcess* cp)
   strcpy(cp->ExitExceptionString, "No exception");
 
   /* Allocate process information for each process.  */
-  cp->ProcessInformation =
-    (PROCESS_INFORMATION*)malloc(sizeof(PROCESS_INFORMATION) *
-                                 cp->NumberOfCommands);
-  if(!cp->ProcessInformation)
-    {
+  cp->ProcessInformation = (PROCESS_INFORMATION*)malloc(
+    sizeof(PROCESS_INFORMATION) * cp->NumberOfCommands);
+  if (!cp->ProcessInformation) {
     return 0;
-    }
+  }
   ZeroMemory(cp->ProcessInformation,
              sizeof(PROCESS_INFORMATION) * cp->NumberOfCommands);
-  if(cp->CommandExitCodes)
-    {
+  if (cp->CommandExitCodes) {
     free(cp->CommandExitCodes);
-    }
-  cp->CommandExitCodes = (DWORD*)malloc(sizeof(DWORD)*cp->NumberOfCommands);
-  if(!cp->CommandExitCodes)
-    {
+  }
+  cp->CommandExitCodes = (DWORD*)malloc(sizeof(DWORD) * cp->NumberOfCommands);
+  if (!cp->CommandExitCodes) {
     return 0;
-    }
-  ZeroMemory(cp->CommandExitCodes, sizeof(DWORD)*cp->NumberOfCommands);
+  }
+  ZeroMemory(cp->CommandExitCodes, sizeof(DWORD) * cp->NumberOfCommands);
 
   /* Allocate event wait array.  The first event is cp->Full, the rest
      are the process termination events.  */
-  cp->ProcessEvents = (PHANDLE)malloc(sizeof(HANDLE)*(cp->NumberOfCommands+1));
-  if(!cp->ProcessEvents)
-    {
+  cp->ProcessEvents =
+    (PHANDLE)malloc(sizeof(HANDLE) * (cp->NumberOfCommands + 1));
+  if (!cp->ProcessEvents) {
     return 0;
-    }
-  ZeroMemory(cp->ProcessEvents, sizeof(HANDLE) * (cp->NumberOfCommands+1));
+  }
+  ZeroMemory(cp->ProcessEvents, sizeof(HANDLE) * (cp->NumberOfCommands + 1));
   cp->ProcessEvents[0] = cp->Full;
-  cp->ProcessEventsLength = cp->NumberOfCommands+1;
+  cp->ProcessEventsLength = cp->NumberOfCommands + 1;
 
   /* Allocate space to save the real working directory of this process.  */
-  if(cp->WorkingDirectory)
-    {
+  if (cp->WorkingDirectory) {
     cp->RealWorkingDirectoryLength = GetCurrentDirectoryW(0, 0);
-    if(cp->RealWorkingDirectoryLength > 0)
-      {
-      cp->RealWorkingDirectory = malloc(cp->RealWorkingDirectoryLength * sizeof(wchar_t));
-      if(!cp->RealWorkingDirectory)
-        {
+    if (cp->RealWorkingDirectoryLength > 0) {
+      cp->RealWorkingDirectory =
+        malloc(cp->RealWorkingDirectoryLength * sizeof(wchar_t));
+      if (!cp->RealWorkingDirectory) {
         return 0;
-        }
       }
     }
+  }
   {
-  int i;
-  for (i=0; i < 3; ++i)
-    {
-    cp->PipeChildStd[i] = INVALID_HANDLE_VALUE;
+    int i;
+    for (i = 0; i < 3; ++i) {
+      cp->PipeChildStd[i] = INVALID_HANDLE_VALUE;
     }
   }
 
@@ -1770,28 +1611,21 @@ static DWORD kwsysProcessCreateChildHandle(PHANDLE out, HANDLE in, int isStdIn)
   DWORD flags;
 
   /* Check whether the handle is valid for this process.  */
-  if (in != INVALID_HANDLE_VALUE && GetHandleInformation(in, &flags))
-    {
+  if (in != INVALID_HANDLE_VALUE && GetHandleInformation(in, &flags)) {
     /* Use the handle as-is if it is already inherited.  */
-    if (flags & HANDLE_FLAG_INHERIT)
-      {
+    if (flags & HANDLE_FLAG_INHERIT) {
       *out = in;
       return ERROR_SUCCESS;
-      }
+    }
 
     /* Create an inherited copy of this handle.  */
-    if (DuplicateHandle(GetCurrentProcess(), in, GetCurrentProcess(), out,
-                        0, TRUE, DUPLICATE_SAME_ACCESS))
-      {
+    if (DuplicateHandle(GetCurrentProcess(), in, GetCurrentProcess(), out, 0,
+                        TRUE, DUPLICATE_SAME_ACCESS)) {
       return ERROR_SUCCESS;
-      }
-    else
-      {
+    } else {
       return GetLastError();
-      }
     }
-  else
-    {
+  } else {
     /* The given handle is not valid for this process.  Some child
        processes may break if they do not have a valid standard handle,
        so open NUL to give to the child.  */
@@ -1799,13 +1633,12 @@ static DWORD kwsysProcessCreateChildHandle(PHANDLE out, HANDLE in, int isStdIn)
     ZeroMemory(&sa, sizeof(sa));
     sa.nLength = (DWORD)sizeof(sa);
     sa.bInheritHandle = 1;
-    *out = CreateFileW(L"NUL",
-                       (isStdIn ? GENERIC_READ :
-                        (GENERIC_WRITE | FILE_READ_ATTRIBUTES)),
-                       FILE_SHARE_READ|FILE_SHARE_WRITE,
-                       &sa, OPEN_EXISTING, 0, 0);
+    *out = CreateFileW(
+      L"NUL",
+      (isStdIn ? GENERIC_READ : (GENERIC_WRITE | FILE_READ_ATTRIBUTES)),
+      FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, 0);
     return (*out != INVALID_HANDLE_VALUE) ? ERROR_SUCCESS : GetLastError();
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -1816,54 +1649,49 @@ DWORD kwsysProcessCreate(kwsysProcess* cp, int index,
   DWORD error = ERROR_SUCCESS;
 
   /* Check if we are currently exiting.  */
-  if (!kwsysTryEnterCreateProcessSection())
-    {
+  if (!kwsysTryEnterCreateProcessSection()) {
     /* The Ctrl handler is currently working on exiting our process.  Rather
     than return an error code, which could cause incorrect conclusions to be
     reached by the caller, we simply hang.  (For example, a CMake try_run
     configure step might cause the project to configure wrong.)  */
     Sleep(INFINITE);
-    }
+  }
 
   /* Create the child in a suspended state so we can wait until all
      children have been created before running any one.  */
   creationFlags = CREATE_SUSPENDED;
-  if (cp->CreateProcessGroup)
-    {
+  if (cp->CreateProcessGroup) {
     creationFlags |= CREATE_NEW_PROCESS_GROUP;
-    }
+  }
 
   /* Create inherited copies of the handles.  */
   (error = kwsysProcessCreateChildHandle(&si->StartupInfo.hStdInput,
-                                          si->hStdInput, 1)) ||
-  (error = kwsysProcessCreateChildHandle(&si->StartupInfo.hStdOutput,
-                                          si->hStdOutput, 0)) ||
-  (error = kwsysProcessCreateChildHandle(&si->StartupInfo.hStdError,
-                                          si->hStdError, 0)) ||
-  /* Create the process.  */
-  (!CreateProcessW(0, cp->Commands[index], 0, 0, TRUE, creationFlags, 0,
-                  0, &si->StartupInfo, &cp->ProcessInformation[index]) &&
-    (error = GetLastError()));
+                                         si->hStdInput, 1)) ||
+    (error = kwsysProcessCreateChildHandle(&si->StartupInfo.hStdOutput,
+                                           si->hStdOutput, 0)) ||
+    (error = kwsysProcessCreateChildHandle(&si->StartupInfo.hStdError,
+                                           si->hStdError, 0)) ||
+    /* Create the process.  */
+    (!CreateProcessW(0, cp->Commands[index], 0, 0, TRUE, creationFlags, 0, 0,
+                     &si->StartupInfo, &cp->ProcessInformation[index]) &&
+     (error = GetLastError()));
 
   /* Close the inherited copies of the handles. */
-  if (si->StartupInfo.hStdInput != si->hStdInput)
-    {
+  if (si->StartupInfo.hStdInput != si->hStdInput) {
     kwsysProcessCleanupHandle(&si->StartupInfo.hStdInput);
-    }
-  if (si->StartupInfo.hStdOutput != si->hStdOutput)
-    {
+  }
+  if (si->StartupInfo.hStdOutput != si->hStdOutput) {
     kwsysProcessCleanupHandle(&si->StartupInfo.hStdOutput);
-    }
-  if (si->StartupInfo.hStdError != si->hStdError)
-    {
+  }
+  if (si->StartupInfo.hStdError != si->hStdError) {
     kwsysProcessCleanupHandle(&si->StartupInfo.hStdError);
-    }
+  }
 
   /* Add the process to the global list of processes. */
   if (!error &&
       !kwsysProcessesAdd(cp->ProcessInformation[index].hProcess,
-      cp->ProcessInformation[index].dwProcessId, cp->CreateProcessGroup))
-    {
+                         cp->ProcessInformation[index].dwProcessId,
+                         cp->CreateProcessGroup)) {
     /* This failed for some reason.  Kill the suspended process. */
     TerminateProcess(cp->ProcessInformation[index].hProcess, 1);
     /* And clean up... */
@@ -1871,7 +1699,7 @@ DWORD kwsysProcessCreate(kwsysProcess* cp, int index,
     kwsysProcessCleanupHandle(&cp->ProcessInformation[index].hThread);
     strcpy(cp->ErrorMessage, "kwsysProcessesAdd function failed");
     error = ERROR_NOT_ENOUGH_MEMORY; /* Most likely reason.  */
-    }
+  }
 
   /* If the console Ctrl handler is waiting for us, this will release it... */
   kwsysLeaveCreateProcessSection();
@@ -1885,13 +1713,11 @@ void kwsysProcessDestroy(kwsysProcess* cp, int event)
   int index;
 
   /* Find the process index for the termination event.  */
-  for(index=0; index < cp->NumberOfCommands; ++index)
-    {
-    if(cp->ProcessInformation[index].hProcess == cp->ProcessEvents[event])
-      {
+  for (index = 0; index < cp->NumberOfCommands; ++index) {
+    if (cp->ProcessInformation[index].hProcess == cp->ProcessEvents[event]) {
       break;
-      }
     }
+  }
 
   /* Check the exit code of the process.  */
   GetExitCodeProcess(cp->ProcessInformation[index].hProcess,
@@ -1905,20 +1731,17 @@ void kwsysProcessDestroy(kwsysProcess* cp, int event)
 
   /* Remove the process from the available events.  */
   cp->ProcessEventsLength -= 1;
-  for(i=event; i < cp->ProcessEventsLength; ++i)
-    {
-    cp->ProcessEvents[i] = cp->ProcessEvents[i+1];
-    }
+  for (i = event; i < cp->ProcessEventsLength; ++i) {
+    cp->ProcessEvents[i] = cp->ProcessEvents[i + 1];
+  }
 
   /* Check if all processes have terminated.  */
-  if(cp->ProcessEventsLength == 1)
-    {
+  if (cp->ProcessEventsLength == 1) {
     cp->Terminated = 1;
 
     /* Close our copies of the pipe write handles so the pipe threads
        can detect end-of-data.  */
-    for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
-      {
+    for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
       /* TODO: If the child created its own child (our grandchild)
          which inherited a copy of the pipe write-end then the pipe
          may not close and we will still need the waker write pipe.
@@ -1929,8 +1752,8 @@ void kwsysProcessDestroy(kwsysProcess* cp, int event)
          read on posix.  */
       KWSYSPE_DEBUG((stderr, "closing wakeup write %d\n", i));
       kwsysProcessCleanupHandle(&cp->Pipe[i].Write);
-      }
     }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -1939,24 +1762,22 @@ DWORD kwsysProcessSetupOutputPipeFile(PHANDLE phandle, const char* name)
   HANDLE fout;
   wchar_t* wname;
   DWORD error;
-  if(!name)
-    {
+  if (!name) {
     return ERROR_INVALID_PARAMETER;
-    }
+  }
 
   /* Close the existing handle.  */
   kwsysProcessCleanupHandle(phandle);
 
   /* Create a handle to write a file for the pipe.  */
   wname = kwsysEncoding_DupToWide(name);
-  fout = CreateFileW(wname, GENERIC_WRITE, FILE_SHARE_READ, 0,
-                    CREATE_ALWAYS, 0, 0);
+  fout =
+    CreateFileW(wname, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
   error = GetLastError();
   free(wname);
-  if(fout == INVALID_HANDLE_VALUE)
-    {
+  if (fout == INVALID_HANDLE_VALUE) {
     return error;
-    }
+  }
 
   /* Assign the replacement handle.  */
   *phandle = fout;
@@ -1986,14 +1807,13 @@ void kwsysProcessSetupPipeNative(HANDLE native, PHANDLE handle)
 /* Close the given handle if it is open.  Reset its value to 0.  */
 void kwsysProcessCleanupHandle(PHANDLE h)
 {
-  if(h && *h && *h != INVALID_HANDLE_VALUE &&
-     *h != GetStdHandle(STD_INPUT_HANDLE) &&
-     *h != GetStdHandle(STD_OUTPUT_HANDLE) &&
-     *h != GetStdHandle(STD_ERROR_HANDLE))
-    {
+  if (h && *h && *h != INVALID_HANDLE_VALUE &&
+      *h != GetStdHandle(STD_INPUT_HANDLE) &&
+      *h != GetStdHandle(STD_OUTPUT_HANDLE) &&
+      *h != GetStdHandle(STD_ERROR_HANDLE)) {
     CloseHandle(*h);
     *h = INVALID_HANDLE_VALUE;
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -2003,35 +1823,31 @@ void kwsysProcessCleanup(kwsysProcess* cp, DWORD error)
 {
   int i;
   /* If this is an error case, report the error.  */
-  if(error)
-    {
+  if (error) {
     /* Construct an error message if one has not been provided already.  */
-    if(cp->ErrorMessage[0] == 0)
-      {
+    if (cp->ErrorMessage[0] == 0) {
       /* Format the error message.  */
       wchar_t err_msg[KWSYSPE_PIPE_BUFFER_SIZE];
-      DWORD length = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
-                                   FORMAT_MESSAGE_IGNORE_INSERTS, 0, error,
-                                   MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-                                   err_msg, KWSYSPE_PIPE_BUFFER_SIZE, 0);
-      if(length < 1)
-        {
+      DWORD length = FormatMessageW(
+        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, error,
+        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), err_msg,
+        KWSYSPE_PIPE_BUFFER_SIZE, 0);
+      if (length < 1) {
         /* FormatMessage failed.  Use a default message.  */
         _snprintf(cp->ErrorMessage, KWSYSPE_PIPE_BUFFER_SIZE,
                   "Process execution failed with error 0x%X.  "
                   "FormatMessage failed with error 0x%X",
                   error, GetLastError());
-        }
-      if(!WideCharToMultiByte(CP_UTF8, 0, err_msg, -1, cp->ErrorMessage,
-                              KWSYSPE_PIPE_BUFFER_SIZE, NULL, NULL))
-        {
+      }
+      if (!WideCharToMultiByte(CP_UTF8, 0, err_msg, -1, cp->ErrorMessage,
+                               KWSYSPE_PIPE_BUFFER_SIZE, NULL, NULL)) {
         /* WideCharToMultiByte failed.  Use a default message.  */
         _snprintf(cp->ErrorMessage, KWSYSPE_PIPE_BUFFER_SIZE,
                   "Process execution failed with error 0x%X.  "
                   "WideCharToMultiByte failed with error 0x%X",
                   error, GetLastError());
-        }
       }
+    }
 
     /* Remove trailing period and newline, if any.  */
     kwsysProcessCleanErrorMessage(cp);
@@ -2040,60 +1856,50 @@ void kwsysProcessCleanup(kwsysProcess* cp, DWORD error)
     cp->State = kwsysProcess_State_Error;
 
     /* Cleanup any processes already started in a suspended state.  */
-    if(cp->ProcessInformation)
-      {
-      for(i=0; i < cp->NumberOfCommands; ++i)
-        {
-        if(cp->ProcessInformation[i].hProcess)
-          {
+    if (cp->ProcessInformation) {
+      for (i = 0; i < cp->NumberOfCommands; ++i) {
+        if (cp->ProcessInformation[i].hProcess) {
           TerminateProcess(cp->ProcessInformation[i].hProcess, 255);
           WaitForSingleObject(cp->ProcessInformation[i].hProcess, INFINITE);
-          }
         }
-      for(i=0; i < cp->NumberOfCommands; ++i)
-        {
+      }
+      for (i = 0; i < cp->NumberOfCommands; ++i) {
         /* Remove from global list of processes and close handles.  */
         kwsysProcessesRemove(cp->ProcessInformation[i].hProcess);
         kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hThread);
         kwsysProcessCleanupHandle(&cp->ProcessInformation[i].hProcess);
-        }
       }
+    }
 
     /* Restore the working directory.  */
-    if(cp->RealWorkingDirectory)
-      {
+    if (cp->RealWorkingDirectory) {
       SetCurrentDirectoryW(cp->RealWorkingDirectory);
-      }
     }
+  }
 
   /* Free memory.  */
-  if(cp->ProcessInformation)
-    {
+  if (cp->ProcessInformation) {
     free(cp->ProcessInformation);
     cp->ProcessInformation = 0;
-    }
-  if(cp->ProcessEvents)
-    {
+  }
+  if (cp->ProcessEvents) {
     free(cp->ProcessEvents);
     cp->ProcessEvents = 0;
-    }
-  if(cp->RealWorkingDirectory)
-    {
+  }
+  if (cp->RealWorkingDirectory) {
     free(cp->RealWorkingDirectory);
     cp->RealWorkingDirectory = 0;
-    }
+  }
 
   /* Close each pipe.  */
-  for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
-    {
+  for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
     kwsysProcessCleanupHandle(&cp->Pipe[i].Write);
     kwsysProcessCleanupHandle(&cp->Pipe[i].Read);
     cp->Pipe[i].Closed = 0;
-    }
-  for(i=0; i < 3; ++i)
-    {
+  }
+  for (i = 0; i < 3; ++i) {
     kwsysProcessCleanupHandle(&cp->PipeChildStd[i]);
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -2101,20 +1907,17 @@ void kwsysProcessCleanErrorMessage(kwsysProcess* cp)
 {
   /* Remove trailing period and newline, if any.  */
   size_t length = strlen(cp->ErrorMessage);
-  if(cp->ErrorMessage[length-1] == '\n')
-    {
-    cp->ErrorMessage[length-1] = 0;
+  if (cp->ErrorMessage[length - 1] == '\n') {
+    cp->ErrorMessage[length - 1] = 0;
     --length;
-    if(length > 0 && cp->ErrorMessage[length-1] == '\r')
-      {
-      cp->ErrorMessage[length-1] = 0;
+    if (length > 0 && cp->ErrorMessage[length - 1] == '\r') {
+      cp->ErrorMessage[length - 1] = 0;
       --length;
-      }
-    }
-  if(length > 0 && cp->ErrorMessage[length-1] == '.')
-    {
-    cp->ErrorMessage[length-1] = 0;
     }
+  }
+  if (length > 0 && cp->ErrorMessage[length - 1] == '.') {
+    cp->ErrorMessage[length - 1] = 0;
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -2125,29 +1928,27 @@ int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
 {
   /* The first time this is called, we need to calculate the time at
      which the child will timeout.  */
-  if(cp->Timeout && cp->TimeoutTime.QuadPart < 0)
-    {
+  if (cp->Timeout && cp->TimeoutTime.QuadPart < 0) {
     kwsysProcessTime length = kwsysProcessTimeFromDouble(cp->Timeout);
     cp->TimeoutTime = kwsysProcessTimeAdd(cp->StartTime, length);
-    }
+  }
 
   /* Start with process timeout.  */
   *timeoutTime = cp->TimeoutTime;
 
   /* Check if the user timeout is earlier.  */
-  if(userTimeout)
-    {
+  if (userTimeout) {
     kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
-    kwsysProcessTime userTimeoutLength = kwsysProcessTimeFromDouble(*userTimeout);
-    kwsysProcessTime userTimeoutTime = kwsysProcessTimeAdd(currentTime,
-                                                           userTimeoutLength);
-    if(timeoutTime->QuadPart < 0 ||
-       kwsysProcessTimeLess(userTimeoutTime, *timeoutTime))
-      {
+    kwsysProcessTime userTimeoutLength =
+      kwsysProcessTimeFromDouble(*userTimeout);
+    kwsysProcessTime userTimeoutTime =
+      kwsysProcessTimeAdd(currentTime, userTimeoutLength);
+    if (timeoutTime->QuadPart < 0 ||
+        kwsysProcessTimeLess(userTimeoutTime, *timeoutTime)) {
       *timeoutTime = userTimeoutTime;
       return 1;
-      }
     }
+  }
   return 0;
 }
 
@@ -2158,34 +1959,27 @@ int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
                                double* userTimeout,
                                kwsysProcessTime* timeoutLength)
 {
-  if(timeoutTime->QuadPart < 0)
-    {
+  if (timeoutTime->QuadPart < 0) {
     /* No timeout time has been requested.  */
     return 0;
-    }
-  else
-    {
+  } else {
     /* Calculate the remaining time.  */
     kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
     *timeoutLength = kwsysProcessTimeSubtract(*timeoutTime, currentTime);
 
-    if(timeoutLength->QuadPart < 0 && userTimeout && *userTimeout <= 0)
-      {
+    if (timeoutLength->QuadPart < 0 && userTimeout && *userTimeout <= 0) {
       /* Caller has explicitly requested a zero timeout.  */
       timeoutLength->QuadPart = 0;
-      }
+    }
 
-    if(timeoutLength->QuadPart < 0)
-      {
+    if (timeoutLength->QuadPart < 0) {
       /* Timeout has already expired.  */
       return 1;
-      }
-    else
-      {
+    } else {
       /* There is some time left.  */
       return 0;
-      }
     }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -2215,7 +2009,7 @@ double kwsysProcessTimeToDouble(kwsysProcessTime t)
 kwsysProcessTime kwsysProcessTimeFromDouble(double d)
 {
   kwsysProcessTime t;
-  t.QuadPart = (LONGLONG)(d*10000000);
+  t.QuadPart = (LONGLONG)(d * 10000000);
   return t;
 }
 
@@ -2226,7 +2020,8 @@ int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2)
 }
 
 /*--------------------------------------------------------------------------*/
-kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
+kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1,
+                                     kwsysProcessTime in2)
 {
   kwsysProcessTime out;
   out.QuadPart = in1.QuadPart + in2.QuadPart;
@@ -2234,7 +2029,8 @@ kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1, kwsysProcessTime in2)
 }
 
 /*--------------------------------------------------------------------------*/
-kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime in2)
+kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1,
+                                          kwsysProcessTime in2)
 {
   kwsysProcessTime out;
   out.QuadPart = in1.QuadPart - in2.QuadPart;
@@ -2242,71 +2038,93 @@ kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1, kwsysProcessTime
 }
 
 /*--------------------------------------------------------------------------*/
-#define KWSYSPE_CASE(type, str) \
-  cp->ExitException = kwsysProcess_Exception_##type; \
+#define KWSYSPE_CASE(type, str)                                               \
+  cp->ExitException = kwsysProcess_Exception_##type;                          \
   strcpy(cp->ExitExceptionString, str)
 static void kwsysProcessSetExitException(kwsysProcess* cp, int code)
 {
-  switch (code)
-    {
+  switch (code) {
     case STATUS_CONTROL_C_EXIT:
-      KWSYSPE_CASE(Interrupt, "User interrupt"); break;
+      KWSYSPE_CASE(Interrupt, "User interrupt");
+      break;
 
     case STATUS_FLOAT_DENORMAL_OPERAND:
-      KWSYSPE_CASE(Numerical, "Floating-point exception (denormal operand)"); break;
+      KWSYSPE_CASE(Numerical, "Floating-point exception (denormal operand)");
+      break;
     case STATUS_FLOAT_DIVIDE_BY_ZERO:
-      KWSYSPE_CASE(Numerical, "Divide-by-zero"); break;
+      KWSYSPE_CASE(Numerical, "Divide-by-zero");
+      break;
     case STATUS_FLOAT_INEXACT_RESULT:
-      KWSYSPE_CASE(Numerical, "Floating-point exception (inexact result)"); break;
+      KWSYSPE_CASE(Numerical, "Floating-point exception (inexact result)");
+      break;
     case STATUS_FLOAT_INVALID_OPERATION:
-      KWSYSPE_CASE(Numerical, "Invalid floating-point operation"); break;
+      KWSYSPE_CASE(Numerical, "Invalid floating-point operation");
+      break;
     case STATUS_FLOAT_OVERFLOW:
-      KWSYSPE_CASE(Numerical, "Floating-point overflow"); break;
+      KWSYSPE_CASE(Numerical, "Floating-point overflow");
+      break;
     case STATUS_FLOAT_STACK_CHECK:
-      KWSYSPE_CASE(Numerical, "Floating-point stack check failed"); break;
+      KWSYSPE_CASE(Numerical, "Floating-point stack check failed");
+      break;
     case STATUS_FLOAT_UNDERFLOW:
-      KWSYSPE_CASE(Numerical, "Floating-point underflow"); break;
+      KWSYSPE_CASE(Numerical, "Floating-point underflow");
+      break;
 #ifdef STATUS_FLOAT_MULTIPLE_FAULTS
     case STATUS_FLOAT_MULTIPLE_FAULTS:
-      KWSYSPE_CASE(Numerical, "Floating-point exception (multiple faults)"); break;
+      KWSYSPE_CASE(Numerical, "Floating-point exception (multiple faults)");
+      break;
 #endif
 #ifdef STATUS_FLOAT_MULTIPLE_TRAPS
     case STATUS_FLOAT_MULTIPLE_TRAPS:
-      KWSYSPE_CASE(Numerical, "Floating-point exception (multiple traps)"); break;
+      KWSYSPE_CASE(Numerical, "Floating-point exception (multiple traps)");
+      break;
 #endif
     case STATUS_INTEGER_DIVIDE_BY_ZERO:
-      KWSYSPE_CASE(Numerical, "Integer divide-by-zero"); break;
+      KWSYSPE_CASE(Numerical, "Integer divide-by-zero");
+      break;
     case STATUS_INTEGER_OVERFLOW:
-      KWSYSPE_CASE(Numerical, "Integer overflow"); break;
+      KWSYSPE_CASE(Numerical, "Integer overflow");
+      break;
 
     case STATUS_DATATYPE_MISALIGNMENT:
-      KWSYSPE_CASE(Fault, "Datatype misalignment"); break;
+      KWSYSPE_CASE(Fault, "Datatype misalignment");
+      break;
     case STATUS_ACCESS_VIOLATION:
-      KWSYSPE_CASE(Fault, "Access violation"); break;
+      KWSYSPE_CASE(Fault, "Access violation");
+      break;
     case STATUS_IN_PAGE_ERROR:
-      KWSYSPE_CASE(Fault, "In-page error"); break;
+      KWSYSPE_CASE(Fault, "In-page error");
+      break;
     case STATUS_INVALID_HANDLE:
-      KWSYSPE_CASE(Fault, "Invalid hanlde"); break;
+      KWSYSPE_CASE(Fault, "Invalid hanlde");
+      break;
     case STATUS_NONCONTINUABLE_EXCEPTION:
-      KWSYSPE_CASE(Fault, "Noncontinuable exception"); break;
+      KWSYSPE_CASE(Fault, "Noncontinuable exception");
+      break;
     case STATUS_INVALID_DISPOSITION:
-      KWSYSPE_CASE(Fault, "Invalid disposition"); break;
+      KWSYSPE_CASE(Fault, "Invalid disposition");
+      break;
     case STATUS_ARRAY_BOUNDS_EXCEEDED:
-      KWSYSPE_CASE(Fault, "Array bounds exceeded"); break;
+      KWSYSPE_CASE(Fault, "Array bounds exceeded");
+      break;
     case STATUS_STACK_OVERFLOW:
-      KWSYSPE_CASE(Fault, "Stack overflow"); break;
+      KWSYSPE_CASE(Fault, "Stack overflow");
+      break;
 
     case STATUS_ILLEGAL_INSTRUCTION:
-      KWSYSPE_CASE(Illegal, "Illegal instruction"); break;
+      KWSYSPE_CASE(Illegal, "Illegal instruction");
+      break;
     case STATUS_PRIVILEGED_INSTRUCTION:
-      KWSYSPE_CASE(Illegal, "Privileged instruction"); break;
+      KWSYSPE_CASE(Illegal, "Privileged instruction");
+      break;
 
     case STATUS_NO_MEMORY:
     default:
       cp->ExitException = kwsysProcess_Exception_Other;
-      _snprintf(cp->ExitExceptionString, KWSYSPE_PIPE_BUFFER_SIZE, "Exit code 0x%x\n", code);
+      _snprintf(cp->ExitExceptionString, KWSYSPE_PIPE_BUFFER_SIZE,
+                "Exit code 0x%x\n", code);
       break;
-    }
+  }
 }
 #undef KWSYSPE_CASE
 
@@ -2338,21 +2156,21 @@ typedef struct _SYSTEM_PROCESS_INFORMATION SYSTEM_PROCESS_INFORMATION;
 typedef SYSTEM_PROCESS_INFORMATION* PSYSTEM_PROCESS_INFORMATION;
 struct _SYSTEM_PROCESS_INFORMATION
 {
-  ULONG          NextEntryDelta;
-  ULONG          ThreadCount;
-  ULONG          Reserved1[6];
-  LARGE_INTEGER  CreateTime;
-  LARGE_INTEGER  UserTime;
-  LARGE_INTEGER  KernelTime;
+  ULONG NextEntryDelta;
+  ULONG ThreadCount;
+  ULONG Reserved1[6];
+  LARGE_INTEGER CreateTime;
+  LARGE_INTEGER UserTime;
+  LARGE_INTEGER KernelTime;
   UNICODE_STRING ProcessName;
-  KPRIORITY      BasePriority;
-  ULONG          ProcessId;
-  ULONG          InheritedFromProcessId;
+  KPRIORITY BasePriority;
+  ULONG ProcessId;
+  ULONG InheritedFromProcessId;
 };
 
 /*--------------------------------------------------------------------------*/
 /* Toolhelp32 API definitions.  */
-#define TH32CS_SNAPPROCESS  0x00000002
+#define TH32CS_SNAPPROCESS 0x00000002
 #if defined(_WIN64)
 typedef unsigned __int64 ProcessULONG_PTR;
 #else
@@ -2369,19 +2187,18 @@ struct tagPROCESSENTRY32
   DWORD th32ModuleID;
   DWORD cntThreads;
   DWORD th32ParentProcessID;
-  LONG  pcPriClassBase;
+  LONG pcPriClassBase;
   DWORD dwFlags;
   char szExeFile[MAX_PATH];
 };
 
 /*--------------------------------------------------------------------------*/
 /* Windows API function types.  */
-typedef HANDLE (WINAPI* CreateToolhelp32SnapshotType)(DWORD, DWORD);
-typedef BOOL (WINAPI* Process32FirstType)(HANDLE, LPPROCESSENTRY32);
-typedef BOOL (WINAPI* Process32NextType)(HANDLE, LPPROCESSENTRY32);
-typedef NTSTATUS (WINAPI* ZwQuerySystemInformationType)(ULONG, PVOID,
-                                                        ULONG, PULONG);
-
+typedef HANDLE(WINAPI* CreateToolhelp32SnapshotType)(DWORD, DWORD);
+typedef BOOL(WINAPI* Process32FirstType)(HANDLE, LPPROCESSENTRY32);
+typedef BOOL(WINAPI* Process32NextType)(HANDLE, LPPROCESSENTRY32);
+typedef NTSTATUS(WINAPI* ZwQuerySystemInformationType)(ULONG, PVOID, ULONG,
+                                                       PULONG);
 
 /*--------------------------------------------------------------------------*/
 static int kwsysProcess_List__New_NT4(kwsysProcess_List* self);
@@ -2423,97 +2240,88 @@ static kwsysProcess_List* kwsysProcess_List_New(void)
   kwsysProcess_List* self;
 
   /* Allocate and initialize the list object.  */
-  if(!(self = (kwsysProcess_List*)malloc(sizeof(kwsysProcess_List))))
-    {
+  if (!(self = (kwsysProcess_List*)malloc(sizeof(kwsysProcess_List)))) {
     return 0;
-    }
+  }
   memset(self, 0, sizeof(*self));
 
   /* Select an implementation.  */
   ZeroMemory(&osv, sizeof(osv));
   osv.dwOSVersionInfoSize = sizeof(osv);
 #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (push)
-# ifdef __INTEL_COMPILER
-#  pragma warning (disable:1478)
-# else
-#  pragma warning (disable:4996)
-# endif
+#pragma warning(push)
+#ifdef __INTEL_COMPILER
+#pragma warning(disable : 1478)
+#else
+#pragma warning(disable : 4996)
+#endif
 #endif
   GetVersionEx(&osv);
 #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (pop)
+#pragma warning(pop)
 #endif
-  self->NT4 = (osv.dwPlatformId == VER_PLATFORM_WIN32_NT &&
-               osv.dwMajorVersion < 5)? 1:0;
+  self->NT4 =
+    (osv.dwPlatformId == VER_PLATFORM_WIN32_NT && osv.dwMajorVersion < 5) ? 1
+                                                                          : 0;
 
   /* Initialize the selected implementation.  */
-  if(!(self->NT4?
-       kwsysProcess_List__New_NT4(self) :
-       kwsysProcess_List__New_Snapshot(self)))
-    {
+  if (!(self->NT4 ? kwsysProcess_List__New_NT4(self)
+                  : kwsysProcess_List__New_Snapshot(self))) {
     kwsysProcess_List_Delete(self);
     return 0;
-    }
+  }
 
   /* Update to the current set of processes.  */
-  if(!kwsysProcess_List_Update(self))
-    {
+  if (!kwsysProcess_List_Update(self)) {
     kwsysProcess_List_Delete(self);
     return 0;
-    }
+  }
   return self;
 }
 
 /*--------------------------------------------------------------------------*/
 static void kwsysProcess_List_Delete(kwsysProcess_List* self)
 {
-  if(self)
-    {
-    if(self->NT4)
-      {
+  if (self) {
+    if (self->NT4) {
       kwsysProcess_List__Delete_NT4(self);
-      }
-    else
-      {
+    } else {
       kwsysProcess_List__Delete_Snapshot(self);
-      }
-    free(self);
     }
+    free(self);
+  }
 }
 
 /*--------------------------------------------------------------------------*/
 static int kwsysProcess_List_Update(kwsysProcess_List* self)
 {
-  return self? (self->NT4?
-                kwsysProcess_List__Update_NT4(self) :
-                kwsysProcess_List__Update_Snapshot(self)) : 0;
+  return self ? (self->NT4 ? kwsysProcess_List__Update_NT4(self)
+                           : kwsysProcess_List__Update_Snapshot(self))
+              : 0;
 }
 
 /*--------------------------------------------------------------------------*/
 static int kwsysProcess_List_GetCurrentProcessId(kwsysProcess_List* self)
 {
-  return self? (self->NT4?
-                kwsysProcess_List__GetProcessId_NT4(self) :
-                kwsysProcess_List__GetProcessId_Snapshot(self)) : -1;
-
+  return self ? (self->NT4 ? kwsysProcess_List__GetProcessId_NT4(self)
+                           : kwsysProcess_List__GetProcessId_Snapshot(self))
+              : -1;
 }
 
 /*--------------------------------------------------------------------------*/
 static int kwsysProcess_List_GetCurrentParentId(kwsysProcess_List* self)
 {
-  return self? (self->NT4?
-                kwsysProcess_List__GetParentId_NT4(self) :
-                kwsysProcess_List__GetParentId_Snapshot(self)) : -1;
-
+  return self ? (self->NT4 ? kwsysProcess_List__GetParentId_NT4(self)
+                           : kwsysProcess_List__GetParentId_Snapshot(self))
+              : -1;
 }
 
 /*--------------------------------------------------------------------------*/
 static int kwsysProcess_List_NextProcess(kwsysProcess_List* self)
 {
-  return (self? (self->NT4?
-                 kwsysProcess_List__Next_NT4(self) :
-                 kwsysProcess_List__Next_Snapshot(self)) : 0);
+  return (self ? (self->NT4 ? kwsysProcess_List__Next_NT4(self)
+                            : kwsysProcess_List__Next_Snapshot(self))
+               : 0);
 }
 
 /*--------------------------------------------------------------------------*/
@@ -2524,100 +2332,85 @@ static int kwsysProcess_List__New_NT4(kwsysProcess_List* self)
      reference count to the module so we do not need to close the
      handle.  */
   HMODULE hNT = GetModuleHandleW(L"ntdll.dll");
-  if(hNT)
-    {
+  if (hNT) {
     /* Get pointers to the needed API functions.  */
     self->P_ZwQuerySystemInformation =
-      ((ZwQuerySystemInformationType)
-       GetProcAddress(hNT, "ZwQuerySystemInformation"));
-    }
-  if(!self->P_ZwQuerySystemInformation)
-    {
+      ((ZwQuerySystemInformationType)GetProcAddress(
+        hNT, "ZwQuerySystemInformation"));
+  }
+  if (!self->P_ZwQuerySystemInformation) {
     return 0;
-    }
+  }
 
   /* Allocate an initial process information buffer.  */
   self->BufferSize = 32768;
   self->Buffer = (char*)malloc(self->BufferSize);
-  return self->Buffer? 1:0;
+  return self->Buffer ? 1 : 0;
 }
 
 /*--------------------------------------------------------------------------*/
 static void kwsysProcess_List__Delete_NT4(kwsysProcess_List* self)
 {
   /* Free the process information buffer.  */
-  if(self->Buffer)
-    {
+  if (self->Buffer) {
     free(self->Buffer);
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
 static int kwsysProcess_List__Update_NT4(kwsysProcess_List* self)
 {
   self->CurrentInfo = 0;
-  for(;;)
-    {
+  for (;;) {
     /* Query number 5 is for system process list.  */
     NTSTATUS status =
       self->P_ZwQuerySystemInformation(5, self->Buffer, self->BufferSize, 0);
-    if(status == STATUS_INFO_LENGTH_MISMATCH)
-      {
+    if (status == STATUS_INFO_LENGTH_MISMATCH) {
       /* The query requires a bigger buffer.  */
       int newBufferSize = self->BufferSize * 2;
       char* newBuffer = (char*)malloc(newBufferSize);
-      if(newBuffer)
-        {
+      if (newBuffer) {
         free(self->Buffer);
         self->Buffer = newBuffer;
         self->BufferSize = newBufferSize;
-        }
-      else
-        {
+      } else {
         return 0;
-        }
       }
-    else if(status >= 0)
-      {
+    } else if (status >= 0) {
       /* The query succeeded.  Initialize traversal of the process list.  */
       self->CurrentInfo = (PSYSTEM_PROCESS_INFORMATION)self->Buffer;
       return 1;
-      }
-    else
-      {
+    } else {
       /* The query failed.  */
       return 0;
-      }
     }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
 static int kwsysProcess_List__Next_NT4(kwsysProcess_List* self)
 {
-  if(self->CurrentInfo)
-    {
-    if(self->CurrentInfo->NextEntryDelta > 0)
-      {
-      self->CurrentInfo = ((PSYSTEM_PROCESS_INFORMATION)
-                              ((char*)self->CurrentInfo +
-                               self->CurrentInfo->NextEntryDelta));
+  if (self->CurrentInfo) {
+    if (self->CurrentInfo->NextEntryDelta > 0) {
+      self->CurrentInfo = ((PSYSTEM_PROCESS_INFORMATION)(
+        (char*)self->CurrentInfo + self->CurrentInfo->NextEntryDelta));
       return 1;
-      }
-    self->CurrentInfo = 0;
     }
+    self->CurrentInfo = 0;
+  }
   return 0;
 }
 
 /*--------------------------------------------------------------------------*/
 static int kwsysProcess_List__GetProcessId_NT4(kwsysProcess_List* self)
 {
-  return self->CurrentInfo? self->CurrentInfo->ProcessId : -1;
+  return self->CurrentInfo ? self->CurrentInfo->ProcessId : -1;
 }
 
 /*--------------------------------------------------------------------------*/
 static int kwsysProcess_List__GetParentId_NT4(kwsysProcess_List* self)
 {
-  return self->CurrentInfo? self->CurrentInfo->InheritedFromProcessId : -1;
+  return self->CurrentInfo ? self->CurrentInfo->InheritedFromProcessId : -1;
 }
 
 /*--------------------------------------------------------------------------*/
@@ -2628,92 +2421,83 @@ static int kwsysProcess_List__New_Snapshot(kwsysProcess_List* self)
      reference count to the module so we do not need to close the
      handle.  */
   HMODULE hKernel = GetModuleHandleW(L"kernel32.dll");
-  if(hKernel)
-    {
+  if (hKernel) {
     self->P_CreateToolhelp32Snapshot =
-      ((CreateToolhelp32SnapshotType)
-       GetProcAddress(hKernel, "CreateToolhelp32Snapshot"));
+      ((CreateToolhelp32SnapshotType)GetProcAddress(
+        hKernel, "CreateToolhelp32Snapshot"));
     self->P_Process32First =
-      ((Process32FirstType)
-       GetProcAddress(hKernel, "Process32First"));
+      ((Process32FirstType)GetProcAddress(hKernel, "Process32First"));
     self->P_Process32Next =
-      ((Process32NextType)
-       GetProcAddress(hKernel, "Process32Next"));
-    }
-  return (self->P_CreateToolhelp32Snapshot &&
-          self->P_Process32First &&
-          self->P_Process32Next)? 1:0;
+      ((Process32NextType)GetProcAddress(hKernel, "Process32Next"));
+  }
+  return (self->P_CreateToolhelp32Snapshot && self->P_Process32First &&
+          self->P_Process32Next)
+    ? 1
+    : 0;
 }
 
 /*--------------------------------------------------------------------------*/
 static void kwsysProcess_List__Delete_Snapshot(kwsysProcess_List* self)
 {
-  if(self->Snapshot)
-    {
+  if (self->Snapshot) {
     CloseHandle(self->Snapshot);
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
 static int kwsysProcess_List__Update_Snapshot(kwsysProcess_List* self)
 {
-  if(self->Snapshot)
-    {
+  if (self->Snapshot) {
     CloseHandle(self->Snapshot);
-    }
-  if(!(self->Snapshot =
-       self->P_CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)))
-    {
+  }
+  if (!(self->Snapshot =
+          self->P_CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0))) {
     return 0;
-    }
+  }
   ZeroMemory(&self->CurrentEntry, sizeof(self->CurrentEntry));
   self->CurrentEntry.dwSize = sizeof(self->CurrentEntry);
-  if(!self->P_Process32First(self->Snapshot, &self->CurrentEntry))
-    {
+  if (!self->P_Process32First(self->Snapshot, &self->CurrentEntry)) {
     CloseHandle(self->Snapshot);
     self->Snapshot = 0;
     return 0;
-    }
+  }
   return 1;
 }
 
 /*--------------------------------------------------------------------------*/
 static int kwsysProcess_List__Next_Snapshot(kwsysProcess_List* self)
 {
-  if(self->Snapshot)
-    {
-    if(self->P_Process32Next(self->Snapshot, &self->CurrentEntry))
-      {
+  if (self->Snapshot) {
+    if (self->P_Process32Next(self->Snapshot, &self->CurrentEntry)) {
       return 1;
-      }
+    }
     CloseHandle(self->Snapshot);
     self->Snapshot = 0;
-    }
+  }
   return 0;
 }
 
 /*--------------------------------------------------------------------------*/
 static int kwsysProcess_List__GetProcessId_Snapshot(kwsysProcess_List* self)
 {
-  return self->Snapshot? self->CurrentEntry.th32ProcessID : -1;
+  return self->Snapshot ? self->CurrentEntry.th32ProcessID : -1;
 }
 
 /*--------------------------------------------------------------------------*/
 static int kwsysProcess_List__GetParentId_Snapshot(kwsysProcess_List* self)
 {
-  return self->Snapshot? self->CurrentEntry.th32ParentProcessID : -1;
+  return self->Snapshot ? self->CurrentEntry.th32ParentProcessID : -1;
 }
 
 /*--------------------------------------------------------------------------*/
 static void kwsysProcessKill(DWORD pid)
 {
   HANDLE h = OpenProcess(PROCESS_TERMINATE, 0, pid);
-  if(h)
-    {
+  if (h) {
     TerminateProcess(h, 255);
     WaitForSingleObject(h, INFINITE);
     CloseHandle(h);
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -2721,18 +2505,15 @@ static void kwsysProcessKillTree(int pid)
 {
   kwsysProcess_List* plist = kwsysProcess_List_New();
   kwsysProcessKill(pid);
-  if(plist)
-    {
-    do
-      {
-      if(kwsysProcess_List_GetCurrentParentId(plist) == pid)
-        {
+  if (plist) {
+    do {
+      if (kwsysProcess_List_GetCurrentParentId(plist) == pid) {
         int ppid = kwsysProcess_List_GetCurrentProcessId(plist);
         kwsysProcessKillTree(ppid);
-        }
-      } while(kwsysProcess_List_NextProcess(plist));
+      }
+    } while (kwsysProcess_List_NextProcess(plist));
     kwsysProcess_List_Delete(plist);
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -2741,16 +2522,14 @@ static void kwsysProcessDisablePipeThreads(kwsysProcess* cp)
   int i;
 
   /* If data were just reported data, release the pipe's thread.  */
-  if(cp->CurrentIndex < KWSYSPE_PIPE_COUNT)
-    {
+  if (cp->CurrentIndex < KWSYSPE_PIPE_COUNT) {
     KWSYSPE_DEBUG((stderr, "releasing reader %d\n", cp->CurrentIndex));
     ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Reader.Go, 1, 0);
     cp->CurrentIndex = KWSYSPE_PIPE_COUNT;
-    }
+  }
 
   /* Wakeup all reading threads that are not on closed pipes.  */
-  for(i=0; i < KWSYSPE_PIPE_COUNT; ++i)
-    {
+  for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
     /* The wakeup threads will write one byte to the pipe write ends.
        If there are no data in the pipe then this is enough to wakeup
        the reading threads.  If there are already data in the pipe
@@ -2762,16 +2541,14 @@ static void kwsysProcessDisablePipeThreads(kwsysProcess* cp)
        thread to call WriteFile.  If it blocks, that is okay because
        it will unblock when we close the read end and break the pipe
        below.  */
-    if(cp->Pipe[i].Read)
-      {
+    if (cp->Pipe[i].Read) {
       KWSYSPE_DEBUG((stderr, "releasing waker %d\n", i));
       ReleaseSemaphore(cp->Pipe[i].Waker.Go, 1, 0);
-      }
     }
+  }
 
   /* Tell pipe threads to reset until we run another process.  */
-  while(cp->PipesLeft > 0)
-    {
+  while (cp->PipesLeft > 0) {
     /* The waking threads will cause all reading threads to report.
        Wait for the next one and save its index.  */
     KWSYSPE_DEBUG((stderr, "waiting for reader\n"));
@@ -2788,7 +2565,7 @@ static void kwsysProcessDisablePipeThreads(kwsysProcess* cp)
     /* Tell the reading thread we are done with the data.  It will
        reset immediately because the pipe is closed.  */
     ReleaseSemaphore(cp->Pipe[cp->CurrentIndex].Reader.Go, 1, 0);
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -2827,18 +2604,16 @@ static kwsysProcessInstances kwsysProcesses;
 static int kwsysProcessesInitialize(void)
 {
   /* Initialize everything if not done already.  */
-  if(!kwsysProcesses.Initialized)
-    {
+  if (!kwsysProcesses.Initialized) {
     InitializeCriticalSection(&kwsysProcesses.Lock);
 
     /* Set up console ctrl handler.  */
-    if(!SetConsoleCtrlHandler(kwsysCtrlHandler, TRUE))
-      {
+    if (!SetConsoleCtrlHandler(kwsysCtrlHandler, TRUE)) {
       return 0;
-      }
+    }
 
     kwsysProcesses.Initialized = 1;
-    }
+  }
   return 1;
 }
 
@@ -2853,15 +2628,12 @@ static int kwsysTryEnterCreateProcessSection(void)
      handler are mutually exclusive.  */
   EnterCriticalSection(&kwsysProcesses.Lock);
   /* Indicate to the caller if they can create a process.  */
-  if(kwsysProcesses.Exiting)
-    {
+  if (kwsysProcesses.Exiting) {
     LeaveCriticalSection(&kwsysProcesses.Lock);
     return 0;
-    }
-  else
-    {
+  } else {
     return 1;
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -2880,41 +2652,35 @@ static void kwsysLeaveCreateProcessSection(void)
 static int kwsysProcessesAdd(HANDLE hProcess, DWORD dwProcessid,
                              int newProcessGroup)
 {
-  if(!kwsysProcessesInitialize() || !hProcess ||
-      hProcess == INVALID_HANDLE_VALUE)
-    {
+  if (!kwsysProcessesInitialize() || !hProcess ||
+      hProcess == INVALID_HANDLE_VALUE) {
     return 0;
-    }
+  }
 
   /* Enter the critical section. */
   EnterCriticalSection(&kwsysProcesses.Lock);
 
   /* Make sure there is enough space for the new process handle.  */
-  if(kwsysProcesses.Count == kwsysProcesses.Size)
-    {
+  if (kwsysProcesses.Count == kwsysProcesses.Size) {
     size_t newSize;
-    kwsysProcessInstance *newArray;
+    kwsysProcessInstance* newArray;
     /* Start with enough space for a small number of process handles
        and double the size each time more is needed.  */
-    newSize = kwsysProcesses.Size? kwsysProcesses.Size*2 : 4;
+    newSize = kwsysProcesses.Size ? kwsysProcesses.Size * 2 : 4;
 
     /* Try allocating the new block of memory.  */
-    if(newArray = (kwsysProcessInstance*)malloc(
-       newSize*sizeof(kwsysProcessInstance)))
-      {
+    if (newArray = (kwsysProcessInstance*)malloc(
+          newSize * sizeof(kwsysProcessInstance))) {
       /* Copy the old process handles to the new memory.  */
-      if(kwsysProcesses.Count > 0)
-        {
+      if (kwsysProcesses.Count > 0) {
         memcpy(newArray, kwsysProcesses.Processes,
                kwsysProcesses.Count * sizeof(kwsysProcessInstance));
-        }
       }
-    else
-      {
+    } else {
       /* Failed to allocate memory for the new process handle set.  */
       LeaveCriticalSection(&kwsysProcesses.Lock);
       return 0;
-      }
+    }
 
     /* Free original array. */
     free(kwsysProcesses.Processes);
@@ -2922,7 +2688,7 @@ static int kwsysProcessesAdd(HANDLE hProcess, DWORD dwProcessid,
     /* Update original structure with new allocation. */
     kwsysProcesses.Size = newSize;
     kwsysProcesses.Processes = newArray;
-    }
+  }
 
   /* Append the new process information to the set.  */
   kwsysProcesses.Processes[kwsysProcesses.Count].hProcess = hProcess;
@@ -2942,38 +2708,32 @@ static void kwsysProcessesRemove(HANDLE hProcess)
 {
   size_t i;
 
-  if (!hProcess || hProcess == INVALID_HANDLE_VALUE)
-    {
+  if (!hProcess || hProcess == INVALID_HANDLE_VALUE) {
     return;
-    }
+  }
 
   EnterCriticalSection(&kwsysProcesses.Lock);
 
   /* Find the given process in the set.  */
-  for(i=0; i < kwsysProcesses.Count; ++i)
-    {
-    if(kwsysProcesses.Processes[i].hProcess == hProcess)
-      {
+  for (i = 0; i < kwsysProcesses.Count; ++i) {
+    if (kwsysProcesses.Processes[i].hProcess == hProcess) {
       break;
-      }
     }
-  if(i < kwsysProcesses.Count)
-    {
+  }
+  if (i < kwsysProcesses.Count) {
     /* Found it!  Remove the process from the set.  */
     --kwsysProcesses.Count;
-    for(; i < kwsysProcesses.Count; ++i)
-      {
-      kwsysProcesses.Processes[i] = kwsysProcesses.Processes[i+1];
-      }
+    for (; i < kwsysProcesses.Count; ++i) {
+      kwsysProcesses.Processes[i] = kwsysProcesses.Processes[i + 1];
+    }
 
     /* If this was the last process, free the array.  */
-    if(kwsysProcesses.Count == 0)
-      {
+    if (kwsysProcesses.Count == 0) {
       kwsysProcesses.Size = 0;
       free(kwsysProcesses.Processes);
       kwsysProcesses.Processes = 0;
-      }
     }
+  }
 
   LeaveCriticalSection(&kwsysProcesses.Lock);
 }
@@ -2991,25 +2751,21 @@ static BOOL WINAPI kwsysCtrlHandler(DWORD dwCtrlType)
 
   /* If some of our processes were created in a new process group, we must
      manually interrupt them.  They won't otherwise receive a Ctrl+C/Break. */
-  for(i=0; i < kwsysProcesses.Count; ++i)
-    {
-    if(kwsysProcesses.Processes[i].NewProcessGroup)
-      {
+  for (i = 0; i < kwsysProcesses.Count; ++i) {
+    if (kwsysProcesses.Processes[i].NewProcessGroup) {
       DWORD groupId = kwsysProcesses.Processes[i].dwProcessId;
-      if(groupId)
-        {
+      if (groupId) {
         GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, groupId);
-        }
       }
     }
+  }
 
   /* Wait for each child process to exit.  This is the key step that prevents
      us from leaving several orphaned children processes running in the
      background when the user presses Ctrl+C.  */
-  for(i=0; i < kwsysProcesses.Count; ++i)
-    {
+  for (i = 0; i < kwsysProcesses.Count; ++i) {
     WaitForSingleObject(kwsysProcesses.Processes[i].hProcess, INFINITE);
-    }
+  }
 
   /* Leave critical section.  */
   LeaveCriticalSection(&kwsysProcesses.Lock);
@@ -3021,10 +2777,9 @@ static BOOL WINAPI kwsysCtrlHandler(DWORD dwCtrlType)
 /*--------------------------------------------------------------------------*/
 void kwsysProcess_ResetStartTime(kwsysProcess* cp)
 {
-  if(!cp)
-    {
+  if (!cp) {
     return;
-    }
+  }
   /* Reset start time. */
   cp->StartTime = kwsysProcessTimeGetCurrent();
 }
diff --git a/Source/kwsys/README.rst b/Source/kwsys/README.rst
new file mode 100644
index 0000000..fc6b590
--- /dev/null
+++ b/Source/kwsys/README.rst
@@ -0,0 +1,37 @@
+KWSys
+*****
+
+Introduction
+============
+
+KWSys is the Kitware System Library.  It provides platform-independent
+APIs to many common system features that are implemented differently on
+every platform.  This library is intended to be shared among many
+projects at the source level, so it has a configurable namespace.
+Each project should configure KWSys to use a namespace unique to itself.
+See comments in `CMakeLists.txt`_ for details.
+
+.. _`CMakeLists.txt`: CMakeLists.txt
+
+License
+=======
+
+KWSys is distributed under the OSI-approved BSD 3-clause License.
+See `Copyright.txt`_ for details.
+
+.. _`Copyright.txt`: Copyright.txt
+
+Reporting Bugs
+==============
+
+KWSys has no independent issue tracker.  After encountering an issue
+(bug) please submit a patch using the instructions for `Contributing`_.
+Otherwise please report the issue to the tracker for the project that
+hosts the copy of KWSys in which the problem was found.
+
+Contributing
+============
+
+See `CONTRIBUTING.rst`_ for instructions to contribute.
+
+.. _`CONTRIBUTING.rst`: CONTRIBUTING.rst
diff --git a/Source/kwsys/README.txt b/Source/kwsys/README.txt
deleted file mode 100644
index b8191f7..0000000
--- a/Source/kwsys/README.txt
+++ /dev/null
@@ -1,12 +0,0 @@
-KWSys provides a platform-independent API to many common system
-features that are implemented differently on every platform.  This
-library is intended to be shared among many projects, so it has a
-configurable namespace.  Each project should configure KWSys to use a
-namespace unique to itself.  See comments in CMakeLists.txt for
-details.
-
-You are probably reading this file in the source tree of a surrounding
-project.  In that case, see "../README.kwsys" for details of using
-KWSys in your project.
-
-See CONTRIBUTING.rst for instructions to contribute KWSys changes.
diff --git a/Source/kwsys/RegularExpression.cxx b/Source/kwsys/RegularExpression.cxx
index 22593b4..6d7f832 100644
--- a/Source/kwsys/RegularExpression.cxx
+++ b/Source/kwsys/RegularExpression.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 //
 // Copyright (C) 1991 Texas Instruments Incorporated.
 //
@@ -34,30 +25,29 @@
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "RegularExpression.hxx.in"
+#include "RegularExpression.hxx.in"
 #endif
 
 #include <stdio.h>
 #include <string.h>
 
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
 
 // RegularExpression -- Copies the given regular expression.
-RegularExpression::RegularExpression (const RegularExpression& rxp) {
-  if ( !rxp.program )
-    {
+RegularExpression::RegularExpression(const RegularExpression& rxp)
+{
+  if (!rxp.program) {
     this->program = 0;
     return;
-    }
+  }
   int ind;
-  this->progsize = rxp.progsize;                // Copy regular expression size
-  this->program = new char[this->progsize];     // Allocate storage
-  for(ind=this->progsize; ind-- != 0;)          // Copy regular expresion
+  this->progsize = rxp.progsize;            // Copy regular expression size
+  this->program = new char[this->progsize]; // Allocate storage
+  for (ind = this->progsize; ind-- != 0;)   // Copy regular expresion
     this->program[ind] = rxp.program[ind];
-  this->startp[0] = rxp.startp[0];              // Copy pointers into last
-  this->endp[0] = rxp.endp[0];                  // Successful "find" operation
-  this->regmust = rxp.regmust;                  // Copy field
+  this->startp[0] = rxp.startp[0]; // Copy pointers into last
+  this->endp[0] = rxp.endp[0];     // Successful "find" operation
+  this->regmust = rxp.regmust;     // Copy field
   if (rxp.regmust != 0) {
     char* dum = rxp.program;
     ind = 0;
@@ -67,32 +57,30 @@ RegularExpression::RegularExpression (const RegularExpression& rxp) {
     }
     this->regmust = this->program + ind;
   }
-  this->regstart = rxp.regstart;                // Copy starting index
-  this->reganch = rxp.reganch;                  // Copy remaining private data
-  this->regmlen = rxp.regmlen;                  // Copy remaining private data
+  this->regstart = rxp.regstart; // Copy starting index
+  this->reganch = rxp.reganch;   // Copy remaining private data
+  this->regmlen = rxp.regmlen;   // Copy remaining private data
 }
 
 // operator= -- Copies the given regular expression.
-RegularExpression& RegularExpression::operator= (const RegularExpression& rxp)
+RegularExpression& RegularExpression::operator=(const RegularExpression& rxp)
 {
-  if(this == &rxp)
-    {
+  if (this == &rxp) {
     return *this;
-    }
-  if ( !rxp.program )
-    {
+  }
+  if (!rxp.program) {
     this->program = 0;
     return *this;
-    }
+  }
   int ind;
-  this->progsize = rxp.progsize;                // Copy regular expression size
-  delete [] this->program;
-  this->program = new char[this->progsize];     // Allocate storage
-  for(ind=this->progsize; ind-- != 0;)          // Copy regular expresion
+  this->progsize = rxp.progsize; // Copy regular expression size
+  delete[] this->program;
+  this->program = new char[this->progsize]; // Allocate storage
+  for (ind = this->progsize; ind-- != 0;)   // Copy regular expresion
     this->program[ind] = rxp.program[ind];
-  this->startp[0] = rxp.startp[0];              // Copy pointers into last
-  this->endp[0] = rxp.endp[0];                  // Successful "find" operation
-  this->regmust = rxp.regmust;                  // Copy field
+  this->startp[0] = rxp.startp[0]; // Copy pointers into last
+  this->endp[0] = rxp.endp[0];     // Successful "find" operation
+  this->regmust = rxp.regmust;     // Copy field
   if (rxp.regmust != 0) {
     char* dum = rxp.program;
     ind = 0;
@@ -102,37 +90,38 @@ RegularExpression& RegularExpression::operator= (const RegularExpression& rxp)
     }
     this->regmust = this->program + ind;
   }
-  this->regstart = rxp.regstart;                // Copy starting index
-  this->reganch = rxp.reganch;                  // Copy remaining private data
-  this->regmlen = rxp.regmlen;                  // Copy remaining private data
+  this->regstart = rxp.regstart; // Copy starting index
+  this->reganch = rxp.reganch;   // Copy remaining private data
+  this->regmlen = rxp.regmlen;   // Copy remaining private data
 
   return *this;
 }
 
 // operator== -- Returns true if two regular expressions have the same
 // compiled program for pattern matching.
-bool RegularExpression::operator== (const RegularExpression& rxp) const {
-  if (this != &rxp) {                           // Same address?
-    int ind = this->progsize;                   // Get regular expression size
-    if (ind != rxp.progsize)                    // If different size regexp
-      return false;                             // Return failure
-    while(ind-- != 0)                           // Else while still characters
-      if(this->program[ind] != rxp.program[ind]) // If regexp are different
-        return false;                            // Return failure
+bool RegularExpression::operator==(const RegularExpression& rxp) const
+{
+  if (this != &rxp) {         // Same address?
+    int ind = this->progsize; // Get regular expression size
+    if (ind != rxp.progsize)  // If different size regexp
+      return false;           // Return failure
+    while (ind-- != 0)        // Else while still characters
+      if (this->program[ind] != rxp.program[ind]) // If regexp are different
+        return false;                             // Return failure
   }
-  return true;                                  // Else same, return success
+  return true; // Else same, return success
 }
 
-
 // deep_equal -- Returns true if have the same compiled regular expressions
 // and the same start and end pointers.
 
-bool RegularExpression::deep_equal (const RegularExpression& rxp) const {
+bool RegularExpression::deep_equal(const RegularExpression& rxp) const
+{
   int ind = this->progsize;                     // Get regular expression size
   if (ind != rxp.progsize)                      // If different size regexp
     return false;                               // Return failure
-  while(ind-- != 0)                             // Else while still characters
-    if(this->program[ind] != rxp.program[ind])  // If regexp are different
+  while (ind-- != 0)                            // Else while still characters
+    if (this->program[ind] != rxp.program[ind]) // If regexp are different
       return false;                             // Return failure
   return (this->startp[0] == rxp.startp[0] &&   // Else if same start/end ptrs,
           this->endp[0] == rxp.endp[0]);        // Return true
@@ -204,26 +193,26 @@ bool RegularExpression::deep_equal (const RegularExpression& rxp) const {
  */
 
 // definition   number  opnd?   meaning
-#define END     0               // no   End of program.
-#define BOL     1               // no   Match "" at beginning of line.
-#define EOL     2               // no   Match "" at end of line.
-#define ANY     3               // no   Match any one character.
-#define ANYOF   4               // str  Match any character in this string.
-#define ANYBUT  5               // str  Match any character not in this
-                                // string.
-#define BRANCH  6               // node Match this alternative, or the
-                                // next...
-#define BACK    7               // no   Match "", "next" ptr points backward.
-#define EXACTLY 8               // str  Match this string.
-#define NOTHING 9               // no   Match empty string.
-#define STAR    10              // node Match this (simple) thing 0 or more
-                                // times.
-#define PLUS    11              // node Match this (simple) thing 1 or more
-                                // times.
-#define OPEN    20              // no   Mark this point in input as start of
-                                // #n.
+#define END 0     // no   End of program.
+#define BOL 1     // no   Match "" at beginning of line.
+#define EOL 2     // no   Match "" at end of line.
+#define ANY 3     // no   Match any one character.
+#define ANYOF 4   // str  Match any character in this string.
+#define ANYBUT 5  // str  Match any character not in this
+                  // string.
+#define BRANCH 6  // node Match this alternative, or the
+                  // next...
+#define BACK 7    // no   Match "", "next" ptr points backward.
+#define EXACTLY 8 // str  Match this string.
+#define NOTHING 9 // no   Match empty string.
+#define STAR 10   // node Match this (simple) thing 0 or more
+                  // times.
+#define PLUS 11   // node Match this (simple) thing 1 or more
+                  // times.
+#define OPEN 20   // no   Mark this point in input as start of
+                  // #n.
 // OPEN+1 is number 1, etc.
-#define CLOSE   30              // no   Analogous to OPEN.
+#define CLOSE 30 // no   Analogous to OPEN.
 
 /*
  * Opcode notes:
@@ -258,32 +247,32 @@ bool RegularExpression::deep_equal (const RegularExpression& rxp) const {
  * but allows patterns to get big without disasters.
  */
 
-#define OP(p)           (*(p))
-#define NEXT(p)         (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
-#define OPERAND(p)      ((p) + 3)
+#define OP(p) (*(p))
+#define NEXT(p) (((*((p) + 1) & 0377) << 8) + (*((p) + 2) & 0377))
+#define OPERAND(p) ((p) + 3)
 
 const unsigned char MAGIC = 0234;
 /*
  * Utility definitions.
  */
 
-#define UCHARAT(p)      (reinterpret_cast<const unsigned char*>(p))[0]
-
-
-#define FAIL(m) { regerror(m); return(0); }
-#define ISMULT(c)       ((c) == '*' || (c) == '+' || (c) == '?')
-#define META    "^$.[()|?+*\\"
+#define UCHARAT(p) (reinterpret_cast<const unsigned char*>(p))[0]
 
+#define FAIL(m)                                                               \
+  {                                                                           \
+    regerror(m);                                                              \
+    return (0);                                                               \
+  }
+#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
+#define META "^$.[()|?+*\\"
 
 /*
  * Flags to be passed up and down.
  */
-#define HASWIDTH        01      // Known never to match null string.
-#define SIMPLE          02      // Simple enough to be STAR/PLUS operand.
-#define SPSTART         04      // Starts with * or +.
-#define WORST           0       // Worst case.
-
-
+#define HASWIDTH 01 // Known never to match null string.
+#define SIMPLE 02   // Simple enough to be STAR/PLUS operand.
+#define SPSTART 04  // Starts with * or +.
+#define WORST 0     // Worst case.
 
 /////////////////////////////////////////////////////////////////////////
 //
@@ -291,15 +280,14 @@ const unsigned char MAGIC = 0234;
 //
 /////////////////////////////////////////////////////////////////////////
 
-
 /*
  * Global work variables for compile().
  */
-static const char* regparse;    // Input-scan pointer.
-static       int   regnpar;     // () count.
-static       char  regdummy;
-static       char* regcode;     // Code-emit pointer; &regdummy = don't.
-static       long  regsize;     // Code size.
+static const char* regparse; // Input-scan pointer.
+static int regnpar;          // () count.
+static char regdummy;
+static char* regcode; // Code-emit pointer; &regdummy = don't.
+static long regsize;  // Code size.
 
 /*
  * Forward declarations for compile()'s friends.
@@ -307,24 +295,22 @@ static       long  regsize;     // Code size.
 // #ifndef static
 // #define      static  static
 // #endif
-static       char* reg (int, int*);
-static       char* regbranch (int*);
-static       char* regpiece (int*);
-static       char* regatom (int*);
-static       char* regnode (char);
-static const char* regnext (const char*);
-static       char* regnext (char*);
-static void        regc (char);
-static void        reginsert (char, char*);
-static void        regtail (char*, const char*);
-static void        regoptail (char*, const char*);
+static char* reg(int, int*);
+static char* regbranch(int*);
+static char* regpiece(int*);
+static char* regatom(int*);
+static char* regnode(char);
+static const char* regnext(const char*);
+static char* regnext(char*);
+static void regc(char);
+static void reginsert(char, char*);
+static void regtail(char*, const char*);
+static void regoptail(char*, const char*);
 
 #ifdef STRCSPN
-static int strcspn ();
+static int strcspn();
 #endif
 
-
-
 /*
  * We can't allocate space until we know how big the compiled form will be,
  * but we can't compile it (and thus know how big it is) until we've got a
@@ -339,101 +325,100 @@ static int strcspn ();
  * of the structure of the compiled regexp.
  */
 
-
 // compile -- compile a regular expression into internal code
 // for later pattern matching.
 
-bool RegularExpression::compile (const char* exp) {
-    const char* scan;
-    const char* longest;
-    size_t      len;
-    int         flags;
+bool RegularExpression::compile(const char* exp)
+{
+  const char* scan;
+  const char* longest;
+  size_t len;
+  int flags;
+
+  if (exp == 0) {
+    // RAISE Error, SYM(RegularExpression), SYM(No_Expr),
+    printf("RegularExpression::compile(): No expression supplied.\n");
+    return false;
+  }
 
-    if (exp == 0) {
-      //RAISE Error, SYM(RegularExpression), SYM(No_Expr),
-      printf ("RegularExpression::compile(): No expression supplied.\n");
-      return false;
-    }
+  // First pass: determine size, legality.
+  regparse = exp;
+  regnpar = 1;
+  regsize = 0L;
+  regcode = ®dummy;
+  regc(static_cast<char>(MAGIC));
+  if (!reg(0, &flags)) {
+    printf("RegularExpression::compile(): Error in compile.\n");
+    return false;
+  }
+  this->startp[0] = this->endp[0] = this->searchstring = 0;
 
-    // First pass: determine size, legality.
-    regparse = exp;
-    regnpar = 1;
-    regsize = 0L;
-    regcode = ®dummy;
-    regc(static_cast<char>(MAGIC));
-    if(!reg(0, &flags))
-      {
-        printf ("RegularExpression::compile(): Error in compile.\n");
-        return false;
-      }
-    this->startp[0] = this->endp[0] = this->searchstring = 0;
+  // Small enough for pointer-storage convention?
+  if (regsize >= 32767L) { // Probably could be 65535L.
+    // RAISE Error, SYM(RegularExpression), SYM(Expr_Too_Big),
+    printf("RegularExpression::compile(): Expression too big.\n");
+    return false;
+  }
 
-    // Small enough for pointer-storage convention?
-    if (regsize >= 32767L) {    // Probably could be 65535L.
-      //RAISE Error, SYM(RegularExpression), SYM(Expr_Too_Big),
-      printf ("RegularExpression::compile(): Expression too big.\n");
-      return false;
-    }
+  // Allocate space.
+  //#ifndef _WIN32
+  if (this->program != 0)
+    delete[] this->program;
+  //#endif
+  this->program = new char[regsize];
+  this->progsize = static_cast<int>(regsize);
+
+  if (this->program == 0) {
+    // RAISE Error, SYM(RegularExpression), SYM(Out_Of_Memory),
+    printf("RegularExpression::compile(): Out of memory.\n");
+    return false;
+  }
 
-    // Allocate space.
-//#ifndef _WIN32
-    if (this->program != 0) delete [] this->program;
-//#endif
-    this->program = new char[regsize];
-    this->progsize = static_cast<int>(regsize);
-
-    if (this->program == 0) {
-      //RAISE Error, SYM(RegularExpression), SYM(Out_Of_Memory),
-      printf ("RegularExpression::compile(): Out of memory.\n");
-      return false;
-    }
+  // Second pass: emit code.
+  regparse = exp;
+  regnpar = 1;
+  regcode = this->program;
+  regc(static_cast<char>(MAGIC));
+  reg(0, &flags);
+
+  // Dig out information for optimizations.
+  this->regstart = '\0'; // Worst-case defaults.
+  this->reganch = 0;
+  this->regmust = 0;
+  this->regmlen = 0;
+  scan = this->program + 1;       // First BRANCH.
+  if (OP(regnext(scan)) == END) { // Only one top-level choice.
+    scan = OPERAND(scan);
+
+    // Starting-point info.
+    if (OP(scan) == EXACTLY)
+      this->regstart = *OPERAND(scan);
+    else if (OP(scan) == BOL)
+      this->reganch++;
 
-    // Second pass: emit code.
-    regparse = exp;
-    regnpar = 1;
-    regcode = this->program;
-    regc(static_cast<char>(MAGIC));
-    reg(0, &flags);
-
-    // Dig out information for optimizations.
-    this->regstart = '\0';              // Worst-case defaults.
-    this->reganch = 0;
-    this->regmust = 0;
-    this->regmlen = 0;
-    scan = this->program + 1;   // First BRANCH.
-    if (OP(regnext(scan)) == END) {     // Only one top-level choice.
-        scan = OPERAND(scan);
-
-        // Starting-point info.
-        if (OP(scan) == EXACTLY)
-            this->regstart = *OPERAND(scan);
-        else if (OP(scan) == BOL)
-            this->reganch++;
-
-         //
-         // If there's something expensive in the r.e., find the longest
-         // literal string that must appear and make it the regmust.  Resolve
-         // ties in favor of later strings, since the regstart check works
-         // with the beginning of the r.e. and avoiding duplication
-         // strengthens checking.  Not a strong reason, but sufficient in the
-         // absence of others.
-         //
-        if (flags & SPSTART) {
-            longest = 0;
-            len = 0;
-            for (; scan != 0; scan = regnext(scan))
-                if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
-                    longest = OPERAND(scan);
-                    len = strlen(OPERAND(scan));
-                }
-            this->regmust = longest;
-            this->regmlen = len;
+    //
+    // If there's something expensive in the r.e., find the longest
+    // literal string that must appear and make it the regmust.  Resolve
+    // ties in favor of later strings, since the regstart check works
+    // with the beginning of the r.e. and avoiding duplication
+    // strengthens checking.  Not a strong reason, but sufficient in the
+    // absence of others.
+    //
+    if (flags & SPSTART) {
+      longest = 0;
+      len = 0;
+      for (; scan != 0; scan = regnext(scan))
+        if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
+          longest = OPERAND(scan);
+          len = strlen(OPERAND(scan));
         }
+      this->regmust = longest;
+      this->regmlen = len;
     }
-    return true;
+  }
+  return true;
 }
 
-
 /*
  - reg - regular expression, i.e. main body or parenthesized thing
  *
@@ -443,115 +428,112 @@ bool RegularExpression::compile (const char* exp) {
  * is a trifle forced, but the need to tie the tails of the branches to what
  * follows makes it hard to avoid.
  */
-static char* reg (int paren, int *flagp) {
-    char* ret;
-    char* br;
-    char* ender;
-    int   parno =0;
-    int   flags;
-
-    *flagp = HASWIDTH;          // Tentatively.
-
-    // Make an OPEN node, if parenthesized.
-    if (paren) {
-        if (regnpar >=  RegularExpression::NSUBEXP) {
-          //RAISE Error, SYM(RegularExpression), SYM(Too_Many_Parens),
-          printf ("RegularExpression::compile(): Too many parentheses.\n");
-          return 0;
-        }
-        parno = regnpar;
-        regnpar++;
-        ret = regnode(static_cast<char>(OPEN + parno));
+static char* reg(int paren, int* flagp)
+{
+  char* ret;
+  char* br;
+  char* ender;
+  int parno = 0;
+  int flags;
+
+  *flagp = HASWIDTH; // Tentatively.
+
+  // Make an OPEN node, if parenthesized.
+  if (paren) {
+    if (regnpar >= RegularExpression::NSUBEXP) {
+      // RAISE Error, SYM(RegularExpression), SYM(Too_Many_Parens),
+      printf("RegularExpression::compile(): Too many parentheses.\n");
+      return 0;
     }
-    else
-        ret = 0;
-
-    // Pick up the branches, linking them together.
+    parno = regnpar;
+    regnpar++;
+    ret = regnode(static_cast<char>(OPEN + parno));
+  } else
+    ret = 0;
+
+  // Pick up the branches, linking them together.
+  br = regbranch(&flags);
+  if (br == 0)
+    return (0);
+  if (ret != 0)
+    regtail(ret, br); // OPEN -> first.
+  else
+    ret = br;
+  if (!(flags & HASWIDTH))
+    *flagp &= ~HASWIDTH;
+  *flagp |= flags & SPSTART;
+  while (*regparse == '|') {
+    regparse++;
     br = regbranch(&flags);
     if (br == 0)
-        return (0);
-    if (ret != 0)
-        regtail(ret, br);       // OPEN -> first.
-    else
-        ret = br;
+      return (0);
+    regtail(ret, br); // BRANCH -> BRANCH.
     if (!(flags & HASWIDTH))
-        *flagp &= ~HASWIDTH;
+      *flagp &= ~HASWIDTH;
     *flagp |= flags & SPSTART;
-    while (*regparse == '|') {
-        regparse++;
-        br = regbranch(&flags);
-        if (br == 0)
-            return (0);
-        regtail(ret, br);       // BRANCH -> BRANCH.
-        if (!(flags & HASWIDTH))
-            *flagp &= ~HASWIDTH;
-        *flagp |= flags & SPSTART;
-      }
-
-    // Make a closing node, and hook it on the end.
-    ender = regnode(static_cast<char>((paren) ? CLOSE + parno : END));
-    regtail(ret, ender);
-
-    // Hook the tails of the branches to the closing node.
-    for (br = ret; br != 0; br = regnext(br))
-        regoptail(br, ender);
+  }
 
-    // Check for proper termination.
-    if (paren && *regparse++ != ')') {
-        //RAISE Error, SYM(RegularExpression), SYM(Unmatched_Parens),
-        printf ("RegularExpression::compile(): Unmatched parentheses.\n");
-        return 0;
-    }
-    else if (!paren && *regparse != '\0') {
-        if (*regparse == ')') {
-            //RAISE Error, SYM(RegularExpression), SYM(Unmatched_Parens),
-            printf ("RegularExpression::compile(): Unmatched parentheses.\n");
-            return 0;
-        }
-        else {
-            //RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
-            printf ("RegularExpression::compile(): Internal error.\n");
-            return 0;
-        }
-        // NOTREACHED
+  // Make a closing node, and hook it on the end.
+  ender = regnode(static_cast<char>((paren) ? CLOSE + parno : END));
+  regtail(ret, ender);
+
+  // Hook the tails of the branches to the closing node.
+  for (br = ret; br != 0; br = regnext(br))
+    regoptail(br, ender);
+
+  // Check for proper termination.
+  if (paren && *regparse++ != ')') {
+    // RAISE Error, SYM(RegularExpression), SYM(Unmatched_Parens),
+    printf("RegularExpression::compile(): Unmatched parentheses.\n");
+    return 0;
+  } else if (!paren && *regparse != '\0') {
+    if (*regparse == ')') {
+      // RAISE Error, SYM(RegularExpression), SYM(Unmatched_Parens),
+      printf("RegularExpression::compile(): Unmatched parentheses.\n");
+      return 0;
+    } else {
+      // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
+      printf("RegularExpression::compile(): Internal error.\n");
+      return 0;
     }
-    return (ret);
+    // NOTREACHED
+  }
+  return (ret);
 }
 
-
 /*
  - regbranch - one alternative of an | operator
  *
  * Implements the concatenation operator.
  */
-static char* regbranch (int *flagp) {
-    char* ret;
-    char* chain;
-    char* latest;
-    int   flags;
-
-    *flagp = WORST;             // Tentatively.
-
-    ret = regnode(BRANCH);
-    chain = 0;
-    while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
-        latest = regpiece(&flags);
-        if (latest == 0)
-            return (0);
-        *flagp |= flags & HASWIDTH;
-        if (chain == 0) // First piece.
-            *flagp |= flags & SPSTART;
-        else
-            regtail(chain, latest);
-        chain = latest;
-    }
-    if (chain == 0)             // Loop ran zero times.
-        regnode(NOTHING);
+static char* regbranch(int* flagp)
+{
+  char* ret;
+  char* chain;
+  char* latest;
+  int flags;
+
+  *flagp = WORST; // Tentatively.
+
+  ret = regnode(BRANCH);
+  chain = 0;
+  while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
+    latest = regpiece(&flags);
+    if (latest == 0)
+      return (0);
+    *flagp |= flags & HASWIDTH;
+    if (chain == 0) // First piece.
+      *flagp |= flags & SPSTART;
+    else
+      regtail(chain, latest);
+    chain = latest;
+  }
+  if (chain == 0) // Loop ran zero times.
+    regnode(NOTHING);
 
-    return (ret);
+  return (ret);
 }
 
-
 /*
  - regpiece - something followed by possible [*+?]
  *
@@ -561,66 +543,64 @@ static char* regbranch (int *flagp) {
  * It might seem that this node could be dispensed with entirely, but the
  * endmarker role is not redundant.
  */
-static char* regpiece (int *flagp) {
-    char* ret;
-    char  op;
-    char* next;
-    int   flags;
-
-    ret = regatom(&flags);
-    if (ret == 0)
-        return (0);
+static char* regpiece(int* flagp)
+{
+  char* ret;
+  char op;
+  char* next;
+  int flags;
 
-    op = *regparse;
-    if (!ISMULT(op)) {
-        *flagp = flags;
-        return (ret);
-    }
+  ret = regatom(&flags);
+  if (ret == 0)
+    return (0);
 
-    if (!(flags & HASWIDTH) && op != '?') {
-        //RAISE Error, SYM(RegularExpression), SYM(Empty_Operand),
-        printf ("RegularExpression::compile() : *+ operand could be empty.\n");
-        return 0;
-    }
-    *flagp = (op != '+') ? (WORST | SPSTART) : (WORST | HASWIDTH);
-
-    if (op == '*' && (flags & SIMPLE))
-        reginsert(STAR, ret);
-    else if (op == '*') {
-        // Emit x* as (x&|), where & means "self".
-        reginsert(BRANCH, ret); // Either x
-        regoptail(ret, regnode(BACK));  // and loop
-        regoptail(ret, ret);    // back
-        regtail(ret, regnode(BRANCH));  // or
-        regtail(ret, regnode(NOTHING)); // null.
-    }
-    else if (op == '+' && (flags & SIMPLE))
-        reginsert(PLUS, ret);
-    else if (op == '+') {
-        // Emit x+ as x(&|), where & means "self".
-        next = regnode(BRANCH); // Either
-        regtail(ret, next);
-        regtail(regnode(BACK), ret);    // loop back
-        regtail(next, regnode(BRANCH)); // or
-        regtail(ret, regnode(NOTHING)); // null.
-    }
-    else if (op == '?') {
-        // Emit x? as (x|)
-        reginsert(BRANCH, ret); // Either x
-        regtail(ret, regnode(BRANCH));  // or
-        next = regnode(NOTHING);// null.
-        regtail(ret, next);
-        regoptail(ret, next);
-    }
-    regparse++;
-    if (ISMULT(*regparse)) {
-        //RAISE Error, SYM(RegularExpression), SYM(Nested_Operand),
-        printf ("RegularExpression::compile(): Nested *?+.\n");
-        return 0;
-    }
+  op = *regparse;
+  if (!ISMULT(op)) {
+    *flagp = flags;
     return (ret);
-}
+  }
 
+  if (!(flags & HASWIDTH) && op != '?') {
+    // RAISE Error, SYM(RegularExpression), SYM(Empty_Operand),
+    printf("RegularExpression::compile() : *+ operand could be empty.\n");
+    return 0;
+  }
+  *flagp = (op != '+') ? (WORST | SPSTART) : (WORST | HASWIDTH);
+
+  if (op == '*' && (flags & SIMPLE))
+    reginsert(STAR, ret);
+  else if (op == '*') {
+    // Emit x* as (x&|), where & means "self".
+    reginsert(BRANCH, ret);         // Either x
+    regoptail(ret, regnode(BACK));  // and loop
+    regoptail(ret, ret);            // back
+    regtail(ret, regnode(BRANCH));  // or
+    regtail(ret, regnode(NOTHING)); // null.
+  } else if (op == '+' && (flags & SIMPLE))
+    reginsert(PLUS, ret);
+  else if (op == '+') {
+    // Emit x+ as x(&|), where & means "self".
+    next = regnode(BRANCH); // Either
+    regtail(ret, next);
+    regtail(regnode(BACK), ret);    // loop back
+    regtail(next, regnode(BRANCH)); // or
+    regtail(ret, regnode(NOTHING)); // null.
+  } else if (op == '?') {
+    // Emit x? as (x|)
+    reginsert(BRANCH, ret);        // Either x
+    regtail(ret, regnode(BRANCH)); // or
+    next = regnode(NOTHING);       // null.
+    regtail(ret, next);
+    regoptail(ret, next);
+  }
+  regparse++;
+  if (ISMULT(*regparse)) {
+    // RAISE Error, SYM(RegularExpression), SYM(Nested_Operand),
+    printf("RegularExpression::compile(): Nested *?+.\n");
+    return 0;
+  }
+  return (ret);
+}
 
 /*
  - regatom - the lowest level
@@ -630,349 +610,340 @@ static char* regpiece (int *flagp) {
  * faster to run.  Backslashed characters are exceptions, each becoming a
  * separate node; the code is simpler that way and it's not worth fixing.
  */
-static char* regatom (int *flagp) {
-    char* ret;
-    int   flags;
-
-    *flagp = WORST;             // Tentatively.
-
-    switch (*regparse++) {
-        case '^':
-            ret = regnode(BOL);
-            break;
-        case '$':
-            ret = regnode(EOL);
-            break;
-        case '.':
-            ret = regnode(ANY);
-            *flagp |= HASWIDTH | SIMPLE;
-            break;
-        case '[':{
-                int    rxpclass;
-                int    rxpclassend;
-
-                if (*regparse == '^') { // Complement of range.
-                    ret = regnode(ANYBUT);
-                    regparse++;
-                }
-                else
-                    ret = regnode(ANYOF);
-                if (*regparse == ']' || *regparse == '-')
-                    regc(*regparse++);
-                while (*regparse != '\0' && *regparse != ']') {
-                    if (*regparse == '-') {
-                        regparse++;
-                        if (*regparse == ']' || *regparse == '\0')
-                            regc('-');
-                        else {
-                            rxpclass = UCHARAT(regparse - 2) + 1;
-                            rxpclassend = UCHARAT(regparse);
-                            if (rxpclass > rxpclassend + 1) {
-                               //RAISE Error, SYM(RegularExpression), SYM(Invalid_Range),
-                               printf ("RegularExpression::compile(): Invalid range in [].\n");
-                               return 0;
-                            }
-                            for (; rxpclass <= rxpclassend; rxpclass++)
-                              regc(static_cast<char>(rxpclass));
-                            regparse++;
-                        }
-                    }
-                    else
-                        regc(*regparse++);
-                }
-                regc('\0');
-                if (*regparse != ']') {
-                    //RAISE Error, SYM(RegularExpression), SYM(Unmatched_Bracket),
-                    printf ("RegularExpression::compile(): Unmatched [].\n");
-                    return 0;
-                }
-                regparse++;
-                *flagp |= HASWIDTH | SIMPLE;
-            }
-            break;
-        case '(':
-            ret = reg(1, &flags);
-            if (ret == 0)
-                return (0);
-            *flagp |= flags & (HASWIDTH | SPSTART);
-            break;
-        case '\0':
-        case '|':
-        case ')':
-            //RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
-            printf ("RegularExpression::compile(): Internal error.\n"); // Never here
-            return 0;
-        case '?':
-        case '+':
-        case '*':
-            //RAISE Error, SYM(RegularExpression), SYM(No_Operand),
-            printf ("RegularExpression::compile(): ?+* follows nothing.\n");
-            return 0;
-        case '\\':
-            if (*regparse == '\0') {
-                //RAISE Error, SYM(RegularExpression), SYM(Trailing_Backslash),
-                printf ("RegularExpression::compile(): Trailing backslash.\n");
-                return 0;
-            }
-            ret = regnode(EXACTLY);
-            regc(*regparse++);
-            regc('\0');
-            *flagp |= HASWIDTH | SIMPLE;
-            break;
-        default:{
-                int    len;
-                char   ender;
-
-                regparse--;
-                len = int(strcspn(regparse, META));
-                if (len <= 0) {
-                    //RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
-                    printf ("RegularExpression::compile(): Internal error.\n");
-                    return 0;
-                }
-                ender = *(regparse + len);
-                if (len > 1 && ISMULT(ender))
-                    len--;      // Back off clear of ?+* operand.
-                *flagp |= HASWIDTH;
-                if (len == 1)
-                    *flagp |= SIMPLE;
-                ret = regnode(EXACTLY);
-                while (len > 0) {
-                    regc(*regparse++);
-                    len--;
-                }
-                regc('\0');
+static char* regatom(int* flagp)
+{
+  char* ret;
+  int flags;
+
+  *flagp = WORST; // Tentatively.
+
+  switch (*regparse++) {
+    case '^':
+      ret = regnode(BOL);
+      break;
+    case '$':
+      ret = regnode(EOL);
+      break;
+    case '.':
+      ret = regnode(ANY);
+      *flagp |= HASWIDTH | SIMPLE;
+      break;
+    case '[': {
+      int rxpclass;
+      int rxpclassend;
+
+      if (*regparse == '^') { // Complement of range.
+        ret = regnode(ANYBUT);
+        regparse++;
+      } else
+        ret = regnode(ANYOF);
+      if (*regparse == ']' || *regparse == '-')
+        regc(*regparse++);
+      while (*regparse != '\0' && *regparse != ']') {
+        if (*regparse == '-') {
+          regparse++;
+          if (*regparse == ']' || *regparse == '\0')
+            regc('-');
+          else {
+            rxpclass = UCHARAT(regparse - 2) + 1;
+            rxpclassend = UCHARAT(regparse);
+            if (rxpclass > rxpclassend + 1) {
+              // RAISE Error, SYM(RegularExpression), SYM(Invalid_Range),
+              printf("RegularExpression::compile(): Invalid range in [].\n");
+              return 0;
             }
-            break;
-    }
-    return (ret);
+            for (; rxpclass <= rxpclassend; rxpclass++)
+              regc(static_cast<char>(rxpclass));
+            regparse++;
+          }
+        } else
+          regc(*regparse++);
+      }
+      regc('\0');
+      if (*regparse != ']') {
+        // RAISE Error, SYM(RegularExpression), SYM(Unmatched_Bracket),
+        printf("RegularExpression::compile(): Unmatched [].\n");
+        return 0;
+      }
+      regparse++;
+      *flagp |= HASWIDTH | SIMPLE;
+    } break;
+    case '(':
+      ret = reg(1, &flags);
+      if (ret == 0)
+        return (0);
+      *flagp |= flags & (HASWIDTH | SPSTART);
+      break;
+    case '\0':
+    case '|':
+    case ')':
+      // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
+      printf("RegularExpression::compile(): Internal error.\n"); // Never here
+      return 0;
+    case '?':
+    case '+':
+    case '*':
+      // RAISE Error, SYM(RegularExpression), SYM(No_Operand),
+      printf("RegularExpression::compile(): ?+* follows nothing.\n");
+      return 0;
+    case '\\':
+      if (*regparse == '\0') {
+        // RAISE Error, SYM(RegularExpression), SYM(Trailing_Backslash),
+        printf("RegularExpression::compile(): Trailing backslash.\n");
+        return 0;
+      }
+      ret = regnode(EXACTLY);
+      regc(*regparse++);
+      regc('\0');
+      *flagp |= HASWIDTH | SIMPLE;
+      break;
+    default: {
+      int len;
+      char ender;
+
+      regparse--;
+      len = int(strcspn(regparse, META));
+      if (len <= 0) {
+        // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
+        printf("RegularExpression::compile(): Internal error.\n");
+        return 0;
+      }
+      ender = *(regparse + len);
+      if (len > 1 && ISMULT(ender))
+        len--; // Back off clear of ?+* operand.
+      *flagp |= HASWIDTH;
+      if (len == 1)
+        *flagp |= SIMPLE;
+      ret = regnode(EXACTLY);
+      while (len > 0) {
+        regc(*regparse++);
+        len--;
+      }
+      regc('\0');
+    } break;
+  }
+  return (ret);
 }
 
-
 /*
  - regnode - emit a node
    Location.
  */
-static char* regnode (char op) {
-    char* ret;
-    char* ptr;
-
-    ret = regcode;
-    if (ret == &regdummy) {
-        regsize += 3;
-        return (ret);
-    }
-
-    ptr = ret;
-    *ptr++ = op;
-    *ptr++ = '\0';              // Null "next" pointer.
-    *ptr++ = '\0';
-    regcode = ptr;
+static char* regnode(char op)
+{
+  char* ret;
+  char* ptr;
 
+  ret = regcode;
+  if (ret == &regdummy) {
+    regsize += 3;
     return (ret);
-}
+  }
 
+  ptr = ret;
+  *ptr++ = op;
+  *ptr++ = '\0'; // Null "next" pointer.
+  *ptr++ = '\0';
+  regcode = ptr;
+
+  return (ret);
+}
 
 /*
  - regc - emit (if appropriate) a byte of code
  */
-static void regc (char b) {
-    if (regcode != &regdummy)
-        *regcode++ = b;
-    else
-        regsize++;
+static void regc(char b)
+{
+  if (regcode != &regdummy)
+    *regcode++ = b;
+  else
+    regsize++;
 }
 
-
 /*
  - reginsert - insert an operator in front of already-emitted operand
  *
  * Means relocating the operand.
  */
-static void reginsert (char op, char* opnd) {
-    char* src;
-    char* dst;
-    char* place;
-
-    if (regcode == &regdummy) {
-        regsize += 3;
-        return;
-    }
+static void reginsert(char op, char* opnd)
+{
+  char* src;
+  char* dst;
+  char* place;
+
+  if (regcode == &regdummy) {
+    regsize += 3;
+    return;
+  }
 
-    src = regcode;
-    regcode += 3;
-    dst = regcode;
-    while (src > opnd)
-        *--dst = *--src;
+  src = regcode;
+  regcode += 3;
+  dst = regcode;
+  while (src > opnd)
+    *--dst = *--src;
 
-    place = opnd;               // Op node, where operand used to be.
-    *place++ = op;
-    *place++ = '\0';
-    *place = '\0';
+  place = opnd; // Op node, where operand used to be.
+  *place++ = op;
+  *place++ = '\0';
+  *place = '\0';
 }
 
-
 /*
  - regtail - set the next-pointer at the end of a node chain
  */
-static void regtail (char* p, const char* val) {
-    char* scan;
-    char* temp;
-    int   offset;
-
-    if (p == &regdummy)
-        return;
-
-    // Find last node.
-    scan = p;
-    for (;;) {
-        temp = regnext(scan);
-        if (temp == 0)
-            break;
-        scan = temp;
-    }
+static void regtail(char* p, const char* val)
+{
+  char* scan;
+  char* temp;
+  int offset;
 
-    if (OP(scan) == BACK)
-        offset = int(scan - val);
-    else
-        offset = int(val - scan);
-    *(scan + 1) = static_cast<char>((offset >> 8) & 0377);
-    *(scan + 2) = static_cast<char>(offset & 0377);
-}
+  if (p == &regdummy)
+    return;
+
+  // Find last node.
+  scan = p;
+  for (;;) {
+    temp = regnext(scan);
+    if (temp == 0)
+      break;
+    scan = temp;
+  }
 
+  if (OP(scan) == BACK)
+    offset = int(scan - val);
+  else
+    offset = int(val - scan);
+  *(scan + 1) = static_cast<char>((offset >> 8) & 0377);
+  *(scan + 2) = static_cast<char>(offset & 0377);
+}
 
 /*
  - regoptail - regtail on operand of first argument; nop if operandless
  */
-static void regoptail (char* p, const char* val) {
-    // "Operandless" and "op != BRANCH" are synonymous in practice.
-    if (p == 0 || p == &regdummy || OP(p) != BRANCH)
-        return;
-    regtail(OPERAND(p), val);
+static void regoptail(char* p, const char* val)
+{
+  // "Operandless" and "op != BRANCH" are synonymous in practice.
+  if (p == 0 || p == &regdummy || OP(p) != BRANCH)
+    return;
+  regtail(OPERAND(p), val);
 }
 
-
-
 ////////////////////////////////////////////////////////////////////////
-// 
+//
 //  find and friends
-// 
+//
 ////////////////////////////////////////////////////////////////////////
 
-
 /*
  * Global work variables for find().
  */
-static const char*  reginput;   // String-input pointer.
-static const char*  regbol;     // Beginning of input, for ^ check.
-static const char* *regstartp;  // Pointer to startp array.
-static const char* *regendp;    // Ditto for endp.
+static const char* reginput;   // String-input pointer.
+static const char* regbol;     // Beginning of input, for ^ check.
+static const char** regstartp; // Pointer to startp array.
+static const char** regendp;   // Ditto for endp.
 
 /*
  * Forwards.
  */
-static int regtry (const char*, const char* *,
-                   const char* *, const char*);
-static int regmatch (const char*);
-static int regrepeat (const char*);
+static int regtry(const char*, const char**, const char**, const char*);
+static int regmatch(const char*);
+static int regrepeat(const char*);
 
 #ifdef DEBUG
-int          regnarrate = 0;
-void         regdump ();
-static char* regprop ();
+int regnarrate = 0;
+void regdump();
+static char* regprop();
 #endif
 
 // find -- Matches the regular expression to the given string.
 // Returns true if found, and sets start and end indexes accordingly.
 
-bool RegularExpression::find (const char* string) {
-    const char* s;
+bool RegularExpression::find(const char* string)
+{
+  const char* s;
 
-    this->searchstring = string;
+  this->searchstring = string;
 
-    if (!this->program)
-      {
-      return false;
-      }
+  if (!this->program) {
+    return false;
+  }
 
-    // Check validity of program.
-    if (UCHARAT(this->program) != MAGIC) {
-        //RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
-        printf ("RegularExpression::find(): Compiled regular expression corrupted.\n");
-        return 0;
-    }
+  // Check validity of program.
+  if (UCHARAT(this->program) != MAGIC) {
+    // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
+    printf(
+      "RegularExpression::find(): Compiled regular expression corrupted.\n");
+    return 0;
+  }
 
-    // If there is a "must appear" string, look for it.
-    if (this->regmust != 0) {
-        s = string;
-        while ((s = strchr(s, this->regmust[0])) != 0) {
-            if (strncmp(s, this->regmust, this->regmlen) == 0)
-                break;          // Found it.
-            s++;
-        }
-        if (s == 0)             // Not present.
-            return (0);
+  // If there is a "must appear" string, look for it.
+  if (this->regmust != 0) {
+    s = string;
+    while ((s = strchr(s, this->regmust[0])) != 0) {
+      if (strncmp(s, this->regmust, this->regmlen) == 0)
+        break; // Found it.
+      s++;
     }
+    if (s == 0) // Not present.
+      return (0);
+  }
 
-    // Mark beginning of line for ^ .
-    regbol = string;
-
-    // Simplest case:  anchored match need be tried only once.
-    if (this->reganch)
-        return (regtry(string, this->startp, this->endp, this->program) != 0);
+  // Mark beginning of line for ^ .
+  regbol = string;
 
-    // Messy cases:  unanchored match.
-    s = string;
-    if (this->regstart != '\0')
-        // We know what char it must start with.
-        while ((s = strchr(s, this->regstart)) != 0) {
-            if (regtry(s, this->startp, this->endp, this->program))
-                return (1);
-            s++;
+  // Simplest case:  anchored match need be tried only once.
+  if (this->reganch)
+    return (regtry(string, this->startp, this->endp, this->program) != 0);
 
-        }
-    else
-        // We don't -- general case.
-        do {
-            if (regtry(s, this->startp, this->endp, this->program))
-                return (1);
-        } while (*s++ != '\0');
+  // Messy cases:  unanchored match.
+  s = string;
+  if (this->regstart != '\0')
+    // We know what char it must start with.
+    while ((s = strchr(s, this->regstart)) != 0) {
+      if (regtry(s, this->startp, this->endp, this->program))
+        return (1);
+      s++;
+    }
+  else
+    // We don't -- general case.
+    do {
+      if (regtry(s, this->startp, this->endp, this->program))
+        return (1);
+    } while (*s++ != '\0');
 
-    // Failure.
-    return (0);
+  // Failure.
+  return (0);
 }
 
-
 /*
  - regtry - try match at specific point
    0 failure, 1 success
  */
-static int regtry (const char* string, const char* *start,
-                   const char* *end, const char* prog) {
-                   int    i;
-                   const char* *sp1;
-                   const char* *ep;
-
-    reginput = string;
-    regstartp = start;
-    regendp = end;
-
-    sp1 = start;
-    ep = end;
-    for (i = RegularExpression::NSUBEXP; i > 0; i--) {
-        *sp1++ = 0;
-        *ep++ = 0;
-    }
-    if (regmatch(prog + 1)) {
-        start[0] = string;
-        end[0] = reginput;
-        return (1);
-    }
-    else
-        return (0);
+static int regtry(const char* string, const char** start, const char** end,
+                  const char* prog)
+{
+  int i;
+  const char** sp1;
+  const char** ep;
+
+  reginput = string;
+  regstartp = start;
+  regendp = end;
+
+  sp1 = start;
+  ep = end;
+  for (i = RegularExpression::NSUBEXP; i > 0; i--) {
+    *sp1++ = 0;
+    *ep++ = 0;
+  }
+  if (regmatch(prog + 1)) {
+    start[0] = string;
+    end[0] = reginput;
+    return (1);
+  } else
+    return (0);
 }
 
-
 /*
  - regmatch - main matching routine
  *
@@ -984,261 +955,260 @@ static int regtry (const char* string, const char* *start,
  * by recursion.
  * 0 failure, 1 success
  */
-static int regmatch (const char* prog) {
-    const char* scan;  // Current node.
-    const char* next;  // Next node.
-
-    scan = prog;
-
-    while (scan != 0) {
-
-        next = regnext(scan);
-
-        switch (OP(scan)) {
-            case BOL:
-                if (reginput != regbol)
-                    return (0);
-                break;
-            case EOL:
-                if (*reginput != '\0')
-                    return (0);
-                break;
-            case ANY:
-                if (*reginput == '\0')
-                    return (0);
-                reginput++;
-                break;
-            case EXACTLY:{
-                    size_t len;
-                    const char* opnd;
-
-                    opnd = OPERAND(scan);
-                    // Inline the first character, for speed.
-                    if (*opnd != *reginput)
-                        return (0);
-                    len = strlen(opnd);
-                    if (len > 1 && strncmp(opnd, reginput, len) != 0)
-                        return (0);
-                    reginput += len;
-                }
-                break;
-            case ANYOF:
-                if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == 0)
-                    return (0);
-                reginput++;
-                break;
-            case ANYBUT:
-                if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != 0)
-                    return (0);
-                reginput++;
-                break;
-            case NOTHING:
-                break;
-            case BACK:
-                break;
-            case OPEN + 1:
-            case OPEN + 2:
-            case OPEN + 3:
-            case OPEN + 4:
-            case OPEN + 5:
-            case OPEN + 6:
-            case OPEN + 7:
-            case OPEN + 8:
-            case OPEN + 9:{
-                    int    no;
-                    const char* save;
-
-                    no = OP(scan) - OPEN;
-                    save = reginput;
-
-                    if (regmatch(next)) {
-
-                        //
-                        // Don't set startp if some later invocation of the
-                        // same parentheses already has.
-                        //
-                        if (regstartp[no] == 0)
-                            regstartp[no] = save;
-                        return (1);
-                    }
-                    else
-                        return (0);
-                }
-//              break;
-            case CLOSE + 1:
-            case CLOSE + 2:
-            case CLOSE + 3:
-            case CLOSE + 4:
-            case CLOSE + 5:
-            case CLOSE + 6:
-            case CLOSE + 7:
-            case CLOSE + 8:
-            case CLOSE + 9:{
-                    int    no;
-                    const char* save;
-
-                    no = OP(scan) - CLOSE;
-                    save = reginput;
-
-                    if (regmatch(next)) {
-
-                        //
-                        // Don't set endp if some later invocation of the
-                        // same parentheses already has.
-                        //
-                        if (regendp[no] == 0)
-                            regendp[no] = save;
-                        return (1);
-                    }
-                    else
-                        return (0);
-                }
-//              break;
-            case BRANCH:{
-
-              const char* save;
-
-                    if (OP(next) != BRANCH)     // No choice.
-                        next = OPERAND(scan);   // Avoid recursion.
-                    else {
-                        do {
-                            save = reginput;
-                            if (regmatch(OPERAND(scan)))
-                                return (1);
-                            reginput = save;
-                            scan = regnext(scan);
-                        } while (scan != 0 && OP(scan) == BRANCH);
-                        return (0);
-                        // NOTREACHED
-                    }
-                }
-                break;
-            case STAR:
-            case PLUS:{
-                    char   nextch;
-                    int        no;
-                    const char* save;
-                    int        min_no;
-
-                    //
-                    // Lookahead to avoid useless match attempts when we know
-                    // what character comes next.
-                    //
-                    nextch = '\0';
-                    if (OP(next) == EXACTLY)
-                        nextch = *OPERAND(next);
-                    min_no = (OP(scan) == STAR) ? 0 : 1;
-                    save = reginput;
-                    no = regrepeat(OPERAND(scan));
-                    while (no >= min_no) {
-                        // If it could work, try it.
-                        if (nextch == '\0' || *reginput == nextch)
-                            if (regmatch(next))
-                                return (1);
-                        // Couldn't or didn't -- back up.
-                        no--;
-                        reginput = save + no;
-                    }
-                    return (0);
-                }
-//              break;
-            case END:
-                return (1);     // Success!
-
-            default:
-                //RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
-                printf ("RegularExpression::find(): Internal error -- memory corrupted.\n");
-                return 0;
+static int regmatch(const char* prog)
+{
+  const char* scan; // Current node.
+  const char* next; // Next node.
+
+  scan = prog;
+
+  while (scan != 0) {
+
+    next = regnext(scan);
+
+    switch (OP(scan)) {
+      case BOL:
+        if (reginput != regbol)
+          return (0);
+        break;
+      case EOL:
+        if (*reginput != '\0')
+          return (0);
+        break;
+      case ANY:
+        if (*reginput == '\0')
+          return (0);
+        reginput++;
+        break;
+      case EXACTLY: {
+        size_t len;
+        const char* opnd;
+
+        opnd = OPERAND(scan);
+        // Inline the first character, for speed.
+        if (*opnd != *reginput)
+          return (0);
+        len = strlen(opnd);
+        if (len > 1 && strncmp(opnd, reginput, len) != 0)
+          return (0);
+        reginput += len;
+      } break;
+      case ANYOF:
+        if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == 0)
+          return (0);
+        reginput++;
+        break;
+      case ANYBUT:
+        if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != 0)
+          return (0);
+        reginput++;
+        break;
+      case NOTHING:
+        break;
+      case BACK:
+        break;
+      case OPEN + 1:
+      case OPEN + 2:
+      case OPEN + 3:
+      case OPEN + 4:
+      case OPEN + 5:
+      case OPEN + 6:
+      case OPEN + 7:
+      case OPEN + 8:
+      case OPEN + 9: {
+        int no;
+        const char* save;
+
+        no = OP(scan) - OPEN;
+        save = reginput;
+
+        if (regmatch(next)) {
+
+          //
+          // Don't set startp if some later invocation of the
+          // same parentheses already has.
+          //
+          if (regstartp[no] == 0)
+            regstartp[no] = save;
+          return (1);
+        } else
+          return (0);
+      }
+      //              break;
+      case CLOSE + 1:
+      case CLOSE + 2:
+      case CLOSE + 3:
+      case CLOSE + 4:
+      case CLOSE + 5:
+      case CLOSE + 6:
+      case CLOSE + 7:
+      case CLOSE + 8:
+      case CLOSE + 9: {
+        int no;
+        const char* save;
+
+        no = OP(scan) - CLOSE;
+        save = reginput;
+
+        if (regmatch(next)) {
+
+          //
+          // Don't set endp if some later invocation of the
+          // same parentheses already has.
+          //
+          if (regendp[no] == 0)
+            regendp[no] = save;
+          return (1);
+        } else
+          return (0);
+      }
+      //              break;
+      case BRANCH: {
+
+        const char* save;
+
+        if (OP(next) != BRANCH) // No choice.
+          next = OPERAND(scan); // Avoid recursion.
+        else {
+          do {
+            save = reginput;
+            if (regmatch(OPERAND(scan)))
+              return (1);
+            reginput = save;
+            scan = regnext(scan);
+          } while (scan != 0 && OP(scan) == BRANCH);
+          return (0);
+          // NOTREACHED
+        }
+      } break;
+      case STAR:
+      case PLUS: {
+        char nextch;
+        int no;
+        const char* save;
+        int min_no;
+
+        //
+        // Lookahead to avoid useless match attempts when we know
+        // what character comes next.
+        //
+        nextch = '\0';
+        if (OP(next) == EXACTLY)
+          nextch = *OPERAND(next);
+        min_no = (OP(scan) == STAR) ? 0 : 1;
+        save = reginput;
+        no = regrepeat(OPERAND(scan));
+        while (no >= min_no) {
+          // If it could work, try it.
+          if (nextch == '\0' || *reginput == nextch)
+            if (regmatch(next))
+              return (1);
+          // Couldn't or didn't -- back up.
+          no--;
+          reginput = save + no;
         }
-        scan = next;
+        return (0);
+      }
+      //              break;
+      case END:
+        return (1); // Success!
+
+      default:
+        // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
+        printf(
+          "RegularExpression::find(): Internal error -- memory corrupted.\n");
+        return 0;
     }
+    scan = next;
+  }
 
-    //
-    //  We get here only if there's trouble -- normally "case END" is the
-    //  terminating point.
-    //
-    //RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
-    printf ("RegularExpression::find(): Internal error -- corrupted pointers.\n");
-    return (0);
+  //
+  //  We get here only if there's trouble -- normally "case END" is the
+  //  terminating point.
+  //
+  // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
+  printf("RegularExpression::find(): Internal error -- corrupted pointers.\n");
+  return (0);
 }
 
-
 /*
  - regrepeat - repeatedly match something simple, report how many
  */
-static int regrepeat (const char* p) {
-    int         count = 0;
-    const char* scan;
-    const char* opnd;
-
-    scan = reginput;
-    opnd = OPERAND(p);
-    switch (OP(p)) {
-        case ANY:
-            count = int(strlen(scan));
-            scan += count;
-            break;
-        case EXACTLY:
-            while (*opnd == *scan) {
-                count++;
-                scan++;
-            }
-            break;
-        case ANYOF:
-            while (*scan != '\0' && strchr(opnd, *scan) != 0) {
-                count++;
-                scan++;
-            }
-            break;
-        case ANYBUT:
-            while (*scan != '\0' && strchr(opnd, *scan) == 0) {
-                count++;
-                scan++;
-            }
-            break;
-        default:                // Oh dear.  Called inappropriately.
-            //RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
-            printf ("cm RegularExpression::find(): Internal error.\n");
-            return 0;
-    }
-    reginput = scan;
-    return (count);
+static int regrepeat(const char* p)
+{
+  int count = 0;
+  const char* scan;
+  const char* opnd;
+
+  scan = reginput;
+  opnd = OPERAND(p);
+  switch (OP(p)) {
+    case ANY:
+      count = int(strlen(scan));
+      scan += count;
+      break;
+    case EXACTLY:
+      while (*opnd == *scan) {
+        count++;
+        scan++;
+      }
+      break;
+    case ANYOF:
+      while (*scan != '\0' && strchr(opnd, *scan) != 0) {
+        count++;
+        scan++;
+      }
+      break;
+    case ANYBUT:
+      while (*scan != '\0' && strchr(opnd, *scan) == 0) {
+        count++;
+        scan++;
+      }
+      break;
+    default: // Oh dear.  Called inappropriately.
+      // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
+      printf("cm RegularExpression::find(): Internal error.\n");
+      return 0;
+  }
+  reginput = scan;
+  return (count);
 }
 
-
 /*
  - regnext - dig the "next" pointer out of a node
  */
-static const char* regnext (const char* p) {
-    int offset;
+static const char* regnext(const char* p)
+{
+  int offset;
 
-    if (p == &regdummy)
-        return (0);
+  if (p == &regdummy)
+    return (0);
 
-    offset = NEXT(p);
-    if (offset == 0)
-        return (0);
+  offset = NEXT(p);
+  if (offset == 0)
+    return (0);
 
-    if (OP(p) == BACK)
-        return (p - offset);
-    else
-        return (p + offset);
+  if (OP(p) == BACK)
+    return (p - offset);
+  else
+    return (p + offset);
 }
 
-static char* regnext (char* p) {
-    int offset;
+static char* regnext(char* p)
+{
+  int offset;
 
-    if (p == &regdummy)
-        return (0);
+  if (p == &regdummy)
+    return (0);
 
-    offset = NEXT(p);
-    if (offset == 0)
-        return (0);
+  offset = NEXT(p);
+  if (offset == 0)
+    return (0);
 
-    if (OP(p) == BACK)
-        return (p - offset);
-    else
-        return (p + offset);
+  if (OP(p) == BACK)
+    return (p - offset);
+  else
+    return (p + offset);
 }
 
 } // namespace KWSYS_NAMESPACE
diff --git a/Source/kwsys/RegularExpression.hxx.in b/Source/kwsys/RegularExpression.hxx.in
index 0bb700f..606e3da 100644
--- a/Source/kwsys/RegularExpression.hxx.in
+++ b/Source/kwsys/RegularExpression.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 // Original Copyright notice:
 // Copyright (C) 1991 Texas Instruments Incorporated.
 //
@@ -38,11 +29,10 @@
 /* Disable useless Borland warnings.  KWSys tries not to force things
    on its includers, but there is no choice here.  */
 #if defined(__BORLANDC__)
-# pragma warn -8027 /* function not inlined.  */
+#pragma warn - 8027 /* function not inlined.  */
 #endif
 
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 
 /** \class RegularExpression
  * \brief Implements pattern matching with regular expressions.
@@ -68,10 +58,10 @@ namespace @KWSYS_NAMESPACE@
  * and utilities.
  *
  * Example: The perl code
- * 
+ *
  *    $filename =~ m"([a-z]+)\.cc";
  *    print $1;
- *    
+ *
  * Is written as follows in C++
  *
  *    RegularExpression re("([a-z]+)\\.cc");
@@ -181,28 +171,28 @@ namespace @KWSYS_NAMESPACE@
  *      the line.  It would match "drepa qrepb" in "rep drepa qrepb".
  *
  */
-class @KWSYS_NAMESPACE at _EXPORT RegularExpression 
+class @KWSYS_NAMESPACE at _EXPORT RegularExpression
 {
 public:
   /**
    * Instantiate RegularExpression with program=NULL.
    */
-  inline RegularExpression ();        
+  inline RegularExpression();
 
   /**
    * Instantiate RegularExpression with compiled char*.
    */
-  inline RegularExpression (char const*);
+  inline RegularExpression(char const*);
 
   /**
    * Instantiate RegularExpression as a copy of another regular expression.
    */
-  RegularExpression (RegularExpression const&);
+  RegularExpression(RegularExpression const&);
 
   /**
    * Instantiate RegularExpression with compiled string.
    */
-  inline RegularExpression (std::string const&);
+  inline RegularExpression(std::string const&);
 
   /**
    * Destructor.
@@ -213,25 +203,25 @@ public:
    * Compile a regular expression into internal code
    * for later pattern matching.
    */
-  bool compile (char const*);
+  bool compile(char const*);
 
   /**
    * Compile a regular expression into internal code
    * for later pattern matching.
    */
-  inline bool compile (std::string const&);
+  inline bool compile(std::string const&);
 
   /**
    * Matches the regular expression to the given string.
    * Returns true if found, and sets start and end indexes accordingly.
    */
-  bool find (char const*);
+  bool find(char const*);
 
   /**
    * Matches the regular expression to the given std string.
    * Returns true if found, and sets start and end indexes accordingly.
    */
-  inline bool find (std::string const&);
+  inline bool find(std::string const&);
 
   /**
    * Index to start of first find.
@@ -246,26 +236,26 @@ public:
   /**
    * Copy the given regular expression.
    */
-  RegularExpression& operator= (const RegularExpression& rxp);
+  RegularExpression& operator=(const RegularExpression& rxp);
 
   /**
    * Returns true if two regular expressions have the same
    * compiled program for pattern matching.
    */
-  bool operator== (RegularExpression const&) const;
+  bool operator==(RegularExpression const&) const;
 
   /**
    * Returns true if two regular expressions have different
    * compiled program for pattern matching.
    */
-  inline bool operator!= (RegularExpression const&) const;
+  inline bool operator!=(RegularExpression const&) const;
 
   /**
    * Returns true if have the same compiled regular expressions
    * and the same start and end pointers.
    */
-  bool deep_equal (RegularExpression const&) const;
-  
+  bool deep_equal(RegularExpression const&) const;
+
   /**
    * True if the compiled regexp is valid.
    */
@@ -274,7 +264,7 @@ public:
   /**
    * Marks the regular expression as invalid.
    */
-  inline void set_invalid();            
+  inline void set_invalid();
 
   /**
    * Destructor.
@@ -283,25 +273,29 @@ public:
   std::string::size_type start(int n) const;
   std::string::size_type end(int n) const;
   std::string match(int n) const;
-  
-  enum { NSUBEXP = 10 };
-private: 
+
+  enum
+  {
+    NSUBEXP = 10
+  };
+
+private:
   const char* startp[NSUBEXP];
   const char* endp[NSUBEXP];
-  char  regstart;                       // Internal use only
-  char  reganch;                        // Internal use only
-  const char* regmust;                  // Internal use only
-  std::string::size_type regmlen;                // Internal use only
-  char* program;   
-  int   progsize;
+  char regstart;                  // Internal use only
+  char reganch;                   // Internal use only
+  const char* regmust;            // Internal use only
+  std::string::size_type regmlen; // Internal use only
+  char* program;
+  int progsize;
   const char* searchstring;
 };
 
 /**
  * Create an empty regular expression.
  */
-inline RegularExpression::RegularExpression () 
-{ 
+inline RegularExpression::RegularExpression()
+{
   this->program = 0;
 }
 
@@ -309,20 +303,19 @@ inline RegularExpression::RegularExpression ()
  * Creates a regular expression from string s, and
  * compiles s.
  */
-inline RegularExpression::RegularExpression (const char* s) 
-{  
+inline RegularExpression::RegularExpression(const char* s)
+{
   this->program = 0;
-  if ( s )
-    {
+  if (s) {
     this->compile(s);
-    }
+  }
 }
 
 /**
  * Creates a regular expression from string s, and
  * compiles s.
  */
-inline RegularExpression::RegularExpression (const std::string& s)
+inline RegularExpression::RegularExpression(const std::string& s)
 {
   this->program = 0;
   this->compile(s);
@@ -331,18 +324,18 @@ inline RegularExpression::RegularExpression (const std::string& s)
 /**
  * Destroys and frees space allocated for the regular expression.
  */
-inline RegularExpression::~RegularExpression () 
+inline RegularExpression::~RegularExpression()
 {
-//#ifndef _WIN32
-  delete [] this->program;
-//#endif
+  //#ifndef _WIN32
+  delete[] this->program;
+  //#endif
 }
 
 /**
  * Compile a regular expression into internal code
  * for later pattern matching.
  */
-inline bool RegularExpression::compile (std::string const& s)
+inline bool RegularExpression::compile(std::string const& s)
 {
   return this->compile(s.c_str());
 }
@@ -351,7 +344,7 @@ inline bool RegularExpression::compile (std::string const& s)
  * Matches the regular expression to the given std string.
  * Returns true if found, and sets start and end indexes accordingly.
  */
-inline bool RegularExpression::find (std::string const& s)
+inline bool RegularExpression::find(std::string const& s)
 {
   return this->find(s.c_str());
 }
@@ -359,46 +352,42 @@ inline bool RegularExpression::find (std::string const& s)
 /**
  * Set the start position for the regular expression.
  */
-inline std::string::size_type RegularExpression::start () const
+inline std::string::size_type RegularExpression::start() const
 {
-  return static_cast<std::string::size_type>(
-    this->startp[0] - searchstring);
+  return static_cast<std::string::size_type>(this->startp[0] - searchstring);
 }
 
-
 /**
  * Returns the start/end index of the last item found.
  */
-inline std::string::size_type RegularExpression::end () const
+inline std::string::size_type RegularExpression::end() const
 {
-  return static_cast<std::string::size_type>(
-    this->endp[0] - searchstring);
+  return static_cast<std::string::size_type>(this->endp[0] - searchstring);
 }
 
 /**
  * Returns true if two regular expressions have different
  * compiled program for pattern matching.
  */
-inline bool RegularExpression::operator!= (const RegularExpression& r) const 
+inline bool RegularExpression::operator!=(const RegularExpression& r) const
 {
-  return(!(*this == r));
+  return (!(*this == r));
 }
 
 /**
  * Returns true if a valid regular expression is compiled
  * and ready for pattern matching.
  */
-inline bool RegularExpression::is_valid () const 
+inline bool RegularExpression::is_valid() const
 {
   return (this->program != 0);
 }
 
-
-inline void RegularExpression::set_invalid () 
+inline void RegularExpression::set_invalid()
 {
-//#ifndef _WIN32
-  delete [] this->program;
-//#endif
+  //#ifndef _WIN32
+  delete[] this->program;
+  //#endif
   this->program = 0;
 }
 
@@ -407,18 +396,15 @@ inline void RegularExpression::set_invalid ()
  */
 inline std::string::size_type RegularExpression::start(int n) const
 {
-  return static_cast<std::string::size_type>(
-    this->startp[n] - searchstring);
+  return static_cast<std::string::size_type>(this->startp[n] - searchstring);
 }
 
-
 /**
  * Return end index of nth submatch. end(0) is the end of the full match.
  */
 inline std::string::size_type RegularExpression::end(int n) const
 {
-  return static_cast<std::string::size_type>(
-    this->endp[n] - searchstring);
+  return static_cast<std::string::size_type>(this->endp[n] - searchstring);
 }
 
 /**
@@ -426,16 +412,12 @@ inline std::string::size_type RegularExpression::end(int n) const
  */
 inline std::string RegularExpression::match(int n) const
 {
-  if (this->startp[n]==0)
-    {
+  if (this->startp[n] == 0) {
     return std::string("");
-    }
-  else
-    {
-    return std::string(this->startp[n],
-                             static_cast<std::string::size_type>(
-                               this->endp[n] - this->startp[n]));
-    }
+  } else {
+    return std::string(this->startp[n], static_cast<std::string::size_type>(
+                                          this->endp[n] - this->startp[n]));
+  }
 }
 
 } // namespace @KWSYS_NAMESPACE@
diff --git a/Source/kwsys/SharedForward.h.in b/Source/kwsys/SharedForward.h.in
index f80ef84..c9ae135 100644
--- a/Source/kwsys/SharedForward.h.in
+++ b/Source/kwsys/SharedForward.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _SharedForward_h
 #define @KWSYS_NAMESPACE at _SharedForward_h
 
@@ -30,7 +21,8 @@
   #define @KWSYS_NAMESPACE at _SHARED_FORWARD_PATH_BUILD "." CONFIG_DIR_POST
   #define @KWSYS_NAMESPACE at _SHARED_FORWARD_PATH_INSTALL "../lib/foo-1.2"
   #define @KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_BUILD CONFIG_DIR_PRE "foo-real"
-  #define @KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_INSTALL "../lib/foo-1.2/foo-real"
+  #define @KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_INSTALL
+  "../lib/foo-1.2/foo-real"
   #define @KWSYS_NAMESPACE at _SHARED_FORWARD_OPTION_COMMAND "--command"
   #define @KWSYS_NAMESPACE at _SHARED_FORWARD_OPTION_PRINT "--print"
   #define @KWSYS_NAMESPACE at _SHARED_FORWARD_OPTION_LDD "--ldd"
@@ -68,16 +60,16 @@
 /* Disable -Wcast-qual warnings since they are too hard to fix in a
    cross-platform way.  */
 #if defined(__clang__) && defined(__has_warning)
-# if __has_warning("-Wcast-qual")
-#  pragma clang diagnostic push
-#  pragma clang diagnostic ignored "-Wcast-qual"
-# endif
+#if __has_warning("-Wcast-qual")
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wcast-qual"
+#endif
 #endif
 
 #if defined(__BORLANDC__) && !defined(__cplusplus)
-  /* Code has no effect; raised by winnt.h in C (not C++) when ignoring an
-     unused parameter using "(param)" syntax (i.e. no cast to void).  */
-# pragma warn -8019
+/* Code has no effect; raised by winnt.h in C (not C++) when ignoring an
+   unused parameter using "(param)" syntax (i.e. no cast to void).  */
+#pragma warn - 8019
 #endif
 
 /*--------------------------------------------------------------------------*/
@@ -85,96 +77,107 @@
 /* Full path to the directory in which this executable is built.  Do
    not include a trailing slash.  */
 #if !defined(@KWSYS_NAMESPACE at _SHARED_FORWARD_DIR_BUILD)
-# error "Must define @KWSYS_NAMESPACE at _SHARED_FORWARD_DIR_BUILD"
+#error "Must define @KWSYS_NAMESPACE at _SHARED_FORWARD_DIR_BUILD"
 #endif
 #if !defined(KWSYS_SHARED_FORWARD_DIR_BUILD)
-# define KWSYS_SHARED_FORWARD_DIR_BUILD @KWSYS_NAMESPACE at _SHARED_FORWARD_DIR_BUILD
+#define KWSYS_SHARED_FORWARD_DIR_BUILD                                        \
+  @KWSYS_NAMESPACE at _SHARED_FORWARD_DIR_BUILD
 #endif
 
 /* Library search path for build tree.  */
 #if !defined(@KWSYS_NAMESPACE at _SHARED_FORWARD_PATH_BUILD)
-# error "Must define @KWSYS_NAMESPACE at _SHARED_FORWARD_PATH_BUILD"
+#error "Must define @KWSYS_NAMESPACE at _SHARED_FORWARD_PATH_BUILD"
 #endif
 #if !defined(KWSYS_SHARED_FORWARD_PATH_BUILD)
-# define KWSYS_SHARED_FORWARD_PATH_BUILD @KWSYS_NAMESPACE at _SHARED_FORWARD_PATH_BUILD
+#define KWSYS_SHARED_FORWARD_PATH_BUILD                                       \
+  @KWSYS_NAMESPACE at _SHARED_FORWARD_PATH_BUILD
 #endif
 
 /* Library search path for install tree.  */
 #if !defined(@KWSYS_NAMESPACE at _SHARED_FORWARD_PATH_INSTALL)
-# error "Must define @KWSYS_NAMESPACE at _SHARED_FORWARD_PATH_INSTALL"
+#error "Must define @KWSYS_NAMESPACE at _SHARED_FORWARD_PATH_INSTALL"
 #endif
 #if !defined(KWSYS_SHARED_FORWARD_PATH_INSTALL)
-# define KWSYS_SHARED_FORWARD_PATH_INSTALL @KWSYS_NAMESPACE at _SHARED_FORWARD_PATH_INSTALL
+#define KWSYS_SHARED_FORWARD_PATH_INSTALL                                     \
+  @KWSYS_NAMESPACE at _SHARED_FORWARD_PATH_INSTALL
 #endif
 
 /* The real executable to which to forward in the build tree.  */
 #if !defined(@KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_BUILD)
-# error "Must define @KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_BUILD"
+#error "Must define @KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_BUILD"
 #endif
 #if !defined(KWSYS_SHARED_FORWARD_EXE_BUILD)
-# define KWSYS_SHARED_FORWARD_EXE_BUILD @KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_BUILD
+#define KWSYS_SHARED_FORWARD_EXE_BUILD                                        \
+  @KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_BUILD
 #endif
 
 /* The real executable to which to forward in the install tree.  */
 #if !defined(@KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_INSTALL)
-# error "Must define @KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_INSTALL"
+#error "Must define @KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_INSTALL"
 #endif
 #if !defined(KWSYS_SHARED_FORWARD_EXE_INSTALL)
-# define KWSYS_SHARED_FORWARD_EXE_INSTALL @KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_INSTALL
+#define KWSYS_SHARED_FORWARD_EXE_INSTALL                                      \
+  @KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_INSTALL
 #endif
 
-/* The configuration name with which this executable was built (Debug/Release). */
+/* The configuration name with which this executable was built (Debug/Release).
+ */
 #if defined(@KWSYS_NAMESPACE at _SHARED_FORWARD_CONFIG_NAME)
-# define KWSYS_SHARED_FORWARD_CONFIG_NAME @KWSYS_NAMESPACE at _SHARED_FORWARD_CONFIG_NAME
+#define KWSYS_SHARED_FORWARD_CONFIG_NAME                                      \
+  @KWSYS_NAMESPACE at _SHARED_FORWARD_CONFIG_NAME
 #else
-# undef KWSYS_SHARED_FORWARD_CONFIG_NAME
+#undef KWSYS_SHARED_FORWARD_CONFIG_NAME
 #endif
 
 /* Create command line option to replace executable.  */
 #if defined(@KWSYS_NAMESPACE at _SHARED_FORWARD_OPTION_COMMAND)
-# if !defined(KWSYS_SHARED_FORWARD_OPTION_COMMAND)
-#  define KWSYS_SHARED_FORWARD_OPTION_COMMAND @KWSYS_NAMESPACE at _SHARED_FORWARD_OPTION_COMMAND
-# endif
+#if !defined(KWSYS_SHARED_FORWARD_OPTION_COMMAND)
+#define KWSYS_SHARED_FORWARD_OPTION_COMMAND                                   \
+  @KWSYS_NAMESPACE at _SHARED_FORWARD_OPTION_COMMAND
+#endif
 #else
-# undef KWSYS_SHARED_FORWARD_OPTION_COMMAND
+#undef KWSYS_SHARED_FORWARD_OPTION_COMMAND
 #endif
 
 /* Create command line option to print environment setting and exit.  */
 #if defined(@KWSYS_NAMESPACE at _SHARED_FORWARD_OPTION_PRINT)
-# if !defined(KWSYS_SHARED_FORWARD_OPTION_PRINT)
-#  define KWSYS_SHARED_FORWARD_OPTION_PRINT @KWSYS_NAMESPACE at _SHARED_FORWARD_OPTION_PRINT
-# endif
+#if !defined(KWSYS_SHARED_FORWARD_OPTION_PRINT)
+#define KWSYS_SHARED_FORWARD_OPTION_PRINT                                     \
+  @KWSYS_NAMESPACE at _SHARED_FORWARD_OPTION_PRINT
+#endif
 #else
-# undef KWSYS_SHARED_FORWARD_OPTION_PRINT
+#undef KWSYS_SHARED_FORWARD_OPTION_PRINT
 #endif
 
 /* Create command line option to run ldd or equivalent.  */
 #if defined(@KWSYS_NAMESPACE at _SHARED_FORWARD_OPTION_LDD)
-# if !defined(KWSYS_SHARED_FORWARD_OPTION_LDD)
-#  define KWSYS_SHARED_FORWARD_OPTION_LDD @KWSYS_NAMESPACE at _SHARED_FORWARD_OPTION_LDD
-# endif
+#if !defined(KWSYS_SHARED_FORWARD_OPTION_LDD)
+#define KWSYS_SHARED_FORWARD_OPTION_LDD                                       \
+  @KWSYS_NAMESPACE at _SHARED_FORWARD_OPTION_LDD
+#endif
 #else
-# undef KWSYS_SHARED_FORWARD_OPTION_LDD
+#undef KWSYS_SHARED_FORWARD_OPTION_LDD
 #endif
 
 /*--------------------------------------------------------------------------*/
 /* Include needed system headers.  */
 
-#include <stddef.h> /* size_t */
+#include <errno.h>
 #include <limits.h>
+#include <stddef.h> /* size_t */
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <errno.h>
-#include <stdio.h>
 
 #if defined(_WIN32) && !defined(__CYGWIN__)
-# include <io.h>
-# include <windows.h>
-# include <process.h>
-# define KWSYS_SHARED_FORWARD_ESCAPE_ARGV /* re-escape argv for execvp */
+#include <windows.h>
+
+#include <io.h>
+#include <process.h>
+#define KWSYS_SHARED_FORWARD_ESCAPE_ARGV /* re-escape argv for execvp */
 #else
-# include <unistd.h>
-# include <sys/stat.h>
+#include <sys/stat.h>
+#include <unistd.h>
 #endif
 
 /*--------------------------------------------------------------------------*/
@@ -182,22 +185,26 @@
 
 /* The path separator for this platform.  */
 #if defined(_WIN32) && !defined(__CYGWIN__)
-# define KWSYS_SHARED_FORWARD_PATH_SEP ';'
-# define KWSYS_SHARED_FORWARD_PATH_SLASH '\\'
+#define KWSYS_SHARED_FORWARD_PATH_SEP ';'
+#define KWSYS_SHARED_FORWARD_PATH_SLASH '\\'
 #else
-# define KWSYS_SHARED_FORWARD_PATH_SEP ':'
-# define KWSYS_SHARED_FORWARD_PATH_SLASH '/'
+#define KWSYS_SHARED_FORWARD_PATH_SEP ':'
+#define KWSYS_SHARED_FORWARD_PATH_SLASH '/'
 #endif
-static const char kwsys_shared_forward_path_sep[2] = {KWSYS_SHARED_FORWARD_PATH_SEP, 0};
-static const char kwsys_shared_forward_path_slash[2] = {KWSYS_SHARED_FORWARD_PATH_SLASH, 0};
+static const char kwsys_shared_forward_path_sep[2] = {
+  KWSYS_SHARED_FORWARD_PATH_SEP, 0
+};
+static const char kwsys_shared_forward_path_slash[2] = {
+  KWSYS_SHARED_FORWARD_PATH_SLASH, 0
+};
 
 /* The maximum length of a file name.  */
 #if defined(PATH_MAX)
-# define KWSYS_SHARED_FORWARD_MAXPATH PATH_MAX
+#define KWSYS_SHARED_FORWARD_MAXPATH PATH_MAX
 #elif defined(MAXPATHLEN)
-# define KWSYS_SHARED_FORWARD_MAXPATH MAXPATHLEN
+#define KWSYS_SHARED_FORWARD_MAXPATH MAXPATHLEN
 #else
-# define KWSYS_SHARED_FORWARD_MAXPATH 16384
+#define KWSYS_SHARED_FORWARD_MAXPATH 16384
 #endif
 
 /* Select the environment variable holding the shared library runtime
@@ -206,82 +213,82 @@ static const char kwsys_shared_forward_path_slash[2] = {KWSYS_SHARED_FORWARD_PAT
 
 /* Linux */
 #if defined(__linux)
-# define KWSYS_SHARED_FORWARD_LDD "ldd"
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
+#define KWSYS_SHARED_FORWARD_LDD "ldd"
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
 
 /* FreeBSD */
 #elif defined(__FreeBSD__)
-# define KWSYS_SHARED_FORWARD_LDD "ldd"
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
+#define KWSYS_SHARED_FORWARD_LDD "ldd"
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
 
 /* OpenBSD */
 #elif defined(__OpenBSD__)
-# define KWSYS_SHARED_FORWARD_LDD "ldd"
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
+#define KWSYS_SHARED_FORWARD_LDD "ldd"
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
 
 /* OSX */
 #elif defined(__APPLE__)
-# define KWSYS_SHARED_FORWARD_LDD "otool", "-L"
-# define KWSYS_SHARED_FORWARD_LDD_N 2
-# define KWSYS_SHARED_FORWARD_LDPATH "DYLD_LIBRARY_PATH"
+#define KWSYS_SHARED_FORWARD_LDD "otool", "-L"
+#define KWSYS_SHARED_FORWARD_LDD_N 2
+#define KWSYS_SHARED_FORWARD_LDPATH "DYLD_LIBRARY_PATH"
 
 /* AIX */
 #elif defined(_AIX)
-# define KWSYS_SHARED_FORWARD_LDD "dump", "-H"
-# define KWSYS_SHARED_FORWARD_LDD_N 2
-# define KWSYS_SHARED_FORWARD_LDPATH "LIBPATH"
+#define KWSYS_SHARED_FORWARD_LDD "dump", "-H"
+#define KWSYS_SHARED_FORWARD_LDD_N 2
+#define KWSYS_SHARED_FORWARD_LDPATH "LIBPATH"
 
 /* SUN */
 #elif defined(__sun)
-# define KWSYS_SHARED_FORWARD_LDD "ldd"
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# include <sys/isa_defs.h>
-# if defined(_ILP32)
-#  define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
-# elif defined(_LP64)
-#  define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH_64"
-# endif
+#define KWSYS_SHARED_FORWARD_LDD "ldd"
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#include <sys/isa_defs.h>
+#if defined(_ILP32)
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
+#elif defined(_LP64)
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH_64"
+#endif
 
 /* HP-UX */
 #elif defined(__hpux)
-# define KWSYS_SHARED_FORWARD_LDD "chatr"
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# if defined(__LP64__)
-#  define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
-# else
-#  define KWSYS_SHARED_FORWARD_LDPATH "SHLIB_PATH"
-# endif
+#define KWSYS_SHARED_FORWARD_LDD "chatr"
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#if defined(__LP64__)
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
+#else
+#define KWSYS_SHARED_FORWARD_LDPATH "SHLIB_PATH"
+#endif
 
 /* SGI MIPS */
 #elif defined(__sgi) && defined(_MIPS_SIM)
-# define KWSYS_SHARED_FORWARD_LDD "ldd"
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# if _MIPS_SIM == _ABIO32
-#  define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
-# elif _MIPS_SIM == _ABIN32
-#  define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARYN32_PATH"
-# elif _MIPS_SIM == _ABI64
-#  define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY64_PATH"
-# endif
+#define KWSYS_SHARED_FORWARD_LDD "ldd"
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#if _MIPS_SIM == _ABIO32
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
+#elif _MIPS_SIM == _ABIN32
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARYN32_PATH"
+#elif _MIPS_SIM == _ABI64
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY64_PATH"
+#endif
 
 /* Cygwin */
 #elif defined(__CYGWIN__)
-# define KWSYS_SHARED_FORWARD_LDD "cygcheck" /* TODO: cygwin 1.7 has ldd */
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# define KWSYS_SHARED_FORWARD_LDPATH "PATH"
+#define KWSYS_SHARED_FORWARD_LDD "cygcheck" /* TODO: cygwin 1.7 has ldd */
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#define KWSYS_SHARED_FORWARD_LDPATH "PATH"
 
 /* Windows */
 #elif defined(_WIN32)
-# define KWSYS_SHARED_FORWARD_LDPATH "PATH"
+#define KWSYS_SHARED_FORWARD_LDPATH "PATH"
 
 /* Guess on this unknown system.  */
 #else
-# define KWSYS_SHARED_FORWARD_LDD "ldd"
-# define KWSYS_SHARED_FORWARD_LDD_N 1
-# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
+#define KWSYS_SHARED_FORWARD_LDD "ldd"
+#define KWSYS_SHARED_FORWARD_LDD_N 1
+#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
 #endif
 
 #ifdef KWSYS_SHARED_FORWARD_ESCAPE_ARGV
@@ -312,45 +319,37 @@ static kwsys_sf_arg_info kwsys_sf_get_arg_info(const char* in)
   info.quote = 0;
 
   /* Scan the string for characters that require escaping or quoting.  */
-  for(c=in; *c; ++c)
-    {
+  for (c = in; *c; ++c) {
     /* Check whether this character needs quotes.  */
-    if(strchr(" \t?'#&<>|^", *c))
-      {
+    if (strchr(" \t?'#&<>|^", *c)) {
       info.quote = 1;
-      }
+    }
 
     /* On Windows only backslashes and double-quotes need escaping.  */
-    if(*c == '\\')
-      {
+    if (*c == '\\') {
       /* Found a backslash.  It may need to be escaped later.  */
       ++windows_backslashes;
-      }
-    else if(*c == '"')
-      {
+    } else if (*c == '"') {
       /* Found a double-quote.  We need to escape it and all
          immediately preceding backslashes.  */
       info.size += windows_backslashes + 1;
       windows_backslashes = 0;
-      }
-    else
-      {
+    } else {
       /* Found another character.  This eliminates the possibility
          that any immediately preceding backslashes will be
          escaped.  */
       windows_backslashes = 0;
-      }
     }
+  }
 
   /* Check whether the argument needs surrounding quotes.  */
-  if(info.quote)
-    {
+  if (info.quote) {
     /* Surrounding quotes are needed.  Allocate space for them.  */
     info.size += 2;
 
     /* We must escape all ending backslashes when quoting on windows.  */
     info.size += windows_backslashes;
-    }
+  }
 
   return info;
 }
@@ -365,57 +364,47 @@ static char* kwsys_sf_get_arg(kwsys_sf_arg_info info, char* out)
   int windows_backslashes = 0;
 
   /* Whether the argument must be quoted.  */
-  if(info.quote)
-    {
+  if (info.quote) {
     /* Add the opening quote for this argument.  */
     *out++ = '"';
-    }
+  }
 
   /* Scan the string for characters that require escaping or quoting.  */
-  for(c=info.arg; *c; ++c)
-    {
+  for (c = info.arg; *c; ++c) {
     /* On Windows only backslashes and double-quotes need escaping.  */
-    if(*c == '\\')
-      {
+    if (*c == '\\') {
       /* Found a backslash.  It may need to be escaped later.  */
       ++windows_backslashes;
-      }
-    else if(*c == '"')
-      {
+    } else if (*c == '"') {
       /* Found a double-quote.  Escape all immediately preceding
          backslashes.  */
-      while(windows_backslashes > 0)
-        {
+      while (windows_backslashes > 0) {
         --windows_backslashes;
         *out++ = '\\';
-        }
+      }
 
       /* Add the backslash to escape the double-quote.  */
       *out++ = '\\';
-      }
-    else
-      {
+    } else {
       /* We encountered a normal character.  This eliminates any
          escaping needed for preceding backslashes.  */
       windows_backslashes = 0;
-      }
+    }
 
     /* Store this character.  */
     *out++ = *c;
-    }
+  }
 
-  if(info.quote)
-    {
+  if (info.quote) {
     /* Add enough backslashes to escape any trailing ones.  */
-    while(windows_backslashes > 0)
-      {
+    while (windows_backslashes > 0) {
       --windows_backslashes;
       *out++ = '\\';
-      }
+    }
 
     /* Add the closing quote for this argument.  */
     *out++ = '"';
-    }
+  }
 
   /* Store a terminating null without incrementing.  */
   *out = 0;
@@ -430,8 +419,8 @@ static int kwsys_shared_forward_realpath(const char* in_path, char* out_path)
 {
 #if defined(_WIN32) && !defined(__CYGWIN__)
   /* Implementation for Windows.  */
-  DWORD n = GetFullPathNameA(in_path, KWSYS_SHARED_FORWARD_MAXPATH,
-                            out_path, 0);
+  DWORD n =
+    GetFullPathNameA(in_path, KWSYS_SHARED_FORWARD_MAXPATH, out_path, 0);
   return n > 0 && n <= KWSYS_SHARED_FORWARD_MAXPATH;
 #else
   /* Implementation for UNIX.  */
@@ -445,11 +434,10 @@ static int kwsys_shared_forward_samepath(const char* file1, const char* file2)
 #if defined(_WIN32)
   int result = 0;
   HANDLE h1 = CreateFileA(file1, GENERIC_READ, FILE_SHARE_READ, NULL,
-                         OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
+                          OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
   HANDLE h2 = CreateFileA(file2, GENERIC_READ, FILE_SHARE_READ, NULL,
-                         OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
-  if(h1 != INVALID_HANDLE_VALUE && h2 != INVALID_HANDLE_VALUE)
-    {
+                          OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
+  if (h1 != INVALID_HANDLE_VALUE && h2 != INVALID_HANDLE_VALUE) {
     BY_HANDLE_FILE_INFORMATION fi1;
     BY_HANDLE_FILE_INFORMATION fi2;
     GetFileInformationByHandle(h1, &fi1);
@@ -457,10 +445,10 @@ static int kwsys_shared_forward_samepath(const char* file1, const char* file2)
     result = (fi1.dwVolumeSerialNumber == fi2.dwVolumeSerialNumber &&
               fi1.nFileIndexHigh == fi2.nFileIndexHigh &&
               fi1.nFileIndexLow == fi2.nFileIndexLow);
-    }
-   CloseHandle(h1);
-   CloseHandle(h2);
-   return result;
+  }
+  CloseHandle(h1);
+  CloseHandle(h2);
+  return result;
 #else
   struct stat fs1, fs2;
   return (stat(file1, &fs1) == 0 && stat(file2, &fs2) == 0 &&
@@ -477,17 +465,16 @@ static void kwsys_shared_forward_strerror(char* message)
 #if defined(_WIN32) && !defined(__CYGWIN__)
   /* Implementation for Windows.  */
   DWORD original = GetLastError();
-  DWORD length = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
-                               FORMAT_MESSAGE_IGNORE_INSERTS, 0, original,
-                               MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-                               message, KWSYS_SHARED_FORWARD_MAXPATH, 0);
-  if(length < 1 || length > KWSYS_SHARED_FORWARD_MAXPATH)
-    {
+  DWORD length =
+    FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
+                   0, original, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+                   message, KWSYS_SHARED_FORWARD_MAXPATH, 0);
+  if (length < 1 || length > KWSYS_SHARED_FORWARD_MAXPATH) {
     /* FormatMessage failed.  Use a default message.  */
     _snprintf(message, KWSYS_SHARED_FORWARD_MAXPATH,
-              "Error 0x%X (FormatMessage failed with error 0x%X)",
-              original, GetLastError());
-    }
+              "Error 0x%X (FormatMessage failed with error 0x%X)", original,
+              GetLastError());
+  }
 #else
   /* Implementation for UNIX.  */
   strcpy(message, strerror(errno));
@@ -503,28 +490,28 @@ static void kwsys_shared_forward_execvp(const char* cmd,
   /* Count the number of arguments.  */
   int argc = 0;
   {
-  char const* const* argvc;
-  for(argvc = argv; *argvc; ++argvc,++argc) {}
+    char const* const* argvc;
+    for (argvc = argv; *argvc; ++argvc, ++argc) {
+    }
   }
 
   /* Create the escaped arguments.  */
   {
-  char** nargv = (char**)malloc((argc+1) * sizeof(char*));
-  int i;
-  for(i=0; i < argc; ++i)
-    {
-    kwsys_sf_arg_info info = kwsys_sf_get_arg_info(argv[i]);
-    nargv[i] = (char*)malloc(info.size);
-    kwsys_sf_get_arg(info, nargv[i]);
+    char** nargv = (char**)malloc((argc + 1) * sizeof(char*));
+    int i;
+    for (i = 0; i < argc; ++i) {
+      kwsys_sf_arg_info info = kwsys_sf_get_arg_info(argv[i]);
+      nargv[i] = (char*)malloc(info.size);
+      kwsys_sf_get_arg(info, nargv[i]);
     }
-  nargv[argc] = 0;
+    nargv[argc] = 0;
 
-  /* Replace the command line to be used.  */
-  argv = (char const* const*)nargv;
+    /* Replace the command line to be used.  */
+    argv = (char const* const*)nargv;
   }
 #endif
 
-  /* Invoke the child process.  */
+/* Invoke the child process.  */
 #if defined(_MSC_VER)
   _execvp(cmd, argv);
 #elif defined(__MINGW32__) && !defined(__MINGW64__)
@@ -541,40 +528,33 @@ static void kwsys_shared_forward_dirname(const char* begin, char* result)
   /* Find the location of the last slash.  */
   int last_slash_index = -1;
   const char* end = begin + strlen(begin);
-  for(;begin <= end && last_slash_index < 0; --end)
-    {
-    if(*end == '/' || *end == '\\')
-      {
-      last_slash_index = (int)(end-begin);
-      }
+  for (; begin <= end && last_slash_index < 0; --end) {
+    if (*end == '/' || *end == '\\') {
+      last_slash_index = (int)(end - begin);
     }
+  }
 
   /* Handle each case of the index of the last slash.  */
-  if(last_slash_index < 0)
-    {
+  if (last_slash_index < 0) {
     /* No slashes.  */
     strcpy(result, ".");
-    }
-  else if(last_slash_index == 0)
-    {
+  } else if (last_slash_index == 0) {
     /* Only one leading slash.  */
     strcpy(result, kwsys_shared_forward_path_slash);
-    }
+  }
 #if defined(_WIN32)
-  else if(last_slash_index == 2 && begin[1] == ':')
-    {
+  else if (last_slash_index == 2 && begin[1] == ':') {
     /* Only one leading drive letter and slash.  */
     strncpy(result, begin, (size_t)last_slash_index);
     result[last_slash_index] = KWSYS_SHARED_FORWARD_PATH_SLASH;
-    result[last_slash_index+1] = 0;
-    }
+    result[last_slash_index + 1] = 0;
+  }
 #endif
-  else
-    {
+  else {
     /* A non-leading slash.  */
     strncpy(result, begin, (size_t)last_slash_index);
     result[last_slash_index] = 0;
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -582,23 +562,20 @@ static void kwsys_shared_forward_dirname(const char* begin, char* result)
 static int kwsys_shared_forward_is_executable(const char* f)
 {
 #if defined(_MSC_VER)
-# define KWSYS_SHARED_FORWARD_ACCESS _access
+#define KWSYS_SHARED_FORWARD_ACCESS _access
 #else
-# define KWSYS_SHARED_FORWARD_ACCESS access
+#define KWSYS_SHARED_FORWARD_ACCESS access
 #endif
 #if defined(X_OK)
-# define KWSYS_SHARED_FORWARD_ACCESS_OK X_OK
+#define KWSYS_SHARED_FORWARD_ACCESS_OK X_OK
 #else
-# define KWSYS_SHARED_FORWARD_ACCESS_OK 04
+#define KWSYS_SHARED_FORWARD_ACCESS_OK 04
 #endif
-  if(KWSYS_SHARED_FORWARD_ACCESS(f, KWSYS_SHARED_FORWARD_ACCESS_OK) == 0)
-    {
+  if (KWSYS_SHARED_FORWARD_ACCESS(f, KWSYS_SHARED_FORWARD_ACCESS_OK) == 0) {
     return 1;
-    }
-  else
-    {
+  } else {
     return 0;
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -608,66 +585,60 @@ static int kwsys_shared_forward_self_path(const char* argv0, char* result)
   /* Check whether argv0 has a slash.  */
   int has_slash = 0;
   const char* p = argv0;
-  for(;*p && !has_slash; ++p)
-    {
-    if(*p == '/' || *p == '\\')
-      {
+  for (; *p && !has_slash; ++p) {
+    if (*p == '/' || *p == '\\') {
       has_slash = 1;
-      }
     }
+  }
 
-  if(has_slash)
-    {
+  if (has_slash) {
     /* There is a slash.  Use the dirname of the given location.  */
     kwsys_shared_forward_dirname(argv0, result);
     return 1;
-    }
-  else
-    {
+  } else {
     /* There is no slash.  Search the PATH for the executable.  */
     const char* path = getenv("PATH");
     const char* begin = path;
-    const char* end = begin + (begin?strlen(begin):0);
+    const char* end = begin + (begin ? strlen(begin) : 0);
     const char* first = begin;
-    while(first != end)
-      {
+    while (first != end) {
       /* Store the end of this path entry.  */
       const char* last;
 
       /* Skip all path separators.  */
-      for(;*first && *first == KWSYS_SHARED_FORWARD_PATH_SEP; ++first);
+      for (; *first && *first == KWSYS_SHARED_FORWARD_PATH_SEP; ++first)
+        ;
 
       /* Find the next separator.  */
-      for(last = first;*last && *last != KWSYS_SHARED_FORWARD_PATH_SEP; ++last);
+      for (last = first; *last && *last != KWSYS_SHARED_FORWARD_PATH_SEP;
+           ++last)
+        ;
 
       /* If we got a non-empty directory, look for the executable there.  */
-      if(first < last)
-        {
+      if (first < last) {
         /* Determine the length without trailing slash.  */
-        size_t length = (size_t)(last-first);
-        if(*(last-1) == '/' || *(last-1) == '\\')
-          {
+        size_t length = (size_t)(last - first);
+        if (*(last - 1) == '/' || *(last - 1) == '\\') {
           --length;
-          }
+        }
 
         /* Construct the name of the executable in this location.  */
         strncpy(result, first, length);
         result[length] = KWSYS_SHARED_FORWARD_PATH_SLASH;
-        strcpy(result+(length)+1, argv0);
+        strcpy(result + (length) + 1, argv0);
 
         /* Check if it exists and is executable.  */
-        if(kwsys_shared_forward_is_executable(result))
-          {
+        if (kwsys_shared_forward_is_executable(result)) {
           /* Found it.  */
           result[length] = 0;
           return 1;
-          }
         }
+      }
 
       /* Move to the next directory in the path.  */
       first = last;
-      }
     }
+  }
 
   /* We could not find the executable.  */
   return 0;
@@ -677,42 +648,36 @@ static int kwsys_shared_forward_self_path(const char* argv0, char* result)
 /* Function to convert a specified path to a full path.  If it is not
    already full, it is taken relative to the self path.  */
 static int kwsys_shared_forward_fullpath(const char* self_path,
-                                         const char* in_path,
-                                         char* result,
+                                         const char* in_path, char* result,
                                          const char* desc)
 {
   /* Check the specified path type.  */
-  if(in_path[0] == '/')
-    {
+  if (in_path[0] == '/') {
     /* Already a full path.  */
     strcpy(result, in_path);
-    }
+  }
 #if defined(_WIN32)
-  else if(in_path[0] && in_path[1] == ':')
-    {
+  else if (in_path[0] && in_path[1] == ':') {
     /* Already a full path.  */
     strcpy(result, in_path);
-    }
+  }
 #endif
-  else
-    {
+  else {
     /* Relative to self path.  */
     char temp_path[KWSYS_SHARED_FORWARD_MAXPATH];
     strcpy(temp_path, self_path);
     strcat(temp_path, kwsys_shared_forward_path_slash);
     strcat(temp_path, in_path);
-    if(!kwsys_shared_forward_realpath(temp_path, result))
-      {
-      if(desc)
-        {
+    if (!kwsys_shared_forward_realpath(temp_path, result)) {
+      if (desc) {
         char msgbuf[KWSYS_SHARED_FORWARD_MAXPATH];
         kwsys_shared_forward_strerror(msgbuf);
-        fprintf(stderr, "Error converting %s \"%s\" to real path: %s\n",
-                desc, temp_path, msgbuf);
-        }
-      return 0;
+        fprintf(stderr, "Error converting %s \"%s\" to real path: %s\n", desc,
+                temp_path, msgbuf);
       }
+      return 0;
     }
+  }
   return 1;
 }
 
@@ -723,16 +688,20 @@ static int kwsys_shared_forward_get_settings(const char* self_path,
                                              char* ldpath, char* exe)
 {
   /* Possible search paths.  */
-  static const char* search_path_build[] = {KWSYS_SHARED_FORWARD_PATH_BUILD, 0};
-  static const char* search_path_install[] = {KWSYS_SHARED_FORWARD_PATH_INSTALL, 0};
+  static const char* search_path_build[] = { KWSYS_SHARED_FORWARD_PATH_BUILD,
+                                             0 };
+  static const char* search_path_install[] = {
+    KWSYS_SHARED_FORWARD_PATH_INSTALL, 0
+  };
 
   /* Chosen paths.  */
   const char** search_path;
   const char* exe_path;
 
-  /* Get the real name of the build and self paths.  */
+/* Get the real name of the build and self paths.  */
 #if defined(KWSYS_SHARED_FORWARD_CONFIG_NAME)
-  char build_path[] = KWSYS_SHARED_FORWARD_DIR_BUILD "/" KWSYS_SHARED_FORWARD_CONFIG_NAME;
+  char build_path[] =
+    KWSYS_SHARED_FORWARD_DIR_BUILD "/" KWSYS_SHARED_FORWARD_CONFIG_NAME;
   char self_path_logical[KWSYS_SHARED_FORWARD_MAXPATH];
 #else
   char build_path[] = KWSYS_SHARED_FORWARD_DIR_BUILD;
@@ -740,19 +709,17 @@ static int kwsys_shared_forward_get_settings(const char* self_path,
 #endif
   char build_path_real[KWSYS_SHARED_FORWARD_MAXPATH];
   char self_path_real[KWSYS_SHARED_FORWARD_MAXPATH];
-  if(!kwsys_shared_forward_realpath(self_path, self_path_real))
-    {
+  if (!kwsys_shared_forward_realpath(self_path, self_path_real)) {
     char msgbuf[KWSYS_SHARED_FORWARD_MAXPATH];
     kwsys_shared_forward_strerror(msgbuf);
     fprintf(stderr, "Error converting self path \"%s\" to real path: %s\n",
             self_path, msgbuf);
     return 0;
-    }
+  }
 
   /* Check whether we are running in the build tree or an install tree.  */
-  if(kwsys_shared_forward_realpath(build_path, build_path_real) &&
-     kwsys_shared_forward_samepath(self_path_real, build_path_real))
-    {
+  if (kwsys_shared_forward_realpath(build_path, build_path_real) &&
+      kwsys_shared_forward_samepath(self_path_real, build_path_real)) {
     /* Running in build tree.  Use the build path and exe.  */
     search_path = search_path_build;
 #if defined(_WIN32)
@@ -765,9 +732,7 @@ static int kwsys_shared_forward_get_settings(const char* self_path,
     /* Remove the configuration directory from self_path.  */
     kwsys_shared_forward_dirname(self_path, self_path_logical);
 #endif
-    }
-  else
-    {
+  } else {
     /* Running in install tree.  Use the install path and exe.  */
     search_path = search_path_install;
 #if defined(_WIN32)
@@ -780,35 +745,31 @@ static int kwsys_shared_forward_get_settings(const char* self_path,
     /* Use the original self path directory.  */
     strcpy(self_path_logical, self_path);
 #endif
-    }
+  }
 
   /* Construct the runtime search path.  */
   {
-  const char** dir;
-  for(dir = search_path; *dir; ++dir)
-    {
-    /* Add separator between path components.  */
-    if(dir != search_path)
-      {
-      strcat(ldpath, kwsys_shared_forward_path_sep);
+    const char** dir;
+    for (dir = search_path; *dir; ++dir) {
+      /* Add separator between path components.  */
+      if (dir != search_path) {
+        strcat(ldpath, kwsys_shared_forward_path_sep);
       }
 
-    /* Add this path component.  */
-    if(!kwsys_shared_forward_fullpath(self_path_logical, *dir,
-                                      ldpath+strlen(ldpath),
-                                      "runtime path entry"))
-      {
-      return 0;
+      /* Add this path component.  */
+      if (!kwsys_shared_forward_fullpath(self_path_logical, *dir,
+                                         ldpath + strlen(ldpath),
+                                         "runtime path entry")) {
+        return 0;
       }
     }
   }
 
   /* Construct the executable location.  */
-  if(!kwsys_shared_forward_fullpath(self_path_logical, exe_path, exe,
-                                    "executable file"))
-    {
+  if (!kwsys_shared_forward_fullpath(self_path_logical, exe_path, exe,
+                                     "executable file")) {
     return 0;
-    }
+  }
   return 1;
 }
 
@@ -820,15 +781,15 @@ static void kwsys_shared_forward_print_failure(char const* const* argv)
   char const* const* arg = argv;
   kwsys_shared_forward_strerror(msg);
   fprintf(stderr, "Error running");
-  for(; *arg; ++arg)
-    {
+  for (; *arg; ++arg) {
     fprintf(stderr, " \"%s\"", *arg);
-    }
+  }
   fprintf(stderr, ": %s\n", msg);
 }
 
 /* Static storage space to store the updated environment variable.  */
-static char kwsys_shared_forward_ldpath[65535] = KWSYS_SHARED_FORWARD_LDPATH "=";
+static char kwsys_shared_forward_ldpath[65535] =
+  KWSYS_SHARED_FORWARD_LDPATH "=";
 
 /*--------------------------------------------------------------------------*/
 /* Main driver function to be called from main.  */
@@ -837,74 +798,67 @@ static int @KWSYS_NAMESPACE at _shared_forward_to_real(int argc, char** argv_in)
   char const** argv = (char const**)argv_in;
   /* Get the directory containing this executable.  */
   char self_path[KWSYS_SHARED_FORWARD_MAXPATH];
-  if(kwsys_shared_forward_self_path(argv[0], self_path))
-    {
+  if (kwsys_shared_forward_self_path(argv[0], self_path)) {
     /* Found this executable.  Use it to get the library directory.  */
     char exe[KWSYS_SHARED_FORWARD_MAXPATH];
-    if(kwsys_shared_forward_get_settings(self_path,
-                                         kwsys_shared_forward_ldpath, exe))
-      {
+    if (kwsys_shared_forward_get_settings(self_path,
+                                          kwsys_shared_forward_ldpath, exe)) {
       /* Append the old runtime search path.  */
       const char* old_ldpath = getenv(KWSYS_SHARED_FORWARD_LDPATH);
-      if(old_ldpath)
-        {
+      if (old_ldpath) {
         strcat(kwsys_shared_forward_ldpath, kwsys_shared_forward_path_sep);
         strcat(kwsys_shared_forward_ldpath, old_ldpath);
-        }
+      }
 
       /* Store the environment variable.  */
       putenv(kwsys_shared_forward_ldpath);
 
 #if defined(KWSYS_SHARED_FORWARD_OPTION_COMMAND)
       /* Look for the command line replacement option.  */
-      if(argc > 1 && strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_COMMAND) == 0)
-        {
-        if(argc > 2)
-          {
+      if (argc > 1 &&
+          strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_COMMAND) == 0) {
+        if (argc > 2) {
           /* Use the command line given.  */
           strcpy(exe, argv[2]);
           argv += 2;
           argc -= 2;
-          }
-        else
-          {
+        } else {
           /* The option was not given an executable.  */
           fprintf(stderr, "Option " KWSYS_SHARED_FORWARD_OPTION_COMMAND
-                  " must be followed by a command line.\n");
+                          " must be followed by a command line.\n");
           return 1;
-          }
         }
+      }
 #endif
 
 #if defined(KWSYS_SHARED_FORWARD_OPTION_PRINT)
       /* Look for the print command line option.  */
-      if(argc > 1 && strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_PRINT) == 0)
-        {
+      if (argc > 1 &&
+          strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_PRINT) == 0) {
         fprintf(stdout, "%s\n", kwsys_shared_forward_ldpath);
         fprintf(stdout, "%s\n", exe);
         return 0;
-        }
+      }
 #endif
 
 #if defined(KWSYS_SHARED_FORWARD_OPTION_LDD)
       /* Look for the ldd command line option.  */
-      if(argc > 1 && strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_LDD) == 0)
-        {
-# if defined(KWSYS_SHARED_FORWARD_LDD)
+      if (argc > 1 && strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_LDD) == 0) {
+#if defined(KWSYS_SHARED_FORWARD_LDD)
         /* Use the named ldd-like executable and arguments.  */
-        char const* ldd_argv[] = {KWSYS_SHARED_FORWARD_LDD, 0, 0};
+        char const* ldd_argv[] = { KWSYS_SHARED_FORWARD_LDD, 0, 0 };
         ldd_argv[KWSYS_SHARED_FORWARD_LDD_N] = exe;
         kwsys_shared_forward_execvp(ldd_argv[0], ldd_argv);
 
         /* Report why execution failed.  */
         kwsys_shared_forward_print_failure(ldd_argv);
         return 1;
-# else
+#else
         /* We have no ldd-like executable available on this platform.  */
         fprintf(stderr, "No ldd-like tool is known to this executable.\n");
         return 1;
-# endif
-        }
+#endif
+      }
 #endif
 
       /* Replace this process with the real executable.  */
@@ -913,17 +867,13 @@ static int @KWSYS_NAMESPACE at _shared_forward_to_real(int argc, char** argv_in)
 
       /* Report why execution failed.  */
       kwsys_shared_forward_print_failure(argv);
-      }
-    else
-      {
+    } else {
       /* Could not convert self path to the library directory.  */
-      }
     }
-  else
-    {
+  } else {
     /* Could not find this executable.  */
     fprintf(stderr, "Error locating executable \"%s\".\n", argv[0]);
-    }
+  }
 
   /* Avoid unused argument warning.  */
   (void)argc;
@@ -934,11 +884,11 @@ static int @KWSYS_NAMESPACE at _shared_forward_to_real(int argc, char** argv_in)
 
 /* Restore warning stack.  */
 #if defined(__clang__) && defined(__has_warning)
-# if __has_warning("-Wcast-qual")
-#  pragma clang diagnostic pop
-# endif
+#if __has_warning("-Wcast-qual")
+#pragma clang diagnostic pop
+#endif
 #endif
 
 #else
-# error "@KWSYS_NAMESPACE@/SharedForward.h should be included only once."
+#error "@KWSYS_NAMESPACE@/SharedForward.h should be included only once."
 #endif
diff --git a/Source/kwsys/String.c b/Source/kwsys/String.c
index ed4a6c5..0482229 100644
--- a/Source/kwsys/String.c
+++ b/Source/kwsys/String.c
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifdef KWSYS_STRING_C
 /*
 All code in this source file is conditionally compiled to work-around
@@ -23,53 +14,49 @@ condition blocks the compiler from seeing the symbols defined here.
 /* Work-around CMake dependency scanning limitation.  This must
    duplicate the above list of headers.  */
 #if 0
-# include "String.h.in"
+#include "String.h.in"
 #endif
 
 /* Select an implementation for strcasecmp.  */
 #if defined(_MSC_VER)
-# define KWSYS_STRING_USE_STRICMP
-# include <string.h>
+#define KWSYS_STRING_USE_STRICMP
+#include <string.h>
 #elif defined(__GNUC__)
-# define KWSYS_STRING_USE_STRCASECMP
-# include <strings.h>
+#define KWSYS_STRING_USE_STRCASECMP
+#include <strings.h>
 #else
 /* Table to convert upper case letters to lower case and leave all
    other characters alone.  */
-static char kwsysString_strcasecmp_tolower[] =
-{
-  '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007',
-  '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017',
-  '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027',
-  '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037',
-  '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047',
-  '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057',
-  '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
-  '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077',
-  '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
-  '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
-  '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
-  '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137',
-  '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
-  '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
-  '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
-  '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177',
-  '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
-  '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217',
-  '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227',
-  '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237',
-  '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247',
-  '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
-  '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
-  '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
-  '\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
-  '\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317',
-  '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327',
-  '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
-  '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
-  '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357',
-  '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
-  '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377'
+static char kwsysString_strcasecmp_tolower[] = {
+  '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007', '\010',
+  '\011', '\012', '\013', '\014', '\015', '\016', '\017', '\020', '\021',
+  '\022', '\023', '\024', '\025', '\026', '\027', '\030', '\031', '\032',
+  '\033', '\034', '\035', '\036', '\037', '\040', '\041', '\042', '\043',
+  '\044', '\045', '\046', '\047', '\050', '\051', '\052', '\053', '\054',
+  '\055', '\056', '\057', '\060', '\061', '\062', '\063', '\064', '\065',
+  '\066', '\067', '\070', '\071', '\072', '\073', '\074', '\075', '\076',
+  '\077', '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
+  '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', '\160',
+  '\161', '\162', '\163', '\164', '\165', '\166', '\167', '\170', '\171',
+  '\172', '\133', '\134', '\135', '\136', '\137', '\140', '\141', '\142',
+  '\143', '\144', '\145', '\146', '\147', '\150', '\151', '\152', '\153',
+  '\154', '\155', '\156', '\157', '\160', '\161', '\162', '\163', '\164',
+  '\165', '\166', '\167', '\170', '\171', '\172', '\173', '\174', '\175',
+  '\176', '\177', '\200', '\201', '\202', '\203', '\204', '\205', '\206',
+  '\207', '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217',
+  '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227', '\230',
+  '\231', '\232', '\233', '\234', '\235', '\236', '\237', '\240', '\241',
+  '\242', '\243', '\244', '\245', '\246', '\247', '\250', '\251', '\252',
+  '\253', '\254', '\255', '\256', '\257', '\260', '\261', '\262', '\263',
+  '\264', '\265', '\266', '\267', '\270', '\271', '\272', '\273', '\274',
+  '\275', '\276', '\277', '\300', '\301', '\302', '\303', '\304', '\305',
+  '\306', '\307', '\310', '\311', '\312', '\313', '\314', '\315', '\316',
+  '\317', '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327',
+  '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337', '\340',
+  '\341', '\342', '\343', '\344', '\345', '\346', '\347', '\350', '\351',
+  '\352', '\353', '\354', '\355', '\356', '\357', '\360', '\361', '\362',
+  '\363', '\364', '\365', '\366', '\367', '\370', '\371', '\372', '\373',
+  '\374', '\375', '\376', '\377'
 };
 #endif
 
@@ -85,9 +72,8 @@ int kwsysString_strcasecmp(const char* lhs, const char* rhs)
   unsigned char const* us1 = (unsigned char const*)lhs;
   unsigned char const* us2 = (unsigned char const*)rhs;
   int result;
-  while((result = lower[*us1] - lower[*us2++], result == 0) && *us1++)
-    {
-    }
+  while ((result = lower[*us1] - lower[*us2++], result == 0) && *us1++) {
+  }
   return result;
 #endif
 }
@@ -104,10 +90,9 @@ int kwsysString_strncasecmp(const char* lhs, const char* rhs, size_t n)
   unsigned char const* us1 = (unsigned char const*)lhs;
   unsigned char const* us2 = (unsigned char const*)rhs;
   int result = 0;
-  while(n && (result = lower[*us1] - lower[*us2++], result == 0) && *us1++)
-    {
+  while (n && (result = lower[*us1] - lower[*us2++], result == 0) && *us1++) {
     --n;
-    }
+  }
   return result;
 #endif
 }
diff --git a/Source/kwsys/String.h.in b/Source/kwsys/String.h.in
index f5bab6e..3c1d571 100644
--- a/Source/kwsys/String.h.in
+++ b/Source/kwsys/String.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _String_h
 #define @KWSYS_NAMESPACE at _String_h
 
@@ -21,17 +12,16 @@
    not visible to user code.  Use kwsysHeaderDump.pl to reproduce
    these macros after making changes to the interface.  */
 #if !defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
 #endif
 #if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-# define kwsysString_strcasecmp                kwsys_ns(String_strcasecmp)
-# define kwsysString_strncasecmp               kwsys_ns(String_strncasecmp)
+#define kwsysString_strcasecmp kwsys_ns(String_strcasecmp)
+#define kwsysString_strncasecmp kwsys_ns(String_strncasecmp)
 #endif
 
 #if defined(__cplusplus)
-extern "C"
-{
+extern "C" {
 #endif
 
 /**
@@ -56,12 +46,12 @@ kwsysEXPORT int kwsysString_strncasecmp(const char* lhs, const char* rhs,
 /* If we are building a kwsys .c or .cxx file, let it use these macros.
    Otherwise, undefine them to keep the namespace clean.  */
 #if !defined(KWSYS_NAMESPACE)
-# undef kwsys_ns
-# undef kwsysEXPORT
-# if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-#  undef kwsysString_strcasecmp
-#  undef kwsysString_strncasecmp
-# endif
+#undef kwsys_ns
+#undef kwsysEXPORT
+#if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
+#undef kwsysString_strcasecmp
+#undef kwsysString_strncasecmp
+#endif
 #endif
 
 #endif
diff --git a/Source/kwsys/String.hxx.in b/Source/kwsys/String.hxx.in
index 2e9aedb..db1cf22 100644
--- a/Source/kwsys/String.hxx.in
+++ b/Source/kwsys/String.hxx.in
@@ -1,21 +1,11 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _String_hxx
 #define @KWSYS_NAMESPACE at _String_hxx
 
 #include <string>
 
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 
 /** \class String
  * \brief Short-name version of the STL basic_string class template.
@@ -25,39 +15,49 @@ namespace @KWSYS_NAMESPACE@
  * simply a subclass of this type with the same interface so that the
  * name is shorter in debugging symbols and error messages.
  */
-class String: public std::string
+class String : public std::string
 {
   /** The original string type.  */
   typedef std::string stl_string;
 
 public:
-
   /** String member types.  */
-  typedef stl_string::value_type             value_type;
-  typedef stl_string::pointer                pointer;
-  typedef stl_string::reference              reference;
-  typedef stl_string::const_reference        const_reference;
-  typedef stl_string::size_type              size_type;
-  typedef stl_string::difference_type        difference_type;
-  typedef stl_string::iterator               iterator;
-  typedef stl_string::const_iterator         const_iterator;
-  typedef stl_string::reverse_iterator       reverse_iterator;
+  typedef stl_string::value_type value_type;
+  typedef stl_string::pointer pointer;
+  typedef stl_string::reference reference;
+  typedef stl_string::const_reference const_reference;
+  typedef stl_string::size_type size_type;
+  typedef stl_string::difference_type difference_type;
+  typedef stl_string::iterator iterator;
+  typedef stl_string::const_iterator const_iterator;
+  typedef stl_string::reverse_iterator reverse_iterator;
   typedef stl_string::const_reverse_iterator const_reverse_iterator;
 
   /** String constructors.  */
-  String(): stl_string() {}
-  String(const value_type* s): stl_string(s) {}
-  String(const value_type* s, size_type n): stl_string(s, n) {}
-  String(const stl_string& s, size_type pos=0, size_type n=npos):
-    stl_string(s, pos, n) {}
+  String()
+    : stl_string()
+  {
+  }
+  String(const value_type* s)
+    : stl_string(s)
+  {
+  }
+  String(const value_type* s, size_type n)
+    : stl_string(s, n)
+  {
+  }
+  String(const stl_string& s, size_type pos = 0, size_type n = npos)
+    : stl_string(s, pos, n)
+  {
+  }
 }; // End Class: String
 
 #if defined(__WATCOMC__)
 inline bool operator<(String const& l, String const& r)
-  {
+{
   return (static_cast<std::string const&>(l) <
           static_cast<std::string const&>(r));
-  }
+}
 #endif
 
 } // namespace @KWSYS_NAMESPACE@
diff --git a/Source/kwsys/System.c b/Source/kwsys/System.c
index ccc7e81..43c60c5 100644
--- a/Source/kwsys/System.c
+++ b/Source/kwsys/System.c
@@ -1,27 +1,18 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(System.h)
 
 /* Work-around CMake dependency scanning limitation.  This must
    duplicate the above list of headers.  */
 #if 0
-# include "System.h.in"
+#include "System.h.in"
 #endif
 
+#include <ctype.h>  /* isspace */
 #include <stddef.h> /* ptrdiff_t */
 #include <stdlib.h> /* malloc, free */
 #include <string.h> /* memcpy */
-#include <ctype.h>  /* isspace */
 
 #include <stdio.h>
 
@@ -32,28 +23,24 @@ typedef int kwsysSystem_ptrdiff_t;
 #endif
 
 /*--------------------------------------------------------------------------*/
-static int kwsysSystem__AppendByte(char* local,
-                                   char** begin, char** end,
+static int kwsysSystem__AppendByte(char* local, char** begin, char** end,
                                    int* size, char c)
 {
   /* Allocate space for the character.  */
-  if((*end - *begin) >= *size)
-    {
+  if ((*end - *begin) >= *size) {
     kwsysSystem_ptrdiff_t length = *end - *begin;
-    char* newBuffer = (char*)malloc((size_t)(*size*2));
-    if(!newBuffer)
-      {
+    char* newBuffer = (char*)malloc((size_t)(*size * 2));
+    if (!newBuffer) {
       return 0;
-      }
-    memcpy(newBuffer, *begin, (size_t)(length)*sizeof(char));
-    if(*begin != local)
-      {
+    }
+    memcpy(newBuffer, *begin, (size_t)(length) * sizeof(char));
+    if (*begin != local) {
       free(*begin);
-      }
+    }
     *begin = newBuffer;
     *end = *begin + length;
     *size *= 2;
-    }
+  }
 
   /* Store the character.  */
   *(*end)++ = c;
@@ -61,47 +48,41 @@ static int kwsysSystem__AppendByte(char* local,
 }
 
 /*--------------------------------------------------------------------------*/
-static int kwsysSystem__AppendArgument(char** local,
-                                       char*** begin, char*** end,
-                                       int* size,
-                                       char* arg_local,
+static int kwsysSystem__AppendArgument(char** local, char*** begin,
+                                       char*** end, int* size, char* arg_local,
                                        char** arg_begin, char** arg_end,
                                        int* arg_size)
 {
   /* Append a null-terminator to the argument string.  */
-  if(!kwsysSystem__AppendByte(arg_local, arg_begin, arg_end, arg_size, '\0'))
-    {
+  if (!kwsysSystem__AppendByte(arg_local, arg_begin, arg_end, arg_size,
+                               '\0')) {
     return 0;
-    }
+  }
 
   /* Allocate space for the argument pointer.  */
-  if((*end - *begin) >= *size)
-    {
+  if ((*end - *begin) >= *size) {
     kwsysSystem_ptrdiff_t length = *end - *begin;
-    char** newPointers = (char**)malloc((size_t)(*size)*2*sizeof(char*));
-    if(!newPointers)
-      {
+    char** newPointers = (char**)malloc((size_t)(*size) * 2 * sizeof(char*));
+    if (!newPointers) {
       return 0;
-      }
-    memcpy(newPointers, *begin, (size_t)(length)*sizeof(char*));
-    if(*begin != local)
-      {
+    }
+    memcpy(newPointers, *begin, (size_t)(length) * sizeof(char*));
+    if (*begin != local) {
       free(*begin);
-      }
+    }
     *begin = newPointers;
     *end = *begin + length;
     *size *= 2;
-    }
+  }
 
   /* Allocate space for the argument string.  */
   **end = (char*)malloc((size_t)(*arg_end - *arg_begin));
-  if(!**end)
-    {
+  if (!**end) {
     return 0;
-    }
+  }
 
   /* Store the argument in the command array.  */
-  memcpy(**end, *arg_begin,(size_t)(*arg_end - *arg_begin));
+  memcpy(**end, *arg_begin, (size_t)(*arg_end - *arg_begin));
   ++(*end);
 
   /* Reset the argument to be empty.  */
@@ -135,150 +116,109 @@ static char** kwsysSystem__ParseUnixCommand(const char* command, int flags)
   int in_single = 0;
   int in_double = 0;
   int failed = 0;
-  for(;*c; ++c)
-    {
-    if(in_escape)
-      {
+  for (; *c; ++c) {
+    if (in_escape) {
       /* This character is escaped so do no special handling.  */
-      if(!in_argument)
-        {
+      if (!in_argument) {
         in_argument = 1;
-        }
-      if(!kwsysSystem__AppendByte(local_buffer, &buffer_begin,
-                                  &buffer_end, &buffer_size, *c))
-        {
+      }
+      if (!kwsysSystem__AppendByte(local_buffer, &buffer_begin, &buffer_end,
+                                   &buffer_size, *c)) {
         failed = 1;
         break;
-        }
-      in_escape = 0;
       }
-    else if(*c == '\\')
-      {
+      in_escape = 0;
+    } else if (*c == '\\') {
       /* The next character should be escaped.  */
       in_escape = 1;
-      }
-    else if(*c == '\'' && !in_double)
-      {
+    } else if (*c == '\'' && !in_double) {
       /* Enter or exit single-quote state.  */
-      if(in_single)
-        {
+      if (in_single) {
         in_single = 0;
-        }
-      else
-        {
+      } else {
         in_single = 1;
-        if(!in_argument)
-          {
+        if (!in_argument) {
           in_argument = 1;
-          }
         }
       }
-    else if(*c == '"' && !in_single)
-      {
+    } else if (*c == '"' && !in_single) {
       /* Enter or exit double-quote state.  */
-      if(in_double)
-        {
+      if (in_double) {
         in_double = 0;
-        }
-      else
-        {
+      } else {
         in_double = 1;
-        if(!in_argument)
-          {
+        if (!in_argument) {
           in_argument = 1;
-          }
         }
       }
-    else if(isspace((unsigned char) *c))
-      {
-      if(in_argument)
-        {
-        if(in_single || in_double)
-          {
+    } else if (isspace((unsigned char)*c)) {
+      if (in_argument) {
+        if (in_single || in_double) {
           /* This space belongs to a quoted argument.  */
-          if(!kwsysSystem__AppendByte(local_buffer, &buffer_begin,
-                                      &buffer_end, &buffer_size, *c))
-            {
+          if (!kwsysSystem__AppendByte(local_buffer, &buffer_begin,
+                                       &buffer_end, &buffer_size, *c)) {
             failed = 1;
             break;
-            }
           }
-        else
-          {
+        } else {
           /* This argument has been terminated by whitespace.  */
-          if(!kwsysSystem__AppendArgument(local_pointers, &pointer_begin,
-                                          &pointer_end, &pointers_size,
-                                          local_buffer, &buffer_begin,
-                                          &buffer_end, &buffer_size))
-            {
+          if (!kwsysSystem__AppendArgument(
+                local_pointers, &pointer_begin, &pointer_end, &pointers_size,
+                local_buffer, &buffer_begin, &buffer_end, &buffer_size)) {
             failed = 1;
             break;
-            }
-          in_argument = 0;
           }
+          in_argument = 0;
         }
       }
-    else
-      {
+    } else {
       /* This character belong to an argument.  */
-      if(!in_argument)
-        {
+      if (!in_argument) {
         in_argument = 1;
-        }
-      if(!kwsysSystem__AppendByte(local_buffer, &buffer_begin,
-                                  &buffer_end, &buffer_size, *c))
-        {
+      }
+      if (!kwsysSystem__AppendByte(local_buffer, &buffer_begin, &buffer_end,
+                                   &buffer_size, *c)) {
         failed = 1;
         break;
-        }
       }
     }
+  }
 
   /* Finish the last argument.  */
-  if(in_argument)
-    {
-    if(!kwsysSystem__AppendArgument(local_pointers, &pointer_begin,
-                                    &pointer_end, &pointers_size,
-                                    local_buffer, &buffer_begin,
-                                    &buffer_end, &buffer_size))
-      {
+  if (in_argument) {
+    if (!kwsysSystem__AppendArgument(
+          local_pointers, &pointer_begin, &pointer_end, &pointers_size,
+          local_buffer, &buffer_begin, &buffer_end, &buffer_size)) {
       failed = 1;
-      }
     }
+  }
 
   /* If we still have memory allocate space for the new command
      buffer.  */
-  if(!failed)
-    {
+  if (!failed) {
     kwsysSystem_ptrdiff_t n = pointer_end - pointer_begin;
-    newCommand = (char**)malloc((size_t)(n+1)*sizeof(char*));
-    }
+    newCommand = (char**)malloc((size_t)(n + 1) * sizeof(char*));
+  }
 
-  if(newCommand)
-    {
+  if (newCommand) {
     /* Copy the arguments into the new command buffer.  */
     kwsysSystem_ptrdiff_t n = pointer_end - pointer_begin;
-    memcpy(newCommand, pointer_begin, sizeof(char*)*(size_t)(n));
+    memcpy(newCommand, pointer_begin, sizeof(char*) * (size_t)(n));
     newCommand[n] = 0;
-    }
-  else
-    {
+  } else {
     /* Free arguments already allocated.  */
-    while(pointer_end != pointer_begin)
-      {
+    while (pointer_end != pointer_begin) {
       free(*(--pointer_end));
-      }
     }
+  }
 
   /* Free temporary buffers.  */
-  if(pointer_begin != local_pointers)
-    {
+  if (pointer_begin != local_pointers) {
     free(pointer_begin);
-    }
-  if(buffer_begin != local_buffer)
-    {
+  }
+  if (buffer_begin != local_buffer) {
     free(buffer_begin);
-    }
+  }
 
   /* The flags argument is currently unused.  */
   (void)flags;
@@ -291,10 +231,9 @@ static char** kwsysSystem__ParseUnixCommand(const char* command, int flags)
 char** kwsysSystem_Parse_CommandForUnix(const char* command, int flags)
 {
   /* Validate the flags.  */
-  if(flags != 0)
-    {
+  if (flags != 0) {
     return 0;
-    }
+  }
 
   /* Forward to our internal implementation.  */
   return kwsysSystem__ParseUnixCommand(command, flags);
diff --git a/Source/kwsys/System.h.in b/Source/kwsys/System.h.in
index 3f3d3f4..102974d 100644
--- a/Source/kwsys/System.h.in
+++ b/Source/kwsys/System.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _System_h
 #define @KWSYS_NAMESPACE at _System_h
 
@@ -19,16 +10,15 @@
    not visible to user code.  Use kwsysHeaderDump.pl to reproduce
    these macros after making changes to the interface.  */
 #if !defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
 #endif
 #if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-# define kwsysSystem_Parse_CommandForUnix             kwsys_ns(System_Parse_CommandForUnix)
+#define kwsysSystem_Parse_CommandForUnix kwsys_ns(System_Parse_CommandForUnix)
 #endif
 
 #if defined(__cplusplus)
-extern "C"
-{
+extern "C" {
 #endif
 
 /**
@@ -59,11 +49,11 @@ kwsysEXPORT char** kwsysSystem_Parse_CommandForUnix(const char* command,
 /* If we are building a kwsys .c or .cxx file, let it use these macros.
    Otherwise, undefine them to keep the namespace clean.  */
 #if !defined(KWSYS_NAMESPACE)
-# undef kwsys_ns
-# undef kwsysEXPORT
-# if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-#  undef kwsysSystem_Parse_CommandForUnix
-# endif
+#undef kwsys_ns
+#undef kwsysEXPORT
+#if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
+#undef kwsysSystem_Parse_CommandForUnix
+#endif
 #endif
 
 #endif
diff --git a/Source/kwsys/SystemInformation.cxx b/Source/kwsys/SystemInformation.cxx
index 56a635a..e01dcd7 100644
--- a/Source/kwsys/SystemInformation.cxx
+++ b/Source/kwsys/SystemInformation.cxx
@@ -1,25 +1,15 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #if defined(_WIN32)
-# define NOMINMAX // use our min,max
-# if !defined(_WIN32_WINNT) && !(defined(_MSC_VER) && _MSC_VER < 1300)
-#  define _WIN32_WINNT 0x0501
-# endif
-# include <winsock.h> // WSADATA, include before sys/types.h
+#define NOMINMAX // use our min,max
+#if !defined(_WIN32_WINNT) && !(defined(_MSC_VER) && _MSC_VER < 1300)
+#define _WIN32_WINNT 0x0501
+#endif
+#include <winsock.h> // WSADATA, include before sys/types.h
 #endif
 
 #if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
-# define _GNU_SOURCE
+#define _GNU_SOURCE
 #endif
 
 // TODO:
@@ -41,157 +31,163 @@
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "SystemInformation.hxx.in"
-# include "Process.h.in"
+#include "Process.h.in"
+#include "SystemInformation.hxx.in"
 #endif
 
+#include <fstream>
 #include <iostream>
 #include <sstream>
-#include <fstream>
 #include <string>
 #include <vector>
 
 #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>
-# endif
-# if !defined(siginfo_t)
+#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>
+#endif
+#if !defined(siginfo_t)
 typedef int siginfo_t;
-# endif
+#endif
 #else
-# include <sys/types.h>
-# include <sys/time.h>
-# include <sys/utsname.h> // int uname(struct utsname *buf);
-# include <sys/resource.h> // getrlimit
-# include <unistd.h>
-# include <signal.h>
-# include <fcntl.h>
-# include <errno.h> // extern int errno;
+#include <sys/types.h>
+
+#include <errno.h> // extern int errno;
+#include <fcntl.h>
+#include <signal.h>
+#include <sys/resource.h> // getrlimit
+#include <sys/time.h>
+#include <sys/utsname.h> // int uname(struct utsname *buf);
+#include <unistd.h>
 #endif
 
-#if defined (__CYGWIN__) && !defined(_WIN32)
-# include <windows.h>
-# undef _WIN32
+#if defined(__CYGWIN__) && !defined(_WIN32)
+#include <windows.h>
+#undef _WIN32
 #endif
 
-#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
-# include <sys/param.h>
-# include <sys/sysctl.h>
-# include <sys/socket.h>
-# include <netdb.h>
-# include <netinet/in.h>
-# if defined(KWSYS_SYS_HAS_IFADDRS_H)
-#  include <ifaddrs.h>
-#  define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
-# endif
+#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) ||    \
+  defined(__DragonFly__)
+#include <netdb.h>
+#include <netinet/in.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <sys/sysctl.h>
+#if defined(KWSYS_SYS_HAS_IFADDRS_H)
+#include <ifaddrs.h>
+#include <net/if.h>
+#define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
+#endif
 #endif
 
 #if defined(KWSYS_SYS_HAS_MACHINE_CPU_H)
-# include <machine/cpu.h>
+#include <machine/cpu.h>
 #endif
 
 #ifdef __APPLE__
-# include <sys/sysctl.h>
-# include <mach/vm_statistics.h>
-# include <mach/host_info.h>
-# include <mach/mach.h>
-# include <mach/mach_types.h>
-# include <fenv.h>
-# include <sys/socket.h>
-# include <netdb.h>
-# include <netinet/in.h>
-# if defined(KWSYS_SYS_HAS_IFADDRS_H)
-#  include <ifaddrs.h>
-#  define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
-# endif
-# if !(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__-0 >= 1050)
-#  undef KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE
-# endif
-#endif
-
-#if defined(__linux) || defined (__sun) || defined(_SCO_DS)
-# include <fenv.h>
-# include <sys/socket.h>
-# include <netdb.h>
-# include <netinet/in.h>
-# if defined(KWSYS_SYS_HAS_IFADDRS_H)
-#  include <ifaddrs.h>
-#  if !defined(__LSB_VERSION__) /* LSB has no getifaddrs */
-#   define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
-#  endif
-# endif
-# if defined(KWSYS_CXX_HAS_RLIMIT64)
+#include <fenv.h>
+#include <mach/host_info.h>
+#include <mach/mach.h>
+#include <mach/mach_types.h>
+#include <mach/vm_statistics.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <sys/socket.h>
+#include <sys/sysctl.h>
+#if defined(KWSYS_SYS_HAS_IFADDRS_H)
+#include <ifaddrs.h>
+#include <net/if.h>
+#define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
+#endif
+#if !(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ - 0 >= 1050)
+#undef KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE
+#endif
+#endif
+
+#if defined(__linux) || defined(__sun) || defined(_SCO_DS)
+#include <fenv.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <sys/socket.h>
+#if defined(KWSYS_SYS_HAS_IFADDRS_H)
+#include <ifaddrs.h>
+#include <net/if.h>
+#if !defined(__LSB_VERSION__) /* LSB has no getifaddrs */
+#define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
+#endif
+#endif
+#if defined(KWSYS_CXX_HAS_RLIMIT64)
 typedef struct rlimit64 ResourceLimitType;
-#  define GetResourceLimit getrlimit64
-# else
+#define GetResourceLimit getrlimit64
+#else
 typedef struct rlimit ResourceLimitType;
-#  define GetResourceLimit getrlimit
-# endif
-#elif defined( __hpux )
-# include <sys/param.h>
-# include <sys/pstat.h>
-# if defined(KWSYS_SYS_HAS_MPCTL_H)
-#  include <sys/mpctl.h>
-# endif
+#define GetResourceLimit getrlimit
+#endif
+#elif defined(__hpux)
+#include <sys/param.h>
+#include <sys/pstat.h>
+#if defined(KWSYS_SYS_HAS_MPCTL_H)
+#include <sys/mpctl.h>
+#endif
 #endif
 
 #ifdef __HAIKU__
-# include <OS.h>
+#include <OS.h>
 #endif
 
 #if defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
-# include <execinfo.h>
-# if defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
-#  include <cxxabi.h>
-# endif
-# if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
-#  include <dlfcn.h>
-# endif
+#include <execinfo.h>
+#if defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
+#include <cxxabi.h>
+#endif
+#if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
+#include <dlfcn.h>
+#endif
 #else
-# undef KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE
-# undef KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP
+#undef KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE
+#undef KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP
 #endif
 
+#include <ctype.h> // int isdigit(int c);
 #include <memory.h>
-#include <stdlib.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <string.h>
-#include <ctype.h> // int isdigit(int c);
 
 #if defined(KWSYS_USE_LONG_LONG)
-# if defined(KWSYS_IOS_HAS_OSTREAM_LONG_LONG)
-#  define iostreamLongLong(x) (x)
-# else
-#  define iostreamLongLong(x) ((long)(x))
-# endif
+#if defined(KWSYS_IOS_HAS_OSTREAM_LONG_LONG)
+#define iostreamLongLong(x) (x)
+#else
+#define iostreamLongLong(x) ((long)(x))
+#endif
 #elif defined(KWSYS_USE___INT64)
-# if defined(KWSYS_IOS_HAS_OSTREAM___INT64)
-#  define iostreamLongLong(x) (x)
-# else
-#  define iostreamLongLong(x) ((long)(x))
-# endif
+#if defined(KWSYS_IOS_HAS_OSTREAM___INT64)
+#define iostreamLongLong(x) (x)
+#else
+#define iostreamLongLong(x) ((long)(x))
+#endif
 #else
-# error "No Long Long"
+#error "No Long Long"
 #endif
 
 #if defined(KWSYS_CXX_HAS_ATOLL)
-# define atoLongLong atoll
+#define atoLongLong atoll
 #else
-# if defined(KWSYS_CXX_HAS__ATOI64)
-#  define atoLongLong _atoi64
-# elif defined(KWSYS_CXX_HAS_ATOL)
-#  define atoLongLong atol
-# else
-#  define atoLongLong atoi
-# endif
+#if defined(KWSYS_CXX_HAS__ATOI64)
+#define atoLongLong _atoi64
+#elif defined(KWSYS_CXX_HAS_ATOL)
+#define atoLongLong atol
+#else
+#define atoLongLong atoi
+#endif
 #endif
 
-#if defined(_MSC_VER) && (_MSC_VER >= 1300) && !defined(_WIN64) && !defined(__clang__)
+#if defined(_MSC_VER) && (_MSC_VER >= 1300) && !defined(_WIN64) &&            \
+  !defined(__clang__)
 #define USE_ASM_INSTRUCTIONS 1
 #else
 #define USE_ASM_INSTRUCTIONS 0
@@ -204,10 +200,11 @@ typedef struct rlimit ResourceLimitType;
 #define USE_CPUID_INTRINSICS 0
 #endif
 
-#if USE_ASM_INSTRUCTIONS || USE_CPUID_INTRINSICS || defined(KWSYS_CXX_HAS_BORLAND_ASM_CPUID)
-# define USE_CPUID 1
+#if USE_ASM_INSTRUCTIONS || USE_CPUID_INTRINSICS ||                           \
+  defined(KWSYS_CXX_HAS_BORLAND_ASM_CPUID)
+#define USE_CPUID 1
 #else
-# define USE_CPUID 0
+#define USE_CPUID 0
 #endif
 
 #if USE_CPUID
@@ -258,14 +255,12 @@ static bool call_cpuid(int select, int result[4])
       pop ebx
       pop eax
 #endif
-      }
     }
-  __except(1)
-    {
+  } __except (1) {
     return false;
-    }
+  }
 
-    memcpy(result, tmp, sizeof(tmp));
+  memcpy(result, tmp, sizeof(tmp));
 #elif defined(KWSYS_CXX_HAS_BORLAND_ASM_CPUID)
   unsigned int a, b, c, d;
   __asm {
@@ -289,33 +284,36 @@ static bool call_cpuid(int select, int result[4])
 }
 #endif
 
-
-namespace KWSYS_NAMESPACE
+namespace KWSYS_NAMESPACE {
+template <typename T>
+T min(T a, T b)
 {
-template<typename T>
-T min(T a, T b){ return a<b ? a : b; }
+  return a < b ? a : b;
+}
 
-extern "C" { typedef void (*SigAction)(int,siginfo_t*,void*); }
+extern "C" {
+typedef void (*SigAction)(int, siginfo_t*, void*);
+}
 
 //  Define SystemInformationImplementation class
-typedef  void (*DELAY_FUNC)(unsigned int uiMS);
+typedef void (*DELAY_FUNC)(unsigned int uiMS);
 
 class SystemInformationImplementation
 {
 public:
   typedef SystemInformation::LongLong LongLong;
-  SystemInformationImplementation ();
-  ~SystemInformationImplementation ();
+  SystemInformationImplementation();
+  ~SystemInformationImplementation();
 
-  const char * GetVendorString();
-  const char * GetVendorID();
+  const char* GetVendorString();
+  const char* GetVendorID();
   std::string GetTypeID();
   std::string GetFamilyID();
   std::string GetModelID();
   std::string GetModelName();
   std::string GetSteppingCode();
-  const char * GetExtendedProcessorName();
-  const char * GetProcessorSerialNumber();
+  const char* GetExtendedProcessorName();
+  const char* GetProcessorSerialNumber();
   int GetProcessorCacheSize();
   unsigned int GetLogicalProcessorsPerPhysical();
   float GetProcessorClockFrequency();
@@ -323,12 +321,12 @@ public:
   int GetProcessorCacheXSize(long int);
   bool DoesCPUSupportFeature(long int);
 
-  const char * GetOSName();
-  const char * GetHostname();
-  int GetFullyQualifiedDomainName(std::string &fqdn);
-  const char * GetOSRelease();
-  const char * GetOSVersion();
-  const char * GetOSPlatform();
+  const char* GetOSName();
+  const char* GetHostname();
+  int GetFullyQualifiedDomainName(std::string& fqdn);
+  const char* GetOSRelease();
+  const char* GetOSVersion();
+  const char* GetOSPlatform();
 
   bool Is64Bits();
 
@@ -347,23 +345,20 @@ public:
 
   // Retrieve memory information in kib
   LongLong GetHostMemoryTotal();
-  LongLong GetHostMemoryAvailable(const char *envVarName);
+  LongLong GetHostMemoryAvailable(const char* envVarName);
   LongLong GetHostMemoryUsed();
 
-  LongLong GetProcMemoryAvailable(
-        const char *hostLimitEnvVarName,
-        const char *procLimitEnvVarName);
+  LongLong GetProcMemoryAvailable(const char* hostLimitEnvVarName,
+                                  const char* procLimitEnvVarName);
   LongLong GetProcMemoryUsed();
 
   double GetLoadAverage();
 
   // enable/disable stack trace signal handler.
-  static
-  void SetStackTraceOnError(int enable);
+  static void SetStackTraceOnError(int enable);
 
   // get current stack
-  static
-  std::string GetProgramStack(int firstFrame, int wholePath);
+  static std::string GetProgramStack(int firstFrame, int wholePath);
 
   /** Run the different checks */
   void RunCPUCheck();
@@ -372,7 +367,7 @@ public:
 
 public:
   typedef struct tagID
-    {
+  {
     int Type;
     int Family;
     int Model;
@@ -383,17 +378,17 @@ public:
     std::string Vendor;
     std::string SerialNumber;
     std::string ModelName;
-    } ID;
+  } ID;
 
   typedef struct tagCPUPowerManagement
-    {
+  {
     bool HasVoltageID;
     bool HasFrequencyID;
     bool HasTempSenseDiode;
-    } CPUPowerManagement;
+  } CPUPowerManagement;
 
   typedef struct tagCPUExtendedFeatures
-    {
+  {
     bool Has3DNow;
     bool Has3DNowPlus;
     bool SupportsMP;
@@ -403,10 +398,10 @@ public:
     unsigned int LogicalProcessorsPerPhysical;
     int APIC_ID;
     CPUPowerManagement PowerManagement;
-    } CPUExtendedFeatures;
+  } CPUExtendedFeatures;
 
   typedef struct CPUtagFeatures
-    {
+  {
     bool HasFPU;
     bool HasTSC;
     bool HasMMX;
@@ -425,13 +420,25 @@ public:
     int L2CacheSize;
     int L3CacheSize;
     CPUExtendedFeatures ExtendedFeatures;
-    } CPUFeatures;
+  } CPUFeatures;
 
   enum Manufacturer
-    {
-    AMD, Intel, NSC, UMC, Cyrix, NexGen, IDT, Rise, Transmeta, Sun, IBM,
-    Motorola, HP, UnknownManufacturer
-    };
+  {
+    AMD,
+    Intel,
+    NSC,
+    UMC,
+    Cyrix,
+    NexGen,
+    IDT,
+    Rise,
+    Transmeta,
+    Sun,
+    IBM,
+    Motorola,
+    HP,
+    UnknownManufacturer
+  };
 
 protected:
   // For windows
@@ -449,12 +456,12 @@ protected:
   bool RetrieveExtendedCPUIdentity();
 
   // Processor information
-  Manufacturer  ChipManufacturer;
-  CPUFeatures   Features;
-  ID            ChipID;
-  float         CPUSpeedInMHz;
-  unsigned int  NumberOfLogicalCPU;
-  unsigned int  NumberOfPhysicalCPU;
+  Manufacturer ChipManufacturer;
+  CPUFeatures Features;
+  ID ChipID;
+  float CPUSpeedInMHz;
+  unsigned int NumberOfLogicalCPU;
+  unsigned int NumberOfPhysicalCPU;
 
   int CPUCount(); // For windows
   unsigned char LogicalCPUPerPhysicalCPU();
@@ -464,20 +471,20 @@ protected:
 
   // For Linux and Cygwin, /proc/cpuinfo formats are slightly different
   bool RetreiveInformationFromCpuInfoFile();
-  std::string ExtractValueFromCpuInfoFile(std::string buffer,
-                                          const char* word, size_t init=0);
+  std::string ExtractValueFromCpuInfoFile(std::string buffer, const char* word,
+                                          size_t init = 0);
 
   bool QueryLinuxMemory();
   bool QueryCygwinMemory();
 
-  static void Delay (unsigned int);
-  static void DelayOverhead (unsigned int);
+  static void Delay(unsigned int);
+  static void DelayOverhead(unsigned int);
 
-  void FindManufacturer(const std::string &family = "");
+  void FindManufacturer(const std::string& family = "");
 
   // For Mac
   bool ParseSysCtl();
-  int CallSwVers(const char *arg, std::string &ver);
+  int CallSwVers(const char* arg, std::string& ver);
   void TrimNewline(std::string&);
   std::string ExtractValueFromSysCtl(const char* word);
   std::string SysCtlBuffer;
@@ -488,25 +495,25 @@ protected:
   std::string ParseValueFromKStat(const char* arguments);
   std::string RunProcess(std::vector<const char*> args);
 
-  //For Haiku OS
+  // For Haiku OS
   bool QueryHaikuInfo();
 
-  //For QNX
+  // For QNX
   bool QueryQNXMemory();
   bool QueryQNXProcessor();
 
-  //For OpenBSD, FreeBSD, NetBSD, DragonFly
+  // For OpenBSD, FreeBSD, NetBSD, DragonFly
   bool QueryBSDMemory();
   bool QueryBSDProcessor();
 
-  //For HP-UX
+  // For HP-UX
   bool QueryHPUXMemory();
   bool QueryHPUXProcessor();
 
-  //For Microsoft Windows
+  // For Microsoft Windows
   bool QueryWindowsMemory();
 
-  //For AIX
+  // For AIX
   bool QueryAIXMemory();
 
   bool QueryProcessorBySysconf();
@@ -531,7 +538,6 @@ protected:
   std::string OSPlatform;
 };
 
-
 SystemInformation::SystemInformation()
 {
   this->Implementation = new SystemInformationImplementation;
@@ -542,12 +548,12 @@ SystemInformation::~SystemInformation()
   delete this->Implementation;
 }
 
-const char * SystemInformation::GetVendorString()
+const char* SystemInformation::GetVendorString()
 {
   return this->Implementation->GetVendorString();
 }
 
-const char * SystemInformation::GetVendorID()
+const char* SystemInformation::GetVendorID()
 {
   return this->Implementation->GetVendorID();
 }
@@ -577,12 +583,12 @@ std::string SystemInformation::GetSteppingCode()
   return this->Implementation->GetSteppingCode();
 }
 
-const char * SystemInformation::GetExtendedProcessorName()
+const char* SystemInformation::GetExtendedProcessorName()
 {
   return this->Implementation->GetExtendedProcessorName();
 }
 
-const char * SystemInformation::GetProcessorSerialNumber()
+const char* SystemInformation::GetProcessorSerialNumber()
 {
   return this->Implementation->GetProcessorSerialNumber();
 }
@@ -620,40 +626,30 @@ bool SystemInformation::DoesCPUSupportFeature(long int i)
 std::string SystemInformation::GetCPUDescription()
 {
   std::ostringstream oss;
-  oss
-    << this->GetNumberOfPhysicalCPU()
-    << " core ";
-  if (this->GetModelName().empty())
-    {
-    oss
-      << this->GetProcessorClockFrequency()
-      << " MHz "
-      << this->GetVendorString()
-      << " "
-      << this->GetExtendedProcessorName();
-    }
-  else
-    {
+  oss << this->GetNumberOfPhysicalCPU() << " core ";
+  if (this->GetModelName().empty()) {
+    oss << this->GetProcessorClockFrequency() << " MHz "
+        << this->GetVendorString() << " " << this->GetExtendedProcessorName();
+  } else {
     oss << this->GetModelName();
-    }
+  }
 
   // remove extra spaces
-  std::string tmp=oss.str();
+  std::string tmp = oss.str();
   size_t pos;
-  while( (pos=tmp.find("  "))!=std::string::npos)
-    {
-    tmp.replace(pos,2," ");
-    }
+  while ((pos = tmp.find("  ")) != std::string::npos) {
+    tmp.replace(pos, 2, " ");
+  }
 
   return tmp;
 }
 
-const char * SystemInformation::GetOSName()
+const char* SystemInformation::GetOSName()
 {
   return this->Implementation->GetOSName();
 }
 
-const char * SystemInformation::GetHostname()
+const char* SystemInformation::GetHostname()
 {
   return this->Implementation->GetHostname();
 }
@@ -665,17 +661,17 @@ std::string SystemInformation::GetFullyQualifiedDomainName()
   return fqdn;
 }
 
-const char * SystemInformation::GetOSRelease()
+const char* SystemInformation::GetOSRelease()
 {
   return this->Implementation->GetOSRelease();
 }
 
-const char * SystemInformation::GetOSVersion()
+const char* SystemInformation::GetOSVersion()
 {
   return this->Implementation->GetOSVersion();
 }
 
-const char * SystemInformation::GetOSPlatform()
+const char* SystemInformation::GetOSPlatform()
 {
   return this->Implementation->GetOSPlatform();
 }
@@ -710,12 +706,8 @@ int SystemInformation::GetOSIsApple()
 std::string SystemInformation::GetOSDescription()
 {
   std::ostringstream oss;
-  oss
-    << this->GetOSName()
-    << " "
-    << this->GetOSRelease()
-    << " "
-    << this->GetOSVersion();
+  oss << this->GetOSName() << " " << this->GetOSRelease() << " "
+      << this->GetOSVersion();
 
   return oss.str();
 }
@@ -762,19 +754,16 @@ size_t SystemInformation::GetAvailablePhysicalMemory()
 }
 
 std::string SystemInformation::GetMemoryDescription(
-      const char *hostLimitEnvVarName,
-      const char *procLimitEnvVarName)
+  const char* hostLimitEnvVarName, const char* procLimitEnvVarName)
 {
   std::ostringstream oss;
-  oss
-    << "Host Total: "
-    << iostreamLongLong(this->GetHostMemoryTotal())
-    << " KiB, Host Available: "
-    << iostreamLongLong(this->GetHostMemoryAvailable(hostLimitEnvVarName))
-    << " KiB, Process Available: "
-    << iostreamLongLong(
-         this->GetProcMemoryAvailable(hostLimitEnvVarName,procLimitEnvVarName))
-    << " KiB";
+  oss << "Host Total: " << iostreamLongLong(this->GetHostMemoryTotal())
+      << " KiB, Host Available: "
+      << iostreamLongLong(this->GetHostMemoryAvailable(hostLimitEnvVarName))
+      << " KiB, Process Available: "
+      << iostreamLongLong(this->GetProcMemoryAvailable(hostLimitEnvVarName,
+                                                       procLimitEnvVarName))
+      << " KiB";
   return oss.str();
 }
 
@@ -784,8 +773,8 @@ SystemInformation::LongLong SystemInformation::GetHostMemoryTotal()
   return this->Implementation->GetHostMemoryTotal();
 }
 
-SystemInformation::LongLong
-SystemInformation::GetHostMemoryAvailable(const char *hostLimitEnvVarName)
+SystemInformation::LongLong SystemInformation::GetHostMemoryAvailable(
+  const char* hostLimitEnvVarName)
 {
   return this->Implementation->GetHostMemoryAvailable(hostLimitEnvVarName);
 }
@@ -796,14 +785,11 @@ SystemInformation::LongLong SystemInformation::GetHostMemoryUsed()
 }
 
 // process memory info in units of KiB.
-SystemInformation::LongLong
-SystemInformation::GetProcMemoryAvailable(
-        const char *hostLimitEnvVarName,
-        const char *procLimitEnvVarName)
+SystemInformation::LongLong SystemInformation::GetProcMemoryAvailable(
+  const char* hostLimitEnvVarName, const char* procLimitEnvVarName)
 {
-  return this->Implementation->GetProcMemoryAvailable(
-          hostLimitEnvVarName,
-          procLimitEnvVarName);
+  return this->Implementation->GetProcMemoryAvailable(hostLimitEnvVarName,
+                                                      procLimitEnvVarName);
 }
 
 SystemInformation::LongLong SystemInformation::GetProcMemoryUsed()
@@ -828,7 +814,8 @@ void SystemInformation::SetStackTraceOnError(int enable)
 
 std::string SystemInformation::GetProgramStack(int firstFrame, int wholePath)
 {
-  return SystemInformationImplementation::GetProgramStack(firstFrame, wholePath);
+  return SystemInformationImplementation::GetProgramStack(firstFrame,
+                                                          wholePath);
 }
 
 /** Run the different checks */
@@ -847,60 +834,59 @@ void SystemInformation::RunMemoryCheck()
   this->Implementation->RunMemoryCheck();
 }
 
-
 // --------------------------------------------------------------
 // SystemInformationImplementation starts here
 
-#define STORE_TLBCACHE_INFO(x,y)  x = (x < (y)) ? (y) : x
-#define TLBCACHE_INFO_UNITS      (15)
-#define CLASSICAL_CPU_FREQ_LOOP    10000000
-#define RDTSC_INSTRUCTION      _asm _emit 0x0f _asm _emit 0x31
+#define STORE_TLBCACHE_INFO(x, y) x = (x < (y)) ? (y) : x
+#define TLBCACHE_INFO_UNITS (15)
+#define CLASSICAL_CPU_FREQ_LOOP 10000000
+#define RDTSC_INSTRUCTION _asm _emit 0x0f _asm _emit 0x31
 
-#define MMX_FEATURE            0x00000001
-#define MMX_PLUS_FEATURE       0x00000002
-#define SSE_FEATURE            0x00000004
-#define SSE2_FEATURE           0x00000008
-#define AMD_3DNOW_FEATURE      0x00000010
+#define MMX_FEATURE 0x00000001
+#define MMX_PLUS_FEATURE 0x00000002
+#define SSE_FEATURE 0x00000004
+#define SSE2_FEATURE 0x00000008
+#define AMD_3DNOW_FEATURE 0x00000010
 #define AMD_3DNOW_PLUS_FEATURE 0x00000020
-#define IA64_FEATURE           0x00000040
-#define MP_CAPABLE             0x00000080
-#define HYPERTHREAD_FEATURE    0x00000100
-#define SERIALNUMBER_FEATURE   0x00000200
-#define APIC_FEATURE           0x00000400
-#define SSE_FP_FEATURE         0x00000800
-#define SSE_MMX_FEATURE        0x00001000
-#define CMOV_FEATURE           0x00002000
-#define MTRR_FEATURE           0x00004000
-#define L1CACHE_FEATURE        0x00008000
-#define L2CACHE_FEATURE        0x00010000
-#define L3CACHE_FEATURE        0x00020000
-#define ACPI_FEATURE           0x00040000
+#define IA64_FEATURE 0x00000040
+#define MP_CAPABLE 0x00000080
+#define HYPERTHREAD_FEATURE 0x00000100
+#define SERIALNUMBER_FEATURE 0x00000200
+#define APIC_FEATURE 0x00000400
+#define SSE_FP_FEATURE 0x00000800
+#define SSE_MMX_FEATURE 0x00001000
+#define CMOV_FEATURE 0x00002000
+#define MTRR_FEATURE 0x00004000
+#define L1CACHE_FEATURE 0x00008000
+#define L2CACHE_FEATURE 0x00010000
+#define L3CACHE_FEATURE 0x00020000
+#define ACPI_FEATURE 0x00040000
 #define THERMALMONITOR_FEATURE 0x00080000
 #define TEMPSENSEDIODE_FEATURE 0x00100000
-#define FREQUENCYID_FEATURE    0x00200000
-#define VOLTAGEID_FREQUENCY    0x00400000
+#define FREQUENCYID_FEATURE 0x00200000
+#define VOLTAGEID_FREQUENCY 0x00400000
 
 // Status Flag
-#define HT_NOT_CAPABLE           0
-#define HT_ENABLED               1
-#define HT_DISABLED              2
+#define HT_NOT_CAPABLE 0
+#define HT_ENABLED 1
+#define HT_DISABLED 2
 #define HT_SUPPORTED_NOT_ENABLED 3
-#define HT_CANNOT_DETECT         4
+#define HT_CANNOT_DETECT 4
 
 // EDX[28]  Bit 28 is set if HT is supported
-#define HT_BIT             0x10000000
+#define HT_BIT 0x10000000
 
 // EAX[11:8] Bit 8-11 contains family processor ID.
-#define FAMILY_ID          0x0F00
-#define PENTIUM4_ID        0x0F00
+#define FAMILY_ID 0x0F00
+#define PENTIUM4_ID 0x0F00
 // EAX[23:20] Bit 20-23 contains extended family processor ID
-#define EXT_FAMILY_ID      0x0F00000
+#define EXT_FAMILY_ID 0x0F00000
 // EBX[23:16] Bit 16-23 in ebx contains the number of logical
-#define NUM_LOGICAL_BITS   0x00FF0000
+#define NUM_LOGICAL_BITS 0x00FF0000
 // processors per physical processor when execute cpuid with
 // eax set to 1
 // EBX[31:24] Bits 24-31 (8 bits) return the 8-bit unique
-#define INITIAL_APIC_ID_BITS  0xFF000000
+#define INITIAL_APIC_ID_BITS 0xFF000000
 // initial APIC ID for the processor this code is running on.
 // Default value = 0xff if HT is not supported
 
@@ -908,174 +894,142 @@ void SystemInformation::RunMemoryCheck()
 namespace {
 // *****************************************************************************
 #if defined(__linux) || defined(__APPLE__)
-int LoadLines(
-      FILE *file,
-      std::vector<std::string> &lines)
+int LoadLines(FILE* file, std::vector<std::string>& lines)
 {
   // Load each line in the given file into a the vector.
-  int nRead=0;
-  const int bufSize=1024;
-  char buf[bufSize]={'\0'};
-  while (!feof(file) && !ferror(file))
-    {
-    errno=0;
-    if (fgets(buf,bufSize,file) == 0)
-      {
-      if (ferror(file) && (errno==EINTR))
-        {
+  int nRead = 0;
+  const int bufSize = 1024;
+  char buf[bufSize] = { '\0' };
+  while (!feof(file) && !ferror(file)) {
+    errno = 0;
+    if (fgets(buf, bufSize, file) == 0) {
+      if (ferror(file) && (errno == EINTR)) {
         clearerr(file);
-        }
-      continue;
-      }
-    char *pBuf=buf;
-    while(*pBuf)
-      {
-      if (*pBuf=='\n') *pBuf='\0';
-      pBuf+=1;
       }
+      continue;
+    }
+    char* pBuf = buf;
+    while (*pBuf) {
+      if (*pBuf == '\n')
+        *pBuf = '\0';
+      pBuf += 1;
+    }
     lines.push_back(buf);
     ++nRead;
-    }
-  if (ferror(file))
-    {
+  }
+  if (ferror(file)) {
     return 0;
-    }
+  }
   return nRead;
 }
 
-# if defined(__linux)
+#if defined(__linux)
 // *****************************************************************************
-int LoadLines(
-      const char *fileName,
-      std::vector<std::string> &lines)
+int LoadLines(const char* fileName, std::vector<std::string>& lines)
 {
-  FILE *file=fopen(fileName,"r");
-  if (file==0)
-    {
+  FILE* file = fopen(fileName, "r");
+  if (file == 0) {
     return 0;
-    }
-  int nRead=LoadLines(file,lines);
+  }
+  int nRead = LoadLines(file, lines);
   fclose(file);
   return nRead;
 }
-# endif
+#endif
 
 // ****************************************************************************
-template<typename T>
-int NameValue(
-      std::vector<std::string> &lines,
-      std::string name, T &value)
+template <typename T>
+int NameValue(std::vector<std::string>& lines, std::string name, T& value)
 {
-  size_t nLines=lines.size();
-  for (size_t i=0; i<nLines; ++i)
-    {
-    size_t at=lines[i].find(name);
-    if (at==std::string::npos)
-      {
+  size_t nLines = lines.size();
+  for (size_t i = 0; i < nLines; ++i) {
+    size_t at = lines[i].find(name);
+    if (at == std::string::npos) {
       continue;
-      }
-    std::istringstream is(lines[i].substr(at+name.size()));
+    }
+    std::istringstream is(lines[i].substr(at + name.size()));
     is >> value;
     return 0;
-    }
+  }
   return -1;
 }
 #endif
 
 #if defined(__linux)
 // ****************************************************************************
-template<typename T>
-int GetFieldsFromFile(
-      const char *fileName,
-      const char **fieldNames,
-      T *values)
+template <typename T>
+int GetFieldsFromFile(const char* fileName, const char** fieldNames, T* values)
 {
   std::vector<std::string> fields;
-  if (!LoadLines(fileName,fields))
-    {
+  if (!LoadLines(fileName, fields)) {
     return -1;
+  }
+  int i = 0;
+  while (fieldNames[i] != NULL) {
+    int ierr = NameValue(fields, fieldNames[i], values[i]);
+    if (ierr) {
+      return -(i + 2);
     }
-  int i=0;
-  while (fieldNames[i]!=NULL)
-    {
-    int ierr=NameValue(fields,fieldNames[i],values[i]);
-    if (ierr)
-      {
-      return -(i+2);
-      }
-    i+=1;
-    }
+    i += 1;
+  }
   return 0;
 }
 
 // ****************************************************************************
-template<typename T>
-int GetFieldFromFile(
-      const char *fileName,
-      const char *fieldName,
-      T &value)
-{
-  const char *fieldNames[2]={fieldName,NULL};
-  T values[1]={T(0)};
-  int ierr=GetFieldsFromFile(fileName,fieldNames,values);
-  if (ierr)
-    {
+template <typename T>
+int GetFieldFromFile(const char* fileName, const char* fieldName, T& value)
+{
+  const char* fieldNames[2] = { fieldName, NULL };
+  T values[1] = { T(0) };
+  int ierr = GetFieldsFromFile(fileName, fieldNames, values);
+  if (ierr) {
     return ierr;
-    }
-  value=values[0];
+  }
+  value = values[0];
   return 0;
 }
 #endif
 
 // ****************************************************************************
 #if defined(__APPLE__)
-template<typename T>
-int GetFieldsFromCommand(
-      const char *command,
-      const char **fieldNames,
-      T *values)
-{
-  FILE *file=popen(command,"r");
-  if (file==0)
-    {
+template <typename T>
+int GetFieldsFromCommand(const char* command, const char** fieldNames,
+                         T* values)
+{
+  FILE* file = popen(command, "r");
+  if (file == 0) {
     return -1;
-    }
+  }
   std::vector<std::string> fields;
-  int nl=LoadLines(file,fields);
+  int nl = LoadLines(file, fields);
   pclose(file);
-  if (nl==0)
-    {
+  if (nl == 0) {
     return -1;
+  }
+  int i = 0;
+  while (fieldNames[i] != NULL) {
+    int ierr = NameValue(fields, fieldNames[i], values[i]);
+    if (ierr) {
+      return -(i + 2);
     }
-  int i=0;
-  while (fieldNames[i]!=NULL)
-    {
-    int ierr=NameValue(fields,fieldNames[i],values[i]);
-    if (ierr)
-      {
-      return -(i+2);
-      }
-    i+=1;
-    }
+    i += 1;
+  }
   return 0;
 }
 #endif
 
 // ****************************************************************************
 #if !defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
-void StacktraceSignalHandler(
-      int sigNo,
-      siginfo_t *sigInfo,
-      void * /*sigContext*/)
+void StacktraceSignalHandler(int sigNo, siginfo_t* sigInfo,
+                             void* /*sigContext*/)
 {
 #if defined(__linux) || defined(__APPLE__)
   std::ostringstream oss;
-  oss
-     << std::endl
-     << "=========================================================" << std::endl
-     << "Process id " << getpid() << " ";
-  switch (sigNo)
-    {
+  oss << std::endl
+      << "========================================================="
+      << std::endl
+      << "Process id " << getpid() << " ";
+  switch (sigNo) {
     case SIGINT:
       oss << "Caught SIGINT";
       break;
@@ -1089,24 +1043,20 @@ void StacktraceSignalHandler(
       break;
 
     case SIGFPE:
-      oss
-        << "Caught SIGFPE at "
-        << (sigInfo->si_addr==0?"0x":"")
-        << sigInfo->si_addr
-        <<  " ";
-      switch (sigInfo->si_code)
-        {
-# if defined(FPE_INTDIV)
+      oss << "Caught SIGFPE at " << (sigInfo->si_addr == 0 ? "0x" : "")
+          << sigInfo->si_addr << " ";
+      switch (sigInfo->si_code) {
+#if defined(FPE_INTDIV)
         case FPE_INTDIV:
           oss << "integer division by zero";
           break;
-# endif
+#endif
 
-# if defined(FPE_INTOVF)
+#if defined(FPE_INTOVF)
         case FPE_INTOVF:
           oss << "integer overflow";
           break;
-# endif
+#endif
 
         case FPE_FLTDIV:
           oss << "floating point divide by zero";
@@ -1137,17 +1087,13 @@ void StacktraceSignalHandler(
         default:
           oss << "code " << sigInfo->si_code;
           break;
-        }
+      }
       break;
 
     case SIGSEGV:
-      oss
-        << "Caught SIGSEGV at "
-        << (sigInfo->si_addr==0?"0x":"")
-        << sigInfo->si_addr
-        <<  " ";
-      switch (sigInfo->si_code)
-        {
+      oss << "Caught SIGSEGV at " << (sigInfo->si_addr == 0 ? "0x" : "")
+          << sigInfo->si_addr << " ";
+      switch (sigInfo->si_code) {
         case SEGV_MAPERR:
           oss << "address not mapped to object";
           break;
@@ -1159,74 +1105,68 @@ void StacktraceSignalHandler(
         default:
           oss << "code " << sigInfo->si_code;
           break;
-        }
+      }
       break;
 
     case SIGBUS:
-      oss
-        << "Caught SIGBUS at "
-        << (sigInfo->si_addr==0?"0x":"")
-        << sigInfo->si_addr
-        <<  " ";
-      switch (sigInfo->si_code)
-        {
+      oss << "Caught SIGBUS at " << (sigInfo->si_addr == 0 ? "0x" : "")
+          << sigInfo->si_addr << " ";
+      switch (sigInfo->si_code) {
         case BUS_ADRALN:
           oss << "invalid address alignment";
           break;
 
-# if defined(BUS_ADRERR)
+#if defined(BUS_ADRERR)
         case BUS_ADRERR:
           oss << "nonexistent physical address";
           break;
-# endif
+#endif
 
-# if defined(BUS_OBJERR)
+#if defined(BUS_OBJERR)
         case BUS_OBJERR:
           oss << "object-specific hardware error";
           break;
-# endif
+#endif
 
-# if defined(BUS_MCEERR_AR)
+#if defined(BUS_MCEERR_AR)
         case BUS_MCEERR_AR:
-          oss << "Hardware memory error consumed on a machine check; action required.";
+          oss << "Hardware memory error consumed on a machine check; action "
+                 "required.";
           break;
-# endif
+#endif
 
-# if defined(BUS_MCEERR_AO)
+#if defined(BUS_MCEERR_AO)
         case BUS_MCEERR_AO:
-          oss << "Hardware memory error detected in process but not consumed; action optional.";
+          oss << "Hardware memory error detected in process but not consumed; "
+                 "action optional.";
           break;
-# endif
+#endif
 
         default:
           oss << "code " << sigInfo->si_code;
           break;
-        }
+      }
       break;
 
     case SIGILL:
-      oss
-        << "Caught SIGILL at "
-        << (sigInfo->si_addr==0?"0x":"")
-        << sigInfo->si_addr
-        <<  " ";
-      switch (sigInfo->si_code)
-        {
+      oss << "Caught SIGILL at " << (sigInfo->si_addr == 0 ? "0x" : "")
+          << sigInfo->si_addr << " ";
+      switch (sigInfo->si_code) {
         case ILL_ILLOPC:
           oss << "illegal opcode";
           break;
 
-# if defined(ILL_ILLOPN)
+#if defined(ILL_ILLOPN)
         case ILL_ILLOPN:
           oss << "illegal operand";
           break;
-# endif
+#endif
 
-# if defined(ILL_ILLADR)
+#if defined(ILL_ILLADR)
         case ILL_ILLADR:
           oss << "illegal addressing mode.";
           break;
-# endif
+#endif
 
         case ILL_ILLTRP:
           oss << "illegal trap";
@@ -1236,39 +1176,39 @@ void StacktraceSignalHandler(
           oss << "privileged opcode";
           break;
 
-# if defined(ILL_PRVREG)
+#if defined(ILL_PRVREG)
         case ILL_PRVREG:
           oss << "privileged register";
           break;
-# endif
+#endif
 
-# if defined(ILL_COPROC)
+#if defined(ILL_COPROC)
         case ILL_COPROC:
           oss << "co-processor error";
           break;
-# endif
+#endif
 
-# if defined(ILL_BADSTK)
+#if defined(ILL_BADSTK)
         case ILL_BADSTK:
           oss << "internal stack error";
           break;
-# endif
+#endif
 
         default:
           oss << "code " << sigInfo->si_code;
           break;
-        }
+      }
       break;
 
     default:
       oss << "Caught " << sigNo << " code " << sigInfo->si_code;
       break;
-    }
-  oss
-    << std::endl
-    << "Program Stack:" << std::endl
-    << SystemInformationImplementation::GetProgramStack(2,0)
-    << "=========================================================" << std::endl;
+  }
+  oss << std::endl
+      << "Program Stack:" << std::endl
+      << SystemInformationImplementation::GetProgramStack(2, 0)
+      << "========================================================="
+      << std::endl;
   std::cerr << oss.str() << std::endl;
 
   // restore the previously registered handlers
@@ -1284,7 +1224,7 @@ void StacktraceSignalHandler(
 #endif
 
 #if defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
-#define safes(_arg)((_arg)?(_arg):"???")
+#define safes(_arg) ((_arg) ? (_arg) : "???")
 
 // Description:
 // A container for symbol properties. Each instance
@@ -1297,65 +1237,73 @@ public:
   // Description:
   // The SymbolProperties instance must be initialized by
   // passing a stack address.
-  void Initialize(void *address);
+  void Initialize(void* address);
 
   // Description:
   // Get the symbol's stack address.
-  void *GetAddress() const { return this->Address; }
+  void* GetAddress() const { return this->Address; }
 
   // Description:
   // If not set paths will be removed. eg, from a binary
   // or source file.
-  void SetReportPath(int rp){ this->ReportPath=rp; }
+  void SetReportPath(int rp) { this->ReportPath = rp; }
 
   // Description:
   // Set/Get the name of the binary file that the symbol
   // is found in.
-  void SetBinary(const char *binary)
-    { this->Binary=safes(binary); }
+  void SetBinary(const char* binary) { this->Binary = safes(binary); }
 
   std::string GetBinary() const;
 
   // Description:
   // Set the name of the function that the symbol is found in.
   // If c++ demangling is supported it will be demangled.
-  void SetFunction(const char *function)
-    { this->Function=this->Demangle(function); }
+  void SetFunction(const char* function)
+  {
+    this->Function = this->Demangle(function);
+  }
 
-  std::string GetFunction() const
-    { return this->Function; }
+  std::string GetFunction() const { return this->Function; }
 
   // Description:
   // Set/Get the name of the source file where the symbol
   // is defined.
-  void SetSourceFile(const char *sourcefile)
-    { this->SourceFile=safes(sourcefile); }
+  void SetSourceFile(const char* sourcefile)
+  {
+    this->SourceFile = safes(sourcefile);
+  }
 
   std::string GetSourceFile() const
-    { return this->GetFileName(this->SourceFile); }
+  {
+    return this->GetFileName(this->SourceFile);
+  }
 
   // Description:
   // Set/Get the line number where the symbol is defined
-  void SetLineNumber(long linenumber){ this->LineNumber=linenumber; }
+  void SetLineNumber(long linenumber) { this->LineNumber = linenumber; }
   long GetLineNumber() const { return this->LineNumber; }
 
   // Description:
   // Set the address where the biinary image is mapped
   // into memory.
-  void SetBinaryBaseAddress(void *address)
-    { this->BinaryBaseAddress=address; }
+  void SetBinaryBaseAddress(void* address)
+  {
+    this->BinaryBaseAddress = address;
+  }
 
 private:
-  void *GetRealAddress() const
-    { return (void*)((char*)this->Address-(char*)this->BinaryBaseAddress); }
+  void* GetRealAddress() const
+  {
+    return (void*)((char*)this->Address - (char*)this->BinaryBaseAddress);
+  }
 
-  std::string GetFileName(const std::string &path) const;
-  std::string Demangle(const char *symbol) const;
+  std::string GetFileName(const std::string& path) const;
+  std::string Demangle(const char* symbol) const;
 
 private:
   std::string Binary;
-  void *BinaryBaseAddress;
-  void *Address;
+  void* BinaryBaseAddress;
+  void* Address;
   std::string SourceFile;
   std::string Function;
   long LineNumber;
@@ -1363,20 +1311,15 @@ private:
 };
 
 // --------------------------------------------------------------------------
-std::ostream &operator<<(
-      std::ostream &os,
-      const SymbolProperties &sp)
+std::ostream& operator<<(std::ostream& os, const SymbolProperties& sp)
 {
 #if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
-  os
-    << std::hex << sp.GetAddress() << " : "
-    << sp.GetFunction()
-    << " [(" << sp.GetBinary() << ") "
-    << sp.GetSourceFile() << ":"
-    << std::dec << sp.GetLineNumber() << "]";
+  os << std::hex << sp.GetAddress() << " : " << sp.GetFunction() << " [("
+     << sp.GetBinary() << ") " << sp.GetSourceFile() << ":" << std::dec
+     << sp.GetLineNumber() << "]";
 #elif defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
-  void *addr = sp.GetAddress();
-  char **syminfo = backtrace_symbols(&addr,1);
+  void* addr = sp.GetAddress();
+  char** syminfo = backtrace_symbols(&addr, 1);
   os << safes(syminfo[0]);
   free(syminfo);
 #else
@@ -1406,17 +1349,15 @@ SymbolProperties::SymbolProperties()
 }
 
 // --------------------------------------------------------------------------
-std::string SymbolProperties::GetFileName(const std::string &path) const
+std::string SymbolProperties::GetFileName(const std::string& path) const
 {
   std::string file(path);
-  if (!this->ReportPath)
-    {
+  if (!this->ReportPath) {
     size_t at = file.rfind("/");
-    if (at!=std::string::npos)
-      {
-      file = file.substr(at+1,std::string::npos);
-      }
+    if (at != std::string::npos) {
+      file = file.substr(at + 1, std::string::npos);
     }
+  }
   return file;
 }
 
@@ -1425,40 +1366,35 @@ std::string SymbolProperties::GetBinary() const
 {
 // only linux has proc fs
 #if defined(__linux__)
-  if (this->Binary=="/proc/self/exe")
-    {
+  if (this->Binary == "/proc/self/exe") {
     std::string binary;
-    char buf[1024]={'\0'};
-    ssize_t ll=0;
-    if ((ll=readlink("/proc/self/exe",buf,1024))>0)
-      {
-      buf[ll]='\0';
-      binary=buf;
-      }
-    else
-      {
-      binary="/proc/self/exe";
-      }
-    return this->GetFileName(binary);
+    char buf[1024] = { '\0' };
+    ssize_t ll = 0;
+    if ((ll = readlink("/proc/self/exe", buf, 1024)) > 0) {
+      buf[ll] = '\0';
+      binary = buf;
+    } else {
+      binary = "/proc/self/exe";
     }
+    return this->GetFileName(binary);
+  }
 #endif
   return this->GetFileName(this->Binary);
 }
 
 // --------------------------------------------------------------------------
-std::string SymbolProperties::Demangle(const char *symbol) const
+std::string SymbolProperties::Demangle(const char* symbol) const
 {
   std::string result = safes(symbol);
 #if defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
   int status = 0;
   size_t bufferLen = 1024;
-  char *buffer = (char*)malloc(1024);
-  char *demangledSymbol =
+  char* buffer = (char*)malloc(1024);
+  char* demangledSymbol =
     abi::__cxa_demangle(symbol, buffer, &bufferLen, &status);
-  if (!status)
-    {
+  if (!status) {
     result = demangledSymbol;
-    }
+  }
   free(buffer);
 #else
   (void)symbol;
@@ -1467,31 +1403,30 @@ std::string SymbolProperties::Demangle(const char *symbol) const
 }
 
 // --------------------------------------------------------------------------
-void SymbolProperties::Initialize(void *address)
+void SymbolProperties::Initialize(void* address)
 {
   this->Address = address;
 #if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
   // first fallback option can demangle c++ functions
   Dl_info info;
-  int ierr=dladdr(this->Address,&info);
-  if (ierr && info.dli_sname && info.dli_saddr)
-    {
+  int ierr = dladdr(this->Address, &info);
+  if (ierr && info.dli_sname && info.dli_saddr) {
     this->SetBinary(info.dli_fname);
     this->SetFunction(info.dli_sname);
-    }
+  }
 #else
-  // second fallback use builtin backtrace_symbols
-  // to decode the bactrace.
+// second fallback use builtin backtrace_symbols
+// to decode the bactrace.
 #endif
 }
 #endif // don't define this class if we're not using it
 
 // --------------------------------------------------------------------------
 #if defined(_WIN32) || defined(__CYGWIN__)
-# define KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes
+#define KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes
 #endif
 #if defined(_MSC_VER) && _MSC_VER < 1310
-# undef KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes
+#undef KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes
 #endif
 #if defined(KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes)
 double calculateCPULoad(unsigned __int64 idleTicks,
@@ -1507,22 +1442,18 @@ double calculateCPULoad(unsigned __int64 idleTicks,
     totalTicks - previousTotalTicks;
 
   double load;
-  if (previousTotalTicks == 0 || totalTicksSinceLastTime == 0)
-    {
+  if (previousTotalTicks == 0 || totalTicksSinceLastTime == 0) {
     // No new information.  Use previous result.
     load = previousLoad;
-    }
-  else
-    {
+  } else {
     // Calculate load since last time.
     load = 1.0 - double(idleTicksSinceLastTime) / totalTicksSinceLastTime;
 
     // Smooth if possible.
-    if (previousLoad > 0)
-      {
+    if (previousLoad > 0) {
       load = 0.25 * load + 0.75 * previousLoad;
-      }
     }
+  }
 
   previousLoad = load;
   previousIdleTicks = idleTicks;
@@ -1542,7 +1473,6 @@ unsigned __int64 fileTimeToUInt64(FILETIME const& ft)
 
 } // anonymous namespace
 
-
 SystemInformationImplementation::SystemInformationImplementation()
 {
   this->TotalVirtualMemory = 0;
@@ -1578,56 +1508,52 @@ void SystemInformationImplementation::RunCPUCheck()
   // Check to see if this processor supports CPUID.
   bool supportsCPUID = DoesCPUSupportCPUID();
 
-  if (supportsCPUID)
-    {
+  if (supportsCPUID) {
     // Retrieve the CPU details.
     RetrieveCPUIdentity();
     this->FindManufacturer();
     RetrieveCPUFeatures();
-    }
+  }
 
   // These two may be called without support for the CPUID instruction.
   // (But if the instruction is there, they should be called *after*
   // the above call to RetrieveCPUIdentity... that's why the two if
   // blocks exist with the same "if (supportsCPUID)" logic...
   //
-  if (!RetrieveCPUClockSpeed())
-    {
+  if (!RetrieveCPUClockSpeed()) {
     RetrieveClassicalCPUClockSpeed();
-    }
+  }
 
-  if (supportsCPUID)
-    {
+  if (supportsCPUID) {
     // Retrieve cache information.
-    if (!RetrieveCPUCacheDetails())
-      {
+    if (!RetrieveCPUCacheDetails()) {
       RetrieveClassicalCPUCacheDetails();
-      }
+    }
 
     // Retrieve the extended CPU details.
-    if (!RetrieveExtendedCPUIdentity())
-      {
+    if (!RetrieveExtendedCPUIdentity()) {
       RetrieveClassicalCPUIdentity();
-      }
+    }
 
     RetrieveExtendedCPUFeatures();
     RetrieveCPUPowerManagement();
 
     // Now attempt to retrieve the serial number (if possible).
     RetrieveProcessorSerialNumber();
-    }
+  }
 
   this->CPUCount();
 
 #elif defined(__APPLE__)
   this->ParseSysCtl();
-#elif defined (__SVR4) && defined (__sun)
+#elif defined(__SVR4) && defined(__sun)
   this->QuerySolarisProcessor();
 #elif defined(__HAIKU__)
   this->QueryHaikuInfo();
 #elif defined(__QNX__)
   this->QueryQNXProcessor();
-#elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
+#elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) ||  \
+  defined(__DragonFly__)
   this->QueryBSDProcessor();
 #elif defined(__hpux)
   this->QueryHPUXProcessor();
@@ -1647,13 +1573,14 @@ void SystemInformationImplementation::RunMemoryCheck()
 {
 #if defined(__APPLE__)
   this->ParseSysCtl();
-#elif defined (__SVR4) && defined (__sun)
+#elif defined(__SVR4) && defined(__sun)
   this->QuerySolarisMemory();
 #elif defined(__HAIKU__)
   this->QueryHaikuInfo();
 #elif defined(__QNX__)
   this->QueryQNXMemory();
-#elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
+#elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) ||  \
+  defined(__DragonFly__)
   this->QueryBSDMemory();
 #elif defined(__CYGWIN__)
   this->QueryCygwinMemory();
@@ -1671,13 +1598,13 @@ void SystemInformationImplementation::RunMemoryCheck()
 }
 
 /** Get the vendor string */
-const char * SystemInformationImplementation::GetVendorString()
+const char* SystemInformationImplementation::GetVendorString()
 {
   return this->ChipID.Vendor.c_str();
 }
 
 /** Get the OS Name */
-const char * SystemInformationImplementation::GetOSName()
+const char* SystemInformationImplementation::GetOSName()
 {
   return this->OSName.c_str();
 }
@@ -1685,65 +1612,59 @@ const char * SystemInformationImplementation::GetOSName()
 /** Get the hostname */
 const char* SystemInformationImplementation::GetHostname()
 {
-  if (this->Hostname.empty())
-    {
-    this->Hostname="localhost";
+  if (this->Hostname.empty()) {
+    this->Hostname = "localhost";
 #if defined(_WIN32)
     WORD wVersionRequested;
     WSADATA wsaData;
     char name[255];
-    wVersionRequested = MAKEWORD(2,0);
-    if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
-      {
-      gethostname(name,sizeof(name));
-      WSACleanup( );
-      }
+    wVersionRequested = MAKEWORD(2, 0);
+    if (WSAStartup(wVersionRequested, &wsaData) == 0) {
+      gethostname(name, sizeof(name));
+      WSACleanup();
+    }
     this->Hostname = name;
 #else
     struct utsname unameInfo;
     int errorFlag = uname(&unameInfo);
-    if(errorFlag == 0)
-      {
+    if (errorFlag == 0) {
       this->Hostname = unameInfo.nodename;
-      }
-#endif
     }
+#endif
+  }
   return this->Hostname.c_str();
 }
 
 /** Get the FQDN */
 int SystemInformationImplementation::GetFullyQualifiedDomainName(
-      std::string &fqdn)
+  std::string& fqdn)
 {
   // in the event of absolute failure return localhost.
-  fqdn="localhost";
+  fqdn = "localhost";
 
 #if defined(_WIN32)
   int ierr;
   // TODO - a more robust implementation for windows, see comments
   // in unix implementation.
   WSADATA wsaData;
-  WORD ver=MAKEWORD(2,0);
-  ierr=WSAStartup(ver,&wsaData);
-  if (ierr)
-    {
+  WORD ver = MAKEWORD(2, 0);
+  ierr = WSAStartup(ver, &wsaData);
+  if (ierr) {
     return -1;
-    }
+  }
 
-  char base[256]={'\0'};
-  ierr=gethostname(base,256);
-  if (ierr)
-    {
+  char base[256] = { '\0' };
+  ierr = gethostname(base, 256);
+  if (ierr) {
     WSACleanup();
     return -2;
-    }
-  fqdn=base;
+  }
+  fqdn = base;
 
-  HOSTENT *hent=gethostbyname(base);
-  if (hent)
-    {
-    fqdn=hent->h_name;
-    }
+  HOSTENT* hent = gethostbyname(base);
+  if (hent) {
+    fqdn = hent->h_name;
+  }
 
   WSACleanup();
   return 0;
@@ -1760,66 +1681,57 @@ int SystemInformationImplementation::GetFullyQualifiedDomainName(
   // system lives on a private network such as in the case of a cluster
   // node.
 
-  int ierr=0;
+  int ierr = 0;
   char base[NI_MAXHOST];
-  ierr=gethostname(base,NI_MAXHOST);
-  if (ierr)
-    {
+  ierr = gethostname(base, NI_MAXHOST);
+  if (ierr) {
     return -1;
-    }
-  size_t baseSize=strlen(base);
-  fqdn=base;
+  }
+  size_t baseSize = strlen(base);
+  fqdn = base;
 
-  struct ifaddrs *ifas;
-  struct ifaddrs *ifa;
-  ierr=getifaddrs(&ifas);
-  if (ierr)
-    {
+  struct ifaddrs* ifas;
+  struct ifaddrs* ifa;
+  ierr = getifaddrs(&ifas);
+  if (ierr) {
     return -2;
-    }
+  }
 
-  for (ifa=ifas; ifa!=NULL; ifa=ifa->ifa_next)
-    {
-    int fam = ifa->ifa_addr? ifa->ifa_addr->sa_family : -1;
-    if ((fam==AF_INET) || (fam==AF_INET6))
-      {
-      char host[NI_MAXHOST]={'\0'};
-
-      const size_t addrlen
-        = (fam==AF_INET?sizeof(struct sockaddr_in):sizeof(struct sockaddr_in6));
-
-      ierr=getnameinfo(
-            ifa->ifa_addr,
-            static_cast<socklen_t>(addrlen),
-            host,
-            NI_MAXHOST,
-            NULL,
-            0,
-            NI_NAMEREQD);
-      if (ierr)
-        {
+  for (ifa = ifas; ifa != NULL; ifa = ifa->ifa_next) {
+    int fam = ifa->ifa_addr ? ifa->ifa_addr->sa_family : -1;
+    // Skip Loopback interfaces
+    if (((fam == AF_INET) || (fam == AF_INET6)) &&
+        !(ifa->ifa_flags & IFF_LOOPBACK)) {
+      char host[NI_MAXHOST] = { '\0' };
+
+      const size_t addrlen = (fam == AF_INET ? sizeof(struct sockaddr_in)
+                                             : sizeof(struct sockaddr_in6));
+
+      ierr = getnameinfo(ifa->ifa_addr, static_cast<socklen_t>(addrlen), host,
+                         NI_MAXHOST, NULL, 0, NI_NAMEREQD);
+      if (ierr) {
         // don't report the failure now since we may succeed on another
         // interface. If all attempts fail then return the failure code.
-        ierr=-3;
+        ierr = -3;
         continue;
-        }
+      }
 
-      std::string candidate=host;
-      if ((candidate.find(base)!=std::string::npos) && baseSize<candidate.size())
-        {
+      std::string candidate = host;
+      if ((candidate.find(base) != std::string::npos) &&
+          baseSize < candidate.size()) {
         // success, stop now.
-        ierr=0;
-        fqdn=candidate;
+        ierr = 0;
+        fqdn = candidate;
         break;
-        }
       }
     }
+  }
   freeifaddrs(ifas);
 
   return ierr;
 #else
   /* TODO: Implement on more platforms.  */
-  fqdn=this->GetHostname();
+  fqdn = this->GetHostname();
   return -1;
 #endif
 }
@@ -1843,11 +1755,10 @@ const char* SystemInformationImplementation::GetOSPlatform()
 }
 
 /** Get the vendor ID */
-const char * SystemInformationImplementation::GetVendorID()
+const char* SystemInformationImplementation::GetVendorID()
 {
   // Return the vendor ID.
-  switch (this->ChipManufacturer)
-    {
+  switch (this->ChipManufacturer) {
     case Intel:
       return "Intel Corporation";
     case AMD:
@@ -1877,7 +1788,7 @@ const char * SystemInformationImplementation::GetVendorID()
     case UnknownManufacturer:
     default:
       return "Unknown Manufacturer";
-    }
+  }
 }
 
 /** Return the type ID of the CPU */
@@ -1919,14 +1830,14 @@ std::string SystemInformationImplementation::GetSteppingCode()
 }
 
 /** Return the stepping code of the CPU present. */
-const char * SystemInformationImplementation::GetExtendedProcessorName()
+const char* SystemInformationImplementation::GetExtendedProcessorName()
 {
   return this->ChipID.ProcessorName.c_str();
 }
 
 /** Return the serial number of the processor
  *  in hexadecimal: xxxx-xxxx-xxxx-xxxx-xxxx-xxxx. */
-const char * SystemInformationImplementation::GetProcessorSerialNumber()
+const char* SystemInformationImplementation::GetProcessorSerialNumber()
 {
   return this->ChipID.SerialNumber.c_str();
 }
@@ -1958,93 +1869,123 @@ int SystemInformationImplementation::GetProcessorCacheSize()
 /** Return the chosen cache size. */
 int SystemInformationImplementation::GetProcessorCacheXSize(long int dwCacheID)
 {
-  switch (dwCacheID)
-    {
+  switch (dwCacheID) {
     case L1CACHE_FEATURE:
       return this->Features.L1CacheSize;
     case L2CACHE_FEATURE:
       return this->Features.L2CacheSize;
     case L3CACHE_FEATURE:
       return this->Features.L3CacheSize;
-    }
+  }
   return -1;
 }
 
-
 bool SystemInformationImplementation::DoesCPUSupportFeature(long int dwFeature)
 {
   bool bHasFeature = false;
 
   // Check for MMX instructions.
-  if (((dwFeature & MMX_FEATURE) != 0) && this->Features.HasMMX) bHasFeature = true;
+  if (((dwFeature & MMX_FEATURE) != 0) && this->Features.HasMMX)
+    bHasFeature = true;
 
   // Check for MMX+ instructions.
-  if (((dwFeature & MMX_PLUS_FEATURE) != 0) && this->Features.ExtendedFeatures.HasMMXPlus) bHasFeature = true;
+  if (((dwFeature & MMX_PLUS_FEATURE) != 0) &&
+      this->Features.ExtendedFeatures.HasMMXPlus)
+    bHasFeature = true;
 
   // Check for SSE FP instructions.
-  if (((dwFeature & SSE_FEATURE) != 0) && this->Features.HasSSE) bHasFeature = true;
+  if (((dwFeature & SSE_FEATURE) != 0) && this->Features.HasSSE)
+    bHasFeature = true;
 
   // Check for SSE FP instructions.
-  if (((dwFeature & SSE_FP_FEATURE) != 0) && this->Features.HasSSEFP) bHasFeature = true;
+  if (((dwFeature & SSE_FP_FEATURE) != 0) && this->Features.HasSSEFP)
+    bHasFeature = true;
 
   // Check for SSE MMX instructions.
-  if (((dwFeature & SSE_MMX_FEATURE) != 0) && this->Features.ExtendedFeatures.HasSSEMMX) bHasFeature = true;
+  if (((dwFeature & SSE_MMX_FEATURE) != 0) &&
+      this->Features.ExtendedFeatures.HasSSEMMX)
+    bHasFeature = true;
 
   // Check for SSE2 instructions.
-  if (((dwFeature & SSE2_FEATURE) != 0) && this->Features.HasSSE2) bHasFeature = true;
+  if (((dwFeature & SSE2_FEATURE) != 0) && this->Features.HasSSE2)
+    bHasFeature = true;
 
   // Check for 3DNow! instructions.
-  if (((dwFeature & AMD_3DNOW_FEATURE) != 0) && this->Features.ExtendedFeatures.Has3DNow) bHasFeature = true;
+  if (((dwFeature & AMD_3DNOW_FEATURE) != 0) &&
+      this->Features.ExtendedFeatures.Has3DNow)
+    bHasFeature = true;
 
   // Check for 3DNow+ instructions.
-  if (((dwFeature & AMD_3DNOW_PLUS_FEATURE) != 0) && this->Features.ExtendedFeatures.Has3DNowPlus) bHasFeature = true;
+  if (((dwFeature & AMD_3DNOW_PLUS_FEATURE) != 0) &&
+      this->Features.ExtendedFeatures.Has3DNowPlus)
+    bHasFeature = true;
 
   // Check for IA64 instructions.
-  if (((dwFeature & IA64_FEATURE) != 0) && this->Features.HasIA64) bHasFeature = true;
+  if (((dwFeature & IA64_FEATURE) != 0) && this->Features.HasIA64)
+    bHasFeature = true;
 
   // Check for MP capable.
-  if (((dwFeature & MP_CAPABLE) != 0) && this->Features.ExtendedFeatures.SupportsMP) bHasFeature = true;
+  if (((dwFeature & MP_CAPABLE) != 0) &&
+      this->Features.ExtendedFeatures.SupportsMP)
+    bHasFeature = true;
 
   // Check for a serial number for the processor.
-  if (((dwFeature & SERIALNUMBER_FEATURE) != 0) && this->Features.HasSerial) bHasFeature = true;
+  if (((dwFeature & SERIALNUMBER_FEATURE) != 0) && this->Features.HasSerial)
+    bHasFeature = true;
 
   // Check for a local APIC in the processor.
-  if (((dwFeature & APIC_FEATURE) != 0) && this->Features.HasAPIC) bHasFeature = true;
+  if (((dwFeature & APIC_FEATURE) != 0) && this->Features.HasAPIC)
+    bHasFeature = true;
 
   // Check for CMOV instructions.
-  if (((dwFeature & CMOV_FEATURE) != 0) && this->Features.HasCMOV) bHasFeature = true;
+  if (((dwFeature & CMOV_FEATURE) != 0) && this->Features.HasCMOV)
+    bHasFeature = true;
 
   // Check for MTRR instructions.
-  if (((dwFeature & MTRR_FEATURE) != 0) && this->Features.HasMTRR) bHasFeature = true;
+  if (((dwFeature & MTRR_FEATURE) != 0) && this->Features.HasMTRR)
+    bHasFeature = true;
 
   // Check for L1 cache size.
-  if (((dwFeature & L1CACHE_FEATURE) != 0) && (this->Features.L1CacheSize != -1)) bHasFeature = true;
+  if (((dwFeature & L1CACHE_FEATURE) != 0) &&
+      (this->Features.L1CacheSize != -1))
+    bHasFeature = true;
 
   // Check for L2 cache size.
-  if (((dwFeature & L2CACHE_FEATURE) != 0) && (this->Features.L2CacheSize != -1)) bHasFeature = true;
+  if (((dwFeature & L2CACHE_FEATURE) != 0) &&
+      (this->Features.L2CacheSize != -1))
+    bHasFeature = true;
 
   // Check for L3 cache size.
-  if (((dwFeature & L3CACHE_FEATURE) != 0) && (this->Features.L3CacheSize != -1)) bHasFeature = true;
+  if (((dwFeature & L3CACHE_FEATURE) != 0) &&
+      (this->Features.L3CacheSize != -1))
+    bHasFeature = true;
 
   // Check for ACPI capability.
-  if (((dwFeature & ACPI_FEATURE) != 0) && this->Features.HasACPI) bHasFeature = true;
+  if (((dwFeature & ACPI_FEATURE) != 0) && this->Features.HasACPI)
+    bHasFeature = true;
 
   // Check for thermal monitor support.
-  if (((dwFeature & THERMALMONITOR_FEATURE) != 0) && this->Features.HasThermal) bHasFeature = true;
+  if (((dwFeature & THERMALMONITOR_FEATURE) != 0) && this->Features.HasThermal)
+    bHasFeature = true;
 
   // Check for temperature sensing diode support.
-  if (((dwFeature & TEMPSENSEDIODE_FEATURE) != 0) && this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode) bHasFeature = true;
+  if (((dwFeature & TEMPSENSEDIODE_FEATURE) != 0) &&
+      this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode)
+    bHasFeature = true;
 
   // Check for frequency ID support.
-  if (((dwFeature & FREQUENCYID_FEATURE) != 0) && this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID) bHasFeature = true;
+  if (((dwFeature & FREQUENCYID_FEATURE) != 0) &&
+      this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID)
+    bHasFeature = true;
 
   // Check for voltage ID support.
-  if (((dwFeature & VOLTAGEID_FREQUENCY) != 0) && this->Features.ExtendedFeatures.PowerManagement.HasVoltageID) bHasFeature = true;
+  if (((dwFeature & VOLTAGEID_FREQUENCY) != 0) &&
+      this->Features.ExtendedFeatures.PowerManagement.HasVoltageID)
+    bHasFeature = true;
 
   return bHasFeature;
 }
 
-
 void SystemInformationImplementation::Delay(unsigned int uiMS)
 {
 #ifdef _WIN32
@@ -2052,21 +1993,21 @@ void SystemInformationImplementation::Delay(unsigned int uiMS)
   __int64 x;
 
   // Get the frequency of the high performance counter.
-  if (!QueryPerformanceFrequency (&Frequency)) return;
+  if (!QueryPerformanceFrequency(&Frequency))
+    return;
   x = Frequency.QuadPart / 1000 * uiMS;
 
   // Get the starting position of the counter.
-  QueryPerformanceCounter (&StartCounter);
+  QueryPerformanceCounter(&StartCounter);
 
   do {
     // Get the ending position of the counter.
-    QueryPerformanceCounter (&EndCounter);
-    } while (EndCounter.QuadPart - StartCounter.QuadPart < x);
+    QueryPerformanceCounter(&EndCounter);
+  } while (EndCounter.QuadPart - StartCounter.QuadPart < x);
 #endif
   (void)uiMS;
 }
 
-
 bool SystemInformationImplementation::DoesCPUSupportCPUID()
 {
 #if USE_CPUID
@@ -2084,76 +2025,86 @@ bool SystemInformationImplementation::DoesCPUSupportCPUID()
 #endif
 }
 
-
 bool SystemInformationImplementation::RetrieveCPUFeatures()
 {
 #if USE_CPUID
   int cpuinfo[4] = { 0, 0, 0, 0 };
 
-  if (!call_cpuid(1, cpuinfo))
-    {
+  if (!call_cpuid(1, cpuinfo)) {
     return false;
-    }
+  }
 
   // Retrieve the features of CPU present.
-  this->Features.HasFPU =     ((cpuinfo[3] & 0x00000001) != 0);    // FPU Present --> Bit 0
-  this->Features.HasTSC =     ((cpuinfo[3] & 0x00000010) != 0);    // TSC Present --> Bit 4
-  this->Features.HasAPIC =    ((cpuinfo[3] & 0x00000200) != 0);    // APIC Present --> Bit 9
-  this->Features.HasMTRR =    ((cpuinfo[3] & 0x00001000) != 0);    // MTRR Present --> Bit 12
-  this->Features.HasCMOV =    ((cpuinfo[3] & 0x00008000) != 0);    // CMOV Present --> Bit 15
-  this->Features.HasSerial =  ((cpuinfo[3] & 0x00040000) != 0);    // Serial Present --> Bit 18
-  this->Features.HasACPI =    ((cpuinfo[3] & 0x00400000) != 0);    // ACPI Capable --> Bit 22
-  this->Features.HasMMX =     ((cpuinfo[3] & 0x00800000) != 0);    // MMX Present --> Bit 23
-  this->Features.HasSSE =     ((cpuinfo[3] & 0x02000000) != 0);    // SSE Present --> Bit 25
-  this->Features.HasSSE2 =    ((cpuinfo[3] & 0x04000000) != 0);    // SSE2 Present --> Bit 26
-  this->Features.HasThermal = ((cpuinfo[3] & 0x20000000) != 0);    // Thermal Monitor Present --> Bit 29
-  this->Features.HasIA64 =    ((cpuinfo[3] & 0x40000000) != 0);    // IA64 Present --> Bit 30
+  this->Features.HasFPU =
+    ((cpuinfo[3] & 0x00000001) != 0); // FPU Present --> Bit 0
+  this->Features.HasTSC =
+    ((cpuinfo[3] & 0x00000010) != 0); // TSC Present --> Bit 4
+  this->Features.HasAPIC =
+    ((cpuinfo[3] & 0x00000200) != 0); // APIC Present --> Bit 9
+  this->Features.HasMTRR =
+    ((cpuinfo[3] & 0x00001000) != 0); // MTRR Present --> Bit 12
+  this->Features.HasCMOV =
+    ((cpuinfo[3] & 0x00008000) != 0); // CMOV Present --> Bit 15
+  this->Features.HasSerial =
+    ((cpuinfo[3] & 0x00040000) != 0); // Serial Present --> Bit 18
+  this->Features.HasACPI =
+    ((cpuinfo[3] & 0x00400000) != 0); // ACPI Capable --> Bit 22
+  this->Features.HasMMX =
+    ((cpuinfo[3] & 0x00800000) != 0); // MMX Present --> Bit 23
+  this->Features.HasSSE =
+    ((cpuinfo[3] & 0x02000000) != 0); // SSE Present --> Bit 25
+  this->Features.HasSSE2 =
+    ((cpuinfo[3] & 0x04000000) != 0); // SSE2 Present --> Bit 26
+  this->Features.HasThermal =
+    ((cpuinfo[3] & 0x20000000) != 0); // Thermal Monitor Present --> Bit 29
+  this->Features.HasIA64 =
+    ((cpuinfo[3] & 0x40000000) != 0); // IA64 Present --> Bit 30
 
 #if USE_ASM_INSTRUCTIONS
   // Retrieve extended SSE capabilities if SSE is available.
   if (this->Features.HasSSE) {
 
     // Attempt to __try some SSE FP instructions.
-    __try
-      {
+    __try {
       // Perform: orps xmm0, xmm0
       _asm
-        {
+      {
         _emit 0x0f
         _emit 0x56
         _emit 0xc0
-        }
+      }
 
       // SSE FP capable processor.
       this->Features.HasSSEFP = true;
-      }
-    __except(1)
-      {
+    } __except (1) {
       // bad instruction - processor or OS cannot handle SSE FP.
       this->Features.HasSSEFP = false;
-      }
     }
-  else
-    {
+  } else {
     // Set the advanced SSE capabilities to not available.
     this->Features.HasSSEFP = false;
-    }
+  }
 #else
   this->Features.HasSSEFP = false;
 #endif
 
   // Retrieve Intel specific extended features.
-  if (this->ChipManufacturer == Intel)
-    {
-    this->Features.ExtendedFeatures.SupportsHyperthreading =  ((cpuinfo[3] &  0x10000000) != 0);  // Intel specific: Hyperthreading --> Bit 28
-    this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical = (this->Features.ExtendedFeatures.SupportsHyperthreading) ? ((cpuinfo[1] & 0x00FF0000) >> 16) : 1;
-
-    if ((this->Features.ExtendedFeatures.SupportsHyperthreading) && (this->Features.HasAPIC))
-      {
+  if (this->ChipManufacturer == Intel) {
+    this->Features.ExtendedFeatures.SupportsHyperthreading =
+      ((cpuinfo[3] & 0x10000000) !=
+       0); // Intel specific: Hyperthreading --> Bit 28
+    this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical =
+      (this->Features.ExtendedFeatures.SupportsHyperthreading)
+      ? ((cpuinfo[1] & 0x00FF0000) >> 16)
+      : 1;
+
+    if ((this->Features.ExtendedFeatures.SupportsHyperthreading) &&
+        (this->Features.HasAPIC)) {
       // Retrieve APIC information if there is one present.
-      this->Features.ExtendedFeatures.APIC_ID = ((cpuinfo[1] & 0xFF000000) >> 24);
-      }
+      this->Features.ExtendedFeatures.APIC_ID =
+        ((cpuinfo[1] & 0xFF000000) >> 24);
     }
+  }
 
   return true;
 
@@ -2162,30 +2113,46 @@ bool SystemInformationImplementation::RetrieveCPUFeatures()
 #endif
 }
 
-
 /** Find the manufacturer given the vendor id */
-void SystemInformationImplementation::FindManufacturer(const std::string& family)
-{
-  if (this->ChipID.Vendor == "GenuineIntel")       this->ChipManufacturer = Intel;        // Intel Corp.
-  else if (this->ChipID.Vendor == "UMC UMC UMC ")  this->ChipManufacturer = UMC;          // United Microelectronics Corp.
-  else if (this->ChipID.Vendor == "AuthenticAMD")  this->ChipManufacturer = AMD;          // Advanced Micro Devices
-  else if (this->ChipID.Vendor == "AMD ISBETTER")  this->ChipManufacturer = AMD;          // Advanced Micro Devices (1994)
-  else if (this->ChipID.Vendor == "CyrixInstead")  this->ChipManufacturer = Cyrix;        // Cyrix Corp., VIA Inc.
-  else if (this->ChipID.Vendor == "NexGenDriven")  this->ChipManufacturer = NexGen;        // NexGen Inc. (now AMD)
-  else if (this->ChipID.Vendor == "CentaurHauls")  this->ChipManufacturer = IDT;          // IDT/Centaur (now VIA)
-  else if (this->ChipID.Vendor == "RiseRiseRise")  this->ChipManufacturer = Rise;        // Rise
-  else if (this->ChipID.Vendor == "GenuineTMx86")  this->ChipManufacturer = Transmeta;      // Transmeta
-  else if (this->ChipID.Vendor == "TransmetaCPU")  this->ChipManufacturer = Transmeta;      // Transmeta
-  else if (this->ChipID.Vendor == "Geode By NSC")  this->ChipManufacturer = NSC;          // National Semiconductor
-  else if (this->ChipID.Vendor == "Sun")           this->ChipManufacturer = Sun;          // Sun Microelectronics
-  else if (this->ChipID.Vendor == "IBM")           this->ChipManufacturer = IBM;          // IBM Microelectronics
-  else if (this->ChipID.Vendor == "Hewlett-Packard") this->ChipManufacturer = HP;         // Hewlett-Packard
-  else if (this->ChipID.Vendor == "Motorola")      this->ChipManufacturer = Motorola;          // Motorola Microelectronics
-  else if (family.substr(0, 7) == "PA-RISC")       this->ChipManufacturer = HP;           // Hewlett-Packard
-  else                                             this->ChipManufacturer = UnknownManufacturer;  // Unknown manufacturer
+void SystemInformationImplementation::FindManufacturer(
+  const std::string& family)
+{
+  if (this->ChipID.Vendor == "GenuineIntel")
+    this->ChipManufacturer = Intel; // Intel Corp.
+  else if (this->ChipID.Vendor == "UMC UMC UMC ")
+    this->ChipManufacturer = UMC; // United Microelectronics Corp.
+  else if (this->ChipID.Vendor == "AuthenticAMD")
+    this->ChipManufacturer = AMD; // Advanced Micro Devices
+  else if (this->ChipID.Vendor == "AMD ISBETTER")
+    this->ChipManufacturer = AMD; // Advanced Micro Devices (1994)
+  else if (this->ChipID.Vendor == "CyrixInstead")
+    this->ChipManufacturer = Cyrix; // Cyrix Corp., VIA Inc.
+  else if (this->ChipID.Vendor == "NexGenDriven")
+    this->ChipManufacturer = NexGen; // NexGen Inc. (now AMD)
+  else if (this->ChipID.Vendor == "CentaurHauls")
+    this->ChipManufacturer = IDT; // IDT/Centaur (now VIA)
+  else if (this->ChipID.Vendor == "RiseRiseRise")
+    this->ChipManufacturer = Rise; // Rise
+  else if (this->ChipID.Vendor == "GenuineTMx86")
+    this->ChipManufacturer = Transmeta; // Transmeta
+  else if (this->ChipID.Vendor == "TransmetaCPU")
+    this->ChipManufacturer = Transmeta; // Transmeta
+  else if (this->ChipID.Vendor == "Geode By NSC")
+    this->ChipManufacturer = NSC; // National Semiconductor
+  else if (this->ChipID.Vendor == "Sun")
+    this->ChipManufacturer = Sun; // Sun Microelectronics
+  else if (this->ChipID.Vendor == "IBM")
+    this->ChipManufacturer = IBM; // IBM Microelectronics
+  else if (this->ChipID.Vendor == "Hewlett-Packard")
+    this->ChipManufacturer = HP; // Hewlett-Packard
+  else if (this->ChipID.Vendor == "Motorola")
+    this->ChipManufacturer = Motorola; // Motorola Microelectronics
+  else if (family.substr(0, 7) == "PA-RISC")
+    this->ChipManufacturer = HP; // Hewlett-Packard
+  else
+    this->ChipManufacturer = UnknownManufacturer; // Unknown manufacturer
 }
 
-
 /** */
 bool SystemInformationImplementation::RetrieveCPUIdentity()
 {
@@ -2193,14 +2160,12 @@ bool SystemInformationImplementation::RetrieveCPUIdentity()
   int localCPUVendor[4];
   int localCPUSignature[4];
 
-  if (!call_cpuid(0, localCPUVendor))
-    {
+  if (!call_cpuid(0, localCPUVendor)) {
     return false;
-    }
-  if (!call_cpuid(1, localCPUSignature))
-    {
+  }
+  if (!call_cpuid(1, localCPUSignature)) {
     return false;
-    }
+  }
 
   // Process the returned information.
   //    ; eax = 0 --> eax: maximum value of CPUID instruction.
@@ -2208,22 +2173,30 @@ bool SystemInformationImplementation::RetrieveCPUIdentity()
   //    ;        edx: part 2 of 3; CPU signature.
   //    ;        ecx: part 3 of 3; CPU signature.
   char vbuf[13];
-  memcpy (&(vbuf[0]), &(localCPUVendor[1]), sizeof (int));
-  memcpy (&(vbuf[4]), &(localCPUVendor[3]), sizeof (int));
-  memcpy (&(vbuf[8]), &(localCPUVendor[2]), sizeof (int));
+  memcpy(&(vbuf[0]), &(localCPUVendor[1]), sizeof(int));
+  memcpy(&(vbuf[4]), &(localCPUVendor[3]), sizeof(int));
+  memcpy(&(vbuf[8]), &(localCPUVendor[2]), sizeof(int));
   vbuf[12] = '\0';
   this->ChipID.Vendor = vbuf;
 
   // Retrieve the family of CPU present.
-  //    ; eax = 1 --> eax: CPU ID - bits 31..16 - unused, bits 15..12 - type, bits 11..8 - family, bits 7..4 - model, bits 3..0 - mask revision
-  //    ;        ebx: 31..24 - default APIC ID, 23..16 - logical processor ID, 15..8 - CFLUSH chunk size , 7..0 - brand ID
+  //    ; eax = 1 --> eax: CPU ID - bits 31..16 - unused, bits 15..12 - type,
+  //    bits 11..8 - family, bits 7..4 - model, bits 3..0 - mask revision
+  //    ;        ebx: 31..24 - default APIC ID, 23..16 - logical processor ID,
+  //    15..8 - CFLUSH chunk size , 7..0 - brand ID
   //    ;        edx: CPU feature flags
-  this->ChipID.ExtendedFamily = ((localCPUSignature[0] & 0x0FF00000) >> 20);  // Bits 27..20 Used
-  this->ChipID.ExtendedModel =  ((localCPUSignature[0] & 0x000F0000) >> 16);  // Bits 19..16 Used
-  this->ChipID.Type =           ((localCPUSignature[0] & 0x0000F000) >> 12);  // Bits 15..12 Used
-  this->ChipID.Family =         ((localCPUSignature[0] & 0x00000F00) >> 8);    // Bits 11..8 Used
-  this->ChipID.Model =          ((localCPUSignature[0] & 0x000000F0) >> 4);    // Bits 7..4 Used
-  this->ChipID.Revision =       ((localCPUSignature[0] & 0x0000000F) >> 0);    // Bits 3..0 Used
+  this->ChipID.ExtendedFamily =
+    ((localCPUSignature[0] & 0x0FF00000) >> 20); // Bits 27..20 Used
+  this->ChipID.ExtendedModel =
+    ((localCPUSignature[0] & 0x000F0000) >> 16); // Bits 19..16 Used
+  this->ChipID.Type =
+    ((localCPUSignature[0] & 0x0000F000) >> 12); // Bits 15..12 Used
+  this->ChipID.Family =
+    ((localCPUSignature[0] & 0x00000F00) >> 8); // Bits 11..8 Used
+  this->ChipID.Model =
+    ((localCPUSignature[0] & 0x000000F0) >> 4); // Bits 7..4 Used
+  this->ChipID.Revision =
+    ((localCPUSignature[0] & 0x0000000F) >> 0); // Bits 3..0 Used
 
   return true;
 
@@ -2232,7 +2205,6 @@ bool SystemInformationImplementation::RetrieveCPUIdentity()
 #endif
 }
 
-
 /** */
 bool SystemInformationImplementation::RetrieveCPUCacheDetails()
 {
@@ -2241,37 +2213,30 @@ bool SystemInformationImplementation::RetrieveCPUCacheDetails()
   int L2Cache[4] = { 0, 0, 0, 0 };
 
   // Check to see if what we are about to do is supported...
-  if (RetrieveCPUExtendedLevelSupport (0x80000005))
-    {
-    if (!call_cpuid(0x80000005, L1Cache))
-      {
+  if (RetrieveCPUExtendedLevelSupport(0x80000005)) {
+    if (!call_cpuid(0x80000005, L1Cache)) {
       return false;
-      }
-    // Save the L1 data cache size (in KB) from ecx: bits 31..24 as well as data cache size from edx: bits 31..24.
+    }
+    // Save the L1 data cache size (in KB) from ecx: bits 31..24 as well as
+    // data cache size from edx: bits 31..24.
     this->Features.L1CacheSize = ((L1Cache[2] & 0xFF000000) >> 24);
     this->Features.L1CacheSize += ((L1Cache[3] & 0xFF000000) >> 24);
-    }
-  else
-    {
+  } else {
     // Store -1 to indicate the cache could not be queried.
     this->Features.L1CacheSize = -1;
-    }
+  }
 
   // Check to see if what we are about to do is supported...
-  if (RetrieveCPUExtendedLevelSupport (0x80000006))
-    {
-    if (!call_cpuid(0x80000006, L2Cache))
-      {
+  if (RetrieveCPUExtendedLevelSupport(0x80000006)) {
+    if (!call_cpuid(0x80000006, L2Cache)) {
       return false;
-      }
+    }
     // Save the L2 unified cache size (in KB) from ecx: bits 31..16.
     this->Features.L2CacheSize = ((L2Cache[2] & 0xFFFF0000) >> 16);
-    }
-  else
-    {
+  } else {
     // Store -1 to indicate the cache could not be queried.
     this->Features.L2CacheSize = -1;
-    }
+  }
 
   // Define L3 as being not present as we cannot test for it.
   this->Features.L3CacheSize = -1;
@@ -2279,173 +2244,294 @@ bool SystemInformationImplementation::RetrieveCPUCacheDetails()
 #endif
 
   // Return failure if we cannot detect either cache with this method.
-  return ((this->Features.L1CacheSize == -1) && (this->Features.L2CacheSize == -1)) ? false : true;
+  return ((this->Features.L1CacheSize == -1) &&
+          (this->Features.L2CacheSize == -1))
+    ? false
+    : true;
 }
 
-
 /** */
 bool SystemInformationImplementation::RetrieveClassicalCPUCacheDetails()
 {
 #if USE_CPUID
-  int TLBCode = -1, TLBData = -1, L1Code = -1, L1Data = -1, L1Trace = -1, L2Unified = -1, L3Unified = -1;
+  int TLBCode = -1, TLBData = -1, L1Code = -1, L1Data = -1, L1Trace = -1,
+      L2Unified = -1, L3Unified = -1;
   int TLBCacheData[4] = { 0, 0, 0, 0 };
   int TLBPassCounter = 0;
   int TLBCacheUnit = 0;
 
-
   do {
-    if (!call_cpuid(2, TLBCacheData))
-      {
+    if (!call_cpuid(2, TLBCacheData)) {
       return false;
-      }
+    }
 
     int bob = ((TLBCacheData[0] & 0x00FF0000) >> 16);
     (void)bob;
     // Process the returned TLB and cache information.
-    for (int nCounter = 0; nCounter < TLBCACHE_INFO_UNITS; nCounter ++)
-      {
+    for (int nCounter = 0; nCounter < TLBCACHE_INFO_UNITS; nCounter++) {
       // First of all - decide which unit we are dealing with.
-      switch (nCounter)
-        {
+      switch (nCounter) {
         // eax: bits 8..15 : bits 16..23 : bits 24..31
-        case 0: TLBCacheUnit = ((TLBCacheData[0] & 0x0000FF00) >> 8); break;
-        case 1: TLBCacheUnit = ((TLBCacheData[0] & 0x00FF0000) >> 16); break;
-        case 2: TLBCacheUnit = ((TLBCacheData[0] & 0xFF000000) >> 24); break;
+        case 0:
+          TLBCacheUnit = ((TLBCacheData[0] & 0x0000FF00) >> 8);
+          break;
+        case 1:
+          TLBCacheUnit = ((TLBCacheData[0] & 0x00FF0000) >> 16);
+          break;
+        case 2:
+          TLBCacheUnit = ((TLBCacheData[0] & 0xFF000000) >> 24);
+          break;
 
         // ebx: bits 0..7 : bits 8..15 : bits 16..23 : bits 24..31
-        case 3: TLBCacheUnit = ((TLBCacheData[1] & 0x000000FF) >> 0); break;
-        case 4: TLBCacheUnit = ((TLBCacheData[1] & 0x0000FF00) >> 8); break;
-        case 5: TLBCacheUnit = ((TLBCacheData[1] & 0x00FF0000) >> 16); break;
-        case 6: TLBCacheUnit = ((TLBCacheData[1] & 0xFF000000) >> 24); break;
+        case 3:
+          TLBCacheUnit = ((TLBCacheData[1] & 0x000000FF) >> 0);
+          break;
+        case 4:
+          TLBCacheUnit = ((TLBCacheData[1] & 0x0000FF00) >> 8);
+          break;
+        case 5:
+          TLBCacheUnit = ((TLBCacheData[1] & 0x00FF0000) >> 16);
+          break;
+        case 6:
+          TLBCacheUnit = ((TLBCacheData[1] & 0xFF000000) >> 24);
+          break;
 
         // ecx: bits 0..7 : bits 8..15 : bits 16..23 : bits 24..31
-        case 7: TLBCacheUnit = ((TLBCacheData[2] & 0x000000FF) >> 0); break;
-        case 8: TLBCacheUnit = ((TLBCacheData[2] & 0x0000FF00) >> 8); break;
-        case 9: TLBCacheUnit = ((TLBCacheData[2] & 0x00FF0000) >> 16); break;
-        case 10: TLBCacheUnit = ((TLBCacheData[2] & 0xFF000000) >> 24); break;
+        case 7:
+          TLBCacheUnit = ((TLBCacheData[2] & 0x000000FF) >> 0);
+          break;
+        case 8:
+          TLBCacheUnit = ((TLBCacheData[2] & 0x0000FF00) >> 8);
+          break;
+        case 9:
+          TLBCacheUnit = ((TLBCacheData[2] & 0x00FF0000) >> 16);
+          break;
+        case 10:
+          TLBCacheUnit = ((TLBCacheData[2] & 0xFF000000) >> 24);
+          break;
 
         // edx: bits 0..7 : bits 8..15 : bits 16..23 : bits 24..31
-        case 11: TLBCacheUnit = ((TLBCacheData[3] & 0x000000FF) >> 0); break;
-        case 12: TLBCacheUnit = ((TLBCacheData[3] & 0x0000FF00) >> 8); break;
-        case 13: TLBCacheUnit = ((TLBCacheData[3] & 0x00FF0000) >> 16); break;
-        case 14: TLBCacheUnit = ((TLBCacheData[3] & 0xFF000000) >> 24); break;
+        case 11:
+          TLBCacheUnit = ((TLBCacheData[3] & 0x000000FF) >> 0);
+          break;
+        case 12:
+          TLBCacheUnit = ((TLBCacheData[3] & 0x0000FF00) >> 8);
+          break;
+        case 13:
+          TLBCacheUnit = ((TLBCacheData[3] & 0x00FF0000) >> 16);
+          break;
+        case 14:
+          TLBCacheUnit = ((TLBCacheData[3] & 0xFF000000) >> 24);
+          break;
 
         // Default case - an error has occurred.
-        default: return false;
-        }
+        default:
+          return false;
+      }
 
       // Now process the resulting unit to see what it means....
-      switch (TLBCacheUnit)
-        {
-        case 0x00: break;
-        case 0x01: STORE_TLBCACHE_INFO (TLBCode, 4); break;
-        case 0x02: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
-        case 0x03: STORE_TLBCACHE_INFO (TLBData, 4); break;
-        case 0x04: STORE_TLBCACHE_INFO (TLBData, 4096); break;
-        case 0x06: STORE_TLBCACHE_INFO (L1Code, 8); break;
-        case 0x08: STORE_TLBCACHE_INFO (L1Code, 16); break;
-        case 0x0a: STORE_TLBCACHE_INFO (L1Data, 8); break;
-        case 0x0c: STORE_TLBCACHE_INFO (L1Data, 16); break;
-        case 0x10: STORE_TLBCACHE_INFO (L1Data, 16); break;      // <-- FIXME: IA-64 Only
-        case 0x15: STORE_TLBCACHE_INFO (L1Code, 16); break;      // <-- FIXME: IA-64 Only
-        case 0x1a: STORE_TLBCACHE_INFO (L2Unified, 96); break;    // <-- FIXME: IA-64 Only
-        case 0x22: STORE_TLBCACHE_INFO (L3Unified, 512); break;
-        case 0x23: STORE_TLBCACHE_INFO (L3Unified, 1024); break;
-        case 0x25: STORE_TLBCACHE_INFO (L3Unified, 2048); break;
-        case 0x29: STORE_TLBCACHE_INFO (L3Unified, 4096); break;
-        case 0x39: STORE_TLBCACHE_INFO (L2Unified, 128); break;
-        case 0x3c: STORE_TLBCACHE_INFO (L2Unified, 256); break;
-        case 0x40: STORE_TLBCACHE_INFO (L2Unified, 0); break;    // <-- FIXME: No integrated L2 cache (P6 core) or L3 cache (P4 core).
-        case 0x41: STORE_TLBCACHE_INFO (L2Unified, 128); break;
-        case 0x42: STORE_TLBCACHE_INFO (L2Unified, 256); break;
-        case 0x43: STORE_TLBCACHE_INFO (L2Unified, 512); break;
-        case 0x44: STORE_TLBCACHE_INFO (L2Unified, 1024); break;
-        case 0x45: STORE_TLBCACHE_INFO (L2Unified, 2048); break;
-        case 0x50: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
-        case 0x51: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
-        case 0x52: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
-        case 0x5b: STORE_TLBCACHE_INFO (TLBData, 4096); break;
-        case 0x5c: STORE_TLBCACHE_INFO (TLBData, 4096); break;
-        case 0x5d: STORE_TLBCACHE_INFO (TLBData, 4096); break;
-        case 0x66: STORE_TLBCACHE_INFO (L1Data, 8); break;
-        case 0x67: STORE_TLBCACHE_INFO (L1Data, 16); break;
-        case 0x68: STORE_TLBCACHE_INFO (L1Data, 32); break;
-        case 0x70: STORE_TLBCACHE_INFO (L1Trace, 12); break;
-        case 0x71: STORE_TLBCACHE_INFO (L1Trace, 16); break;
-        case 0x72: STORE_TLBCACHE_INFO (L1Trace, 32); break;
-        case 0x77: STORE_TLBCACHE_INFO (L1Code, 16); break;      // <-- FIXME: IA-64 Only
-        case 0x79: STORE_TLBCACHE_INFO (L2Unified, 128); break;
-        case 0x7a: STORE_TLBCACHE_INFO (L2Unified, 256); break;
-        case 0x7b: STORE_TLBCACHE_INFO (L2Unified, 512); break;
-        case 0x7c: STORE_TLBCACHE_INFO (L2Unified, 1024); break;
-        case 0x7e: STORE_TLBCACHE_INFO (L2Unified, 256); break;
-        case 0x81: STORE_TLBCACHE_INFO (L2Unified, 128); break;
-        case 0x82: STORE_TLBCACHE_INFO (L2Unified, 256); break;
-        case 0x83: STORE_TLBCACHE_INFO (L2Unified, 512); break;
-        case 0x84: STORE_TLBCACHE_INFO (L2Unified, 1024); break;
-        case 0x85: STORE_TLBCACHE_INFO (L2Unified, 2048); break;
-        case 0x88: STORE_TLBCACHE_INFO (L3Unified, 2048); break;  // <-- FIXME: IA-64 Only
-        case 0x89: STORE_TLBCACHE_INFO (L3Unified, 4096); break;  // <-- FIXME: IA-64 Only
-        case 0x8a: STORE_TLBCACHE_INFO (L3Unified, 8192); break;  // <-- FIXME: IA-64 Only
-        case 0x8d: STORE_TLBCACHE_INFO (L3Unified, 3096); break;  // <-- FIXME: IA-64 Only
-        case 0x90: STORE_TLBCACHE_INFO (TLBCode, 262144); break;  // <-- FIXME: IA-64 Only
-        case 0x96: STORE_TLBCACHE_INFO (TLBCode, 262144); break;  // <-- FIXME: IA-64 Only
-        case 0x9b: STORE_TLBCACHE_INFO (TLBCode, 262144); break;  // <-- FIXME: IA-64 Only
+      switch (TLBCacheUnit) {
+        case 0x00:
+          break;
+        case 0x01:
+          STORE_TLBCACHE_INFO(TLBCode, 4);
+          break;
+        case 0x02:
+          STORE_TLBCACHE_INFO(TLBCode, 4096);
+          break;
+        case 0x03:
+          STORE_TLBCACHE_INFO(TLBData, 4);
+          break;
+        case 0x04:
+          STORE_TLBCACHE_INFO(TLBData, 4096);
+          break;
+        case 0x06:
+          STORE_TLBCACHE_INFO(L1Code, 8);
+          break;
+        case 0x08:
+          STORE_TLBCACHE_INFO(L1Code, 16);
+          break;
+        case 0x0a:
+          STORE_TLBCACHE_INFO(L1Data, 8);
+          break;
+        case 0x0c:
+          STORE_TLBCACHE_INFO(L1Data, 16);
+          break;
+        case 0x10:
+          STORE_TLBCACHE_INFO(L1Data, 16);
+          break; // <-- FIXME: IA-64 Only
+        case 0x15:
+          STORE_TLBCACHE_INFO(L1Code, 16);
+          break; // <-- FIXME: IA-64 Only
+        case 0x1a:
+          STORE_TLBCACHE_INFO(L2Unified, 96);
+          break; // <-- FIXME: IA-64 Only
+        case 0x22:
+          STORE_TLBCACHE_INFO(L3Unified, 512);
+          break;
+        case 0x23:
+          STORE_TLBCACHE_INFO(L3Unified, 1024);
+          break;
+        case 0x25:
+          STORE_TLBCACHE_INFO(L3Unified, 2048);
+          break;
+        case 0x29:
+          STORE_TLBCACHE_INFO(L3Unified, 4096);
+          break;
+        case 0x39:
+          STORE_TLBCACHE_INFO(L2Unified, 128);
+          break;
+        case 0x3c:
+          STORE_TLBCACHE_INFO(L2Unified, 256);
+          break;
+        case 0x40:
+          STORE_TLBCACHE_INFO(L2Unified, 0);
+          break; // <-- FIXME: No integrated L2 cache (P6 core) or L3 cache (P4
+                 // core).
+        case 0x41:
+          STORE_TLBCACHE_INFO(L2Unified, 128);
+          break;
+        case 0x42:
+          STORE_TLBCACHE_INFO(L2Unified, 256);
+          break;
+        case 0x43:
+          STORE_TLBCACHE_INFO(L2Unified, 512);
+          break;
+        case 0x44:
+          STORE_TLBCACHE_INFO(L2Unified, 1024);
+          break;
+        case 0x45:
+          STORE_TLBCACHE_INFO(L2Unified, 2048);
+          break;
+        case 0x50:
+          STORE_TLBCACHE_INFO(TLBCode, 4096);
+          break;
+        case 0x51:
+          STORE_TLBCACHE_INFO(TLBCode, 4096);
+          break;
+        case 0x52:
+          STORE_TLBCACHE_INFO(TLBCode, 4096);
+          break;
+        case 0x5b:
+          STORE_TLBCACHE_INFO(TLBData, 4096);
+          break;
+        case 0x5c:
+          STORE_TLBCACHE_INFO(TLBData, 4096);
+          break;
+        case 0x5d:
+          STORE_TLBCACHE_INFO(TLBData, 4096);
+          break;
+        case 0x66:
+          STORE_TLBCACHE_INFO(L1Data, 8);
+          break;
+        case 0x67:
+          STORE_TLBCACHE_INFO(L1Data, 16);
+          break;
+        case 0x68:
+          STORE_TLBCACHE_INFO(L1Data, 32);
+          break;
+        case 0x70:
+          STORE_TLBCACHE_INFO(L1Trace, 12);
+          break;
+        case 0x71:
+          STORE_TLBCACHE_INFO(L1Trace, 16);
+          break;
+        case 0x72:
+          STORE_TLBCACHE_INFO(L1Trace, 32);
+          break;
+        case 0x77:
+          STORE_TLBCACHE_INFO(L1Code, 16);
+          break; // <-- FIXME: IA-64 Only
+        case 0x79:
+          STORE_TLBCACHE_INFO(L2Unified, 128);
+          break;
+        case 0x7a:
+          STORE_TLBCACHE_INFO(L2Unified, 256);
+          break;
+        case 0x7b:
+          STORE_TLBCACHE_INFO(L2Unified, 512);
+          break;
+        case 0x7c:
+          STORE_TLBCACHE_INFO(L2Unified, 1024);
+          break;
+        case 0x7e:
+          STORE_TLBCACHE_INFO(L2Unified, 256);
+          break;
+        case 0x81:
+          STORE_TLBCACHE_INFO(L2Unified, 128);
+          break;
+        case 0x82:
+          STORE_TLBCACHE_INFO(L2Unified, 256);
+          break;
+        case 0x83:
+          STORE_TLBCACHE_INFO(L2Unified, 512);
+          break;
+        case 0x84:
+          STORE_TLBCACHE_INFO(L2Unified, 1024);
+          break;
+        case 0x85:
+          STORE_TLBCACHE_INFO(L2Unified, 2048);
+          break;
+        case 0x88:
+          STORE_TLBCACHE_INFO(L3Unified, 2048);
+          break; // <-- FIXME: IA-64 Only
+        case 0x89:
+          STORE_TLBCACHE_INFO(L3Unified, 4096);
+          break; // <-- FIXME: IA-64 Only
+        case 0x8a:
+          STORE_TLBCACHE_INFO(L3Unified, 8192);
+          break; // <-- FIXME: IA-64 Only
+        case 0x8d:
+          STORE_TLBCACHE_INFO(L3Unified, 3096);
+          break; // <-- FIXME: IA-64 Only
+        case 0x90:
+          STORE_TLBCACHE_INFO(TLBCode, 262144);
+          break; // <-- FIXME: IA-64 Only
+        case 0x96:
+          STORE_TLBCACHE_INFO(TLBCode, 262144);
+          break; // <-- FIXME: IA-64 Only
+        case 0x9b:
+          STORE_TLBCACHE_INFO(TLBCode, 262144);
+          break; // <-- FIXME: IA-64 Only
 
         // Default case - an error has occurred.
-        default: return false;
-        }
+        default:
+          return false;
       }
+    }
 
     // Increment the TLB pass counter.
-    TLBPassCounter ++;
-    } while ((TLBCacheData[0] & 0x000000FF) > TLBPassCounter);
+    TLBPassCounter++;
+  } while ((TLBCacheData[0] & 0x000000FF) > TLBPassCounter);
 
   // Ok - we now have the maximum TLB, L1, L2, and L3 sizes...
-  if ((L1Code == -1) && (L1Data == -1) && (L1Trace == -1))
-    {
+  if ((L1Code == -1) && (L1Data == -1) && (L1Trace == -1)) {
     this->Features.L1CacheSize = -1;
-    }
-  else if ((L1Code == -1) && (L1Data == -1) && (L1Trace != -1))
-    {
+  } else if ((L1Code == -1) && (L1Data == -1) && (L1Trace != -1)) {
     this->Features.L1CacheSize = L1Trace;
-    }
-  else if ((L1Code != -1) && (L1Data == -1))
-    {
+  } else if ((L1Code != -1) && (L1Data == -1)) {
     this->Features.L1CacheSize = L1Code;
-    }
-  else if ((L1Code == -1) && (L1Data != -1))
-    {
+  } else if ((L1Code == -1) && (L1Data != -1)) {
     this->Features.L1CacheSize = L1Data;
-    }
-  else if ((L1Code != -1) && (L1Data != -1))
-    {
+  } else if ((L1Code != -1) && (L1Data != -1)) {
     this->Features.L1CacheSize = L1Code + L1Data;
-    }
-  else
-    {
+  } else {
     this->Features.L1CacheSize = -1;
-    }
+  }
 
   // Ok - we now have the maximum TLB, L1, L2, and L3 sizes...
-  if (L2Unified == -1)
-    {
+  if (L2Unified == -1) {
     this->Features.L2CacheSize = -1;
-    }
-  else
-    {
+  } else {
     this->Features.L2CacheSize = L2Unified;
-    }
+  }
 
   // Ok - we now have the maximum TLB, L1, L2, and L3 sizes...
-  if (L3Unified == -1)
-    {
+  if (L3Unified == -1) {
     this->Features.L3CacheSize = -1;
-    }
-  else
-    {
+  } else {
     this->Features.L3CacheSize = L3Unified;
-    }
+  }
 
   return true;
 
@@ -2454,7 +2540,6 @@ bool SystemInformationImplementation::RetrieveClassicalCPUCacheDetails()
 #endif
 }
 
-
 /** */
 bool SystemInformationImplementation::RetrieveCPUClockSpeed()
 {
@@ -2463,22 +2548,19 @@ bool SystemInformationImplementation::RetrieveCPUClockSpeed()
 #if defined(_WIN32)
   unsigned int uiRepetitions = 1;
   unsigned int uiMSecPerRepetition = 50;
-  __int64  i64Total = 0;
+  __int64 i64Total = 0;
   __int64 i64Overhead = 0;
 
   // Check if the TSC implementation works at all
   if (this->Features.HasTSC &&
       GetCyclesDifference(SystemInformationImplementation::Delay,
-                          uiMSecPerRepetition) > 0)
-    {
-    for (unsigned int nCounter = 0; nCounter < uiRepetitions; nCounter ++)
-      {
-      i64Total += GetCyclesDifference (SystemInformationImplementation::Delay,
-                                       uiMSecPerRepetition);
-      i64Overhead +=
-        GetCyclesDifference (SystemInformationImplementation::DelayOverhead,
-                             uiMSecPerRepetition);
-      }
+                          uiMSecPerRepetition) > 0) {
+    for (unsigned int nCounter = 0; nCounter < uiRepetitions; nCounter++) {
+      i64Total += GetCyclesDifference(SystemInformationImplementation::Delay,
+                                      uiMSecPerRepetition);
+      i64Overhead += GetCyclesDifference(
+        SystemInformationImplementation::DelayOverhead, uiMSecPerRepetition);
+    }
 
     // Calculate the MHz speed.
     i64Total -= i64Overhead;
@@ -2487,45 +2569,42 @@ bool SystemInformationImplementation::RetrieveCPUClockSpeed()
     i64Total /= 1000;
 
     // Save the CPU speed.
-    this->CPUSpeedInMHz = (float) i64Total;
+    this->CPUSpeedInMHz = (float)i64Total;
 
     retrieved = true;
-    }
+  }
 
   // If RDTSC is not supported, we fallback to trying to read this value
   // from the registry:
-  if (!retrieved)
-    {
+  if (!retrieved) {
     HKEY hKey = NULL;
-    LONG err = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
-      L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0,
-      KEY_READ, &hKey);
+    LONG err =
+      RegOpenKeyExW(HKEY_LOCAL_MACHINE,
+                    L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0,
+                    KEY_READ, &hKey);
 
-    if (ERROR_SUCCESS == err)
-      {
+    if (ERROR_SUCCESS == err) {
       DWORD dwType = 0;
       DWORD data = 0;
       DWORD dwSize = sizeof(DWORD);
 
-      err = RegQueryValueExW(hKey, L"~MHz", 0,
-        &dwType, (LPBYTE) &data, &dwSize);
+      err =
+        RegQueryValueExW(hKey, L"~MHz", 0, &dwType, (LPBYTE)&data, &dwSize);
 
-      if (ERROR_SUCCESS == err)
-        {
-        this->CPUSpeedInMHz = (float) data;
+      if (ERROR_SUCCESS == err) {
+        this->CPUSpeedInMHz = (float)data;
         retrieved = true;
-        }
+      }
 
       RegCloseKey(hKey);
       hKey = NULL;
-      }
     }
+  }
 #endif
 
   return retrieved;
 }
 
-
 /** */
 bool SystemInformationImplementation::RetrieveClassicalCPUClockSpeed()
 {
@@ -2534,51 +2613,43 @@ bool SystemInformationImplementation::RetrieveClassicalCPUClockSpeed()
   double dFrequency, dDifference;
 
   // Attempt to get a starting tick count.
-  QueryPerformanceCounter (&liStart);
+  QueryPerformanceCounter(&liStart);
 
-  __try
-    {
-    _asm
-      {
+  __try {
+    _asm {
       mov eax, 0x80000000
       mov ebx, CLASSICAL_CPU_FREQ_LOOP
       Timer_Loop:
       bsf ecx,eax
       dec ebx
       jnz Timer_Loop
-      }
     }
-  __except(1)
-    {
+  } __except (1) {
     return false;
-    }
+  }
 
   // Attempt to get a starting tick count.
-  QueryPerformanceCounter (&liEnd);
+  QueryPerformanceCounter(&liEnd);
 
   // Get the difference...  NB: This is in seconds....
-  QueryPerformanceFrequency (&liCountsPerSecond);
-  dDifference = (((double) liEnd.QuadPart - (double) liStart.QuadPart) / (double) liCountsPerSecond.QuadPart);
+  QueryPerformanceFrequency(&liCountsPerSecond);
+  dDifference = (((double)liEnd.QuadPart - (double)liStart.QuadPart) /
+                 (double)liCountsPerSecond.QuadPart);
 
   // Calculate the clock speed.
-  if (this->ChipID.Family == 3)
-    {
+  if (this->ChipID.Family == 3) {
     // 80386 processors....  Loop time is 115 cycles!
     dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 115) / dDifference) / 1000000);
-    }
-  else if (this->ChipID.Family == 4)
-    {
+  } else if (this->ChipID.Family == 4) {
     // 80486 processors....  Loop time is 47 cycles!
     dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 47) / dDifference) / 1000000);
-    }
-  else if (this->ChipID.Family == 5)
-    {
+  } else if (this->ChipID.Family == 5) {
     // Pentium processors....  Loop time is 43 cycles!
     dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 43) / dDifference) / 1000000);
-    }
+  }
 
   // Save the clock speed.
-  this->Features.CPUSpeed = (int) dFrequency;
+  this->Features.CPUSpeed = (int)dFrequency;
 
   return true;
 
@@ -2587,13 +2658,14 @@ bool SystemInformationImplementation::RetrieveClassicalCPUClockSpeed()
 #endif
 }
 
-
 /** */
-bool SystemInformationImplementation::RetrieveCPUExtendedLevelSupport(int CPULevelToCheck)
+bool SystemInformationImplementation::RetrieveCPUExtendedLevelSupport(
+  int CPULevelToCheck)
 {
   int cpuinfo[4] = { 0, 0, 0, 0 };
 
-  // The extended CPUID is supported by various vendors starting with the following CPU models:
+  // The extended CPUID is supported by various vendors starting with the
+  // following CPU models:
   //
   //    Manufacturer & Chip Name      |    Family     Model    Revision
   //
@@ -2606,39 +2678,36 @@ bool SystemInformationImplementation::RetrieveCPUExtendedLevelSupport(int CPULev
   //
 
   // We check to see if a supported processor is present...
-  if (this->ChipManufacturer == AMD)
-    {
-    if (this->ChipID.Family < 5) return false;
-    if ((this->ChipID.Family == 5) && (this->ChipID.Model < 6)) return false;
-    }
-  else if (this->ChipManufacturer == Cyrix)
-    {
-    if (this->ChipID.Family < 5) return false;
-    if ((this->ChipID.Family == 5) && (this->ChipID.Model < 4)) return false;
-    if ((this->ChipID.Family == 6) && (this->ChipID.Model < 5)) return false;
-    }
-  else if (this->ChipManufacturer == IDT)
-    {
-    if (this->ChipID.Family < 5) return false;
-    if ((this->ChipID.Family == 5) && (this->ChipID.Model < 8)) return false;
-    }
-  else if (this->ChipManufacturer == Transmeta)
-    {
-    if (this->ChipID.Family < 5) return false;
-    }
-  else if (this->ChipManufacturer == Intel)
-    {
-    if (this->ChipID.Family < 0xf)
-      {
+  if (this->ChipManufacturer == AMD) {
+    if (this->ChipID.Family < 5)
+      return false;
+    if ((this->ChipID.Family == 5) && (this->ChipID.Model < 6))
+      return false;
+  } else if (this->ChipManufacturer == Cyrix) {
+    if (this->ChipID.Family < 5)
+      return false;
+    if ((this->ChipID.Family == 5) && (this->ChipID.Model < 4))
+      return false;
+    if ((this->ChipID.Family == 6) && (this->ChipID.Model < 5))
+      return false;
+  } else if (this->ChipManufacturer == IDT) {
+    if (this->ChipID.Family < 5)
+      return false;
+    if ((this->ChipID.Family == 5) && (this->ChipID.Model < 8))
+      return false;
+  } else if (this->ChipManufacturer == Transmeta) {
+    if (this->ChipID.Family < 5)
+      return false;
+  } else if (this->ChipManufacturer == Intel) {
+    if (this->ChipID.Family < 0xf) {
       return false;
-      }
     }
+  }
 
 #if USE_CPUID
-  if (!call_cpuid(0x80000000, cpuinfo))
-    {
+  if (!call_cpuid(0x80000000, cpuinfo)) {
     return false;
-    }
+  }
 #endif
 
   // Now we have to check the level wanted vs level returned...
@@ -2646,56 +2715,62 @@ bool SystemInformationImplementation::RetrieveCPUExtendedLevelSupport(int CPULev
   int nLevelReturn = (cpuinfo[0] & 0x7FFFFFFF);
 
   // Check to see if the level provided is supported...
-  if (nLevelWanted > nLevelReturn)
-    {
+  if (nLevelWanted > nLevelReturn) {
     return false;
-    }
+  }
 
   return true;
 }
 
-
 /** */
 bool SystemInformationImplementation::RetrieveExtendedCPUFeatures()
 {
 
-  // Check that we are not using an Intel processor as it does not support this.
-  if (this->ChipManufacturer == Intel)
-    {
+  // Check that we are not using an Intel processor as it does not support
+  // this.
+  if (this->ChipManufacturer == Intel) {
     return false;
-    }
+  }
 
   // Check to see if what we are about to do is supported...
-  if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000001)))
-    {
+  if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000001))) {
     return false;
-    }
+  }
 
 #if USE_CPUID
   int localCPUExtendedFeatures[4] = { 0, 0, 0, 0 };
 
-  if (!call_cpuid(0x80000001, localCPUExtendedFeatures))
-    {
+  if (!call_cpuid(0x80000001, localCPUExtendedFeatures)) {
     return false;
-    }
+  }
 
   // Retrieve the extended features of CPU present.
-  this->Features.ExtendedFeatures.Has3DNow =     ((localCPUExtendedFeatures[3] & 0x80000000) != 0);  // 3DNow Present --> Bit 31.
-  this->Features.ExtendedFeatures.Has3DNowPlus = ((localCPUExtendedFeatures[3] & 0x40000000) != 0);  // 3DNow+ Present -- > Bit 30.
-  this->Features.ExtendedFeatures.HasSSEMMX =    ((localCPUExtendedFeatures[3] & 0x00400000) != 0);  // SSE MMX Present --> Bit 22.
-  this->Features.ExtendedFeatures.SupportsMP =   ((localCPUExtendedFeatures[3] & 0x00080000) != 0);  // MP Capable -- > Bit 19.
+  this->Features.ExtendedFeatures.Has3DNow =
+    ((localCPUExtendedFeatures[3] & 0x80000000) !=
+     0); // 3DNow Present --> Bit 31.
+  this->Features.ExtendedFeatures.Has3DNowPlus =
+    ((localCPUExtendedFeatures[3] & 0x40000000) !=
+     0); // 3DNow+ Present -- > Bit 30.
+  this->Features.ExtendedFeatures.HasSSEMMX =
+    ((localCPUExtendedFeatures[3] & 0x00400000) !=
+     0); // SSE MMX Present --> Bit 22.
+  this->Features.ExtendedFeatures.SupportsMP =
+    ((localCPUExtendedFeatures[3] & 0x00080000) !=
+     0); // MP Capable -- > Bit 19.
 
   // Retrieve AMD specific extended features.
-  if (this->ChipManufacturer == AMD)
-    {
-    this->Features.ExtendedFeatures.HasMMXPlus = ((localCPUExtendedFeatures[3] & 0x00400000) != 0);  // AMD specific: MMX-SSE --> Bit 22
-    }
+  if (this->ChipManufacturer == AMD) {
+    this->Features.ExtendedFeatures.HasMMXPlus =
+      ((localCPUExtendedFeatures[3] & 0x00400000) !=
+       0); // AMD specific: MMX-SSE --> Bit 22
+  }
 
   // Retrieve Cyrix specific extended features.
-  if (this->ChipManufacturer == Cyrix)
-    {
-    this->Features.ExtendedFeatures.HasMMXPlus = ((localCPUExtendedFeatures[3] & 0x01000000) != 0);  // Cyrix specific: Extended MMX --> Bit 24
-    }
+  if (this->ChipManufacturer == Cyrix) {
+    this->Features.ExtendedFeatures.HasMMXPlus =
+      ((localCPUExtendedFeatures[3] & 0x01000000) !=
+       0); // Cyrix specific: Extended MMX --> Bit 24
+  }
 
   return true;
 
@@ -2704,42 +2779,40 @@ bool SystemInformationImplementation::RetrieveExtendedCPUFeatures()
 #endif
 }
 
-
 /** */
 bool SystemInformationImplementation::RetrieveProcessorSerialNumber()
 {
   // Check to see if the processor supports the processor serial number.
-  if (!this->Features.HasSerial)
-    {
+  if (!this->Features.HasSerial) {
     return false;
-    }
+  }
 
 #if USE_CPUID
   int SerialNumber[4];
 
-  if (!call_cpuid(3, SerialNumber))
-    {
+  if (!call_cpuid(3, SerialNumber)) {
     return false;
-    }
+  }
 
   // Process the returned information.
-  //    ; eax = 3 --> ebx: top 32 bits are the processor signature bits --> NB: Transmeta only ?!?
+  //    ; eax = 3 --> ebx: top 32 bits are the processor signature bits --> NB:
+  //    Transmeta only ?!?
   //    ;        ecx: middle 32 bits are the processor signature bits
   //    ;        edx: bottom 32 bits are the processor signature bits
   char sn[128];
-  sprintf (sn, "%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x",
-       ((SerialNumber[1] & 0xff000000) >> 24),
-       ((SerialNumber[1] & 0x00ff0000) >> 16),
-       ((SerialNumber[1] & 0x0000ff00) >> 8),
-       ((SerialNumber[1] & 0x000000ff) >> 0),
-       ((SerialNumber[2] & 0xff000000) >> 24),
-       ((SerialNumber[2] & 0x00ff0000) >> 16),
-       ((SerialNumber[2] & 0x0000ff00) >> 8),
-       ((SerialNumber[2] & 0x000000ff) >> 0),
-       ((SerialNumber[3] & 0xff000000) >> 24),
-       ((SerialNumber[3] & 0x00ff0000) >> 16),
-       ((SerialNumber[3] & 0x0000ff00) >> 8),
-       ((SerialNumber[3] & 0x000000ff) >> 0));
+  sprintf(sn, "%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x",
+          ((SerialNumber[1] & 0xff000000) >> 24),
+          ((SerialNumber[1] & 0x00ff0000) >> 16),
+          ((SerialNumber[1] & 0x0000ff00) >> 8),
+          ((SerialNumber[1] & 0x000000ff) >> 0),
+          ((SerialNumber[2] & 0xff000000) >> 24),
+          ((SerialNumber[2] & 0x00ff0000) >> 16),
+          ((SerialNumber[2] & 0x0000ff00) >> 8),
+          ((SerialNumber[2] & 0x000000ff) >> 0),
+          ((SerialNumber[3] & 0xff000000) >> 24),
+          ((SerialNumber[3] & 0x00ff0000) >> 16),
+          ((SerialNumber[3] & 0x0000ff00) >> 8),
+          ((SerialNumber[3] & 0x000000ff) >> 0));
   this->ChipID.SerialNumber = sn;
   return true;
 
@@ -2748,31 +2821,31 @@ bool SystemInformationImplementation::RetrieveProcessorSerialNumber()
 #endif
 }
 
-
 /** */
 bool SystemInformationImplementation::RetrieveCPUPowerManagement()
 {
   // Check to see if what we are about to do is supported...
-  if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000007)))
-    {
+  if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000007))) {
     this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID = false;
     this->Features.ExtendedFeatures.PowerManagement.HasVoltageID = false;
     this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode = false;
     return false;
-    }
+  }
 
 #if USE_CPUID
   int localCPUPowerManagement[4] = { 0, 0, 0, 0 };
 
-  if (!call_cpuid(0x80000007, localCPUPowerManagement))
-    {
+  if (!call_cpuid(0x80000007, localCPUPowerManagement)) {
     return false;
-    }
+  }
 
   // Check for the power management capabilities of the CPU.
-  this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode =  ((localCPUPowerManagement[3] & 0x00000001) != 0);
-  this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID =     ((localCPUPowerManagement[3] & 0x00000002) != 0);
-  this->Features.ExtendedFeatures.PowerManagement.HasVoltageID =       ((localCPUPowerManagement[3] & 0x00000004) != 0);
+  this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode =
+    ((localCPUPowerManagement[3] & 0x00000001) != 0);
+  this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID =
+    ((localCPUPowerManagement[3] & 0x00000002) != 0);
+  this->Features.ExtendedFeatures.PowerManagement.HasVoltageID =
+    ((localCPUPowerManagement[3] & 0x00000004) != 0);
 
   return true;
 
@@ -2785,12 +2858,12 @@ bool SystemInformationImplementation::RetrieveCPUPowerManagement()
 // Used only in USE_CPUID implementation below.
 static void SystemInformationStripLeadingSpace(std::string& str)
 {
-  // Because some manufacturers have leading white space - we have to post-process the name.
+  // Because some manufacturers have leading white space - we have to
+  // post-process the name.
   std::string::size_type pos = str.find_first_not_of(" ");
-  if(pos != std::string::npos)
-    {
+  if (pos != std::string::npos) {
     str = str.substr(pos);
-    }
+  }
 }
 #endif
 
@@ -2808,38 +2881,36 @@ bool SystemInformationImplementation::RetrieveExtendedCPUIdentity()
 #if USE_CPUID
   int CPUExtendedIdentity[12];
 
-  if (!call_cpuid(0x80000002, CPUExtendedIdentity))
-    {
+  if (!call_cpuid(0x80000002, CPUExtendedIdentity)) {
     return false;
-    }
-  if (!call_cpuid(0x80000003, CPUExtendedIdentity + 4))
-    {
+  }
+  if (!call_cpuid(0x80000003, CPUExtendedIdentity + 4)) {
     return false;
-    }
-  if (!call_cpuid(0x80000004, CPUExtendedIdentity + 8))
-    {
+  }
+  if (!call_cpuid(0x80000004, CPUExtendedIdentity + 8)) {
     return false;
-    }
+  }
 
   // Process the returned information.
   char nbuf[49];
-  memcpy (&(nbuf[0]), &(CPUExtendedIdentity[0]), sizeof (int));
-  memcpy (&(nbuf[4]), &(CPUExtendedIdentity[1]), sizeof (int));
-  memcpy (&(nbuf[8]), &(CPUExtendedIdentity[2]), sizeof (int));
-  memcpy (&(nbuf[12]), &(CPUExtendedIdentity[3]), sizeof (int));
-  memcpy (&(nbuf[16]), &(CPUExtendedIdentity[4]), sizeof (int));
-  memcpy (&(nbuf[20]), &(CPUExtendedIdentity[5]), sizeof (int));
-  memcpy (&(nbuf[24]), &(CPUExtendedIdentity[6]), sizeof (int));
-  memcpy (&(nbuf[28]), &(CPUExtendedIdentity[7]), sizeof (int));
-  memcpy (&(nbuf[32]), &(CPUExtendedIdentity[8]), sizeof (int));
-  memcpy (&(nbuf[36]), &(CPUExtendedIdentity[9]), sizeof (int));
-  memcpy (&(nbuf[40]), &(CPUExtendedIdentity[10]), sizeof (int));
-  memcpy (&(nbuf[44]), &(CPUExtendedIdentity[11]), sizeof (int));
+  memcpy(&(nbuf[0]), &(CPUExtendedIdentity[0]), sizeof(int));
+  memcpy(&(nbuf[4]), &(CPUExtendedIdentity[1]), sizeof(int));
+  memcpy(&(nbuf[8]), &(CPUExtendedIdentity[2]), sizeof(int));
+  memcpy(&(nbuf[12]), &(CPUExtendedIdentity[3]), sizeof(int));
+  memcpy(&(nbuf[16]), &(CPUExtendedIdentity[4]), sizeof(int));
+  memcpy(&(nbuf[20]), &(CPUExtendedIdentity[5]), sizeof(int));
+  memcpy(&(nbuf[24]), &(CPUExtendedIdentity[6]), sizeof(int));
+  memcpy(&(nbuf[28]), &(CPUExtendedIdentity[7]), sizeof(int));
+  memcpy(&(nbuf[32]), &(CPUExtendedIdentity[8]), sizeof(int));
+  memcpy(&(nbuf[36]), &(CPUExtendedIdentity[9]), sizeof(int));
+  memcpy(&(nbuf[40]), &(CPUExtendedIdentity[10]), sizeof(int));
+  memcpy(&(nbuf[44]), &(CPUExtendedIdentity[11]), sizeof(int));
   nbuf[48] = '\0';
   this->ChipID.ProcessorName = nbuf;
   this->ChipID.ModelName = nbuf;
 
-  // Because some manufacturers have leading white space - we have to post-process the name.
+  // Because some manufacturers have leading white space - we have to
+  // post-process the name.
   SystemInformationStripLeadingSpace(this->ChipID.ProcessorName);
   return true;
 #else
@@ -2847,270 +2918,420 @@ bool SystemInformationImplementation::RetrieveExtendedCPUIdentity()
 #endif
 }
 
-
 /** */
 bool SystemInformationImplementation::RetrieveClassicalCPUIdentity()
 {
   // Start by decided which manufacturer we are using....
-  switch (this->ChipManufacturer)
-    {
+  switch (this->ChipManufacturer) {
     case Intel:
       // Check the family / model / revision to determine the CPU ID.
       switch (this->ChipID.Family) {
         case 3:
-          this->ChipID.ProcessorName =  "Newer i80386 family";
+          this->ChipID.ProcessorName = "Newer i80386 family";
           break;
         case 4:
           switch (this->ChipID.Model) {
-            case 0: this->ChipID.ProcessorName = "i80486DX-25/33"; break;
-            case 1: this->ChipID.ProcessorName = "i80486DX-50"; break;
-            case 2: this->ChipID.ProcessorName = "i80486SX"; break;
-            case 3: this->ChipID.ProcessorName = "i80486DX2"; break;
-            case 4: this->ChipID.ProcessorName = "i80486SL"; break;
-            case 5: this->ChipID.ProcessorName = "i80486SX2"; break;
-            case 7: this->ChipID.ProcessorName = "i80486DX2 WriteBack"; break;
-            case 8: this->ChipID.ProcessorName = "i80486DX4"; break;
-            case 9: this->ChipID.ProcessorName = "i80486DX4 WriteBack"; break;
-            default: this->ChipID.ProcessorName = "Unknown 80486 family"; return false;
-            }
+            case 0:
+              this->ChipID.ProcessorName = "i80486DX-25/33";
+              break;
+            case 1:
+              this->ChipID.ProcessorName = "i80486DX-50";
+              break;
+            case 2:
+              this->ChipID.ProcessorName = "i80486SX";
+              break;
+            case 3:
+              this->ChipID.ProcessorName = "i80486DX2";
+              break;
+            case 4:
+              this->ChipID.ProcessorName = "i80486SL";
+              break;
+            case 5:
+              this->ChipID.ProcessorName = "i80486SX2";
+              break;
+            case 7:
+              this->ChipID.ProcessorName = "i80486DX2 WriteBack";
+              break;
+            case 8:
+              this->ChipID.ProcessorName = "i80486DX4";
+              break;
+            case 9:
+              this->ChipID.ProcessorName = "i80486DX4 WriteBack";
+              break;
+            default:
+              this->ChipID.ProcessorName = "Unknown 80486 family";
+              return false;
+          }
           break;
         case 5:
-          switch (this->ChipID.Model)
-            {
-            case 0: this->ChipID.ProcessorName = "P5 A-Step"; break;
-            case 1: this->ChipID.ProcessorName = "P5"; break;
-            case 2: this->ChipID.ProcessorName = "P54C"; break;
-            case 3: this->ChipID.ProcessorName = "P24T OverDrive"; break;
-            case 4: this->ChipID.ProcessorName = "P55C"; break;
-            case 7: this->ChipID.ProcessorName = "P54C"; break;
-            case 8: this->ChipID.ProcessorName = "P55C (0.25micron)"; break;
-            default: this->ChipID.ProcessorName = "Unknown Pentium family"; return false;
-            }
+          switch (this->ChipID.Model) {
+            case 0:
+              this->ChipID.ProcessorName = "P5 A-Step";
+              break;
+            case 1:
+              this->ChipID.ProcessorName = "P5";
+              break;
+            case 2:
+              this->ChipID.ProcessorName = "P54C";
+              break;
+            case 3:
+              this->ChipID.ProcessorName = "P24T OverDrive";
+              break;
+            case 4:
+              this->ChipID.ProcessorName = "P55C";
+              break;
+            case 7:
+              this->ChipID.ProcessorName = "P54C";
+              break;
+            case 8:
+              this->ChipID.ProcessorName = "P55C (0.25micron)";
+              break;
+            default:
+              this->ChipID.ProcessorName = "Unknown Pentium family";
+              return false;
+          }
           break;
         case 6:
-          switch (this->ChipID.Model)
-            {
-            case 0: this->ChipID.ProcessorName = "P6 A-Step"; break;
-            case 1: this->ChipID.ProcessorName = "P6"; break;
-            case 3: this->ChipID.ProcessorName = "Pentium II (0.28 micron)"; break;
-            case 5: this->ChipID.ProcessorName = "Pentium II (0.25 micron)"; break;
-            case 6: this->ChipID.ProcessorName = "Pentium II With On-Die L2 Cache"; break;
-            case 7: this->ChipID.ProcessorName = "Pentium III (0.25 micron)"; break;
-            case 8: this->ChipID.ProcessorName = "Pentium III (0.18 micron) With 256 KB On-Die L2 Cache "; break;
-            case 0xa: this->ChipID.ProcessorName = "Pentium III (0.18 micron) With 1 Or 2 MB On-Die L2 Cache "; break;
-            case 0xb: this->ChipID.ProcessorName = "Pentium III (0.13 micron) With 256 Or 512 KB On-Die L2 Cache "; break;
-            case 23: this->ChipID.ProcessorName =  "Intel(R) Core(TM)2 Duo CPU     T9500  @ 2.60GHz"; break;
-            default: this->ChipID.ProcessorName = "Unknown P6 family"; return false;
-            }
+          switch (this->ChipID.Model) {
+            case 0:
+              this->ChipID.ProcessorName = "P6 A-Step";
+              break;
+            case 1:
+              this->ChipID.ProcessorName = "P6";
+              break;
+            case 3:
+              this->ChipID.ProcessorName = "Pentium II (0.28 micron)";
+              break;
+            case 5:
+              this->ChipID.ProcessorName = "Pentium II (0.25 micron)";
+              break;
+            case 6:
+              this->ChipID.ProcessorName = "Pentium II With On-Die L2 Cache";
+              break;
+            case 7:
+              this->ChipID.ProcessorName = "Pentium III (0.25 micron)";
+              break;
+            case 8:
+              this->ChipID.ProcessorName =
+                "Pentium III (0.18 micron) With 256 KB On-Die L2 Cache ";
+              break;
+            case 0xa:
+              this->ChipID.ProcessorName =
+                "Pentium III (0.18 micron) With 1 Or 2 MB On-Die L2 Cache ";
+              break;
+            case 0xb:
+              this->ChipID.ProcessorName = "Pentium III (0.13 micron) With "
+                                           "256 Or 512 KB On-Die L2 Cache ";
+              break;
+            case 23:
+              this->ChipID.ProcessorName =
+                "Intel(R) Core(TM)2 Duo CPU     T9500  @ 2.60GHz";
+              break;
+            default:
+              this->ChipID.ProcessorName = "Unknown P6 family";
+              return false;
+          }
           break;
         case 7:
           this->ChipID.ProcessorName = "Intel Merced (IA-64)";
           break;
         case 0xf:
           // Check the extended family bits...
-          switch (this->ChipID.ExtendedFamily)
-            {
+          switch (this->ChipID.ExtendedFamily) {
             case 0:
-              switch (this->ChipID.Model)
-                {
-                case 0: this->ChipID.ProcessorName = "Pentium IV (0.18 micron)"; break;
-                case 1: this->ChipID.ProcessorName = "Pentium IV (0.18 micron)"; break;
-                case 2: this->ChipID.ProcessorName = "Pentium IV (0.13 micron)"; break;
-                default: this->ChipID.ProcessorName = "Unknown Pentium 4 family"; return false;
-                }
+              switch (this->ChipID.Model) {
+                case 0:
+                  this->ChipID.ProcessorName = "Pentium IV (0.18 micron)";
+                  break;
+                case 1:
+                  this->ChipID.ProcessorName = "Pentium IV (0.18 micron)";
+                  break;
+                case 2:
+                  this->ChipID.ProcessorName = "Pentium IV (0.13 micron)";
+                  break;
+                default:
+                  this->ChipID.ProcessorName = "Unknown Pentium 4 family";
+                  return false;
+              }
               break;
             case 1:
               this->ChipID.ProcessorName = "Intel McKinley (IA-64)";
               break;
             default:
               this->ChipID.ProcessorName = "Pentium";
-            }
+          }
           break;
         default:
           this->ChipID.ProcessorName = "Unknown Intel family";
           return false;
-        }
+      }
       break;
 
     case AMD:
       // Check the family / model / revision to determine the CPU ID.
-      switch (this->ChipID.Family)
-        {
+      switch (this->ChipID.Family) {
         case 4:
-          switch (this->ChipID.Model)
-            {
-            case 3: this->ChipID.ProcessorName = "80486DX2"; break;
-            case 7: this->ChipID.ProcessorName = "80486DX2 WriteBack"; break;
-            case 8: this->ChipID.ProcessorName = "80486DX4"; break;
-            case 9: this->ChipID.ProcessorName = "80486DX4 WriteBack"; break;
-            case 0xe: this->ChipID.ProcessorName = "5x86"; break;
-            case 0xf: this->ChipID.ProcessorName = "5x86WB"; break;
-            default: this->ChipID.ProcessorName = "Unknown 80486 family"; return false;
-            }
+          switch (this->ChipID.Model) {
+            case 3:
+              this->ChipID.ProcessorName = "80486DX2";
+              break;
+            case 7:
+              this->ChipID.ProcessorName = "80486DX2 WriteBack";
+              break;
+            case 8:
+              this->ChipID.ProcessorName = "80486DX4";
+              break;
+            case 9:
+              this->ChipID.ProcessorName = "80486DX4 WriteBack";
+              break;
+            case 0xe:
+              this->ChipID.ProcessorName = "5x86";
+              break;
+            case 0xf:
+              this->ChipID.ProcessorName = "5x86WB";
+              break;
+            default:
+              this->ChipID.ProcessorName = "Unknown 80486 family";
+              return false;
+          }
           break;
         case 5:
-          switch (this->ChipID.Model)
-            {
-            case 0: this->ChipID.ProcessorName = "SSA5 (PR75, PR90 =  PR100)"; break;
-            case 1: this->ChipID.ProcessorName = "5k86 (PR120 =  PR133)"; break;
-            case 2: this->ChipID.ProcessorName = "5k86 (PR166)"; break;
-            case 3: this->ChipID.ProcessorName = "5k86 (PR200)"; break;
-            case 6: this->ChipID.ProcessorName = "K6 (0.30 micron)"; break;
-            case 7: this->ChipID.ProcessorName = "K6 (0.25 micron)"; break;
-            case 8: this->ChipID.ProcessorName = "K6-2"; break;
-            case 9: this->ChipID.ProcessorName = "K6-III"; break;
-            case 0xd: this->ChipID.ProcessorName = "K6-2+ or K6-III+ (0.18 micron)"; break;
-            default: this->ChipID.ProcessorName = "Unknown 80586 family"; return false;
-            }
+          switch (this->ChipID.Model) {
+            case 0:
+              this->ChipID.ProcessorName = "SSA5 (PR75, PR90 =  PR100)";
+              break;
+            case 1:
+              this->ChipID.ProcessorName = "5k86 (PR120 =  PR133)";
+              break;
+            case 2:
+              this->ChipID.ProcessorName = "5k86 (PR166)";
+              break;
+            case 3:
+              this->ChipID.ProcessorName = "5k86 (PR200)";
+              break;
+            case 6:
+              this->ChipID.ProcessorName = "K6 (0.30 micron)";
+              break;
+            case 7:
+              this->ChipID.ProcessorName = "K6 (0.25 micron)";
+              break;
+            case 8:
+              this->ChipID.ProcessorName = "K6-2";
+              break;
+            case 9:
+              this->ChipID.ProcessorName = "K6-III";
+              break;
+            case 0xd:
+              this->ChipID.ProcessorName = "K6-2+ or K6-III+ (0.18 micron)";
+              break;
+            default:
+              this->ChipID.ProcessorName = "Unknown 80586 family";
+              return false;
+          }
           break;
         case 6:
-          switch (this->ChipID.Model)
-            {
-            case 1: this->ChipID.ProcessorName = "Athlon- (0.25 micron)"; break;
-            case 2: this->ChipID.ProcessorName = "Athlon- (0.18 micron)"; break;
-            case 3: this->ChipID.ProcessorName = "Duron- (SF core)"; break;
-            case 4: this->ChipID.ProcessorName = "Athlon- (Thunderbird core)"; break;
-            case 6: this->ChipID.ProcessorName = "Athlon- (Palomino core)"; break;
-            case 7: this->ChipID.ProcessorName = "Duron- (Morgan core)"; break;
+          switch (this->ChipID.Model) {
+            case 1:
+              this->ChipID.ProcessorName = "Athlon- (0.25 micron)";
+              break;
+            case 2:
+              this->ChipID.ProcessorName = "Athlon- (0.18 micron)";
+              break;
+            case 3:
+              this->ChipID.ProcessorName = "Duron- (SF core)";
+              break;
+            case 4:
+              this->ChipID.ProcessorName = "Athlon- (Thunderbird core)";
+              break;
+            case 6:
+              this->ChipID.ProcessorName = "Athlon- (Palomino core)";
+              break;
+            case 7:
+              this->ChipID.ProcessorName = "Duron- (Morgan core)";
+              break;
             case 8:
               if (this->Features.ExtendedFeatures.SupportsMP)
                 this->ChipID.ProcessorName = "Athlon - MP (Thoroughbred core)";
-              else this->ChipID.ProcessorName = "Athlon - XP (Thoroughbred core)";
+              else
+                this->ChipID.ProcessorName = "Athlon - XP (Thoroughbred core)";
               break;
-            default: this->ChipID.ProcessorName = "Unknown K7 family"; return false;
-            }
+            default:
+              this->ChipID.ProcessorName = "Unknown K7 family";
+              return false;
+          }
           break;
         default:
           this->ChipID.ProcessorName = "Unknown AMD family";
           return false;
-        }
+      }
       break;
 
     case Transmeta:
-      switch (this->ChipID.Family)
-        {
+      switch (this->ChipID.Family) {
         case 5:
-          switch (this->ChipID.Model)
-            {
-            case 4: this->ChipID.ProcessorName = "Crusoe TM3x00 and TM5x00"; break;
-            default: this->ChipID.ProcessorName = "Unknown Crusoe family"; return false;
-            }
+          switch (this->ChipID.Model) {
+            case 4:
+              this->ChipID.ProcessorName = "Crusoe TM3x00 and TM5x00";
+              break;
+            default:
+              this->ChipID.ProcessorName = "Unknown Crusoe family";
+              return false;
+          }
           break;
         default:
           this->ChipID.ProcessorName = "Unknown Transmeta family";
           return false;
-        }
+      }
       break;
 
     case Rise:
-      switch (this->ChipID.Family)
-        {
+      switch (this->ChipID.Family) {
         case 5:
-          switch (this->ChipID.Model)
-            {
-            case 0: this->ChipID.ProcessorName = "mP6 (0.25 micron)"; break;
-            case 2: this->ChipID.ProcessorName = "mP6 (0.18 micron)"; break;
-            default: this->ChipID.ProcessorName = "Unknown Rise family"; return false;
-            }
+          switch (this->ChipID.Model) {
+            case 0:
+              this->ChipID.ProcessorName = "mP6 (0.25 micron)";
+              break;
+            case 2:
+              this->ChipID.ProcessorName = "mP6 (0.18 micron)";
+              break;
+            default:
+              this->ChipID.ProcessorName = "Unknown Rise family";
+              return false;
+          }
           break;
         default:
           this->ChipID.ProcessorName = "Unknown Rise family";
           return false;
-        }
+      }
       break;
 
     case UMC:
-      switch (this->ChipID.Family)
-        {
+      switch (this->ChipID.Family) {
         case 4:
-          switch (this->ChipID.Model)
-            {
-            case 1: this->ChipID.ProcessorName = "U5D"; break;
-            case 2: this->ChipID.ProcessorName = "U5S"; break;
-            default: this->ChipID.ProcessorName = "Unknown UMC family"; return false;
-            }
+          switch (this->ChipID.Model) {
+            case 1:
+              this->ChipID.ProcessorName = "U5D";
+              break;
+            case 2:
+              this->ChipID.ProcessorName = "U5S";
+              break;
+            default:
+              this->ChipID.ProcessorName = "Unknown UMC family";
+              return false;
+          }
           break;
         default:
           this->ChipID.ProcessorName = "Unknown UMC family";
           return false;
-        }
+      }
       break;
 
     case IDT:
-      switch (this->ChipID.Family)
-        {
+      switch (this->ChipID.Family) {
         case 5:
-          switch (this->ChipID.Model)
-            {
-            case 4: this->ChipID.ProcessorName = "C6"; break;
-            case 8: this->ChipID.ProcessorName = "C2"; break;
-            case 9: this->ChipID.ProcessorName = "C3"; break;
-            default: this->ChipID.ProcessorName = "Unknown IDT\\Centaur family"; return false;
-            }
+          switch (this->ChipID.Model) {
+            case 4:
+              this->ChipID.ProcessorName = "C6";
+              break;
+            case 8:
+              this->ChipID.ProcessorName = "C2";
+              break;
+            case 9:
+              this->ChipID.ProcessorName = "C3";
+              break;
+            default:
+              this->ChipID.ProcessorName = "Unknown IDT\\Centaur family";
+              return false;
+          }
           break;
         case 6:
-          switch (this->ChipID.Model)
-            {
-            case 6: this->ChipID.ProcessorName = "VIA Cyrix III - Samuel"; break;
-            default: this->ChipID.ProcessorName = "Unknown IDT\\Centaur family"; return false;
-            }
+          switch (this->ChipID.Model) {
+            case 6:
+              this->ChipID.ProcessorName = "VIA Cyrix III - Samuel";
+              break;
+            default:
+              this->ChipID.ProcessorName = "Unknown IDT\\Centaur family";
+              return false;
+          }
           break;
         default:
           this->ChipID.ProcessorName = "Unknown IDT\\Centaur family";
           return false;
-        }
+      }
       break;
 
     case Cyrix:
-      switch (this->ChipID.Family)
-        {
+      switch (this->ChipID.Family) {
         case 4:
-          switch (this->ChipID.Model)
-            {
-            case 4: this->ChipID.ProcessorName = "MediaGX GX =  GXm"; break;
-            case 9: this->ChipID.ProcessorName = "5x86"; break;
-            default: this->ChipID.ProcessorName = "Unknown Cx5x86 family"; return false;
-            }
+          switch (this->ChipID.Model) {
+            case 4:
+              this->ChipID.ProcessorName = "MediaGX GX =  GXm";
+              break;
+            case 9:
+              this->ChipID.ProcessorName = "5x86";
+              break;
+            default:
+              this->ChipID.ProcessorName = "Unknown Cx5x86 family";
+              return false;
+          }
           break;
         case 5:
-          switch (this->ChipID.Model)
-            {
-            case 2: this->ChipID.ProcessorName = "Cx6x86"; break;
-            case 4: this->ChipID.ProcessorName = "MediaGX GXm"; break;
-            default: this->ChipID.ProcessorName = "Unknown Cx6x86 family"; return false;
-            }
+          switch (this->ChipID.Model) {
+            case 2:
+              this->ChipID.ProcessorName = "Cx6x86";
+              break;
+            case 4:
+              this->ChipID.ProcessorName = "MediaGX GXm";
+              break;
+            default:
+              this->ChipID.ProcessorName = "Unknown Cx6x86 family";
+              return false;
+          }
           break;
         case 6:
-          switch (this->ChipID.Model)
-            {
-            case 0: this->ChipID.ProcessorName = "6x86MX"; break;
-            case 5: this->ChipID.ProcessorName = "Cyrix M2 Core"; break;
-            case 6: this->ChipID.ProcessorName = "WinChip C5A Core"; break;
-            case 7: this->ChipID.ProcessorName = "WinChip C5B\\C5C Core"; break;
-            case 8: this->ChipID.ProcessorName = "WinChip C5C-T Core"; break;
-            default: this->ChipID.ProcessorName = "Unknown 6x86MX\\Cyrix III family"; return false;
-            }
+          switch (this->ChipID.Model) {
+            case 0:
+              this->ChipID.ProcessorName = "6x86MX";
+              break;
+            case 5:
+              this->ChipID.ProcessorName = "Cyrix M2 Core";
+              break;
+            case 6:
+              this->ChipID.ProcessorName = "WinChip C5A Core";
+              break;
+            case 7:
+              this->ChipID.ProcessorName = "WinChip C5B\\C5C Core";
+              break;
+            case 8:
+              this->ChipID.ProcessorName = "WinChip C5C-T Core";
+              break;
+            default:
+              this->ChipID.ProcessorName = "Unknown 6x86MX\\Cyrix III family";
+              return false;
+          }
           break;
         default:
           this->ChipID.ProcessorName = "Unknown Cyrix family";
           return false;
-        }
+      }
       break;
 
     case NexGen:
-      switch (this->ChipID.Family)
-        {
+      switch (this->ChipID.Family) {
         case 5:
-          switch (this->ChipID.Model)
-            {
-            case 0: this->ChipID.ProcessorName = "Nx586 or Nx586FPU"; break;
-            default: this->ChipID.ProcessorName = "Unknown NexGen family"; return false;
-            }
+          switch (this->ChipID.Model) {
+            case 0:
+              this->ChipID.ProcessorName = "Nx586 or Nx586FPU";
+              break;
+            default:
+              this->ChipID.ProcessorName = "Unknown NexGen family";
+              return false;
+          }
           break;
         default:
           this->ChipID.ProcessorName = "Unknown NexGen family";
           return false;
-        }
+      }
       break;
 
     case NSC:
@@ -3123,38 +3344,38 @@ bool SystemInformationImplementation::RetrieveClassicalCPUIdentity()
     case HP:
     case UnknownManufacturer:
     default:
-      this->ChipID.ProcessorName = "Unknown family"; // We cannot identify the processor.
+      this->ChipID.ProcessorName =
+        "Unknown family"; // We cannot identify the processor.
       return false;
-    }
+  }
 
   return true;
 }
 
-
 /** Extract a value from the CPUInfo file */
-std::string SystemInformationImplementation::ExtractValueFromCpuInfoFile(std::string buffer,const char* word,size_t init)
+std::string SystemInformationImplementation::ExtractValueFromCpuInfoFile(
+  std::string buffer, const char* word, size_t init)
 {
-  size_t pos = buffer.find(word,init);
-  if(pos != buffer.npos)
-    {
+  size_t pos = buffer.find(word, init);
+  if (pos != buffer.npos) {
     this->CurrentPositionInFile = pos;
-    pos = buffer.find(":",pos);
-    size_t pos2 = buffer.find("\n",pos);
-    if(pos!=buffer.npos && pos2!=buffer.npos)
-      {
-      // It may happen that the beginning matches, but this is still not the requested key.
-      // An example is looking for "cpu" when "cpu family" comes first. So we check that
+    pos = buffer.find(":", pos);
+    size_t pos2 = buffer.find("\n", pos);
+    if (pos != buffer.npos && pos2 != buffer.npos) {
+      // It may happen that the beginning matches, but this is still not the
+      // requested key.
+      // An example is looking for "cpu" when "cpu family" comes first. So we
+      // check that
       // we have only spaces from here to pos, otherwise we search again.
-      for(size_t i=this->CurrentPositionInFile+strlen(word); i < pos; ++i)
-        {
-        if(buffer[i] != ' ' && buffer[i] != '\t')
-          {
+      for (size_t i = this->CurrentPositionInFile + strlen(word); i < pos;
+           ++i) {
+        if (buffer[i] != ' ' && buffer[i] != '\t') {
           return this->ExtractValueFromCpuInfoFile(buffer, word, pos2);
-          }
         }
-      return buffer.substr(pos+2,pos2-pos-2);
       }
+      return buffer.substr(pos + 2, pos2 - pos - 2);
     }
+  }
   this->CurrentPositionInFile = buffer.npos;
   return "";
 }
@@ -3166,113 +3387,98 @@ bool SystemInformationImplementation::RetreiveInformationFromCpuInfoFile()
   this->NumberOfPhysicalCPU = 0;
   std::string buffer;
 
-  FILE *fd = fopen("/proc/cpuinfo", "r" );
-  if ( !fd )
-    {
+  FILE* fd = fopen("/proc/cpuinfo", "r");
+  if (!fd) {
     std::cout << "Problem opening /proc/cpuinfo" << std::endl;
     return false;
-    }
+  }
 
   size_t fileSize = 0;
-  while(!feof(fd))
-    {
+  while (!feof(fd)) {
     buffer += static_cast<char>(fgetc(fd));
     fileSize++;
-    }
-  fclose( fd );
-  buffer.resize(fileSize-2);
+  }
+  fclose(fd);
+  buffer.resize(fileSize - 2);
   // Number of logical CPUs (combination of multiple processors, multi-core
   // and hyperthreading)
   size_t pos = buffer.find("processor\t");
-  while(pos != buffer.npos)
-    {
+  while (pos != buffer.npos) {
     this->NumberOfLogicalCPU++;
-    pos = buffer.find("processor\t",pos+1);
-    }
+    pos = buffer.find("processor\t", pos + 1);
+  }
 
 #ifdef __linux
   // Find the largest physical id.
-  int maxId = -1;
-  std::string idc =
-                       this->ExtractValueFromCpuInfoFile(buffer,"physical id");
-  while(this->CurrentPositionInFile != buffer.npos)
-    {
-      int id = atoi(idc.c_str());
-      if(id > maxId)
-      {
-       maxId=id;
-      }
-    idc = this->ExtractValueFromCpuInfoFile(buffer,"physical id",
-                                            this->CurrentPositionInFile+1);
-    }
+  int maxId = -1;
+  std::string idc = this->ExtractValueFromCpuInfoFile(buffer, "physical id");
+  while (this->CurrentPositionInFile != buffer.npos) {
+    int id = atoi(idc.c_str());
+    if (id > maxId) {
+      maxId = id;
+    }
+    idc = this->ExtractValueFromCpuInfoFile(buffer, "physical id",
+                                            this->CurrentPositionInFile + 1);
+  }
   // Physical ids returned by Linux don't distinguish cores.
   // We want to record the total number of cores in this->NumberOfPhysicalCPU
   // (checking only the first proc)
-  std::string cores =
-                        this->ExtractValueFromCpuInfoFile(buffer,"cpu cores");
-  int numberOfCoresPerCPU=atoi(cores.c_str());
-  if (maxId > 0)
-    {
-    this->NumberOfPhysicalCPU=static_cast<unsigned int>(
-      numberOfCoresPerCPU*(maxId+1));
-    }
-  else
-    {
+  std::string cores = this->ExtractValueFromCpuInfoFile(buffer, "cpu cores");
+  int numberOfCoresPerCPU = atoi(cores.c_str());
+  if (maxId > 0) {
+    this->NumberOfPhysicalCPU =
+      static_cast<unsigned int>(numberOfCoresPerCPU * (maxId + 1));
+  } else {
     // Linux Sparc: get cpu count
-    this->NumberOfPhysicalCPU=
-            atoi(this->ExtractValueFromCpuInfoFile(buffer,"ncpus active").c_str());
-    }
+    this->NumberOfPhysicalCPU =
+      atoi(this->ExtractValueFromCpuInfoFile(buffer, "ncpus active").c_str());
+  }
 
 #else // __CYGWIN__
   // does not have "physical id" entries, neither "cpu cores"
   // this has to be fixed for hyper-threading.
   std::string cpucount =
-    this->ExtractValueFromCpuInfoFile(buffer,"cpu count");
-  this->NumberOfPhysicalCPU=
-    this->NumberOfLogicalCPU = atoi(cpucount.c_str());
+    this->ExtractValueFromCpuInfoFile(buffer, "cpu count");
+  this->NumberOfPhysicalCPU = this->NumberOfLogicalCPU =
+    atoi(cpucount.c_str());
 #endif
   // gotta have one, and if this is 0 then we get a / by 0n
   // better to have a bad answer than a crash
-  if(this->NumberOfPhysicalCPU <= 0)
-    {
+  if (this->NumberOfPhysicalCPU <= 0) {
     this->NumberOfPhysicalCPU = 1;
-    }
+  }
   // LogicalProcessorsPerPhysical>1 => hyperthreading.
-  this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical=
-      this->NumberOfLogicalCPU/this->NumberOfPhysicalCPU;
+  this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical =
+    this->NumberOfLogicalCPU / this->NumberOfPhysicalCPU;
 
   // CPU speed (checking only the first processor)
-  std::string CPUSpeed = this->ExtractValueFromCpuInfoFile(buffer,"cpu MHz");
-  if(!CPUSpeed.empty())
-    {
+  std::string CPUSpeed = this->ExtractValueFromCpuInfoFile(buffer, "cpu MHz");
+  if (!CPUSpeed.empty()) {
     this->CPUSpeedInMHz = static_cast<float>(atof(CPUSpeed.c_str()));
-    }
+  }
 #ifdef __linux
-  else
-    {
+  else {
     // Linux Sparc: CPU speed is in Hz and encoded in hexadecimal
-    CPUSpeed = this->ExtractValueFromCpuInfoFile(buffer,"Cpu0ClkTck");
-    this->CPUSpeedInMHz = static_cast<float>(
-                                 strtoull(CPUSpeed.c_str(),0,16))/1000000.0f;
-    }
+    CPUSpeed = this->ExtractValueFromCpuInfoFile(buffer, "Cpu0ClkTck");
+    this->CPUSpeedInMHz =
+      static_cast<float>(strtoull(CPUSpeed.c_str(), 0, 16)) / 1000000.0f;
+  }
 #endif
 
   // Chip family
   std::string familyStr =
-    this->ExtractValueFromCpuInfoFile(buffer,"cpu family");
-  if(familyStr.empty())
-    {
-    familyStr = this->ExtractValueFromCpuInfoFile(buffer,"CPU architecture");
-    }
+    this->ExtractValueFromCpuInfoFile(buffer, "cpu family");
+  if (familyStr.empty()) {
+    familyStr = this->ExtractValueFromCpuInfoFile(buffer, "CPU architecture");
+  }
   this->ChipID.Family = atoi(familyStr.c_str());
 
   // Chip Vendor
-  this->ChipID.Vendor = this->ExtractValueFromCpuInfoFile(buffer,"vendor_id");
+  this->ChipID.Vendor = this->ExtractValueFromCpuInfoFile(buffer, "vendor_id");
   this->FindManufacturer(familyStr);
 
   // second try for setting family
-  if (this->ChipID.Family == 0 && this->ChipManufacturer == HP)
-    {
+  if (this->ChipID.Family == 0 && this->ChipManufacturer == HP) {
     if (familyStr == "PA-RISC 1.1a")
       this->ChipID.Family = 0x11a;
     else if (familyStr == "PA-RISC 2.0")
@@ -3280,31 +3486,30 @@ bool SystemInformationImplementation::RetreiveInformationFromCpuInfoFile()
     // If you really get CMake to work on a machine not belonging to
     // any of those families I owe you a dinner if you get it to
     // contribute nightly builds regularly.
-    }
+  }
 
   // Chip Model
-  this->ChipID.Model = atoi(this->ExtractValueFromCpuInfoFile(buffer,"model").c_str());
-  if(!this->RetrieveClassicalCPUIdentity())
-    {
+  this->ChipID.Model =
+    atoi(this->ExtractValueFromCpuInfoFile(buffer, "model").c_str());
+  if (!this->RetrieveClassicalCPUIdentity()) {
     // Some platforms (e.g. PA-RISC) tell us their CPU name here.
     // Note: x86 does not.
-    std::string cpuname = this->ExtractValueFromCpuInfoFile(buffer,"cpu");
-    if(!cpuname.empty())
-      {
+    std::string cpuname = this->ExtractValueFromCpuInfoFile(buffer, "cpu");
+    if (!cpuname.empty()) {
       this->ChipID.ProcessorName = cpuname;
-      }
     }
+  }
 
   // Chip revision
-  std::string cpurev = this->ExtractValueFromCpuInfoFile(buffer,"stepping");
-  if(cpurev.empty())
-    {
-    cpurev = this->ExtractValueFromCpuInfoFile(buffer,"CPU revision");
-    }
+  std::string cpurev = this->ExtractValueFromCpuInfoFile(buffer, "stepping");
+  if (cpurev.empty()) {
+    cpurev = this->ExtractValueFromCpuInfoFile(buffer, "CPU revision");
+  }
   this->ChipID.Revision = atoi(cpurev.c_str());
 
   // Chip Model Name
-  this->ChipID.ModelName = this->ExtractValueFromCpuInfoFile(buffer,"model name").c_str();
+  this->ChipID.ModelName =
+    this->ExtractValueFromCpuInfoFile(buffer, "model name").c_str();
 
   // L1 Cache size
   // Different architectures may show different names for the caches.
@@ -3313,71 +3518,58 @@ bool SystemInformationImplementation::RetreiveInformationFromCpuInfoFile()
   cachename.clear();
 
   cachename.push_back("cache size"); // e.g. x86
-  cachename.push_back("I-cache"); // e.g. PA-RISC
-  cachename.push_back("D-cache"); // e.g. PA-RISC
+  cachename.push_back("I-cache");    // e.g. PA-RISC
+  cachename.push_back("D-cache");    // e.g. PA-RISC
 
   this->Features.L1CacheSize = 0;
-  for (size_t index = 0; index < cachename.size(); index ++)
-    {
-    std::string cacheSize = this->ExtractValueFromCpuInfoFile(buffer,cachename[index]);
-    if (!cacheSize.empty())
-      {
+  for (size_t index = 0; index < cachename.size(); index++) {
+    std::string cacheSize =
+      this->ExtractValueFromCpuInfoFile(buffer, cachename[index]);
+    if (!cacheSize.empty()) {
       pos = cacheSize.find(" KB");
-      if(pos!=cacheSize.npos)
-        {
-        cacheSize = cacheSize.substr(0,pos);
-        }
-      this->Features.L1CacheSize += atoi(cacheSize.c_str());
+      if (pos != cacheSize.npos) {
+        cacheSize = cacheSize.substr(0, pos);
       }
+      this->Features.L1CacheSize += atoi(cacheSize.c_str());
     }
+  }
 
   // processor feature flags (probably x86 specific)
-  std::string cpuflags = this->ExtractValueFromCpuInfoFile(buffer,"flags");
-  if(!cpurev.empty())
-    {
+  std::string cpuflags = this->ExtractValueFromCpuInfoFile(buffer, "flags");
+  if (!cpurev.empty()) {
     // now we can match every flags as space + flag + space
     cpuflags = " " + cpuflags + " ";
-    if ((cpuflags.find(" fpu ")!=std::string::npos))
-      {
+    if ((cpuflags.find(" fpu ") != std::string::npos)) {
       this->Features.HasFPU = true;
-      }
-    if ((cpuflags.find(" tsc ")!=std::string::npos))
-      {
+    }
+    if ((cpuflags.find(" tsc ") != std::string::npos)) {
       this->Features.HasTSC = true;
-      }
-    if ((cpuflags.find(" mmx ")!=std::string::npos))
-      {
+    }
+    if ((cpuflags.find(" mmx ") != std::string::npos)) {
       this->Features.HasMMX = true;
-      }
-    if ((cpuflags.find(" sse ")!=std::string::npos))
-      {
+    }
+    if ((cpuflags.find(" sse ") != std::string::npos)) {
       this->Features.HasSSE = true;
-      }
-    if ((cpuflags.find(" sse2 ")!=std::string::npos))
-      {
+    }
+    if ((cpuflags.find(" sse2 ") != std::string::npos)) {
       this->Features.HasSSE2 = true;
-      }
-    if ((cpuflags.find(" apic ")!=std::string::npos))
-      {
+    }
+    if ((cpuflags.find(" apic ") != std::string::npos)) {
       this->Features.HasAPIC = true;
-      }
-    if ((cpuflags.find(" cmov ")!=std::string::npos))
-      {
+    }
+    if ((cpuflags.find(" cmov ") != std::string::npos)) {
       this->Features.HasCMOV = true;
-      }
-    if ((cpuflags.find(" mtrr ")!=std::string::npos))
-      {
+    }
+    if ((cpuflags.find(" mtrr ") != std::string::npos)) {
       this->Features.HasMTRR = true;
-      }
-    if ((cpuflags.find(" acpi ")!=std::string::npos))
-      {
+    }
+    if ((cpuflags.find(" acpi ") != std::string::npos)) {
       this->Features.HasACPI = true;
-      }
-    if ((cpuflags.find(" 3dnow ")!=std::string::npos))
-      {
+    }
+    if ((cpuflags.find(" 3dnow ") != std::string::npos)) {
       this->Features.ExtendedFeatures.Has3DNow = true;
-      }
     }
+  }
 
   return true;
 }
@@ -3386,15 +3578,14 @@ bool SystemInformationImplementation::QueryProcessorBySysconf()
 {
 #if defined(_SC_NPROC_ONLN) && !defined(_SC_NPROCESSORS_ONLN)
 // IRIX names this slightly different
-# define _SC_NPROCESSORS_ONLN _SC_NPROC_ONLN
+#define _SC_NPROCESSORS_ONLN _SC_NPROC_ONLN
 #endif
 
 #ifdef _SC_NPROCESSORS_ONLN
   long c = sysconf(_SC_NPROCESSORS_ONLN);
-  if (c <= 0)
-    {
+  if (c <= 0) {
     return false;
-    }
+  }
 
   this->NumberOfPhysicalCPU = static_cast<unsigned int>(c);
   this->NumberOfLogicalCPU = this->NumberOfPhysicalCPU;
@@ -3417,34 +3608,32 @@ SystemInformation::LongLong
 SystemInformationImplementation::GetHostMemoryTotal()
 {
 #if defined(_WIN32)
-# if defined(_MSC_VER) && _MSC_VER < 1300
+#if defined(_MSC_VER) && _MSC_VER < 1300
   MEMORYSTATUS stat;
   stat.dwLength = sizeof(stat);
   GlobalMemoryStatus(&stat);
-  return stat.dwTotalPhys/1024;
-# else
+  return stat.dwTotalPhys / 1024;
+#else
   MEMORYSTATUSEX statex;
-  statex.dwLength=sizeof(statex);
+  statex.dwLength = sizeof(statex);
   GlobalMemoryStatusEx(&statex);
-  return statex.ullTotalPhys/1024;
-# endif
+  return statex.ullTotalPhys / 1024;
+#endif
 #elif defined(__linux)
-  SystemInformation::LongLong memTotal=0;
-  int ierr=GetFieldFromFile("/proc/meminfo","MemTotal:",memTotal);
-  if (ierr)
-    {
+  SystemInformation::LongLong memTotal = 0;
+  int ierr = GetFieldFromFile("/proc/meminfo", "MemTotal:", memTotal);
+  if (ierr) {
     return -1;
-    }
+  }
   return memTotal;
 #elif defined(__APPLE__)
   uint64_t mem;
   size_t len = sizeof(mem);
-  int ierr=sysctlbyname("hw.memsize", &mem, &len, NULL, 0);
-  if (ierr)
-    {
+  int ierr = sysctlbyname("hw.memsize", &mem, &len, NULL, 0);
+  if (ierr) {
     return -1;
-    }
-  return mem/1024;
+  }
+  return mem / 1024;
 #else
   return 0;
 #endif
@@ -3455,9 +3644,10 @@ Get total system RAM in units of KiB. This may differ from the
 host total if a host-wide resource limit is applied.
 */
 SystemInformation::LongLong
-SystemInformationImplementation::GetHostMemoryAvailable(const char *hostLimitEnvVarName)
+SystemInformationImplementation::GetHostMemoryAvailable(
+  const char* hostLimitEnvVarName)
 {
-  SystemInformation::LongLong memTotal=this->GetHostMemoryTotal();
+  SystemInformation::LongLong memTotal = this->GetHostMemoryTotal();
 
   // the following mechanism is provided for systems that
   // apply resource limits across groups of processes.
@@ -3465,18 +3655,16 @@ SystemInformationImplementation::GetHostMemoryAvailable(const char *hostLimitEnv
   // where the host has a large amount of ram but a given user's
   // access to it is severly restricted. The system will
   // apply a limit across a set of processes. Units are in KiB.
-  if (hostLimitEnvVarName)
-    {
-    const char *hostLimitEnvVarValue=getenv(hostLimitEnvVarName);
-    if (hostLimitEnvVarValue)
-      {
-      SystemInformation::LongLong hostLimit=atoLongLong(hostLimitEnvVarValue);
-      if (hostLimit>0)
-        {
-        memTotal=min(hostLimit,memTotal);
-        }
+  if (hostLimitEnvVarName) {
+    const char* hostLimitEnvVarValue = getenv(hostLimitEnvVarName);
+    if (hostLimitEnvVarValue) {
+      SystemInformation::LongLong hostLimit =
+        atoLongLong(hostLimitEnvVarValue);
+      if (hostLimit > 0) {
+        memTotal = min(hostLimit, memTotal);
       }
     }
+  }
 
   return memTotal;
 }
@@ -3487,55 +3675,52 @@ host total if a per-process resource limit is applied.
 */
 SystemInformation::LongLong
 SystemInformationImplementation::GetProcMemoryAvailable(
-        const char *hostLimitEnvVarName,
-        const char *procLimitEnvVarName)
+  const char* hostLimitEnvVarName, const char* procLimitEnvVarName)
 {
-  SystemInformation::LongLong memAvail
-    = this->GetHostMemoryAvailable(hostLimitEnvVarName);
+  SystemInformation::LongLong memAvail =
+    this->GetHostMemoryAvailable(hostLimitEnvVarName);
 
   // the following mechanism is provide for systems where rlimits
   // are not employed. Units are in KiB.
-  if (procLimitEnvVarName)
-    {
-    const char *procLimitEnvVarValue=getenv(procLimitEnvVarName);
-    if (procLimitEnvVarValue)
-      {
-      SystemInformation::LongLong procLimit=atoLongLong(procLimitEnvVarValue);
-      if (procLimit>0)
-        {
-        memAvail=min(procLimit,memAvail);
-        }
+  if (procLimitEnvVarName) {
+    const char* procLimitEnvVarValue = getenv(procLimitEnvVarName);
+    if (procLimitEnvVarValue) {
+      SystemInformation::LongLong procLimit =
+        atoLongLong(procLimitEnvVarValue);
+      if (procLimit > 0) {
+        memAvail = min(procLimit, memAvail);
       }
     }
+  }
 
 #if defined(__linux)
   int ierr;
   ResourceLimitType rlim;
-  ierr=GetResourceLimit(RLIMIT_DATA,&rlim);
-  if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
-    {
-    memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
-    }
+  ierr = GetResourceLimit(RLIMIT_DATA, &rlim);
+  if ((ierr == 0) && (rlim.rlim_cur != RLIM_INFINITY)) {
+    memAvail =
+      min((SystemInformation::LongLong)rlim.rlim_cur / 1024, memAvail);
+  }
 
-  ierr=GetResourceLimit(RLIMIT_AS,&rlim);
-  if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
-    {
-    memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
-    }
+  ierr = GetResourceLimit(RLIMIT_AS, &rlim);
+  if ((ierr == 0) && (rlim.rlim_cur != RLIM_INFINITY)) {
+    memAvail =
+      min((SystemInformation::LongLong)rlim.rlim_cur / 1024, memAvail);
+  }
 #elif defined(__APPLE__)
   struct rlimit rlim;
   int ierr;
-  ierr=getrlimit(RLIMIT_DATA,&rlim);
-  if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
-    {
-    memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
-    }
+  ierr = getrlimit(RLIMIT_DATA, &rlim);
+  if ((ierr == 0) && (rlim.rlim_cur != RLIM_INFINITY)) {
+    memAvail =
+      min((SystemInformation::LongLong)rlim.rlim_cur / 1024, memAvail);
+  }
 
-  ierr=getrlimit(RLIMIT_RSS,&rlim);
-  if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
-    {
-    memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
-    }
+  ierr = getrlimit(RLIMIT_RSS, &rlim);
+  if ((ierr == 0) && (rlim.rlim_cur != RLIM_INFINITY)) {
+    memAvail =
+      min((SystemInformation::LongLong)rlim.rlim_cur / 1024, memAvail);
+  }
 #endif
 
   return memAvail;
@@ -3548,56 +3733,54 @@ SystemInformation::LongLong
 SystemInformationImplementation::GetHostMemoryUsed()
 {
 #if defined(_WIN32)
-# if defined(_MSC_VER) && _MSC_VER < 1300
+#if defined(_MSC_VER) && _MSC_VER < 1300
   MEMORYSTATUS stat;
   stat.dwLength = sizeof(stat);
   GlobalMemoryStatus(&stat);
-  return (stat.dwTotalPhys - stat.dwAvailPhys)/1024;
-# else
+  return (stat.dwTotalPhys - stat.dwAvailPhys) / 1024;
+#else
   MEMORYSTATUSEX statex;
-  statex.dwLength=sizeof(statex);
+  statex.dwLength = sizeof(statex);
   GlobalMemoryStatusEx(&statex);
-  return (statex.ullTotalPhys - statex.ullAvailPhys)/1024;
-# endif
+  return (statex.ullTotalPhys - statex.ullAvailPhys) / 1024;
+#endif
 #elif defined(__linux)
   // First try to use MemAvailable, but it only works on newer kernels
-  const char *names2[3]={"MemTotal:","MemAvailable:",NULL};
-  SystemInformation::LongLong values2[2]={SystemInformation::LongLong(0)};
-  int ierr=GetFieldsFromFile("/proc/meminfo",names2,values2);
-  if (ierr)
-    {
-    const char *names4[5]={"MemTotal:","MemFree:","Buffers:","Cached:",NULL};
-    SystemInformation::LongLong values4[4]={SystemInformation::LongLong(0)};
-    ierr=GetFieldsFromFile("/proc/meminfo",names4,values4);
-    if(ierr)
-      {
+  const char* names2[3] = { "MemTotal:", "MemAvailable:", NULL };
+  SystemInformation::LongLong values2[2] = { SystemInformation::LongLong(0) };
+  int ierr = GetFieldsFromFile("/proc/meminfo", names2, values2);
+  if (ierr) {
+    const char* names4[5] = { "MemTotal:", "MemFree:", "Buffers:", "Cached:",
+                              NULL };
+    SystemInformation::LongLong values4[4] = { SystemInformation::LongLong(
+      0) };
+    ierr = GetFieldsFromFile("/proc/meminfo", names4, values4);
+    if (ierr) {
       return ierr;
-      }
-    SystemInformation::LongLong &memTotal=values4[0];
-    SystemInformation::LongLong &memFree=values4[1];
-    SystemInformation::LongLong &memBuffers=values4[2];
-    SystemInformation::LongLong &memCached=values4[3];
-    return memTotal - memFree - memBuffers - memCached;
     }
-  SystemInformation::LongLong &memTotal=values2[0];
-  SystemInformation::LongLong &memAvail=values2[1];
+    SystemInformation::LongLong& memTotal = values4[0];
+    SystemInformation::LongLong& memFree = values4[1];
+    SystemInformation::LongLong& memBuffers = values4[2];
+    SystemInformation::LongLong& memCached = values4[3];
+    return memTotal - memFree - memBuffers - memCached;
+  }
+  SystemInformation::LongLong& memTotal = values2[0];
+  SystemInformation::LongLong& memAvail = values2[1];
   return memTotal - memAvail;
 #elif defined(__APPLE__)
-  SystemInformation::LongLong psz=getpagesize();
-  if (psz<1)
-    {
+  SystemInformation::LongLong psz = getpagesize();
+  if (psz < 1) {
     return -1;
-    }
-  const char *names[3]={"Pages wired down:","Pages active:",NULL};
-  SystemInformation::LongLong values[2]={SystemInformation::LongLong(0)};
-  int ierr=GetFieldsFromCommand("vm_stat", names, values);
-  if (ierr)
-    {
+  }
+  const char* names[3] = { "Pages wired down:", "Pages active:", NULL };
+  SystemInformation::LongLong values[2] = { SystemInformation::LongLong(0) };
+  int ierr = GetFieldsFromCommand("vm_stat", names, values);
+  if (ierr) {
     return -1;
-    }
-  SystemInformation::LongLong &vmWired=values[0];
-  SystemInformation::LongLong &vmActive=values[1];
-  return ((vmActive+vmWired)*psz)/1024;
+  }
+  SystemInformation::LongLong& vmWired = values[0];
+  SystemInformation::LongLong& vmActive = values[1];
+  return ((vmActive + vmWired) * psz) / 1024;
 #else
   return 0;
 #endif
@@ -3611,60 +3794,51 @@ SystemInformation::LongLong
 SystemInformationImplementation::GetProcMemoryUsed()
 {
 #if defined(_WIN32) && defined(KWSYS_SYS_HAS_PSAPI)
-  long pid=GetCurrentProcessId();
+  long pid = GetCurrentProcessId();
   HANDLE hProc;
-  hProc=OpenProcess(
-      PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,
-      false,
-      pid);
-  if (hProc==0)
-    {
+  hProc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid);
+  if (hProc == 0) {
     return -1;
-    }
+  }
   PROCESS_MEMORY_COUNTERS pmc;
-  int ok=GetProcessMemoryInfo(hProc,&pmc,sizeof(pmc));
+  int ok = GetProcessMemoryInfo(hProc, &pmc, sizeof(pmc));
   CloseHandle(hProc);
-  if (!ok)
-    {
+  if (!ok) {
     return -2;
-    }
-  return pmc.WorkingSetSize/1024;
+  }
+  return pmc.WorkingSetSize / 1024;
 #elif defined(__linux)
-  SystemInformation::LongLong memUsed=0;
-  int ierr=GetFieldFromFile("/proc/self/status","VmRSS:",memUsed);
-  if (ierr)
-    {
+  SystemInformation::LongLong memUsed = 0;
+  int ierr = GetFieldFromFile("/proc/self/status", "VmRSS:", memUsed);
+  if (ierr) {
     return -1;
-    }
+  }
   return memUsed;
 #elif defined(__APPLE__)
-  SystemInformation::LongLong memUsed=0;
-  pid_t pid=getpid();
+  SystemInformation::LongLong memUsed = 0;
+  pid_t pid = getpid();
   std::ostringstream oss;
   oss << "ps -o rss= -p " << pid;
-  FILE *file=popen(oss.str().c_str(),"r");
-  if (file==0)
-    {
+  FILE* file = popen(oss.str().c_str(), "r");
+  if (file == 0) {
     return -1;
-    }
+  }
   oss.str("");
-  while (!feof(file) && !ferror(file))
-    {
-    char buf[256]={'\0'};
-    errno=0;
-    size_t nRead=fread(buf,1,256,file);
-    if (ferror(file) && (errno==EINTR))
-      {
+  while (!feof(file) && !ferror(file)) {
+    char buf[256] = { '\0' };
+    errno = 0;
+    size_t nRead = fread(buf, 1, 256, file);
+    if (ferror(file) && (errno == EINTR)) {
       clearerr(file);
-      }
-    if (nRead) oss << buf;
     }
-  int ierr=ferror(file);
+    if (nRead)
+      oss << buf;
+  }
+  int ierr = ferror(file);
   pclose(file);
-  if (ierr)
-    {
+  if (ierr) {
     return -2;
-    }
+  }
   std::istringstream iss(oss.str());
   iss >> memUsed;
   return memUsed;
@@ -3677,27 +3851,24 @@ double SystemInformationImplementation::GetLoadAverage()
 {
 #if defined(KWSYS_CXX_HAS_GETLOADAVG)
   double loadavg[3] = { 0.0, 0.0, 0.0 };
-  if (getloadavg(loadavg, 3) > 0)
-    {
+  if (getloadavg(loadavg, 3) > 0) {
     return loadavg[0];
-    }
+  }
   return -0.0;
 #elif defined(KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes)
   // Old windows.h headers do not provide GetSystemTimes.
-  typedef BOOL (WINAPI *GetSystemTimesType)(LPFILETIME, LPFILETIME,
+  typedef BOOL(WINAPI * GetSystemTimesType)(LPFILETIME, LPFILETIME,
                                             LPFILETIME);
   static GetSystemTimesType pGetSystemTimes =
     (GetSystemTimesType)GetProcAddress(GetModuleHandleW(L"kernel32"),
                                        "GetSystemTimes");
   FILETIME idleTime, kernelTime, userTime;
-  if (pGetSystemTimes && pGetSystemTimes(&idleTime, &kernelTime, &userTime))
-    {
-    unsigned __int64 const idleTicks =
-      fileTimeToUInt64(idleTime);
+  if (pGetSystemTimes && pGetSystemTimes(&idleTime, &kernelTime, &userTime)) {
+    unsigned __int64 const idleTicks = fileTimeToUInt64(idleTime);
     unsigned __int64 const totalTicks =
       fileTimeToUInt64(kernelTime) + fileTimeToUInt64(userTime);
     return calculateCPULoad(idleTicks, totalTicks) * GetNumberOfPhysicalCPU();
-    }
+  }
   return -0.0;
 #else
   // Not implemented on this platform.
@@ -3708,8 +3879,7 @@ double SystemInformationImplementation::GetLoadAverage()
 /**
 Get the process id of the running process.
 */
-SystemInformation::LongLong
-SystemInformationImplementation::GetProcessId()
+SystemInformation::LongLong SystemInformationImplementation::GetProcessId()
 {
 #if defined(_WIN32)
   return GetCurrentProcessId();
@@ -3724,40 +3894,39 @@ SystemInformationImplementation::GetProcessId()
 return current program stack in a string
 demangle cxx symbols if possible.
 */
-std::string SystemInformationImplementation::GetProgramStack(
-      int firstFrame,
-      int wholePath)
+std::string SystemInformationImplementation::GetProgramStack(int firstFrame,
+                                                             int wholePath)
 {
   std::string programStack = ""
 #if !defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
-    "WARNING: The stack could not be examined "
-    "because backtrace is not supported.\n"
+                             "WARNING: The stack could not be examined "
+                             "because backtrace is not supported.\n"
 #elif !defined(KWSYS_SYSTEMINFORMATION_HAS_DEBUG_BUILD)
-    "WARNING: The stack trace will not use advanced "
-    "capabilities because this is a release build.\n"
+                             "WARNING: The stack trace will not use advanced "
+                             "capabilities because this is a release build.\n"
 #else
-# if !defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
-    "WARNING: Function names will not be demangled because "
-    "dladdr is not available.\n"
-# endif
-# if !defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
-    "WARNING: Function names will not be demangled "
-    "because cxxabi is not available.\n"
-# endif
+#if !defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
+                             "WARNING: Function names will not be demangled "
+                             "because "
+                             "dladdr is not available.\n"
+#endif
+#if !defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
+                             "WARNING: Function names will not be demangled "
+                             "because cxxabi is not available.\n"
+#endif
 #endif
     ;
 
   std::ostringstream oss;
 #if defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
-  void *stackSymbols[256];
-  int nFrames=backtrace(stackSymbols,256);
-  for (int i=firstFrame; i<nFrames; ++i)
-    {
+  void* stackSymbols[256];
+  int nFrames = backtrace(stackSymbols, 256);
+  for (int i = firstFrame; i < nFrames; ++i) {
     SymbolProperties symProps;
     symProps.SetReportPath(wholePath);
     symProps.Initialize(stackSymbols[i]);
     oss << symProps << std::endl;
-    }
+  }
 #else
   (void)firstFrame;
   (void)wholePath;
@@ -3767,14 +3936,13 @@ std::string SystemInformationImplementation::GetProgramStack(
   return programStack;
 }
 
-
 /**
 when set print stack trace in response to common signals.
 */
 void SystemInformationImplementation::SetStackTraceOnError(int enable)
 {
 #if !defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
-  static int saOrigValid=0;
+  static int saOrigValid = 0;
   static struct sigaction saABRTOrig;
   static struct sigaction saSEGVOrig;
   static struct sigaction saTERMOrig;
@@ -3783,53 +3951,48 @@ void SystemInformationImplementation::SetStackTraceOnError(int enable)
   static struct sigaction saBUSOrig;
   static struct sigaction saFPEOrig;
 
-
-  if (enable && !saOrigValid)
-    {
+  if (enable && !saOrigValid) {
     // save the current actions
-    sigaction(SIGABRT,0,&saABRTOrig);
-    sigaction(SIGSEGV,0,&saSEGVOrig);
-    sigaction(SIGTERM,0,&saTERMOrig);
-    sigaction(SIGINT,0,&saINTOrig);
-    sigaction(SIGILL,0,&saILLOrig);
-    sigaction(SIGBUS,0,&saBUSOrig);
-    sigaction(SIGFPE,0,&saFPEOrig);
+    sigaction(SIGABRT, 0, &saABRTOrig);
+    sigaction(SIGSEGV, 0, &saSEGVOrig);
+    sigaction(SIGTERM, 0, &saTERMOrig);
+    sigaction(SIGINT, 0, &saINTOrig);
+    sigaction(SIGILL, 0, &saILLOrig);
+    sigaction(SIGBUS, 0, &saBUSOrig);
+    sigaction(SIGFPE, 0, &saFPEOrig);
 
     // enable read, disable write
-    saOrigValid=1;
+    saOrigValid = 1;
 
     // install ours
     struct sigaction sa;
-    sa.sa_sigaction=(SigAction)StacktraceSignalHandler;
-    sa.sa_flags=SA_SIGINFO|SA_RESETHAND;
-# ifdef SA_RESTART
-    sa.sa_flags|=SA_RESTART;
-# endif
+    sa.sa_sigaction = (SigAction)StacktraceSignalHandler;
+    sa.sa_flags = SA_SIGINFO | SA_RESETHAND;
+#ifdef SA_RESTART
+    sa.sa_flags |= SA_RESTART;
+#endif
     sigemptyset(&sa.sa_mask);
 
-    sigaction(SIGABRT,&sa,0);
-    sigaction(SIGSEGV,&sa,0);
-    sigaction(SIGTERM,&sa,0);
-    sigaction(SIGINT,&sa,0);
-    sigaction(SIGILL,&sa,0);
-    sigaction(SIGBUS,&sa,0);
-    sigaction(SIGFPE,&sa,0);
-    }
-  else
-  if (!enable && saOrigValid)
-    {
+    sigaction(SIGABRT, &sa, 0);
+    sigaction(SIGSEGV, &sa, 0);
+    sigaction(SIGTERM, &sa, 0);
+    sigaction(SIGINT, &sa, 0);
+    sigaction(SIGILL, &sa, 0);
+    sigaction(SIGBUS, &sa, 0);
+    sigaction(SIGFPE, &sa, 0);
+  } else if (!enable && saOrigValid) {
     // restore previous actions
-    sigaction(SIGABRT,&saABRTOrig,0);
-    sigaction(SIGSEGV,&saSEGVOrig,0);
-    sigaction(SIGTERM,&saTERMOrig,0);
-    sigaction(SIGINT,&saINTOrig,0);
-    sigaction(SIGILL,&saILLOrig,0);
-    sigaction(SIGBUS,&saBUSOrig,0);
-    sigaction(SIGFPE,&saFPEOrig,0);
+    sigaction(SIGABRT, &saABRTOrig, 0);
+    sigaction(SIGSEGV, &saSEGVOrig, 0);
+    sigaction(SIGTERM, &saTERMOrig, 0);
+    sigaction(SIGINT, &saINTOrig, 0);
+    sigaction(SIGILL, &saILLOrig, 0);
+    sigaction(SIGBUS, &saBUSOrig, 0);
+    sigaction(SIGFPE, &saFPEOrig, 0);
 
     // enable write, disable read
-    saOrigValid=0;
-    }
+    saOrigValid = 0;
+  }
 #else
   // avoid warning C4100
   (void)enable;
@@ -3839,30 +4002,29 @@ void SystemInformationImplementation::SetStackTraceOnError(int enable)
 bool SystemInformationImplementation::QueryWindowsMemory()
 {
 #if defined(_WIN32)
-# if defined(_MSC_VER) && _MSC_VER < 1300
+#if defined(_MSC_VER) && _MSC_VER < 1300
   MEMORYSTATUS ms;
   unsigned long tv, tp, av, ap;
   ms.dwLength = sizeof(ms);
   GlobalMemoryStatus(&ms);
-#  define MEM_VAL(value) dw##value
-# else
+#define MEM_VAL(value) dw##value
+#else
   MEMORYSTATUSEX ms;
   DWORDLONG tv, tp, av, ap;
   ms.dwLength = sizeof(ms);
-  if (0 == GlobalMemoryStatusEx(&ms))
-  {
+  if (0 == GlobalMemoryStatusEx(&ms)) {
     return 0;
   }
-#  define MEM_VAL(value) ull##value
-# endif
+#define MEM_VAL(value) ull##value
+#endif
   tv = ms.MEM_VAL(TotalPageFile);
   tp = ms.MEM_VAL(TotalPhys);
   av = ms.MEM_VAL(AvailPageFile);
   ap = ms.MEM_VAL(AvailPhys);
-  this->TotalVirtualMemory = tv>>10>>10;
-  this->TotalPhysicalMemory = tp>>10>>10;
-  this->AvailableVirtualMemory = av>>10>>10;
-  this->AvailablePhysicalMemory = ap>>10>>10;
+  this->TotalVirtualMemory = tv >> 10 >> 10;
+  this->TotalPhysicalMemory = tp >> 10 >> 10;
+  this->AvailableVirtualMemory = av >> 10 >> 10;
+  this->AvailablePhysicalMemory = ap >> 10 >> 10;
   return true;
 #else
   return false;
@@ -3872,10 +4034,10 @@ bool SystemInformationImplementation::QueryWindowsMemory()
 bool SystemInformationImplementation::QueryLinuxMemory()
 {
 #if defined(__linux)
-  unsigned long tv=0;
-  unsigned long tp=0;
-  unsigned long av=0;
-  unsigned long ap=0;
+  unsigned long tv = 0;
+  unsigned long tp = 0;
+  unsigned long av = 0;
+  unsigned long ap = 0;
 
   char buffer[1024]; // for reading lines
 
@@ -3885,109 +4047,99 @@ bool SystemInformationImplementation::QueryLinuxMemory()
   // Find the Linux kernel version first
   struct utsname unameInfo;
   int errorFlag = uname(&unameInfo);
-  if( errorFlag!=0 )
-    {
+  if (errorFlag != 0) {
     std::cout << "Problem calling uname(): " << strerror(errno) << std::endl;
     return false;
-    }
+  }
 
-  if( strlen(unameInfo.release)>=3 )
-    {
+  if (strlen(unameInfo.release) >= 3) {
     // release looks like "2.6.3-15mdk-i686-up-4GB"
-    char majorChar=unameInfo.release[0];
-    char minorChar=unameInfo.release[2];
+    char majorChar = unameInfo.release[0];
+    char minorChar = unameInfo.release[2];
 
-    if( isdigit(majorChar) )
-      {
-      linuxMajor=majorChar-'0';
-      }
+    if (isdigit(majorChar)) {
+      linuxMajor = majorChar - '0';
+    }
 
-    if( isdigit(minorChar) )
-      {
-      linuxMinor=minorChar-'0';
-      }
+    if (isdigit(minorChar)) {
+      linuxMinor = minorChar - '0';
     }
+  }
 
-  FILE *fd = fopen("/proc/meminfo", "r" );
-  if ( !fd )
-    {
+  FILE* fd = fopen("/proc/meminfo", "r");
+  if (!fd) {
     std::cout << "Problem opening /proc/meminfo" << std::endl;
     return false;
-    }
+  }
 
-  if( linuxMajor>=3 || ( (linuxMajor>=2) && (linuxMinor>=6) ) )
-    {
+  if (linuxMajor >= 3 || ((linuxMajor >= 2) && (linuxMinor >= 6))) {
     // new /proc/meminfo format since kernel 2.6.x
     // Rigorously, this test should check from the developping version 2.5.x
     // that introduced the new format...
 
-    enum { mMemTotal, mMemFree, mBuffers, mCached, mSwapTotal, mSwapFree };
-    const char* format[6] =
-      { "MemTotal:%lu kB", "MemFree:%lu kB", "Buffers:%lu kB",
-        "Cached:%lu kB", "SwapTotal:%lu kB", "SwapFree:%lu kB" };
+    enum
+    {
+      mMemTotal,
+      mMemFree,
+      mBuffers,
+      mCached,
+      mSwapTotal,
+      mSwapFree
+    };
+    const char* format[6] = { "MemTotal:%lu kB",  "MemFree:%lu kB",
+                              "Buffers:%lu kB",   "Cached:%lu kB",
+                              "SwapTotal:%lu kB", "SwapFree:%lu kB" };
     bool have[6] = { false, false, false, false, false, false };
     unsigned long value[6];
     int count = 0;
-    while(fgets(buffer, static_cast<int>(sizeof(buffer)), fd))
-      {
-      for(int i=0; i < 6; ++i)
-        {
-        if(!have[i] && sscanf(buffer, format[i], &value[i]) == 1)
-          {
+    while (fgets(buffer, static_cast<int>(sizeof(buffer)), fd)) {
+      for (int i = 0; i < 6; ++i) {
+        if (!have[i] && sscanf(buffer, format[i], &value[i]) == 1) {
           have[i] = true;
           ++count;
-          }
         }
       }
-    if(count == 6)
-      {
+    }
+    if (count == 6) {
       this->TotalPhysicalMemory = value[mMemTotal] / 1024;
       this->AvailablePhysicalMemory =
         (value[mMemFree] + value[mBuffers] + value[mCached]) / 1024;
       this->TotalVirtualMemory = value[mSwapTotal] / 1024;
       this->AvailableVirtualMemory = value[mSwapFree] / 1024;
-      }
-    else
-      {
+    } else {
       std::cout << "Problem parsing /proc/meminfo" << std::endl;
       fclose(fd);
       return false;
-      }
     }
-  else
-    {
+  } else {
     // /proc/meminfo format for kernel older than 2.6.x
 
     unsigned long temp;
     unsigned long cachedMem;
     unsigned long buffersMem;
     // Skip "total: used:..."
-    char *r=fgets(buffer, static_cast<int>(sizeof(buffer)), fd);
-    int status=0;
-    if(r==buffer)
-      {
-      status+=fscanf(fd, "Mem: %lu %lu %lu %lu %lu %lu\n",
-                     &tp, &temp, &ap, &temp, &buffersMem, &cachedMem);
-      }
-    if(status==6)
-      {
-      status+=fscanf(fd, "Swap: %lu %lu %lu\n", &tv, &temp, &av);
-      }
-    if(status==9)
-      {
-      this->TotalVirtualMemory = tv>>10>>10;
-      this->TotalPhysicalMemory = tp>>10>>10;
-      this->AvailableVirtualMemory = av>>10>>10;
-      this->AvailablePhysicalMemory = (ap+buffersMem+cachedMem)>>10>>10;
-      }
-    else
-      {
+    char* r = fgets(buffer, static_cast<int>(sizeof(buffer)), fd);
+    int status = 0;
+    if (r == buffer) {
+      status += fscanf(fd, "Mem: %lu %lu %lu %lu %lu %lu\n", &tp, &temp, &ap,
+                       &temp, &buffersMem, &cachedMem);
+    }
+    if (status == 6) {
+      status += fscanf(fd, "Swap: %lu %lu %lu\n", &tv, &temp, &av);
+    }
+    if (status == 9) {
+      this->TotalVirtualMemory = tv >> 10 >> 10;
+      this->TotalPhysicalMemory = tp >> 10 >> 10;
+      this->AvailableVirtualMemory = av >> 10 >> 10;
+      this->AvailablePhysicalMemory =
+        (ap + buffersMem + cachedMem) >> 10 >> 10;
+    } else {
       std::cout << "Problem parsing /proc/meminfo" << std::endl;
       fclose(fd);
       return false;
-      }
     }
-  fclose( fd );
+  }
+  fclose(fd);
 
   return true;
 #else
@@ -4002,10 +4154,9 @@ bool SystemInformationImplementation::QueryCygwinMemory()
   // see http://cygwin.com/ml/cygwin/2006-06/msg00350.html
   // Therefore just use 4096 as the page size of Windows.
   long m = sysconf(_SC_PHYS_PAGES);
-  if (m < 0)
-    {
+  if (m < 0) {
     return false;
-    }
+  }
   this->TotalPhysicalMemory = m >> 8;
   return true;
 #else
@@ -4017,10 +4168,9 @@ bool SystemInformationImplementation::QueryAIXMemory()
 {
 #if defined(_AIX) && defined(_SC_AIX_REALMEM)
   long c = sysconf(_SC_AIX_REALMEM);
-  if (c <= 0)
-    {
+  if (c <= 0) {
     return false;
-    }
+  }
 
   this->TotalPhysicalMemory = c / 1024;
 
@@ -4039,10 +4189,9 @@ bool SystemInformationImplementation::QueryMemoryBySysconf()
   long p = sysconf(_SC_PHYS_PAGES);
   long m = sysconf(_SC_PAGESIZE);
 
-  if (p < 0 || m < 0)
-    {
+  if (p < 0 || m < 0) {
     return false;
-    }
+  }
 
   // assume pagesize is a power of 2 and smaller 1 MiB
   size_t pagediv = (1024 * 1024 / m);
@@ -4052,10 +4201,9 @@ bool SystemInformationImplementation::QueryMemoryBySysconf()
 
 #if defined(_SC_AVPHYS_PAGES)
   p = sysconf(_SC_AVPHYS_PAGES);
-  if (p < 0)
-    {
+  if (p < 0) {
     return false;
-    }
+  }
 
   this->AvailablePhysicalMemory = p;
   this->AvailablePhysicalMemory /= pagediv;
@@ -4098,8 +4246,8 @@ size_t SystemInformationImplementation::GetAvailablePhysicalMemory()
 
 /** Get Cycle differences */
 SystemInformation::LongLong
-SystemInformationImplementation::GetCyclesDifference (DELAY_FUNC DelayFunction,
-                                                  unsigned int uiParameter)
+SystemInformationImplementation::GetCyclesDifference(DELAY_FUNC DelayFunction,
+                                                     unsigned int uiParameter)
 {
 #if defined(_MSC_VER) && (_MSC_VER >= 1400)
   unsigned __int64 stamp1, stamp2;
@@ -4137,13 +4285,11 @@ SystemInformationImplementation::GetCyclesDifference (DELAY_FUNC DelayFunction,
       mov edx1, edi      ; edx2 = edi
       mov eax1, esi      ; eax2 = esi
     }
-  }
-  __except(1)
-    {
+  } __except (1) {
     return -1;
-    }
+  }
 
-  return ((((__int64) edx2 << 32) + eax2) - (((__int64) edx1 << 32) + eax1));
+  return ((((__int64)edx2 << 32) + eax2) - (((__int64)edx1 << 32) + eax1));
 
 #else
   (void)DelayFunction;
@@ -4152,7 +4298,6 @@ SystemInformationImplementation::GetCyclesDifference (DELAY_FUNC DelayFunction,
 #endif
 }
 
-
 /** Compute the delay overhead */
 void SystemInformationImplementation::DelayOverhead(unsigned int uiMS)
 {
@@ -4161,238 +4306,213 @@ void SystemInformationImplementation::DelayOverhead(unsigned int uiMS)
   __int64 x;
 
   // Get the frequency of the high performance counter.
-  if(!QueryPerformanceFrequency (&Frequency))
-    {
+  if (!QueryPerformanceFrequency(&Frequency)) {
     return;
-    }
+  }
   x = Frequency.QuadPart / 1000 * uiMS;
 
   // Get the starting position of the counter.
-  QueryPerformanceCounter (&StartCounter);
+  QueryPerformanceCounter(&StartCounter);
 
   do {
     // Get the ending position of the counter.
-    QueryPerformanceCounter (&EndCounter);
+    QueryPerformanceCounter(&EndCounter);
   } while (EndCounter.QuadPart - StartCounter.QuadPart == x);
 #endif
   (void)uiMS;
 }
 
-/** Return the number of logical CPU per physical CPUs Works only for windows */
+/** Return the number of logical CPU per physical CPUs Works only for windows
+ */
 unsigned char SystemInformationImplementation::LogicalCPUPerPhysicalCPU(void)
 {
 #ifdef __APPLE__
   size_t len = 4;
   int cores_per_package = 0;
-  int err = sysctlbyname("machdep.cpu.cores_per_package", &cores_per_package, &len, NULL, 0);
-  if (err != 0)
-    {
-      return 1; // That name was not found, default to 1
-    }
+  int err = sysctlbyname("machdep.cpu.cores_per_package", &cores_per_package,
+                         &len, NULL, 0);
+  if (err != 0) {
+    return 1; // That name was not found, default to 1
+  }
   return static_cast<unsigned char>(cores_per_package);
 #else
   int Regs[4] = { 0, 0, 0, 0 };
 #if USE_CPUID
-  if (!this->IsHyperThreadingSupported())
-    {
-    return static_cast<unsigned char>(1);  // HT not supported
-    }
+  if (!this->IsHyperThreadingSupported()) {
+    return static_cast<unsigned char>(1); // HT not supported
+  }
   call_cpuid(1, Regs);
 #endif
-  return static_cast<unsigned char> ((Regs[1] & NUM_LOGICAL_BITS) >> 16);
+  return static_cast<unsigned char>((Regs[1] & NUM_LOGICAL_BITS) >> 16);
 #endif
 }
 
-
 /** Works only for windows */
 bool SystemInformationImplementation::IsHyperThreadingSupported()
 {
-  if (this->Features.ExtendedFeatures.SupportsHyperthreading)
-    {
+  if (this->Features.ExtendedFeatures.SupportsHyperthreading) {
     return true;
-    }
+  }
 
 #if USE_CPUID
-  int Regs[4] = { 0, 0, 0, 0 },
-             VendorId[4] = { 0, 0, 0, 0 };
+  int Regs[4] = { 0, 0, 0, 0 }, VendorId[4] = { 0, 0, 0, 0 };
   // Get vendor id string
-  if (!call_cpuid(0, VendorId))
-    {
+  if (!call_cpuid(0, VendorId)) {
     return false;
-    }
+  }
   // eax contains family processor type
   // edx has info about the availability of hyper-Threading
-  if (!call_cpuid(1, Regs))
-    {
+  if (!call_cpuid(1, Regs)) {
     return false;
-    }
+  }
 
-  if (((Regs[0] & FAMILY_ID) == PENTIUM4_ID) || (Regs[0] & EXT_FAMILY_ID))
-    {
+  if (((Regs[0] & FAMILY_ID) == PENTIUM4_ID) || (Regs[0] & EXT_FAMILY_ID)) {
     if (VendorId[1] == 0x756e6547) // 'uneG'
-      {
+    {
       if (VendorId[3] == 0x49656e69) // 'Ieni'
-        {
+      {
         if (VendorId[2] == 0x6c65746e) // 'letn'
-          {
+        {
           // Genuine Intel with hyper-Threading technology
-          this->Features.ExtendedFeatures.SupportsHyperthreading = ((Regs[3] & HT_BIT) != 0);
+          this->Features.ExtendedFeatures.SupportsHyperthreading =
+            ((Regs[3] & HT_BIT) != 0);
           return this->Features.ExtendedFeatures.SupportsHyperthreading;
-          }
         }
       }
     }
+  }
 #endif
 
-  return 0;    // Not genuine Intel processor
+  return 0; // Not genuine Intel processor
 }
 
-
 /** Return the APIC Id. Works only for windows. */
 unsigned char SystemInformationImplementation::GetAPICId()
 {
   int Regs[4] = { 0, 0, 0, 0 };
 
 #if USE_CPUID
-  if (!this->IsHyperThreadingSupported())
-    {
-    return static_cast<unsigned char>(-1);  // HT not supported
-    } // Logical processor = 1
+  if (!this->IsHyperThreadingSupported()) {
+    return static_cast<unsigned char>(-1); // HT not supported
+  }                                        // Logical processor = 1
   call_cpuid(1, Regs);
 #endif
 
   return static_cast<unsigned char>((Regs[1] & INITIAL_APIC_ID_BITS) >> 24);
 }
 
-
 /** Count the number of CPUs. Works only on windows. */
 int SystemInformationImplementation::CPUCount()
 {
 #if defined(_WIN32)
-  unsigned char StatusFlag  = 0;
+  unsigned char StatusFlag = 0;
   SYSTEM_INFO info;
 
   this->NumberOfPhysicalCPU = 0;
   this->NumberOfLogicalCPU = 0;
   info.dwNumberOfProcessors = 0;
-  GetSystemInfo (&info);
+  GetSystemInfo(&info);
 
   // Number of physical processors in a non-Intel system
   // or in a 32-bit Intel system with Hyper-Threading technology disabled
-  this->NumberOfPhysicalCPU = (unsigned char) info.dwNumberOfProcessors;
+  this->NumberOfPhysicalCPU = (unsigned char)info.dwNumberOfProcessors;
 
-  if (this->IsHyperThreadingSupported())
-    {
+  if (this->IsHyperThreadingSupported()) {
     unsigned char HT_Enabled = 0;
     this->NumberOfLogicalCPU = this->LogicalCPUPerPhysicalCPU();
-    if (this->NumberOfLogicalCPU >= 1)    // >1 Doesn't mean HT is enabled in the BIOS
-      {
+    if (this->NumberOfLogicalCPU >=
+        1) // >1 Doesn't mean HT is enabled in the BIOS
+    {
       HANDLE hCurrentProcessHandle;
 #ifndef _WIN64
-# define DWORD_PTR DWORD
+#define DWORD_PTR DWORD
 #endif
-      DWORD_PTR  dwProcessAffinity;
-      DWORD_PTR  dwSystemAffinity;
-      DWORD  dwAffinityMask;
+      DWORD_PTR dwProcessAffinity;
+      DWORD_PTR dwSystemAffinity;
+      DWORD dwAffinityMask;
 
       // Calculate the appropriate  shifts and mask based on the
       // number of logical processors.
       unsigned int i = 1;
-      unsigned char PHY_ID_MASK  = 0xFF;
-      //unsigned char PHY_ID_SHIFT = 0;
+      unsigned char PHY_ID_MASK = 0xFF;
+      // unsigned char PHY_ID_SHIFT = 0;
 
-      while (i < this->NumberOfLogicalCPU)
-        {
+      while (i < this->NumberOfLogicalCPU) {
         i *= 2;
-         PHY_ID_MASK  <<= 1;
-         // PHY_ID_SHIFT++;
-        }
+        PHY_ID_MASK <<= 1;
+        // PHY_ID_SHIFT++;
+      }
 
       hCurrentProcessHandle = GetCurrentProcess();
       GetProcessAffinityMask(hCurrentProcessHandle, &dwProcessAffinity,
-                                                  &dwSystemAffinity);
+                             &dwSystemAffinity);
 
       // Check if available process affinity mask is equal to the
       // available system affinity mask
-      if (dwProcessAffinity != dwSystemAffinity)
-        {
+      if (dwProcessAffinity != dwSystemAffinity) {
         StatusFlag = HT_CANNOT_DETECT;
         this->NumberOfPhysicalCPU = (unsigned char)-1;
         return StatusFlag;
-        }
+      }
 
       dwAffinityMask = 1;
-      while (dwAffinityMask != 0 && dwAffinityMask <= dwProcessAffinity)
-        {
+      while (dwAffinityMask != 0 && dwAffinityMask <= dwProcessAffinity) {
         // Check if this CPU is available
-        if (dwAffinityMask & dwProcessAffinity)
-          {
-          if (SetProcessAffinityMask(hCurrentProcessHandle,
-                                     dwAffinityMask))
-            {
+        if (dwAffinityMask & dwProcessAffinity) {
+          if (SetProcessAffinityMask(hCurrentProcessHandle, dwAffinityMask)) {
             unsigned char APIC_ID, LOG_ID;
             Sleep(0); // Give OS time to switch CPU
 
             APIC_ID = GetAPICId();
-            LOG_ID  = APIC_ID & ~PHY_ID_MASK;
+            LOG_ID = APIC_ID & ~PHY_ID_MASK;
 
-            if (LOG_ID != 0)
-              {
+            if (LOG_ID != 0) {
               HT_Enabled = 1;
-              }
             }
           }
-        dwAffinityMask = dwAffinityMask << 1;
         }
+        dwAffinityMask = dwAffinityMask << 1;
+      }
       // Reset the processor affinity
       SetProcessAffinityMask(hCurrentProcessHandle, dwProcessAffinity);
 
-      if (this->NumberOfLogicalCPU == 1)  // Normal P4 : HT is disabled in hardware
-        {
+      if (this->NumberOfLogicalCPU ==
+          1) // Normal P4 : HT is disabled in hardware
+      {
         StatusFlag = HT_DISABLED;
-        }
-      else
-        {
-        if (HT_Enabled)
-          {
+      } else {
+        if (HT_Enabled) {
           // Total physical processors in a Hyper-Threading enabled system.
           this->NumberOfPhysicalCPU /= (this->NumberOfLogicalCPU);
           StatusFlag = HT_ENABLED;
-          }
-        else
-          {
+        } else {
           StatusFlag = HT_SUPPORTED_NOT_ENABLED;
-          }
         }
       }
     }
-  else
-    {
+  } else {
     // Processors do not have Hyper-Threading technology
     StatusFlag = HT_NOT_CAPABLE;
     this->NumberOfLogicalCPU = 1;
-    }
+  }
   return StatusFlag;
 #else
   return 0;
 #endif
 }
 
-
 /** Return the number of logical CPUs on the system */
 unsigned int SystemInformationImplementation::GetNumberOfLogicalCPU()
 {
   return this->NumberOfLogicalCPU;
 }
 
-
 /** Return the number of physical CPUs on the system */
 unsigned int SystemInformationImplementation::GetNumberOfPhysicalCPU()
 {
   return this->NumberOfPhysicalCPU;
 }
 
-
 /** For Mac use sysctlbyname calls to find system info */
 bool SystemInformationImplementation::ParseSysCtl()
 {
@@ -4402,20 +4522,20 @@ bool SystemInformationImplementation::ParseSysCtl()
   uint64_t value = 0;
   size_t len = sizeof(value);
   sysctlbyname("hw.memsize", &value, &len, NULL, 0);
-  this->TotalPhysicalMemory = static_cast< size_t >( value/1048576 );
+  this->TotalPhysicalMemory = static_cast<size_t>(value / 1048576);
 
   // Parse values for Mac
   this->AvailablePhysicalMemory = 0;
-  vm_statistics_data_t  vmstat;
+  vm_statistics_data_t vmstat;
   mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
-  if ( host_statistics(mach_host_self(), HOST_VM_INFO,
-                       (host_info_t) &vmstat, &count) == KERN_SUCCESS )
-    {
+  if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmstat,
+                      &count) == KERN_SUCCESS) {
     len = sizeof(value);
     err = sysctlbyname("hw.pagesize", &value, &len, NULL, 0);
     int64_t available_memory = vmstat.free_count * value;
-    this->AvailablePhysicalMemory = static_cast< size_t >( available_memory / 1048576 );
-    }
+    this->AvailablePhysicalMemory =
+      static_cast<size_t>(available_memory / 1048576);
+  }
 
 #ifdef VM_SWAPUSAGE
   // Virtual memory.
@@ -4424,17 +4544,17 @@ bool SystemInformationImplementation::ParseSysCtl()
   struct xsw_usage swap;
   len = sizeof(swap);
   err = sysctl(mib, miblen, &swap, &len, NULL, 0);
-  if (err == 0)
-    {
-    this->AvailableVirtualMemory = static_cast< size_t >( swap.xsu_avail/1048576 );
-    this->TotalVirtualMemory = static_cast< size_t >( swap.xsu_total/1048576 );
-    }
+  if (err == 0) {
+    this->AvailableVirtualMemory =
+      static_cast<size_t>(swap.xsu_avail / 1048576);
+    this->TotalVirtualMemory = static_cast<size_t>(swap.xsu_total / 1048576);
+  }
 #else
-   this->AvailableVirtualMemory = 0;
-   this->TotalVirtualMemory = 0;
+  this->AvailableVirtualMemory = 0;
+  this->TotalVirtualMemory = 0;
 #endif
 
-// CPU Info
+  // CPU Info
   len = sizeof(this->NumberOfPhysicalCPU);
   sysctlbyname("hw.physicalcpu", &this->NumberOfPhysicalCPU, &len, NULL, 0);
   len = sizeof(this->NumberOfLogicalCPU);
@@ -4444,34 +4564,31 @@ bool SystemInformationImplementation::ParseSysCtl()
 
   len = sizeof(value);
   sysctlbyname("hw.cpufrequency", &value, &len, NULL, 0);
-  this->CPUSpeedInMHz = static_cast< float >( value )/ 1000000;
-
+  this->CPUSpeedInMHz = static_cast<float>(value) / 1000000;
 
   // Chip family
   len = sizeof(this->ChipID.Family);
-  //Seems only the intel chips will have this name so if this fails it is
-  //probably a PPC machine
-  err = sysctlbyname("machdep.cpu.family",
-                     &this->ChipID.Family, &len, NULL, 0);
+  // Seems only the intel chips will have this name so if this fails it is
+  // probably a PPC machine
+  err =
+    sysctlbyname("machdep.cpu.family", &this->ChipID.Family, &len, NULL, 0);
   if (err != 0) // Go back to names we know but are less descriptive
-    {
+  {
     this->ChipID.Family = 0;
     ::memset(retBuf, 0, 128);
     len = 32;
     err = sysctlbyname("hw.machine", &retBuf, &len, NULL, 0);
     std::string machineBuf(retBuf);
-    if (machineBuf.find_first_of("Power") != std::string::npos)
-      {
+    if (machineBuf.find_first_of("Power") != std::string::npos) {
       this->ChipID.Vendor = "IBM";
       len = sizeof(this->ChipID.Family);
       err = sysctlbyname("hw.cputype", &this->ChipID.Family, &len, NULL, 0);
       len = sizeof(this->ChipID.Model);
       err = sysctlbyname("hw.cpusubtype", &this->ChipID.Model, &len, NULL, 0);
       this->FindManufacturer();
-      }
     }
-  else  // Should be an Intel Chip.
-    {
+  } else // Should be an Intel Chip.
+  {
     len = sizeof(this->ChipID.Family);
     err =
       sysctlbyname("machdep.cpu.family", &this->ChipID.Family, &len, NULL, 0);
@@ -4486,101 +4603,88 @@ bool SystemInformationImplementation::ParseSysCtl()
     // Chip Model
     len = sizeof(value);
     err = sysctlbyname("machdep.cpu.model", &value, &len, NULL, 0);
-    this->ChipID.Model = static_cast< int >( value );
+    this->ChipID.Model = static_cast<int>(value);
 
     // Chip Stepping
     len = sizeof(value);
     value = 0;
     err = sysctlbyname("machdep.cpu.stepping", &value, &len, NULL, 0);
-    if (!err)
-      {
-      this->ChipID.Revision = static_cast< int >( value );
-      }
+    if (!err) {
+      this->ChipID.Revision = static_cast<int>(value);
+    }
 
     // feature string
-    char *buf = 0;
+    char* buf = 0;
     size_t allocSize = 128;
 
     err = 0;
     len = 0;
 
-    // sysctlbyname() will return with err==0 && len==0 if the buffer is too small
-    while (err == 0 && len == 0)
-      {
+    // sysctlbyname() will return with err==0 && len==0 if the buffer is too
+    // small
+    while (err == 0 && len == 0) {
       delete[] buf;
       allocSize *= 2;
       buf = new char[allocSize];
-      if (!buf)
-        {
+      if (!buf) {
         break;
-        }
+      }
       buf[0] = ' ';
       len = allocSize - 2; // keep space for leading and trailing space
       err = sysctlbyname("machdep.cpu.features", buf + 1, &len, NULL, 0);
-      }
-    if (!err && buf && len)
-      {
+    }
+    if (!err && buf && len) {
       // now we can match every flags as space + flag + space
       buf[len + 1] = ' ';
       std::string cpuflags(buf, len + 2);
 
-      if ((cpuflags.find(" FPU ")!=std::string::npos))
-        {
+      if ((cpuflags.find(" FPU ") != std::string::npos)) {
         this->Features.HasFPU = true;
-        }
-      if ((cpuflags.find(" TSC ")!=std::string::npos))
-        {
+      }
+      if ((cpuflags.find(" TSC ") != std::string::npos)) {
         this->Features.HasTSC = true;
-        }
-      if ((cpuflags.find(" MMX ")!=std::string::npos))
-        {
+      }
+      if ((cpuflags.find(" MMX ") != std::string::npos)) {
         this->Features.HasMMX = true;
-        }
-      if ((cpuflags.find(" SSE ")!=std::string::npos))
-        {
+      }
+      if ((cpuflags.find(" SSE ") != std::string::npos)) {
         this->Features.HasSSE = true;
-        }
-      if ((cpuflags.find(" SSE2 ")!=std::string::npos))
-        {
+      }
+      if ((cpuflags.find(" SSE2 ") != std::string::npos)) {
         this->Features.HasSSE2 = true;
-        }
-      if ((cpuflags.find(" APIC ")!=std::string::npos))
-        {
+      }
+      if ((cpuflags.find(" APIC ") != std::string::npos)) {
         this->Features.HasAPIC = true;
-        }
-      if ((cpuflags.find(" CMOV ")!=std::string::npos))
-        {
+      }
+      if ((cpuflags.find(" CMOV ") != std::string::npos)) {
         this->Features.HasCMOV = true;
-        }
-      if ((cpuflags.find(" MTRR ")!=std::string::npos))
-        {
+      }
+      if ((cpuflags.find(" MTRR ") != std::string::npos)) {
         this->Features.HasMTRR = true;
-        }
-      if ((cpuflags.find(" ACPI ")!=std::string::npos))
-        {
+      }
+      if ((cpuflags.find(" ACPI ") != std::string::npos)) {
         this->Features.HasACPI = true;
-        }
       }
-    delete[] buf;
     }
+    delete[] buf;
+  }
 
   // brand string
   ::memset(retBuf, 0, sizeof(retBuf));
   len = sizeof(retBuf);
   err = sysctlbyname("machdep.cpu.brand_string", retBuf, &len, NULL, 0);
-  if (!err)
-    {
+  if (!err) {
     this->ChipID.ProcessorName = retBuf;
     this->ChipID.ModelName = retBuf;
-    }
+  }
 
   // Cache size
   len = sizeof(value);
   err = sysctlbyname("hw.l1icachesize", &value, &len, NULL, 0);
-  this->Features.L1CacheSize = static_cast< int >( value );
+  this->Features.L1CacheSize = static_cast<int>(value);
   len = sizeof(value);
   err = sysctlbyname("hw.l2cachesize", &value, &len, NULL, 0);
-  this->Features.L2CacheSize = static_cast< int >( value );
+  this->Features.L2CacheSize = static_cast<int>(value);
 
   return true;
 #else
@@ -4588,33 +4692,31 @@ bool SystemInformationImplementation::ParseSysCtl()
 #endif
 }
 
-
 /** Extract a value from sysctl command */
-std::string SystemInformationImplementation::ExtractValueFromSysCtl(const char* word)
+std::string SystemInformationImplementation::ExtractValueFromSysCtl(
+  const char* word)
 {
   size_t pos = this->SysCtlBuffer.find(word);
-  if(pos != this->SysCtlBuffer.npos)
-    {
-    pos = this->SysCtlBuffer.find(": ",pos);
-    size_t pos2 = this->SysCtlBuffer.find("\n",pos);
-    if(pos!=this->SysCtlBuffer.npos && pos2!=this->SysCtlBuffer.npos)
-      {
-      return this->SysCtlBuffer.substr(pos+2,pos2-pos-2);
-      }
+  if (pos != this->SysCtlBuffer.npos) {
+    pos = this->SysCtlBuffer.find(": ", pos);
+    size_t pos2 = this->SysCtlBuffer.find("\n", pos);
+    if (pos != this->SysCtlBuffer.npos && pos2 != this->SysCtlBuffer.npos) {
+      return this->SysCtlBuffer.substr(pos + 2, pos2 - pos - 2);
     }
+  }
   return "";
 }
 
-
 /** Run a given process */
-std::string SystemInformationImplementation::RunProcess(std::vector<const char*> args)
+std::string SystemInformationImplementation::RunProcess(
+  std::vector<const char*> args)
 {
   std::string buffer = "";
 
   // Run the application
   kwsysProcess* gp = kwsysProcess_New();
   kwsysProcess_SetCommand(gp, &*args.begin());
-  kwsysProcess_SetOption(gp,kwsysProcess_Option_HideWindow,1);
+  kwsysProcess_SetOption(gp, kwsysProcess_Option_HideWindow, 1);
 
   kwsysProcess_Execute(gp);
 
@@ -4623,51 +4725,46 @@ std::string SystemInformationImplementation::RunProcess(std::vector<const char*>
   double timeout = 255;
   int pipe; // pipe id as returned by kwsysProcess_WaitForData()
 
-  while( ( static_cast<void>(pipe = kwsysProcess_WaitForData(gp,&data,&length,&timeout)),
-           (pipe == kwsysProcess_Pipe_STDOUT || pipe == kwsysProcess_Pipe_STDERR) ) ) // wait for 1s
-    {
-      buffer.append(data, length);
-    }
+  while ((static_cast<void>(
+            pipe = kwsysProcess_WaitForData(gp, &data, &length, &timeout)),
+          (pipe == kwsysProcess_Pipe_STDOUT ||
+           pipe == kwsysProcess_Pipe_STDERR))) // wait for 1s
+  {
+    buffer.append(data, length);
+  }
   kwsysProcess_WaitForExit(gp, 0);
 
   int result = 0;
-  switch(kwsysProcess_GetState(gp))
-    {
-    case kwsysProcess_State_Exited:
-      {
+  switch (kwsysProcess_GetState(gp)) {
+    case kwsysProcess_State_Exited: {
       result = kwsysProcess_GetExitValue(gp);
-      } break;
-    case kwsysProcess_State_Error:
-      {
+    } break;
+    case kwsysProcess_State_Error: {
       std::cerr << "Error: Could not run " << args[0] << ":\n";
       std::cerr << kwsysProcess_GetErrorString(gp) << "\n";
-      } break;
-    case kwsysProcess_State_Exception:
-      {
-      std::cerr << "Error: " << args[0]
-                << " terminated with an exception: "
+    } break;
+    case kwsysProcess_State_Exception: {
+      std::cerr << "Error: " << args[0] << " terminated with an exception: "
                 << kwsysProcess_GetExceptionString(gp) << "\n";
-      } break;
+    } break;
     case kwsysProcess_State_Starting:
     case kwsysProcess_State_Executing:
     case kwsysProcess_State_Expired:
-    case kwsysProcess_State_Killed:
-      {
+    case kwsysProcess_State_Killed: {
       // Should not get here.
       std::cerr << "Unexpected ending state after running " << args[0]
                 << std::endl;
-      } break;
-    }
+    } break;
+  }
   kwsysProcess_Delete(gp);
-  if(result)
-    {
+  if (result) {
     std::cerr << "Error " << args[0] << " returned :" << result << "\n";
-    }
+  }
   return buffer;
 }
 
-
-std::string SystemInformationImplementation::ParseValueFromKStat(const char* arguments)
+std::string SystemInformationImplementation::ParseValueFromKStat(
+  const char* arguments)
 {
   std::vector<const char*> args;
   args.clear();
@@ -4676,41 +4773,36 @@ std::string SystemInformationImplementation::ParseValueFromKStat(const char* arg
 
   std::string command = arguments;
   size_t start = command.npos;
-  size_t pos = command.find(' ',0);
-  while(pos!=command.npos)
-    {
+  size_t pos = command.find(' ', 0);
+  while (pos != command.npos) {
     bool inQuotes = false;
     // Check if we are between quotes
-    size_t b0 = command.find('"',0);
-    size_t b1 = command.find('"',b0+1);
-    while(b0 != command.npos && b1 != command.npos && b1>b0)
-      {
-      if(pos>b0 && pos<b1)
-        {
+    size_t b0 = command.find('"', 0);
+    size_t b1 = command.find('"', b0 + 1);
+    while (b0 != command.npos && b1 != command.npos && b1 > b0) {
+      if (pos > b0 && pos < b1) {
         inQuotes = true;
         break;
-        }
-      b0 = command.find('"',b1+1);
-      b1 = command.find('"',b0+1);
       }
+      b0 = command.find('"', b1 + 1);
+      b1 = command.find('"', b0 + 1);
+    }
 
-    if(!inQuotes)
-      {
-      std::string arg = command.substr(start+1,pos-start-1);
+    if (!inQuotes) {
+      std::string arg = command.substr(start + 1, pos - start - 1);
 
       // Remove the quotes if any
       size_t quotes = arg.find('"');
-      while(quotes != arg.npos)
-        {
-        arg.erase(quotes,1);
+      while (quotes != arg.npos) {
+        arg.erase(quotes, 1);
         quotes = arg.find('"');
-        }
+      }
       args.push_back(arg.c_str());
       start = pos;
-      }
-    pos = command.find(' ',pos+1);
     }
-  std::string lastArg = command.substr(start+1,command.size()-start-1);
+    pos = command.find(' ', pos + 1);
+  }
+  std::string lastArg = command.substr(start + 1, command.size() - start - 1);
   args.push_back(lastArg.c_str());
 
   args.push_back(0);
@@ -4718,41 +4810,37 @@ std::string SystemInformationImplementation::ParseValueFromKStat(const char* arg
   std::string buffer = this->RunProcess(args);
 
   std::string value = "";
-  for(size_t i=buffer.size()-1;i>0;i--)
-    {
-    if(buffer[i] == ' ' || buffer[i] == '\t')
-      {
+  for (size_t i = buffer.size() - 1; i > 0; i--) {
+    if (buffer[i] == ' ' || buffer[i] == '\t') {
       break;
-      }
-    if(buffer[i] != '\n' && buffer[i] != '\r')
-      {
+    }
+    if (buffer[i] != '\n' && buffer[i] != '\r') {
       std::string val = value;
       value = buffer[i];
       value += val;
-      }
     }
+  }
   return value;
 }
 
 /** Querying for system information from Solaris */
 bool SystemInformationImplementation::QuerySolarisMemory()
 {
-#if defined (__SVR4) && defined (__sun)
-  // Solaris allows querying this value by sysconf, but if this is
-  // a 32 bit process on a 64 bit host the returned memory will be
-  // limited to 4GiB. So if this is a 32 bit process or if the sysconf
-  // method fails use the kstat interface.
+#if defined(__SVR4) && defined(__sun)
+// Solaris allows querying this value by sysconf, but if this is
+// a 32 bit process on a 64 bit host the returned memory will be
+// limited to 4GiB. So if this is a 32 bit process or if the sysconf
+// method fails use the kstat interface.
 #if SIZEOF_VOID_P == 8
-  if (this->QueryMemoryBySysconf())
-    {
+  if (this->QueryMemoryBySysconf()) {
     return true;
-    }
+  }
 #endif
 
   char* tail;
   unsigned long totalMemory =
-       strtoul(this->ParseValueFromKStat("-s physmem").c_str(),&tail,0);
-  this->TotalPhysicalMemory = totalMemory/128;
+    strtoul(this->ParseValueFromKStat("-s physmem").c_str(), &tail, 0);
+  this->TotalPhysicalMemory = totalMemory / 128;
 
   return true;
 #else
@@ -4762,13 +4850,13 @@ bool SystemInformationImplementation::QuerySolarisMemory()
 
 bool SystemInformationImplementation::QuerySolarisProcessor()
 {
-  if (!this->QueryProcessorBySysconf())
-    {
+  if (!this->QueryProcessorBySysconf()) {
     return false;
-    }
+  }
 
   // Parse values
-  this->CPUSpeedInMHz = static_cast<float>(atoi(this->ParseValueFromKStat("-s clock_MHz").c_str()));
+  this->CPUSpeedInMHz = static_cast<float>(
+    atoi(this->ParseValueFromKStat("-s clock_MHz").c_str()));
 
   // Chip family
   this->ChipID.Family = 0;
@@ -4778,16 +4866,14 @@ bool SystemInformationImplementation::QuerySolarisProcessor()
   this->ChipID.Model = 0;
 
   // Chip Vendor
-  if (this->ChipID.ProcessorName != "i386")
-    {
+  if (this->ChipID.ProcessorName != "i386") {
     this->ChipID.Vendor = "Sun";
     this->FindManufacturer();
-    }
+  }
 
   return true;
 }
 
-
 /** Querying for system information from Haiku OS */
 bool SystemInformationImplementation::QueryHaikuInfo()
 {
@@ -4808,8 +4894,8 @@ bool SystemInformationImplementation::QueryHaikuInfo()
 
   for (uint32 i = 0; i < topologyNodeCount; i++) {
     if (topology[i].type == B_TOPOLOGY_CORE) {
-      this->CPUSpeedInMHz = topology[i].data.core.default_frequency /
-        1000000.0f;
+      this->CPUSpeedInMHz =
+        topology[i].data.core.default_frequency / 1000000.0f;
       break;
     }
   }
@@ -4817,11 +4903,10 @@ bool SystemInformationImplementation::QueryHaikuInfo()
   delete[] topology;
 
   // Physical Memory
-  this->TotalPhysicalMemory = (info.max_pages * B_PAGE_SIZE) / (1024 * 1024) ;
+  this->TotalPhysicalMemory = (info.max_pages * B_PAGE_SIZE) / (1024 * 1024);
   this->AvailablePhysicalMemory = this->TotalPhysicalMemory -
     ((info.used_pages * B_PAGE_SIZE) / (1024 * 1024));
 
-
   // NOTE: get_system_info_etc is currently a private call so just set to 0
   // until it becomes public
   this->TotalVirtualMemory = 0;
@@ -4910,7 +4995,8 @@ bool SystemInformationImplementation::QueryQNXMemory()
 
 bool SystemInformationImplementation::QueryBSDMemory()
 {
-#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
+#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) ||    \
+  defined(__DragonFly__)
   int ctrl[2] = { CTL_HW, HW_PHYSMEM };
 #if defined(HW_PHYSMEM64)
   int64_t k;
@@ -4920,12 +5006,11 @@ bool SystemInformationImplementation::QueryBSDMemory()
 #endif
   size_t sz = sizeof(k);
 
-  if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
-    {
+  if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0) {
     return false;
-    }
+  }
 
-  this->TotalPhysicalMemory = k>>10>>10;
+  this->TotalPhysicalMemory = k >> 10 >> 10;
 
   return true;
 #else
@@ -4963,21 +5048,19 @@ bool SystemInformationImplementation::QueryQNXProcessor()
   this->CPUSpeedInMHz = atoi(buffer.substr(pos3 + 1, pos2 - pos3 - 1).c_str());
 
   pos2 = buffer.find(" Stepping", pos);
-  if (pos2 != buffer.npos)
-    {
+  if (pos2 != buffer.npos) {
     pos2 = buffer.find(" ", pos2 + 1);
-    if (pos2 != buffer.npos && pos2 < pos3)
-      {
-      this->ChipID.Revision = atoi(buffer.substr(pos2 + 1, pos3 - pos2).c_str());
-      }
+    if (pos2 != buffer.npos && pos2 < pos3) {
+      this->ChipID.Revision =
+        atoi(buffer.substr(pos2 + 1, pos3 - pos2).c_str());
     }
+  }
 
   this->NumberOfPhysicalCPU = 0;
-  do
-    {
+  do {
     pos = buffer.find("\nProcessor", pos + 1);
     ++this->NumberOfPhysicalCPU;
-    } while (pos != buffer.npos);
+  } while (pos != buffer.npos);
   this->NumberOfLogicalCPU = 1;
 
   return true;
@@ -4988,15 +5071,15 @@ bool SystemInformationImplementation::QueryQNXProcessor()
 
 bool SystemInformationImplementation::QueryBSDProcessor()
 {
-#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
+#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) ||    \
+  defined(__DragonFly__)
   int k;
   size_t sz = sizeof(k);
   int ctrl[2] = { CTL_HW, HW_NCPU };
 
-  if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
-    {
+  if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0) {
     return false;
-    }
+  }
 
   this->NumberOfPhysicalCPU = k;
   this->NumberOfLogicalCPU = this->NumberOfPhysicalCPU;
@@ -5004,22 +5087,20 @@ bool SystemInformationImplementation::QueryBSDProcessor()
 #if defined(HW_CPUSPEED)
   ctrl[1] = HW_CPUSPEED;
 
-  if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
-    {
+  if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0) {
     return false;
-    }
+  }
 
-  this->CPUSpeedInMHz = (float) k;
+  this->CPUSpeedInMHz = (float)k;
 #endif
 
 #if defined(CPU_SSE)
   ctrl[0] = CTL_MACHDEP;
   ctrl[1] = CPU_SSE;
 
-  if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
-    {
+  if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0) {
     return false;
-    }
+  }
 
   this->Features.HasSSE = (k > 0);
 #endif
@@ -5028,10 +5109,9 @@ bool SystemInformationImplementation::QueryBSDProcessor()
   ctrl[0] = CTL_MACHDEP;
   ctrl[1] = CPU_SSE2;
 
-  if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
-    {
+  if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0) {
     return false;
-    }
+  }
 
   this->Features.HasSSE2 = (k > 0);
 #endif
@@ -5042,10 +5122,9 @@ bool SystemInformationImplementation::QueryBSDProcessor()
   char vbuf[25];
   ::memset(vbuf, 0, sizeof(vbuf));
   sz = sizeof(vbuf) - 1;
-  if (sysctl(ctrl, 2, vbuf, &sz, NULL, 0) != 0)
-    {
+  if (sysctl(ctrl, 2, vbuf, &sz, NULL, 0) != 0) {
     return false;
-    }
+  }
 
   this->ChipID.Vendor = vbuf;
   this->FindManufacturer();
@@ -5060,33 +5139,31 @@ bool SystemInformationImplementation::QueryBSDProcessor()
 bool SystemInformationImplementation::QueryHPUXMemory()
 {
 #if defined(__hpux)
-  unsigned long tv=0;
-  unsigned long tp=0;
-  unsigned long av=0;
-  unsigned long ap=0;
+  unsigned long tv = 0;
+  unsigned long tp = 0;
+  unsigned long av = 0;
+  unsigned long ap = 0;
   struct pst_static pst;
   struct pst_dynamic pdy;
 
   unsigned long ps = 0;
-  if (pstat_getstatic(&pst, sizeof(pst), (size_t) 1, 0) == -1)
-    {
+  if (pstat_getstatic(&pst, sizeof(pst), (size_t)1, 0) == -1) {
     return false;
-    }
+  }
 
   ps = pst.page_size;
-  tp =  pst.physical_memory *ps;
+  tp = pst.physical_memory * ps;
   tv = (pst.physical_memory + pst.pst_maxmem) * ps;
-  if (pstat_getdynamic(&pdy, sizeof(pdy), (size_t) 1, 0) == -1)
-    {
+  if (pstat_getdynamic(&pdy, sizeof(pdy), (size_t)1, 0) == -1) {
     return false;
-    }
+  }
 
   ap = tp - pdy.psd_rm * ps;
   av = tv - pdy.psd_vm;
-  this->TotalVirtualMemory = tv>>10>>10;
-  this->TotalPhysicalMemory = tp>>10>>10;
-  this->AvailableVirtualMemory = av>>10>>10;
-  this->AvailablePhysicalMemory = ap>>10>>10;
+  this->TotalVirtualMemory = tv >> 10 >> 10;
+  this->TotalPhysicalMemory = tp >> 10 >> 10;
+  this->AvailableVirtualMemory = av >> 10 >> 10;
+  this->AvailablePhysicalMemory = ap >> 10 >> 10;
   return true;
 #else
   return false;
@@ -5096,25 +5173,22 @@ bool SystemInformationImplementation::QueryHPUXMemory()
 bool SystemInformationImplementation::QueryHPUXProcessor()
 {
 #if defined(__hpux)
-# if defined(KWSYS_SYS_HAS_MPCTL_H)
+#if defined(KWSYS_SYS_HAS_MPCTL_H)
   int c = mpctl(MPC_GETNUMSPUS_SYS, 0, 0);
-  if (c <= 0)
-    {
+  if (c <= 0) {
     return false;
-    }
+  }
 
   this->NumberOfPhysicalCPU = c;
   this->NumberOfLogicalCPU = this->NumberOfPhysicalCPU;
 
   long t = sysconf(_SC_CPU_VERSION);
 
-  if (t == -1)
-    {
+  if (t == -1) {
     return false;
-    }
+  }
 
-  switch (t)
-    {
+  switch (t) {
     case CPU_PA_RISC1_0:
       this->ChipID.Vendor = "Hewlett-Packard";
       this->ChipID.Family = 0x100;
@@ -5127,27 +5201,27 @@ bool SystemInformationImplementation::QueryHPUXProcessor()
       this->ChipID.Vendor = "Hewlett-Packard";
       this->ChipID.Family = 0x200;
       break;
-#  if defined(CPU_HP_INTEL_EM_1_0) || defined(CPU_IA64_ARCHREV_0)
-#   ifdef CPU_HP_INTEL_EM_1_0
+#if defined(CPU_HP_INTEL_EM_1_0) || defined(CPU_IA64_ARCHREV_0)
+#ifdef CPU_HP_INTEL_EM_1_0
     case CPU_HP_INTEL_EM_1_0:
-#   endif
-#   ifdef CPU_IA64_ARCHREV_0
+#endif
+#ifdef CPU_IA64_ARCHREV_0
     case CPU_IA64_ARCHREV_0:
-#   endif
+#endif
       this->ChipID.Vendor = "GenuineIntel";
       this->Features.HasIA64 = true;
       break;
-#  endif
+#endif
     default:
       return false;
-    }
+  }
 
   this->FindManufacturer();
 
   return true;
-# else
+#else
   return false;
-# endif
+#endif
 #else
   return false;
 #endif
@@ -5166,215 +5240,178 @@ bool SystemInformationImplementation::QueryOSInformation()
   char operatingSystem[256];
 
   // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
-  ZeroMemory (&osvi, sizeof (OSVERSIONINFOEXW));
-  osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW);
+  ZeroMemory(&osvi, sizeof(OSVERSIONINFOEXW));
+  osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
 #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (push)
-# ifdef __INTEL_COMPILER
-#  pragma warning (disable:1478)
-# else
-#  pragma warning (disable:4996)
-# endif
-#endif
-  bOsVersionInfoEx = GetVersionExW ((OSVERSIONINFOW*)&osvi);
-  if (!bOsVersionInfoEx)
-    {
-    osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFOW);
-    if (!GetVersionExW((OSVERSIONINFOW*)&osvi))
-      {
+#pragma warning(push)
+#ifdef __INTEL_COMPILER
+#pragma warning(disable : 1478)
+#else
+#pragma warning(disable : 4996)
+#endif
+#endif
+  bOsVersionInfoEx = GetVersionExW((OSVERSIONINFOW*)&osvi);
+  if (!bOsVersionInfoEx) {
+    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
+    if (!GetVersionExW((OSVERSIONINFOW*)&osvi)) {
       return false;
-      }
     }
+  }
 #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (pop)
+#pragma warning(pop)
 #endif
 
-  switch (osvi.dwPlatformId)
-    {
+  switch (osvi.dwPlatformId) {
     case VER_PLATFORM_WIN32_NT:
       // Test for the product.
-      if (osvi.dwMajorVersion <= 4)
-        {
+      if (osvi.dwMajorVersion <= 4) {
         this->OSRelease = "NT";
-        }
-      if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
-        {
+      }
+      if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) {
         this->OSRelease = "2000";
-        }
-      if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
-        {
+      }
+      if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) {
         this->OSRelease = "XP";
-        }
+      }
       // XP Professional x64
-      if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
-        {
+      if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) {
         this->OSRelease = "XP";
-        }
+      }
 #ifdef VER_NT_WORKSTATION
       // Test for product type.
-      if (bOsVersionInfoEx)
-        {
-        if (osvi.wProductType == VER_NT_WORKSTATION)
-          {
-          if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0)
-            {
+      if (bOsVersionInfoEx) {
+        if (osvi.wProductType == VER_NT_WORKSTATION) {
+          if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0) {
             this->OSRelease = "Vista";
-            }
-          if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1)
-            {
+          }
+          if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1) {
             this->OSRelease = "7";
-            }
+          }
 // VER_SUITE_PERSONAL may not be defined
 #ifdef VER_SUITE_PERSONAL
-          else
-            {
-            if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
-              {
+          else {
+            if (osvi.wSuiteMask & VER_SUITE_PERSONAL) {
               this->OSRelease += " Personal";
-              }
-            else
-              {
+            } else {
               this->OSRelease += " Professional";
-              }
             }
-#endif
           }
-        else if (osvi.wProductType == VER_NT_SERVER)
-          {
+#endif
+        } else if (osvi.wProductType == VER_NT_SERVER) {
           // Check for .NET Server instead of Windows XP.
-          if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
-            {
+          if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) {
             this->OSRelease = ".NET";
-            }
+          }
 
           // Continue with the type detection.
-          if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
-            {
+          if (osvi.wSuiteMask & VER_SUITE_DATACENTER) {
             this->OSRelease += " DataCenter Server";
-            }
-          else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
-            {
+          } else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
             this->OSRelease += " Advanced Server";
-            }
-          else
-            {
+          } else {
             this->OSRelease += " Server";
-            }
           }
+        }
 
-        sprintf (operatingSystem, "%ls (Build %ld)", osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF);
+        sprintf(operatingSystem, "%ls (Build %ld)", osvi.szCSDVersion,
+                osvi.dwBuildNumber & 0xFFFF);
         this->OSVersion = operatingSystem;
-        }
-      else
-#endif        // VER_NT_WORKSTATION
-        {
+      } else
+#endif // VER_NT_WORKSTATION
+      {
         HKEY hKey;
         wchar_t szProductType[80];
         DWORD dwBufLen;
 
         // Query the registry to retrieve information.
-        RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0, KEY_QUERY_VALUE, &hKey);
-        RegQueryValueExW(hKey, L"ProductType", NULL, NULL, (LPBYTE) szProductType, &dwBufLen);
-        RegCloseKey (hKey);
-
-        if (lstrcmpiW(L"WINNT", szProductType) == 0)
-          {
+        RegOpenKeyExW(HKEY_LOCAL_MACHINE,
+                      L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0,
+                      KEY_QUERY_VALUE, &hKey);
+        RegQueryValueExW(hKey, L"ProductType", NULL, NULL,
+                         (LPBYTE)szProductType, &dwBufLen);
+        RegCloseKey(hKey);
+
+        if (lstrcmpiW(L"WINNT", szProductType) == 0) {
           this->OSRelease += " Professional";
-          }
-        if (lstrcmpiW(L"LANMANNT", szProductType) == 0)
-          {
-          // Decide between Windows 2000 Advanced Server and Windows .NET Enterprise Server.
-          if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
-            {
+        }
+        if (lstrcmpiW(L"LANMANNT", szProductType) == 0) {
+          // Decide between Windows 2000 Advanced Server and Windows .NET
+          // Enterprise Server.
+          if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) {
             this->OSRelease += " Standard Server";
-            }
-          else
-            {
+          } else {
             this->OSRelease += " Server";
-            }
           }
-        if (lstrcmpiW(L"SERVERNT", szProductType) == 0)
-          {
-          // Decide between Windows 2000 Advanced Server and Windows .NET Enterprise Server.
-          if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
-            {
+        }
+        if (lstrcmpiW(L"SERVERNT", szProductType) == 0) {
+          // Decide between Windows 2000 Advanced Server and Windows .NET
+          // Enterprise Server.
+          if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) {
             this->OSRelease += " Enterprise Server";
-            }
-          else
-            {
+          } else {
             this->OSRelease += " Advanced Server";
-            }
           }
-         }
+        }
+      }
 
       // Display version, service pack (if any), and build number.
-      if (osvi.dwMajorVersion <= 4)
-        {
+      if (osvi.dwMajorVersion <= 4) {
         // NB: NT 4.0 and earlier.
-        sprintf (operatingSystem, "version %ld.%ld %ls (Build %ld)",
-                 osvi.dwMajorVersion,
-                 osvi.dwMinorVersion,
-                 osvi.szCSDVersion,
-                 osvi.dwBuildNumber & 0xFFFF);
+        sprintf(operatingSystem, "version %ld.%ld %ls (Build %ld)",
+                osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.szCSDVersion,
+                osvi.dwBuildNumber & 0xFFFF);
         this->OSVersion = operatingSystem;
-        }
-      else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
-        {
+      } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) {
         // Windows XP and .NET server.
-        typedef BOOL (CALLBACK* LPFNPROC) (HANDLE, BOOL *);
+        typedef BOOL(CALLBACK * LPFNPROC)(HANDLE, BOOL*);
         HINSTANCE hKernelDLL;
         LPFNPROC DLLProc;
 
         // Load the Kernel32 DLL.
         hKernelDLL = LoadLibraryW(L"kernel32");
-        if (hKernelDLL != NULL)  {
-          // Only XP and .NET Server support IsWOW64Process so... Load dynamically!
-          DLLProc = (LPFNPROC) GetProcAddress (hKernelDLL, "IsWow64Process");
+        if (hKernelDLL != NULL) {
+          // Only XP and .NET Server support IsWOW64Process so... Load
+          // dynamically!
+          DLLProc = (LPFNPROC)GetProcAddress(hKernelDLL, "IsWow64Process");
 
           // If the function address is valid, call the function.
-          if (DLLProc != NULL) (DLLProc) (GetCurrentProcess (), &bIsWindows64Bit);
-          else bIsWindows64Bit = false;
+          if (DLLProc != NULL)
+            (DLLProc)(GetCurrentProcess(), &bIsWindows64Bit);
+          else
+            bIsWindows64Bit = false;
 
           // Free the DLL module.
-          FreeLibrary (hKernelDLL);
-          }
+          FreeLibrary(hKernelDLL);
         }
-      else
-        {
+      } else {
         // Windows 2000 and everything else.
-        sprintf (operatingSystem,"%ls (Build %ld)", osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF);
+        sprintf(operatingSystem, "%ls (Build %ld)", osvi.szCSDVersion,
+                osvi.dwBuildNumber & 0xFFFF);
         this->OSVersion = operatingSystem;
-        }
+      }
       break;
 
     case VER_PLATFORM_WIN32_WINDOWS:
       // Test for the product.
-      if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
-        {
+      if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) {
         this->OSRelease = "95";
-        if(osvi.szCSDVersion[1] == 'C')
-          {
+        if (osvi.szCSDVersion[1] == 'C') {
           this->OSRelease += "OSR 2.5";
-          }
-        else if(osvi.szCSDVersion[1] == 'B')
-          {
+        } else if (osvi.szCSDVersion[1] == 'B') {
           this->OSRelease += "OSR 2";
-          }
+        }
       }
 
-      if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
-        {
+      if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) {
         this->OSRelease = "98";
-        if (osvi.szCSDVersion[1] == 'A' )
-          {
+        if (osvi.szCSDVersion[1] == 'A') {
           this->OSRelease += "SE";
-          }
         }
+      }
 
-      if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
-        {
+      if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) {
         this->OSRelease = "Me";
-        }
+      }
       break;
 
     case VER_PLATFORM_WIN32s:
@@ -5390,42 +5427,39 @@ bool SystemInformationImplementation::QueryOSInformation()
   WORD wVersionRequested;
   WSADATA wsaData;
   char name[255];
-  wVersionRequested = MAKEWORD(2,0);
+  wVersionRequested = MAKEWORD(2, 0);
 
-  if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
-    {
-    gethostname(name,sizeof(name));
-    WSACleanup( );
-    }
+  if (WSAStartup(wVersionRequested, &wsaData) == 0) {
+    gethostname(name, sizeof(name));
+    WSACleanup();
+  }
   this->Hostname = name;
 
   const char* arch = getenv("PROCESSOR_ARCHITECTURE");
-  if(arch)
-    {
+  if (arch) {
     this->OSPlatform = arch;
-    }
+  }
 
 #else
 
   struct utsname unameInfo;
   int errorFlag = uname(&unameInfo);
-  if(errorFlag == 0)
-    {
+  if (errorFlag == 0) {
     this->OSName = unameInfo.sysname;
     this->Hostname = unameInfo.nodename;
     this->OSRelease = unameInfo.release;
     this->OSVersion = unameInfo.version;
     this->OSPlatform = unameInfo.machine;
-    }
+  }
 
 #ifdef __APPLE__
-  this->OSName="Unknown Apple OS";
-  this->OSRelease="Unknown product version";
-  this->OSVersion="Unknown build version";
+  this->OSName = "Unknown Apple OS";
+  this->OSRelease = "Unknown product version";
+  this->OSVersion = "Unknown build version";
 
-  this->CallSwVers("-productName",this->OSName);
-  this->CallSwVers("-productVersion",this->OSRelease);
-  this->CallSwVers("-buildVersion",this->OSVersion);
+  this->CallSwVers("-productName", this->OSName);
+  this->CallSwVers("-productVersion", this->OSRelease);
+  this->CallSwVers("-buildVersion", this->OSVersion);
 #endif
 
 #endif
@@ -5433,9 +5467,8 @@ bool SystemInformationImplementation::QueryOSInformation()
   return true;
 }
 
-int SystemInformationImplementation::CallSwVers(
-      const char *arg,
-      std::string &ver)
+int SystemInformationImplementation::CallSwVers(const char* arg,
+                                                std::string& ver)
 {
 #ifdef __APPLE__
   std::vector<const char*> args;
@@ -5455,26 +5488,21 @@ int SystemInformationImplementation::CallSwVers(
 void SystemInformationImplementation::TrimNewline(std::string& output)
 {
   // remove \r
-  std::string::size_type pos=0;
-  while((pos = output.find("\r", pos)) != std::string::npos)
-    {
+  std::string::size_type pos = 0;
+  while ((pos = output.find("\r", pos)) != std::string::npos) {
     output.erase(pos);
-    }
+  }
 
   // remove \n
   pos = 0;
-  while((pos = output.find("\n", pos)) != std::string::npos)
-    {
+  while ((pos = output.find("\n", pos)) != std::string::npos) {
     output.erase(pos);
-    }
+  }
 }
 
-
 /** Return true if the machine is 64 bits */
 bool SystemInformationImplementation::Is64Bits()
 {
   return (sizeof(void*) == 8);
 }
-
-
-} // namespace @KWSYS_NAMESPACE@
+}
diff --git a/Source/kwsys/SystemInformation.hxx.in b/Source/kwsys/SystemInformation.hxx.in
index 7c45388..0fc1067 100644
--- a/Source/kwsys/SystemInformation.hxx.in
+++ b/Source/kwsys/SystemInformation.hxx.in
@@ -1,23 +1,14 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _SystemInformation_h
 #define @KWSYS_NAMESPACE at _SystemInformation_h
 
 #include <@KWSYS_NAMESPACE@/Configure.hxx>
+
 #include <stddef.h> /* size_t */
 #include <string>
 
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 
 // forward declare the implementation class
 class SystemInformationImplementation;
@@ -29,24 +20,24 @@ class @KWSYS_NAMESPACE at _EXPORT SystemInformation
 #elif @KWSYS_USE___INT64@
   typedef __int64 LongLong;
 #else
-# error "No Long Long"
+#error "No Long Long"
 #endif
   friend class SystemInformationImplementation;
   SystemInformationImplementation* Implementation;
-public:
 
-  SystemInformation ();
-  ~SystemInformation ();
+public:
+  SystemInformation();
+  ~SystemInformation();
 
-  const char * GetVendorString();
-  const char * GetVendorID();
+  const char* GetVendorString();
+  const char* GetVendorID();
   std::string GetTypeID();
   std::string GetFamilyID();
   std::string GetModelID();
   std::string GetModelName();
   std::string GetSteppingCode();
-  const char * GetExtendedProcessorName();
-  const char * GetProcessorSerialNumber();
+  const char* GetExtendedProcessorName();
+  const char* GetProcessorSerialNumber();
   int GetProcessorCacheSize();
   unsigned int GetLogicalProcessorsPerPhysical();
   float GetProcessorClockFrequency();
@@ -58,13 +49,13 @@ public:
   // on this system.
   std::string GetCPUDescription();
 
-  const char * GetHostname();
+  const char* GetHostname();
   std::string GetFullyQualifiedDomainName();
 
-  const char * GetOSName();
-  const char * GetOSRelease();
-  const char * GetOSVersion();
-  const char * GetOSPlatform();
+  const char* GetOSName();
+  const char* GetOSRelease();
+  const char* GetOSVersion();
+  const char* GetOSPlatform();
 
   int GetOSIsWindows();
   int GetOSIsLinux();
@@ -93,9 +84,8 @@ public:
   // returns an informative general description if the installed and
   // available ram on this system. See the  GetHostMmeoryTotal, and
   // Get{Host,Proc}MemoryAvailable methods for more information.
-  std::string GetMemoryDescription(
-        const char *hostLimitEnvVarName=NULL,
-        const char *procLimitEnvVarName=NULL);
+  std::string GetMemoryDescription(const char* hostLimitEnvVarName = NULL,
+                                   const char* procLimitEnvVarName = NULL);
 
   // Retrieve amount of physical memory installed on the system in KiB
   // units.
@@ -107,7 +97,7 @@ public:
   // parallel. The amount of memory reported may differ from the host
   // total if a host wide resource limit is applied. Such reource limits
   // are reported to us via an applicaiton specified environment variable.
-  LongLong GetHostMemoryAvailable(const char *hostLimitEnvVarName=NULL);
+  LongLong GetHostMemoryAvailable(const char* hostLimitEnvVarName = NULL);
 
   // Get total system RAM in units of KiB available to this process.
   // This may differ from the host available if a per-process resource
@@ -115,9 +105,8 @@ public:
   // system via rlimit API. Resource limits that are not imposed via
   // rlimit API may be reported to us via an application specified
   // environment variable.
-  LongLong GetProcMemoryAvailable(
-        const char *hostLimitEnvVarName=NULL,
-        const char *procLimitEnvVarName=NULL);
+  LongLong GetProcMemoryAvailable(const char* hostLimitEnvVarName = NULL,
+                                  const char* procLimitEnvVarName = NULL);
 
   // Get the system RAM used by all processes on the host, in units of KiB.
   LongLong GetHostMemoryUsed();
@@ -132,14 +121,12 @@ public:
   // enable/disable stack trace signal handler. In order to
   // produce an informative stack trace the application should
   // be dynamically linked and compiled with debug symbols.
-  static
-  void SetStackTraceOnError(int enable);
+  static void SetStackTraceOnError(int enable);
 
   // format and return the current program stack in a string. In
   // order to produce an informative stack trace the application
   // should be dynamically linked and compiled with debug symbols.
-  static
-  std::string GetProgramStack(int firstFrame, int wholePath);
+  static std::string GetProgramStack(int firstFrame, int wholePath);
 
   /** Run the different checks */
   void RunCPUCheck();
diff --git a/Source/kwsys/SystemTools.cxx b/Source/kwsys/SystemTools.cxx
index 5da715f..97dd4ae 100644
--- a/Source/kwsys/SystemTools.cxx
+++ b/Source/kwsys/SystemTools.cxx
@@ -1,27 +1,18 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
-
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifdef __osf__
-#  define _OSF_SOURCE
-#  define _POSIX_C_SOURCE 199506L
-#  define _XOPEN_SOURCE_EXTENDED
+#define _OSF_SOURCE
+#define _POSIX_C_SOURCE 199506L
+#define _XOPEN_SOURCE_EXTENDED
 #endif
 
-#if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__))
-#  define KWSYS_WINDOWS_DIRS
+#if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||          \
+                        defined(__BORLANDC__) || defined(__MINGW32__))
+#define KWSYS_WINDOWS_DIRS
 #else
-#  if defined(__SUNPRO_CC)
-#    include <fcntl.h>
-#  endif
+#if defined(__SUNPRO_CC)
+#include <fcntl.h>
+#endif
 #endif
 
 #include "kwsysPrivate.h"
@@ -31,34 +22,34 @@
 #include KWSYS_HEADER(FStream.hxx)
 #include KWSYS_HEADER(Encoding.hxx)
 
-#include <iostream>
 #include <fstream>
-#include <sstream>
+#include <iostream>
 #include <set>
+#include <sstream>
 #include <vector>
 
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "RegularExpression.hxx.in"
-# include "SystemTools.hxx.in"
-# include "Directory.hxx.in"
-# include "FStream.hxx.in"
-# include "Encoding.hxx.in"
+#include "Directory.hxx.in"
+#include "Encoding.hxx.in"
+#include "FStream.hxx.in"
+#include "RegularExpression.hxx.in"
+#include "SystemTools.hxx.in"
 #endif
 
 #ifdef _MSC_VER
-# pragma warning (disable: 4786)
+#pragma warning(disable : 4786)
 #endif
 
 #if defined(__sgi) && !defined(__GNUC__)
-# pragma set woff 1375 /* base class destructor not virtual */
+#pragma set woff 1375 /* base class destructor not virtual */
 #endif
 
 #include <ctype.h>
 #include <errno.h>
 #ifdef __QNX__
-# include <malloc.h> /* for malloc/free on QNX */
+#include <malloc.h> /* for malloc/free on QNX */
 #endif
 #include <stdio.h>
 #include <stdlib.h>
@@ -67,64 +58,66 @@
 #include <time.h>
 
 #if defined(_WIN32) && !defined(_MSC_VER) && defined(__GNUC__)
-# include <strings.h> /* for strcasecmp */
+#include <strings.h> /* for strcasecmp */
 #endif
 
 #ifdef _MSC_VER
-# define umask _umask // Note this is still umask on Borland
+#define umask _umask // Note this is still umask on Borland
 #endif
 
 // support for realpath call
 #ifndef _WIN32
-#include <sys/time.h>
-#include <utime.h>
 #include <limits.h>
-#include <sys/wait.h>
+#include <pwd.h>
 #include <sys/ioctl.h>
+#include <sys/time.h>
+#include <sys/wait.h>
 #include <unistd.h>
-#include <pwd.h>
+#include <utime.h>
 #ifndef __VMS
 #include <sys/param.h>
 #include <termios.h>
 #endif
-#include <signal.h>    /* sigprocmask */
+#include <signal.h> /* sigprocmask */
 #endif
 
 // Windows API.
 #if defined(_WIN32)
-# include <windows.h>
-# include <winioctl.h>
-# 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
+#include <windows.h>
+#include <winioctl.h>
+#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
 #endif
 
 #if !KWSYS_CXX_HAS_ENVIRON_IN_STDLIB_H
-extern char **environ;
+extern char** environ;
 #endif
 
 #ifdef __CYGWIN__
-# include <sys/cygwin.h>
+#include <sys/cygwin.h>
 #endif
 
 // getpwnam doesn't exist on Windows and Cray Xt3/Catamount
 // same for TIOCGWINSZ
-#if defined(_WIN32) || defined (__LIBCATAMOUNT__)
-# undef HAVE_GETPWNAM
-# undef HAVE_TTY_INFO
+#if defined(_WIN32) || defined(__LIBCATAMOUNT__)
+#undef HAVE_GETPWNAM
+#undef HAVE_TTY_INFO
 #else
-# define HAVE_GETPWNAM 1
-# define HAVE_TTY_INFO 1
+#define HAVE_GETPWNAM 1
+#define HAVE_TTY_INFO 1
 #endif
 
 #define VTK_URL_PROTOCOL_REGEX "([a-zA-Z0-9]*)://(.*)"
-#define VTK_URL_REGEX "([a-zA-Z0-9]*)://(([A-Za-z0-9]+)(:([^:@]+))?@)?([^:@/]+)(:([0-9]+))?/(.+)?"
+#define VTK_URL_REGEX                                                         \
+  "([a-zA-Z0-9]*)://(([A-Za-z0-9]+)(:([^:@]+))?@)?([^:@/]+)(:([0-9]+))?/"     \
+  "(.+)?"
 
 #ifdef _MSC_VER
 #include <sys/utime.h>
@@ -132,13 +125,11 @@ extern char **environ;
 #include <utime.h>
 #endif
 
-
 // This is a hack to prevent warnings about these functions being
 // declared but not referenced.
 #if defined(__sgi) && !defined(__GNUC__)
-# include <sys/termios.h>
-namespace KWSYS_NAMESPACE
-{
+#include <sys/termios.h>
+namespace KWSYS_NAMESPACE {
 class SystemToolsHack
 {
 public:
@@ -148,26 +139,27 @@ public:
     Ref2 = sizeof(cfgetispeed(0)),
     Ref3 = sizeof(tcgetattr(0, 0)),
     Ref4 = sizeof(tcsetattr(0, 0, 0)),
-    Ref5 = sizeof(cfsetospeed(0,0)),
-    Ref6 = sizeof(cfsetispeed(0,0))
+    Ref5 = sizeof(cfsetospeed(0, 0)),
+    Ref6 = sizeof(cfsetispeed(0, 0))
   };
 };
 }
 #endif
 
-#if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||defined(__BORLANDC__) || defined(__MINGW32__))
-#include <io.h>
+#if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) ||          \
+                        defined(__BORLANDC__) || defined(__MINGW32__))
 #include <direct.h>
+#include <io.h>
 #define _unlink unlink
 #endif
 
 /* The maximum length of a file name.  */
 #if defined(PATH_MAX)
-# define KWSYS_SYSTEMTOOLS_MAXPATH PATH_MAX
+#define KWSYS_SYSTEMTOOLS_MAXPATH PATH_MAX
 #elif defined(MAXPATHLEN)
-# define KWSYS_SYSTEMTOOLS_MAXPATH MAXPATHLEN
+#define KWSYS_SYSTEMTOOLS_MAXPATH MAXPATHLEN
 #else
-# define KWSYS_SYSTEMTOOLS_MAXPATH 16384
+#define KWSYS_SYSTEMTOOLS_MAXPATH 16384
 #endif
 #if defined(__WATCOMC__)
 #include <direct.h>
@@ -188,20 +180,19 @@ static inline void usleep(unsigned int msec)
 }
 
 // BeOS 5 also doesn't have realpath(), but its C++ API offers something close.
-static inline char *realpath(const char *path, char *resolved_path)
+static inline char* realpath(const char* path, char* resolved_path)
 {
   const size_t maxlen = KWSYS_SYSTEMTOOLS_MAXPATH;
   snprintf(resolved_path, maxlen, "%s", path);
   BPath normalized(resolved_path, NULL, true);
-  const char *resolved = normalized.Path();
-  if (resolved != NULL)   // NULL == No such file.
-    {
-    if (snprintf(resolved_path, maxlen, "%s", resolved) < maxlen)
-      {
+  const char* resolved = normalized.Path();
+  if (resolved != NULL) // NULL == No such file.
+  {
+    if (snprintf(resolved_path, maxlen, "%s", resolved) < maxlen) {
       return resolved_path;
-      }
     }
-  return NULL;   // something went wrong.
+  }
+  return NULL; // something went wrong.
 }
 #endif
 
@@ -236,74 +227,60 @@ inline int Rmdir(const std::string& dir)
 inline const char* Getcwd(char* buf, unsigned int len)
 {
   std::vector<wchar_t> w_buf(len);
-  if(_wgetcwd(&w_buf[0], len))
-    {
+  if (_wgetcwd(&w_buf[0], len)) {
     // make sure the drive letter is capital
-    if(wcslen(&w_buf[0]) > 1 && w_buf[1] == L':')
-      {
+    if (wcslen(&w_buf[0]) > 1 && w_buf[1] == L':') {
       w_buf[0] = towupper(w_buf[0]);
-      }
+    }
     std::string tmp = KWSYS_NAMESPACE::Encoding::ToNarrow(&w_buf[0]);
     strcpy(buf, tmp.c_str());
     return buf;
-    }
+  }
   return 0;
 }
 inline int Chdir(const std::string& dir)
 {
-  #if defined(__BORLANDC__)
+#if defined(__BORLANDC__)
   return chdir(dir.c_str());
-  #else
+#else
   return _wchdir(KWSYS_NAMESPACE::Encoding::ToWide(dir).c_str());
-  #endif
+#endif
 }
-inline void Realpath(const std::string& path,
-                     std::string& resolved_path,
+inline void Realpath(const std::string& path, std::string& resolved_path,
                      std::string* errorMessage = 0)
 {
   std::wstring tmp = KWSYS_NAMESPACE::Encoding::ToWide(path);
-  wchar_t *ptemp;
+  wchar_t* ptemp;
   wchar_t fullpath[MAX_PATH];
-  DWORD bufferLen = GetFullPathNameW(tmp.c_str(),
-      sizeof(fullpath) / sizeof(fullpath[0]),
-      fullpath, &ptemp);
-  if( bufferLen < sizeof(fullpath)/sizeof(fullpath[0]) )
-    {
+  DWORD bufferLen = GetFullPathNameW(
+    tmp.c_str(), sizeof(fullpath) / sizeof(fullpath[0]), fullpath, &ptemp);
+  if (bufferLen < sizeof(fullpath) / sizeof(fullpath[0])) {
     resolved_path = KWSYS_NAMESPACE::Encoding::ToNarrow(fullpath);
     KWSYS_NAMESPACE::SystemTools::ConvertToUnixSlashes(resolved_path);
-    }
-  else if(errorMessage)
-    {
-    if(bufferLen)
-      {
+  } else if (errorMessage) {
+    if (bufferLen) {
       *errorMessage = "Destination path buffer size too small.";
-      }
-    else if(unsigned int errorId = GetLastError())
-      {
+    } else if (unsigned int errorId = GetLastError()) {
       LPSTR message = NULL;
-      DWORD size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
-                                   | FORMAT_MESSAGE_FROM_SYSTEM
-                                   | FORMAT_MESSAGE_IGNORE_INSERTS,
-                                   NULL, errorId,
-                                   MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-                                   (LPSTR)&message, 0, NULL);
+      DWORD size = FormatMessageA(
+        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
+          FORMAT_MESSAGE_IGNORE_INSERTS,
+        NULL, errorId, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+        (LPSTR)&message, 0, NULL);
       *errorMessage = std::string(message, size);
       LocalFree(message);
-      }
-    else
-      {
+    } else {
       *errorMessage = "Unknown error.";
-      }
+    }
 
     resolved_path = "";
-    }
-  else
-    {
+  } else {
     resolved_path = path;
-    }
+  }
 }
 #else
 #include <sys/types.h>
+
 #include <fcntl.h>
 #include <unistd.h>
 inline int Mkdir(const std::string& dir)
@@ -323,72 +300,59 @@ inline int Chdir(const std::string& dir)
 {
   return chdir(dir.c_str());
 }
-inline void Realpath(const std::string& path,
-                     std::string& resolved_path,
+inline void Realpath(const std::string& path, std::string& resolved_path,
                      std::string* errorMessage = 0)
 {
   char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH];
 
   errno = 0;
-  char *ret = realpath(path.c_str(), resolved_name);
-  if(ret)
-    {
+  char* ret = realpath(path.c_str(), resolved_name);
+  if (ret) {
     resolved_path = ret;
-    }
-  else if(errorMessage)
-    {
-    if(errno)
-      {
+  } else if (errorMessage) {
+    if (errno) {
       *errorMessage = strerror(errno);
-      }
-    else
-      {
+    } else {
       *errorMessage = "Unknown error.";
-      }
+    }
 
     resolved_path = "";
-    }
-  else
-    {
+  } else {
     // if path resolution fails, return what was passed in
     resolved_path = path;
-    }
+  }
 }
 #endif
 
 #if !defined(_WIN32) && defined(__COMO__)
 // Hack for como strict mode to avoid defining _SVID_SOURCE or _BSD_SOURCE.
-extern "C"
-{
-extern FILE *popen (__const char *__command, __const char *__modes) __THROW;
-extern int pclose (FILE *__stream) __THROW;
-extern char *realpath (__const char *__restrict __name,
-                       char *__restrict __resolved) __THROW;
-extern char *strdup (__const char *__s) __THROW;
-extern int putenv (char *__string) __THROW;
+extern "C" {
+extern FILE* popen(__const char* __command, __const char* __modes) __THROW;
+extern int pclose(FILE* __stream) __THROW;
+extern char* realpath(__const char* __restrict __name,
+                      char* __restrict __resolved) __THROW;
+extern char* strdup(__const char* __s) __THROW;
+extern int putenv(char* __string) __THROW;
 }
 #endif
 
-namespace KWSYS_NAMESPACE
-{
+namespace KWSYS_NAMESPACE {
 
 double SystemTools::GetTime(void)
 {
 #if defined(_WIN32) && !defined(__CYGWIN__)
   FILETIME ft;
   GetSystemTimeAsFileTime(&ft);
-  return (429.4967296*ft.dwHighDateTime
-          + 0.0000001*ft.dwLowDateTime
-          - 11644473600.0);
+  return (429.4967296 * ft.dwHighDateTime + 0.0000001 * ft.dwLowDateTime -
+          11644473600.0);
 #else
   struct timeval t;
   gettimeofday(&t, 0);
-  return 1.0*double(t.tv_sec) + 0.000001*double(t.tv_usec);
+  return 1.0 * double(t.tv_sec) + 0.000001 * double(t.tv_usec);
 #endif
 }
 
-class SystemToolsTranslationMap :
-    public std::map<std::string,std::string>
+class SystemToolsTranslationMap : public std::map<std::string, std::string>
 {
 };
 
@@ -402,83 +366,82 @@ typedef char envchar;
 /* Order by environment key only (VAR from VAR=VALUE).  */
 struct kwsysEnvCompare
 {
-  bool operator() (const envchar* l, const envchar* r) const
-    {
+  bool operator()(const envchar* l, const envchar* r) const
+  {
 #if defined(_WIN32)
     const wchar_t* leq = wcschr(l, L'=');
     const wchar_t* req = wcschr(r, L'=');
-    size_t llen = leq? (leq-l) : wcslen(l);
-    size_t rlen = req? (req-r) : wcslen(r);
-    if(llen == rlen)
-      {
-      return wcsncmp(l,r,llen) < 0;
-      }
-    else
-      {
-      return wcscmp(l,r) < 0;
-      }
+    size_t llen = leq ? (leq - l) : wcslen(l);
+    size_t rlen = req ? (req - r) : wcslen(r);
+    if (llen == rlen) {
+      return wcsncmp(l, r, llen) < 0;
+    } else {
+      return wcscmp(l, r) < 0;
+    }
 #else
     const char* leq = strchr(l, '=');
     const char* req = strchr(r, '=');
-    size_t llen = leq? (leq-l) : strlen(l);
-    size_t rlen = req? (req-r) : strlen(r);
-    if(llen == rlen)
-      {
-      return strncmp(l,r,llen) < 0;
-      }
-    else
-      {
-      return strcmp(l,r) < 0;
-      }
-#endif
+    size_t llen = leq ? (leq - l) : strlen(l);
+    size_t rlen = req ? (req - r) : strlen(r);
+    if (llen == rlen) {
+      return strncmp(l, r, llen) < 0;
+    } else {
+      return strcmp(l, r) < 0;
     }
+#endif
+  }
 };
 
-class kwsysEnvSet: public std::set<const envchar*, kwsysEnvCompare>
+class kwsysEnvSet : public std::set<const envchar*, kwsysEnvCompare>
 {
 public:
   class Free
   {
     const envchar* Env;
+
   public:
-    Free(const envchar* env): Env(env) {}
+    Free(const envchar* env)
+      : Env(env)
+    {
+    }
     ~Free() { free(const_cast<envchar*>(this->Env)); }
   };
 
   const envchar* Release(const envchar* env)
-    {
+  {
     const envchar* old = 0;
     iterator i = this->find(env);
-    if(i != this->end())
-      {
+    if (i != this->end()) {
       old = *i;
       this->erase(i);
-      }
-    return old;
     }
+    return old;
+  }
 };
 
 #ifdef _WIN32
 struct SystemToolsPathCaseCmp
 {
   bool operator()(std::string const& l, std::string const& r) const
-    {
-# ifdef _MSC_VER
+  {
+#ifdef _MSC_VER
     return _stricmp(l.c_str(), r.c_str()) < 0;
-# elif defined(__GNUC__)
+#elif defined(__GNUC__)
     return strcasecmp(l.c_str(), r.c_str()) < 0;
-# else
+#else
     return SystemTools::Strucmp(l.c_str(), r.c_str()) < 0;
-# endif
-    }
+#endif
+  }
 };
 
-class SystemToolsPathCaseMap:
-  public std::map<std::string, std::string,
-                        SystemToolsPathCaseCmp> {};
+class SystemToolsPathCaseMap
+  : public std::map<std::string, std::string, SystemToolsPathCaseCmp>
+{
+};
 
-class SystemToolsEnvMap :
-    public std::map<std::string,std::string> {};
+class SystemToolsEnvMap : public std::map<std::string, std::string>
+{
+};
 #endif
 
 // adds the elements of the env variable path to the arg passed in
@@ -490,54 +453,45 @@ void SystemTools::GetPath(std::vector<std::string>& path, const char* env)
 #else
   const char pathSep = ':';
 #endif
-  if(!env)
-    {
+  if (!env) {
     env = "PATH";
-    }
+  }
   std::string pathEnv;
-  if ( !SystemTools::GetEnv(env, pathEnv) )
-    {
+  if (!SystemTools::GetEnv(env, pathEnv)) {
     return;
-    }
+  }
 
   // A hack to make the below algorithm work.
-  if(!pathEnv.empty() && *pathEnv.rbegin() != pathSep)
-    {
+  if (!pathEnv.empty() && *pathEnv.rbegin() != pathSep) {
     pathEnv += pathSep;
-    }
-  std::string::size_type start =0;
+  }
+  std::string::size_type start = 0;
   bool done = false;
-  while(!done)
-    {
+  while (!done) {
     std::string::size_type endpos = pathEnv.find(pathSep, start);
-    if(endpos != std::string::npos)
-      {
-      path.push_back(pathEnv.substr(start, endpos-start));
-      start = endpos+1;
-      }
-    else
-      {
+    if (endpos != std::string::npos) {
+      path.push_back(pathEnv.substr(start, endpos - start));
+      start = endpos + 1;
+    } else {
       done = true;
-      }
     }
-  for(std::vector<std::string>::iterator i = path.begin() + old_size;
-      i != path.end(); ++i)
-    {
+  }
+  for (std::vector<std::string>::iterator i = path.begin() + old_size;
+       i != path.end(); ++i) {
     SystemTools::ConvertToUnixSlashes(*i);
-    }
+  }
 }
 
 const char* SystemTools::GetEnvImpl(const char* key)
 {
-  const char *v = 0;
+  const char* v = 0;
 #if defined(_WIN32)
   std::string env;
-  if (SystemTools::GetEnv(key, env))
-    {
+  if (SystemTools::GetEnv(key, env)) {
     std::string& menv = (*SystemTools::EnvMap)[key];
     menv = env;
     v = menv.c_str();
-    }
+  }
 #else
   v = getenv(key);
 #endif
@@ -559,18 +513,16 @@ bool SystemTools::GetEnv(const char* key, std::string& result)
 #if defined(_WIN32)
   const std::wstring wkey = Encoding::ToWide(key);
   const wchar_t* wv = _wgetenv(wkey.c_str());
-  if (wv)
-    {
+  if (wv) {
     result = Encoding::ToNarrow(wv);
     return true;
-    }
+  }
 #else
   const char* v = getenv(key);
-  if(v)
-    {
+  if (v) {
     result = v;
     return true;
-    }
+  }
 #endif
   return false;
 }
@@ -604,15 +556,12 @@ bool SystemTools::HasEnv(const std::string& key)
 static int kwsysUnPutEnv(const std::string& env)
 {
   size_t pos = env.find('=');
-  if(pos != env.npos)
-    {
+  if (pos != env.npos) {
     std::string name = env.substr(0, pos);
     unsetenv(name.c_str());
-    }
-  else
-    {
+  } else {
     unsetenv(env.c_str());
-    }
+  }
   return 0;
 }
 
@@ -627,25 +576,21 @@ static int kwsysUnPutEnv(const std::string& env)
   size_t const sz = len + 1;
   char local_buf[256];
   char* buf = sz > sizeof(local_buf) ? (char*)malloc(sz) : local_buf;
-  if(!buf)
-    {
+  if (!buf) {
     return -1;
-    }
+  }
   strncpy(buf, env.c_str(), len);
   buf[len] = 0;
-  if(putenv(buf) < 0 && errno != EINVAL)
-    {
+  if (putenv(buf) < 0 && errno != EINVAL) {
     err = errno;
-    }
-  if(buf != local_buf)
-    {
+  }
+  if (buf != local_buf) {
     free(buf);
-    }
-  if(err)
-    {
+  }
+  if (err) {
     errno = err;
     return -1;
-    }
+  }
   return 0;
 }
 
@@ -662,12 +607,11 @@ static int kwsysUnPutEnv(std::string const& env)
   std::wstring wEnv = Encoding::ToWide(env);
   size_t const pos = wEnv.find('=');
   size_t const len = pos == wEnv.npos ? wEnv.size() : pos;
-  wEnv.resize(len+1, L'=');
+  wEnv.resize(len + 1, L'=');
   wchar_t* newEnv = _wcsdup(wEnv.c_str());
-  if(!newEnv)
-    {
+  if (!newEnv) {
     return -1;
-    }
+  }
   kwsysEnvSet::Free oldEnv(kwsysUnPutEnvSet.Release(newEnv));
   kwsysUnPutEnvSet.insert(newEnv);
   return _wputenv(newEnv);
@@ -681,23 +625,17 @@ static int kwsysUnPutEnv(const std::string& env)
   size_t const len = pos == env.npos ? env.size() : pos;
   int in = 0;
   int out = 0;
-  while(environ[in])
-    {
-    if(strlen(environ[in]) > len &&
-       environ[in][len] == '=' &&
-       strncmp(env.c_str(), environ[in], len) == 0)
-      {
+  while (environ[in]) {
+    if (strlen(environ[in]) > len && environ[in][len] == '=' &&
+        strncmp(env.c_str(), environ[in], len) == 0) {
       ++in;
-      }
-    else
-      {
+    } else {
       environ[out++] = environ[in++];
-      }
     }
-  while(out < in)
-    {
+  }
+  while (out < in) {
     environ[out++] = 0;
-    }
+  }
   return 0;
 }
 #endif
@@ -711,15 +649,12 @@ static int kwsysUnPutEnv(const std::string& env)
 bool SystemTools::PutEnv(const std::string& env)
 {
   size_t pos = env.find('=');
-  if(pos != env.npos)
-    {
+  if (pos != env.npos) {
     std::string name = env.substr(0, pos);
     return setenv(name.c_str(), env.c_str() + pos + 1, 1) == 0;
-    }
-  else
-    {
+  } else {
     return kwsysUnPutEnv(env) == 0;
-    }
+  }
 }
 
 bool SystemTools::UnPutEnv(const std::string& env)
@@ -736,17 +671,16 @@ bool SystemTools::UnPutEnv(const std::string& env)
    environment values that may still reference memory we allocated.  Then free
    the memory.  This will not affect any environment values we never set.  */
 
-# ifdef __INTEL_COMPILER
-#  pragma warning disable 444 /* base has non-virtual destructor */
-# endif
+#ifdef __INTEL_COMPILER
+#pragma warning disable 444 /* base has non-virtual destructor */
+#endif
 
-class kwsysEnv: public kwsysEnvSet
+class kwsysEnv : public kwsysEnvSet
 {
 public:
   ~kwsysEnv()
-    {
-    for(iterator i = this->begin(); i != this->end(); ++i)
-      {
+  {
+    for (iterator i = this->begin(); i != this->end(); ++i) {
 #if defined(_WIN32)
       const std::string s = Encoding::ToNarrow(*i);
       kwsysUnPutEnv(s.c_str());
@@ -754,10 +688,10 @@ public:
       kwsysUnPutEnv(*i);
 #endif
       free(const_cast<envchar*>(*i));
-      }
     }
+  }
   bool Put(const char* env)
-    {
+  {
 #if defined(_WIN32)
     const std::wstring wEnv = Encoding::ToWide(env);
     wchar_t* newEnv = _wcsdup(wEnv.c_str());
@@ -771,9 +705,9 @@ public:
 #else
     return putenv(newEnv) == 0;
 #endif
-    }
+  }
   bool UnPut(const char* env)
-    {
+  {
 #if defined(_WIN32)
     const std::wstring wEnv = Encoding::ToWide(env);
     Free oldEnv(this->Release(wEnv.c_str()));
@@ -781,7 +715,7 @@ public:
     Free oldEnv(this->Release(env));
 #endif
     return kwsysUnPutEnv(env) == 0;
-    }
+  }
 };
 
 static kwsysEnv kwsysEnvInstance;
@@ -821,54 +755,47 @@ FILE* SystemTools::Fopen(const std::string& file, const char* mode)
 
 bool SystemTools::MakeDirectory(const char* path)
 {
-  if(!path)
-    {
+  if (!path) {
     return false;
-    }
+  }
   return SystemTools::MakeDirectory(std::string(path));
 }
 
 bool SystemTools::MakeDirectory(const std::string& path)
 {
-  if(SystemTools::FileExists(path))
-    {
+  if (SystemTools::PathExists(path)) {
     return SystemTools::FileIsDirectory(path);
-    }
-  if(path.empty())
-    {
+  }
+  if (path.empty()) {
     return false;
-    }
+  }
   std::string dir = path;
   SystemTools::ConvertToUnixSlashes(dir);
 
   std::string::size_type pos = 0;
   std::string topdir;
-  while((pos = dir.find('/', pos)) != std::string::npos)
-    {
+  while ((pos = dir.find('/', pos)) != std::string::npos) {
     topdir = dir.substr(0, pos);
     Mkdir(topdir);
     pos++;
-    }
+  }
   topdir = dir;
-  if(Mkdir(topdir) != 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
     // if it is some other error besides directory exists
     // then return false
-    if( (errno != EEXIST)
+    if ((errno != EEXIST)
 #ifdef __BORLANDC__
         && (errno != EACCES)
 #endif
-      )
-      {
+          ) {
       return false;
-      }
     }
+  }
   return true;
 }
 
-
 // replace replace with with as many times as it shows up in source.
 // write the result into source.
 void SystemTools::ReplaceString(std::string& source,
@@ -876,58 +803,51 @@ void SystemTools::ReplaceString(std::string& source,
                                 const std::string& with)
 {
   // do while hangs if replaceSize is 0
-  if (replace.empty())
-    {
+  if (replace.empty()) {
     return;
-    }
+  }
 
   SystemTools::ReplaceString(source, replace.c_str(), replace.size(), with);
 }
 
-void SystemTools::ReplaceString(std::string& source,
-                                const char* replace,
+void SystemTools::ReplaceString(std::string& source, const char* replace,
                                 const char* with)
 {
   // do while hangs if replaceSize is 0
-  if (!*replace)
-    {
+  if (!*replace) {
     return;
-    }
+  }
 
-  SystemTools::ReplaceString(source, replace, strlen(replace), with ? with : "");
+  SystemTools::ReplaceString(source, replace, strlen(replace),
+                             with ? with : "");
 }
 
-void SystemTools::ReplaceString(std::string& source,
-                                const char* replace,
-                                size_t replaceSize,
-                                const std::string& with)
+void SystemTools::ReplaceString(std::string& source, const char* replace,
+                                size_t replaceSize, const std::string& with)
 {
-  const char *src = source.c_str();
-  char *searchPos = const_cast<char *>(strstr(src,replace));
+  const char* src = source.c_str();
+  char* searchPos = const_cast<char*>(strstr(src, replace));
 
   // get out quick if string is not found
-  if (!searchPos)
-    {
+  if (!searchPos) {
     return;
-    }
+  }
 
   // perform replacements until done
-  char *orig = strdup(src);
-  char *currentPos = orig;
+  char* orig = strdup(src);
+  char* currentPos = orig;
   searchPos = searchPos - src + orig;
 
   // initialize the result
-  source.erase(source.begin(),source.end());
-  do
-    {
+  source.erase(source.begin(), source.end());
+  do {
     *searchPos = '\0';
     source += currentPos;
     currentPos = searchPos + replaceSize;
     // replace
     source += with;
-    searchPos = strstr(currentPos,replace);
-    }
-  while (searchPos);
+    searchPos = strstr(currentPos, replace);
+  } while (searchPos);
 
   // copy any trailing text
   source += currentPos;
@@ -935,56 +855,48 @@ void SystemTools::ReplaceString(std::string& source,
 }
 
 #if defined(KEY_WOW64_32KEY) && defined(KEY_WOW64_64KEY)
-# define KWSYS_ST_KEY_WOW64_32KEY KEY_WOW64_32KEY
-# define KWSYS_ST_KEY_WOW64_64KEY KEY_WOW64_64KEY
+#define KWSYS_ST_KEY_WOW64_32KEY KEY_WOW64_32KEY
+#define KWSYS_ST_KEY_WOW64_64KEY KEY_WOW64_64KEY
 #else
-# define KWSYS_ST_KEY_WOW64_32KEY 0x0200
-# define KWSYS_ST_KEY_WOW64_64KEY 0x0100
+#define KWSYS_ST_KEY_WOW64_32KEY 0x0200
+#define KWSYS_ST_KEY_WOW64_64KEY 0x0100
 #endif
 
 #if defined(_WIN32) && !defined(__CYGWIN__)
 static bool SystemToolsParseRegistryKey(const std::string& key,
-                                        HKEY& primaryKey,
-                                        std::string& second,
+                                        HKEY& primaryKey, std::string& second,
                                         std::string& valuename)
 {
   std::string primary = key;
 
   size_t start = primary.find('\\');
-  if (start == std::string::npos)
-    {
+  if (start == std::string::npos) {
     return false;
-    }
+  }
 
   size_t valuenamepos = primary.find(';');
-  if (valuenamepos != std::string::npos)
-    {
-    valuename = primary.substr(valuenamepos+1);
-    }
+  if (valuenamepos != std::string::npos) {
+    valuename = primary.substr(valuenamepos + 1);
+  }
 
-  second = primary.substr(start+1, valuenamepos-start-1);
+  second = primary.substr(start + 1, valuenamepos - start - 1);
   primary = primary.substr(0, start);
 
-  if (primary == "HKEY_CURRENT_USER")
-    {
+  if (primary == "HKEY_CURRENT_USER") {
     primaryKey = HKEY_CURRENT_USER;
-    }
-  if (primary == "HKEY_CURRENT_CONFIG")
-    {
+  }
+  if (primary == "HKEY_CURRENT_CONFIG") {
     primaryKey = HKEY_CURRENT_CONFIG;
-    }
-  if (primary == "HKEY_CLASSES_ROOT")
-    {
+  }
+  if (primary == "HKEY_CLASSES_ROOT") {
     primaryKey = HKEY_CLASSES_ROOT;
-    }
-  if (primary == "HKEY_LOCAL_MACHINE")
-    {
+  }
+  if (primary == "HKEY_LOCAL_MACHINE") {
     primaryKey = HKEY_LOCAL_MACHINE;
-    }
-  if (primary == "HKEY_USERS")
-    {
+  }
+  if (primary == "HKEY_USERS") {
     primaryKey = HKEY_USERS;
-    }
+  }
 
   return true;
 }
@@ -993,69 +905,56 @@ static DWORD SystemToolsMakeRegistryMode(DWORD mode,
                                          SystemTools::KeyWOW64 view)
 {
   // only add the modes when on a system that supports Wow64.
-  static FARPROC wow64p = GetProcAddress(GetModuleHandleW(L"kernel32"),
-                                         "IsWow64Process");
-  if(wow64p == NULL)
-    {
+  static FARPROC wow64p =
+    GetProcAddress(GetModuleHandleW(L"kernel32"), "IsWow64Process");
+  if (wow64p == NULL) {
     return mode;
-    }
+  }
 
-  if(view == SystemTools::KeyWOW64_32)
-    {
+  if (view == SystemTools::KeyWOW64_32) {
     return mode | KWSYS_ST_KEY_WOW64_32KEY;
-    }
-  else if(view == SystemTools::KeyWOW64_64)
-    {
+  } else if (view == SystemTools::KeyWOW64_64) {
     return mode | KWSYS_ST_KEY_WOW64_64KEY;
-    }
+  }
   return mode;
 }
 #endif
 
 #if defined(_WIN32) && !defined(__CYGWIN__)
-bool
-SystemTools::GetRegistrySubKeys(const std::string& key,
-                                std::vector<std::string>& subkeys,
-                                KeyWOW64 view)
+bool SystemTools::GetRegistrySubKeys(const std::string& key,
+                                     std::vector<std::string>& subkeys,
+                                     KeyWOW64 view)
 {
   HKEY primaryKey = HKEY_CURRENT_USER;
   std::string second;
   std::string valuename;
-  if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
-    {
+  if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename)) {
     return false;
-    }
+  }
 
   HKEY hKey;
-  if(RegOpenKeyExW(primaryKey,
-                  Encoding::ToWide(second).c_str(),
-                  0,
-                  SystemToolsMakeRegistryMode(KEY_READ, view),
-                  &hKey) != ERROR_SUCCESS)
-    {
+  if (RegOpenKeyExW(primaryKey, Encoding::ToWide(second).c_str(), 0,
+                    SystemToolsMakeRegistryMode(KEY_READ, view),
+                    &hKey) != ERROR_SUCCESS) {
     return false;
-    }
-  else
-    {
+  } else {
     wchar_t name[1024];
-    DWORD dwNameSize = sizeof(name)/sizeof(name[0]);
+    DWORD dwNameSize = sizeof(name) / sizeof(name[0]);
 
     DWORD i = 0;
-    while (RegEnumKeyW(hKey, i, name, dwNameSize) == ERROR_SUCCESS)
-      {
+    while (RegEnumKeyW(hKey, i, name, dwNameSize) == ERROR_SUCCESS) {
       subkeys.push_back(Encoding::ToNarrow(name));
       ++i;
-      }
+    }
 
     RegCloseKey(hKey);
-    }
+  }
 
   return true;
 }
 #else
 bool SystemTools::GetRegistrySubKeys(const std::string&,
-                                     std::vector<std::string>&,
-                                     KeyWOW64)
+                                     std::vector<std::string>&, KeyWOW64)
 {
   return false;
 }
@@ -1069,71 +968,53 @@ bool SystemTools::GetRegistrySubKeys(const std::string&,
 //      =>  will return the data of the "Root" value of the key
 
 #if defined(_WIN32) && !defined(__CYGWIN__)
-bool SystemTools::ReadRegistryValue(const std::string& key, std::string &value,
+bool SystemTools::ReadRegistryValue(const std::string& key, std::string& value,
                                     KeyWOW64 view)
 {
   bool valueset = false;
   HKEY primaryKey = HKEY_CURRENT_USER;
   std::string second;
   std::string valuename;
-  if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
-    {
+  if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename)) {
     return false;
-    }
+  }
 
   HKEY hKey;
-  if(RegOpenKeyExW(primaryKey,
-                  Encoding::ToWide(second).c_str(),
-                  0,
-                  SystemToolsMakeRegistryMode(KEY_READ, view),
-                  &hKey) != ERROR_SUCCESS)
-    {
+  if (RegOpenKeyExW(primaryKey, Encoding::ToWide(second).c_str(), 0,
+                    SystemToolsMakeRegistryMode(KEY_READ, view),
+                    &hKey) != ERROR_SUCCESS) {
     return false;
-    }
-  else
-    {
+  } else {
     DWORD dwType, dwSize;
     dwSize = 1023;
     wchar_t data[1024];
-    if(RegQueryValueExW(hKey,
-                       Encoding::ToWide(valuename).c_str(),
-                       NULL,
-                       &dwType,
-                       (BYTE *)data,
-                       &dwSize) == ERROR_SUCCESS)
-      {
-      if (dwType == REG_SZ)
-        {
+    if (RegQueryValueExW(hKey, Encoding::ToWide(valuename).c_str(), NULL,
+                         &dwType, (BYTE*)data, &dwSize) == ERROR_SUCCESS) {
+      if (dwType == REG_SZ) {
         value = Encoding::ToNarrow(data);
         valueset = true;
-        }
-      else if (dwType == REG_EXPAND_SZ)
-        {
+      } else if (dwType == REG_EXPAND_SZ) {
         wchar_t expanded[1024];
-        DWORD dwExpandedSize = sizeof(expanded)/sizeof(expanded[0]);
-        if(ExpandEnvironmentStringsW(data, expanded,
-            dwExpandedSize))
-          {
+        DWORD dwExpandedSize = sizeof(expanded) / sizeof(expanded[0]);
+        if (ExpandEnvironmentStringsW(data, expanded, dwExpandedSize)) {
           value = Encoding::ToNarrow(expanded);
           valueset = true;
-          }
         }
       }
+    }
 
     RegCloseKey(hKey);
-    }
+  }
 
   return valueset;
 }
 #else
-bool SystemTools::ReadRegistryValue(const std::string&, std::string &,
-                                    KeyWOW64)
+bool SystemTools::ReadRegistryValue(const std::string&, std::string&, KeyWOW64)
 {
   return false;
 }
 #endif
 
-
 // Write a registry value.
 // Example :
 //      HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.1\InstallPath
@@ -1143,47 +1024,37 @@ bool SystemTools::ReadRegistryValue(const std::string&, std::string &,
 
 #if defined(_WIN32) && !defined(__CYGWIN__)
 bool SystemTools::WriteRegistryValue(const std::string& key,
-                                     const std::string& value,
-                                     KeyWOW64 view)
+                                     const std::string& value, KeyWOW64 view)
 {
   HKEY primaryKey = HKEY_CURRENT_USER;
   std::string second;
   std::string valuename;
-  if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
-    {
+  if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename)) {
     return false;
-    }
+  }
 
   HKEY hKey;
   DWORD dwDummy;
   wchar_t lpClass[] = L"";
-  if(RegCreateKeyExW(primaryKey,
-                    Encoding::ToWide(second).c_str(),
-                    0,
-                    lpClass,
-                    REG_OPTION_NON_VOLATILE,
-                    SystemToolsMakeRegistryMode(KEY_WRITE, view),
-                    NULL,
-                    &hKey,
-                    &dwDummy) != ERROR_SUCCESS)
-    {
+  if (RegCreateKeyExW(primaryKey, Encoding::ToWide(second).c_str(), 0, lpClass,
+                      REG_OPTION_NON_VOLATILE,
+                      SystemToolsMakeRegistryMode(KEY_WRITE, view), NULL,
+                      &hKey, &dwDummy) != ERROR_SUCCESS) {
     return false;
-    }
+  }
 
   std::wstring wvalue = Encoding::ToWide(value);
-  if(RegSetValueExW(hKey,
-                   Encoding::ToWide(valuename).c_str(),
-                   0,
-                   REG_SZ,
-                   (CONST BYTE *)wvalue.c_str(),
-                   (DWORD)(sizeof(wchar_t) * (wvalue.size() + 1))) == ERROR_SUCCESS)
-    {
+  if (RegSetValueExW(hKey, Encoding::ToWide(valuename).c_str(), 0, REG_SZ,
+                     (CONST BYTE*)wvalue.c_str(),
+                     (DWORD)(sizeof(wchar_t) * (wvalue.size() + 1))) ==
+      ERROR_SUCCESS) {
     return true;
-    }
+  }
   return false;
 }
 #else
-bool SystemTools::WriteRegistryValue(const std::string&, const std::string&, KeyWOW64)
+bool SystemTools::WriteRegistryValue(const std::string&, const std::string&,
+                                     KeyWOW64)
 {
   return false;
 }
@@ -1202,29 +1073,21 @@ bool SystemTools::DeleteRegistryValue(const std::string& key, KeyWOW64 view)
   HKEY primaryKey = HKEY_CURRENT_USER;
   std::string second;
   std::string valuename;
-  if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename))
-    {
+  if (!SystemToolsParseRegistryKey(key, primaryKey, second, valuename)) {
     return false;
-    }
+  }
 
   HKEY hKey;
-  if(RegOpenKeyExW(primaryKey,
-                  Encoding::ToWide(second).c_str(),
-                  0,
-                  SystemToolsMakeRegistryMode(KEY_WRITE, view),
-                  &hKey) != ERROR_SUCCESS)
-    {
+  if (RegOpenKeyExW(primaryKey, Encoding::ToWide(second).c_str(), 0,
+                    SystemToolsMakeRegistryMode(KEY_WRITE, view),
+                    &hKey) != ERROR_SUCCESS) {
     return false;
-    }
-  else
-    {
-    if(RegDeleteValue(hKey,
-                      (LPTSTR)valuename.c_str()) == ERROR_SUCCESS)
-      {
+  } else {
+    if (RegDeleteValue(hKey, (LPTSTR)valuename.c_str()) == ERROR_SUCCESS) {
       RegCloseKey(hKey);
       return true;
-      }
     }
+  }
   return false;
 }
 #else
@@ -1239,58 +1102,45 @@ bool SystemTools::SameFile(const std::string& file1, const std::string& file2)
 #ifdef _WIN32
   HANDLE hFile1, hFile2;
 
-  hFile1 = CreateFileW( Encoding::ToWide(file1).c_str(),
-                      GENERIC_READ,
-                      FILE_SHARE_READ ,
-                      NULL,
-                      OPEN_EXISTING,
-                      FILE_FLAG_BACKUP_SEMANTICS,
-                      NULL
-    );
-  hFile2 = CreateFileW( Encoding::ToWide(file2).c_str(),
-                      GENERIC_READ,
-                      FILE_SHARE_READ,
-                      NULL,
-                      OPEN_EXISTING,
-                      FILE_FLAG_BACKUP_SEMANTICS,
-                      NULL
-    );
-  if( hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE)
-    {
-    if(hFile1 != INVALID_HANDLE_VALUE)
-      {
+  hFile1 =
+    CreateFileW(Encoding::ToWide(file1).c_str(), GENERIC_READ, FILE_SHARE_READ,
+                NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
+  hFile2 =
+    CreateFileW(Encoding::ToWide(file2).c_str(), GENERIC_READ, FILE_SHARE_READ,
+                NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
+  if (hFile1 == INVALID_HANDLE_VALUE || hFile2 == INVALID_HANDLE_VALUE) {
+    if (hFile1 != INVALID_HANDLE_VALUE) {
       CloseHandle(hFile1);
-      }
-    if(hFile2 != INVALID_HANDLE_VALUE)
-      {
+    }
+    if (hFile2 != INVALID_HANDLE_VALUE) {
       CloseHandle(hFile2);
-      }
-    return false;
     }
+    return false;
+  }
 
-   BY_HANDLE_FILE_INFORMATION fiBuf1;
-   BY_HANDLE_FILE_INFORMATION fiBuf2;
-   GetFileInformationByHandle( hFile1, &fiBuf1 );
-   GetFileInformationByHandle( hFile2, &fiBuf2 );
-   CloseHandle(hFile1);
-   CloseHandle(hFile2);
-   return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
-           fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
-           fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
+  BY_HANDLE_FILE_INFORMATION fiBuf1;
+  BY_HANDLE_FILE_INFORMATION fiBuf2;
+  GetFileInformationByHandle(hFile1, &fiBuf1);
+  GetFileInformationByHandle(hFile2, &fiBuf2);
+  CloseHandle(hFile1);
+  CloseHandle(hFile2);
+  return (fiBuf1.dwVolumeSerialNumber == fiBuf2.dwVolumeSerialNumber &&
+          fiBuf1.nFileIndexHigh == fiBuf2.nFileIndexHigh &&
+          fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
 #else
   struct stat fileStat1, fileStat2;
-  if (stat(file1.c_str(), &fileStat1) == 0 && stat(file2.c_str(), &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
-    if(memcmp(&fileStat2.st_dev, &fileStat1.st_dev, sizeof(fileStat1.st_dev)) == 0 &&
-       memcmp(&fileStat2.st_ino, &fileStat1.st_ino, sizeof(fileStat1.st_ino)) == 0 &&
-       fileStat2.st_size == fileStat1.st_size
-      )
-      {
+    if (memcmp(&fileStat2.st_dev, &fileStat1.st_dev,
+               sizeof(fileStat1.st_dev)) == 0 &&
+        memcmp(&fileStat2.st_ino, &fileStat1.st_ino,
+               sizeof(fileStat1.st_ino)) == 0 &&
+        fileStat2.st_size == fileStat1.st_size) {
       return true;
-      }
     }
+  }
   return false;
 #endif
 }
@@ -1298,23 +1148,21 @@ bool SystemTools::SameFile(const std::string& file1, const std::string& file2)
 //----------------------------------------------------------------------------
 bool SystemTools::PathExists(const std::string& path)
 {
-  if(path.empty())
-    {
+  if (path.empty()) {
     return false;
-    }
+  }
 #if defined(__CYGWIN__)
   // Convert path to native windows path if possible.
   char winpath[MAX_PATH];
-  if(SystemTools::PathCygwinToWin32(path.c_str(), winpath))
-    {
+  if (SystemTools::PathCygwinToWin32(path.c_str(), winpath)) {
     return (GetFileAttributesA(winpath) != INVALID_FILE_ATTRIBUTES);
-    }
+  }
   struct stat st;
   return lstat(path.c_str(), &st) == 0;
 #elif defined(_WIN32)
   return (GetFileAttributesW(
-            SystemTools::ConvertToWindowsExtendedPath(path).c_str())
-          != INVALID_FILE_ATTRIBUTES);
+            SystemTools::ConvertToWindowsExtendedPath(path).c_str()) !=
+          INVALID_FILE_ATTRIBUTES);
 #else
   struct stat st;
   return lstat(path.c_str(), &st) == 0;
@@ -1324,32 +1172,29 @@ bool SystemTools::PathExists(const std::string& path)
 //----------------------------------------------------------------------------
 bool SystemTools::FileExists(const char* filename)
 {
-  if(!filename)
-    {
+  if (!filename) {
     return false;
-    }
+  }
   return SystemTools::FileExists(std::string(filename));
 }
 
 //----------------------------------------------------------------------------
 bool SystemTools::FileExists(const std::string& filename)
 {
-  if(filename.empty())
-    {
+  if (filename.empty()) {
     return false;
-    }
+  }
 #if defined(__CYGWIN__)
   // Convert filename to native windows path if possible.
   char winpath[MAX_PATH];
-  if(SystemTools::PathCygwinToWin32(filename.c_str(), winpath))
-    {
+  if (SystemTools::PathCygwinToWin32(filename.c_str(), winpath)) {
     return (GetFileAttributesA(winpath) != INVALID_FILE_ATTRIBUTES);
-    }
+  }
   return access(filename.c_str(), R_OK) == 0;
 #elif defined(_WIN32)
   return (GetFileAttributesW(
-            SystemTools::ConvertToWindowsExtendedPath(filename).c_str())
-          != INVALID_FILE_ATTRIBUTES);
+            SystemTools::ConvertToWindowsExtendedPath(filename).c_str()) !=
+          INVALID_FILE_ATTRIBUTES);
 #else
 // SCO OpenServer 5.0.7/3.2's command has 711 permission.
 #if defined(_SCO_DS)
@@ -1363,22 +1208,20 @@ bool SystemTools::FileExists(const std::string& filename)
 //----------------------------------------------------------------------------
 bool SystemTools::FileExists(const char* filename, bool isFile)
 {
-  if(!filename)
-    {
+  if (!filename) {
     return false;
-    }
+  }
   return SystemTools::FileExists(std::string(filename), isFile);
 }
 
 //----------------------------------------------------------------------------
 bool SystemTools::FileExists(const std::string& filename, bool isFile)
 {
-  if(SystemTools::FileExists(filename))
-    {
+  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;
 }
 
@@ -1386,34 +1229,29 @@ bool SystemTools::FileExists(const std::string& filename, bool isFile)
 bool SystemTools::TestFileAccess(const char* filename,
                                  TestFilePermissions permissions)
 {
-  if(!filename)
-    {
+  if (!filename) {
     return false;
-    }
-  return SystemTools::TestFileAccess(std::string(filename),
-                                     permissions);
+  }
+  return SystemTools::TestFileAccess(std::string(filename), permissions);
 }
 
 //----------------------------------------------------------------------------
 bool SystemTools::TestFileAccess(const std::string& filename,
                                  TestFilePermissions permissions)
 {
-  if(filename.empty())
-    {
+  if (filename.empty()) {
     return false;
-    }
+  }
 #if defined(_WIN32) && !defined(__CYGWIN__)
   // If execute set, change to read permission (all files on Windows
   // are executable if they are readable).  The CRT will always fail
   // if you pass an execute bit.
-  if(permissions & TEST_FILE_EXECUTE)
-    {
+  if (permissions & TEST_FILE_EXECUTE) {
     permissions &= ~TEST_FILE_EXECUTE;
     permissions |= TEST_FILE_READ;
-    }
-  return _waccess(
-    SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
-    permissions) == 0;
+  }
+  return _waccess(SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
+                  permissions) == 0;
 #else
   return access(filename.c_str(), permissions) == 0;
 #endif
@@ -1421,109 +1259,93 @@ bool SystemTools::TestFileAccess(const std::string& filename,
 
 //----------------------------------------------------------------------------
 #ifdef __CYGWIN__
-bool SystemTools::PathCygwinToWin32(const char *path, char *win32_path)
+bool SystemTools::PathCygwinToWin32(const char* path, char* win32_path)
 {
   SystemToolsTranslationMap::iterator i =
     SystemTools::Cyg2Win32Map->find(path);
 
-  if (i != SystemTools::Cyg2Win32Map->end())
-    {
+  if (i != SystemTools::Cyg2Win32Map->end()) {
     strncpy(win32_path, i->second.c_str(), MAX_PATH);
-    }
-  else
-    {
-    if(cygwin_conv_path(CCP_POSIX_TO_WIN_A, path, win32_path, MAX_PATH) != 0)
-      {
+  } else {
+    if (cygwin_conv_path(CCP_POSIX_TO_WIN_A, path, win32_path, MAX_PATH) !=
+        0) {
       win32_path[0] = 0;
-      }
+    }
     SystemToolsTranslationMap::value_type entry(path, win32_path);
     SystemTools::Cyg2Win32Map->insert(entry);
-    }
+  }
   return win32_path[0] != 0;
 }
 #endif
 
 bool SystemTools::Touch(const std::string& filename, bool create)
 {
-  if (!SystemTools::FileExists(filename))
-    {
-    if(create)
-      {
+  if (!SystemTools::PathExists(filename)) {
+    if (create) {
       FILE* file = Fopen(filename, "a+b");
-      if(file)
-        {
+      if (file) {
         fclose(file);
         return true;
-        }
-      return false;
       }
-    else
-      {
+      return false;
+    } else {
       return true;
-      }
     }
+  }
 #if defined(_WIN32) && !defined(__CYGWIN__)
-  HANDLE h = CreateFileW(
-    SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
-    FILE_WRITE_ATTRIBUTES,
-    FILE_SHARE_WRITE, 0, OPEN_EXISTING,
-    FILE_FLAG_BACKUP_SEMANTICS, 0);
-  if(!h)
-    {
+  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;
-    }
+  }
   FILETIME mtime;
   GetSystemTimeAsFileTime(&mtime);
-  if(!SetFileTime(h, 0, 0, &mtime))
-    {
+  if (!SetFileTime(h, 0, 0, &mtime)) {
     CloseHandle(h);
     return false;
-    }
+  }
   CloseHandle(h);
 #elif KWSYS_CXX_HAS_UTIMENSAT
-  struct timespec times[2] = {{0,UTIME_OMIT},{0,UTIME_NOW}};
-  if(utimensat(AT_FDCWD, filename.c_str(), times, 0) < 0)
-    {
+  struct timespec times[2] = { { 0, UTIME_OMIT }, { 0, UTIME_NOW } };
+  if (utimensat(AT_FDCWD, filename.c_str(), times, 0) < 0) {
     return false;
-    }
+  }
 #else
   struct stat st;
-  if(stat(filename.c_str(), &st) < 0)
-    {
+  if (stat(filename.c_str(), &st) < 0) {
     return false;
-    }
+  }
   struct timeval mtime;
   gettimeofday(&mtime, 0);
-# if KWSYS_CXX_HAS_UTIMES
+#if KWSYS_CXX_HAS_UTIMES
   struct timeval atime;
-#  if KWSYS_CXX_STAT_HAS_ST_MTIM
+#if KWSYS_CXX_STAT_HAS_ST_MTIM
   atime.tv_sec = st.st_atim.tv_sec;
-  atime.tv_usec = st.st_atim.tv_nsec/1000;
-#  elif KWSYS_CXX_STAT_HAS_ST_MTIMESPEC
+  atime.tv_usec = st.st_atim.tv_nsec / 1000;
+#elif KWSYS_CXX_STAT_HAS_ST_MTIMESPEC
   atime.tv_sec = st.st_atimespec.tv_sec;
-  atime.tv_usec = st.st_atimespec.tv_nsec/1000;
-#  else
+  atime.tv_usec = st.st_atimespec.tv_nsec / 1000;
+#else
   atime.tv_sec = st.st_atime;
   atime.tv_usec = 0;
-#  endif
+#endif
   struct timeval times[2] = { atime, mtime };
-  if(utimes(filename.c_str(), times) < 0)
-    {
+  if (utimes(filename.c_str(), times) < 0) {
     return false;
-    }
-# else
-  struct utimbuf times = {st.st_atime, mtime.tv_sec};
-  if(utime(filename.c_str(), &times) < 0)
-    {
+  }
+#else
+  struct utimbuf times = { st.st_atime, mtime.tv_sec };
+  if (utime(filename.c_str(), &times) < 0) {
     return false;
-    }
-# endif
+  }
+#endif
 #endif
   return true;
 }
 
-bool SystemTools::FileTimeCompare(const std::string& f1,
-                                  const std::string& f2,
+bool SystemTools::FileTimeCompare(const std::string& f1, const std::string& f2,
                                   int* result)
 {
   // Default to same time.
@@ -1531,78 +1353,57 @@ bool SystemTools::FileTimeCompare(const std::string& f1,
 #if !defined(_WIN32) || defined(__CYGWIN__)
   // POSIX version.  Use stat function to get file modification time.
   struct stat s1;
-  if(stat(f1.c_str(), &s1) != 0)
-    {
+  if (stat(f1.c_str(), &s1) != 0) {
     return false;
-    }
+  }
   struct stat s2;
-  if(stat(f2.c_str(), &s2) != 0)
-    {
+  if (stat(f2.c_str(), &s2) != 0) {
     return false;
-    }
-# if KWSYS_CXX_STAT_HAS_ST_MTIM
+  }
+#if KWSYS_CXX_STAT_HAS_ST_MTIM
   // Compare using nanosecond resolution.
-  if(s1.st_mtim.tv_sec < s2.st_mtim.tv_sec)
-    {
+  if (s1.st_mtim.tv_sec < s2.st_mtim.tv_sec) {
     *result = -1;
-    }
-  else if(s1.st_mtim.tv_sec > s2.st_mtim.tv_sec)
-    {
+  } else if (s1.st_mtim.tv_sec > s2.st_mtim.tv_sec) {
     *result = 1;
-    }
-  else if(s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec)
-    {
+  } else if (s1.st_mtim.tv_nsec < s2.st_mtim.tv_nsec) {
     *result = -1;
-    }
-  else if(s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec)
-    {
+  } else if (s1.st_mtim.tv_nsec > s2.st_mtim.tv_nsec) {
     *result = 1;
-    }
-# elif KWSYS_CXX_STAT_HAS_ST_MTIMESPEC
+  }
+#elif KWSYS_CXX_STAT_HAS_ST_MTIMESPEC
   // Compare using nanosecond resolution.
-  if(s1.st_mtimespec.tv_sec < s2.st_mtimespec.tv_sec)
-    {
+  if (s1.st_mtimespec.tv_sec < s2.st_mtimespec.tv_sec) {
     *result = -1;
-    }
-  else if(s1.st_mtimespec.tv_sec > s2.st_mtimespec.tv_sec)
-    {
+  } else if (s1.st_mtimespec.tv_sec > s2.st_mtimespec.tv_sec) {
     *result = 1;
-    }
-  else if(s1.st_mtimespec.tv_nsec < s2.st_mtimespec.tv_nsec)
-    {
+  } else if (s1.st_mtimespec.tv_nsec < s2.st_mtimespec.tv_nsec) {
     *result = -1;
-    }
-  else if(s1.st_mtimespec.tv_nsec > s2.st_mtimespec.tv_nsec)
-    {
+  } else if (s1.st_mtimespec.tv_nsec > s2.st_mtimespec.tv_nsec) {
     *result = 1;
-    }
-# else
+  }
+#else
   // Compare using 1 second resolution.
-  if(s1.st_mtime < s2.st_mtime)
-    {
+  if (s1.st_mtime < s2.st_mtime) {
     *result = -1;
-    }
-  else if(s1.st_mtime > s2.st_mtime)
-    {
+  } else if (s1.st_mtime > s2.st_mtime) {
     *result = 1;
-    }
-# endif
+  }
+#endif
 #else
   // Windows version.  Get the modification time from extended file attributes.
   WIN32_FILE_ATTRIBUTE_DATA f1d;
   WIN32_FILE_ATTRIBUTE_DATA f2d;
-  if(!GetFileAttributesExW(
-       SystemTools::ConvertToWindowsExtendedPath(f1).c_str(),
-       GetFileExInfoStandard, &f1d))
-    {
+  if (!GetFileAttributesExW(
+        SystemTools::ConvertToWindowsExtendedPath(f1).c_str(),
+        GetFileExInfoStandard, &f1d)) {
     return false;
-    }
-  if(!GetFileAttributesExW(
-       SystemTools::ConvertToWindowsExtendedPath(f2).c_str(),
-       GetFileExInfoStandard, &f2d))
-    {
+  }
+  if (!GetFileAttributesExW(
+        SystemTools::ConvertToWindowsExtendedPath(f2).c_str(),
+        GetFileExInfoStandard, &f2d)) {
     return false;
-    }
+  }
 
   // Compare the file times using resolution provided by system call.
   *result = (int)CompareFileTime(&f1d.ftLastWriteTime, &f2d.ftLastWriteTime);
@@ -1610,22 +1411,19 @@ bool SystemTools::FileTimeCompare(const std::string& f1,
   return true;
 }
 
-
 // Return a capitalized string (i.e the first letter is uppercased, all other
 // are lowercased)
 std::string SystemTools::Capitalized(const std::string& s)
 {
   std::string n;
-  if(s.empty())
-    {
+  if (s.empty()) {
     return n;
-    }
+  }
   n.resize(s.size());
   n[0] = static_cast<std::string::value_type>(toupper(s[0]));
-  for (size_t i = 1; i < s.size(); i++)
-    {
+  for (size_t i = 1; i < s.size(); i++) {
     n[i] = static_cast<std::string::value_type>(tolower(s[i]));
-    }
+  }
   return n;
 }
 
@@ -1633,9 +1431,8 @@ std::string SystemTools::Capitalized(const std::string& s)
 std::string SystemTools::CapitalizedWords(const std::string& s)
 {
   std::string n(s);
-  for (size_t i = 0; i < s.size(); i++)
-    {
-#if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
+  for (size_t i = 0; i < s.size(); i++) {
+#if defined(_MSC_VER) && defined(_MT) && defined(_DEBUG)
     // MS has an assert that will fail if s[i] < 0; setting
     // LC_CTYPE using setlocale() does *not* help. Painful.
     if ((int)s[i] >= 0 && isalpha(s[i]) &&
@@ -1643,10 +1440,10 @@ std::string SystemTools::CapitalizedWords(const std::string& s)
 #else
     if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
 #endif
-      {
+    {
       n[i] = static_cast<std::string::value_type>(toupper(s[i]));
-      }
     }
+  }
   return n;
 }
 
@@ -1654,9 +1451,8 @@ std::string SystemTools::CapitalizedWords(const std::string& s)
 std::string SystemTools::UnCapitalizedWords(const std::string& s)
 {
   std::string n(s);
-  for (size_t i = 0; i < s.size(); i++)
-    {
-#if defined(_MSC_VER) && defined (_MT) && defined (_DEBUG)
+  for (size_t i = 0; i < s.size(); i++) {
+#if defined(_MSC_VER) && defined(_MT) && defined(_DEBUG)
     // MS has an assert that will fail if s[i] < 0; setting
     // LC_CTYPE using setlocale() does *not* help. Painful.
     if ((int)s[i] >= 0 && isalpha(s[i]) &&
@@ -1664,77 +1460,66 @@ std::string SystemTools::UnCapitalizedWords(const std::string& s)
 #else
     if (isalpha(s[i]) && (i == 0 || isspace(s[i - 1])))
 #endif
-      {
+    {
       n[i] = static_cast<std::string::value_type>(tolower(s[i]));
-      }
     }
+  }
   return n;
 }
 
 // only works for words with at least two letters
-std::string SystemTools::AddSpaceBetweenCapitalizedWords(
-  const std::string& s)
+std::string SystemTools::AddSpaceBetweenCapitalizedWords(const std::string& s)
 {
   std::string n;
-  if (!s.empty())
-    {
+  if (!s.empty()) {
     n.reserve(s.size());
     n += s[0];
-    for (size_t i = 1; i < s.size(); i++)
-      {
-      if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1]))
-        {
+    for (size_t i = 1; i < s.size(); i++) {
+      if (isupper(s[i]) && !isspace(s[i - 1]) && !isupper(s[i - 1])) {
         n += ' ';
-        }
-      n += s[i];
       }
+      n += s[i];
     }
+  }
   return n;
 }
 
 char* SystemTools::AppendStrings(const char* str1, const char* str2)
 {
-  if (!str1)
-    {
+  if (!str1) {
     return SystemTools::DuplicateString(str2);
-    }
-  if (!str2)
-    {
+  }
+  if (!str2) {
     return SystemTools::DuplicateString(str1);
-    }
+  }
   size_t len1 = strlen(str1);
-  char *newstr = new char[len1 + strlen(str2) + 1];
-  if (!newstr)
-    {
+  char* newstr = new char[len1 + strlen(str2) + 1];
+  if (!newstr) {
     return 0;
-    }
+  }
   strcpy(newstr, str1);
   strcat(newstr + len1, str2);
   return newstr;
 }
 
-char* SystemTools::AppendStrings(
-  const char* str1, const char* str2, const char* str3)
+char* SystemTools::AppendStrings(const char* str1, const char* str2,
+                                 const char* str3)
 {
-  if (!str1)
-    {
+  if (!str1) {
     return SystemTools::AppendStrings(str2, str3);
-    }
-  if (!str2)
-    {
+  }
+  if (!str2) {
     return SystemTools::AppendStrings(str1, str3);
-    }
-  if (!str3)
-    {
+  }
+  if (!str3) {
     return SystemTools::AppendStrings(str1, str2);
-    }
+  }
 
   size_t len1 = strlen(str1), len2 = strlen(str2);
-  char *newstr = new char[len1 + len2 + strlen(str3) + 1];
-  if (!newstr)
-    {
+  char* newstr = new char[len1 + len2 + strlen(str3) + 1];
+  if (!newstr) {
     return 0;
-    }
+  }
   strcpy(newstr, str1);
   strcat(newstr + len1, str2);
   strcat(newstr + len1 + len2, str3);
@@ -1746,10 +1531,9 @@ std::string SystemTools::LowerCase(const std::string& s)
 {
   std::string n;
   n.resize(s.size());
-  for (size_t i = 0; i < s.size(); i++)
-    {
+  for (size_t i = 0; i < s.size(); i++) {
     n[i] = static_cast<std::string::value_type>(tolower(s[i]));
-    }
+  }
   return n;
 }
 
@@ -1758,10 +1542,9 @@ std::string SystemTools::UpperCase(const std::string& s)
 {
   std::string n;
   n.resize(s.size());
-  for (size_t i = 0; i < s.size(); i++)
-    {
+  for (size_t i = 0; i < s.size(); i++) {
     n[i] = static_cast<std::string::value_type>(toupper(s[i]));
-    }
+  }
   return n;
 }
 
@@ -1770,42 +1553,35 @@ size_t SystemTools::CountChar(const char* str, char c)
 {
   size_t count = 0;
 
-  if (str)
-    {
-    while (*str)
-      {
-      if (*str == c)
-        {
+  if (str) {
+    while (*str) {
+      if (*str == c) {
         ++count;
-        }
-      ++str;
       }
+      ++str;
     }
+  }
   return count;
 }
 
 // Remove chars in string
-char* SystemTools::RemoveChars(const char* str, const char *toremove)
+char* SystemTools::RemoveChars(const char* str, const char* toremove)
 {
-  if (!str)
-    {
+  if (!str) {
     return NULL;
-    }
-  char *clean_str = new char [strlen(str) + 1];
-  char *ptr = clean_str;
-  while (*str)
-    {
-    const char *str2 = toremove;
-    while (*str2 && *str != *str2)
-      {
+  }
+  char* clean_str = new char[strlen(str) + 1];
+  char* ptr = clean_str;
+  while (*str) {
+    const char* str2 = toremove;
+    while (*str2 && *str != *str2) {
       ++str2;
-      }
-    if (!*str2)
-      {
+    }
+    if (!*str2) {
       *ptr++ = *str;
-      }
-    ++str;
     }
+    ++str;
+  }
   *ptr = '\0';
   return clean_str;
 }
@@ -1813,54 +1589,47 @@ char* SystemTools::RemoveChars(const char* str, const char *toremove)
 // Remove chars in string
 char* SystemTools::RemoveCharsButUpperHex(const char* str)
 {
-  if (!str)
-    {
+  if (!str) {
     return 0;
-    }
-  char *clean_str = new char [strlen(str) + 1];
-  char *ptr = clean_str;
-  while (*str)
-    {
-    if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'F'))
-      {
+  }
+  char* clean_str = new char[strlen(str) + 1];
+  char* ptr = clean_str;
+  while (*str) {
+    if ((*str >= '0' && *str <= '9') || (*str >= 'A' && *str <= 'F')) {
       *ptr++ = *str;
-      }
-    ++str;
     }
+    ++str;
+  }
   *ptr = '\0';
   return clean_str;
 }
 
 // Replace chars in string
-char* SystemTools::ReplaceChars(char* str, const char *toreplace, char replacement)
-{
-  if (str)
-    {
-    char *ptr = str;
-    while (*ptr)
-      {
-      const char *ptr2 = toreplace;
-      while (*ptr2)
-        {
-        if (*ptr == *ptr2)
-          {
+char* SystemTools::ReplaceChars(char* str, const char* toreplace,
+                                char replacement)
+{
+  if (str) {
+    char* ptr = str;
+    while (*ptr) {
+      const char* ptr2 = toreplace;
+      while (*ptr2) {
+        if (*ptr == *ptr2) {
           *ptr = replacement;
-          }
-        ++ptr2;
         }
-      ++ptr;
+        ++ptr2;
       }
+      ++ptr;
     }
+  }
   return str;
 }
 
 // Returns if string starts with another string
 bool SystemTools::StringStartsWith(const char* str1, const char* str2)
 {
-  if (!str1 || !str2)
-    {
+  if (!str1 || !str2) {
     return false;
-    }
+  }
   size_t len1 = strlen(str1), len2 = strlen(str2);
   return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
 }
@@ -1868,10 +1637,9 @@ bool SystemTools::StringStartsWith(const char* str1, const char* str2)
 // Returns if string starts with another string
 bool SystemTools::StringStartsWith(const std::string& str1, const char* str2)
 {
-  if (!str2)
-    {
+  if (!str2) {
     return false;
-    }
+  }
   size_t len1 = str1.size(), len2 = strlen(str2);
   return len1 >= len2 && !strncmp(str1.c_str(), str2, len2) ? true : false;
 }
@@ -1879,45 +1647,42 @@ bool SystemTools::StringStartsWith(const std::string& str1, const char* str2)
 // Returns if string ends with another string
 bool SystemTools::StringEndsWith(const char* str1, const char* str2)
 {
-  if (!str1 || !str2)
-    {
+  if (!str1 || !str2) {
     return false;
-    }
+  }
   size_t len1 = strlen(str1), len2 = strlen(str2);
-  return len1 >= len2 &&  !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
+  return len1 >= len2 && !strncmp(str1 + (len1 - len2), str2, len2) ? true
+                                                                    : false;
 }
 
 // Returns if string ends with another string
 bool SystemTools::StringEndsWith(const std::string& str1, const char* str2)
 {
-  if (!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;
+  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)
 {
-  if (!str1 || !str2)
-    {
+  if (!str1 || !str2) {
     return NULL;
-    }
+  }
 
   size_t len1 = strlen(str1), len2 = strlen(str2);
-  if (len1 >= len2)
-    {
-    const char *ptr = str1 + len1 - len2;
-    do
-      {
-      if (!strncmp(ptr, str2, len2))
-        {
+  if (len1 >= len2) {
+    const char* ptr = str1 + len1 - len2;
+    do {
+      if (!strncmp(ptr, str2, len2)) {
         return ptr;
-        }
-      } while (ptr-- != str1);
-    }
+      }
+    } while (ptr-- != str1);
+  }
 
   return NULL;
 }
@@ -1925,22 +1690,19 @@ const char* SystemTools::FindLastString(const char* str1, const char* str2)
 // Duplicate string
 char* SystemTools::DuplicateString(const char* str)
 {
-  if (str)
-    {
-    char *newstr = new char [strlen(str) + 1];
+  if (str) {
+    char* newstr = new char[strlen(str) + 1];
     return strcpy(newstr, str);
-    }
+  }
   return NULL;
 }
 
 // Return a cropped string
-std::string SystemTools::CropString(const std::string& s,
-                                          size_t max_len)
+std::string SystemTools::CropString(const std::string& s, size_t max_len)
 {
-  if (!s.size() || max_len == 0 || max_len >= s.size())
-    {
+  if (!s.size() || max_len == 0 || max_len >= s.size()) {
     return s;
-    }
+  }
 
   std::string n;
   n.reserve(max_len);
@@ -1950,56 +1712,50 @@ std::string SystemTools::CropString(const std::string& s,
   n += s.substr(0, middle);
   n += s.substr(s.size() - (max_len - middle), std::string::npos);
 
-  if (max_len > 2)
-    {
+  if (max_len > 2) {
     n[middle] = '.';
-    if (max_len > 3)
-      {
+    if (max_len > 3) {
       n[middle - 1] = '.';
-      if (max_len > 4)
-        {
+      if (max_len > 4) {
         n[middle + 1] = '.';
-        }
       }
     }
+  }
 
   return n;
 }
 
 //----------------------------------------------------------------------------
-std::vector<kwsys::String> SystemTools::SplitString(const std::string& p, char sep, bool isPath)
+std::vector<kwsys::String> SystemTools::SplitString(const std::string& p,
+                                                    char sep, bool isPath)
 {
   std::string path = p;
   std::vector<kwsys::String> paths;
-  if(path.empty())
-    {
+  if (path.empty()) {
     return paths;
-    }
-  if(isPath && path[0] == '/')
-    {
+  }
+  if (isPath && path[0] == '/') {
     path.erase(path.begin());
     paths.push_back("/");
-    }
+  }
   std::string::size_type pos1 = 0;
-  std::string::size_type pos2 = path.find(sep, pos1+1);
-  while(pos2 != std::string::npos)
-    {
-    paths.push_back(path.substr(pos1, pos2-pos1));
-    pos1 = pos2+1;
-    pos2 = path.find(sep, pos1+1);
-    }
-  paths.push_back(path.substr(pos1, pos2-pos1));
+  std::string::size_type pos2 = path.find(sep, pos1 + 1);
+  while (pos2 != std::string::npos) {
+    paths.push_back(path.substr(pos1, pos2 - pos1));
+    pos1 = pos2 + 1;
+    pos2 = path.find(sep, pos1 + 1);
+  }
+  paths.push_back(path.substr(pos1, pos2 - pos1));
 
   return paths;
 }
 
 //----------------------------------------------------------------------------
-int SystemTools::EstimateFormatLength(const char *format, va_list ap)
+int SystemTools::EstimateFormatLength(const char* format, va_list ap)
 {
-  if (!format)
-    {
+  if (!format) {
     return 0;
-    }
+  }
 
   // Quick-hack attempt at estimating the length of the string.
   // Should never under-estimate.
@@ -2011,89 +1767,72 @@ int SystemTools::EstimateFormatLength(const char *format, va_list ap)
   // Increase the length for every argument in the format.
 
   const char* cur = format;
-  while(*cur)
-    {
-    if(*cur++ == '%')
-      {
+  while (*cur) {
+    if (*cur++ == '%') {
       // Skip "%%" since it doesn't correspond to a va_arg.
-      if(*cur != '%')
-        {
-        while(!int(isalpha(*cur)))
-          {
+      if (*cur != '%') {
+        while (!int(isalpha(*cur))) {
           ++cur;
-          }
-        switch (*cur)
-          {
-          case 's':
-          {
-          // Check the length of the string.
-          char* s = va_arg(ap, char*);
-          if(s)
-            {
-            length += strlen(s);
+        }
+        switch (*cur) {
+          case 's': {
+            // Check the length of the string.
+            char* s = va_arg(ap, char*);
+            if (s) {
+              length += strlen(s);
             }
           } break;
           case 'e':
           case 'f':
-          case 'g':
-          {
-          // Assume the argument contributes no more than 64 characters.
-          length += 64;
+          case 'g': {
+            // Assume the argument contributes no more than 64 characters.
+            length += 64;
 
-          // Eat the argument.
-          static_cast<void>(va_arg(ap, double));
+            // Eat the argument.
+            static_cast<void>(va_arg(ap, double));
           } break;
-          default:
-          {
-          // Assume the argument contributes no more than 64 characters.
-          length += 64;
+          default: {
+            // Assume the argument contributes no more than 64 characters.
+            length += 64;
 
-          // Eat the argument.
-          static_cast<void>(va_arg(ap, int));
+            // Eat the argument.
+            static_cast<void>(va_arg(ap, int));
           } break;
-          }
         }
+      }
 
       // Move past the characters just tested.
       ++cur;
-      }
     }
+  }
 
   return static_cast<int>(length);
 }
 
-std::string SystemTools::EscapeChars(
-  const char *str,
-  const char *chars_to_escape,
-  char escape_char)
+std::string SystemTools::EscapeChars(const char* str,
+                                     const char* chars_to_escape,
+                                     char escape_char)
 {
   std::string n;
-  if (str)
-    {
-    if (!chars_to_escape || !*chars_to_escape)
-      {
+  if (str) {
+    if (!chars_to_escape || !*chars_to_escape) {
       n.append(str);
-      }
-    else
-      {
+    } else {
       n.reserve(strlen(str));
-      while (*str)
-        {
-        const char *ptr = chars_to_escape;
-        while (*ptr)
-          {
-          if (*str == *ptr)
-            {
+      while (*str) {
+        const char* ptr = chars_to_escape;
+        while (*ptr) {
+          if (*str == *ptr) {
             n += escape_char;
             break;
-            }
-          ++ptr;
           }
+          ++ptr;
+        }
         n += *str;
         ++str;
-        }
       }
     }
+  }
   return n;
 }
 
@@ -2102,22 +1841,19 @@ static void ConvertVMSToUnix(std::string& path)
 {
   std::string::size_type rootEnd = path.find(":[");
   std::string::size_type pathEnd = path.find("]");
-  if(rootEnd != path.npos)
-    {
+  if (rootEnd != path.npos) {
     std::string root = path.substr(0, rootEnd);
-    std::string pathPart = path.substr(rootEnd+2, pathEnd - rootEnd-2);
+    std::string pathPart = path.substr(rootEnd + 2, pathEnd - rootEnd - 2);
     const char* pathCString = pathPart.c_str();
     const char* pos0 = pathCString;
-    for (std::string::size_type pos = 0; *pos0; ++ pos )
-      {
-      if ( *pos0 == '.' )
-        {
+    for (std::string::size_type pos = 0; *pos0; ++pos) {
+      if (*pos0 == '.') {
         pathPart[pos] = '/';
-        }
-      pos0 ++;
       }
-    path = "/"+ root + "/" + pathPart;
+      pos0++;
     }
+    path = "/" + root + "/" + pathPart;
+  }
 }
 #endif
 
@@ -2130,83 +1866,72 @@ void SystemTools::ConvertToUnixSlashes(std::string& path)
   ConvertVMSToUnix(path);
 #else
   const char* pos0 = pathCString;
-  const char* pos1 = pathCString+1;
-  for (std::string::size_type pos = 0; *pos0; ++ pos )
-    {
+  const char* pos1 = pathCString + 1;
+  for (std::string::size_type pos = 0; *pos0; ++pos) {
     // make sure we don't convert an escaped space to a unix slash
-    if ( *pos0 == '\\' && *pos1 != ' ' )
-      {
+    if (*pos0 == '\\' && *pos1 != ' ') {
       path[pos] = '/';
-      }
+    }
 
     // Also, reuse the loop to check for slash followed by another slash
-    if (*pos1 == '/' && *(pos1+1) == '/' && !hasDoubleSlash)
-      {
+    if (*pos1 == '/' && *(pos1 + 1) == '/' && !hasDoubleSlash) {
 #ifdef _WIN32
       // However, on windows if the first characters are both slashes,
       // then keep them that way, so that network paths can be handled.
-      if ( pos > 0)
-        {
+      if (pos > 0) {
         hasDoubleSlash = true;
-        }
+      }
 #else
       hasDoubleSlash = true;
 #endif
-      }
-
-    pos0 ++;
-    pos1 ++;
     }
 
-  if ( hasDoubleSlash )
-    {
+    pos0++;
+    pos1++;
+  }
+
+  if (hasDoubleSlash) {
     SystemTools::ReplaceString(path, "//", "/");
-    }
+  }
 #endif
   // remove any trailing slash
-  if(!path.empty())
-    {
+  if (!path.empty()) {
     // if there is a tilda ~ then replace it with HOME
     pathCString = path.c_str();
-    if(pathCString[0] == '~' && (pathCString[1] == '/' || pathCString[1] == '\0'))
-      {
+    if (pathCString[0] == '~' &&
+        (pathCString[1] == '/' || pathCString[1] == '\0')) {
       std::string homeEnv;
-      if (SystemTools::GetEnv("HOME", homeEnv))
-        {
-        path.replace(0,1,homeEnv);
-        }
+      if (SystemTools::GetEnv("HOME", homeEnv)) {
+        path.replace(0, 1, homeEnv);
       }
+    }
 #ifdef HAVE_GETPWNAM
-    else if(pathCString[0] == '~')
-      {
+    else if (pathCString[0] == '~') {
       std::string::size_type idx = path.find_first_of("/\0");
-      std::string user = path.substr(1, idx-1);
+      std::string user = path.substr(1, idx - 1);
       passwd* pw = getpwnam(user.c_str());
-      if(pw)
-        {
+      if (pw) {
         path.replace(0, idx, pw->pw_dir);
-        }
       }
+    }
 #endif
     // remove trailing slash if the path is more than
     // a single /
     pathCString = path.c_str();
     size_t size = path.size();
-    if(size > 1 && *path.rbegin() == '/')
-      {
+    if (size > 1 && *path.rbegin() == '/') {
       // if it is c:/ then do not remove the trailing slash
-      if(!((size == 3 && pathCString[1] == ':')))
-        {
+      if (!((size == 3 && pathCString[1] == ':'))) {
         path.resize(size - 1);
-        }
       }
     }
+  }
 }
 
 #ifdef _WIN32
 // Convert local paths to UNC style paths
-std::wstring
-SystemTools::ConvertToWindowsExtendedPath(const std::string &source)
+std::wstring SystemTools::ConvertToWindowsExtendedPath(
+  const std::string& source)
 {
   std::wstring wsource = Encoding::ToWide(source);
 
@@ -2223,44 +1948,36 @@ SystemTools::ConvertToWindowsExtendedPath(const std::string &source)
    * 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 */
+  if (wfull_len >= 2 && isalpha(wfull[0]) &&
+      wfull[1] == L':') { /* C:\Foo\bar\FooBar.txt */
     return L"\\\\?\\" + std::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 */
+  } 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 std::wstring(&wfull[0]);
-        }
-      else if(wfull_len >= 6 && isalpha(wfull[4]) && wfull[5] == L':')
-        { /* \\?\C:\Foo\bar\FooBar.txt */
+      } else if (wfull_len >= 6 && isalpha(wfull[4]) &&
+                 wfull[5] == L':') { /* \\?\C:\Foo\bar\FooBar.txt */
         return std::wstring(&wfull[0]);
-        }
-      else if(wfull_len >= 5)
-        { /* \\?\Foo\bar\FooBar.txt */
+      } else if (wfull_len >= 5) { /* \\?\Foo\bar\FooBar.txt */
         return L"\\\\?\\UNC\\" + std::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 */
+    } 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"\\\\?\\" + std::wstring(&wfull[4]);
-        }
-      else if(wfull_len >= 5)
-        { /* \\.\Foo\bar\ Device name is left unchanged */
+      } else if (wfull_len >=
+                 5) { /* \\.\Foo\bar\ Device name is left unchanged */
         return std::wstring(&wfull[0]);
-        }
       }
-    else if(wfull_len >= 3)
-      { /* \\Foo\bar\FooBar.txt */
+    } else if (wfull_len >= 3) { /* \\Foo\bar\FooBar.txt */
       return L"\\\\?\\UNC\\" + std::wstring(&wfull[2]);
-      }
     }
+  }
 
   // If this case has been reached, then the path is invalid.  Leave it
   // unchanged
@@ -2274,28 +1991,24 @@ std::string SystemTools::ConvertToUnixOutputPath(const std::string& path)
   std::string ret = path;
 
   // remove // except at the beginning might be a cygwin drive
-  std::string::size_type pos=1;
-  while((pos = ret.find("//", pos)) != std::string::npos)
-    {
+  std::string::size_type pos = 1;
+  while ((pos = ret.find("//", pos)) != std::string::npos) {
     ret.erase(pos, 1);
-    }
+  }
   // escape spaces and () in the path
-  if(ret.find_first_of(" ") != std::string::npos)
-    {
+  if (ret.find_first_of(" ") != std::string::npos) {
     std::string result = "";
     char lastch = 1;
-    for(const char* ch = ret.c_str(); *ch != '\0'; ++ch)
-      {
-        // if it is already escaped then don't try to escape it again
-      if((*ch == ' ') && lastch != '\\')
-        {
+    for (const char* ch = ret.c_str(); *ch != '\0'; ++ch) {
+      // if it is already escaped then don't try to escape it again
+      if ((*ch == ' ') && lastch != '\\') {
         result += '\\';
-        }
+      }
       result += *ch;
       lastch = *ch;
-      }
-    ret = result;
     }
+    ret = result;
+  }
   return ret;
 }
 
@@ -2313,46 +2026,39 @@ std::string SystemTools::ConvertToWindowsOutputPath(const std::string& path)
 {
   std::string ret;
   // make it big enough for all of path and double quotes
-  ret.reserve(path.size()+3);
+  ret.reserve(path.size() + 3);
   // put path into the string
   ret = path;
   std::string::size_type pos = 0;
   // first convert all of the slashes
-  while((pos = ret.find('/', pos)) != std::string::npos)
-    {
+  while ((pos = ret.find('/', pos)) != std::string::npos) {
     ret[pos] = '\\';
     pos++;
-    }
+  }
   // check for really small paths
-  if(ret.size() < 2)
-    {
+  if (ret.size() < 2) {
     return ret;
-    }
+  }
   // now clean up a bit and remove double slashes
   // Only if it is not the first position in the path which is a network
   // path on windows
   pos = 1; // start at position 1
-  if(ret[0] == '\"')
-    {
-    pos = 2;  // if the string is already quoted then start at 2
-    if(ret.size() < 3)
-      {
+  if (ret[0] == '\"') {
+    pos = 2; // if the string is already quoted then start at 2
+    if (ret.size() < 3) {
       return ret;
-      }
     }
-  while((pos = ret.find("\\\\", pos)) != std::string::npos)
-    {
+  }
+  while ((pos = ret.find("\\\\", pos)) != std::string::npos) {
     ret.erase(pos, 1);
-    }
+  }
   // now double quote the path if it has spaces in it
   // and is not already double quoted
-  if(ret.find(' ') != std::string::npos
-     && ret[0] != '\"')
-    {
+  if (ret.find(' ') != std::string::npos && ret[0] != '\"') {
     ret.insert(static_cast<std::string::size_type>(0),
                static_cast<std::string::size_type>(1), '\"');
     ret.append(1, '\"');
-    }
+  }
   return ret;
 }
 
@@ -2361,30 +2067,25 @@ bool SystemTools::CopyFileIfDifferent(const std::string& source,
 {
   // special check for a destination that is a directory
   // FilesDiffer does not handle file to directory compare
-  if(SystemTools::FileIsDirectory(destination))
-    {
+  if (SystemTools::FileIsDirectory(destination)) {
     std::string new_destination = destination;
     SystemTools::ConvertToUnixSlashes(new_destination);
     new_destination += '/';
     std::string source_name = source;
     new_destination += SystemTools::GetFilenameName(source_name);
-    if(SystemTools::FilesDiffer(source, new_destination))
-      {
+    if (SystemTools::FilesDiffer(source, new_destination)) {
       return SystemTools::CopyFileAlways(source, destination);
-      }
-    else
-      {
+    } else {
       // the files are the same so the copy is done return
       // true
       return true;
-      }
     }
+  }
   // source and destination are files so do a copy if they
   // are different
-  if(SystemTools::FilesDiffer(source, destination))
-    {
+  if (SystemTools::FilesDiffer(source, destination)) {
     return SystemTools::CopyFileAlways(source, destination);
-    }
+  }
   // at this point the files must be the same so return true
   return true;
 }
@@ -2399,131 +2100,112 @@ bool SystemTools::FilesDiffer(const std::string& source,
   WIN32_FILE_ATTRIBUTE_DATA statSource;
   if (GetFileAttributesExW(
         SystemTools::ConvertToWindowsExtendedPath(source).c_str(),
-        GetFileExInfoStandard,
-        &statSource) == 0)
-    {
+        GetFileExInfoStandard, &statSource) == 0) {
     return true;
-    }
+  }
 
   WIN32_FILE_ATTRIBUTE_DATA statDestination;
   if (GetFileAttributesExW(
         SystemTools::ConvertToWindowsExtendedPath(destination).c_str(),
-        GetFileExInfoStandard,
-        &statDestination) == 0)
-    {
+        GetFileExInfoStandard, &statDestination) == 0) {
     return true;
-    }
+  }
 
-  if(statSource.nFileSizeHigh != statDestination.nFileSizeHigh ||
-     statSource.nFileSizeLow != statDestination.nFileSizeLow)
-    {
+  if (statSource.nFileSizeHigh != statDestination.nFileSizeHigh ||
+      statSource.nFileSizeLow != statDestination.nFileSizeLow) {
     return true;
-    }
+  }
 
-  if(statSource.nFileSizeHigh == 0 && statSource.nFileSizeLow == 0)
-    {
+  if (statSource.nFileSizeHigh == 0 && statSource.nFileSizeLow == 0) {
     return false;
-    }
-  off_t nleft = ((__int64)statSource.nFileSizeHigh << 32) +
-                statSource.nFileSizeLow;
+  }
+  off_t nleft =
+    ((__int64)statSource.nFileSizeHigh << 32) + statSource.nFileSizeLow;
 
 #else
 
   struct stat statSource;
-  if (stat(source.c_str(), &statSource) != 0)
-    {
+  if (stat(source.c_str(), &statSource) != 0) {
     return true;
-    }
+  }
 
   struct stat statDestination;
-  if (stat(destination.c_str(), &statDestination) != 0)
-    {
+  if (stat(destination.c_str(), &statDestination) != 0) {
     return true;
-    }
+  }
 
-  if(statSource.st_size != statDestination.st_size)
-    {
+  if (statSource.st_size != statDestination.st_size) {
     return true;
-    }
+  }
 
-  if(statSource.st_size == 0)
-    {
+  if (statSource.st_size == 0) {
     return false;
-    }
+  }
   off_t nleft = statSource.st_size;
 #endif
 
 #if defined(_WIN32)
-  kwsys::ifstream finSource(source.c_str(),
-                            (std::ios::binary |
-                             std::ios::in));
+  kwsys::ifstream finSource(source.c_str(), (std::ios::binary | std::ios::in));
   kwsys::ifstream finDestination(destination.c_str(),
-                                 (std::ios::binary |
-                                  std::ios::in));
+                                 (std::ios::binary | std::ios::in));
 #else
   kwsys::ifstream finSource(source.c_str());
   kwsys::ifstream finDestination(destination.c_str());
 #endif
-  if(!finSource || !finDestination)
-    {
+  if (!finSource || !finDestination) {
     return true;
-    }
+  }
 
   // Compare the files a block at a time.
   char source_buf[KWSYS_ST_BUFFER];
   char dest_buf[KWSYS_ST_BUFFER];
-  while(nleft > 0)
-    {
+  while (nleft > 0) {
     // Read a block from each file.
-    std::streamsize nnext = (nleft > KWSYS_ST_BUFFER)? KWSYS_ST_BUFFER : static_cast<std::streamsize>(nleft);
+    std::streamsize nnext = (nleft > KWSYS_ST_BUFFER)
+      ? KWSYS_ST_BUFFER
+      : static_cast<std::streamsize>(nleft);
     finSource.read(source_buf, nnext);
     finDestination.read(dest_buf, nnext);
 
     // If either failed to read assume they are different.
-    if(static_cast<std::streamsize>(finSource.gcount()) != nnext ||
-       static_cast<std::streamsize>(finDestination.gcount()) != nnext)
-      {
+    if (static_cast<std::streamsize>(finSource.gcount()) != nnext ||
+        static_cast<std::streamsize>(finDestination.gcount()) != nnext) {
       return true;
-      }
+    }
 
     // If this block differs the file differs.
-    if(memcmp(static_cast<const void*>(source_buf),
-              static_cast<const void*>(dest_buf),
-              static_cast<size_t>(nnext)) != 0)
-      {
+    if (memcmp(static_cast<const void*>(source_buf),
+               static_cast<const void*>(dest_buf),
+               static_cast<size_t>(nnext)) != 0) {
       return true;
-      }
+    }
 
     // Update the byte count remaining.
     nleft -= nnext;
-    }
+  }
 
   // No differences found.
   return false;
 }
 
-
 //----------------------------------------------------------------------------
 /**
  * Copy a file named by "source" to the file named by "destination".
  */
-bool SystemTools::CopyFileAlways(const std::string& source, const std::string& destination)
+bool SystemTools::CopyFileAlways(const std::string& source,
+                                 const std::string& destination)
 {
   // If files are the same do not copy
-  if ( SystemTools::SameFile(source, destination) )
-    {
+  if (SystemTools::SameFile(source, destination)) {
     return true;
-    }
+  }
   mode_t perm = 0;
   bool perms = SystemTools::GetPermissions(source, perm);
   std::string real_destination = destination;
 
-  if(SystemTools::FileIsDirectory(source))
-    {
+  if (SystemTools::FileIsDirectory(source)) {
     SystemTools::MakeDirectory(destination);
-    }
-  else
-    {
+  } else {
     const int bufferSize = 4096;
     char buffer[bufferSize];
 
@@ -2531,36 +2213,32 @@ bool SystemTools::CopyFileAlways(const std::string& source, const std::string& d
     // name as the source in that directory.
 
     std::string destination_dir;
-    if(SystemTools::FileIsDirectory(destination))
-      {
+    if (SystemTools::FileIsDirectory(destination)) {
       destination_dir = real_destination;
       SystemTools::ConvertToUnixSlashes(real_destination);
       real_destination += '/';
       std::string source_name = source;
       real_destination += SystemTools::GetFilenameName(source_name);
-      }
-    else
-      {
+    } else {
       destination_dir = SystemTools::GetFilenamePath(destination);
-      }
+    }
 
     // Create destination directory
 
     SystemTools::MakeDirectory(destination_dir);
 
-    // Open files
+// Open files
 #if defined(_WIN32)
-    kwsys::ifstream fin(Encoding::ToNarrow(
-      SystemTools::ConvertToWindowsExtendedPath(source)).c_str(),
-                  std::ios::in | std::ios::binary);
+    kwsys::ifstream fin(
+      Encoding::ToNarrow(SystemTools::ConvertToWindowsExtendedPath(source))
+        .c_str(),
+      std::ios::in | std::ios::binary);
 #else
-    kwsys::ifstream fin(source.c_str(),
-                  std::ios::in | std::ios::binary);
+    kwsys::ifstream fin(source.c_str(), std::ios::in | std::ios::binary);
 #endif
-    if(!fin)
-      {
+    if (!fin) {
       return false;
-      }
+    }
 
     // try and remove the destination file so that read only destination files
     // can be written to.
@@ -2569,35 +2247,32 @@ bool SystemTools::CopyFileAlways(const std::string& source, const std::string& d
     SystemTools::RemoveFile(real_destination);
 
 #if defined(_WIN32)
-    kwsys::ofstream fout(Encoding::ToNarrow(
-      SystemTools::ConvertToWindowsExtendedPath(real_destination)).c_str(),
-                     std::ios::out | std::ios::trunc | std::ios::binary);
+    kwsys::ofstream fout(
+      Encoding::ToNarrow(
+        SystemTools::ConvertToWindowsExtendedPath(real_destination))
+        .c_str(),
+      std::ios::out | std::ios::trunc | std::ios::binary);
 #else
     kwsys::ofstream fout(real_destination.c_str(),
-                     std::ios::out | std::ios::trunc | std::ios::binary);
+                         std::ios::out | std::ios::trunc | std::ios::binary);
 #endif
-    if(!fout)
-      {
+    if (!fout) {
       return false;
-      }
+    }
 
     // This copy loop is very sensitive on certain platforms with
     // slightly broken stream libraries (like HPUX).  Normally, it is
     // incorrect to not check the error condition on the fin.read()
     // before using the data, but the fin.gcount() will be zero if an
     // error occurred.  Therefore, the loop should be safe everywhere.
-    while(fin)
-      {
+    while (fin) {
       fin.read(buffer, bufferSize);
-      if(fin.gcount())
-        {
+      if (fin.gcount()) {
         fout.write(buffer, fin.gcount());
-        }
-      else
-        {
+      } else {
         break;
-        }
       }
+    }
 
     // Make sure the operating system has finished writing the file
     // before closing it.  This will ensure the file is finished before
@@ -2607,88 +2282,71 @@ bool SystemTools::CopyFileAlways(const std::string& source, const std::string& d
     fin.close();
     fout.close();
 
-    if(!fout)
-      {
+    if (!fout) {
       return false;
-      }
     }
-  if ( perms )
-    {
-    if ( !SystemTools::SetPermissions(real_destination, perm) )
-      {
+  }
+  if (perms) {
+    if (!SystemTools::SetPermissions(real_destination, perm)) {
       return false;
-      }
     }
+  }
   return true;
 }
 
 //----------------------------------------------------------------------------
-bool SystemTools::CopyAFile(const std::string& source, const std::string& destination,
-                            bool always)
+bool SystemTools::CopyAFile(const std::string& source,
+                            const std::string& destination, bool always)
 {
-  if(always)
-    {
+  if (always) {
     return SystemTools::CopyFileAlways(source, destination);
-    }
-  else
-    {
+  } else {
     return SystemTools::CopyFileIfDifferent(source, destination);
-    }
+  }
 }
 
 /**
  * Copy a directory content from "source" directory to the directory named by
  * "destination".
  */
-bool SystemTools::CopyADirectory(const std::string& source, const std::string& destination,
-                                 bool always)
+bool SystemTools::CopyADirectory(const std::string& source,
+                                 const std::string& destination, bool always)
 {
   Directory dir;
 #ifdef _WIN32
-  dir.Load(Encoding::ToNarrow(
-             SystemTools::ConvertToWindowsExtendedPath(source)));
+  dir.Load(
+    Encoding::ToNarrow(SystemTools::ConvertToWindowsExtendedPath(source)));
 #else
   dir.Load(source);
 #endif
   size_t fileNum;
-  if ( !SystemTools::MakeDirectory(destination) )
-    {
+  if (!SystemTools::MakeDirectory(destination)) {
     return false;
-    }
-  for (fileNum = 0; fileNum <  dir.GetNumberOfFiles(); ++fileNum)
-    {
-    if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
-        strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
-      {
+  }
+  for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) {
+    if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") &&
+        strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), "..")) {
       std::string fullPath = source;
       fullPath += "/";
       fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
-      if(SystemTools::FileIsDirectory(fullPath))
-        {
+      if (SystemTools::FileIsDirectory(fullPath)) {
         std::string fullDestPath = destination;
         fullDestPath += "/";
         fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
-        if (!SystemTools::CopyADirectory(fullPath,
-                                         fullDestPath,
-                                         always))
-          {
+        if (!SystemTools::CopyADirectory(fullPath, fullDestPath, always)) {
           return false;
-          }
         }
-      else
-        {
-        if(!SystemTools::CopyAFile(fullPath, destination, always))
-          {
+      } else {
+        if (!SystemTools::CopyAFile(fullPath, destination, always)) {
           return false;
-          }
         }
       }
     }
+  }
 
   return true;
 }
 
-
 // return size of file; also returns zero if no file exists
 unsigned long SystemTools::FileLength(const std::string& filename)
 {
@@ -2697,21 +2355,19 @@ unsigned long SystemTools::FileLength(const std::string& filename)
   WIN32_FILE_ATTRIBUTE_DATA fs;
   if (GetFileAttributesExW(
         SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
-        GetFileExInfoStandard, &fs) != 0)
-    {
+        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.c_str(), &fs) == 0)
-    {
+  if (stat(filename.c_str(), &fs) == 0) {
     length = static_cast<unsigned long>(fs.st_size);
-    }
+  }
 #endif
   return length;
 }
@@ -2723,7 +2379,7 @@ int SystemTools::Strucmp(const char* l, const char* r)
   do {
     lc = tolower(*l++);
     rc = tolower(*r++);
-  } while(lc == rc && lc);
+  } while (lc == rc && lc);
   return lc - rc;
 }
 
@@ -2735,17 +2391,14 @@ long int SystemTools::ModifiedTime(const std::string& filename)
   WIN32_FILE_ATTRIBUTE_DATA fs;
   if (GetFileAttributesExW(
         SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
-                           GetFileExInfoStandard,
-                           &fs) != 0)
-    {
+        GetFileExInfoStandard, &fs) != 0) {
     mt = windows_filetime_to_posix_time(fs.ftLastWriteTime);
-    }
+  }
 #else
   struct stat fs;
-  if (stat(filename.c_str(), &fs) == 0)
-    {
+  if (stat(filename.c_str(), &fs) == 0) {
     mt = static_cast<long int>(fs.st_mtime);
-    }
+  }
 #endif
   return mt;
 }
@@ -2758,27 +2411,23 @@ long int SystemTools::CreationTime(const std::string& filename)
   WIN32_FILE_ATTRIBUTE_DATA fs;
   if (GetFileAttributesExW(
         SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
-                           GetFileExInfoStandard,
-                           &fs) != 0)
-    {
+        GetFileExInfoStandard, &fs) != 0) {
     ct = windows_filetime_to_posix_time(fs.ftCreationTime);
-    }
+  }
 #else
   struct stat fs;
-  if (stat(filename.c_str(), &fs) == 0)
-    {
+  if (stat(filename.c_str(), &fs) == 0) {
     ct = fs.st_ctime >= 0 ? static_cast<long int>(fs.st_ctime) : 0;
-    }
+  }
 #endif
   return ct;
 }
 
-bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt)
+bool SystemTools::ConvertDateMacroString(const char* str, time_t* tmt)
 {
-  if (!str || !tmt || strlen(str) > 11)
-    {
+  if (!str || !tmt || strlen(str) > 11) {
     return false;
-    }
+  }
 
   struct tm tmt2;
 
@@ -2797,36 +2446,34 @@ bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt)
   strcpy(buffer, str);
 
   buffer[3] = 0;
-  char *ptr = strstr(month_names, buffer);
-  if (!ptr)
-    {
+  char* ptr = strstr(month_names, buffer);
+  if (!ptr) {
     return false;
-    }
+  }
 
   int month = static_cast<int>((ptr - month_names) / 3);
   int day = atoi(buffer + 4);
   int year = atoi(buffer + 7);
 
   tmt2.tm_isdst = -1;
-  tmt2.tm_hour  = 0;
-  tmt2.tm_min   = 0;
-  tmt2.tm_sec   = 0;
-  tmt2.tm_wday  = 0;
-  tmt2.tm_yday  = 0;
-  tmt2.tm_mday  = day;
-  tmt2.tm_mon   = month;
-  tmt2.tm_year  = year - 1900;
+  tmt2.tm_hour = 0;
+  tmt2.tm_min = 0;
+  tmt2.tm_sec = 0;
+  tmt2.tm_wday = 0;
+  tmt2.tm_yday = 0;
+  tmt2.tm_mday = day;
+  tmt2.tm_mon = month;
+  tmt2.tm_year = year - 1900;
 
   *tmt = mktime(&tmt2);
   return true;
 }
 
-bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt)
+bool SystemTools::ConvertTimeStampMacroString(const char* str, time_t* tmt)
 {
-  if (!str || !tmt || strlen(str) > 26)
-    {
+  if (!str || !tmt || strlen(str) > 26) {
     return false;
-    }
+  }
 
   struct tm tmt2;
 
@@ -2848,11 +2495,10 @@ bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt)
   strcpy(buffer, str);
 
   buffer[7] = 0;
-  char *ptr = strstr(month_names, buffer + 4);
-  if (!ptr)
-    {
+  char* ptr = strstr(month_names, buffer + 4);
+  if (!ptr) {
     return false;
-    }
+  }
 
   int month = static_cast<int>((ptr - month_names) / 3);
   int day = atoi(buffer + 8);
@@ -2862,14 +2508,14 @@ bool SystemTools::ConvertTimeStampMacroString(const char *str, time_t *tmt)
   int year = atoi(buffer + 20);
 
   tmt2.tm_isdst = -1;
-  tmt2.tm_hour  = hour;
-  tmt2.tm_min   = min;
-  tmt2.tm_sec   = sec;
-  tmt2.tm_wday  = 0;
-  tmt2.tm_yday  = 0;
-  tmt2.tm_mday  = day;
-  tmt2.tm_mon   = month;
-  tmt2.tm_year  = year - 1900;
+  tmt2.tm_hour = hour;
+  tmt2.tm_min = min;
+  tmt2.tm_sec = sec;
+  tmt2.tm_wday = 0;
+  tmt2.tm_yday = 0;
+  tmt2.tm_mday = day;
+  tmt2.tm_mon = month;
+  tmt2.tm_year = year - 1900;
 
   *tmt = mktime(&tmt2);
   return true;
@@ -2886,17 +2532,15 @@ std::string SystemTools::GetLastSystemError()
 static bool IsJunction(const std::wstring& source)
 {
 #ifdef FSCTL_GET_REPARSE_POINT
-  const DWORD JUNCTION_ATTRS = FILE_ATTRIBUTE_DIRECTORY |
-                               FILE_ATTRIBUTE_REPARSE_POINT;
+  const DWORD JUNCTION_ATTRS =
+    FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT;
   DWORD attrs = GetFileAttributesW(source.c_str());
-  if (attrs == INVALID_FILE_ATTRIBUTES)
-    {
+  if (attrs == INVALID_FILE_ATTRIBUTES) {
     return false;
-    }
-  if ((attrs & JUNCTION_ATTRS) != JUNCTION_ATTRS)
-    {
+  }
+  if ((attrs & JUNCTION_ATTRS) != JUNCTION_ATTRS) {
     return false;
-    }
+  }
 
   // Adjust privileges so that we can succefully open junction points.
   HANDLE token;
@@ -2905,32 +2549,30 @@ static bool IsJunction(const std::wstring& source)
   LookupPrivilegeValue(NULL, SE_BACKUP_NAME, &privs.Privileges[0].Luid);
   privs.PrivilegeCount = 1;
   privs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
-  AdjustTokenPrivileges(token, FALSE, &privs, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
+  AdjustTokenPrivileges(token, FALSE, &privs, sizeof(TOKEN_PRIVILEGES), NULL,
+                        NULL);
   CloseHandle(token);
 
-  HANDLE dir = CreateFileW(source.c_str(), GENERIC_READ,
-                           0, NULL, OPEN_EXISTING,
-                           FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
-  if (dir == INVALID_HANDLE_VALUE)
-    {
+  HANDLE dir = CreateFileW(
+    source.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING,
+    FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
+  if (dir == INVALID_HANDLE_VALUE) {
     return false;
-    }
+  }
 
   // Query whether this is a reparse point or not.
   BYTE buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
-  REPARSE_GUID_DATA_BUFFER *reparse_buffer =
-    (REPARSE_GUID_DATA_BUFFER*) buffer;
+  REPARSE_GUID_DATA_BUFFER* reparse_buffer = (REPARSE_GUID_DATA_BUFFER*)buffer;
   DWORD sentinel;
 
-  BOOL success = DeviceIoControl(
-    dir, FSCTL_GET_REPARSE_POINT,
-    NULL, 0,
-    reparse_buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
-    &sentinel, NULL);
+  BOOL success =
+    DeviceIoControl(dir, FSCTL_GET_REPARSE_POINT, NULL, 0, reparse_buffer,
+                    MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &sentinel, NULL);
 
   CloseHandle(dir);
 
-  return (success && (reparse_buffer->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT));
+  return (success &&
+          (reparse_buffer->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT));
 #else
   return false;
 #endif
@@ -2947,30 +2589,28 @@ static bool DeleteJunction(const std::wstring& source)
   LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &privs.Privileges[0].Luid);
   privs.PrivilegeCount = 1;
   privs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
-  AdjustTokenPrivileges(token, FALSE, &privs, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
+  AdjustTokenPrivileges(token, FALSE, &privs, sizeof(TOKEN_PRIVILEGES), NULL,
+                        NULL);
   CloseHandle(token);
 
-  HANDLE dir = CreateFileW(source.c_str(), GENERIC_READ | GENERIC_WRITE,
-                           0, NULL, OPEN_EXISTING,
-                           FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
-  if (dir == INVALID_HANDLE_VALUE)
-    {
+  HANDLE dir = CreateFileW(
+    source.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
+    FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
+  if (dir == INVALID_HANDLE_VALUE) {
     return false;
-    }
+  }
 
   // Set up the structure so that we can delete the junction.
   std::vector<BYTE> buffer(REPARSE_GUID_DATA_BUFFER_HEADER_SIZE, 0);
-  REPARSE_GUID_DATA_BUFFER *reparse_buffer =
-    (REPARSE_GUID_DATA_BUFFER*) &buffer[0];
+  REPARSE_GUID_DATA_BUFFER* reparse_buffer =
+    (REPARSE_GUID_DATA_BUFFER*)&buffer[0];
   DWORD sentinel;
 
   reparse_buffer->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
 
   BOOL success = DeviceIoControl(
-    dir, FSCTL_DELETE_REPARSE_POINT,
-    reparse_buffer, REPARSE_GUID_DATA_BUFFER_HEADER_SIZE,
-    NULL, 0,
-    &sentinel, NULL);
+    dir, FSCTL_DELETE_REPARSE_POINT, reparse_buffer,
+    REPARSE_GUID_DATA_BUFFER_HEADER_SIZE, NULL, 0, &sentinel, NULL);
 
   CloseHandle(dir);
 
@@ -2985,40 +2625,31 @@ static bool DeleteJunction(const std::wstring& source)
 bool SystemTools::RemoveFile(const std::string& source)
 {
 #ifdef _WIN32
-  std::wstring const& ws =
-    SystemTools::ConvertToWindowsExtendedPath(source);
-  if (DeleteFileW(ws.c_str()))
-    {
+  std::wstring const& ws = SystemTools::ConvertToWindowsExtendedPath(source);
+  if (DeleteFileW(ws.c_str())) {
     return true;
-    }
+  }
   DWORD err = GetLastError();
-  if (err == ERROR_FILE_NOT_FOUND ||
-      err == ERROR_PATH_NOT_FOUND)
-    {
+  if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) {
     return true;
-    }
-  if (err != ERROR_ACCESS_DENIED)
-    {
+  }
+  if (err != ERROR_ACCESS_DENIED) {
     return false;
-    }
+  }
   /* The file may be read-only.  Try adding write permission.  */
   mode_t mode;
   if (!SystemTools::GetPermissions(source, mode) ||
-      !SystemTools::SetPermissions(source, S_IWRITE))
-    {
+      !SystemTools::SetPermissions(source, S_IWRITE)) {
     SetLastError(err);
     return false;
-    }
-  if (IsJunction(ws) && DeleteJunction(ws))
-    {
+  }
+  if (IsJunction(ws) && DeleteJunction(ws)) {
     return true;
-    }
-  if (DeleteFileW(ws.c_str()) ||
-      GetLastError() == ERROR_FILE_NOT_FOUND ||
-      GetLastError() == ERROR_PATH_NOT_FOUND)
-    {
+  }
+  if (DeleteFileW(ws.c_str()) || GetLastError() == ERROR_FILE_NOT_FOUND ||
+      GetLastError() == ERROR_PATH_NOT_FOUND) {
     return true;
-    }
+  }
   /* Try to restore the original permissions.  */
   SystemTools::SetPermissions(source, mode);
   SetLastError(err);
@@ -3033,49 +2664,41 @@ bool SystemTools::RemoveADirectory(const std::string& source)
   // Add write permission to the directory so we can modify its
   // content to remove files and directories from it.
   mode_t mode;
-  if(SystemTools::GetPermissions(source, mode))
-    {
+  if (SystemTools::GetPermissions(source, mode)) {
 #if defined(_WIN32) && !defined(__CYGWIN__)
     mode |= S_IWRITE;
 #else
     mode |= S_IWUSR;
 #endif
     SystemTools::SetPermissions(source, mode);
-    }
+  }
 
   Directory dir;
 #ifdef _WIN32
-  dir.Load(Encoding::ToNarrow(
-             SystemTools::ConvertToWindowsExtendedPath(source)));
+  dir.Load(
+    Encoding::ToNarrow(SystemTools::ConvertToWindowsExtendedPath(source)));
 #else
   dir.Load(source);
 #endif
   size_t fileNum;
-  for (fileNum = 0; fileNum <  dir.GetNumberOfFiles(); ++fileNum)
-    {
-    if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".") &&
-        strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)),".."))
-      {
+  for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) {
+    if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") &&
+        strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), "..")) {
       std::string fullPath = source;
       fullPath += "/";
       fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
-      if(SystemTools::FileIsDirectory(fullPath) &&
-        !SystemTools::FileIsSymlink(fullPath))
-        {
-        if (!SystemTools::RemoveADirectory(fullPath))
-          {
+      if (SystemTools::FileIsDirectory(fullPath) &&
+          !SystemTools::FileIsSymlink(fullPath)) {
+        if (!SystemTools::RemoveADirectory(fullPath)) {
           return false;
-          }
         }
-      else
-        {
-        if(!SystemTools::RemoveFile(fullPath))
-          {
+      } else {
+        if (!SystemTools::RemoveFile(fullPath)) {
           return false;
-          }
         }
       }
     }
+  }
 
   return (Rmdir(source) == 0);
 }
@@ -3092,50 +2715,43 @@ size_t SystemTools::GetMaximumFilePathLength()
  * the system search path.  Returns the full path to the file if it is
  * found.  Otherwise, the empty string is returned.
  */
-std::string SystemTools
-::FindName(const std::string& name,
-           const std::vector<std::string>& userPaths,
-           bool no_system_path)
+std::string SystemTools::FindName(const std::string& name,
+                                  const std::vector<std::string>& userPaths,
+                                  bool no_system_path)
 {
   // Add the system search path to our path first
   std::vector<std::string> path;
-  if (!no_system_path)
-    {
+  if (!no_system_path) {
     SystemTools::GetPath(path, "CMAKE_FILE_PATH");
     SystemTools::GetPath(path);
-    }
+  }
   // now add the additional paths
   {
-  for(std::vector<std::string>::const_iterator i = userPaths.begin();
-        i != userPaths.end(); ++i)
-    {
-    path.push_back(*i);
+    for (std::vector<std::string>::const_iterator i = userPaths.begin();
+         i != userPaths.end(); ++i) {
+      path.push_back(*i);
     }
   }
   // Add a trailing slash to all paths to aid the search process.
   {
-  for(std::vector<std::string>::iterator i = path.begin();
-      i != path.end(); ++i)
-    {
-    std::string& p = *i;
-    if(p.empty() || *p.rbegin() != '/')
-      {
-      p += "/";
+    for (std::vector<std::string>::iterator i = path.begin(); i != path.end();
+         ++i) {
+      std::string& p = *i;
+      if (p.empty() || *p.rbegin() != '/') {
+        p += "/";
       }
     }
   }
   // now look for the file
   std::string tryPath;
-  for(std::vector<std::string>::const_iterator p = path.begin();
-      p != path.end(); ++p)
-    {
+  for (std::vector<std::string>::const_iterator p = path.begin();
+       p != path.end(); ++p) {
     tryPath = *p;
     tryPath += name;
-    if(SystemTools::FileExists(tryPath))
-      {
+    if (SystemTools::FileExists(tryPath)) {
       return tryPath;
-      }
     }
+  }
   // Couldn't find the file.
   return "";
 }
@@ -3145,16 +2761,14 @@ std::string SystemTools
  * the system search path.  Returns the full path to the file if it is
  * found.  Otherwise, the empty string is returned.
  */
-std::string SystemTools
-::FindFile(const std::string& name,
-           const std::vector<std::string>& userPaths,
-           bool no_system_path)
+std::string SystemTools::FindFile(const std::string& name,
+                                  const std::vector<std::string>& userPaths,
+                                  bool no_system_path)
 {
   std::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
-  if(!tryPath.empty() && !SystemTools::FileIsDirectory(tryPath))
-    {
+  if (!tryPath.empty() && !SystemTools::FileIsDirectory(tryPath)) {
     return SystemTools::CollapseFullPath(tryPath);
-    }
+  }
   // Couldn't find the file.
   return "";
 }
@@ -3164,16 +2778,14 @@ std::string SystemTools
  * the system search path.  Returns the full path to the directory if it is
  * found.  Otherwise, the empty string is returned.
  */
-std::string SystemTools
-::FindDirectory(const std::string& name,
-                const std::vector<std::string>& userPaths,
-                bool no_system_path)
+std::string SystemTools::FindDirectory(
+  const std::string& name, const std::vector<std::string>& userPaths,
+  bool no_system_path)
 {
   std::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
-  if(!tryPath.empty() && SystemTools::FileIsDirectory(tryPath))
-    {
+  if (!tryPath.empty() && SystemTools::FileIsDirectory(tryPath)) {
     return SystemTools::CollapseFullPath(tryPath);
-    }
+  }
   // Couldn't find the file.
   return "";
 }
@@ -3183,132 +2795,113 @@ std::string SystemTools
  * the system search path.  Returns the full path to the executable if it is
  * found.  Otherwise, the empty string is returned.
  */
-std::string SystemTools::FindProgram(
-  const char* nameIn,
-  const std::vector<std::string>& userPaths,
-  bool no_system_path)
+std::string SystemTools::FindProgram(const char* nameIn,
+                                     const std::vector<std::string>& userPaths,
+                                     bool no_system_path)
 {
-  if(!nameIn || !*nameIn)
-    {
+  if (!nameIn || !*nameIn) {
     return "";
-    }
-  return SystemTools::FindProgram(std::string(nameIn), userPaths, no_system_path);
+  }
+  return SystemTools::FindProgram(std::string(nameIn), userPaths,
+                                  no_system_path);
 }
 
-std::string SystemTools::FindProgram(
-  const std::string& name,
-  const std::vector<std::string>& userPaths,
-  bool no_system_path)
+std::string SystemTools::FindProgram(const std::string& name,
+                                     const std::vector<std::string>& userPaths,
+                                     bool no_system_path)
 {
   std::string tryPath;
 
-#if defined (_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
   std::vector<std::string> extensions;
   // check to see if the name already has a .xxx at
   // the end of it
   // on windows try .com then .exe
-  if(name.size() <= 3 || name[name.size()-4] != '.')
-    {
+  if (name.size() <= 3 || name[name.size() - 4] != '.') {
     extensions.push_back(".com");
     extensions.push_back(".exe");
 
     // first try with extensions if the os supports them
-    for(std::vector<std::string>::iterator i =
-          extensions.begin(); i != extensions.end(); ++i)
-      {
+    for (std::vector<std::string>::iterator i = extensions.begin();
+         i != extensions.end(); ++i) {
       tryPath = name;
       tryPath += *i;
-      if(SystemTools::FileExists(tryPath, true))
-        {
+      if (SystemTools::FileExists(tryPath, true)) {
         return SystemTools::CollapseFullPath(tryPath);
-        }
       }
     }
+  }
 #endif
 
   // now try just the name
-  if(SystemTools::FileExists(name, true))
-    {
+  if (SystemTools::FileExists(name, true)) {
     return SystemTools::CollapseFullPath(name);
-    }
+  }
   // now construct the path
   std::vector<std::string> path;
   // Add the system search path to our path.
-  if (!no_system_path)
-    {
+  if (!no_system_path) {
     SystemTools::GetPath(path);
-    }
+  }
   // now add the additional paths
   {
-  for(std::vector<std::string>::const_iterator i =
-        userPaths.begin();  i != userPaths.end(); ++i)
-    {
-    path.push_back(*i);
+    for (std::vector<std::string>::const_iterator i = userPaths.begin();
+         i != userPaths.end(); ++i) {
+      path.push_back(*i);
     }
   }
   // Add a trailing slash to all paths to aid the search process.
   {
-  for(std::vector<std::string>::iterator i = path.begin();
-      i != path.end(); ++i)
-    {
-    std::string& p = *i;
-    if(p.empty() || *p.rbegin() != '/')
-      {
-      p += "/";
+    for (std::vector<std::string>::iterator i = path.begin(); i != path.end();
+         ++i) {
+      std::string& p = *i;
+      if (p.empty() || *p.rbegin() != '/') {
+        p += "/";
       }
     }
   }
   // Try each path
-  for(std::vector<std::string>::iterator p = path.begin();
-      p != path.end(); ++p)
-    {
+  for (std::vector<std::string>::iterator p = path.begin(); p != path.end();
+       ++p) {
 #ifdef _WIN32
     // Remove double quotes from the path on windows
     SystemTools::ReplaceString(*p, "\"", "");
 #endif
-#if defined (_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
     // first try with extensions
-    for(std::vector<std::string>::iterator ext
-          = extensions.begin(); ext != extensions.end(); ++ext)
-      {
+    for (std::vector<std::string>::iterator ext = extensions.begin();
+         ext != extensions.end(); ++ext) {
       tryPath = *p;
       tryPath += name;
       tryPath += *ext;
-      if(SystemTools::FileExists(tryPath, true))
-        {
+      if (SystemTools::FileExists(tryPath, true)) {
         return SystemTools::CollapseFullPath(tryPath);
-        }
       }
+    }
 #endif
     // now try it without them
     tryPath = *p;
     tryPath += name;
-    if(SystemTools::FileExists(tryPath, true))
-      {
+    if (SystemTools::FileExists(tryPath, true)) {
       return SystemTools::CollapseFullPath(tryPath);
-      }
     }
+  }
   // Couldn't find the program.
   return "";
 }
 
-std::string SystemTools::FindProgram(
-  const std::vector<std::string>& names,
-  const std::vector<std::string>& path,
-  bool noSystemPath)
+std::string SystemTools::FindProgram(const std::vector<std::string>& names,
+                                     const std::vector<std::string>& path,
+                                     bool noSystemPath)
 {
-  for(std::vector<std::string>::const_iterator it = names.begin();
-      it != names.end() ; ++it)
-    {
+  for (std::vector<std::string>::const_iterator it = names.begin();
+       it != names.end(); ++it) {
     // Try to find the program.
-    std::string result = SystemTools::FindProgram(*it,
-                                                  path,
-                                                  noSystemPath);
-    if ( !result.empty() )
-      {
+    std::string result = SystemTools::FindProgram(*it, path, noSystemPath);
+    if (!result.empty()) {
       return result;
-      }
     }
+  }
   return "";
 }
 
@@ -3317,110 +2910,97 @@ std::string SystemTools::FindProgram(
  * the system search path.  Returns the full path to the library if it is
  * found.  Otherwise, the empty string is returned.
  */
-std::string SystemTools
-::FindLibrary(const std::string& name,
-              const std::vector<std::string>& userPaths)
+std::string SystemTools::FindLibrary(const std::string& name,
+                                     const std::vector<std::string>& userPaths)
 {
   // See if the executable exists as written.
-  if(SystemTools::FileExists(name, true))
-    {
+  if (SystemTools::FileExists(name, true)) {
     return SystemTools::CollapseFullPath(name);
-    }
+  }
 
   // Add the system search path to our path.
   std::vector<std::string> path;
   SystemTools::GetPath(path);
-   // now add the additional paths
+  // now add the additional paths
   {
-  for(std::vector<std::string>::const_iterator i = userPaths.begin();
-        i != userPaths.end(); ++i)
-    {
-    path.push_back(*i);
+    for (std::vector<std::string>::const_iterator i = userPaths.begin();
+         i != userPaths.end(); ++i) {
+      path.push_back(*i);
     }
   }
   // Add a trailing slash to all paths to aid the search process.
   {
-  for(std::vector<std::string>::iterator i = path.begin();
-      i != path.end(); ++i)
-    {
-    std::string& p = *i;
-    if(p.empty() || *p.rbegin() != '/')
-      {
-      p += "/";
+    for (std::vector<std::string>::iterator i = path.begin(); i != path.end();
+         ++i) {
+      std::string& p = *i;
+      if (p.empty() || *p.rbegin() != '/') {
+        p += "/";
       }
     }
   }
   std::string tryPath;
-  for(std::vector<std::string>::const_iterator p = path.begin();
-      p != path.end(); ++p)
-    {
+  for (std::vector<std::string>::const_iterator p = path.begin();
+       p != path.end(); ++p) {
 #if defined(__APPLE__)
     tryPath = *p;
     tryPath += name;
     tryPath += ".framework";
-    if(SystemTools::FileIsDirectory(tryPath))
-      {
+    if (SystemTools::FileIsDirectory(tryPath)) {
       return SystemTools::CollapseFullPath(tryPath);
-      }
+    }
 #endif
 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__MINGW32__)
     tryPath = *p;
     tryPath += name;
     tryPath += ".lib";
-    if(SystemTools::FileExists(tryPath, true))
-      {
+    if (SystemTools::FileExists(tryPath, true)) {
       return SystemTools::CollapseFullPath(tryPath);
-      }
+    }
 #else
     tryPath = *p;
     tryPath += "lib";
     tryPath += name;
     tryPath += ".so";
-    if(SystemTools::FileExists(tryPath, true))
-      {
+    if (SystemTools::FileExists(tryPath, true)) {
       return SystemTools::CollapseFullPath(tryPath);
-      }
+    }
     tryPath = *p;
     tryPath += "lib";
     tryPath += name;
     tryPath += ".a";
-    if(SystemTools::FileExists(tryPath, true))
-      {
+    if (SystemTools::FileExists(tryPath, true)) {
       return SystemTools::CollapseFullPath(tryPath);
-      }
+    }
     tryPath = *p;
     tryPath += "lib";
     tryPath += name;
     tryPath += ".sl";
-    if(SystemTools::FileExists(tryPath, true))
-      {
+    if (SystemTools::FileExists(tryPath, true)) {
       return SystemTools::CollapseFullPath(tryPath);
-      }
+    }
     tryPath = *p;
     tryPath += "lib";
     tryPath += name;
     tryPath += ".dylib";
-    if(SystemTools::FileExists(tryPath, true))
-      {
+    if (SystemTools::FileExists(tryPath, true)) {
       return SystemTools::CollapseFullPath(tryPath);
-      }
+    }
     tryPath = *p;
     tryPath += "lib";
     tryPath += name;
     tryPath += ".dll";
-    if(SystemTools::FileExists(tryPath, true))
-      {
+    if (SystemTools::FileExists(tryPath, true)) {
       return SystemTools::CollapseFullPath(tryPath);
-      }
-#endif
     }
+#endif
+  }
 
   // Couldn't find the library.
   return "";
 }
 
 std::string SystemTools::GetRealPath(const std::string& path,
-                                           std::string* errorMessage)
+                                     std::string* errorMessage)
 {
   std::string ret;
   Realpath(path, ret, errorMessage);
@@ -3429,76 +3009,61 @@ std::string SystemTools::GetRealPath(const std::string& path,
 
 bool SystemTools::FileIsDirectory(const std::string& inName)
 {
-  if (inName.empty())
-    {
+  if (inName.empty()) {
     return false;
-    }
+  }
   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] != ':')
-    {
-    if (last < sizeof(local_buffer))
-      {
+  size_t last = length - 1;
+  if (last > 0 && (name[last] == '/' || name[last] == '\\') &&
+      strcmp(name, "/") != 0 && name[last - 1] != ':') {
+    if (last < sizeof(local_buffer)) {
       memcpy(local_buffer, name, last);
       local_buffer[last] = '\0';
       name = local_buffer;
-      }
-    else
-      {
+    } else {
       string_buffer.append(name, last);
       name = string_buffer.c_str();
-      }
     }
+  }
 
-  // Now check the file node type.
-#if defined( _WIN32 )
+// Now check the file node type.
+#if defined(_WIN32)
   DWORD attr = GetFileAttributesW(
     SystemTools::ConvertToWindowsExtendedPath(name).c_str());
-  if (attr != INVALID_FILE_ATTRIBUTES)
-    {
+  if (attr != INVALID_FILE_ATTRIBUTES) {
     return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
 #else
   struct stat fs;
-  if(stat(name, &fs) == 0)
-    {
+  if (stat(name, &fs) == 0) {
     return S_ISDIR(fs.st_mode);
 #endif
-    }
-  else
-    {
+  } else {
     return false;
-    }
+  }
 }
 
 bool SystemTools::FileIsSymlink(const std::string& name)
 {
-#if defined( _WIN32 )
+#if defined(_WIN32)
   DWORD attr = GetFileAttributesW(
     SystemTools::ConvertToWindowsExtendedPath(name).c_str());
-  if (attr != INVALID_FILE_ATTRIBUTES)
-    {
+  if (attr != INVALID_FILE_ATTRIBUTES) {
     return (attr & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
-    }
-  else
-    {
+  } else {
     return false;
-    }
+  }
 #else
   struct stat fs;
-  if(lstat(name.c_str(), &fs) == 0)
-    {
+  if (lstat(name.c_str(), &fs) == 0) {
     return S_ISLNK(fs.st_mode);
-    }
-  else
-    {
+  } else {
     return false;
-    }
+  }
 #endif
 }
 
@@ -3508,7 +3073,8 @@ bool SystemTools::CreateSymlink(const std::string&, const std::string&)
   return false;
 }
 #else
-bool SystemTools::CreateSymlink(const std::string& origName, const std::string& newName)
+bool SystemTools::CreateSymlink(const std::string& origName,
+                                const std::string& newName)
 {
   return symlink(origName.c_str(), newName.c_str()) >= 0;
 }
@@ -3523,20 +3089,17 @@ bool SystemTools::ReadSymlink(const std::string&, std::string&)
 bool SystemTools::ReadSymlink(const std::string& newName,
                               std::string& origName)
 {
-  char buf[KWSYS_SYSTEMTOOLS_MAXPATH+1];
-  int count =
-    static_cast<int>(readlink(newName.c_str(), buf, KWSYS_SYSTEMTOOLS_MAXPATH));
-  if(count >= 0)
-    {
+  char buf[KWSYS_SYSTEMTOOLS_MAXPATH + 1];
+  int count = static_cast<int>(
+    readlink(newName.c_str(), buf, KWSYS_SYSTEMTOOLS_MAXPATH));
+  if (count >= 0) {
     // Add null-terminator.
     buf[count] = 0;
     origName = buf;
     return true;
-    }
-  else
-    {
+  } else {
     return false;
-    }
+  }
 }
 #endif
 
@@ -3550,14 +3113,12 @@ std::string SystemTools::GetCurrentWorkingDirectory(bool collapse)
   char buf[2048];
   const char* cwd = Getcwd(buf, 2048);
   std::string path;
-  if ( cwd )
-    {
+  if (cwd) {
     path = cwd;
-    }
-  if(collapse)
-    {
+  }
+  if (collapse) {
     return SystemTools::CollapseFullPath(path);
-    }
+  }
   return path;
 }
 
@@ -3569,56 +3130,45 @@ std::string SystemTools::GetProgramPath(const std::string& in_name)
 }
 
 bool SystemTools::SplitProgramPath(const std::string& in_name,
-                                   std::string& dir,
-                                   std::string& file,
-                                   bool)
+                                   std::string& dir, std::string& file, bool)
 {
   dir = in_name;
   file = "";
   SystemTools::ConvertToUnixSlashes(dir);
 
-  if(!SystemTools::FileIsDirectory(dir))
-    {
+  if (!SystemTools::FileIsDirectory(dir)) {
     std::string::size_type slashPos = dir.rfind("/");
-    if(slashPos != std::string::npos)
-      {
-      file = dir.substr(slashPos+1);
+    if (slashPos != std::string::npos) {
+      file = dir.substr(slashPos + 1);
       dir = dir.substr(0, slashPos);
-      }
-    else
-      {
+    } else {
       file = dir;
       dir = "";
-      }
     }
-  if(!(dir.empty()) && !SystemTools::FileIsDirectory(dir))
-    {
+  }
+  if (!(dir.empty()) && !SystemTools::FileIsDirectory(dir)) {
     std::string oldDir = in_name;
     SystemTools::ConvertToUnixSlashes(oldDir);
     dir = in_name;
     return false;
-    }
+  }
   return true;
 }
 
-bool SystemTools::FindProgramPath(const char* argv0,
-                                  std::string& pathOut,
-                                  std::string& errorMsg,
-                                  const char* exeName,
+bool SystemTools::FindProgramPath(const char* argv0, std::string& pathOut,
+                                  std::string& errorMsg, const char* exeName,
                                   const char* buildDir,
-                                  const char* installPrefix )
+                                  const char* installPrefix)
 {
   std::vector<std::string> failures;
   std::string self = argv0 ? argv0 : "";
   failures.push_back(self);
   SystemTools::ConvertToUnixSlashes(self);
   self = SystemTools::FindProgram(self);
-  if(!SystemTools::FileExists(self))
-    {
-    if(buildDir)
-      {
+  if (!SystemTools::FileExists(self)) {
+    if (buildDir) {
       std::string intdir = ".";
-#ifdef  CMAKE_INTDIR
+#ifdef CMAKE_INTDIR
       intdir = CMAKE_INTDIR;
 #endif
       self = buildDir;
@@ -3627,52 +3177,46 @@ bool SystemTools::FindProgramPath(const char* argv0,
       self += "/";
       self += exeName;
       self += SystemTools::GetExecutableExtension();
-      }
     }
-  if(installPrefix)
-    {
-    if(!SystemTools::FileExists(self))
-      {
+  }
+  if (installPrefix) {
+    if (!SystemTools::FileExists(self)) {
       failures.push_back(self);
       self = installPrefix;
       self += "/bin/";
-      self +=  exeName;
-      }
+      self += exeName;
     }
-  if(!SystemTools::FileExists(self))
-    {
+  }
+  if (!SystemTools::FileExists(self)) {
     failures.push_back(self);
     std::ostringstream msg;
     msg << "Can not find the command line program ";
-    if (exeName)
-      {
+    if (exeName) {
       msg << exeName;
-      }
+    }
     msg << "\n";
-    if (argv0)
-      {
+    if (argv0) {
       msg << "  argv[0] = \"" << argv0 << "\"\n";
-      }
+    }
     msg << "  Attempted paths:\n";
     std::vector<std::string>::iterator i;
-    for(i=failures.begin(); i != failures.end(); ++i)
-      {
+    for (i = failures.begin(); i != failures.end(); ++i) {
       msg << "    \"" << *i << "\"\n";
-      }
+    }
     errorMsg = msg.str();
     return false;
-    }
+  }
   pathOut = self;
   return true;
 }
 
-
 std::string SystemTools::CollapseFullPath(const std::string& in_relative)
 {
   return SystemTools::CollapseFullPath(in_relative, 0);
 }
 
-void SystemTools::AddTranslationPath(const std::string& a, const std::string& b)
+void SystemTools::AddTranslationPath(const std::string& a,
+                                     const std::string& b)
 {
   std::string path_a = a;
   std::string path_b = b;
@@ -3680,30 +3224,25 @@ void SystemTools::AddTranslationPath(const std::string& a, const std::string& b)
   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 ) )
-    {
+  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) && path_b.find("..")
-        == std::string::npos )
-      {
+    if (SystemTools::FileIsFullPath(path_b) &&
+        path_b.find("..") == std::string::npos) {
       // Before inserting make sure path ends with '/'
-      if(!path_a.empty() && *path_a.rbegin() != '/')
-        {
+      if (!path_a.empty() && *path_a.rbegin() != '/') {
         path_a += '/';
-        }
-      if(!path_b.empty() && *path_b.rbegin() != '/')
-        {
+      }
+      if (!path_b.empty() && *path_b.rbegin() != '/') {
         path_b += '/';
-        }
-      if( !(path_a == path_b) )
-        {
+      }
+      if (!(path_a == path_b)) {
         SystemTools::TranslationMap->insert(
           SystemToolsTranslationMap::value_type(path_a, path_b));
-        }
       }
     }
+  }
 }
 
 void SystemTools::AddKeepPath(const std::string& dir)
@@ -3713,14 +3252,13 @@ void SystemTools::AddKeepPath(const std::string& dir)
   SystemTools::AddTranslationPath(cdir, dir);
 }
 
-void SystemTools::CheckTranslationPath(std::string & path)
+void SystemTools::CheckTranslationPath(std::string& path)
 {
   // Do not translate paths that are too short to have meaningful
   // translations.
-  if(path.size() < 2)
-    {
+  if (path.size() < 2) {
     return;
-    }
+  }
 
   // Always add a trailing slash before translation.  It does not
   // matter if this adds an extra slash, but we do not want to
@@ -3729,49 +3267,39 @@ void SystemTools::CheckTranslationPath(std::string & path)
 
   // In case a file was specified we still have to go through this:
   // Now convert any path found in the table back to the one desired:
-  std::map<std::string,std::string>::const_iterator it;
-  for(it  = SystemTools::TranslationMap->begin();
-      it != SystemTools::TranslationMap->end();
-      ++it )
-    {
+  std::map<std::string, std::string>::const_iterator it;
+  for (it = SystemTools::TranslationMap->begin();
+       it != SystemTools::TranslationMap->end(); ++it) {
     // We need to check of the path is a substring of the other path
-    if(path.find( it->first ) == 0)
-      {
-      path = path.replace( 0, it->first.size(), it->second);
-      }
+    if (path.find(it->first) == 0) {
+      path = path.replace(0, it->first.size(), it->second);
     }
+  }
 
   // Remove the trailing slash we added before.
-  path.erase(path.end()-1, path.end());
+  path.erase(path.end() - 1, path.end());
 }
 
-static void
-SystemToolsAppendComponents(
+static void SystemToolsAppendComponents(
   std::vector<std::string>& out_components,
   std::vector<std::string>::const_iterator first,
   std::vector<std::string>::const_iterator last)
 {
   static const std::string up = "..";
   static const std::string cur = ".";
-  for(std::vector<std::string>::const_iterator i = first;
-      i != last; ++i)
-    {
-    if(*i == up)
-      {
-      if(out_components.size() > 1)
-        {
-        out_components.resize(out_components.size()-1);
-        }
+  for (std::vector<std::string>::const_iterator i = first; i != last; ++i) {
+    if (*i == up) {
+      if (out_components.size() > 1) {
+        out_components.resize(out_components.size() - 1);
       }
-    else if(!i->empty() && *i != cur)
-      {
+    } else if (!i->empty() && *i != cur) {
       out_components.push_back(*i);
-      }
     }
+  }
 }
 
 std::string SystemTools::CollapseFullPath(const std::string& in_path,
-                                                const char* in_base)
+                                          const char* in_base)
 {
   // Collect the output path components.
   std::vector<std::string> out_components;
@@ -3781,38 +3309,29 @@ std::string SystemTools::CollapseFullPath(const std::string& in_path,
   SystemTools::SplitPath(in_path, path_components);
 
   // If the input path is relative, start with a base path.
-  if(path_components[0].length() == 0)
-    {
+  if (path_components[0].length() == 0) {
     std::vector<std::string> base_components;
-    if(in_base)
-      {
+    if (in_base) {
       // Use the given base path.
       SystemTools::SplitPath(in_base, base_components);
-      }
-    else
-      {
+    } else {
       // Use the current working directory as a base path.
       char buf[2048];
-      if(const char* cwd = Getcwd(buf, 2048))
-        {
+      if (const char* cwd = Getcwd(buf, 2048)) {
         SystemTools::SplitPath(cwd, base_components);
-        }
-      else
-        {
+      } else {
         base_components.push_back("");
-        }
       }
+    }
 
     // Append base path components to the output path.
     out_components.push_back(base_components[0]);
-    SystemToolsAppendComponents(out_components,
-                                base_components.begin()+1,
+    SystemToolsAppendComponents(out_components, base_components.begin() + 1,
                                 base_components.end());
-    }
+  }
 
   // Append input path components to the output path.
-  SystemToolsAppendComponents(out_components,
-                              path_components.begin(),
+  SystemToolsAppendComponents(out_components, path_components.begin(),
                               path_components.end());
 
   // Transform the path back to a string.
@@ -3830,7 +3349,7 @@ std::string SystemTools::CollapseFullPath(const std::string& in_path,
   // collapsed, so I am going to try to comment it out, and see what hits the
   // fan, hopefully quickly.
   // Commented out line below:
-  //SystemTools::AddTranslationPath(newPath, in_path);
+  // SystemTools::AddTranslationPath(newPath, in_path);
 
   SystemTools::CheckTranslationPath(newPath);
 #ifdef _WIN32
@@ -3842,7 +3361,7 @@ std::string SystemTools::CollapseFullPath(const std::string& in_path,
 }
 
 std::string SystemTools::CollapseFullPath(const std::string& in_path,
-                                                const std::string& in_base)
+                                          const std::string& in_base)
 {
   // Collect the output path components.
   std::vector<std::string> out_components;
@@ -3852,22 +3371,19 @@ std::string SystemTools::CollapseFullPath(const std::string& in_path,
   SystemTools::SplitPath(in_path, path_components);
 
   // If the input path is relative, start with a base path.
-  if(path_components[0].length() == 0)
-    {
+  if (path_components[0].length() == 0) {
     std::vector<std::string> base_components;
     // Use the given base path.
     SystemTools::SplitPath(in_base, base_components);
 
     // Append base path components to the output path.
     out_components.push_back(base_components[0]);
-    SystemToolsAppendComponents(out_components,
-                                base_components.begin()+1,
+    SystemToolsAppendComponents(out_components, base_components.begin() + 1,
                                 base_components.end());
-    }
+  }
 
   // Append input path components to the output path.
-  SystemToolsAppendComponents(out_components,
-                              path_components.begin(),
+  SystemToolsAppendComponents(out_components, path_components.begin(),
                               path_components.end());
 
   // Transform the path back to a string.
@@ -3885,7 +3401,7 @@ std::string SystemTools::CollapseFullPath(const std::string& in_path,
   // collapsed, so I am going to try to comment it out, and see what hits the
   // fan, hopefully quickly.
   // Commented out line below:
-  //SystemTools::AddTranslationPath(newPath, in_path);
+  // SystemTools::AddTranslationPath(newPath, in_path);
 
   SystemTools::CheckTranslationPath(newPath);
 #ifdef _WIN32
@@ -3897,89 +3413,82 @@ std::string SystemTools::CollapseFullPath(const std::string& in_path,
 }
 
 // compute the relative path from here to there
-std::string SystemTools::RelativePath(const std::string& local, const std::string& remote)
+std::string SystemTools::RelativePath(const std::string& local,
+                                      const std::string& remote)
 {
-  if(!SystemTools::FileIsFullPath(local))
-    {
+  if (!SystemTools::FileIsFullPath(local)) {
     return "";
-    }
-  if(!SystemTools::FileIsFullPath(remote))
-    {
+  }
+  if (!SystemTools::FileIsFullPath(remote)) {
     return "";
-    }
+  }
 
   std::string l = SystemTools::CollapseFullPath(local);
   std::string r = SystemTools::CollapseFullPath(remote);
 
   // split up both paths into arrays of strings using / as a separator
-  std::vector<kwsys::String> localSplit = SystemTools::SplitString(l, '/', true);
-  std::vector<kwsys::String> remoteSplit = SystemTools::SplitString(r, '/', true);
-  std::vector<kwsys::String> commonPath; // store shared parts of path in this array
-  std::vector<kwsys::String> finalPath;  // store the final relative path here
+  std::vector<kwsys::String> localSplit =
+    SystemTools::SplitString(l, '/', true);
+  std::vector<kwsys::String> remoteSplit =
+    SystemTools::SplitString(r, '/', true);
+  std::vector<kwsys::String>
+    commonPath; // store shared parts of path in this array
+  std::vector<kwsys::String> finalPath; // store the final relative path here
   // count up how many matching directory names there are from the start
   unsigned int sameCount = 0;
-  while(
-    ((sameCount <= (localSplit.size()-1)) && (sameCount <= (remoteSplit.size()-1)))
-    &&
+  while (((sameCount <= (localSplit.size() - 1)) &&
+          (sameCount <= (remoteSplit.size() - 1))) &&
 // for windows and apple do a case insensitive string compare
 #if defined(_WIN32) || defined(__APPLE__)
-    SystemTools::Strucmp(localSplit[sameCount].c_str(),
-                         remoteSplit[sameCount].c_str()) == 0
+         SystemTools::Strucmp(localSplit[sameCount].c_str(),
+                              remoteSplit[sameCount].c_str()) == 0
 #else
-    localSplit[sameCount] == remoteSplit[sameCount]
+         localSplit[sameCount] == remoteSplit[sameCount]
 #endif
-    )
-    {
+         ) {
     // put the common parts of the path into the commonPath array
     commonPath.push_back(localSplit[sameCount]);
     // erase the common parts of the path from the original path arrays
     localSplit[sameCount] = "";
     remoteSplit[sameCount] = "";
     sameCount++;
-    }
+  }
 
   // If there is nothing in common at all then just return the full
   // path.  This is the case only on windows when the paths have
   // different drive letters.  On unix two full paths always at least
   // have the root "/" in common so we will return a relative path
   // that passes through the root directory.
-  if(sameCount == 0)
-    {
+  if (sameCount == 0) {
     return remote;
-    }
+  }
 
   // for each entry that is not common in the local path
   // add a ../ to the finalpath array, this gets us out of the local
   // path into the remote dir
-  for(unsigned int i = 0; i < localSplit.size(); ++i)
-    {
-    if(!localSplit[i].empty())
-      {
+  for (unsigned int i = 0; i < localSplit.size(); ++i) {
+    if (!localSplit[i].empty()) {
       finalPath.push_back("../");
-      }
     }
+  }
   // for each entry that is not common in the remote path add it
   // to the final path.
-  for(std::vector<String>::iterator vit = remoteSplit.begin();
-      vit != remoteSplit.end(); ++vit)
-    {
-    if(!vit->empty())
-      {
+  for (std::vector<String>::iterator vit = remoteSplit.begin();
+       vit != remoteSplit.end(); ++vit) {
+    if (!vit->empty()) {
       finalPath.push_back(*vit);
-      }
     }
-  std::string relativePath;     // result string
+  }
+  std::string relativePath; // result string
   // now turn the array of directories into a unix path by puttint /
   // between each entry that does not already have one
-  for(std::vector<String>::iterator vit1 = finalPath.begin();
-      vit1 != finalPath.end(); ++vit1)
-    {
-    if(!relativePath.empty() && *relativePath.rbegin() != '/')
-      {
+  for (std::vector<String>::iterator vit1 = finalPath.begin();
+       vit1 != finalPath.end(); ++vit1) {
+    if (!relativePath.empty() && *relativePath.rbegin() != '/') {
       relativePath += "/";
-      }
-    relativePath += *vit1;
     }
+    relativePath += *vit1;
+  }
   return relativePath;
 }
 
@@ -3989,77 +3498,66 @@ static std::string GetCasePathName(std::string const& pathIn)
   std::string casePath;
   std::vector<std::string> path_components;
   SystemTools::SplitPath(pathIn, path_components);
-  if(path_components[0].empty()) // First component always exists.
-    {
+  if (path_components[0].empty()) // First component always exists.
+  {
     // Relative paths cannot be converted.
     casePath = pathIn;
     return casePath;
-    }
+  }
 
   // Start with root component.
   std::vector<std::string>::size_type idx = 0;
   casePath = path_components[idx++];
   // make sure drive letter is always upper case
-  if(casePath.size() > 1 && casePath[1] == ':')
-    {
+  if (casePath.size() > 1 && casePath[1] == ':') {
     casePath[0] = toupper(casePath[0]);
-    }
+  }
   const char* sep = "";
 
   // If network path, fill casePath with server/share so FindFirstFile
   // will work after that.  Maybe someday call other APIs to get
   // actual case of servers and shares.
-  if(path_components.size() > 2 && path_components[0] == "//")
-    {
+  if (path_components.size() > 2 && path_components[0] == "//") {
     casePath += path_components[idx++];
     casePath += "/";
     casePath += path_components[idx++];
     sep = "/";
-    }
+  }
 
   // Convert case of all components that exist.
   bool converting = true;
-  for(; idx < path_components.size(); idx++)
-    {
+  for (; idx < path_components.size(); idx++) {
     casePath += sep;
     sep = "/";
 
-    if (converting)
-      {
+    if (converting) {
       // 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('*') != std::string::npos ||
-         path_components[idx].find('?') != std::string::npos)
-        {
+      if (path_components[idx].find('*') != std::string::npos ||
+          path_components[idx].find('?') != std::string::npos) {
         converting = false;
-        }
-      else
-        {
+      } else {
         std::string test_str = casePath;
         test_str += path_components[idx];
         WIN32_FIND_DATAW findData;
-        HANDLE hFind = ::FindFirstFileW(Encoding::ToWide(test_str).c_str(),
-          &findData);
-        if (INVALID_HANDLE_VALUE != hFind)
-          {
+        HANDLE hFind =
+          ::FindFirstFileW(Encoding::ToWide(test_str).c_str(), &findData);
+        if (INVALID_HANDLE_VALUE != hFind) {
           path_components[idx] = Encoding::ToNarrow(findData.cFileName);
           ::FindClose(hFind);
-          }
-        else
-          {
+        } else {
           converting = false;
-          }
         }
       }
+    }
 
     casePath += path_components[idx];
-    }
+  }
   return casePath;
 }
 #endif
 
-
 //----------------------------------------------------------------------------
 std::string SystemTools::GetActualCaseForPath(const std::string& p)
 {
@@ -4068,17 +3566,14 @@ std::string SystemTools::GetActualCaseForPath(const std::string& p)
 #else
   // Check to see if actual case has already been called
   // for this path, and the result is stored in the PathCaseMap
-  SystemToolsPathCaseMap::iterator i =
-    SystemTools::PathCaseMap->find(p);
-  if(i != SystemTools::PathCaseMap->end())
-    {
+  SystemToolsPathCaseMap::iterator i = SystemTools::PathCaseMap->find(p);
+  if (i != SystemTools::PathCaseMap->end()) {
     return i->second;
-    }
+  }
   std::string casePath = GetCasePathName(p);
-  if (casePath.size() > MAX_PATH)
-    {
+  if (casePath.size() > MAX_PATH) {
     return casePath;
-    }
+  }
   (*SystemTools::PathCaseMap)[p] = casePath;
   return casePath;
 #endif
@@ -4090,46 +3585,33 @@ const char* SystemTools::SplitPathRootComponent(const std::string& p,
 {
   // Identify the root component.
   const char* c = p.c_str();
-  if((c[0] == '/' && c[1] == '/') || (c[0] == '\\' && c[1] == '\\'))
-    {
+  if ((c[0] == '/' && c[1] == '/') || (c[0] == '\\' && c[1] == '\\')) {
     // Network path.
-    if(root)
-      {
+    if (root) {
       *root = "//";
-      }
-    c += 2;
     }
-  else if(c[0] == '/' || c[0] == '\\')
-    {
+    c += 2;
+  } else if (c[0] == '/' || c[0] == '\\') {
     // Unix path (or Windows path w/out drive letter).
-    if(root)
-      {
+    if (root) {
       *root = "/";
-      }
-    c += 1;
     }
-  else if(c[0] && c[1] == ':' && (c[2] == '/' || c[2] == '\\'))
-    {
+    c += 1;
+  } else if (c[0] && c[1] == ':' && (c[2] == '/' || c[2] == '\\')) {
     // Windows path.
-    if(root)
-      {
+    if (root) {
       (*root) = "_:/";
       (*root)[0] = c[0];
-      }
-    c += 3;
     }
-  else if(c[0] && c[1] == ':')
-    {
+    c += 3;
+  } else if (c[0] && c[1] == ':') {
     // Path relative to a windows drive working directory.
-    if(root)
-      {
+    if (root) {
       (*root) = "_:";
       (*root)[0] = c[0];
-      }
-    c += 2;
     }
-  else if(c[0] == '~')
-    {
+    c += 2;
+  } else if (c[0] == '~') {
     // Home directory.  The returned root should always have a
     // trailing slash so that appending components as
     // c[0]c[1]/c[2]/... works.  The remaining path returned should
@@ -4142,29 +3624,23 @@ const char* SystemTools::SplitPathRootComponent(const std::string& p,
     //   "~u/"  : root = "~u/", return ""
     //   "~u/x" : root = "~u/", return "x"
     size_t n = 1;
-    while(c[n] && c[n] != '/')
-      {
+    while (c[n] && c[n] != '/') {
       ++n;
-      }
-    if(root)
-      {
+    }
+    if (root) {
       root->assign(c, n);
       *root += '/';
-      }
-    if(c[n] == '/')
-      {
+    }
+    if (c[n] == '/') {
       ++n;
-      }
-    c += n;
     }
-  else
-    {
+    c += n;
+  } else {
     // Relative path.
-    if(root)
-      {
+    if (root) {
       *root = "";
-      }
     }
+  }
 
   // Return the remaining path.
   return c;
@@ -4180,102 +3656,86 @@ void SystemTools::SplitPath(const std::string& p,
 
   // Identify the root component.
   {
-  std::string root;
-  c = SystemTools::SplitPathRootComponent(p, &root);
-
-  // Expand home directory references if requested.
-  if(expand_home_dir && !root.empty() && root[0] == '~')
-    {
-    std::string homedir;
-    root = root.substr(0, root.size()-1);
-    if(root.size() == 1)
-      {
+    std::string root;
+    c = SystemTools::SplitPathRootComponent(p, &root);
+
+    // Expand home directory references if requested.
+    if (expand_home_dir && !root.empty() && root[0] == '~') {
+      std::string homedir;
+      root = root.substr(0, root.size() - 1);
+      if (root.size() == 1) {
 #if defined(_WIN32) && !defined(__CYGWIN__)
-      if (!SystemTools::GetEnv("USERPROFILE", homedir))
+        if (!SystemTools::GetEnv("USERPROFILE", homedir))
 #endif
-      SystemTools::GetEnv("HOME", homedir);
+          SystemTools::GetEnv("HOME", homedir);
       }
 #ifdef HAVE_GETPWNAM
-    else if(passwd* pw = getpwnam(root.c_str()+1))
-      {
-      if(pw->pw_dir)
-        {
-        homedir = pw->pw_dir;
+      else if (passwd* pw = getpwnam(root.c_str() + 1)) {
+        if (pw->pw_dir) {
+          homedir = pw->pw_dir;
         }
       }
 #endif
-    if(!homedir.empty() && (*homedir.rbegin() == '/' ||
-                            *homedir.rbegin() == '\\'))
-      {
-      homedir.resize(homedir.size() - 1);
+      if (!homedir.empty() &&
+          (*homedir.rbegin() == '/' || *homedir.rbegin() == '\\')) {
+        homedir.resize(homedir.size() - 1);
       }
-    SystemTools::SplitPath(homedir, components);
-    }
-  else
-    {
-    components.push_back(root);
+      SystemTools::SplitPath(homedir, components);
+    } else {
+      components.push_back(root);
     }
   }
 
   // Parse the remaining components.
   const char* first = c;
   const char* last = first;
-  for(;*last; ++last)
-    {
-    if(*last == '/' || *last == '\\')
-      {
+  for (; *last; ++last) {
+    if (*last == '/' || *last == '\\') {
       // End of a component.  Save it.
       components.push_back(std::string(first, last));
-      first = last+1;
-      }
+      first = last + 1;
     }
+  }
 
   // Save the last component unless there were no components.
-  if(last != c)
-    {
+  if (last != c) {
     components.push_back(std::string(first, last));
-    }
+  }
 }
 
 //----------------------------------------------------------------------------
-std::string
-SystemTools::JoinPath(const std::vector<std::string>& components)
+std::string SystemTools::JoinPath(const std::vector<std::string>& components)
 {
   return SystemTools::JoinPath(components.begin(), components.end());
 }
 
 //----------------------------------------------------------------------------
-std::string
-SystemTools
-::JoinPath(std::vector<std::string>::const_iterator first,
-           std::vector<std::string>::const_iterator last)
+std::string SystemTools::JoinPath(
+  std::vector<std::string>::const_iterator first,
+  std::vector<std::string>::const_iterator last)
 {
   // Construct result in a single string.
   std::string result;
   size_t len = 0;
   std::vector<std::string>::const_iterator i;
-  for(i = first; i != last; ++i)
-    {
+  for (i = first; i != last; ++i) {
     len += 1 + i->size();
-    }
+  }
   result.reserve(len);
 
   // The first two components do not add a slash.
-  if(first != last)
-    {
+  if (first != last) {
     result.append(*first++);
-    }
-  if(first != last)
-    {
+  }
+  if (first != last) {
     result.append(*first++);
-    }
+  }
 
   // All remaining components are always separated with a slash.
-  while(first != last)
-    {
+  while (first != last) {
     result.append("/");
     result.append((*first++));
-    }
+  }
 
   // Return the concatenated result.
   return result;
@@ -4285,68 +3745,61 @@ SystemTools
 bool SystemTools::ComparePath(const std::string& c1, const std::string& c2)
 {
 #if defined(_WIN32) || defined(__APPLE__)
-# ifdef _MSC_VER
+#ifdef _MSC_VER
   return _stricmp(c1.c_str(), c2.c_str()) == 0;
-# elif defined(__APPLE__) || defined(__GNUC__)
+#elif defined(__APPLE__) || defined(__GNUC__)
   return strcasecmp(c1.c_str(), c2.c_str()) == 0;
 #else
   return SystemTools::Strucmp(c1.c_str(), c2.c_str()) == 0;
-# endif
+#endif
 #else
   return c1 == c2;
 #endif
 }
 
 //----------------------------------------------------------------------------
-bool SystemTools::Split(const std::string& str, std::vector<std::string>& lines, char separator)
+bool SystemTools::Split(const std::string& str,
+                        std::vector<std::string>& lines, char separator)
 {
   std::string data(str);
   std::string::size_type lpos = 0;
-  while(lpos < data.length())
-    {
+  while (lpos < data.length()) {
     std::string::size_type rpos = data.find_first_of(separator, lpos);
-    if(rpos == std::string::npos)
-      {
+    if (rpos == std::string::npos) {
       // Line ends at end of string without a newline.
       lines.push_back(data.substr(lpos));
       return false;
-      }
-    else
-      {
+    } else {
       // Line ends in a "\n", remove the character.
-      lines.push_back(data.substr(lpos, rpos-lpos));
-      }
-    lpos = rpos+1;
+      lines.push_back(data.substr(lpos, rpos - lpos));
     }
+    lpos = rpos + 1;
+  }
   return true;
 }
 
 //----------------------------------------------------------------------------
-bool SystemTools::Split(const std::string& str, std::vector<std::string>& lines)
+bool SystemTools::Split(const std::string& str,
+                        std::vector<std::string>& lines)
 {
   std::string data(str);
   std::string::size_type lpos = 0;
-  while(lpos < data.length())
-    {
+  while (lpos < data.length()) {
     std::string::size_type rpos = data.find_first_of("\n", lpos);
-    if(rpos == std::string::npos)
-      {
+    if (rpos == std::string::npos) {
       // Line ends at end of string without a newline.
       lines.push_back(data.substr(lpos));
       return false;
-      }
-    if((rpos > lpos) && (data[rpos-1] == '\r'))
-      {
+    }
+    if ((rpos > lpos) && (data[rpos - 1] == '\r')) {
       // Line ends in a "\r\n" pair, remove both characters.
-      lines.push_back(data.substr(lpos, (rpos-1)-lpos));
-      }
-    else
-      {
+      lines.push_back(data.substr(lpos, (rpos - 1) - lpos));
+    } else {
       // Line ends in a "\n", remove the character.
-      lines.push_back(data.substr(lpos, rpos-lpos));
-      }
-    lpos = rpos+1;
+      lines.push_back(data.substr(lpos, rpos - lpos));
     }
+    lpos = rpos + 1;
+  }
   return true;
 }
 
@@ -4360,26 +3813,20 @@ std::string SystemTools::GetFilenamePath(const std::string& filename)
   SystemTools::ConvertToUnixSlashes(fn);
 
   std::string::size_type slash_pos = fn.rfind("/");
-  if(slash_pos != std::string::npos)
-    {
-    std::string  ret = fn.substr(0, slash_pos);
-    if(ret.size() == 2 && ret[1] == ':')
-      {
+  if (slash_pos != std::string::npos) {
+    std::string ret = fn.substr(0, slash_pos);
+    if (ret.size() == 2 && ret[1] == ':') {
       return ret + '/';
-      }
-    if(ret.empty())
-      {
+    }
+    if (ret.empty()) {
       return "/";
-      }
-    return ret;
     }
-  else
-    {
+    return ret;
+  } else {
     return "";
-    }
+  }
 }
 
-
 /**
  * Return file name of a full filename (i.e. file name without path).
  */
@@ -4390,17 +3837,13 @@ std::string SystemTools::GetFilenameName(const std::string& filename)
 #else
   std::string::size_type slash_pos = filename.rfind('/');
 #endif
-  if(slash_pos != std::string::npos)
-    {
+  if (slash_pos != std::string::npos) {
     return filename.substr(slash_pos + 1);
-    }
-  else
-    {
+  } else {
     return filename;
-    }
+  }
 }
 
-
 /**
  * Return file extension of a full filename (dot included).
  * Warning: this is the longest extension (for example: .tar.gz)
@@ -4409,14 +3852,11 @@ std::string SystemTools::GetFilenameExtension(const std::string& filename)
 {
   std::string name = SystemTools::GetFilenameName(filename);
   std::string::size_type dot_pos = name.find('.');
-  if(dot_pos != std::string::npos)
-    {
+  if (dot_pos != std::string::npos) {
     return name.substr(dot_pos);
-    }
-  else
-    {
+  } else {
     return "";
-    }
+  }
 }
 
 /**
@@ -4427,161 +3867,135 @@ std::string SystemTools::GetFilenameLastExtension(const std::string& filename)
 {
   std::string name = SystemTools::GetFilenameName(filename);
   std::string::size_type dot_pos = name.rfind('.');
-  if(dot_pos != std::string::npos)
-    {
+  if (dot_pos != std::string::npos) {
     return name.substr(dot_pos);
-    }
-  else
-    {
+  } else {
     return "";
-    }
+  }
 }
 
 /**
  * Return file name without extension of a full filename (i.e. without path).
  * Warning: it considers the longest extension (for example: .tar.gz)
  */
-std::string SystemTools::GetFilenameWithoutExtension(const std::string& filename)
+std::string SystemTools::GetFilenameWithoutExtension(
+  const std::string& filename)
 {
   std::string name = SystemTools::GetFilenameName(filename);
   std::string::size_type dot_pos = name.find('.');
-  if(dot_pos != std::string::npos)
-    {
+  if (dot_pos != std::string::npos) {
     return name.substr(0, dot_pos);
-    }
-  else
-    {
+  } else {
     return name;
-    }
+  }
 }
 
-
 /**
  * Return file name without extension of a full filename (i.e. without path).
  * Warning: it considers the last extension (for example: removes .gz
  * from .tar.gz)
  */
-std::string
-SystemTools::GetFilenameWithoutLastExtension(const std::string& filename)
+std::string SystemTools::GetFilenameWithoutLastExtension(
+  const std::string& filename)
 {
   std::string name = SystemTools::GetFilenameName(filename);
   std::string::size_type dot_pos = name.rfind('.');
-  if(dot_pos != std::string::npos)
-    {
+  if (dot_pos != std::string::npos) {
     return name.substr(0, dot_pos);
-    }
-  else
-    {
+  } else {
     return name;
-    }
+  }
 }
 
-bool SystemTools::FileHasSignature(const char *filename,
-                                   const char *signature,
+bool SystemTools::FileHasSignature(const char* filename, const char* signature,
                                    long offset)
 {
-  if (!filename || !signature)
-    {
+  if (!filename || !signature) {
     return false;
-    }
+  }
 
-  FILE *fp = Fopen(filename, "rb");
-  if (!fp)
-    {
+  FILE* fp = Fopen(filename, "rb");
+  if (!fp) {
     return false;
-    }
+  }
 
   fseek(fp, offset, SEEK_SET);
 
   bool res = false;
   size_t signature_len = strlen(signature);
-  char *buffer = new char [signature_len];
+  char* buffer = new char[signature_len];
 
-  if (fread(buffer, 1, signature_len, fp) == signature_len)
-    {
+  if (fread(buffer, 1, signature_len, fp) == signature_len) {
     res = (!strncmp(buffer, signature, signature_len) ? true : false);
-    }
+  }
 
-  delete [] buffer;
+  delete[] buffer;
 
   fclose(fp);
   return res;
 }
 
-SystemTools::FileTypeEnum
-SystemTools::DetectFileType(const char *filename,
-                            unsigned long length,
-                            double percent_bin)
+SystemTools::FileTypeEnum SystemTools::DetectFileType(const char* filename,
+                                                      unsigned long length,
+                                                      double percent_bin)
 {
-  if (!filename || percent_bin < 0)
-    {
+  if (!filename || percent_bin < 0) {
     return SystemTools::FileTypeUnknown;
-    }
+  }
 
-  if (SystemTools::FileIsDirectory(filename))
-    {
+  if (SystemTools::FileIsDirectory(filename)) {
     return SystemTools::FileTypeUnknown;
-    }
+  }
 
-  FILE *fp = Fopen(filename, "rb");
-  if (!fp)
-    {
+  FILE* fp = Fopen(filename, "rb");
+  if (!fp) {
     return SystemTools::FileTypeUnknown;
-    }
+  }
 
   // Allocate buffer and read bytes
 
-  unsigned char *buffer = new unsigned char [length];
+  unsigned char* buffer = new unsigned char[length];
   size_t read_length = fread(buffer, 1, length, fp);
   fclose(fp);
-  if (read_length == 0)
-    {
-    delete [] buffer;
+  if (read_length == 0) {
+    delete[] buffer;
     return SystemTools::FileTypeUnknown;
-    }
+  }
 
   // Loop over contents and count
 
   size_t text_count = 0;
 
-  const unsigned char *ptr = buffer;
-  const unsigned char *buffer_end = buffer + read_length;
+  const unsigned char* ptr = buffer;
+  const unsigned char* buffer_end = buffer + read_length;
 
-  while (ptr != buffer_end)
-    {
-    if ((*ptr >= 0x20 && *ptr <= 0x7F) ||
-        *ptr == '\n' ||
-        *ptr == '\r' ||
-        *ptr == '\t')
-      {
+  while (ptr != buffer_end) {
+    if ((*ptr >= 0x20 && *ptr <= 0x7F) || *ptr == '\n' || *ptr == '\r' ||
+        *ptr == '\t') {
       text_count++;
-      }
-    ptr++;
     }
+    ptr++;
+  }
 
-  delete [] buffer;
+  delete[] buffer;
 
-  double current_percent_bin =
-    (static_cast<double>(read_length - text_count) /
-     static_cast<double>(read_length));
+  double current_percent_bin = (static_cast<double>(read_length - text_count) /
+                                static_cast<double>(read_length));
 
-  if (current_percent_bin >= percent_bin)
-    {
+  if (current_percent_bin >= percent_bin) {
     return SystemTools::FileTypeBinary;
-    }
+  }
 
   return SystemTools::FileTypeText;
 }
 
-bool SystemTools::LocateFileInDir(const char *filename,
-                                  const char *dir,
+bool SystemTools::LocateFileInDir(const char* filename, const char* dir,
                                   std::string& filename_found,
                                   int try_filename_dirs)
 {
-  if (!filename || !dir)
-    {
+  if (!filename || !dir) {
     return false;
-    }
+  }
 
   // Get the basename of 'filename'
 
@@ -4591,81 +4005,72 @@ bool SystemTools::LocateFileInDir(const char *filename,
   // If win32 and matches something like C:, accept it as a dir
 
   std::string real_dir;
-  if (!SystemTools::FileIsDirectory(dir))
-    {
-#if defined( _WIN32 )
+  if (!SystemTools::FileIsDirectory(dir)) {
+#if defined(_WIN32)
     size_t dir_len = strlen(dir);
-    if (dir_len < 2 || dir[dir_len - 1] != ':')
-      {
+    if (dir_len < 2 || dir[dir_len - 1] != ':') {
 #endif
       real_dir = SystemTools::GetFilenamePath(dir);
       dir = real_dir.c_str();
-#if defined( _WIN32 )
-      }
-#endif
+#if defined(_WIN32)
     }
+#endif
+  }
 
   // Try to find the file in 'dir'
 
   bool res = false;
-  if (!filename_base.empty() && dir)
-    {
+  if (!filename_base.empty() && dir) {
     size_t dir_len = strlen(dir);
     int need_slash =
       (dir_len && dir[dir_len - 1] != '/' && dir[dir_len - 1] != '\\');
 
     std::string temp = dir;
-    if (need_slash)
-      {
+    if (need_slash) {
       temp += "/";
-      }
+    }
     temp += filename_base;
 
-    if (SystemTools::FileExists(temp))
-      {
+    if (SystemTools::FileExists(temp)) {
       res = true;
       filename_found = temp;
-      }
+    }
 
     // If not found, we can try harder by appending part of the file to
     // to the directory to look inside.
     // Example: if we were looking for /foo/bar/yo.txt in /d1/d2, then
     // try to find yo.txt in /d1/d2/bar, then /d1/d2/foo/bar, etc.
 
-    else if (try_filename_dirs)
-      {
+    else if (try_filename_dirs) {
       std::string filename_dir(filename);
       std::string filename_dir_base;
       std::string filename_dir_bases;
-      do
-        {
+      do {
         filename_dir = SystemTools::GetFilenamePath(filename_dir);
         filename_dir_base = SystemTools::GetFilenameName(filename_dir);
-#if defined( _WIN32 )
-        if (filename_dir_base.empty() ||
-            *filename_dir_base.rbegin() == ':')
+#if defined(_WIN32)
+        if (filename_dir_base.empty() || *filename_dir_base.rbegin() == ':')
 #else
         if (filename_dir_base.empty())
 #endif
-          {
+        {
           break;
-          }
+        }
 
         filename_dir_bases = filename_dir_base + "/" + filename_dir_bases;
 
         temp = dir;
-        if (need_slash)
-          {
+        if (need_slash) {
           temp += "/";
-          }
+        }
         temp += filename_dir_bases;
 
-        res = SystemTools::LocateFileInDir(
-          filename_base.c_str(), temp.c_str(), filename_found, 0);
+        res = SystemTools::LocateFileInDir(filename_base.c_str(), temp.c_str(),
+                                           filename_found, 0);
 
-        } while (!res && !filename_dir_base.empty());
-      }
+      } while (!res && !filename_dir_base.empty());
     }
+  }
 
   return res;
 }
@@ -4677,77 +4082,67 @@ bool SystemTools::FileIsFullPath(const std::string& in_name)
 
 bool SystemTools::FileIsFullPath(const char* in_name)
 {
-  return SystemTools::FileIsFullPath(in_name, in_name[0] ? (in_name[1] ? 2 : 1) : 0);
+  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)
-    {
+  if (len < 2) {
     return false;
-    }
-  if(in_name[1] == ':')
-    {
+  }
+  if (in_name[1] == ':') {
     return true;
-    }
-  if(in_name[0] == '\\')
-    {
+  }
+  if (in_name[0] == '\\') {
     return true;
-    }
+  }
 #else
   // On UNIX, the name must be at least one character long.
-  if(len < 1)
-    {
+  if (len < 1) {
     return false;
-    }
+  }
 #endif
 #if !defined(_WIN32)
-  if(in_name[0] == '~')
-    {
+  if (in_name[0] == '~') {
     return true;
-    }
+  }
 #endif
   // On UNIX, the name must begin in a '/'.
   // On Windows, if the name begins in a '/', then it is a full
   // network path.
-  if(in_name[0] == '/')
-    {
+  if (in_name[0] == '/') {
     return true;
-    }
+  }
   return false;
 }
 
 bool SystemTools::GetShortPath(const std::string& path, std::string& shortPath)
 {
 #if defined(_WIN32) && !defined(__CYGWIN__)
-  std::string tempPath = path;  // create a buffer
+  std::string tempPath = path; // create a buffer
 
   // if the path passed in has quotes around it, first remove the quotes
-  if (!path.empty() && path[0] == '"' && *path.rbegin() == '"')
-    {
-    tempPath = path.substr(1, path.length()-2);
-    }
+  if (!path.empty() && path[0] == '"' && *path.rbegin() == '"') {
+    tempPath = path.substr(1, path.length() - 2);
+  }
 
   std::wstring wtempPath = Encoding::ToWide(tempPath);
   DWORD ret = GetShortPathNameW(wtempPath.c_str(), NULL, 0);
   std::vector<wchar_t> buffer(ret);
-  if (ret != 0)
-    {
-    ret = GetShortPathNameW(wtempPath.c_str(),
-                            &buffer[0], static_cast<DWORD>(buffer.size()));
-    }
+  if (ret != 0) {
+    ret = GetShortPathNameW(wtempPath.c_str(), &buffer[0],
+                            static_cast<DWORD>(buffer.size()));
+  }
 
-  if (ret == 0)
-    {
+  if (ret == 0) {
     return false;
-    }
-  else
-    {
+  } else {
     shortPath = Encoding::ToNarrow(&buffer[0]);
     return true;
-    }
+  }
 #else
   shortPath = path;
   return true;
@@ -4759,63 +4154,56 @@ void SystemTools::SplitProgramFromArgs(const std::string& path,
 {
   // see if this is a full path to a program
   // if so then set program to path and args to nothing
-  if(SystemTools::FileExists(path))
-    {
+  if (SystemTools::FileExists(path)) {
     program = path;
     args = "";
     return;
-    }
+  }
   // Try to find the program in the path, note the program
   // may have spaces in its name so we have to look for it
   std::vector<std::string> e;
   std::string findProg = SystemTools::FindProgram(path, e);
-  if(!findProg.empty())
-    {
+  if (!findProg.empty()) {
     program = findProg;
     args = "";
     return;
-    }
+  }
 
   // Now try and peel off space separated chunks from the end of the string
   // so the largest path possible is found allowing for spaces in the path
   std::string dir = path;
   std::string::size_type spacePos = dir.rfind(' ');
-  while(spacePos != std::string::npos)
-    {
+  while (spacePos != std::string::npos) {
     std::string tryProg = dir.substr(0, spacePos);
     // See if the file exists
-    if(SystemTools::FileExists(tryProg))
-      {
+    if (SystemTools::FileExists(tryProg)) {
       program = tryProg;
       // remove trailing spaces from program
-      std::string::size_type pos = program.size()-1;
-      while(program[pos] == ' ')
-        {
+      std::string::size_type pos = program.size() - 1;
+      while (program[pos] == ' ') {
         program.erase(pos);
         pos--;
-        }
-      args = dir.substr(spacePos, dir.size()-spacePos);
-      return;
       }
+      args = dir.substr(spacePos, dir.size() - spacePos);
+      return;
+    }
     // Now try and find the program in the path
     findProg = SystemTools::FindProgram(tryProg, e);
-    if(!findProg.empty())
-      {
+    if (!findProg.empty()) {
       program = findProg;
       // remove trailing spaces from program
-      std::string::size_type pos = program.size()-1;
-      while(program[pos] == ' ')
-        {
+      std::string::size_type pos = program.size() - 1;
+      while (program[pos] == ' ') {
         program.erase(pos);
         pos--;
-        }
-      args = dir.substr(spacePos, dir.size()-spacePos);
-      return;
       }
+      args = dir.substr(spacePos, dir.size() - spacePos);
+      return;
+    }
     // move past the space for the next search
     spacePos--;
     spacePos = dir.rfind(' ', spacePos);
-    }
+  }
 
   program = "";
   args = "";
@@ -4833,28 +4221,26 @@ std::string SystemTools::GetCurrentDateTime(const char* format)
 std::string SystemTools::MakeCidentifier(const std::string& s)
 {
   std::string str(s);
-  if (str.find_first_of("0123456789") == 0)
-    {
+  if (str.find_first_of("0123456789") == 0) {
     str = "_" + str;
-    }
+  }
 
   std::string permited_chars("_"
                              "abcdefghijklmnopqrstuvwxyz"
                              "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                              "0123456789");
   std::string::size_type pos = 0;
-  while ((pos = str.find_first_not_of(permited_chars, pos)) != std::string::npos)
-    {
+  while ((pos = str.find_first_not_of(permited_chars, pos)) !=
+         std::string::npos) {
     str[pos] = '_';
-    }
+  }
   return str;
 }
 
 // Due to a buggy stream library on the HP and another on Mac OS X, we
 // need this very carefully written version of getline.  Returns true
 // if any data were read before the end-of-file was reached.
-bool SystemTools::GetLineFromStream(std::istream& is,
-                                    std::string& line,
+bool SystemTools::GetLineFromStream(std::istream& is, std::string& line,
                                     bool* has_newline /* = 0 */,
                                     long sizeLimit /* = -1 */)
 {
@@ -4872,63 +4258,52 @@ bool SystemTools::GetLineFromStream(std::istream& is,
   // false and the empty line. (Probably means caller tried to
   // create a file stream with a non-existent file name...)
   //
-  if(!is)
-    {
-    if(has_newline)
-      {
+  if (!is) {
+    if (has_newline) {
       *has_newline = false;
-      }
-    return false;
     }
+    return false;
+  }
 
   // If no characters are read from the stream, the end of file has
   // been reached.  Clear the fail bit just before reading.
-  while(!haveNewline &&
-        leftToRead != 0 &&
-        (static_cast<void>(is.clear(is.rdstate() & ~std::ios::failbit)),
-         static_cast<void>(is.getline(buffer, bufferSize)),
-         is.gcount() > 0))
-    {
+  while (!haveNewline && leftToRead != 0 &&
+         (static_cast<void>(is.clear(is.rdstate() & ~std::ios::failbit)),
+          static_cast<void>(is.getline(buffer, bufferSize)),
+          is.gcount() > 0)) {
     // We have read at least one byte.
     haveData = true;
 
     // If newline character was read the gcount includes the character
     // but the buffer does not: the end of line has been reached.
     size_t length = strlen(buffer);
-    if(length < static_cast<size_t>(is.gcount()))
-      {
+    if (length < static_cast<size_t>(is.gcount())) {
       haveNewline = true;
-      }
+    }
 
     // Avoid storing a carriage return character.
-    if(length > 0 && buffer[length-1] == '\r')
-      {
-      buffer[length-1] = 0;
-      }
+    if (length > 0 && buffer[length - 1] == '\r') {
+      buffer[length - 1] = 0;
+    }
 
     // if we read too much then truncate the buffer
-    if (leftToRead > 0)
-      {
-      if (static_cast<long>(length) > leftToRead)
-        {
-        buffer[leftToRead-1] = 0;
+    if (leftToRead > 0) {
+      if (static_cast<long>(length) > leftToRead) {
+        buffer[leftToRead] = 0;
         leftToRead = 0;
-        }
-      else
-        {
+      } else {
         leftToRead -= static_cast<long>(length);
-        }
       }
+    }
 
     // Append the data read to the line.
     line.append(buffer);
-    }
+  }
 
   // Return the results.
-  if(has_newline)
-    {
+  if (has_newline) {
     *has_newline = haveNewline;
-    }
+  }
   return haveData;
 }
 
@@ -4938,38 +4313,32 @@ int SystemTools::GetTerminalWidth()
 #ifdef HAVE_TTY_INFO
   struct winsize ws;
   std::string columns; /* Unix98 environment variable */
-  if(ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col>0 && ws.ws_row>0)
-    {
+  if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col > 0 && ws.ws_row > 0) {
     width = ws.ws_col;
-    }
-  if(!isatty(STDOUT_FILENO))
-    {
+  }
+  if (!isatty(STDOUT_FILENO)) {
     width = -1;
-    }
-  if(SystemTools::GetEnv("COLUMNS", columns) && !columns.empty())
-    {
+  }
+  if (SystemTools::GetEnv("COLUMNS", columns) && !columns.empty()) {
     long t;
-    char *endptr;
+    char* endptr;
     t = strtol(columns.c_str(), &endptr, 0);
-    if(endptr && !*endptr && (t>0) && (t<1000))
-      {
+    if (endptr && !*endptr && (t > 0) && (t < 1000)) {
       width = static_cast<int>(t);
-      }
     }
-  if ( width < 9 )
-    {
+  }
+  if (width < 9) {
     width = -1;
-    }
+  }
 #endif
   return width;
 }
 
 bool SystemTools::GetPermissions(const char* file, mode_t& mode)
 {
-  if ( !file )
-    {
+  if (!file) {
     return false;
-    }
+  }
   return SystemTools::GetPermissions(std::string(file), mode);
 }
 
@@ -4978,85 +4347,65 @@ bool SystemTools::GetPermissions(const std::string& file, mode_t& mode)
 #if defined(_WIN32)
   DWORD attr = GetFileAttributesW(
     SystemTools::ConvertToWindowsExtendedPath(file).c_str());
-  if(attr == INVALID_FILE_ATTRIBUTES)
-    {
+  if (attr == INVALID_FILE_ATTRIBUTES) {
     return false;
-    }
-  if((attr & FILE_ATTRIBUTE_READONLY) != 0)
-    {
-    mode = (_S_IREAD  | (_S_IREAD  >> 3) | (_S_IREAD  >> 6));
-    }
-  else
-    {
+  }
+  if ((attr & FILE_ATTRIBUTE_READONLY) != 0) {
+    mode = (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6));
+  } else {
     mode = (_S_IWRITE | (_S_IWRITE >> 3) | (_S_IWRITE >> 6)) |
-           (_S_IREAD  | (_S_IREAD  >> 3) | (_S_IREAD  >> 6));
-    }
-  if((attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
-    {
-    mode |= S_IFDIR | (_S_IEXEC  | (_S_IEXEC  >> 3) | (_S_IEXEC  >> 6));
-    }
-  else
-    {
+      (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6));
+  }
+  if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
+    mode |= S_IFDIR | (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6));
+  } else {
     mode |= S_IFREG;
-    }
+  }
   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 ||
-    Strucmp(ext, ".bat") == 0))
-    {
-    mode |= (_S_IEXEC  | (_S_IEXEC  >> 3) | (_S_IEXEC  >> 6));
-    }
+  if (ext && (Strucmp(ext, ".exe") == 0 || Strucmp(ext, ".com") == 0 ||
+              Strucmp(ext, ".cmd") == 0 || Strucmp(ext, ".bat") == 0)) {
+    mode |= (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6));
+  }
 #else
   struct stat st;
-  if ( stat(file.c_str(), &st) < 0 )
-    {
+  if (stat(file.c_str(), &st) < 0) {
     return false;
-    }
+  }
   mode = st.st_mode;
 #endif
   return true;
 }
 
-bool SystemTools::SetPermissions(const char* file,
-                                 mode_t mode,
+bool SystemTools::SetPermissions(const char* file, mode_t mode,
                                  bool honor_umask)
 {
-  if ( !file )
-    {
+  if (!file) {
     return false;
-    }
-  return SystemTools::SetPermissions(
-    std::string(file), mode, honor_umask);
+  }
+  return SystemTools::SetPermissions(std::string(file), mode, honor_umask);
 }
 
-bool SystemTools::SetPermissions(const std::string& file,
-                                 mode_t mode,
+bool SystemTools::SetPermissions(const std::string& file, mode_t mode,
                                  bool honor_umask)
 {
-  // TEMPORARY / TODO:  After FileExists calls lstat() instead of
-  // access(), change this call to FileExists instead of
-  // TestFileAccess so that we don't follow symlinks.
-  if ( !SystemTools::TestFileAccess(file, TEST_FILE_OK) )
-    {
+  if (!SystemTools::PathExists(file)) {
     return false;
-    }
-  if (honor_umask)
-    {
+  }
+  if (honor_umask) {
     mode_t currentMask = umask(0);
     umask(currentMask);
     mode &= ~currentMask;
-    }
+  }
 #ifdef _WIN32
-  if ( _wchmod(SystemTools::ConvertToWindowsExtendedPath(file).c_str(),
-               mode) < 0 )
+  if (_wchmod(SystemTools::ConvertToWindowsExtendedPath(file).c_str(), mode) <
+      0)
 #else
-  if ( chmod(file.c_str(), mode) < 0 )
+  if (chmod(file.c_str(), mode) < 0)
 #endif
-    {
+  {
     return false;
-    }
+  }
 
   return true;
 }
@@ -5066,21 +4415,20 @@ std::string SystemTools::GetParentDirectory(const std::string& fileOrDir)
   return SystemTools::GetFilenamePath(fileOrDir);
 }
 
-bool SystemTools::IsSubDirectory(const std::string& cSubdir, const std::string& cDir)
+bool SystemTools::IsSubDirectory(const std::string& cSubdir,
+                                 const std::string& cDir)
 {
-  if(cDir.empty())
-    {
+  if (cDir.empty()) {
     return false;
-    }
+  }
   std::string subdir = cSubdir;
   std::string dir = cDir;
   SystemTools::ConvertToUnixSlashes(subdir);
   SystemTools::ConvertToUnixSlashes(dir);
-  if(subdir.size() > dir.size() && subdir[dir.size()] == '/')
-    {
+  if (subdir.size() > dir.size() && subdir[dir.size()] == '/') {
     std::string s = subdir.substr(0, dir.size());
     return SystemTools::ComparePath(s, dir);
-    }
+  }
   return false;
 }
 
@@ -5096,15 +4444,12 @@ void SystemTools::Delay(unsigned int msec)
   // atomically.  If select is given empty sets and zero as the max
   // file descriptor but a non-zero timeout it can be used to block
   // for a precise amount of time.
-  if(msec >= 1000)
-    {
+  if (msec >= 1000) {
     sleep(msec / 1000);
     usleep((msec % 1000) * 1000);
-    }
-  else
-    {
+  } else {
     usleep(msec * 1000);
-    }
+  }
 #endif
 }
 
@@ -5122,229 +4467,171 @@ std::string SystemTools::GetOperatingSystemNameAndVersion()
   osvi.dwOSVersionInfoSize = sizeof(osvi);
 
 #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (push)
-# ifdef __INTEL_COMPILER
-#  pragma warning (disable:1478)
-# else
-#  pragma warning (disable:4996)
-# endif
-#endif
-  bOsVersionInfoEx = GetVersionExA((OSVERSIONINFOA *)&osvi);
-  if (!bOsVersionInfoEx)
-    {
+#pragma warning(push)
+#ifdef __INTEL_COMPILER
+#pragma warning(disable : 1478)
+#else
+#pragma warning(disable : 4996)
+#endif
+#endif
+  bOsVersionInfoEx = GetVersionExA((OSVERSIONINFOA*)&osvi);
+  if (!bOsVersionInfoEx) {
     return 0;
-    }
+  }
 #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
-# pragma warning (pop)
+#pragma warning(pop)
 #endif
 
-  switch (osvi.dwPlatformId)
-    {
+  switch (osvi.dwPlatformId) {
     // Test for the Windows NT product family.
 
     case VER_PLATFORM_WIN32_NT:
 
       // Test for the specific product family.
-      if (osvi.dwMajorVersion == 10 && osvi.dwMinorVersion == 0)
-        {
-        if (osvi.wProductType == VER_NT_WORKSTATION)
-          {
+      if (osvi.dwMajorVersion == 10 && osvi.dwMinorVersion == 0) {
+        if (osvi.wProductType == VER_NT_WORKSTATION) {
           res += "Microsoft Windows 10";
-          }
-        else
-          {
+        } else {
           res += "Microsoft Windows Server 2016 family";
-          }
         }
+      }
 
-      if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 3)
-        {
-        if (osvi.wProductType == VER_NT_WORKSTATION)
-          {
+      if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 3) {
+        if (osvi.wProductType == VER_NT_WORKSTATION) {
           res += "Microsoft Windows 8.1";
-          }
-        else
-          {
+        } else {
           res += "Microsoft Windows Server 2012 R2 family";
-          }
         }
+      }
 
-      if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 2)
-        {
-        if (osvi.wProductType == VER_NT_WORKSTATION)
-          {
+      if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 2) {
+        if (osvi.wProductType == VER_NT_WORKSTATION) {
           res += "Microsoft Windows 8";
-          }
-        else
-          {
+        } else {
           res += "Microsoft Windows Server 2012 family";
-          }
         }
+      }
 
-      if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1)
-        {
-        if (osvi.wProductType == VER_NT_WORKSTATION)
-          {
+      if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1) {
+        if (osvi.wProductType == VER_NT_WORKSTATION) {
           res += "Microsoft Windows 7";
-          }
-        else
-          {
+        } else {
           res += "Microsoft Windows Server 2008 R2 family";
-          }
         }
+      }
 
-      if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0)
-        {
-        if (osvi.wProductType == VER_NT_WORKSTATION)
-          {
+      if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0) {
+        if (osvi.wProductType == VER_NT_WORKSTATION) {
           res += "Microsoft Windows Vista";
-          }
-        else
-          {
+        } else {
           res += "Microsoft Windows Server 2008 family";
-          }
         }
+      }
 
-      if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
-        {
+      if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) {
         res += "Microsoft Windows Server 2003 family";
-        }
+      }
 
-      if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
-        {
+      if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) {
         res += "Microsoft Windows XP";
-        }
+      }
 
-      if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
-        {
+      if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) {
         res += "Microsoft Windows 2000";
-        }
+      }
 
-      if (osvi.dwMajorVersion <= 4)
-        {
+      if (osvi.dwMajorVersion <= 4) {
         res += "Microsoft Windows NT";
-        }
+      }
 
       // Test for specific product on Windows NT 4.0 SP6 and later.
 
-      if (bOsVersionInfoEx)
-        {
+      if (bOsVersionInfoEx) {
         // Test for the workstation type.
 
-        if (osvi.wProductType == VER_NT_WORKSTATION)
-          {
-          if (osvi.dwMajorVersion == 4)
-            {
+        if (osvi.wProductType == VER_NT_WORKSTATION) {
+          if (osvi.dwMajorVersion == 4) {
             res += " Workstation 4.0";
-            }
-          else if (osvi.dwMajorVersion == 5)
-            {
-            if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
-              {
+          } else if (osvi.dwMajorVersion == 5) {
+            if (osvi.wSuiteMask & VER_SUITE_PERSONAL) {
               res += " Home Edition";
-              }
-            else
-              {
+            } else {
               res += " Professional";
-              }
             }
           }
+        }
 
         // Test for the server type.
 
-        else if (osvi.wProductType == VER_NT_SERVER)
-          {
-          if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
-            {
-            if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
-              {
+        else if (osvi.wProductType == VER_NT_SERVER) {
+          if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) {
+            if (osvi.wSuiteMask & VER_SUITE_DATACENTER) {
               res += " Datacenter Edition";
-              }
-            else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
-              {
+            } else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
               res += " Enterprise Edition";
-              }
-            else if (osvi.wSuiteMask == VER_SUITE_BLADE)
-              {
+            } else if (osvi.wSuiteMask == VER_SUITE_BLADE) {
               res += " Web Edition";
-              }
-            else
-              {
+            } else {
               res += " Standard Edition";
-              }
             }
+          }
 
-          else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
-            {
-            if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
-              {
+          else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) {
+            if (osvi.wSuiteMask & VER_SUITE_DATACENTER) {
               res += " Datacenter Server";
-              }
-            else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
-              {
+            } else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
               res += " Advanced Server";
-              }
-            else
-              {
+            } else {
               res += " Server";
-              }
             }
+          }
 
-          else if (osvi.dwMajorVersion <= 4)  // Windows NT 4.0
-            {
-            if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
-              {
+          else if (osvi.dwMajorVersion <= 4) // Windows NT 4.0
+          {
+            if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE) {
               res += " Server 4.0, Enterprise Edition";
-              }
-            else
-              {
+            } else {
               res += " Server 4.0";
-              }
             }
           }
         }
+      }
 
       // Test for specific product on Windows NT 4.0 SP5 and earlier
 
-      else
-        {
+      else {
         HKEY hKey;
-        #define BUFSIZE 80
+#define BUFSIZE 80
         wchar_t szProductType[BUFSIZE];
-        DWORD dwBufLen=BUFSIZE;
+        DWORD dwBufLen = BUFSIZE;
         LONG lRet;
 
-        lRet = RegOpenKeyExW(
-          HKEY_LOCAL_MACHINE,
-          L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
-          0, KEY_QUERY_VALUE, &hKey);
-        if (lRet != ERROR_SUCCESS)
-          {
+        lRet =
+          RegOpenKeyExW(HKEY_LOCAL_MACHINE,
+                        L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
+                        0, KEY_QUERY_VALUE, &hKey);
+        if (lRet != ERROR_SUCCESS) {
           return 0;
-          }
+        }
 
         lRet = RegQueryValueExW(hKey, L"ProductType", NULL, NULL,
-                                (LPBYTE) szProductType, &dwBufLen);
+                                (LPBYTE)szProductType, &dwBufLen);
 
-        if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE))
-          {
+        if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE)) {
           return 0;
-          }
+        }
 
         RegCloseKey(hKey);
 
-        if (lstrcmpiW(L"WINNT", szProductType) == 0)
-          {
+        if (lstrcmpiW(L"WINNT", szProductType) == 0) {
           res += " Workstation";
-          }
-        if (lstrcmpiW(L"LANMANNT", szProductType) == 0)
-          {
+        }
+        if (lstrcmpiW(L"LANMANNT", szProductType) == 0) {
           res += " Server";
-          }
-        if (lstrcmpiW(L"SERVERNT", szProductType) == 0)
-          {
+        }
+        if (lstrcmpiW(L"SERVERNT", szProductType) == 0) {
           res += " Advanced Server";
-          }
+        }
 
         res += " ";
         sprintf(buffer, "%ld", osvi.dwMajorVersion);
@@ -5352,13 +4639,12 @@ std::string SystemTools::GetOperatingSystemNameAndVersion()
         res += ".";
         sprintf(buffer, "%ld", osvi.dwMinorVersion);
         res += buffer;
-        }
+      }
 
       // Display service pack (if any) and build number.
 
       if (osvi.dwMajorVersion == 4 &&
-          lstrcmpiA(osvi.szCSDVersion, "Service Pack 6") == 0)
-        {
+          lstrcmpiA(osvi.szCSDVersion, "Service Pack 6") == 0) {
         HKEY hKey;
         LONG lRet;
 
@@ -5369,104 +4655,95 @@ std::string SystemTools::GetOperatingSystemNameAndVersion()
           L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009",
           0, KEY_QUERY_VALUE, &hKey);
 
-        if (lRet == ERROR_SUCCESS)
-          {
+        if (lRet == ERROR_SUCCESS) {
           res += " Service Pack 6a (Build ";
           sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
           res += buffer;
           res += ")";
-          }
-        else // Windows NT 4.0 prior to SP6a
-          {
+        } else // Windows NT 4.0 prior to SP6a
+        {
           res += " ";
           res += osvi.szCSDVersion;
           res += " (Build ";
           sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
           res += buffer;
           res += ")";
-          }
+        }
 
         RegCloseKey(hKey);
-        }
-      else // Windows NT 3.51 and earlier or Windows 2000 and later
-        {
+      } else // Windows NT 3.51 and earlier or Windows 2000 and later
+      {
         res += " ";
         res += osvi.szCSDVersion;
         res += " (Build ";
         sprintf(buffer, "%ld", osvi.dwBuildNumber & 0xFFFF);
         res += buffer;
         res += ")";
-        }
+      }
 
       break;
 
-      // Test for the Windows 95 product family.
+    // Test for the Windows 95 product family.
 
     case VER_PLATFORM_WIN32_WINDOWS:
 
-      if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
-        {
+      if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) {
         res += "Microsoft Windows 95";
-        if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B')
-          {
+        if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B') {
           res += " OSR2";
-          }
         }
+      }
 
-      if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
-        {
+      if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) {
         res += "Microsoft Windows 98";
-        if (osvi.szCSDVersion[1] == 'A')
-          {
+        if (osvi.szCSDVersion[1] == 'A') {
           res += " SE";
-          }
         }
+      }
 
-      if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
-        {
+      if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) {
         res += "Microsoft Windows Millennium Edition";
-        }
+      }
       break;
 
     case VER_PLATFORM_WIN32s:
 
-      res +=  "Microsoft Win32s";
+      res += "Microsoft Win32s";
       break;
-    }
+  }
 #endif
 
   return res;
 }
 
 // ----------------------------------------------------------------------
-bool SystemTools::ParseURLProtocol( const std::string& URL,
-                                    std::string& protocol,
-                                    std::string& dataglom )
+bool SystemTools::ParseURLProtocol(const std::string& URL,
+                                   std::string& protocol,
+                                   std::string& dataglom)
 {
   // match 0 entire url
   // match 1 protocol
   // match 2 dataglom following protocol://
-  kwsys::RegularExpression urlRe( VTK_URL_PROTOCOL_REGEX );
+  kwsys::RegularExpression urlRe(VTK_URL_PROTOCOL_REGEX);
 
-  if ( ! urlRe.find( URL ) ) return false;
+  if (!urlRe.find(URL))
+    return false;
 
-  protocol = urlRe.match( 1 );
-  dataglom = urlRe.match( 2 );
+  protocol = urlRe.match(1);
+  dataglom = urlRe.match(2);
 
   return true;
 }
 
 // ----------------------------------------------------------------------
-bool SystemTools::ParseURL( const std::string& URL,
-                            std::string& protocol,
-                            std::string& username,
-                            std::string& password,
-                            std::string& hostname,
-                            std::string& dataport,
-                            std::string& database )
+bool SystemTools::ParseURL(const std::string& URL, std::string& protocol,
+                           std::string& username, std::string& password,
+                           std::string& hostname, std::string& dataport,
+                           std::string& database)
 {
-  kwsys::RegularExpression urlRe( VTK_URL_REGEX );
-  if ( ! urlRe.find( URL ) ) return false;
+  kwsys::RegularExpression urlRe(VTK_URL_REGEX);
+  if (!urlRe.find(URL))
+    return false;
 
   // match 0 URL
   // match 1 protocol
@@ -5479,12 +4756,12 @@ bool SystemTools::ParseURL( const std::string& URL,
   // match 8 dataport
   // match 9 database name
 
-  protocol = urlRe.match( 1 );
-  username = urlRe.match( 3 );
-  password = urlRe.match( 5 );
-  hostname = urlRe.match( 6 );
-  dataport = urlRe.match( 8 );
-  database = urlRe.match( 9 );
+  protocol = urlRe.match(1);
+  username = urlRe.match(3);
+  password = urlRe.match(5);
+  hostname = urlRe.match(6);
+  dataport = urlRe.match(8);
+  database = urlRe.match(9);
 
   return true;
 }
@@ -5493,13 +4770,13 @@ bool SystemTools::ParseURL( const std::string& URL,
 // These must NOT be initialized.  Default initialization to zero is
 // necessary.
 static unsigned int SystemToolsManagerCount;
-SystemToolsTranslationMap *SystemTools::TranslationMap;
+SystemToolsTranslationMap* SystemTools::TranslationMap;
 #ifdef _WIN32
-SystemToolsPathCaseMap *SystemTools::PathCaseMap;
-SystemToolsEnvMap *SystemTools::EnvMap;
+SystemToolsPathCaseMap* SystemTools::PathCaseMap;
+SystemToolsEnvMap* SystemTools::EnvMap;
 #endif
 #ifdef __CYGWIN__
-SystemToolsTranslationMap *SystemTools::Cyg2Win32Map;
+SystemToolsTranslationMap* SystemTools::Cyg2Win32Map;
 #endif
 
 // SystemToolsManager manages the SystemTools singleton.
@@ -5510,24 +4787,22 @@ SystemToolsTranslationMap *SystemTools::Cyg2Win32Map;
 
 SystemToolsManager::SystemToolsManager()
 {
-  if(++SystemToolsManagerCount == 1)
-    {
+  if (++SystemToolsManagerCount == 1) {
     SystemTools::ClassInitialize();
-    }
+  }
 }
 
 SystemToolsManager::~SystemToolsManager()
 {
-  if(--SystemToolsManagerCount == 0)
-    {
+  if (--SystemToolsManagerCount == 0) {
     SystemTools::ClassFinalize();
-    }
+  }
 }
 
 #if defined(__VMS)
 // On VMS we configure the run time C library to be more UNIX like.
 // http://h71000.www7.hp.com/doc/732final/5763/5763pro_004.html
-extern "C" int decc$feature_get_index(char *name);
+extern "C" int decc$feature_get_index(char* name);
 extern "C" int decc$feature_set_value(int index, int mode, int value);
 static int SetVMSFeature(char* name, int value)
 {
@@ -5553,9 +4828,9 @@ void SystemTools::ClassInitialize()
   SystemTools::Cyg2Win32Map = new SystemToolsTranslationMap;
 #endif
 
-  // Add some special translation paths for unix.  These are not added
-  // for windows because drive letters need to be maintained.  Also,
-  // there are not sym-links and mount points on windows anyway.
+// Add some special translation paths for unix.  These are not added
+// for windows because drive letters need to be maintained.  Also,
+// there are not sym-links and mount points on windows anyway.
 #if !defined(_WIN32) || defined(__CYGWIN__)
   // The tmp path is frequently a logical path so always keep it:
   SystemTools::AddKeepPath("/tmp/");
@@ -5563,11 +4838,9 @@ void SystemTools::ClassInitialize()
   // If the current working directory is a logical path then keep the
   // logical name.
   std::string pwd_str;
-  if(SystemTools::GetEnv("PWD", pwd_str))
-    {
+  if (SystemTools::GetEnv("PWD", pwd_str)) {
     char buf[2048];
-    if(const char* cwd = Getcwd(buf, 2048))
-      {
+    if (const char* cwd = Getcwd(buf, 2048)) {
       // The current working directory may be a logical path.  Find
       // the shortest logical path that still produces the correct
       // physical path.
@@ -5578,8 +4851,7 @@ void SystemTools::ClassInitialize()
       std::string cwd_str = cwd;
       std::string pwd_path;
       Realpath(pwd_str.c_str(), pwd_path);
-      while(cwd_str == pwd_path && cwd_str != pwd_str)
-        {
+      while (cwd_str == pwd_path && cwd_str != pwd_str) {
         // The current pair of paths is a working logical mapping.
         cwd_changed = cwd_str;
         pwd_changed = pwd_str;
@@ -5589,16 +4861,14 @@ void SystemTools::ClassInitialize()
         pwd_str = SystemTools::GetFilenamePath(pwd_str);
         cwd_str = SystemTools::GetFilenamePath(cwd_str);
         Realpath(pwd_str.c_str(), pwd_path);
-        }
+      }
 
       // Add the translation to keep the logical path name.
-      if(!cwd_changed.empty() && !pwd_changed.empty())
-        {
-        SystemTools::AddTranslationPath(cwd_changed,
-                                        pwd_changed);
-        }
+      if (!cwd_changed.empty() && !pwd_changed.empty()) {
+        SystemTools::AddTranslationPath(cwd_changed, pwd_changed);
       }
     }
+  }
 #endif
 }
 
@@ -5614,15 +4884,13 @@ void SystemTools::ClassFinalize()
 #endif
 }
 
-
 } // namespace KWSYS_NAMESPACE
 
 #if defined(_MSC_VER) && defined(_DEBUG)
-# include <crtdbg.h>
-# include <stdio.h>
-# include <stdlib.h>
-namespace KWSYS_NAMESPACE
-{
+#include <crtdbg.h>
+#include <stdio.h>
+#include <stdlib.h>
+namespace KWSYS_NAMESPACE {
 
 static int SystemToolsDebugReport(int, char* message, int*)
 {
@@ -5634,16 +4902,16 @@ static int SystemToolsDebugReport(int, char* message, int*)
 void SystemTools::EnableMSVCDebugHook()
 {
   if (SystemTools::HasEnv("DART_TEST_FROM_DART") ||
-      SystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST"))
-    {
+      SystemTools::HasEnv("DASHBOARD_TEST_FROM_CTEST")) {
     _CrtSetReportHook(SystemToolsDebugReport);
-    }
+  }
 }
 
 } // namespace KWSYS_NAMESPACE
 #else
-namespace KWSYS_NAMESPACE
+namespace KWSYS_NAMESPACE {
+void SystemTools::EnableMSVCDebugHook()
 {
-void SystemTools::EnableMSVCDebugHook() {}
+}
 } // namespace KWSYS_NAMESPACE
 #endif
diff --git a/Source/kwsys/SystemTools.hxx.in b/Source/kwsys/SystemTools.hxx.in
index 5849145..f3d06fe 100644
--- a/Source/kwsys/SystemTools.hxx.in
+++ b/Source/kwsys/SystemTools.hxx.in
@@ -1,29 +1,20 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _SystemTools_hxx
 #define @KWSYS_NAMESPACE at _SystemTools_hxx
 
 #include <@KWSYS_NAMESPACE@/Configure.hxx>
 
 #include <iosfwd>
+#include <map>
 #include <string>
 #include <vector>
-#include <map>
 
 #include <@KWSYS_NAMESPACE@/String.hxx>
 
 #include <sys/types.h>
 #if !defined(_WIN32) || defined(__CYGWIN__)
-# include <unistd.h> // For access permissions for use with access()
+#include <unistd.h> // For access permissions for use with access()
 #endif
 
 // Required for va_list
@@ -36,20 +27,18 @@
 // after stdarg.h does not solve things because we do not have control over
 // what the user does. This hack solves this problem by moving va_list to our
 // own namespace that is local for kwsys.
-namespace std {} // Required for platforms that do not have std namespace
-namespace @KWSYS_NAMESPACE at _VA_LIST
-{
-  using namespace std;
-  typedef va_list hack_va_list;
+namespace std {
+} // Required for platforms that do not have std namespace
+namespace @KWSYS_NAMESPACE at _VA_LIST {
+using namespace std;
+typedef va_list hack_va_list;
 }
-namespace @KWSYS_NAMESPACE@
-{
-  typedef @KWSYS_NAMESPACE at _VA_LIST::hack_va_list va_list;
+namespace @KWSYS_NAMESPACE@ {
+typedef @KWSYS_NAMESPACE at _VA_LIST::hack_va_list va_list;
 }
 #endif // va_list
 
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 
 class SystemToolsTranslationMap;
 class SystemToolsPathCaseMap;
@@ -76,17 +65,17 @@ static SystemToolsManager SystemToolsManagerInstance;
 // combined using the | operator.
 typedef int TestFilePermissions;
 #if defined(_WIN32) && !defined(__CYGWIN__)
-  // On Windows (VC and Borland), no system header defines these constants...
-  static const TestFilePermissions TEST_FILE_OK = 0;
-  static const TestFilePermissions TEST_FILE_READ = 4;
-  static const TestFilePermissions TEST_FILE_WRITE = 2;
-  static const TestFilePermissions TEST_FILE_EXECUTE = 1;
+// On Windows (VC and Borland), no system header defines these constants...
+static const TestFilePermissions TEST_FILE_OK = 0;
+static const TestFilePermissions TEST_FILE_READ = 4;
+static const TestFilePermissions TEST_FILE_WRITE = 2;
+static const TestFilePermissions TEST_FILE_EXECUTE = 1;
 #else
-  // Standard POSIX constants
-  static const TestFilePermissions TEST_FILE_OK = F_OK;
-  static const TestFilePermissions TEST_FILE_READ = R_OK;
-  static const TestFilePermissions TEST_FILE_WRITE = W_OK;
-  static const TestFilePermissions TEST_FILE_EXECUTE = X_OK;
+// Standard POSIX constants
+static const TestFilePermissions TEST_FILE_OK = F_OK;
+static const TestFilePermissions TEST_FILE_READ = R_OK;
+static const TestFilePermissions TEST_FILE_WRITE = W_OK;
+static const TestFilePermissions TEST_FILE_EXECUTE = X_OK;
 #endif
 
 /** \class SystemTools
@@ -95,7 +84,6 @@ typedef int TestFilePermissions;
 class @KWSYS_NAMESPACE at _EXPORT SystemTools
 {
 public:
-
   /** -----------------------------------------------------------------
    *               String Manipulation Routines
    *  -----------------------------------------------------------------
@@ -118,11 +106,9 @@ public:
   /**
    * Replace replace all occurences of the string in the source string.
    */
-  static void ReplaceString(std::string& source,
-                            const char* replace,
+  static void ReplaceString(std::string& source, const char* replace,
                             const char* with);
-  static void ReplaceString(std::string& source,
-                            const std::string& replace,
+  static void ReplaceString(std::string& source, const std::string& replace,
                             const std::string& with);
 
   /**
@@ -162,7 +148,7 @@ public:
    * Remove some characters from a string.
    * Return a pointer to the new resulting string (allocated with 'new')
    */
-  static char* RemoveChars(const char* str, const char *toremove);
+  static char* RemoveChars(const char* str, const char* toremove);
 
   /**
    * Remove remove all but 0->9, A->F characters from a string.
@@ -174,7 +160,8 @@ public:
    * Replace some characters by another character in a string (in-place)
    * Return a pointer to string
    */
-  static char* ReplaceChars(char* str, const char *toreplace,char replacement);
+  static char* ReplaceChars(char* str, const char* toreplace,
+                            char replacement);
 
   /**
    * Returns true if str1 starts (respectively ends) with str2
@@ -200,41 +187,42 @@ public:
    * Return the string cropped to a given length by removing chars in the
    * center of the string and replacing them with an ellipsis (...)
    */
-  static std::string CropString(const std::string&,size_t max_len);
+  static std::string CropString(const std::string&, size_t max_len);
 
   /** split a path by separator into an array of strings, default is /.
       If isPath is true then the string is treated like a path and if
       s starts with a / then the first element of the returned array will
       be /, so /foo/bar will be [/, foo, bar]
   */
-  static std::vector<String> SplitString(const std::string& s, char separator = '/',
-                                               bool isPath = false);
+  static std::vector<String> SplitString(const std::string& s,
+                                         char separator = '/',
+                                         bool isPath = false);
   /**
    * Perform a case-independent string comparison
    */
-  static int Strucmp(const char *s1, const char *s2);
+  static int Strucmp(const char* s1, const char* s2);
 
   /**
    * Convert a string in __DATE__ or __TIMESTAMP__ format into a time_t.
    * Return false on error, true on success
    */
-  static bool ConvertDateMacroString(const char *str, time_t *tmt);
-  static bool ConvertTimeStampMacroString(const char *str, time_t *tmt);
+  static bool ConvertDateMacroString(const char* str, time_t* tmt);
+  static bool ConvertTimeStampMacroString(const char* str, time_t* tmt);
 
   /**
    * Split a string on its newlines into multiple lines
    * Return false only if the last line stored had no newline
    */
   static bool Split(const std::string& s, std::vector<std::string>& l);
-  static bool Split(const std::string& s, std::vector<std::string>& l, char separator);
+  static bool Split(const std::string& s, std::vector<std::string>& l,
+                    char separator);
 
   /**
    * Return string with space added between capitalized words
    * (i.e. EatMyShorts becomes Eat My Shorts )
    * (note that IEatShorts becomes IEat Shorts)
    */
-  static std::string AddSpaceBetweenCapitalizedWords(
-    const std::string&);
+  static std::string AddSpaceBetweenCapitalizedWords(const std::string&);
 
   /**
    * Append two or more strings and produce new one.
@@ -242,10 +230,9 @@ public:
    * with 'new'.
    * Return 0 if inputs are empty or there was an error
    */
-  static char* AppendStrings(
-    const char* str1, const char* str2);
-  static char* AppendStrings(
-    const char* str1, const char* str2, const char* str3);
+  static char* AppendStrings(const char* str1, const char* str2);
+  static char* AppendStrings(const char* str1, const char* str2,
+                             const char* str3);
 
   /**
    * Estimate the length of the string that will be produced
@@ -256,13 +243,13 @@ public:
    * you will not be able to use this 'ap' anymore from the beginning.
    * It's up to you to call va_end though.
    */
-  static int EstimateFormatLength(const char *format, va_list ap);
+  static int EstimateFormatLength(const char* format, va_list ap);
 
   /**
    * Escape specific characters in 'str'.
    */
-  static std::string EscapeChars(
-    const char *str, const char *chars_to_escape, char escape_char = '\\');
+  static std::string EscapeChars(const char* str, const char* chars_to_escape,
+                                 char escape_char = '\\');
 
   /** -----------------------------------------------------------------
    *               Filename Manipulation Routines
@@ -338,13 +325,13 @@ public:
   static bool TestFileAccess(const std::string& filename,
                              TestFilePermissions permissions);
 
-  /**
-   * Converts Cygwin path to Win32 path. Uses dictionary container for
-   * caching and calls to cygwin_conv_to_win32_path from Cygwin dll
-   * for actual translation.  Returns true on success, else false.
-   */
+/**
+ * Converts Cygwin path to Win32 path. Uses dictionary container for
+ * caching and calls to cygwin_conv_to_win32_path from Cygwin dll
+ * for actual translation.  Returns true on success, else false.
+ */
 #ifdef __CYGWIN__
-  static bool PathCygwinToWin32(const char *path, char *win32_path);
+  static bool PathCygwinToWin32(const char* path, char* win32_path);
 #endif
 
   /**
@@ -363,8 +350,7 @@ public:
    *  When true is returned, result has -1, 0, +1 for
    *  f1 older, same, or newer than f2.
    */
-  static bool FileTimeCompare(const std::string& f1,
-                              const std::string& f2,
+  static bool FileTimeCompare(const std::string& f1, const std::string& f2,
                               int* result);
 
   /**
@@ -388,10 +374,8 @@ public:
    * part, the empty string is returned.
    */
   static std::string GetProgramPath(const std::string&);
-  static bool SplitProgramPath(const std::string& in_name,
-                               std::string& dir,
-                               std::string& file,
-                               bool errorReport = true);
+  static bool SplitProgramPath(const std::string& in_name, std::string& dir,
+                               std::string& file, bool errorReport = true);
 
   /**
    *  Given argv[0] for a unix program find the full path to a running
@@ -405,10 +389,8 @@ public:
    *  buildDir is a possibly null path to the build directory.
    *  installPrefix is a possibly null pointer to the install directory.
    */
-  static bool FindProgramPath(const char* argv0,
-                              std::string& pathOut,
-                              std::string& errorMsg,
-                              const char* exeName = 0,
+  static bool FindProgramPath(const char* argv0, std::string& pathOut,
+                              std::string& errorMsg, const char* exeName = 0,
                               const char* buildDir = 0,
                               const char* installPrefix = 0);
 
@@ -420,9 +402,9 @@ public:
    */
   static std::string CollapseFullPath(const std::string& in_relative);
   static std::string CollapseFullPath(const std::string& in_relative,
-                                            const char* in_base);
+                                      const char* in_base);
   static std::string CollapseFullPath(const std::string& in_relative,
-                                            const std::string& in_base);
+                                      const std::string& in_base);
 
   /**
    * Get the real path for a given path, removing all symlinks.  In
@@ -432,7 +414,7 @@ public:
    * contains error description.
    */
   static std::string GetRealPath(const std::string& path,
-                                       std::string* errorMessage = 0);
+                                 std::string* errorMessage = 0);
 
   /**
    * Split a path name into its root component and the rest of the
@@ -450,7 +432,7 @@ public:
    * given.
    */
   static const char* SplitPathRootComponent(const std::string& p,
-                                            std::string* root=0);
+                                            std::string* root = 0);
 
   /**
    * Split a path name into its basic components.  The first component
@@ -470,18 +452,15 @@ public:
    * Join components of a path name into a single string.  See
    * SplitPath for the format of the components.
    */
-  static std::string JoinPath(
-    const std::vector<std::string>& components);
-  static std::string JoinPath(
-    std::vector<std::string>::const_iterator first,
-    std::vector<std::string>::const_iterator last);
+  static std::string JoinPath(const std::vector<std::string>& components);
+  static std::string JoinPath(std::vector<std::string>::const_iterator first,
+                              std::vector<std::string>::const_iterator last);
 
   /**
    * Compare a path or components of a path.
    */
   static bool ComparePath(const std::string& c1, const std::string& c2);
 
-
   /**
    * Return path of a full filename (no trailing slashes)
    */
@@ -495,9 +474,8 @@ public:
   /**
    * Split a program from its arguments and handle spaces in the paths
    */
-  static void SplitProgramFromArgs(
-    const std::string& path,
-    std::string& program, std::string& args);
+  static void SplitProgramFromArgs(const std::string& path,
+                                   std::string& program, std::string& args);
 
   /**
    * Return longest file extension of a full filename (dot included)
@@ -507,20 +485,17 @@ public:
   /**
    * Return shortest file extension of a full filename (dot included)
    */
-  static std::string GetFilenameLastExtension(
-    const std::string& filename);
+  static std::string GetFilenameLastExtension(const std::string& filename);
 
   /**
    * Return file name without extension of a full filename
    */
-  static std::string GetFilenameWithoutExtension(
-    const std::string&);
+  static std::string GetFilenameWithoutExtension(const std::string&);
 
   /**
    * Return file name without its last (shortest) extension
    */
-  static std::string GetFilenameWithoutLastExtension(
-    const std::string&);
+  static std::string GetFilenameWithoutLastExtension(const std::string&);
 
   /**
    * Return whether the path represents a full path (not relative)
@@ -541,10 +516,8 @@ public:
    * end-of-file was reached. If the has_newline argument is specified, it will
    * be true when the line read had a newline character.
    */
-  static bool GetLineFromStream(std::istream& istr,
-                                std::string& line,
-                                bool* has_newline=0,
-                                long sizeLimit=-1);
+  static bool GetLineFromStream(std::istream& istr, std::string& line,
+                                bool* has_newline = 0, long sizeLimit = -1);
 
   /**
    * Get the parent directory of the directory or file
@@ -554,7 +527,8 @@ public:
   /**
    * Check if the given file or directory is in subdirectory of dir
    */
-  static bool IsSubDirectory(const std::string& fileOrDir, const std::string& dir);
+  static bool IsSubDirectory(const std::string& fileOrDir,
+                             const std::string& dir);
 
   /** -----------------------------------------------------------------
    *               File Manipulation Routines
@@ -584,7 +558,8 @@ public:
   /**
    * Compare the contents of two files.  Return true if different
    */
-  static bool FilesDiffer(const std::string& source, const std::string& destination);
+  static bool FilesDiffer(const std::string& source,
+                          const std::string& destination);
 
   /**
    * Return true if the two files are the same file
@@ -594,15 +569,16 @@ public:
   /**
    * Copy a file.
    */
-  static bool CopyFileAlways(const std::string& source, const std::string& destination);
+  static bool CopyFileAlways(const std::string& source,
+                             const std::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 std::string& source, const std::string& destination,
-                        bool always = true);
+  static bool CopyAFile(const std::string& source,
+                        const std::string& destination, bool always = true);
 
   /**
    * Copy content directory to another directory with all files and
@@ -610,7 +586,8 @@ public:
    * always copied.  If it is false, only files that have changed or
    * are new are copied.
    */
-  static bool CopyADirectory(const std::string& source, const std::string& destination,
+  static bool CopyADirectory(const std::string& source,
+                             const std::string& destination,
                              bool always = true);
 
   /**
@@ -633,8 +610,7 @@ public:
    */
   static std::string FindFile(
     const std::string& name,
-    const std::vector<std::string>& path =
-    std::vector<std::string>(),
+    const std::vector<std::string>& path = std::vector<std::string>(),
     bool no_system_path = false);
 
   /**
@@ -642,8 +618,7 @@ public:
    */
   static std::string FindDirectory(
     const std::string& name,
-    const std::vector<std::string>& path =
-    std::vector<std::string>(),
+    const std::vector<std::string>& path = std::vector<std::string>(),
     bool no_system_path = false);
 
   /**
@@ -651,26 +626,22 @@ public:
    */
   static std::string FindProgram(
     const char* name,
-    const std::vector<std::string>& path =
-    std::vector<std::string>(),
+    const std::vector<std::string>& path = std::vector<std::string>(),
     bool no_system_path = false);
   static std::string FindProgram(
     const std::string& name,
-    const std::vector<std::string>& path =
-    std::vector<std::string>(),
+    const std::vector<std::string>& path = std::vector<std::string>(),
     bool no_system_path = false);
   static std::string FindProgram(
     const std::vector<std::string>& names,
-    const std::vector<std::string>& path =
-    std::vector<std::string>(),
+    const std::vector<std::string>& path = std::vector<std::string>(),
     bool no_system_path = false);
 
   /**
    * Find a library in the system PATH, with optional extra paths
    */
-  static std::string FindLibrary(
-    const std::string& name,
-    const std::vector<std::string>& path);
+  static std::string FindLibrary(const std::string& name,
+                                 const std::vector<std::string>& path);
 
   /**
    * Return true if the file is a directory
@@ -685,8 +656,8 @@ public:
   /**
    * Return true if the file has a given signature (first set of bytes)
    */
-  static bool FileHasSignature(
-    const char* filename, const char *signature, long offset = 0);
+  static bool FileHasSignature(const char* filename, const char* signature,
+                               long offset = 0);
 
   /**
    * Attempt to detect and return the type of a file.
@@ -703,16 +674,16 @@ public:
     FileTypeBinary,
     FileTypeText
   };
-  static SystemTools::FileTypeEnum DetectFileType(
-    const char* filename,
-    unsigned long length = 256,
-    double percent_bin = 0.05);
+  static SystemTools::FileTypeEnum DetectFileType(const char* filename,
+                                                  unsigned long length = 256,
+                                                  double percent_bin = 0.05);
 
   /**
    * Create a symbolic link if the platform supports it.  Returns whether
    * creation succeeded.
    */
-  static bool CreateSymlink(const std::string& origName, const std::string& newName);
+  static bool CreateSymlink(const std::string& origName,
+                            const std::string& newName);
 
   /**
    * Read the contents of a symbolic link.  Returns whether reading
@@ -735,8 +706,7 @@ public:
    * etc.
    * Return true if the file was found, false otherwise.
    */
-  static bool LocateFileInDir(const char *filename,
-                              const char *dir,
+  static bool LocateFileInDir(const char* filename, const char* dir,
                               std::string& filename_found,
                               int try_filename_dirs = 0);
 
@@ -748,7 +718,8 @@ public:
       /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 std::string RelativePath(const std::string& local, const std::string& remote);
+  static std::string RelativePath(const std::string& local,
+                                  const std::string& remote);
 
   /**
    * Return file's modified time
@@ -760,12 +731,12 @@ public:
    */
   static long int CreationTime(const std::string& filename);
 
-  /**
-   * Visual C++ does not define mode_t (note that Borland does, however).
-   */
-  #if defined( _MSC_VER )
+/**
+ * Visual C++ does not define mode_t (note that Borland does, however).
+ */
+#if defined(_MSC_VER)
   typedef unsigned short mode_t;
-  #endif
+#endif
 
   /**
    * Get and set permissions of the file.  If honor_umask is set, the umask
@@ -777,8 +748,10 @@ public:
    */
   static bool GetPermissions(const char* file, mode_t& mode);
   static bool GetPermissions(const std::string& file, mode_t& mode);
-  static bool SetPermissions(const char* file, mode_t mode, bool honor_umask = false);
-  static bool SetPermissions(const std::string& file, mode_t mode, bool honor_umask = false);
+  static bool SetPermissions(const char* file, mode_t mode,
+                             bool honor_umask = false);
+  static bool SetPermissions(const std::string& file, mode_t mode,
+                             bool honor_umask = false);
 
   /** -----------------------------------------------------------------
    *               Time Manipulation Routines
@@ -803,7 +776,12 @@ public:
    * registry values.  The default is to match the currently running
    * binary type.
    */
-  enum KeyWOW64 { KeyWOW64_Default, KeyWOW64_32, KeyWOW64_64 };
+  enum KeyWOW64
+  {
+    KeyWOW64_Default,
+    KeyWOW64_32,
+    KeyWOW64_64
+  };
 
   /**
    * Get a list of subkeys.
@@ -815,13 +793,14 @@ public:
   /**
    * Read a registry value
    */
-  static bool ReadRegistryValue(const std::string& key, std::string &value,
+  static bool ReadRegistryValue(const std::string& key, std::string& value,
                                 KeyWOW64 view = KeyWOW64_Default);
 
   /**
    * Write a registry value
    */
-  static bool WriteRegistryValue(const std::string& key, const std::string& value,
+  static bool WriteRegistryValue(const std::string& key,
+                                 const std::string& value,
                                  KeyWOW64 view = KeyWOW64_Default);
 
   /**
@@ -840,8 +819,7 @@ public:
    *  string vector passed in.  If env is set then the value
    *  of env will be used instead of PATH.
    */
-  static void GetPath(std::vector<std::string>& path,
-                      const char* env=0);
+  static void GetPath(std::vector<std::string>& path, const char* env = 0);
 
   /**
    * Read an environment variable
@@ -864,7 +842,7 @@ public:
   /**
    * Get current working directory CWD
    */
-  static std::string GetCurrentWorkingDirectory(bool collapse =true);
+  static std::string GetCurrentWorkingDirectory(bool collapse = true);
 
   /**
    * Change directory to the directory specified
@@ -893,7 +871,8 @@ public:
   /**
    * Add an entry in the path translation table.
    */
-  static void AddTranslationPath(const std::string& dir, const std::string& refdir);
+  static void AddTranslationPath(const std::string& dir,
+                                 const std::string& refdir);
 
   /**
    * If dir is different after CollapseFullPath is called,
@@ -904,7 +883,7 @@ public:
   /**
    * Update path by going through the Path Translation table;
    */
-  static void CheckTranslationPath(std::string & path);
+  static void CheckTranslationPath(std::string& path);
 
   /**
    * Delay the execution for a specified amount of time specified
@@ -929,9 +908,8 @@ public:
    * and fill protocol as appropriate.
    * Return false if the URL does not have the required form, true otherwise.
    */
-   static bool ParseURLProtocol( const std::string& URL,
-                                 std::string& protocol,
-                                 std::string& dataglom );
+  static bool ParseURLProtocol(const std::string& URL, std::string& protocol,
+                               std::string& dataglom);
 
   /**
    * Parse a string (a URL without protocol prefix) with the form:
@@ -940,13 +918,10 @@ public:
    * when values are found.
    * Return true if the string matches the format; false otherwise.
    */
-  static bool ParseURL( const std::string& URL,
-                        std::string& protocol,
-                        std::string& username,
-                        std::string& password,
-                        std::string& hostname,
-                        std::string& dataport,
-                        std::string& datapath );
+  static bool ParseURL(const std::string& URL, std::string& protocol,
+                       std::string& username, std::string& password,
+                       std::string& hostname, std::string& dataport,
+                       std::string& datapath);
 
 private:
   /**
@@ -963,17 +938,15 @@ private:
    * This method prevents warning on SGI
    */
   SystemToolsManager* GetSystemToolsManager()
-    {
+  {
     return &SystemToolsManagerInstance;
-    }
+  }
 
   /**
    * Actual implementation of ReplaceString.
    */
-  static void ReplaceString(std::string& source,
-                            const char* replace,
-                            size_t replaceSize,
-                            const std::string& with);
+  static void ReplaceString(std::string& source, const char* replace,
+                            size_t replaceSize, const std::string& with);
 
   /**
    * Actual implementation of FileIsFullPath.
@@ -986,8 +959,7 @@ private:
    */
   static std::string FindName(
     const std::string& name,
-    const std::vector<std::string>& path =
-    std::vector<std::string>(),
+    const std::vector<std::string>& path = std::vector<std::string>(),
     bool no_system_path = false);
 
   static const char* GetEnvImpl(const char* key);
@@ -996,13 +968,13 @@ private:
    * Path translation table from dir to refdir
    * Each time 'dir' will be found it will be replace by 'refdir'
    */
-  static SystemToolsTranslationMap *TranslationMap;
+  static SystemToolsTranslationMap* TranslationMap;
 #ifdef _WIN32
-  static SystemToolsPathCaseMap *PathCaseMap;
-  static SystemToolsEnvMap *EnvMap;
+  static SystemToolsPathCaseMap* PathCaseMap;
+  static SystemToolsEnvMap* EnvMap;
 #endif
 #ifdef __CYGWIN__
-  static SystemToolsTranslationMap *Cyg2Win32Map;
+  static SystemToolsTranslationMap* Cyg2Win32Map;
 #endif
   friend class SystemToolsManager;
 };
diff --git a/Source/kwsys/Terminal.c b/Source/kwsys/Terminal.c
index a8abb6c..c0b7f45 100644
--- a/Source/kwsys/Terminal.c
+++ b/Source/kwsys/Terminal.c
@@ -1,48 +1,39 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(Terminal.h)
 
 /* Work-around CMake dependency scanning limitation.  This must
    duplicate the above list of headers.  */
 #if 0
-# include "Terminal.h.in"
+#include "Terminal.h.in"
 #endif
 
 /*--------------------------------------------------------------------------*/
 /* Configure support for this platform.  */
 #if defined(_WIN32) || defined(__CYGWIN__)
-# define KWSYS_TERMINAL_SUPPORT_CONSOLE
+#define KWSYS_TERMINAL_SUPPORT_CONSOLE
 #endif
 #if !defined(_WIN32)
-# define KWSYS_TERMINAL_ISATTY_WORKS
+#define KWSYS_TERMINAL_ISATTY_WORKS
 #endif
 
 /*--------------------------------------------------------------------------*/
 /* Include needed system APIs.  */
 
+#include <stdarg.h> /* va_list */
 #include <stdlib.h> /* getenv */
 #include <string.h> /* strcmp */
-#include <stdarg.h> /* va_list */
 
 #if defined(KWSYS_TERMINAL_SUPPORT_CONSOLE)
-# include <windows.h> /* SetConsoleTextAttribute */
-# include <io.h>      /* _get_osfhandle */
+#include <io.h>      /* _get_osfhandle */
+#include <windows.h> /* SetConsoleTextAttribute */
 #endif
 
 #if defined(KWSYS_TERMINAL_ISATTY_WORKS)
-# include <unistd.h> /* isatty */
+#include <unistd.h> /* isatty */
 #else
-# include <sys/stat.h> /* fstat */
+#include <sys/stat.h> /* fstat */
 #endif
 
 /*--------------------------------------------------------------------------*/
@@ -53,8 +44,7 @@ static void kwsysTerminalSetVT100Color(FILE* stream, int color);
 static HANDLE kwsysTerminalGetStreamHandle(FILE* stream);
 static void kwsysTerminalSetConsoleColor(HANDLE hOut,
                                          CONSOLE_SCREEN_BUFFER_INFO* hOutInfo,
-                                         FILE* stream,
-                                         int color);
+                                         FILE* stream, int color);
 #endif
 
 /*--------------------------------------------------------------------------*/
@@ -68,39 +58,35 @@ void kwsysTerminal_cfprintf(int color, FILE* stream, const char* format, ...)
 #if defined(KWSYS_TERMINAL_SUPPORT_CONSOLE)
   CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
   HANDLE hOut = kwsysTerminalGetStreamHandle(stream);
-  if(GetConsoleScreenBufferInfo(hOut, &hOutInfo))
-    {
+  if (GetConsoleScreenBufferInfo(hOut, &hOutInfo)) {
     pipeIsConsole = 1;
     kwsysTerminalSetConsoleColor(hOut, &hOutInfo, stream, color);
-    }
+  }
 #endif
-  if(!pipeIsConsole && kwsysTerminalStreamIsVT100(stream,
-                                                  default_vt100, default_tty))
-    {
+  if (!pipeIsConsole &&
+      kwsysTerminalStreamIsVT100(stream, default_vt100, default_tty)) {
     pipeIsVT100 = 1;
     kwsysTerminalSetVT100Color(stream, color);
-    }
+  }
 
   /* Format the text into the stream.  */
   {
-  va_list var_args;
-  va_start(var_args, format);
-  vfprintf(stream, format, var_args);
-  va_end(var_args);
+    va_list var_args;
+    va_start(var_args, format);
+    vfprintf(stream, format, var_args);
+    va_end(var_args);
   }
 
-  /* Restore the normal color state for the stream.  */
+/* Restore the normal color state for the stream.  */
 #if defined(KWSYS_TERMINAL_SUPPORT_CONSOLE)
-  if(pipeIsConsole)
-    {
+  if (pipeIsConsole) {
     kwsysTerminalSetConsoleColor(hOut, &hOutInfo, stream,
                                  kwsysTerminal_Color_Normal);
-    }
+  }
 #endif
-  if(pipeIsVT100)
-    {
+  if (pipeIsVT100) {
     kwsysTerminalSetVT100Color(stream, kwsysTerminal_Color_Normal);
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
@@ -111,73 +97,70 @@ static int kwsysTerminalStreamIsNotInteractive(FILE* stream)
   /* The given stream is definitely not interactive if it is a regular
      file.  */
   struct stat stream_stat;
-  if(fstat(fileno(stream), &stream_stat) == 0)
-    {
-    if(stream_stat.st_mode & S_IFREG)
-      {
+  if (fstat(fileno(stream), &stream_stat) == 0) {
+    if (stream_stat.st_mode & S_IFREG) {
       return 1;
-      }
     }
+  }
   return 0;
 }
 #endif
 
 /*--------------------------------------------------------------------------*/
 /* List of terminal names known to support VT100 color escape sequences.  */
-static const char* kwsysTerminalVT100Names[] =
-{
-  "Eterm",
-  "ansi",
-  "color-xterm",
-  "con132x25",
-  "con132x30",
-  "con132x43",
-  "con132x60",
-  "con80x25",
-  "con80x28",
-  "con80x30",
-  "con80x43",
-  "con80x50",
-  "con80x60",
-  "cons25",
-  "console",
-  "cygwin",
-  "dtterm",
-  "eterm-color",
-  "gnome",
-  "gnome-256color",
-  "konsole",
-  "konsole-256color",
-  "kterm",
-  "linux",
-  "msys",
-  "linux-c",
-  "mach-color",
-  "mlterm",
-  "putty",
-  "putty-256color",
-  "rxvt",
-  "rxvt-256color",
-  "rxvt-cygwin",
-  "rxvt-cygwin-native",
-  "rxvt-unicode",
-  "rxvt-unicode-256color",
-  "screen",
-  "screen-256color",
-  "screen-256color-bce",
-  "screen-bce",
-  "screen-w",
-  "screen.linux",
-  "vt100",
-  "xterm",
-  "xterm-16color",
-  "xterm-256color",
-  "xterm-88color",
-  "xterm-color",
-  "xterm-debian",
-  "xterm-termite",
-  0
-};
+static const char* kwsysTerminalVT100Names[] = { "Eterm",
+                                                 "ansi",
+                                                 "color-xterm",
+                                                 "con132x25",
+                                                 "con132x30",
+                                                 "con132x43",
+                                                 "con132x60",
+                                                 "con80x25",
+                                                 "con80x28",
+                                                 "con80x30",
+                                                 "con80x43",
+                                                 "con80x50",
+                                                 "con80x60",
+                                                 "cons25",
+                                                 "console",
+                                                 "cygwin",
+                                                 "dtterm",
+                                                 "eterm-color",
+                                                 "gnome",
+                                                 "gnome-256color",
+                                                 "konsole",
+                                                 "konsole-256color",
+                                                 "kterm",
+                                                 "linux",
+                                                 "msys",
+                                                 "linux-c",
+                                                 "mach-color",
+                                                 "mlterm",
+                                                 "putty",
+                                                 "putty-256color",
+                                                 "rxvt",
+                                                 "rxvt-256color",
+                                                 "rxvt-cygwin",
+                                                 "rxvt-cygwin-native",
+                                                 "rxvt-unicode",
+                                                 "rxvt-unicode-256color",
+                                                 "screen",
+                                                 "screen-256color",
+                                                 "screen-256color-bce",
+                                                 "screen-bce",
+                                                 "screen-w",
+                                                 "screen.linux",
+                                                 "tmux",
+                                                 "tmux-256color",
+                                                 "vt100",
+                                                 "xterm",
+                                                 "xterm-16color",
+                                                 "xterm-256color",
+                                                 "xterm-88color",
+                                                 "xterm-color",
+                                                 "xterm-debian",
+                                                 "xterm-termite",
+                                                 0 };
 
 /*--------------------------------------------------------------------------*/
 /* Detect whether a stream is displayed in a VT100-compatible terminal.  */
@@ -186,10 +169,10 @@ static int kwsysTerminalStreamIsVT100(FILE* stream, int default_vt100,
 {
   /* Force color according to http://bixense.com/clicolors/ convention.  */
   {
-  const char* clicolor_force = getenv("CLICOLOR_FORCE");
-  if (clicolor_force && *clicolor_force && strcmp(clicolor_force, "0") != 0)
-    {
-    return 1;
+    const char* clicolor_force = getenv("CLICOLOR_FORCE");
+    if (clicolor_force && *clicolor_force &&
+        strcmp(clicolor_force, "0") != 0) {
+      return 1;
     }
   }
 
@@ -197,38 +180,34 @@ static int kwsysTerminalStreamIsVT100(FILE* stream, int default_vt100,
      seem to claim the TERM is xterm even though they do not support
      VT100 escapes.  */
   {
-  const char* emacs = getenv("EMACS");
-  if(emacs && *emacs == 't')
-    {
-    return 0;
+    const char* emacs = getenv("EMACS");
+    if (emacs && *emacs == 't') {
+      return 0;
     }
   }
 
   /* Check for a valid terminal.  */
-  if(!default_vt100)
-    {
+  if (!default_vt100) {
     const char** t = 0;
     const char* term = getenv("TERM");
-    if(term)
-      {
-      for(t = kwsysTerminalVT100Names; *t && strcmp(term, *t) != 0; ++t) {}
+    if (term) {
+      for (t = kwsysTerminalVT100Names; *t && strcmp(term, *t) != 0; ++t) {
       }
-    if(!(t && *t))
-      {
+    }
+    if (!(t && *t)) {
       return 0;
-      }
     }
+  }
 
 #if defined(KWSYS_TERMINAL_ISATTY_WORKS)
   /* Make sure the stream is a tty. */
   (void)default_tty;
-  return isatty(fileno(stream))? 1:0;
+  return isatty(fileno(stream)) ? 1 : 0;
 #else
   /* Check for cases in which the stream is definitely not a tty.  */
-  if(kwsysTerminalStreamIsNotInteractive(stream))
-    {
+  if (kwsysTerminalStreamIsNotInteractive(stream)) {
     return 0;
-    }
+  }
 
   /* Use the provided default for whether this is a tty.  */
   return default_tty;
@@ -237,40 +216,38 @@ static int kwsysTerminalStreamIsVT100(FILE* stream, int default_vt100,
 
 /*--------------------------------------------------------------------------*/
 /* VT100 escape sequence strings.  */
-#define KWSYS_TERMINAL_VT100_NORMAL              "\33[0m"
-#define KWSYS_TERMINAL_VT100_BOLD                "\33[1m"
-#define KWSYS_TERMINAL_VT100_UNDERLINE           "\33[4m"
-#define KWSYS_TERMINAL_VT100_BLINK               "\33[5m"
-#define KWSYS_TERMINAL_VT100_INVERSE             "\33[7m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_BLACK    "\33[30m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_RED      "\33[31m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_GREEN    "\33[32m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_YELLOW   "\33[33m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_BLUE     "\33[34m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_MAGENTA  "\33[35m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_CYAN     "\33[36m"
-#define KWSYS_TERMINAL_VT100_FOREGROUND_WHITE    "\33[37m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_BLACK    "\33[40m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_RED      "\33[41m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_GREEN    "\33[42m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_YELLOW   "\33[43m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_BLUE     "\33[44m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_MAGENTA  "\33[45m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_CYAN     "\33[46m"
-#define KWSYS_TERMINAL_VT100_BACKGROUND_WHITE    "\33[47m"
+#define KWSYS_TERMINAL_VT100_NORMAL "\33[0m"
+#define KWSYS_TERMINAL_VT100_BOLD "\33[1m"
+#define KWSYS_TERMINAL_VT100_UNDERLINE "\33[4m"
+#define KWSYS_TERMINAL_VT100_BLINK "\33[5m"
+#define KWSYS_TERMINAL_VT100_INVERSE "\33[7m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_BLACK "\33[30m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_RED "\33[31m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_GREEN "\33[32m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_YELLOW "\33[33m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_BLUE "\33[34m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_MAGENTA "\33[35m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_CYAN "\33[36m"
+#define KWSYS_TERMINAL_VT100_FOREGROUND_WHITE "\33[37m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_BLACK "\33[40m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_RED "\33[41m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_GREEN "\33[42m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_YELLOW "\33[43m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_BLUE "\33[44m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_MAGENTA "\33[45m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_CYAN "\33[46m"
+#define KWSYS_TERMINAL_VT100_BACKGROUND_WHITE "\33[47m"
 
 /*--------------------------------------------------------------------------*/
 /* Write VT100 escape sequences to the stream for the given color.  */
 static void kwsysTerminalSetVT100Color(FILE* stream, int color)
 {
-  if(color == kwsysTerminal_Color_Normal)
-    {
+  if (color == kwsysTerminal_Color_Normal) {
     fprintf(stream, KWSYS_TERMINAL_VT100_NORMAL);
     return;
-    }
+  }
 
-  switch(color & kwsysTerminal_Color_ForegroundMask)
-    {
+  switch (color & kwsysTerminal_Color_ForegroundMask) {
     case kwsysTerminal_Color_Normal:
       fprintf(stream, KWSYS_TERMINAL_VT100_NORMAL);
       break;
@@ -298,9 +275,8 @@ static void kwsysTerminalSetVT100Color(FILE* stream, int color)
     case kwsysTerminal_Color_ForegroundWhite:
       fprintf(stream, KWSYS_TERMINAL_VT100_FOREGROUND_WHITE);
       break;
-    }
-  switch(color & kwsysTerminal_Color_BackgroundMask)
-    {
+  }
+  switch (color & kwsysTerminal_Color_BackgroundMask) {
     case kwsysTerminal_Color_BackgroundBlack:
       fprintf(stream, KWSYS_TERMINAL_VT100_BACKGROUND_BLACK);
       break;
@@ -325,19 +301,18 @@ static void kwsysTerminalSetVT100Color(FILE* stream, int color)
     case kwsysTerminal_Color_BackgroundWhite:
       fprintf(stream, KWSYS_TERMINAL_VT100_BACKGROUND_WHITE);
       break;
-    }
-  if(color & kwsysTerminal_Color_ForegroundBold)
-    {
+  }
+  if (color & kwsysTerminal_Color_ForegroundBold) {
     fprintf(stream, KWSYS_TERMINAL_VT100_BOLD);
-    }
+  }
 }
 
 /*--------------------------------------------------------------------------*/
 #if defined(KWSYS_TERMINAL_SUPPORT_CONSOLE)
 
-# define KWSYS_TERMINAL_MASK_FOREGROUND \
+#define KWSYS_TERMINAL_MASK_FOREGROUND                                        \
   (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)
-# define KWSYS_TERMINAL_MASK_BACKGROUND \
+#define KWSYS_TERMINAL_MASK_BACKGROUND                                        \
   (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY)
 
 /* Get the Windows handle for a FILE stream.  */
@@ -346,19 +321,16 @@ static HANDLE kwsysTerminalGetStreamHandle(FILE* stream)
   /* Get the C-library file descriptor from the stream.  */
   int fd = fileno(stream);
 
-# if defined(__CYGWIN__)
+#if defined(__CYGWIN__)
   /* Cygwin seems to have an extra pipe level.  If the file descriptor
      corresponds to stdout or stderr then obtain the matching windows
      handle directly.  */
-  if(fd == fileno(stdout))
-    {
+  if (fd == fileno(stdout)) {
     return GetStdHandle(STD_OUTPUT_HANDLE);
-    }
-  else if(fd == fileno(stderr))
-    {
+  } else if (fd == fileno(stderr)) {
     return GetStdHandle(STD_ERROR_HANDLE);
-    }
-# endif
+  }
+#endif
 
   /* Get the underlying Windows handle for the descriptor.  */
   return (HANDLE)_get_osfhandle(fd);
@@ -367,12 +339,10 @@ static HANDLE kwsysTerminalGetStreamHandle(FILE* stream)
 /* Set color attributes in a Windows console.  */
 static void kwsysTerminalSetConsoleColor(HANDLE hOut,
                                          CONSOLE_SCREEN_BUFFER_INFO* hOutInfo,
-                                         FILE* stream,
-                                         int color)
+                                         FILE* stream, int color)
 {
   WORD attributes = 0;
-  switch(color & kwsysTerminal_Color_ForegroundMask)
-    {
+  switch (color & kwsysTerminal_Color_ForegroundMask) {
     case kwsysTerminal_Color_Normal:
       attributes |= hOutInfo->wAttributes & KWSYS_TERMINAL_MASK_FOREGROUND;
       break;
@@ -400,9 +370,8 @@ static void kwsysTerminalSetConsoleColor(HANDLE hOut,
     case kwsysTerminal_Color_ForegroundWhite:
       attributes |= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
       break;
-    }
-  switch(color & kwsysTerminal_Color_BackgroundMask)
-    {
+  }
+  switch (color & kwsysTerminal_Color_BackgroundMask) {
     case kwsysTerminal_Color_Normal:
       attributes |= hOutInfo->wAttributes & KWSYS_TERMINAL_MASK_BACKGROUND;
       break;
@@ -430,15 +399,13 @@ static void kwsysTerminalSetConsoleColor(HANDLE hOut,
     case kwsysTerminal_Color_BackgroundWhite:
       attributes |= BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;
       break;
-    }
-  if(color & kwsysTerminal_Color_ForegroundBold)
-    {
+  }
+  if (color & kwsysTerminal_Color_ForegroundBold) {
     attributes |= FOREGROUND_INTENSITY;
-    }
-  if(color & kwsysTerminal_Color_BackgroundBold)
-    {
+  }
+  if (color & kwsysTerminal_Color_BackgroundBold) {
     attributes |= BACKGROUND_INTENSITY;
-    }
+  }
   fflush(stream);
   SetConsoleTextAttribute(hOut, attributes);
 }
diff --git a/Source/kwsys/Terminal.h.in b/Source/kwsys/Terminal.h.in
index 108cba0..5d29830 100644
--- a/Source/kwsys/Terminal.h.in
+++ b/Source/kwsys/Terminal.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _Terminal_h
 #define @KWSYS_NAMESPACE at _Terminal_h
 
@@ -21,41 +12,61 @@
    not visible to user code.  Use kwsysHeaderDump.pl to reproduce
    these macros after making changes to the interface.  */
 #if !defined(KWSYS_NAMESPACE)
-# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
-# define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
+#define kwsys_ns(x) @KWSYS_NAMESPACE@##x
+#define kwsysEXPORT @KWSYS_NAMESPACE at _EXPORT
 #endif
 #if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-# define kwsysTerminal_cfprintf                kwsys_ns(Terminal_cfprintf)
-# define kwsysTerminal_Color_e                 kwsys_ns(Terminal_Color_e)
-# define kwsysTerminal_Color_Normal            kwsys_ns(Terminal_Color_Normal)
-# define kwsysTerminal_Color_ForegroundBlack   kwsys_ns(Terminal_Color_ForegroundBlack)
-# define kwsysTerminal_Color_ForegroundRed     kwsys_ns(Terminal_Color_ForegroundRed)
-# define kwsysTerminal_Color_ForegroundGreen   kwsys_ns(Terminal_Color_ForegroundGreen)
-# define kwsysTerminal_Color_ForegroundYellow  kwsys_ns(Terminal_Color_ForegroundYellow)
-# define kwsysTerminal_Color_ForegroundBlue    kwsys_ns(Terminal_Color_ForegroundBlue)
-# define kwsysTerminal_Color_ForegroundMagenta kwsys_ns(Terminal_Color_ForegroundMagenta)
-# define kwsysTerminal_Color_ForegroundCyan    kwsys_ns(Terminal_Color_ForegroundCyan)
-# define kwsysTerminal_Color_ForegroundWhite   kwsys_ns(Terminal_Color_ForegroundWhite)
-# define kwsysTerminal_Color_ForegroundMask    kwsys_ns(Terminal_Color_ForegroundMask)
-# define kwsysTerminal_Color_BackgroundBlack   kwsys_ns(Terminal_Color_BackgroundBlack)
-# define kwsysTerminal_Color_BackgroundRed     kwsys_ns(Terminal_Color_BackgroundRed)
-# define kwsysTerminal_Color_BackgroundGreen   kwsys_ns(Terminal_Color_BackgroundGreen)
-# define kwsysTerminal_Color_BackgroundYellow  kwsys_ns(Terminal_Color_BackgroundYellow)
-# define kwsysTerminal_Color_BackgroundBlue    kwsys_ns(Terminal_Color_BackgroundBlue)
-# define kwsysTerminal_Color_BackgroundMagenta kwsys_ns(Terminal_Color_BackgroundMagenta)
-# define kwsysTerminal_Color_BackgroundCyan    kwsys_ns(Terminal_Color_BackgroundCyan)
-# define kwsysTerminal_Color_BackgroundWhite   kwsys_ns(Terminal_Color_BackgroundWhite)
-# define kwsysTerminal_Color_BackgroundMask    kwsys_ns(Terminal_Color_BackgroundMask)
-# define kwsysTerminal_Color_ForegroundBold    kwsys_ns(Terminal_Color_ForegroundBold)
-# define kwsysTerminal_Color_BackgroundBold    kwsys_ns(Terminal_Color_BackgroundBold)
-# define kwsysTerminal_Color_AssumeTTY         kwsys_ns(Terminal_Color_AssumeTTY)
-# define kwsysTerminal_Color_AssumeVT100       kwsys_ns(Terminal_Color_AssumeVT100)
-# define kwsysTerminal_Color_AttributeMask     kwsys_ns(Terminal_Color_AttributeMask)
+#define kwsysTerminal_cfprintf kwsys_ns(Terminal_cfprintf)
+#define kwsysTerminal_Color_e kwsys_ns(Terminal_Color_e)
+#define kwsysTerminal_Color_Normal kwsys_ns(Terminal_Color_Normal)
+#define kwsysTerminal_Color_ForegroundBlack                                   \
+  kwsys_ns(Terminal_Color_ForegroundBlack)
+#define kwsysTerminal_Color_ForegroundRed                                     \
+  kwsys_ns(Terminal_Color_ForegroundRed)
+#define kwsysTerminal_Color_ForegroundGreen                                   \
+  kwsys_ns(Terminal_Color_ForegroundGreen)
+#define kwsysTerminal_Color_ForegroundYellow                                  \
+  kwsys_ns(Terminal_Color_ForegroundYellow)
+#define kwsysTerminal_Color_ForegroundBlue                                    \
+  kwsys_ns(Terminal_Color_ForegroundBlue)
+#define kwsysTerminal_Color_ForegroundMagenta                                 \
+  kwsys_ns(Terminal_Color_ForegroundMagenta)
+#define kwsysTerminal_Color_ForegroundCyan                                    \
+  kwsys_ns(Terminal_Color_ForegroundCyan)
+#define kwsysTerminal_Color_ForegroundWhite                                   \
+  kwsys_ns(Terminal_Color_ForegroundWhite)
+#define kwsysTerminal_Color_ForegroundMask                                    \
+  kwsys_ns(Terminal_Color_ForegroundMask)
+#define kwsysTerminal_Color_BackgroundBlack                                   \
+  kwsys_ns(Terminal_Color_BackgroundBlack)
+#define kwsysTerminal_Color_BackgroundRed                                     \
+  kwsys_ns(Terminal_Color_BackgroundRed)
+#define kwsysTerminal_Color_BackgroundGreen                                   \
+  kwsys_ns(Terminal_Color_BackgroundGreen)
+#define kwsysTerminal_Color_BackgroundYellow                                  \
+  kwsys_ns(Terminal_Color_BackgroundYellow)
+#define kwsysTerminal_Color_BackgroundBlue                                    \
+  kwsys_ns(Terminal_Color_BackgroundBlue)
+#define kwsysTerminal_Color_BackgroundMagenta                                 \
+  kwsys_ns(Terminal_Color_BackgroundMagenta)
+#define kwsysTerminal_Color_BackgroundCyan                                    \
+  kwsys_ns(Terminal_Color_BackgroundCyan)
+#define kwsysTerminal_Color_BackgroundWhite                                   \
+  kwsys_ns(Terminal_Color_BackgroundWhite)
+#define kwsysTerminal_Color_BackgroundMask                                    \
+  kwsys_ns(Terminal_Color_BackgroundMask)
+#define kwsysTerminal_Color_ForegroundBold                                    \
+  kwsys_ns(Terminal_Color_ForegroundBold)
+#define kwsysTerminal_Color_BackgroundBold                                    \
+  kwsys_ns(Terminal_Color_BackgroundBold)
+#define kwsysTerminal_Color_AssumeTTY kwsys_ns(Terminal_Color_AssumeTTY)
+#define kwsysTerminal_Color_AssumeVT100 kwsys_ns(Terminal_Color_AssumeVT100)
+#define kwsysTerminal_Color_AttributeMask                                     \
+  kwsys_ns(Terminal_Color_AttributeMask)
 #endif
 
 #if defined(__cplusplus)
-extern "C"
-{
+extern "C" {
 #endif
 
 /**
@@ -88,33 +99,33 @@ enum kwsysTerminal_Color_e
   kwsysTerminal_Color_Normal = 0,
 
   /* Foreground Color */
-  kwsysTerminal_Color_ForegroundBlack   = 0x1,
-  kwsysTerminal_Color_ForegroundRed     = 0x2,
-  kwsysTerminal_Color_ForegroundGreen   = 0x3,
-  kwsysTerminal_Color_ForegroundYellow  = 0x4,
-  kwsysTerminal_Color_ForegroundBlue    = 0x5,
+  kwsysTerminal_Color_ForegroundBlack = 0x1,
+  kwsysTerminal_Color_ForegroundRed = 0x2,
+  kwsysTerminal_Color_ForegroundGreen = 0x3,
+  kwsysTerminal_Color_ForegroundYellow = 0x4,
+  kwsysTerminal_Color_ForegroundBlue = 0x5,
   kwsysTerminal_Color_ForegroundMagenta = 0x6,
-  kwsysTerminal_Color_ForegroundCyan    = 0x7,
-  kwsysTerminal_Color_ForegroundWhite   = 0x8,
-  kwsysTerminal_Color_ForegroundMask    = 0xF,
+  kwsysTerminal_Color_ForegroundCyan = 0x7,
+  kwsysTerminal_Color_ForegroundWhite = 0x8,
+  kwsysTerminal_Color_ForegroundMask = 0xF,
 
   /* Background Color */
-  kwsysTerminal_Color_BackgroundBlack   = 0x10,
-  kwsysTerminal_Color_BackgroundRed     = 0x20,
-  kwsysTerminal_Color_BackgroundGreen   = 0x30,
-  kwsysTerminal_Color_BackgroundYellow  = 0x40,
-  kwsysTerminal_Color_BackgroundBlue    = 0x50,
+  kwsysTerminal_Color_BackgroundBlack = 0x10,
+  kwsysTerminal_Color_BackgroundRed = 0x20,
+  kwsysTerminal_Color_BackgroundGreen = 0x30,
+  kwsysTerminal_Color_BackgroundYellow = 0x40,
+  kwsysTerminal_Color_BackgroundBlue = 0x50,
   kwsysTerminal_Color_BackgroundMagenta = 0x60,
-  kwsysTerminal_Color_BackgroundCyan    = 0x70,
-  kwsysTerminal_Color_BackgroundWhite   = 0x80,
-  kwsysTerminal_Color_BackgroundMask    = 0xF0,
+  kwsysTerminal_Color_BackgroundCyan = 0x70,
+  kwsysTerminal_Color_BackgroundWhite = 0x80,
+  kwsysTerminal_Color_BackgroundMask = 0xF0,
 
   /* Attributes */
   kwsysTerminal_Color_ForegroundBold = 0x100,
   kwsysTerminal_Color_BackgroundBold = 0x200,
-  kwsysTerminal_Color_AssumeTTY      = 0x400,
-  kwsysTerminal_Color_AssumeVT100    = 0x800,
-  kwsysTerminal_Color_AttributeMask  = 0xF00
+  kwsysTerminal_Color_AssumeTTY = 0x400,
+  kwsysTerminal_Color_AssumeVT100 = 0x800,
+  kwsysTerminal_Color_AttributeMask = 0xF00
 };
 
 #if defined(__cplusplus)
@@ -124,36 +135,36 @@ enum kwsysTerminal_Color_e
 /* If we are building a kwsys .c or .cxx file, let it use these macros.
    Otherwise, undefine them to keep the namespace clean.  */
 #if !defined(KWSYS_NAMESPACE)
-# undef kwsys_ns
-# undef kwsysEXPORT
-# if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
-#  undef kwsysTerminal_cfprintf
-#  undef kwsysTerminal_Color_e
-#  undef kwsysTerminal_Color_Normal
-#  undef kwsysTerminal_Color_ForegroundBlack
-#  undef kwsysTerminal_Color_ForegroundRed
-#  undef kwsysTerminal_Color_ForegroundGreen
-#  undef kwsysTerminal_Color_ForegroundYellow
-#  undef kwsysTerminal_Color_ForegroundBlue
-#  undef kwsysTerminal_Color_ForegroundMagenta
-#  undef kwsysTerminal_Color_ForegroundCyan
-#  undef kwsysTerminal_Color_ForegroundWhite
-#  undef kwsysTerminal_Color_ForegroundMask
-#  undef kwsysTerminal_Color_BackgroundBlack
-#  undef kwsysTerminal_Color_BackgroundRed
-#  undef kwsysTerminal_Color_BackgroundGreen
-#  undef kwsysTerminal_Color_BackgroundYellow
-#  undef kwsysTerminal_Color_BackgroundBlue
-#  undef kwsysTerminal_Color_BackgroundMagenta
-#  undef kwsysTerminal_Color_BackgroundCyan
-#  undef kwsysTerminal_Color_BackgroundWhite
-#  undef kwsysTerminal_Color_BackgroundMask
-#  undef kwsysTerminal_Color_ForegroundBold
-#  undef kwsysTerminal_Color_BackgroundBold
-#  undef kwsysTerminal_Color_AssumeTTY
-#  undef kwsysTerminal_Color_AssumeVT100
-#  undef kwsysTerminal_Color_AttributeMask
-# endif
+#undef kwsys_ns
+#undef kwsysEXPORT
+#if !@KWSYS_NAMESPACE at _NAME_IS_KWSYS
+#undef kwsysTerminal_cfprintf
+#undef kwsysTerminal_Color_e
+#undef kwsysTerminal_Color_Normal
+#undef kwsysTerminal_Color_ForegroundBlack
+#undef kwsysTerminal_Color_ForegroundRed
+#undef kwsysTerminal_Color_ForegroundGreen
+#undef kwsysTerminal_Color_ForegroundYellow
+#undef kwsysTerminal_Color_ForegroundBlue
+#undef kwsysTerminal_Color_ForegroundMagenta
+#undef kwsysTerminal_Color_ForegroundCyan
+#undef kwsysTerminal_Color_ForegroundWhite
+#undef kwsysTerminal_Color_ForegroundMask
+#undef kwsysTerminal_Color_BackgroundBlack
+#undef kwsysTerminal_Color_BackgroundRed
+#undef kwsysTerminal_Color_BackgroundGreen
+#undef kwsysTerminal_Color_BackgroundYellow
+#undef kwsysTerminal_Color_BackgroundBlue
+#undef kwsysTerminal_Color_BackgroundMagenta
+#undef kwsysTerminal_Color_BackgroundCyan
+#undef kwsysTerminal_Color_BackgroundWhite
+#undef kwsysTerminal_Color_BackgroundMask
+#undef kwsysTerminal_Color_ForegroundBold
+#undef kwsysTerminal_Color_BackgroundBold
+#undef kwsysTerminal_Color_AssumeTTY
+#undef kwsysTerminal_Color_AssumeVT100
+#undef kwsysTerminal_Color_AttributeMask
+#endif
 #endif
 
 #endif
diff --git a/Source/kwsys/hash_fun.hxx.in b/Source/kwsys/hash_fun.hxx.in
index 4872b51..8626c2a 100644
--- a/Source/kwsys/hash_fun.hxx.in
+++ b/Source/kwsys/hash_fun.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 /*
  * Copyright (c) 1996
  * Silicon Graphics Computer Systems, Inc.
@@ -38,108 +29,134 @@
 #define @KWSYS_NAMESPACE at _hash_fun_hxx
 
 #include <@KWSYS_NAMESPACE@/Configure.hxx>
-#include <stddef.h>        // size_t
+
+#include <stddef.h> // size_t
 #include <string>
 
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 
-template <class _Key> struct hash { };
+template <class _Key>
+struct hash
+{
+};
 
 inline size_t _stl_hash_string(const char* __s)
 {
   unsigned long __h = 0;
-  for ( ; *__s; ++__s)
-    __h = 5*__h + *__s;
+  for (; *__s; ++__s)
+    __h = 5 * __h + *__s;
 
   return size_t(__h);
 }
 
 template <>
-struct hash<char*> {
+struct hash<char*>
+{
   size_t operator()(const char* __s) const { return _stl_hash_string(__s); }
 };
 
 template <>
-struct hash<const char*> {
+struct hash<const char*>
+{
   size_t operator()(const char* __s) const { return _stl_hash_string(__s); }
 };
 
 template <>
-  struct hash<std::string> {
-  size_t operator()(const std::string & __s) const { return _stl_hash_string(__s.c_str()); }
+struct hash<std::string>
+{
+  size_t operator()(const std::string& __s) const
+  {
+    return _stl_hash_string(__s.c_str());
+  }
 };
 
 #if !defined(__BORLANDC__)
 template <>
-  struct hash<const std::string> {
-  size_t operator()(const std::string & __s) const { return _stl_hash_string(__s.c_str()); }
+struct hash<const std::string>
+{
+  size_t operator()(const std::string& __s) const
+  {
+    return _stl_hash_string(__s.c_str());
+  }
 };
 #endif
 
 template <>
-struct hash<char> {
+struct hash<char>
+{
   size_t operator()(char __x) const { return __x; }
 };
 
 template <>
-struct hash<unsigned char> {
+struct hash<unsigned char>
+{
   size_t operator()(unsigned char __x) const { return __x; }
 };
 
 template <>
-struct hash<signed char> {
+struct hash<signed char>
+{
   size_t operator()(unsigned char __x) const { return __x; }
 };
 
 template <>
-struct hash<short> {
+struct hash<short>
+{
   size_t operator()(short __x) const { return __x; }
 };
 
 template <>
-struct hash<unsigned short> {
+struct hash<unsigned short>
+{
   size_t operator()(unsigned short __x) const { return __x; }
 };
 
 template <>
-struct hash<int> {
+struct hash<int>
+{
   size_t operator()(int __x) const { return __x; }
 };
 
 template <>
-struct hash<unsigned int> {
+struct hash<unsigned int>
+{
   size_t operator()(unsigned int __x) const { return __x; }
 };
 
 template <>
-struct hash<long> {
+struct hash<long>
+{
   size_t operator()(long __x) const { return __x; }
 };
 
 template <>
-struct hash<unsigned long> {
+struct hash<unsigned long>
+{
   size_t operator()(unsigned long __x) const { return __x; }
 };
 
 // use long long or __int64
 #if @KWSYS_USE_LONG_LONG@
 template <>
-struct hash<long long> {
+struct hash<long long>
+{
   size_t operator()(long long __x) const { return __x; }
 };
 
 template <>
-struct hash<unsigned long long> {
+struct hash<unsigned long long>
+{
   size_t operator()(unsigned long long __x) const { return __x; }
 };
 #elif @KWSYS_USE___INT64@
 template <>
-struct hash<__int64> {
+struct hash<__int64>
+{
   size_t operator()(__int64 __x) const { return __x; }
 };
 template <>
-struct hash<unsigned __int64> {
+struct hash<unsigned __int64>
+{
   size_t operator()(unsigned __int64 __x) const { return __x; }
 };
 #endif // use long long or __int64
diff --git a/Source/kwsys/hash_map.hxx.in b/Source/kwsys/hash_map.hxx.in
index 60c7086..3f9174f 100644
--- a/Source/kwsys/hash_map.hxx.in
+++ b/Source/kwsys/hash_map.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 /*
  * Copyright (c) 1996
  * Silicon Graphics Computer Systems, Inc.
@@ -38,36 +29,37 @@
 #define @KWSYS_NAMESPACE at _hash_map_hxx
 
 #include <@KWSYS_NAMESPACE@/hashtable.hxx>
+
 #include <@KWSYS_NAMESPACE@/hash_fun.hxx>
+
 #include <functional> // equal_to
 
 #if defined(_MSC_VER)
-# pragma warning (push)
-# pragma warning (disable:4284)
-# pragma warning (disable:4786)
+#pragma warning(push)
+#pragma warning(disable : 4284)
+#pragma warning(disable : 4786)
 #endif
 
 #if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
-# pragma set woff 1174
-# pragma set woff 1375
+#pragma set woff 1174
+#pragma set woff 1375
 #endif
 
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 
 // select1st is an extension: it is not part of the standard.
 template <class T1, class T2>
-struct hash_select1st:
-    public std::unary_function<std::pair<T1, T2>, T1>
+struct hash_select1st : public std::unary_function<std::pair<T1, T2>, T1>
 {
   const T1& operator()(const std::pair<T1, T2>& __x) const
-    { return __x.first; }
+  {
+    return __x.first;
+  }
 };
 
 // Forward declaration of equality operator; needed for friend declaration.
 
-template <class _Key, class _Tp,
-          class _HashFcn  = hash<_Key>,
+template <class _Key, class _Tp, class _HashFcn = hash<_Key>,
           class _EqualKey = std::equal_to<_Key>,
           class _Alloc = std::allocator<char> >
 class hash_map;
@@ -76,13 +68,13 @@ template <class _Key, class _Tp, class _HashFn, class _EqKey, class _Alloc>
 bool operator==(const hash_map<_Key, _Tp, _HashFn, _EqKey, _Alloc>&,
                 const hash_map<_Key, _Tp, _HashFn, _EqKey, _Alloc>&);
 
-template <class _Key, class _Tp, class _HashFcn, class _EqualKey,
-          class _Alloc>
+template <class _Key, class _Tp, class _HashFcn, class _EqualKey, class _Alloc>
 class hash_map
 {
 private:
-  typedef hashtable<std::pair<const _Key,_Tp>,_Key,_HashFcn,
-                    hash_select1st<const _Key,_Tp>,_EqualKey,_Alloc> _Ht;
+  typedef hashtable<std::pair<const _Key, _Tp>, _Key, _HashFcn,
+                    hash_select1st<const _Key, _Tp>, _EqualKey, _Alloc>
+    _Ht;
   _Ht _M_ht;
 
 public:
@@ -110,34 +102,51 @@ public:
   allocator_type get_allocator() const { return _M_ht.get_allocator(); }
 
 public:
-  hash_map() : _M_ht(100, hasher(), key_equal(), allocator_type()) {}
+  hash_map()
+    : _M_ht(100, hasher(), key_equal(), allocator_type())
+  {
+  }
   explicit hash_map(size_type __n)
-    : _M_ht(__n, hasher(), key_equal(), allocator_type()) {}
+    : _M_ht(__n, hasher(), key_equal(), allocator_type())
+  {
+  }
   hash_map(size_type __n, const hasher& __hf)
-    : _M_ht(__n, __hf, key_equal(), allocator_type()) {}
+    : _M_ht(__n, __hf, key_equal(), allocator_type())
+  {
+  }
   hash_map(size_type __n, const hasher& __hf, const key_equal& __eql,
            const allocator_type& __a = allocator_type())
-    : _M_ht(__n, __hf, __eql, __a) {}
+    : _M_ht(__n, __hf, __eql, __a)
+  {
+  }
 
   template <class _InputIterator>
   hash_map(_InputIterator __f, _InputIterator __l)
     : _M_ht(100, hasher(), key_equal(), allocator_type())
-    { _M_ht.insert_unique(__f, __l); }
+  {
+    _M_ht.insert_unique(__f, __l);
+  }
   template <class _InputIterator>
   hash_map(_InputIterator __f, _InputIterator __l, size_type __n)
     : _M_ht(__n, hasher(), key_equal(), allocator_type())
-    { _M_ht.insert_unique(__f, __l); }
+  {
+    _M_ht.insert_unique(__f, __l);
+  }
   template <class _InputIterator>
   hash_map(_InputIterator __f, _InputIterator __l, size_type __n,
            const hasher& __hf)
     : _M_ht(__n, __hf, key_equal(), allocator_type())
-    { _M_ht.insert_unique(__f, __l); }
+  {
+    _M_ht.insert_unique(__f, __l);
+  }
   template <class _InputIterator>
   hash_map(_InputIterator __f, _InputIterator __l, size_type __n,
            const hasher& __hf, const key_equal& __eql,
            const allocator_type& __a = allocator_type())
     : _M_ht(__n, __hf, __eql, __a)
-    { _M_ht.insert_unique(__f, __l); }
+  {
+    _M_ht.insert_unique(__f, __l);
+  }
 
 public:
   size_type size() const { return _M_ht.size(); }
@@ -145,8 +154,7 @@ public:
   bool empty() const { return _M_ht.empty(); }
   void swap(hash_map& __hs) { _M_ht.swap(__hs._M_ht); }
 
-  friend bool operator==<>(const hash_map&,
-                           const hash_map&);
+  friend bool operator==<>(const hash_map&, const hash_map&);
 
   iterator begin() { return _M_ht.begin(); }
   iterator end() { return _M_ht.end(); }
@@ -154,31 +162,44 @@ public:
   const_iterator end() const { return _M_ht.end(); }
 
 public:
-  std::pair<iterator,bool> insert(const value_type& __obj)
-    { return _M_ht.insert_unique(__obj); }
+  std::pair<iterator, bool> insert(const value_type& __obj)
+  {
+    return _M_ht.insert_unique(__obj);
+  }
   template <class _InputIterator>
   void insert(_InputIterator __f, _InputIterator __l)
-    { _M_ht.insert_unique(__f,__l); }
-  std::pair<iterator,bool> insert_noresize(const value_type& __obj)
-    { return _M_ht.insert_unique_noresize(__obj); }
+  {
+    _M_ht.insert_unique(__f, __l);
+  }
+  std::pair<iterator, bool> insert_noresize(const value_type& __obj)
+  {
+    return _M_ht.insert_unique_noresize(__obj);
+  }
 
   iterator find(const key_type& __key) { return _M_ht.find(__key); }
   const_iterator find(const key_type& __key) const
-    { return _M_ht.find(__key); }
+  {
+    return _M_ht.find(__key);
+  }
 
-  _Tp& operator[](const key_type& __key) {
+  _Tp& operator[](const key_type& __key)
+  {
     return _M_ht.find_or_insert(value_type(__key, _Tp())).second;
   }
 
   size_type count(const key_type& __key) const { return _M_ht.count(__key); }
 
   std::pair<iterator, iterator> equal_range(const key_type& __key)
-    { return _M_ht.equal_range(__key); }
-  std::pair<const_iterator, const_iterator>
-  equal_range(const key_type& __key) const
-    { return _M_ht.equal_range(__key); }
+  {
+    return _M_ht.equal_range(__key);
+  }
+  std::pair<const_iterator, const_iterator> equal_range(
+    const key_type& __key) const
+  {
+    return _M_ht.equal_range(__key);
+  }
 
-  size_type erase(const key_type& __key) {return _M_ht.erase(__key); }
+  size_type erase(const key_type& __key) { return _M_ht.erase(__key); }
   void erase(iterator __it) { _M_ht.erase(__it); }
   void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
   void clear() { _M_ht.clear(); }
@@ -187,53 +208,51 @@ public:
   size_type bucket_count() const { return _M_ht.bucket_count(); }
   size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
   size_type elems_in_bucket(size_type __n) const
-    { return _M_ht.elems_in_bucket(__n); }
+  {
+    return _M_ht.elems_in_bucket(__n);
+  }
 };
 
 template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
-bool
-operator==(const hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm1,
-           const hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm2)
+bool operator==(const hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm1,
+                const hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm2)
 {
   return __hm1._M_ht == __hm2._M_ht;
 }
 
 template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
-inline bool
-operator!=(const hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm1,
-           const hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm2) {
+inline bool operator!=(
+  const hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm1,
+  const hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm2)
+{
   return !(__hm1 == __hm2);
 }
 
 template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
-inline void
-swap(hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm1,
-     hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm2)
+inline void swap(hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm1,
+                 hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm2)
 {
   __hm1.swap(__hm2);
 }
 
 // Forward declaration of equality operator; needed for friend declaration.
 
-template <class _Key, class _Tp,
-          class _HashFcn  = hash<_Key>,
+template <class _Key, class _Tp, class _HashFcn = hash<_Key>,
           class _EqualKey = std::equal_to<_Key>,
           class _Alloc = std::allocator<char> >
 class hash_multimap;
 
 template <class _Key, class _Tp, class _HF, class _EqKey, class _Alloc>
-bool
-operator==(const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm1,
-           const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm2);
+bool operator==(const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm1,
+                const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm2);
 
-template <class _Key, class _Tp, class _HashFcn, class _EqualKey,
-          class _Alloc>
+template <class _Key, class _Tp, class _HashFcn, class _EqualKey, class _Alloc>
 class hash_multimap
 {
 private:
   typedef hashtable<std::pair<const _Key, _Tp>, _Key, _HashFcn,
                     hash_select1st<const _Key, _Tp>, _EqualKey, _Alloc>
-          _Ht;
+    _Ht;
   _Ht _M_ht;
 
 public:
@@ -261,34 +280,51 @@ public:
   allocator_type get_allocator() const { return _M_ht.get_allocator(); }
 
 public:
-  hash_multimap() : _M_ht(100, hasher(), key_equal(), allocator_type()) {}
+  hash_multimap()
+    : _M_ht(100, hasher(), key_equal(), allocator_type())
+  {
+  }
   explicit hash_multimap(size_type __n)
-    : _M_ht(__n, hasher(), key_equal(), allocator_type()) {}
+    : _M_ht(__n, hasher(), key_equal(), allocator_type())
+  {
+  }
   hash_multimap(size_type __n, const hasher& __hf)
-    : _M_ht(__n, __hf, key_equal(), allocator_type()) {}
+    : _M_ht(__n, __hf, key_equal(), allocator_type())
+  {
+  }
   hash_multimap(size_type __n, const hasher& __hf, const key_equal& __eql,
                 const allocator_type& __a = allocator_type())
-    : _M_ht(__n, __hf, __eql, __a) {}
+    : _M_ht(__n, __hf, __eql, __a)
+  {
+  }
 
   template <class _InputIterator>
   hash_multimap(_InputIterator __f, _InputIterator __l)
     : _M_ht(100, hasher(), key_equal(), allocator_type())
-    { _M_ht.insert_equal(__f, __l); }
+  {
+    _M_ht.insert_equal(__f, __l);
+  }
   template <class _InputIterator>
   hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n)
     : _M_ht(__n, hasher(), key_equal(), allocator_type())
-    { _M_ht.insert_equal(__f, __l); }
+  {
+    _M_ht.insert_equal(__f, __l);
+  }
   template <class _InputIterator>
   hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n,
                 const hasher& __hf)
     : _M_ht(__n, __hf, key_equal(), allocator_type())
-    { _M_ht.insert_equal(__f, __l); }
+  {
+    _M_ht.insert_equal(__f, __l);
+  }
   template <class _InputIterator>
   hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n,
                 const hasher& __hf, const key_equal& __eql,
                 const allocator_type& __a = allocator_type())
     : _M_ht(__n, __hf, __eql, __a)
-    { _M_ht.insert_equal(__f, __l); }
+  {
+    _M_ht.insert_equal(__f, __l);
+  }
 
 public:
   size_type size() const { return _M_ht.size(); }
@@ -296,8 +332,7 @@ public:
   bool empty() const { return _M_ht.empty(); }
   void swap(hash_multimap& __hs) { _M_ht.swap(__hs._M_ht); }
 
-  friend bool operator==<>(const hash_multimap&,
-                           const hash_multimap&);
+  friend bool operator==<>(const hash_multimap&, const hash_multimap&);
 
   iterator begin() { return _M_ht.begin(); }
   iterator end() { return _M_ht.end(); }
@@ -306,26 +341,38 @@ public:
 
 public:
   iterator insert(const value_type& __obj)
-    { return _M_ht.insert_equal(__obj); }
+  {
+    return _M_ht.insert_equal(__obj);
+  }
   template <class _InputIterator>
   void insert(_InputIterator __f, _InputIterator __l)
-    { _M_ht.insert_equal(__f,__l); }
+  {
+    _M_ht.insert_equal(__f, __l);
+  }
   iterator insert_noresize(const value_type& __obj)
-    { return _M_ht.insert_equal_noresize(__obj); }
+  {
+    return _M_ht.insert_equal_noresize(__obj);
+  }
 
   iterator find(const key_type& __key) { return _M_ht.find(__key); }
   const_iterator find(const key_type& __key) const
-    { return _M_ht.find(__key); }
+  {
+    return _M_ht.find(__key);
+  }
 
   size_type count(const key_type& __key) const { return _M_ht.count(__key); }
 
   std::pair<iterator, iterator> equal_range(const key_type& __key)
-    { return _M_ht.equal_range(__key); }
-  std::pair<const_iterator, const_iterator>
-  equal_range(const key_type& __key) const
-    { return _M_ht.equal_range(__key); }
+  {
+    return _M_ht.equal_range(__key);
+  }
+  std::pair<const_iterator, const_iterator> equal_range(
+    const key_type& __key) const
+  {
+    return _M_ht.equal_range(__key);
+  }
 
-  size_type erase(const key_type& __key) {return _M_ht.erase(__key); }
+  size_type erase(const key_type& __key) { return _M_ht.erase(__key); }
   void erase(iterator __it) { _M_ht.erase(__it); }
   void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
   void clear() { _M_ht.clear(); }
@@ -335,28 +382,29 @@ public:
   size_type bucket_count() const { return _M_ht.bucket_count(); }
   size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
   size_type elems_in_bucket(size_type __n) const
-    { return _M_ht.elems_in_bucket(__n); }
+  {
+    return _M_ht.elems_in_bucket(__n);
+  }
 };
 
 template <class _Key, class _Tp, class _HF, class _EqKey, class _Alloc>
-bool
-operator==(const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm1,
-           const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm2)
+bool operator==(const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm1,
+                const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm2)
 {
   return __hm1._M_ht == __hm2._M_ht;
 }
 
 template <class _Key, class _Tp, class _HF, class _EqKey, class _Alloc>
-inline bool
-operator!=(const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm1,
-           const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm2) {
+inline bool operator!=(
+  const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm1,
+  const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm2)
+{
   return !(__hm1 == __hm2);
 }
 
 template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
-inline void
-swap(hash_multimap<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm1,
-     hash_multimap<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm2)
+inline void swap(hash_multimap<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm1,
+                 hash_multimap<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm2)
 {
   __hm1.swap(__hm2);
 }
@@ -364,12 +412,12 @@ swap(hash_multimap<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm1,
 } // namespace @KWSYS_NAMESPACE@
 
 #if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
-# pragma reset woff 1174
-# pragma reset woff 1375
+#pragma reset woff 1174
+#pragma reset woff 1375
 #endif
 
 #if defined(_MSC_VER)
-# pragma warning (pop)
+#pragma warning(pop)
 #endif
 
 #endif
diff --git a/Source/kwsys/hash_set.hxx.in b/Source/kwsys/hash_set.hxx.in
index c314979..e3a0c6c 100644
--- a/Source/kwsys/hash_set.hxx.in
+++ b/Source/kwsys/hash_set.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 /*
  * Copyright (c) 1996
  * Silicon Graphics Computer Systems, Inc.
@@ -38,49 +29,49 @@
 #define @KWSYS_NAMESPACE at _hash_set_hxx
 
 #include <@KWSYS_NAMESPACE@/hashtable.hxx>
+
 #include <@KWSYS_NAMESPACE@/hash_fun.hxx>
+
 #include <functional> // equal_to
 
 #if defined(_MSC_VER)
-# pragma warning (push)
-# pragma warning (disable:4284)
-# pragma warning (disable:4786)
+#pragma warning(push)
+#pragma warning(disable : 4284)
+#pragma warning(disable : 4786)
 #endif
 
 #if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
-# pragma set woff 1174
-# pragma set woff 1375
+#pragma set woff 1174
+#pragma set woff 1375
 #endif
 
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 
 // identity is an extension: it is not part of the standard.
 template <class _Tp>
-struct _Identity : public std::unary_function<_Tp,_Tp>
+struct _Identity : public std::unary_function<_Tp, _Tp>
 {
   const _Tp& operator()(const _Tp& __x) const { return __x; }
 };
 
 // Forward declaration of equality operator; needed for friend declaration.
 
-template <class _Value,
-          class _HashFcn  = hash<_Value>,
+template <class _Value, class _HashFcn = hash<_Value>,
           class _EqualKey = std::equal_to<_Value>,
           class _Alloc = std::allocator<char> >
 class hash_set;
 
 template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
-bool
-operator==(const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs1,
-           const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs2);
+bool operator==(const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs1,
+                const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs2);
 
 template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
 class hash_set
 {
 private:
-  typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>,
-                    _EqualKey, _Alloc> _Ht;
+  typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>, _EqualKey,
+                    _Alloc>
+    _Ht;
   _Ht _M_ht;
 
 public:
@@ -107,34 +98,50 @@ public:
 
 public:
   hash_set()
-    : _M_ht(100, hasher(), key_equal(), allocator_type()) {}
+    : _M_ht(100, hasher(), key_equal(), allocator_type())
+  {
+  }
   explicit hash_set(size_type __n)
-    : _M_ht(__n, hasher(), key_equal(), allocator_type()) {}
+    : _M_ht(__n, hasher(), key_equal(), allocator_type())
+  {
+  }
   hash_set(size_type __n, const hasher& __hf)
-    : _M_ht(__n, __hf, key_equal(), allocator_type()) {}
+    : _M_ht(__n, __hf, key_equal(), allocator_type())
+  {
+  }
   hash_set(size_type __n, const hasher& __hf, const key_equal& __eql,
            const allocator_type& __a = allocator_type())
-    : _M_ht(__n, __hf, __eql, __a) {}
+    : _M_ht(__n, __hf, __eql, __a)
+  {
+  }
 
   template <class _InputIterator>
   hash_set(_InputIterator __f, _InputIterator __l)
     : _M_ht(100, hasher(), key_equal(), allocator_type())
-    { _M_ht.insert_unique(__f, __l); }
+  {
+    _M_ht.insert_unique(__f, __l);
+  }
   template <class _InputIterator>
   hash_set(_InputIterator __f, _InputIterator __l, size_type __n)
     : _M_ht(__n, hasher(), key_equal(), allocator_type())
-    { _M_ht.insert_unique(__f, __l); }
+  {
+    _M_ht.insert_unique(__f, __l);
+  }
   template <class _InputIterator>
   hash_set(_InputIterator __f, _InputIterator __l, size_type __n,
            const hasher& __hf)
     : _M_ht(__n, __hf, key_equal(), allocator_type())
-    { _M_ht.insert_unique(__f, __l); }
+  {
+    _M_ht.insert_unique(__f, __l);
+  }
   template <class _InputIterator>
   hash_set(_InputIterator __f, _InputIterator __l, size_type __n,
            const hasher& __hf, const key_equal& __eql,
            const allocator_type& __a = allocator_type())
     : _M_ht(__n, __hf, __eql, __a)
-    { _M_ht.insert_unique(__f, __l); }
+  {
+    _M_ht.insert_unique(__f, __l);
+  }
 
 public:
   size_type size() const { return _M_ht.size(); }
@@ -142,27 +149,27 @@ public:
   bool empty() const { return _M_ht.empty(); }
   void swap(hash_set& __hs) { _M_ht.swap(__hs._M_ht); }
 
-  friend bool operator==<>(const hash_set&,
-                           const hash_set&);
+  friend bool operator==<>(const hash_set&, const hash_set&);
 
   iterator begin() const { return _M_ht.begin(); }
   iterator end() const { return _M_ht.end(); }
 
 public:
   std::pair<iterator, bool> insert(const value_type& __obj)
-    {
-      typedef typename _Ht::iterator _Ht_iterator;
-      std::pair<_Ht_iterator, bool> __p = _M_ht.insert_unique(__obj);
-      return std::pair<iterator,bool>(__p.first, __p.second);
-    }
+  {
+    typedef typename _Ht::iterator _Ht_iterator;
+    std::pair<_Ht_iterator, bool> __p = _M_ht.insert_unique(__obj);
+    return std::pair<iterator, bool>(__p.first, __p.second);
+  }
   template <class _InputIterator>
   void insert(_InputIterator __f, _InputIterator __l)
-    { _M_ht.insert_unique(__f,__l); }
+  {
+    _M_ht.insert_unique(__f, __l);
+  }
   std::pair<iterator, bool> insert_noresize(const value_type& __obj)
   {
     typedef typename _Ht::iterator _Ht_iterator;
-    std::pair<_Ht_iterator, bool> __p =
-      _M_ht.insert_unique_noresize(__obj);
+    std::pair<_Ht_iterator, bool> __p = _M_ht.insert_unique_noresize(__obj);
     return std::pair<iterator, bool>(__p.first, __p.second);
   }
 
@@ -171,9 +178,11 @@ public:
   size_type count(const key_type& __key) const { return _M_ht.count(__key); }
 
   std::pair<iterator, iterator> equal_range(const key_type& __key) const
-    { return _M_ht.equal_range(__key); }
+  {
+    return _M_ht.equal_range(__key);
+  }
 
-  size_type erase(const key_type& __key) {return _M_ht.erase(__key); }
+  size_type erase(const key_type& __key) { return _M_ht.erase(__key); }
   void erase(iterator __it) { _M_ht.erase(__it); }
   void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
   void clear() { _M_ht.clear(); }
@@ -183,50 +192,49 @@ public:
   size_type bucket_count() const { return _M_ht.bucket_count(); }
   size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
   size_type elems_in_bucket(size_type __n) const
-    { return _M_ht.elems_in_bucket(__n); }
+  {
+    return _M_ht.elems_in_bucket(__n);
+  }
 };
 
 template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
-bool
-operator==(const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs1,
-           const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs2)
+bool operator==(const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs1,
+                const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs2)
 {
   return __hs1._M_ht == __hs2._M_ht;
 }
 
 template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
-inline bool
-operator!=(const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs1,
-           const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs2) {
+inline bool operator!=(
+  const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs1,
+  const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs2)
+{
   return !(__hs1 == __hs2);
 }
 
 template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
-inline void
-swap(hash_set<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
-     hash_set<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2)
+inline void swap(hash_set<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1,
+                 hash_set<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2)
 {
   __hs1.swap(__hs2);
 }
 
-template <class _Value,
-          class _HashFcn = hash<_Value>,
+template <class _Value, class _HashFcn = hash<_Value>,
           class _EqualKey = std::equal_to<_Value>,
           class _Alloc = std::allocator<char> >
 class hash_multiset;
 
 template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
-bool
-operator==(const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
-           const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2);
-
+bool operator==(const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1,
+                const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2);
 
 template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
 class hash_multiset
 {
 private:
-  typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>,
-                    _EqualKey, _Alloc> _Ht;
+  typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>, _EqualKey,
+                    _Alloc>
+    _Ht;
   _Ht _M_ht;
 
 public:
@@ -253,34 +261,50 @@ public:
 
 public:
   hash_multiset()
-    : _M_ht(100, hasher(), key_equal(), allocator_type()) {}
+    : _M_ht(100, hasher(), key_equal(), allocator_type())
+  {
+  }
   explicit hash_multiset(size_type __n)
-    : _M_ht(__n, hasher(), key_equal(), allocator_type()) {}
+    : _M_ht(__n, hasher(), key_equal(), allocator_type())
+  {
+  }
   hash_multiset(size_type __n, const hasher& __hf)
-    : _M_ht(__n, __hf, key_equal(), allocator_type()) {}
+    : _M_ht(__n, __hf, key_equal(), allocator_type())
+  {
+  }
   hash_multiset(size_type __n, const hasher& __hf, const key_equal& __eql,
                 const allocator_type& __a = allocator_type())
-    : _M_ht(__n, __hf, __eql, __a) {}
+    : _M_ht(__n, __hf, __eql, __a)
+  {
+  }
 
   template <class _InputIterator>
   hash_multiset(_InputIterator __f, _InputIterator __l)
     : _M_ht(100, hasher(), key_equal(), allocator_type())
-    { _M_ht.insert_equal(__f, __l); }
+  {
+    _M_ht.insert_equal(__f, __l);
+  }
   template <class _InputIterator>
   hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n)
     : _M_ht(__n, hasher(), key_equal(), allocator_type())
-    { _M_ht.insert_equal(__f, __l); }
+  {
+    _M_ht.insert_equal(__f, __l);
+  }
   template <class _InputIterator>
   hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n,
                 const hasher& __hf)
     : _M_ht(__n, __hf, key_equal(), allocator_type())
-    { _M_ht.insert_equal(__f, __l); }
+  {
+    _M_ht.insert_equal(__f, __l);
+  }
   template <class _InputIterator>
   hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n,
                 const hasher& __hf, const key_equal& __eql,
                 const allocator_type& __a = allocator_type())
     : _M_ht(__n, __hf, __eql, __a)
-    { _M_ht.insert_equal(__f, __l); }
+  {
+    _M_ht.insert_equal(__f, __l);
+  }
 
 public:
   size_type size() const { return _M_ht.size(); }
@@ -288,29 +312,36 @@ public:
   bool empty() const { return _M_ht.empty(); }
   void swap(hash_multiset& hs) { _M_ht.swap(hs._M_ht); }
 
-  friend bool operator==<>(const hash_multiset&,
-                           const hash_multiset&);
+  friend bool operator==<>(const hash_multiset&, const hash_multiset&);
 
   iterator begin() const { return _M_ht.begin(); }
   iterator end() const { return _M_ht.end(); }
 
 public:
   iterator insert(const value_type& __obj)
-    { return _M_ht.insert_equal(__obj); }
+  {
+    return _M_ht.insert_equal(__obj);
+  }
   template <class _InputIterator>
   void insert(_InputIterator __f, _InputIterator __l)
-    { _M_ht.insert_equal(__f,__l); }
+  {
+    _M_ht.insert_equal(__f, __l);
+  }
   iterator insert_noresize(const value_type& __obj)
-    { return _M_ht.insert_equal_noresize(__obj); }
+  {
+    return _M_ht.insert_equal_noresize(__obj);
+  }
 
   iterator find(const key_type& __key) const { return _M_ht.find(__key); }
 
   size_type count(const key_type& __key) const { return _M_ht.count(__key); }
 
   std::pair<iterator, iterator> equal_range(const key_type& __key) const
-    { return _M_ht.equal_range(__key); }
+  {
+    return _M_ht.equal_range(__key);
+  }
 
-  size_type erase(const key_type& __key) {return _M_ht.erase(__key); }
+  size_type erase(const key_type& __key) { return _M_ht.erase(__key); }
   void erase(iterator __it) { _M_ht.erase(__it); }
   void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
   void clear() { _M_ht.clear(); }
@@ -320,40 +351,42 @@ public:
   size_type bucket_count() const { return _M_ht.bucket_count(); }
   size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
   size_type elems_in_bucket(size_type __n) const
-    { return _M_ht.elems_in_bucket(__n); }
+  {
+    return _M_ht.elems_in_bucket(__n);
+  }
 };
 
 template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
-bool
-operator==(const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
-           const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2)
+bool operator==(const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1,
+                const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2)
 {
   return __hs1._M_ht == __hs2._M_ht;
 }
 
 template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
-inline bool
-operator!=(const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
-           const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2) {
+inline bool operator!=(
+  const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1,
+  const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2)
+{
   return !(__hs1 == __hs2);
 }
 
 template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
-inline void
-swap(hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
-     hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2) {
+inline void swap(hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1,
+                 hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2)
+{
   __hs1.swap(__hs2);
 }
 
 } // namespace @KWSYS_NAMESPACE@
 
 #if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
-# pragma reset woff 1174
-# pragma reset woff 1375
+#pragma reset woff 1174
+#pragma reset woff 1375
 #endif
 
 #if defined(_MSC_VER)
-# pragma warning (pop)
+#pragma warning(pop)
 #endif
 
 #endif
diff --git a/Source/kwsys/hashtable.hxx.in b/Source/kwsys/hashtable.hxx.in
index 9a20226..dd92cb9 100644
--- a/Source/kwsys/hashtable.hxx.in
+++ b/Source/kwsys/hashtable.hxx.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 /*
  * Copyright (c) 1996
  * Silicon Graphics Computer Systems, Inc.
@@ -35,31 +26,31 @@
  *
  */
 #ifdef __BORLANDC__
-# pragma warn -8027 /* 'for' not inlined.  */
-# pragma warn -8026 /* 'exception' not inlined.  */
-#endif 
+#pragma warn - 8027 /* 'for' not inlined.  */
+#pragma warn - 8026 /* 'exception' not inlined.  */
+#endif
 
 #ifndef @KWSYS_NAMESPACE at _hashtable_hxx
 #define @KWSYS_NAMESPACE at _hashtable_hxx
 
 #include <@KWSYS_NAMESPACE@/Configure.hxx>
 
-#include <stddef.h>   // size_t
 #include <algorithm>  // lower_bound
 #include <functional> // unary_function
 #include <iterator>   // iterator_traits
 #include <memory>     // allocator
+#include <stddef.h>   // size_t
 #include <utility>    // pair
 #include <vector>     // vector
 
 #if defined(_MSC_VER)
-# pragma warning (push)
-# pragma warning (disable:4284)
-# pragma warning (disable:4786)
-# pragma warning (disable:4512) /* no assignment operator for class */
+#pragma warning(push)
+#pragma warning(disable : 4284)
+#pragma warning(disable : 4786)
+#pragma warning(disable : 4512) /* no assignment operator for class */
 #endif
 #if defined(__sgi) && !defined(__GNUC__)
-# pragma set woff 3970 /* pointer to int conversion */ 3321 3968
+#pragma set woff 3970 /* pointer to int conversion */ 3321 3968
 #endif
 
 // In C++11, clang will warn about using dynamic exception specifications
@@ -67,14 +58,13 @@
 // mimic unordered_set and unordered_map, we want to keep the 'throw()'
 // decorations below.  So we suppress the warning.
 #if defined(__clang__) && defined(__has_warning)
-# if __has_warning("-Wdeprecated")
-#  pragma clang diagnostic push
-#  pragma clang diagnostic ignored "-Wdeprecated"
-# endif
+#if __has_warning("-Wdeprecated")
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated"
+#endif
 #endif
 
-namespace @KWSYS_NAMESPACE@
-{
+namespace @KWSYS_NAMESPACE@ {
 
 template <class _Val>
 struct _Hashtable_node
@@ -82,34 +72,35 @@ struct _Hashtable_node
   _Hashtable_node* _M_next;
   _Val _M_val;
   void public_method_to_quiet_warning_about_all_methods_private();
+
 private:
   void operator=(_Hashtable_node<_Val> const&); // poison node assignment
 };
 
-template <class _Val, class _Key, class _HashFcn,
-          class _ExtractKey, class _EqualKey,
-          class _Alloc = std::allocator<char> >
+template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
+          class _EqualKey, class _Alloc = std::allocator<char> >
 class hashtable;
 
-template <class _Val, class _Key, class _HashFcn,
-          class _ExtractKey, class _EqualKey, class _Alloc>
+template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
+          class _EqualKey, class _Alloc>
 struct _Hashtable_iterator;
 
-template <class _Val, class _Key, class _HashFcn,
-          class _ExtractKey, class _EqualKey, class _Alloc>
+template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
+          class _EqualKey, class _Alloc>
 struct _Hashtable_const_iterator;
 
-template <class _Val, class _Key, class _HashFcn,
-          class _ExtractKey, class _EqualKey, class _Alloc>
-struct _Hashtable_iterator {
-  typedef hashtable<_Val,_Key,_HashFcn,_ExtractKey,_EqualKey,_Alloc>
-          _Hashtable;
-  typedef _Hashtable_iterator<_Val, _Key, _HashFcn,
-                              _ExtractKey, _EqualKey, _Alloc>
-          iterator;
-  typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn,
-                                    _ExtractKey, _EqualKey, _Alloc>
-          const_iterator;
+template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
+          class _EqualKey, class _Alloc>
+struct _Hashtable_iterator
+{
+  typedef hashtable<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc>
+    _Hashtable;
+  typedef _Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey,
+                              _Alloc>
+    iterator;
+  typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey,
+                                    _EqualKey, _Alloc>
+    const_iterator;
   typedef _Hashtable_node<_Val> _Node;
 
   typedef std::forward_iterator_tag iterator_category;
@@ -123,30 +114,31 @@ struct _Hashtable_iterator {
   _Hashtable* _M_ht;
 
   _Hashtable_iterator(_Node* __n, _Hashtable* __tab)
-    : _M_cur(__n), _M_ht(__tab) {}
+    : _M_cur(__n)
+    , _M_ht(__tab)
+  {
+  }
   _Hashtable_iterator() {}
   reference operator*() const { return _M_cur->_M_val; }
   pointer operator->() const { return &(operator*()); }
   iterator& operator++();
   iterator operator++(int);
-  bool operator==(const iterator& __it) const
-    { return _M_cur == __it._M_cur; }
-  bool operator!=(const iterator& __it) const
-    { return _M_cur != __it._M_cur; }
+  bool operator==(const iterator& __it) const { return _M_cur == __it._M_cur; }
+  bool operator!=(const iterator& __it) const { return _M_cur != __it._M_cur; }
 };
 
-
-template <class _Val, class _Key, class _HashFcn,
-          class _ExtractKey, class _EqualKey, class _Alloc>
-struct _Hashtable_const_iterator {
-  typedef hashtable<_Val,_Key,_HashFcn,_ExtractKey,_EqualKey,_Alloc>
-          _Hashtable;
-  typedef _Hashtable_iterator<_Val,_Key,_HashFcn,
-                              _ExtractKey,_EqualKey,_Alloc>
-          iterator;
-  typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn,
-                                    _ExtractKey, _EqualKey, _Alloc>
-          const_iterator;
+template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
+          class _EqualKey, class _Alloc>
+struct _Hashtable_const_iterator
+{
+  typedef hashtable<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc>
+    _Hashtable;
+  typedef _Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey,
+                              _Alloc>
+    iterator;
+  typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey,
+                                    _EqualKey, _Alloc>
+    const_iterator;
   typedef _Hashtable_node<_Val> _Node;
 
   typedef std::forward_iterator_tag iterator_category;
@@ -160,39 +152,53 @@ struct _Hashtable_const_iterator {
   const _Hashtable* _M_ht;
 
   _Hashtable_const_iterator(const _Node* __n, const _Hashtable* __tab)
-    : _M_cur(__n), _M_ht(__tab) {}
+    : _M_cur(__n)
+    , _M_ht(__tab)
+  {
+  }
   _Hashtable_const_iterator() {}
   _Hashtable_const_iterator(const iterator& __it)
-    : _M_cur(__it._M_cur), _M_ht(__it._M_ht) {}
+    : _M_cur(__it._M_cur)
+    , _M_ht(__it._M_ht)
+  {
+  }
   reference operator*() const { return _M_cur->_M_val; }
   pointer operator->() const { return &(operator*()); }
   const_iterator& operator++();
   const_iterator operator++(int);
   bool operator==(const const_iterator& __it) const
-    { return _M_cur == __it._M_cur; }
+  {
+    return _M_cur == __it._M_cur;
+  }
   bool operator!=(const const_iterator& __it) const
-    { return _M_cur != __it._M_cur; }
+  {
+    return _M_cur != __it._M_cur;
+  }
 };
 
 // Note: assumes long is at least 32 bits.
-enum { _stl_num_primes = 31 };
+enum
+{
+  _stl_num_primes = 31
+};
 
 // create a function with a static local to that function that returns
 // the static
-static inline const unsigned long* get_stl_prime_list() {
-
-static const unsigned long _stl_prime_list[_stl_num_primes] =
+static inline const unsigned long* get_stl_prime_list()
 {
-  5ul,          11ul,         23ul,
-  53ul,         97ul,         193ul,       389ul,       769ul,
-  1543ul,       3079ul,       6151ul,      12289ul,     24593ul,
-  49157ul,      98317ul,      196613ul,    393241ul,    786433ul,
-  1572869ul,    3145739ul,    6291469ul,   12582917ul,  25165843ul,
-  50331653ul,   100663319ul,  201326611ul, 402653189ul, 805306457ul,
-  1610612741ul, 3221225473ul, 4294967291ul
-};
 
-return &_stl_prime_list[0]; }
+  static const unsigned long _stl_prime_list[_stl_num_primes] = {
+    5ul,         11ul,        23ul,        53ul,         97ul,
+    193ul,       389ul,       769ul,       1543ul,       3079ul,
+    6151ul,      12289ul,     24593ul,     49157ul,      98317ul,
+    196613ul,    393241ul,    786433ul,    1572869ul,    3145739ul,
+    6291469ul,   12582917ul,  25165843ul,  50331653ul,   100663319ul,
+    201326611ul, 402653189ul, 805306457ul, 1610612741ul, 3221225473ul,
+    4294967291ul
+  };
+
+  return &_stl_prime_list[0];
+}
 
 static inline size_t _stl_next_prime(size_t __n)
 {
@@ -208,8 +214,8 @@ template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
 class hashtable;
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-bool operator==(const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht1,
-                const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht2);
+bool operator==(const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht1,
+                const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht2);
 
 // Hashtables handle allocators a bit differently than other containers
 //  do.  If we're using standard-conforming allocators, then a hashtable
@@ -219,20 +225,21 @@ bool operator==(const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht1,
 //  Additionally, a base class wouldn't serve any other purposes; it
 //  wouldn't, for example, simplify the exception-handling code.
 
-template <class _Val, class _Key, class _HashFcn,
-          class _ExtractKey, class _EqualKey, class _Alloc>
-class hashtable {
+template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
+          class _EqualKey, class _Alloc>
+class hashtable
+{
 public:
   typedef _Key key_type;
   typedef _Val value_type;
   typedef _HashFcn hasher;
   typedef _EqualKey key_equal;
 
-  typedef size_t            size_type;
-  typedef ptrdiff_t         difference_type;
-  typedef value_type*       pointer;
+  typedef size_t size_type;
+  typedef ptrdiff_t difference_type;
+  typedef value_type* pointer;
   typedef const value_type* const_pointer;
-  typedef value_type&       reference;
+  typedef value_type& reference;
   typedef const value_type& const_reference;
 
   hasher hash_funct() const { return _M_hash; }
@@ -245,75 +252,74 @@ public:
   typedef typename _Alloc::template rebind<_Val>::other allocator_type;
   allocator_type get_allocator() const { return _M_node_allocator; }
 private:
-  typedef typename _Alloc::template rebind<_Node>::other _M_node_allocator_type;
-  typedef typename _Alloc::template rebind<_Node*>::other _M_node_ptr_allocator_type;
-  typedef std::vector<_Node*,_M_node_ptr_allocator_type> _M_buckets_type;
+  typedef
+    typename _Alloc::template rebind<_Node>::other _M_node_allocator_type;
+  typedef
+    typename _Alloc::template rebind<_Node*>::other _M_node_ptr_allocator_type;
+  typedef std::vector<_Node*, _M_node_ptr_allocator_type> _M_buckets_type;
 
 private:
   _M_node_allocator_type _M_node_allocator;
-  hasher                 _M_hash;
-  key_equal              _M_equals;
-  _ExtractKey            _M_get_key;
-  _M_buckets_type        _M_buckets;
-  size_type              _M_num_elements;
+  hasher _M_hash;
+  key_equal _M_equals;
+  _ExtractKey _M_get_key;
+  _M_buckets_type _M_buckets;
+  size_type _M_num_elements;
 
   _Node* _M_get_node() { return _M_node_allocator.allocate(1); }
   void _M_put_node(_Node* __p) { _M_node_allocator.deallocate(__p, 1); }
 
 public:
-  typedef _Hashtable_iterator<_Val,_Key,_HashFcn,_ExtractKey,_EqualKey,_Alloc>
-          iterator;
-  typedef _Hashtable_const_iterator<_Val,_Key,_HashFcn,_ExtractKey,_EqualKey,
-                                    _Alloc>
-          const_iterator;
-
-  friend struct
-  _Hashtable_iterator<_Val,_Key,_HashFcn,_ExtractKey,_EqualKey,_Alloc>;
-  friend struct
-  _Hashtable_const_iterator<_Val,_Key,_HashFcn,_ExtractKey,_EqualKey,_Alloc>;
+  typedef _Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey,
+                              _Alloc>
+    iterator;
+  typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey,
+                                    _EqualKey, _Alloc>
+    const_iterator;
+
+  friend struct _Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey,
+                                    _EqualKey, _Alloc>;
+  friend struct _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey,
+                                          _EqualKey, _Alloc>;
 
 public:
-  hashtable(size_type __n,
-            const _HashFcn&    __hf,
-            const _EqualKey&   __eql,
+  hashtable(size_type __n, const _HashFcn& __hf, const _EqualKey& __eql,
             const _ExtractKey& __ext,
             const allocator_type& __a = allocator_type())
-    : _M_node_allocator(__a),
-      _M_hash(__hf),
-      _M_equals(__eql),
-      _M_get_key(__ext),
-      _M_buckets(__a),
-      _M_num_elements(0)
+    : _M_node_allocator(__a)
+    , _M_hash(__hf)
+    , _M_equals(__eql)
+    , _M_get_key(__ext)
+    , _M_buckets(__a)
+    , _M_num_elements(0)
   {
     _M_initialize_buckets(__n);
   }
 
-  hashtable(size_type __n,
-            const _HashFcn&    __hf,
-            const _EqualKey&   __eql,
+  hashtable(size_type __n, const _HashFcn& __hf, const _EqualKey& __eql,
             const allocator_type& __a = allocator_type())
-    : _M_node_allocator(__a),
-      _M_hash(__hf),
-      _M_equals(__eql),
-      _M_get_key(_ExtractKey()),
-      _M_buckets(__a),
-      _M_num_elements(0)
+    : _M_node_allocator(__a)
+    , _M_hash(__hf)
+    , _M_equals(__eql)
+    , _M_get_key(_ExtractKey())
+    , _M_buckets(__a)
+    , _M_num_elements(0)
   {
     _M_initialize_buckets(__n);
   }
 
   hashtable(const hashtable& __ht)
-    : _M_node_allocator(__ht.get_allocator()),
-      _M_hash(__ht._M_hash),
-      _M_equals(__ht._M_equals),
-      _M_get_key(__ht._M_get_key),
-      _M_buckets(__ht.get_allocator()),
-      _M_num_elements(0)
+    : _M_node_allocator(__ht.get_allocator())
+    , _M_hash(__ht._M_hash)
+    , _M_equals(__ht._M_equals)
+    , _M_get_key(__ht._M_get_key)
+    , _M_buckets(__ht.get_allocator())
+    , _M_num_elements(0)
   {
     _M_copy_from(__ht);
   }
 
-  hashtable& operator= (const hashtable& __ht)
+  hashtable& operator=(const hashtable& __ht)
   {
     if (&__ht != this) {
       clear();
@@ -360,15 +366,15 @@ public:
 
   const_iterator end() const { return const_iterator(0, this); }
 
-  friend bool operator==<>(const hashtable&,
-                           const hashtable&);
+  friend bool operator==<>(const hashtable&, const hashtable&);
 
 public:
-
   size_type bucket_count() const { return _M_buckets.size(); }
 
   size_type max_bucket_count() const
-    { return get_stl_prime_list()[(int)_stl_num_primes - 1]; }
+  {
+    return get_stl_prime_list()[(int)_stl_num_primes - 1];
+  }
 
   size_type elems_in_bucket(size_type __bucket) const
   {
@@ -396,14 +402,16 @@ public:
   template <class _InputIterator>
   void insert_unique(_InputIterator __f, _InputIterator __l)
   {
-    insert_unique(__f, __l,
+    insert_unique(
+      __f, __l,
       typename std::iterator_traits<_InputIterator>::iterator_category());
   }
 
   template <class _InputIterator>
   void insert_equal(_InputIterator __f, _InputIterator __l)
   {
-    insert_equal(__f, __l,
+    insert_equal(
+      __f, __l,
       typename std::iterator_traits<_InputIterator>::iterator_category());
   }
 
@@ -411,7 +419,7 @@ public:
   void insert_unique(_InputIterator __f, _InputIterator __l,
                      std::input_iterator_tag)
   {
-    for ( ; __f != __l; ++__f)
+    for (; __f != __l; ++__f)
       insert_unique(*__f);
   }
 
@@ -419,7 +427,7 @@ public:
   void insert_equal(_InputIterator __f, _InputIterator __l,
                     std::input_iterator_tag)
   {
-    for ( ; __f != __l; ++__f)
+    for (; __f != __l; ++__f)
       insert_equal(*__f);
   }
 
@@ -430,7 +438,7 @@ public:
     size_type __n = 0;
     std::distance(__f, __l, __n);
     resize(_M_num_elements + __n);
-    for ( ; __n > 0; --__n, ++__f)
+    for (; __n > 0; --__n, ++__f)
       insert_unique_noresize(*__f);
   }
 
@@ -441,7 +449,7 @@ public:
     size_type __n = 0;
     std::distance(__f, __l, __n);
     resize(_M_num_elements + __n);
-    for ( ; __n > 0; --__n, ++__f)
+    for (; __n > 0; --__n, ++__f)
       insert_equal_noresize(*__f);
   }
 
@@ -451,10 +459,10 @@ public:
   {
     size_type __n = _M_bkt_num_key(__key);
     _Node* __first;
-    for ( __first = _M_buckets[__n];
-          __first && !_M_equals(_M_get_key(__first->_M_val), __key);
-          __first = __first->_M_next)
-      {}
+    for (__first = _M_buckets[__n];
+         __first && !_M_equals(_M_get_key(__first->_M_val), __key);
+         __first = __first->_M_next) {
+    }
     return iterator(__first, this);
   }
 
@@ -462,10 +470,10 @@ public:
   {
     size_type __n = _M_bkt_num_key(__key);
     const _Node* __first;
-    for ( __first = _M_buckets[__n];
-          __first && !_M_equals(_M_get_key(__first->_M_val), __key);
-          __first = __first->_M_next)
-      {}
+    for (__first = _M_buckets[__n];
+         __first && !_M_equals(_M_get_key(__first->_M_val), __key);
+         __first = __first->_M_next) {
+    }
     return const_iterator(__first, this);
   }
 
@@ -480,11 +488,10 @@ public:
     return __result;
   }
 
-  std::pair<iterator, iterator>
-  equal_range(const key_type& __key);
+  std::pair<iterator, iterator> equal_range(const key_type& __key);
 
-  std::pair<const_iterator, const_iterator>
-  equal_range(const key_type& __key) const;
+  std::pair<const_iterator, const_iterator> equal_range(
+    const key_type& __key) const;
 
   size_type erase(const key_type& __key);
   void erase(const iterator& __it);
@@ -497,14 +504,13 @@ public:
   void clear();
 
 private:
-  size_type _M_next_size(size_type __n) const
-    { return _stl_next_prime(__n); }
+  size_type _M_next_size(size_type __n) const { return _stl_next_prime(__n); }
 
   void _M_initialize_buckets(size_type __n)
   {
     const size_type __n_buckets = _M_next_size(__n);
     _M_buckets.reserve(__n_buckets);
-    _M_buckets.insert(_M_buckets.end(), __n_buckets, (_Node*) 0);
+    _M_buckets.insert(_M_buckets.end(), __n_buckets, (_Node*)0);
     _M_num_elements = 0;
   }
 
@@ -528,15 +534,12 @@ private:
     return _M_bkt_num_key(_M_get_key(__obj), __n);
   }
 
-  void construct(_Val* p, const _Val& v)
-    {
-    new (p) _Val(v);
-    }
+  void construct(_Val* p, const _Val& v) { new (p) _Val(v); }
   void destroy(_Val* p)
-    {
+  {
     (void)p;
     p->~_Val();
-    }
+  }
 
   _Node* _M_new_node(const value_type& __obj)
   {
@@ -545,8 +548,10 @@ private:
     try {
       construct(&__n->_M_val, __obj);
       return __n;
+    } catch (...) {
+      _M_put_node(__n);
+      throw;
     }
-    catch(...) {_M_put_node(__n); throw;}
   }
 
   void _M_delete_node(_Node* __n)
@@ -559,13 +564,12 @@ private:
   void _M_erase_bucket(const size_type __n, _Node* __last);
 
   void _M_copy_from(const hashtable& __ht);
-
 };
 
 template <class _Val, class _Key, class _HF, class _ExK, class _EqK,
           class _All>
-_Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>&
-_Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++()
+_Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>&
+  _Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>::operator++()
 {
   const _Node* __old = _M_cur;
   _M_cur = _M_cur->_M_next;
@@ -579,8 +583,8 @@ _Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++()
 
 template <class _Val, class _Key, class _HF, class _ExK, class _EqK,
           class _All>
-inline _Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>
-_Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++(int)
+inline _Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>
+  _Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>::operator++(int)
 {
   iterator __tmp = *this;
   ++*this;
@@ -589,8 +593,8 @@ _Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++(int)
 
 template <class _Val, class _Key, class _HF, class _ExK, class _EqK,
           class _All>
-_Hashtable_const_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>&
-_Hashtable_const_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++()
+_Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>&
+  _Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>::operator++()
 {
   const _Node* __old = _M_cur;
   _M_cur = _M_cur->_M_next;
@@ -604,8 +608,8 @@ _Hashtable_const_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++()
 
 template <class _Val, class _Key, class _HF, class _ExK, class _EqK,
           class _All>
-inline _Hashtable_const_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>
-_Hashtable_const_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++(int)
+inline _Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>
+  _Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>::operator++(int)
 {
   const_iterator __tmp = *this;
   ++*this;
@@ -613,18 +617,18 @@ _Hashtable_const_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>::operator++(int)
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-bool operator==(const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht1,
-                const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht2)
+bool operator==(const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht1,
+                const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht2)
 {
-  typedef typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::_Node _Node;
+  typedef typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::_Node _Node;
   if (__ht1._M_buckets.size() != __ht2._M_buckets.size())
     return false;
   for (int __n = 0; __n < __ht1._M_buckets.size(); ++__n) {
     _Node* __cur1 = __ht1._M_buckets[__n];
     _Node* __cur2 = __ht2._M_buckets[__n];
-    for ( ; __cur1 && __cur2 && __cur1->_M_val == __cur2->_M_val;
-          __cur1 = __cur1->_M_next, __cur2 = __cur2->_M_next)
-      {}
+    for (; __cur1 && __cur2 && __cur1->_M_val == __cur2->_M_val;
+         __cur1 = __cur1->_M_next, __cur2 = __cur2->_M_next) {
+    }
     if (__cur1 || __cur2)
       return false;
   }
@@ -632,22 +636,24 @@ bool operator==(const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht1,
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-inline bool operator!=(const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht1,
-                       const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht2) {
+inline bool operator!=(const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht1,
+                       const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht2)
+{
   return !(__ht1 == __ht2);
 }
 
 template <class _Val, class _Key, class _HF, class _Extract, class _EqKey,
           class _All>
 inline void swap(hashtable<_Val, _Key, _HF, _Extract, _EqKey, _All>& __ht1,
-                 hashtable<_Val, _Key, _HF, _Extract, _EqKey, _All>& __ht2) {
+                 hashtable<_Val, _Key, _HF, _Extract, _EqKey, _All>& __ht2)
+{
   __ht1.swap(__ht2);
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-std::pair<typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::iterator, bool>
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
-  ::insert_unique_noresize(const value_type& __obj)
+std::pair<typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::iterator, bool>
+hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::insert_unique_noresize(
+  const value_type& __obj)
 {
   const size_type __n = _M_bkt_num(__obj);
   _Node* __first = _M_buckets[__n];
@@ -664,9 +670,9 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::iterator
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
-  ::insert_equal_noresize(const value_type& __obj)
+typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::iterator
+hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::insert_equal_noresize(
+  const value_type& __obj)
 {
   const size_type __n = _M_bkt_num(__obj);
   _Node* __first = _M_buckets[__n];
@@ -688,8 +694,8 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::reference
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::find_or_insert(const value_type& __obj)
+typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::reference hashtable<
+  _Val, _Key, _HF, _Ex, _Eq, _All>::find_or_insert(const value_type& __obj)
 {
   resize(_M_num_elements + 1);
 
@@ -708,9 +714,9 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::find_or_insert(const value_type& __obj)
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-std::pair<typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::iterator,
-          typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::iterator>
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::equal_range(const key_type& __key)
+std::pair<typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::iterator,
+          typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::iterator>
+hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::equal_range(const key_type& __key)
 {
   typedef std::pair<iterator, iterator> _Pii;
   const size_type __n = _M_bkt_num_key(__key);
@@ -723,27 +729,25 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::equal_range(const key_type& __key)
       for (size_type __m = __n + 1; __m < _M_buckets.size(); ++__m)
         if (_M_buckets[__m])
           return _Pii(iterator(__first, this),
-                     iterator(_M_buckets[__m], this));
+                      iterator(_M_buckets[__m], this));
       return _Pii(iterator(__first, this), end());
     }
   return _Pii(end(), end());
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-std::pair<typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::const_iterator,
-          typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::const_iterator>
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
-  ::equal_range(const key_type& __key) const
+std::pair<typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::const_iterator,
+          typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::const_iterator>
+hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::equal_range(
+  const key_type& __key) const
 {
   typedef std::pair<const_iterator, const_iterator> _Pii;
   const size_type __n = _M_bkt_num_key(__key);
 
-  for (const _Node* __first = _M_buckets[__n] ;
-       __first;
+  for (const _Node* __first = _M_buckets[__n]; __first;
        __first = __first->_M_next) {
     if (_M_equals(_M_get_key(__first->_M_val), __key)) {
-      for (const _Node* __cur = __first->_M_next;
-           __cur;
+      for (const _Node* __cur = __first->_M_next; __cur;
            __cur = __cur->_M_next)
         if (!_M_equals(_M_get_key(__cur->_M_val), __key))
           return _Pii(const_iterator(__first, this),
@@ -759,8 +763,8 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-typename hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::size_type
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const key_type& __key)
+typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::size_type
+hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::erase(const key_type& __key)
 {
   const size_type __n = _M_bkt_num_key(__key);
   _Node* __first = _M_buckets[__n];
@@ -776,8 +780,7 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const key_type& __key)
         __next = __cur->_M_next;
         ++__erased;
         --_M_num_elements;
-      }
-      else {
+      } else {
         __cur = __next;
         __next = __cur->_M_next;
       }
@@ -793,7 +796,7 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const key_type& __key)
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const iterator& __it)
+void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::erase(const iterator& __it)
 {
   _Node* __p = __it._M_cur;
   if (__p) {
@@ -804,8 +807,7 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const iterator& __it)
       _M_buckets[__n] = __cur->_M_next;
       _M_delete_node(__cur);
       --_M_num_elements;
-    }
-    else {
+    } else {
       _Node* __next = __cur->_M_next;
       while (__next) {
         if (__next == __p) {
@@ -813,8 +815,7 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const iterator& __it)
           _M_delete_node(__next);
           --_M_num_elements;
           break;
-        }
-        else {
+        } else {
           __cur = __next;
           __next = __cur->_M_next;
         }
@@ -824,13 +825,13 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const iterator& __it)
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
-  ::erase(iterator __first, iterator __last)
+void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::erase(iterator __first,
+                                                       iterator __last)
 {
-  size_type __f_bucket = __first._M_cur ?
-    _M_bkt_num(__first._M_cur->_M_val) : _M_buckets.size();
-  size_type __l_bucket = __last._M_cur ?
-    _M_bkt_num(__last._M_cur->_M_val) : _M_buckets.size();
+  size_type __f_bucket =
+    __first._M_cur ? _M_bkt_num(__first._M_cur->_M_val) : _M_buckets.size();
+  size_type __l_bucket =
+    __last._M_cur ? _M_bkt_num(__last._M_cur->_M_val) : _M_buckets.size();
 
   if (__first._M_cur == __last._M_cur)
     return;
@@ -846,9 +847,8 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-inline void
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const_iterator __first,
-                                             const_iterator __last)
+inline void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::erase(
+  const_iterator __first, const_iterator __last)
 {
   erase(iterator(const_cast<_Node*>(__first._M_cur),
                  const_cast<hashtable*>(__first._M_ht)),
@@ -857,24 +857,22 @@ hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const_iterator __first,
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-inline void
-hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::erase(const const_iterator& __it)
+inline void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::erase(
+  const const_iterator& __it)
 {
   erase(iterator(const_cast<_Node*>(__it._M_cur),
                  const_cast<hashtable*>(__it._M_ht)));
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
-  ::resize(size_type __num_elements_hint)
+void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::resize(
+  size_type __num_elements_hint)
 {
   const size_type __old_n = _M_buckets.size();
   if (__num_elements_hint > __old_n) {
     const size_type __n = _M_next_size(__num_elements_hint);
     if (__n > __old_n) {
-      _M_buckets_type __tmp(
-        __n, (_Node*)(0),
-        _M_buckets.get_allocator());
+      _M_buckets_type __tmp(__n, (_Node*)(0), _M_buckets.get_allocator());
       try {
         for (size_type __bucket = 0; __bucket < __old_n; ++__bucket) {
           _Node* __first = _M_buckets[__bucket];
@@ -887,8 +885,7 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
           }
         }
         _M_buckets.swap(__tmp);
-      }
-      catch(...) {
+      } catch (...) {
         for (size_type __bucket = 0; __bucket < __tmp.size(); ++__bucket) {
           while (__tmp[__bucket]) {
             _Node* __next = __tmp[__bucket]->_M_next;
@@ -903,16 +900,15 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
-  ::_M_erase_bucket(const size_type __n, _Node* __first, _Node* __last)
+void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::_M_erase_bucket(
+  const size_type __n, _Node* __first, _Node* __last)
 {
   _Node* __cur = _M_buckets[__n];
   if (__cur == __first)
     _M_erase_bucket(__n, __last);
   else {
     _Node* __next;
-    for (__next = __cur->_M_next;
-         __next != __first;
+    for (__next = __cur->_M_next; __next != __first;
          __cur = __next, __next = __cur->_M_next)
       ;
     while (__next != __last) {
@@ -925,8 +921,8 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
-  ::_M_erase_bucket(const size_type __n, _Node* __last)
+void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::_M_erase_bucket(
+  const size_type __n, _Node* __last)
 {
   _Node* __cur = _M_buckets[__n];
   while (__cur != __last) {
@@ -939,7 +935,7 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
 }
 
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::clear()
+void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::clear()
 {
   for (size_type __i = 0; __i < _M_buckets.size(); ++__i) {
     _Node* __cur = _M_buckets[__i];
@@ -953,14 +949,13 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>::clear()
   _M_num_elements = 0;
 }
 
-
 template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
-  ::_M_copy_from(const hashtable& __ht)
+void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::_M_copy_from(
+  const hashtable& __ht)
 {
   _M_buckets.clear();
   _M_buckets.reserve(__ht._M_buckets.size());
-  _M_buckets.insert(_M_buckets.end(), __ht._M_buckets.size(), (_Node*) 0);
+  _M_buckets.insert(_M_buckets.end(), __ht._M_buckets.size(), (_Node*)0);
   try {
     for (size_type __i = 0; __i < __ht._M_buckets.size(); ++__i) {
       const _Node* __cur = __ht._M_buckets[__i];
@@ -968,8 +963,7 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
         _Node* __copy = _M_new_node(__cur->_M_val);
         _M_buckets[__i] = __copy;
 
-        for (_Node* __next = __cur->_M_next;
-             __next;
+        for (_Node *__next = __cur->_M_next; __next;
              __cur = __next, __next = __cur->_M_next) {
           __copy->_M_next = _M_new_node(__next->_M_val);
           __copy = __copy->_M_next;
@@ -977,21 +971,23 @@ void hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>
       }
     }
     _M_num_elements = __ht._M_num_elements;
+  } catch (...) {
+    clear();
+    throw;
   }
-  catch(...) {clear(); throw;}
 }
 
 } // namespace @KWSYS_NAMESPACE@
 
 // Undo warning suppression.
 #if defined(__clang__) && defined(__has_warning)
-# if __has_warning("-Wdeprecated")
-#  pragma clang diagnostic pop
-# endif
+#if __has_warning("-Wdeprecated")
+#pragma clang diagnostic pop
+#endif
 #endif
 
 #if defined(_MSC_VER)
-# pragma warning (pop)
+#pragma warning(pop)
 #endif
 
 #endif
diff --git a/Source/kwsys/kwsysHeaderDump.pl b/Source/kwsys/kwsysHeaderDump.pl
index 0dc4a52..e3391e7 100755
--- a/Source/kwsys/kwsysHeaderDump.pl
+++ b/Source/kwsys/kwsysHeaderDump.pl
@@ -1,15 +1,6 @@
 #!/usr/bin/perl
-#=============================================================================
-# KWSys - Kitware System Library
-# 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.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing#kwsys for details.
 
 if ( $#ARGV+1 < 2 )
 {
diff --git a/Source/kwsys/kwsysPlatformTests.cmake b/Source/kwsys/kwsysPlatformTests.cmake
index 0da0f63..5386a49 100644
--- a/Source/kwsys/kwsysPlatformTests.cmake
+++ b/Source/kwsys/kwsysPlatformTests.cmake
@@ -1,14 +1,6 @@
-#=============================================================================
-# KWSys - Kitware System Library
-# 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.
-#=============================================================================
+# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+# file Copyright.txt or https://cmake.org/licensing#kwsys for details.
+
 SET(KWSYS_PLATFORM_TEST_FILE_C kwsysPlatformTestsC.c)
 SET(KWSYS_PLATFORM_TEST_FILE_CXX kwsysPlatformTestsCXX.cxx)
 
diff --git a/Source/kwsys/kwsysPlatformTestsC.c b/Source/kwsys/kwsysPlatformTestsC.c
index e602964..d12fac0 100644
--- a/Source/kwsys/kwsysPlatformTestsC.c
+++ b/Source/kwsys/kwsysPlatformTestsC.c
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 /*
   Macros to define main() in a cross-platform way.
 
@@ -26,21 +17,23 @@
     }
 */
 #if defined(__CLASSIC_C__)
-# define KWSYS_PLATFORM_TEST_C_MAIN() \
-  main()
-# define KWSYS_PLATFORM_TEST_C_MAIN_ARGS(argc, argv) \
-  main(argc,argv) int argc; char* argv[];
+#define KWSYS_PLATFORM_TEST_C_MAIN() main()
+#define KWSYS_PLATFORM_TEST_C_MAIN_ARGS(argc, argv)                           \
+  main(argc, argv) int argc;                                                  \
+  char* argv[];
 #else
-# define KWSYS_PLATFORM_TEST_C_MAIN() \
-  main(void)
-# define KWSYS_PLATFORM_TEST_C_MAIN_ARGS(argc, argv) \
+#define KWSYS_PLATFORM_TEST_C_MAIN() main(void)
+#define KWSYS_PLATFORM_TEST_C_MAIN_ARGS(argc, argv)                           \
   main(int argc, char* argv[])
 #endif
 
 /*--------------------------------------------------------------------------*/
 #ifdef TEST_KWSYS_C_HAS_PTRDIFF_T
 #include <stddef.h>
-int f(ptrdiff_t n) { return n > 0; }
+int f(ptrdiff_t n)
+{
+  return n > 0;
+}
 int KWSYS_PLATFORM_TEST_C_MAIN()
 {
   char* p = 0;
@@ -53,7 +46,10 @@ int KWSYS_PLATFORM_TEST_C_MAIN()
 /*--------------------------------------------------------------------------*/
 #ifdef TEST_KWSYS_C_HAS_SSIZE_T
 #include <unistd.h>
-int f(ssize_t n) { return (int)n; }
+int f(ssize_t n)
+{
+  return (int)n;
+}
 int KWSYS_PLATFORM_TEST_C_MAIN()
 {
   ssize_t n = 0;
@@ -65,28 +61,28 @@ int KWSYS_PLATFORM_TEST_C_MAIN()
 #ifdef TEST_KWSYS_C_TYPE_MACROS
 char* info_macros =
 #if defined(__SIZEOF_SHORT__)
-"INFO:macro[__SIZEOF_SHORT__]\n"
+  "INFO:macro[__SIZEOF_SHORT__]\n"
 #endif
 #if defined(__SIZEOF_INT__)
-"INFO:macro[__SIZEOF_INT__]\n"
+  "INFO:macro[__SIZEOF_INT__]\n"
 #endif
 #if defined(__SIZEOF_LONG__)
-"INFO:macro[__SIZEOF_LONG__]\n"
+  "INFO:macro[__SIZEOF_LONG__]\n"
 #endif
 #if defined(__SIZEOF_LONG_LONG__)
-"INFO:macro[__SIZEOF_LONG_LONG__]\n"
+  "INFO:macro[__SIZEOF_LONG_LONG__]\n"
 #endif
 #if defined(__SHORT_MAX__)
-"INFO:macro[__SHORT_MAX__]\n"
+  "INFO:macro[__SHORT_MAX__]\n"
 #endif
 #if defined(__INT_MAX__)
-"INFO:macro[__INT_MAX__]\n"
+  "INFO:macro[__INT_MAX__]\n"
 #endif
 #if defined(__LONG_MAX__)
-"INFO:macro[__LONG_MAX__]\n"
+  "INFO:macro[__LONG_MAX__]\n"
 #endif
 #if defined(__LONG_LONG_MAX__)
-"INFO:macro[__LONG_LONG_MAX__]\n"
+  "INFO:macro[__LONG_LONG_MAX__]\n"
 #endif
   "";
 
diff --git a/Source/kwsys/kwsysPlatformTestsCXX.cxx b/Source/kwsys/kwsysPlatformTestsCXX.cxx
index b35808b..01c6951 100644
--- a/Source/kwsys/kwsysPlatformTestsCXX.cxx
+++ b/Source/kwsys/kwsysPlatformTestsCXX.cxx
@@ -1,21 +1,18 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifdef TEST_KWSYS_CXX_HAS_CSTDIO
 #include <cstdio>
-int main() { return 0; }
+int main()
+{
+  return 0;
+}
 #endif
 
 #ifdef TEST_KWSYS_CXX_HAS_LONG_LONG
-long long f(long long n) { return n; }
+long long f(long long n)
+{
+  return n;
+}
 int main()
 {
   long long n = 0;
@@ -24,7 +21,10 @@ int main()
 #endif
 
 #ifdef TEST_KWSYS_CXX_HAS___INT64
-__int64 f(__int64 n) { return n; }
+__int64 f(__int64 n)
+{
+  return n;
+}
 int main()
 {
   __int64 n = 0;
@@ -34,6 +34,7 @@ int main()
 
 #ifdef TEST_KWSYS_CXX_STAT_HAS_ST_MTIM
 #include <sys/types.h>
+
 #include <sys/stat.h>
 #include <unistd.h>
 int main()
@@ -47,6 +48,7 @@ int main()
 
 #ifdef TEST_KWSYS_CXX_STAT_HAS_ST_MTIMESPEC
 #include <sys/types.h>
+
 #include <sys/stat.h>
 #include <unistd.h>
 int main()
@@ -59,7 +61,9 @@ int main()
 #endif
 
 #ifdef TEST_KWSYS_CXX_SAME_LONG_AND___INT64
-void function(long**) {}
+void function(long**)
+{
+}
 int main()
 {
   __int64** p = 0;
@@ -69,7 +73,9 @@ int main()
 #endif
 
 #ifdef TEST_KWSYS_CXX_SAME_LONG_LONG_AND___INT64
-void function(long long**) {}
+void function(long long**)
+{
+}
 int main()
 {
   __int64** p = 0;
@@ -79,10 +85,10 @@ int main()
 #endif
 
 #ifdef TEST_KWSYS_IOS_HAS_ISTREAM_LONG_LONG
-# include <iostream>
+#include <iostream>
 int test_istream(std::istream& is, long long& x)
 {
-  return (is >> x)? 1:0;
+  return (is >> x) ? 1 : 0;
 }
 int main()
 {
@@ -92,10 +98,10 @@ int main()
 #endif
 
 #ifdef TEST_KWSYS_IOS_HAS_OSTREAM_LONG_LONG
-# include <iostream>
+#include <iostream>
 int test_ostream(std::ostream& os, long long x)
 {
-  return (os << x)? 1:0;
+  return (os << x) ? 1 : 0;
 }
 int main()
 {
@@ -105,10 +111,10 @@ int main()
 #endif
 
 #ifdef TEST_KWSYS_IOS_HAS_ISTREAM___INT64
-# include <iostream>
+#include <iostream>
 int test_istream(std::istream& is, __int64& x)
 {
-  return (is >> x)? 1:0;
+  return (is >> x) ? 1 : 0;
 }
 int main()
 {
@@ -118,10 +124,10 @@ int main()
 #endif
 
 #ifdef TEST_KWSYS_IOS_HAS_OSTREAM___INT64
-# include <iostream>
+#include <iostream>
 int test_ostream(std::ostream& os, __int64 x)
 {
-  return (os << x)? 1:0;
+  return (os << x) ? 1 : 0;
 }
 int main()
 {
@@ -137,30 +143,31 @@ int main()
 #define _LARGE_FILES
 #define _FILE_OFFSET_BITS 64
 #include <sys/types.h>
-#include <sys/stat.h>
+
 #include <assert.h>
+#include <sys/stat.h>
 #if KWSYS_CXX_HAS_CSTDIO
-# include <cstdio>
+#include <cstdio>
 #endif
 #include <stdio.h>
 
-int main(int, char **argv)
+int main(int, char** argv)
 {
-  /* check that off_t can hold 2^63 - 1 and perform basic operations... */
-#define OFF_T_64 (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+/* check that off_t can hold 2^63 - 1 and perform basic operations... */
+#define OFF_T_64 (((off_t)1 << 62) - 1 + ((off_t)1 << 62))
   if (OFF_T_64 % 2147483647 != 1)
     return 1;
 
   // stat breaks on SCO OpenServer
   struct stat buf;
-  stat( argv[0], &buf );
+  stat(argv[0], &buf);
   if (!S_ISREG(buf.st_mode))
     return 2;
 
-  FILE *file = fopen( argv[0], "r" );
-  off_t offset = ftello( file );
-  fseek( file, offset, SEEK_CUR );
-  fclose( file );
+  FILE* file = fopen(argv[0], "r");
+  off_t offset = ftello(file);
+  fseek(file, offset, SEEK_CUR);
+  fclose(file);
   return 0;
 }
 #endif
@@ -187,14 +194,14 @@ int main()
 int main()
 {
   char* e = environ[0];
-  return e? 0:1;
+  return e ? 0 : 1;
 }
 #endif
 
 #ifdef TEST_KWSYS_CXX_HAS_GETLOADAVG
 // Match feature definitions from SystemInformation.cxx
 #if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
-# define _GNU_SOURCE
+#define _GNU_SOURCE
 #endif
 #include <stdlib.h>
 int main()
@@ -205,17 +212,17 @@ int main()
 #endif
 
 #ifdef TEST_KWSYS_CXX_HAS_RLIMIT64
-# if defined(KWSYS_HAS_LFS)
-#  define _LARGEFILE_SOURCE
-#  define _LARGEFILE64_SOURCE
-#  define _LARGE_FILES
-#  define _FILE_OFFSET_BITS 64
-# endif
-# include <sys/resource.h>
+#if defined(KWSYS_HAS_LFS)
+#define _LARGEFILE_SOURCE
+#define _LARGEFILE64_SOURCE
+#define _LARGE_FILES
+#define _FILE_OFFSET_BITS 64
+#endif
+#include <sys/resource.h>
 int main()
 {
   struct rlimit64 rlim;
-  return getrlimit64(0,&rlim);
+  return getrlimit64(0, &rlim);
 }
 #endif
 
@@ -223,7 +230,7 @@ int main()
 #include <stdlib.h>
 int main()
 {
-  const char *str="1024";
+  const char* str = "1024";
   return static_cast<int>(atoll(str));
 }
 #endif
@@ -232,7 +239,7 @@ int main()
 #include <stdlib.h>
 int main()
 {
-  const char *str="1024";
+  const char* str = "1024";
   return static_cast<int>(atol(str));
 }
 #endif
@@ -241,7 +248,7 @@ int main()
 #include <stdlib.h>
 int main()
 {
-  const char *str="1024";
+  const char* str = "1024";
   return static_cast<int>(_atoi64(str));
 }
 #endif
@@ -260,58 +267,58 @@ int main()
 #include <sys/stat.h>
 int main()
 {
-  struct timespec times[2] = {{0,UTIME_OMIT},{0,UTIME_NOW}};
+  struct timespec times[2] = { { 0, UTIME_OMIT }, { 0, UTIME_NOW } };
   return utimensat(AT_FDCWD, "/example", times, AT_SYMLINK_NOFOLLOW);
 }
 #endif
 
 #ifdef TEST_KWSYS_CXX_HAS_BACKTRACE
-#if defined(__PATHSCALE__) || defined(__PATHCC__) \
-  || (defined(__LSB_VERSION__) && (__LSB_VERSION__ < 41))
+#if defined(__PATHSCALE__) || defined(__PATHCC__) ||                          \
+  (defined(__LSB_VERSION__) && (__LSB_VERSION__ < 41))
 backtrace doesnt work with this compiler or os
 #endif
 #if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
-# define _GNU_SOURCE
+#define _GNU_SOURCE
 #endif
 #include <execinfo.h>
 int main()
 {
-  void *stackSymbols[256];
-  backtrace(stackSymbols,256);
-  backtrace_symbols(&stackSymbols[0],1);
+  void* stackSymbols[256];
+  backtrace(stackSymbols, 256);
+  backtrace_symbols(&stackSymbols[0], 1);
   return 0;
 }
 #endif
 
 #ifdef TEST_KWSYS_CXX_HAS_DLADDR
 #if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
-# define _GNU_SOURCE
+#define _GNU_SOURCE
 #endif
 #include <dlfcn.h>
 int main()
 {
   Dl_info info;
-  int ierr=dladdr((void*)main,&info);
+  int ierr = dladdr((void*)main, &info);
   return 0;
 }
 #endif
 
 #ifdef TEST_KWSYS_CXX_HAS_CXXABI
 #if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
-# define _GNU_SOURCE
+#define _GNU_SOURCE
 #endif
-#if defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5130 \
-     && __linux && __SUNPRO_CC_COMPAT == 'G'
-#  include <iostream>
+#if defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x5130 && __linux &&               \
+  __SUNPRO_CC_COMPAT == 'G'
+#include <iostream>
 #endif
 #include <cxxabi.h>
 int main()
 {
   int status = 0;
   size_t bufferLen = 512;
-  char buffer[512] = {'\0'};
-  const char *function="_ZN5kwsys17SystemInformation15GetProgramStackEii";
-  char *demangledFunction =
+  char buffer[512] = { '\0' };
+  const char* function = "_ZN5kwsys17SystemInformation15GetProgramStackEii";
+  char* demangledFunction =
     abi::__cxa_demangle(function, buffer, &bufferLen, &status);
   return status;
 }
@@ -346,11 +353,19 @@ int main()
 
 #ifdef TEST_KWSYS_STL_HAS_WSTRING
 #include <string>
-void f(std ::wstring*) {}
-int main() { return 0; }
+void f(std::wstring*)
+{
+}
+int main()
+{
+  return 0;
+}
 #endif
 
 #ifdef TEST_KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H
 #include <ext/stdio_filebuf.h>
-int main() { return 0; }
+int main()
+{
+  return 0;
+}
 #endif
diff --git a/Source/kwsys/kwsysPrivate.h b/Source/kwsys/kwsysPrivate.h
index 3a26c26..ce1b53e 100644
--- a/Source/kwsys/kwsysPrivate.h
+++ b/Source/kwsys/kwsysPrivate.h
@@ -1,16 +1,7 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef KWSYS_NAMESPACE
-# error "Do not include kwsysPrivate.h outside of kwsys c and cxx files."
+#error "Do not include kwsysPrivate.h outside of kwsys c and cxx files."
 #endif
 
 #ifndef _kwsysPrivate_h
@@ -24,7 +15,9 @@
   #include KWSYS_HEADER(Directory.hxx)
   #include KWSYS_HEADER(std/vector)
 */
+/* clang-format off */
 #define KWSYS_HEADER(x) KWSYS_HEADER0(KWSYS_NAMESPACE/x)
+/* clang-format on */
 #define KWSYS_HEADER0(x) KWSYS_HEADER1(x)
 #define KWSYS_HEADER1(x) <x>
 
@@ -37,5 +30,5 @@
 #define KWSYS_NAMESPACE_STRING1(x) #x
 
 #else
-# error "kwsysPrivate.h included multiple times."
+#error "kwsysPrivate.h included multiple times."
 #endif
diff --git a/Source/kwsys/testCommandLineArguments.cxx b/Source/kwsys/testCommandLineArguments.cxx
index 525522d..d2215d6 100644
--- a/Source/kwsys/testCommandLineArguments.cxx
+++ b/Source/kwsys/testCommandLineArguments.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(CommandLineArguments.hxx)
 
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "CommandLineArguments.hxx.in"
+#include "CommandLineArguments.hxx.in"
 #endif
 
 #include <iostream>
@@ -28,33 +19,45 @@ static void* random_ptr = reinterpret_cast<void*>(0x123);
 
 static int argument(const char* arg, const char* value, void* call_data)
 {
-  std::cout << "Got argument: \"" << arg << "\" value: \"" << (value?value:"(null)") << "\"" << std::endl;
-  if ( call_data != random_ptr )
-    {
+  std::cout << "Got argument: \"" << arg << "\" value: \""
+            << (value ? value : "(null)") << "\"" << std::endl;
+  if (call_data != random_ptr) {
     std::cerr << "Problem processing call_data" << std::endl;
     return 0;
-    }
+  }
   return 1;
 }
 
 static int unknown_argument(const char* argument, void* call_data)
 {
   std::cout << "Got unknown argument: \"" << argument << "\"" << std::endl;
-  if ( call_data != random_ptr )
-    {
+  if (call_data != random_ptr) {
     std::cerr << "Problem processing call_data" << std::endl;
     return 0;
-    }
+  }
   return 1;
 }
 
-static bool CompareTwoItemsOnList(bool i1, bool i2) { return i1 == i2; }
-static bool CompareTwoItemsOnList(int i1, int i2) { return i1 == i2; }
-static bool CompareTwoItemsOnList(double i1, double i2) { return i1 == i2; }
-static bool CompareTwoItemsOnList(const char* i1,
-  const char* i2) { return strcmp(i1, i2) == 0; }
-static bool CompareTwoItemsOnList(const std::string& i1,
-  const std::string& i2) { return i1 == i2; }
+static bool CompareTwoItemsOnList(bool i1, bool i2)
+{
+  return i1 == i2;
+}
+static bool CompareTwoItemsOnList(int i1, int i2)
+{
+  return i1 == i2;
+}
+static bool CompareTwoItemsOnList(double i1, double i2)
+{
+  return i1 == i2;
+}
+static bool CompareTwoItemsOnList(const char* i1, const char* i2)
+{
+  return strcmp(i1, i2) == 0;
+}
+static bool CompareTwoItemsOnList(const std::string& i1, const std::string& i2)
+{
+  return i1 == i2;
+}
 
 int testCommandLineArguments(int argc, char* argv[])
 {
@@ -97,73 +100,89 @@ int testCommandLineArguments(int argc, char* argv[])
 
   typedef kwsys::CommandLineArguments argT;
 
-  arg.AddArgument("--some-int-variable", argT::SPACE_ARGUMENT, &some_int_variable, "Set some random int variable");
-  arg.AddArgument("--some-double-variable", argT::CONCAT_ARGUMENT, &some_double_variable, "Set some random double variable");
-  arg.AddArgument("--some-string-variable", argT::EQUAL_ARGUMENT, &some_string_variable, "Set some random string variable");
-  arg.AddArgument("--some-stl-string-variable", argT::EQUAL_ARGUMENT, &some_stl_string_variable, "Set some random stl string variable");
-  arg.AddArgument("--some-bool-variable", argT::EQUAL_ARGUMENT, &some_bool_variable, "Set some random bool variable");
-  arg.AddArgument("--another-bool-variable", argT::NO_ARGUMENT, &some_bool_variable1, "Set some random bool variable 1");
-  arg.AddBooleanArgument("--set-bool-arg1", &bool_arg1, "Test AddBooleanArgument 1");
-  arg.AddBooleanArgument("--set-bool-arg2", &bool_arg2, "Test AddBooleanArgument 2");
-  arg.AddArgument("--some-multi-argument", argT::MULTI_ARGUMENT, &numbers_argument, "Some multiple values variable");
-  arg.AddArgument("-N", argT::SPACE_ARGUMENT, &doubles_argument, "Some explicit multiple values variable");
-  arg.AddArgument("-BB", argT::CONCAT_ARGUMENT, &bools_argument, "Some explicit multiple values variable");
-  arg.AddArgument("-SS", argT::EQUAL_ARGUMENT, &strings_argument, "Some explicit multiple values variable");
-  arg.AddArgument("-SSS", argT::MULTI_ARGUMENT, &stl_strings_argument, "Some explicit multiple values variable");
-
-  arg.AddCallback("-A", argT::NO_ARGUMENT, argument, random_ptr, "Some option -A. This option has a multiline comment. It should demonstrate how the code splits lines.");
-  arg.AddCallback("-B", argT::SPACE_ARGUMENT, argument, random_ptr, "Option -B takes argument with space");
-  arg.AddCallback("-C", argT::EQUAL_ARGUMENT, argument, random_ptr, "Option -C takes argument after =");
-  arg.AddCallback("-D", argT::CONCAT_ARGUMENT, argument, random_ptr, "This option takes concatinated argument");
+  arg.AddArgument("--some-int-variable", argT::SPACE_ARGUMENT,
+                  &some_int_variable, "Set some random int variable");
+  arg.AddArgument("--some-double-variable", argT::CONCAT_ARGUMENT,
+                  &some_double_variable, "Set some random double variable");
+  arg.AddArgument("--some-string-variable", argT::EQUAL_ARGUMENT,
+                  &some_string_variable, "Set some random string variable");
+  arg.AddArgument("--some-stl-string-variable", argT::EQUAL_ARGUMENT,
+                  &some_stl_string_variable,
+                  "Set some random stl string variable");
+  arg.AddArgument("--some-bool-variable", argT::EQUAL_ARGUMENT,
+                  &some_bool_variable, "Set some random bool variable");
+  arg.AddArgument("--another-bool-variable", argT::NO_ARGUMENT,
+                  &some_bool_variable1, "Set some random bool variable 1");
+  arg.AddBooleanArgument("--set-bool-arg1", &bool_arg1,
+                         "Test AddBooleanArgument 1");
+  arg.AddBooleanArgument("--set-bool-arg2", &bool_arg2,
+                         "Test AddBooleanArgument 2");
+  arg.AddArgument("--some-multi-argument", argT::MULTI_ARGUMENT,
+                  &numbers_argument, "Some multiple values variable");
+  arg.AddArgument("-N", argT::SPACE_ARGUMENT, &doubles_argument,
+                  "Some explicit multiple values variable");
+  arg.AddArgument("-BB", argT::CONCAT_ARGUMENT, &bools_argument,
+                  "Some explicit multiple values variable");
+  arg.AddArgument("-SS", argT::EQUAL_ARGUMENT, &strings_argument,
+                  "Some explicit multiple values variable");
+  arg.AddArgument("-SSS", argT::MULTI_ARGUMENT, &stl_strings_argument,
+                  "Some explicit multiple values variable");
+
+  arg.AddCallback("-A", argT::NO_ARGUMENT, argument, random_ptr,
+                  "Some option -A. This option has a multiline comment. It "
+                  "should demonstrate how the code splits lines.");
+  arg.AddCallback("-B", argT::SPACE_ARGUMENT, argument, random_ptr,
+                  "Option -B takes argument with space");
+  arg.AddCallback("-C", argT::EQUAL_ARGUMENT, argument, random_ptr,
+                  "Option -C takes argument after =");
+  arg.AddCallback("-D", argT::CONCAT_ARGUMENT, argument, random_ptr,
+                  "This option takes concatinated argument");
   arg.AddCallback("--long1", argT::NO_ARGUMENT, argument, random_ptr, "-A");
   arg.AddCallback("--long2", argT::SPACE_ARGUMENT, argument, random_ptr, "-B");
-  arg.AddCallback("--long3", argT::EQUAL_ARGUMENT, argument, random_ptr, "Same as -C but a bit different");
-  arg.AddCallback("--long4", argT::CONCAT_ARGUMENT, argument, random_ptr, "-C");
+  arg.AddCallback("--long3", argT::EQUAL_ARGUMENT, argument, random_ptr,
+                  "Same as -C but a bit different");
+  arg.AddCallback("--long4", argT::CONCAT_ARGUMENT, argument, random_ptr,
+                  "-C");
 
-  if ( !arg.Parse() )
-    {
+  if (!arg.Parse()) {
     std::cerr << "Problem parsing arguments" << std::endl;
     res = 1;
-    }
+  }
   std::cout << "Help: " << arg.GetHelp() << std::endl;
 
-  std::cout << "Some int variable was set to: " << some_int_variable << std::endl;
-  std::cout << "Some double variable was set to: " << some_double_variable << std::endl;
-  if ( some_string_variable && strcmp(some_string_variable, "test string with space") == 0)
-    {
-    std::cout << "Some string variable was set to: " << some_string_variable << std::endl;
-    delete [] some_string_variable;
-    }
-  else
-    {
+  std::cout << "Some int variable was set to: " << some_int_variable
+            << std::endl;
+  std::cout << "Some double variable was set to: " << some_double_variable
+            << std::endl;
+  if (some_string_variable &&
+      strcmp(some_string_variable, "test string with space") == 0) {
+    std::cout << "Some string variable was set to: " << some_string_variable
+              << std::endl;
+    delete[] some_string_variable;
+  } else {
     std::cerr << "Problem setting string variable" << std::endl;
     res = 1;
-    }
+  }
   size_t cc;
-#define CompareTwoLists(list1, list_valid, lsize) \
-  if ( list1.size() != lsize ) \
-    { \
-    std::cerr << "Problem setting " #list1 ". Size is: " << list1.size() \
-     << " should be: " << lsize << std::endl; \
-    res = 1; \
-    } \
-  else \
-    { \
-    std::cout << #list1 " argument set:"; \
-    for ( cc =0; cc < lsize; ++ cc ) \
-      { \
-      std::cout << " " << list1[cc]; \
-      if ( !CompareTwoItemsOnList(list1[cc], list_valid[cc]) ) \
-        { \
-        std::cerr << "Problem setting " #list1 ". Value of " \
-        << cc << " is: [" << list1[cc] << "] <> [" \
-        << list_valid[cc] << "]" << std::endl; \
-        res = 1; \
-        break; \
-        } \
-      } \
-    std::cout << std::endl; \
-    }
+#define CompareTwoLists(list1, list_valid, lsize)                             \
+  if (list1.size() != lsize) {                                                \
+    std::cerr << "Problem setting " #list1 ". Size is: " << list1.size()      \
+              << " should be: " << lsize << std::endl;                        \
+    res = 1;                                                                  \
+  } else {                                                                    \
+    std::cout << #list1 " argument set:";                                     \
+    for (cc = 0; cc < lsize; ++cc) {                                          \
+      std::cout << " " << list1[cc];                                          \
+      if (!CompareTwoItemsOnList(list1[cc], list_valid[cc])) {                \
+        std::cerr << "Problem setting " #list1 ". Value of " << cc            \
+                  << " is: [" << list1[cc] << "] <> [" << list_valid[cc]      \
+                  << "]" << std::endl;                                        \
+        res = 1;                                                              \
+        break;                                                                \
+      }                                                                       \
+    }                                                                         \
+    std::cout << std::endl;                                                   \
+  }
 
   CompareTwoLists(numbers_argument, valid_numbers, 10);
   CompareTwoLists(doubles_argument, valid_doubles, 3);
@@ -171,17 +190,19 @@ int testCommandLineArguments(int argc, char* argv[])
   CompareTwoLists(strings_argument, valid_strings, 4);
   CompareTwoLists(stl_strings_argument, valid_stl_strings, 4);
 
-  std::cout << "Some STL String variable was set to: " << some_stl_string_variable << std::endl;
-  std::cout << "Some bool variable was set to: " << some_bool_variable << std::endl;
-  std::cout << "Some bool variable was set to: " << some_bool_variable1 << std::endl;
+  std::cout << "Some STL String variable was set to: "
+            << some_stl_string_variable << std::endl;
+  std::cout << "Some bool variable was set to: " << some_bool_variable
+            << std::endl;
+  std::cout << "Some bool variable was set to: " << some_bool_variable1
+            << std::endl;
   std::cout << "bool_arg1 variable was set to: " << bool_arg1 << std::endl;
   std::cout << "bool_arg2 variable was set to: " << bool_arg2 << std::endl;
   std::cout << std::endl;
 
-  for ( cc = 0; cc < strings_argument.size(); ++ cc )
-    {
-    delete [] strings_argument[cc];
+  for (cc = 0; cc < strings_argument.size(); ++cc) {
+    delete[] strings_argument[cc];
     strings_argument[cc] = 0;
-    }
+  }
   return res;
 }
diff --git a/Source/kwsys/testCommandLineArguments1.cxx b/Source/kwsys/testCommandLineArguments1.cxx
index 6eb465d..5a03401 100644
--- a/Source/kwsys/testCommandLineArguments1.cxx
+++ b/Source/kwsys/testCommandLineArguments1.cxx
@@ -1,21 +1,12 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(CommandLineArguments.hxx)
 
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "CommandLineArguments.hxx.in"
+#include "CommandLineArguments.hxx.in"
 #endif
 
 #include <iostream>
@@ -41,68 +32,62 @@ int testCommandLineArguments1(int argc, char* argv[])
 
   arg.StoreUnusedArguments(true);
 
-  if ( !arg.Parse() )
-    {
+  if (!arg.Parse()) {
     std::cerr << "Problem parsing arguments" << std::endl;
     res = 1;
-    }
-  if ( n != 24 )
-    {
+  }
+  if (n != 24) {
     std::cout << "Problem setting N. Value of N: " << n << std::endl;
     res = 1;
-    }
-  if ( !m || strcmp(m, "test value") != 0 )
-    {
+  }
+  if (!m || strcmp(m, "test value") != 0) {
     std::cout << "Problem setting M. Value of M: " << m << std::endl;
     res = 1;
-    }
-  if ( p != "1" )
-    {
+  }
+  if (p != "1") {
     std::cout << "Problem setting P. Value of P: " << p << std::endl;
     res = 1;
-    }
+  }
   std::cout << "Value of N: " << n << std::endl;
   std::cout << "Value of M: " << m << std::endl;
   std::cout << "Value of P: " << p << std::endl;
-  if ( m )
-    {
-    delete [] m;
-    }
+  if (m) {
+    delete[] m;
+  }
 
   char** newArgv = 0;
   int newArgc = 0;
   arg.GetUnusedArguments(&newArgc, &newArgv);
   int cc;
-  const char* valid_unused_args[9] = {
-    0, "--ignored", "--second-ignored", "third-ignored",
-    "some", "junk", "at", "the", "end"
-  };
-  if ( newArgc != 9 )
-    {
+  const char* valid_unused_args[9] = { 0,
+                                       "--ignored",
+                                       "--second-ignored",
+                                       "third-ignored",
+                                       "some",
+                                       "junk",
+                                       "at",
+                                       "the",
+                                       "end" };
+  if (newArgc != 9) {
     std::cerr << "Bad number of unused arguments: " << newArgc << std::endl;
     res = 1;
-    }
-  for ( cc = 0; cc < newArgc; ++ cc )
-    {
+  }
+  for (cc = 0; cc < newArgc; ++cc) {
     assert(newArgv[cc]); /* Quiet Clang scan-build. */
     std::cout << "Unused argument[" << cc << "] = [" << newArgv[cc] << "]"
-      << std::endl;
-    if ( cc >= 9 )
-      {
+              << std::endl;
+    if (cc >= 9) {
       std::cerr << "Too many unused arguments: " << cc << std::endl;
       res = 1;
-      }
-    else if ( valid_unused_args[cc] &&
-      strcmp(valid_unused_args[cc], newArgv[cc]) != 0 )
-      {
-      std::cerr << "Bad unused argument [" << cc << "] \""
-        << newArgv[cc] << "\" should be: \"" << valid_unused_args[cc] << "\""
-        << std::endl;
+    } else if (valid_unused_args[cc] &&
+               strcmp(valid_unused_args[cc], newArgv[cc]) != 0) {
+      std::cerr << "Bad unused argument [" << cc << "] \"" << newArgv[cc]
+                << "\" should be: \"" << valid_unused_args[cc] << "\""
+                << std::endl;
       res = 1;
-      }
     }
+  }
   arg.DeleteRemainingArguments(newArgc, &newArgv);
 
   return res;
 }
- 
diff --git a/Source/kwsys/testConsoleBuf.cxx b/Source/kwsys/testConsoleBuf.cxx
index d7775e6..3b8cdab 100644
--- a/Source/kwsys/testConsoleBuf.cxx
+++ b/Source/kwsys/testConsoleBuf.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  Copyright 2000-2016 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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 
 // Ignore Windows version levels defined by command-line flags.  This
@@ -22,24 +13,27 @@
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "Encoding.hxx.in"
+#include "Encoding.hxx.in"
 #endif
 
 #if defined(_WIN32)
 
-#include <windows.h>
-#include <string.h>
-#include <wchar.h>
-#include <iostream>
+#include <algorithm>
 #include <iomanip>
+#include <iostream>
 #include <stdexcept>
+#include <string.h>
+#include <wchar.h>
+#include <windows.h>
+
 #include "testConsoleBuf.hxx"
 
 #if defined(_MSC_VER) && _MSC_VER >= 1800
-# define KWSYS_WINDOWS_DEPRECATED_GetVersion
+#define KWSYS_WINDOWS_DEPRECATED_GetVersion
 #endif
 // يونيكود
-static const WCHAR UnicodeInputTestString[] = L"\u064A\u0648\u0646\u064A\u0643\u0648\u062F!";
+static const WCHAR UnicodeInputTestString[] =
+  L"\u064A\u0648\u0646\u064A\u0643\u0648\u062F!";
 static UINT TestCodepage = KWSYS_ENCODING_DEFAULT_CODEPAGE;
 
 static const DWORD waitTimeout = 10 * 1000;
@@ -50,55 +44,62 @@ static HANDLE afterOutputEvent;
 static std::string encodedInputTestString;
 static std::string encodedTestString;
 
-static void displayError(DWORD errorCode) {
+static void displayError(DWORD errorCode)
+{
   std::cerr.setf(std::ios::hex, std::ios::basefield);
   std::cerr << "Failed with error: 0x" << errorCode << "!" << std::endl;
   LPWSTR message;
-  if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
-                     NULL,
-                     errorCode,
-                     0,
-                     (LPWSTR)&message, 0,
-                     NULL)
-  ) {
-    std::cerr << "Error message: " << kwsys::Encoding::ToNarrow(message) << std::endl;
+  if (FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
+                       FORMAT_MESSAGE_FROM_SYSTEM,
+                     NULL, errorCode, 0, (LPWSTR)&message, 0, NULL)) {
+    std::cerr << "Error message: " << kwsys::Encoding::ToNarrow(message)
+              << std::endl;
     HeapFree(GetProcessHeap(), 0, message);
   } else {
-    std::cerr << "FormatMessage() failed with error: 0x" << GetLastError() << "!" << std::endl;
+    std::cerr << "FormatMessage() failed with error: 0x" << GetLastError()
+              << "!" << std::endl;
   }
   std::cerr.unsetf(std::ios::hex);
 }
 
-std::basic_streambuf<char> *errstream(const char *unused) {
+std::basic_streambuf<char>* errstream(const char* unused)
+{
   static_cast<void>(unused);
   return std::cerr.rdbuf();
 }
 
-std::basic_streambuf<wchar_t> *errstream(const wchar_t *unused) {
+std::basic_streambuf<wchar_t>* errstream(const wchar_t* unused)
+{
   static_cast<void>(unused);
   return std::wcerr.rdbuf();
 }
 
 //----------------------------------------------------------------------------
-template<typename T>
-static void dumpBuffers(const T *expected, const T *received, size_t size) {
+template <typename T>
+static void dumpBuffers(const T* expected, const T* received, size_t size)
+{
   std::basic_ostream<T> err(errstream(expected));
-  err << "Expected output: '" << std::basic_string<T>(expected, size) << "'" << std::endl;
+  err << "Expected output: '" << std::basic_string<T>(expected, size) << "'"
+      << std::endl;
   if (err.fail()) {
     err.clear();
     err << "--- Error while outputting ---" << std::endl;
   }
-  err << "Received output: '" << std::basic_string<T>(received, size) << "'" << std::endl;
+  err << "Received output: '" << std::basic_string<T>(received, size) << "'"
+      << std::endl;
   if (err.fail()) {
     err.clear();
     err << "--- Error while outputting ---" << std::endl;
   }
   std::cerr << "Expected output | Received output" << std::endl;
   for (size_t i = 0; i < size; i++) {
-    std::cerr << std::setbase(16) << std::setfill('0') << "     " <<
-    "0x" << std::setw(8) << static_cast<unsigned int>(expected[i]) << " | " <<
-    "0x" << std::setw(8) << static_cast<unsigned int>(received[i]);
-    if (static_cast<unsigned int>(expected[i]) != static_cast<unsigned int>(received[i])) {
+    std::cerr << std::setbase(16) << std::setfill('0') << "     "
+              << "0x" << std::setw(8) << static_cast<unsigned int>(expected[i])
+              << " | "
+              << "0x" << std::setw(8)
+              << static_cast<unsigned int>(received[i]);
+    if (static_cast<unsigned int>(expected[i]) !=
+        static_cast<unsigned int>(received[i])) {
       std::cerr << "   MISMATCH!";
     }
     std::cerr << std::endl;
@@ -129,25 +130,29 @@ static bool createProcess(HANDLE hIn, HANDLE hOut, HANDLE hErr)
     std::cerr << "GetModuleFileName failed!" << std::endl;
     return false;
   }
-  WCHAR *p = cmd + wcslen(cmd);
-  while (p > cmd && *p != L'\\') p--;
-  *(p+1) = 0;
+  WCHAR* p = cmd + wcslen(cmd);
+  while (p > cmd && *p != L'\\')
+    p--;
+  *(p + 1) = 0;
   wcscat(cmd, cmdConsoleBufChild);
   wcscat(cmd, L".exe");
 
-  bool success = CreateProcessW(NULL,             // No module name (use command line)
-                                cmd,              // Command line
-                                NULL,             // Process handle not inheritable
-                                NULL,             // Thread handle not inheritable
-                                bInheritHandles,  // Set handle inheritance
-                                dwCreationFlags,
-                                NULL,             // Use parent's environment block
-                                NULL,             // Use parent's starting directory
-                                &startupInfo,     // Pointer to STARTUPINFO structure
-                                &processInfo) != 0; // Pointer to PROCESS_INFORMATION structure
+  bool success =
+    CreateProcessW(NULL,            // No module name (use command line)
+                   cmd,             // Command line
+                   NULL,            // Process handle not inheritable
+                   NULL,            // Thread handle not inheritable
+                   bInheritHandles, // Set handle inheritance
+                   dwCreationFlags,
+                   NULL,         // Use parent's environment block
+                   NULL,         // Use parent's starting directory
+                   &startupInfo, // Pointer to STARTUPINFO structure
+                   &processInfo) !=
+    0; // Pointer to PROCESS_INFORMATION structure
   if (!success) {
     DWORD lastError = GetLastError();
-    std::cerr << "CreateProcess(" << kwsys::Encoding::ToNarrow(cmd) << ")" << std::endl;
+    std::cerr << "CreateProcess(" << kwsys::Encoding::ToNarrow(cmd) << ")"
+              << std::endl;
     displayError(lastError);
   }
   return success;
@@ -157,8 +162,8 @@ static bool createProcess(HANDLE hIn, HANDLE hOut, HANDLE hErr)
 static void finishProcess(bool success)
 {
   if (success) {
-    success = WaitForSingleObject(processInfo.hProcess, waitTimeout)
-              == WAIT_OBJECT_0;
+    success =
+      WaitForSingleObject(processInfo.hProcess, waitTimeout) == WAIT_OBJECT_0;
   };
   if (!success) {
     TerminateProcess(processInfo.hProcess, 1);
@@ -174,8 +179,8 @@ static bool createPipe(PHANDLE readPipe, PHANDLE writePipe)
   securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
   securityAttributes.bInheritHandle = TRUE;
   securityAttributes.lpSecurityDescriptor = NULL;
-  return CreatePipe(readPipe, writePipe, &securityAttributes, 0) == 0
-         ? false : true;
+  return CreatePipe(readPipe, writePipe, &securityAttributes, 0) == 0 ? false
+                                                                      : true;
 }
 
 //----------------------------------------------------------------------------
@@ -197,16 +202,17 @@ static HANDLE createFile(LPCWSTR fileName)
   securityAttributes.bInheritHandle = TRUE;
   securityAttributes.lpSecurityDescriptor = NULL;
 
-  HANDLE file = CreateFileW(fileName,
-                            GENERIC_READ | GENERIC_WRITE,
-                            0,                    // do not share
-                            &securityAttributes,
-                            CREATE_ALWAYS,        // overwrite existing
-                            FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
-                            NULL);                // no template
+  HANDLE file =
+    CreateFileW(fileName, GENERIC_READ | GENERIC_WRITE,
+                0, // do not share
+                &securityAttributes,
+                CREATE_ALWAYS, // overwrite existing
+                FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
+                NULL); // no template
   if (file == INVALID_HANDLE_VALUE) {
     DWORD lastError = GetLastError();
-    std::cerr << "CreateFile(" << kwsys::Encoding::ToNarrow(fileName) << ")" << std::endl;
+    std::cerr << "CreateFile(" << kwsys::Encoding::ToNarrow(fileName) << ")"
+              << std::endl;
     displayError(lastError);
   }
   return file;
@@ -223,7 +229,7 @@ static void finishFile(HANDLE file)
 //----------------------------------------------------------------------------
 
 #ifndef MAPVK_VK_TO_VSC
-#  define MAPVK_VK_TO_VSC  (0)
+#define MAPVK_VK_TO_VSC (0)
 #endif
 
 static void writeInputKeyEvent(INPUT_RECORD inputBuffer[], WCHAR chr)
@@ -238,9 +244,8 @@ static void writeInputKeyEvent(INPUT_RECORD inputBuffer[], WCHAR chr)
     keyCode = 'K';
   }
   inputBuffer[0].Event.KeyEvent.wVirtualKeyCode = LOBYTE(keyCode);
-  inputBuffer[0].Event.KeyEvent.wVirtualScanCode =
-      MapVirtualKey(inputBuffer[0].Event.KeyEvent.wVirtualKeyCode,
-                    MAPVK_VK_TO_VSC);
+  inputBuffer[0].Event.KeyEvent.wVirtualScanCode = MapVirtualKey(
+    inputBuffer[0].Event.KeyEvent.wVirtualKeyCode, MAPVK_VK_TO_VSC);
   inputBuffer[0].Event.KeyEvent.uChar.UnicodeChar = chr;
   inputBuffer[0].Event.KeyEvent.dwControlKeyState = 0;
   if ((HIBYTE(keyCode) & 1) == 1) {
@@ -255,12 +260,12 @@ static void writeInputKeyEvent(INPUT_RECORD inputBuffer[], WCHAR chr)
   inputBuffer[1].EventType = inputBuffer[0].EventType;
   inputBuffer[1].Event.KeyEvent.bKeyDown = FALSE;
   inputBuffer[1].Event.KeyEvent.wRepeatCount = 1;
-  inputBuffer[1].Event.KeyEvent.wVirtualKeyCode   = inputBuffer[0].Event.
-                                                      KeyEvent.wVirtualKeyCode;
-  inputBuffer[1].Event.KeyEvent.wVirtualScanCode  = inputBuffer[0].Event.
-                                                      KeyEvent.wVirtualScanCode;
-  inputBuffer[1].Event.KeyEvent.uChar.UnicodeChar = inputBuffer[0].Event.
-                                                      KeyEvent.uChar.UnicodeChar;
+  inputBuffer[1].Event.KeyEvent.wVirtualKeyCode =
+    inputBuffer[0].Event.KeyEvent.wVirtualKeyCode;
+  inputBuffer[1].Event.KeyEvent.wVirtualScanCode =
+    inputBuffer[0].Event.KeyEvent.wVirtualScanCode;
+  inputBuffer[1].Event.KeyEvent.uChar.UnicodeChar =
+    inputBuffer[0].Event.KeyEvent.uChar.UnicodeChar;
   inputBuffer[1].Event.KeyEvent.dwControlKeyState = 0;
 }
 
@@ -292,29 +297,34 @@ static int testPipe()
 
     DWORD bytesWritten = 0;
     if (!WriteFile(inPipeWrite, encodedInputTestString.c_str(),
-                   (DWORD)encodedInputTestString.size(), &bytesWritten, NULL)
-        || bytesWritten == 0) {
+                   (DWORD)encodedInputTestString.size(), &bytesWritten,
+                   NULL) ||
+        bytesWritten == 0) {
       throw std::runtime_error("WriteFile failed!");
     }
 
     if (createProcess(inPipeRead, outPipeWrite, errPipeWrite)) {
       try {
         DWORD status;
-        if ((status = WaitForSingleObject(afterOutputEvent, waitTimeout)) != WAIT_OBJECT_0) {
+        if ((status = WaitForSingleObject(afterOutputEvent, waitTimeout)) !=
+            WAIT_OBJECT_0) {
           std::cerr.setf(std::ios::hex, std::ios::basefield);
-          std::cerr << "WaitForSingleObject returned unexpected status 0x" << status << std::endl;
+          std::cerr << "WaitForSingleObject returned unexpected status 0x"
+                    << status << std::endl;
           std::cerr.unsetf(std::ios::hex);
           throw std::runtime_error("WaitForSingleObject failed!");
         }
         DWORD bytesRead = 0;
-        if (!ReadFile(outPipeRead, buffer, sizeof(buffer), &bytesRead, NULL)
-            || bytesRead == 0) {
+        if (!ReadFile(outPipeRead, buffer, sizeof(buffer), &bytesRead, NULL) ||
+            bytesRead == 0) {
           throw std::runtime_error("ReadFile#1 failed!");
         }
-        if ((bytesRead < encodedTestString.size() + 1 + encodedInputTestString.size()
-             && !ReadFile(outPipeRead, buffer + bytesRead,
-                          sizeof(buffer) - bytesRead, &bytesRead, NULL))
-            || bytesRead == 0) {
+        buffer[bytesRead] = 0;
+        if ((bytesRead <
+               encodedTestString.size() + 1 + encodedInputTestString.size() &&
+             !ReadFile(outPipeRead, buffer + bytesRead,
+                       sizeof(buffer) - bytesRead, &bytesRead, NULL)) ||
+            bytesRead == 0) {
           throw std::runtime_error("ReadFile#2 failed!");
         }
         if (memcmp(buffer, encodedTestString.c_str(),
@@ -323,31 +333,41 @@ static int testPipe()
                    encodedInputTestString.c_str(),
                    encodedInputTestString.size()) == 0) {
           bytesRead = 0;
-          if (!ReadFile(errPipeRead, buffer2, sizeof(buffer2), &bytesRead, NULL)
-              || bytesRead == 0) {
+          if (!ReadFile(errPipeRead, buffer2, sizeof(buffer2), &bytesRead,
+                        NULL) ||
+              bytesRead == 0) {
             throw std::runtime_error("ReadFile#3 failed!");
           }
-          buffer2[bytesRead - 1] = 0;
-          didFail = encodedTestString.compare(buffer2) == 0 ? 0 : 1;
+          buffer2[bytesRead] = 0;
+          didFail =
+            encodedTestString.compare(0, encodedTestString.npos, buffer2,
+                                      encodedTestString.size()) == 0
+            ? 0
+            : 1;
         }
         if (didFail != 0) {
-          std::cerr << "Pipe's output didn't match expected output!" << std::endl;
-          dumpBuffers<char>(encodedTestString.c_str(), buffer, encodedTestString.size());
-          dumpBuffers<char>(encodedInputTestString.c_str(), buffer + encodedTestString.size() + 1, encodedInputTestString.size());
-          dumpBuffers<char>(encodedTestString.c_str(), buffer2, encodedTestString.size());
+          std::cerr << "Pipe's output didn't match expected output!"
+                    << std::endl;
+          dumpBuffers<char>(encodedTestString.c_str(), buffer,
+                            encodedTestString.size());
+          dumpBuffers<char>(encodedInputTestString.c_str(),
+                            buffer + encodedTestString.size() + 1,
+                            encodedInputTestString.size());
+          dumpBuffers<char>(encodedTestString.c_str(), buffer2,
+                            encodedTestString.size());
         }
-      } catch (const std::runtime_error &ex) {
+      } catch (const std::runtime_error& ex) {
         DWORD lastError = GetLastError();
-        std::cerr << "In function testPipe, line " <<  __LINE__ << ": "
+        std::cerr << "In function testPipe, line " << __LINE__ << ": "
                   << ex.what() << std::endl;
         displayError(lastError);
       }
       finishProcess(didFail == 0);
     }
-  } catch (const std::runtime_error &ex) {
+  } catch (const std::runtime_error& ex) {
     DWORD lastError = GetLastError();
-    std::cerr << "In function testPipe, line " <<  __LINE__ << ": "
-              << ex.what() << std::endl;
+    std::cerr << "In function testPipe, line " << __LINE__ << ": " << ex.what()
+              << std::endl;
     displayError(lastError);
   }
   finishPipe(inPipeRead, inPipeWrite);
@@ -375,14 +395,14 @@ static int testFile()
     char buffer2[200];
 
     int length;
-    if ((length = WideCharToMultiByte(TestCodepage, 0, UnicodeInputTestString, -1,
-                                      buffer, sizeof(buffer),
-                                      NULL, NULL)) == 0) {
+    if ((length =
+           WideCharToMultiByte(TestCodepage, 0, UnicodeInputTestString, -1,
+                               buffer, sizeof(buffer), NULL, NULL)) == 0) {
       throw std::runtime_error("WideCharToMultiByte failed!");
     }
     buffer[length - 1] = '\n';
-    if (!WriteFile(inFile, buffer, length, &bytesWritten, NULL)
-        || bytesWritten == 0) {
+    if (!WriteFile(inFile, buffer, length, &bytesWritten, NULL) ||
+        bytesWritten == 0) {
       throw std::runtime_error("WriteFile failed!");
     }
     if (SetFilePointer(inFile, 0, 0, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
@@ -393,56 +413,68 @@ static int testFile()
       DWORD bytesRead = 0;
       try {
         DWORD status;
-        if ((status = WaitForSingleObject(afterOutputEvent, waitTimeout)) != WAIT_OBJECT_0) {
+        if ((status = WaitForSingleObject(afterOutputEvent, waitTimeout)) !=
+            WAIT_OBJECT_0) {
           std::cerr.setf(std::ios::hex, std::ios::basefield);
-          std::cerr << "WaitForSingleObject returned unexpected status 0x" << status << std::endl;
+          std::cerr << "WaitForSingleObject returned unexpected status 0x"
+                    << status << std::endl;
           std::cerr.unsetf(std::ios::hex);
           throw std::runtime_error("WaitForSingleObject failed!");
         }
-        if (SetFilePointer(outFile, 0, 0, FILE_BEGIN)
-            == INVALID_SET_FILE_POINTER) {
+        if (SetFilePointer(outFile, 0, 0, FILE_BEGIN) ==
+            INVALID_SET_FILE_POINTER) {
           throw std::runtime_error("SetFilePointer#1 failed!");
         }
-        if (!ReadFile(outFile, buffer, sizeof(buffer), &bytesRead, NULL)
-            || bytesRead == 0) {
+        if (!ReadFile(outFile, buffer, sizeof(buffer), &bytesRead, NULL) ||
+            bytesRead == 0) {
           throw std::runtime_error("ReadFile#1 failed!");
         }
-        buffer[bytesRead - 1] = 0;
+        buffer[bytesRead] = 0;
         if (memcmp(buffer, encodedTestString.c_str(),
                    encodedTestString.size()) == 0 &&
             memcmp(buffer + encodedTestString.size() + 1,
                    encodedInputTestString.c_str(),
-                   encodedInputTestString.size() - 1) == 0) {
+                   encodedInputTestString.size()) == 0) {
           bytesRead = 0;
-          if (SetFilePointer(errFile, 0, 0, FILE_BEGIN)
-              == INVALID_SET_FILE_POINTER) {
+          if (SetFilePointer(errFile, 0, 0, FILE_BEGIN) ==
+              INVALID_SET_FILE_POINTER) {
             throw std::runtime_error("SetFilePointer#2 failed!");
           }
-          if (!ReadFile(errFile, buffer2, sizeof(buffer2), &bytesRead, NULL)
-              || bytesRead == 0) {
+
+          if (!ReadFile(errFile, buffer2, sizeof(buffer2), &bytesRead, NULL) ||
+              bytesRead == 0) {
             throw std::runtime_error("ReadFile#2 failed!");
           }
-          buffer2[bytesRead - 1] = 0;
-          didFail = encodedTestString.compare(buffer2) == 0 ? 0 : 1;
+          buffer2[bytesRead] = 0;
+          didFail =
+            encodedTestString.compare(0, encodedTestString.npos, buffer2,
+                                      encodedTestString.size()) == 0
+            ? 0
+            : 1;
         }
         if (didFail != 0) {
-          std::cerr << "File's output didn't match expected output!" << std::endl;
-          dumpBuffers<char>(encodedTestString.c_str(), buffer, encodedTestString.size());
-          dumpBuffers<char>(encodedInputTestString.c_str(), buffer + encodedTestString.size() + 1, encodedInputTestString.size() - 1);
-          dumpBuffers<char>(encodedTestString.c_str(), buffer2, encodedTestString.size());
+          std::cerr << "File's output didn't match expected output!"
+                    << std::endl;
+          dumpBuffers<char>(encodedTestString.c_str(), buffer,
+                            encodedTestString.size());
+          dumpBuffers<char>(encodedInputTestString.c_str(),
+                            buffer + encodedTestString.size() + 1,
+                            encodedInputTestString.size());
+          dumpBuffers<char>(encodedTestString.c_str(), buffer2,
+                            encodedTestString.size());
         }
-      } catch (const std::runtime_error &ex) {
+      } catch (const std::runtime_error& ex) {
         DWORD lastError = GetLastError();
-        std::cerr << "In function testFile, line " <<  __LINE__ << ": "
+        std::cerr << "In function testFile, line " << __LINE__ << ": "
                   << ex.what() << std::endl;
         displayError(lastError);
       }
       finishProcess(didFail == 0);
     }
-  } catch (const std::runtime_error &ex) {
+  } catch (const std::runtime_error& ex) {
     DWORD lastError = GetLastError();
-    std::cerr << "In function testFile, line " <<  __LINE__ << ": "
-              << ex.what() << std::endl;
+    std::cerr << "In function testFile, line " << __LINE__ << ": " << ex.what()
+              << std::endl;
     displayError(lastError);
   }
   finishFile(inFile);
@@ -452,7 +484,7 @@ static int testFile()
 }
 
 #ifndef _WIN32_WINNT_VISTA
-# define _WIN32_WINNT_VISTA 0x0600
+#define _WIN32_WINNT_VISTA 0x0600
 #endif
 
 //----------------------------------------------------------------------------
@@ -478,16 +510,17 @@ static int testConsole()
   DWORD FontFamily = TestFontFamily;
   DWORD FontSize = TestFontSize;
 #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersion
-# pragma warning (push)
-# ifdef __INTEL_COMPILER
-#  pragma warning (disable:1478)
-# else
-#  pragma warning (disable:4996)
-# endif
+#pragma warning(push)
+#ifdef __INTEL_COMPILER
+#pragma warning(disable : 1478)
+#else
+#pragma warning(disable : 4996)
+#endif
 #endif
-  const bool isVistaOrGreater = LOBYTE(LOWORD(GetVersion())) >= HIBYTE(_WIN32_WINNT_VISTA);
+  const bool isVistaOrGreater =
+    LOBYTE(LOWORD(GetVersion())) >= HIBYTE(_WIN32_WINNT_VISTA);
 #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersion
-# pragma warning (pop)
+#pragma warning(pop)
 #endif
   if (!isVistaOrGreater) {
     if (RegOpenKeyExW(HKEY_CURRENT_USER, L"Console", 0, KEY_READ | KEY_WRITE,
@@ -502,11 +535,12 @@ static int testConsole()
                            (LPBYTE)&FontSize, &dwordSize);
 
           RegSetValueExW(hConsoleKey, L"FontFamily", 0, REG_DWORD,
-                         (BYTE *)&TestFontFamily, sizeof(TestFontFamily));
+                         (BYTE*)&TestFontFamily, sizeof(TestFontFamily));
           RegSetValueExW(hConsoleKey, L"FaceName", 0, REG_SZ,
-                         (BYTE *)TestFaceName, (DWORD)((wcslen(TestFaceName) + 1) * sizeof(WCHAR)));
+                         (BYTE*)TestFaceName,
+                         (DWORD)((wcslen(TestFaceName) + 1) * sizeof(WCHAR)));
           RegSetValueExW(hConsoleKey, L"FontSize", 0, REG_DWORD,
-                         (BYTE *)&TestFontSize, sizeof(TestFontSize));
+                         (BYTE*)&TestFontSize, sizeof(TestFontSize));
 
           restoreConsole = true;
           forceNewConsole = true;
@@ -516,7 +550,8 @@ static int testConsole()
       }
       RegCloseKey(hConsoleKey);
     } else {
-      std::cerr << "RegOpenKeyExW(HKEY_CURRENT_USER\\Console) failed!" << std::endl;
+      std::cerr << "RegOpenKeyExW(HKEY_CURRENT_USER\\Console) failed!"
+                << std::endl;
     }
   }
   if (forceNewConsole || GetConsoleMode(parentOut, &consoleMode) == 0) {
@@ -530,15 +565,17 @@ static int testConsole()
     securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
     securityAttributes.bInheritHandle = TRUE;
     securityAttributes.lpSecurityDescriptor = NULL;
-    hIn = CreateFileW(L"CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
-                       &securityAttributes, OPEN_EXISTING, 0, NULL);
+    hIn = CreateFileW(L"CONIN$", GENERIC_READ | GENERIC_WRITE,
+                      FILE_SHARE_READ | FILE_SHARE_WRITE, &securityAttributes,
+                      OPEN_EXISTING, 0, NULL);
     if (hIn == INVALID_HANDLE_VALUE) {
       DWORD lastError = GetLastError();
       std::cerr << "CreateFile(CONIN$)" << std::endl;
       displayError(lastError);
     }
-    hOut = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
-                       &securityAttributes, OPEN_EXISTING, 0, NULL);
+    hOut = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE,
+                       FILE_SHARE_READ | FILE_SHARE_WRITE, &securityAttributes,
+                       OPEN_EXISTING, 0, NULL);
     if (hOut == INVALID_HANDLE_VALUE) {
       DWORD lastError = GetLastError();
       std::cerr << "CreateFile(CONOUT$)" << std::endl;
@@ -556,10 +593,18 @@ static int testConsole()
     memset(&consoleFont, 0, sizeof(consoleFont));
     consoleFont.cbSize = sizeof(consoleFont);
     HMODULE kernel32 = LoadLibraryW(L"kernel32.dll");
-    typedef BOOL (WINAPI *GetCurrentConsoleFontExFunc)(HANDLE hConsoleOutput, BOOL bMaximumWindow, PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx);
-    typedef BOOL (WINAPI *SetCurrentConsoleFontExFunc)(HANDLE hConsoleOutput, BOOL bMaximumWindow, PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx);
-    GetCurrentConsoleFontExFunc getConsoleFont = (GetCurrentConsoleFontExFunc)GetProcAddress(kernel32, "GetCurrentConsoleFontEx");
-    SetCurrentConsoleFontExFunc setConsoleFont = (SetCurrentConsoleFontExFunc)GetProcAddress(kernel32, "SetCurrentConsoleFontEx");
+    typedef BOOL(WINAPI * GetCurrentConsoleFontExFunc)(
+      HANDLE hConsoleOutput, BOOL bMaximumWindow,
+      PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx);
+    typedef BOOL(WINAPI * SetCurrentConsoleFontExFunc)(
+      HANDLE hConsoleOutput, BOOL bMaximumWindow,
+      PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx);
+    GetCurrentConsoleFontExFunc getConsoleFont =
+      (GetCurrentConsoleFontExFunc)GetProcAddress(kernel32,
+                                                  "GetCurrentConsoleFontEx");
+    SetCurrentConsoleFontExFunc setConsoleFont =
+      (SetCurrentConsoleFontExFunc)GetProcAddress(kernel32,
+                                                  "SetCurrentConsoleFontEx");
     if (getConsoleFont(hOut, FALSE, &consoleFont)) {
       if (consoleFont.FontFamily != TestFontFamily) {
         consoleFont.FontFamily = TestFontFamily;
@@ -573,18 +618,19 @@ static int testConsole()
     }
   } else {
 #endif
-    if (restoreConsole && RegOpenKeyExW(HKEY_CURRENT_USER, L"Console", 0,
-                                        KEY_WRITE, &hConsoleKey) == ERROR_SUCCESS) {
+    if (restoreConsole &&
+        RegOpenKeyExW(HKEY_CURRENT_USER, L"Console", 0, KEY_WRITE,
+                      &hConsoleKey) == ERROR_SUCCESS) {
       RegSetValueExW(hConsoleKey, L"FontFamily", 0, REG_DWORD,
-                     (BYTE *)&FontFamily, sizeof(FontFamily));
+                     (BYTE*)&FontFamily, sizeof(FontFamily));
       if (FaceName[0] != 0) {
-        RegSetValueExW(hConsoleKey, L"FaceName", 0, REG_SZ,
-                       (BYTE *)FaceName, FaceNameSize);
+        RegSetValueExW(hConsoleKey, L"FaceName", 0, REG_SZ, (BYTE*)FaceName,
+                       FaceNameSize);
       } else {
         RegDeleteValueW(hConsoleKey, L"FaceName");
       }
-      RegSetValueExW(hConsoleKey, L"FontSize", 0, REG_DWORD,
-                     (BYTE *)&FontSize, sizeof(FontSize));
+      RegSetValueExW(hConsoleKey, L"FontSize", 0, REG_DWORD, (BYTE*)&FontSize,
+                     sizeof(FontSize));
       RegCloseKey(hConsoleKey);
     }
 #if _WIN32_WINNT >= _WIN32_WINNT_VISTA
@@ -594,32 +640,41 @@ static int testConsole()
   if (createProcess(NULL, NULL, NULL)) {
     try {
       DWORD status;
-      if ((status = WaitForSingleObject(beforeInputEvent, waitTimeout)) != WAIT_OBJECT_0) {
+      if ((status = WaitForSingleObject(beforeInputEvent, waitTimeout)) !=
+          WAIT_OBJECT_0) {
         std::cerr.setf(std::ios::hex, std::ios::basefield);
-        std::cerr << "WaitForSingleObject returned unexpected status 0x" << status << std::endl;
+        std::cerr << "WaitForSingleObject returned unexpected status 0x"
+                  << status << std::endl;
         std::cerr.unsetf(std::ios::hex);
         throw std::runtime_error("WaitForSingleObject#1 failed!");
       }
       INPUT_RECORD inputBuffer[(sizeof(UnicodeInputTestString) /
-                                sizeof(UnicodeInputTestString[0])) * 2];
+                                sizeof(UnicodeInputTestString[0])) *
+                               2];
       memset(&inputBuffer, 0, sizeof(inputBuffer));
       unsigned int i;
       for (i = 0; i < (sizeof(UnicodeInputTestString) /
-                       sizeof(UnicodeInputTestString[0]) - 1); i++) {
-        writeInputKeyEvent(&inputBuffer[i*2], UnicodeInputTestString[i]);
+                         sizeof(UnicodeInputTestString[0]) -
+                       1);
+           i++) {
+        writeInputKeyEvent(&inputBuffer[i * 2], UnicodeInputTestString[i]);
       }
-      writeInputKeyEvent(&inputBuffer[i*2], VK_RETURN);
+      writeInputKeyEvent(&inputBuffer[i * 2], VK_RETURN);
       DWORD eventsWritten = 0;
-      // We need to wait a bit before writing to console so child process have started waiting for input on stdin.
+      // We need to wait a bit before writing to console so child process have
+      // started waiting for input on stdin.
       Sleep(300);
-      if (!WriteConsoleInputW(hIn, inputBuffer, sizeof(inputBuffer) /
-                                                sizeof(inputBuffer[0]),
-                              &eventsWritten) || eventsWritten == 0) {
+      if (!WriteConsoleInputW(hIn, inputBuffer,
+                              sizeof(inputBuffer) / sizeof(inputBuffer[0]),
+                              &eventsWritten) ||
+          eventsWritten == 0) {
         throw std::runtime_error("WriteConsoleInput failed!");
       }
-      if ((status = WaitForSingleObject(afterOutputEvent, waitTimeout)) != WAIT_OBJECT_0) {
+      if ((status = WaitForSingleObject(afterOutputEvent, waitTimeout)) !=
+          WAIT_OBJECT_0) {
         std::cerr.setf(std::ios::hex, std::ios::basefield);
-        std::cerr << "WaitForSingleObject returned unexpected status 0x" << status << std::endl;
+        std::cerr << "WaitForSingleObject returned unexpected status 0x"
+                  << status << std::endl;
         std::cerr.unsetf(std::ios::hex);
         throw std::runtime_error("WaitForSingleObject#2 failed!");
       }
@@ -632,38 +687,49 @@ static int testConsole()
       DWORD charsRead = 0;
       coord.X = 0;
       coord.Y = screenBufferInfo.dwCursorPosition.Y - 4;
-      WCHAR *outputBuffer = new WCHAR[screenBufferInfo.dwSize.X * 4];
+      WCHAR* outputBuffer = new WCHAR[screenBufferInfo.dwSize.X * 4];
       if (!ReadConsoleOutputCharacterW(hOut, outputBuffer,
-          screenBufferInfo.dwSize.X * 4, coord, &charsRead)
-          || charsRead == 0) {
+                                       screenBufferInfo.dwSize.X * 4, coord,
+                                       &charsRead) ||
+          charsRead == 0) {
         delete[] outputBuffer;
         throw std::runtime_error("ReadConsoleOutputCharacter failed!");
       }
       std::wstring wideTestString = kwsys::Encoding::ToWide(encodedTestString);
-      std::wstring wideInputTestString = kwsys::Encoding::ToWide(encodedInputTestString);
+      std::replace(wideTestString.begin(), wideTestString.end(), '\0', ' ');
+      std::wstring wideInputTestString =
+        kwsys::Encoding::ToWide(encodedInputTestString);
       if (memcmp(outputBuffer, wideTestString.c_str(),
                  wideTestString.size() * sizeof(wchar_t)) == 0 &&
           memcmp(outputBuffer + screenBufferInfo.dwSize.X * 1,
-                 wideTestString.c_str(), wideTestString.size() * sizeof(wchar_t)) == 0 &&
+                 wideTestString.c_str(),
+                 wideTestString.size() * sizeof(wchar_t)) == 0 &&
           memcmp(outputBuffer + screenBufferInfo.dwSize.X * 2,
-                 UnicodeInputTestString, sizeof(UnicodeInputTestString) -
-                                         sizeof(WCHAR)) == 0 &&
+                 UnicodeInputTestString,
+                 sizeof(UnicodeInputTestString) - sizeof(WCHAR)) == 0 &&
           memcmp(outputBuffer + screenBufferInfo.dwSize.X * 3,
                  wideInputTestString.c_str(),
-                 (wideInputTestString.size() - 1) * sizeof(wchar_t)) == 0
-      ) {
+                 (wideInputTestString.size() - 1) * sizeof(wchar_t)) == 0) {
         didFail = 0;
       } else {
-        std::cerr << "Console's output didn't match expected output!" << std::endl;
-        dumpBuffers<wchar_t>(wideTestString.c_str(), outputBuffer, wideTestString.size());
-        dumpBuffers<wchar_t>(wideTestString.c_str(), outputBuffer + screenBufferInfo.dwSize.X * 1, wideTestString.size());
-        dumpBuffers<wchar_t>(UnicodeInputTestString, outputBuffer + screenBufferInfo.dwSize.X * 2, (sizeof(UnicodeInputTestString) - 1) / sizeof(WCHAR));
-        dumpBuffers<wchar_t>(wideInputTestString.c_str(), outputBuffer + screenBufferInfo.dwSize.X * 3, wideInputTestString.size() - 1);
+        std::cerr << "Console's output didn't match expected output!"
+                  << std::endl;
+        dumpBuffers<wchar_t>(wideTestString.c_str(), outputBuffer,
+                             wideTestString.size());
+        dumpBuffers<wchar_t>(wideTestString.c_str(),
+                             outputBuffer + screenBufferInfo.dwSize.X * 1,
+                             wideTestString.size());
+        dumpBuffers<wchar_t>(
+          UnicodeInputTestString, outputBuffer + screenBufferInfo.dwSize.X * 2,
+          (sizeof(UnicodeInputTestString) - 1) / sizeof(WCHAR));
+        dumpBuffers<wchar_t>(wideInputTestString.c_str(),
+                             outputBuffer + screenBufferInfo.dwSize.X * 3,
+                             wideInputTestString.size() - 1);
       }
       delete[] outputBuffer;
-    } catch (const std::runtime_error &ex) {
+    } catch (const std::runtime_error& ex) {
       DWORD lastError = GetLastError();
-      std::cerr << "In function testConsole, line " <<  __LINE__ << ": "
+      std::cerr << "In function testConsole, line " << __LINE__ << ": "
                 << ex.what() << std::endl;
       displayError(lastError);
     }
@@ -683,15 +749,15 @@ static int testConsole()
 #endif
 
 //----------------------------------------------------------------------------
-int testConsoleBuf(int, char*[])
+int testConsoleBuf(int, char* [])
 {
   int ret = 0;
 
 #if defined(_WIN32)
   beforeInputEvent = CreateEventW(NULL,
-                       FALSE,  // auto-reset event
-                       FALSE,  // initial state is nonsignaled
-                       BeforeInputEventName);  // object name
+                                  FALSE, // auto-reset event
+                                  FALSE, // initial state is nonsignaled
+                                  BeforeInputEventName); // object name
   if (!beforeInputEvent) {
     std::cerr << "CreateEvent#1 failed " << GetLastError() << std::endl;
     return 1;
@@ -703,8 +769,11 @@ int testConsoleBuf(int, char*[])
     return 1;
   }
 
-  encodedTestString = kwsys::Encoding::ToNarrow(UnicodeTestString);
-  encodedInputTestString = kwsys::Encoding::ToNarrow(UnicodeInputTestString);
+  encodedTestString = kwsys::Encoding::ToNarrow(std::wstring(
+    UnicodeTestString, sizeof(UnicodeTestString) / sizeof(wchar_t) - 1));
+  encodedInputTestString = kwsys::Encoding::ToNarrow(
+    std::wstring(UnicodeInputTestString,
+                 sizeof(UnicodeInputTestString) / sizeof(wchar_t) - 1));
   encodedInputTestString += "\n";
 
   ret |= testPipe();
diff --git a/Source/kwsys/testConsoleBuf.hxx b/Source/kwsys/testConsoleBuf.hxx
index 7c2f4c6..e93cb4f 100644
--- a/Source/kwsys/testConsoleBuf.hxx
+++ b/Source/kwsys/testConsoleBuf.hxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  Copyright 2000-2016 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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef testConsoleBuf_hxx
 #define testConsoleBuf_hxx
 
@@ -18,8 +9,9 @@ static const wchar_t BeforeInputEventName[] = L"BeforeInputEvent";
 static const wchar_t AfterOutputEventName[] = L"AfterOutputEvent";
 
 // यूनिकोड είναι здорово!
-static const wchar_t UnicodeTestString[] = L"\u092F\u0942\u0928\u093F\u0915\u094B\u0921 "
-                                           L"\u03B5\u03AF\u03BD\u03B1\u03B9 "
-                                           L"\u0437\u0434\u043E\u0440\u043E\u0432\u043E!";
+static const wchar_t UnicodeTestString[] =
+  L"\u092F\u0942\u0928\u093F\u0915\u094B\u0921 "
+  L"\u03B5\u03AF\u03BD\0\u03B1\u03B9 "
+  L"\u0437\u0434\u043E\u0440\u043E\u0432\u043E!";
 
 #endif
diff --git a/Source/kwsys/testConsoleBufChild.cxx b/Source/kwsys/testConsoleBufChild.cxx
index 2da39f2..83bf545 100644
--- a/Source/kwsys/testConsoleBufChild.cxx
+++ b/Source/kwsys/testConsoleBufChild.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  Copyright 2000-2016 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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 
 #include KWSYS_HEADER(ConsoleBuf.hxx)
@@ -17,11 +8,12 @@
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "ConsoleBuf.hxx.in"
-# include "Encoding.hxx.in"
+#include "ConsoleBuf.hxx.in"
+#include "Encoding.hxx.in"
 #endif
 
 #include <iostream>
+
 #include "testConsoleBuf.hxx"
 
 //----------------------------------------------------------------------------
@@ -36,7 +28,8 @@ int main(int argc, const char* argv[])
     std::cout << argv[1] << std::endl;
     std::cerr << argv[1] << std::endl;
   } else {
-    std::string str = kwsys::Encoding::ToNarrow(UnicodeTestString);
+    std::string str = kwsys::Encoding::ToNarrow(std::wstring(
+      UnicodeTestString, sizeof(UnicodeTestString) / sizeof(wchar_t) - 1));
     std::cout << str << std::endl;
     std::cerr << str << std::endl;
   }
diff --git a/Source/kwsys/testDynamicLoader.cxx b/Source/kwsys/testDynamicLoader.cxx
index 7c58769..b52ddda 100644
--- a/Source/kwsys/testDynamicLoader.cxx
+++ b/Source/kwsys/testDynamicLoader.cxx
@@ -1,30 +1,21 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 
 #include KWSYS_HEADER(DynamicLoader.hxx)
 
 #if defined(__BEOS__) || defined(__HAIKU__)
-#include <be/kernel/OS.h>  /* disable_debugger() API. */
+#include <be/kernel/OS.h> /* disable_debugger() API. */
 #endif
 
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "DynamicLoader.hxx.in"
+#include "DynamicLoader.hxx.in"
 #endif
 
-#include <string>
 #include <iostream>
+#include <string>
 
 // Include with <> instead of "" to avoid getting any in-source copy
 // left on disk.
@@ -53,41 +44,36 @@ static std::string GetLibName(const char* lname)
  * r2: should GetSymbolAddress succeed ?
  * r3: should CloseLibrary succeed ?
  */
-static int TestDynamicLoader(const char* libname, const char* symbol, int r1, int r2, int r3)
+static int TestDynamicLoader(const char* libname, const char* symbol, int r1,
+                             int r2, int r3)
 {
   std::cerr << "Testing: " << libname << std::endl;
-  kwsys::DynamicLoader::LibraryHandle l
-    = kwsys::DynamicLoader::OpenLibrary(libname);
+  kwsys::DynamicLoader::LibraryHandle l =
+    kwsys::DynamicLoader::OpenLibrary(libname);
   // If result is incompatible with expectation just fails (xor):
-  if( (r1 && !l) || (!r1 && l) )
-    {
-    std::cerr
-      << kwsys::DynamicLoader::LastError() << std::endl;
+  if ((r1 && !l) || (!r1 && l)) {
+    std::cerr << kwsys::DynamicLoader::LastError() << std::endl;
     return 1;
-    }
-  kwsys::DynamicLoader::SymbolPointer f
-    = kwsys::DynamicLoader::GetSymbolAddress(l, symbol);
-  if( (r2 && !f) || (!r2 && f) )
-    {
-    std::cerr
-      << kwsys::DynamicLoader::LastError() << std::endl;
+  }
+  kwsys::DynamicLoader::SymbolPointer f =
+    kwsys::DynamicLoader::GetSymbolAddress(l, symbol);
+  if ((r2 && !f) || (!r2 && f)) {
+    std::cerr << kwsys::DynamicLoader::LastError() << std::endl;
     return 1;
-    }
+  }
 #ifndef __APPLE__
   int s = kwsys::DynamicLoader::CloseLibrary(l);
-  if( (r3 && !s) || (!r3 && s) )
-    {
-    std::cerr
-      << kwsys::DynamicLoader::LastError() << std::endl;
+  if ((r3 && !s) || (!r3 && s)) {
+    std::cerr << kwsys::DynamicLoader::LastError() << std::endl;
     return 1;
-    }
+  }
 #else
   (void)r3;
 #endif
   return 0;
 }
 
-int testDynamicLoader(int argc, char *argv[])
+int testDynamicLoader(int argc, char* argv[])
 {
 #if defined(_WIN32)
   SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
@@ -95,34 +81,37 @@ int testDynamicLoader(int argc, char *argv[])
   disable_debugger(1);
 #endif
   int res = 0;
-  if( argc == 3 )
-    {
+  if (argc == 3) {
     // User specify a libname and symbol to check.
-    res = TestDynamicLoader(argv[1], argv[2],1,1,1);
+    res = TestDynamicLoader(argv[1], argv[2], 1, 1, 1);
     return res;
-    }
+  }
 
 // dlopen() on Syllable before 11/22/2007 doesn't return 0 on error
 #ifndef __SYLLABLE__
   // Make sure that inexistent lib is giving correct result
-  res += TestDynamicLoader("azerty_", "foo_bar",0,0,0);
+  res += TestDynamicLoader("azerty_", "foo_bar", 0, 0, 0);
   // Make sure that random binary file cannot be assimilated as dylib
-  res += TestDynamicLoader(TEST_SYSTEMTOOLS_SOURCE_DIR "/testSystemTools.bin", "wp",0,0,0);
+  res += TestDynamicLoader(TEST_SYSTEMTOOLS_SOURCE_DIR "/testSystemTools.bin",
+                           "wp", 0, 0, 0);
 #endif
 
 #ifdef __linux__
-  // This one is actually fun to test, since dlopen is by default loaded...wonder why :)
-  res += TestDynamicLoader("foobar.lib", "dlopen",0,1,0);
-  res += TestDynamicLoader("libdl.so", "dlopen",1,1,1);
-  res += TestDynamicLoader("libdl.so", "TestDynamicLoader",1,0,1);
+  // This one is actually fun to test, since dlopen is by default
+  // loaded...wonder why :)
+  res += TestDynamicLoader("foobar.lib", "dlopen", 0, 1, 0);
+  res += TestDynamicLoader("libdl.so", "dlopen", 1, 1, 1);
+  res += TestDynamicLoader("libdl.so", "TestDynamicLoader", 1, 0, 1);
 #endif
   // Now try on the generated library
   std::string libname = GetLibName(KWSYS_NAMESPACE_STRING "TestDynload");
-  res += TestDynamicLoader(libname.c_str(), "dummy",1,0,1);
-  res += TestDynamicLoader(libname.c_str(), "TestDynamicLoaderSymbolPointer",1,1,1);
-  res += TestDynamicLoader(libname.c_str(), "_TestDynamicLoaderSymbolPointer",1,0,1);
-  res += TestDynamicLoader(libname.c_str(), "TestDynamicLoaderData",1,1,1);
-  res += TestDynamicLoader(libname.c_str(), "_TestDynamicLoaderData",1,0,1);
+  res += TestDynamicLoader(libname.c_str(), "dummy", 1, 0, 1);
+  res += TestDynamicLoader(libname.c_str(), "TestDynamicLoaderSymbolPointer",
+                           1, 1, 1);
+  res += TestDynamicLoader(libname.c_str(), "_TestDynamicLoaderSymbolPointer",
+                           1, 0, 1);
+  res += TestDynamicLoader(libname.c_str(), "TestDynamicLoaderData", 1, 1, 1);
+  res += TestDynamicLoader(libname.c_str(), "_TestDynamicLoaderData", 1, 0, 1);
 
   return res;
 }
diff --git a/Source/kwsys/testDynload.c b/Source/kwsys/testDynload.c
index ba60bec..cdb9e5c 100644
--- a/Source/kwsys/testDynload.c
+++ b/Source/kwsys/testDynload.c
@@ -1,16 +1,7 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifdef _WIN32
-#define DL_EXPORT __declspec( dllexport )
+#define DL_EXPORT __declspec(dllexport)
 #else
 #define DL_EXPORT
 #endif
diff --git a/Source/kwsys/testEncode.c b/Source/kwsys/testEncode.c
index 26d483b..a20d46f 100644
--- a/Source/kwsys/testEncode.c
+++ b/Source/kwsys/testEncode.c
@@ -1,29 +1,20 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(MD5.h)
 
 /* Work-around CMake dependency scanning limitation.  This must
    duplicate the above list of headers.  */
 #if 0
-# include "MD5.h.in"
+#include "MD5.h.in"
 #endif
 
 #include <stdio.h>
 #include <string.h>
 
 static const unsigned char testMD5input1[] =
-"  A quick brown fox jumps over the lazy dog.\n"
-"  This is sample text for MD5 sum input.\n";
+  "  A quick brown fox jumps over the lazy dog.\n"
+  "  This is sample text for MD5 sum input.\n";
 static const char testMD5output1[] = "8f146af46ed4f267921bb937d4d3500c";
 
 static const int testMD5input2len = 28;
@@ -40,7 +31,7 @@ static int testMD5_1(kwsysMD5* md5)
   printf("md5sum 1: expected [%s]\n"
          "               got [%s]\n",
          testMD5output1, md5out);
-  return (strcmp(md5out, testMD5output1) != 0)? 1:0;
+  return (strcmp(md5out, testMD5output1) != 0) ? 1 : 0;
 }
 
 static int testMD5_2(kwsysMD5* md5)
@@ -55,7 +46,7 @@ static int testMD5_2(kwsysMD5* md5)
   printf("md5sum 2: expected [%s]\n"
          "               got [%s]\n",
          testMD5output2, md5out);
-  return (strcmp(md5out, testMD5output2) != 0)? 1:0;
+  return (strcmp(md5out, testMD5output2) != 0) ? 1 : 0;
 }
 
 int testEncode(int argc, char* argv[])
@@ -66,10 +57,10 @@ int testEncode(int argc, char* argv[])
 
   /* Test MD5 digest.  */
   {
-  kwsysMD5* md5 = kwsysMD5_New();
-  result |= testMD5_1(md5);
-  result |= testMD5_2(md5);
-  kwsysMD5_Delete(md5);
+    kwsysMD5* md5 = kwsysMD5_New();
+    result |= testMD5_1(md5);
+    result |= testMD5_2(md5);
+    kwsysMD5_Delete(md5);
   }
 
   return result;
diff --git a/Source/kwsys/testEncoding.cxx b/Source/kwsys/testEncoding.cxx
index 80ec040..03f2ec9 100644
--- a/Source/kwsys/testEncoding.cxx
+++ b/Source/kwsys/testEncoding.cxx
@@ -1,87 +1,74 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 
 #if defined(_MSC_VER)
-# pragma warning (disable:4786)
+#pragma warning(disable : 4786)
 #endif
 
 #include KWSYS_HEADER(Encoding.hxx)
 #include KWSYS_HEADER(Encoding.h)
 
+#include <algorithm>
 #include <iostream>
 #include <locale.h>
-#include <string.h>
 #include <stdlib.h>
+#include <string.h>
 
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "Encoding.hxx.in"
-# include "Encoding.h.in"
+#include "Encoding.h.in"
+#include "Encoding.hxx.in"
 #endif
 
 //----------------------------------------------------------------------------
-static const unsigned char helloWorldStrings[][32] =
-{
+static const unsigned char helloWorldStrings[][32] = {
   // English
-  {'H','e','l','l','o',' ','W','o','r','l','d',0},
+  { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', 0 },
   // Japanese
-  {0xE3, 0x81, 0x93, 0xE3, 0x82, 0x93, 0xE3, 0x81, 0xAB, 0xE3,
-   0x81, 0xA1, 0xE3, 0x81, 0xAF, 0xE4, 0xB8, 0x96, 0xE7, 0x95,
-   0x8C, 0},
-   // Arabic
-  {0xD9, 0x85, 0xD8, 0xB1, 0xD8, 0xAD, 0xD8, 0xA8, 0xD8, 0xA7,
-   0x20, 0xD8, 0xA7, 0xD9, 0x84, 0xD8, 0xB9, 0xD8, 0xA7, 0xD9,
-   0x84, 0xD9, 0x85, 0},
+  { 0xE3, 0x81, 0x93, 0xE3, 0x82, 0x93, 0xE3, 0x81, 0xAB, 0xE3, 0x81,
+    0xA1, 0xE3, 0x81, 0xAF, 0xE4, 0xB8, 0x96, 0xE7, 0x95, 0x8C, 0 },
+  // Arabic
+  { 0xD9, 0x85, 0xD8, 0xB1, 0xD8, 0xAD, 0xD8, 0xA8, 0xD8, 0xA7, 0x20, 0xD8,
+    0xA7, 0xD9, 0x84, 0xD8, 0xB9, 0xD8, 0xA7, 0xD9, 0x84, 0xD9, 0x85, 0 },
   // Yiddish
-  {0xD7, 0x94, 0xD7, 0xA2, 0xD7, 0x9C, 0xD7, 0x90, 0x20, 0xD7,
-   0x95, 0xD7, 0x95, 0xD7, 0xA2, 0xD7, 0x9C, 0xD7, 0x98, 0},
+  { 0xD7, 0x94, 0xD7, 0xA2, 0xD7, 0x9C, 0xD7, 0x90, 0x20, 0xD7,
+    0x95, 0xD7, 0x95, 0xD7, 0xA2, 0xD7, 0x9C, 0xD7, 0x98, 0 },
   // Russian
-  {0xD0, 0xBF, 0xD1, 0x80, 0xD0, 0xB8, 0xD0, 0xB2, 0xD0, 0xB5,
-   0xD1, 0x82, 0x20, 0xD0, 0xBC, 0xD0, 0xB8, 0xD1, 0x80, 0},
+  { 0xD0, 0xBF, 0xD1, 0x80, 0xD0, 0xB8, 0xD0, 0xB2, 0xD0, 0xB5,
+    0xD1, 0x82, 0x20, 0xD0, 0xBC, 0xD0, 0xB8, 0xD1, 0x80, 0 },
   // Latin
-  {0x4D, 0x75, 0x6E, 0x64, 0x75, 0x73, 0x20, 0x73, 0x61, 0x6C,
-   0x76, 0x65, 0},
+  { 0x4D, 0x75, 0x6E, 0x64, 0x75, 0x73, 0x20, 0x73, 0x61, 0x6C, 0x76, 0x65,
+    0 },
   // Swahili
-  {0x68, 0x75, 0x6A, 0x61, 0x6D, 0x62, 0x6F, 0x20, 0x44, 0x75,
-   0x6E, 0x69, 0x61, 0},
+  { 0x68, 0x75, 0x6A, 0x61, 0x6D, 0x62, 0x6F, 0x20, 0x44, 0x75, 0x6E, 0x69,
+    0x61, 0 },
   // Icelandic
-  {0x48, 0x61, 0x6C, 0x6C, 0xC3, 0xB3, 0x20, 0x68, 0x65, 0x69,
-   0x6D, 0x75, 0x72, 0},
-  {0}
+  { 0x48, 0x61, 0x6C, 0x6C, 0xC3, 0xB3, 0x20, 0x68, 0x65, 0x69, 0x6D, 0x75,
+    0x72, 0 },
+  { 0 }
 };
 
 //----------------------------------------------------------------------------
 static int testHelloWorldEncoding()
 {
   int ret = 0;
-  for(int i=0; helloWorldStrings[i][0] != 0; i++)
-    {
+  for (int i = 0; helloWorldStrings[i][0] != 0; i++) {
     std::string str = reinterpret_cast<const char*>(helloWorldStrings[i]);
     std::cout << str << std::endl;
     std::wstring wstr = kwsys::Encoding::ToWide(str);
     std::string str2 = kwsys::Encoding::ToNarrow(wstr);
     wchar_t* c_wstr = kwsysEncoding_DupToWide(str.c_str());
     char* c_str2 = kwsysEncoding_DupToNarrow(c_wstr);
-    if(!wstr.empty() && (str != str2 || strcmp(c_str2, str.c_str())))
-      {
+    if (!wstr.empty() && (str != str2 || strcmp(c_str2, str.c_str()))) {
       std::cout << "converted string was different: " << str2 << std::endl;
       std::cout << "converted string was different: " << c_str2 << std::endl;
       ret++;
-      }
+    }
     free(c_wstr);
     free(c_str2);
-    }
+  }
   return ret;
 }
 
@@ -91,80 +78,98 @@ static int testRobustEncoding()
   // unicode correctly/gracefully
 
   int ret = 0;
-  char cstr[] = {(char)-1, 0};
+  char cstr[] = { (char)-1, 0 };
   // this conversion could fail
   std::wstring wstr = kwsys::Encoding::ToWide(cstr);
 
   wstr = kwsys::Encoding::ToWide(NULL);
-  if(wstr != L"")
-    {
+  if (wstr != L"") {
     const wchar_t* wcstr = wstr.c_str();
     std::cout << "ToWide(NULL) returned";
-    for(size_t i=0; i<wstr.size(); i++)
-      {
+    for (size_t i = 0; i < wstr.size(); i++) {
       std::cout << " " << std::hex << (int)wcstr[i];
-      }
+    }
     std::cout << std::endl;
     ret++;
-    }
+  }
   wstr = kwsys::Encoding::ToWide("");
-  if(wstr != L"")
-    {
+  if (wstr != L"") {
     const wchar_t* wcstr = wstr.c_str();
     std::cout << "ToWide(\"\") returned";
-    for(size_t i=0; i<wstr.size(); i++)
-      {
+    for (size_t i = 0; i < wstr.size(); i++) {
       std::cout << " " << std::hex << (int)wcstr[i];
-      }
+    }
     std::cout << std::endl;
     ret++;
-    }
+  }
 
 #ifdef _WIN32
   // 16 bit wchar_t - we make an invalid surrogate pair
-  wchar_t cwstr[] = {0xD801, 0xDA00, 0};
+  wchar_t cwstr[] = { 0xD801, 0xDA00, 0 };
   // this conversion could fail
   std::string win_str = kwsys::Encoding::ToNarrow(cwstr);
 #endif
 
   std::string str = kwsys::Encoding::ToNarrow(NULL);
-  if(str != "")
-    {
+  if (str != "") {
     std::cout << "ToNarrow(NULL) returned " << str << std::endl;
     ret++;
-    }
+  }
 
   str = kwsys::Encoding::ToNarrow(L"");
-  if(wstr != L"")
-    {
+  if (wstr != L"") {
     std::cout << "ToNarrow(\"\") returned " << str << std::endl;
     ret++;
-    }
+  }
 
   return ret;
 }
 
+static int testWithNulls()
+{
+  int ret = 0;
+  std::vector<std::string> strings;
+  strings.push_back(std::string("ab") + '\0' + 'c');
+  strings.push_back(std::string("d") + '\0' + '\0' + 'e');
+  strings.push_back(std::string() + '\0' + 'f');
+  strings.push_back(std::string() + '\0' + '\0' + "gh");
+  strings.push_back(std::string("ij") + '\0');
+  strings.push_back(std::string("k") + '\0' + '\0');
+  strings.push_back(std::string("\0\0\0\0", 4) + "lmn" +
+                    std::string("\0\0\0\0", 4));
+  for (std::vector<std::string>::iterator it = strings.begin();
+       it != strings.end(); ++it) {
+    std::wstring wstr = kwsys::Encoding::ToWide(*it);
+    std::string str = kwsys::Encoding::ToNarrow(wstr);
+    std::string s(*it);
+    std::replace(s.begin(), s.end(), '\0', ' ');
+    std::cout << "'" << s << "' (" << it->size() << ")" << std::endl;
+    if (str != *it) {
+      std::replace(str.begin(), str.end(), '\0', ' ');
+      std::cout << "string with null was different: '" << str << "' ("
+                << str.size() << ")" << std::endl;
+      ret++;
+    }
+  }
+  return ret;
+}
+
 static int testCommandLineArguments()
 {
   int status = 0;
 
-  char const* argv[2] = {
-    "./app.exe",
-    (char const*)helloWorldStrings[1]
-  };
+  char const* argv[2] = { "./app.exe", (char const*)helloWorldStrings[1] };
 
   kwsys::Encoding::CommandLineArguments args(2, argv);
   kwsys::Encoding::CommandLineArguments arg2 =
     kwsys::Encoding::CommandLineArguments(args);
 
   char const* const* u8_argv = args.argv();
-  for(int i=0; i<args.argc(); i++)
-  {
+  for (int i = 0; i < args.argc(); i++) {
     char const* u8_arg = u8_argv[i];
-    if(strcmp(argv[i], u8_arg) != 0)
-    {
-      std::cout << "argv[" << i << "] " << argv[i] << " != "
-                << u8_arg << std::endl;
+    if (strcmp(argv[i], u8_arg) != 0) {
+      std::cout << "argv[" << i << "] " << argv[i] << " != " << u8_arg
+                << std::endl;
       status++;
     }
   }
@@ -176,23 +181,21 @@ static int testCommandLineArguments()
 }
 
 //----------------------------------------------------------------------------
-int testEncoding(int, char*[])
+int testEncoding(int, char* [])
 {
   const char* loc = setlocale(LC_ALL, "");
-  if(loc)
-    {
+  if (loc) {
     std::cout << "Locale: " << loc << std::endl;
-    }
-  else
-    {
+  } else {
     std::cout << "Locale: None" << std::endl;
-    }
+  }
 
   int ret = 0;
 
   ret |= testHelloWorldEncoding();
   ret |= testRobustEncoding();
   ret |= testCommandLineArguments();
+  ret |= testWithNulls();
 
   return ret;
 }
diff --git a/Source/kwsys/testFStream.cxx b/Source/kwsys/testFStream.cxx
index 5e53725..670f5e7 100644
--- a/Source/kwsys/testFStream.cxx
+++ b/Source/kwsys/testFStream.cxx
@@ -1,30 +1,21 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 
 #if defined(_MSC_VER)
-# pragma warning (disable:4786)
+#pragma warning(disable : 4786)
 #endif
 
 #include KWSYS_HEADER(FStream.hxx)
 #include <string.h>
 #ifdef __BORLANDC__
-# include <mem.h> /* memcmp */
+#include <mem.h> /* memcmp */
 #endif
 
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "FStream.hxx.in"
+#include "FStream.hxx.in"
 #endif
 
 #include <iostream>
@@ -33,10 +24,9 @@
 static int testNoFile()
 {
   kwsys::ifstream in_file("NoSuchFile.txt");
-  if(in_file)
-    {
+  if (in_file) {
     return 1;
-    }
+  }
 
   return 0;
 }
@@ -44,90 +34,78 @@ static int testNoFile()
 static const int num_test_files = 7;
 static const int max_test_file_size = 45;
 
-static kwsys::FStream::BOM expected_bom[num_test_files] =
-{
-  kwsys::FStream::BOM_None,
-  kwsys::FStream::BOM_None,
-  kwsys::FStream::BOM_UTF8,
-  kwsys::FStream::BOM_UTF16LE,
-  kwsys::FStream::BOM_UTF16BE,
-  kwsys::FStream::BOM_UTF32LE,
+static kwsys::FStream::BOM expected_bom[num_test_files] = {
+  kwsys::FStream::BOM_None,    kwsys::FStream::BOM_None,
+  kwsys::FStream::BOM_UTF8,    kwsys::FStream::BOM_UTF16LE,
+  kwsys::FStream::BOM_UTF16BE, kwsys::FStream::BOM_UTF32LE,
   kwsys::FStream::BOM_UTF32BE
 };
 
-static unsigned char expected_bom_data[num_test_files][5] =
-{
-    {0},
-    {0},
-    {3, 0xEF, 0xBB, 0xBF},
-    {2, 0xFF, 0xFE},
-    {2, 0xFE, 0xFF},
-    {4, 0xFF, 0xFE, 0x00, 0x00},
-    {4, 0x00, 0x00, 0xFE, 0xFF},
+static unsigned char expected_bom_data[num_test_files][5] = {
+  { 0 },
+  { 0 },
+  { 3, 0xEF, 0xBB, 0xBF },
+  { 2, 0xFF, 0xFE },
+  { 2, 0xFE, 0xFF },
+  { 4, 0xFF, 0xFE, 0x00, 0x00 },
+  { 4, 0x00, 0x00, 0xFE, 0xFF },
 };
 
-static unsigned char file_data[num_test_files][max_test_file_size] =
-{
-    {1, 'H'},
-    {11, 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'},
-    {11, 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'},
-    {22, 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x20, 0x00,
-    0x57, 0x00, 0x6F, 0x00, 0x72, 0x00, 0x6C, 0x00, 0x64, 0x00},
-    {22, 0x00, 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x20,
-    0x00, 0x57, 0x00, 0x6F, 0x00, 0x72, 0x00, 0x6C, 0x00, 0x64},
-    {44, 0x48, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00,
-    0x6C, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
-    0x57, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x72, 0x00, 0x00, 0x00,
-    0x6C, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00},
-    {44, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x6C,
-    0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x20,
-    0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x72,
-    0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x64},
+static unsigned char file_data[num_test_files][max_test_file_size] = {
+  { 1, 'H' },
+  { 11, 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' },
+  { 11, 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' },
+  { 22,   0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x20,
+    0x00, 0x57, 0x00, 0x6F, 0x00, 0x72, 0x00, 0x6C, 0x00, 0x64, 0x00 },
+  { 22,   0x00, 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00,
+    0x20, 0x00, 0x57, 0x00, 0x6F, 0x00, 0x72, 0x00, 0x6C, 0x00, 0x64 },
+  { 44,   0x48, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00,
+    0x00, 0x6C, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00,
+    0x00, 0x57, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x72, 0x00, 0x00,
+    0x00, 0x6C, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00 },
+  { 44,   0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00,
+    0x6C, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00,
+    0x20, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00,
+    0x72, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x64 },
 };
 
 //----------------------------------------------------------------------------
 static int testBOM()
 {
   // test various encodings in binary mode
-  for(int i=0; i<num_test_files; i++)
+  for (int i = 0; i < num_test_files; i++) {
     {
-      {
       kwsys::ofstream out("bom.txt", kwsys::ofstream::binary);
-      out.write(reinterpret_cast<const char*>(expected_bom_data[i]+1),
+      out.write(reinterpret_cast<const char*>(expected_bom_data[i] + 1),
                 *expected_bom_data[i]);
-      out.write(reinterpret_cast<const char*>(file_data[i]+1),
+      out.write(reinterpret_cast<const char*>(file_data[i] + 1),
                 file_data[i][0]);
-      }
+    }
 
     kwsys::ifstream in("bom.txt", kwsys::ofstream::binary);
     kwsys::FStream::BOM bom = kwsys::FStream::ReadBOM(in);
-    if(bom != expected_bom[i])
-      {
+    if (bom != expected_bom[i]) {
       std::cout << "Unexpected BOM " << i << std::endl;
       return 1;
-      }
+    }
     char data[max_test_file_size];
     in.read(data, file_data[i][0]);
-    if(!in.good())
-      {
+    if (!in.good()) {
       std::cout << "Unable to read data " << i << std::endl;
       return 1;
-      }
+    }
 
-    if(memcmp(data, file_data[i]+1, file_data[i][0]) != 0)
-      {
+    if (memcmp(data, file_data[i] + 1, file_data[i][0]) != 0) {
       std::cout << "Incorrect read data " << i << std::endl;
       return 1;
-      }
-
     }
+  }
 
   return 0;
 }
 
-
 //----------------------------------------------------------------------------
-int testFStream(int, char*[])
+int testFStream(int, char* [])
 {
   int ret = 0;
 
diff --git a/Source/kwsys/testFail.c b/Source/kwsys/testFail.c
index 7e062c1..82caeac 100644
--- a/Source/kwsys/testFail.c
+++ b/Source/kwsys/testFail.c
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -17,19 +8,17 @@ int testFail(int argc, char* argv[])
 {
   char* env = getenv("DASHBOARD_TEST_FROM_CTEST");
   int oldCtest = 0;
-  if(env)
-    {
-    if(strcmp(env, "1") == 0)
-      {
+  if (env) {
+    if (strcmp(env, "1") == 0) {
       oldCtest = 1;
-      }
-    printf("DASHBOARD_TEST_FROM_CTEST = %s\n", env);
     }
+    printf("DASHBOARD_TEST_FROM_CTEST = %s\n", env);
+  }
   printf("%s: This test intentionally fails\n", argv[0]);
-  if(oldCtest)
-    {
-    printf("The version of ctest is not able to handle intentionally failing tests, so pass.\n");
+  if (oldCtest) {
+    printf("The version of ctest is not able to handle intentionally failing "
+           "tests, so pass.\n");
     return 0;
-    }
+  }
   return argc;
 }
diff --git a/Source/kwsys/testHashSTL.cxx b/Source/kwsys/testHashSTL.cxx
index ae66ceb..0444874 100644
--- a/Source/kwsys/testHashSTL.cxx
+++ b/Source/kwsys/testHashSTL.cxx
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(hash_map.hxx)
 #include KWSYS_HEADER(hash_set.hxx)
@@ -16,18 +7,18 @@
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "hash_map.hxx.in"
-# include "hash_set.hxx.in"
+#include "hash_map.hxx.in"
+#include "hash_set.hxx.in"
 #endif
 
 #include <iostream>
 
 #if defined(_MSC_VER)
-# pragma warning (disable:4786)
+#pragma warning(disable : 4786)
 #endif
 
 #if defined(__sgi) && !defined(__GNUC__)
-# pragma set woff 1468 /* inline function cannot be explicitly instantiated */
+#pragma set woff 1468 /* inline function cannot be explicitly instantiated */
 #endif
 
 template class kwsys::hash_map<const char*, int>;
@@ -37,16 +28,15 @@ static bool test_hash_map()
 {
   typedef kwsys::hash_map<const char*, int> mtype;
   mtype m;
-  const char* keys[] = {"hello", "world"};
+  const char* keys[] = { "hello", "world" };
   m[keys[0]] = 1;
   m.insert(mtype::value_type(keys[1], 2));
   int sum = 0;
-  for(mtype::iterator mi = m.begin(); mi != m.end(); ++mi)
-    {
+  for (mtype::iterator mi = m.begin(); mi != m.end(); ++mi) {
     std::cout << "Found entry [" << mi->first << "," << mi->second << "]"
               << std::endl;
     sum += mi->second;
-    }
+  }
   return sum == 3;
 }
 
@@ -57,18 +47,17 @@ static bool test_hash_set()
   s.insert(1);
   s.insert(2);
   int sum = 0;
-  for(stype::iterator si = s.begin(); si != s.end(); ++si)
-    {
+  for (stype::iterator si = s.begin(); si != s.end(); ++si) {
     std::cout << "Found entry [" << *si << "]" << std::endl;
     sum += *si;
-    }
+  }
   return sum == 3;
 }
 
-int testHashSTL(int, char*[])
+int testHashSTL(int, char* [])
 {
   bool result = true;
   result = test_hash_map() && result;
   result = test_hash_set() && result;
-  return result? 0:1;
+  return result ? 0 : 1;
 }
diff --git a/Source/kwsys/testIOS.cxx b/Source/kwsys/testIOS.cxx
index 5ff7955..3e4c325 100644
--- a/Source/kwsys/testIOS.cxx
+++ b/Source/kwsys/testIOS.cxx
@@ -1,163 +1,138 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(Configure.hxx)
 
-#include <sstream>
 #include <fstream>
 #include <iostream>
-#include <vector>
+#include <sstream>
 #include <string.h> /* strlen */
+#include <vector>
 
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "Configure.hxx.in"
+#include "Configure.hxx.in"
 #endif
 
-int testIOS(int, char*[])
+int testIOS(int, char* [])
 {
   std::ostringstream ostr;
   const char hello[] = "hello";
   ostr << hello;
-  if(ostr.str() != hello)
-    {
+  if (ostr.str() != hello) {
     std::cerr << "failed to write hello to ostr" << std::endl;
     return 1;
-    }
+  }
   const char world[] = "world";
   std::ostringstream ostr2;
-  ostr2.write( hello, strlen(hello) ); /* I could do sizeof */
-  ostr2.put( '\0' );
-  ostr2.write( world, strlen(world) );
-  if(ostr2.str().size() !=  strlen(hello) + 1 + strlen(world) )
-    {
+  ostr2.write(hello, strlen(hello)); /* I could do sizeof */
+  ostr2.put('\0');
+  ostr2.write(world, strlen(world));
+  if (ostr2.str().size() != strlen(hello) + 1 + strlen(world)) {
     std::cerr << "failed to write hello to ostr2" << std::endl;
     return 1;
-    }
-  static const unsigned char array[] = { 0xff,0x4f,0xff,0x51,0x00,0x29,0x00,0x00,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x3e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x3e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x07,0x01,0x01,0xff,0x52,0x00,0x0c,0x00,0x00,0x00,0x01,0x00,0x05,0x04,0x04,0x00,0x01,0xff,0x5c,0x00,0x13,0x40,0x40,0x48,0x48,0x50,0x48,0x48,0x50,0x48,0x48,0x50,0x48,0x48,0x50,0x48,0x48,0x50,0xff,0x64,0x00,0x2c,0x00,0x00,0x43,0x72,0x65,0x61,0 [...]
+  }
+  static const unsigned char array[] = {
+    0xff, 0x4f, 0xff, 0x51, 0x00, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30,
+    0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01, 0x01, 0xff, 0x52, 0x00,
+    0x0c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x05, 0x04, 0x04, 0x00, 0x01, 0xff,
+    0x5c, 0x00, 0x13, 0x40, 0x40, 0x48, 0x48, 0x50, 0x48, 0x48, 0x50, 0x48,
+    0x48, 0x50, 0x48, 0x48, 0x50, 0x48, 0x48, 0x50, 0xff, 0x64, 0x00, 0x2c,
+    0x00, 0x00, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79,
+    0x20, 0x49, 0x54, 0x4b, 0x2f, 0x47, 0x44, 0x43, 0x4d, 0x2f, 0x4f, 0x70,
+    0x65, 0x6e, 0x4a, 0x50, 0x45, 0x47, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69,
+    0x6f, 0x6e, 0x20, 0x31, 0x2e, 0x30, 0xff, 0x90, 0x00, 0x0a, 0x00, 0x00,
+    0x00, 0x00, 0x06, 0x2c, 0x00, 0x01, 0xff, 0x93, 0xcf, 0xb0, 0x18, 0x08,
+    0x7f, 0xc6, 0x99, 0xbf, 0xff, 0xc0, 0xf8, 0xc1, 0xc1, 0xf3, 0x05, 0x81,
+    0xf2, 0x83, 0x0a, 0xa5, 0xff, 0x10, 0x90, 0xbf, 0x2f, 0xff, 0x04, 0xa8,
+    0x7f, 0xc0, 0xf8, 0xc4, 0xc1, 0xf3, 0x09, 0x81, 0xf3, 0x0c, 0x19, 0x34
+  };
   const size_t narray = sizeof(array); // 180
   std::stringstream strstr;
-  strstr.write( (char*)array, narray );
-  //strstr.seekp( narray / 2 ); // set position of put pointer in mid string
-  if(strstr.str().size() != narray )
-    {
+  strstr.write((char*)array, narray);
+  // strstr.seekp( narray / 2 ); // set position of put pointer in mid string
+  if (strstr.str().size() != narray) {
     std::cerr << "failed to write array to strstr" << std::endl;
     return 1;
-    }
+  }
 
   std::istringstream istr(" 10 20 str ");
   std::string s;
   int x;
-  if(istr >> x)
-    {
-    if(x != 10)
-      {
+  if (istr >> x) {
+    if (x != 10) {
       std::cerr << "x != 10" << std::endl;
       return 1;
-      }
     }
-  else
-    {
+  } else {
     std::cerr << "Failed to read 10 from istr" << std::endl;
     return 1;
-    }
-  if(istr >> x)
-    {
-    if(x != 20)
-      {
+  }
+  if (istr >> x) {
+    if (x != 20) {
       std::cerr << "x != 20" << std::endl;
       return 1;
-      }
     }
-  else
-    {
+  } else {
     std::cerr << "Failed to read 20 from istr" << std::endl;
     return 1;
-    }
-  if(istr >> s)
-    {
-    if(s != "str")
-      {
+  }
+  if (istr >> s) {
+    if (s != "str") {
       std::cerr << "s != \"str\"" << std::endl;
       return 1;
-      }
     }
-  else
-    {
+  } else {
     std::cerr << "Failed to read str from istr" << std::endl;
     return 1;
-    }
-  if(istr >> s)
-    {
+  }
+  if (istr >> s) {
     std::cerr << "Able to read past end of stream" << std::endl;
     return 1;
-    }
-  else
-    {
+  } else {
     // Clear the failure.
     istr.clear(istr.rdstate() & ~std::ios::eofbit);
     istr.clear(istr.rdstate() & ~std::ios::failbit);
-    }
+  }
   istr.str("30");
-  if(istr >> x)
-    {
-    if(x != 30)
-      {
+  if (istr >> x) {
+    if (x != 30) {
       std::cerr << "x != 30" << std::endl;
       return 1;
-      }
     }
-  else
-    {
+  } else {
     std::cerr << "Failed to read 30 from istr" << std::endl;
     return 1;
-    }
+  }
 
   std::stringstream sstr;
   sstr << "40 str2";
-  if(sstr >> x)
-    {
-    if(x != 40)
-      {
+  if (sstr >> x) {
+    if (x != 40) {
       std::cerr << "x != 40" << std::endl;
       return 1;
-      }
     }
-  else
-    {
+  } else {
     std::cerr << "Failed to read 40 from sstr" << std::endl;
     return 1;
-    }
-  if(sstr >> s)
-    {
-    if(s != "str2")
-      {
+  }
+  if (sstr >> s) {
+    if (s != "str2") {
       std::cerr << "s != \"str2\"" << std::endl;
       return 1;
-      }
     }
-  else
-    {
+  } else {
     std::cerr << "Failed to read str2 from sstr" << std::endl;
     return 1;
-    }
+  }
 
   // Just try to compile this.
-  if(x == 12345)
-    {
-    std::ifstream fin("/does_not_exist",
-                      std::ios::in | std::ios::binary);
-    }
+  if (x == 12345) {
+    std::ifstream fin("/does_not_exist", std::ios::in | std::ios::binary);
+  }
 
   std::cout << "IOS tests passed" << std::endl;
   return 0;
diff --git a/Source/kwsys/testProcess.c b/Source/kwsys/testProcess.c
index 8fd3382..092dd03 100644
--- a/Source/kwsys/testProcess.c
+++ b/Source/kwsys/testProcess.c
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(Process.h)
 #include KWSYS_HEADER(Encoding.h)
@@ -16,8 +7,8 @@
 /* Work-around CMake dependency scanning limitation.  This must
    duplicate the above list of headers.  */
 #if 0
-# include "Process.h.in"
-# include "Encoding.h.in"
+#include "Encoding.h.in"
+#include "Process.h.in"
 #endif
 
 #include <assert.h>
@@ -27,21 +18,21 @@
 #include <string.h>
 
 #if defined(_WIN32)
-# include <windows.h>
+#include <windows.h>
 #else
-# include <unistd.h>
-# include <signal.h>
+#include <signal.h>
+#include <unistd.h>
 #endif
 
 #if defined(__BORLANDC__)
-# pragma warn -8060 /* possibly incorrect assignment */
+#pragma warn - 8060 /* possibly incorrect assignment */
 #endif
 
 /* Platform-specific sleep functions. */
 
 #if defined(__BEOS__) && !defined(__ZETA__)
 /* BeOS 5 doesn't have usleep(), but it has snooze(), which is identical. */
-# include <be/kernel/OS.h>
+#include <be/kernel/OS.h>
 static inline void testProcess_usleep(unsigned int usec)
 {
   snooze(usec);
@@ -53,13 +44,13 @@ static void testProcess_usleep(unsigned int usec)
   Sleep(usec / 1000);
 }
 #else
-# define testProcess_usleep usleep
+#define testProcess_usleep usleep
 #endif
 
 #if defined(_WIN32)
 static void testProcess_sleep(unsigned int sec)
 {
-  Sleep(sec*1000);
+  Sleep(sec * 1000);
 }
 #else
 static void testProcess_sleep(unsigned int sec)
@@ -68,10 +59,9 @@ static void testProcess_sleep(unsigned int sec)
 }
 #endif
 
-int runChild(const char* cmd[], int state, int exception, int value,
-             int share, int output, int delay, double timeout, int poll,
-             int repeat, int disown, int createNewGroup,
-             unsigned int interruptDelay);
+int runChild(const char* cmd[], int state, int exception, int value, int share,
+             int output, int delay, double timeout, int poll, int repeat,
+             int disown, int createNewGroup, unsigned int interruptDelay);
 
 static int test1(int argc, const char* argv[])
 {
@@ -85,7 +75,8 @@ static int test1(int argc, const char* argv[])
      If you have problems with this test timing out on your system, or want to
      run more than 257 iterations, you can change the number of iterations by
      setting the KWSYS_TEST_PROCESS_1_COUNT environment variable.  */
-  (void)argc; (void)argv;
+  (void)argc;
+  (void)argv;
   fprintf(stdout, "Output on stdout from test returning 0.\n");
   fprintf(stderr, "Output on stderr from test returning 0.\n");
   return 0;
@@ -93,7 +84,8 @@ static int test1(int argc, const char* argv[])
 
 static int test2(int argc, const char* argv[])
 {
-  (void)argc; (void)argv;
+  (void)argc;
+  (void)argv;
   fprintf(stdout, "Output on stdout from test returning 123.\n");
   fprintf(stderr, "Output on stderr from test returning 123.\n");
   return 123;
@@ -101,7 +93,8 @@ static int test2(int argc, const char* argv[])
 
 static int test3(int argc, const char* argv[])
 {
-  (void)argc; (void)argv;
+  (void)argc;
+  (void)argv;
   fprintf(stdout, "Output before sleep on stdout from timeout test.\n");
   fprintf(stderr, "Output before sleep on stderr from timeout test.\n");
   fflush(stdout);
@@ -120,7 +113,7 @@ static int test4(int argc, const char* argv[])
   optimize away the write. We hope to 'outsmart' them by using
   'volatile' and a slightly larger address, based on a runtime value. */
   volatile int* invalidAddress = 0;
-  invalidAddress += argc?1:2;
+  invalidAddress += argc ? 1 : 2;
 
 #if defined(_WIN32)
   /* Avoid error diagnostic popups since we are crashing on purpose.  */
@@ -129,7 +122,8 @@ static int test4(int argc, const char* argv[])
   /* Avoid error diagnostic popups since we are crashing on purpose.  */
   disable_debugger(1);
 #endif
-  (void)argc; (void)argv;
+  (void)argc;
+  (void)argv;
   fprintf(stdout, "Output before crash on stdout from crash test.\n");
   fprintf(stderr, "Output before crash on stderr from crash test.\n");
   fflush(stdout);
@@ -155,8 +149,8 @@ static int test5(int argc, const char* argv[])
   fprintf(stderr, "Output on stderr before recursive test.\n");
   fflush(stdout);
   fflush(stderr);
-  r = runChild(cmd, kwsysProcess_State_Exception,
-               kwsysProcess_Exception_Fault, 1, 1, 1, 0, 15, 0, 1, 0, 0, 0);
+  r = runChild(cmd, kwsysProcess_State_Exception, kwsysProcess_Exception_Fault,
+               1, 1, 1, 0, 15, 0, 1, 0, 0, 0);
   fprintf(stdout, "Output on stdout after recursive test.\n");
   fprintf(stderr, "Output on stderr after recursive test.\n");
   fflush(stdout);
@@ -164,24 +158,23 @@ static int test5(int argc, const char* argv[])
   return r;
 }
 
-#define TEST6_SIZE (4096*2)
+#define TEST6_SIZE (4096 * 2)
 static void test6(int argc, const char* argv[])
 {
   int i;
-  char runaway[TEST6_SIZE+1];
-  (void)argc; (void)argv;
-  for(i=0;i < TEST6_SIZE;++i)
-    {
+  char runaway[TEST6_SIZE + 1];
+  (void)argc;
+  (void)argv;
+  for (i = 0; i < TEST6_SIZE; ++i) {
     runaway[i] = '.';
-    }
+  }
   runaway[TEST6_SIZE] = '\n';
 
   /* Generate huge amounts of output to test killing.  */
-  for(;;)
-    {
-    fwrite(runaway, 1, TEST6_SIZE+1, stdout);
+  for (;;) {
+    fwrite(runaway, 1, TEST6_SIZE + 1, stdout);
     fflush(stdout);
-    }
+  }
 }
 
 /* Define MINPOLL to be one more than the number of times output is
@@ -191,7 +184,8 @@ static void test6(int argc, const char* argv[])
 #define MAXPOLL 20
 static int test7(int argc, const char* argv[])
 {
-  (void)argc; (void)argv;
+  (void)argc;
+  (void)argv;
   fprintf(stdout, "Output on stdout before sleep.\n");
   fprintf(stderr, "Output on stderr before sleep.\n");
   fflush(stdout);
@@ -231,7 +225,8 @@ static int test8(int argc, const char* argv[])
 
 static int test8_grandchild(int argc, const char* argv[])
 {
-  (void)argc; (void)argv;
+  (void)argc;
+  (void)argv;
   fprintf(stdout, "Output on stdout from grandchild before sleep.\n");
   fprintf(stderr, "Output on stderr from grandchild before sleep.\n");
   fflush(stdout);
@@ -266,9 +261,8 @@ static int test9(int argc, const char* argv[])
   fprintf(stderr, "Output on stderr before grandchild test.\n");
   fflush(stdout);
   fflush(stderr);
-  r = runChild(cmd, kwsysProcess_State_Exited,
-               kwsysProcess_Exception_None,
-               0, 1, 1, 0, 30, 0, 1, 0, 0, 0);
+  r = runChild(cmd, kwsysProcess_State_Exited, kwsysProcess_Exception_None, 0,
+               1, 1, 0, 30, 0, 1, 0, 0, 0);
   /* This sleep will avoid a race condition between this function exiting
      normally and our Ctrl+C handler exiting abnormally after the process
      exits.  */
@@ -294,21 +288,20 @@ static BOOL WINAPI test9_grandchild_handler(DWORD dwCtrlType)
 static int test9_grandchild(int argc, const char* argv[])
 {
   /* The grandchild just sleeps for a few seconds while ignoring signals.  */
-  (void)argc; (void)argv;
+  (void)argc;
+  (void)argv;
 #if defined(_WIN32)
-  if(!SetConsoleCtrlHandler(test9_grandchild_handler, TRUE))
-    {
+  if (!SetConsoleCtrlHandler(test9_grandchild_handler, TRUE)) {
     return 1;
-    }
+  }
 #else
   struct sigaction sa;
   memset(&sa, 0, sizeof(sa));
   sa.sa_handler = SIG_IGN;
   sigemptyset(&sa.sa_mask);
-  if(sigaction(SIGINT, &sa, 0) < 0)
-    {
+  if (sigaction(SIGINT, &sa, 0) < 0) {
     return 1;
-    }
+  }
 #endif
   fprintf(stdout, "Output on stdout from grandchild before sleep.\n");
   fprintf(stderr, "Output on stderr from grandchild before sleep.\n");
@@ -341,9 +334,9 @@ static int test10(int argc, const char* argv[])
   fprintf(stderr, "Output on stderr before grandchild test.\n");
   fflush(stdout);
   fflush(stderr);
-  r = runChild(cmd, kwsysProcess_State_Exception,
-               kwsysProcess_Exception_Interrupt,
-               0, 1, 1, 0, 30, 0, 1, 0, 1, 0);
+  r =
+    runChild(cmd, kwsysProcess_State_Exception,
+             kwsysProcess_Exception_Interrupt, 0, 1, 1, 0, 30, 0, 1, 0, 1, 0);
   fprintf(stdout, "Output on stdout after grandchild test.\n");
   fprintf(stderr, "Output on stderr after grandchild test.\n");
   fflush(stdout);
@@ -354,7 +347,8 @@ static int test10(int argc, const char* argv[])
 static int test10_grandchild(int argc, const char* argv[])
 {
   /* The grandchild just sleeps for a few seconds and handles signals.  */
-  (void)argc; (void)argv;
+  (void)argc;
+  (void)argv;
   fprintf(stdout, "Output on stdout from grandchild before sleep.\n");
   fprintf(stderr, "Output on stderr from grandchild before sleep.\n");
   fflush(stdout);
@@ -368,11 +362,10 @@ static int test10_grandchild(int argc, const char* argv[])
   return 0;
 }
 
-static int runChild2(kwsysProcess* kp,
-              const char* cmd[], int state, int exception, int value,
-              int share, int output, int delay, double timeout,
-              int poll, int disown, int createNewGroup,
-              unsigned int interruptDelay)
+static int runChild2(kwsysProcess* kp, const char* cmd[], int state,
+                     int exception, int value, int share, int output,
+                     int delay, double timeout, int poll, int disown,
+                     int createNewGroup, unsigned int interruptDelay)
 {
   int result = 0;
   char* data = 0;
@@ -380,146 +373,128 @@ static int runChild2(kwsysProcess* kp,
   double userTimeout = 0;
   double* pUserTimeout = 0;
   kwsysProcess_SetCommand(kp, cmd);
-  if(timeout >= 0)
-    {
+  if (timeout >= 0) {
     kwsysProcess_SetTimeout(kp, timeout);
-    }
-  if(share)
-    {
+  }
+  if (share) {
     kwsysProcess_SetPipeShared(kp, kwsysProcess_Pipe_STDOUT, 1);
     kwsysProcess_SetPipeShared(kp, kwsysProcess_Pipe_STDERR, 1);
-    }
-  if(disown)
-    {
+  }
+  if (disown) {
     kwsysProcess_SetOption(kp, kwsysProcess_Option_Detach, 1);
-    }
-  if(createNewGroup)
-    {
+  }
+  if (createNewGroup) {
     kwsysProcess_SetOption(kp, kwsysProcess_Option_CreateProcessGroup, 1);
-    }
+  }
   kwsysProcess_Execute(kp);
 
-  if(poll)
-    {
+  if (poll) {
     pUserTimeout = &userTimeout;
-    }
+  }
 
-  if(interruptDelay)
-    {
+  if (interruptDelay) {
     testProcess_sleep(interruptDelay);
     kwsysProcess_Interrupt(kp);
-    }
+  }
 
-  if(!share && !disown)
-    {
+  if (!share && !disown) {
     int p;
-    while((p = kwsysProcess_WaitForData(kp, &data, &length, pUserTimeout)))
-      {
-      if(output)
-        {
-        if(poll && p == kwsysProcess_Pipe_Timeout)
-          {
+    while ((p = kwsysProcess_WaitForData(kp, &data, &length, pUserTimeout))) {
+      if (output) {
+        if (poll && p == kwsysProcess_Pipe_Timeout) {
           fprintf(stdout, "WaitForData timeout reached.\n");
           fflush(stdout);
 
           /* Count the number of times we polled without getting data.
              If it is excessive then kill the child and fail.  */
-          if(++poll >= MAXPOLL)
-            {
-            fprintf(stdout, "Poll count reached limit %d.\n",
-                    MAXPOLL);
+          if (++poll >= MAXPOLL) {
+            fprintf(stdout, "Poll count reached limit %d.\n", MAXPOLL);
             kwsysProcess_Kill(kp);
-            }
           }
-        else
-          {
-          fwrite(data, 1, (size_t) length, stdout);
+        } else {
+          fwrite(data, 1, (size_t)length, stdout);
           fflush(stdout);
-          }
         }
-      if(poll)
-        {
+      }
+      if (poll) {
         /* Delay to avoid busy loop during polling.  */
         testProcess_usleep(100000);
-        }
-      if(delay)
-        {
-        /* Purposely sleeping only on Win32 to let pipe fill up.  */
+      }
+      if (delay) {
+/* Purposely sleeping only on Win32 to let pipe fill up.  */
 #if defined(_WIN32)
         testProcess_usleep(100000);
 #endif
-        }
       }
     }
+  }
 
-  if(disown)
-    {
+  if (disown) {
     kwsysProcess_Disown(kp);
-    }
-  else
-    {
+  } else {
     kwsysProcess_WaitForExit(kp, 0);
-    }
+  }
 
-  switch (kwsysProcess_GetState(kp))
-    {
+  switch (kwsysProcess_GetState(kp)) {
     case kwsysProcess_State_Starting:
-      printf("No process has been executed.\n"); break;
+      printf("No process has been executed.\n");
+      break;
     case kwsysProcess_State_Executing:
-      printf("The process is still executing.\n"); break;
+      printf("The process is still executing.\n");
+      break;
     case kwsysProcess_State_Expired:
-      printf("Child was killed when timeout expired.\n"); break;
+      printf("Child was killed when timeout expired.\n");
+      break;
     case kwsysProcess_State_Exited:
-      printf("Child exited with value = %d\n",
-             kwsysProcess_GetExitValue(kp));
+      printf("Child exited with value = %d\n", kwsysProcess_GetExitValue(kp));
       result = ((exception != kwsysProcess_GetExitException(kp)) ||
-                (value != kwsysProcess_GetExitValue(kp))); break;
+                (value != kwsysProcess_GetExitValue(kp)));
+      break;
     case kwsysProcess_State_Killed:
-      printf("Child was killed by parent.\n"); break;
+      printf("Child was killed by parent.\n");
+      break;
     case kwsysProcess_State_Exception:
       printf("Child terminated abnormally: %s\n",
              kwsysProcess_GetExceptionString(kp));
       result = ((exception != kwsysProcess_GetExitException(kp)) ||
-                (value != kwsysProcess_GetExitValue(kp))); break;
+                (value != kwsysProcess_GetExitValue(kp)));
+      break;
     case kwsysProcess_State_Disowned:
-      printf("Child was disowned.\n"); break;
+      printf("Child was disowned.\n");
+      break;
     case kwsysProcess_State_Error:
       printf("Error in administrating child process: [%s]\n",
-             kwsysProcess_GetErrorString(kp)); break;
-    };
+             kwsysProcess_GetErrorString(kp));
+      break;
+  };
 
-  if(result)
-    {
-    if(exception != kwsysProcess_GetExitException(kp))
-      {
+  if (result) {
+    if (exception != kwsysProcess_GetExitException(kp)) {
       fprintf(stderr, "Mismatch in exit exception.  "
-              "Should have been %d, was %d.\n",
+                      "Should have been %d, was %d.\n",
               exception, kwsysProcess_GetExitException(kp));
-      }
-    if(value != kwsysProcess_GetExitValue(kp))
-      {
+    }
+    if (value != kwsysProcess_GetExitValue(kp)) {
       fprintf(stderr, "Mismatch in exit value.  "
-              "Should have been %d, was %d.\n",
+                      "Should have been %d, was %d.\n",
               value, kwsysProcess_GetExitValue(kp));
-      }
     }
+  }
 
-  if(kwsysProcess_GetState(kp) != state)
-    {
+  if (kwsysProcess_GetState(kp) != state) {
     fprintf(stderr, "Mismatch in state.  "
-            "Should have been %d, was %d.\n",
+                    "Should have been %d, was %d.\n",
             state, kwsysProcess_GetState(kp));
     result = 1;
-    }
+  }
 
   /* We should have polled more times than there were data if polling
      was enabled.  */
-  if(poll && poll < MINPOLL)
-    {
-    fprintf(stderr, "Poll count is %d, which is less than %d.\n",
-            poll, MINPOLL);
+  if (poll && poll < MINPOLL) {
+    fprintf(stderr, "Poll count is %d, which is less than %d.\n", poll,
+            MINPOLL);
     result = 1;
-    }
+  }
 
   return result;
 }
@@ -551,28 +526,23 @@ static int runChild2(kwsysProcess* kp,
  *                  BEFORE any reading/polling of pipes occurs and before any
  *                  detachment occurs.
  */
-int runChild(const char* cmd[], int state, int exception, int value,
-             int share, int output, int delay, double timeout,
-             int poll, int repeat, int disown, int createNewGroup,
-             unsigned int interruptDelay)
+int runChild(const char* cmd[], int state, int exception, int value, int share,
+             int output, int delay, double timeout, int poll, int repeat,
+             int disown, int createNewGroup, unsigned int interruptDelay)
 {
   int result = 1;
   kwsysProcess* kp = kwsysProcess_New();
-  if(!kp)
-    {
+  if (!kp) {
     fprintf(stderr, "kwsysProcess_New returned NULL!\n");
     return 1;
-    }
-  while(repeat-- > 0)
-    {
-    result = runChild2(kp, cmd, state, exception, value, share,
-                       output, delay, timeout, poll, disown, createNewGroup,
-                       interruptDelay);
-    if(result)
-      {
+  }
+  while (repeat-- > 0) {
+    result = runChild2(kp, cmd, state, exception, value, share, output, delay,
+                       timeout, poll, disown, createNewGroup, interruptDelay);
+    if (result) {
       break;
-      }
     }
+  }
   kwsysProcess_Delete(kp);
   return result;
 }
@@ -585,8 +555,7 @@ int main(int argc, const char* argv[])
   int i;
   char new_args[10][_MAX_PATH];
   LPWSTR* w_av = CommandLineToArgvW(GetCommandLineW(), &argc);
-  for(i=0; i<argc; i++)
-  {
+  for (i = 0; i < argc; i++) {
     kwsysEncoding_wcstombs(new_args[i], w_av[i], _MAX_PATH);
     argv[i] = new_args[i];
   }
@@ -609,107 +578,96 @@ int main(int argc, const char* argv[])
     SetStdHandle(STD_ERROR_HANDLE, out);
     }
 #endif
-  if(argc == 2)
-    {
+  if (argc == 2) {
     n = atoi(argv[1]);
-    }
-  else if(argc == 3 && strcmp(argv[1], "run") == 0)
-    {
+  } else if (argc == 3 && strcmp(argv[1], "run") == 0) {
     n = atoi(argv[2]);
-    }
+  }
   /* Check arguments.  */
-  if(((n >= 1 && n <= 10) || n == 108 || n == 109 || n == 110) && argc == 3)
-    {
+  if (((n >= 1 && n <= 10) || n == 108 || n == 109 || n == 110) && argc == 3) {
     /* This is the child process for a requested test number.  */
-    switch (n)
-      {
-      case 1: return test1(argc, argv);
-      case 2: return test2(argc, argv);
-      case 3: return test3(argc, argv);
-      case 4: return test4(argc, argv);
-      case 5: return test5(argc, argv);
-      case 6: test6(argc, argv); return 0;
-      case 7: return test7(argc, argv);
-      case 8: return test8(argc, argv);
-      case 9: return test9(argc, argv);
-      case 10: return test10(argc, argv);
-      case 108: return test8_grandchild(argc, argv);
-      case 109: return test9_grandchild(argc, argv);
-      case 110: return test10_grandchild(argc, argv);
-      }
+    switch (n) {
+      case 1:
+        return test1(argc, argv);
+      case 2:
+        return test2(argc, argv);
+      case 3:
+        return test3(argc, argv);
+      case 4:
+        return test4(argc, argv);
+      case 5:
+        return test5(argc, argv);
+      case 6:
+        test6(argc, argv);
+        return 0;
+      case 7:
+        return test7(argc, argv);
+      case 8:
+        return test8(argc, argv);
+      case 9:
+        return test9(argc, argv);
+      case 10:
+        return test10(argc, argv);
+      case 108:
+        return test8_grandchild(argc, argv);
+      case 109:
+        return test9_grandchild(argc, argv);
+      case 110:
+        return test10_grandchild(argc, argv);
+    }
     fprintf(stderr, "Invalid test number %d.\n", n);
     return 1;
-    }
-  else if(n >= 1 && n <= 10)
-    {
+  } else if (n >= 1 && n <= 10) {
     /* This is the parent process for a requested test number.  */
-    int states[10] =
-    {
-      kwsysProcess_State_Exited,
-      kwsysProcess_State_Exited,
-      kwsysProcess_State_Expired,
-      kwsysProcess_State_Exception,
-      kwsysProcess_State_Exited,
-      kwsysProcess_State_Expired,
-      kwsysProcess_State_Exited,
-      kwsysProcess_State_Exited,
-      kwsysProcess_State_Expired, /* Ctrl+C handler test */
+    int states[10] = {
+      kwsysProcess_State_Exited,   kwsysProcess_State_Exited,
+      kwsysProcess_State_Expired,  kwsysProcess_State_Exception,
+      kwsysProcess_State_Exited,   kwsysProcess_State_Expired,
+      kwsysProcess_State_Exited,   kwsysProcess_State_Exited,
+      kwsysProcess_State_Expired,  /* Ctrl+C handler test */
       kwsysProcess_State_Exception /* Process group test */
     };
-    int exceptions[10] =
-    {
-      kwsysProcess_Exception_None,
-      kwsysProcess_Exception_None,
-      kwsysProcess_Exception_None,
-      kwsysProcess_Exception_Fault,
-      kwsysProcess_Exception_None,
-      kwsysProcess_Exception_None,
-      kwsysProcess_Exception_None,
-      kwsysProcess_Exception_None,
-      kwsysProcess_Exception_None,
-      kwsysProcess_Exception_Interrupt
+    int exceptions[10] = {
+      kwsysProcess_Exception_None, kwsysProcess_Exception_None,
+      kwsysProcess_Exception_None, kwsysProcess_Exception_Fault,
+      kwsysProcess_Exception_None, kwsysProcess_Exception_None,
+      kwsysProcess_Exception_None, kwsysProcess_Exception_None,
+      kwsysProcess_Exception_None, kwsysProcess_Exception_Interrupt
     };
-    int values[10] = {0, 123, 1, 1, 0, 0, 0, 0, 1, 1};
-    int shares[10] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1};
-    int outputs[10] = {1, 1, 1, 1, 1, 0, 1, 1, 1, 1};
-    int delays[10] = {0, 0, 0, 0, 0, 1, 0, 0, 0, 0};
-    double timeouts[10] = {10, 10, 10, 30, 30, 10, -1, 10, 6, 4};
-    int polls[10] = {0, 0, 0, 0, 0, 0, 1, 0, 0, 0};
-    int repeat[10] = {257, 1, 1, 1, 1, 1, 1, 1, 1, 1};
-    int createNewGroups[10] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1};
-    unsigned int interruptDelays[10] = {0, 0, 0, 0, 0, 0, 0, 0, 3, 2};
+    int values[10] = { 0, 123, 1, 1, 0, 0, 0, 0, 1, 1 };
+    int shares[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 };
+    int outputs[10] = { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 };
+    int delays[10] = { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 };
+    double timeouts[10] = { 10, 10, 10, 30, 30, 10, -1, 10, 6, 4 };
+    int polls[10] = { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 };
+    int repeat[10] = { 257, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
+    int createNewGroups[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 };
+    unsigned int interruptDelays[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 3, 2 };
     int r;
     const char* cmd[4];
 #ifdef _WIN32
     char* argv0 = 0;
 #endif
     char* test1IterationsStr = getenv("KWSYS_TEST_PROCESS_1_COUNT");
-    if(test1IterationsStr)
-      {
+    if (test1IterationsStr) {
       long int test1Iterations = strtol(test1IterationsStr, 0, 10);
-      if(test1Iterations > 10 && test1Iterations != LONG_MAX)
-        {
+      if (test1Iterations > 10 && test1Iterations != LONG_MAX) {
         repeat[0] = (int)test1Iterations;
-        }
       }
+    }
 #ifdef _WIN32
-    if(n == 0 && (argv0 = strdup(argv[0])))
-      {
+    if (n == 0 && (argv0 = strdup(argv[0]))) {
       /* Try converting to forward slashes to see if it works.  */
       char* c;
-      for(c=argv0; *c; ++c)
-        {
-        if(*c == '\\')
-          {
+      for (c = argv0; *c; ++c) {
+        if (*c == '\\') {
           *c = '/';
-          }
         }
-      cmd[0] = argv0;
       }
-    else
-      {
+      cmd[0] = argv0;
+    } else {
       cmd[0] = argv[0];
-      }
+    }
 #else
     cmd[0] = argv[0];
 #endif
@@ -720,36 +678,34 @@ int main(int argc, const char* argv[])
     fprintf(stderr, "Output on stderr before test %d.\n", n);
     fflush(stdout);
     fflush(stderr);
-    r = runChild(cmd, states[n-1], exceptions[n-1], values[n-1], shares[n-1],
-                 outputs[n-1], delays[n-1], timeouts[n-1],
-                 polls[n-1], repeat[n-1], 0, createNewGroups[n-1],
-                 interruptDelays[n-1]);
+    r = runChild(cmd, states[n - 1], exceptions[n - 1], values[n - 1],
+                 shares[n - 1], outputs[n - 1], delays[n - 1], timeouts[n - 1],
+                 polls[n - 1], repeat[n - 1], 0, createNewGroups[n - 1],
+                 interruptDelays[n - 1]);
     fprintf(stdout, "Output on stdout after test %d.\n", n);
     fprintf(stderr, "Output on stderr after test %d.\n", n);
     fflush(stdout);
     fflush(stderr);
 #if defined(_WIN32)
-    if(argv0) { free(argv0); }
+    if (argv0) {
+      free(argv0);
+    }
 #endif
     return r;
-    }
-  else if(argc > 2 && strcmp(argv[1], "0") == 0)
-    {
+  } else if (argc > 2 && strcmp(argv[1], "0") == 0) {
     /* This is the special debugging test to run a given command
        line.  */
-    const char** cmd = argv+2;
+    const char** cmd = argv + 2;
     int state = kwsysProcess_State_Exited;
     int exception = kwsysProcess_Exception_None;
     int value = 0;
     double timeout = 0;
-    int r = runChild(cmd, state, exception, value, 0, 1, 0, timeout,
-      0, 1, 0, 0, 0);
+    int r =
+      runChild(cmd, state, exception, value, 0, 1, 0, timeout, 0, 1, 0, 0, 0);
     return r;
-    }
-  else
-    {
+  } else {
     /* Improper usage.  */
     fprintf(stdout, "Usage: %s <test number>\n", argv[0]);
     return 1;
-    }
+  }
 }
diff --git a/Source/kwsys/testSharedForward.c.in b/Source/kwsys/testSharedForward.c.in
index ee753ef..9a0c0c0 100644
--- a/Source/kwsys/testSharedForward.c.in
+++ b/Source/kwsys/testSharedForward.c.in
@@ -1,33 +1,24 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #if defined(CMAKE_INTDIR)
-# define CONFIG_DIR_PRE CMAKE_INTDIR "/"
-# define CONFIG_DIR_POST "/" CMAKE_INTDIR
+#define CONFIG_DIR_PRE CMAKE_INTDIR "/"
+#define CONFIG_DIR_POST "/" CMAKE_INTDIR
 #else
-# define CONFIG_DIR_PRE ""
-# define CONFIG_DIR_POST ""
+#define CONFIG_DIR_PRE ""
+#define CONFIG_DIR_POST ""
 #endif
 #define @KWSYS_NAMESPACE at _SHARED_FORWARD_DIR_BUILD "@EXEC_DIR@"
 #define @KWSYS_NAMESPACE at _SHARED_FORWARD_PATH_BUILD "." CONFIG_DIR_POST
 #define @KWSYS_NAMESPACE at _SHARED_FORWARD_PATH_INSTALL 0
-#define @KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_BUILD \
+#define @KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_BUILD                            \
   CONFIG_DIR_PRE "@KWSYS_NAMESPACE at TestProcess"
-#define @KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_INSTALL \
+#define @KWSYS_NAMESPACE at _SHARED_FORWARD_EXE_INSTALL                          \
   "@KWSYS_NAMESPACE at TestProcess"
 #define @KWSYS_NAMESPACE at _SHARED_FORWARD_OPTION_COMMAND "--command"
 #define @KWSYS_NAMESPACE at _SHARED_FORWARD_OPTION_PRINT "--print"
 #define @KWSYS_NAMESPACE at _SHARED_FORWARD_OPTION_LDD "--ldd"
 #if defined(CMAKE_INTDIR)
-# define @KWSYS_NAMESPACE at _SHARED_FORWARD_CONFIG_NAME CMAKE_INTDIR
+#define @KWSYS_NAMESPACE at _SHARED_FORWARD_CONFIG_NAME CMAKE_INTDIR
 #endif
 #include <@KWSYS_NAMESPACE@/SharedForward.h>
 int main(int argc, char** argv)
diff --git a/Source/kwsys/testSystemInformation.cxx b/Source/kwsys/testSystemInformation.cxx
index c96751a..86a1e1e 100644
--- a/Source/kwsys/testSystemInformation.cxx
+++ b/Source/kwsys/testSystemInformation.cxx
@@ -1,51 +1,41 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(SystemInformation.hxx)
 
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "SystemInformation.hxx.in"
+#include "SystemInformation.hxx.in"
 #endif
 
 #include <iostream>
 
 #if defined(KWSYS_USE_LONG_LONG)
-# if defined(KWSYS_IOS_HAS_OSTREAM_LONG_LONG)
-#  define iostreamLongLong(x) (x)
-# else
-#  define iostreamLongLong(x) ((long)x)
-# endif
+#if defined(KWSYS_IOS_HAS_OSTREAM_LONG_LONG)
+#define iostreamLongLong(x) (x)
+#else
+#define iostreamLongLong(x) ((long)x)
+#endif
 #elif defined(KWSYS_USE___INT64)
-# if defined(KWSYS_IOS_HAS_OSTREAM___INT64)
-#  define iostreamLongLong(x) (x)
-# else
-#  define iostreamLongLong(x) ((long)x)
-# endif
+#if defined(KWSYS_IOS_HAS_OSTREAM___INT64)
+#define iostreamLongLong(x) (x)
+#else
+#define iostreamLongLong(x) ((long)x)
+#endif
 #else
-# error "No Long Long"
+#error "No Long Long"
 #endif
 
-#define printMethod(info, m) std::cout << #m << ": " \
-<< info.m() << "\n"
+#define printMethod(info, m) std::cout << #m << ": " << info.m() << "\n"
 
-#define printMethod2(info, m, unit) std::cout << #m << ": " \
-<< info.m() << " " << unit << "\n"
+#define printMethod2(info, m, unit)                                           \
+  std::cout << #m << ": " << info.m() << " " << unit << "\n"
 
-#define printMethod3(info, m, unit) std::cout << #m << ": " \
-<< iostreamLongLong(info.m) << " " << unit << "\n"
+#define printMethod3(info, m, unit)                                           \
+  std::cout << #m << ": " << iostreamLongLong(info.m) << " " << unit << "\n"
 
-int testSystemInformation(int, char*[])
+int testSystemInformation(int, char* [])
 {
   std::cout << "CTEST_FULL_OUTPUT\n"; // avoid truncation
 
@@ -84,25 +74,22 @@ int testSystemInformation(int, char*[])
   printMethod2(info, GetAvailablePhysicalMemory, "MB");
   printMethod3(info, GetHostMemoryTotal(), "KiB");
   printMethod3(info, GetHostMemoryAvailable("KWSHL"), "KiB");
-  printMethod3(info, GetProcMemoryAvailable("KWSHL","KWSPL"), "KiB");
+  printMethod3(info, GetProcMemoryAvailable("KWSHL", "KWSPL"), "KiB");
   printMethod3(info, GetHostMemoryUsed(), "KiB");
   printMethod3(info, GetProcMemoryUsed(), "KiB");
   printMethod(info, GetLoadAverage);
 
-  for (long int i = 0; i <= 31; i++)
-    {
-    if (info.DoesCPUSupportFeature(static_cast<long int>(1) << i))
-      {
+  for (long int i = 0; i <= 31; i++) {
+    if (info.DoesCPUSupportFeature(static_cast<long int>(1) << i)) {
       std::cout << "CPU feature " << i << "\n";
-      }
     }
+  }
 
   /* test stack trace
   */
-  std::cout
-    << "Program Stack:" << std::endl
-    << kwsys::SystemInformation::GetProgramStack(0,0) << std::endl
-    << std::endl;
+  std::cout << "Program Stack:" << std::endl
+            << kwsys::SystemInformation::GetProgramStack(0, 0) << std::endl
+            << std::endl;
 
   /* test segv handler
   info.SetStackTraceOnError(1);
diff --git a/Source/kwsys/testSystemTools.cxx b/Source/kwsys/testSystemTools.cxx
index 880b46e..8e1ea25 100644
--- a/Source/kwsys/testSystemTools.cxx
+++ b/Source/kwsys/testSystemTools.cxx
@@ -1,26 +1,19 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 
 #if defined(_MSC_VER)
-# pragma warning (disable:4786)
+#pragma warning(disable : 4786)
 #endif
 
+#include KWSYS_HEADER(FStream.hxx)
 #include KWSYS_HEADER(SystemTools.hxx)
 
 // Work-around CMake dependency scanning limitation.  This must
 // duplicate the above list of headers.
 #if 0
-# include "SystemTools.hxx.in"
+#include "FStream.hxx.in"
+#include "SystemTools.hxx.in"
 #endif
 
 // Include with <> instead of "" to avoid getting any in-source copy
@@ -31,77 +24,65 @@
 #include <sstream>
 #include <string.h> /* strcmp */
 #if defined(_WIN32) && !defined(__CYGWIN__)
-# include <io.h> /* _umask (MSVC) / umask (Borland) */
-# ifdef _MSC_VER
-#  define umask _umask // Note this is still umask on Borland
-# endif
+#include <io.h> /* _umask (MSVC) / umask (Borland) */
+#ifdef _MSC_VER
+#define umask _umask // Note this is still umask on Borland
+#endif
 #endif
 #include <sys/stat.h> /* umask (POSIX), _S_I* constants (Windows) */
 // Visual C++ does not define mode_t (note that Borland does, however).
-#if defined( _MSC_VER )
+#if defined(_MSC_VER)
 typedef unsigned short mode_t;
 #endif
 
 //----------------------------------------------------------------------------
-static const char* toUnixPaths[][2] =
-{
-    { "/usr/local/bin/passwd", "/usr/local/bin/passwd" },
-    { "/usr/lo cal/bin/pa sswd", "/usr/lo cal/bin/pa sswd" },
-    { "/usr/lo\\ cal/bin/pa\\ sswd", "/usr/lo\\ cal/bin/pa\\ sswd" },
-    { "c:/usr/local/bin/passwd", "c:/usr/local/bin/passwd" },
-    { "c:/usr/lo cal/bin/pa sswd", "c:/usr/lo cal/bin/pa sswd" },
-    { "c:/usr/lo\\ cal/bin/pa\\ sswd", "c:/usr/lo\\ cal/bin/pa\\ sswd" },
-    { "\\usr\\local\\bin\\passwd", "/usr/local/bin/passwd" },
-    { "\\usr\\lo cal\\bin\\pa sswd", "/usr/lo cal/bin/pa sswd" },
-    { "\\usr\\lo\\ cal\\bin\\pa\\ sswd", "/usr/lo\\ cal/bin/pa\\ sswd" },
-    { "c:\\usr\\local\\bin\\passwd", "c:/usr/local/bin/passwd" },
-    { "c:\\usr\\lo cal\\bin\\pa sswd", "c:/usr/lo cal/bin/pa sswd" },
-    { "c:\\usr\\lo\\ cal\\bin\\pa\\ sswd", "c:/usr/lo\\ cal/bin/pa\\ sswd" },
-    { "\\\\usr\\local\\bin\\passwd", "//usr/local/bin/passwd" },
-    { "\\\\usr\\lo cal\\bin\\pa sswd", "//usr/lo cal/bin/pa sswd" },
-    { "\\\\usr\\lo\\ cal\\bin\\pa\\ sswd", "//usr/lo\\ cal/bin/pa\\ sswd" },
-    {0, 0}
+static const char* toUnixPaths[][2] = {
+  { "/usr/local/bin/passwd", "/usr/local/bin/passwd" },
+  { "/usr/lo cal/bin/pa sswd", "/usr/lo cal/bin/pa sswd" },
+  { "/usr/lo\\ cal/bin/pa\\ sswd", "/usr/lo\\ cal/bin/pa\\ sswd" },
+  { "c:/usr/local/bin/passwd", "c:/usr/local/bin/passwd" },
+  { "c:/usr/lo cal/bin/pa sswd", "c:/usr/lo cal/bin/pa sswd" },
+  { "c:/usr/lo\\ cal/bin/pa\\ sswd", "c:/usr/lo\\ cal/bin/pa\\ sswd" },
+  { "\\usr\\local\\bin\\passwd", "/usr/local/bin/passwd" },
+  { "\\usr\\lo cal\\bin\\pa sswd", "/usr/lo cal/bin/pa sswd" },
+  { "\\usr\\lo\\ cal\\bin\\pa\\ sswd", "/usr/lo\\ cal/bin/pa\\ sswd" },
+  { "c:\\usr\\local\\bin\\passwd", "c:/usr/local/bin/passwd" },
+  { "c:\\usr\\lo cal\\bin\\pa sswd", "c:/usr/lo cal/bin/pa sswd" },
+  { "c:\\usr\\lo\\ cal\\bin\\pa\\ sswd", "c:/usr/lo\\ cal/bin/pa\\ sswd" },
+  { "\\\\usr\\local\\bin\\passwd", "//usr/local/bin/passwd" },
+  { "\\\\usr\\lo cal\\bin\\pa sswd", "//usr/lo cal/bin/pa sswd" },
+  { "\\\\usr\\lo\\ cal\\bin\\pa\\ sswd", "//usr/lo\\ cal/bin/pa\\ sswd" },
+  { 0, 0 }
 };
 
-static bool CheckConvertToUnixSlashes(std::string input,
-                                      std::string output)
+static bool CheckConvertToUnixSlashes(std::string input, std::string output)
 {
   std::string result = input;
   kwsys::SystemTools::ConvertToUnixSlashes(result);
-  if ( result != output )
-    {
-    std::cerr
-      << "Problem with ConvertToUnixSlashes - input: " << input
-      << " output: " << result << " expected: " << output
-      << std::endl;
+  if (result != output) {
+    std::cerr << "Problem with ConvertToUnixSlashes - input: " << input
+              << " output: " << result << " expected: " << output << std::endl;
     return false;
-    }
+  }
   return true;
 }
 
 //----------------------------------------------------------------------------
-static const char* checkEscapeChars[][4] =
-{
-  { "1 foo 2 bar 2", "12", "\\", "\\1 foo \\2 bar \\2"},
-  { " {} ", "{}", "#", " #{#} "},
-  {0, 0, 0, 0}
-};
+static const char* checkEscapeChars[][4] = { { "1 foo 2 bar 2", "12", "\\",
+                                               "\\1 foo \\2 bar \\2" },
+                                             { " {} ", "{}", "#", " #{#} " },
+                                             { 0, 0, 0, 0 } };
 
-static bool CheckEscapeChars(std::string input,
-                             const char *chars_to_escape,
-                             char escape_char,
-                             std::string output)
+static bool CheckEscapeChars(std::string input, const char* chars_to_escape,
+                             char escape_char, std::string output)
 {
   std::string result = kwsys::SystemTools::EscapeChars(
     input.c_str(), chars_to_escape, escape_char);
-  if (result != output)
-    {
-    std::cerr
-      << "Problem with CheckEscapeChars - input: " << input
-      << " output: " << result << " expected: " << output
-      << std::endl;
+  if (result != output) {
+    std::cerr << "Problem with CheckEscapeChars - input: " << input
+              << " output: " << result << " expected: " << output << std::endl;
     return false;
-    }
+  }
   return true;
 }
 
@@ -110,268 +91,192 @@ static bool CheckFileOperations()
 {
   bool res = true;
   const std::string testNonExistingFile(TEST_SYSTEMTOOLS_SOURCE_DIR
-    "/testSystemToolsNonExistingFile");
-  const std::string testDotFile(TEST_SYSTEMTOOLS_SOURCE_DIR
-    "/.");
+                                        "/testSystemToolsNonExistingFile");
+  const std::string testDotFile(TEST_SYSTEMTOOLS_SOURCE_DIR "/.");
   const std::string testBinFile(TEST_SYSTEMTOOLS_SOURCE_DIR
-    "/testSystemTools.bin");
+                                "/testSystemTools.bin");
   const std::string testTxtFile(TEST_SYSTEMTOOLS_SOURCE_DIR
-    "/testSystemTools.cxx");
+                                "/testSystemTools.cxx");
   const std::string testNewDir(TEST_SYSTEMTOOLS_BINARY_DIR
-    "/testSystemToolsNewDir");
+                               "/testSystemToolsNewDir");
   const std::string testNewFile(testNewDir + "/testNewFile.txt");
 
   if (kwsys::SystemTools::DetectFileType(testNonExistingFile.c_str()) !=
-      kwsys::SystemTools::FileTypeUnknown)
-    {
-    std::cerr
-      << "Problem with DetectFileType - failed to detect type of: "
-      << testNonExistingFile << std::endl;
+      kwsys::SystemTools::FileTypeUnknown) {
+    std::cerr << "Problem with DetectFileType - failed to detect type of: "
+              << testNonExistingFile << std::endl;
     res = false;
-    }
+  }
 
   if (kwsys::SystemTools::DetectFileType(testDotFile.c_str()) !=
-      kwsys::SystemTools::FileTypeUnknown)
-    {
-    std::cerr
-      << "Problem with DetectFileType - failed to detect type of: "
-      << testDotFile << std::endl;
+      kwsys::SystemTools::FileTypeUnknown) {
+    std::cerr << "Problem with DetectFileType - failed to detect type of: "
+              << testDotFile << std::endl;
     res = false;
-    }
+  }
 
   if (kwsys::SystemTools::DetectFileType(testBinFile.c_str()) !=
-      kwsys::SystemTools::FileTypeBinary)
-    {
-    std::cerr
-      << "Problem with DetectFileType - failed to detect type of: "
-      << testBinFile << std::endl;
+      kwsys::SystemTools::FileTypeBinary) {
+    std::cerr << "Problem with DetectFileType - failed to detect type of: "
+              << testBinFile << std::endl;
     res = false;
-    }
+  }
 
   if (kwsys::SystemTools::DetectFileType(testTxtFile.c_str()) !=
-      kwsys::SystemTools::FileTypeText)
-    {
-    std::cerr
-      << "Problem with DetectFileType - failed to detect type of: "
-      << testTxtFile << std::endl;
+      kwsys::SystemTools::FileTypeText) {
+    std::cerr << "Problem with DetectFileType - failed to detect type of: "
+              << testTxtFile << std::endl;
     res = false;
-    }
+  }
 
-  if (kwsys::SystemTools::FileLength(testBinFile) != 766)
-    {
-    std::cerr
-      << "Problem with FileLength - incorrect length for: "
-      << testBinFile << std::endl;
+  if (kwsys::SystemTools::FileLength(testBinFile) != 766) {
+    std::cerr << "Problem with FileLength - incorrect length for: "
+              << testBinFile << std::endl;
     res = false;
-    }
+  }
 
-  if (!kwsys::SystemTools::MakeDirectory(testNewDir))
-    {
-    std::cerr
-      << "Problem with MakeDirectory for: "
-      << testNewDir << std::endl;
+  if (!kwsys::SystemTools::MakeDirectory(testNewDir)) {
+    std::cerr << "Problem with MakeDirectory for: " << testNewDir << std::endl;
     res = false;
-    }
+  }
   // calling it again should just return true
-  if (!kwsys::SystemTools::MakeDirectory(testNewDir))
-    {
-    std::cerr
-      << "Problem with second call to MakeDirectory for: "
-      << testNewDir << std::endl;
+  if (!kwsys::SystemTools::MakeDirectory(testNewDir)) {
+    std::cerr << "Problem with second call to MakeDirectory for: "
+              << testNewDir << std::endl;
     res = false;
-    }
+  }
   // calling with 0 pointer should return false
-  if (kwsys::SystemTools::MakeDirectory(0))
-    {
-    std::cerr
-      << "Problem with MakeDirectory(0)"
-      << std::endl;
+  if (kwsys::SystemTools::MakeDirectory(0)) {
+    std::cerr << "Problem with MakeDirectory(0)" << std::endl;
     res = false;
-    }
+  }
   // calling with an empty string should return false
-  if (kwsys::SystemTools::MakeDirectory(std::string()))
-    {
-    std::cerr
-      << "Problem with MakeDirectory(std::string())"
-      << std::endl;
+  if (kwsys::SystemTools::MakeDirectory(std::string())) {
+    std::cerr << "Problem with MakeDirectory(std::string())" << std::endl;
     res = false;
-    }
+  }
   // check existence
-  if (!kwsys::SystemTools::FileExists(testNewDir.c_str(), false))
-    {
-    std::cerr
-      << "Problem with FileExists as C string and not file for: "
-      << testNewDir << std::endl;
+  if (!kwsys::SystemTools::FileExists(testNewDir.c_str(), false)) {
+    std::cerr << "Problem with FileExists as C string and not file for: "
+              << testNewDir << std::endl;
     res = false;
-    }
+  }
   // check existence
-  if (!kwsys::SystemTools::PathExists(testNewDir))
-    {
-    std::cerr
-      << "Problem with PathExists for: "
-      << testNewDir << std::endl;
+  if (!kwsys::SystemTools::PathExists(testNewDir)) {
+    std::cerr << "Problem with PathExists for: " << testNewDir << std::endl;
     res = false;
-    }
+  }
   // remove it
-  if (!kwsys::SystemTools::RemoveADirectory(testNewDir))
-    {
-    std::cerr
-      << "Problem with RemoveADirectory for: "
-      << testNewDir << std::endl;
+  if (!kwsys::SystemTools::RemoveADirectory(testNewDir)) {
+    std::cerr << "Problem with RemoveADirectory for: " << testNewDir
+              << std::endl;
     res = false;
-    }
+  }
   // check existence
-  if (kwsys::SystemTools::FileExists(testNewDir.c_str(), false))
-    {
-    std::cerr
-      << "After RemoveADirectory: "
-      << "Problem with FileExists as C string and not file for: "
-      << testNewDir << std::endl;
+  if (kwsys::SystemTools::FileExists(testNewDir.c_str(), false)) {
+    std::cerr << "After RemoveADirectory: "
+              << "Problem with FileExists as C string and not file for: "
+              << testNewDir << std::endl;
     res = false;
-    }
+  }
   // check existence
-  if (kwsys::SystemTools::PathExists(testNewDir))
-    {
-    std::cerr
-      << "After RemoveADirectory: "
-      << "Problem with PathExists for: "
-      << testNewDir << std::endl;
+  if (kwsys::SystemTools::PathExists(testNewDir)) {
+    std::cerr << "After RemoveADirectory: "
+              << "Problem with PathExists for: " << testNewDir << std::endl;
     res = false;
-    }
+  }
   // create it using the char* version
-  if (!kwsys::SystemTools::MakeDirectory(testNewDir.c_str()))
-    {
-    std::cerr
-      << "Problem with second call to MakeDirectory as C string for: "
-      << testNewDir << std::endl;
+  if (!kwsys::SystemTools::MakeDirectory(testNewDir.c_str())) {
+    std::cerr << "Problem with second call to MakeDirectory as C string for: "
+              << testNewDir << std::endl;
     res = false;
-    }
+  }
 
-  if (!kwsys::SystemTools::Touch(testNewFile.c_str(), true))
-    {
-    std::cerr
-      << "Problem with Touch for: "
-      << testNewFile << std::endl;
+  if (!kwsys::SystemTools::Touch(testNewFile.c_str(), true)) {
+    std::cerr << "Problem with Touch for: " << testNewFile << std::endl;
     res = false;
-    }
+  }
   // calling MakeDirectory with something that is no file should fail
-  if (kwsys::SystemTools::MakeDirectory(testNewFile))
-    {
-    std::cerr
-      << "Problem with to MakeDirectory for: "
-      << testNewFile << std::endl;
+  if (kwsys::SystemTools::MakeDirectory(testNewFile)) {
+    std::cerr << "Problem with to MakeDirectory for: " << testNewFile
+              << std::endl;
     res = false;
-    }
+  }
 
   // calling with 0 pointer should return false
-  if (kwsys::SystemTools::FileExists(0))
-    {
-    std::cerr
-      << "Problem with FileExists(0)"
-      << std::endl;
+  if (kwsys::SystemTools::FileExists(0)) {
+    std::cerr << "Problem with FileExists(0)" << std::endl;
     res = false;
-    }
-  if (kwsys::SystemTools::FileExists(0, true))
-    {
-    std::cerr
-      << "Problem with FileExists(0) as file"
-      << std::endl;
+  }
+  if (kwsys::SystemTools::FileExists(0, true)) {
+    std::cerr << "Problem with FileExists(0) as file" << std::endl;
     res = false;
-    }
+  }
   // calling with an empty string should return false
-  if (kwsys::SystemTools::FileExists(std::string()))
-    {
-    std::cerr
-      << "Problem with FileExists(std::string())"
-      << std::endl;
+  if (kwsys::SystemTools::FileExists(std::string())) {
+    std::cerr << "Problem with FileExists(std::string())" << std::endl;
     res = false;
-    }
+  }
   // FileExists(x, true) should return false on a directory
-  if (kwsys::SystemTools::FileExists(testNewDir, true))
-    {
-    std::cerr
-      << "Problem with FileExists as file for: "
-      << testNewDir << std::endl;
+  if (kwsys::SystemTools::FileExists(testNewDir, true)) {
+    std::cerr << "Problem with FileExists as file for: " << testNewDir
+              << std::endl;
     res = false;
-    }
-  if (kwsys::SystemTools::FileExists(testNewDir.c_str(), true))
-    {
-    std::cerr
-      << "Problem with FileExists as C string and file for: "
-      << testNewDir << std::endl;
+  }
+  if (kwsys::SystemTools::FileExists(testNewDir.c_str(), true)) {
+    std::cerr << "Problem with FileExists as C string and file for: "
+              << testNewDir << std::endl;
     res = false;
-    }
+  }
   // FileExists(x, false) should return true even on a directory
-  if (!kwsys::SystemTools::FileExists(testNewDir, false))
-    {
-    std::cerr
-      << "Problem with FileExists as not file for: "
-      << testNewDir << std::endl;
+  if (!kwsys::SystemTools::FileExists(testNewDir, false)) {
+    std::cerr << "Problem with FileExists as not file for: " << testNewDir
+              << std::endl;
     res = false;
-    }
-  if (!kwsys::SystemTools::FileExists(testNewDir.c_str(), false))
-    {
-    std::cerr
-      << "Problem with FileExists as C string and not file for: "
-      << testNewDir << std::endl;
+  }
+  if (!kwsys::SystemTools::FileExists(testNewDir.c_str(), false)) {
+    std::cerr << "Problem with FileExists as C string and not file for: "
+              << testNewDir << std::endl;
     res = false;
-    }
+  }
   // should work, was created as new file before
-  if (!kwsys::SystemTools::FileExists(testNewFile))
-    {
-    std::cerr
-      << "Problem with FileExists for: "
-      << testNewDir << std::endl;
+  if (!kwsys::SystemTools::FileExists(testNewFile)) {
+    std::cerr << "Problem with FileExists for: " << testNewDir << std::endl;
     res = false;
-    }
-  if (!kwsys::SystemTools::FileExists(testNewFile.c_str()))
-    {
-    std::cerr
-      << "Problem with FileExists as C string for: "
-      << testNewDir << std::endl;
+  }
+  if (!kwsys::SystemTools::FileExists(testNewFile.c_str())) {
+    std::cerr << "Problem with FileExists as C string for: " << testNewDir
+              << std::endl;
     res = false;
-    }
-  if (!kwsys::SystemTools::FileExists(testNewFile, true))
-    {
-    std::cerr
-      << "Problem with FileExists as file for: "
-      << testNewDir << std::endl;
+  }
+  if (!kwsys::SystemTools::FileExists(testNewFile, true)) {
+    std::cerr << "Problem with FileExists as file for: " << testNewDir
+              << std::endl;
     res = false;
-    }
-  if (!kwsys::SystemTools::FileExists(testNewFile.c_str(), true))
-    {
-    std::cerr
-      << "Problem with FileExists as C string and file for: "
-      << testNewDir << std::endl;
+  }
+  if (!kwsys::SystemTools::FileExists(testNewFile.c_str(), true)) {
+    std::cerr << "Problem with FileExists as C string and file for: "
+              << testNewDir << std::endl;
     res = false;
-    }
+  }
 
   // calling with an empty string should return false
-  if (kwsys::SystemTools::PathExists(std::string()))
-    {
-    std::cerr
-      << "Problem with PathExists(std::string())"
-      << std::endl;
+  if (kwsys::SystemTools::PathExists(std::string())) {
+    std::cerr << "Problem with PathExists(std::string())" << std::endl;
     res = false;
-    }
+  }
   // PathExists(x) should return true on a directory
-  if (!kwsys::SystemTools::PathExists(testNewDir))
-    {
-    std::cerr
-      << "Problem with PathExists for: "
-      << testNewDir << std::endl;
+  if (!kwsys::SystemTools::PathExists(testNewDir)) {
+    std::cerr << "Problem with PathExists for: " << testNewDir << std::endl;
     res = false;
-    }
+  }
   // should work, was created as new file before
-  if (!kwsys::SystemTools::PathExists(testNewFile))
-    {
-    std::cerr
-      << "Problem with PathExists for: "
-      << testNewDir << std::endl;
+  if (!kwsys::SystemTools::PathExists(testNewFile)) {
+    std::cerr << "Problem with PathExists for: " << testNewDir << std::endl;
     res = false;
-    }
+  }
 
-  // Reset umask
+// Reset umask
 #if defined(_WIN32) && !defined(__CYGWIN__)
   // NOTE:  Windows doesn't support toggling _S_IREAD.
   mode_t fullMask = _S_IWRITE;
@@ -383,208 +288,169 @@ static bool CheckFileOperations()
 
   // Test file permissions without umask
   mode_t origPerm, thisPerm;
-  if (!kwsys::SystemTools::GetPermissions(testNewFile, origPerm))
-    {
-    std::cerr
-      << "Problem with GetPermissions (1) for: "
-      << testNewFile << std::endl;
+  if (!kwsys::SystemTools::GetPermissions(testNewFile, origPerm)) {
+    std::cerr << "Problem with GetPermissions (1) for: " << testNewFile
+              << std::endl;
     res = false;
-    }
+  }
 
-  if (!kwsys::SystemTools::SetPermissions(testNewFile, 0))
-    {
-    std::cerr
-      << "Problem with SetPermissions (1) for: "
-      << testNewFile << std::endl;
+  if (!kwsys::SystemTools::SetPermissions(testNewFile, 0)) {
+    std::cerr << "Problem with SetPermissions (1) for: " << testNewFile
+              << std::endl;
     res = false;
-    }
+  }
 
-  if (!kwsys::SystemTools::GetPermissions(testNewFile, thisPerm))
-    {
-    std::cerr
-      << "Problem with GetPermissions (2) for: "
-      << testNewFile << std::endl;
+  if (!kwsys::SystemTools::GetPermissions(testNewFile, thisPerm)) {
+    std::cerr << "Problem with GetPermissions (2) for: " << testNewFile
+              << std::endl;
     res = false;
-    }
+  }
 
-  if ((thisPerm & fullMask) != 0)
-    {
-    std::cerr
-      << "SetPermissions failed to set permissions (1) for: "
-      << testNewFile << ": actual = " << thisPerm << "; expected = "
-      << 0 << std::endl;
+  if ((thisPerm & fullMask) != 0) {
+    std::cerr << "SetPermissions failed to set permissions (1) for: "
+              << testNewFile << ": actual = " << thisPerm
+              << "; expected = " << 0 << std::endl;
     res = false;
-    }
+  }
 
   // While we're at it, check proper TestFileAccess functionality.
   if (kwsys::SystemTools::TestFileAccess(testNewFile,
-                                         kwsys::TEST_FILE_WRITE))
-    {
+                                         kwsys::TEST_FILE_WRITE)) {
     std::cerr
       << "TestFileAccess incorrectly indicated that this is a writable file:"
       << testNewFile << std::endl;
     res = false;
-    }
+  }
 
-  if (!kwsys::SystemTools::TestFileAccess(testNewFile,
-                                          kwsys::TEST_FILE_OK))
-    {
+  if (!kwsys::SystemTools::TestFileAccess(testNewFile, kwsys::TEST_FILE_OK)) {
     std::cerr
       << "TestFileAccess incorrectly indicated that this file does not exist:"
       << testNewFile << std::endl;
     res = false;
-    }
+  }
 
   // Test restoring/setting full permissions.
-  if (!kwsys::SystemTools::SetPermissions(testNewFile, fullMask))
-    {
-    std::cerr
-      << "Problem with SetPermissions (2) for: "
-      << testNewFile << std::endl;
+  if (!kwsys::SystemTools::SetPermissions(testNewFile, fullMask)) {
+    std::cerr << "Problem with SetPermissions (2) for: " << testNewFile
+              << std::endl;
     res = false;
-    }
+  }
 
-  if (!kwsys::SystemTools::GetPermissions(testNewFile, thisPerm))
-    {
-    std::cerr
-      << "Problem with GetPermissions (3) for: "
-      << testNewFile << std::endl;
+  if (!kwsys::SystemTools::GetPermissions(testNewFile, thisPerm)) {
+    std::cerr << "Problem with GetPermissions (3) for: " << testNewFile
+              << std::endl;
     res = false;
-    }
+  }
 
-  if ((thisPerm & fullMask) != fullMask)
-    {
-    std::cerr
-      << "SetPermissions failed to set permissions (2) for: "
-      << testNewFile << ": actual = " << thisPerm << "; expected = "
-      << fullMask << std::endl;
+  if ((thisPerm & fullMask) != fullMask) {
+    std::cerr << "SetPermissions failed to set permissions (2) for: "
+              << testNewFile << ": actual = " << thisPerm
+              << "; expected = " << fullMask << std::endl;
     res = false;
-    }
+  }
 
   // Test setting file permissions while honoring umask
-  if (!kwsys::SystemTools::SetPermissions(testNewFile, fullMask, true))
-    {
-    std::cerr
-      << "Problem with SetPermissions (3) for: "
-      << testNewFile << std::endl;
+  if (!kwsys::SystemTools::SetPermissions(testNewFile, fullMask, true)) {
+    std::cerr << "Problem with SetPermissions (3) for: " << testNewFile
+              << std::endl;
     res = false;
-    }
+  }
 
-  if (!kwsys::SystemTools::GetPermissions(testNewFile, thisPerm))
-    {
-    std::cerr
-      << "Problem with GetPermissions (4) for: "
-      << testNewFile << std::endl;
+  if (!kwsys::SystemTools::GetPermissions(testNewFile, thisPerm)) {
+    std::cerr << "Problem with GetPermissions (4) for: " << testNewFile
+              << std::endl;
     res = false;
-    }
+  }
 
-  if ((thisPerm & fullMask) != 0)
-    {
-    std::cerr
-      << "SetPermissions failed to honor umask for: "
-      << testNewFile << ": actual = " << thisPerm << "; expected = "
-      << 0 << std::endl;
+  if ((thisPerm & fullMask) != 0) {
+    std::cerr << "SetPermissions failed to honor umask for: " << testNewFile
+              << ": actual = " << thisPerm << "; expected = " << 0
+              << std::endl;
     res = false;
-    }
+  }
 
   // Restore umask
   umask(orig_umask);
 
   // Restore file permissions
-  if (!kwsys::SystemTools::SetPermissions(testNewFile, origPerm))
-    {
-    std::cerr
-      << "Problem with SetPermissions (4) for: "
-      << testNewFile << std::endl;
+  if (!kwsys::SystemTools::SetPermissions(testNewFile, origPerm)) {
+    std::cerr << "Problem with SetPermissions (4) for: " << testNewFile
+              << std::endl;
     res = false;
-    }
+  }
 
   // Remove the test file
-  if (!kwsys::SystemTools::RemoveFile(testNewFile))
-    {
-    std::cerr
-      << "Problem with RemoveFile: "
-      << testNewFile << std::endl;
+  if (!kwsys::SystemTools::RemoveFile(testNewFile)) {
+    std::cerr << "Problem with RemoveFile: " << testNewFile << std::endl;
     res = false;
-    }
+  }
 
   std::string const testFileMissing(testNewDir + "/testMissingFile.txt");
-  if (!kwsys::SystemTools::RemoveFile(testFileMissing))
-    {
+  if (!kwsys::SystemTools::RemoveFile(testFileMissing)) {
     std::string const& msg = kwsys::SystemTools::GetLastSystemError();
-    std::cerr <<
-      "RemoveFile(\"" << testFileMissing << "\") failed: " << msg << "\n";
+    std::cerr << "RemoveFile(\"" << testFileMissing << "\") failed: " << msg
+              << "\n";
     res = false;
-    }
+  }
 
   std::string const testFileMissingDir(testNewDir + "/missing/file.txt");
-  if (!kwsys::SystemTools::RemoveFile(testFileMissingDir))
-    {
+  if (!kwsys::SystemTools::RemoveFile(testFileMissingDir)) {
     std::string const& msg = kwsys::SystemTools::GetLastSystemError();
-    std::cerr <<
-      "RemoveFile(\"" << testFileMissingDir << "\") failed: " << msg << "\n";
+    std::cerr << "RemoveFile(\"" << testFileMissingDir << "\") failed: " << msg
+              << "\n";
     res = false;
-    }
+  }
 
   kwsys::SystemTools::Touch(testNewFile.c_str(), true);
-  if (!kwsys::SystemTools::RemoveADirectory(testNewDir))
-    {
-    std::cerr
-      << "Problem with RemoveADirectory for: "
-      << testNewDir << std::endl;
+  if (!kwsys::SystemTools::RemoveADirectory(testNewDir)) {
+    std::cerr << "Problem with RemoveADirectory for: " << testNewDir
+              << std::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 std::string testNewLongDir(
-    TEST_SYSTEMTOOLS_BINARY_DIR "/"
+    TEST_SYSTEMTOOLS_BINARY_DIR
+    "/"
     "012345678901234567890123456789012345678901234567890123456789"
     "012345678901234567890123456789012345678901234567890123456789"
     "012345678901234567890123456789012345678901234567890123456789"
     "012345678901234567890123456789012345678901234567890123456789"
     "01234567890123");
-  const std::string testNewLongFile(testNewLongDir + "/"
+  const std::string testNewLongFile(
+    testNewLongDir +
+    "/"
     "012345678901234567890123456789012345678901234567890123456789"
     "012345678901234567890123456789012345678901234567890123456789"
     "012345678901234567890123456789012345678901234567890123456789"
     "012345678901234567890123456789012345678901234567890123456789"
     "0123456789.txt");
 
-  if (!kwsys::SystemTools::MakeDirectory(testNewLongDir))
-    {
-    std::cerr
-      << "Problem with MakeDirectory for: "
-      << testNewLongDir << std::endl;
+  if (!kwsys::SystemTools::MakeDirectory(testNewLongDir)) {
+    std::cerr << "Problem with MakeDirectory for: " << testNewLongDir
+              << std::endl;
     res = false;
-    }
+  }
 
-  if (!kwsys::SystemTools::Touch(testNewLongFile.c_str(), true))
-    {
-    std::cerr
-      << "Problem with Touch for: "
-      << testNewLongFile << std::endl;
+  if (!kwsys::SystemTools::Touch(testNewLongFile.c_str(), true)) {
+    std::cerr << "Problem with Touch for: " << testNewLongFile << std::endl;
     res = false;
-    }
+  }
 
-  if (!kwsys::SystemTools::RemoveFile(testNewLongFile))
-    {
-    std::cerr
-      << "Problem with RemoveFile: "
-      << testNewLongFile << std::endl;
+  if (!kwsys::SystemTools::RemoveFile(testNewLongFile)) {
+    std::cerr << "Problem with RemoveFile: " << testNewLongFile << std::endl;
     res = false;
-    }
+  }
 
   kwsys::SystemTools::Touch(testNewLongFile.c_str(), true);
-  if (!kwsys::SystemTools::RemoveADirectory(testNewLongDir))
-    {
-    std::cerr
-      << "Problem with RemoveADirectory for: "
-      << testNewLongDir << std::endl;
+  if (!kwsys::SystemTools::RemoveADirectory(testNewLongDir)) {
+    std::cerr << "Problem with RemoveADirectory for: " << testNewLongDir
+              << std::endl;
     res = false;
-    }
+  }
 #endif
 
   return res;
@@ -596,326 +462,254 @@ static bool CheckStringOperations()
   bool res = true;
 
   std::string test = "mary had a little lamb.";
-  if (kwsys::SystemTools::CapitalizedWords(test) != "Mary Had A Little Lamb.")
-    {
-    std::cerr
-      << "Problem with CapitalizedWords "
-      << '"' << test << '"' << std::endl;
+  if (kwsys::SystemTools::CapitalizedWords(test) !=
+      "Mary Had A Little Lamb.") {
+    std::cerr << "Problem with CapitalizedWords " << '"' << test << '"'
+              << std::endl;
     res = false;
-    }
+  }
 
   test = "Mary Had A Little Lamb.";
   if (kwsys::SystemTools::UnCapitalizedWords(test) !=
-      "mary had a little lamb.")
-    {
-    std::cerr
-      << "Problem with UnCapitalizedWords "
-      << '"' << test << '"' << std::endl;
+      "mary had a little lamb.") {
+    std::cerr << "Problem with UnCapitalizedWords " << '"' << test << '"'
+              << std::endl;
     res = false;
-    }
+  }
 
   test = "MaryHadTheLittleLamb.";
   if (kwsys::SystemTools::AddSpaceBetweenCapitalizedWords(test) !=
-      "Mary Had The Little Lamb.")
-    {
-    std::cerr
-      << "Problem with AddSpaceBetweenCapitalizedWords "
-      << '"' << test << '"' << std::endl;
+      "Mary Had The Little Lamb.") {
+    std::cerr << "Problem with AddSpaceBetweenCapitalizedWords " << '"' << test
+              << '"' << std::endl;
     res = false;
-    }
+  }
 
-  char * cres =
-    kwsys::SystemTools::AppendStrings("Mary Had A"," Little Lamb.");
-  if (strcmp(cres,"Mary Had A Little Lamb."))
-    {
-    std::cerr
-      << "Problem with AppendStrings "
-      << "\"Mary Had A\" \" Little Lamb.\"" << std::endl;
+  char* cres =
+    kwsys::SystemTools::AppendStrings("Mary Had A", " Little Lamb.");
+  if (strcmp(cres, "Mary Had A Little Lamb.")) {
+    std::cerr << "Problem with AppendStrings "
+              << "\"Mary Had A\" \" Little Lamb.\"" << std::endl;
     res = false;
-    }
-  delete [] cres;
+  }
+  delete[] cres;
 
-  cres =
-    kwsys::SystemTools::AppendStrings("Mary Had"," A ","Little Lamb.");
-  if (strcmp(cres,"Mary Had A Little Lamb."))
-    {
-    std::cerr
-      << "Problem with AppendStrings "
-      << "\"Mary Had\" \" A \" \"Little Lamb.\"" << std::endl;
+  cres = kwsys::SystemTools::AppendStrings("Mary Had", " A ", "Little Lamb.");
+  if (strcmp(cres, "Mary Had A Little Lamb.")) {
+    std::cerr << "Problem with AppendStrings "
+              << "\"Mary Had\" \" A \" \"Little Lamb.\"" << std::endl;
     res = false;
-    }
-  delete [] cres;
+  }
+  delete[] cres;
 
-  if (kwsys::SystemTools::CountChar("Mary Had A Little Lamb.",'a') != 3)
-    {
-    std::cerr
-      << "Problem with CountChar "
-      << "\"Mary Had A Little Lamb.\"" << std::endl;
+  if (kwsys::SystemTools::CountChar("Mary Had A Little Lamb.", 'a') != 3) {
+    std::cerr << "Problem with CountChar "
+              << "\"Mary Had A Little Lamb.\"" << std::endl;
     res = false;
-    }
+  }
 
-  cres =
-    kwsys::SystemTools::RemoveChars("Mary Had A Little Lamb.","aeiou");
-  if (strcmp(cres,"Mry Hd A Lttl Lmb."))
-    {
-    std::cerr
-      << "Problem with RemoveChars "
-      << "\"Mary Had A Little Lamb.\"" << std::endl;
+  cres = kwsys::SystemTools::RemoveChars("Mary Had A Little Lamb.", "aeiou");
+  if (strcmp(cres, "Mry Hd A Lttl Lmb.")) {
+    std::cerr << "Problem with RemoveChars "
+              << "\"Mary Had A Little Lamb.\"" << std::endl;
     res = false;
-    }
-  delete [] cres;
+  }
+  delete[] cres;
 
-  cres =
-    kwsys::SystemTools::RemoveCharsButUpperHex("Mary Had A Little Lamb.");
-  if (strcmp(cres,"A"))
-    {
-    std::cerr
-      << "Problem with RemoveCharsButUpperHex "
-      << "\"Mary Had A Little Lamb.\"" << std::endl;
+  cres = kwsys::SystemTools::RemoveCharsButUpperHex("Mary Had A Little Lamb.");
+  if (strcmp(cres, "A")) {
+    std::cerr << "Problem with RemoveCharsButUpperHex "
+              << "\"Mary Had A Little Lamb.\"" << std::endl;
     res = false;
-    }
-  delete [] cres;
+  }
+  delete[] cres;
 
-  char *cres2 = new char [strlen("Mary Had A Little Lamb.")+1];
-  strcpy(cres2,"Mary Had A Little Lamb.");
-  kwsys::SystemTools::ReplaceChars(cres2,"aeiou",'X');
-  if (strcmp(cres2,"MXry HXd A LXttlX LXmb."))
-    {
-    std::cerr
-      << "Problem with ReplaceChars "
-      << "\"Mary Had A Little Lamb.\"" << std::endl;
+  char* cres2 = new char[strlen("Mary Had A Little Lamb.") + 1];
+  strcpy(cres2, "Mary Had A Little Lamb.");
+  kwsys::SystemTools::ReplaceChars(cres2, "aeiou", 'X');
+  if (strcmp(cres2, "MXry HXd A LXttlX LXmb.")) {
+    std::cerr << "Problem with ReplaceChars "
+              << "\"Mary Had A Little Lamb.\"" << std::endl;
     res = false;
-    }
-  delete [] cres2;
+  }
+  delete[] cres2;
 
   if (!kwsys::SystemTools::StringStartsWith("Mary Had A Little Lamb.",
-                                            "Mary "))
-    {
-    std::cerr
-      << "Problem with StringStartsWith "
-      << "\"Mary Had A Little Lamb.\"" << std::endl;
+                                            "Mary ")) {
+    std::cerr << "Problem with StringStartsWith "
+              << "\"Mary Had A Little Lamb.\"" << std::endl;
     res = false;
-    }
+  }
 
   if (!kwsys::SystemTools::StringEndsWith("Mary Had A Little Lamb.",
-                                          " Lamb."))
-    {
-    std::cerr
-      << "Problem with StringEndsWith "
-      << "\"Mary Had A Little Lamb.\"" << std::endl;
+                                          " Lamb.")) {
+    std::cerr << "Problem with StringEndsWith "
+              << "\"Mary Had A Little Lamb.\"" << std::endl;
     res = false;
-    }
+  }
 
   cres = kwsys::SystemTools::DuplicateString("Mary Had A Little Lamb.");
-  if (strcmp(cres,"Mary Had A Little Lamb."))
-    {
-    std::cerr
-      << "Problem with DuplicateString "
-      << "\"Mary Had A Little Lamb.\"" << std::endl;
+  if (strcmp(cres, "Mary Had A Little Lamb.")) {
+    std::cerr << "Problem with DuplicateString "
+              << "\"Mary Had A Little Lamb.\"" << std::endl;
     res = false;
-    }
-  delete [] cres;
+  }
+  delete[] cres;
 
   test = "Mary Had A Little Lamb.";
-  if (kwsys::SystemTools::CropString(test,13) !=
-      "Mary ...Lamb.")
-    {
-    std::cerr
-      << "Problem with CropString "
-      << "\"Mary Had A Little Lamb.\"" << std::endl;
+  if (kwsys::SystemTools::CropString(test, 13) != "Mary ...Lamb.") {
+    std::cerr << "Problem with CropString "
+              << "\"Mary Had A Little Lamb.\"" << std::endl;
     res = false;
-    }
+  }
 
   std::vector<std::string> lines;
-  kwsys::SystemTools::Split("Mary Had A Little Lamb.",lines,' ');
-  if (lines[0] != "Mary" || lines[1] != "Had" ||
-      lines[2] != "A" || lines[3] != "Little" || lines[4] != "Lamb.")
-    {
-    std::cerr
-      << "Problem with Split "
-      << "\"Mary Had A Little Lamb.\"" << std::endl;
+  kwsys::SystemTools::Split("Mary Had A Little Lamb.", lines, ' ');
+  if (lines[0] != "Mary" || lines[1] != "Had" || lines[2] != "A" ||
+      lines[3] != "Little" || lines[4] != "Lamb.") {
+    std::cerr << "Problem with Split "
+              << "\"Mary Had A Little Lamb.\"" << std::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")
-    {
-    std::cerr
-      << "Problem with ConvertToWindowsExtendedPath "
-      << "\"L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\""
-      << std::endl;
+  if (kwsys::SystemTools::ConvertToWindowsExtendedPath(
+        "L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") !=
+      L"\\\\?\\L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") {
+    std::cerr << "Problem with ConvertToWindowsExtendedPath "
+              << "\"L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\""
+              << std::endl;
     res = false;
-    }
+  }
 
-  if (kwsys::SystemTools::ConvertToWindowsExtendedPath
-      ("L:/Local Mojo/Hex Power Pack/Iffy Voodoo") !=
-      L"\\\\?\\L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo")
-    {
-    std::cerr
-      << "Problem with ConvertToWindowsExtendedPath "
-      << "\"L:/Local Mojo/Hex Power Pack/Iffy Voodoo\""
-      << std::endl;
+  if (kwsys::SystemTools::ConvertToWindowsExtendedPath(
+        "L:/Local Mojo/Hex Power Pack/Iffy Voodoo") !=
+      L"\\\\?\\L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") {
+    std::cerr << "Problem with ConvertToWindowsExtendedPath "
+              << "\"L:/Local Mojo/Hex Power Pack/Iffy Voodoo\"" << std::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")
-    {
-    std::cerr
-      << "Problem with ConvertToWindowsExtendedPath "
-      << "\"\\\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\""
-      << std::endl;
+  if (kwsys::SystemTools::ConvertToWindowsExtendedPath(
+        "\\\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") !=
+      L"\\\\?\\UNC\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") {
+    std::cerr << "Problem with ConvertToWindowsExtendedPath "
+              << "\"\\\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\""
+              << std::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")
-    {
-    std::cerr
-      << "Problem with ConvertToWindowsExtendedPath "
-      << "\"//Foo/Local Mojo/Hex Power Pack/Iffy Voodoo\""
-      << std::endl;
+  if (kwsys::SystemTools::ConvertToWindowsExtendedPath(
+        "//Foo/Local Mojo/Hex Power Pack/Iffy Voodoo") !=
+      L"\\\\?\\UNC\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") {
+    std::cerr << "Problem with ConvertToWindowsExtendedPath "
+              << "\"//Foo/Local Mojo/Hex Power Pack/Iffy Voodoo\""
+              << std::endl;
     res = false;
-    }
+  }
 
-  if (kwsys::SystemTools::ConvertToWindowsExtendedPath("//") !=
-      L"//")
-    {
-    std::cerr
-      << "Problem with ConvertToWindowsExtendedPath "
-      << "\"//\""
-      << std::endl;
+  if (kwsys::SystemTools::ConvertToWindowsExtendedPath("//") != L"//") {
+    std::cerr << "Problem with ConvertToWindowsExtendedPath "
+              << "\"//\"" << std::endl;
     res = false;
-    }
+  }
 
   if (kwsys::SystemTools::ConvertToWindowsExtendedPath("\\\\.\\") !=
-      L"\\\\.\\")
-    {
-    std::cerr
-      << "Problem with ConvertToWindowsExtendedPath "
-      << "\"\\\\.\\\""
-      << std::endl;
+      L"\\\\.\\") {
+    std::cerr << "Problem with ConvertToWindowsExtendedPath "
+              << "\"\\\\.\\\"" << std::endl;
     res = false;
-    }
+  }
 
   if (kwsys::SystemTools::ConvertToWindowsExtendedPath("\\\\.\\X") !=
-      L"\\\\.\\X")
-    {
-    std::cerr
-      << "Problem with ConvertToWindowsExtendedPath "
-      << "\"\\\\.\\X\""
-      << std::endl;
+      L"\\\\.\\X") {
+    std::cerr << "Problem with ConvertToWindowsExtendedPath "
+              << "\"\\\\.\\X\"" << std::endl;
     res = false;
-    }
+  }
 
   if (kwsys::SystemTools::ConvertToWindowsExtendedPath("\\\\.\\X:") !=
-      L"\\\\?\\X:")
-    {
-    std::cerr
-      << "Problem with ConvertToWindowsExtendedPath "
-      << "\"\\\\.\\X:\""
-      << std::endl;
+      L"\\\\?\\X:") {
+    std::cerr << "Problem with ConvertToWindowsExtendedPath "
+              << "\"\\\\.\\X:\"" << std::endl;
     res = false;
-    }
+  }
 
   if (kwsys::SystemTools::ConvertToWindowsExtendedPath("\\\\.\\X:\\") !=
-      L"\\\\?\\X:\\")
-    {
-    std::cerr
-      << "Problem with ConvertToWindowsExtendedPath "
-      << "\"\\\\.\\X:\\\""
-      << std::endl;
+      L"\\\\?\\X:\\") {
+    std::cerr << "Problem with ConvertToWindowsExtendedPath "
+              << "\"\\\\.\\X:\\\"" << std::endl;
     res = false;
-    }
+  }
 
   if (kwsys::SystemTools::ConvertToWindowsExtendedPath("NUL") !=
-      L"\\\\.\\NUL")
-    {
-    std::cerr
-      << "Problem with ConvertToWindowsExtendedPath "
-      << "\"NUL\""
-      << std::endl;
+      L"\\\\.\\NUL") {
+    std::cerr << "Problem with ConvertToWindowsExtendedPath "
+              << "\"NUL\"" << std::endl;
     res = false;
-    }
+  }
 
 #endif
 
-  if (kwsys::SystemTools::ConvertToWindowsOutputPath
-      ("L://Local Mojo/Hex Power Pack/Iffy Voodoo") !=
-      "\"L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\"")
-    {
-    std::cerr
-      << "Problem with ConvertToWindowsOutputPath "
-      << "\"L://Local Mojo/Hex Power Pack/Iffy Voodoo\""
-      << std::endl;
+  if (kwsys::SystemTools::ConvertToWindowsOutputPath(
+        "L://Local Mojo/Hex Power Pack/Iffy Voodoo") !=
+      "\"L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\"") {
+    std::cerr << "Problem with ConvertToWindowsOutputPath "
+              << "\"L://Local Mojo/Hex Power Pack/Iffy Voodoo\"" << std::endl;
     res = false;
-    }
+  }
 
-  if (kwsys::SystemTools::ConvertToWindowsOutputPath
-      ("//grayson/Local Mojo/Hex Power Pack/Iffy Voodoo") !=
-      "\"\\\\grayson\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\"")
-    {
-    std::cerr
-      << "Problem with ConvertToWindowsOutputPath "
-      << "\"//grayson/Local Mojo/Hex Power Pack/Iffy Voodoo\""
-      << std::endl;
+  if (kwsys::SystemTools::ConvertToWindowsOutputPath(
+        "//grayson/Local Mojo/Hex Power Pack/Iffy Voodoo") !=
+      "\"\\\\grayson\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\"") {
+    std::cerr << "Problem with ConvertToWindowsOutputPath "
+              << "\"//grayson/Local Mojo/Hex Power Pack/Iffy Voodoo\""
+              << std::endl;
     res = false;
-    }
+  }
 
-  if (kwsys::SystemTools::ConvertToUnixOutputPath
-      ("//Local Mojo/Hex Power Pack/Iffy Voodoo") !=
-      "//Local\\ Mojo/Hex\\ Power\\ Pack/Iffy\\ Voodoo")
-    {
-    std::cerr
-      << "Problem with ConvertToUnixOutputPath "
-      << "\"//Local Mojo/Hex Power Pack/Iffy Voodoo\""
-      << std::endl;
+  if (kwsys::SystemTools::ConvertToUnixOutputPath(
+        "//Local Mojo/Hex Power Pack/Iffy Voodoo") !=
+      "//Local\\ Mojo/Hex\\ Power\\ Pack/Iffy\\ Voodoo") {
+    std::cerr << "Problem with ConvertToUnixOutputPath "
+              << "\"//Local Mojo/Hex Power Pack/Iffy Voodoo\"" << std::endl;
     res = false;
-    }
+  }
 
   return res;
 }
 
 //----------------------------------------------------------------------------
 
-static bool CheckPutEnv(const std::string& env, const char* name, const char* value)
+static bool CheckPutEnv(const std::string& env, const char* name,
+                        const char* value)
 {
-  if(!kwsys::SystemTools::PutEnv(env))
-    {
-    std::cerr << "PutEnv(\"" << env
-                    << "\") failed!" << std::endl;
+  if (!kwsys::SystemTools::PutEnv(env)) {
+    std::cerr << "PutEnv(\"" << env << "\") failed!" << std::endl;
     return false;
-    }
+  }
   std::string v = "(null)";
   kwsys::SystemTools::GetEnv(name, v);
-  if(v != value)
-    {
-    std::cerr << "GetEnv(\"" << name << "\") returned \""
-                    << v << "\", not \"" << value << "\"!" << std::endl;
+  if (v != value) {
+    std::cerr << "GetEnv(\"" << name << "\") returned \"" << v << "\", not \""
+              << value << "\"!" << std::endl;
     return false;
-    }
+  }
   return true;
 }
 
 static bool CheckUnPutEnv(const char* env, const char* name)
 {
-  if(!kwsys::SystemTools::UnPutEnv(env))
-    {
-    std::cerr << "UnPutEnv(\"" << env << "\") failed!"
-                    << std::endl;
+  if (!kwsys::SystemTools::UnPutEnv(env)) {
+    std::cerr << "UnPutEnv(\"" << env << "\") failed!" << std::endl;
     return false;
-    }
+  }
   std::string v;
-  if(kwsys::SystemTools::GetEnv(name, v))
-    {
-    std::cerr << "GetEnv(\"" << name << "\") returned \""
-                    << v << "\", not (null)!" << std::endl;
+  if (kwsys::SystemTools::GetEnv(name, v)) {
+    std::cerr << "GetEnv(\"" << name << "\") returned \"" << v
+              << "\", not (null)!" << std::endl;
     return false;
-    }
+  }
   return true;
 }
 
@@ -933,19 +727,16 @@ static bool CheckEnvironmentOperations()
   return res;
 }
 
-
-static bool CheckRelativePath(
-  const std::string& local,
-  const std::string& remote,
-  const std::string& expected)
+static bool CheckRelativePath(const std::string& local,
+                              const std::string& remote,
+                              const std::string& expected)
 {
   std::string result = kwsys::SystemTools::RelativePath(local, remote);
-  if (!kwsys::SystemTools::ComparePath(expected, result))
-    {
-    std::cerr << "RelativePath(" << local << ", " << remote
-      << ")  yielded " << result << " instead of " << expected << std::endl;
+  if (!kwsys::SystemTools::ComparePath(expected, result)) {
+    std::cerr << "RelativePath(" << local << ", " << remote << ")  yielded "
+              << result << " instead of " << expected << std::endl;
     return false;
-    }
+  }
   return true;
 }
 
@@ -955,22 +746,21 @@ static bool CheckRelativePaths()
   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/../bin/", "/bin/bash", "../../bin/bash");
   res &= CheckRelativePath("/usr/share", "/usr/share//bin", "bin");
   return res;
 }
 
-static bool CheckCollapsePath(
-  const std::string& path,
-  const std::string& expected)
+static bool CheckCollapsePath(const std::string& path,
+                              const std::string& expected)
 {
   std::string result = kwsys::SystemTools::CollapseFullPath(path);
-  if (!kwsys::SystemTools::ComparePath(expected, result))
-    {
-    std::cerr << "CollapseFullPath(" << path
-      << ")  yielded " << result << " instead of " << expected << std::endl;
+  if (!kwsys::SystemTools::ComparePath(expected, result)) {
+    std::cerr << "CollapseFullPath(" << path << ")  yielded " << result
+              << " instead of " << expected << std::endl;
     return false;
-    }
+  }
   return true;
 }
 
@@ -987,14 +777,12 @@ static std::string StringVectorToString(const std::vector<std::string>& vec)
   std::stringstream ss;
   ss << "vector(";
   for (std::vector<std::string>::const_iterator i = vec.begin();
-       i != vec.end(); ++i)
-    {
-    if (i != vec.begin())
-      {
+       i != vec.end(); ++i) {
+    if (i != vec.begin()) {
       ss << ", ";
-      }
-    ss << *i;
     }
+    ss << *i;
+  }
   ss << ")";
   return ss.str();
 }
@@ -1028,15 +816,13 @@ static bool CheckGetPath()
   std::vector<std::string> pathes = originalPathes;
   kwsys::SystemTools::GetPath(pathes, envName);
 
-  if (pathes != expectedPathes)
-    {
-    std::cerr <<
-      "GetPath(" << StringVectorToString(originalPathes) <<
-      ", " << envName << ")  yielded " << StringVectorToString(pathes) <<
-      " instead of " << StringVectorToString(expectedPathes) <<
-      std::endl;
+  if (pathes != expectedPathes) {
+    std::cerr << "GetPath(" << StringVectorToString(originalPathes) << ", "
+              << envName << ")  yielded " << StringVectorToString(pathes)
+              << " instead of " << StringVectorToString(expectedPathes)
+              << std::endl;
     res = false;
-    }
+  }
 
   res &= CheckUnPutEnv(envName, envName);
   return res;
@@ -1046,64 +832,103 @@ static bool CheckFind()
 {
   bool res = true;
   const std::string testFindFileName("testFindFile.txt");
-  const std::string testFindFile(TEST_SYSTEMTOOLS_BINARY_DIR "/"
-                                 + testFindFileName);
+  const std::string testFindFile(TEST_SYSTEMTOOLS_BINARY_DIR "/" +
+                                 testFindFileName);
 
-  if (!kwsys::SystemTools::Touch(testFindFile.c_str(), true))
-    {
-    std::cerr
-      << "Problem with Touch for: "
-      << testFindFile << std::endl;
+  if (!kwsys::SystemTools::Touch(testFindFile.c_str(), true)) {
+    std::cerr << "Problem with Touch for: " << testFindFile << std::endl;
     // abort here as the existence of the file only makes the test meaningful
     return false;
-    }
+  }
 
   std::vector<std::string> searchPaths;
   searchPaths.push_back(TEST_SYSTEMTOOLS_BINARY_DIR);
-  if (kwsys::SystemTools::FindFile(testFindFileName,
-                                    searchPaths, true).empty())
-    {
-    std::cerr
-      << "Problem with FindFile without system paths for: "
-      << testFindFileName << std::endl;
+  if (kwsys::SystemTools::FindFile(testFindFileName, searchPaths, true)
+        .empty()) {
+    std::cerr << "Problem with FindFile without system paths for: "
+              << testFindFileName << std::endl;
     res = false;
-    }
-  if (kwsys::SystemTools::FindFile(testFindFileName,
-                                    searchPaths, false).empty())
-    {
-    std::cerr
-      << "Problem with FindFile with system paths for: "
-      << testFindFileName << std::endl;
+  }
+  if (kwsys::SystemTools::FindFile(testFindFileName, searchPaths, false)
+        .empty()) {
+    std::cerr << "Problem with FindFile with system paths for: "
+              << testFindFileName << std::endl;
     res = false;
-    }
+  }
 
   return res;
 }
 
+static bool CheckGetLineFromStream()
+{
+  const std::string fileWithFiveCharsOnFirstLine(TEST_SYSTEMTOOLS_SOURCE_DIR
+                                                 "/README.rst");
+
+  kwsys::ifstream file(fileWithFiveCharsOnFirstLine.c_str(), std::ios::in);
+
+  if (!file) {
+    std::cerr << "Problem opening: " << fileWithFiveCharsOnFirstLine
+              << std::endl;
+    return false;
+  }
+
+  std::string line;
+  bool has_newline = false;
+  bool result;
+
+  file.seekg(0, std::ios::beg);
+  result = kwsys::SystemTools::GetLineFromStream(file, line, &has_newline, -1);
+  if (!result || line.size() != 5) {
+    std::cerr << "First line does not have five characters: " << line.size()
+              << std::endl;
+    return false;
+  }
+
+  file.seekg(0, std::ios::beg);
+  result = kwsys::SystemTools::GetLineFromStream(file, line, &has_newline, -1);
+  if (!result || line.size() != 5) {
+    std::cerr << "First line does not have five characters after rewind: "
+              << line.size() << std::endl;
+    return false;
+  }
+
+  bool ret = true;
+
+  for (size_t size = 1; size <= 5; ++size) {
+    file.seekg(0, std::ios::beg);
+    result = kwsys::SystemTools::GetLineFromStream(file, line, &has_newline,
+                                                   static_cast<long>(size));
+    if (!result || line.size() != size) {
+      std::cerr << "Should have read " << size << " characters but got "
+                << line.size() << std::endl;
+      ret = false;
+    }
+  }
+
+  return ret;
+}
+
 //----------------------------------------------------------------------------
-int testSystemTools(int, char*[])
+int testSystemTools(int, char* [])
 {
   bool res = true;
 
   int cc;
-  for ( cc = 0; toUnixPaths[cc][0]; cc ++ )
-    {
+  for (cc = 0; toUnixPaths[cc][0]; cc++) {
     res &= CheckConvertToUnixSlashes(toUnixPaths[cc][0], toUnixPaths[cc][1]);
-    }
+  }
 
   // Special check for ~
   std::string output;
-  if(kwsys::SystemTools::GetEnv("HOME", output))
-    {
+  if (kwsys::SystemTools::GetEnv("HOME", output)) {
     output += "/foo bar/lala";
     res &= CheckConvertToUnixSlashes("~/foo bar/lala", output);
-    }
+  }
 
-  for (cc = 0; checkEscapeChars[cc][0]; cc ++ )
-    {
+  for (cc = 0; checkEscapeChars[cc][0]; cc++) {
     res &= CheckEscapeChars(checkEscapeChars[cc][0], checkEscapeChars[cc][1],
                             *checkEscapeChars[cc][2], checkEscapeChars[cc][3]);
-    }
+  }
 
   res &= CheckFileOperations();
 
@@ -1119,5 +944,7 @@ int testSystemTools(int, char*[])
 
   res &= CheckFind();
 
+  res &= CheckGetLineFromStream();
+
   return res ? 0 : 1;
 }
diff --git a/Source/kwsys/testSystemTools.h.in b/Source/kwsys/testSystemTools.h.in
index 66f0f72..022e36e 100644
--- a/Source/kwsys/testSystemTools.h.in
+++ b/Source/kwsys/testSystemTools.h.in
@@ -1,14 +1,5 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #ifndef @KWSYS_NAMESPACE at _testSystemtools_h
 #define @KWSYS_NAMESPACE at _testSystemtools_h
 
diff --git a/Source/kwsys/testTerminal.c b/Source/kwsys/testTerminal.c
index 0d2d7a7..f6c1edd 100644
--- a/Source/kwsys/testTerminal.c
+++ b/Source/kwsys/testTerminal.c
@@ -1,21 +1,12 @@
-/*============================================================================
-  KWSys - Kitware System Library
-  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.
-============================================================================*/
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(Terminal.h)
 
 /* Work-around CMake dependency scanning limitation.  This must
    duplicate the above list of headers.  */
 #if 0
-# include "Terminal.h.in"
+#include "Terminal.h.in"
 #endif
 
 int testTerminal(int argc, char* argv[])
@@ -23,8 +14,8 @@ int testTerminal(int argc, char* argv[])
   (void)argc;
   (void)argv;
   kwsysTerminal_cfprintf(kwsysTerminal_Color_ForegroundYellow |
-                         kwsysTerminal_Color_BackgroundBlue |
-                         kwsysTerminal_Color_AssumeTTY,
+                           kwsysTerminal_Color_BackgroundBlue |
+                           kwsysTerminal_Color_AssumeTTY,
                          stdout, "Hello %s!", "World");
   fprintf(stdout, "\n");
   return 0;
diff --git a/Templates/TestDriver.cxx.in b/Templates/TestDriver.cxx.in
index 3e0afa5..ecf6fa1 100644
--- a/Templates/TestDriver.cxx.in
+++ b/Templates/TestDriver.cxx.in
@@ -1,21 +1,26 @@
-#include <ctype.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
+#include <ctype.h>  /* NOLINT */
+#include <stdio.h>  /* NOLINT */
+#include <stdlib.h> /* NOLINT */
+#include <string.h> /* NOLINT */
 
 #if defined(_MSC_VER)
-# pragma warning(disable:4996) /* deprecation */
+#pragma warning(disable : 4996) /* deprecation */
 #endif
 
 @CMAKE_TESTDRIVER_EXTRA_INCLUDES@
 
-
 /* Forward declare test functions. */
 @CMAKE_FORWARD_DECLARE_TESTS@
 
+#ifdef __cplusplus
+#define CM_CAST(TYPE, EXPR) static_cast<TYPE>(EXPR)
+#else
+#define CM_CAST(TYPE, EXPR) (TYPE)(EXPR)
+#endif
+
 /* Create map.  */
 
-typedef int (*MainFuncPointer)(int , char*[]);
+typedef int (*MainFuncPointer)(int, char* []);
 typedef struct
 {
   const char* name;
@@ -24,143 +29,108 @@ typedef struct
 
 static functionMapEntry cmakeGeneratedFunctionMapEntries[] = {
   @CMAKE_FUNCTION_TABLE_ENTIRES@
-  {0,0}
+  { NULL, NULL } /* NOLINT */
 };
 
+static const int NumTests =
+  (sizeof(cmakeGeneratedFunctionMapEntries) / sizeof(functionMapEntry)) - 1;
+
 /* Allocate and create a lowercased copy of string
    (note that it has to be free'd manually) */
-
-static char* lowercase(const char *string)
+static char* lowercase(const char* string)
 {
   char *new_string, *p;
   size_t stringSize = 0;
 
-#ifdef __cplusplus
-  stringSize = static_cast<size_t>(strlen(string) + 1);
-  new_string = static_cast<char *>(malloc(sizeof(char) * stringSize));
-#else
-  stringSize = (size_t)(strlen(string) + 1);
-  new_string = (char *)(malloc(sizeof(char) * stringSize));
-#endif
+  stringSize = CM_CAST(size_t, strlen(string) + 1);
+  new_string = CM_CAST(char*, malloc(sizeof(char) * stringSize));
 
-  if (!new_string)
-    {
-    return 0;
-    }
+  if (new_string == NULL) { /* NOLINT */
+    return NULL;            /* NOLINT */
+  }
   strncpy(new_string, string, stringSize);
-  p = new_string;
-  while (*p != 0)
-    {
-#ifdef __cplusplus
-    *p = static_cast<char>(tolower(*p));
-#else
-    *p = (char)(tolower(*p));
-#endif
-
-    ++p;
-    }
+  for (p = new_string; *p != 0; ++p) {
+    *p = CM_CAST(char, tolower(*p));
+  }
   return new_string;
 }
 
-int main(int ac, char *av[])
+int main(int ac, char* av[])
 {
-  int i, NumTests, testNum = 0, partial_match;
+  int i, testNum = 0, partial_match;
   char *arg, *test_name;
-  int count;
   int testToRun = -1;
 
   @CMAKE_TESTDRIVER_ARGVC_FUNCTION@
 
-  for(count =0; cmakeGeneratedFunctionMapEntries[count].name != 0; count++)
-    {
-    }
-  NumTests = count;
   /* If no test name was given */
   /* process command line with user function.  */
-  if (ac < 2)
-    {
+  if (ac < 2) {
     /* Ask for a test.  */
     printf("Available tests:\n");
-    for (i =0; i < NumTests; ++i)
-      {
+    for (i = 0; i < NumTests; ++i) {
       printf("%3d. %s\n", i, cmakeGeneratedFunctionMapEntries[i].name);
-      }
+    }
     printf("To run a test, enter the test number: ");
     fflush(stdout);
-    if( scanf("%d", &testNum) != 1 )
-      {
+    if (scanf("%d", &testNum) != 1) {
       printf("Couldn't parse that input as a number\n");
       return -1;
-      }
-    if (testNum >= NumTests)
-      {
+    }
+    if (testNum >= NumTests) {
       printf("%3d is an invalid test number.\n", testNum);
       return -1;
-      }
+    }
     testToRun = testNum;
     ac--;
     av++;
-    }
+  }
   partial_match = 0;
-  arg = 0;
+  arg = NULL; /* NOLINT */
   /* If partial match is requested.  */
-  if(testToRun == -1 && ac > 1)
-    {
+  if (testToRun == -1 && ac > 1) {
     partial_match = (strcmp(av[1], "-R") == 0) ? 1 : 0;
-    }
-  if (partial_match && ac < 3)
-    {
+  }
+  if (partial_match != 0 && ac < 3) {
     printf("-R needs an additional parameter.\n");
     return -1;
-    }
-  if(testToRun == -1)
-    {
+  }
+  if (testToRun == -1) {
     arg = lowercase(av[1 + partial_match]);
-    }
-  for (i =0; i < NumTests && testToRun == -1; ++i)
-    {
+  }
+  for (i = 0; i < NumTests && testToRun == -1; ++i) {
     test_name = lowercase(cmakeGeneratedFunctionMapEntries[i].name);
-    if (partial_match && strstr(test_name, arg) != NULL)
-      {
+    if (partial_match != 0 && strstr(test_name, arg) != NULL) { /* NOLINT */
       testToRun = i;
-      ac -=2;
+      ac -= 2;
       av += 2;
-      }
-    else if (!partial_match && strcmp(test_name, arg) == 0)
-      {
+    } else if (partial_match == 0 && strcmp(test_name, arg) == 0) {
       testToRun = i;
       ac--;
       av++;
-      }
-    free(test_name);
-    }
-  if(arg)
-    {
-    free(arg);
     }
-  if(testToRun != -1)
-    {
+    free(test_name);
+  }
+  free(arg);
+  if (testToRun != -1) {
     int result;
 @CMAKE_TESTDRIVER_BEFORE_TESTMAIN@
-    if (testToRun < 0 || testToRun >= NumTests)
-      {
-      printf(
-        "testToRun was modified by TestDriver code to an invalid value: %3d.\n",
-        testNum);
+    if (testToRun < 0 || testToRun >= NumTests) {
+      printf("testToRun was modified by TestDriver code to an invalid value: "
+             "%3d.\n",
+             testNum);
       return -1;
-      }
+    }
     result = (*cmakeGeneratedFunctionMapEntries[testToRun].func)(ac, av);
 @CMAKE_TESTDRIVER_AFTER_TESTMAIN@
     return result;
-    }
-
+  }
 
   /* Nothing was run, display the test names.  */
   printf("Available tests:\n");
-  for (i =0; i < NumTests; ++i)
-    {
+  for (i = 0; i < NumTests; ++i) {
     printf("%3d. %s\n", i, cmakeGeneratedFunctionMapEntries[i].name);
-    }
+  }
   printf("Failed: %s is an invalid test name.\n", av[1]);
 
   return -1;
diff --git a/Tests/BootstrapTest.cmake b/Tests/BootstrapTest.cmake
index 9c9fe09..07a65bf 100644
--- a/Tests/BootstrapTest.cmake
+++ b/Tests/BootstrapTest.cmake
@@ -1,7 +1,12 @@
 file(MAKE_DIRECTORY "${bin_dir}")
-message(STATUS "running bootstrap: ${bootstrap}")
+include(ProcessorCount)
+ProcessorCount(nproc)
+if(NOT nproc EQUAL 0)
+  set(parallel_arg --parallel=${nproc})
+endif()
+message(STATUS "running bootstrap: ${bootstrap} ${parallel_arg}")
 execute_process(
-  COMMAND ${bootstrap}
+  COMMAND ${bootstrap} ${parallel_arg}
   WORKING_DIRECTORY "${bin_dir}"
   RESULT_VARIABLE result
   )
diff --git a/Tests/CMakeCommands/target_compile_features/CMakeLists.txt b/Tests/CMakeCommands/target_compile_features/CMakeLists.txt
index 9b35f27..555a08f 100644
--- a/Tests/CMakeCommands/target_compile_features/CMakeLists.txt
+++ b/Tests/CMakeCommands/target_compile_features/CMakeLists.txt
@@ -26,7 +26,7 @@ if (CMAKE_C_COMPILE_FEATURES)
   target_link_libraries(restrict_user lib_restrict)
 endif()
 
-if (CMAKE_CXX_COMPILE_FEATURES)
+if (CMAKE_CXX_COMPILE_FEATURES AND ";${CMAKE_CXX_COMPILE_FEATURES};" MATCHES ";cxx_auto_type;")
   if (CMAKE_C_COMPILE_FEATURES)
     set(target_suffix _cxx)
   endif()
diff --git a/Tests/CMakeLib/CMakeLists.txt b/Tests/CMakeLib/CMakeLists.txt
index 405917a..d680205 100644
--- a/Tests/CMakeLib/CMakeLists.txt
+++ b/Tests/CMakeLib/CMakeLists.txt
@@ -31,6 +31,9 @@ create_test_sourcelist(CMakeLib_TEST_SRCS CMakeLibTests.cxx ${CMakeLib_TESTS})
 add_executable(CMakeLibTests ${CMakeLib_TEST_SRCS})
 target_link_libraries(CMakeLibTests CMakeLib)
 
+add_executable(testEncoding testEncoding.cxx)
+target_link_libraries(testEncoding cmsys)
+
 # Xcode 2.x forgets to create the output directory before linking
 # the individual architectures.
 if(CMAKE_OSX_ARCHITECTURES AND XCODE
diff --git a/Tests/CMakeLib/run_compile_commands.cxx b/Tests/CMakeLib/run_compile_commands.cxx
index 0bf0a7c..5d4ca70 100644
--- a/Tests/CMakeLib/run_compile_commands.cxx
+++ b/Tests/CMakeLib/run_compile_commands.cxx
@@ -1,4 +1,4 @@
-#include "cmSystemTools.h"
+#include <cmConfigure.h>
 
 #include <cmsys/FStream.hxx>
 #include <iostream>
@@ -8,6 +8,8 @@
 #include <utility>
 #include <vector>
 
+#include "cmSystemTools.h"
+
 class CompileCommandParser
 {
 public:
diff --git a/Tests/CMakeLib/testEncoding.cxx b/Tests/CMakeLib/testEncoding.cxx
new file mode 100644
index 0000000..88743b0
--- /dev/null
+++ b/Tests/CMakeLib/testEncoding.cxx
@@ -0,0 +1,49 @@
+#include <fstream>
+#include <iostream>
+#include <string>
+
+#include <cmsys/ConsoleBuf.hxx>
+
+#ifdef _WIN32
+void setEncoding(cmsys::ConsoleBuf::Manager& buf, UINT codepage)
+{
+  cmsys::ConsoleBuf* cb = buf.GetConsoleBuf();
+  if (cb) {
+    cb->input_pipe_codepage = codepage;
+    cb->output_pipe_codepage = codepage;
+    cb->input_file_codepage = codepage;
+    cb->output_file_codepage = codepage;
+    cb->activateCodepageChange();
+  }
+}
+#endif
+
+int main(int argc, char* argv[])
+{
+#ifdef _WIN32
+  cmsys::ConsoleBuf::Manager consoleOut(std::cout);
+#endif
+  if (argc <= 2) {
+    std::cout << "Usage: testEncoding <encoding> <file>" << std::endl;
+    return 1;
+  }
+  const std::string encoding(argv[1]);
+#ifdef _WIN32
+  if (encoding == "UTF8") {
+    setEncoding(consoleOut, CP_UTF8);
+  } else if (encoding == "ANSI") {
+    setEncoding(consoleOut, CP_ACP);
+  } else if (encoding == "OEM") {
+    setEncoding(consoleOut, CP_OEMCP);
+  } // else AUTO
+#endif
+  std::ifstream file(argv[2]);
+  if (!file.is_open()) {
+    std::cout << "Failed to open file: " << argv[2] << std::endl;
+    return 2;
+  }
+  std::string text((std::istreambuf_iterator<char>(file)),
+                   std::istreambuf_iterator<char>());
+  std::cout << text;
+  return 0;
+}
diff --git a/Tests/CMakeLib/testFindPackageCommand.cxx b/Tests/CMakeLib/testFindPackageCommand.cxx
index 7622756..bfd429f 100644
--- a/Tests/CMakeLib/testFindPackageCommand.cxx
+++ b/Tests/CMakeLib/testFindPackageCommand.cxx
@@ -1,9 +1,13 @@
 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
    file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmFindPackageCommand.h"
+
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <iostream>
 #include <string>
+#include <vector>
+
+#include "cmFindPackageCommand.h"
 
 #define cmPassed(m) std::cout << "Passed: " << (m) << "\n"
 #define cmFailed(m)                                                           \
diff --git a/Tests/CMakeLib/testSystemTools.cxx b/Tests/CMakeLib/testSystemTools.cxx
index b16b088..0dfa326 100644
--- a/Tests/CMakeLib/testSystemTools.cxx
+++ b/Tests/CMakeLib/testSystemTools.cxx
@@ -1,9 +1,14 @@
 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
    file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmSystemTools.h"
+
+#include <cmConfigure.h> // IWYU pragma: keep
 
 #include <iostream>
+#include <stddef.h>
 #include <string>
+#include <vector>
+
+#include "cmSystemTools.h"
 
 #define cmPassed(m) std::cout << "Passed: " << (m) << "\n"
 #define cmFailed(m)                                                           \
diff --git a/Tests/CMakeLib/testXMLSafe.cxx b/Tests/CMakeLib/testXMLSafe.cxx
index 6c59128..fe776c5 100644
--- a/Tests/CMakeLib/testXMLSafe.cxx
+++ b/Tests/CMakeLib/testXMLSafe.cxx
@@ -1,11 +1,14 @@
 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
    file Copyright.txt or https://cmake.org/licensing for details.  */
-#include "cmXMLSafe.h"
+
+#include <cmConfigure.h>
 
 #include <sstream>
 #include <stdio.h>
 #include <string>
 
+#include "cmXMLSafe.h"
+
 struct test_pair
 {
   const char* in;
diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt
index 7df9403..4945b31 100644
--- a/Tests/CMakeLists.txt
+++ b/Tests/CMakeLists.txt
@@ -324,6 +324,11 @@ if(BUILD_TESTING)
       ADD_TEST_MACRO(VSGNUFortran ${CMAKE_COMMAND} -P runtest.cmake)
     endif()
   endif()
+
+  if(${CMAKE_GENERATOR} MATCHES "Visual Studio ([^789]|[789][0-9])")
+    ADD_TEST_MACRO(CSharpOnly CSharpOnly)
+  endif()
+
   ADD_TEST_MACRO(COnly COnly)
   ADD_TEST_MACRO(CxxOnly CxxOnly)
   ADD_TEST_MACRO(CxxSubdirC CxxSubdirC)
@@ -1243,7 +1248,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
     set(run_autogen_test ${CMAKE_CTEST_COMMAND} -V)
     set(run_autouic_test ${CMAKE_CTEST_COMMAND} -V)
   else()
-    set(run_autogen_test QtAutogen)
+    set(run_autogen_test complex/QtAutogen)
     set(run_autouic_test QtAutoUicInterface)
   endif()
   if(NOT CMAKE_CONFIGURATION_TYPES)
@@ -1353,6 +1358,11 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
     endif()
   endif()
 
+  if(CMake_TEST_CUDA)
+    add_subdirectory(Cuda)
+    add_subdirectory(CudaOnly)
+  endif()
+
   if(CMake_TEST_FindBoost)
     add_subdirectory(FindBoost)
   endif()
@@ -1377,6 +1387,10 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
     add_subdirectory(FindJsonCpp)
   endif()
 
+  if(CMake_TEST_FindLibRHash)
+    add_subdirectory(FindLibRHash)
+  endif()
+
   if(CMake_TEST_FindLibUV)
     add_subdirectory(FindLibUV)
   endif()
@@ -1389,6 +1403,10 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
     add_subdirectory(FindOpenCL)
   endif()
 
+  if(CMake_TEST_FindOpenGL)
+    add_subdirectory(FindOpenGL)
+  endif()
+
   if(CMake_TEST_FindOpenSSL)
     add_subdirectory(FindOpenSSL)
   endif()
@@ -3081,8 +3099,8 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
         -P ${CMAKE_CURRENT_SOURCE_DIR}/BootstrapTest.cmake
       )
     list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/BootstrapTest")
-    # Make this test run early during parallel execution
-    set_tests_properties(BootstrapTest PROPERTIES COST 5000)
+    # This test will use all processors.
+    set_tests_properties(BootstrapTest PROPERTIES RUN_SERIAL 1)
 
     # provide more time for the bootstrap test
     get_test_property(BootstrapTest TIMEOUT PREVIOUS_TIMEOUT)
@@ -3346,20 +3364,6 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
     --test-command InterfaceLinkLibraries)
   list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/InterfaceLinkLibraries")
 
-  if(CMAKE_USE_KWSTYLE AND KWSTYLE_EXECUTABLE)
-    # The "make StyleCheck" command line as a test. If the test fails, look
-    # for lines like "Error #0 (624) Line length exceed 88 (max=79)" in the
-    # output to find where the style errors are...
-    add_test(KWStyle ${KWSTYLE_EXECUTABLE}
-      -xml ${CMake_BINARY_DIR}/CMake.kws.xml
-      -o ${CMake_SOURCE_DIR}/Utilities/KWStyle/CMakeOverwrite.txt
-      -v
-      -D ${CMake_BINARY_DIR}/CMakeKWSFiles.txt
-      )
-    set_tests_properties(KWStyle PROPERTIES
-      WORKING_DIRECTORY ${CMake_BINARY_DIR}/Utilities/KWStyle)
-  endif()
-
   if(NOT CMake_TEST_EXTERNAL_CMAKE)
     add_subdirectory(CMakeTests)
   endif()
diff --git a/Tests/CMakeOnly/CMakeLists.txt b/Tests/CMakeOnly/CMakeLists.txt
index 7586de6..c692cbd 100644
--- a/Tests/CMakeOnly/CMakeLists.txt
+++ b/Tests/CMakeOnly/CMakeLists.txt
@@ -26,6 +26,9 @@ add_CMakeOnly_test(CompilerIdCXX)
 if(CMAKE_Fortran_COMPILER)
   add_CMakeOnly_test(CompilerIdFortran)
 endif()
+if(CMAKE_GENERATOR MATCHES "Visual Studio ([^789]|[789][0-9])")
+  add_CMakeOnly_test(CompilerIdCSharp)
+endif()
 
 add_CMakeOnly_test(AllFindModules)
 
diff --git a/Tests/CMakeOnly/CompilerIdCSharp/CMakeLists.txt b/Tests/CMakeOnly/CompilerIdCSharp/CMakeLists.txt
new file mode 100644
index 0000000..6c07037
--- /dev/null
+++ b/Tests/CMakeOnly/CompilerIdCSharp/CMakeLists.txt
@@ -0,0 +1,21 @@
+cmake_minimum_required(VERSION 3.7.0)
+project(CompilerIdCSharp CSharp)
+
+foreach(v
+    CMAKE_CSharp_COMPILER
+    CMAKE_CSharp_COMPILER_ID
+    CMAKE_CSharp_COMPILER_VERSION
+    )
+  if(${v})
+    message(STATUS "${v}=[${${v}}]")
+  else()
+    message(SEND_ERROR "${v} not set!")
+  endif()
+endforeach()
+
+# Version numbers may only contain numbers and periods.
+if(NOT CMAKE_CSharp_COMPILER_VERSION MATCHES
+    "^([0-9]+)(\\.([0-9]+))?(\\.([0-9]+))?(\\.([0-9]+))?$"
+    )
+  message(SEND_ERROR "Compiler version is not numeric!")
+endif()
diff --git a/Tests/CMakeTests/File-SHA3_224-Works.cmake b/Tests/CMakeTests/File-SHA3_224-Works.cmake
new file mode 100644
index 0000000..e4f4e85
--- /dev/null
+++ b/Tests/CMakeTests/File-SHA3_224-Works.cmake
@@ -0,0 +1,2 @@
+file(SHA3_224 ${CMAKE_CURRENT_LIST_DIR}/File-HASH-Input.txt sha3_224)
+message("${sha3_224}")
diff --git a/Tests/CMakeTests/File-SHA3_256-Works.cmake b/Tests/CMakeTests/File-SHA3_256-Works.cmake
new file mode 100644
index 0000000..189c8a2
--- /dev/null
+++ b/Tests/CMakeTests/File-SHA3_256-Works.cmake
@@ -0,0 +1,2 @@
+file(SHA3_256 ${CMAKE_CURRENT_LIST_DIR}/File-HASH-Input.txt sha3_256)
+message("${sha3_256}")
diff --git a/Tests/CMakeTests/File-SHA3_384-Works.cmake b/Tests/CMakeTests/File-SHA3_384-Works.cmake
new file mode 100644
index 0000000..08f9f5b
--- /dev/null
+++ b/Tests/CMakeTests/File-SHA3_384-Works.cmake
@@ -0,0 +1,2 @@
+file(SHA3_384 ${CMAKE_CURRENT_LIST_DIR}/File-HASH-Input.txt sha3_384)
+message("${sha3_384}")
diff --git a/Tests/CMakeTests/File-SHA3_512-Works.cmake b/Tests/CMakeTests/File-SHA3_512-Works.cmake
new file mode 100644
index 0000000..4182196
--- /dev/null
+++ b/Tests/CMakeTests/File-SHA3_512-Works.cmake
@@ -0,0 +1,2 @@
+file(SHA3_512 ${CMAKE_CURRENT_LIST_DIR}/File-HASH-Input.txt sha3_512)
+message("${sha3_512}")
diff --git a/Tests/CMakeTests/File-TIMESTAMP-NotBogus.cmake b/Tests/CMakeTests/File-TIMESTAMP-NotBogus.cmake
index d0e5fe3..f1aa390 100644
--- a/Tests/CMakeTests/File-TIMESTAMP-NotBogus.cmake
+++ b/Tests/CMakeTests/File-TIMESTAMP-NotBogus.cmake
@@ -1,6 +1,7 @@
 set(STAMP_FILENAME "${CMAKE_CURRENT_BINARY_DIR}/FileTimestamp-Stamp")
 set(STAMP_FORMAT "%Y-%m-%d")
 
+unset(ENV{SOURCE_DATE_EPOCH})
 string(TIMESTAMP timestamp1 "${STAMP_FORMAT}")
 
 file(WRITE "${STAMP_FILENAME}" "foo")
diff --git a/Tests/CMakeTests/FileTest.cmake.in b/Tests/CMakeTests/FileTest.cmake.in
index 61523e6..71cb3db 100644
--- a/Tests/CMakeTests/FileTest.cmake.in
+++ b/Tests/CMakeTests/FileTest.cmake.in
@@ -36,6 +36,14 @@ set(SHA384-Works-RESULT 0)
 set(SHA384-Works-STDERR "1de9560b4e030e02051ea408200ffc55d70c97ac64ebf822461a5c786f495c36df43259b14483bc8d364f0106f4971ee")
 set(SHA512-Works-RESULT 0)
 set(SHA512-Works-STDERR "3982a1b4e651768bec70ab1fb97045cb7a659f4ba7203d501c52ab2e803071f9d5fd272022df15f27727fc67f8cd022e710e29010b2a9c0b467c111e2f6abf51")
+set(SHA3_224-Works-RESULT 0)
+set(SHA3_224-Works-STDERR "4272868085f4f25080681a7712509fd12e16dcda79bd356836dd2100")
+set(SHA3_256-Works-RESULT 0)
+set(SHA3_256-Works-STDERR "be0df472b6bd474417a166d12f2774f2ef5095e86f0a88ef4c78c703800cfc8a")
+set(SHA3_384-Works-RESULT 0)
+set(SHA3_384-Works-STDERR "935a17cc708443c1369549483656a4521af03a52e4f3b314566272017ccae03a2c5db838f6d4c156b1dc5c366182481b")
+set(SHA3_512-Works-RESULT 0)
+set(SHA3_512-Works-STDERR "471a85ed537e8f77f31412a089f22d836054ffa179599f87a5d7568927d8fa236b6793ded8a387d1de92398c967177bcc6361672a722bf736cb0f63a0956d5cf")
 set(TIMESTAMP-NoFile-RESULT 0)
 set(TIMESTAMP-NoFile-STDERR "~~")
 set(TIMESTAMP-BadArg1-RESULT 1)
@@ -66,6 +74,10 @@ check_cmake_test(File
   SHA256-Works
   SHA384-Works
   SHA512-Works
+  SHA3_224-Works
+  SHA3_256-Works
+  SHA3_384-Works
+  SHA3_512-Works
   TIMESTAMP-NoFile
   TIMESTAMP-BadArg1
   TIMESTAMP-NotBogus
diff --git a/Tests/CMakeTests/ImplicitLinkInfoTest.cmake.in b/Tests/CMakeTests/ImplicitLinkInfoTest.cmake.in
index 1313dbf..58e2bf9 100644
--- a/Tests/CMakeTests/ImplicitLinkInfoTest.cmake.in
+++ b/Tests/CMakeTests/ImplicitLinkInfoTest.cmake.in
@@ -261,6 +261,12 @@ set(mac_absoft_libs "af90math;afio;amisc;absoftmain;af77math;m;mv")
 set(mac_absoft_dirs "/Applications/Absoft11.1/lib;/usr/lib/i686-apple-darwin10/4.2.1;/usr/lib/gcc/i686-apple-darwin10/4.2.1;/usr/lib")
 list(APPEND platforms mac_absoft)
 
+# Xcode 8.3: clang++ dummy.cpp -v
+set(mac_clang_v_text " \"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld\" -demangle -lto_library /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/libLTO.dylib -no_deduplicate -dynamic -arch x86_64 -macosx_version_min 10.12.0 -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -o a.out /var/folders/hc/95l7dhnx459c57g4yg_6yd8c0000gp/T/dummy-384ea1.o - [...]
+set(mac_clang_v_libs "c++")
+set(mac_clang_v_dirs "")
+list(APPEND platforms mac_clang_v)
+
 #-----------------------------------------------------------------------------
 # Sun
 
@@ -518,6 +524,13 @@ set(msys_g77_libs "frtbegin;g2c;mingw32;moldname;mingwex;msvcrt;user32;kernel32;
 set(msys_g77_dirs "C:/some-mingw/lib/gcc/mingw32/3.4.5;C:/some-mingw/lib/gcc;/some-mingw/lib;C:/some-mingw/lib")
 list(APPEND platforms msys_g77)
 
+#-----------------------------------------------------------------------------
+# MSVC from NVIDIA CUDA
+
+set(nvcc_msvc_text [[cuda-fake-ld cl.exe -nologo "tmp/a_dlink.obj" "tmp/CMakeCUDACompilerId.obj" -link -INCREMENTAL:NO   "/LIBPATH:C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v8.0/bin/../lib/x64" cudadevrt.lib  cudart_static.lib -Fe"a.exe"]])
+set(nvcc_msvc_libs "cudadevrt.lib;cudart_static.lib")
+set(nvcc_msvc_dirs "C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v8.0/lib/x64")
+list(APPEND platforms nvcc_msvc)
 
 #-----------------------------------------------------------------------------
 # Test parsing for all above examples.
diff --git a/Tests/CMakeTests/String-SHA3_224-Works.cmake b/Tests/CMakeTests/String-SHA3_224-Works.cmake
new file mode 100644
index 0000000..6aeb91d
--- /dev/null
+++ b/Tests/CMakeTests/String-SHA3_224-Works.cmake
@@ -0,0 +1,2 @@
+string(SHA3_224 sha3_224 "sample input string\n")
+message("${sha3_224}")
diff --git a/Tests/CMakeTests/String-SHA3_256-Works.cmake b/Tests/CMakeTests/String-SHA3_256-Works.cmake
new file mode 100644
index 0000000..cc7ea1a
--- /dev/null
+++ b/Tests/CMakeTests/String-SHA3_256-Works.cmake
@@ -0,0 +1,2 @@
+string(SHA3_256 sha3_256 "sample input string\n")
+message("${sha3_256}")
diff --git a/Tests/CMakeTests/String-SHA3_384-Works.cmake b/Tests/CMakeTests/String-SHA3_384-Works.cmake
new file mode 100644
index 0000000..9341c3f
--- /dev/null
+++ b/Tests/CMakeTests/String-SHA3_384-Works.cmake
@@ -0,0 +1,2 @@
+string(SHA3_384 sha3_384 "sample input string\n")
+message("${sha3_384}")
diff --git a/Tests/CMakeTests/String-SHA3_512-Works.cmake b/Tests/CMakeTests/String-SHA3_512-Works.cmake
new file mode 100644
index 0000000..cf4eddd
--- /dev/null
+++ b/Tests/CMakeTests/String-SHA3_512-Works.cmake
@@ -0,0 +1,2 @@
+string(SHA3_512 sha3_512 "sample input string\n")
+message("${sha3_512}")
diff --git a/Tests/CMakeTests/StringTest.cmake.in b/Tests/CMakeTests/StringTest.cmake.in
index a45b205..83655da 100644
--- a/Tests/CMakeTests/StringTest.cmake.in
+++ b/Tests/CMakeTests/StringTest.cmake.in
@@ -16,6 +16,14 @@ set(SHA384-Works-RESULT 0)
 set(SHA384-Works-STDERR "1de9560b4e030e02051ea408200ffc55d70c97ac64ebf822461a5c786f495c36df43259b14483bc8d364f0106f4971ee")
 set(SHA512-Works-RESULT 0)
 set(SHA512-Works-STDERR "3982a1b4e651768bec70ab1fb97045cb7a659f4ba7203d501c52ab2e803071f9d5fd272022df15f27727fc67f8cd022e710e29010b2a9c0b467c111e2f6abf51")
+set(SHA3_224-Works-RESULT 0)
+set(SHA3_224-Works-STDERR "4272868085f4f25080681a7712509fd12e16dcda79bd356836dd2100")
+set(SHA3_256-Works-RESULT 0)
+set(SHA3_256-Works-STDERR "be0df472b6bd474417a166d12f2774f2ef5095e86f0a88ef4c78c703800cfc8a")
+set(SHA3_384-Works-RESULT 0)
+set(SHA3_384-Works-STDERR "935a17cc708443c1369549483656a4521af03a52e4f3b314566272017ccae03a2c5db838f6d4c156b1dc5c366182481b")
+set(SHA3_512-Works-RESULT 0)
+set(SHA3_512-Works-STDERR "471a85ed537e8f77f31412a089f22d836054ffa179599f87a5d7568927d8fa236b6793ded8a387d1de92398c967177bcc6361672a722bf736cb0f63a0956d5cf")
 set(TIMESTAMP-BadArg1-RESULT 1)
 set(TIMESTAMP-BadArg1-STDERR "string sub-command TIMESTAMP requires at least one argument")
 set(TIMESTAMP-BadArg2-RESULT 1)
@@ -52,6 +60,10 @@ check_cmake_test(String
   SHA256-Works
   SHA384-Works
   SHA512-Works
+  SHA3_224-Works
+  SHA3_256-Works
+  SHA3_384-Works
+  SHA3_512-Works
   TIMESTAMP-BadArg1
   TIMESTAMP-BadArg2
   TIMESTAMP-BadArg3
diff --git a/Tests/CPackComponentsForAll/RunCPackVerifyResult.cmake b/Tests/CPackComponentsForAll/RunCPackVerifyResult.cmake
index fc90d09..a5b38fd 100644
--- a/Tests/CPackComponentsForAll/RunCPackVerifyResult.cmake
+++ b/Tests/CPackComponentsForAll/RunCPackVerifyResult.cmake
@@ -205,14 +205,14 @@ if(CPackGen MATCHES "RPM")
 /usr/foo/bar/non_relocatable/depth_two
 /usr/foo/bar/non_relocatable/depth_two/symlink_from_non_relocatable_path
 /usr/foo/bar/other_relocatable
-/usr/foo/bar/other_relocatable/depth_two$")
+/usr/foo/bar/other_relocatable/depth_two(\n.*\.build-id.*)*$")
       elseif(check_file_headers_match)
         set(check_file_match_expected_summary ".*${CPACK_RPM_HEADERS_PACKAGE_SUMMARY}.*")
         set(check_file_match_expected_description ".*${CPACK_RPM_HEADERS_PACKAGE_DESCRIPTION}.*")
         set(check_file_match_expected_relocation_path "Relocations${whitespaces}:${whitespaces}${CPACK_PACKAGING_INSTALL_PREFIX}${whitespaces}${CPACK_PACKAGING_INSTALL_PREFIX}/${CMAKE_INSTALL_INCLUDEDIR}")
         set(check_file_match_expected_architecture "noarch")
         set(spec_regex "*headers*")
-        set(check_content_list "^/usr/foo/bar\n/usr/foo/bar/include\n/usr/foo/bar/include/mylib.h$")
+        set(check_content_list "^/usr/foo/bar\n/usr/foo/bar/include\n/usr/foo/bar/include/mylib.h(\n.*\.build-id.*)*$")
       elseif(check_file_applications_match)
         set(check_file_match_expected_summary ".*${CPACK_RPM_PACKAGE_SUMMARY}.*")
         set(check_file_match_expected_description ".*${CPACK_COMPONENT_APPLICATIONS_DESCRIPTION}.*")
@@ -221,7 +221,7 @@ if(CPackGen MATCHES "RPM")
         set(spec_regex "*applications*")
         set(check_content_list "^/usr/foo/bar
 /usr/foo/bar/bin
-/usr/foo/bar/bin/mylibapp$")
+/usr/foo/bar/bin/mylibapp(\n.*\.build-id.*)*$")
       elseif(check_file_Unspecified_match)
         set(check_file_match_expected_summary ".*${CPACK_RPM_PACKAGE_SUMMARY}.*")
         set(check_file_match_expected_description ".*DESCRIPTION.*")
@@ -241,7 +241,7 @@ if(CPackGen MATCHES "RPM")
 /usr/foo/bar/share/man/mylib/man3
 /usr/foo/bar/share/man/mylib/man3/mylib.1
 /usr/foo/bar/share/man/mylib/man3/mylib.1/mylib
-/usr/foo/bar/share/man/mylib/man3/mylib.1/mylib2$")
+/usr/foo/bar/share/man/mylib/man3/mylib.1/mylib2(\n.*\.build-id.*)*$")
       else()
         message(FATAL_ERROR "error: unexpected rpm package '${check_file}'")
       endif()
diff --git a/Tests/CSharpOnly/CMakeLists.txt b/Tests/CSharpOnly/CMakeLists.txt
new file mode 100644
index 0000000..0e3e39e
--- /dev/null
+++ b/Tests/CSharpOnly/CMakeLists.txt
@@ -0,0 +1,10 @@
+# a simple CSharp only test case
+project (CSharpOnly CSharp)
+
+# C# does not make any difference between STATIC and SHARED libs
+add_library(lib1 STATIC lib1.cs)
+add_library(lib2 SHARED lib2.cs)
+
+add_executable(CSharpOnly csharponly.cs)
+
+target_link_libraries(CSharpOnly lib1 lib2)
diff --git a/Tests/CSharpOnly/csharponly.cs b/Tests/CSharpOnly/csharponly.cs
new file mode 100644
index 0000000..ad4641a
--- /dev/null
+++ b/Tests/CSharpOnly/csharponly.cs
@@ -0,0 +1,15 @@
+namespace CSharpOnly
+{
+    class CSharpOnly
+    {
+        public static void Main(string[] args)
+        {
+            int val = Lib1.getResult();
+
+            Lib2 l = new Lib2();
+            val = l.myVal;
+
+            return;
+        }
+    }
+}
diff --git a/Tests/CSharpOnly/lib1.cs b/Tests/CSharpOnly/lib1.cs
new file mode 100644
index 0000000..7a7ae10
--- /dev/null
+++ b/Tests/CSharpOnly/lib1.cs
@@ -0,0 +1,10 @@
+namespace CSharpOnly
+{
+    public class Lib1
+    {
+        public static int getResult()
+        {
+            return 23;
+        }
+    }
+}
diff --git a/Tests/CSharpOnly/lib2.cs b/Tests/CSharpOnly/lib2.cs
new file mode 100644
index 0000000..b4b38ce
--- /dev/null
+++ b/Tests/CSharpOnly/lib2.cs
@@ -0,0 +1,10 @@
+namespace CSharpOnly
+{
+    public class Lib2
+    {
+        public int myVal = 42;
+
+        public Lib2()
+        {}
+    }
+}
diff --git a/Tests/CTestTestChecksum/test.cmake.in b/Tests/CTestTestChecksum/test.cmake.in
index 32d62bb..2a435d2 100644
--- a/Tests/CTestTestChecksum/test.cmake.in
+++ b/Tests/CTestTestChecksum/test.cmake.in
@@ -5,8 +5,8 @@ set(CTEST_DASHBOARD_ROOT                "@CMake_BINARY_DIR@/Tests/CTestTest")
 set(CTEST_SITE                          "@SITE@")
 set(CTEST_BUILD_NAME                    "CTestTest- at BUILDNAME@-Checksum")
 
-set(CTEST_SOURCE_DIRECTORY              "@CMake_SOURCE_DIR@/Tests/CTestTestParallel")
-set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestParallel")
+set(CTEST_SOURCE_DIRECTORY              "@CMake_SOURCE_DIR@/Tests/CTestTestChecksum")
+set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestChecksum")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
 set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
diff --git a/Tests/CTestTestLaunchers/launcher_compiler_test_project/CMakeLists.txt b/Tests/CTestTestLaunchers/launcher_compiler_test_project/CMakeLists.txt
new file mode 100644
index 0000000..7376a40
--- /dev/null
+++ b/Tests/CTestTestLaunchers/launcher_compiler_test_project/CMakeLists.txt
@@ -0,0 +1,7 @@
+cmake_minimum_required(VERSION 2.8.12)
+
+project(launcher_compiler_test_project)
+
+include(CTest)
+
+add_executable(build_error build_error.cxx)
diff --git a/Tests/CTestTestLaunchers/launcher_test_project/CTestConfig.cmake b/Tests/CTestTestLaunchers/launcher_compiler_test_project/CTestConfig.cmake
similarity index 100%
copy from Tests/CTestTestLaunchers/launcher_test_project/CTestConfig.cmake
copy to Tests/CTestTestLaunchers/launcher_compiler_test_project/CTestConfig.cmake
diff --git a/Tests/CTestTestLaunchers/launcher_compiler_test_project/build_error.cxx b/Tests/CTestTestLaunchers/launcher_compiler_test_project/build_error.cxx
new file mode 100644
index 0000000..2d51693
--- /dev/null
+++ b/Tests/CTestTestLaunchers/launcher_compiler_test_project/build_error.cxx
@@ -0,0 +1,5 @@
+int main()
+{
+  int = 3;
+  return;
+}
diff --git a/Tests/CTestTestLaunchers/launcher_custom_command_test_project/CMakeLists.txt b/Tests/CTestTestLaunchers/launcher_custom_command_test_project/CMakeLists.txt
new file mode 100644
index 0000000..b31f587
--- /dev/null
+++ b/Tests/CTestTestLaunchers/launcher_custom_command_test_project/CMakeLists.txt
@@ -0,0 +1,19 @@
+cmake_minimum_required(VERSION 2.8.12)
+
+project(launcher_custom_command_test_project)
+
+include(CTest)
+
+add_custom_command(
+  OUTPUT test1.txt
+  COMMAND ${CMAKE_COMMAND}
+  ARGS -DTESTID=1 -P "${CMAKE_CURRENT_SOURCE_DIR}/command.cmake"
+)
+
+add_custom_command(
+  OUTPUT test2.txt
+  COMMAND ${CMAKE_COMMAND}
+  ARGS -DTESTID=2 -P "${CMAKE_CURRENT_SOURCE_DIR}/command.cmake"
+)
+
+add_custom_target(mytarget ALL DEPENDS test1.txt test2.txt)
diff --git a/Tests/CTestTestLaunchers/launcher_test_project/CTestConfig.cmake b/Tests/CTestTestLaunchers/launcher_custom_command_test_project/CTestConfig.cmake
similarity index 100%
copy from Tests/CTestTestLaunchers/launcher_test_project/CTestConfig.cmake
copy to Tests/CTestTestLaunchers/launcher_custom_command_test_project/CTestConfig.cmake
diff --git a/Tests/CTestTestLaunchers/launcher_test_project/command.cmake b/Tests/CTestTestLaunchers/launcher_custom_command_test_project/command.cmake
similarity index 100%
rename from Tests/CTestTestLaunchers/launcher_test_project/command.cmake
rename to Tests/CTestTestLaunchers/launcher_custom_command_test_project/command.cmake
diff --git a/Tests/CTestTestLaunchers/launcher_linker_test_project/CMakeLists.txt b/Tests/CTestTestLaunchers/launcher_linker_test_project/CMakeLists.txt
new file mode 100644
index 0000000..38980aa
--- /dev/null
+++ b/Tests/CTestTestLaunchers/launcher_linker_test_project/CMakeLists.txt
@@ -0,0 +1,7 @@
+cmake_minimum_required(VERSION 2.8.12)
+
+project(launcher_linker_test_project)
+
+include(CTest)
+
+add_executable(link_error link_error.cxx)
diff --git a/Tests/CTestTestLaunchers/launcher_test_project/CTestConfig.cmake b/Tests/CTestTestLaunchers/launcher_linker_test_project/CTestConfig.cmake
similarity index 100%
rename from Tests/CTestTestLaunchers/launcher_test_project/CTestConfig.cmake
rename to Tests/CTestTestLaunchers/launcher_linker_test_project/CTestConfig.cmake
diff --git a/Tests/CTestTestLaunchers/launcher_linker_test_project/link_error.cxx b/Tests/CTestTestLaunchers/launcher_linker_test_project/link_error.cxx
new file mode 100644
index 0000000..c879be1
--- /dev/null
+++ b/Tests/CTestTestLaunchers/launcher_linker_test_project/link_error.cxx
@@ -0,0 +1,6 @@
+extern int foo();
+
+int main()
+{
+  return foo();
+}
diff --git a/Tests/CTestTestLaunchers/launcher_test_project/CMakeLists.txt b/Tests/CTestTestLaunchers/launcher_test_project/CMakeLists.txt
deleted file mode 100644
index 06c5725..0000000
--- a/Tests/CTestTestLaunchers/launcher_test_project/CMakeLists.txt
+++ /dev/null
@@ -1,19 +0,0 @@
-cmake_minimum_required(VERSION 2.8.12)
-
-project(launcher_test_project)
-
-include(CTest)
-
-add_custom_command(
-  OUTPUT test1.txt
-  COMMAND ${CMAKE_COMMAND}
-  ARGS -DTESTID=1 -P "${CMAKE_CURRENT_SOURCE_DIR}/command.cmake"
-)
-
-add_custom_command(
-  OUTPUT test2.txt
-  COMMAND ${CMAKE_COMMAND}
-  ARGS -DTESTID=2 -P "${CMAKE_CURRENT_SOURCE_DIR}/command.cmake"
-)
-
-add_custom_target(mytarget ALL DEPENDS test1.txt test2.txt)
diff --git a/Tests/CTestTestLaunchers/test.cmake.in b/Tests/CTestTestLaunchers/test.cmake.in
index 03a118a..2db1ddd 100644
--- a/Tests/CTestTestLaunchers/test.cmake.in
+++ b/Tests/CTestTestLaunchers/test.cmake.in
@@ -1,39 +1,51 @@
 cmake_minimum_required(VERSION 2.8.12)
 
-# Settings:
-set(CTEST_DASHBOARD_SOURCE              "@CMake_SOURCE_DIR@/Tests/CTestTestLaunchers")
-set(CTEST_DASHBOARD_ROOT                "@CMake_BINARY_DIR@/Tests/CTestTestLaunchers")
-set(CTEST_SITE                          "@SITE@")
-set(CTEST_BUILD_NAME                    "Launchers- at BUILDNAME@-CTestTestLaunchers")
-
-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}")
-
-ctest_empty_binary_directory(${CTEST_BINARY_DIRECTORY})
-
-file(WRITE "${CTEST_BINARY_DIRECTORY}/CMakeCache.txt" "
-CMAKE_CXX_FLAGS:STRING=@CMAKE_CXX_FLAGS@
-CMAKE_C_FLAGS:STRING=@CMAKE_C_FLAGS@
-CMAKE_C_COMPILER:STRING=@CMAKE_C_COMPILER@
-CMAKE_CXX_COMPILER:STRING=@CMAKE_CXX_COMPILER@
-CMAKE_C_COMPILER_ARG1:STRING=@CMAKE_C_COMPILER_ARG1@
-CMAKE_CXX_COMPILER_ARG1:STRING=@CMAKE_CXX_COMPILER_ARG1@
-")
-
-set(TEST_SUCCESS FALSE)
-
-ctest_start(Experimental)
-ctest_configure(OPTIONS "-DCTEST_USE_LAUNCHERS=1")
-ctest_build(NUMBER_ERRORS error_count)
-
-if("${error_count}" STREQUAL "1")
-  set(TEST_SUCCESS TRUE)
-endif()
+set(TEST_SUCCESS TRUE)
+
+function(run_test_case NAME WHAT)
+  set(_message "Testing that launchers are used when running ${WHAT}")
+  message(STATUS "${_message}...")
+
+  # Settings:
+  set(CTEST_DASHBOARD_SOURCE              "@CMake_SOURCE_DIR@/Tests/CTestTestLaunchers")
+  set(CTEST_DASHBOARD_ROOT                "@CMake_BINARY_DIR@/Tests/CTestTestLaunchers")
+  set(CTEST_SITE                          "@SITE@")
+  set(CTEST_BUILD_NAME                    "Launchers- at BUILDNAME@-CTestTestLaunchers")
+
+  set(CTEST_SOURCE_DIRECTORY              "${CTEST_DASHBOARD_SOURCE}/${NAME}")
+  set(CTEST_BINARY_DIRECTORY              "${CTEST_DASHBOARD_ROOT}/${NAME}-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}")
+
+  ctest_empty_binary_directory(${CTEST_BINARY_DIRECTORY})
+
+  file(WRITE "${CTEST_BINARY_DIRECTORY}/CMakeCache.txt" "
+  CMAKE_CXX_FLAGS:STRING=@CMAKE_CXX_FLAGS@
+  CMAKE_C_FLAGS:STRING=@CMAKE_C_FLAGS@
+  CMAKE_C_COMPILER:STRING=@CMAKE_C_COMPILER@
+  CMAKE_CXX_COMPILER:STRING=@CMAKE_CXX_COMPILER@
+  CMAKE_C_COMPILER_ARG1:STRING=@CMAKE_C_COMPILER_ARG1@
+  CMAKE_CXX_COMPILER_ARG1:STRING=@CMAKE_CXX_COMPILER_ARG1@
+  ")
+
+  ctest_start(Experimental)
+  ctest_configure(OPTIONS "-DCTEST_USE_LAUNCHERS=1")
+  ctest_build(NUMBER_ERRORS error_count)
+
+  if("${error_count}" STREQUAL "0")
+    set(TEST_SUCCESS FALSE PARENT_SCOPE)
+    message(STATUS "${_message}... FAIL")
+  else()
+    message(STATUS "${_message}... PASS")
+  endif()
+endfunction()
+
+run_test_case(launcher_compiler_test_project "the compiler")
+run_test_case(launcher_linker_test_project "the linker")
+run_test_case(launcher_custom_command_test_project "a custom command")
 
 if(TEST_SUCCESS)
   message("CTEST_TEST_LAUNCHER_SUCCESS")
diff --git a/Tests/CTestTestStopTime/GetDate.cmake b/Tests/CTestTestStopTime/GetDate.cmake
index 1f4cb24..46ab2fb 100644
--- a/Tests/CTestTestStopTime/GetDate.cmake
+++ b/Tests/CTestTestStopTime/GetDate.cmake
@@ -49,6 +49,7 @@ macro(GET_DATE)
   # 01/12/2006  08:55:12
   # mm/dd/YYYY HH:MM:SS
   #
+  unset(ENV{SOURCE_DATE_EPOCH})
   string(TIMESTAMP "${GD_PREFIX}OV" "%m/%d/%Y %H:%M:%S")
 
   if(${GD_PREFIX}VERBOSE)
diff --git a/Tests/CompileFeatures/.gitattributes b/Tests/CompileFeatures/.gitattributes
new file mode 100644
index 0000000..83da28d
--- /dev/null
+++ b/Tests/CompileFeatures/.gitattributes
@@ -0,0 +1,2 @@
+# Do not format a source containing C++11 '>>' syntax as C++98.
+cxx_right_angle_brackets.cpp -format.clang-format
diff --git a/Tests/CompileFeatures/CMakeLists.txt b/Tests/CompileFeatures/CMakeLists.txt
index 9f08523..2a307d0 100644
--- a/Tests/CompileFeatures/CMakeLists.txt
+++ b/Tests/CompileFeatures/CMakeLists.txt
@@ -3,14 +3,6 @@ cmake_minimum_required(VERSION 3.1)
 
 project(CompileFeatures)
 
-if (NOT CMAKE_C_COMPILE_FEATURES AND NOT CMAKE_CXX_COMPILE_FEATURES)
-  file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp"
-    "int main(int,char**) { return 0; }\n"
-  )
-  add_executable(CompileFeatures "${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp")
-  return()
-endif()
-
 macro(run_test feature lang)
   if (";${CMAKE_${lang}_COMPILE_FEATURES};" MATCHES ${feature})
     add_library(test_${feature} OBJECT ${feature})
@@ -23,10 +15,12 @@ macro(run_test feature lang)
 endmacro()
 
 get_property(c_features GLOBAL PROPERTY CMAKE_C_KNOWN_FEATURES)
+list(REMOVE_ITEM c_features c_std_90 c_std_99 c_std_11)
 foreach(feature ${c_features})
   run_test(${feature} C)
 endforeach()
 get_property(cxx_features GLOBAL PROPERTY CMAKE_CXX_KNOWN_FEATURES)
+list(REMOVE_ITEM cxx_features cxx_std_98 cxx_std_11 cxx_std_14 cxx_std_17)
 foreach(feature ${cxx_features})
   run_test(${feature} CXX)
 endforeach()
@@ -168,6 +162,15 @@ if (CMAKE_CXX_COMPILER_ID STREQUAL "Intel")
   endif()
 endif()
 
+if (CMAKE_C_COMPILER_ID STREQUAL "Intel")
+  if (CMAKE_C_COMPILER_VERSION VERSION_LESS 15.0.2)
+    # This works on some pre-15.0.2 versions and not others.
+    list(REMOVE_ITEM C_non_features
+      c_static_assert
+      )
+  endif()
+endif()
+
 set(C_ext c)
 set(C_standard_flag 11)
 set(CXX_ext cpp)
@@ -257,13 +260,23 @@ if (CMAKE_CXX_COMPILE_FEATURES)
     if (std_flag_idx EQUAL -1)
       add_executable(default_dialect default_dialect.cpp)
       target_compile_definitions(default_dialect PRIVATE
+        DEFAULT_CXX17=$<EQUAL:${CMAKE_CXX_STANDARD_DEFAULT},17>
         DEFAULT_CXX14=$<EQUAL:${CMAKE_CXX_STANDARD_DEFAULT},14>
         DEFAULT_CXX11=$<EQUAL:${CMAKE_CXX_STANDARD_DEFAULT},11>
         DEFAULT_CXX98=$<EQUAL:${CMAKE_CXX_STANDARD_DEFAULT},98>
       )
     endif()
   endif()
+endif ()
 
+# always add a target "CompileFeatures"
+if (NOT ";${CMAKE_CXX_COMPILE_FEATURES};" MATCHES ";cxx_auto_type;")
+  file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp"
+    "int main(int,char**) { return 0; }\n"
+  )
+  add_executable(CompileFeatures "${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp")
+else()
+  # these tests only work if at least cxx_auto_type is available
   add_executable(CompileFeatures main.cpp)
   set_property(TARGET CompileFeatures
     PROPERTY COMPILE_FEATURES "cxx_auto_type"
@@ -396,7 +409,7 @@ if (CMAKE_CXX_COMPILE_FEATURES)
   )
 
   add_executable(CompileFeaturesGenex2 genex_test.cpp)
-  target_compile_features(CompileFeaturesGenex2 PRIVATE cxx_static_assert)
+  target_compile_features(CompileFeaturesGenex2 PRIVATE cxx_std_11)
   target_compile_definitions(CompileFeaturesGenex2 PRIVATE
     HAVE_OVERRIDE_CONTROL=$<COMPILE_FEATURES:cxx_final,cxx_override>
     HAVE_AUTO_TYPE=$<COMPILE_FEATURES:cxx_auto_type>
@@ -405,10 +418,10 @@ if (CMAKE_CXX_COMPILE_FEATURES)
     HAVE_INHERITING_CONSTRUCTORS_AND_FINAL=$<COMPILE_FEATURES:cxx_inheriting_constructors,cxx_final>
   )
 
-  add_library(static_assert_iface INTERFACE)
-  target_compile_features(static_assert_iface INTERFACE cxx_static_assert)
+  add_library(std_11_iface INTERFACE)
+  target_compile_features(std_11_iface INTERFACE cxx_std_11)
   add_executable(CompileFeaturesGenex3 genex_test.cpp)
-  target_link_libraries(CompileFeaturesGenex3 PRIVATE static_assert_iface)
+  target_link_libraries(CompileFeaturesGenex3 PRIVATE std_11_iface)
   target_compile_definitions(CompileFeaturesGenex3 PRIVATE
     HAVE_OVERRIDE_CONTROL=$<COMPILE_FEATURES:cxx_final,cxx_override>
     HAVE_AUTO_TYPE=$<COMPILE_FEATURES:cxx_auto_type>
diff --git a/Tests/CompileFeatures/cxx_right_angle_brackets.cpp b/Tests/CompileFeatures/cxx_right_angle_brackets.cpp
index 8f1b0ee..4d494b5 100644
--- a/Tests/CompileFeatures/cxx_right_angle_brackets.cpp
+++ b/Tests/CompileFeatures/cxx_right_angle_brackets.cpp
@@ -7,6 +7,8 @@ struct A
 
 void someFunc()
 {
-  A<A<int> > object;
+  /* clang-format off */
+  A<A<int>> object;
+  /* clang-format on */
   (void)object;
 }
diff --git a/Tests/CompileFeatures/default_dialect.cpp b/Tests/CompileFeatures/default_dialect.cpp
index 0efaefa..9b65b42 100644
--- a/Tests/CompileFeatures/default_dialect.cpp
+++ b/Tests/CompileFeatures/default_dialect.cpp
@@ -2,7 +2,11 @@
 template <long l>
 struct Outputter;
 
-#if DEFAULT_CXX14
+#if DEFAULT_CXX17
+#if __cplusplus <= 201402L
+Outputter<__cplusplus> o;
+#endif
+#elif DEFAULT_CXX14
 #if __cplusplus != 201402L
 Outputter<__cplusplus> o;
 #endif
diff --git a/Tests/Cuda/.clang-format b/Tests/Cuda/.clang-format
new file mode 100644
index 0000000..a77589a
--- /dev/null
+++ b/Tests/Cuda/.clang-format
@@ -0,0 +1,9 @@
+---
+# This configuration requires clang-format 3.8 or higher.
+BasedOnStyle: Mozilla
+AlignOperands: false
+AlwaysBreakAfterReturnType: None
+AlwaysBreakAfterDefinitionReturnType: None
+ColumnLimit: 79
+Standard: Cpp11
+...
diff --git a/Tests/Cuda/CMakeLists.txt b/Tests/Cuda/CMakeLists.txt
new file mode 100644
index 0000000..de48501
--- /dev/null
+++ b/Tests/Cuda/CMakeLists.txt
@@ -0,0 +1,7 @@
+
+ADD_TEST_MACRO(Cuda.Complex CudaComplex)
+ADD_TEST_MACRO(Cuda.ConsumeCompileFeatures CudaConsumeCompileFeatures)
+ADD_TEST_MACRO(Cuda.ObjectLibrary CudaObjectLibrary)
+ADD_TEST_MACRO(Cuda.ToolkitInclude CudaToolkitInclude)
+ADD_TEST_MACRO(Cuda.ProperLinkFlags ProperLinkFlags)
+ADD_TEST_MACRO(Cuda.WithC CudaWithC)
diff --git a/Tests/Cuda/Complex/CMakeLists.txt b/Tests/Cuda/Complex/CMakeLists.txt
new file mode 100644
index 0000000..bff7d07
--- /dev/null
+++ b/Tests/Cuda/Complex/CMakeLists.txt
@@ -0,0 +1,40 @@
+
+cmake_minimum_required(VERSION 3.7)
+project (CudaComplex CXX CUDA)
+#Goal for this example:
+
+#build a cpp dynamic library base
+#build a cuda static library base that uses separable compilation
+
+#build a cuda dynamic library that uses the first dynamic library
+#build a mixed cpp & cuda dynamic library uses all 3 previous libraries
+
+#lastly build a cpp executable that uses this last cuda dynamic library
+
+#this tests that we can properly handle linking cuda and cpp together
+#and also bulding cpp targets that need cuda implicit libraries
+
+#verify that we can pass explicit cuda arch flags
+string(APPEND CMAKE_CUDA_FLAGS " -gencode arch=compute_30,code=compute_30")
+set(CMAKE_CUDA_STANDARD 11)
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CUDA_STANDARD_REQUIRED TRUE)
+set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
+
+add_library(CudaComplexCppBase SHARED dynamic.cpp)
+add_library(CudaComplexSeperableLib STATIC file1.cu file2.cu file3.cu)
+set_target_properties(CudaComplexSeperableLib
+                       PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
+set_target_properties( CudaComplexSeperableLib
+                       PROPERTIES POSITION_INDEPENDENT_CODE ON)
+
+add_library(CudaComplexSharedLib SHARED dynamic.cu)
+target_link_libraries(CudaComplexSharedLib PUBLIC CudaComplexCppBase)
+
+add_library(CudaComplexMixedLib SHARED mixed.cpp mixed.cu)
+target_link_libraries(CudaComplexMixedLib
+                      PUBLIC CudaComplexSharedLib
+                      PRIVATE CudaComplexSeperableLib)
+
+add_executable(CudaComplex main.cpp)
+target_link_libraries(CudaComplex PUBLIC CudaComplexMixedLib)
diff --git a/Tests/Cuda/Complex/dynamic.cpp b/Tests/Cuda/Complex/dynamic.cpp
new file mode 100644
index 0000000..3848ce7
--- /dev/null
+++ b/Tests/Cuda/Complex/dynamic.cpp
@@ -0,0 +1,11 @@
+
+#ifdef _WIN32
+#define EXPORT __declspec(dllexport)
+#else
+#define EXPORT
+#endif
+
+EXPORT int dynamic_base_func(int x)
+{
+  return x * x;
+}
diff --git a/Tests/Cuda/Complex/dynamic.cu b/Tests/Cuda/Complex/dynamic.cu
new file mode 100644
index 0000000..82255c5
--- /dev/null
+++ b/Tests/Cuda/Complex/dynamic.cu
@@ -0,0 +1,30 @@
+
+#include <cuda.h>
+#include <iostream>
+#include <string>
+
+#ifdef _WIN32
+#define EXPORT __declspec(dllexport)
+#else
+#define EXPORT
+#endif
+
+int dynamic_base_func(int);
+
+EXPORT int __host__ cuda_dynamic_host_func(int x)
+{
+  return dynamic_base_func(x);
+}
+
+static __global__ void DetermineIfValidCudaDevice()
+{
+}
+
+EXPORT void cuda_dynamic_lib_func()
+{
+  DetermineIfValidCudaDevice<<<1, 1>>>();
+  cudaError_t err = cudaGetLastError();
+  if (err == cudaSuccess) {
+    std::cerr << cudaGetErrorString(err) << std::endl;
+  }
+}
diff --git a/Tests/Cuda/Complex/file1.cu b/Tests/Cuda/Complex/file1.cu
new file mode 100644
index 0000000..1ce63bf
--- /dev/null
+++ b/Tests/Cuda/Complex/file1.cu
@@ -0,0 +1,10 @@
+
+#include "file1.h"
+
+result_type __device__ file1_func(int x)
+{
+  result_type r;
+  r.input = x;
+  r.sum = x * x;
+  return r;
+}
diff --git a/Tests/Cuda/Complex/file1.h b/Tests/Cuda/Complex/file1.h
new file mode 100644
index 0000000..ff1945c
--- /dev/null
+++ b/Tests/Cuda/Complex/file1.h
@@ -0,0 +1,7 @@
+
+#pragma once
+struct result_type
+{
+  int input;
+  int sum;
+};
diff --git a/Tests/Cuda/Complex/file2.cu b/Tests/Cuda/Complex/file2.cu
new file mode 100644
index 0000000..74f3558
--- /dev/null
+++ b/Tests/Cuda/Complex/file2.cu
@@ -0,0 +1,16 @@
+
+#include "file2.h"
+
+result_type __device__ file1_func(int x);
+
+result_type_dynamic __device__ file2_func(int x)
+{
+  if (x != 42) {
+    const result_type r = file1_func(x);
+    const result_type_dynamic rd{ r.input, r.sum, true };
+    return rd;
+  } else {
+    const result_type_dynamic rd{ x, x * x * x, false };
+    return rd;
+  }
+}
diff --git a/Tests/Cuda/Complex/file2.h b/Tests/Cuda/Complex/file2.h
new file mode 100644
index 0000000..d2dbaa4
--- /dev/null
+++ b/Tests/Cuda/Complex/file2.h
@@ -0,0 +1,10 @@
+
+#pragma once
+#include "file1.h"
+
+struct result_type_dynamic
+{
+  int input;
+  int sum;
+  bool from_static;
+};
diff --git a/Tests/Cuda/Complex/file3.cu b/Tests/Cuda/Complex/file3.cu
new file mode 100644
index 0000000..7c37d66
--- /dev/null
+++ b/Tests/Cuda/Complex/file3.cu
@@ -0,0 +1,26 @@
+
+#include <iostream>
+
+#include "file1.h"
+#include "file2.h"
+
+result_type __device__ file1_func(int x);
+result_type_dynamic __device__ file2_func(int x);
+
+static __global__ void file3_kernel(result_type& r, int x)
+{
+  r = file1_func(x);
+  result_type_dynamic rd = file2_func(x);
+}
+
+int file3_launch_kernel(int x)
+{
+  result_type r;
+  file3_kernel<<<1, 1>>>(r, x);
+  cudaError_t err = cudaGetLastError();
+  if (err == cudaSuccess) {
+    std::cerr << cudaGetErrorString(err) << std::endl;
+    return x;
+  }
+  return r.sum;
+}
diff --git a/Tests/Cuda/Complex/main.cpp b/Tests/Cuda/Complex/main.cpp
new file mode 100644
index 0000000..5a3f820
--- /dev/null
+++ b/Tests/Cuda/Complex/main.cpp
@@ -0,0 +1,20 @@
+#include <iostream>
+
+#include "file1.h"
+#include "file2.h"
+
+#ifdef _WIN32
+#define IMPORT __declspec(dllimport)
+#else
+#define IMPORT
+#endif
+
+IMPORT int call_cuda_seperable_code(int x);
+IMPORT int mixed_launch_kernel(int x);
+
+int main(int argc, char** argv)
+{
+  call_cuda_seperable_code(42);
+  mixed_launch_kernel(42);
+  return 0;
+}
diff --git a/Tests/Cuda/Complex/mixed.cpp b/Tests/Cuda/Complex/mixed.cpp
new file mode 100644
index 0000000..bd32e51
--- /dev/null
+++ b/Tests/Cuda/Complex/mixed.cpp
@@ -0,0 +1,22 @@
+
+#ifdef _WIN32
+#define EXPORT __declspec(dllexport)
+#define IMPORT __declspec(dllimport)
+#else
+#define EXPORT
+#define IMPORT
+#endif
+
+int dynamic_base_func(int);
+IMPORT int cuda_dynamic_host_func(int);
+int file3_launch_kernel(int);
+
+int dynamic_final_func(int x)
+{
+  return cuda_dynamic_host_func(dynamic_base_func(x));
+}
+
+EXPORT int call_cuda_seperable_code(int x)
+{
+  return file3_launch_kernel(x);
+}
diff --git a/Tests/Cuda/Complex/mixed.cu b/Tests/Cuda/Complex/mixed.cu
new file mode 100644
index 0000000..4bba07c
--- /dev/null
+++ b/Tests/Cuda/Complex/mixed.cu
@@ -0,0 +1,33 @@
+
+#include <iostream>
+
+#include "file1.h"
+#include "file2.h"
+
+#ifdef _WIN32
+#define EXPORT __declspec(dllexport)
+#define IMPORT __declspec(dllimport)
+#else
+#define EXPORT
+#define IMPORT
+#endif
+
+result_type __device__ file1_func(int x);
+result_type_dynamic __device__ file2_func(int x);
+
+IMPORT void __host__ cuda_dynamic_lib_func();
+
+static __global__ void mixed_kernel(result_type& r, int x)
+{
+  r = file1_func(x);
+  result_type_dynamic rd = file2_func(x);
+}
+
+EXPORT int mixed_launch_kernel(int x)
+{
+  cuda_dynamic_lib_func();
+
+  result_type r;
+  mixed_kernel<<<1, 1>>>(r, x);
+  return r.sum;
+}
diff --git a/Tests/Cuda/ConsumeCompileFeatures/CMakeLists.txt b/Tests/Cuda/ConsumeCompileFeatures/CMakeLists.txt
new file mode 100644
index 0000000..9fda2d0
--- /dev/null
+++ b/Tests/Cuda/ConsumeCompileFeatures/CMakeLists.txt
@@ -0,0 +1,17 @@
+
+cmake_minimum_required(VERSION 3.7)
+project (CudaConsumeCompileFeatures CXX CUDA)
+#Goal for this example:
+
+#build a c++11 library that express a c++11 public compile feature
+#link a cuda library and verify it builds with c++11 enabled
+
+#build a standalone c++/cuda mixed executable where we express a c++11
+#compile feature.
+
+
+add_library(CudaConsumeLib STATIC static.cpp static.cu)
+target_compile_features(CudaConsumeLib PUBLIC cxx_nullptr)
+
+add_executable(CudaConsumeCompileFeatures main.cu)
+target_link_libraries(CudaConsumeCompileFeatures PRIVATE CudaConsumeLib)
diff --git a/Tests/Cuda/ConsumeCompileFeatures/main.cu b/Tests/Cuda/ConsumeCompileFeatures/main.cu
new file mode 100644
index 0000000..bc32450
--- /dev/null
+++ b/Tests/Cuda/ConsumeCompileFeatures/main.cu
@@ -0,0 +1,20 @@
+
+#include <iostream>
+
+int static_cxx11_func(int);
+
+void test_functions()
+{
+  auto x = static_cxx11_func(int(42));
+  std::cout << x << std::endl;
+}
+
+int main(int argc, char** argv)
+{
+  test_functions();
+  std::cout
+    << "this executable doesn't use cuda code, just call methods defined"
+    << std::endl;
+  std::cout << "in libraries that have cuda code" << std::endl;
+  return 0;
+}
diff --git a/Tests/Cuda/ConsumeCompileFeatures/static.cpp b/Tests/Cuda/ConsumeCompileFeatures/static.cpp
new file mode 100644
index 0000000..565d52e
--- /dev/null
+++ b/Tests/Cuda/ConsumeCompileFeatures/static.cpp
@@ -0,0 +1,10 @@
+
+
+#include <type_traits>
+
+int static_cuda11_func(int);
+
+int static_cxx11_func(int x)
+{
+  return static_cuda11_func(x) + std::integral_constant<int, 32>::value;
+}
diff --git a/Tests/Cuda/ConsumeCompileFeatures/static.cu b/Tests/Cuda/ConsumeCompileFeatures/static.cu
new file mode 100644
index 0000000..73e43a8
--- /dev/null
+++ b/Tests/Cuda/ConsumeCompileFeatures/static.cu
@@ -0,0 +1,9 @@
+
+#include <type_traits>
+
+using tt = std::true_type;
+using ft = std::false_type;
+int __host__ static_cuda11_func(int x)
+{
+  return x * x + std::integral_constant<int, 17>::value;
+}
diff --git a/Tests/Cuda/ObjectLibrary/CMakeLists.txt b/Tests/Cuda/ObjectLibrary/CMakeLists.txt
new file mode 100644
index 0000000..cbe1e67
--- /dev/null
+++ b/Tests/Cuda/ObjectLibrary/CMakeLists.txt
@@ -0,0 +1,12 @@
+cmake_minimum_required(VERSION 3.7)
+project (CudaObjectLibrary CUDA CXX)
+#Goal for this example:
+
+#build a object files some with cuda and some without than
+#embed these into an executable
+
+add_library(CudaMixedObjectLib OBJECT static.cu static.cpp)
+
+add_executable(CudaObjectLibrary
+               main.cpp
+               $<TARGET_OBJECTS:CudaMixedObjectLib>)
diff --git a/Tests/Cuda/ObjectLibrary/main.cpp b/Tests/Cuda/ObjectLibrary/main.cpp
new file mode 100644
index 0000000..1a70a99
--- /dev/null
+++ b/Tests/Cuda/ObjectLibrary/main.cpp
@@ -0,0 +1,20 @@
+
+#include <iostream>
+
+int static_func(int);
+int file1_sq_func(int);
+
+void test_functions()
+{
+  file1_sq_func(static_func(42));
+}
+
+int main(int argc, char** argv)
+{
+  test_functions();
+  std::cout
+    << "this executable doesn't use cuda code, just call methods defined"
+    << std::endl;
+  std::cout << "in object files that have cuda code" << std::endl;
+  return 0;
+}
diff --git a/Tests/Cuda/ObjectLibrary/static.cpp b/Tests/Cuda/ObjectLibrary/static.cpp
new file mode 100644
index 0000000..6db1f91
--- /dev/null
+++ b/Tests/Cuda/ObjectLibrary/static.cpp
@@ -0,0 +1,6 @@
+int file1_sq_func(int);
+
+int static_func(int x)
+{
+  return file1_sq_func(x);
+}
diff --git a/Tests/Cuda/ObjectLibrary/static.cu b/Tests/Cuda/ObjectLibrary/static.cu
new file mode 100644
index 0000000..cdf682b
--- /dev/null
+++ b/Tests/Cuda/ObjectLibrary/static.cu
@@ -0,0 +1,21 @@
+
+#include <cuda.h>
+#include <cuda_runtime.h>
+#include <iostream>
+
+int __host__ file1_sq_func(int x)
+{
+  cudaError_t err;
+  int nDevices = 0;
+  err = cudaGetDeviceCount(&nDevices);
+  if (err != cudaSuccess) {
+    std::cout << "nDevices: " << nDevices << std::endl;
+    std::cout << "err: " << err << std::endl;
+    return 1;
+  }
+  std::cout << "this library uses cuda code" << std::endl;
+  std::cout << "you have " << nDevices << " devices that support cuda"
+            << std::endl;
+
+  return x * x;
+}
diff --git a/Tests/Cuda/ProperLinkFlags/CMakeLists.txt b/Tests/Cuda/ProperLinkFlags/CMakeLists.txt
new file mode 100644
index 0000000..b6e0e39
--- /dev/null
+++ b/Tests/Cuda/ProperLinkFlags/CMakeLists.txt
@@ -0,0 +1,20 @@
+
+cmake_minimum_required(VERSION 3.7)
+project (ProperLinkFlags CUDA CXX)
+
+#Goal for this example:
+#Verify that when we have CXX and CUDA enabled and we link an executable that
+#has CUDA and CXX we use the CUDA link flags when doing the device link
+#step
+
+#Specify a set of valid CUDA flags and an invalid set of CXX flags ( for CUDA )
+#to make sure we don't use the CXX flags when linking CUDA executables
+string(APPEND CMAKE_CUDA_FLAGS " -arch=sm_35 --use_fast_math")
+set(CMAKE_CXX_FLAGS "-Wall")
+
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CUDA_STANDARD 11)
+add_executable(ProperLinkFlags file1.cu main.cxx)
+
+set_target_properties( ProperLinkFlags
+                       PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
diff --git a/Tests/Cuda/ProperLinkFlags/file1.cu b/Tests/Cuda/ProperLinkFlags/file1.cu
new file mode 100644
index 0000000..9a105f0
--- /dev/null
+++ b/Tests/Cuda/ProperLinkFlags/file1.cu
@@ -0,0 +1,11 @@
+
+#include "file1.h"
+
+result_type __device__ file1_func(int x)
+{
+  __ldg(&x);
+  result_type r;
+  r.input = x;
+  r.sum = x * x;
+  return r;
+}
diff --git a/Tests/Cuda/ProperLinkFlags/file1.h b/Tests/Cuda/ProperLinkFlags/file1.h
new file mode 100644
index 0000000..ff1945c
--- /dev/null
+++ b/Tests/Cuda/ProperLinkFlags/file1.h
@@ -0,0 +1,7 @@
+
+#pragma once
+struct result_type
+{
+  int input;
+  int sum;
+};
diff --git a/Tests/Cuda/ProperLinkFlags/main.cxx b/Tests/Cuda/ProperLinkFlags/main.cxx
new file mode 100644
index 0000000..7c0ee9e
--- /dev/null
+++ b/Tests/Cuda/ProperLinkFlags/main.cxx
@@ -0,0 +1,9 @@
+
+#include <iostream>
+
+#include "file1.h"
+
+int main(int argc, char** argv)
+{
+  return 0;
+}
diff --git a/Tests/Cuda/ToolkitInclude/CMakeLists.txt b/Tests/Cuda/ToolkitInclude/CMakeLists.txt
new file mode 100644
index 0000000..f246b54
--- /dev/null
+++ b/Tests/Cuda/ToolkitInclude/CMakeLists.txt
@@ -0,0 +1,11 @@
+cmake_minimum_required(VERSION 3.8)
+project (ToolkitInclude CXX CUDA)
+
+#Goal for this example:
+# Validate that between the CXX implicit include directories and the
+# CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES directories we can find
+# the cuda runtime headers
+
+add_executable(CudaToolkitInclude main.cpp)
+target_include_directories(CudaToolkitInclude PRIVATE
+                           ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})
diff --git a/Tests/Cuda/ToolkitInclude/main.cpp b/Tests/Cuda/ToolkitInclude/main.cpp
new file mode 100644
index 0000000..c8d5c6b
--- /dev/null
+++ b/Tests/Cuda/ToolkitInclude/main.cpp
@@ -0,0 +1,8 @@
+// Only thing we care about is that these headers are found
+#include <cuda.h>
+#include <cuda_runtime_api.h>
+
+int main()
+{
+  return 0;
+}
diff --git a/Tests/Cuda/WithC/CMakeLists.txt b/Tests/Cuda/WithC/CMakeLists.txt
new file mode 100644
index 0000000..1f25ab4
--- /dev/null
+++ b/Tests/Cuda/WithC/CMakeLists.txt
@@ -0,0 +1,12 @@
+cmake_minimum_required(VERSION 3.7)
+project(CudaComplex CUDA C)
+
+string(APPEND CMAKE_CUDA_FLAGS " -gencode arch=compute_30,code=compute_30")
+
+add_executable(CudaWithC main.c cuda.cu)
+
+if(APPLE)
+  # We need to add the default path to the driver (libcuda.dylib) as an rpath, so that
+  # the static cuda runtime can find it at runtime.
+  target_link_libraries(CudaWithC PRIVATE -Wl,-rpath,/usr/local/cuda/lib)
+endif()
diff --git a/Tests/Cuda/WithC/cuda.cu b/Tests/Cuda/WithC/cuda.cu
new file mode 100644
index 0000000..06bd7b9
--- /dev/null
+++ b/Tests/Cuda/WithC/cuda.cu
@@ -0,0 +1,16 @@
+#include <cuda.h>
+
+#include <iostream>
+
+extern "C" int use_cuda(void)
+{
+  int nDevices = 0;
+  cudaError_t err = cudaGetDeviceCount(&nDevices);
+  if (err != cudaSuccess) {
+    std::cerr << "Failed to retrieve the number of CUDA enabled devices"
+              << std::endl;
+    return 1;
+  }
+  std::cout << "Found " << nDevices << " CUDA enabled devices" << std::endl;
+  return 0;
+}
diff --git a/Tests/Cuda/WithC/main.c b/Tests/Cuda/WithC/main.c
new file mode 100644
index 0000000..cb5fddc
--- /dev/null
+++ b/Tests/Cuda/WithC/main.c
@@ -0,0 +1,14 @@
+extern int use_cuda(void);
+
+#ifdef _WIN32
+#include <windows.h>
+#endif
+
+int main()
+{
+#ifdef _WIN32
+  /* Use an API that requires CMake's "standard" C libraries.  */
+  GetOpenFileName(NULL);
+#endif
+  return use_cuda();
+}
diff --git a/Tests/CudaOnly/.clang-format b/Tests/CudaOnly/.clang-format
new file mode 100644
index 0000000..a77589a
--- /dev/null
+++ b/Tests/CudaOnly/.clang-format
@@ -0,0 +1,9 @@
+---
+# This configuration requires clang-format 3.8 or higher.
+BasedOnStyle: Mozilla
+AlignOperands: false
+AlwaysBreakAfterReturnType: None
+AlwaysBreakAfterDefinitionReturnType: None
+ColumnLimit: 79
+Standard: Cpp11
+...
diff --git a/Tests/CudaOnly/CMakeLists.txt b/Tests/CudaOnly/CMakeLists.txt
new file mode 100644
index 0000000..85a2051
--- /dev/null
+++ b/Tests/CudaOnly/CMakeLists.txt
@@ -0,0 +1,4 @@
+
+ADD_TEST_MACRO(CudaOnly.EnableStandard CudaOnlyEnableStandard)
+ADD_TEST_MACRO(CudaOnly.SeparateCompilation CudaOnlySeparateCompilation)
+ADD_TEST_MACRO(CudaOnly.WithDefs CudaOnlyWithDefs)
diff --git a/Tests/CudaOnly/EnableStandard/CMakeLists.txt b/Tests/CudaOnly/EnableStandard/CMakeLists.txt
new file mode 100644
index 0000000..35a1deb
--- /dev/null
+++ b/Tests/CudaOnly/EnableStandard/CMakeLists.txt
@@ -0,0 +1,26 @@
+
+cmake_minimum_required(VERSION 3.7)
+project (CudaOnlyEnableStandard CUDA)
+
+#Goal for this example:
+#build cuda sources that require C++11 to be enabled.
+
+add_library(CUDAStatic11 STATIC static.cu)
+add_library(CUDADynamic11 SHARED shared.cu)
+
+add_executable(CudaOnlyEnableStandard main.cu)
+target_link_libraries(CudaOnlyEnableStandard PRIVATE CUDAStatic11 CUDADynamic11)
+
+set_target_properties(CUDAStatic11 CUDADynamic11 PROPERTIES CUDA_STANDARD 11)
+set_target_properties(CUDAStatic11 CUDADynamic11 PROPERTIES CUDA_STANDARD_REQUIRED TRUE)
+
+#Verify CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES
+foreach(dir ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})
+  if(NOT IS_DIRECTORY "${dir}")
+    message(FATAL_ERROR
+      "CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES entry\n"
+      " ${dir}\n"
+      "is not an existing directory."
+      )
+  endif()
+endforeach()
diff --git a/Tests/CudaOnly/EnableStandard/main.cu b/Tests/CudaOnly/EnableStandard/main.cu
new file mode 100644
index 0000000..f219583
--- /dev/null
+++ b/Tests/CudaOnly/EnableStandard/main.cu
@@ -0,0 +1,23 @@
+
+#include <iostream>
+
+#ifdef _WIN32
+#define IMPORT __declspec(dllimport)
+#else
+#define IMPORT
+#endif
+
+int static_cuda11_func(int);
+IMPORT int shared_cuda11_func(int);
+
+void test_functions()
+{
+  static_cuda11_func(int(42));
+  shared_cuda11_func(int(42));
+}
+
+int main(int argc, char** argv)
+{
+  test_functions();
+  return 0;
+}
diff --git a/Tests/CudaOnly/EnableStandard/shared.cu b/Tests/CudaOnly/EnableStandard/shared.cu
new file mode 100644
index 0000000..ccdd0b2
--- /dev/null
+++ b/Tests/CudaOnly/EnableStandard/shared.cu
@@ -0,0 +1,15 @@
+
+#include <type_traits>
+
+#ifdef _WIN32
+#define EXPORT __declspec(dllexport)
+#else
+#define EXPORT
+#endif
+
+using tt = std::true_type;
+using ft = std::false_type;
+EXPORT int __host__ shared_cuda11_func(int x)
+{
+  return x * x + std::integral_constant<int, 17>::value;
+}
diff --git a/Tests/CudaOnly/EnableStandard/static.cu b/Tests/CudaOnly/EnableStandard/static.cu
new file mode 100644
index 0000000..73e43a8
--- /dev/null
+++ b/Tests/CudaOnly/EnableStandard/static.cu
@@ -0,0 +1,9 @@
+
+#include <type_traits>
+
+using tt = std::true_type;
+using ft = std::false_type;
+int __host__ static_cuda11_func(int x)
+{
+  return x * x + std::integral_constant<int, 17>::value;
+}
diff --git a/Tests/CudaOnly/SeparateCompilation/CMakeLists.txt b/Tests/CudaOnly/SeparateCompilation/CMakeLists.txt
new file mode 100644
index 0000000..d134b96
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/CMakeLists.txt
@@ -0,0 +1,33 @@
+
+cmake_minimum_required(VERSION 3.7)
+project (CudaOnlySeparateCompilation CUDA)
+
+#Goal for this example:
+#Build a static library that defines multiple methods and kernels that
+#use each other.
+#After that confirm that we can call those methods from dynamic libraries
+#and executables.
+#We complicate the matter by also testing that multiple static libraries
+#all containing cuda separable compilation code links properly
+string(APPEND CMAKE_CUDA_FLAGS " -gencode arch=compute_30,code=compute_30")
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CUDA_STANDARD 11)
+add_library(CUDASerarateLibA STATIC file1.cu file2.cu file3.cu)
+
+#Having file4/file5 in a shared library causes serious problems
+#with the nvcc linker and it will generate bad entries that will
+#cause a segv when trying to run the executable
+#
+add_library(CUDASerarateLibB STATIC file4.cu file5.cu)
+target_link_libraries(CUDASerarateLibB PRIVATE CUDASerarateLibA)
+
+add_executable(CudaOnlySeparateCompilation main.cu)
+target_link_libraries(CudaOnlySeparateCompilation PRIVATE CUDASerarateLibB)
+
+set_target_properties( CUDASerarateLibA
+                       CUDASerarateLibB
+                       PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
+
+set_target_properties( CUDASerarateLibA
+                       CUDASerarateLibB
+                       PROPERTIES POSITION_INDEPENDENT_CODE ON)
diff --git a/Tests/CudaOnly/SeparateCompilation/file1.cu b/Tests/CudaOnly/SeparateCompilation/file1.cu
new file mode 100644
index 0000000..1ce63bf
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/file1.cu
@@ -0,0 +1,10 @@
+
+#include "file1.h"
+
+result_type __device__ file1_func(int x)
+{
+  result_type r;
+  r.input = x;
+  r.sum = x * x;
+  return r;
+}
diff --git a/Tests/CudaOnly/SeparateCompilation/file1.h b/Tests/CudaOnly/SeparateCompilation/file1.h
new file mode 100644
index 0000000..ff1945c
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/file1.h
@@ -0,0 +1,7 @@
+
+#pragma once
+struct result_type
+{
+  int input;
+  int sum;
+};
diff --git a/Tests/CudaOnly/SeparateCompilation/file2.cu b/Tests/CudaOnly/SeparateCompilation/file2.cu
new file mode 100644
index 0000000..74f3558
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/file2.cu
@@ -0,0 +1,16 @@
+
+#include "file2.h"
+
+result_type __device__ file1_func(int x);
+
+result_type_dynamic __device__ file2_func(int x)
+{
+  if (x != 42) {
+    const result_type r = file1_func(x);
+    const result_type_dynamic rd{ r.input, r.sum, true };
+    return rd;
+  } else {
+    const result_type_dynamic rd{ x, x * x * x, false };
+    return rd;
+  }
+}
diff --git a/Tests/CudaOnly/SeparateCompilation/file2.h b/Tests/CudaOnly/SeparateCompilation/file2.h
new file mode 100644
index 0000000..d2dbaa4
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/file2.h
@@ -0,0 +1,10 @@
+
+#pragma once
+#include "file1.h"
+
+struct result_type_dynamic
+{
+  int input;
+  int sum;
+  bool from_static;
+};
diff --git a/Tests/CudaOnly/SeparateCompilation/file3.cu b/Tests/CudaOnly/SeparateCompilation/file3.cu
new file mode 100644
index 0000000..155b513
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/file3.cu
@@ -0,0 +1,22 @@
+
+
+#include "file1.h"
+#include "file2.h"
+
+result_type __device__ file1_func(int x);
+result_type_dynamic __device__ file2_func(int x);
+
+static __global__ void file3_kernel(result_type& r, int x)
+{
+  // call static_func which is a method that is defined in the
+  // static library that is always out of date
+  r = file1_func(x);
+  result_type_dynamic rd = file2_func(x);
+}
+
+result_type file3_launch_kernel(int x)
+{
+  result_type r;
+  file3_kernel<<<1, 1>>>(r, x);
+  return r;
+}
diff --git a/Tests/CudaOnly/SeparateCompilation/file4.cu b/Tests/CudaOnly/SeparateCompilation/file4.cu
new file mode 100644
index 0000000..2e3e01e
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/file4.cu
@@ -0,0 +1,23 @@
+
+#include <iostream>
+
+#include "file1.h"
+#include "file2.h"
+
+result_type __device__ file1_func(int x);
+result_type_dynamic __device__ file2_func(int x);
+
+static __global__ void file4_kernel(result_type& r, int x)
+{
+  // call static_func which is a method that is defined in the
+  // static library that is always out of date
+  r = file1_func(x);
+  result_type_dynamic rd = file2_func(x);
+}
+
+int file4_launch_kernel(int x)
+{
+  result_type r;
+  file4_kernel<<<1, 1>>>(r, x);
+  return r.sum;
+}
diff --git a/Tests/CudaOnly/SeparateCompilation/file5.cu b/Tests/CudaOnly/SeparateCompilation/file5.cu
new file mode 100644
index 0000000..fee8e9e
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/file5.cu
@@ -0,0 +1,23 @@
+
+#include <iostream>
+
+#include "file1.h"
+#include "file2.h"
+
+result_type __device__ file1_func(int x);
+result_type_dynamic __device__ file2_func(int x);
+
+static __global__ void file5_kernel(result_type& r, int x)
+{
+  // call static_func which is a method that is defined in the
+  // static library that is always out of date
+  r = file1_func(x);
+  result_type_dynamic rd = file2_func(x);
+}
+
+int file5_launch_kernel(int x)
+{
+  result_type r;
+  file5_kernel<<<1, 1>>>(r, x);
+  return r.sum;
+}
diff --git a/Tests/CudaOnly/SeparateCompilation/main.cu b/Tests/CudaOnly/SeparateCompilation/main.cu
new file mode 100644
index 0000000..03e0921
--- /dev/null
+++ b/Tests/CudaOnly/SeparateCompilation/main.cu
@@ -0,0 +1,15 @@
+
+#include <iostream>
+
+#include "file1.h"
+#include "file2.h"
+
+int file4_launch_kernel(int x);
+int file5_launch_kernel(int x);
+
+int main(int argc, char** argv)
+{
+  file4_launch_kernel(42);
+  file5_launch_kernel(42);
+  return 0;
+}
diff --git a/Tests/CudaOnly/WithDefs/CMakeLists.txt b/Tests/CudaOnly/WithDefs/CMakeLists.txt
new file mode 100644
index 0000000..2646d29
--- /dev/null
+++ b/Tests/CudaOnly/WithDefs/CMakeLists.txt
@@ -0,0 +1,36 @@
+
+cmake_minimum_required(VERSION 3.7)
+project (CudaOnlyWithDefs CUDA)
+
+#verify that we can pass explicit cuda arch flags
+string(APPEND CMAKE_CUDA_FLAGS " -gencode arch=compute_30,code=compute_30")
+set(debug_compile_flags --generate-code arch=compute_20,code=sm_20)
+if(CMAKE_CUDA_SIMULATE_ID STREQUAL "MSVC")
+  list(APPEND debug_compile_flags -Xcompiler=-WX)
+else()
+  list(APPEND debug_compile_flags -Xcompiler=-Werror)
+endif()
+set(release_compile_defs DEFREL)
+
+#Goal for this example:
+#build a executable that needs to be passed a complex define through add_defintions
+#this verifies we can pass things such as '_','(' to nvcc
+add_definitions("-DPACKED_DEFINE=__attribute__((packed))")
+set_source_files_properties(main.notcu PROPERTIES LANGUAGE CUDA)
+add_executable(CudaOnlyWithDefs main.notcu)
+
+target_compile_options(CudaOnlyWithDefs
+  PRIVATE
+    $<$<CONFIG:DEBUG>:$<BUILD_INTERFACE:${debug_compile_flags}>>
+  )
+
+target_compile_definitions(CudaOnlyWithDefs
+  PRIVATE
+    $<$<CONFIG:RELEASE>:$<BUILD_INTERFACE:${release_compile_defs}>>
+  )
+
+#we need to add an rpath for the cuda library so that everything
+#loads properly on the mac
+if(CMAKE_SYSTEM_NAME MATCHES "Darwin")
+  set_target_properties(CudaOnlyWithDefs PROPERTIES LINK_FLAGS "-Wl,-rpath,${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES}")
+endif()
diff --git a/Tests/CudaOnly/WithDefs/main.notcu b/Tests/CudaOnly/WithDefs/main.notcu
new file mode 100644
index 0000000..80ed3a5
--- /dev/null
+++ b/Tests/CudaOnly/WithDefs/main.notcu
@@ -0,0 +1,53 @@
+#include <cuda.h>
+#include <cuda_runtime.h>
+#include <iostream>
+
+#ifndef PACKED_DEFINE
+#error "PACKED_DEFINE not defined!"
+#endif
+
+static __global__ void DetermineIfValidCudaDevice()
+{
+}
+
+#ifdef _MSC_VER
+#pragma pack(push, 1)
+#undef PACKED_DEFINE
+#define PACKED_DEFINE
+#endif
+struct PACKED_DEFINE result_type
+{
+  bool valid;
+  int value;
+#if defined(NDEBUG) && !defined(DEFREL)
+#error missing DEFREL flag
+#endif
+};
+#ifdef _MSC_VER
+#pragma pack(pop)
+#endif
+
+result_type can_launch_kernel()
+{
+  result_type r;
+  DetermineIfValidCudaDevice<<<1, 1>>>();
+  r.valid = (cudaSuccess == cudaGetLastError());
+  if (r.valid) {
+    r.value = 1;
+  } else {
+    r.value = -1;
+  }
+  return r;
+}
+
+int main(int argc, char** argv)
+{
+  cudaError_t err;
+  int nDevices = 0;
+  err = cudaGetDeviceCount(&nDevices);
+  if (err != cudaSuccess) {
+    std::cerr << cudaGetErrorString(err) << std::endl;
+    return 1;
+  }
+  return 0;
+}
diff --git a/Tests/CustomCommand/CMakeLists.txt b/Tests/CustomCommand/CMakeLists.txt
index db57e19..e9a9f52 100644
--- a/Tests/CustomCommand/CMakeLists.txt
+++ b/Tests/CustomCommand/CMakeLists.txt
@@ -513,3 +513,24 @@ add_custom_target(UseConsoleTarget ALL
   VERBATIM
   USES_TERMINAL
 )
+
+# Test COMMAND_EXPAND_LISTS
+set(cmp_args "1ARG=COMMAND_EXPAND_LISTS" "2ARG=test" "3ARG=outfile"
+  "4ARG=content")
+set(AARGS "")
+foreach(arg IN LISTS cmp_args)
+  list(APPEND AARGS "-DA${arg}")
+endforeach()
+
+set(gen_file "expand_custom_command.phony")
+add_custom_command(
+  OUTPUT "${gen_file}"
+  COMMAND ${CMAKE_COMMAND} ${AARGS}
+    "-DB$<JOIN:$<TARGET_PROPERTY:command_expand_lists,CMPARGS>,;-DB>"
+    "-P" "${CMAKE_CURRENT_SOURCE_DIR}/compare_options.cmake"
+    COMMAND_EXPAND_LISTS
+  VERBATIM
+)
+set_property(SOURCE "${gen_file}" PROPERTY SYMBOLIC ON)
+add_custom_target(command_expand_lists ALL DEPENDS "${gen_file}")
+set_property(TARGET command_expand_lists PROPERTY CMPARGS "${cmp_args}")
diff --git a/Tests/CustomCommand/compare_options.cmake b/Tests/CustomCommand/compare_options.cmake
new file mode 100644
index 0000000..a32e579
--- /dev/null
+++ b/Tests/CustomCommand/compare_options.cmake
@@ -0,0 +1,14 @@
+set(range 1 2 3 4 5 6 7 8 9 10)
+set(aargs "")
+set(bargs "")
+foreach(n IN LISTS range)
+  set(aval "${A${n}ARG}")
+  set(bval "${B${n}ARG}")
+  if(aval OR bval)
+    list(APPEND aargs "\"${aval}\"")
+    list(APPEND bargs "\"${bval}\"")
+  endif()
+endforeach()
+if(NOT "${aargs}" STREQUAL "${bargs}")
+  message(FATAL_ERROR "COMPARE_OPTIONS: \n\t${aargs} != \n\t${bargs}")
+endif()
diff --git a/Tests/ExternalProject/CMakeLists.txt b/Tests/ExternalProject/CMakeLists.txt
index ca6462d..72c20eb 100644
--- a/Tests/ExternalProject/CMakeLists.txt
+++ b/Tests/ExternalProject/CMakeLists.txt
@@ -363,6 +363,23 @@ if(do_git_tests)
   )
   set_property(TARGET ${proj} PROPERTY FOLDER "GIT")
 
+  # Live git / master (no GIT_TAG), but git config flags
+  #
+  # The `git clone --config` parameter has been introduced in Git 1.7.7
+  if(NOT git_version VERSION_LESS 1.7.7)
+    set(proj TutorialStep1-GIT-config)
+    ExternalProject_Add(${proj}
+      GIT_REPOSITORY "${local_git_repo}"
+      GIT_CONFIG core.eol=lf core.autocrlf=input
+      CMAKE_GENERATOR "${CMAKE_GENERATOR}"
+      CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
+      INSTALL_COMMAND ""
+      DEPENDS "SetupLocalGITRepository"
+      LOG_UPDATE 1
+    )
+    set_property(TARGET ${proj} PROPERTY FOLDER "GIT")
+  endif()
+
   # git by explicit branch/tag with empty submodule list
   #
   set(proj TutorialStep1-GIT-bytag-withsubmodules)
diff --git a/Tests/ExternalProjectLocal/CMakeLists.txt b/Tests/ExternalProjectLocal/CMakeLists.txt
index 17f1630..5b94163 100644
--- a/Tests/ExternalProjectLocal/CMakeLists.txt
+++ b/Tests/ExternalProjectLocal/CMakeLists.txt
@@ -131,6 +131,7 @@ ExternalProject_Add(${proj}
   CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR> -G ${CMAKE_GENERATOR} <SOURCE_DIR>
   INSTALL_COMMAND ""
   LOG_BUILD 1
+  UPDATE_DISCONNECTED 1
 )
 set_property(TARGET ${proj} PROPERTY FOLDER "Local/TGZ")
 
diff --git a/Tests/FindLibRHash/CMakeLists.txt b/Tests/FindLibRHash/CMakeLists.txt
new file mode 100644
index 0000000..4d3954d
--- /dev/null
+++ b/Tests/FindLibRHash/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindLibRHash.Test COMMAND
+  ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+  --build-and-test
+  "${CMake_SOURCE_DIR}/Tests/FindLibRHash/Test"
+  "${CMake_BINARY_DIR}/Tests/FindLibRHash/Test"
+  ${build_generator_args}
+  --build-project TestFindLibRHash
+  --build-options ${build_options}
+  --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+  )
diff --git a/Tests/FindLibRHash/Test/CMakeLists.txt b/Tests/FindLibRHash/Test/CMakeLists.txt
new file mode 100644
index 0000000..37e062a
--- /dev/null
+++ b/Tests/FindLibRHash/Test/CMakeLists.txt
@@ -0,0 +1,17 @@
+cmake_minimum_required(VERSION 3.7)
+project(TestFindLibRHash C)
+include(CTest)
+
+# CMake does not actually provide FindLibRHash publicly.
+set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../../Source/Modules)
+
+find_package(LibRHash REQUIRED)
+
+add_executable(test_librhash_tgt main.c)
+target_link_libraries(test_librhash_tgt LibRHash::LibRHash)
+add_test(NAME test_librhash_tgt COMMAND test_librhash_tgt)
+
+add_executable(test_librhash_var main.c)
+target_include_directories(test_librhash_var PRIVATE ${LibRHash_INCLUDE_DIRS})
+target_link_libraries(test_librhash_var PRIVATE ${LibRHash_LIBRARIES})
+add_test(NAME test_librhash_var COMMAND test_librhash_var)
diff --git a/Tests/FindLibRHash/Test/main.c b/Tests/FindLibRHash/Test/main.c
new file mode 100644
index 0000000..201dced
--- /dev/null
+++ b/Tests/FindLibRHash/Test/main.c
@@ -0,0 +1,7 @@
+#include <rhash.h>
+
+int main()
+{
+  rhash_library_init();
+  return 0;
+}
diff --git a/Tests/FindOpenGL/CMakeLists.txt b/Tests/FindOpenGL/CMakeLists.txt
new file mode 100644
index 0000000..9aa3aba
--- /dev/null
+++ b/Tests/FindOpenGL/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindOpenGL.Test COMMAND
+  ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+  --build-and-test
+  "${CMake_SOURCE_DIR}/Tests/FindOpenGL/Test"
+  "${CMake_BINARY_DIR}/Tests/FindOpenGL/Test"
+  ${build_generator_args}
+  --build-project TestFindOpenGL
+  --build-options ${build_options}
+  --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+  )
diff --git a/Tests/FindOpenGL/Test/CMakeLists.txt b/Tests/FindOpenGL/Test/CMakeLists.txt
new file mode 100644
index 0000000..cac3424
--- /dev/null
+++ b/Tests/FindOpenGL/Test/CMakeLists.txt
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.7)
+project(TestFindOpenGL C)
+include(CTest)
+
+find_package(OpenGL REQUIRED)
+
+add_executable(test_tgt main.c)
+target_link_libraries(test_tgt OpenGL::GLU)
+add_test(NAME test_tgt COMMAND test_tgt)
+
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${OPENGL_INGLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${OPENGL_LIBRARIES})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindOpenGL/Test/main.c b/Tests/FindOpenGL/Test/main.c
new file mode 100644
index 0000000..bca3d7e
--- /dev/null
+++ b/Tests/FindOpenGL/Test/main.c
@@ -0,0 +1,17 @@
+#ifdef _WIN32
+#include <windows.h>
+#endif
+#ifdef __APPLE__
+#include <OpenGL/gl.h>
+#else
+#include <GL/gl.h>
+#endif
+
+#include <stdio.h>
+
+int main()
+{
+  /* Reference a GL symbol without requiring a context at runtime.  */
+  printf("&glGetString = %p\n", &glGetString);
+  return 0;
+}
diff --git a/Tests/FindPackageModeMakefileTest/CMakeLists.txt b/Tests/FindPackageModeMakefileTest/CMakeLists.txt
index 56fcc5d..23832da 100644
--- a/Tests/FindPackageModeMakefileTest/CMakeLists.txt
+++ b/Tests/FindPackageModeMakefileTest/CMakeLists.txt
@@ -20,16 +20,9 @@ if(UNIX  AND  "${CMAKE_GENERATOR}" MATCHES "Makefile" AND
     configure_file(FindFoo.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/FindFoo.cmake @ONLY)
 
     # now set up the test:
-    if (NOT CMAKE_VERSION VERSION_LESS 2.8.12)
-      file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/cmakeExecutable.mk"
-        CONTENT "CMAKE = \"$<TARGET_FILE:cmake>\"\n"
-      )
-    else()
-      get_target_property(cmakeLocation cmake LOCATION)
-      file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/cmakeExecutable.mk"
-        "CMAKE = \"${cmakeLocation}\"\n"
-      )
-    endif()
+    file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/cmakeExecutable.mk"
+      CONTENT "CMAKE = \"$<TARGET_FILE:cmake>\"\n"
+    )
     configure_file(${CMAKE_CURRENT_SOURCE_DIR}/Makefile.in ${CMAKE_CURRENT_BINARY_DIR}/ConfMakefile @ONLY)
     configure_file(${CMAKE_CURRENT_SOURCE_DIR}/main.cpp ${CMAKE_CURRENT_BINARY_DIR}/main.cpp COPYONLY)
 
diff --git a/Tests/Framework/CMakeLists.txt b/Tests/Framework/CMakeLists.txt
index 271aaf1..a313c2c 100644
--- a/Tests/Framework/CMakeLists.txt
+++ b/Tests/Framework/CMakeLists.txt
@@ -57,29 +57,30 @@ add_custom_target(fooCustom ALL COMMAND ${CMAKE_COMMAND} -E copy foo-post-build
 add_dependencies(fooCustom foo)
 
 # Make a static library and apply the framework properties to it to verify
-# that everything still builds correctly, but it will not actually produce
-# a framework... The framework properties only apply when the library type
-# is SHARED.
+# that everything still builds correctly. Xcode prior to version 5 does not
+# support static Frameworks.
 #
-add_library(fooStatic STATIC
-  foo.cxx
-  foo.h
-  foo2.h
-  fooExtensionlessResource
-  fooPublic.h
-  fooPublicExtensionlessHeader
-  fooPrivate.h
-  fooPrivateExtensionlessHeader
-  fooNeither.h
-  fooBoth.h
-  test.lua
-  fooDeepPublic.h
-)
-set_target_properties(fooStatic PROPERTIES
-  FRAMEWORK TRUE
-  FRAMEWORK_VERSION none
-)
-add_executable(barStatic bar.cxx)
-target_link_libraries(barStatic fooStatic)
+if(NOT XCODE OR NOT XCODE_VERSION VERSION_LESS 5)
+  add_library(fooStatic STATIC
+    foo.cxx
+    foo.h
+    foo2.h
+    fooExtensionlessResource
+    fooPublic.h
+    fooPublicExtensionlessHeader
+    fooPrivate.h
+    fooPrivateExtensionlessHeader
+    fooNeither.h
+    fooBoth.h
+    test.lua
+    fooDeepPublic.h
+  )
+  set_target_properties(fooStatic PROPERTIES
+    FRAMEWORK TRUE
+    FRAMEWORK_VERSION none
+  )
+  add_executable(barStatic bar.cxx)
+  target_link_libraries(barStatic fooStatic)
+endif()
 
 include(CPack)
diff --git a/Tests/GeneratorExpression/CMakeLists.txt b/Tests/GeneratorExpression/CMakeLists.txt
index 27f33a2..adc87cd 100644
--- a/Tests/GeneratorExpression/CMakeLists.txt
+++ b/Tests/GeneratorExpression/CMakeLists.txt
@@ -145,13 +145,13 @@ add_library(imported1 SHARED IMPORTED)
 set_property(TARGET imported1 PROPERTY IMPORTED_LOCATION_RELEASE release_loc)
 set_property(TARGET imported1 PROPERTY IMPORTED_LOCATION_DEBUG debug_loc)
 set_property(TARGET imported1 PROPERTY IMPORTED_CONFIGURATIONS RELEASE DEBUG)
-set_property(TARGET imported1 PROPERTY INTERFACE_INCLUDE_DIRECTORIES /imported1/include)
+set_property(TARGET imported1 PROPERTY INTERFACE_INCLUDE_DIRECTORIES "/imported1/include/with space")
 
 add_library(imported2 SHARED IMPORTED)
 set_property(TARGET imported2 PROPERTY IMPORTED_LOCATION_RELEASE release_loc)
 set_property(TARGET imported2 PROPERTY IMPORTED_LOCATION_DEBUG debug_loc)
 set_property(TARGET imported2 PROPERTY IMPORTED_CONFIGURATIONS RELEASE DEBUG)
-set_property(TARGET imported2 PROPERTY INTERFACE_INCLUDE_DIRECTORIES /imported2/include)
+set_property(TARGET imported2 PROPERTY INTERFACE_INCLUDE_DIRECTORIES "/imported2/include/with space")
 
 add_library(imported3 SHARED IMPORTED)
 set_property(TARGET imported3 PROPERTY IMPORTED_LOCATION_RELEASE release_loc)
@@ -161,6 +161,10 @@ set_property(TARGET imported3 APPEND PROPERTY
   INTERFACE_INCLUDE_DIRECTORIES $<$<CONFIG:DEBUG>:$<TARGET_PROPERTY:imported1,INTERFACE_INCLUDE_DIRECTORIES>>)
 set_property(TARGET imported3 APPEND PROPERTY
   INTERFACE_INCLUDE_DIRECTORIES $<$<CONFIG:RELEASE>:$<TARGET_PROPERTY:imported2,INTERFACE_INCLUDE_DIRECTORIES>>)
+set_property(TARGET imported3 APPEND PROPERTY
+  INTERFACE_INCLUDE_DIRECTORIES $<$<CONFIG:RELWITHDEBINFO>:$<TARGET_PROPERTY:imported2,INTERFACE_INCLUDE_DIRECTORIES>>)
+set_property(TARGET imported3 APPEND PROPERTY
+  INTERFACE_INCLUDE_DIRECTORIES $<$<CONFIG:MINSIZEREL>:$<TARGET_PROPERTY:imported2,INTERFACE_INCLUDE_DIRECTORIES>>)
 
 add_library(imported4 SHARED IMPORTED)
 set_property(TARGET imported4 APPEND PROPERTY
@@ -171,6 +175,13 @@ add_executable(Alias::SomeExe ALIAS someexe)
 
 add_library(Alias::SomeLib ALIAS empty1)
 
+add_library(importedFallback STATIC IMPORTED)
+set_property(TARGET importedFallback PROPERTY IMPORTED_LOCATION_DEBUG debug_loc)
+set_property(TARGET importedFallback PROPERTY IMPORTED_LOCATION_RELEASE release_loc)
+set_property(TARGET importedFallback PROPERTY IMPORTED_LOCATION fallback_loc)
+set_property(TARGET importedFallback PROPERTY MAP_IMPORTED_CONFIG_DEBUG "" DEBUG)
+set_property(TARGET importedFallback PROPERTY MAP_IMPORTED_CONFIG_RELEASE "")
+
 add_custom_target(check-part3 ALL
   COMMAND ${CMAKE_COMMAND}
     -Dtest_version_greater_1=$<VERSION_GREATER:1.0,1.1.1>
@@ -180,10 +191,8 @@ add_custom_target(check-part3 ALL
     -Dtest_version_equal_1=$<VERSION_EQUAL:1.0.1,1.1>
     -Dtest_version_equal_2=$<VERSION_EQUAL:1.1,1.1>
     -Dconfig=$<CONFIGURATION>
-    -Dtest_imported_debug=$<TARGET_PROPERTY:imported4,INCLUDE_DIRECTORIES>
-    -Dtest_imported_release=$<TARGET_PROPERTY:imported4,INCLUDE_DIRECTORIES>
-    -Dtest_imported_relwithdebinfo=$<TARGET_PROPERTY:imported4,INCLUDE_DIRECTORIES>
-    -Dtest_imported_minsizerel=$<TARGET_PROPERTY:imported4,INCLUDE_DIRECTORIES>
+    -Dtest_imported_includes=$<TARGET_PROPERTY:imported4,INCLUDE_DIRECTORIES>
+    -Dtest_imported_fallback=$<STREQUAL:$<TARGET_FILE_NAME:importedFallback>,fallback_loc>
     -Dtest_alias_file_exe=$<STREQUAL:$<TARGET_FILE:Alias::SomeExe>,$<TARGET_FILE:someexe>>
     -Dtest_alias_file_lib=$<STREQUAL:$<TARGET_FILE:Alias::SomeLib>,$<TARGET_FILE:empty1>>
     -Dtest_alias_target_name=$<STREQUAL:$<TARGET_PROPERTY:Alias::SomeLib,NAME>,$<TARGET_PROPERTY:empty1,NAME>>
@@ -238,6 +247,10 @@ add_custom_target(check-part4 ALL
     # CMake as command-line argument
     -Dtest_shell_path=${path_prefix}$<SHELL_PATH:${test_shell_path}>
     -Dpath_prefix=${path_prefix}
+    -Dif_1=$<IF:1,a,b>
+    -Dif_2=$<IF:0,a,b>
+    -Dif_3=$<IF:$<EQUAL:10,30>,a,b>
+    -Dif_4=$<IF:$<EQUAL:30,30>,a,b>
     -DWIN32=${WIN32}
     -DCMAKE_GENERATOR=${CMAKE_GENERATOR}
     -P ${CMAKE_CURRENT_SOURCE_DIR}/check-part4.cmake
@@ -249,6 +262,7 @@ add_custom_target(check-part4 ALL
 # Cover test properties with generator expressions.
 add_executable(echo echo.c)
 add_executable(pwd pwd.c)
+set_property(SOURCE echo.c PROPERTY COMPILE_FLAGS $<1:-DSRC_GENEX_WORKS>)
 
 add_test(NAME echo-configuration COMMAND echo $<CONFIGURATION>)
 set_property(TEST echo-configuration PROPERTY
diff --git a/Tests/GeneratorExpression/check-part3.cmake b/Tests/GeneratorExpression/check-part3.cmake
index 70ccfe1..9014406 100644
--- a/Tests/GeneratorExpression/check-part3.cmake
+++ b/Tests/GeneratorExpression/check-part3.cmake
@@ -8,18 +8,17 @@ check(test_version_less_2 "1")
 check(test_version_equal_1 "0")
 check(test_version_equal_2 "1")
 
-foreach(c debug release relwithdebinfo minsizerel)
-  if(config AND NOT config STREQUAL NoConfig)
-    if(NOT "${test_imported_${c}}" MATCHES "^;/imported2/include$"
-        AND NOT "${test_imported_${c}}" MATCHES "^/imported1/include;$")
-      message(SEND_ERROR "test_imported_${c} is not correct: ${test_imported_${c}}")
-    endif()
-  else()
-    if(NOT "${test_imported_${c}}" MATCHES "^;$")
-      message(SEND_ERROR "test_imported_${c} is not an empty list: ${test_imported_${c}}")
-    endif()
+if(config AND NOT config STREQUAL NoConfig)
+  if(NOT "${test_imported_includes}" MATCHES "^;*/imported[12]/include/with space;*$")
+    message(SEND_ERROR "test_imported_includes is not correct: ${test_imported_includes}")
   endif()
-endforeach()
+else()
+  if(NOT "${test_imported_includes}" MATCHES "^;;;$")
+    message(SEND_ERROR "test_imported_includes is not an empty list: ${test_imported_includes}")
+  endif()
+endif()
+
+check(test_imported_fallback "1")
 
 check(test_alias_file_exe "1")
 check(test_alias_file_lib "1")
diff --git a/Tests/GeneratorExpression/check-part4.cmake b/Tests/GeneratorExpression/check-part4.cmake
index 9e516d5..f5d14dd 100644
--- a/Tests/GeneratorExpression/check-part4.cmake
+++ b/Tests/GeneratorExpression/check-part4.cmake
@@ -13,3 +13,8 @@ if(WIN32)
 else()
   check(test_shell_path [[/shell/path]])
 endif()
+
+check(if_1 "a")
+check(if_2 "b")
+check(if_3 "b")
+check(if_4 "a")
diff --git a/Tests/GeneratorExpression/echo.c b/Tests/GeneratorExpression/echo.c
index 06b0844..41596a2 100644
--- a/Tests/GeneratorExpression/echo.c
+++ b/Tests/GeneratorExpression/echo.c
@@ -3,6 +3,9 @@
 
 int main(int argc, char* argv[])
 {
+#ifndef SRC_GENEX_WORKS
+#error SRC_GENEX_WORKS not defined
+#endif
   printf("%s\n", argv[1]);
   return EXIT_SUCCESS;
 }
diff --git a/Tests/IncludeDirectories/CMakeLists.txt b/Tests/IncludeDirectories/CMakeLists.txt
index 4920582..db18462 100644
--- a/Tests/IncludeDirectories/CMakeLists.txt
+++ b/Tests/IncludeDirectories/CMakeLists.txt
@@ -3,7 +3,9 @@ project(IncludeDirectories)
 
 if (((CMAKE_C_COMPILER_ID STREQUAL GNU AND CMAKE_C_COMPILER_VERSION VERSION_GREATER 4.4)
     OR CMAKE_C_COMPILER_ID STREQUAL Clang OR CMAKE_C_COMPILER_ID STREQUAL AppleClang)
-    AND (CMAKE_GENERATOR STREQUAL "Unix Makefiles" OR CMAKE_GENERATOR STREQUAL "Ninja"))
+    AND (CMAKE_GENERATOR STREQUAL "Unix Makefiles"
+      OR CMAKE_GENERATOR STREQUAL "Ninja"
+      OR (CMAKE_GENERATOR STREQUAL "Xcode" AND NOT XCODE_VERSION VERSION_LESS 6.0)))
   include(CheckCXXCompilerFlag)
   check_cxx_compiler_flag(-Wunused-variable run_sys_includes_test)
   if(run_sys_includes_test)
diff --git a/Tests/IncludeDirectories/SystemIncludeDirectories/CMakeLists.txt b/Tests/IncludeDirectories/SystemIncludeDirectories/CMakeLists.txt
index dcee85e..5078f30 100644
--- a/Tests/IncludeDirectories/SystemIncludeDirectories/CMakeLists.txt
+++ b/Tests/IncludeDirectories/SystemIncludeDirectories/CMakeLists.txt
@@ -15,10 +15,17 @@ target_include_directories(upstream SYSTEM PUBLIC
 )
 
 add_library(config_specific INTERFACE)
-set(testConfig ${CMAKE_BUILD_TYPE})
-target_include_directories(config_specific SYSTEM INTERFACE
-  "$<$<CONFIG:${testConfig}>:${CMAKE_CURRENT_SOURCE_DIR}/config_specific>"
-)
+if(CMAKE_GENERATOR STREQUAL "Xcode")
+  # CMAKE_BUILD_TYPE does not work here for multi-config generators
+  target_include_directories(config_specific SYSTEM INTERFACE
+    "${CMAKE_CURRENT_SOURCE_DIR}/config_specific"
+  )
+else()
+  set(testConfig ${CMAKE_BUILD_TYPE})
+  target_include_directories(config_specific SYSTEM INTERFACE
+    "$<$<CONFIG:${testConfig}>:${CMAKE_CURRENT_SOURCE_DIR}/config_specific>"
+  )
+endif()
 
 add_library(consumer consumer.cpp)
 target_link_libraries(consumer upstream config_specific)
diff --git a/Tests/InterfaceLibrary/CMakeLists.txt b/Tests/InterfaceLibrary/CMakeLists.txt
index ee81419..33c4b90 100644
--- a/Tests/InterfaceLibrary/CMakeLists.txt
+++ b/Tests/InterfaceLibrary/CMakeLists.txt
@@ -25,8 +25,25 @@ target_sources(iface_objlib INTERFACE $<TARGET_OBJECTS:objlib>)
 add_library(intermediate INTERFACE)
 target_link_libraries(intermediate INTERFACE iface_objlib)
 
+add_library(item_fake_tgt STATIC item_fake.cpp)
+set_property(TARGET item_fake_tgt PROPERTY OUTPUT_NAME item_fake)
+add_library(item_real STATIC item.cpp)
+add_library(item_iface INTERFACE IMPORTED)
+set_property(TARGET item_iface PROPERTY IMPORTED_LIBNAME item_real)
+add_dependencies(item_iface item_real)
+link_directories(${CMAKE_CURRENT_BINARY_DIR})
+
 add_executable(InterfaceLibrary definetestexe.cpp)
-target_link_libraries(InterfaceLibrary iface_nodepends headeriface subiface intermediate)
+target_link_libraries(InterfaceLibrary
+  iface_nodepends
+  headeriface
+  subiface
+  intermediate
+
+  item_iface
+  item_fake # ensure that 'item_real' is ordered in place of item_iface
+  )
+add_dependencies(InterfaceLibrary item_fake_tgt)
 
 add_subdirectory(libsdir)
 
@@ -47,6 +64,7 @@ target_link_libraries(iface_whitelist INTERFACE $<$<BOOL:$<TARGET_PROPERTY:CUSTO
 add_executable(exec_whitelist dummy.cpp)
 target_link_libraries(exec_whitelist iface_whitelist)
 
+set(CMAKE_NO_SYSTEM_FROM_IMPORTED 1)
 add_library(iface_imported INTERFACE IMPORTED)
 set_property(TARGET iface_imported PROPERTY
   INTERFACE_COMPILE_DEFINITIONS
diff --git a/Tests/InterfaceLibrary/definetestexe.cpp b/Tests/InterfaceLibrary/definetestexe.cpp
index a6b5592..098502c 100644
--- a/Tests/InterfaceLibrary/definetestexe.cpp
+++ b/Tests/InterfaceLibrary/definetestexe.cpp
@@ -17,8 +17,9 @@
 
 extern int obj();
 extern int sub();
+extern int item();
 
 int main(int, char**)
 {
-  return obj() + sub();
+  return obj() + sub() + item();
 }
diff --git a/Tests/InterfaceLibrary/item.cpp b/Tests/InterfaceLibrary/item.cpp
new file mode 100644
index 0000000..85cda1b
--- /dev/null
+++ b/Tests/InterfaceLibrary/item.cpp
@@ -0,0 +1,4 @@
+int item()
+{
+  return 0;
+}
diff --git a/Tests/InterfaceLibrary/item_fake.cpp b/Tests/InterfaceLibrary/item_fake.cpp
new file mode 100644
index 0000000..b4bd829
--- /dev/null
+++ b/Tests/InterfaceLibrary/item_fake.cpp
@@ -0,0 +1,5 @@
+extern int item_undefined();
+int item()
+{
+  return item_undefined();
+}
diff --git a/Tests/MacRuntimePath/A/CMakeLists.txt b/Tests/MacRuntimePath/A/CMakeLists.txt
index ade0a3c..bf937e6 100644
--- a/Tests/MacRuntimePath/A/CMakeLists.txt
+++ b/Tests/MacRuntimePath/A/CMakeLists.txt
@@ -40,21 +40,30 @@ target_link_libraries(test3 framework)
 add_executable(test4 test1.cpp)
 target_link_libraries(test4 shared2)
 
+# executable to test a shared library dependency with build rpath
+add_executable(test5 test1.cpp)
+
+# avoid linking by 'target_link_libraries' so CMake
+# will not be able to set correct RPATH automatically
+add_dependencies(test5 shared)
+target_link_libraries(test5 "$<TARGET_FILE:shared>")
+set_target_properties(test5 PROPERTIES BUILD_RPATH "@loader_path/../lib")
+
 set_target_properties(shared shared2 framework PROPERTIES
   LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/lib")
-set_target_properties(test1 test2 test3 test4 PROPERTIES
+set_target_properties(test1 test2 test3 test4 test5 PROPERTIES
   RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/bin")
 foreach(config ${CMAKE_CONFIGURATION_TYPES})
   string(TOUPPER ${config} CONFIG)
   set_target_properties(shared shared2 framework PROPERTIES
     LIBRARY_OUTPUT_DIRECTORY_${CONFIG}
       "${CMAKE_CURRENT_BINARY_DIR}/${config}/lib")
-  set_target_properties(test1 test2 test3 test4 PROPERTIES
+  set_target_properties(test1 test2 test3 test4 test5 PROPERTIES
     RUNTIME_OUTPUT_DIRECTORY_${CONFIG}
       "${CMAKE_CURRENT_BINARY_DIR}/${config}/bin")
 endforeach()
 
-foreach(test test1 test2 test3 test4)
+foreach(test test1 test2 test3 test4 test5)
   add_custom_target(${test}_run  ALL
     COMMAND ${test}
     DEPENDS ${test}
diff --git a/Tests/MathTest/CMakeLists.txt b/Tests/MathTest/CMakeLists.txt
index ed2c7d4..f764b3a 100644
--- a/Tests/MathTest/CMakeLists.txt
+++ b/Tests/MathTest/CMakeLists.txt
@@ -10,6 +10,9 @@ set(expressions
   "1 +(3*4) + 10 >> 2"
   "10000 / 20 / 4"
   "10000 / (20 / 4)"
+  "-1 + +1"
+  "+1 - -1"
+  "+1 - - + + -(-3 + - - +1)"
   )
 
 set(FILE_EXPRESSIONS "")
diff --git a/Tests/Module/ExternalData/CMakeLists.txt b/Tests/Module/ExternalData/CMakeLists.txt
index 1018dd8..737e17a 100644
--- a/Tests/Module/ExternalData/CMakeLists.txt
+++ b/Tests/Module/ExternalData/CMakeLists.txt
@@ -45,6 +45,8 @@ ExternalData_Add_Test(Data1
     -D Meta=DATA{MetaTop.dat,REGEX:Meta[ABC].dat}
     -D Directory=DATA{Directory/,A.dat,REGEX:[BC].dat}
     -D DirRecurse=DATA{DirRecurse/,RECURSE:,A.dat,REGEX:[BC].dat}
+    -D MultipleAlgorithmNoSHA1=DATA{MultipleAlgorithmNoSHA1.dat}
+    -D MultipleAlgorithmNoMD5=DATA{MultipleAlgorithmNoMD5.dat}
     -D "Semicolons=DATA{Data.dat}\\;DATA{Data.dat}"
     -P ${CMAKE_CURRENT_SOURCE_DIR}/Data1Check.cmake
   )
diff --git a/Tests/Module/ExternalData/MultipleAlgorithmNoMD5.dat.md5 b/Tests/Module/ExternalData/MultipleAlgorithmNoMD5.dat.md5
new file mode 100644
index 0000000..a956f36
--- /dev/null
+++ b/Tests/Module/ExternalData/MultipleAlgorithmNoMD5.dat.md5
@@ -0,0 +1 @@
+29848e54a4d0343f138ab14419b863de
diff --git a/Tests/Module/ExternalData/MultipleAlgorithmNoMD5.dat.sha1 b/Tests/Module/ExternalData/MultipleAlgorithmNoMD5.dat.sha1
new file mode 100644
index 0000000..43a3540
--- /dev/null
+++ b/Tests/Module/ExternalData/MultipleAlgorithmNoMD5.dat.sha1
@@ -0,0 +1 @@
+2af59a7022024974f3b8521b7ed8137c996a79f1
diff --git a/Tests/Module/ExternalData/MultipleAlgorithmNoSHA1.dat.md5 b/Tests/Module/ExternalData/MultipleAlgorithmNoSHA1.dat.md5
new file mode 100644
index 0000000..1906cbf
--- /dev/null
+++ b/Tests/Module/ExternalData/MultipleAlgorithmNoSHA1.dat.md5
@@ -0,0 +1 @@
+08cfcf221f76ace7b906b312284e73d7
diff --git a/Tests/Module/ExternalData/MultipleAlgorithmNoSHA1.dat.sha1 b/Tests/Module/ExternalData/MultipleAlgorithmNoSHA1.dat.sha1
new file mode 100644
index 0000000..65781b2
--- /dev/null
+++ b/Tests/Module/ExternalData/MultipleAlgorithmNoSHA1.dat.sha1
@@ -0,0 +1 @@
+223b134e6e3a9bf34aa7531c009d97cff6b0d8a3
diff --git a/Tests/Module/ExternalData/SHA3_256/.gitattributes b/Tests/Module/ExternalData/SHA3_256/.gitattributes
new file mode 100644
index 0000000..3e51d39
--- /dev/null
+++ b/Tests/Module/ExternalData/SHA3_256/.gitattributes
@@ -0,0 +1 @@
+*               -crlf
diff --git a/Tests/Module/ExternalData/SHA3_256/c01b0bfd51ece4295c7b45493750a3612ecc483095eb1366f9f46b179550e231 b/Tests/Module/ExternalData/SHA3_256/c01b0bfd51ece4295c7b45493750a3612ecc483095eb1366f9f46b179550e231
new file mode 100644
index 0000000..0377f5d
--- /dev/null
+++ b/Tests/Module/ExternalData/SHA3_256/c01b0bfd51ece4295c7b45493750a3612ecc483095eb1366f9f46b179550e231
@@ -0,0 +1 @@
+SeriesMixed.5
diff --git a/Tests/Module/ExternalData/SeriesMixed.5.dat.sha3-256 b/Tests/Module/ExternalData/SeriesMixed.5.dat.sha3-256
new file mode 100644
index 0000000..1a5db39
--- /dev/null
+++ b/Tests/Module/ExternalData/SeriesMixed.5.dat.sha3-256
@@ -0,0 +1 @@
+c01b0bfd51ece4295c7b45493750a3612ecc483095eb1366f9f46b179550e231
diff --git a/Tests/Module/WriteCompilerDetectionHeader/CMakeLists.txt b/Tests/Module/WriteCompilerDetectionHeader/CMakeLists.txt
index 8b251d7..2657aeb 100644
--- a/Tests/Module/WriteCompilerDetectionHeader/CMakeLists.txt
+++ b/Tests/Module/WriteCompilerDetectionHeader/CMakeLists.txt
@@ -4,6 +4,7 @@ project(WriteCompilerDetectionHeader)
 set(CMAKE_INCLUDE_CURRENT_DIR ON)
 
 include(WriteCompilerDetectionHeader)
+include(CheckCXXSourceCompiles)
 
 get_property(cxx_known_features GLOBAL PROPERTY CMAKE_CXX_KNOWN_FEATURES)
 get_property(c_known_features GLOBAL PROPERTY CMAKE_C_KNOWN_FEATURES)
@@ -19,14 +20,78 @@ write_compiler_detection_header(
     ${cxx_known_features} ${c_known_features}
 )
 
-if (NOT CMAKE_CXX_COMPILE_FEATURES AND NOT CMAKE_C_COMPILE_FEATURES)
+write_compiler_detection_header(
+  FILE "${CMAKE_CURRENT_BINARY_DIR}/compiler_multi_files/multi_file_compiler_detection.h"
+  PREFIX MULTI
+  OUTPUT_FILES_VAR multi_files
+  OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/compiler_multi_files/compiler_support"
+  COMPILERS GNU Clang AppleClang MSVC SunPro Intel
+  VERSION 3.1
+  FEATURES
+    ${cxx_known_features} ${c_known_features}
+)
+
+macro(set_defines target true_defs false_defs)
+  set(defines)
+  foreach(def ${true_defs})
+    list(APPEND defines ${def}=1)
+  endforeach()
+  foreach(def ${false_defs})
+    list(APPEND defines ${def}=0)
+  endforeach()
+  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()
+
+if (CMAKE_C_COMPILE_FEATURES)
+  string(REGEX REPLACE "^([0-9]+)\\.[0-9]+\\.[0-9]+.*" "\\1" COMPILER_VERSION_MAJOR "${CMAKE_C_COMPILER_VERSION}")
+  string(REGEX REPLACE "^[0-9]+\\.([0-9]+)\\.[0-9]+.*" "\\1" COMPILER_VERSION_MINOR "${CMAKE_C_COMPILER_VERSION}")
+  string(REGEX REPLACE "^[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" COMPILER_VERSION_PATCH "${CMAKE_C_COMPILER_VERSION}")
+
+  if (CMAKE_C_COMPILER_ID STREQUAL "GNU"
+      OR CMAKE_C_COMPILER_ID STREQUAL "Clang"
+      OR CMAKE_C_COMPILER_ID STREQUAL "AppleClang"
+      OR CMAKE_C_COMPILER_ID STREQUAL "Intel")
+    add_executable(WriteCompilerDetectionHeader_C11 main.c)
+    set_property(TARGET WriteCompilerDetectionHeader_C11 PROPERTY C_STANDARD 11)
+    set_defines(WriteCompilerDetectionHeader_C11 "EXPECTED_COMPILER_C_FUNCTION_PROTOTYPES;EXPECTED_COMPILER_C_RESTRICT" "")
+
+    add_executable(WriteCompilerDetectionHeader_C11_multi main_multi.c)
+    set_property(TARGET WriteCompilerDetectionHeader_C11_multi PROPERTY C_STANDARD 11)
+    set_defines(WriteCompilerDetectionHeader_C11_multi "EXPECTED_COMPILER_C_FUNCTION_PROTOTYPES;EXPECTED_COMPILER_C_RESTRICT" "")
+    target_include_directories(WriteCompilerDetectionHeader_C11_multi PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/compiler_multi_files)
+
+    add_executable(C_undefined c_undefined.c)
+    set_property(TARGET C_undefined PROPERTY C_STANDARD 90)
+    include(CheckCCompilerFlag)
+    check_c_compiler_flag(-Werror=undef use_error_undef)
+    if (use_error_undef)
+        target_compile_options(C_undefined PRIVATE -Werror=undef)
+    endif()
+
+    add_executable(WriteCompilerDetectionHeader_C main.c)
+    set_property(TARGET WriteCompilerDetectionHeader_C PROPERTY C_STANDARD 90)
+    set_defines(WriteCompilerDetectionHeader_C "EXPECTED_COMPILER_C_FUNCTION_PROTOTYPES" "EXPECTED_COMPILER_C_RESTRICT")
+
+    add_executable(WriteCompilerDetectionHeader_C_multi main_multi.c)
+    set_property(TARGET WriteCompilerDetectionHeader_C_multi PROPERTY C_STANDARD 90)
+    set_defines(WriteCompilerDetectionHeader_C_multi "EXPECTED_COMPILER_C_FUNCTION_PROTOTYPES" "EXPECTED_COMPILER_C_RESTRICT")
+    target_include_directories(WriteCompilerDetectionHeader_C_multi PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/compiler_multi_files)
+  endif()
+endif()
+
+if (NOT CMAKE_CXX_COMPILE_FEATURES)
   file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp"
     "int main(int,char**) { return 0; }\n"
   )
   add_executable(WriteCompilerDetectionHeader "${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp")
 
   if(UNIX OR NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
-    include(CheckCXXSourceCompiles)
     check_cxx_source_compiles("#include \"${CMAKE_CURRENT_BINARY_DIR}/test_compiler_detection.h\"\nint main() { return 0; }\n"
       file_include_works
     )
@@ -41,23 +106,6 @@ string(REGEX REPLACE "^([0-9]+)\\.[0-9]+\\.[0-9]+.*" "\\1" COMPILER_VERSION_MAJO
 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})
-    list(APPEND defines ${def}=1)
-  endforeach()
-  foreach(def ${false_defs})
-    list(APPEND defines ${def}=0)
-  endforeach()
-  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()
-
 if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU"
     OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang"
     OR CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang"
@@ -79,40 +127,10 @@ if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
   endif()
 endif()
 
-if (CMAKE_C_COMPILER_ID STREQUAL "GNU"
-    OR CMAKE_C_COMPILER_ID STREQUAL "Clang"
-    OR CMAKE_C_COMPILER_ID STREQUAL "AppleClang"
-    OR CMAKE_C_COMPILER_ID STREQUAL "Intel")
-
-  add_executable(C_undefined c_undefined.c)
-  set_property(TARGET C_undefined PROPERTY C_STANDARD 90)
-  target_compile_options(C_undefined PRIVATE -Werror=undef)
-
-  add_executable(WriteCompilerDetectionHeader_C main.c)
-  set_property(TARGET WriteCompilerDetectionHeader_C PROPERTY C_STANDARD 90)
-  set_defines(WriteCompilerDetectionHeader_C "EXPECTED_COMPILER_C_FUNCTION_PROTOTYPES" "EXPECTED_COMPILER_C_RESTRICT")
-
-  add_executable(WriteCompilerDetectionHeader_C_multi main_multi.c)
-  set_property(TARGET WriteCompilerDetectionHeader_C_multi PROPERTY C_STANDARD 90)
-  set_defines(WriteCompilerDetectionHeader_C_multi "EXPECTED_COMPILER_C_FUNCTION_PROTOTYPES" "EXPECTED_COMPILER_C_RESTRICT")
-  target_include_directories(WriteCompilerDetectionHeader_C_multi PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/compiler_multi_files)
-endif()
-
 add_executable(WriteCompilerDetectionHeader main.cpp)
 set_property(TARGET WriteCompilerDetectionHeader PROPERTY CXX_STANDARD 98)
 set_defines(WriteCompilerDetectionHeader "${true_defs}" "${false_defs}")
 
-write_compiler_detection_header(
-  FILE "${CMAKE_CURRENT_BINARY_DIR}/compiler_multi_files/multi_file_compiler_detection.h"
-  PREFIX MULTI
-  OUTPUT_FILES_VAR multi_files
-  OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/compiler_multi_files/compiler_support"
-  COMPILERS GNU Clang AppleClang MSVC SunPro Intel
-  VERSION 3.1
-  FEATURES
-    ${cxx_known_features} ${c_known_features}
-)
-
 add_executable(multi_files multi_files.cpp)
 set_property(TARGET multi_files PROPERTY CXX_STANDARD 98)
 target_include_directories(multi_files PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/compiler_multi_files)
@@ -143,16 +161,30 @@ set_property(TARGET multi_files_11 PROPERTY CXX_STANDARD 11)
 target_include_directories(multi_files_11 PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/compiler_multi_files)
 set_defines(multi_files_11 "${true_defs}" "${false_defs}")
 
-if (CMAKE_C_COMPILER_ID STREQUAL "GNU"
-    OR CMAKE_C_COMPILER_ID STREQUAL "Clang"
-    OR CMAKE_C_COMPILER_ID STREQUAL "AppleClang"
-    OR CMAKE_C_COMPILER_ID STREQUAL "Intel")
-  add_executable(WriteCompilerDetectionHeader_C11 main.c)
-  set_property(TARGET WriteCompilerDetectionHeader_C11 PROPERTY C_STANDARD 11)
-  set_defines(WriteCompilerDetectionHeader_C11 "EXPECTED_COMPILER_C_FUNCTION_PROTOTYPES;EXPECTED_COMPILER_C_RESTRICT" "")
-
-  add_executable(WriteCompilerDetectionHeader_C11_multi main_multi.c)
-  set_property(TARGET WriteCompilerDetectionHeader_C11_multi PROPERTY C_STANDARD 11)
-  set_defines(WriteCompilerDetectionHeader_C11_multi "EXPECTED_COMPILER_C_FUNCTION_PROTOTYPES;EXPECTED_COMPILER_C_RESTRICT" "")
-  target_include_directories(WriteCompilerDetectionHeader_C11_multi PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/compiler_multi_files)
+# test for ALLOW_UNKNOWN_COMPILERS
+
+# use a compiler does not match the current one,
+# so one always hits the fallback code
+if (CMAKE_CXX_COMPILER_ID STREQUAL "SunPro")
+  set(OTHER_CXX "Intel")
+else()
+  set(OTHER_CXX "SunPro")
+endif()
+
+write_compiler_detection_header(
+  FILE "${CMAKE_CURRENT_BINARY_DIR}/test_compiler_detection_allow_unknown.h"
+  PREFIX TEST
+  COMPILERS ${OTHER_CXX}
+  FEATURES cxx_nullptr
+  ALLOW_UNKNOWN_COMPILERS
+)
+
+# intentionally abuse the TEST_NULLPR variable: this will only work
+# with the fallback code.
+check_cxx_source_compiles("#include \"${CMAKE_CURRENT_BINARY_DIR}/test_compiler_detection_allow_unknown.h\"
+int main() {\n int i = TEST_NULLPTR;\n return 0; }\n"
+  file_include_works_allow_unknown
+)
+if (NOT file_include_works_allow_unknown)
+  message(SEND_ERROR "Inclusion of ${CMAKE_CURRENT_BINARY_DIR}/test_compiler_detection_allow_unknown.h was expected to work, but did not.")
 endif()
diff --git a/Tests/ObjectLibrary/A/CMakeLists.txt b/Tests/ObjectLibrary/A/CMakeLists.txt
index 188fd64..c185d75 100644
--- a/Tests/ObjectLibrary/A/CMakeLists.txt
+++ b/Tests/ObjectLibrary/A/CMakeLists.txt
@@ -21,3 +21,4 @@ add_custom_command(
 
 add_library(A OBJECT a1.c a2.c a.cmake)
 target_include_directories(A PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
+set_property(TARGET A PROPERTY COMPILE_PDB_NAME Apdb)
diff --git a/Tests/PositionIndependentTargets/.gitattributes b/Tests/PositionIndependentTargets/.gitattributes
new file mode 100644
index 0000000..ed36631
--- /dev/null
+++ b/Tests/PositionIndependentTargets/.gitattributes
@@ -0,0 +1,2 @@
+# Do not format a source where we want a long line preserved.
+pic_test.h -format.clang-format
diff --git a/Tests/Preprocess/CMakeLists.txt b/Tests/Preprocess/CMakeLists.txt
index 15f0338..807a427 100644
--- a/Tests/Preprocess/CMakeLists.txt
+++ b/Tests/Preprocess/CMakeLists.txt
@@ -214,18 +214,24 @@ set(FILE_PATH "${Preprocess_SOURCE_DIR}/file_def.h")
 set(TARGET_PATH "${Preprocess_SOURCE_DIR}/target_def.h")
 
 # Set some definition properties.
-foreach(c "" "_DEBUG" "_RELEASE")
+foreach(c "" "_DEBUG" "_RELEASE" "_RELWITHDEBINFO" "_MINSIZEREL")
+  set(FLAVOR "${c}")
+  # Treat RelWithDebInfo and MinSizeRel as Release to avoid having
+  # an exponentional matrix of inclusions and exclusions of defines
+  if("${c}" STREQUAL "_RELWITHDEBINFO" OR "${c}" STREQUAL "_MINSIZEREL")
+    set(FLAVOR "_RELEASE")
+  endif()
   set_property(
     DIRECTORY .
-    APPEND PROPERTY COMPILE_DEFINITIONS${c} "DIRECTORY_DEF${c}"
+    APPEND PROPERTY COMPILE_DEFINITIONS${c} "DIRECTORY_DEF${FLAVOR}"
     )
   set_property(
     TARGET Preprocess
-    PROPERTY COMPILE_DEFINITIONS${c} "TARGET_DEF${c}"
+    PROPERTY COMPILE_DEFINITIONS${c} "TARGET_DEF${FLAVOR}"
     )
   set_property(
     SOURCE preprocess.c preprocess.cxx
-    PROPERTY COMPILE_DEFINITIONS${c} "FILE_DEF${c}"
+    PROPERTY COMPILE_DEFINITIONS${c} "FILE_DEF${FLAVOR}"
     )
 endforeach()
 
diff --git a/Tests/QtAutoUicInterface/CMakeLists.txt b/Tests/QtAutoUicInterface/CMakeLists.txt
index 555f016..70175fb 100644
--- a/Tests/QtAutoUicInterface/CMakeLists.txt
+++ b/Tests/QtAutoUicInterface/CMakeLists.txt
@@ -1,5 +1,5 @@
 
-cmake_minimum_required(VERSION 2.8.12)
+cmake_minimum_required(VERSION 3.7)
 
 project(QtAutoUicInterface)
 
@@ -21,7 +21,6 @@ else()
 endif()
 
 set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON)
-set(CMAKE_INCLUDE_CURRENT_DIR ON)
 set(CMAKE_AUTOMOC ON)
 set(CMAKE_AUTOUIC ON)
 
@@ -65,6 +64,6 @@ target_link_libraries(MyWidget KI18n ${QT_GUI_TARGET})
 add_executable(QtAutoUicInterface main.cpp)
 target_compile_definitions(QtAutoUicInterface
   PRIVATE
-    UI_LIBWIDGET_H="${CMAKE_CURRENT_BINARY_DIR}/ui_libwidget.h"
-    UI_MYWIDGET_H="${CMAKE_CURRENT_BINARY_DIR}/ui_mywidget.h"
+    UI_LIBWIDGET_H="${CMAKE_CURRENT_BINARY_DIR}/LibWidget_autogen/include/ui_libwidget.h"
+    UI_MYWIDGET_H="${CMAKE_CURRENT_BINARY_DIR}/MyWidget_autogen/include/ui_mywidget.h"
 )
diff --git a/Tests/QtAutoUicInterface/libwidget.cpp b/Tests/QtAutoUicInterface/libwidget.cpp
index b25f3d7..008c22a 100644
--- a/Tests/QtAutoUicInterface/libwidget.cpp
+++ b/Tests/QtAutoUicInterface/libwidget.cpp
@@ -7,3 +7,8 @@ LibWidget::LibWidget(QWidget* parent)
 {
   ui->setupUi(this);
 }
+
+LibWidget::~LibWidget()
+{
+  delete ui;
+}
diff --git a/Tests/QtAutoUicInterface/libwidget.h b/Tests/QtAutoUicInterface/libwidget.h
index a4400d2..b6f3e82 100644
--- a/Tests/QtAutoUicInterface/libwidget.h
+++ b/Tests/QtAutoUicInterface/libwidget.h
@@ -16,9 +16,10 @@ class LibWidget : public QWidget
   Q_OBJECT
 public:
   explicit LibWidget(QWidget* parent = 0);
+  ~LibWidget();
 
 private:
-  const std::auto_ptr<Ui::LibWidget> ui;
+  Ui::LibWidget* ui;
 };
 
 #endif
diff --git a/Tests/QtAutoUicInterface/mywidget.cpp b/Tests/QtAutoUicInterface/mywidget.cpp
index 885165b..7cf1a13 100644
--- a/Tests/QtAutoUicInterface/mywidget.cpp
+++ b/Tests/QtAutoUicInterface/mywidget.cpp
@@ -7,3 +7,8 @@ MyWidget::MyWidget(QWidget* parent)
 {
   ui->setupUi(this);
 }
+
+MyWidget::~MyWidget()
+{
+  delete ui;
+}
diff --git a/Tests/QtAutoUicInterface/mywidget.h b/Tests/QtAutoUicInterface/mywidget.h
index fc49e80..c23e55d 100644
--- a/Tests/QtAutoUicInterface/mywidget.h
+++ b/Tests/QtAutoUicInterface/mywidget.h
@@ -16,9 +16,10 @@ class MyWidget : public QWidget
   Q_OBJECT
 public:
   explicit MyWidget(QWidget* parent = 0);
+  ~MyWidget();
 
 private:
-  const std::auto_ptr<Ui::MyWidget> ui;
+  Ui::MyWidget* ui;
 };
 
 #endif
diff --git a/Tests/QtAutogen/Bdir/CMakeLists.txt b/Tests/QtAutogen/Bdir/CMakeLists.txt
deleted file mode 100644
index d9d4aa7..0000000
--- a/Tests/QtAutogen/Bdir/CMakeLists.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-
-set(CMAKE_INCLUDE_CURRENT_DIR ON)
-set(CMAKE_AUTOMOC ON)
-set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON)
-
-add_library(libB SHARED libB.cpp)
-generate_export_header(libB)
-
-# set_property(TARGET libB APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} )
-target_link_libraries(libB LINK_PUBLIC libA)
diff --git a/Tests/QtAutogen/CMakeLists.txt b/Tests/QtAutogen/CMakeLists.txt
index c713d1c..4b90ad8 100644
--- a/Tests/QtAutogen/CMakeLists.txt
+++ b/Tests/QtAutogen/CMakeLists.txt
@@ -1,4 +1,4 @@
-cmake_minimum_required(VERSION 3.1)
+cmake_minimum_required(VERSION 3.7)
 
 project(QtAutogen)
 
@@ -44,114 +44,44 @@ else()
 
 endif()
 
-# -- RCC only
-add_executable(rcconly rcconly.cpp second_resource.qrc)
-set_property(TARGET rcconly PROPERTY AUTORCC ON)
-target_link_libraries(rcconly ${QT_QTCORE_TARGET})
+get_property(QT_COMPILE_FEATURES TARGET ${QT_QTCORE_TARGET} PROPERTY INTERFACE_COMPILE_FEATURES)
 
-# -- RCC empty
-add_executable(rcc_empty rcc_empty.cpp rcc_empty_resource.qrc)
-set_property(TARGET rcc_empty PROPERTY AUTORCC ON)
-target_link_libraries(rcc_empty ${QT_QTCORE_TARGET})
+# -- Test: AUTORCC
+# RCC only
+add_executable(rccOnly rccOnly.cpp rccOnlyRes.qrc)
+set_property(TARGET rccOnly PROPERTY AUTORCC ON)
+target_link_libraries(rccOnly ${QT_QTCORE_TARGET})
 
-include_directories(${CMAKE_CURRENT_BINARY_DIR})
+# -- Test: AUTORCC
+# RCC empty
+add_executable(rccEmpty rccEmpty.cpp rccEmptyRes.qrc)
+set_property(TARGET rccEmpty PROPERTY AUTORCC ON)
+target_link_libraries(rccEmpty ${QT_QTCORE_TARGET})
 
-add_definitions(-DFOO -DSomeDefine="Barx")
-
-# enable relaxed mode so automoc can handle all the special cases:
-set(CMAKE_AUTOMOC_RELAXED_MODE TRUE)
-
-set(CMAKE_AUTOUIC ON)
-set(CMAKE_AUTORCC ON)
-
-# create an executable and two library targets, each requiring automoc:
-add_library(codeeditorLib STATIC codeeditor.cpp)
-
-add_library(privateSlot OBJECT private_slot.cpp)
-
-configure_file(generated_resource.qrc.in generated_resource.qrc @ONLY)
-add_custom_command(
-  OUTPUT generated.txt
-  COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/generated.txt.in" "${CMAKE_CURRENT_BINARY_DIR}/generated.txt"
-  DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/generated.txt.in"
-  )
-
-add_custom_target(generate_moc_input
-  DEPENDS generated.txt
-  COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/myinterface.h.in" "${CMAKE_CURRENT_BINARY_DIR}"
-  COMMAND ${CMAKE_COMMAND} -E rename "${CMAKE_CURRENT_BINARY_DIR}/myinterface.h.in" "${CMAKE_CURRENT_BINARY_DIR}/myinterface.h"
-)
-
-add_custom_command(
-  OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/myotherinterface.h"
-  COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/myotherinterface.h.in" "${CMAKE_CURRENT_BINARY_DIR}/myotherinterface.h"
-  DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/myotherinterface.h.in"
-)
-
-if (NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_GENERATOR STREQUAL Ninja)
-  set(debug_srcs "$<$<CONFIG:Debug>:debug_class.cpp>" $<$<CONFIG:Debug>:debug_resource.qrc>)
-  set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS $<$<CONFIG:Debug>:TEST_DEBUG_CLASS>)
-endif()
-
-# The -no-protection option disables the generation of include guards.  Verify
-# that setting the source file property has an effect by using this and
-# issue an error in the preprocessor in calwidget.cpp if the include guard
-# is defined.
-set_source_files_properties(calwidget.ui PROPERTIES AUTOUIC_OPTIONS "-no-protection")
-
-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}
-               ${CMAKE_CURRENT_BINARY_DIR}/generated_resource.qrc
-)
-set_property(TARGET QtAutogen APPEND PROPERTY AUTOGEN_TARGET_DEPENDS generate_moc_input "${CMAKE_CURRENT_BINARY_DIR}/myotherinterface.h")
-
-add_executable(targetObjectsTest targetObjectsTest.cpp $<TARGET_OBJECTS:privateSlot>)
-target_link_libraries(targetObjectsTest ${QT_LIBRARIES})
-
-set_target_properties(
-  QtAutogen codeeditorLib privateSlot targetObjectsTest
-  PROPERTIES
-  AUTOMOC TRUE
-)
-
-# Test AUTOMOC and AUTORCC on source files with the same name
-# but in different subdirectories
-add_subdirectory(sameName)
-
-include(GenerateExportHeader)
-# The order is relevant here. B depends on A, and B headers depend on A
-# headers both subdirectories use CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE and we
-# test that CMAKE_AUTOMOC successfully reads the include directories
-# for the build interface from those targets. There has previously been
-# a bug where caching of the include directories happened before
-# extracting the includes to pass to moc.
-add_subdirectory(Bdir)
-add_subdirectory(Adir)
-add_library(libC SHARED libC.cpp)
-set_target_properties(libC PROPERTIES AUTOMOC TRUE)
-generate_export_header(libC)
-target_link_libraries(libC LINK_PUBLIC libB)
-
-target_link_libraries(QtAutogen codeeditorLib ${QT_LIBRARIES} libC)
+# -- Test: AUTOUIC
+# UIC only
+qtx_wrap_cpp(uicOnlyMoc uicOnlySource/uiconly.h)
+add_executable(uicOnly uicOnlySource/uiconly.cpp ${uicOnlyMoc})
+set_property(TARGET uicOnly PROPERTY AUTOUIC ON)
+target_link_libraries(uicOnly ${QT_LIBRARIES})
 
+# -- Test: AUTOMOC, AUTORCC
 # Add not_generated_file.qrc to the source list to get the file-level
 # dependency, but don't generate a c++ file from it.  Disable the AUTORCC
 # feature for this target.  This tests that qrc files in the sources don't
 # have an effect on generation if AUTORCC is off.
 add_library(empty STATIC empty.cpp not_generated_file.qrc)
 set_target_properties(empty PROPERTIES AUTORCC OFF)
-
 set_target_properties(empty PROPERTIES AUTOMOC TRUE)
 target_link_libraries(empty no_link_language)
 add_library(no_link_language STATIC empty.h)
 set_target_properties(no_link_language PROPERTIES AUTOMOC TRUE)
+# Pass Qt compiler features to targets that don't link against Qt
+target_compile_features(no_link_language PRIVATE ${QT_COMPILE_FEATURES})
+target_compile_features(empty PRIVATE ${QT_COMPILE_FEATURES})
 
-qtx_wrap_cpp(uicOnlyMoc sub/uiconly.h)
-add_executable(uiconly sub/uiconly.cpp ${uicOnlyMoc})
-target_link_libraries(uiconly ${QT_LIBRARIES})
-
+# -- Test: AUTORCC
+# When a file listed in a .qrc file changes the target must be rebuilt
 try_compile(RCC_DEPENDS
   "${CMAKE_CURRENT_BINARY_DIR}/autorcc_depends"
   "${CMAKE_CURRENT_SOURCE_DIR}/autorcc_depends"
@@ -185,7 +115,8 @@ if (NOT file1_step1 GREATER file1_before)
   message(SEND_ERROR "file1 (${qrc_file1}) should have changed in the first step!")
 endif()
 
-#-----------------------------------------------------------------------------
+# -- Test: AUTOMOC
+# Ensure a repeated build succeeds when a header containing a QObject changes
 try_compile(MOC_RERUN
   "${CMAKE_CURRENT_BINARY_DIR}/automoc_rerun"
   "${CMAKE_CURRENT_SOURCE_DIR}/automoc_rerun"
@@ -207,3 +138,74 @@ execute_process(COMMAND "${CMAKE_COMMAND}" --build .
 if (automoc_rerun_result)
   message(SEND_ERROR "Second build of automoc_rerun failed.")
 endif()
+
+# -- Test: AUTOMOC, SKIP_AUTOMOC
+# Test for SKIP_AUTOMOC and SKIP_AUTOGEN on an AUTOMOC enabled target
+qtx_wrap_cpp(skipMocWrapMoc
+  skipSource/qItemA.hpp
+  skipSource/qItemB.hpp)
+set(skipMocSources
+  skipMoc.cpp
+  skipSource/qItemA.cpp
+  skipSource/qItemB.cpp
+  skipSource/qItemC.cpp)
+set_property(SOURCE skipSource/qItemA.cpp PROPERTY SKIP_AUTOMOC ON)
+set_property(SOURCE skipSource/qItemB.cpp PROPERTY SKIP_AUTOGEN ON)
+# AUTOMOC enabled only
+add_executable(skipMocA ${skipMocSources} ${skipMocWrapMoc})
+set_property(TARGET skipMocA PROPERTY AUTOMOC ON)
+target_link_libraries(skipMocA ${QT_LIBRARIES})
+# AUTOMOC and AUTOUIC enabled
+add_executable(skipMocB ${skipMocSources} ${skipMocWrapMoc})
+set_property(TARGET skipMocB PROPERTY AUTOMOC ON)
+set_property(TARGET skipMocB PROPERTY AUTOUIC ON)
+target_link_libraries(skipMocB ${QT_LIBRARIES})
+
+# -- Test: AUTOUIC, SKIP_AUTOUIC
+# Test for SKIP_AUTOUIC and SKIP_AUTOGEN on an AUTOUIC enabled target
+set(skipUicSources
+  skipUic.cpp
+  skipSource/skipUicGen.cpp
+  skipSource/skipUicNoGen1.cpp
+  skipSource/skipUicNoGen2.cpp
+)
+set_property(SOURCE skipSource/skipUicNoGen1.cpp PROPERTY SKIP_AUTOUIC ON)
+set_property(SOURCE skipSource/skipUicNoGen2.cpp PROPERTY SKIP_AUTOGEN ON)
+# AUTOUIC enabled
+add_executable(skipUicA ${skipUicSources})
+set_property(TARGET skipUicA PROPERTY AUTOUIC ON)
+target_link_libraries(skipUicA ${QT_LIBRARIES})
+# AUTOUIC and AUTOMOC enabled
+add_executable(skipUicB ${skipUicSources})
+set_property(TARGET skipUicB PROPERTY AUTOUIC ON)
+set_property(TARGET skipUicB PROPERTY AUTOMOC ON)
+target_link_libraries(skipUicB ${QT_LIBRARIES})
+
+# -- Test: AUTORCC, SKIP_AUTORCC
+# Test for SKIP_AUTORCC and SKIP_AUTOGEN on an AUTORCC enabled target
+set(skipRccSources
+  skipRcc.cpp
+  skipSource/skipRccBad1.qrc
+  skipSource/skipRccBad2.qrc
+  skipSource/skipRccGood.qrc
+)
+set_property(SOURCE skipSource/skipRccBad1.qrc PROPERTY SKIP_AUTORCC ON)
+set_property(SOURCE skipSource/skipRccBad2.qrc PROPERTY SKIP_AUTOGEN ON)
+# AUTORCC enabled
+add_executable(skipRccA ${skipRccSources})
+set_property(TARGET skipRccA PROPERTY AUTORCC ON)
+target_link_libraries(skipRccA ${QT_LIBRARIES})
+# AUTORCC, AUTOUIC and AUTOMOC enabled
+add_executable(skipRccB ${skipRccSources})
+set_property(TARGET skipRccB PROPERTY AUTORCC ON)
+set_property(TARGET skipRccB PROPERTY AUTOUIC ON)
+set_property(TARGET skipRccB PROPERTY AUTOMOC ON)
+target_link_libraries(skipRccB ${QT_LIBRARIES})
+
+# -- Test: AUTOMOC AUTORCC
+# Source files with the same basename in different subdirectories
+add_subdirectory(sameName)
+
+# -- Test: AUTOMOC AUTORCC AUTOUIC
+# Complex test case
+add_subdirectory(complex)
diff --git a/Tests/QtAutogen/automoc_rerun/CMakeLists.txt b/Tests/QtAutogen/automoc_rerun/CMakeLists.txt
index 17bc332..92a682b 100644
--- a/Tests/QtAutogen/automoc_rerun/CMakeLists.txt
+++ b/Tests/QtAutogen/automoc_rerun/CMakeLists.txt
@@ -1,4 +1,4 @@
-cmake_minimum_required(VERSION 3.1)
+cmake_minimum_required(VERSION 3.7)
 project(automoc_rerun CXX)
 
 if (QT_TEST_VERSION STREQUAL 4)
diff --git a/Tests/QtAutogen/autorcc_depends/CMakeLists.txt b/Tests/QtAutogen/autorcc_depends/CMakeLists.txt
index fbe71ad..7b51e11 100644
--- a/Tests/QtAutogen/autorcc_depends/CMakeLists.txt
+++ b/Tests/QtAutogen/autorcc_depends/CMakeLists.txt
@@ -1,4 +1,4 @@
-cmake_minimum_required(VERSION 3.1)
+cmake_minimum_required(VERSION 3.7)
 project(autorcc_depends)
 
 set(CMAKE_AUTORCC ON)
diff --git a/Tests/QtAutogen/Adir/CMakeLists.txt b/Tests/QtAutogen/complex/Adir/CMakeLists.txt
similarity index 100%
rename from Tests/QtAutogen/Adir/CMakeLists.txt
rename to Tests/QtAutogen/complex/Adir/CMakeLists.txt
diff --git a/Tests/QtAutogen/Adir/libA.cpp b/Tests/QtAutogen/complex/Adir/libA.cpp
similarity index 100%
rename from Tests/QtAutogen/Adir/libA.cpp
rename to Tests/QtAutogen/complex/Adir/libA.cpp
diff --git a/Tests/QtAutogen/Adir/libA.h b/Tests/QtAutogen/complex/Adir/libA.h
similarity index 100%
rename from Tests/QtAutogen/Adir/libA.h
rename to Tests/QtAutogen/complex/Adir/libA.h
diff --git a/Tests/QtAutogen/complex/Bdir/CMakeLists.txt b/Tests/QtAutogen/complex/Bdir/CMakeLists.txt
new file mode 100644
index 0000000..d338763
--- /dev/null
+++ b/Tests/QtAutogen/complex/Bdir/CMakeLists.txt
@@ -0,0 +1,9 @@
+
+set(CMAKE_INCLUDE_CURRENT_DIR ON)
+set(CMAKE_AUTOMOC ON)
+set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON)
+
+add_library(libB SHARED libB.cpp)
+generate_export_header(libB)
+
+target_link_libraries(libB LINK_PUBLIC libA)
diff --git a/Tests/QtAutogen/Bdir/libB.cpp b/Tests/QtAutogen/complex/Bdir/libB.cpp
similarity index 100%
rename from Tests/QtAutogen/Bdir/libB.cpp
rename to Tests/QtAutogen/complex/Bdir/libB.cpp
diff --git a/Tests/QtAutogen/Bdir/libB.h b/Tests/QtAutogen/complex/Bdir/libB.h
similarity index 100%
rename from Tests/QtAutogen/Bdir/libB.h
rename to Tests/QtAutogen/complex/Bdir/libB.h
diff --git a/Tests/QtAutogen/complex/CMakeLists.txt b/Tests/QtAutogen/complex/CMakeLists.txt
new file mode 100644
index 0000000..d48f6cc
--- /dev/null
+++ b/Tests/QtAutogen/complex/CMakeLists.txt
@@ -0,0 +1,82 @@
+cmake_minimum_required(VERSION 3.7)
+
+# -- Test: AUTOMOC AUTORCC AUTOUIC
+add_definitions(-DFOO -DSomeDefine="Barx")
+
+# enable relaxed mode so automoc can handle all the special cases:
+set(CMAKE_AUTOMOC_RELAXED_MODE TRUE)
+set(CMAKE_AUTOUIC ON)
+set(CMAKE_AUTORCC ON)
+
+# create an executable and two library targets, each requiring automoc:
+add_library(codeeditorLib STATIC codeeditor.cpp)
+add_library(privateSlot OBJECT private_slot.cpp)
+# Pass Qt compiler features to targets that don't link against Qt
+target_compile_features(codeeditorLib PRIVATE ${QT_COMPILE_FEATURES})
+target_compile_features(privateSlot PRIVATE ${QT_COMPILE_FEATURES})
+
+configure_file(generated_resource.qrc.in generated_resource.qrc @ONLY)
+add_custom_command(
+  OUTPUT generated.txt
+  COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/generated.txt.in" "${CMAKE_CURRENT_BINARY_DIR}/generated.txt"
+  DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/generated.txt.in"
+  )
+
+add_custom_target(generate_moc_input
+  DEPENDS generated.txt
+  COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/myinterface.h.in" "${CMAKE_CURRENT_BINARY_DIR}"
+  COMMAND ${CMAKE_COMMAND} -E rename "${CMAKE_CURRENT_BINARY_DIR}/myinterface.h.in" "${CMAKE_CURRENT_BINARY_DIR}/myinterface.h"
+)
+
+add_custom_command(
+  OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/myotherinterface.h"
+  COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/myotherinterface.h.in" "${CMAKE_CURRENT_BINARY_DIR}/myotherinterface.h"
+  DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/myotherinterface.h.in"
+)
+
+if (NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_GENERATOR STREQUAL Ninja)
+  set(debug_srcs "$<$<CONFIG:Debug>:debug_class.cpp>" $<$<CONFIG:Debug>:debug_resource.qrc>)
+  set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS $<$<CONFIG:Debug>:TEST_DEBUG_CLASS>)
+endif()
+
+# The -no-protection option disables the generation of include guards.  Verify
+# that setting the source file property has an effect by using this and
+# issue an error in the preprocessor in calwidget.cpp if the include guard
+# is defined.
+set_source_files_properties(calwidget.ui PROPERTIES AUTOUIC_OPTIONS "-no-protection")
+
+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}
+               ${CMAKE_CURRENT_BINARY_DIR}/generated_resource.qrc
+)
+set_property(TARGET QtAutogen APPEND PROPERTY AUTOGEN_TARGET_DEPENDS generate_moc_input "${CMAKE_CURRENT_BINARY_DIR}/myotherinterface.h")
+
+add_executable(targetObjectsTest targetObjectsTest.cpp $<TARGET_OBJECTS:privateSlot>)
+target_link_libraries(targetObjectsTest ${QT_LIBRARIES})
+
+set_target_properties(
+  QtAutogen codeeditorLib privateSlot targetObjectsTest
+  PROPERTIES
+  AUTOMOC TRUE
+)
+
+
+include(GenerateExportHeader)
+# The order is relevant here. B depends on A, and B headers depend on A
+# headers both subdirectories use CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE and we
+# test that CMAKE_AUTOMOC successfully reads the include directories
+# for the build interface from those targets. There has previously been
+# a bug where caching of the include directories happened before
+# extracting the includes to pass to moc.
+add_subdirectory(Bdir)
+add_subdirectory(Adir)
+add_library(libC SHARED libC.cpp)
+set_target_properties(libC PROPERTIES AUTOMOC TRUE)
+generate_export_header(libC)
+target_link_libraries(libC LINK_PUBLIC libB)
+target_include_directories(libC PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
+set_property(TARGET libC APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_BINARY_DIR} )
+
+target_link_libraries(QtAutogen codeeditorLib ${QT_LIBRARIES} libC)
diff --git a/Tests/QtAutogen/abc.cpp b/Tests/QtAutogen/complex/abc.cpp
similarity index 100%
rename from Tests/QtAutogen/abc.cpp
rename to Tests/QtAutogen/complex/abc.cpp
diff --git a/Tests/QtAutogen/abc.h b/Tests/QtAutogen/complex/abc.h
similarity index 100%
rename from Tests/QtAutogen/abc.h
rename to Tests/QtAutogen/complex/abc.h
diff --git a/Tests/QtAutogen/abc_p.h b/Tests/QtAutogen/complex/abc_p.h
similarity index 100%
rename from Tests/QtAutogen/abc_p.h
rename to Tests/QtAutogen/complex/abc_p.h
diff --git a/Tests/QtAutogen/bar.cpp b/Tests/QtAutogen/complex/bar.cpp
similarity index 100%
rename from Tests/QtAutogen/bar.cpp
rename to Tests/QtAutogen/complex/bar.cpp
diff --git a/Tests/QtAutogen/blub.cpp b/Tests/QtAutogen/complex/blub.cpp
similarity index 100%
rename from Tests/QtAutogen/blub.cpp
rename to Tests/QtAutogen/complex/blub.cpp
diff --git a/Tests/QtAutogen/blub.h b/Tests/QtAutogen/complex/blub.h
similarity index 100%
rename from Tests/QtAutogen/blub.h
rename to Tests/QtAutogen/complex/blub.h
diff --git a/Tests/QtAutogen/calwidget.cpp b/Tests/QtAutogen/complex/calwidget.cpp
similarity index 100%
rename from Tests/QtAutogen/calwidget.cpp
rename to Tests/QtAutogen/complex/calwidget.cpp
diff --git a/Tests/QtAutogen/calwidget.h b/Tests/QtAutogen/complex/calwidget.h
similarity index 100%
rename from Tests/QtAutogen/calwidget.h
rename to Tests/QtAutogen/complex/calwidget.h
diff --git a/Tests/QtAutogen/calwidget.ui b/Tests/QtAutogen/complex/calwidget.ui
similarity index 100%
rename from Tests/QtAutogen/calwidget.ui
rename to Tests/QtAutogen/complex/calwidget.ui
diff --git a/Tests/QtAutogen/codeeditor.cpp b/Tests/QtAutogen/complex/codeeditor.cpp
similarity index 100%
rename from Tests/QtAutogen/codeeditor.cpp
rename to Tests/QtAutogen/complex/codeeditor.cpp
diff --git a/Tests/QtAutogen/codeeditor.h b/Tests/QtAutogen/complex/codeeditor.h
similarity index 100%
rename from Tests/QtAutogen/codeeditor.h
rename to Tests/QtAutogen/complex/codeeditor.h
diff --git a/Tests/QtAutogen/debug_class.cpp b/Tests/QtAutogen/complex/debug_class.cpp
similarity index 100%
rename from Tests/QtAutogen/debug_class.cpp
rename to Tests/QtAutogen/complex/debug_class.cpp
diff --git a/Tests/QtAutogen/debug_class.h b/Tests/QtAutogen/complex/debug_class.h
similarity index 100%
rename from Tests/QtAutogen/debug_class.h
rename to Tests/QtAutogen/complex/debug_class.h
diff --git a/Tests/QtAutogen/debug_class.ui b/Tests/QtAutogen/complex/debug_class.ui
similarity index 100%
rename from Tests/QtAutogen/debug_class.ui
rename to Tests/QtAutogen/complex/debug_class.ui
diff --git a/Tests/QtAutogen/debug_resource.qrc b/Tests/QtAutogen/complex/debug_resource.qrc
similarity index 100%
rename from Tests/QtAutogen/debug_resource.qrc
rename to Tests/QtAutogen/complex/debug_resource.qrc
diff --git a/Tests/QtAutogen/foo.cpp b/Tests/QtAutogen/complex/foo.cpp
similarity index 100%
rename from Tests/QtAutogen/foo.cpp
rename to Tests/QtAutogen/complex/foo.cpp
diff --git a/Tests/QtAutogen/foo.h b/Tests/QtAutogen/complex/foo.h
similarity index 100%
rename from Tests/QtAutogen/foo.h
rename to Tests/QtAutogen/complex/foo.h
diff --git a/Tests/QtAutogen/gadget.cpp b/Tests/QtAutogen/complex/gadget.cpp
similarity index 100%
rename from Tests/QtAutogen/gadget.cpp
rename to Tests/QtAutogen/complex/gadget.cpp
diff --git a/Tests/QtAutogen/gadget.h b/Tests/QtAutogen/complex/gadget.h
similarity index 100%
rename from Tests/QtAutogen/gadget.h
rename to Tests/QtAutogen/complex/gadget.h
diff --git a/Tests/QtAutogen/generated.cpp b/Tests/QtAutogen/complex/generated.cpp
similarity index 100%
rename from Tests/QtAutogen/generated.cpp
rename to Tests/QtAutogen/complex/generated.cpp
diff --git a/Tests/QtAutogen/generated.h b/Tests/QtAutogen/complex/generated.h
similarity index 100%
rename from Tests/QtAutogen/generated.h
rename to Tests/QtAutogen/complex/generated.h
diff --git a/Tests/QtAutogen/generated.txt.in b/Tests/QtAutogen/complex/generated.txt.in
similarity index 100%
rename from Tests/QtAutogen/generated.txt.in
rename to Tests/QtAutogen/complex/generated.txt.in
diff --git a/Tests/QtAutogen/generated_resource.qrc.in b/Tests/QtAutogen/complex/generated_resource.qrc.in
similarity index 100%
rename from Tests/QtAutogen/generated_resource.qrc.in
rename to Tests/QtAutogen/complex/generated_resource.qrc.in
diff --git a/Tests/QtAutogen/libC.cpp b/Tests/QtAutogen/complex/libC.cpp
similarity index 100%
rename from Tests/QtAutogen/libC.cpp
rename to Tests/QtAutogen/complex/libC.cpp
diff --git a/Tests/QtAutogen/libC.h b/Tests/QtAutogen/complex/libC.h
similarity index 100%
rename from Tests/QtAutogen/libC.h
rename to Tests/QtAutogen/complex/libC.h
diff --git a/Tests/QtAutogen/main.cpp b/Tests/QtAutogen/complex/main.cpp
similarity index 100%
rename from Tests/QtAutogen/main.cpp
rename to Tests/QtAutogen/complex/main.cpp
diff --git a/Tests/QtAutogen/multiplewidgets.cpp b/Tests/QtAutogen/complex/multiplewidgets.cpp
similarity index 100%
rename from Tests/QtAutogen/multiplewidgets.cpp
rename to Tests/QtAutogen/complex/multiplewidgets.cpp
diff --git a/Tests/QtAutogen/multiplewidgets.h b/Tests/QtAutogen/complex/multiplewidgets.h
similarity index 100%
rename from Tests/QtAutogen/multiplewidgets.h
rename to Tests/QtAutogen/complex/multiplewidgets.h
diff --git a/Tests/QtAutogen/myinterface.h.in b/Tests/QtAutogen/complex/myinterface.h.in
similarity index 100%
rename from Tests/QtAutogen/myinterface.h.in
rename to Tests/QtAutogen/complex/myinterface.h.in
diff --git a/Tests/QtAutogen/myotherinterface.h.in b/Tests/QtAutogen/complex/myotherinterface.h.in
similarity index 100%
rename from Tests/QtAutogen/myotherinterface.h.in
rename to Tests/QtAutogen/complex/myotherinterface.h.in
diff --git a/Tests/QtAutogen/private_slot.cpp b/Tests/QtAutogen/complex/private_slot.cpp
similarity index 100%
rename from Tests/QtAutogen/private_slot.cpp
rename to Tests/QtAutogen/complex/private_slot.cpp
diff --git a/Tests/QtAutogen/private_slot.h b/Tests/QtAutogen/complex/private_slot.h
similarity index 100%
rename from Tests/QtAutogen/private_slot.h
rename to Tests/QtAutogen/complex/private_slot.h
diff --git a/Tests/QtAutogen/resourcetester.cpp b/Tests/QtAutogen/complex/resourcetester.cpp
similarity index 100%
rename from Tests/QtAutogen/resourcetester.cpp
rename to Tests/QtAutogen/complex/resourcetester.cpp
diff --git a/Tests/QtAutogen/resourcetester.h b/Tests/QtAutogen/complex/resourcetester.h
similarity index 100%
rename from Tests/QtAutogen/resourcetester.h
rename to Tests/QtAutogen/complex/resourcetester.h
diff --git a/Tests/QtAutogen/second_resource.qrc b/Tests/QtAutogen/complex/second_resource.qrc
similarity index 100%
rename from Tests/QtAutogen/second_resource.qrc
rename to Tests/QtAutogen/complex/second_resource.qrc
diff --git a/Tests/QtAutogen/second_widget.cpp b/Tests/QtAutogen/complex/second_widget.cpp
similarity index 100%
rename from Tests/QtAutogen/second_widget.cpp
rename to Tests/QtAutogen/complex/second_widget.cpp
diff --git a/Tests/QtAutogen/second_widget.h b/Tests/QtAutogen/complex/second_widget.h
similarity index 100%
rename from Tests/QtAutogen/second_widget.h
rename to Tests/QtAutogen/complex/second_widget.h
diff --git a/Tests/QtAutogen/second_widget.ui b/Tests/QtAutogen/complex/second_widget.ui
similarity index 100%
rename from Tests/QtAutogen/second_widget.ui
rename to Tests/QtAutogen/complex/second_widget.ui
diff --git a/Tests/QtAutogen/sub/bar.h b/Tests/QtAutogen/complex/sub/bar.h
similarity index 100%
rename from Tests/QtAutogen/sub/bar.h
rename to Tests/QtAutogen/complex/sub/bar.h
diff --git a/Tests/QtAutogen/targetObjectsTest.cpp b/Tests/QtAutogen/complex/targetObjectsTest.cpp
similarity index 100%
rename from Tests/QtAutogen/targetObjectsTest.cpp
rename to Tests/QtAutogen/complex/targetObjectsTest.cpp
diff --git a/Tests/QtAutogen/test.qrc b/Tests/QtAutogen/complex/test.qrc
similarity index 100%
rename from Tests/QtAutogen/test.qrc
rename to Tests/QtAutogen/complex/test.qrc
diff --git a/Tests/QtAutogen/widget1.ui b/Tests/QtAutogen/complex/widget1.ui
similarity index 100%
rename from Tests/QtAutogen/widget1.ui
rename to Tests/QtAutogen/complex/widget1.ui
diff --git a/Tests/QtAutogen/widget2.ui b/Tests/QtAutogen/complex/widget2.ui
similarity index 100%
rename from Tests/QtAutogen/widget2.ui
rename to Tests/QtAutogen/complex/widget2.ui
diff --git a/Tests/QtAutogen/xyz.cpp b/Tests/QtAutogen/complex/xyz.cpp
similarity index 100%
rename from Tests/QtAutogen/xyz.cpp
rename to Tests/QtAutogen/complex/xyz.cpp
diff --git a/Tests/QtAutogen/xyz.h b/Tests/QtAutogen/complex/xyz.h
similarity index 100%
rename from Tests/QtAutogen/xyz.h
rename to Tests/QtAutogen/complex/xyz.h
diff --git a/Tests/QtAutogen/yaf.cpp b/Tests/QtAutogen/complex/yaf.cpp
similarity index 100%
rename from Tests/QtAutogen/yaf.cpp
rename to Tests/QtAutogen/complex/yaf.cpp
diff --git a/Tests/QtAutogen/yaf.h b/Tests/QtAutogen/complex/yaf.h
similarity index 100%
rename from Tests/QtAutogen/yaf.h
rename to Tests/QtAutogen/complex/yaf.h
diff --git a/Tests/QtAutogen/yaf_p.h b/Tests/QtAutogen/complex/yaf_p.h
similarity index 100%
rename from Tests/QtAutogen/yaf_p.h
rename to Tests/QtAutogen/complex/yaf_p.h
diff --git a/Tests/QtAutogen/defines_test/CMakeLists.txt b/Tests/QtAutogen/defines_test/CMakeLists.txt
index ad4e684..9ee9a22 100644
--- a/Tests/QtAutogen/defines_test/CMakeLists.txt
+++ b/Tests/QtAutogen/defines_test/CMakeLists.txt
@@ -1,6 +1,4 @@
 
-include_directories(${CMAKE_CURRENT_BINARY_DIR})
-
 add_executable(defines_test defines_test.cpp)
 set_target_properties(defines_test PROPERTIES AUTOMOC TRUE)
 target_link_libraries(defines_test Qt4::QtGui)
diff --git a/Tests/QtAutogen/rccEmpty.cpp b/Tests/QtAutogen/rccEmpty.cpp
new file mode 100644
index 0000000..7f2c527
--- /dev/null
+++ b/Tests/QtAutogen/rccEmpty.cpp
@@ -0,0 +1,9 @@
+
+extern int qInitResources_rccEmptyRes();
+
+int main(int, char**)
+{
+  // Fails to link if the symbol is not present.
+  qInitResources_rccEmptyRes();
+  return 0;
+}
diff --git a/Tests/QtAutogen/rcc_empty_resource.qrc b/Tests/QtAutogen/rccEmptyRes.qrc
similarity index 100%
rename from Tests/QtAutogen/rcc_empty_resource.qrc
rename to Tests/QtAutogen/rccEmptyRes.qrc
diff --git a/Tests/QtAutogen/rccOnly.cpp b/Tests/QtAutogen/rccOnly.cpp
new file mode 100644
index 0000000..61c7bf4
--- /dev/null
+++ b/Tests/QtAutogen/rccOnly.cpp
@@ -0,0 +1,9 @@
+
+extern int qInitResources_rccOnlyRes();
+
+int main(int, char**)
+{
+  // Fails to link if the symbol is not present.
+  qInitResources_rccOnlyRes();
+  return 0;
+}
diff --git a/Tests/QtAutogen/rccOnlyRes.qrc b/Tests/QtAutogen/rccOnlyRes.qrc
new file mode 100644
index 0000000..5551348
--- /dev/null
+++ b/Tests/QtAutogen/rccOnlyRes.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+    <file>rccOnly.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/rcc_empty.cpp b/Tests/QtAutogen/rcc_empty.cpp
deleted file mode 100644
index 3f9f9a2..0000000
--- a/Tests/QtAutogen/rcc_empty.cpp
+++ /dev/null
@@ -1,9 +0,0 @@
-
-extern int qInitResources_rcc_empty_resource();
-
-int main(int, char**)
-{
-  // Fails to link if the symbol is not present.
-  qInitResources_rcc_empty_resource();
-  return 0;
-}
diff --git a/Tests/QtAutogen/rcconly.cpp b/Tests/QtAutogen/rcconly.cpp
deleted file mode 100644
index 854c4c1..0000000
--- a/Tests/QtAutogen/rcconly.cpp
+++ /dev/null
@@ -1,9 +0,0 @@
-
-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/sameName/CMakeLists.txt b/Tests/QtAutogen/sameName/CMakeLists.txt
index ed045fb..9e47a3e 100644
--- a/Tests/QtAutogen/sameName/CMakeLists.txt
+++ b/Tests/QtAutogen/sameName/CMakeLists.txt
@@ -16,6 +16,5 @@ add_executable(sameName
   data.qrc
   main.cpp
 )
-target_include_directories(sameName PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
 target_link_libraries(sameName ${QT_LIBRARIES})
-set_target_properties( sameName PROPERTIES AUTOMOC TRUE AUTORCC TRUE )
+set_target_properties(sameName PROPERTIES AUTOMOC TRUE AUTORCC TRUE)
diff --git a/Tests/QtAutogen/skipMoc.cpp b/Tests/QtAutogen/skipMoc.cpp
new file mode 100644
index 0000000..85305f5
--- /dev/null
+++ b/Tests/QtAutogen/skipMoc.cpp
@@ -0,0 +1,14 @@
+
+#include "skipSource/qItemA.hpp"
+#include "skipSource/qItemB.hpp"
+#include "skipSource/qItemC.hpp"
+
+int main(int, char**)
+{
+  QItemA itemA;
+  QItemA itemB;
+  QItemA itemC;
+
+  // Fails to link if the symbol is not present.
+  return 0;
+}
diff --git a/Tests/QtAutogen/skipRcc.cpp b/Tests/QtAutogen/skipRcc.cpp
new file mode 100644
index 0000000..ec57110
--- /dev/null
+++ b/Tests/QtAutogen/skipRcc.cpp
@@ -0,0 +1,9 @@
+
+extern int qInitResources_skipRccGood();
+
+int main(int, char**)
+{
+  // Fails to link if the symbol is not present.
+  qInitResources_skipRccGood();
+  return 0;
+}
diff --git a/Tests/QtAutogen/skipSource/qItemA.cpp b/Tests/QtAutogen/skipSource/qItemA.cpp
new file mode 100644
index 0000000..522c2c7
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/qItemA.cpp
@@ -0,0 +1,5 @@
+#include "qItemA.hpp"
+
+void QItemA::go()
+{
+}
diff --git a/Tests/QtAutogen/skipSource/qItemA.hpp b/Tests/QtAutogen/skipSource/qItemA.hpp
new file mode 100644
index 0000000..d295faf
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/qItemA.hpp
@@ -0,0 +1,13 @@
+#ifndef QITEMA_HPP
+#define QITEMA_HPP
+
+#include <QObject>
+
+class QItemA : public QObject
+{
+  Q_OBJECT
+  Q_SLOT
+  void go();
+};
+
+#endif
diff --git a/Tests/QtAutogen/skipSource/qItemB.cpp b/Tests/QtAutogen/skipSource/qItemB.cpp
new file mode 100644
index 0000000..636e15d
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/qItemB.cpp
@@ -0,0 +1,5 @@
+#include "qItemB.hpp"
+
+void QItemB::go()
+{
+}
diff --git a/Tests/QtAutogen/skipSource/qItemB.hpp b/Tests/QtAutogen/skipSource/qItemB.hpp
new file mode 100644
index 0000000..1775915
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/qItemB.hpp
@@ -0,0 +1,13 @@
+#ifndef QITEMB_HPP
+#define QITEMB_HPP
+
+#include <QObject>
+
+class QItemB : public QObject
+{
+  Q_OBJECT
+  Q_SLOT
+  void go();
+};
+
+#endif
diff --git a/Tests/QtAutogen/skipSource/qItemC.cpp b/Tests/QtAutogen/skipSource/qItemC.cpp
new file mode 100644
index 0000000..700abd6
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/qItemC.cpp
@@ -0,0 +1,5 @@
+#include "qItemC.hpp"
+
+void QItemC::go()
+{
+}
diff --git a/Tests/QtAutogen/skipSource/qItemC.hpp b/Tests/QtAutogen/skipSource/qItemC.hpp
new file mode 100644
index 0000000..f06bda2
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/qItemC.hpp
@@ -0,0 +1,13 @@
+#ifndef QITEMC_HPP
+#define QITEMC_HPP
+
+#include <QObject>
+
+class QItemC : public QObject
+{
+  Q_OBJECT
+  Q_SLOT
+  void go();
+};
+
+#endif
diff --git a/Tests/QtAutogen/skipSource/skipRccBad1.qrc b/Tests/QtAutogen/skipSource/skipRccBad1.qrc
new file mode 100644
index 0000000..6cbd9ed
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/skipRccBad1.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+    <file>skipRccGood.cpp</file>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/skipSource/skipRccBad2.qrc b/Tests/QtAutogen/skipSource/skipRccBad2.qrc
new file mode 100644
index 0000000..b32c589
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/skipRccBad2.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><
+<qresource>
+    <file>skipRccGood.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/skipSource/skipRccGood.qrc b/Tests/QtAutogen/skipSource/skipRccGood.qrc
new file mode 100644
index 0000000..21a94b0
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/skipRccGood.qrc
@@ -0,0 +1,6 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+    <file>skipRccBad1.qrc</file>
+    <file>skipRccBad2.qrc</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/skipSource/skipUicGen.cpp b/Tests/QtAutogen/skipSource/skipUicGen.cpp
new file mode 100644
index 0000000..d2a55a6
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/skipUicGen.cpp
@@ -0,0 +1,7 @@
+
+#include "skipUicGen.hpp"
+#include "ui_uigen2.h"
+
+void skipGen()
+{
+}
diff --git a/Tests/QtAutogen/skipSource/skipUicGen.hpp b/Tests/QtAutogen/skipSource/skipUicGen.hpp
new file mode 100644
index 0000000..3669f0e
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/skipUicGen.hpp
@@ -0,0 +1,8 @@
+#ifndef SKIPUICGEN_HPP
+#define SKIPUICGEN_HPP
+
+#include "ui_uigen1.h"
+
+void skipGen();
+
+#endif
diff --git a/Tests/QtAutogen/skipSource/skipUicNoGen1.cpp b/Tests/QtAutogen/skipSource/skipUicNoGen1.cpp
new file mode 100644
index 0000000..f591a42
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/skipUicNoGen1.cpp
@@ -0,0 +1,7 @@
+
+#include "skipUicNoGen1.hpp"
+#include "ui_nogen2.h"
+
+void skipNoGen1()
+{
+}
diff --git a/Tests/QtAutogen/skipSource/skipUicNoGen1.hpp b/Tests/QtAutogen/skipSource/skipUicNoGen1.hpp
new file mode 100644
index 0000000..2864695
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/skipUicNoGen1.hpp
@@ -0,0 +1,8 @@
+#ifndef SKIPUICNOGEN1_H
+#define SKIPUICNOGEN1_H
+
+#include "ui_nogen1.h"
+
+void skipNoGen1();
+
+#endif
diff --git a/Tests/QtAutogen/skipSource/skipUicNoGen2.cpp b/Tests/QtAutogen/skipSource/skipUicNoGen2.cpp
new file mode 100644
index 0000000..8c1c324
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/skipUicNoGen2.cpp
@@ -0,0 +1,7 @@
+
+#include "skipUicNoGen2.hpp"
+#include "ui_nogen2.h"
+
+void skipNoGen2()
+{
+}
diff --git a/Tests/QtAutogen/skipSource/skipUicNoGen2.hpp b/Tests/QtAutogen/skipSource/skipUicNoGen2.hpp
new file mode 100644
index 0000000..7c38193
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/skipUicNoGen2.hpp
@@ -0,0 +1,8 @@
+#ifndef SKIPUICNOGEN2_H
+#define SKIPUICNOGEN2_H
+
+#include "ui_nogen1.h"
+
+void skipNoGen2();
+
+#endif
diff --git a/Tests/QtAutogen/skipSource/ui_nogen1.h b/Tests/QtAutogen/skipSource/ui_nogen1.h
new file mode 100644
index 0000000..a7be52b
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/ui_nogen1.h
@@ -0,0 +1,6 @@
+#ifndef UI_NOGEN1_H
+#define UI_NOGEN1_H
+
+void ui_nogen1();
+
+#endif
diff --git a/Tests/QtAutogen/skipSource/ui_nogen2.h b/Tests/QtAutogen/skipSource/ui_nogen2.h
new file mode 100644
index 0000000..5d547d4
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/ui_nogen2.h
@@ -0,0 +1,6 @@
+#ifndef UI_NOGEN2_H
+#define UI_NOGEN2_H
+
+void ui_nogen2();
+
+#endif
\ No newline at end of file
diff --git a/Tests/QtAutogen/skipSource/uigen1.ui b/Tests/QtAutogen/skipSource/uigen1.ui
new file mode 100644
index 0000000..fc7cb82
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/uigen1.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>UiGen1</class>
+ <widget class="QWidget" name="UiGen1">
+  <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>
+  <layout class="QHBoxLayout" name="horizontalLayout">
+   <item>
+    <widget class="QTreeView" name="treeView"/>
+   </item>
+  </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Tests/QtAutogen/skipSource/uigen2.ui b/Tests/QtAutogen/skipSource/uigen2.ui
new file mode 100644
index 0000000..01f08d2
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/uigen2.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>UiGen2</class>
+ <widget class="QWidget" name="UiGen2">
+  <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>
+  <layout class="QHBoxLayout" name="horizontalLayout">
+   <item>
+    <widget class="QTreeView" name="treeView"/>
+   </item>
+  </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Tests/QtAutogen/skipUic.cpp b/Tests/QtAutogen/skipUic.cpp
new file mode 100644
index 0000000..0adf011
--- /dev/null
+++ b/Tests/QtAutogen/skipUic.cpp
@@ -0,0 +1,22 @@
+
+#include "skipSource/skipUicGen.hpp"
+#include "skipSource/skipUicNoGen1.hpp"
+#include "skipSource/skipUicNoGen2.hpp"
+
+int main(int, char**)
+{
+  skipGen();
+  skipNoGen1();
+  skipNoGen2();
+
+  return 0;
+}
+
+// -- Function definitions
+void ui_nogen1()
+{
+}
+
+void ui_nogen2()
+{
+}
diff --git a/Tests/QtAutogen/sub/uiconly.cpp b/Tests/QtAutogen/sub/uiconly.cpp
deleted file mode 100644
index ac22789..0000000
--- a/Tests/QtAutogen/sub/uiconly.cpp
+++ /dev/null
@@ -1,13 +0,0 @@
-
-#include "uiconly.h"
-
-UicOnly::UicOnly(QWidget* parent)
-  : QWidget(parent)
-  , ui(new Ui::UicOnly)
-{
-}
-
-int main()
-{
-  return 0;
-}
diff --git a/Tests/QtAutogen/sub/uiconly.h b/Tests/QtAutogen/sub/uiconly.h
deleted file mode 100644
index 9b0b1b4..0000000
--- a/Tests/QtAutogen/sub/uiconly.h
+++ /dev/null
@@ -1,20 +0,0 @@
-
-#ifndef UIC_ONLY_H
-#define UIC_ONLY_H
-
-#include <QWidget>
-#include <memory>
-
-#include "ui_uiconly.h"
-
-class UicOnly : public QWidget
-{
-  Q_OBJECT
-public:
-  explicit UicOnly(QWidget* parent = 0);
-
-private:
-  const std::auto_ptr<Ui::UicOnly> ui;
-};
-
-#endif
diff --git a/Tests/QtAutogen/uicOnlySource/uiconly.cpp b/Tests/QtAutogen/uicOnlySource/uiconly.cpp
new file mode 100644
index 0000000..7b91b25
--- /dev/null
+++ b/Tests/QtAutogen/uicOnlySource/uiconly.cpp
@@ -0,0 +1,18 @@
+
+#include "uiconly.h"
+
+UicOnly::UicOnly(QWidget* parent)
+  : QWidget(parent)
+  , ui(new Ui::UicOnly)
+{
+}
+
+UicOnly::~UicOnly()
+{
+  delete ui;
+}
+
+int main()
+{
+  return 0;
+}
diff --git a/Tests/QtAutogen/uicOnlySource/uiconly.h b/Tests/QtAutogen/uicOnlySource/uiconly.h
new file mode 100644
index 0000000..8f4eebe
--- /dev/null
+++ b/Tests/QtAutogen/uicOnlySource/uiconly.h
@@ -0,0 +1,20 @@
+
+#ifndef UIC_ONLY_H
+#define UIC_ONLY_H
+
+#include <QWidget>
+
+#include "ui_uiconly.h"
+
+class UicOnly : public QWidget
+{
+  Q_OBJECT
+public:
+  explicit UicOnly(QWidget* parent = 0);
+  ~UicOnly();
+
+private:
+  Ui::UicOnly* ui;
+};
+
+#endif
diff --git a/Tests/QtAutogen/sub/uiconly.ui b/Tests/QtAutogen/uicOnlySource/uiconly.ui
similarity index 100%
rename from Tests/QtAutogen/sub/uiconly.ui
rename to Tests/QtAutogen/uicOnlySource/uiconly.ui
diff --git a/Tests/RunCMake/AndroidTestUtilities/RunCMakeTest.cmake b/Tests/RunCMake/AndroidTestUtilities/RunCMakeTest.cmake
index f0ae24b..7d031d4 100644
--- a/Tests/RunCMake/AndroidTestUtilities/RunCMakeTest.cmake
+++ b/Tests/RunCMake/AndroidTestUtilities/RunCMakeTest.cmake
@@ -18,3 +18,4 @@ endfunction()
 run_ATU(SetupTest1 "")
 run_ATU(SetupTest2 "tests")
 run_ATU(SetupTest3 "tests")
+run_ATU(SetupTest4 "")
diff --git a/Tests/RunCMake/AndroidTestUtilities/SetupTest4.cmake b/Tests/RunCMake/AndroidTestUtilities/SetupTest4.cmake
new file mode 100644
index 0000000..9a27266
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/SetupTest4.cmake
@@ -0,0 +1,13 @@
+enable_testing()
+include(AndroidTestUtilities)
+
+find_program(adb_executable adb)
+
+set(test_files "data/a.txt")
+
+set(ANDROID 1)
+
+android_add_test_data(setup_test
+  FILES ${test_files}
+  DEVICE_TEST_DIR "/data/local/tests/example1"
+  DEVICE_OBJECT_STORE "/sdcard/.ExternalData/SHA")
diff --git a/Tests/RunCMake/AndroidTestUtilities/SetupTest4Build-check.cmake b/Tests/RunCMake/AndroidTestUtilities/SetupTest4Build-check.cmake
new file mode 100644
index 0000000..ef7569d
--- /dev/null
+++ b/Tests/RunCMake/AndroidTestUtilities/SetupTest4Build-check.cmake
@@ -0,0 +1,5 @@
+include(${CMAKE_CURRENT_LIST_DIR}/check.cmake)
+compare_build_to_expected(FILES
+  "data/a.txt"
+  )
+check_for_setup_test()
diff --git a/Tests/RunCMake/CMakeLists.txt b/Tests/RunCMake/CMakeLists.txt
index 9dc540f..a16efb3 100644
--- a/Tests/RunCMake/CMakeLists.txt
+++ b/Tests/RunCMake/CMakeLists.txt
@@ -153,6 +153,9 @@ add_RunCMake_test(TargetPropertyGeneratorExpressions)
 add_RunCMake_test(Languages)
 add_RunCMake_test(LinkStatic)
 add_RunCMake_test(ObjectLibrary)
+if(UNIX AND CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG AND CMAKE_EXECUTABLE_FORMAT STREQUAL "ELF")
+  add_RunCMake_test(RuntimePath)
+endif()
 add_RunCMake_test(Swift)
 add_RunCMake_test(TargetObjects)
 add_RunCMake_test(TargetSources)
@@ -179,6 +182,9 @@ add_RunCMake_test(add_custom_target)
 add_RunCMake_test(add_dependencies)
 add_RunCMake_test(add_subdirectory)
 add_RunCMake_test(build_command)
+if(NOT CMake_TEST_EXTERNAL_CMAKE)
+  set(execute_process_ARGS -DTEST_ENCODING_EXE=$<TARGET_FILE:testEncoding>)
+endif()
 add_RunCMake_test(execute_process)
 add_RunCMake_test(export)
 add_RunCMake_test(cmake_minimum_required)
@@ -212,6 +218,19 @@ add_RunCMake_test(project -DCMake_TEST_RESOURCES=${CMake_TEST_RESOURCES})
 add_RunCMake_test(return)
 add_RunCMake_test(set_property)
 add_RunCMake_test(string)
+foreach(var
+    CMAKE_C_COMPILER_ID
+    CMAKE_C_COMPILER_VERSION
+    CMAKE_C_STANDARD_DEFAULT
+    CMAKE_CXX_COMPILER_ID
+    CMAKE_CXX_COMPILER_VERSION
+    CMAKE_CXX_STANDARD_DEFAULT
+    CMake_TEST_CUDA
+    )
+  if(DEFINED ${var})
+    list(APPEND try_compile_ARGS -D${var}=${${var}})
+  endif()
+endforeach()
 add_RunCMake_test(try_compile)
 add_RunCMake_test(try_run)
 add_RunCMake_test(set)
@@ -239,6 +258,11 @@ if(PKG_CONFIG_FOUND)
   add_RunCMake_test(FindPkgConfig)
 endif()
 
+find_package(GTK2 QUIET)
+if (GTK2_FOUND)
+  add_RunCMake_test(FindGTK2)
+endif()
+
 if("${CMAKE_GENERATOR}" MATCHES "Visual Studio")
   add_RunCMake_test(include_external_msproject)
   if("${CMAKE_GENERATOR}" MATCHES "Visual Studio ([789]|10)" AND NOT CMAKE_VS_DEVENV_COMMAND)
@@ -255,8 +279,7 @@ if(XCODE_VERSION AND NOT "${XCODE_VERSION}" VERSION_LESS 3)
   add_RunCMake_test(XcodeProject -DXCODE_VERSION=${XCODE_VERSION})
 endif()
 
-if(NOT XCODE
-    AND CMAKE_C_COMPILER_ID STREQUAL "AppleClang"
+if(CMAKE_C_COMPILER_ID STREQUAL "AppleClang"
     AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 6.0)
   add_RunCMake_test(Framework)
 endif()
@@ -324,12 +347,14 @@ if("${CMAKE_GENERATOR}" MATCHES "Make|Ninja")
   endif()
   add_executable(pseudo_tidy pseudo_tidy.c)
   add_executable(pseudo_iwyu pseudo_iwyu.c)
+  add_executable(pseudo_cpplint pseudo_cpplint.c)
   add_RunCMake_test(ClangTidy -DPSEUDO_TIDY=$<TARGET_FILE:pseudo_tidy>)
   add_RunCMake_test(IncludeWhatYouUse -DPSEUDO_IWYU=$<TARGET_FILE:pseudo_iwyu>)
+  add_RunCMake_test(Cpplint -DPSEUDO_CPPLINT=$<TARGET_FILE:pseudo_cpplint>)
   add_RunCMake_test(CompilerLauncher)
 endif()
 
-add_RunCMake_test_group(CPack "DEB;RPM;TGZ")
+add_RunCMake_test_group(CPack "DEB;RPM;7Z;TBZ2;TGZ;TXZ;TZ;ZIP;STGZ")
 # add a test to make sure symbols are exported from a shared library
 # for MSVC compilers CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS property is used
 add_RunCMake_test(AutoExportDll)
diff --git a/Tests/RunCMake/CPack/7Z/Helpers.cmake b/Tests/RunCMake/CPack/7Z/Helpers.cmake
new file mode 100644
index 0000000..f256a42
--- /dev/null
+++ b/Tests/RunCMake/CPack/7Z/Helpers.cmake
@@ -0,0 +1,3 @@
+set(cpack_archive_extension_ "7z")
+
+include("${CMAKE_CURRENT_LIST_DIR}/../ArchiveCommon/common_helpers.cmake")
diff --git a/Tests/RunCMake/CPack/7Z/Prerequirements.cmake b/Tests/RunCMake/CPack/7Z/Prerequirements.cmake
new file mode 100644
index 0000000..dbaf682
--- /dev/null
+++ b/Tests/RunCMake/CPack/7Z/Prerequirements.cmake
@@ -0,0 +1,4 @@
+function(get_test_prerequirements found_var config_file)
+  file(WRITE "${config_file}" "")
+  set(${found_var} true PARENT_SCOPE)
+endfunction()
diff --git a/Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake b/Tests/RunCMake/CPack/7Z/packaging_COMPONENT_default.cmake
similarity index 100%
copy from Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake
copy to Tests/RunCMake/CPack/7Z/packaging_COMPONENT_default.cmake
diff --git a/Tests/RunCMake/CPack/ArchiveCommon/common_helpers.cmake b/Tests/RunCMake/CPack/ArchiveCommon/common_helpers.cmake
new file mode 100644
index 0000000..ce039f5
--- /dev/null
+++ b/Tests/RunCMake/CPack/ArchiveCommon/common_helpers.cmake
@@ -0,0 +1,62 @@
+set(ALL_FILES_GLOB "*.${cpack_archive_extension_}")
+
+function(getPackageContent FILE RESULT_VAR)
+  # TODO for some types this only works because libarchive handles it... (not
+  #      part of for e.g. gnu tar)
+  execute_process(COMMAND ${CMAKE_COMMAND} -E tar -xtf ${FILE}
+          OUTPUT_VARIABLE package_content_
+          ERROR_QUIET
+          OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+  set(${RESULT_VAR} "${package_content_}" PARENT_SCOPE)
+endfunction()
+
+function(getPackageNameGlobexpr NAME COMPONENT VERSION REVISION FILE_NO RESULT_VAR)
+  if(COMPONENT)
+    set(COMPONENT "-${COMPONENT}")
+  endif()
+
+  set(${RESULT_VAR}
+    "${NAME}-${VERSION}-*${COMPONENT}.${cpack_archive_extension_}" PARENT_SCOPE)
+endfunction()
+
+function(getPackageContentList FILE RESULT_VAR)
+  getPackageContent("${FILE}" package_content_)
+
+  string(REPLACE "\n" ";" package_content_ "${package_content_}")
+  foreach(i_ IN LISTS package_content_)
+    string(REGEX REPLACE "/$" "" result_ "${i_}")
+    list(APPEND items_ "${result_}")
+  endforeach()
+
+  set(${RESULT_VAR} "${items_}" PARENT_SCOPE)
+endfunction()
+
+function(toExpectedContentList FILE_NO CONTENT_VAR)
+  findExpectedFile("${FILE_NO}" "file_")
+
+  # component and monolithic packages differ for some reason by either having
+  # package filename prefix in path or not
+  if(PACKAGING_TYPE STREQUAL "MONOLITHIC")
+    get_filename_component(prefix_ "${file_}" NAME)
+    # NAME_WE removes everything after the dot and dot is in version so replace instead
+    string(REPLACE ".${cpack_archive_extension_}" "/" prefix_ "${prefix_}")
+  else()
+    unset(prefix_)
+  endif()
+
+  if(NOT DEFINED TEST_MAIN_INSTALL_PREFIX_PATH)
+    set(TEST_MAIN_INSTALL_PREFIX_PATH "/usr")
+  endif()
+
+  unset(filtered_)
+  foreach(part_ IN LISTS ${CONTENT_VAR})
+    string(REGEX REPLACE "^${TEST_MAIN_INSTALL_PREFIX_PATH}(/|$)" "" part_ "${part_}")
+
+    if(part_)
+      list(APPEND filtered_ "${prefix_}${part_}")
+    endif()
+  endforeach()
+
+  set(${CONTENT_VAR} "${filtered_}" PARENT_SCOPE)
+endfunction()
diff --git a/Tests/RunCMake/CPack/CMakeLists.txt b/Tests/RunCMake/CPack/CMakeLists.txt
index e42e971..c361af0 100644
--- a/Tests/RunCMake/CPack/CMakeLists.txt
+++ b/Tests/RunCMake/CPack/CMakeLists.txt
@@ -1,12 +1,17 @@
 cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
 
+set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "")
+
 project(${RunCMake_TEST} CXX)
-include(${RunCMake_TEST_FILE_PREFIX}.cmake)
 
-# include test generator specifics
-if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${GENERATOR_TYPE}/${RunCMake_TEST_FILE_PREFIX}-specifics.cmake")
-  include("${GENERATOR_TYPE}/${RunCMake_TEST_FILE_PREFIX}-specifics.cmake")
+if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${GENERATOR_TYPE}/packaging_${PACKAGING_TYPE}_default.cmake")
+  include(${GENERATOR_TYPE}/packaging_${PACKAGING_TYPE}_default.cmake)
 endif()
 
+# set default test name (can be overwritten in test.cmake or specifics.cmake)
+string(TOLOWER "${RunCMake_TEST_FILE_PREFIX}" CPACK_PACKAGE_NAME)
+
+include(tests/${RunCMake_TEST_FILE_PREFIX}/test.cmake)
+
 set(CPACK_GENERATOR "${GENERATOR_TYPE}")
 include(CPack)
diff --git a/Tests/RunCMake/CPack/COMPONENTS_EMPTY_DIR.cmake b/Tests/RunCMake/CPack/COMPONENTS_EMPTY_DIR.cmake
deleted file mode 100644
index 7210e7d..0000000
--- a/Tests/RunCMake/CPack/COMPONENTS_EMPTY_DIR.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(CPACK_COMPONENTS_ALL test)
-install(DIRECTORY DESTINATION empty
-        COMPONENT test)
-
-set(CPACK_PACKAGE_NAME "components_empty_dir")
diff --git a/Tests/RunCMake/CPack/CPackTestHelpers.cmake b/Tests/RunCMake/CPack/CPackTestHelpers.cmake
index 7e6b4b1..f883c69 100644
--- a/Tests/RunCMake/CPack/CPackTestHelpers.cmake
+++ b/Tests/RunCMake/CPack/CPackTestHelpers.cmake
@@ -1,6 +1,6 @@
 cmake_policy(SET CMP0057 NEW)
 
-function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source)
+function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source PACKAGING_TYPE)
   if(TEST_TYPE IN_LIST types)
     set(RunCMake_TEST_NO_CLEAN TRUE)
     set(RunCMake_TEST_BINARY_DIR "${RunCMake_BINARY_DIR}/${TEST_NAME}-build")
@@ -11,16 +11,17 @@ function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source)
       set(full_test_name_ "${full_test_name_}-${SUBTEST_SUFFIX}-subtest")
     endif()
 
+    string(APPEND full_test_name_ "-${PACKAGING_TYPE}-type")
+
      # TODO this should be executed only once per ctest run (not per generator)
     file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
     file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
 
-    if(EXISTS "${RunCMake_SOURCE_DIR}/${TEST_TYPE}/${TEST_NAME}-Prerequirements.cmake")
-      include("${RunCMake_SOURCE_DIR}/${TEST_TYPE}/${TEST_NAME}-Prerequirements.cmake")
+    if(EXISTS "${RunCMake_SOURCE_DIR}/tests/${TEST_NAME}/${TEST_TYPE}-Prerequirements.cmake")
+      include("${RunCMake_SOURCE_DIR}/tests/${TEST_NAME}/${TEST_TYPE}-Prerequirements.cmake")
 
       set(FOUND_PREREQUIREMENTS false)
-      get_test_prerequirements("FOUND_PREREQUIREMENTS"
-          "${TEST_CONFIG_DIR}/${type}_config.cmake")
+      get_test_prerequirements("FOUND_PREREQUIREMENTS" "${config_file}")
 
       # skip the test if prerequirements are not met
       if(NOT FOUND_PREREQUIREMENTS)
@@ -32,7 +33,8 @@ function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source)
     # execute cmake
     set(RunCMake_TEST_OPTIONS "-DGENERATOR_TYPE=${TEST_TYPE}"
       "-DRunCMake_TEST_FILE_PREFIX=${TEST_NAME}"
-      "-DRunCMake_SUBTEST_SUFFIX=${SUBTEST_SUFFIX}")
+      "-DRunCMake_SUBTEST_SUFFIX=${SUBTEST_SUFFIX}"
+      "-DPACKAGING_TYPE=${PACKAGING_TYPE}")
     run_cmake(${full_test_name_})
 
     # execute optional build step
@@ -43,7 +45,7 @@ function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source)
     if(source)
       set(pack_params_ -G ${TEST_TYPE} --config ./CPackSourceConfig.cmake)
       FILE(APPEND ${RunCMake_TEST_BINARY_DIR}/CPackSourceConfig.cmake
-        "\nset(CPACK_RPM_SOURCE_PKG_BUILD_PARAMS \"-DRunCMake_TEST:STRING=${full_test_name_}\ -DRunCMake_TEST_FILE_PREFIX:STRING=${TEST_NAME}\")")
+        "\nset(CPACK_RPM_SOURCE_PKG_BUILD_PARAMS \"-DRunCMake_TEST:STRING=${full_test_name_} -DRunCMake_TEST_FILE_PREFIX:STRING=${TEST_NAME} -DGENERATOR_TYPE:STRING=${TEST_TYPE}\")")
     else()
       unset(pack_params_)
     endif()
@@ -58,10 +60,16 @@ function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source)
       )
 
     foreach(o out err)
-      if(SUBTEST_SUFFIX AND EXISTS ${RunCMake_SOURCE_DIR}/${TEST_TYPE}/${TEST_NAME}-${SUBTEST_SUFFIX}-std${o}.txt)
-        set(RunCMake-std${o}-file "${TEST_TYPE}/${TEST_NAME}-${SUBTEST_SUFFIX}-std${o}.txt")
-      elseif(EXISTS ${RunCMake_SOURCE_DIR}/${TEST_TYPE}/${TEST_NAME}-std${o}.txt)
-        set(RunCMake-std${o}-file "${TEST_TYPE}/${TEST_NAME}-std${o}.txt")
+      if(SUBTEST_SUFFIX AND EXISTS ${RunCMake_SOURCE_DIR}/tests/${TEST_NAME}/${TEST_TYPE}-${PACKAGING_TYPE}-${SUBTEST_SUFFIX}-std${o}.txt)
+        set(RunCMake-std${o}-file "tests/${TEST_NAME}/${TEST_TYPE}-${PACKAGING_TYPE}-${SUBTEST_SUFFIX}-std${o}.txt")
+      elseif(EXISTS ${RunCMake_SOURCE_DIR}/tests/${TEST_NAME}/${TEST_TYPE}-${PACKAGING_TYPE}-std${o}.txt)
+        set(RunCMake-std${o}-file "tests/${TEST_NAME}/${TEST_TYPE}-${PACKAGING_TYPE}-std${o}.txt")
+      elseif(SUBTEST_SUFFIX AND EXISTS ${RunCMake_SOURCE_DIR}/tests/${TEST_NAME}/${TEST_TYPE}-${SUBTEST_SUFFIX}-std${o}.txt)
+        set(RunCMake-std${o}-file "tests/${TEST_NAME}/${TEST_TYPE}-${SUBTEST_SUFFIX}-std${o}.txt")
+      elseif(EXISTS ${RunCMake_SOURCE_DIR}/tests/${TEST_NAME}/${TEST_TYPE}-std${o}.txt)
+        set(RunCMake-std${o}-file "tests/${TEST_NAME}/${TEST_TYPE}-std${o}.txt")
+      elseif(EXISTS ${RunCMake_SOURCE_DIR}/${TEST_TYPE}/default_expected_std${o}.txt)
+        set(RunCMake-std${o}-file "${TEST_TYPE}/default_expected_std${o}.txt")
       endif()
     endforeach()
 
@@ -73,6 +81,7 @@ function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source)
         -DRunCMake_TEST_FILE_PREFIX=${TEST_NAME}
         -DRunCMake_SUBTEST_SUFFIX=${SUBTEST_SUFFIX}
         -DGENERATOR_TYPE=${TEST_TYPE}
+        -DPACKAGING_TYPE=${PACKAGING_TYPE}
         "-Dsrc_dir=${RunCMake_SOURCE_DIR}"
         "-Dbin_dir=${RunCMake_TEST_BINARY_DIR}"
         "-Dconfig_file=${config_file}"
@@ -81,16 +90,20 @@ function(run_cpack_test_common_ TEST_NAME types build SUBTEST_SUFFIX source)
   endif()
 endfunction()
 
-function(run_cpack_test TEST_NAME types build)
-  run_cpack_test_common_("${TEST_NAME}" "${types}" "${build}" "" false)
-endfunction()
-
-function(run_cpack_source_test TEST_NAME types build)
-  run_cpack_test_common_("${TEST_NAME}" "${types}" "${build}" "" true)
+function(run_cpack_test TEST_NAME types build PACKAGING_TYPES)
+  foreach(packaging_type_ IN LISTS PACKAGING_TYPES)
+    run_cpack_test_common_("${TEST_NAME}" "${types}" "${build}" "" false "${packaging_type_}")
+  endforeach()
 endfunction()
 
-function(run_cpack_test_subtests TEST_NAME SUBTEST_SUFFIXES types build)
+function(run_cpack_test_subtests TEST_NAME SUBTEST_SUFFIXES types build PACKAGING_TYPES)
   foreach(suffix_ IN LISTS SUBTEST_SUFFIXES)
-    run_cpack_test_common_("${TEST_NAME}" "${types}" "${build}" "${suffix_}" false)
+    foreach(packaging_type_ IN LISTS PACKAGING_TYPES)
+      run_cpack_test_common_("${TEST_NAME}" "${types}" "${build}" "${suffix_}" false "${packaging_type_}")
+    endforeach()
   endforeach()
 endfunction()
+
+function(run_cpack_source_test TEST_NAME types)
+  run_cpack_test_common_("${TEST_NAME}" "${types}" false "" true "")
+endfunction()
diff --git a/Tests/RunCMake/CPack/CUSTOM_NAMES.cmake b/Tests/RunCMake/CPack/CUSTOM_NAMES.cmake
deleted file mode 100644
index c89df89..0000000
--- a/Tests/RunCMake/CPack/CUSTOM_NAMES.cmake
+++ /dev/null
@@ -1,7 +0,0 @@
-set(CPACK_RPM_COMPONENT_INSTALL "ON")
-
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_1)
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_2)
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_3)
-
-set(CPACK_PACKAGE_NAME "custom_names")
diff --git a/Tests/RunCMake/CPack/DEB/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake
deleted file mode 100644
index 62f2f9c..0000000
--- a/Tests/RunCMake/CPack/DEB/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "components_empty_dir-test_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/${whitespaces_}.*/usr/empty/$")
diff --git a/Tests/RunCMake/CPack/DEB/COMPONENTS_EMPTY_DIR-specifics.cmake b/Tests/RunCMake/CPack/DEB/COMPONENTS_EMPTY_DIR-specifics.cmake
deleted file mode 100644
index 4b4ac8d..0000000
--- a/Tests/RunCMake/CPack/DEB/COMPONENTS_EMPTY_DIR-specifics.cmake
+++ /dev/null
@@ -1,3 +0,0 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEB_COMPONENT_INSTALL "ON")
-set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
diff --git a/Tests/RunCMake/CPack/DEB/CUSTOM_NAMES-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/CUSTOM_NAMES-ExpectedFiles.cmake
deleted file mode 100644
index 2acf45b..0000000
--- a/Tests/RunCMake/CPack/DEB/CUSTOM_NAMES-ExpectedFiles.cmake
+++ /dev/null
@@ -1,9 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "3")
-set(EXPECTED_FILE_1 "custom_names-pkg_1_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/foo${whitespaces_}.*/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_2 "second*.deb")
-set(EXPECTED_FILE_CONTENT_2 "^.*/usr/foo${whitespaces_}.*/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_3 "pkg_3_abc.deb")
-set(EXPECTED_FILE_CONTENT_3 "^.*/usr/foo${whitespaces_}.*/usr/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/DEB/CUSTOM_NAMES-specifics.cmake b/Tests/RunCMake/CPack/DEB/CUSTOM_NAMES-specifics.cmake
deleted file mode 100644
index c64f161..0000000
--- a/Tests/RunCMake/CPack/DEB/CUSTOM_NAMES-specifics.cmake
+++ /dev/null
@@ -1,6 +0,0 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEB_COMPONENT_INSTALL "ON")
-
-set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
-set(CPACK_DEBIAN_PKG_2_PACKAGE_NAME "second")
-set(CPACK_DEBIAN_PKG_3_FILE_NAME "pkg_3_abc.deb")
diff --git a/Tests/RunCMake/CPack/DEB/DEB_EXTRA-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/DEB_EXTRA-ExpectedFiles.cmake
deleted file mode 100644
index 4531a34..0000000
--- a/Tests/RunCMake/CPack/DEB/DEB_EXTRA-ExpectedFiles.cmake
+++ /dev/null
@@ -1,9 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "3")
-set(EXPECTED_FILE_1 "deb_extra-foo_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/${whitespaces_}.*/usr/foo/${whitespaces_}.*/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_2 "deb_extra-bar_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_2 "^.*/usr/${whitespaces_}.*/usr/bar/${whitespaces_}.*/usr/bar/CMakeLists.txt$")
-set(EXPECTED_FILE_3 "deb_extra-bas_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_3 "^.*/usr/${whitespaces_}.*/usr/bas/${whitespaces_}.*/usr/bas/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-ExpectedFiles.cmake
deleted file mode 100644
index a8efb61..0000000
--- a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-ExpectedFiles.cmake
+++ /dev/null
@@ -1,6 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "generate_shlibs_0.1.1-1_*.deb")
-# dynamic lib extension is .so on Linux and .dylib on Mac so we will use a wildcard .* for it
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/foo${whitespaces_}.*/usr/foo/libtest_lib\\..*$")
diff --git a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-Prerequirements.cmake b/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-Prerequirements.cmake
deleted file mode 100644
index b98065a..0000000
--- a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-Prerequirements.cmake
+++ /dev/null
@@ -1,7 +0,0 @@
-function(get_test_prerequirements found_var)
-  find_program(READELF_EXECUTABLE NAMES readelf)
-
-  if(READELF_EXECUTABLE)
-    set(${found_var} true PARENT_SCOPE)
-  endif()
-endfunction()
diff --git a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-ExpectedFiles.cmake
deleted file mode 100644
index 9a9dee3..0000000
--- a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-ExpectedFiles.cmake
+++ /dev/null
@@ -1,6 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "generate_shlibs_ldconfig_0.1.1-1_*.deb")
-# dynamic lib extension is .so on Linux and .dylib on Mac so we will use a wildcard .* for it
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/lib${whitespaces_}.*/usr/lib/libtest_lib\\..*$")
diff --git a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-Prerequirements.cmake b/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-Prerequirements.cmake
deleted file mode 100644
index b98065a..0000000
--- a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-Prerequirements.cmake
+++ /dev/null
@@ -1,7 +0,0 @@
-function(get_test_prerequirements found_var)
-  find_program(READELF_EXECUTABLE NAMES readelf)
-
-  if(READELF_EXECUTABLE)
-    set(${found_var} true PARENT_SCOPE)
-  endif()
-endfunction()
diff --git a/Tests/RunCMake/CPack/DEB/DEPENDENCIES-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/DEPENDENCIES-ExpectedFiles.cmake
deleted file mode 100644
index a6f08fe..0000000
--- a/Tests/RunCMake/CPack/DEB/DEPENDENCIES-ExpectedFiles.cmake
+++ /dev/null
@@ -1,14 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "5")
-set(EXPECTED_FILE_1 "dependencies-0.1.1-*-applications.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/foo${whitespaces_}.*/usr/foo/test_prog$")
-set(EXPECTED_FILE_2 "dependencies-0.1.1-*-applications_auto.deb")
-set(EXPECTED_FILE_CONTENT_2 "^.*/usr/foo_auto${whitespaces_}.*/usr/foo_auto/test_prog$")
-set(EXPECTED_FILE_3 "dependencies-0.1.1-*-headers.deb")
-set(EXPECTED_FILE_CONTENT_3 "^.*/usr/bar${whitespaces_}.*/usr/bar/CMakeLists.txt$")
-set(EXPECTED_FILE_4 "dependencies-0.1.1-*-libs.deb")
-# dynamic lib extension is .so on Linux and .dylib on Mac so we will use a wildcard .* for it
-set(EXPECTED_FILE_CONTENT_4 "^.*/usr/bas${whitespaces_}.*/usr/bas/libtest_lib\\..*$")
-set(EXPECTED_FILE_5 "dependencies-0.1.1-*-libs_auto.deb")
-set(EXPECTED_FILE_CONTENT_5 "^.*/usr/bas_auto${whitespaces_}.*/usr/bas_auto/libtest_lib\\..*$")
diff --git a/Tests/RunCMake/CPack/DEB/DEPENDENCIES-VerifyResult.cmake b/Tests/RunCMake/CPack/DEB/DEPENDENCIES-VerifyResult.cmake
deleted file mode 100644
index ba39f2e..0000000
--- a/Tests/RunCMake/CPack/DEB/DEPENDENCIES-VerifyResult.cmake
+++ /dev/null
@@ -1,34 +0,0 @@
-function(checkDependencies_ FILE REGEX)
-  set(whitespaces_ "[\t\n\r ]*")
-
-  getPackageInfo("${FILE}" "FILE_INFO_")
-  if(NOT FILE_INFO_ MATCHES "${REGEX}")
-    message(FATAL_ERROR "Unexpected dependencies in '${FILE}'; file info: '${FILE_INFO_}'")
-  endif()
-endfunction()
-
-foreach(dependency_type_ DEPENDS CONFLICTS ENHANCES BREAKS REPLACES RECOMMENDS SUGGESTS)
-  string(TOLOWER "${dependency_type_}" lower_dependency_type_)
-  string(SUBSTRING ${lower_dependency_type_} 1 -1 lower_dependency_type_tail_)
-  string(SUBSTRING ${dependency_type_} 0 1 dependency_type_head_)
-  set(dependency_type_name_ "${dependency_type_head_}${lower_dependency_type_tail_}")
-
-  checkDependencies_("${FOUND_FILE_1}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b.*")
-  checkDependencies_("${FOUND_FILE_2}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}.*${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b.*")
-  checkDependencies_("${FOUND_FILE_3}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-headers.*")
-  checkDependencies_("${FOUND_FILE_4}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-default, ${lower_dependency_type_}-default-b.*")
-  checkDependencies_("${FOUND_FILE_5}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-default, ${lower_dependency_type_}-default-b.*")
-endforeach()
-
-checkDependencies_("${FOUND_FILE_1}" ".*Provides${whitespaces_}:${whitespaces_}provided-default, provided-default-b")
-checkDependencies_("${FOUND_FILE_2}" ".*Provides${whitespaces_}:${whitespaces_}provided-default, provided-default-b")
-checkDependencies_("${FOUND_FILE_3}" ".*Provides${whitespaces_}:${whitespaces_}provided-default, provided-default-b")
-checkDependencies_("${FOUND_FILE_4}" ".*Provides${whitespaces_}:${whitespaces_}provided-lib.*")
-checkDependencies_("${FOUND_FILE_5}" ".*Provides${whitespaces_}:${whitespaces_}provided-lib_auto.*, provided-lib_auto-b.*")
-
-# PREDEPENDS
-checkDependencies_("${FOUND_FILE_1}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-application, predepends-application-b.*")
-checkDependencies_("${FOUND_FILE_2}" ".*Pre-Depends${whitespaces_}:${whitespaces_}.*predepends-application, predepends-application-b.*")
-checkDependencies_("${FOUND_FILE_3}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-headers.*")
-checkDependencies_("${FOUND_FILE_4}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-default, predepends-default-b.*")
-checkDependencies_("${FOUND_FILE_5}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-default, predepends-default-b.*")
diff --git a/Tests/RunCMake/CPack/DEB/DEPENDENCIES-specifics.cmake b/Tests/RunCMake/CPack/DEB/DEPENDENCIES-specifics.cmake
deleted file mode 100644
index 5f82cc6..0000000
--- a/Tests/RunCMake/CPack/DEB/DEPENDENCIES-specifics.cmake
+++ /dev/null
@@ -1,23 +0,0 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEB_COMPONENT_INSTALL "ON")
-#intentionaly commented out to test old file naming
-#set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
-
-# false by default
-set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS FALSE)
-# FIXME can not be tested as libraries first have to be part of a package in order
-# to determine their dependencies and we can not be certain if there will be any
-set(CPACK_DEBIAN_APPLICATIONS_AUTO_PACKAGE_SHLIBDEPS TRUE)
-
-foreach(dependency_type_ DEPENDS CONFLICTS PREDEPENDS ENHANCES BREAKS REPLACES RECOMMENDS SUGGESTS)
-  string(TOLOWER "${dependency_type_}" lower_dependency_type_)
-
-  set(CPACK_DEBIAN_PACKAGE_${dependency_type_} "${lower_dependency_type_}-default, ${lower_dependency_type_}-default-b")
-  set(CPACK_DEBIAN_APPLICATIONS_PACKAGE_${dependency_type_} "${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b")
-  set(CPACK_DEBIAN_APPLICATIONS_AUTO_PACKAGE_${dependency_type_} "${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b")
-  set(CPACK_DEBIAN_HEADERS_PACKAGE_${dependency_type_} "${lower_dependency_type_}-headers")
-endforeach()
-
-set(CPACK_DEBIAN_PACKAGE_PROVIDES "provided-default, provided-default-b")
-set(CPACK_DEBIAN_LIBS_PACKAGE_PROVIDES "provided-lib")
-set(CPACK_DEBIAN_LIBS_AUTO_PACKAGE_PROVIDES "provided-lib_auto, provided-lib_auto-b")
diff --git a/Tests/RunCMake/CPack/DEB/EMPTY_DIR-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/EMPTY_DIR-ExpectedFiles.cmake
deleted file mode 100644
index 6dc5906..0000000
--- a/Tests/RunCMake/CPack/DEB/EMPTY_DIR-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "empty_dir_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/${whitespaces_}.*/usr/empty/$")
diff --git a/Tests/RunCMake/CPack/DEB/EMPTY_DIR-specifics.cmake b/Tests/RunCMake/CPack/DEB/EMPTY_DIR-specifics.cmake
deleted file mode 100644
index 4e9a2e7..0000000
--- a/Tests/RunCMake/CPack/DEB/EMPTY_DIR-specifics.cmake
+++ /dev/null
@@ -1,2 +0,0 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
diff --git a/Tests/RunCMake/CPack/DEB/Helpers.cmake b/Tests/RunCMake/CPack/DEB/Helpers.cmake
index 9b1be22..ad1b47b 100644
--- a/Tests/RunCMake/CPack/DEB/Helpers.cmake
+++ b/Tests/RunCMake/CPack/DEB/Helpers.cmake
@@ -9,6 +9,47 @@ function(getPackageContent FILE RESULT_VAR)
   set(${RESULT_VAR} "${package_content_}" PARENT_SCOPE)
 endfunction()
 
+function(getPackageNameGlobexpr NAME COMPONENT VERSION REVISION FILE_NO RESULT_VAR)
+  if(COMPONENT)
+    set(COMPONENT "-${COMPONENT}")
+  endif()
+
+  if(DEFINED EXPECTED_FILE_${FILE_NO}_FILENAME_GENERATOR_SPECIFIC_FORMAT)
+    set(GENERATOR_SPECIFIC_FORMAT "${EXPECTED_FILE_${FILE_NO}_FILENAME_GENERATOR_SPECIFIC_FORMAT}")
+  elseif(DEFINED EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT)
+    set(GENERATOR_SPECIFIC_FORMAT "${EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT}")
+  else()
+    set(GENERATOR_SPECIFIC_FORMAT FALSE)
+  endif()
+
+  if(GENERATOR_SPECIFIC_FORMAT)
+    set(${RESULT_VAR} "${NAME}${COMPONENT}_${VERSION}-${REVISION}_*.deb" PARENT_SCOPE)
+  else()
+    set(${RESULT_VAR} "${NAME}-${VERSION}-*${COMPONENT}.deb" PARENT_SCOPE)
+  endif()
+endfunction()
+
+function(getPackageContentList FILE RESULT_VAR)
+  execute_process(COMMAND ${DPKG_EXECUTABLE} -c "${FILE}"
+          OUTPUT_VARIABLE package_content_
+          ERROR_QUIET
+          OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+  unset(items_)
+  string(REPLACE "\n" ";" package_content_ "${package_content_}")
+  foreach(i_ IN LISTS package_content_)
+    string(REGEX REPLACE "^.* \.(/[^$]*)$" "\\1" result_ "${i_}")
+    string(REGEX REPLACE "/$" "" result_ "${result_}")
+    list(APPEND items_ "${result_}")
+  endforeach()
+
+  set(${RESULT_VAR} "${items_}" PARENT_SCOPE)
+endfunction()
+
+function(toExpectedContentList FILE_NO CONTENT_VAR)
+  # no need to do anything
+endfunction()
+
 function(getMissingShlibsErrorExtra FILE RESULT_VAR)
     execute_process(COMMAND ${DPKG_EXECUTABLE} -x "${FILE}" data_${PREFIX}
             ERROR_VARIABLE err_)
@@ -43,8 +84,6 @@ function(getMissingShlibsErrorExtra FILE RESULT_VAR)
         string(APPEND error_extra "; errors \"${deb_install_files_errors}\"")
       endif()
 
-      find_program(READELF_EXECUTABLE NAMES readelf)
-
       if(READELF_EXECUTABLE)
         string(APPEND error_extra "; readelf \"\n")
 
diff --git a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-ExpectedFiles.cmake
deleted file mode 100644
index dd72cf7..0000000
--- a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "long_filenames_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/${whitespaces_}.*/usr/foo/${whitespaces_}.*/usr/foo/llllllllll_oooooooooo_nnnnnnnnnn_gggggggggg_ffffffffff_iiiiiiiiii_llllllllll_eeeeeeeeee_nnnnnnnnnn_aaaaaaaaaa_mmmmmmmmmm_eeeeeeeeee.txt$")
diff --git a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-Prerequirements.cmake b/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-Prerequirements.cmake
deleted file mode 100644
index 0c1d77e..0000000
--- a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-Prerequirements.cmake
+++ /dev/null
@@ -1,7 +0,0 @@
-function(get_test_prerequirements found_var)
-  find_program(FAKEROOT_EXECUTABLE NAMES fakeroot)
-
-  if(FAKEROOT_EXECUTABLE)
-    set(${found_var} true PARENT_SCOPE)
-  endif()
-endfunction()
diff --git a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-specifics.cmake b/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-specifics.cmake
deleted file mode 100644
index 39a6be4..0000000
--- a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-specifics.cmake
+++ /dev/null
@@ -1,3 +0,0 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
-set(CPACK_DEBIAN_ARCHIVE_TYPE "gnutar")
diff --git a/Tests/RunCMake/CPack/DEB/MINIMAL-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/MINIMAL-ExpectedFiles.cmake
deleted file mode 100644
index 648c866..0000000
--- a/Tests/RunCMake/CPack/DEB/MINIMAL-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "minimal_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/${whitespaces_}.*/usr/foo/${whitespaces_}.*/usr/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/DEB/MINIMAL-specifics.cmake b/Tests/RunCMake/CPack/DEB/MINIMAL-specifics.cmake
deleted file mode 100644
index 4e9a2e7..0000000
--- a/Tests/RunCMake/CPack/DEB/MINIMAL-specifics.cmake
+++ /dev/null
@@ -1,2 +0,0 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
diff --git a/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-ExpectedFiles.cmake b/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-ExpectedFiles.cmake
deleted file mode 100644
index 40f6730..0000000
--- a/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-ExpectedFiles.cmake
+++ /dev/null
@@ -1,9 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "3")
-set(EXPECTED_FILE_1 "per_component-pkg_1_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_1 "^.*/usr/foo${whitespaces_}.*/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_2 "second_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_2 "^.*/usr/foo${whitespaces_}.*/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_3 "per_component-pkg_3_0.1.1-1_*.deb")
-set(EXPECTED_FILE_CONTENT_3 "^.*/usr/foo${whitespaces_}.*/usr/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-VerifyResult.cmake b/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-VerifyResult.cmake
deleted file mode 100644
index 55293be..0000000
--- a/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-VerifyResult.cmake
+++ /dev/null
@@ -1,18 +0,0 @@
-function(checkPackageInfo_ TYPE FILE REGEX)
-  set(whitespaces_ "[\t\n\r ]*")
-
-  getPackageInfo("${FILE}" "FILE_INFO_")
-  if(NOT FILE_INFO_ MATCHES "${REGEX}")
-    message(FATAL_ERROR "Unexpected ${TYPE} in '${FILE}'; file info: '${FILE_INFO_}'")
-  endif()
-endfunction()
-
-# check package name
-checkPackageInfo_("name" "${FOUND_FILE_1}" ".*Package${whitespaces_}:${whitespaces_}per_component-pkg_1")
-checkPackageInfo_("name" "${FOUND_FILE_2}" ".*Package${whitespaces_}:${whitespaces_}second")
-checkPackageInfo_("name" "${FOUND_FILE_3}" ".*Package${whitespaces_}:${whitespaces_}per_component-pkg_3")
-
-# check package group
-checkPackageInfo_("group" "${FOUND_FILE_1}" ".*Section${whitespaces_}:${whitespaces_}default")
-checkPackageInfo_("group" "${FOUND_FILE_2}" ".*Section${whitespaces_}:${whitespaces_}second_group")
-checkPackageInfo_("group" "${FOUND_FILE_3}" ".*Section${whitespaces_}:${whitespaces_}default")
diff --git a/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-specifics.cmake b/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-specifics.cmake
deleted file mode 100644
index 25bd2e7..0000000
--- a/Tests/RunCMake/CPack/DEB/PER_COMPONENT_FIELDS-specifics.cmake
+++ /dev/null
@@ -1,7 +0,0 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEB_COMPONENT_INSTALL "ON")
-set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
-
-set(CPACK_DEBIAN_PACKAGE_SECTION "default")
-set(CPACK_DEBIAN_PKG_2_PACKAGE_NAME "second")
-set(CPACK_DEBIAN_PKG_2_PACKAGE_SECTION "second_group")
diff --git a/Tests/RunCMake/CPack/DEB/Prerequirements.cmake b/Tests/RunCMake/CPack/DEB/Prerequirements.cmake
index cb9a277..60d02e7 100644
--- a/Tests/RunCMake/CPack/DEB/Prerequirements.cmake
+++ b/Tests/RunCMake/CPack/DEB/Prerequirements.cmake
@@ -12,4 +12,11 @@ function(get_test_prerequirements found_var config_file)
     file(APPEND "${config_file}"
       "\nset(FAKEROOT_EXECUTABLE \"${FAKEROOT_EXECUTABLE}\")")
   endif()
+
+  # optional tool for some tests
+  find_program(READELF_EXECUTABLE NAMES readelf)
+  if(READELF_EXECUTABLE)
+    file(APPEND "${config_file}"
+      "\nset(READELF_EXECUTABLE \"${READELF_EXECUTABLE}\")")
+  endif()
 endfunction()
diff --git a/Tests/RunCMake/CPack/DEB/packaging_COMPONENT_default.cmake b/Tests/RunCMake/CPack/DEB/packaging_COMPONENT_default.cmake
new file mode 100644
index 0000000..4219b0c
--- /dev/null
+++ b/Tests/RunCMake/CPack/DEB/packaging_COMPONENT_default.cmake
@@ -0,0 +1,2 @@
+set(CPACK_DEB_COMPONENT_INSTALL "ON")
+set(CPACK_PACKAGE_CONTACT "someone")
diff --git a/Tests/RunCMake/CPack/DEB/packaging_MONOLITHIC_default.cmake b/Tests/RunCMake/CPack/DEB/packaging_MONOLITHIC_default.cmake
new file mode 100644
index 0000000..8821ab9
--- /dev/null
+++ b/Tests/RunCMake/CPack/DEB/packaging_MONOLITHIC_default.cmake
@@ -0,0 +1 @@
+set(CPACK_PACKAGE_CONTACT "someone")
diff --git a/Tests/RunCMake/CPack/DEBUGINFO.cmake b/Tests/RunCMake/CPack/DEBUGINFO.cmake
deleted file mode 100644
index d98b682..0000000
--- a/Tests/RunCMake/CPack/DEBUGINFO.cmake
+++ /dev/null
@@ -1,34 +0,0 @@
-set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
-
-# PGI compiler doesn't add build id to binaries by default
-if(CMAKE_CXX_COMPILER_ID STREQUAL "PGI")
-  string(APPEND CMAKE_EXE_LINKER_FLAGS "-Wl,--build-id")
-  string(APPEND CMAKE_SHARED_LINKER_FLAGS "-Wl,--build-id")
-endif()
-
-set(CPACK_RPM_COMPONENT_INSTALL "ON")
-
-set(CMAKE_BUILD_TYPE Debug)
-
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.hpp"
-    "int test_lib();\n")
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp"
-    "#include \"test_lib.hpp\"\nint test_lib() {return 0;}\n")
-add_library(test_lib SHARED "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp")
-
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/main.cpp"
-    "#include \"test_lib.hpp\"\nint main() {return test_lib();}\n")
-add_executable(test_prog "${CMAKE_CURRENT_BINARY_DIR}/main.cpp")
-target_link_libraries(test_prog test_lib)
-
-install(TARGETS test_prog DESTINATION foo COMPONENT applications)
-install(FILES CMakeLists.txt DESTINATION bar COMPONENT headers)
-install(TARGETS test_lib DESTINATION bas COMPONENT libs)
-
-set(CPACK_RPM_APPLICATIONS_FILE_NAME "RPM-DEFAULT")
-set(CPACK_RPM_APPLICATIONS_DEBUGINFO_PACKAGE ON)
-set(CPACK_RPM_LIBS_DEBUGINFO_PACKAGE ON)
-
-set(CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX "/src")
-
-set(CPACK_PACKAGE_NAME "debuginfo")
diff --git a/Tests/RunCMake/CPack/DEB_EXTRA.cmake b/Tests/RunCMake/CPack/DEB_EXTRA.cmake
deleted file mode 100644
index 189d123..0000000
--- a/Tests/RunCMake/CPack/DEB_EXTRA.cmake
+++ /dev/null
@@ -1,39 +0,0 @@
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT foo)
-install(FILES CMakeLists.txt DESTINATION bar COMPONENT bar)
-install(FILES CMakeLists.txt DESTINATION bas COMPONENT bas)
-
-file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/tmp/preinst "echo default_preinst")
-file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/tmp/prerm "echo default_prerm")
-
-foreach(file_ preinst prerm)
-  file(COPY ${CMAKE_CURRENT_BINARY_DIR}/tmp/${file_}
-    DESTINATION ${CMAKE_CURRENT_BINARY_DIR}
-    FILE_PERMISSIONS
-      OWNER_READ OWNER_WRITE OWNER_EXECUTE
-      GROUP_READ GROUP_EXECUTE
-      WORLD_READ WORLD_EXECUTE)
-endforeach()
-
-set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA
-    "${CMAKE_CURRENT_BINARY_DIR}/preinst;${CMAKE_CURRENT_BINARY_DIR}/prerm;${CMAKE_CURRENT_BINARY_DIR}/conffiles")
-
-file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/bar_tmp/preinst "echo bar_preinst")
-file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/bar_tmp/prerm "echo bar_prerm")
-
-foreach(file_ preinst prerm)
-  # not acceptable permissions for lintian but we need to check that
-  # permissions are preserved
-  file(COPY ${CMAKE_CURRENT_BINARY_DIR}/bar_tmp/${file_}
-    DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/bar
-    FILE_PERMISSIONS
-      OWNER_READ OWNER_WRITE OWNER_EXECUTE)
-endforeach()
-
-set(CPACK_DEBIAN_BAR_PACKAGE_CONTROL_EXTRA
-    "${CMAKE_CURRENT_BINARY_DIR}/bar/preinst;${CMAKE_CURRENT_BINARY_DIR}/bar/prerm")
-
-set(CPACK_PACKAGE_NAME "deb_extra")
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
-
-set(CPACK_DEB_COMPONENT_INSTALL ON)
diff --git a/Tests/RunCMake/CPack/DEB_GENERATE_SHLIBS.cmake b/Tests/RunCMake/CPack/DEB_GENERATE_SHLIBS.cmake
deleted file mode 100644
index 1aeb06f..0000000
--- a/Tests/RunCMake/CPack/DEB_GENERATE_SHLIBS.cmake
+++ /dev/null
@@ -1,18 +0,0 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEB_COMPONENT_INSTALL "ON")
-set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
-
-set(CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS "ON")
-
-set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
-
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.hpp"
-    "int test_lib();\n")
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp"
-    "#include \"test_lib.hpp\"\nint test_lib() {return 0;}\n")
-add_library(test_lib SHARED "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp")
-set_target_properties(test_lib PROPERTIES SOVERSION "0.8")
-
-install(TARGETS test_lib DESTINATION foo COMPONENT libs)
-
-set(CPACK_PACKAGE_NAME "generate_shlibs")
diff --git a/Tests/RunCMake/CPack/DEB_GENERATE_SHLIBS_LDCONFIG.cmake b/Tests/RunCMake/CPack/DEB_GENERATE_SHLIBS_LDCONFIG.cmake
deleted file mode 100644
index f58c876..0000000
--- a/Tests/RunCMake/CPack/DEB_GENERATE_SHLIBS_LDCONFIG.cmake
+++ /dev/null
@@ -1,19 +0,0 @@
-set(CPACK_PACKAGE_CONTACT "someone")
-set(CPACK_DEB_COMPONENT_INSTALL "ON")
-set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
-
-set(CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS "ON")
-set(CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS_POLICY ">=")
-
-set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
-
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.hpp"
-    "int test_lib();\n")
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp"
-    "#include \"test_lib.hpp\"\nint test_lib() {return 0;}\n")
-add_library(test_lib SHARED "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp")
-set_target_properties(test_lib PROPERTIES SOVERSION "0.8")
-
-install(TARGETS test_lib LIBRARY DESTINATION lib COMPONENT libs NAMELINK_SKIP)
-
-set(CPACK_PACKAGE_NAME "generate_shlibs_ldconfig")
diff --git a/Tests/RunCMake/CPack/DEPENDENCIES.cmake b/Tests/RunCMake/CPack/DEPENDENCIES.cmake
deleted file mode 100644
index 4f6d65f..0000000
--- a/Tests/RunCMake/CPack/DEPENDENCIES.cmake
+++ /dev/null
@@ -1,20 +0,0 @@
-set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
-
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.hpp"
-    "int test_lib();\n")
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp"
-    "#include \"test_lib.hpp\"\nint test_lib() {return 0;}\n")
-add_library(test_lib SHARED "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp")
-
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/main.cpp"
-    "#include \"test_lib.hpp\"\nint main() {return test_lib();}\n")
-add_executable(test_prog "${CMAKE_CURRENT_BINARY_DIR}/main.cpp")
-target_link_libraries(test_prog test_lib)
-
-install(TARGETS test_prog DESTINATION foo COMPONENT applications)
-install(TARGETS test_prog DESTINATION foo_auto COMPONENT applications_auto)
-install(FILES CMakeLists.txt DESTINATION bar COMPONENT headers)
-install(TARGETS test_lib DESTINATION bas COMPONENT libs)
-install(TARGETS test_lib DESTINATION bas_auto COMPONENT libs_auto)
-
-set(CPACK_PACKAGE_NAME "dependencies")
diff --git a/Tests/RunCMake/CPack/EMPTY_DIR.cmake b/Tests/RunCMake/CPack/EMPTY_DIR.cmake
deleted file mode 100644
index 023ba17..0000000
--- a/Tests/RunCMake/CPack/EMPTY_DIR.cmake
+++ /dev/null
@@ -1,4 +0,0 @@
-install(DIRECTORY DESTINATION empty
-        COMPONENT test)
-
-set(CPACK_PACKAGE_NAME "empty_dir")
diff --git a/Tests/RunCMake/CPack/INSTALL_SCRIPTS.cmake b/Tests/RunCMake/CPack/INSTALL_SCRIPTS.cmake
deleted file mode 100644
index 13aa77b..0000000
--- a/Tests/RunCMake/CPack/INSTALL_SCRIPTS.cmake
+++ /dev/null
@@ -1,26 +0,0 @@
-set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
-
-# default
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/pre_install.sh"
-    "echo \"pre install\"\n")
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/post_install.sh"
-    "echo \"post install\"\n")
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/pre_uninstall.sh"
-    "echo \"pre uninstall\"\n")
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/post_uninstall.sh"
-    "echo \"post uninstall\"\n")
-
-# specific
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/pre_install_foo.sh"
-    "echo \"pre install foo\"\n")
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/post_install_foo.sh"
-    "echo \"post install foo\"\n")
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/pre_uninstall_foo.sh"
-    "echo \"pre uninstall foo\"\n")
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/post_uninstall_foo.sh"
-    "echo \"post uninstall foo\"\n")
-
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT foo)
-install(FILES CMakeLists.txt DESTINATION bar COMPONENT bar)
-
-set(CPACK_PACKAGE_NAME "install_scripts")
diff --git a/Tests/RunCMake/CPack/LONG_FILENAMES.cmake b/Tests/RunCMake/CPack/LONG_FILENAMES.cmake
deleted file mode 100644
index 3242aef..0000000
--- a/Tests/RunCMake/CPack/LONG_FILENAMES.cmake
+++ /dev/null
@@ -1,10 +0,0 @@
-set(LONG_FILENAME
-  "${CMAKE_CURRENT_BINARY_DIR}/llllllllll_oooooooooo_nnnnnnnnnn_gggggggggg_ffffffffff_iiiiiiiiii_llllllllll_eeeeeeeeee_nnnnnnnnnn_aaaaaaaaaa_mmmmmmmmmm_eeeeeeeeee.txt")
-
-file(WRITE
-  "${LONG_FILENAME}"
-  "long_filename_test")
-
-install(FILES ${LONG_FILENAME} DESTINATION foo)
-
-set(CPACK_PACKAGE_NAME "long_filenames")
diff --git a/Tests/RunCMake/CPack/MINIMAL.cmake b/Tests/RunCMake/CPack/MINIMAL.cmake
deleted file mode 100644
index f29ad2a..0000000
--- a/Tests/RunCMake/CPack/MINIMAL.cmake
+++ /dev/null
@@ -1,3 +0,0 @@
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT test)
-
-set(CPACK_PACKAGE_NAME "minimal")
diff --git a/Tests/RunCMake/CPack/PACKAGE_CHECKSUM.cmake b/Tests/RunCMake/CPack/PACKAGE_CHECKSUM.cmake
deleted file mode 100644
index 5ca288c..0000000
--- a/Tests/RunCMake/CPack/PACKAGE_CHECKSUM.cmake
+++ /dev/null
@@ -1,4 +0,0 @@
-install(FILES CMakeLists.txt DESTINATION foo)
-
-set(CPACK_PACKAGE_NAME "package_checksum")
-set(CPACK_PACKAGE_CHECKSUM ${RunCMake_SUBTEST_SUFFIX})
diff --git a/Tests/RunCMake/CPack/PARTIALLY_RELOCATABLE_WARNING.cmake b/Tests/RunCMake/CPack/PARTIALLY_RELOCATABLE_WARNING.cmake
deleted file mode 100644
index 31e729b..0000000
--- a/Tests/RunCMake/CPack/PARTIALLY_RELOCATABLE_WARNING.cmake
+++ /dev/null
@@ -1,6 +0,0 @@
-install(FILES CMakeLists.txt DESTINATION /not_relocatable COMPONENT static)
-
-set(CPACK_PACKAGE_RELOCATABLE TRUE)
-set(CPACK_PACKAGING_INSTALL_PREFIX "/opt")
-
-set(CPACK_RPM_COMPONENT_INSTALL ON)
diff --git a/Tests/RunCMake/CPack/PER_COMPONENT_FIELDS.cmake b/Tests/RunCMake/CPack/PER_COMPONENT_FIELDS.cmake
deleted file mode 100644
index bb42cf4..0000000
--- a/Tests/RunCMake/CPack/PER_COMPONENT_FIELDS.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_1)
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_2)
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_3)
-
-set(CPACK_PACKAGE_NAME "per_component")
diff --git a/Tests/RunCMake/CPack/README.txt b/Tests/RunCMake/CPack/README.txt
index 5c86880..7c98f69 100644
--- a/Tests/RunCMake/CPack/README.txt
+++ b/Tests/RunCMake/CPack/README.txt
@@ -1,41 +1,75 @@
 RunCMake.CPack is a test module that is intended for testing of package
 generators that can be validated from command line.
 
-TODO: all tests should cover all packaging types (single package, grouped and
-      component packaging)
-
 -------------
 Adding a test
 -------------
 
-CPack test root directory: 'Tests/RunCMake/CPack'.
+CPack test root directory: 'Tests/RunCMake/CPack/tests'.
 
 All phases are executed separately for each generator that is bound to a test.
 Tests for each generator are subtests of test 'RunCMake.CPack_<generator_name>'.
 
 Each test must also be added to 'RunCMakeTest.cmake' script located in CPack
 test root directory.
+
 Line that adds a test is:
-run_cpack_test(<test_name> "<generator_name>")
+run_cpack_test(<test_name> "<generator_name_list>" <compile_stage>
+               "<packaging_type_list>")
+
+<generator_name_list> may be one generator e.g. "RPM" or multiple e.g. "RPM;DEB"
+and will be run for all listed generators. In test and verification scripts
+current generator can be accessed through GENERATOR_TYPE variable.
+
+<compile_stage> is a boolean variable that enables or disables compile stage -
+most tests don't require compilation as a non binary file can be used for
+package content but sometimes an executable or a library has to be created
+before the packaging stage.
 
-<generator_name> may be one generator e.g. "RPM" or multiple e.g. "RPM;DEB" and
-will be run for all listed generators.
+<packaging_type_list> can be a list of one or more packaging types: MONOLITHIC,
+COMPONENT or GROUP - each type sets per generator default variables which can
+be overwritten in the test if needed
+(see <generator_type>/packaging_<packaging_type>_default.cmake for the variables
+that are set by default for each packaging type).
+Alternatively CUSTOM value can be set which means that default values will not
+be set and that values will be set manually in the test itself.
+
+Alternatively a test with subtests can be added:
+run_cpack_test_subtests(<test_name> "<subtests_list>" "<generator_name_list>"
+                        <compile_stage> "<packaging_type_list>")
+
+<subtests_list> is the only new parameter and it is a list of names that will
+be used for subtests. In test and verification scripts subtest name can be
+accessed through RunCMake_SUBTEST_SUFFIX variable.
+
+Also source package tests can be added:
+run_cpack_source_test(<test_name> "<generator_name_list>" true)
 
 Test consists of
 - test prerequirements phase (optional)
 - CMake execution phase
+- build phase (optional and not available for source package tests)
 - CPack execution phase
 - verification of generated files
 
+The phases are executed once per specified generator, packaging type and subtest
+combinatiion.
+
 test prerequirements phase (optional):
 --------------------------------------
 
 In some cases individual tests for certain generator need additional
 prerequirements met.
 
-In such cases '<generator_name>/<test_name>-Prerequirements.cmake' file
-containing 'function(get_test_prerequirements found_var)' should be created.
-Function should return true if all prerequirements are met.
+In such cases '<test_name>/<generator_name>-Prerequirements.cmake' file
+containing 'function(get_test_prerequirements found_var config_file)' should be
+created. Function should return true in found_var if all prerequirements are
+met. config_file variable contains the location of config file generated by the
+generator so that this function can check if prerequired variable is set in the
+file.
+NOTE: All required programs should be searched for in generator prerequirements
+function and only checked for the variable in configure file in per test
+function.
 
 If prerequirements are not met test will be skipped outputting
 '<test_name> - SKIPPED' string. Note that this doesn't fail the entire test
@@ -48,15 +82,21 @@ TODO: skipped tests should provide expected error string so test should fail
 CMake execution phase:
 ----------------------
 
-To add a new CPack test we first create a <test_name>.cmake script that contains
-CMake commands that should be used as a preparation script for generation of
-different types of packages. This script is placed into CPack test root
-directory even if it will be used for only one of the generators.
+To add a new CPack test we first create a '<test_name>/test.cmake' script that
+contains CMake commands that should be used as a preparation script for
+generation of different types of packages. This script is placed into CPack
+test root directory.
 
 If test will be used for multiple generators but some of them require some
-generator specific commands then those commands should be added to a separate
-file that should be located in '<generator_name>/<test_name>-specifics.cmake'
-in CPack test root directory.
+generator specific commands then those commands should be added to 'test.cmake'
+script wrapped with 'if(GENERATOR_TYPE STREQUAL <name_of_the_generator>)'.
+
+build phase (optional and not available for source package tests)
+-----------------------------------------------------------------
+
+This phase only runs make command.
+
+NOTE: By default all tests have CMAKE_BUILD_TYPE variable set to Debug.
 
 CPack execution phase:
 ----------------------
@@ -64,6 +104,8 @@ CPack execution phase:
 Only executes CPack for content that was generated during CMake execution
 phase.
 
+NOTE: By default CPACK_PACKAGE_NAME variable is set to lower case test name.
+
 Verification of generated files:
 --------------------------------
 
@@ -76,24 +118,59 @@ contain expected files.
 Mandatory verification phase also checks that no other unexpected package files
 were generated (this is executed even if EXPECTED_FILES_COUNT contains 0 in
 order to verify that no files were generated).
-CMake script '<generator_name>/<test_name>-ExpectedFiles.cmake' is required by
+CMake script '<test_name>/ExpectedFiles.cmake' is required by
 this step and must contain
 - EXPECTED_FILES_COUNT variable that contains the number of expected files that
   will be generated (0 or more)
+
 - EXPECTED_FILE_<file_number_starting_with_1> that contains globing expression
   that uniquely defines expected file name (will be used to find expected file)
-  and should be present once for each expected file
+  and should be present once for each expected file.
+  NOTE: This variable should be used only as last resort as it sets generator
+        specific globbing expression. Each generator can recreate file name from
+        parts that are already populated by default but can always be
+        overwritten if needed:
+  - EXPECTED_FILE_<file_number_starting_with_1>_NAME is the name component of
+    the file (by default it is set to package name that is same as test name
+    in lowercase)
+  - EXPECTED_FILE_<file_number_starting_with_1>_VERSION is the version of the
+    package (by default it is set to '0.1.1')
+  - EXPECTED_FILE_<file_number_starting_with_1>_REVISION is the revision of the
+    package (by default it is set to '1')
+
 - EXPECTED_FILE_CONTENT_<file_number_starting_with_1> that contains regular
   expression of files that should be present in generated file and should be
   present once for each expected file
+  NOTE: This variable should be used only as last resort as it sets generator
+        specific regular expression.
+        EXPECTED_FILE_CONTENT_<file_number_starting_with_1>_LIST should be
+        prefered as it requires a list of expected files and directories that
+        is later changed automatically depending on the generator so expected
+        package content can be written only once per test for all generators.
 
 Optional verification phase is generator specific and is optionaly executed.
-This phase is executed if '<generator_name>/<test_name>-VerifyResult.cmake'
-script exists.
-In case that the script doesn't exist VerifyResult.cmake script automatically
-prints out standard output and standard error from CPack execution phase that
-is compared with '<generator_name>/<test_name>-stdout.txt' regular expression
-and '<generator_name>/<test_name>-stderr.txt' regular expresson respectively.
+This phase is executed if '<test_name>/VerifyResult.cmake' script exists.
+
+VerifyResult.cmake script also automatically prints out standard output and
+standard error from CPack execution phase that is compared with
+'<test_name>/<generator_name>-stdout.txt' regular expression and
+and '<test_name>/<generator_name>-stderr.txt' regular expresson respectively.
+NOTE: For subtests generator name can also be suffixed with subtest name and/or
+      packaging type (MONOLITHIC, COMPONENT, GROUP) and in such cases the
+      preferences of which file will be used are as follows:
+        - generator name + packaging type + subtest name
+        - generator name + packaging type
+        - generator name + subtest name
+        - generator name
+        - default generator
+      File name format: '<generator_name>-<packaging_type>-<subtest_name>-std<type>.txt'
+                        where <type> can either be 'out' or 'err'.
+      File name format: '<generator_name>-<packaging_type>-std<type>.txt'
+                        where <type> can either be 'out' or 'err'.
+      File name format: '<generator_name>-<subtest_name>-std<type>.txt' where
+                        <type> can either be 'out' or 'err'.
+NOTE: If none of the comparison files are present then the default generator
+      file is used if present.
 
 ----------------------
 Adding a new generator
@@ -101,13 +178,44 @@ Adding a new generator
 
 To add a new generator we must
 - add new generator directory (e.g. RPM for RPM generator) to CPack test root
-  directory that contains 'Helpers.cmake' script. In this script a function
-  named 'getPackageContent' must exist. This function should list files that
-  are contained in a package. Function should accept two parameters
-  + FILE variable that will contain path to file for which the content should be
-    listed
-  + RESULT_VAR that will tell the function which variable in parent scope should
-    contain the result (list of files inside package file)
+  directory that contains 'Helpers.cmake' script.
+  - In this script some functions must exist:
+    - getPackageContent: This function should list files that are contained in
+                         a package.
+      Function parameters:
+      + FILE variable that will contain path to file for which the content
+        should be listed
+      + RESULT_VAR that will tell the function which variable in parent scope
+        should contain the result (list of files inside package file)
+    - getPackageNameGlobexpr: This function should generate package name
+                              globbing expression.
+      Function parameters:
+      + NAME that will contain the expected package name
+      + COMPONENT that will contain the expected package component
+      + VERSION that will contain the expected package version
+      + REVISION that will contain the expected package revision number
+      + FILE_NO that will contain the file number for which the globbing
+        expression is generated
+      + RESULT_VAR that will tell the function which variable in parent scope
+        should contain the result (file name globbing expression)
+    - getPackageContentList: This function should return a list of files and
+                             directories that are in the provided package.
+      Function parameters:
+      + FILE that will contain the package file for which the package content
+        should be returned.
+      + RESULT_VAR that will tell the function which variable in parent scope
+        should contain the result (list of pacakge content)
+    - toExpectedContentList: This function should convert an expected package
+                             content list into one that is expected for the
+                             generator (e.g. rpm packages have install/relocate
+                             path prefixes which aren't part of the package so
+                             those paths have to be removed from the expected
+                             content list).
+      Function parameters:
+      + FILE_NO that will contain the file number for which the conversion
+        should be performed
+      + CONTENT_VAR that will contain the input list and is also the variable
+        in parent scope which should contain the result (converted content list)
 - add 'Prerequirements.cmake' script to generator directory. In this script a
   function named 'get_test_prerequirements' must exist. This function should
   set a variable in parent scope (name of the variable is the first parameter)
@@ -119,3 +227,10 @@ To add a new generator we must
 - add tests the same way as described above
 - add generator to 'add_RunCMake_test_group' function call that is located in
   RunCMake CMakeLists.txt file
+- if needed add 'packaging_<packaging_type>_default.cmake' scripts that define
+  default variables that will be set for each packaging type (MONOLITHIC,
+  COMPONENT and GROUP)
+- if needed add 'default_expected_std<type>.txt' files where <type> is either
+  'out' or 'err' which will contain default expected output of package
+  generation regular expression.
+- add generator to list of other CPack generators in RunCMake/CMakeLists.txt
diff --git a/Tests/RunCMake/CPack/RPM/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake
deleted file mode 100644
index d396276..0000000
--- a/Tests/RunCMake/CPack/RPM/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "components_empty_dir*.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/empty$")
diff --git a/Tests/RunCMake/CPack/RPM/COMPONENTS_EMPTY_DIR-stderr.txt b/Tests/RunCMake/CPack/RPM/COMPONENTS_EMPTY_DIR-stderr.txt
deleted file mode 100644
index 6ddca12..0000000
--- a/Tests/RunCMake/CPack/RPM/COMPONENTS_EMPTY_DIR-stderr.txt
+++ /dev/null
@@ -1 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/COMPONENTS_EMPTY_DIR-build/_CPack_Packages/.*/RPM/SPECS/components_empty_dir.spec$
diff --git a/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-ExpectedFiles.cmake
deleted file mode 100644
index 780e57e..0000000
--- a/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-ExpectedFiles.cmake
+++ /dev/null
@@ -1,9 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "3")
-set(EXPECTED_FILE_1 "custom_names-pkg_1*.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_2 "second*.rpm")
-set(EXPECTED_FILE_CONTENT_2 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_3 "pkg_3_abc.rpm")
-set(EXPECTED_FILE_CONTENT_3 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-specifics.cmake b/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-specifics.cmake
deleted file mode 100644
index 575aa01..0000000
--- a/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-specifics.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(CPACK_RPM_COMPONENT_INSTALL "ON")
-
-set(CPACK_RPM_FILE_NAME "RPM-DEFAULT")
-set(CPACK_RPM_PKG_2_PACKAGE_NAME "second")
-set(CPACK_RPM_PKG_3_FILE_NAME "pkg_3_abc.rpm")
diff --git a/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-stderr.txt b/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-stderr.txt
deleted file mode 100644
index 9bfba7e..0000000
--- a/Tests/RunCMake/CPack/RPM/CUSTOM_NAMES-stderr.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/CUSTOM_NAMES-build/_CPack_Packages/.*/RPM/SPECS/custom_names-pkg_1.spec
-CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/CUSTOM_NAMES-build/_CPack_Packages/.*/RPM/SPECS/second.spec
-CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/CUSTOM_NAMES-build/_CPack_Packages/.*/RPM/SPECS/custom_names-pkg_3.spec$
diff --git a/Tests/RunCMake/CPack/RPM/DEBUGINFO-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/DEBUGINFO-ExpectedFiles.cmake
deleted file mode 100644
index a583e32..0000000
--- a/Tests/RunCMake/CPack/RPM/DEBUGINFO-ExpectedFiles.cmake
+++ /dev/null
@@ -1,14 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "5")
-set(EXPECTED_FILE_1 "debuginfo-applications-0*.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/test_prog$")
-set(EXPECTED_FILE_2 "debuginfo*-headers.rpm")
-set(EXPECTED_FILE_CONTENT_2 "^/usr/bar${whitespaces_}/usr/bar/CMakeLists.txt$")
-set(EXPECTED_FILE_3 "debuginfo*-libs.rpm")
-set(EXPECTED_FILE_CONTENT_3 "^/usr/bas${whitespaces_}/usr/bas/libtest_lib.so$")
-
-set(EXPECTED_FILE_4 "debuginfo-applications-debuginfo*.rpm")
-set(EXPECTED_FILE_CONTENT_4 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/main.cpp.*")
-set(EXPECTED_FILE_5 "debuginfo-libs-debuginfo*.rpm")
-set(EXPECTED_FILE_CONTENT_5 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/test_lib.cpp.*")
diff --git a/Tests/RunCMake/CPack/RPM/DEBUGINFO-stderr.txt b/Tests/RunCMake/CPack/RPM/DEBUGINFO-stderr.txt
deleted file mode 100644
index 557ef3d..0000000
--- a/Tests/RunCMake/CPack/RPM/DEBUGINFO-stderr.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/DEBUGINFO-build/_CPack_Packages/.*/RPM/SPECS/debuginfo-applications.spec
-CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/DEBUGINFO-build/_CPack_Packages/.*/RPM/SPECS/debuginfo-headers.spec
-CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/DEBUGINFO-build/_CPack_Packages/.*/RPM/SPECS/debuginfo-libs.spec$
diff --git a/Tests/RunCMake/CPack/RPM/DEPENDENCIES-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/DEPENDENCIES-ExpectedFiles.cmake
deleted file mode 100644
index cf85dab..0000000
--- a/Tests/RunCMake/CPack/RPM/DEPENDENCIES-ExpectedFiles.cmake
+++ /dev/null
@@ -1,13 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "5")
-set(EXPECTED_FILE_1 "dependencies*-applications.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/test_prog$")
-set(EXPECTED_FILE_2 "dependencies*-applications_auto.rpm")
-set(EXPECTED_FILE_CONTENT_2 "^/usr/foo_auto${whitespaces_}/usr/foo_auto/test_prog$")
-set(EXPECTED_FILE_3 "dependencies*-headers.rpm")
-set(EXPECTED_FILE_CONTENT_3 "^/usr/bar${whitespaces_}/usr/bar/CMakeLists.txt$")
-set(EXPECTED_FILE_4 "dependencies*-libs.rpm")
-set(EXPECTED_FILE_CONTENT_4 "^/usr/bas${whitespaces_}/usr/bas/libtest_lib.so$")
-set(EXPECTED_FILE_5 "dependencies*-libs_auto.rpm")
-set(EXPECTED_FILE_CONTENT_5 "^/usr/bas_auto${whitespaces_}/usr/bas_auto/libtest_lib.so$")
diff --git a/Tests/RunCMake/CPack/RPM/DEPENDENCIES-VerifyResult.cmake b/Tests/RunCMake/CPack/RPM/DEPENDENCIES-VerifyResult.cmake
deleted file mode 100644
index fec8889..0000000
--- a/Tests/RunCMake/CPack/RPM/DEPENDENCIES-VerifyResult.cmake
+++ /dev/null
@@ -1,45 +0,0 @@
-function(checkDependencies_ FILE TYPE COMPARE_LIST)
-  set(whitespaces_ "[\t\n\r ]*")
-
-  execute_process(COMMAND ${RPM_EXECUTABLE} -qp --${TYPE} ${FILE}
-          WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
-          OUTPUT_VARIABLE FILE_DEPENDENCIES_
-          ERROR_QUIET
-          OUTPUT_STRIP_TRAILING_WHITESPACE)
-
-  string(REPLACE "\n" ";" FILE_DEPENDENCIES_LIST_ "${FILE_DEPENDENCIES_}")
-
-  foreach(COMPARE_REGEX_ IN LISTS COMPARE_LIST)
-    unset(FOUND_)
-
-    foreach(COMPARE_ IN LISTS FILE_DEPENDENCIES_LIST_)
-      if(COMPARE_ MATCHES "${COMPARE_REGEX_}")
-        set(FOUND_ true)
-        break()
-      endif()
-    endforeach()
-
-    if(NOT FOUND_)
-      message(FATAL_ERROR "Missing dependencies in '${FILE}'; check type: '${TYPE}'; file info: '${FILE_DEPENDENCIES_}'; missing: '${COMPARE_REGEX_}'")
-    endif()
-  endforeach()
-endfunction()
-
-# TODO add tests for what should not be present in lists
-checkDependencies_("${FOUND_FILE_1}" "requires" "depend-application;depend-application-b")
-checkDependencies_("${FOUND_FILE_2}" "requires" "depend-application;depend-application-b;libtest_lib\\.so.*")
-checkDependencies_("${FOUND_FILE_3}" "requires" "depend-headers")
-checkDependencies_("${FOUND_FILE_4}" "requires" "depend-default;depend-default-b")
-checkDependencies_("${FOUND_FILE_5}" "requires" "depend-default;depend-default-b")
-
-checkDependencies_("${FOUND_FILE_1}" "conflicts" "conflict-application;conflict-application-b")
-checkDependencies_("${FOUND_FILE_2}" "conflicts" "conflict-application;conflict-application-b")
-checkDependencies_("${FOUND_FILE_3}" "conflicts" "conflict-headers")
-checkDependencies_("${FOUND_FILE_4}" "conflicts" "conflict-default;conflict-default-b")
-checkDependencies_("${FOUND_FILE_5}" "conflicts" "conflict-default;conflict-default-b")
-
-checkDependencies_("${FOUND_FILE_1}" "provides" "provided-default;provided-default-b")
-checkDependencies_("${FOUND_FILE_2}" "provides" "provided-default;provided-default-b")
-checkDependencies_("${FOUND_FILE_3}" "provides" "provided-default;provided-default-b")
-checkDependencies_("${FOUND_FILE_4}" "provides" "provided-lib")
-checkDependencies_("${FOUND_FILE_5}" "provides" "provided-lib_auto;provided-lib_auto-b")
diff --git a/Tests/RunCMake/CPack/RPM/DEPENDENCIES-specifics.cmake b/Tests/RunCMake/CPack/RPM/DEPENDENCIES-specifics.cmake
deleted file mode 100644
index 8b7fb1e..0000000
--- a/Tests/RunCMake/CPack/RPM/DEPENDENCIES-specifics.cmake
+++ /dev/null
@@ -1,22 +0,0 @@
-set(CPACK_RPM_COMPONENT_INSTALL "ON")
-
-# FIXME auto autoprov is not tested at the moment as Ubuntu 15.04 rpmbuild
-# does not use them correctly: https://bugs.launchpad.net/rpm/+bug/1475755
-set(CPACK_RPM_PACKAGE_AUTOREQ "no")
-set(CPACK_RPM_PACKAGE_AUTOPROV "no")
-set(CPACK_RPM_APPLICATIONS_AUTO_PACKAGE_AUTOREQPROV "yes")
-set(CPACK_RPM_LIBS_AUTO_PACKAGE_AUTOREQPROV "yes")
-
-set(CPACK_RPM_PACKAGE_REQUIRES "depend-default, depend-default-b")
-set(CPACK_RPM_APPLICATIONS_PACKAGE_REQUIRES "depend-application, depend-application-b")
-set(CPACK_RPM_APPLICATIONS_AUTO_PACKAGE_REQUIRES "depend-application, depend-application-b")
-set(CPACK_RPM_HEADERS_PACKAGE_REQUIRES "depend-headers")
-
-set(CPACK_RPM_PACKAGE_CONFLICTS "conflict-default, conflict-default-b")
-set(CPACK_RPM_APPLICATIONS_PACKAGE_CONFLICTS "conflict-application, conflict-application-b")
-set(CPACK_RPM_APPLICATIONS_AUTO_PACKAGE_CONFLICTS "conflict-application, conflict-application-b")
-set(CPACK_RPM_HEADERS_PACKAGE_CONFLICTS "conflict-headers")
-
-set(CPACK_RPM_PACKAGE_PROVIDES "provided-default, provided-default-b")
-set(CPACK_RPM_LIBS_PACKAGE_PROVIDES "provided-lib")
-set(CPACK_RPM_LIBS_AUTO_PACKAGE_PROVIDES "provided-lib_auto, provided-lib_auto-b")
diff --git a/Tests/RunCMake/CPack/RPM/EMPTY_DIR-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/EMPTY_DIR-ExpectedFiles.cmake
deleted file mode 100644
index 0c2977f..0000000
--- a/Tests/RunCMake/CPack/RPM/EMPTY_DIR-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "empty_dir*.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/empty$")
diff --git a/Tests/RunCMake/CPack/RPM/EMPTY_DIR-stderr.txt b/Tests/RunCMake/CPack/RPM/EMPTY_DIR-stderr.txt
deleted file mode 100644
index 1777aa0..0000000
--- a/Tests/RunCMake/CPack/RPM/EMPTY_DIR-stderr.txt
+++ /dev/null
@@ -1 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/EMPTY_DIR-build/_CPack_Packages/.*/RPM/SPECS/empty_dir.spec$
diff --git a/Tests/RunCMake/CPack/RPM/Helpers.cmake b/Tests/RunCMake/CPack/RPM/Helpers.cmake
index ba77a4a..d8012b1 100644
--- a/Tests/RunCMake/CPack/RPM/Helpers.cmake
+++ b/Tests/RunCMake/CPack/RPM/Helpers.cmake
@@ -9,6 +9,63 @@ function(getPackageContent FILE RESULT_VAR)
   set(${RESULT_VAR} "${package_content_}" PARENT_SCOPE)
 endfunction()
 
+function(getPackageNameGlobexpr NAME COMPONENT VERSION REVISION FILE_NO RESULT_VAR)
+  if(COMPONENT)
+    set(COMPONENT "-${COMPONENT}")
+  endif()
+
+  if(DEFINED EXPECTED_FILE_${FILE_NO}_FILENAME_GENERATOR_SPECIFIC_FORMAT)
+    set(GENERATOR_SPECIFIC_FORMAT "${EXPECTED_FILE_${FILE_NO}_FILENAME_GENERATOR_SPECIFIC_FORMAT}")
+  elseif(DEFINED EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT)
+    set(GENERATOR_SPECIFIC_FORMAT "${EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT}")
+  else()
+    set(GENERATOR_SPECIFIC_FORMAT FALSE)
+  endif()
+
+  if(GENERATOR_SPECIFIC_FORMAT)
+    set(${RESULT_VAR} "${NAME}${COMPONENT}-${VERSION}-${REVISION}.*.rpm" PARENT_SCOPE)
+  else()
+    set(${RESULT_VAR} "${NAME}-${VERSION}-*${COMPONENT}.rpm" PARENT_SCOPE)
+  endif()
+endfunction()
+
+function(getPackageContentList FILE RESULT_VAR)
+  execute_process(COMMAND ${RPM_EXECUTABLE} -pql ${FILE}
+          OUTPUT_VARIABLE package_content_
+          ERROR_QUIET
+          OUTPUT_STRIP_TRAILING_WHITESPACE)
+  string(REGEX REPLACE "\n" ";" package_content_ "${package_content_}")
+
+  # never versions of rpmbuild (introduced in rpm 4.13.0.1) add build_id links
+  # to packages - tests should ignore them
+  list(FILTER package_content_ EXCLUDE REGEX ".*\.build-id.*")
+
+  set(${RESULT_VAR} "${package_content_}" PARENT_SCOPE)
+endfunction()
+
+function(toExpectedContentList FILE_NO CONTENT_VAR)
+  if(NOT DEFINED TEST_INSTALL_PREFIX_PATHS)
+    set(TEST_INSTALL_PREFIX_PATHS "/usr")
+  endif()
+
+  unset(filtered_)
+  foreach(part_ IN LISTS ${CONTENT_VAR})
+    unset(dont_add_)
+    foreach(for_removal_ IN LISTS TEST_INSTALL_PREFIX_PATHS)
+      if(part_ STREQUAL for_removal_)
+        set(dont_add_ TRUE)
+        break()
+      endif()
+    endforeach()
+
+    if(NOT dont_add_)
+      list(APPEND filtered_ "${part_}")
+    endif()
+  endforeach()
+
+  set(${CONTENT_VAR} "${filtered_}" PARENT_SCOPE)
+endfunction()
+
 function(getPackageInfo FILE RESULT_VAR)
   execute_process(COMMAND ${RPM_EXECUTABLE} -pqi ${FILE}
           OUTPUT_VARIABLE info_content
diff --git a/Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-ExpectedFiles.cmake
deleted file mode 100644
index 033a45d..0000000
--- a/Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-ExpectedFiles.cmake
+++ /dev/null
@@ -1,7 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "2")
-set(EXPECTED_FILE_1 "install_scripts*-foo.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_2 "install_scripts*-bar.rpm")
-set(EXPECTED_FILE_CONTENT_2 "^/usr/bar${whitespaces_}/usr/bar/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-specifics.cmake b/Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-specifics.cmake
deleted file mode 100644
index 4eb53c3..0000000
--- a/Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-specifics.cmake
+++ /dev/null
@@ -1,19 +0,0 @@
-set(CPACK_RPM_COMPONENT_INSTALL "ON")
-
-set(CPACK_RPM_PRE_INSTALL_SCRIPT_FILE
-  "${CMAKE_CURRENT_BINARY_DIR}/pre_install.sh")
-set(CPACK_RPM_POST_INSTALL_SCRIPT_FILE
-  "${CMAKE_CURRENT_BINARY_DIR}/post_install.sh")
-set(CPACK_RPM_PRE_UNINSTALL_SCRIPT_FILE
-  "${CMAKE_CURRENT_BINARY_DIR}/pre_uninstall.sh")
-set(CPACK_RPM_POST_UNINSTALL_SCRIPT_FILE
-  "${CMAKE_CURRENT_BINARY_DIR}/post_uninstall.sh")
-
-set(CPACK_RPM_foo_PRE_INSTALL_SCRIPT_FILE
-  "${CMAKE_CURRENT_BINARY_DIR}/pre_install_foo.sh")
-set(CPACK_RPM_foo_POST_INSTALL_SCRIPT_FILE
-  "${CMAKE_CURRENT_BINARY_DIR}/post_install_foo.sh")
-set(CPACK_RPM_foo_PRE_UNINSTALL_SCRIPT_FILE
-  "${CMAKE_CURRENT_BINARY_DIR}/pre_uninstall_foo.sh")
-set(CPACK_RPM_foo_POST_UNINSTALL_SCRIPT_FILE
-  "${CMAKE_CURRENT_BINARY_DIR}/post_uninstall_foo.sh")
diff --git a/Tests/RunCMake/CPack/RPM/MINIMAL-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/MINIMAL-ExpectedFiles.cmake
deleted file mode 100644
index 800b78e..0000000
--- a/Tests/RunCMake/CPack/RPM/MINIMAL-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "minimal*.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/RPM/MINIMAL-stderr.txt b/Tests/RunCMake/CPack/RPM/MINIMAL-stderr.txt
deleted file mode 100644
index 7c5fb46..0000000
--- a/Tests/RunCMake/CPack/RPM/MINIMAL-stderr.txt
+++ /dev/null
@@ -1 +0,0 @@
-^CPackRPM: Will use GENERATED spec file: .*/Tests/RunCMake/RPM/CPack/MINIMAL-build/_CPack_Packages/.*/RPM/SPECS/minimal.spec$
diff --git a/Tests/RunCMake/CPack/RPM/PARTIALLY_RELOCATABLE_WARNING-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/PARTIALLY_RELOCATABLE_WARNING-ExpectedFiles.cmake
deleted file mode 100644
index 4e01f7b..0000000
--- a/Tests/RunCMake/CPack/RPM/PARTIALLY_RELOCATABLE_WARNING-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "PARTIALLY_RELOCATABLE_WARNING-0.1.1-*.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/not_relocatable${whitespaces_}/not_relocatable/CMakeLists.txt${whitespaces_}/opt$")
diff --git a/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-ExpectedFiles.cmake
deleted file mode 100644
index 3d28d41..0000000
--- a/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-ExpectedFiles.cmake
+++ /dev/null
@@ -1,9 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "3")
-set(EXPECTED_FILE_1 "per_component*-pkg_1.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_2 "per_component*-pkg_2.rpm")
-set(EXPECTED_FILE_CONTENT_2 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
-set(EXPECTED_FILE_3 "per_component*-pkg_3.rpm")
-set(EXPECTED_FILE_CONTENT_3 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-VerifyResult.cmake b/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-VerifyResult.cmake
deleted file mode 100644
index d7d4f9d..0000000
--- a/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-VerifyResult.cmake
+++ /dev/null
@@ -1,18 +0,0 @@
-function(checkPackageInfo_ TYPE FILE REGEX)
-  set(whitespaces_ "[\t\n\r ]*")
-
-  getPackageInfo("${FILE}" "FILE_INFO_")
-  if(NOT FILE_INFO_ MATCHES "${REGEX}")
-    message(FATAL_ERROR "Unexpected ${TYPE} in '${FILE}'; file info: '${FILE_INFO_}'")
-  endif()
-endfunction()
-
-# check package name
-checkPackageInfo_("name" "${FOUND_FILE_1}" ".*Name${whitespaces_}:${whitespaces_}per_component-pkg_1")
-checkPackageInfo_("name" "${FOUND_FILE_2}" ".*Name${whitespaces_}:${whitespaces_}second")
-checkPackageInfo_("name" "${FOUND_FILE_3}" ".*Name${whitespaces_}:${whitespaces_}per_component-pkg_3")
-
-# check package group
-checkPackageInfo_("group" "${FOUND_FILE_1}" ".*Group${whitespaces_}:${whitespaces_}default")
-checkPackageInfo_("group" "${FOUND_FILE_2}" ".*Group${whitespaces_}:${whitespaces_}second_group")
-checkPackageInfo_("group" "${FOUND_FILE_3}" ".*Group${whitespaces_}:${whitespaces_}default")
diff --git a/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-specifics.cmake b/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-specifics.cmake
deleted file mode 100644
index 524ef0c..0000000
--- a/Tests/RunCMake/CPack/RPM/PER_COMPONENT_FIELDS-specifics.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(CPACK_RPM_COMPONENT_INSTALL "ON")
-
-set(CPACK_RPM_PACKAGE_GROUP "default")
-set(CPACK_RPM_PKG_2_PACKAGE_NAME "second")
-set(CPACK_RPM_PKG_2_PACKAGE_GROUP "second_group")
diff --git a/Tests/RunCMake/CPack/RPM/RPM_DIST-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/RPM_DIST-ExpectedFiles.cmake
deleted file mode 100644
index 3b5a347..0000000
--- a/Tests/RunCMake/CPack/RPM/RPM_DIST-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "rpm_dist*.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^/usr/foo${whitespaces_}/usr/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-ExpectedFiles.cmake b/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-ExpectedFiles.cmake
deleted file mode 100644
index d6811eb..0000000
--- a/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "source_package*.src.rpm")
-set(EXPECTED_FILE_CONTENT_1 "^source_package-0.1.1.tar.gz${whitespaces_}source_package.spec$")
diff --git a/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-VerifyResult.cmake b/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-VerifyResult.cmake
deleted file mode 100644
index a84e296..0000000
--- a/Tests/RunCMake/CPack/RPM/SOURCE_PACKAGE-VerifyResult.cmake
+++ /dev/null
@@ -1,63 +0,0 @@
-file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm")
-file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/BUILD")
-file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/BUILDROOT")
-file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/RPMS")
-file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/SOURCES")
-file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/SPECS")
-file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/SRPMS")
-
-# make sure that we are using the version of cmake and cpack that we are testing
-get_filename_component(cpack_path_ "${CMAKE_CPACK_COMMAND}" DIRECTORY)
-set(ENV{PATH} "${cpack_path_}:$ENV{PATH}")
-
-execute_process(COMMAND ${RPMBUILD_EXECUTABLE} --define "_topdir ${CMAKE_CURRENT_BINARY_DIR}/test_rpm" --rebuild ${FOUND_FILE_1}
-      RESULT_VARIABLE result_
-      ERROR_VARIABLE  error_
-      OUTPUT_QUIET
-  )
-
-set(output_error_message_
-    "\n${RPMBUILD_EXECUTABLE} error: '${error_}';\nresult: '${result_}';\n${output_error_message}")
-
-set(EXPECTED_FILE_CONTENT_ "^/foo${whitespaces_}/foo/test_prog$")
-
-file(GLOB_RECURSE FOUND_FILE_ RELATIVE "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/RPMS" "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/RPMS/*.rpm")
-list(APPEND foundFiles_ "${FOUND_FILE_}")
-list(LENGTH FOUND_FILE_ foundFilesCount_)
-
-if(foundFilesCount_ EQUAL 1)
-  unset(PACKAGE_CONTENT)
-  getPackageContent("${CMAKE_CURRENT_BINARY_DIR}/test_rpm/RPMS/${FOUND_FILE_}" "PACKAGE_CONTENT")
-
-  string(REGEX MATCH "${EXPECTED_FILE_CONTENT_}"
-      expected_content_list "${PACKAGE_CONTENT}")
-
-  if(NOT expected_content_list)
-    message(FATAL_ERROR
-      "Unexpected file content!\n"
-      " Content: '${PACKAGE_CONTENT}'\n\n"
-      " Expected: '${EXPECTED_FILE_CONTENT_}'"
-      "${output_error_message_}")
-  endif()
-else()
-  message(FATAL_ERROR
-    "Found more than one file!"
-    " Found files count '${foundFilesCount_}'."
-    " Files: '${FOUND_FILE_}'"
-    "${output_error_message_}")
-endif()
-
-# check that there were no extra files generated
-foreach(all_files_glob_ IN LISTS ALL_FILES_GLOB)
-  file(GLOB foundAll_ RELATIVE "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/RPMS" "${all_files_glob_}")
-  list(APPEND allFoundFiles_ "${foundAll_}")
-endforeach()
-
-list(LENGTH foundFiles_ foundFilesCount_)
-list(LENGTH allFoundFiles_ allFoundFilesCount_)
-
-if(NOT foundFilesCount_ EQUAL allFoundFilesCount_)
-  message(FATAL_ERROR
-      "Found more files than expected! Found files: '${allFoundFiles_}'"
-      "${output_error_message_}")
-endif()
diff --git a/Tests/RunCMake/CPack/RPM/default_expected_stderr.txt b/Tests/RunCMake/CPack/RPM/default_expected_stderr.txt
new file mode 100644
index 0000000..4a0e4e6
--- /dev/null
+++ b/Tests/RunCMake/CPack/RPM/default_expected_stderr.txt
@@ -0,0 +1 @@
+^(CPackRPM: Will use GENERATED spec file: (/[^/]*)*/Tests/RunCMake/RPM/CPack/[^-]*-build((-[^-]*-subtest/)|/)_CPack_Packages/.*/RPM/SPECS/[^\.]*\.spec(\n|$))*$
diff --git a/Tests/RunCMake/CPack/RPM/packaging_COMPONENT_default.cmake b/Tests/RunCMake/CPack/RPM/packaging_COMPONENT_default.cmake
new file mode 100644
index 0000000..c8b93e9
--- /dev/null
+++ b/Tests/RunCMake/CPack/RPM/packaging_COMPONENT_default.cmake
@@ -0,0 +1 @@
+set(CPACK_RPM_COMPONENT_INSTALL "ON")
diff --git a/Tests/RunCMake/CPack/RPM_DIST.cmake b/Tests/RunCMake/CPack/RPM_DIST.cmake
deleted file mode 100644
index eb2a123..0000000
--- a/Tests/RunCMake/CPack/RPM_DIST.cmake
+++ /dev/null
@@ -1,4 +0,0 @@
-install(FILES CMakeLists.txt DESTINATION foo COMPONENT test)
-
-set(CPACK_RPM_PACKAGE_RELEASE_DIST ON)
-set(CPACK_PACKAGE_NAME "rpm_dist")
diff --git a/Tests/RunCMake/CPack/RunCMakeTest.cmake b/Tests/RunCMake/CPack/RunCMakeTest.cmake
index 60d42ac..65399db 100644
--- a/Tests/RunCMake/CPack/RunCMakeTest.cmake
+++ b/Tests/RunCMake/CPack/RunCMakeTest.cmake
@@ -3,20 +3,25 @@ cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
 include(RunCMake)
 include("${RunCMake_SOURCE_DIR}/CPackTestHelpers.cmake")
 
-# args: TEST_NAME "GENERATORS" RUN_CMAKE_BUILD_STEP
-run_cpack_test(MINIMAL "RPM;DEB;TGZ" false)
-run_cpack_source_test(SOURCE_PACKAGE "RPM" true)
-run_cpack_test(PARTIALLY_RELOCATABLE_WARNING "RPM" false)
-run_cpack_test(DEB_EXTRA "DEB" false)
-run_cpack_test(DEPENDENCIES "RPM;DEB" true)
-run_cpack_test(EMPTY_DIR "RPM;DEB;TGZ" true)
-run_cpack_test(COMPONENTS_EMPTY_DIR "RPM;DEB;TGZ" true)
-run_cpack_test(CUSTOM_NAMES "RPM;DEB" true)
-run_cpack_test(PER_COMPONENT_FIELDS "RPM;DEB" false)
-run_cpack_test(RPM_DIST "RPM" false)
-run_cpack_test(INSTALL_SCRIPTS "RPM" false)
-run_cpack_test(DEB_GENERATE_SHLIBS "DEB" true)
-run_cpack_test(DEB_GENERATE_SHLIBS_LDCONFIG "DEB" true)
-run_cpack_test(DEBUGINFO "RPM" true)
-run_cpack_test(LONG_FILENAMES "DEB" false)
-run_cpack_test_subtests(PACKAGE_CHECKSUM "invalid;MD5;SHA1;SHA224;SHA256;SHA384;SHA512" "TGZ" false)
+# run_cpack_test args: TEST_NAME "GENERATORS" RUN_CMAKE_BUILD_STEP "PACKAGING_TYPES"
+run_cpack_test(CUSTOM_BINARY_SPEC_FILE "RPM" false "MONOLITHIC;COMPONENT")
+run_cpack_test(CUSTOM_NAMES "RPM;DEB" true "COMPONENT")
+run_cpack_test(DEBUGINFO "RPM" true "COMPONENT")
+run_cpack_test(DEPENDENCIES "RPM;DEB" true "COMPONENT")
+run_cpack_test(DIST "RPM" false "MONOLITHIC")
+run_cpack_test(EMPTY_DIR "RPM;DEB;TGZ" true "MONOLITHIC;COMPONENT")
+run_cpack_test(EXTRA "DEB" false "COMPONENT")
+run_cpack_test(GENERATE_SHLIBS "DEB" true "COMPONENT")
+run_cpack_test(GENERATE_SHLIBS_LDCONFIG "DEB" true "COMPONENT")
+run_cpack_test(INSTALL_SCRIPTS "RPM" false "COMPONENT")
+run_cpack_test(LONG_FILENAMES "DEB" false "MONOLITHIC")
+run_cpack_test_subtests(MAIN_COMPONENT "invalid;found" "RPM" false "COMPONENT")
+run_cpack_test(MINIMAL "RPM;DEB;7Z;TBZ2;TGZ;TXZ;TZ;ZIP;STGZ" false "MONOLITHIC;COMPONENT")
+run_cpack_test_subtests(PACKAGE_CHECKSUM "invalid;MD5;SHA1;SHA224;SHA256;SHA384;SHA512" "TGZ" false "MONOLITHIC")
+run_cpack_test(PARTIALLY_RELOCATABLE_WARNING "RPM" false "COMPONENT")
+run_cpack_test(PER_COMPONENT_FIELDS "RPM;DEB" false "COMPONENT")
+run_cpack_test_subtests(SINGLE_DEBUGINFO "no_main_component;one_component;one_component_main;no_debuginfo;one_component_no_debuginfo;no_components;valid" "RPM" true "CUSTOM")
+run_cpack_source_test(SOURCE_PACKAGE "RPM")
+run_cpack_test(SUGGESTS "RPM" false "MONOLITHIC")
+run_cpack_test(USER_FILELIST "RPM" false "MONOLITHIC")
+run_cpack_test(MD5SUMS "DEB" false "MONOLITHIC;COMPONENT")
diff --git a/Tests/RunCMake/CPack/SOURCE_PACKAGE.cmake b/Tests/RunCMake/CPack/SOURCE_PACKAGE.cmake
deleted file mode 100644
index 946439d..0000000
--- a/Tests/RunCMake/CPack/SOURCE_PACKAGE.cmake
+++ /dev/null
@@ -1,9 +0,0 @@
-file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/main.cpp"
-    "int main() {return 0;}\n")
-add_executable(test_prog "${CMAKE_CURRENT_BINARY_DIR}/main.cpp")
-
-install(TARGETS test_prog DESTINATION foo COMPONENT applications)
-
-set(CPACK_RPM_FILE_NAME "RPM-DEFAULT")
-
-set(CPACK_PACKAGE_NAME "source_package")
diff --git a/Tests/RunCMake/CPack/STGZ/Helpers.cmake b/Tests/RunCMake/CPack/STGZ/Helpers.cmake
new file mode 100644
index 0000000..08224d3
--- /dev/null
+++ b/Tests/RunCMake/CPack/STGZ/Helpers.cmake
@@ -0,0 +1,64 @@
+set(ALL_FILES_GLOB "*.sh")
+
+function(getPackageContent FILE RESULT_VAR)
+  get_filename_component(path_ "${FILE}" DIRECTORY)
+  file(REMOVE_RECURSE "${path_}/content")
+  file(MAKE_DIRECTORY "${path_}/content")
+  execute_process(COMMAND ${FILE} --prefix=${path_}/content --include-subdir
+          RESULT_VARIABLE extract_result_
+          ERROR_VARIABLE extract_error_
+          OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+  if(extract_result_)
+    message(FATAL_ERROR "Extracting STGZ archive failed: '${extract_result_}';"
+          " '${extract_error_}'.")
+  endif()
+
+  file(GLOB_RECURSE package_content_ LIST_DIRECTORIES true RELATIVE
+      "${path_}/content" "${path_}/content/*")
+
+  set(${RESULT_VAR} "${package_content_}" PARENT_SCOPE)
+endfunction()
+
+function(getPackageNameGlobexpr NAME COMPONENT VERSION REVISION FILE_NO RESULT_VAR)
+  if(COMPONENT)
+    set(COMPONENT "-${COMPONENT}")
+  endif()
+
+  set(${RESULT_VAR} "${NAME}-${VERSION}-*${COMPONENT}.sh" PARENT_SCOPE)
+endfunction()
+
+function(getPackageContentList FILE RESULT_VAR)
+  getPackageContent("${FILE}" package_content_)
+
+  set(${RESULT_VAR} "${package_content_}" PARENT_SCOPE)
+endfunction()
+
+function(toExpectedContentList FILE_NO CONTENT_VAR)
+  findExpectedFile("${FILE_NO}" "file_")
+
+  get_filename_component(prefix_ "${file_}" NAME)
+  # NAME_WE removes everything after the dot and dot is in version so replace instead
+  string(REPLACE ".sh" "" prefix_ "${prefix_}")
+
+  if(NOT PACKAGING_TYPE STREQUAL "MONOLITHIC")
+    # STGZ packages don't have component dir prefix in subdir
+    string(FIND "${prefix_}" "-" pos_ REVERSE)
+    string(SUBSTRING "${prefix_}" 0 ${pos_} prefix_)
+  endif()
+
+  if(NOT DEFINED TEST_MAIN_INSTALL_PREFIX_PATH)
+    set(TEST_MAIN_INSTALL_PREFIX_PATH "/usr")
+  endif()
+
+  set(filtered_ "${prefix_}")
+  foreach(part_ IN LISTS ${CONTENT_VAR})
+    string(REGEX REPLACE "^${TEST_MAIN_INSTALL_PREFIX_PATH}(/|$)" "" part_ "${part_}")
+
+    if(part_)
+      list(APPEND filtered_ "${prefix_}/${part_}")
+    endif()
+  endforeach()
+
+  set(${CONTENT_VAR} "${filtered_}" PARENT_SCOPE)
+endfunction()
diff --git a/Tests/RunCMake/CPack/STGZ/Prerequirements.cmake b/Tests/RunCMake/CPack/STGZ/Prerequirements.cmake
new file mode 100644
index 0000000..3b015ca
--- /dev/null
+++ b/Tests/RunCMake/CPack/STGZ/Prerequirements.cmake
@@ -0,0 +1,11 @@
+function(get_test_prerequirements found_var config_file)
+  if(EXISTS "/bin/sh")
+    #gunzip is not part of posix so we should not rely on it being installed
+    find_program(GUNZIP_EXECUTABLE gunzip)
+
+    if(GUNZIP_EXECUTABLE)
+      file(WRITE "${config_file}" "")
+      set(${found_var} true PARENT_SCOPE)
+    endif()
+  endif()
+endfunction()
diff --git a/Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake b/Tests/RunCMake/CPack/STGZ/packaging_COMPONENT_default.cmake
similarity index 100%
copy from Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake
copy to Tests/RunCMake/CPack/STGZ/packaging_COMPONENT_default.cmake
diff --git a/Tests/RunCMake/CPack/TBZ2/Helpers.cmake b/Tests/RunCMake/CPack/TBZ2/Helpers.cmake
new file mode 100644
index 0000000..292b691
--- /dev/null
+++ b/Tests/RunCMake/CPack/TBZ2/Helpers.cmake
@@ -0,0 +1,3 @@
+set(cpack_archive_extension_ "tar.bz2")
+
+include("${CMAKE_CURRENT_LIST_DIR}/../ArchiveCommon/common_helpers.cmake")
diff --git a/Tests/RunCMake/CPack/TBZ2/Prerequirements.cmake b/Tests/RunCMake/CPack/TBZ2/Prerequirements.cmake
new file mode 100644
index 0000000..dbaf682
--- /dev/null
+++ b/Tests/RunCMake/CPack/TBZ2/Prerequirements.cmake
@@ -0,0 +1,4 @@
+function(get_test_prerequirements found_var config_file)
+  file(WRITE "${config_file}" "")
+  set(${found_var} true PARENT_SCOPE)
+endfunction()
diff --git a/Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake b/Tests/RunCMake/CPack/TBZ2/packaging_COMPONENT_default.cmake
similarity index 100%
copy from Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake
copy to Tests/RunCMake/CPack/TBZ2/packaging_COMPONENT_default.cmake
diff --git a/Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake b/Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake
deleted file mode 100644
index 26e2ab0..0000000
--- a/Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-ExpectedFiles.cmake
+++ /dev/null
@@ -1,3 +0,0 @@
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "components_empty_dir*.tar.gz")
-set(EXPECTED_FILE_CONTENT_1 "^[^\n]*empty/$")
diff --git a/Tests/RunCMake/CPack/TGZ/EMPTY_DIR-ExpectedFiles.cmake b/Tests/RunCMake/CPack/TGZ/EMPTY_DIR-ExpectedFiles.cmake
deleted file mode 100644
index a75514a..0000000
--- a/Tests/RunCMake/CPack/TGZ/EMPTY_DIR-ExpectedFiles.cmake
+++ /dev/null
@@ -1,3 +0,0 @@
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "empty_dir*.tar.gz")
-set(EXPECTED_FILE_CONTENT_1 "^[^\n]*empty_dir-0.1.1-[^\n]*/empty/$")
diff --git a/Tests/RunCMake/CPack/TGZ/Helpers.cmake b/Tests/RunCMake/CPack/TGZ/Helpers.cmake
index f14d532..4357a59 100644
--- a/Tests/RunCMake/CPack/TGZ/Helpers.cmake
+++ b/Tests/RunCMake/CPack/TGZ/Helpers.cmake
@@ -1,10 +1,3 @@
-set(ALL_FILES_GLOB "*.tar.gz")
+set(cpack_archive_extension_ "tar.gz")
 
-function(getPackageContent FILE RESULT_VAR)
-  execute_process(COMMAND ${CMAKE_COMMAND} -E tar -ztvf ${FILE}
-          OUTPUT_VARIABLE package_content_
-          ERROR_QUIET
-          OUTPUT_STRIP_TRAILING_WHITESPACE)
-
-  set(${RESULT_VAR} "${package_content_}" PARENT_SCOPE)
-endfunction()
+include("${CMAKE_CURRENT_LIST_DIR}/../ArchiveCommon/common_helpers.cmake")
diff --git a/Tests/RunCMake/CPack/TGZ/MINIMAL-ExpectedFiles.cmake b/Tests/RunCMake/CPack/TGZ/MINIMAL-ExpectedFiles.cmake
deleted file mode 100644
index 5c31f27..0000000
--- a/Tests/RunCMake/CPack/TGZ/MINIMAL-ExpectedFiles.cmake
+++ /dev/null
@@ -1,5 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "1")
-set(EXPECTED_FILE_1 "minimal*.tar.gz")
-set(EXPECTED_FILE_CONTENT_1 "^[^\n]*minimal-0.1.1-[^\n]*/foo/\n[^\n]*minimal-0.1.1-[^\n]*/foo/CMakeLists.txt$")
diff --git a/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-ExpectedFiles.cmake b/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-ExpectedFiles.cmake
deleted file mode 100644
index 205dcd8..0000000
--- a/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-ExpectedFiles.cmake
+++ /dev/null
@@ -1,9 +0,0 @@
-set(whitespaces_ "[\t\n\r ]*")
-
-set(EXPECTED_FILES_COUNT "0")
-
-if (NOT ${RunCMake_SUBTEST_SUFFIX} MATCHES "invalid")
-  set(EXPECTED_FILES_COUNT "1")
-  set(EXPECTED_FILE_1 "package_checksum*.tar.gz")
-  set(EXPECTED_FILE_CONTENT_1 "^[^\n]*package_checksum*-[^\n]*/foo/\n[^\n]*package_checksum-[^\n]*/foo/CMakeLists.txt$")
-endif()
diff --git a/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-VerifyResult.cmake b/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-VerifyResult.cmake
deleted file mode 100644
index e9e65d6..0000000
--- a/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-VerifyResult.cmake
+++ /dev/null
@@ -1,14 +0,0 @@
-if(NOT ${RunCMake_SUBTEST_SUFFIX} MATCHES "invalid")
-  string(TOLOWER ${RunCMake_SUBTEST_SUFFIX} EXTENSION)
-  file(GLOB PACKAGE RELATIVE ${bin_dir} "*.tar.gz")
-  file(GLOB CSUMFILE RELATIVE ${bin_dir} "*.${EXTENSION}")
-  file(STRINGS ${CSUMFILE} CHSUM_VALUE)
-  file(${RunCMake_SUBTEST_SUFFIX} ${PACKAGE} expected_value )
-  set(expected_value "${expected_value}  ${PACKAGE}")
-
-  if(NOT expected_value STREQUAL CHSUM_VALUE)
-    message(FATAL_ERROR "Generated checksum is not valid! Expected [${expected_value}] Got [${CHSUM_VALUE}]")
-  endif()
-else()
-  message(${error})
-endif()
diff --git a/Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake b/Tests/RunCMake/CPack/TGZ/packaging_COMPONENT_default.cmake
similarity index 100%
copy from Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake
copy to Tests/RunCMake/CPack/TGZ/packaging_COMPONENT_default.cmake
diff --git a/Tests/RunCMake/CPack/TXZ/Helpers.cmake b/Tests/RunCMake/CPack/TXZ/Helpers.cmake
new file mode 100644
index 0000000..f390cb4
--- /dev/null
+++ b/Tests/RunCMake/CPack/TXZ/Helpers.cmake
@@ -0,0 +1,3 @@
+set(cpack_archive_extension_ "tar.xz")
+
+include("${CMAKE_CURRENT_LIST_DIR}/../ArchiveCommon/common_helpers.cmake")
diff --git a/Tests/RunCMake/CPack/TXZ/Prerequirements.cmake b/Tests/RunCMake/CPack/TXZ/Prerequirements.cmake
new file mode 100644
index 0000000..dbaf682
--- /dev/null
+++ b/Tests/RunCMake/CPack/TXZ/Prerequirements.cmake
@@ -0,0 +1,4 @@
+function(get_test_prerequirements found_var config_file)
+  file(WRITE "${config_file}" "")
+  set(${found_var} true PARENT_SCOPE)
+endfunction()
diff --git a/Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake b/Tests/RunCMake/CPack/TXZ/packaging_COMPONENT_default.cmake
similarity index 100%
copy from Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake
copy to Tests/RunCMake/CPack/TXZ/packaging_COMPONENT_default.cmake
diff --git a/Tests/RunCMake/CPack/TZ/Helpers.cmake b/Tests/RunCMake/CPack/TZ/Helpers.cmake
new file mode 100644
index 0000000..117cd24
--- /dev/null
+++ b/Tests/RunCMake/CPack/TZ/Helpers.cmake
@@ -0,0 +1,3 @@
+set(cpack_archive_extension_ "tar.Z")
+
+include("${CMAKE_CURRENT_LIST_DIR}/../ArchiveCommon/common_helpers.cmake")
diff --git a/Tests/RunCMake/CPack/TZ/Prerequirements.cmake b/Tests/RunCMake/CPack/TZ/Prerequirements.cmake
new file mode 100644
index 0000000..dbaf682
--- /dev/null
+++ b/Tests/RunCMake/CPack/TZ/Prerequirements.cmake
@@ -0,0 +1,4 @@
+function(get_test_prerequirements found_var config_file)
+  file(WRITE "${config_file}" "")
+  set(${found_var} true PARENT_SCOPE)
+endfunction()
diff --git a/Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake b/Tests/RunCMake/CPack/TZ/packaging_COMPONENT_default.cmake
similarity index 100%
copy from Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake
copy to Tests/RunCMake/CPack/TZ/packaging_COMPONENT_default.cmake
diff --git a/Tests/RunCMake/CPack/VerifyResult.cmake b/Tests/RunCMake/CPack/VerifyResult.cmake
index 8bc2a58..59751a7 100644
--- a/Tests/RunCMake/CPack/VerifyResult.cmake
+++ b/Tests/RunCMake/CPack/VerifyResult.cmake
@@ -1,5 +1,28 @@
 cmake_minimum_required(VERSION ${CMAKE_VERSION} FATAL_ERROR)
 
+function(findExpectedFile FILE_NO RESULT_VAR)
+  if(NOT DEFINED EXPECTED_FILE_${FILE_NO}) # explicit file name regex was not provided - construct one from other data
+    # set defaults if parameters are not provided
+    if(NOT DEFINED EXPECTED_FILE_${FILE_NO}_NAME)
+      string(TOLOWER "${RunCMake_TEST_FILE_PREFIX}" EXPECTED_FILE_${FILE_NO}_NAME)
+    endif()
+    if(NOT DEFINED EXPECTED_FILE_${FILE_NO}_VERSION)
+      set(EXPECTED_FILE_${FILE_NO}_VERSION "0.1.1")
+    endif()
+    if(NOT DEFINED EXPECTED_FILE_${FILE_NO}_REVISION)
+      set(EXPECTED_FILE_${FILE_NO}_REVISION "1")
+    endif()
+
+    getPackageNameGlobexpr("${EXPECTED_FILE_${FILE_NO}_NAME}"
+      "${EXPECTED_FILE_${FILE_NO}_COMPONENT}" "${EXPECTED_FILE_${FILE_NO}_VERSION}"
+      "${EXPECTED_FILE_${FILE_NO}_REVISION}" "${FILE_NO}" "EXPECTED_FILE_${FILE_NO}")
+  endif()
+
+  file(GLOB found_file_ RELATIVE "${bin_dir}" "${EXPECTED_FILE_${FILE_NO}}")
+
+  set(${RESULT_VAR} "${found_file_}" PARENT_SCOPE)
+endfunction()
+
 include("${config_file}")
 include("${src_dir}/${GENERATOR_TYPE}/Helpers.cmake")
 
@@ -10,27 +33,46 @@ file(READ "${config_file}" config_file_content)
 set(output_error_message
     "\nCPack output: '${output}'\nCPack error: '${error}';\nCPack result: '${PACKAGING_RESULT}';\nconfig file: '${config_file_content}'")
 
-# check that expected generated files exist and contain expected content
-include("${src_dir}/${GENERATOR_TYPE}/${RunCMake_TEST_FILE_PREFIX}-ExpectedFiles.cmake")
+# generate default expected files data
+include("${src_dir}/tests/${RunCMake_TEST_FILE_PREFIX}/ExpectedFiles.cmake")
 
+# check that expected generated files exist and contain expected content
 if(NOT EXPECTED_FILES_COUNT EQUAL 0)
   foreach(file_no_ RANGE 1 ${EXPECTED_FILES_COUNT})
-    file(GLOB FOUND_FILE_${file_no_} RELATIVE "${bin_dir}" "${EXPECTED_FILE_${file_no_}}")
+    findExpectedFile("${file_no_}" "FOUND_FILE_${file_no_}")
     list(APPEND foundFiles_ "${FOUND_FILE_${file_no_}}")
     list(LENGTH FOUND_FILE_${file_no_} foundFilesCount_)
 
     if(foundFilesCount_ EQUAL 1)
       unset(PACKAGE_CONTENT)
-      getPackageContent("${bin_dir}/${FOUND_FILE_${file_no_}}" "PACKAGE_CONTENT")
 
-      string(REGEX MATCH "${EXPECTED_FILE_CONTENT_${file_no_}}"
-          expected_content_list "${PACKAGE_CONTENT}")
+      if(DEFINED EXPECTED_FILE_CONTENT_${file_no_})
+        getPackageContent("${bin_dir}/${FOUND_FILE_${file_no_}}" "PACKAGE_CONTENT")
+
+        string(REGEX MATCH "${EXPECTED_FILE_CONTENT_${file_no_}}"
+            expected_content_list "${PACKAGE_CONTENT}")
+      else() # use content list
+        getPackageContentList("${bin_dir}/${FOUND_FILE_${file_no_}}" "PACKAGE_CONTENT")
+        set(EXPECTED_FILE_CONTENT_${file_no_} "${EXPECTED_FILE_CONTENT_${file_no_}_LIST}")
+        toExpectedContentList("${file_no_}" "EXPECTED_FILE_CONTENT_${file_no_}")
+
+        list(SORT PACKAGE_CONTENT)
+        list(SORT EXPECTED_FILE_CONTENT_${file_no_})
+
+        if(PACKAGE_CONTENT STREQUAL EXPECTED_FILE_CONTENT_${file_no_})
+          set(expected_content_list TRUE)
+        else()
+          set(expected_content_list FALSE)
+        endif()
+      endif()
 
       if(NOT expected_content_list)
+        string(REPLACE "\n" "\n actual> " msg_actual "\n${PACKAGE_CONTENT}")
+        string(REPLACE "\n" "\n expect> " msg_expected "\n${EXPECTED_FILE_CONTENT_${file_no_}}")
         message(FATAL_ERROR
           "Unexpected file content for file No. '${file_no_}'!\n"
-          " Content: '${PACKAGE_CONTENT}'\n\n"
-          " Expected: '${EXPECTED_FILE_CONTENT_${file_no_}}'"
+          "The content was:${msg_actual}\n"
+          "which does not match:${msg_expected}\n"
           "${output_error_message}")
       endif()
     else()
@@ -38,6 +80,7 @@ if(NOT EXPECTED_FILES_COUNT EQUAL 0)
         "Found more than one file for file No. '${file_no_}'!"
         " Found files count '${foundFilesCount_}'."
         " Files: '${FOUND_FILE_${file_no_}}'"
+        " Globbing expression: '${EXPECTED_FILE_${file_no_}}'"
         "${output_error_message}")
     endif()
   endforeach()
@@ -82,11 +125,9 @@ else()
 endif()
 
 # handle additional result verifications
-if(EXISTS "${src_dir}/${GENERATOR_TYPE}/${RunCMake_TEST_FILE_PREFIX}-VerifyResult.cmake")
-  include("${src_dir}/${GENERATOR_TYPE}/${RunCMake_TEST_FILE_PREFIX}-VerifyResult.cmake")
-else()
-  # by default only print out output and error so that they can be compared by
-  # regex
-  message(STATUS "${output}")
-  message("${error}")
+if(EXISTS "${src_dir}/tests/${RunCMake_TEST_FILE_PREFIX}/VerifyResult.cmake")
+  include("${src_dir}/tests/${RunCMake_TEST_FILE_PREFIX}/VerifyResult.cmake")
 endif()
+
+message(STATUS "${output}")
+message("${error}")
diff --git a/Tests/RunCMake/CPack/ZIP/Helpers.cmake b/Tests/RunCMake/CPack/ZIP/Helpers.cmake
new file mode 100644
index 0000000..3710bcf
--- /dev/null
+++ b/Tests/RunCMake/CPack/ZIP/Helpers.cmake
@@ -0,0 +1,3 @@
+set(cpack_archive_extension_ "zip")
+
+include("${CMAKE_CURRENT_LIST_DIR}/../ArchiveCommon/common_helpers.cmake")
diff --git a/Tests/RunCMake/CPack/ZIP/Prerequirements.cmake b/Tests/RunCMake/CPack/ZIP/Prerequirements.cmake
new file mode 100644
index 0000000..dbaf682
--- /dev/null
+++ b/Tests/RunCMake/CPack/ZIP/Prerequirements.cmake
@@ -0,0 +1,4 @@
+function(get_test_prerequirements found_var config_file)
+  file(WRITE "${config_file}" "")
+  set(${found_var} true PARENT_SCOPE)
+endfunction()
diff --git a/Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake b/Tests/RunCMake/CPack/ZIP/packaging_COMPONENT_default.cmake
similarity index 100%
rename from Tests/RunCMake/CPack/TGZ/COMPONENTS_EMPTY_DIR-specifics.cmake
rename to Tests/RunCMake/CPack/ZIP/packaging_COMPONENT_default.cmake
diff --git a/Tests/RunCMake/CPack/tests/CUSTOM_BINARY_SPEC_FILE/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/CUSTOM_BINARY_SPEC_FILE/ExpectedFiles.cmake
new file mode 100644
index 0000000..694dc00
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/CUSTOM_BINARY_SPEC_FILE/ExpectedFiles.cmake
@@ -0,0 +1,9 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+
+if(PACKAGING_TYPE STREQUAL "COMPONENT")
+  set(EXPECTED_FILES_COUNT "2")
+  set(EXPECTED_FILE_1_COMPONENT "test")
+  set(EXPECTED_FILE_2_COMPONENT "test2")
+  set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/bar;/usr/bar/CMakeLists.txt")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/CUSTOM_BINARY_SPEC_FILE/RPM-COMPONENT-stderr.txt b/Tests/RunCMake/CPack/tests/CUSTOM_BINARY_SPEC_FILE/RPM-COMPONENT-stderr.txt
new file mode 100644
index 0000000..e6d86d0
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/CUSTOM_BINARY_SPEC_FILE/RPM-COMPONENT-stderr.txt
@@ -0,0 +1,2 @@
+^CPackRPM: Will use USER specified spec file: (/[^/]*)*/CUSTOM_BINARY_SPEC_FILE/custom\.spec\.in
+CPackRPM: Will use GENERATED spec file:.*/Tests/RunCMake/RPM/CPack/CUSTOM_BINARY_SPEC_FILE-build/_CPack_Packages/.*/RPM/SPECS/custom_binary_spec_file-test2\.spec$
diff --git a/Tests/RunCMake/CPack/tests/CUSTOM_BINARY_SPEC_FILE/RPM-MONOLITHIC-stderr.txt b/Tests/RunCMake/CPack/tests/CUSTOM_BINARY_SPEC_FILE/RPM-MONOLITHIC-stderr.txt
new file mode 100644
index 0000000..d7bb7af
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/CUSTOM_BINARY_SPEC_FILE/RPM-MONOLITHIC-stderr.txt
@@ -0,0 +1 @@
+CPackRPM: Will use USER specified spec file: (/[^/]*)*/CUSTOM_BINARY_SPEC_FILE/custom\.spec\.in
diff --git a/Tests/RunCMake/CPack/tests/CUSTOM_BINARY_SPEC_FILE/custom.spec.in b/Tests/RunCMake/CPack/tests/CUSTOM_BINARY_SPEC_FILE/custom.spec.in
new file mode 100644
index 0000000..db0ac6f
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/CUSTOM_BINARY_SPEC_FILE/custom.spec.in
@@ -0,0 +1,80 @@
+# -*- rpm-spec -*-
+BuildRoot:      %_topdir/@CPACK_PACKAGE_FILE_NAME@@CPACK_RPM_PACKAGE_COMPONENT_PART_PATH@
+Summary:        @CPACK_RPM_PACKAGE_SUMMARY@
+Name:           @CPACK_RPM_PACKAGE_NAME@
+Version:        @CPACK_RPM_PACKAGE_VERSION@
+Release:        @CPACK_RPM_PACKAGE_RELEASE@
+License:        @CPACK_RPM_PACKAGE_LICENSE@
+Group:          @CPACK_RPM_PACKAGE_GROUP@
+Vendor:         @CPACK_RPM_PACKAGE_VENDOR@
+
+ at TMP_RPM_URL@
+ at TMP_RPM_REQUIRES@
+ at TMP_RPM_REQUIRES_PRE@
+ at TMP_RPM_REQUIRES_POST@
+ at TMP_RPM_REQUIRES_PREUN@
+ at TMP_RPM_REQUIRES_POSTUN@
+ at TMP_RPM_PROVIDES@
+ at TMP_RPM_OBSOLETES@
+ at TMP_RPM_CONFLICTS@
+ at TMP_RPM_SUGGESTS@
+ at TMP_RPM_AUTOPROV@
+ at TMP_RPM_AUTOREQ@
+ at TMP_RPM_AUTOREQPROV@
+ at TMP_RPM_BUILDARCH@
+ at TMP_RPM_PREFIXES@
+
+ at TMP_RPM_DEBUGINFO@
+
+%define _rpmdir %_topdir/RPMS
+%define _srcrpmdir %_topdir/SRPMS
+ at FILE_NAME_DEFINE@
+%define _unpackaged_files_terminate_build 0
+ at TMP_RPM_SPEC_INSTALL_POST@
+ at CPACK_RPM_SPEC_MORE_DEFINE@
+ at CPACK_RPM_COMPRESSION_TYPE_TMP@
+
+%description
+ at CPACK_RPM_PACKAGE_DESCRIPTION@
+
+# This is a shortcutted spec file generated by CMake RPM generator
+# we skip _install step because CPack does that for us.
+# We do only save CPack installed tree in _prepr
+# and then restore it in build.
+%prep
+mv $RPM_BUILD_ROOT %_topdir/tmpBBroot
+
+%install
+if [ -e $RPM_BUILD_ROOT ];
+then
+  rm -rf $RPM_BUILD_ROOT
+fi
+mv %_topdir/tmpBBroot $RPM_BUILD_ROOT
+
+ at TMP_RPM_DEBUGINFO_INSTALL@
+
+%clean
+
+%post
+ at RPM_SYMLINK_POSTINSTALL@
+ at CPACK_RPM_SPEC_POSTINSTALL@
+
+%postun
+ at CPACK_RPM_SPEC_POSTUNINSTALL@
+
+%pre
+ at CPACK_RPM_SPEC_PREINSTALL@
+
+%preun
+ at CPACK_RPM_SPEC_PREUNINSTALL@
+
+%files
+%defattr(@TMP_DEFAULT_FILE_PERMISSIONS@, at TMP_DEFAULT_USER@, at TMP_DEFAULT_GROUP@, at TMP_DEFAULT_DIR_PERMISSIONS@)
+ at CPACK_RPM_INSTALL_FILES@
+ at CPACK_RPM_ABSOLUTE_INSTALL_FILES@
+ at CPACK_RPM_USER_INSTALL_FILES@
+
+%changelog
+ at CPACK_RPM_SPEC_CHANGELOG@
+
+ at TMP_OTHER_COMPONENTS@
diff --git a/Tests/RunCMake/CPack/tests/CUSTOM_BINARY_SPEC_FILE/test.cmake b/Tests/RunCMake/CPack/tests/CUSTOM_BINARY_SPEC_FILE/test.cmake
new file mode 100644
index 0000000..a604863
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/CUSTOM_BINARY_SPEC_FILE/test.cmake
@@ -0,0 +1,9 @@
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT test)
+
+if(PACKAGING_TYPE STREQUAL "MONOLITHIC")
+  set(CPACK_RPM_USER_BINARY_SPECFILE "${CMAKE_CURRENT_LIST_DIR}/custom.spec.in")
+elseif(PACKAGING_TYPE STREQUAL "COMPONENT")
+  install(FILES CMakeLists.txt DESTINATION bar COMPONENT test2)
+  set(CPACK_RPM_TEST_USER_BINARY_SPECFILE
+    "${CMAKE_CURRENT_LIST_DIR}/custom.spec.in")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/CUSTOM_NAMES/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/CUSTOM_NAMES/ExpectedFiles.cmake
new file mode 100644
index 0000000..ae5f0af
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/CUSTOM_NAMES/ExpectedFiles.cmake
@@ -0,0 +1,12 @@
+set(EXPECTED_FILES_COUNT "3")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
+set(EXPECTED_FILE_1_COMPONENT "pkg_1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+set(EXPECTED_FILE_2_NAME "second")
+set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+set(EXPECTED_FILE_CONTENT_3_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+
+if(GENERATOR_TYPE STREQUAL "DEB" OR GENERATOR_TYPE STREQUAL "RPM")
+  string(TOLOWER "${GENERATOR_TYPE}" file_extension_)
+  set(EXPECTED_FILE_3 "pkg_3_abc.${file_extension_}")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/CUSTOM_NAMES/test.cmake b/Tests/RunCMake/CPack/tests/CUSTOM_NAMES/test.cmake
new file mode 100644
index 0000000..0c2b37b
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/CUSTOM_NAMES/test.cmake
@@ -0,0 +1,14 @@
+if(GENERATOR_TYPE STREQUAL "DEB" OR GENERATOR_TYPE STREQUAL "RPM")
+  if(GENERATOR_TYPE STREQUAL "DEB")
+    set(generator_type_suffix_ "IAN") # not entirely compatible...
+  endif()
+
+  set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_FILE_NAME "${GENERATOR_TYPE}-DEFAULT")
+  set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_PKG_2_PACKAGE_NAME "second")
+  string(TOLOWER "${GENERATOR_TYPE}" file_extension_)
+  set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_PKG_3_FILE_NAME "pkg_3_abc.${file_extension_}")
+endif()
+
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_1)
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_2)
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_3)
diff --git a/Tests/RunCMake/CPack/tests/DEBUGINFO/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/DEBUGINFO/ExpectedFiles.cmake
new file mode 100644
index 0000000..06e56d3
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEBUGINFO/ExpectedFiles.cmake
@@ -0,0 +1,16 @@
+set(whitespaces_ "[\t\n\r ]*")
+
+set(EXPECTED_FILES_COUNT "5")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
+
+set(EXPECTED_FILE_1_COMPONENT "applications")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/test_prog")
+set(EXPECTED_FILE_2 "debuginfo*-headers.rpm")
+set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/bar;/usr/bar/CMakeLists.txt")
+set(EXPECTED_FILE_3 "debuginfo*-libs.rpm")
+set(EXPECTED_FILE_CONTENT_3_LIST "/usr;/usr/bas;/usr/bas/libtest_lib.so")
+
+set(EXPECTED_FILE_4_COMPONENT "applications-debuginfo")
+set(EXPECTED_FILE_CONTENT_4 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/main.cpp.*")
+set(EXPECTED_FILE_5_COMPONENT "libs-debuginfo")
+set(EXPECTED_FILE_CONTENT_5 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/test_lib.cpp.*")
diff --git a/Tests/RunCMake/CPack/tests/DEBUGINFO/test.cmake b/Tests/RunCMake/CPack/tests/DEBUGINFO/test.cmake
new file mode 100644
index 0000000..0642d83
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEBUGINFO/test.cmake
@@ -0,0 +1,30 @@
+set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
+
+# PGI compiler doesn't add build id to binaries by default
+if(CMAKE_CXX_COMPILER_ID STREQUAL "PGI")
+  string(APPEND CMAKE_EXE_LINKER_FLAGS "-Wl,--build-id")
+  string(APPEND CMAKE_SHARED_LINKER_FLAGS "-Wl,--build-id")
+endif()
+
+set(CMAKE_BUILD_TYPE Debug)
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.hpp"
+    "int test_lib();\n")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp"
+    "#include \"test_lib.hpp\"\nint test_lib() {return 0;}\n")
+add_library(test_lib SHARED "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp")
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/main.cpp"
+    "#include \"test_lib.hpp\"\nint main() {return test_lib();}\n")
+add_executable(test_prog "${CMAKE_CURRENT_BINARY_DIR}/main.cpp")
+target_link_libraries(test_prog test_lib)
+
+install(TARGETS test_prog DESTINATION foo COMPONENT applications)
+install(FILES CMakeLists.txt DESTINATION bar COMPONENT headers)
+install(TARGETS test_lib DESTINATION bas COMPONENT libs)
+
+set(CPACK_RPM_APPLICATIONS_FILE_NAME "RPM-DEFAULT")
+set(CPACK_RPM_APPLICATIONS_DEBUGINFO_PACKAGE ON)
+set(CPACK_RPM_LIBS_DEBUGINFO_PACKAGE ON)
+
+set(CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX "/src")
diff --git a/Tests/RunCMake/CPack/tests/DEPENDENCIES/DEB-stderr.txt b/Tests/RunCMake/CPack/tests/DEPENDENCIES/DEB-stderr.txt
new file mode 100644
index 0000000..5df274a
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEPENDENCIES/DEB-stderr.txt
@@ -0,0 +1 @@
+^CPackDeb: ((- Generating dependency list)|(Using only user-provided dependencies because dpkg-shlibdeps is not found\.))$
diff --git a/Tests/RunCMake/CPack/tests/DEPENDENCIES/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/DEPENDENCIES/ExpectedFiles.cmake
new file mode 100644
index 0000000..3b280ba
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEPENDENCIES/ExpectedFiles.cmake
@@ -0,0 +1,18 @@
+set(EXPECTED_FILES_COUNT "5")
+set(EXPECTED_FILE_1_COMPONENT "applications")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/test_prog")
+set(EXPECTED_FILE_2_COMPONENT "applications_auto")
+set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/foo_auto;/usr/foo_auto/test_prog")
+set(EXPECTED_FILE_3_COMPONENT "headers")
+set(EXPECTED_FILE_CONTENT_3_LIST "/usr;/usr/bar;/usr/bar/CMakeLists.txt")
+set(EXPECTED_FILE_4_COMPONENT "libs")
+set(EXPECTED_FILE_CONTENT_4_LIST "/usr/bas;/usr/bas/libtest_lib.so")
+set(EXPECTED_FILE_5_COMPONENT "libs_auto")
+set(EXPECTED_FILE_CONTENT_5_LIST "/usr;/usr/bas_auto;/usr/bas_auto/libtest_lib.so")
+
+if(GENERATOR_TYPE STREQUAL "DEB")
+  set(whitespaces_ "[\t\n\r ]*")
+  # dynamic lib extension is .so on Linux and .dylib on Mac so we will use a wildcard .* for it
+  set(EXPECTED_FILE_CONTENT_4 "^.*/usr/bas${whitespaces_}.*/usr/bas/libtest_lib\\..*$")
+  set(EXPECTED_FILE_CONTENT_5 "^.*/usr/bas_auto${whitespaces_}.*/usr/bas_auto/libtest_lib\\..*$")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/DEPENDENCIES/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/DEPENDENCIES/VerifyResult.cmake
new file mode 100644
index 0000000..7923148
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEPENDENCIES/VerifyResult.cmake
@@ -0,0 +1,82 @@
+if(GENERATOR_TYPE STREQUAL "DEB")
+  function(checkDependencies_ FILE REGEX)
+    set(whitespaces_ "[\t\n\r ]*")
+
+    getPackageInfo("${FILE}" "FILE_INFO_")
+    if(NOT FILE_INFO_ MATCHES "${REGEX}")
+      message(FATAL_ERROR "Unexpected dependencies in '${FILE}'; file info: '${FILE_INFO_}'")
+    endif()
+  endfunction()
+
+  foreach(dependency_type_ DEPENDS CONFLICTS ENHANCES BREAKS REPLACES RECOMMENDS SUGGESTS)
+    string(TOLOWER "${dependency_type_}" lower_dependency_type_)
+    string(SUBSTRING ${lower_dependency_type_} 1 -1 lower_dependency_type_tail_)
+    string(SUBSTRING ${dependency_type_} 0 1 dependency_type_head_)
+    set(dependency_type_name_ "${dependency_type_head_}${lower_dependency_type_tail_}")
+
+    checkDependencies_("${FOUND_FILE_1}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b.*")
+    checkDependencies_("${FOUND_FILE_2}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}.*${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b.*")
+    checkDependencies_("${FOUND_FILE_3}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-headers.*")
+    checkDependencies_("${FOUND_FILE_4}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-default, ${lower_dependency_type_}-default-b.*")
+    checkDependencies_("${FOUND_FILE_5}" ".*${dependency_type_name_}${whitespaces_}:${whitespaces_}${lower_dependency_type_}-default, ${lower_dependency_type_}-default-b.*")
+  endforeach()
+
+  checkDependencies_("${FOUND_FILE_1}" ".*Provides${whitespaces_}:${whitespaces_}provided-default, provided-default-b")
+  checkDependencies_("${FOUND_FILE_2}" ".*Provides${whitespaces_}:${whitespaces_}provided-default, provided-default-b")
+  checkDependencies_("${FOUND_FILE_3}" ".*Provides${whitespaces_}:${whitespaces_}provided-default, provided-default-b")
+  checkDependencies_("${FOUND_FILE_4}" ".*Provides${whitespaces_}:${whitespaces_}provided-lib.*")
+  checkDependencies_("${FOUND_FILE_5}" ".*Provides${whitespaces_}:${whitespaces_}provided-lib_auto.*, provided-lib_auto-b.*")
+
+  # PREDEPENDS
+  checkDependencies_("${FOUND_FILE_1}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-application, predepends-application-b.*")
+  checkDependencies_("${FOUND_FILE_2}" ".*Pre-Depends${whitespaces_}:${whitespaces_}.*predepends-application, predepends-application-b.*")
+  checkDependencies_("${FOUND_FILE_3}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-headers.*")
+  checkDependencies_("${FOUND_FILE_4}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-default, predepends-default-b.*")
+  checkDependencies_("${FOUND_FILE_5}" ".*Pre-Depends${whitespaces_}:${whitespaces_}predepends-default, predepends-default-b.*")
+elseif(GENERATOR_TYPE STREQUAL "RPM")
+  function(checkDependencies_ FILE TYPE COMPARE_LIST)
+    set(whitespaces_ "[\t\n\r ]*")
+
+    execute_process(COMMAND ${RPM_EXECUTABLE} -qp --${TYPE} ${FILE}
+            WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+            OUTPUT_VARIABLE FILE_DEPENDENCIES_
+            ERROR_QUIET
+            OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+    string(REPLACE "\n" ";" FILE_DEPENDENCIES_LIST_ "${FILE_DEPENDENCIES_}")
+
+    foreach(COMPARE_REGEX_ IN LISTS COMPARE_LIST)
+      unset(FOUND_)
+
+      foreach(COMPARE_ IN LISTS FILE_DEPENDENCIES_LIST_)
+        if(COMPARE_ MATCHES "${COMPARE_REGEX_}")
+          set(FOUND_ true)
+          break()
+        endif()
+      endforeach()
+
+      if(NOT FOUND_)
+        message(FATAL_ERROR "Missing dependencies in '${FILE}'; check type: '${TYPE}'; file info: '${FILE_DEPENDENCIES_}'; missing: '${COMPARE_REGEX_}'")
+      endif()
+    endforeach()
+  endfunction()
+
+  # TODO add tests for what should not be present in lists
+  checkDependencies_("${FOUND_FILE_1}" "requires" "depend-application;depend-application-b")
+  checkDependencies_("${FOUND_FILE_2}" "requires" "depend-application;depend-application-b;libtest_lib\\.so.*")
+  checkDependencies_("${FOUND_FILE_3}" "requires" "depend-headers")
+  checkDependencies_("${FOUND_FILE_4}" "requires" "depend-default;depend-default-b")
+  checkDependencies_("${FOUND_FILE_5}" "requires" "depend-default;depend-default-b")
+
+  checkDependencies_("${FOUND_FILE_1}" "conflicts" "conflicts-application;conflicts-application-b")
+  checkDependencies_("${FOUND_FILE_2}" "conflicts" "conflicts-application;conflicts-application-b")
+  checkDependencies_("${FOUND_FILE_3}" "conflicts" "conflicts-headers")
+  checkDependencies_("${FOUND_FILE_4}" "conflicts" "conflicts-default;conflicts-default-b")
+  checkDependencies_("${FOUND_FILE_5}" "conflicts" "conflicts-default;conflicts-default-b")
+
+  checkDependencies_("${FOUND_FILE_1}" "provides" "provided-default;provided-default-b")
+  checkDependencies_("${FOUND_FILE_2}" "provides" "provided-default;provided-default-b")
+  checkDependencies_("${FOUND_FILE_3}" "provides" "provided-default;provided-default-b")
+  checkDependencies_("${FOUND_FILE_4}" "provides" "provided-lib")
+  checkDependencies_("${FOUND_FILE_5}" "provides" "provided-lib_auto;provided-lib_auto-b")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/DEPENDENCIES/test.cmake b/Tests/RunCMake/CPack/tests/DEPENDENCIES/test.cmake
new file mode 100644
index 0000000..fbd786e
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEPENDENCIES/test.cmake
@@ -0,0 +1,60 @@
+if(GENERATOR_TYPE STREQUAL "DEB" OR GENERATOR_TYPE STREQUAL "RPM")
+  if(GENERATOR_TYPE STREQUAL "DEB")
+    # false by default
+    set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS FALSE)
+    # FIXME can not be tested as libraries first have to be part of a package in order
+    # to determine their dependencies and we can not be certain if there will be any
+    set(CPACK_DEBIAN_APPLICATIONS_AUTO_PACKAGE_SHLIBDEPS TRUE)
+
+    foreach(dependency_type_ DEPENDS PREDEPENDS ENHANCES BREAKS REPLACES RECOMMENDS SUGGESTS)
+      string(TOLOWER "${dependency_type_}" lower_dependency_type_)
+
+      set(CPACK_DEBIAN_PACKAGE_${dependency_type_} "${lower_dependency_type_}-default, ${lower_dependency_type_}-default-b")
+      set(CPACK_DEBIAN_APPLICATIONS_PACKAGE_${dependency_type_} "${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b")
+      set(CPACK_DEBIAN_APPLICATIONS_AUTO_PACKAGE_${dependency_type_} "${lower_dependency_type_}-application, ${lower_dependency_type_}-application-b")
+      set(CPACK_DEBIAN_HEADERS_PACKAGE_${dependency_type_} "${lower_dependency_type_}-headers")
+    endforeach()
+
+    set(generator_type_suffix_ "IAN") # not entirely compatible...
+  else() # RPM
+    # FIXME auto autoprov is not tested at the moment as Ubuntu 15.04 rpmbuild
+    # does not use them correctly: https://bugs.launchpad.net/rpm/+bug/1475755
+    set(CPACK_RPM_PACKAGE_AUTOREQ "no")
+    set(CPACK_RPM_PACKAGE_AUTOPROV "no")
+    set(CPACK_RPM_APPLICATIONS_AUTO_PACKAGE_AUTOREQPROV "yes")
+    set(CPACK_RPM_LIBS_AUTO_PACKAGE_AUTOREQPROV "yes")
+
+    set(CPACK_RPM_PACKAGE_REQUIRES "depend-default, depend-default-b")
+    set(CPACK_RPM_APPLICATIONS_PACKAGE_REQUIRES "depend-application, depend-application-b")
+    set(CPACK_RPM_APPLICATIONS_AUTO_PACKAGE_REQUIRES "depend-application, depend-application-b")
+    set(CPACK_RPM_HEADERS_PACKAGE_REQUIRES "depend-headers")
+  endif()
+
+  set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_PACKAGE_CONFLICTS "conflicts-default, conflicts-default-b")
+  set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_APPLICATIONS_PACKAGE_CONFLICTS "conflicts-application, conflicts-application-b")
+  set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_APPLICATIONS_AUTO_PACKAGE_CONFLICTS "conflicts-application, conflicts-application-b")
+  set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_HEADERS_PACKAGE_CONFLICTS "conflicts-headers")
+
+  set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_PACKAGE_PROVIDES "provided-default, provided-default-b")
+  set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_LIBS_PACKAGE_PROVIDES "provided-lib")
+  set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_LIBS_AUTO_PACKAGE_PROVIDES "provided-lib_auto, provided-lib_auto-b")
+endif()
+
+set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.hpp"
+    "int test_lib();\n")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp"
+    "#include \"test_lib.hpp\"\nint test_lib() {return 0;}\n")
+add_library(test_lib SHARED "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp")
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/main.cpp"
+    "#include \"test_lib.hpp\"\nint main() {return test_lib();}\n")
+add_executable(test_prog "${CMAKE_CURRENT_BINARY_DIR}/main.cpp")
+target_link_libraries(test_prog test_lib)
+
+install(TARGETS test_prog DESTINATION foo COMPONENT applications)
+install(TARGETS test_prog DESTINATION foo_auto COMPONENT applications_auto)
+install(FILES CMakeLists.txt DESTINATION bar COMPONENT headers)
+install(TARGETS test_lib DESTINATION bas COMPONENT libs)
+install(TARGETS test_lib DESTINATION bas_auto COMPONENT libs_auto)
diff --git a/Tests/RunCMake/CPack/tests/DIST/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/DIST/ExpectedFiles.cmake
new file mode 100644
index 0000000..6142eb3
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DIST/ExpectedFiles.cmake
@@ -0,0 +1,2 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
diff --git a/Tests/RunCMake/CPack/RPM/RPM_DIST-VerifyResult.cmake b/Tests/RunCMake/CPack/tests/DIST/VerifyResult.cmake
similarity index 100%
rename from Tests/RunCMake/CPack/RPM/RPM_DIST-VerifyResult.cmake
rename to Tests/RunCMake/CPack/tests/DIST/VerifyResult.cmake
diff --git a/Tests/RunCMake/CPack/tests/DIST/test.cmake b/Tests/RunCMake/CPack/tests/DIST/test.cmake
new file mode 100644
index 0000000..6bdd2c0
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DIST/test.cmake
@@ -0,0 +1,3 @@
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT test)
+
+set(CPACK_RPM_PACKAGE_RELEASE_DIST ON)
diff --git a/Tests/RunCMake/CPack/tests/EMPTY_DIR/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/EMPTY_DIR/ExpectedFiles.cmake
new file mode 100644
index 0000000..650687c
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EMPTY_DIR/ExpectedFiles.cmake
@@ -0,0 +1,7 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/empty")
+
+if(PACKAGING_TYPE STREQUAL "COMPONENT")
+  set(EXPECTED_FILE_1_COMPONENT "test")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/EMPTY_DIR/test.cmake b/Tests/RunCMake/CPack/tests/EMPTY_DIR/test.cmake
new file mode 100644
index 0000000..cd2c9fd
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EMPTY_DIR/test.cmake
@@ -0,0 +1,14 @@
+if(GENERATOR_TYPE STREQUAL "DEB" OR GENERATOR_TYPE STREQUAL "RPM")
+  if(GENERATOR_TYPE STREQUAL "DEB")
+    set(generator_type_suffix_ "IAN") # not entirely compatible...
+  endif()
+
+  set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_FILE_NAME "${GENERATOR_TYPE}-DEFAULT")
+endif()
+
+install(DIRECTORY DESTINATION empty
+        COMPONENT test)
+
+if(PACKAGING_TYPE STREQUAL "COMPONENT")
+  set(CPACK_COMPONENTS_ALL test)
+endif()
diff --git a/Tests/RunCMake/CPack/tests/EXTRA/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/EXTRA/ExpectedFiles.cmake
new file mode 100644
index 0000000..ded2923
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EXTRA/ExpectedFiles.cmake
@@ -0,0 +1,8 @@
+set(EXPECTED_FILES_COUNT "3")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
+set(EXPECTED_FILE_1_COMPONENT "foo")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+set(EXPECTED_FILE_2_COMPONENT "bar")
+set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/bar;/usr/bar/CMakeLists.txt")
+set(EXPECTED_FILE_3_COMPONENT "bas")
+set(EXPECTED_FILE_CONTENT_3_LIST "/usr;/usr/bas;/usr/bas/CMakeLists.txt")
diff --git a/Tests/RunCMake/CPack/DEB/DEB_EXTRA-VerifyResult.cmake b/Tests/RunCMake/CPack/tests/EXTRA/VerifyResult.cmake
similarity index 100%
rename from Tests/RunCMake/CPack/DEB/DEB_EXTRA-VerifyResult.cmake
rename to Tests/RunCMake/CPack/tests/EXTRA/VerifyResult.cmake
diff --git a/Tests/RunCMake/CPack/tests/EXTRA/test.cmake b/Tests/RunCMake/CPack/tests/EXTRA/test.cmake
new file mode 100644
index 0000000..efa6dac
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EXTRA/test.cmake
@@ -0,0 +1,35 @@
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT foo)
+install(FILES CMakeLists.txt DESTINATION bar COMPONENT bar)
+install(FILES CMakeLists.txt DESTINATION bas COMPONENT bas)
+
+file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/tmp/preinst "echo default_preinst")
+file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/tmp/prerm "echo default_prerm")
+
+foreach(file_ preinst prerm)
+  file(COPY ${CMAKE_CURRENT_BINARY_DIR}/tmp/${file_}
+    DESTINATION ${CMAKE_CURRENT_BINARY_DIR}
+    FILE_PERMISSIONS
+      OWNER_READ OWNER_WRITE OWNER_EXECUTE
+      GROUP_READ GROUP_EXECUTE
+      WORLD_READ WORLD_EXECUTE)
+endforeach()
+
+set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA
+    "${CMAKE_CURRENT_BINARY_DIR}/preinst;${CMAKE_CURRENT_BINARY_DIR}/prerm;${CMAKE_CURRENT_BINARY_DIR}/conffiles")
+
+file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/bar_tmp/preinst "echo bar_preinst")
+file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/bar_tmp/prerm "echo bar_prerm")
+
+foreach(file_ preinst prerm)
+  # not acceptable permissions for lintian but we need to check that
+  # permissions are preserved
+  file(COPY ${CMAKE_CURRENT_BINARY_DIR}/bar_tmp/${file_}
+    DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/bar
+    FILE_PERMISSIONS
+      OWNER_READ OWNER_WRITE OWNER_EXECUTE)
+endforeach()
+
+set(CPACK_DEBIAN_BAR_PACKAGE_CONTROL_EXTRA
+    "${CMAKE_CURRENT_BINARY_DIR}/bar/preinst;${CMAKE_CURRENT_BINARY_DIR}/bar/prerm")
+
+set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
diff --git a/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/DEB-Prerequirements.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/DEB-Prerequirements.cmake
new file mode 100644
index 0000000..be44b2e
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/DEB-Prerequirements.cmake
@@ -0,0 +1,7 @@
+function(get_test_prerequirements found_var config_file)
+  include(${config_file})
+
+  if(READELF_EXECUTABLE)
+    set(${found_var} true PARENT_SCOPE)
+  endif()
+endfunction()
diff --git a/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/ExpectedFiles.cmake
new file mode 100644
index 0000000..ccb5ef0
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/ExpectedFiles.cmake
@@ -0,0 +1,6 @@
+set(whitespaces_ "[\t\n\r ]*")
+
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
+# dynamic lib extension is .so on Linux and .dylib on Mac so we will use a wildcard .* for it
+set(EXPECTED_FILE_CONTENT_1 "^.*/usr/foo${whitespaces_}.*/usr/foo/libtest_lib\\..*$")
diff --git a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-VerifyResult.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/VerifyResult.cmake
similarity index 100%
rename from Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS-VerifyResult.cmake
rename to Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/VerifyResult.cmake
diff --git a/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/test.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/test.cmake
new file mode 100644
index 0000000..90351ba
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS/test.cmake
@@ -0,0 +1,14 @@
+set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
+
+set(CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS "ON")
+
+set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.hpp"
+    "int test_lib();\n")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp"
+    "#include \"test_lib.hpp\"\nint test_lib() {return 0;}\n")
+add_library(test_lib SHARED "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp")
+set_target_properties(test_lib PROPERTIES SOVERSION "0.8")
+
+install(TARGETS test_lib DESTINATION foo COMPONENT libs)
diff --git a/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/DEB-Prerequirements.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/DEB-Prerequirements.cmake
new file mode 100644
index 0000000..be44b2e
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/DEB-Prerequirements.cmake
@@ -0,0 +1,7 @@
+function(get_test_prerequirements found_var config_file)
+  include(${config_file})
+
+  if(READELF_EXECUTABLE)
+    set(${found_var} true PARENT_SCOPE)
+  endif()
+endfunction()
diff --git a/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/ExpectedFiles.cmake
new file mode 100644
index 0000000..d66c044
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/ExpectedFiles.cmake
@@ -0,0 +1,6 @@
+set(whitespaces_ "[\t\n\r ]*")
+
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
+# dynamic lib extension is .so on Linux and .dylib on Mac so we will use a wildcard .* for it
+set(EXPECTED_FILE_CONTENT_1 "^.*/usr/lib${whitespaces_}.*/usr/lib/libtest_lib\\..*$")
diff --git a/Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-VerifyResult.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/VerifyResult.cmake
similarity index 100%
rename from Tests/RunCMake/CPack/DEB/DEB_GENERATE_SHLIBS_LDCONFIG-VerifyResult.cmake
rename to Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/VerifyResult.cmake
diff --git a/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/test.cmake b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/test.cmake
new file mode 100644
index 0000000..15c496b
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/GENERATE_SHLIBS_LDCONFIG/test.cmake
@@ -0,0 +1,15 @@
+set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
+
+set(CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS "ON")
+set(CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS_POLICY ">=")
+
+set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.hpp"
+    "int test_lib();\n")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp"
+    "#include \"test_lib.hpp\"\nint test_lib() {return 0;}\n")
+add_library(test_lib SHARED "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp")
+set_target_properties(test_lib PROPERTIES SOVERSION "0.8")
+
+install(TARGETS test_lib LIBRARY DESTINATION lib COMPONENT libs NAMELINK_SKIP)
diff --git a/Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/ExpectedFiles.cmake
new file mode 100644
index 0000000..44346ab
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/ExpectedFiles.cmake
@@ -0,0 +1,5 @@
+set(EXPECTED_FILES_COUNT "2")
+set(EXPECTED_FILE_1_COMPONENT "foo")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+set(EXPECTED_FILE_2_COMPONENT "bar")
+set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/bar;/usr/bar/CMakeLists.txt")
diff --git a/Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-VerifyResult.cmake b/Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/VerifyResult.cmake
similarity index 100%
rename from Tests/RunCMake/CPack/RPM/INSTALL_SCRIPTS-VerifyResult.cmake
rename to Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/VerifyResult.cmake
diff --git a/Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/test.cmake b/Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/test.cmake
new file mode 100644
index 0000000..fb1b8de
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/INSTALL_SCRIPTS/test.cmake
@@ -0,0 +1,44 @@
+if(GENERATOR_TYPE STREQUAL "RPM")
+  set(CPACK_RPM_PRE_INSTALL_SCRIPT_FILE
+    "${CMAKE_CURRENT_BINARY_DIR}/pre_install.sh")
+  set(CPACK_RPM_POST_INSTALL_SCRIPT_FILE
+    "${CMAKE_CURRENT_BINARY_DIR}/post_install.sh")
+  set(CPACK_RPM_PRE_UNINSTALL_SCRIPT_FILE
+    "${CMAKE_CURRENT_BINARY_DIR}/pre_uninstall.sh")
+  set(CPACK_RPM_POST_UNINSTALL_SCRIPT_FILE
+    "${CMAKE_CURRENT_BINARY_DIR}/post_uninstall.sh")
+
+  set(CPACK_RPM_foo_PRE_INSTALL_SCRIPT_FILE
+    "${CMAKE_CURRENT_BINARY_DIR}/pre_install_foo.sh")
+  set(CPACK_RPM_foo_POST_INSTALL_SCRIPT_FILE
+    "${CMAKE_CURRENT_BINARY_DIR}/post_install_foo.sh")
+  set(CPACK_RPM_foo_PRE_UNINSTALL_SCRIPT_FILE
+    "${CMAKE_CURRENT_BINARY_DIR}/pre_uninstall_foo.sh")
+  set(CPACK_RPM_foo_POST_UNINSTALL_SCRIPT_FILE
+    "${CMAKE_CURRENT_BINARY_DIR}/post_uninstall_foo.sh")
+endif()
+
+set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
+
+# default
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/pre_install.sh"
+    "echo \"pre install\"\n")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/post_install.sh"
+    "echo \"post install\"\n")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/pre_uninstall.sh"
+    "echo \"pre uninstall\"\n")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/post_uninstall.sh"
+    "echo \"post uninstall\"\n")
+
+# specific
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/pre_install_foo.sh"
+    "echo \"pre install foo\"\n")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/post_install_foo.sh"
+    "echo \"post install foo\"\n")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/pre_uninstall_foo.sh"
+    "echo \"pre uninstall foo\"\n")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/post_uninstall_foo.sh"
+    "echo \"post uninstall foo\"\n")
+
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT foo)
+install(FILES CMakeLists.txt DESTINATION bar COMPONENT bar)
diff --git a/Tests/RunCMake/CPack/tests/LONG_FILENAMES/DEB-Prerequirements.cmake b/Tests/RunCMake/CPack/tests/LONG_FILENAMES/DEB-Prerequirements.cmake
new file mode 100644
index 0000000..ddd16e5
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/LONG_FILENAMES/DEB-Prerequirements.cmake
@@ -0,0 +1,7 @@
+function(get_test_prerequirements found_var config_file)
+  include(${config_file})
+
+  if(FAKEROOT_EXECUTABLE)
+    set(${found_var} true PARENT_SCOPE)
+  endif()
+endfunction()
diff --git a/Tests/RunCMake/CPack/tests/LONG_FILENAMES/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/LONG_FILENAMES/ExpectedFiles.cmake
new file mode 100644
index 0000000..631d957
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/LONG_FILENAMES/ExpectedFiles.cmake
@@ -0,0 +1,3 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/llllllllll_oooooooooo_nnnnnnnnnn_gggggggggg_ffffffffff_iiiiiiiiii_llllllllll_eeeeeeeeee_nnnnnnnnnn_aaaaaaaaaa_mmmmmmmmmm_eeeeeeeeee.txt")
diff --git a/Tests/RunCMake/CPack/DEB/LONG_FILENAMES-VerifyResult.cmake b/Tests/RunCMake/CPack/tests/LONG_FILENAMES/VerifyResult.cmake
similarity index 100%
rename from Tests/RunCMake/CPack/DEB/LONG_FILENAMES-VerifyResult.cmake
rename to Tests/RunCMake/CPack/tests/LONG_FILENAMES/VerifyResult.cmake
diff --git a/Tests/RunCMake/CPack/tests/LONG_FILENAMES/test.cmake b/Tests/RunCMake/CPack/tests/LONG_FILENAMES/test.cmake
new file mode 100644
index 0000000..f235d47
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/LONG_FILENAMES/test.cmake
@@ -0,0 +1,13 @@
+if(GENERATOR_TYPE STREQUAL "DEB")
+  set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT")
+  set(CPACK_DEBIAN_ARCHIVE_TYPE "gnutar")
+endif()
+
+set(LONG_FILENAME
+  "${CMAKE_CURRENT_BINARY_DIR}/llllllllll_oooooooooo_nnnnnnnnnn_gggggggggg_ffffffffff_iiiiiiiiii_llllllllll_eeeeeeeeee_nnnnnnnnnn_aaaaaaaaaa_mmmmmmmmmm_eeeeeeeeee.txt")
+
+file(WRITE
+  "${LONG_FILENAME}"
+  "long_filename_test")
+
+install(FILES ${LONG_FILENAME} DESTINATION foo)
diff --git a/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/ExpectedFiles.cmake
new file mode 100644
index 0000000..6bfb0c1
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/ExpectedFiles.cmake
@@ -0,0 +1,11 @@
+set(EXPECTED_FILES_COUNT "0")
+
+if(NOT RunCMake_SUBTEST_SUFFIX STREQUAL "invalid")
+  set(EXPECTED_FILES_COUNT "3")
+  set(EXPECTED_FILE_1 "main_component-0.1.1-1.*.rpm")
+  set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+  set(EXPECTED_FILE_2_COMPONENT "headers")
+  set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/bar;/usr/bar/CMakeLists.txt")
+  set(EXPECTED_FILE_3_COMPONENT "libs")
+  set(EXPECTED_FILE_CONTENT_3_LIST "/usr;/usr/bas;/usr/bas/CMakeLists.txt")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/RPM-invalid-stderr.txt b/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/RPM-invalid-stderr.txt
new file mode 100644
index 0000000..4d8ac6e
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/RPM-invalid-stderr.txt
@@ -0,0 +1 @@
+CPACK_RPM_MAIN_COMPONENT set to non existing component.
diff --git a/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/test.cmake b/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/test.cmake
new file mode 100644
index 0000000..791c586
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/MAIN_COMPONENT/test.cmake
@@ -0,0 +1,10 @@
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT applications)
+install(FILES CMakeLists.txt DESTINATION bar COMPONENT headers)
+install(FILES CMakeLists.txt DESTINATION bas COMPONENT libs)
+
+if(RunCMake_SUBTEST_SUFFIX STREQUAL "invalid")
+  set(CPACK_RPM_MAIN_COMPONENT "")
+else()
+  set(CPACK_RPM_MAIN_COMPONENT "applications")
+  set(CPACK_RPM_APPLICATIONS_FILE_NAME "RPM-DEFAULT")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/MD5SUMS/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/MD5SUMS/ExpectedFiles.cmake
new file mode 100644
index 0000000..6142eb3
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/MD5SUMS/ExpectedFiles.cmake
@@ -0,0 +1,2 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
diff --git a/Tests/RunCMake/CPack/tests/MD5SUMS/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/MD5SUMS/VerifyResult.cmake
new file mode 100644
index 0000000..fbdda9c
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/MD5SUMS/VerifyResult.cmake
@@ -0,0 +1,3 @@
+set(whitespaces_ "[\t\n\r ]*")
+set(md5sums_md5sums "^.* usr/foo/CMakeLists\.txt${whitespaces_}$")
+verifyDebControl("${FOUND_FILE_1}" "md5sums" "md5sums")
diff --git a/Tests/RunCMake/CPack/tests/MD5SUMS/test.cmake b/Tests/RunCMake/CPack/tests/MD5SUMS/test.cmake
new file mode 100644
index 0000000..15c5892
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/MD5SUMS/test.cmake
@@ -0,0 +1,5 @@
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT test)
+
+if(PACKAGING_TYPE STREQUAL "COMPONENT")
+  set(CPACK_COMPONENTS_ALL test)
+endif()
diff --git a/Tests/RunCMake/CPack/tests/MINIMAL/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/MINIMAL/ExpectedFiles.cmake
new file mode 100644
index 0000000..6142eb3
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/MINIMAL/ExpectedFiles.cmake
@@ -0,0 +1,2 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
diff --git a/Tests/RunCMake/CPack/tests/MINIMAL/test.cmake b/Tests/RunCMake/CPack/tests/MINIMAL/test.cmake
new file mode 100644
index 0000000..15c5892
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/MINIMAL/test.cmake
@@ -0,0 +1,5 @@
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT test)
+
+if(PACKAGING_TYPE STREQUAL "COMPONENT")
+  set(CPACK_COMPONENTS_ALL test)
+endif()
diff --git a/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/ExpectedFiles.cmake
new file mode 100644
index 0000000..eed5b92
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/ExpectedFiles.cmake
@@ -0,0 +1,6 @@
+set(EXPECTED_FILES_COUNT "0")
+
+if(NOT ${RunCMake_SUBTEST_SUFFIX} MATCHES "invalid")
+  set(EXPECTED_FILES_COUNT "1")
+  set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+endif()
diff --git a/Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-invalid-stderr.txt b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/TGZ-invalid-stderr.txt
similarity index 100%
rename from Tests/RunCMake/CPack/TGZ/PACKAGE_CHECKSUM-invalid-stderr.txt
rename to Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/TGZ-invalid-stderr.txt
diff --git a/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/VerifyResult.cmake
new file mode 100644
index 0000000..e4f9618
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/VerifyResult.cmake
@@ -0,0 +1,12 @@
+if(NOT ${RunCMake_SUBTEST_SUFFIX} MATCHES "invalid")
+  string(TOLOWER ${RunCMake_SUBTEST_SUFFIX} EXTENSION)
+  file(GLOB PACKAGE RELATIVE ${bin_dir} "*.tar.gz")
+  file(GLOB CSUMFILE RELATIVE ${bin_dir} "*.${EXTENSION}")
+  file(STRINGS ${CSUMFILE} CHSUM_VALUE)
+  file(${RunCMake_SUBTEST_SUFFIX} ${PACKAGE} expected_value )
+  set(expected_value "${expected_value}  ${PACKAGE}")
+
+  if(NOT expected_value STREQUAL CHSUM_VALUE)
+    message(FATAL_ERROR "Generated checksum is not valid! Expected [${expected_value}] Got [${CHSUM_VALUE}]")
+  endif()
+endif()
diff --git a/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/test.cmake b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/test.cmake
new file mode 100644
index 0000000..0838063
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/test.cmake
@@ -0,0 +1,3 @@
+install(FILES CMakeLists.txt DESTINATION foo)
+
+set(CPACK_PACKAGE_CHECKSUM ${RunCMake_SUBTEST_SUFFIX})
diff --git a/Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/ExpectedFiles.cmake
new file mode 100644
index 0000000..ae58c4b
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/ExpectedFiles.cmake
@@ -0,0 +1,2 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/not_relocatable;/not_relocatable/CMakeLists.txt;/opt")
diff --git a/Tests/RunCMake/CPack/RPM/PARTIALLY_RELOCATABLE_WARNING-stderr.txt b/Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/RPM-stderr.txt
similarity index 100%
rename from Tests/RunCMake/CPack/RPM/PARTIALLY_RELOCATABLE_WARNING-stderr.txt
rename to Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/RPM-stderr.txt
diff --git a/Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/test.cmake b/Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/test.cmake
new file mode 100644
index 0000000..4698fb3
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/PARTIALLY_RELOCATABLE_WARNING/test.cmake
@@ -0,0 +1,4 @@
+install(FILES CMakeLists.txt DESTINATION /not_relocatable COMPONENT static)
+
+set(CPACK_PACKAGE_RELOCATABLE TRUE)
+set(CPACK_PACKAGING_INSTALL_PREFIX "/opt")
diff --git a/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/ExpectedFiles.cmake
new file mode 100644
index 0000000..9bdb176
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/ExpectedFiles.cmake
@@ -0,0 +1,8 @@
+set(EXPECTED_FILES_COUNT "3")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
+set(EXPECTED_FILE_1_COMPONENT "pkg_1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+set(EXPECTED_FILE_2_NAME "second")
+set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+set(EXPECTED_FILE_3_COMPONENT "pkg_3")
+set(EXPECTED_FILE_CONTENT_3_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
diff --git a/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/VerifyResult.cmake
new file mode 100644
index 0000000..18ef63c
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/VerifyResult.cmake
@@ -0,0 +1,26 @@
+function(checkPackageInfo_ TYPE FILE REGEX)
+  getPackageInfo("${FILE}" "FILE_INFO_")
+  if(NOT FILE_INFO_ MATCHES "${REGEX}")
+    message(FATAL_ERROR "Unexpected ${TYPE} in '${FILE}'; file info: '${FILE_INFO_}'")
+  endif()
+endfunction()
+
+if(GENERATOR_TYPE STREQUAL "DEB")
+  set(name_ "Package")
+  set(group_ "Section")
+elseif(GENERATOR_TYPE STREQUAL "RPM")
+  set(name_ "Name")
+  set(group_ "Group")
+endif()
+
+set(whitespaces_ "[\t\n\r ]*")
+
+# check package name
+checkPackageInfo_("name" "${FOUND_FILE_1}" ".*${name_}${whitespaces_}:${whitespaces_}per_component_fields-pkg_1")
+checkPackageInfo_("name" "${FOUND_FILE_2}" ".*${name_}${whitespaces_}:${whitespaces_}second")
+checkPackageInfo_("name" "${FOUND_FILE_3}" ".*${name_}${whitespaces_}:${whitespaces_}per_component_fields-pkg_3")
+
+# check package group
+checkPackageInfo_("group" "${FOUND_FILE_1}" ".*${group_}${whitespaces_}:${whitespaces_}default")
+checkPackageInfo_("group" "${FOUND_FILE_2}" ".*${group_}${whitespaces_}:${whitespaces_}second_group")
+checkPackageInfo_("group" "${FOUND_FILE_3}" ".*${group_}${whitespaces_}:${whitespaces_}default")
diff --git a/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/test.cmake b/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/test.cmake
new file mode 100644
index 0000000..8719c0b
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/PER_COMPONENT_FIELDS/test.cmake
@@ -0,0 +1,18 @@
+if(GENERATOR_TYPE STREQUAL "DEB" OR GENERATOR_TYPE STREQUAL "RPM")
+  if(GENERATOR_TYPE STREQUAL "DEB")
+    set(generator_type_suffix_ "IAN") # not entirely compatible...
+    set(group_ "SECTION")
+  else()
+    set(group_ "GROUP")
+  endif()
+
+  set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_FILE_NAME "${GENERATOR_TYPE}-DEFAULT")
+
+  set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_PACKAGE_${group_} "default")
+  set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_PKG_2_PACKAGE_NAME "second")
+  set(CPACK_${GENERATOR_TYPE}${generator_type_suffix_}_PKG_2_PACKAGE_${group_} "second_group")
+endif()
+
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_1)
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_2)
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT pkg_3)
diff --git a/Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/ExpectedFiles.cmake
new file mode 100644
index 0000000..ca866ea
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/ExpectedFiles.cmake
@@ -0,0 +1,30 @@
+set(whitespaces_ "[\t\n\r ]*")
+set(EXPECTED_FILES_COUNT "0")
+set(EXPECTED_FILES_NAME_GENERATOR_SPECIFIC_FORMAT TRUE)
+
+if(RunCMake_SUBTEST_SUFFIX STREQUAL "valid" OR RunCMake_SUBTEST_SUFFIX STREQUAL "no_debuginfo")
+  set(EXPECTED_FILES_COUNT "4")
+  set(EXPECTED_FILE_1 "single_debuginfo-0.1.1-1.*.rpm")
+  set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/test_prog")
+  set(EXPECTED_FILE_2 "single_debuginfo*-headers.rpm")
+  set(EXPECTED_FILE_CONTENT_2_LIST "/usr;/usr/bar;/usr/bar/CMakeLists.txt")
+  set(EXPECTED_FILE_3 "single_debuginfo*-libs.rpm")
+  set(EXPECTED_FILE_CONTENT_3_LIST "/usr;/usr/bas;/usr/bas/libtest_lib.so")
+
+  set(EXPECTED_FILE_4_COMPONENT "debuginfo")
+  set(EXPECTED_FILE_CONTENT_4 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/main.cpp${whitespaces_}/src/src_1/test_lib.cpp.*")
+elseif(RunCMake_SUBTEST_SUFFIX STREQUAL "one_component" OR RunCMake_SUBTEST_SUFFIX STREQUAL "one_component_no_debuginfo")
+  set(EXPECTED_FILES_COUNT "2")
+  set(EXPECTED_FILE_1 "single_debuginfo-0*-applications.rpm")
+  set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/test_prog")
+
+  set(EXPECTED_FILE_2 "single_debuginfo-applications-debuginfo*.rpm")
+  set(EXPECTED_FILE_CONTENT_2 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/main.cpp.*")
+elseif(RunCMake_SUBTEST_SUFFIX STREQUAL "one_component_main" OR RunCMake_SUBTEST_SUFFIX STREQUAL "no_components")
+  set(EXPECTED_FILES_COUNT "2")
+  set(EXPECTED_FILE_1 "single_debuginfo-0*.rpm")
+  set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/test_prog")
+
+  set(EXPECTED_FILE_2 "single_debuginfo-debuginfo*.rpm")
+  set(EXPECTED_FILE_CONTENT_2 ".*/src${whitespaces_}/src/src_1${whitespaces_}/src/src_1/main.cpp.*")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/RPM-no_main_component-stderr.txt b/Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/RPM-no_main_component-stderr.txt
new file mode 100644
index 0000000..454283c
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/RPM-no_main_component-stderr.txt
@@ -0,0 +1 @@
+CPack Error: CPACK_RPM_MAIN_COMPONENT not set but it is mandatory with CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE being set.
diff --git a/Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/test.cmake b/Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/test.cmake
new file mode 100644
index 0000000..60e9038
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/SINGLE_DEBUGINFO/test.cmake
@@ -0,0 +1,54 @@
+set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
+
+# PGI compiler doesn't add build id to binaries by default
+if(CMAKE_CXX_COMPILER_ID STREQUAL "PGI")
+  string(APPEND CMAKE_EXE_LINKER_FLAGS "-Wl,--build-id")
+  string(APPEND CMAKE_SHARED_LINKER_FLAGS "-Wl,--build-id")
+endif()
+
+if(NOT RunCMake_SUBTEST_SUFFIX STREQUAL "no_components")
+  set(CPACK_RPM_COMPONENT_INSTALL "ON")
+endif()
+
+set(CMAKE_BUILD_TYPE Debug)
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.hpp"
+    "int test_lib();\n")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp"
+    "#include \"test_lib.hpp\"\nint test_lib() {return 0;}\n")
+add_library(test_lib SHARED "${CMAKE_CURRENT_BINARY_DIR}/test_lib.cpp")
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/main.cpp"
+    "#include \"test_lib.hpp\"\nint main() {return test_lib();}\n")
+add_executable(test_prog "${CMAKE_CURRENT_BINARY_DIR}/main.cpp")
+target_link_libraries(test_prog test_lib)
+
+install(TARGETS test_prog DESTINATION foo COMPONENT applications)
+
+if(RunCMake_SUBTEST_SUFFIX STREQUAL "valid"
+  OR RunCMake_SUBTEST_SUFFIX STREQUAL "no_main_component"
+  OR RunCMake_SUBTEST_SUFFIX STREQUAL "no_debuginfo")
+  install(FILES CMakeLists.txt DESTINATION bar COMPONENT headers)
+  install(TARGETS test_lib DESTINATION bas COMPONENT libs)
+elseif(RunCMake_SUBTEST_SUFFIX STREQUAL "one_component"
+  OR RunCMake_SUBTEST_SUFFIX STREQUAL "one_component_no_debuginfo")
+  set(CPACK_COMPONENTS_ALL applications)
+endif()
+
+set(CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE ON)
+
+if(RunCMake_SUBTEST_SUFFIX STREQUAL "valid"
+  OR RunCMake_SUBTEST_SUFFIX STREQUAL "one_component_main"
+  OR RunCMake_SUBTEST_SUFFIX STREQUAL "no_debuginfo")
+  set(CPACK_RPM_MAIN_COMPONENT "applications")
+  set(CPACK_RPM_APPLICATIONS_FILE_NAME "RPM-DEFAULT")
+endif()
+
+if(RunCMake_SUBTEST_SUFFIX STREQUAL "valid"
+  OR RunCMake_SUBTEST_SUFFIX STREQUAL "no_main_component"
+  OR RunCMake_SUBTEST_SUFFIX STREQUAL "one_component")
+  set(CPACK_RPM_APPLICATIONS_DEBUGINFO_PACKAGE ON)
+  set(CPACK_RPM_LIBS_DEBUGINFO_PACKAGE ON)
+endif()
+
+set(CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX "/src")
diff --git a/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/ExpectedFiles.cmake
new file mode 100644
index 0000000..0a3e426
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/ExpectedFiles.cmake
@@ -0,0 +1,2 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "source_package-0.1.1.tar.gz;source_package.spec")
diff --git a/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/VerifyResult.cmake
new file mode 100644
index 0000000..73d7481
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/VerifyResult.cmake
@@ -0,0 +1,67 @@
+set(whitespaces_ "[\t\n\r ]*")
+
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/BUILD")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/BUILDROOT")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/RPMS")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/SOURCES")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/SPECS")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/SRPMS")
+
+# make sure that we are using the version of cmake and cpack that we are testing
+get_filename_component(cpack_path_ "${CMAKE_CPACK_COMMAND}" DIRECTORY)
+set(ENV{PATH} "${cpack_path_}:$ENV{PATH}")
+
+execute_process(COMMAND ${RPMBUILD_EXECUTABLE} --define "_topdir ${CMAKE_CURRENT_BINARY_DIR}/test_rpm" --rebuild ${FOUND_FILE_1}
+      RESULT_VARIABLE result_
+      ERROR_VARIABLE  error_
+      OUTPUT_QUIET
+  )
+
+set(output_error_message_
+    "\n${RPMBUILD_EXECUTABLE} error: '${error_}';\nresult: '${result_}';\n${output_error_message}")
+
+# expected file content are test_prog and optional build-id links that are
+# generated by rpmbuild (introduced in rpm 4.13.0.1)
+set(EXPECTED_FILE_CONTENT_ "^/foo${whitespaces_}/foo/test_prog(${whitespaces_}.*\.build-id.*)*$")
+
+file(GLOB_RECURSE FOUND_FILE_ RELATIVE "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/RPMS" "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/RPMS/*.rpm")
+list(APPEND foundFiles_ "${FOUND_FILE_}")
+list(LENGTH FOUND_FILE_ foundFilesCount_)
+
+if(foundFilesCount_ EQUAL 1)
+  unset(PACKAGE_CONTENT)
+  getPackageContent("${CMAKE_CURRENT_BINARY_DIR}/test_rpm/RPMS/${FOUND_FILE_}" "PACKAGE_CONTENT")
+
+  string(REGEX MATCH "${EXPECTED_FILE_CONTENT_}"
+      expected_content_list "${PACKAGE_CONTENT}")
+
+  if(NOT expected_content_list)
+    message(FATAL_ERROR
+      "Unexpected file content!\n"
+      " Content: '${PACKAGE_CONTENT}'\n\n"
+      " Expected: '${EXPECTED_FILE_CONTENT_}'"
+      "${output_error_message_}")
+  endif()
+else()
+  message(FATAL_ERROR
+    "Found more than one file!"
+    " Found files count '${foundFilesCount_}'."
+    " Files: '${FOUND_FILE_}'"
+    "${output_error_message_}")
+endif()
+
+# check that there were no extra files generated
+foreach(all_files_glob_ IN LISTS ALL_FILES_GLOB)
+  file(GLOB foundAll_ RELATIVE "${CMAKE_CURRENT_BINARY_DIR}/test_rpm/RPMS" "${all_files_glob_}")
+  list(APPEND allFoundFiles_ "${foundAll_}")
+endforeach()
+
+list(LENGTH foundFiles_ foundFilesCount_)
+list(LENGTH allFoundFiles_ allFoundFilesCount_)
+
+if(NOT foundFilesCount_ EQUAL allFoundFilesCount_)
+  message(FATAL_ERROR
+      "Found more files than expected! Found files: '${allFoundFiles_}'"
+      "${output_error_message_}")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/test.cmake b/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/test.cmake
new file mode 100644
index 0000000..359b98f
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/SOURCE_PACKAGE/test.cmake
@@ -0,0 +1,7 @@
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/main.cpp"
+    "int main() {return 0;}\n")
+add_executable(test_prog "${CMAKE_CURRENT_BINARY_DIR}/main.cpp")
+
+install(TARGETS test_prog DESTINATION foo COMPONENT applications)
+
+set(CPACK_RPM_FILE_NAME "RPM-DEFAULT")
diff --git a/Tests/RunCMake/CPack/tests/SUGGESTS/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/SUGGESTS/ExpectedFiles.cmake
new file mode 100644
index 0000000..6142eb3
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/SUGGESTS/ExpectedFiles.cmake
@@ -0,0 +1,2 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
diff --git a/Tests/RunCMake/CPack/tests/SUGGESTS/RPM-stderr.txt b/Tests/RunCMake/CPack/tests/SUGGESTS/RPM-stderr.txt
new file mode 100644
index 0000000..feb296c
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/SUGGESTS/RPM-stderr.txt
@@ -0,0 +1 @@
+^(.*CPackRPM:Warning: SUGGESTS not supported in provided rpmbuild.*)?CPackRPM: Will use GENERATED spec file: (/[^/]*)*/Tests/RunCMake/RPM/CPack/[^-]*-build/_CPack_Packages/.*/RPM/SPECS/[^\.]*\.spec$
diff --git a/Tests/RunCMake/CPack/tests/SUGGESTS/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/SUGGESTS/VerifyResult.cmake
new file mode 100644
index 0000000..32cc6d1
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/SUGGESTS/VerifyResult.cmake
@@ -0,0 +1,31 @@
+execute_process(COMMAND ${RPMBUILD_EXECUTABLE} --querytags
+                OUTPUT_VARIABLE RPMBUILD_CAPS
+                RESULT_VARIABLE RPMBUILD_CAPS_RESULT)
+
+if(NOT RPMBUILD_CAPS_RESULT)
+  string(REPLACE "\n" ";" RPMBUILD_CAPS "${RPMBUILD_CAPS}")
+  cmake_policy(PUSH)
+    cmake_policy(SET CMP0057 NEW)
+    if(SUGGESTS IN_LIST RPMBUILD_CAPS)
+      set(should_contain_suggests_tag_ true)
+    endif()
+  cmake_policy(POP)
+endif()
+
+# Only verify that suggests tag is present only if that tag is supported.
+# If it is not supported the rpm package was corretly generated by ignoring
+# that tag and that was already checked by expected files test.
+if(should_contain_suggests_tag_)
+  execute_process(COMMAND ${RPM_EXECUTABLE} -q --suggests -p "${FOUND_FILE_1}"
+                  WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+                  RESULT_VARIABLE rpm_result_
+                  OUTPUT_VARIABLE rpm_output_
+                  ERROR_VARIABLE error_variable_
+                  OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+  if(rpm_result_ OR NOT rpm_output_ STREQUAL "libsuggested")
+    message(FATAL_ERROR "RPM_SUGGESTED package error: no suggested packages"
+        " (result: '${rpm_result_}'; output: '${rpm_output_}';"
+        " error: '${error_variable_}')")
+  endif()
+endif()
diff --git a/Tests/RunCMake/CPack/tests/SUGGESTS/test.cmake b/Tests/RunCMake/CPack/tests/SUGGESTS/test.cmake
new file mode 100644
index 0000000..dc90ae8
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/SUGGESTS/test.cmake
@@ -0,0 +1,3 @@
+install(FILES CMakeLists.txt DESTINATION foo)
+
+set(CPACK_RPM_PACKAGE_SUGGESTS "libsuggested")
diff --git a/Tests/RunCMake/CPack/tests/USER_FILELIST/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/USER_FILELIST/ExpectedFiles.cmake
new file mode 100644
index 0000000..aabe537
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/USER_FILELIST/ExpectedFiles.cmake
@@ -0,0 +1,2 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr/one;/usr/one/foo.txt;/usr/one/two;/usr/one/two/bar.txt;/usr/three;/usr/three/baz.txt;/usr/three/qux.txt")
diff --git a/Tests/RunCMake/CPack/tests/USER_FILELIST/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/USER_FILELIST/VerifyResult.cmake
new file mode 100644
index 0000000..57444ed
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/USER_FILELIST/VerifyResult.cmake
@@ -0,0 +1,12 @@
+execute_process(COMMAND ${RPM_EXECUTABLE} -qpd ${FOUND_FILE_1}
+  WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+  OUTPUT_VARIABLE DOC_FILES_
+  ERROR_QUIET
+  OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+string(REPLACE "\n" ";" DOC_FILES_ "${DOC_FILES_}")
+
+set(DOC_FILES_WANTED_ "/usr/one/foo.txt;/usr/one/two/bar.txt;/usr/three/baz.txt")
+if (NOT "${DOC_FILES_}" STREQUAL "${DOC_FILES_WANTED_}")
+  message(FATAL_ERROR "USER_FILELIST handling error: Check filelist in spec file. Doc files were: ${DOC_FILES_}. Should have been ${DOC_FILES_WANTED_}")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/USER_FILELIST/test.cmake b/Tests/RunCMake/CPack/tests/USER_FILELIST/test.cmake
new file mode 100644
index 0000000..acfee42
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/USER_FILELIST/test.cmake
@@ -0,0 +1,13 @@
+install(FILES CMakeLists.txt DESTINATION one     RENAME foo.txt)
+install(FILES CMakeLists.txt DESTINATION one/two RENAME bar.txt)
+install(FILES CMakeLists.txt DESTINATION three   RENAME baz.txt)
+install(FILES CMakeLists.txt DESTINATION three   RENAME qux.txt)
+
+# We are verifying the USER_FILELIST works by comparing what
+# ends up with a %doc tag in the final rpm with what we expect
+# from this USER_FILELIST.
+set(CPACK_RPM_USER_FILELIST
+  "%doc /usr/one/foo.txt"
+  "%doc %attr(640,root,root) /usr/one/two/bar.txt"
+  "%attr(600, -, root) %doc /usr/three/baz.txt"
+)
diff --git a/Tests/RunCMake/CTestCommandLine/RunCMakeTest.cmake b/Tests/RunCMake/CTestCommandLine/RunCMakeTest.cmake
index 2bc3693..e936dab 100644
--- a/Tests/RunCMake/CTestCommandLine/RunCMakeTest.cmake
+++ b/Tests/RunCMake/CTestCommandLine/RunCMakeTest.cmake
@@ -135,6 +135,7 @@ function(run_TestOutputSize)
 ")
   run_cmake_command(TestOutputSize
     ${CMAKE_CTEST_COMMAND} -M Experimental -T Test
+                           --no-compress-output
                            --test-output-size-passed 10
                            --test-output-size-failed 12
     )
diff --git a/Tests/RunCMake/CTestCommandLine/repeat-until-fail-cmake.cmake b/Tests/RunCMake/CTestCommandLine/repeat-until-fail-cmake.cmake
index 4654416..ecb9a64 100644
--- a/Tests/RunCMake/CTestCommandLine/repeat-until-fail-cmake.cmake
+++ b/Tests/RunCMake/CTestCommandLine/repeat-until-fail-cmake.cmake
@@ -12,4 +12,6 @@ add_test(NAME test1
 set_tests_properties(test1 PROPERTIES DEPENDS "initialization")
 
 add_test(hello ${CMAKE_COMMAND} -E echo hello)
+set_tests_properties(hello PROPERTIES FAIL_REGULAR_EXPRESSION "hello.*hello")
+
 add_test(goodbye ${CMAKE_COMMAND} -E echo goodbye)
diff --git a/Tests/RunCMake/ClangTidy/C-bad-Build-result.txt b/Tests/RunCMake/ClangTidy/C-bad-Build-result.txt
new file mode 100644
index 0000000..d197c91
--- /dev/null
+++ b/Tests/RunCMake/ClangTidy/C-bad-Build-result.txt
@@ -0,0 +1 @@
+[^0]
diff --git a/Tests/RunCMake/ClangTidy/C-bad-Build-stdout.txt b/Tests/RunCMake/ClangTidy/C-bad-Build-stdout.txt
new file mode 100644
index 0000000..2370ce1
--- /dev/null
+++ b/Tests/RunCMake/ClangTidy/C-bad-Build-stdout.txt
@@ -0,0 +1,2 @@
+stdout from bad command line arg '-bad'
+stderr from bad command line arg '-bad'
diff --git a/Tests/RunCMake/ClangTidy/C-bad.cmake b/Tests/RunCMake/ClangTidy/C-bad.cmake
new file mode 100644
index 0000000..aa54c08
--- /dev/null
+++ b/Tests/RunCMake/ClangTidy/C-bad.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+set(CMAKE_C_CLANG_TIDY "${PSEUDO_TIDY}" -bad)
+add_executable(main main.c)
diff --git a/Tests/RunCMake/ClangTidy/RunCMakeTest.cmake b/Tests/RunCMake/ClangTidy/RunCMakeTest.cmake
index 27cd922..2f41e50 100644
--- a/Tests/RunCMake/ClangTidy/RunCMakeTest.cmake
+++ b/Tests/RunCMake/ClangTidy/RunCMakeTest.cmake
@@ -20,3 +20,4 @@ if (NOT RunCMake_GENERATOR STREQUAL "Watcom WMake")
   run_tidy(C-launch)
   run_tidy(CXX-launch)
 endif()
+run_tidy(C-bad)
diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-stderr.txt b/Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-stderr.txt
index 0d0d899..35f50b7 100644
--- a/Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-stderr.txt
+++ b/Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-stderr.txt
@@ -1 +1 @@
-^__run_iwyu missing --tidy= or --iwyu=$
+^__run_iwyu missing --cpplint=, --iwyu=, --lwyu=, and/or --tidy=$
diff --git a/Tests/RunCMake/CommandLine/cmake_depends/.gitattributes b/Tests/RunCMake/CommandLine/cmake_depends/.gitattributes
new file mode 100644
index 0000000..9c22288
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/cmake_depends/.gitattributes
@@ -0,0 +1,2 @@
+# Do not format a source encoded in UTF-16.
+test_UTF-16LE.h -format.clang-format
diff --git a/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycle.cmake b/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycle.cmake
index 09594bd..2d14a9e 100644
--- a/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycle.cmake
+++ b/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycle.cmake
@@ -3,13 +3,13 @@ add_library(empty1 empty.cpp)
 
 add_library(empty2 INTERFACE)
 add_library(empty3 INTERFACE)
-target_compile_features(empty3 INTERFACE cxx_static_assert)
+target_compile_features(empty3 INTERFACE cxx_std_11)
 
 target_link_libraries(empty1
   # When starting, $<COMPILE_FEATURES:cxx_auto_type> is '0', so 'freeze' the
   # CXX_STANDARD at 98 during computation.
   $<$<COMPILE_FEATURES:cxx_auto_type>:empty2>
-  # This would add cxx_static_assert, but that would require CXX_STANDARD = 11,
+  # This would add cxx_std_11, but that would require CXX_STANDARD = 11,
   # which is not allowed after freeze.  Report an error.
   empty3
 )
diff --git a/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycleSolved.cmake b/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycleSolved.cmake
index bbcf4e0..a04dcec 100644
--- a/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycleSolved.cmake
+++ b/Tests/RunCMake/CompileFeatures/LinkImplementationFeatureCycleSolved.cmake
@@ -3,7 +3,7 @@ add_library(empty1 empty.cpp)
 
 add_library(empty2 INTERFACE)
 add_library(empty3 INTERFACE)
-target_compile_features(empty3 INTERFACE cxx_static_assert)
+target_compile_features(empty3 INTERFACE cxx_std_11)
 
 target_link_libraries(empty1
   $<$<COMPILE_FEATURES:cxx_nullptr>:empty2>
diff --git a/Tests/RunCMake/Configure/RemoveCache-stdout.txt b/Tests/RunCMake/Configure/RemoveCache-stdout.txt
new file mode 100644
index 0000000..73e7e5d
--- /dev/null
+++ b/Tests/RunCMake/Configure/RemoveCache-stdout.txt
@@ -0,0 +1 @@
+-- The C compiler identification is
diff --git a/Tests/RunCMake/Configure/RemoveCache.cmake b/Tests/RunCMake/Configure/RemoveCache.cmake
new file mode 100644
index 0000000..304918f
--- /dev/null
+++ b/Tests/RunCMake/Configure/RemoveCache.cmake
@@ -0,0 +1,17 @@
+enable_language(C)
+
+set(vars
+  CMAKE_EXECUTABLE_FORMAT
+  )
+
+if(CMAKE_HOST_UNIX)
+  list(APPEND vars
+    CMAKE_UNAME
+    )
+endif()
+
+foreach(v IN LISTS vars)
+  if(NOT DEFINED ${v})
+    message(SEND_ERROR "Variable '${v}' is not set!")
+  endif()
+endforeach()
diff --git a/Tests/RunCMake/Configure/RunCMakeTest.cmake b/Tests/RunCMake/Configure/RunCMakeTest.cmake
index 91adb4e..4a135be 100644
--- a/Tests/RunCMake/Configure/RunCMakeTest.cmake
+++ b/Tests/RunCMake/Configure/RunCMakeTest.cmake
@@ -24,3 +24,12 @@ file(WRITE "${depend}" "2")
 run_cmake_command(RerunCMake-build2 ${CMAKE_COMMAND} --build .)
 unset(RunCMake_TEST_BINARY_DIR)
 unset(RunCMake_TEST_NO_CLEAN)
+
+# Use a single build tree for a few tests without cleaning.
+set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/RemoveCache-build)
+set(RunCMake_TEST_NO_CLEAN 1)
+file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+run_cmake(RemoveCache)
+file(REMOVE "${RunCMake_TEST_BINARY_DIR}/CMakeCache.txt")
+run_cmake(RemoveCache)
diff --git a/Tests/RunCMake/Cpplint/C-Build-stdout.txt b/Tests/RunCMake/Cpplint/C-Build-stdout.txt
new file mode 100644
index 0000000..6a22b79
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/C-Build-stdout.txt
@@ -0,0 +1 @@
+Total errors found: 0
diff --git a/Tests/RunCMake/Cpplint/C-error-Build-result.txt b/Tests/RunCMake/Cpplint/C-error-Build-result.txt
new file mode 100644
index 0000000..d197c91
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/C-error-Build-result.txt
@@ -0,0 +1 @@
+[^0]
diff --git a/Tests/RunCMake/Cpplint/C-error-Build-stdout.txt b/Tests/RunCMake/Cpplint/C-error-Build-stdout.txt
new file mode 100644
index 0000000..3e7a1e9
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/C-error-Build-stdout.txt
@@ -0,0 +1 @@
+Tests[/\]RunCMake[/\]Cpplint[/\]main\.c:0:  message  \[category/category\] \[0\]
diff --git a/Tests/RunCMake/Cpplint/C-error-launch-Build-result.txt b/Tests/RunCMake/Cpplint/C-error-launch-Build-result.txt
new file mode 100644
index 0000000..d197c91
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/C-error-launch-Build-result.txt
@@ -0,0 +1 @@
+[^0]
diff --git a/Tests/RunCMake/Cpplint/C-error-launch-Build-stdout.txt b/Tests/RunCMake/Cpplint/C-error-launch-Build-stdout.txt
new file mode 100644
index 0000000..3e7a1e9
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/C-error-launch-Build-stdout.txt
@@ -0,0 +1 @@
+Tests[/\]RunCMake[/\]Cpplint[/\]main\.c:0:  message  \[category/category\] \[0\]
diff --git a/Tests/RunCMake/Cpplint/C-error-launch.cmake b/Tests/RunCMake/Cpplint/C-error-launch.cmake
new file mode 100644
index 0000000..c76e2e2
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/C-error-launch.cmake
@@ -0,0 +1,3 @@
+set(CTEST_USE_LAUNCHERS 1)
+include(CTestUseLaunchers)
+include(C-error.cmake)
diff --git a/Tests/RunCMake/Cpplint/C-error.cmake b/Tests/RunCMake/Cpplint/C-error.cmake
new file mode 100644
index 0000000..29cf7ba
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/C-error.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+set(CMAKE_C_CPPLINT "${PSEUDO_CPPLINT}" --error)
+add_executable(main main.c)
diff --git a/Tests/RunCMake/Cpplint/C-launch-Build-stdout.txt b/Tests/RunCMake/Cpplint/C-launch-Build-stdout.txt
new file mode 100644
index 0000000..6a22b79
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/C-launch-Build-stdout.txt
@@ -0,0 +1 @@
+Total errors found: 0
diff --git a/Tests/RunCMake/Cpplint/C-launch.cmake b/Tests/RunCMake/Cpplint/C-launch.cmake
new file mode 100644
index 0000000..e66ca20
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/C-launch.cmake
@@ -0,0 +1,3 @@
+set(CTEST_USE_LAUNCHERS 1)
+include(CTestUseLaunchers)
+include(C.cmake)
diff --git a/Tests/RunCMake/Cpplint/C.cmake b/Tests/RunCMake/Cpplint/C.cmake
new file mode 100644
index 0000000..68e6ff4
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/C.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+set(CMAKE_C_CPPLINT "${PSEUDO_CPPLINT}" --verbose=0 --linelength=80)
+add_executable(main main.c)
diff --git a/Tests/RunCMake/Cpplint/CMakeLists.txt b/Tests/RunCMake/Cpplint/CMakeLists.txt
new file mode 100644
index 0000000..a640c56
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.7)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/Cpplint/CXX-Build-stdout.txt b/Tests/RunCMake/Cpplint/CXX-Build-stdout.txt
new file mode 100644
index 0000000..6a22b79
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/CXX-Build-stdout.txt
@@ -0,0 +1 @@
+Total errors found: 0
diff --git a/Tests/RunCMake/Cpplint/CXX-error-Build-result.txt b/Tests/RunCMake/Cpplint/CXX-error-Build-result.txt
new file mode 100644
index 0000000..d197c91
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/CXX-error-Build-result.txt
@@ -0,0 +1 @@
+[^0]
diff --git a/Tests/RunCMake/Cpplint/CXX-error-Build-stdout.txt b/Tests/RunCMake/Cpplint/CXX-error-Build-stdout.txt
new file mode 100644
index 0000000..028cd37
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/CXX-error-Build-stdout.txt
@@ -0,0 +1 @@
+Tests[/\]RunCMake[/\]Cpplint[/\]main\.cxx:0:  message  \[category\/category\] \[0\]
diff --git a/Tests/RunCMake/Cpplint/CXX-error-launch-Build-result.txt b/Tests/RunCMake/Cpplint/CXX-error-launch-Build-result.txt
new file mode 100644
index 0000000..d197c91
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/CXX-error-launch-Build-result.txt
@@ -0,0 +1 @@
+[^0]
diff --git a/Tests/RunCMake/Cpplint/CXX-error-launch-Build-stdout.txt b/Tests/RunCMake/Cpplint/CXX-error-launch-Build-stdout.txt
new file mode 100644
index 0000000..028cd37
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/CXX-error-launch-Build-stdout.txt
@@ -0,0 +1 @@
+Tests[/\]RunCMake[/\]Cpplint[/\]main\.cxx:0:  message  \[category\/category\] \[0\]
diff --git a/Tests/RunCMake/Cpplint/CXX-error-launch.cmake b/Tests/RunCMake/Cpplint/CXX-error-launch.cmake
new file mode 100644
index 0000000..72dcbe9
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/CXX-error-launch.cmake
@@ -0,0 +1,3 @@
+set(CTEST_USE_LAUNCHERS 1)
+include(CTestUseLaunchers)
+include(CXX-error.cmake)
diff --git a/Tests/RunCMake/Cpplint/CXX-error.cmake b/Tests/RunCMake/Cpplint/CXX-error.cmake
new file mode 100644
index 0000000..ad66ff5
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/CXX-error.cmake
@@ -0,0 +1,3 @@
+enable_language(CXX)
+set(CMAKE_CXX_CPPLINT "${PSEUDO_CPPLINT}" --error)
+add_executable(main main.cxx)
diff --git a/Tests/RunCMake/Cpplint/CXX-launch-Build-stdout.txt b/Tests/RunCMake/Cpplint/CXX-launch-Build-stdout.txt
new file mode 100644
index 0000000..6a22b79
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/CXX-launch-Build-stdout.txt
@@ -0,0 +1 @@
+Total errors found: 0
diff --git a/Tests/RunCMake/Cpplint/CXX-launch.cmake b/Tests/RunCMake/Cpplint/CXX-launch.cmake
new file mode 100644
index 0000000..3002c9d
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/CXX-launch.cmake
@@ -0,0 +1,3 @@
+set(CTEST_USE_LAUNCHERS 1)
+include(CTestUseLaunchers)
+include(CXX.cmake)
diff --git a/Tests/RunCMake/Cpplint/CXX.cmake b/Tests/RunCMake/Cpplint/CXX.cmake
new file mode 100644
index 0000000..35f05ee
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/CXX.cmake
@@ -0,0 +1,3 @@
+enable_language(CXX)
+set(CMAKE_CXX_CPPLINT "${PSEUDO_CPPLINT}" --verbose=0 --linelength=80)
+add_executable(main main.cxx)
diff --git a/Tests/RunCMake/Cpplint/RunCMakeTest.cmake b/Tests/RunCMake/Cpplint/RunCMakeTest.cmake
new file mode 100644
index 0000000..5a8471e
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/RunCMakeTest.cmake
@@ -0,0 +1,26 @@
+include(RunCMake)
+
+set(RunCMake_TEST_OPTIONS "-DPSEUDO_CPPLINT=${PSEUDO_CPPLINT}")
+
+function(run_cpplint lang)
+  # Use a single build tree for tests without cleaning.
+  set(RunCMake_TEST_BINARY_DIR "${RunCMake_BINARY_DIR}/${lang}-build")
+  set(RunCMake_TEST_NO_CLEAN 1)
+  file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+  file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+  run_cmake(${lang})
+  set(RunCMake_TEST_OUTPUT_MERGE 1)
+  run_cmake_command(${lang}-Build ${CMAKE_COMMAND} --build .)
+endfunction()
+
+run_cpplint(C)
+run_cpplint(CXX)
+run_cpplint(C-error)
+run_cpplint(CXX-error)
+
+if(NOT RunCMake_GENERATOR STREQUAL "Watcom WMake")
+  run_cpplint(C-launch)
+  run_cpplint(CXX-launch)
+  run_cpplint(C-error-launch)
+  run_cpplint(CXX-error-launch)
+endif()
diff --git a/Tests/RunCMake/Cpplint/main.c b/Tests/RunCMake/Cpplint/main.c
new file mode 100644
index 0000000..8488f4e
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/main.c
@@ -0,0 +1,4 @@
+int main(void)
+{
+  return 0;
+}
diff --git a/Tests/RunCMake/Cpplint/main.cxx b/Tests/RunCMake/Cpplint/main.cxx
new file mode 100644
index 0000000..f8b643a
--- /dev/null
+++ b/Tests/RunCMake/Cpplint/main.cxx
@@ -0,0 +1,4 @@
+int main()
+{
+  return 0;
+}
diff --git a/Tests/RunCMake/CrosscompilingEmulator/AddCustomCommand.cmake b/Tests/RunCMake/CrosscompilingEmulator/AddCustomCommand.cmake
index 67fa30f..c4db11b 100644
--- a/Tests/RunCMake/CrosscompilingEmulator/AddCustomCommand.cmake
+++ b/Tests/RunCMake/CrosscompilingEmulator/AddCustomCommand.cmake
@@ -4,7 +4,15 @@ set(CMAKE_CROSSCOMPILING 1)
 add_executable(generated_exe_emulator_expected simple_src_exiterror.cxx)
 
 # Executable: Return error code equal to 0
-add_executable(generated_exe_emulator_unexpected simple_src_exitsuccess.cxx)
+add_executable(generated_exe_emulator_unexpected generated_exe_emulator_unexpected.cxx)
+# Place the executable in a predictable location.
+set_property(TARGET generated_exe_emulator_unexpected PROPERTY RUNTIME_OUTPUT_DIRECTORY $<1:${CMAKE_CURRENT_BINARY_DIR}>)
+
+# Executable: Imported version of above.  Fake the imported target to use the above.
+add_executable(generated_exe_emulator_unexpected_imported IMPORTED)
+set_property(TARGET generated_exe_emulator_unexpected_imported PROPERTY IMPORTED_LOCATION
+  "${CMAKE_CURRENT_BINARY_DIR}/generated_exe_emulator_unexpected${CMAKE_EXECUTABLE_SUFFIX}")
+add_dependencies(generated_exe_emulator_unexpected_imported generated_exe_emulator_unexpected)
 
 # DoesNotUseEmulator
 add_custom_command(OUTPUT output1
@@ -22,6 +30,12 @@ add_custom_command(OUTPUT output3
   COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/output3
   DEPENDS generated_exe_emulator_unexpected)
 
+# DoesNotUseEmulator: The command will fail if emulator is prepended
+add_custom_command(OUTPUT outputImp
+  COMMAND generated_exe_emulator_unexpected_imported
+  COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/outputImp
+  )
+
 # UsesEmulator: The command only succeeds if the emulator is prepended
 #               to the command.
 add_custom_command(OUTPUT output4
@@ -34,5 +48,6 @@ add_custom_target(ensure_build ALL
     ${CMAKE_CURRENT_BINARY_DIR}/output1
     ${CMAKE_CURRENT_BINARY_DIR}/output2
     ${CMAKE_CURRENT_BINARY_DIR}/output3
+    ${CMAKE_CURRENT_BINARY_DIR}/outputImp
     ${CMAKE_CURRENT_BINARY_DIR}/output4
 )
diff --git a/Tests/RunCMake/CrosscompilingEmulator/AddCustomTarget.cmake b/Tests/RunCMake/CrosscompilingEmulator/AddCustomTarget.cmake
index ced569f..5b01abc 100644
--- a/Tests/RunCMake/CrosscompilingEmulator/AddCustomTarget.cmake
+++ b/Tests/RunCMake/CrosscompilingEmulator/AddCustomTarget.cmake
@@ -4,7 +4,15 @@ set(CMAKE_CROSSCOMPILING 1)
 add_executable(generated_exe_emulator_expected simple_src_exiterror.cxx)
 
 # Executable: Return error code equal to 0
-add_executable(generated_exe_emulator_unexpected simple_src_exitsuccess.cxx)
+add_executable(generated_exe_emulator_unexpected generated_exe_emulator_unexpected.cxx)
+# Place the executable in a predictable location.
+set_property(TARGET generated_exe_emulator_unexpected PROPERTY RUNTIME_OUTPUT_DIRECTORY $<1:${CMAKE_CURRENT_BINARY_DIR}>)
+
+# Executable: Imported version of above.  Fake the imported target to use the above.
+add_executable(generated_exe_emulator_unexpected_imported IMPORTED)
+set_property(TARGET generated_exe_emulator_unexpected_imported PROPERTY IMPORTED_LOCATION
+  "${CMAKE_CURRENT_BINARY_DIR}/generated_exe_emulator_unexpected${CMAKE_EXECUTABLE_SUFFIX}")
+add_dependencies(generated_exe_emulator_unexpected_imported generated_exe_emulator_unexpected)
 
 # DoesNotUseEmulator
 add_custom_target(generate_output1 ALL
@@ -22,6 +30,12 @@ add_custom_target(generate_output3 ALL
   COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/output3
   DEPENDS generated_exe_emulator_unexpected)
 
+# DoesNotUseEmulator: The command will fail if emulator is prepended
+add_custom_target(generate_outputImp ALL
+  COMMAND generated_exe_emulator_unexpected_imported
+  COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/outputImp
+  )
+
 # UsesEmulator: The command only succeeds if the emulator is prepended
 #               to the command.
 add_custom_target(generate_output4 ALL
diff --git a/Tests/RunCMake/CrosscompilingEmulator/generated_exe_emulator_unexpected.cxx b/Tests/RunCMake/CrosscompilingEmulator/generated_exe_emulator_unexpected.cxx
new file mode 100644
index 0000000..233f432
--- /dev/null
+++ b/Tests/RunCMake/CrosscompilingEmulator/generated_exe_emulator_unexpected.cxx
@@ -0,0 +1,9 @@
+#include <stdio.h>
+
+int main(int argc, const char* argv[])
+{
+  for (int i = 1; i < argc; ++i) {
+    fprintf(stderr, "unexpected argument: '%s'\n", argv[i]);
+  }
+  return argc == 1 ? 0 : 1;
+}
diff --git a/Tests/RunCMake/CrosscompilingEmulator/simple_src_exitsuccess.cxx b/Tests/RunCMake/CrosscompilingEmulator/simple_src_exitsuccess.cxx
deleted file mode 100644
index a3dd891..0000000
--- a/Tests/RunCMake/CrosscompilingEmulator/simple_src_exitsuccess.cxx
+++ /dev/null
@@ -1,4 +0,0 @@
-int main(int, char**)
-{
-  return 0;
-}
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomBadDefault-result.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomBadDefault-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomBadDefault-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomBadDefault-stderr.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomBadDefault-stderr.txt
new file mode 100644
index 0000000..58f6125
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomBadDefault-stderr.txt
@@ -0,0 +1,9 @@
+CMake Error at .*/Modules/FeatureSummary\.cmake:[0-9]+. \(message\):
+  Bad package property type OPTIONAL used in global property
+  FeatureSummary_DEFAULT_PKG_TYPE.  Valid types are TYPE1, TYPE2 and TYPE3.
+  Either update FeatureSummary_DEFAULT_PKG_TYPE or add OPTIONAL to the
+  FeatureSummary_PKG_TYPES global property.
+Call Stack \(most recent call first\):
+  .*/Modules/FeatureSummary\.cmake:[0-9]+. \(_FS_GET_FEATURE_SUMMARY\)
+  FeatureSummaryCustomBadDefault.cmake:[0-9]+ \(feature_summary\)
+  CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomBadDefault.cmake b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomBadDefault.cmake
new file mode 100644
index 0000000..7e2fd55
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomBadDefault.cmake
@@ -0,0 +1,8 @@
+include(FeatureSummary)
+set_property(GLOBAL PROPERTY FeatureSummary_PKG_TYPES TYPE1 TYPE2 TYPE3)
+
+list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
+
+find_package(Foo)
+
+feature_summary(WHAT ALL)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequired-result.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequired-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequired-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequired-stderr.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequired-stderr.txt
new file mode 100644
index 0000000..e37b9f5
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequired-stderr.txt
@@ -0,0 +1,6 @@
+CMake Error at .*/Modules/FeatureSummary\.cmake:[0-9]+. \(message\):
+  feature_summary\(\) Error: REQUIRED package\(s\) are missing, aborting CMake
+  run.
+Call Stack \(most recent call first\):
+  FeatureSummaryCustomRequired.cmake:[0-9]+ \(feature_summary\)
+  CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequired-stdout.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequired-stdout.txt
new file mode 100644
index 0000000..ecca71f
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequired-stdout.txt
@@ -0,0 +1,17 @@
+-- The following TYPE3 packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following TYPE2 packages have not been found:
+
+ \* Bar
+
+-- The following TYPE3 packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following TYPE3 packages have not been found:
+
+ \* Bar
+
+-- Configuring incomplete, errors occurred!
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequired.cmake b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequired.cmake
new file mode 100644
index 0000000..11cf04c
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequired.cmake
@@ -0,0 +1,16 @@
+include(FeatureSummary)
+
+list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
+
+set_property(GLOBAL PROPERTY FeatureSummary_PKG_TYPES TYPE1 TYPE2 TYPE3)
+set_property(GLOBAL PROPERTY FeatureSummary_REQUIRED_PKG_TYPES TYPE3)
+set_property(GLOBAL PROPERTY FeatureSummary_DEFAULT_PKG_TYPE TYPE2)
+
+find_package(Foo)
+find_package(Bar)
+
+set_package_properties(Foo PROPERTIES TYPE TYPE3)
+feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES)
+
+set_package_properties(Bar PROPERTIES TYPE TYPE3)
+feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListA-result.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListA-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListA-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListA-stderr.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListA-stderr.txt
new file mode 100644
index 0000000..c9d8b4b
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListA-stderr.txt
@@ -0,0 +1,6 @@
+CMake Error at .*/Modules/FeatureSummary\.cmake:[0-9]+. \(message\):
+  feature_summary\(\) Error: REQUIRED package\(s\) are missing, aborting CMake
+  run.
+Call Stack \(most recent call first\):
+  FeatureSummaryCustomRequiredListA.cmake:[0-9]+ \(feature_summary\)
+  CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListA-stdout.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListA-stdout.txt
new file mode 100644
index 0000000..b12d53a
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListA-stdout.txt
@@ -0,0 +1,17 @@
+-- The following TYPE2 packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following TYPE1 packages have not been found:
+
+ \* Bar
+
+-- The following TYPE2 packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following TYPE2 packages have not been found:
+
+ \* Bar
+
+-- Configuring incomplete, errors occurred!
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListA.cmake b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListA.cmake
new file mode 100644
index 0000000..53111be
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListA.cmake
@@ -0,0 +1,16 @@
+include(FeatureSummary)
+
+list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
+
+set_property(GLOBAL PROPERTY FeatureSummary_PKG_TYPES TYPE1 TYPE2 TYPE3)
+set_property(GLOBAL PROPERTY FeatureSummary_REQUIRED_PKG_TYPES TYPE2 TYPE3)
+set_property(GLOBAL PROPERTY FeatureSummary_DEFAULT_PKG_TYPE TYPE1)
+
+find_package(Foo)
+find_package(Bar)
+
+set_package_properties(Foo PROPERTIES TYPE TYPE2)
+feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES)
+
+set_package_properties(Bar PROPERTIES TYPE TYPE2)
+feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListB-result.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListB-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListB-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListB-stderr.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListB-stderr.txt
new file mode 100644
index 0000000..8ef7a8d
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListB-stderr.txt
@@ -0,0 +1,6 @@
+CMake Error at .*/Modules/FeatureSummary\.cmake:[0-9]+. \(message\):
+  feature_summary\(\) Error: REQUIRED package\(s\) are missing, aborting CMake
+  run.
+Call Stack \(most recent call first\):
+  FeatureSummaryCustomRequiredListB.cmake:[0-9]+ \(feature_summary\)
+  CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListB-stdout.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListB-stdout.txt
new file mode 100644
index 0000000..5f07173
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListB-stdout.txt
@@ -0,0 +1,17 @@
+-- The following TYPE3 packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following TYPE1 packages have not been found:
+
+ \* Bar
+
+-- The following TYPE3 packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following TYPE3 packages have not been found:
+
+ \* Bar
+
+-- Configuring incomplete, errors occurred!
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListB.cmake b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListB.cmake
new file mode 100644
index 0000000..526b979
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomRequiredListB.cmake
@@ -0,0 +1,16 @@
+include(FeatureSummary)
+
+list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
+
+set_property(GLOBAL PROPERTY FeatureSummary_PKG_TYPES TYPE1 TYPE2 TYPE3)
+set_property(GLOBAL PROPERTY FeatureSummary_REQUIRED_PKG_TYPES TYPE2 TYPE3)
+set_property(GLOBAL PROPERTY FeatureSummary_DEFAULT_PKG_TYPE TYPE1)
+
+find_package(Foo)
+find_package(Bar)
+
+set_package_properties(Foo PROPERTIES TYPE TYPE3)
+feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES)
+
+set_package_properties(Bar PROPERTIES TYPE TYPE3)
+feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomTypes-stdout.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomTypes-stdout.txt
new file mode 100644
index 0000000..a7f973b
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomTypes-stdout.txt
@@ -0,0 +1,29 @@
+-- The following TYPE2 packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following TYPE1 packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following TYPE2 packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following TYPE2 packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following TYPE3 packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following TYPE3 packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following TYPE3 packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- Configuring done
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomTypes.cmake b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomTypes.cmake
new file mode 100644
index 0000000..34b0c1f
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryCustomTypes.cmake
@@ -0,0 +1,36 @@
+include(FeatureSummary)
+
+list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
+
+set_property(GLOBAL PROPERTY FeatureSummary_PKG_TYPES TYPE1 TYPE2 TYPE3)
+set_property(GLOBAL PROPERTY FeatureSummary_REQUIRED_PKG_TYPES TYPE3)
+set_property(GLOBAL PROPERTY FeatureSummary_DEFAULT_PKG_TYPE TYPE2)
+
+find_package(Foo)
+
+# Type not set => TYPE2
+feature_summary(WHAT ALL)
+
+# TYPE1 > not set => TYPE1
+set_package_properties(Foo PROPERTIES TYPE TYPE1)
+feature_summary(WHAT ALL)
+
+# TYPE2 > TYPE1 => TYPE2
+set_package_properties(Foo PROPERTIES TYPE TYPE2)
+feature_summary(WHAT ALL)
+
+# TYPE1 < TYPE2 => TYPE2
+set_package_properties(Foo PROPERTIES TYPE TYPE2)
+feature_summary(WHAT ALL)
+
+# TYPE3 > TYPE2 => TYPE3
+set_package_properties(Foo PROPERTIES TYPE TYPE3)
+feature_summary(WHAT ALL)
+
+# TYPE2 < TYPE3 => TYPE3
+set_package_properties(Foo PROPERTIES TYPE TYPE2)
+feature_summary(WHAT ALL)
+
+# TYPE1 < TYPE3 => TYPE3
+set_package_properties(Foo PROPERTIES TYPE TYPE1)
+feature_summary(WHAT ALL)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryFatalOnMissingRequiredPackages-result.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryFatalOnMissingRequiredPackages-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryFatalOnMissingRequiredPackages-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryFatalOnMissingRequiredPackages-stderr.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryFatalOnMissingRequiredPackages-stderr.txt
new file mode 100644
index 0000000..214d74a
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryFatalOnMissingRequiredPackages-stderr.txt
@@ -0,0 +1,6 @@
+CMake Error at .*/Modules/FeatureSummary\.cmake:[0-9]+. \(message\):
+  feature_summary\(\) Error: REQUIRED package\(s\) are missing, aborting CMake
+  run.
+Call Stack \(most recent call first\):
+  FeatureSummaryFatalOnMissingRequiredPackages.cmake:[0-9]+ \(feature_summary\)
+  CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryFatalOnMissingRequiredPackages-stdout.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryFatalOnMissingRequiredPackages-stdout.txt
new file mode 100644
index 0000000..6bd6427
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryFatalOnMissingRequiredPackages-stdout.txt
@@ -0,0 +1,17 @@
+-- The following REQUIRED packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following OPTIONAL packages have not been found:
+
+ \* Bar
+
+-- The following REQUIRED packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following REQUIRED packages have not been found:
+
+ \* Bar
+
+-- Configuring incomplete, errors occurred!
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryFatalOnMissingRequiredPackages.cmake b/Tests/RunCMake/FeatureSummary/FeatureSummaryFatalOnMissingRequiredPackages.cmake
new file mode 100644
index 0000000..9563186
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryFatalOnMissingRequiredPackages.cmake
@@ -0,0 +1,12 @@
+include(FeatureSummary)
+
+list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
+
+find_package(Foo)
+find_package(Bar)
+
+set_package_properties(Foo PROPERTIES TYPE REQUIRED)
+feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES)
+
+set_package_properties(Bar PROPERTIES TYPE REQUIRED)
+feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryIncludeQuietPackages-stdout.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryIncludeQuietPackages-stdout.txt
new file mode 100644
index 0000000..58599e0
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryIncludeQuietPackages-stdout.txt
@@ -0,0 +1,14 @@
+-- The following OPTIONAL packages have not been found:
+
+ \* Baz
+
+-- The following OPTIONAL packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following OPTIONAL packages have not been found:
+
+ \* Bar
+ \* Baz
+
+-- Configuring done
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryIncludeQuietPackages.cmake b/Tests/RunCMake/FeatureSummary/FeatureSummaryIncludeQuietPackages.cmake
new file mode 100644
index 0000000..5cdb443
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryIncludeQuietPackages.cmake
@@ -0,0 +1,11 @@
+include(FeatureSummary)
+
+list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
+
+find_package(Foo QUIET)
+find_package(Bar QUIET)
+find_package(Baz)
+
+feature_summary(WHAT ALL)
+
+feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryMultipleDepends-stdout.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryMultipleDepends-stdout.txt
new file mode 100644
index 0000000..d5875e0
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryMultipleDepends-stdout.txt
@@ -0,0 +1,10 @@
+-- The following features have been enabled:
+
+ \* Bar, Bar\.
+ \* Baz, Baz\.
+ \* Goo, Goo\.
+
+-- The following features have been disabled:
+
+ \* Foo, Foo\.
+ \* Fez, Fez\.
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryMultipleDepends.cmake b/Tests/RunCMake/FeatureSummary/FeatureSummaryMultipleDepends.cmake
new file mode 100644
index 0000000..f355ae7
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryMultipleDepends.cmake
@@ -0,0 +1,12 @@
+include(FeatureSummary)
+
+set(WITH_FOO 1)
+set(WITH_BAR 0)
+
+add_feature_info(Foo "WITH_FOO;WITH_BAR" "Foo.")
+add_feature_info(Bar "WITH_FOO;NOT WITH_BAR" "Bar.")
+add_feature_info(Baz "WITH_FOO AND NOT WITH_BAR" "Baz.")
+add_feature_info(Goo "WITH_FOO OR WITH_BAR" "Goo.")
+add_feature_info(Fez "NOT WITH_FOO OR WITH_BAR" "Fez.")
+
+feature_summary(WHAT ALL)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryPurpose-stdout.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryPurpose-stdout.txt
new file mode 100644
index 0000000..78e4fe1
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryPurpose-stdout.txt
@@ -0,0 +1,16 @@
+The following OPTIONAL packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following OPTIONAL packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+   Because everyone needs some Foo.
+
+-- The following OPTIONAL packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+   Because everyone needs some Foo.
+   Because Foo is better than Bar.
+
+-- Configuring done
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryPurpose.cmake b/Tests/RunCMake/FeatureSummary/FeatureSummaryPurpose.cmake
new file mode 100644
index 0000000..64735b6
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryPurpose.cmake
@@ -0,0 +1,16 @@
+include(FeatureSummary)
+
+list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
+
+find_package(Foo)
+
+# Purpose not set
+feature_summary(WHAT ALL)
+
+# Purpose set once
+set_package_properties(Foo PROPERTIES PURPOSE "Because everyone needs some Foo.")
+feature_summary(WHAT ALL)
+
+# Purpose set twice
+set_package_properties(Foo PROPERTIES PURPOSE "Because Foo is better than Bar.")
+feature_summary(WHAT ALL)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryQuietOnEmpty-stdout.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryQuietOnEmpty-stdout.txt
new file mode 100644
index 0000000..65e97e0
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryQuietOnEmpty-stdout.txt
@@ -0,0 +1,5 @@
+-- Enabled features:
+ \* Foo, Foo\.
+ \* Bar, Bar\.
+
+-- Configuring done
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryQuietOnEmpty.cmake b/Tests/RunCMake/FeatureSummary/FeatureSummaryQuietOnEmpty.cmake
new file mode 100644
index 0000000..8d1d007
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryQuietOnEmpty.cmake
@@ -0,0 +1,14 @@
+include(FeatureSummary)
+
+set(WITH_FOO 1)
+set(WITH_BAR 1)
+
+add_feature_info(Foo WITH_FOO "Foo.")
+add_feature_info(Bar WITH_BAR "Bar.")
+
+feature_summary(WHAT ENABLED_FEATURES
+                DESCRIPTION "Enabled features:"
+                QUIET_ON_EMPTY)
+feature_summary(WHAT DISABLED_FEATURES
+                DESCRIPTION "Disabled features:"
+                QUIET_ON_EMPTY)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryTypes-stdout.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryTypes-stdout.txt
new file mode 100644
index 0000000..79bb1e3
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryTypes-stdout.txt
@@ -0,0 +1,45 @@
+-- The following OPTIONAL packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following RUNTIME packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following OPTIONAL packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following OPTIONAL packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following RECOMMENDED packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following RECOMMENDED packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following RECOMMENDED packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following REQUIRED packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following REQUIRED packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following REQUIRED packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following REQUIRED packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- Configuring done
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryTypes.cmake b/Tests/RunCMake/FeatureSummary/FeatureSummaryTypes.cmake
new file mode 100644
index 0000000..09d1e7a
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryTypes.cmake
@@ -0,0 +1,48 @@
+include(FeatureSummary)
+
+list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
+
+find_package(Foo)
+
+# Type not set => OPTIONAL
+feature_summary(WHAT ALL)
+
+# RUNTIME > not set => RUNTIME
+set_package_properties(Foo PROPERTIES TYPE RUNTIME)
+feature_summary(WHAT ALL)
+
+# OPTIONAL > RUNTIME => OPTIONAL
+set_package_properties(Foo PROPERTIES TYPE OPTIONAL)
+feature_summary(WHAT ALL)
+
+# RUNTIME < OPTIONAL => OPTIONAL
+set_package_properties(Foo PROPERTIES TYPE OPTIONAL)
+feature_summary(WHAT ALL)
+
+# RECOMMENDED > OPTIONAL => RECOMMENDED
+set_package_properties(Foo PROPERTIES TYPE RECOMMENDED)
+feature_summary(WHAT ALL)
+
+# OPTIONAL < RECOMMENDED => RECOMMENDED
+set_package_properties(Foo PROPERTIES TYPE OPTIONAL)
+feature_summary(WHAT ALL)
+
+# RUNTIME < RECOMMENDED => RECOMMENDED
+set_package_properties(Foo PROPERTIES TYPE RUNTIME)
+feature_summary(WHAT ALL)
+
+# REQUIRED > RECOMMENDED => REQUIRED
+set_package_properties(Foo PROPERTIES TYPE REQUIRED)
+feature_summary(WHAT ALL)
+
+# RECOMMENDED < REQUIRED => REQUIRED
+set_package_properties(Foo PROPERTIES TYPE RECOMMENDED)
+feature_summary(WHAT ALL)
+
+# OPTIONAL < REQUIRED => REQUIRED
+set_package_properties(Foo PROPERTIES TYPE OPTIONAL)
+feature_summary(WHAT ALL)
+
+# RUNTIME < REQUIRED => REQUIRED
+set_package_properties(Foo PROPERTIES TYPE RUNTIME)
+feature_summary(WHAT ALL)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryURLDescription-stdout.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryURLDescription-stdout.txt
new file mode 100644
index 0000000..6a55bdf
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryURLDescription-stdout.txt
@@ -0,0 +1,32 @@
+-- The following OPTIONAL packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following OPTIONAL packages have not been found:
+
+ \* Bar
+ \* Baz
+
+-- The following OPTIONAL packages have been found:
+
+ \* Foo, The Foo package, <https://foo.example/>
+
+-- The following OPTIONAL packages have not been found:
+
+ \* Bar, <https://bar.net/>
+ \* Baz, A Baz package
+
+-- Warning: Property DESCRIPTION for package Foo already set to "The Foo package", overriding it with "A Foo package"
+-- Warning: Property URL already set to "https://foo.example/", overriding it with "https://foo.net/"
+-- Warning: Property URL already set to "https://bar.net/", overriding it with "https://bar.example/"
+-- Warning: Property DESCRIPTION for package Baz already set to "A Baz package", overriding it with "The Baz package"
+-- The following OPTIONAL packages have been found:
+
+ \* Foo, A Foo package, <https://foo.net/>
+
+-- The following OPTIONAL packages have not been found:
+
+ \* Bar, The Bar package, <https://bar.example/>
+ \* Baz, The Baz package, <https://baz.example/>
+
+-- Configuring done
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryURLDescription.cmake b/Tests/RunCMake/FeatureSummary/FeatureSummaryURLDescription.cmake
new file mode 100644
index 0000000..77fcf28
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryURLDescription.cmake
@@ -0,0 +1,28 @@
+include(FeatureSummary)
+
+list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
+
+find_package(Foo) # URL and DESCRIPTION are set in the FindFoo.cmake file
+find_package(Bar) # URL and DESCRIPTION are not set
+find_package(Baz) # URL and DESCRIPTION are not set
+
+feature_summary(WHAT ALL)
+
+set_package_properties(Bar PROPERTIES URL "https://bar.net/") # URL and no DESCRIPTION
+set_package_properties(Baz PROPERTIES DESCRIPTION "A Baz package") # DESCRIPTION and no URL
+feature_summary(WHAT ALL)
+
+# Overwrite with the same value (no warning)
+set_package_properties(Foo PROPERTIES URL "https://foo.example/"
+                                      DESCRIPTION "The Foo package")
+set_package_properties(Bar PROPERTIES URL "https://bar.net/")
+set_package_properties(Baz PROPERTIES DESCRIPTION "A Baz package")
+
+# Overwrite with different values (warnings)
+set_package_properties(Foo PROPERTIES URL "https://foo.net/"
+                                      DESCRIPTION "A Foo package") # Overwrite URL and DESCRIPTION
+set_package_properties(Bar PROPERTIES URL "https://bar.example/"
+                                      DESCRIPTION "The Bar package") # Overwrite URL and add DESCRIPTION
+set_package_properties(Baz PROPERTIES URL "https://baz.example/"
+                                      DESCRIPTION "The Baz package") # Overwrite URL and add DESCRIPTION
+feature_summary(WHAT ALL)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatAll-stdout.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatAll-stdout.txt
index 9a3f023..f0631ae 100644
--- a/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatAll-stdout.txt
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatAll-stdout.txt
@@ -1,7 +1,7 @@
 -- The following features have been enabled:
 
- \* Foo , Foo\.
+ \* Foo, Foo\.
 
 -- The following features have been disabled:
 
- \* Bar , Bar\.
+ \* Bar, Bar\.
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatList-stdout.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatList-stdout.txt
index 4d8f25f..f121417 100644
--- a/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatList-stdout.txt
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatList-stdout.txt
@@ -1,7 +1,7 @@
 -- The following features have been disabled:
 
- \* Bar , Bar\.
+ \* Bar, Bar\.
 
 -- The following features have been enabled:
 
- \* Foo , Foo\.
+ \* Foo, Foo\.
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatOnce-stdout.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatOnce-stdout.txt
index 39be105..8b4cd43 100644
--- a/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatOnce-stdout.txt
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatOnce-stdout.txt
@@ -1,4 +1,4 @@
 --( )
- \* Foo , Foo decscription\.
+ \* Foo, Foo description\.
 +
 --
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatOnce.cmake b/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatOnce.cmake
index 545fb92..eaea40e 100644
--- a/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatOnce.cmake
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatOnce.cmake
@@ -2,7 +2,7 @@ include(FeatureSummary)
 
 set(WITH_FOO 1)
 
-add_feature_info(Foo WITH_FOO "Foo decscription.")
-add_feature_info(Foo WITH_FOO "Foo decscription.")
+add_feature_info(Foo WITH_FOO "Foo description.")
+add_feature_info(Foo WITH_FOO "Foo description.")
 
 feature_summary(WHAT ENABLED_FEATURES)
diff --git a/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatSingle-stdout.txt b/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatSingle-stdout.txt
index 240632d..7485df9 100644
--- a/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatSingle-stdout.txt
+++ b/Tests/RunCMake/FeatureSummary/FeatureSummaryWhatSingle-stdout.txt
@@ -1 +1 @@
- \* Foo , Foo\.
+ \* Foo, Foo\.
diff --git a/Tests/RunCMake/FeatureSummary/FindBar.cmake b/Tests/RunCMake/FeatureSummary/FindBar.cmake
new file mode 100644
index 0000000..45f4d54
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FindBar.cmake
@@ -0,0 +1,2 @@
+include(FeatureSummary)
+set(Bar_FOUND 0)
diff --git a/Tests/RunCMake/FeatureSummary/FindBaz.cmake b/Tests/RunCMake/FeatureSummary/FindBaz.cmake
new file mode 100644
index 0000000..73aafcd
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FindBaz.cmake
@@ -0,0 +1,2 @@
+include(FeatureSummary)
+set(Baz_FOUND 0)
diff --git a/Tests/RunCMake/FeatureSummary/FindFoo.cmake b/Tests/RunCMake/FeatureSummary/FindFoo.cmake
new file mode 100644
index 0000000..baec987
--- /dev/null
+++ b/Tests/RunCMake/FeatureSummary/FindFoo.cmake
@@ -0,0 +1,4 @@
+include(FeatureSummary)
+set_package_properties(Foo PROPERTIES URL "https://foo.example/"
+                                      DESCRIPTION "The Foo package")
+set(Foo_FOUND 1)
diff --git a/Tests/RunCMake/FeatureSummary/RunCMakeTest.cmake b/Tests/RunCMake/FeatureSummary/RunCMakeTest.cmake
index 6a5fc28..9caee4c 100644
--- a/Tests/RunCMake/FeatureSummary/RunCMakeTest.cmake
+++ b/Tests/RunCMake/FeatureSummary/RunCMakeTest.cmake
@@ -7,3 +7,15 @@ run_cmake(FeatureSummaryWhatList)
 run_cmake(FeatureSummaryWhatListUnknown)
 run_cmake(FeatureSummaryWhatListAll)
 run_cmake(FeatureSummaryWhatOnce)
+run_cmake(FeatureSummaryPurpose)
+run_cmake(FeatureSummaryURLDescription)
+run_cmake(FeatureSummaryTypes)
+run_cmake(FeatureSummaryFatalOnMissingRequiredPackages)
+run_cmake(FeatureSummaryIncludeQuietPackages)
+run_cmake(FeatureSummaryQuietOnEmpty)
+run_cmake(FeatureSummaryMultipleDepends)
+run_cmake(FeatureSummaryCustomTypes)
+run_cmake(FeatureSummaryCustomBadDefault)
+run_cmake(FeatureSummaryCustomRequired)
+run_cmake(FeatureSummaryCustomRequiredListA)
+run_cmake(FeatureSummaryCustomRequiredListB)
diff --git a/Tests/RunCMake/FindGTK2/CMakeLists.txt b/Tests/RunCMake/FindGTK2/CMakeLists.txt
new file mode 100644
index 0000000..93ee9df
--- /dev/null
+++ b/Tests/RunCMake/FindGTK2/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.5)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/FindGTK2/FindGTK2RunTwice.cmake b/Tests/RunCMake/FindGTK2/FindGTK2RunTwice.cmake
new file mode 100644
index 0000000..e0585ee
--- /dev/null
+++ b/Tests/RunCMake/FindGTK2/FindGTK2RunTwice.cmake
@@ -0,0 +1,21 @@
+cmake_minimum_required(VERSION 3.7)
+project(testFindGTK2 C)
+
+# First call
+find_package(GTK2 REQUIRED)
+
+# Backup variables
+set(GTK2_LIBRARIES_BAK ${GTK2_LIBRARIES})
+set(GTK2_TARGETS_BAK ${GTK2_TARGETS})
+
+# Second call
+find_package(GTK2 REQUIRED)
+
+# Check variables
+if(NOT "${GTK2_LIBRARIES_BAK}" STREQUAL "${GTK2_LIBRARIES}")
+  message(SEND_ERROR "GTK2_LIBRARIES is different:\nbefore: ${GTK2_LIBRARIES_BAK}\nafter:  ${GTK2_LIBRARIES}")
+endif()
+
+if(NOT "${GTK2_TARGETS_BAK}" STREQUAL "${GTK2_TARGETS}")
+  message(SEND_ERROR "GTK2_TARGETS is different:\nbefore: ${GTK2_TARGETS_BAK}\nafter:  ${GTK2_TARGETS}")
+endif()
diff --git a/Tests/RunCMake/FindGTK2/RunCMakeTest.cmake b/Tests/RunCMake/FindGTK2/RunCMakeTest.cmake
new file mode 100644
index 0000000..66364ca
--- /dev/null
+++ b/Tests/RunCMake/FindGTK2/RunCMakeTest.cmake
@@ -0,0 +1,3 @@
+include(RunCMake)
+
+run_cmake(FindGTK2RunTwice)
diff --git a/Tests/RunCMake/Framework/FrameworkLayout.cmake b/Tests/RunCMake/Framework/FrameworkLayout.cmake
index 5184755..ae32134 100644
--- a/Tests/RunCMake/Framework/FrameworkLayout.cmake
+++ b/Tests/RunCMake/Framework/FrameworkLayout.cmake
@@ -1,7 +1,7 @@
 cmake_minimum_required(VERSION 3.4)
 enable_language(C)
 
-add_library(Framework SHARED
+add_library(Framework ${FRAMEWORK_TYPE}
             foo.c
             foo.h
             res.txt)
@@ -9,3 +9,6 @@ set_target_properties(Framework PROPERTIES
                       FRAMEWORK TRUE
                       PUBLIC_HEADER foo.h
                       RESOURCE "res.txt")
+
+add_custom_command(TARGET Framework POST_BUILD
+                   COMMAND /usr/bin/file $<TARGET_FILE:Framework>)
diff --git a/Tests/RunCMake/Framework/FrameworkTypeSHARED-build-stdout.txt b/Tests/RunCMake/Framework/FrameworkTypeSHARED-build-stdout.txt
new file mode 100644
index 0000000..8d90f5f
--- /dev/null
+++ b/Tests/RunCMake/Framework/FrameworkTypeSHARED-build-stdout.txt
@@ -0,0 +1 @@
+.*/Framework: Mach-O[^\n]* dynamically linked shared library.*
diff --git a/Tests/RunCMake/Framework/FrameworkTypeSTATIC-build-stdout.txt b/Tests/RunCMake/Framework/FrameworkTypeSTATIC-build-stdout.txt
new file mode 100644
index 0000000..c9f50b6
--- /dev/null
+++ b/Tests/RunCMake/Framework/FrameworkTypeSTATIC-build-stdout.txt
@@ -0,0 +1 @@
+.*/Framework: current ar archive random library.*
diff --git a/Tests/RunCMake/Framework/RunCMakeTest.cmake b/Tests/RunCMake/Framework/RunCMakeTest.cmake
index eeea6f1..e64892d 100644
--- a/Tests/RunCMake/Framework/RunCMakeTest.cmake
+++ b/Tests/RunCMake/Framework/RunCMakeTest.cmake
@@ -1,33 +1,40 @@
 include(RunCMake)
 
-# iOS
-
-set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/iOSFrameworkLayout-build)
-set(RunCMake_TEST_NO_CLEAN 1)
-set(RunCMake_TEST_OPTIONS "-DCMAKE_TOOLCHAIN_FILE=${RunCMake_SOURCE_DIR}/ios.cmake")
-
-file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
-file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
-
-run_cmake(FrameworkLayout)
-run_cmake_command(iOSFrameworkLayout-build ${CMAKE_COMMAND} --build .)
-
-unset(RunCMake_TEST_BINARY_DIR)
-unset(RunCMake_TEST_NO_CLEAN)
-unset(RunCMake_TEST_OPTIONS)
-
-# OSX
-
-set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/OSXFrameworkLayout-build)
-set(RunCMake_TEST_NO_CLEAN 1)
-set(RunCMake_TEST_OPTIONS "-DCMAKE_TOOLCHAIN_FILE=${RunCMake_SOURCE_DIR}/osx.cmake")
-
-file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
-file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
-
-run_cmake(FrameworkLayout)
-run_cmake_command(OSXFrameworkLayout-build ${CMAKE_COMMAND} --build .)
-
-unset(RunCMake_TEST_BINARY_DIR)
-unset(RunCMake_TEST_NO_CLEAN)
-unset(RunCMake_TEST_OPTIONS)
+function(framework_layout_test Name Toolchain Type)
+  set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/${Toolchain}${Type}FrameworkLayout-build)
+  set(RunCMake_TEST_NO_CLEAN 1)
+  set(RunCMake_TEST_OPTIONS "-DCMAKE_TOOLCHAIN_FILE=${RunCMake_SOURCE_DIR}/${Toolchain}.cmake")
+  list(APPEND RunCMake_TEST_OPTIONS "-DFRAMEWORK_TYPE=${Type}")
+
+  file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+  file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+
+  run_cmake(FrameworkLayout)
+  run_cmake_command(${Name} ${CMAKE_COMMAND} --build .)
+endfunction()
+
+# build check cannot cope with multi-configuration generators directory layout
+if(NOT RunCMake_GENERATOR STREQUAL "Xcode")
+  framework_layout_test(iOSFrameworkLayout-build ios SHARED)
+  framework_layout_test(iOSFrameworkLayout-build ios STATIC)
+  framework_layout_test(OSXFrameworkLayout-build osx SHARED)
+  framework_layout_test(OSXFrameworkLayout-build osx STATIC)
+endif()
+
+function(framework_type_test Toolchain Type)
+  set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/${Toolchain}${Type}FrameworkType-build)
+  set(RunCMake_TEST_NO_CLEAN 1)
+  set(RunCMake_TEST_OPTIONS "-DCMAKE_TOOLCHAIN_FILE=${RunCMake_SOURCE_DIR}/${Toolchain}.cmake")
+  list(APPEND RunCMake_TEST_OPTIONS "-DFRAMEWORK_TYPE=${Type}")
+
+  file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+  file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+
+  run_cmake(FrameworkLayout)
+  run_cmake_command(FrameworkType${Type}-build ${CMAKE_COMMAND} --build .)
+endfunction()
+
+framework_type_test(ios SHARED)
+framework_type_test(ios STATIC)
+framework_type_test(osx SHARED)
+framework_type_test(osx STATIC)
diff --git a/Tests/RunCMake/GenerateExportHeader/reference/.gitattributes b/Tests/RunCMake/GenerateExportHeader/reference/.gitattributes
new file mode 100644
index 0000000..883a7f1
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/reference/.gitattributes
@@ -0,0 +1,2 @@
+# Exclude reference content from formatting.
+* -format.clang-format
diff --git a/Tests/RunCMake/GeneratorExpression/BadIF-result.txt b/Tests/RunCMake/GeneratorExpression/BadIF-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/BadIF-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/BadIF-stderr.txt b/Tests/RunCMake/GeneratorExpression/BadIF-stderr.txt
new file mode 100644
index 0000000..7c7506c
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/BadIF-stderr.txt
@@ -0,0 +1,15 @@
+CMake Error at BadIF.cmake:2 \(add_custom_target\):
+  Error evaluating generator expression:
+
+    \$<IF:asdf,a,b>
+
+  First parameter to \$<IF> must resolve to exactly one '0' or '1' value.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
++
+CMake Error at BadIF.cmake:2 \(add_custom_target\):
+  Error evaluating generator expression:
+
+    \$<IF:asdf,a>
+
+  \$<IF> expression requires 3 comma separated parameters, but got 2 instead.
diff --git a/Tests/RunCMake/GeneratorExpression/BadIF.cmake b/Tests/RunCMake/GeneratorExpression/BadIF.cmake
new file mode 100644
index 0000000..583f68d
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/BadIF.cmake
@@ -0,0 +1,5 @@
+
+add_custom_target(check ALL COMMAND check
+    $<IF:asdf,a,b>
+    $<IF:asdf,a>
+    )
diff --git a/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake b/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake
index f5584d5..084b5c3 100644
--- a/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake
+++ b/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake
@@ -1,5 +1,6 @@
 include(RunCMake)
 
+run_cmake(BadIF)
 run_cmake(BadCONFIG)
 run_cmake(BadOR)
 run_cmake(BadAND)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-LOCATION-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-LOCATION-stderr.txt
index e4dbb71..d4e5b29 100644
--- a/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-LOCATION-stderr.txt
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-LOCATION-stderr.txt
@@ -1,4 +1,4 @@
-CMake Warning \(dev\) in CMakeLists.txt:
+CMake Warning \(dev\) at TARGET_PROPERTY-LOCATION.cmake:2 \(add_library\):
   Policy CMP0026 is not set: Disallow use of the LOCATION target property.
   Run "cmake --help-policy CMP0026" for policy details.  Use the cmake_policy
   command to set the policy and suppress this warning.
@@ -7,4 +7,6 @@ CMake Warning \(dev\) in CMakeLists.txt:
   name directly with add_custom_command, or use the generator expression
   \$<TARGET_FILE>, as appropriate.
 
+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/GeneratorToolset/BadToolsetHostArch-result.txt b/Tests/RunCMake/GeneratorToolset/BadToolsetHostArch-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/BadToolsetHostArch-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorToolset/BadToolsetHostArch-stderr.txt b/Tests/RunCMake/GeneratorToolset/BadToolsetHostArch-stderr.txt
new file mode 100644
index 0000000..5737e95
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/BadToolsetHostArch-stderr.txt
@@ -0,0 +1,10 @@
+CMake Error at CMakeLists.txt:[0-9]+ \(project\):
+  Generator
+
+    .*
+
+  does not recognize the toolset
+
+    Test Toolset,host=x6[45]
+
+  that was specified\.$
diff --git a/Tests/RunCMake/GeneratorToolset/BadToolsetHostArch.cmake b/Tests/RunCMake/GeneratorToolset/BadToolsetHostArch.cmake
new file mode 100644
index 0000000..2fc38e5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/BadToolsetHostArch.cmake
@@ -0,0 +1 @@
+message(FATAL_ERROR "This should not be reached!")
diff --git a/Tests/RunCMake/GeneratorToolset/RunCMakeTest.cmake b/Tests/RunCMake/GeneratorToolset/RunCMakeTest.cmake
index 283a2a0..e8ce47d 100644
--- a/Tests/RunCMake/GeneratorToolset/RunCMakeTest.cmake
+++ b/Tests/RunCMake/GeneratorToolset/RunCMakeTest.cmake
@@ -6,6 +6,21 @@ run_cmake(NoToolset)
 if("${RunCMake_GENERATOR}" MATCHES "Visual Studio 1[01245]|Xcode" AND NOT XCODE_BELOW_3)
   set(RunCMake_GENERATOR_TOOLSET "Test Toolset")
   run_cmake(TestToolset)
+  if("${RunCMake_GENERATOR}" MATCHES "Visual Studio 1[245]")
+    set(RunCMake_GENERATOR_TOOLSET "Test Toolset,host=x64")
+    run_cmake(TestToolsetHostArchBoth)
+    set(RunCMake_GENERATOR_TOOLSET ",host=x64")
+    run_cmake(TestToolsetHostArchOnly)
+    set(RunCMake_GENERATOR_TOOLSET "host=x64")
+    run_cmake(TestToolsetHostArchOnly)
+    set(RunCMake_GENERATOR_TOOLSET "Test Toolset")
+    run_cmake(TestToolsetHostArchNone)
+    set(RunCMake_GENERATOR_TOOLSET "Test Toolset,host=x65")
+    run_cmake(BadToolsetHostArch)
+  else()
+    set(RunCMake_GENERATOR_TOOLSET "Test Toolset,host=x64")
+    run_cmake(BadToolsetHostArch)
+  endif()
 else()
   set(RunCMake_GENERATOR_TOOLSET "Bad Toolset")
   run_cmake(BadToolset)
diff --git a/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchBoth-stdout.txt b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchBoth-stdout.txt
new file mode 100644
index 0000000..f0b6d46
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchBoth-stdout.txt
@@ -0,0 +1,2 @@
+-- CMAKE_VS_PLATFORM_TOOLSET='Test Toolset'
+-- CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE='x64'
diff --git a/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchBoth.cmake b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchBoth.cmake
new file mode 100644
index 0000000..26926f9
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchBoth.cmake
@@ -0,0 +1,2 @@
+message(STATUS "CMAKE_VS_PLATFORM_TOOLSET='${CMAKE_VS_PLATFORM_TOOLSET}'")
+message(STATUS "CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE='${CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE}'")
diff --git a/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchNone-stdout.txt b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchNone-stdout.txt
new file mode 100644
index 0000000..576b40c
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchNone-stdout.txt
@@ -0,0 +1,2 @@
+-- CMAKE_VS_PLATFORM_TOOLSET='Test Toolset'
+-- CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE=''
diff --git a/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchNone.cmake b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchNone.cmake
new file mode 100644
index 0000000..26926f9
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchNone.cmake
@@ -0,0 +1,2 @@
+message(STATUS "CMAKE_VS_PLATFORM_TOOLSET='${CMAKE_VS_PLATFORM_TOOLSET}'")
+message(STATUS "CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE='${CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE}'")
diff --git a/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly-stdout.txt b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly-stdout.txt
new file mode 100644
index 0000000..8271bd4
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly-stdout.txt
@@ -0,0 +1,2 @@
+-- CMAKE_VS_PLATFORM_TOOLSET='v[0-9]+'
+-- CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE='x64'
diff --git a/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly.cmake b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly.cmake
new file mode 100644
index 0000000..26926f9
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly.cmake
@@ -0,0 +1,2 @@
+message(STATUS "CMAKE_VS_PLATFORM_TOOLSET='${CMAKE_VS_PLATFORM_TOOLSET}'")
+message(STATUS "CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE='${CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE}'")
diff --git a/Tests/RunCMake/Ninja/NinjaToolMissing-result.txt b/Tests/RunCMake/Ninja/NinjaToolMissing-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/Ninja/NinjaToolMissing-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Ninja/NinjaToolMissing-stderr.txt b/Tests/RunCMake/Ninja/NinjaToolMissing-stderr.txt
new file mode 100644
index 0000000..1214288
--- /dev/null
+++ b/Tests/RunCMake/Ninja/NinjaToolMissing-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at CMakeLists.txt:[0-9]+ \(project\):
+  Running
+
+   'ninja-tool-missing' '--version'
+
+  failed with:
diff --git a/Utilities/KWStyle/CMakeOverwrite.txt b/Tests/RunCMake/Ninja/NinjaToolMissing.cmake
similarity index 100%
rename from Utilities/KWStyle/CMakeOverwrite.txt
rename to Tests/RunCMake/Ninja/NinjaToolMissing.cmake
diff --git a/Tests/RunCMake/Ninja/RunCMakeTest.cmake b/Tests/RunCMake/Ninja/RunCMakeTest.cmake
index 1d3639d..7b4e51e 100644
--- a/Tests/RunCMake/Ninja/RunCMakeTest.cmake
+++ b/Tests/RunCMake/Ninja/RunCMakeTest.cmake
@@ -15,6 +15,12 @@ else()
   message(FATAL_ERROR "'ninja --version' reported:\n${ninja_out}")
 endif()
 
+function(run_NinjaToolMissing)
+  set(RunCMake_MAKE_PROGRAM ninja-tool-missing)
+  run_cmake(NinjaToolMissing)
+endfunction()
+run_NinjaToolMissing()
+
 function(run_CMP0058 case)
   # Use a single build tree for a few tests without cleaning.
   set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/CMP0058-${case}-build)
diff --git a/Tests/RunCMake/RunCMake.cmake b/Tests/RunCMake/RunCMake.cmake
index 247855a..5f66da0 100644
--- a/Tests/RunCMake/RunCMake.cmake
+++ b/Tests/RunCMake/RunCMake.cmake
@@ -75,6 +75,7 @@ function(run_cmake test)
       OUTPUT_VARIABLE actual_stdout
       ERROR_VARIABLE ${actual_stderr_var}
       RESULT_VARIABLE actual_result
+      ENCODING UTF8
       ${maybe_timeout}
       )
   else()
@@ -90,6 +91,7 @@ function(run_cmake test)
       OUTPUT_VARIABLE actual_stdout
       ERROR_VARIABLE ${actual_stderr_var}
       RESULT_VARIABLE actual_result
+      ENCODING UTF8
       ${maybe_timeout}
       )
   endif()
@@ -99,7 +101,7 @@ function(run_cmake test)
   endif()
   foreach(o out err)
     string(REGEX REPLACE "\r\n" "\n" actual_std${o} "${actual_std${o}}")
-    string(REGEX REPLACE "(^|\n)((==[0-9]+==|BullseyeCoverage|[a-z]+\\([0-9]+\\) malloc:|Error kstat returned|[^\n]*from Time Machine by path|[^\n]*Bullseye Testing Technology)[^\n]*\n)+" "\\1" actual_std${o} "${actual_std${o}}")
+    string(REGEX REPLACE "(^|\n)((==[0-9]+==|BullseyeCoverage|[a-z]+\\([0-9]+\\) malloc:|Error kstat returned|[^\n]*is a member of multiple groups|[^\n]*from Time Machine by path|[^\n]*Bullseye Testing Technology)[^\n]*\n)+" "\\1" actual_std${o} "${actual_std${o}}")
     string(REGEX REPLACE "\n+$" "" actual_std${o} "${actual_std${o}}")
     set(expect_${o} "")
     if(DEFINED expect_std${o})
diff --git a/Tests/RunCMake/RunCTest.cmake b/Tests/RunCMake/RunCTest.cmake
index e94432b..89e16ee 100644
--- a/Tests/RunCMake/RunCTest.cmake
+++ b/Tests/RunCMake/RunCTest.cmake
@@ -12,6 +12,7 @@ function(run_ctest CASE_NAME)
     -S ${RunCMake_BINARY_DIR}/${CASE_NAME}/test.cmake
     -V
     --output-log ${RunCMake_BINARY_DIR}/${CASE_NAME}-build/testOutput.log
+    --no-compress-output
     ${ARGN}
     )
 endfunction()
diff --git a/Tests/RunCMake/RuntimePath/A.c b/Tests/RunCMake/RuntimePath/A.c
new file mode 100644
index 0000000..e9d4195
--- /dev/null
+++ b/Tests/RunCMake/RuntimePath/A.c
@@ -0,0 +1,4 @@
+int libA(void)
+{
+  return 0;
+}
diff --git a/Tests/RunCMake/RuntimePath/CMakeLists.txt b/Tests/RunCMake/RuntimePath/CMakeLists.txt
new file mode 100644
index 0000000..a640c56
--- /dev/null
+++ b/Tests/RunCMake/RuntimePath/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.7)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/RuntimePath/RunCMakeTest.cmake b/Tests/RunCMake/RuntimePath/RunCMakeTest.cmake
new file mode 100644
index 0000000..a9a7f05
--- /dev/null
+++ b/Tests/RunCMake/RuntimePath/RunCMakeTest.cmake
@@ -0,0 +1,18 @@
+include(RunCMake)
+
+
+function(run_SymlinkImplicit)
+  # Use a single build tree for a few tests without cleaning.
+  set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/SymlinkImplicit-build)
+  set(RunCMake_TEST_NO_CLEAN 1)
+  if(RunCMake_GENERATOR MATCHES "Make|Ninja")
+    set(RunCMake_TEST_OPTIONS -DCMAKE_BUILD_TYPE=Debug)
+  endif()
+  file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+  file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+  run_cmake(SymlinkImplicit)
+  run_cmake_command(SymlinkImplicit-build ${CMAKE_COMMAND} --build . --config Debug)
+  run_cmake_command(SymlinkImplicitCheck
+    ${CMAKE_COMMAND} -Ddir=${RunCMake_TEST_BINARY_DIR} -P ${RunCMake_SOURCE_DIR}/SymlinkImplicitCheck.cmake)
+endfunction()
+run_SymlinkImplicit()
diff --git a/Tests/RunCMake/RuntimePath/SymlinkImplicit.cmake b/Tests/RunCMake/RuntimePath/SymlinkImplicit.cmake
new file mode 100644
index 0000000..6578f8f
--- /dev/null
+++ b/Tests/RunCMake/RuntimePath/SymlinkImplicit.cmake
@@ -0,0 +1,17 @@
+enable_language(C)
+
+set(lib_dir ${CMAKE_CURRENT_BINARY_DIR}/lib)
+set(lib_link ${CMAKE_CURRENT_BINARY_DIR}/libLink)
+set(lib_always ${CMAKE_CURRENT_BINARY_DIR}/libAlways)
+file(MAKE_DIRECTORY ${lib_dir})
+execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink lib ${lib_link})
+execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink lib ${lib_always})
+
+add_library(A SHARED A.c)
+list(APPEND CMAKE_C_IMPLICIT_LINK_DIRECTORIES ${lib_dir})
+set_property(TARGET A PROPERTY LIBRARY_OUTPUT_DIRECTORY ${lib_link})
+
+add_executable(exe main.c)
+target_link_libraries(exe A)
+set_property(TARGET exe PROPERTY RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin)
+set_property(TARGET exe PROPERTY BUILD_RPATH ${lib_always})
diff --git a/Tests/RunCMake/RuntimePath/SymlinkImplicitCheck-result.txt b/Tests/RunCMake/RuntimePath/SymlinkImplicitCheck-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/RuntimePath/SymlinkImplicitCheck-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/RuntimePath/SymlinkImplicitCheck-stderr.txt b/Tests/RunCMake/RuntimePath/SymlinkImplicitCheck-stderr.txt
new file mode 100644
index 0000000..b0ede70
--- /dev/null
+++ b/Tests/RunCMake/RuntimePath/SymlinkImplicitCheck-stderr.txt
@@ -0,0 +1,22 @@
+^CMake Error at .*/Tests/RunCMake/RuntimePath/SymlinkImplicitCheck.cmake:[0-9]+ \(file\):
+  file RPATH_CHANGE could not write new RPATH:
+
+    old-should-not-exist
+
+  to the file:
+
+    [^
+]*/Tests/RunCMake/RuntimePath/SymlinkImplicit-build/exe
+
+  The current (RPATH|RUNPATH) is:
+
+    [^
+]*/Tests/RunCMake/RuntimePath/SymlinkImplicit-build/libAlways(:[^
+]*)?
+
+  which does not contain:
+
+    [^
+]*/Tests/RunCMake/RuntimePath/SymlinkImplicit-build/libLink
+
+  as was expected\.$
diff --git a/Tests/RunCMake/RuntimePath/SymlinkImplicitCheck.cmake b/Tests/RunCMake/RuntimePath/SymlinkImplicitCheck.cmake
new file mode 100644
index 0000000..d34742e
--- /dev/null
+++ b/Tests/RunCMake/RuntimePath/SymlinkImplicitCheck.cmake
@@ -0,0 +1,2 @@
+file(COPY ${dir}/bin/exe DESTINATION ${dir})
+file(RPATH_CHANGE FILE "${dir}/exe" OLD_RPATH "${dir}/libLink" NEW_RPATH "old-should-not-exist")
diff --git a/Tests/RunCMake/RuntimePath/main.c b/Tests/RunCMake/RuntimePath/main.c
new file mode 100644
index 0000000..8488f4e
--- /dev/null
+++ b/Tests/RunCMake/RuntimePath/main.c
@@ -0,0 +1,4 @@
+int main(void)
+{
+  return 0;
+}
diff --git a/Tests/RunCMake/VS10Project/RunCMakeTest.cmake b/Tests/RunCMake/VS10Project/RunCMakeTest.cmake
index cc2cc2e..3af877f 100644
--- a/Tests/RunCMake/VS10Project/RunCMakeTest.cmake
+++ b/Tests/RunCMake/VS10Project/RunCMakeTest.cmake
@@ -1,2 +1,6 @@
 include(RunCMake)
 run_cmake(VsConfigurationType)
+run_cmake(VsTargetsFileReferences)
+run_cmake(VsCustomProps)
+run_cmake(VsDebuggerWorkingDir)
+run_cmake(VsCSharpCustomTags)
diff --git a/Tests/RunCMake/VS10Project/VsCSharpCustomTags-check.cmake b/Tests/RunCMake/VS10Project/VsCSharpCustomTags-check.cmake
new file mode 100644
index 0000000..70ea193
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCSharpCustomTags-check.cmake
@@ -0,0 +1,23 @@
+set(csProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.csproj")
+if(NOT EXISTS "${csProjectFile}")
+  set(RunCMake_TEST_FAILED "Project file ${csProjectFile} does not exist.")
+  return()
+endif()
+
+set(tagFound FALSE)
+
+set(tagName "MyCustomTag")
+set(tagValue "MyCustomValue")
+
+file(STRINGS "${csProjectFile}" lines)
+foreach(line IN LISTS lines)
+  if(line MATCHES "^ *<${tagName}>${tagValue}</${tagName}>")
+    message(STATUS "foo.csproj has tag ${tagName} with value ${tagValue} defined")
+    set(tagFound TRUE)
+  endif()
+endforeach()
+
+if(NOT tagFound)
+  set(RunCMake_TEST_FAILED "Source file tag ${tagName} with value ${tagValue} not found.")
+  return()
+endif()
diff --git a/Tests/RunCMake/VS10Project/VsCSharpCustomTags.cmake b/Tests/RunCMake/VS10Project/VsCSharpCustomTags.cmake
new file mode 100644
index 0000000..c51e9c3
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCSharpCustomTags.cmake
@@ -0,0 +1,11 @@
+enable_language(CSharp)
+add_library(foo foo.cs)
+
+set(props_file "${CMAKE_CURRENT_SOURCE_DIR}/my.props")
+
+set(tagName "MyCustomTag")
+set(tagValue "MyCustomValue")
+
+set_source_files_properties(foo.cs
+  PROPERTIES
+  VS_CSHARP_${tagName} "${tagValue}")
diff --git a/Tests/RunCMake/VS10Project/VsCustomProps-check.cmake b/Tests/RunCMake/VS10Project/VsCustomProps-check.cmake
new file mode 100644
index 0000000..22a3df0
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCustomProps-check.cmake
@@ -0,0 +1,25 @@
+set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.vcxproj")
+if(NOT EXISTS "${vcProjectFile}")
+  set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.")
+  return()
+endif()
+
+set(importFound FALSE)
+
+set(props_file "${RunCMake_SOURCE_DIR}/my.props")
+file(TO_NATIVE_PATH "${props_file}" check_file)
+file(STRINGS "${vcProjectFile}" lines)
+foreach(line IN LISTS lines)
+  if(line MATCHES "^ *<Import Project=\"([^\"]+)\".*Label=\"([^\"]+)\".*$")
+    if("${CMAKE_MATCH_1}" STREQUAL "${check_file}" AND
+       "${CMAKE_MATCH_2}" STREQUAL "LocalAppDataPlatform")
+        message(STATUS "foo.vcxproj is importing ${check_file}")
+        set(importFound TRUE)
+    endif()
+  endif()
+endforeach()
+
+if(NOT importFound)
+  set(RunCMake_TEST_FAILED "Import of custom .props file not found.")
+  return()
+endif()
diff --git a/Tests/RunCMake/VS10Project/VsCustomProps.cmake b/Tests/RunCMake/VS10Project/VsCustomProps.cmake
new file mode 100644
index 0000000..fbbcfcf
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCustomProps.cmake
@@ -0,0 +1,7 @@
+enable_language(CXX)
+add_library(foo foo.cpp)
+
+set(props_file "${CMAKE_CURRENT_SOURCE_DIR}/my.props")
+
+set_target_properties(foo PROPERTIES
+    VS_USER_PROPS "${props_file}")
diff --git a/Tests/RunCMake/VS10Project/VsDebuggerWorkingDir-check.cmake b/Tests/RunCMake/VS10Project/VsDebuggerWorkingDir-check.cmake
new file mode 100644
index 0000000..637c68c
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsDebuggerWorkingDir-check.cmake
@@ -0,0 +1,22 @@
+set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.vcxproj")
+if(NOT EXISTS "${vcProjectFile}")
+  set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.")
+  return()
+endif()
+
+set(debuggerWorkDirSet FALSE)
+
+file(STRINGS "${vcProjectFile}" lines)
+foreach(line IN LISTS lines)
+  if(line MATCHES "^ *<LocalDebuggerWorkingDirectory[^>]*>([^<>]+)</LocalDebuggerWorkingDirectory>$")
+    if("${CMAKE_MATCH_1}" STREQUAL "my-debugger-directory")
+        message(STATUS "foo.vcxproj has debugger working dir set")
+        set(debuggerWorkDirSet TRUE)
+    endif()
+  endif()
+endforeach()
+
+if(NOT debuggerWorkDirSet)
+  set(RunCMake_TEST_FAILED "LocalDebuggerWorkingDirectory not found or not set correctly.")
+  return()
+endif()
diff --git a/Tests/RunCMake/VS10Project/VsDebuggerWorkingDir.cmake b/Tests/RunCMake/VS10Project/VsDebuggerWorkingDir.cmake
new file mode 100644
index 0000000..a277c65
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsDebuggerWorkingDir.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(foo foo.cpp)
+
+set_target_properties(foo PROPERTIES
+    VS_DEBUGGER_WORKING_DIRECTORY "my-debugger-directory")
diff --git a/Tests/RunCMake/VS10Project/VsTargetsFileReferences-check.cmake b/Tests/RunCMake/VS10Project/VsTargetsFileReferences-check.cmake
new file mode 100644
index 0000000..3d01c2c
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsTargetsFileReferences-check.cmake
@@ -0,0 +1,45 @@
+set(files foo.vcxproj bar.vcxproj baz.vcxproj)
+
+foreach(file ${files})
+  set(vsProjectFile ${RunCMake_TEST_BINARY_DIR}/${file})
+
+  if(NOT EXISTS "${vsProjectFile}")
+    set(RunCMake_TEST_FAILED "Project file ${vsProjectFile} does not exist.")
+    return()
+  endif()
+
+  set(waldoFound FALSE)
+  set(xyzzyFound FALSE)
+  file(STRINGS "${vsProjectFile}" lines)
+  foreach(line IN LISTS lines)
+    if(line MATCHES "^ *<Import Project=.*/>$")
+      if(line MATCHES "^.*waldo.targets.*$")
+        set(waldoFound TRUE)
+        message(STATUS "${file} is importing waldo.targets")
+      elseif(line MATCHES "^.*xyzzy.targets.*$")
+        set(xyzzyFound TRUE)
+        message(STATUS "${file} is importing xyzzy.targets")
+      endif()
+    endif()
+  endforeach()
+
+  if("${file}" STREQUAL "foo.vcxproj")
+    if(NOT xyzzyFound)
+      set(RunCMake_TEST_FAILED "xyzzy.targets not imported from ${file}")
+      return()
+    endif()
+    if(waldoFound)
+      set(RunCMake_TEST_FAILED "waldo.targets imported from ${file}")
+      return()
+    endif()
+  else()
+    if(NOT xyzzyFound)
+      set(RunCMake_TEST_FAILED "xyzzy.targets not imported from ${file}")
+      return()
+    endif()
+    if(NOT waldoFound)
+      set(RunCMake_TEST_FAILED "waldo.targets not imported from ${file}")
+      return()
+    endif()
+  endif()
+endforeach()
diff --git a/Tests/RunCMake/VS10Project/VsTargetsFileReferences.cmake b/Tests/RunCMake/VS10Project/VsTargetsFileReferences.cmake
new file mode 100644
index 0000000..5ca4f1f
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsTargetsFileReferences.cmake
@@ -0,0 +1,9 @@
+enable_language(CXX)
+add_library(foo foo.cpp)
+target_link_libraries(foo ${CMAKE_BINARY_DIR}/xyzzy.targets)
+
+add_library(bar bar.cpp)
+target_link_libraries(bar foo ${CMAKE_BINARY_DIR}/waldo.targets)
+
+add_executable(baz baz.cpp)
+target_link_libraries(baz bar)
diff --git a/Tests/RunCMake/VS10Project/bar.cpp b/Tests/RunCMake/VS10Project/bar.cpp
new file mode 100644
index 0000000..b72a1a5
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/bar.cpp
@@ -0,0 +1,3 @@
+void bar()
+{
+}
diff --git a/Tests/RunCMake/VS10Project/baz.cpp b/Tests/RunCMake/VS10Project/baz.cpp
new file mode 100644
index 0000000..d5d334a
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/baz.cpp
@@ -0,0 +1,3 @@
+void baz()
+{
+}
diff --git a/Tests/RunCMake/VS10Project/foo.cs b/Tests/RunCMake/VS10Project/foo.cs
new file mode 100644
index 0000000..3695dc9
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/foo.cs
@@ -0,0 +1,3 @@
+void foo()
+{
+}
diff --git a/Tests/RunCMake/VS10Project/my.props b/Tests/RunCMake/VS10Project/my.props
new file mode 100644
index 0000000..7c98cde
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/my.props
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+	<PropertyGroup>
+	</PropertyGroup>
+</Project>
diff --git a/Tests/RunCMake/VSSolution/AddPackageToDefault-check.cmake b/Tests/RunCMake/VSSolution/AddPackageToDefault-check.cmake
new file mode 100644
index 0000000..7265900
--- /dev/null
+++ b/Tests/RunCMake/VSSolution/AddPackageToDefault-check.cmake
@@ -0,0 +1,29 @@
+set(vcSlnFile "${RunCMake_TEST_BINARY_DIR}/AddPackageToDefault.sln")
+if(NOT EXISTS "${vcSlnFile}")
+  set(RunCMake_TEST_FAILED "Project file ${vcSlnFile} does not exist.")
+  return()
+endif()
+
+set(packageGuidFound FALSE)
+set(packageGuid "")
+set(packageInBuild FALSE)
+file(STRINGS "${vcSlnFile}" lines)
+foreach(line IN LISTS lines)
+  if(NOT packageGuidFound)
+    if(line MATCHES "^Project.*\"PACKAGE.vcx?proj\".*\"{([A-F0-9-]+)}\"$")
+      set(packageGuidFound TRUE)
+      set(packageGuid ${CMAKE_MATCH_1})
+    endif()
+  else()
+    if(line MATCHES ".*{${packageGuid}}.*")
+      if(line MATCHES "^[ \t]*{${packageGuid}}\\..*\\.Build.0 = .*$")
+          set(packageInBuild TRUE)
+      endif()
+    endif()
+  endif()
+endforeach()
+
+if(NOT packageInBuild)
+  set(RunCMake_TEST_FAILED "PACKAGE is not in default build")
+  return()
+endif()
diff --git a/Tests/RunCMake/VSSolution/AddPackageToDefault.cmake b/Tests/RunCMake/VSSolution/AddPackageToDefault.cmake
new file mode 100644
index 0000000..5f69ec5
--- /dev/null
+++ b/Tests/RunCMake/VSSolution/AddPackageToDefault.cmake
@@ -0,0 +1,2 @@
+include(CPack)
+set(CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD TRUE)
diff --git a/Tests/RunCMake/VSSolution/RunCMakeTest.cmake b/Tests/RunCMake/VSSolution/RunCMakeTest.cmake
index afd74a1..4ec3e3b 100644
--- a/Tests/RunCMake/VSSolution/RunCMakeTest.cmake
+++ b/Tests/RunCMake/VSSolution/RunCMakeTest.cmake
@@ -10,6 +10,7 @@ run_cmake(Override1)
 run_cmake(Override2)
 run_cmake(StartupProject)
 run_cmake(StartupProjectMissing)
+run_cmake(AddPackageToDefault)
 
 if(RunCMake_GENERATOR MATCHES "Visual Studio ([^7]|[7][0-9])" AND NOT NO_USE_FOLDERS)
   run_cmake(StartupProjectUseFolders)
diff --git a/Tests/RunCMake/XcodeProject/PerConfigPerSourceFlags-result.txt b/Tests/RunCMake/XcodeProject/PerConfigPerSourceFlags-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/PerConfigPerSourceFlags-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/XcodeProject/PerConfigPerSourceFlags-stderr.txt b/Tests/RunCMake/XcodeProject/PerConfigPerSourceFlags-stderr.txt
new file mode 100644
index 0000000..6500649
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/PerConfigPerSourceFlags-stderr.txt
@@ -0,0 +1,8 @@
+^CMake Error in CMakeLists.txt:
+  Xcode does not support per-config per-source COMPILE_FLAGS:
+
+    \$<\$<CONFIG:Debug>:-DMYDEBUG>
+
+  specified for source:
+
+    .*/Tests/RunCMake/XcodeProject/main.c$
diff --git a/Tests/RunCMake/XcodeProject/PerConfigPerSourceFlags.cmake b/Tests/RunCMake/XcodeProject/PerConfigPerSourceFlags.cmake
new file mode 100644
index 0000000..99cec5b
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/PerConfigPerSourceFlags.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+add_executable(main main.c)
+set_property(SOURCE main.c PROPERTY COMPILE_FLAGS "$<$<CONFIG:Debug>:-DMYDEBUG>")
diff --git a/Tests/RunCMake/XcodeProject/RunCMakeTest.cmake b/Tests/RunCMake/XcodeProject/RunCMakeTest.cmake
index d43c80d..f51a107 100644
--- a/Tests/RunCMake/XcodeProject/RunCMakeTest.cmake
+++ b/Tests/RunCMake/XcodeProject/RunCMakeTest.cmake
@@ -13,6 +13,8 @@ if (NOT XCODE_VERSION VERSION_LESS 6)
   run_cmake(XcodePlatformFrameworks)
 endif()
 
+run_cmake(PerConfigPerSourceFlags)
+
 # Use a single build tree for a few tests without cleaning.
 
 if(NOT XCODE_VERSION VERSION_LESS 5)
@@ -164,3 +166,24 @@ if(NOT XCODE_VERSION VERSION_LESS 6)
   unset(RunCMake_TEST_NO_CLEAN)
   unset(RunCMake_TEST_OPTIONS)
 endif()
+
+if(NOT XCODE_VERSION VERSION_LESS 5)
+  set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/XcodeMultiplatform-build)
+  set(RunCMake_TEST_NO_CLEAN 1)
+
+  file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+  file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+
+  run_cmake(XcodeMultiplatform)
+
+  # build ios before macos
+  run_cmake_command(XcodeMultiplatform-iphonesimulator-build ${CMAKE_COMMAND} --build . -- -sdk iphonesimulator)
+  run_cmake_command(XcodeMultiplatform-iphonesimulator-install ${CMAKE_COMMAND} --build . --target install -- -sdk iphonesimulator DESTDIR=${RunCMake_TEST_BINARY_DIR}/_install_iphonesimulator)
+
+  run_cmake_command(XcodeMultiplatform-macosx-build ${CMAKE_COMMAND} --build . -- -sdk macosx)
+  run_cmake_command(XcodeMultiplatform-macosx-install ${CMAKE_COMMAND} --build . --target install -- -sdk macosx DESTDIR=${RunCMake_TEST_BINARY_DIR}/_install_macosx)
+
+  unset(RunCMake_TEST_BINARY_DIR)
+  unset(RunCMake_TEST_NO_CLEAN)
+  unset(RunCMake_TEST_OPTIONS)
+endif()
diff --git a/Tests/RunCMake/XcodeProject/XcodeBundles.cmake b/Tests/RunCMake/XcodeProject/XcodeBundles.cmake
index ad4268d..833eb85 100644
--- a/Tests/RunCMake/XcodeProject/XcodeBundles.cmake
+++ b/Tests/RunCMake/XcodeProject/XcodeBundles.cmake
@@ -50,30 +50,56 @@ if (NOT TEST_IOS AND NOT TEST_WATCHOS AND NOT TEST_TVOS)
   add_dependencies(AppBundleExtTest AppBundleExt)
 endif()
 
-# Framework (not supported for iOS on Xcode < 6)
+# Shared Framework (not supported for iOS on Xcode < 6)
 
 if(NOT TEST_IOS OR NOT XCODE_VERSION VERSION_LESS 6)
-  add_library(Framework SHARED main.c)
-  set_target_properties(Framework PROPERTIES FRAMEWORK TRUE)
+  add_library(SharedFramework SHARED main.c)
+  set_target_properties(SharedFramework PROPERTIES FRAMEWORK TRUE)
 
-  add_custom_target(FrameworkTest ALL
+  add_custom_target(SharedFrameworkTest ALL
     COMMAND ${CMAKE_COMMAND} -E copy
-      "$<TARGET_FILE:Framework>" "$<TARGET_FILE:Framework>.old")
+      "$<TARGET_FILE:SharedFramework>" "$<TARGET_FILE:SharedFramework>.old")
 
-  add_dependencies(FrameworkTest Framework)
+  add_dependencies(SharedFrameworkTest SharedFramework)
 
   # with custom extension
 
-  add_library(FrameworkExt SHARED main.c)
-  set_target_properties(FrameworkExt PROPERTIES FRAMEWORK TRUE)
-  set_target_properties(FrameworkExt PROPERTIES BUNDLE_EXTENSION "foo")
-  install(TARGETS FrameworkExt FRAMEWORK DESTINATION FooExtension)
+  add_library(SharedFrameworkExt SHARED main.c)
+  set_target_properties(SharedFrameworkExt PROPERTIES FRAMEWORK TRUE)
+  set_target_properties(SharedFrameworkExt PROPERTIES BUNDLE_EXTENSION "foo")
+  install(TARGETS SharedFrameworkExt FRAMEWORK DESTINATION FooExtension)
 
-  add_custom_target(FrameworkExtTest ALL
+  add_custom_target(SharedFrameworkExtTest ALL
     COMMAND ${CMAKE_COMMAND} -E copy
-      "$<TARGET_FILE:FrameworkExt>" "$<TARGET_FILE:FrameworkExt>.old")
+      "$<TARGET_FILE:SharedFrameworkExt>" "$<TARGET_FILE:SharedFrameworkExt>.old")
 
-  add_dependencies(FrameworkExtTest FrameworkExt)
+  add_dependencies(SharedFrameworkExtTest SharedFrameworkExt)
+endif()
+
+# Static Framework (not supported for Xcode < 6)
+
+if(NOT XCODE_VERSION VERSION_LESS 6)
+  add_library(StaticFramework STATIC main.c)
+  set_target_properties(StaticFramework PROPERTIES FRAMEWORK TRUE)
+
+  add_custom_target(StaticFrameworkTest ALL
+    COMMAND ${CMAKE_COMMAND} -E copy
+      "$<TARGET_FILE:StaticFramework>" "$<TARGET_FILE:StaticFramework>.old")
+
+  add_dependencies(StaticFrameworkTest StaticFramework)
+
+  # with custom extension
+
+  add_library(StaticFrameworkExt STATIC main.c)
+  set_target_properties(StaticFrameworkExt PROPERTIES FRAMEWORK TRUE)
+  set_target_properties(StaticFrameworkExt PROPERTIES BUNDLE_EXTENSION "foo")
+  install(TARGETS StaticFrameworkExt FRAMEWORK DESTINATION StaticFooExtension)
+
+  add_custom_target(StaticFrameworkExtTest ALL
+    COMMAND ${CMAKE_COMMAND} -E copy
+      "$<TARGET_FILE:StaticFrameworkExt>" "$<TARGET_FILE:StaticFrameworkExt>.old")
+
+  add_dependencies(StaticFrameworkExtTest StaticFrameworkExt)
 endif()
 
 # Bundle
diff --git a/Tests/RunCMake/XcodeProject/XcodeMultiplatform.cmake b/Tests/RunCMake/XcodeProject/XcodeMultiplatform.cmake
new file mode 100644
index 0000000..a1064f4
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/XcodeMultiplatform.cmake
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.3)
+enable_language(CXX)
+
+set_property(GLOBAL PROPERTY XCODE_EMIT_EFFECTIVE_PLATFORM_NAME ON)
+
+set(CMAKE_XCODE_ATTRIBUTE_SUPPORTED_PLATFORMS "macosx iphonesimulator")
+set(CMAKE_MACOSX_BUNDLE true)
+
+add_library(library STATIC foo.cpp)
+
+add_executable(main main.cpp)
+target_link_libraries(main library)
+
+install(TARGETS library ARCHIVE DESTINATION lib)
diff --git a/Tests/RunCMake/add_dependencies/ReadOnlyProperty-result.txt b/Tests/RunCMake/add_dependencies/ReadOnlyProperty-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/add_dependencies/ReadOnlyProperty-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/add_dependencies/ReadOnlyProperty-stderr.txt b/Tests/RunCMake/add_dependencies/ReadOnlyProperty-stderr.txt
new file mode 100644
index 0000000..da30b81
--- /dev/null
+++ b/Tests/RunCMake/add_dependencies/ReadOnlyProperty-stderr.txt
@@ -0,0 +1 @@
+MANUALLY_ADDED_DEPENDENCIES property is read-only
diff --git a/Tests/RunCMake/add_dependencies/ReadOnlyProperty.cmake b/Tests/RunCMake/add_dependencies/ReadOnlyProperty.cmake
new file mode 100644
index 0000000..f0e4069
--- /dev/null
+++ b/Tests/RunCMake/add_dependencies/ReadOnlyProperty.cmake
@@ -0,0 +1,6 @@
+cmake_minimum_required(VERSION 3.7)
+project(ReadOnlyProperty C)
+
+add_library(a a.c)
+
+set_property(TARGET a PROPERTY MANUALLY_ADDED_DEPENDENCIES DEPENDENCIES foo)
diff --git a/Tests/RunCMake/add_dependencies/RetrieveDependencies.cmake b/Tests/RunCMake/add_dependencies/RetrieveDependencies.cmake
new file mode 100644
index 0000000..45b3974
--- /dev/null
+++ b/Tests/RunCMake/add_dependencies/RetrieveDependencies.cmake
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.7)
+project(RetrieveDependencies C)
+
+add_library(a a.c)
+
+add_library(b c.c)
+target_link_libraries(a b)
+
+add_library(c c.c)
+add_dependencies(a c)
+
+get_property(DEPS_A TARGET a PROPERTY MANUALLY_ADDED_DEPENDENCIES)
+
+if(NOT DEPS_A STREQUAL "c")
+  message(FATAL_ERROR "Expected target c being a dependency of a but got: '${DEPS_A}'")
+endif()
diff --git a/Tests/RunCMake/add_dependencies/RunCMakeTest.cmake b/Tests/RunCMake/add_dependencies/RunCMakeTest.cmake
index 30b7e67..507d43f 100644
--- a/Tests/RunCMake/add_dependencies/RunCMakeTest.cmake
+++ b/Tests/RunCMake/add_dependencies/RunCMakeTest.cmake
@@ -1,3 +1,5 @@
 include(RunCMake)
 
 run_cmake(NoTarget)
+run_cmake(ReadOnlyProperty)
+run_cmake(RetrieveDependencies)
diff --git a/Tests/RunCMake/add_dependencies/a.c b/Tests/RunCMake/add_dependencies/a.c
new file mode 100644
index 0000000..707c1c3
--- /dev/null
+++ b/Tests/RunCMake/add_dependencies/a.c
@@ -0,0 +1,3 @@
+void a()
+{
+}
diff --git a/Tests/RunCMake/add_dependencies/b.c b/Tests/RunCMake/add_dependencies/b.c
new file mode 100644
index 0000000..57b2900
--- /dev/null
+++ b/Tests/RunCMake/add_dependencies/b.c
@@ -0,0 +1,3 @@
+void b()
+{
+}
diff --git a/Tests/RunCMake/add_dependencies/c.c b/Tests/RunCMake/add_dependencies/c.c
new file mode 100644
index 0000000..cbf94ca
--- /dev/null
+++ b/Tests/RunCMake/add_dependencies/c.c
@@ -0,0 +1,3 @@
+void c()
+{
+}
diff --git a/Tests/RunCMake/ctest_build/CMakeLists.txt.in b/Tests/RunCMake/ctest_build/CMakeLists.txt.in
index 82cb7c4..133ae36 100644
--- a/Tests/RunCMake/ctest_build/CMakeLists.txt.in
+++ b/Tests/RunCMake/ctest_build/CMakeLists.txt.in
@@ -1,4 +1,5 @@
 cmake_minimum_required(VERSION 3.1)
+ at CASE_CMAKELISTS_PREFIX_CODE@
 project(CTestBuild at CASE_NAME@ NONE)
 include(CTest)
 add_test(NAME RunCMakeVersion COMMAND "${CMAKE_COMMAND}" --version)
diff --git a/Tests/RunCMake/ctest_build/RunCMakeTest.cmake b/Tests/RunCMake/ctest_build/RunCMakeTest.cmake
index 324f25c..1092d2a 100644
--- a/Tests/RunCMake/ctest_build/RunCMakeTest.cmake
+++ b/Tests/RunCMake/ctest_build/RunCMakeTest.cmake
@@ -13,6 +13,11 @@ function(run_BuildFailure)
   set(CASE_CMAKELISTS_SUFFIX_CODE [[
 add_custom_target(BuildFailure ALL COMMAND command-does-not-exist)
 ]])
+  set(CASE_CMAKELISTS_PREFIX_CODE [[
+if(NOT CTEST_USE_LAUNCHERS)
+  message(FATAL_ERROR "CTEST_USE_LAUNCHERS not set")
+endif()
+]])
   set(CASE_TEST_PREFIX_CODE [[
 cmake_policy(SET CMP0061 NEW)
 ]])
diff --git a/Tests/RunCMake/ctest_build/test.cmake.in b/Tests/RunCMake/ctest_build/test.cmake.in
index 768f1c6..6f15ec9 100644
--- a/Tests/RunCMake/ctest_build/test.cmake.in
+++ b/Tests/RunCMake/ctest_build/test.cmake.in
@@ -9,6 +9,7 @@ set(CTEST_CMAKE_GENERATOR               "@RunCMake_GENERATOR@")
 set(CTEST_CMAKE_GENERATOR_PLATFORM      "@RunCMake_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@RunCMake_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
+set(CTEST_USE_LAUNCHERS                 TRUE)
 
 set(ctest_build_args "@CASE_CTEST_BUILD_ARGS@")
 ctest_start(Experimental)
diff --git a/Tests/RunCMake/ctest_fixtures/CMakeLists.txt.in b/Tests/RunCMake/ctest_fixtures/CMakeLists.txt.in
index ba1c77a..ab50fdd 100644
--- a/Tests/RunCMake/ctest_fixtures/CMakeLists.txt.in
+++ b/Tests/RunCMake/ctest_fixtures/CMakeLists.txt.in
@@ -30,6 +30,8 @@ failTest(setupFails)    # 9
 passTest(wontRun)       # 10
 passTest(cyclicSetup)   # 11
 passTest(cyclicCleanup) # 12
+passTest(cleanupUnused) # 13
+passTest(setupUnused)   # 14
 
 # Define fixture dependencies and ordering
 set_tests_properties(setupFoo   PROPERTIES FIXTURES_SETUP    "Foo")
@@ -50,6 +52,9 @@ set_tests_properties(two        PROPERTIES FIXTURES_REQUIRED "Bar")
 set_tests_properties(three      PROPERTIES FIXTURES_REQUIRED "Meta;Bar")
 set_tests_properties(wontRun    PROPERTIES FIXTURES_REQUIRED "Fails")
 
+set_tests_properties(cleanupUnused PROPERTIES FIXTURES_CLEANUP "Unused")
+set_tests_properties(setupUnused   PROPERTIES FIXTURES_SETUP   "Unused")
+
 @CASE_CMAKELISTS_CYCLIC_CODE@
 
 # These are the cases verified by the main cmake build
@@ -62,6 +67,7 @@ set_tests_properties(wontRun    PROPERTIES FIXTURES_REQUIRED "Fails")
 #    wontRun        9, 10
 #    cyclicSetup    -NA- (configure fails)
 #    cyclicCleanup  -NA- (configure fails)
+#    unused         14, 13
 #
 # In the case of asking for just setupFoo, since there are
 # no tests using the Foo fixture, we do NOT expect cleanupFoo
diff --git a/Tests/RunCMake/ctest_fixtures/RunCMakeTest.cmake b/Tests/RunCMake/ctest_fixtures/RunCMakeTest.cmake
index f13289a..673cf57 100644
--- a/Tests/RunCMake/ctest_fixtures/RunCMakeTest.cmake
+++ b/Tests/RunCMake/ctest_fixtures/RunCMakeTest.cmake
@@ -17,6 +17,7 @@ run_ctest_test(two      INCLUDE two)
 run_ctest_test(three    INCLUDE three)
 run_ctest_test(setupFoo INCLUDE setupFoo)
 run_ctest_test(wontRun  INCLUDE wontRun)
+run_ctest_test(unused   INCLUDE Unused)
 
 #------------------------------------------------------------
 # CMake configure will fail due to cyclic test dependencies
diff --git a/Tests/RunCMake/ctest_fixtures/unused-stdout.txt b/Tests/RunCMake/ctest_fixtures/unused-stdout.txt
new file mode 100644
index 0000000..b04a621
--- /dev/null
+++ b/Tests/RunCMake/ctest_fixtures/unused-stdout.txt
@@ -0,0 +1,9 @@
+Test project .*/Tests/RunCMake/ctest_fixtures/unused-build
+    Start 14: setupUnused
+1/2 Test #14: setupUnused +\.+ +Passed +[0-9.]+ sec
+    Start 13: cleanupUnused
+2/2 Test #13: cleanupUnused +\.+ +Passed +[0-9.]+ sec
++
+100% tests passed, 0 tests failed out of 2
++
+Total Test time \(real\) = +[0-9.]+ sec$
diff --git a/Tests/RunCMake/ctest_submit/CDashUploadRETRY_COUNT-result.txt b/Tests/RunCMake/ctest_memcheck/DummyAddressLeakSanitizer-result.txt
similarity index 100%
copy from Tests/RunCMake/ctest_submit/CDashUploadRETRY_COUNT-result.txt
copy to Tests/RunCMake/ctest_memcheck/DummyAddressLeakSanitizer-result.txt
diff --git a/Tests/RunCMake/ctest_memcheck/DummyAddressLeakSanitizer-stderr.txt b/Tests/RunCMake/ctest_memcheck/DummyAddressLeakSanitizer-stderr.txt
new file mode 100644
index 0000000..327bd5c
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/DummyAddressLeakSanitizer-stderr.txt
@@ -0,0 +1 @@
+Cannot find memory tester output file: .*/Tests/RunCMake/ctest_memcheck/DummyAddressLeakSanitizer-build/Testing/Temporary/MemoryChecker.1.log\.\*
diff --git a/Tests/RunCMake/ctest_memcheck/DummyAddressLeakSanitizer-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyAddressLeakSanitizer-stdout.txt
new file mode 100644
index 0000000..97a8a9b
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/DummyAddressLeakSanitizer-stdout.txt
@@ -0,0 +1,3 @@
+Memory checking results:
+Direct leak - 2
+Indirect leak - 1
diff --git a/Tests/RunCMake/ctest_submit/CDashUploadRETRY_DELAY-result.txt b/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-result.txt
similarity index 100%
rename from Tests/RunCMake/ctest_submit/CDashUploadRETRY_DELAY-result.txt
rename to Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-result.txt
diff --git a/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-stderr.txt b/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-stderr.txt
new file mode 100644
index 0000000..d4b71ae
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-stderr.txt
@@ -0,0 +1 @@
+Defect count: 3
diff --git a/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-stdout.txt
new file mode 100644
index 0000000..97a8a9b
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/DummyLeakSanitizerPrintDefects-stdout.txt
@@ -0,0 +1,3 @@
+Memory checking results:
+Direct leak - 2
+Indirect leak - 1
diff --git a/Tests/RunCMake/ctest_memcheck/DummyPurify-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyPurify-stdout.txt
index dabb004..69ab584 100644
--- a/Tests/RunCMake/ctest_memcheck/DummyPurify-stdout.txt
+++ b/Tests/RunCMake/ctest_memcheck/DummyPurify-stdout.txt
@@ -2,5 +2,7 @@
 
 100% tests passed, 0 tests failed out of 1
 .*
--- Processing memory checking output:( )
+-- Processing memory checking output:
+MemCheck log files can be found here:.*corresponds to test number.
+.*MemoryChecker.*log
 Memory checking results:
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrind-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrind-stdout.txt
index dabb004..69ab584 100644
--- a/Tests/RunCMake/ctest_memcheck/DummyValgrind-stdout.txt
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrind-stdout.txt
@@ -2,5 +2,7 @@
 
 100% tests passed, 0 tests failed out of 1
 .*
--- Processing memory checking output:( )
+-- Processing memory checking output:
+MemCheck log files can be found here:.*corresponds to test number.
+.*MemoryChecker.*log
 Memory checking results:
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrindCustomOptions-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrindCustomOptions-stdout.txt
index dabb004..69ab584 100644
--- a/Tests/RunCMake/ctest_memcheck/DummyValgrindCustomOptions-stdout.txt
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrindCustomOptions-stdout.txt
@@ -2,5 +2,7 @@
 
 100% tests passed, 0 tests failed out of 1
 .*
--- Processing memory checking output:( )
+-- Processing memory checking output:
+MemCheck log files can be found here:.*corresponds to test number.
+.*MemoryChecker.*log
 Memory checking results:
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrindFailPost-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrindFailPost-stdout.txt
index dabb004..69ab584 100644
--- a/Tests/RunCMake/ctest_memcheck/DummyValgrindFailPost-stdout.txt
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrindFailPost-stdout.txt
@@ -2,5 +2,7 @@
 
 100% tests passed, 0 tests failed out of 1
 .*
--- Processing memory checking output:( )
+-- Processing memory checking output:
+MemCheck log files can be found here:.*corresponds to test number.
+.*MemoryChecker.*log
 Memory checking results:
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrindIgnoreMemcheck-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrindIgnoreMemcheck-stdout.txt
index 5a5675c..88b4788 100644
--- a/Tests/RunCMake/ctest_memcheck/DummyValgrindIgnoreMemcheck-stdout.txt
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrindIgnoreMemcheck-stdout.txt
@@ -3,5 +3,7 @@
 
 100% tests passed, 0 tests failed out of 1
 .*
--- Processing memory checking output:( )
+-- Processing memory checking output:
+MemCheck log files can be found here:.*corresponds to test number.
+.*MemoryChecker.*log
 Memory checking results:
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-result.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-result.txt
new file mode 100644
index 0000000..573541a
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-stderr.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-stderr.txt
new file mode 100644
index 0000000..ad28645
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-stderr.txt
@@ -0,0 +1 @@
+Defect count: 0
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-stdout.txt
new file mode 100644
index 0000000..69ab584
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrindNoDefects-stdout.txt
@@ -0,0 +1,8 @@
+1/1 MemCheck #1: RunCMake \.+   Passed +[0-9]+.[0-9]+ sec
+
+100% tests passed, 0 tests failed out of 1
+.*
+-- Processing memory checking output:
+MemCheck log files can be found here:.*corresponds to test number.
+.*MemoryChecker.*log
+Memory checking results:
diff --git a/Tests/RunCMake/ctest_memcheck/DummyValgrindPrePost-stdout.txt b/Tests/RunCMake/ctest_memcheck/DummyValgrindPrePost-stdout.txt
index dabb004..69ab584 100644
--- a/Tests/RunCMake/ctest_memcheck/DummyValgrindPrePost-stdout.txt
+++ b/Tests/RunCMake/ctest_memcheck/DummyValgrindPrePost-stdout.txt
@@ -2,5 +2,7 @@
 
 100% tests passed, 0 tests failed out of 1
 .*
--- Processing memory checking output:( )
+-- Processing memory checking output:
+MemCheck log files can be found here:.*corresponds to test number.
+.*MemoryChecker.*log
 Memory checking results:
diff --git a/Tests/RunCMake/ctest_memcheck/RunCMakeTest.cmake b/Tests/RunCMake/ctest_memcheck/RunCMakeTest.cmake
index 5ad6511..ab4c5ab 100644
--- a/Tests/RunCMake/ctest_memcheck/RunCMakeTest.cmake
+++ b/Tests/RunCMake/ctest_memcheck/RunCMakeTest.cmake
@@ -12,12 +12,14 @@ endfunction()
 
 unset(CTEST_EXTRA_CONFIG)
 unset(CTEST_EXTRA_CODE)
+unset(CTEST_SUFFIX_CODE)
+unset(CTEST_MEMCHECK_ARGS)
 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(CTEST_MEMORYCHECK_SANITIZER_OPTIONS \"report_bugs=1:history_size=5:exitcode=55\")
 ")
 set(CMAKELISTS_EXTRA_CODE
 "add_test(NAME TestSan COMMAND \"\${CMAKE_COMMAND}\"
@@ -28,22 +30,22 @@ unset(CMAKELISTS_EXTRA_CODE)
 unset(CTEST_EXTRA_CODE)
 
 #-----------------------------------------------------------------------------
-# add LeakSanitizer test
+# add standalone LeakSanitizer test
 set(CTEST_EXTRA_CODE
-"set(CTEST_MEMORYCHECK_SANITIZER_OPTIONS \"simulate_sanitizer=1 report_bugs=1 history_size=5 exitcode=55\")
+"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 \"${RunCMake_SOURCE_DIR}/testLeakSanitizer.cmake\")
 ")
-run_mc_test(DummyLeakSanitizer "" -DMEMCHECK_TYPE=AddressSanitizer)
+run_mc_test(DummyLeakSanitizer "" -DMEMCHECK_TYPE=LeakSanitizer)
 unset(CMAKELISTS_EXTRA_CODE)
 unset(CTEST_EXTRA_CODE)
 
 #-----------------------------------------------------------------------------
 # add AddressSanitizer test
 set(CTEST_EXTRA_CODE
-"set(CTEST_MEMORYCHECK_SANITIZER_OPTIONS \"simulate_sanitizer=1 report_bugs=1 history_size=5 exitcode=55\")
+"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}\"
@@ -54,9 +56,22 @@ unset(CMAKELISTS_EXTRA_CODE)
 unset(CTEST_EXTRA_CODE)
 
 #-----------------------------------------------------------------------------
+# add AddressSanitizer/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 \"${RunCMake_SOURCE_DIR}/testAddressLeakSanitizer.cmake\")
+")
+run_mc_test(DummyAddressLeakSanitizer "" -DMEMCHECK_TYPE=AddressSanitizer)
+unset(CMAKELISTS_EXTRA_CODE)
+unset(CTEST_EXTRA_CODE)
+
+#-----------------------------------------------------------------------------
 # add MemorySanitizer test
 set(CTEST_EXTRA_CODE
-"set(CTEST_MEMORYCHECK_COMMAND_OPTIONS \"simulate_sanitizer=1 report_bugs=1 history_size=5 exitcode=55\")
+"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}\"
@@ -132,4 +147,31 @@ run_mc_test(DummyValgrindNoLogFile "${PSEUDO_VALGRIND_NOLOG}")
 run_mc_test(DummyBCNoLogFile "${PSEUDO_BC_NOLOG}")
 run_mc_test(NotExist "\${CTEST_BINARY_DIRECTORY}/no-memcheck-exe")
 run_mc_test(Unknown "\${CMAKE_COMMAND}")
-run_mc_test(DummyQuiet "${PSEUDO_VALGRIND}" -DMEMCHECK_ARGS=QUIET)
+
+#----------------------------------------------------------------------------
+set(CTEST_MEMCHECK_ARGS QUIET)
+run_mc_test(DummyQuiet "${PSEUDO_VALGRIND}")
+unset(CTEST_MEMCHECK_ARGS)
+
+#-----------------------------------------------------------------------------
+set(CTEST_SUFFIX_CODE "message(\"Defect count: \${defect_count}\")")
+set(CTEST_MEMCHECK_ARGS "DEFECT_COUNT defect_count")
+run_mc_test(DummyValgrindNoDefects "${PSEUDO_VALGRIND}")
+unset(CTEST_MEMCHECK_ARGS)
+unset(CTEST_SUFFIX_CODE)
+
+#-----------------------------------------------------------------------------
+set(CTEST_SUFFIX_CODE "message(\"Defect count: \${defect_count}\")")
+set(CTEST_MEMCHECK_ARGS "DEFECT_COUNT defect_count")
+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 \"${RunCMake_SOURCE_DIR}/testLeakSanitizer.cmake\")
+")
+run_mc_test(DummyLeakSanitizerPrintDefects "" -DMEMCHECK_TYPE=LeakSanitizer)
+unset(CMAKELISTS_EXTRA_CODE)
+unset(CTEST_EXTRA_CODE)
+unset(CTEST_MEMCHECK_ARGS)
+unset(CTEST_SUFFIX_CODE)
diff --git a/Tests/RunCMake/ctest_memcheck/test.cmake.in b/Tests/RunCMake/ctest_memcheck/test.cmake.in
index 8431fa6..50b4b6a 100644
--- a/Tests/RunCMake/ctest_memcheck/test.cmake.in
+++ b/Tests/RunCMake/ctest_memcheck/test.cmake.in
@@ -21,4 +21,6 @@ set(CTEST_MEMORYCHECK_TYPE "${MEMCHECK_TYPE}")
 CTEST_START(Experimental)
 CTEST_CONFIGURE(BUILD "${CTEST_BINARY_DIRECTORY}" RETURN_VALUE res)
 CTEST_TEST(BUILD "${CTEST_BINARY_DIRECTORY}" RETURN_VALUE res)
-CTEST_MEMCHECK(BUILD "${CTEST_BINARY_DIRECTORY}" RETURN_VALUE res ${MEMCHECK_ARGS})
+CTEST_MEMCHECK(BUILD "${CTEST_BINARY_DIRECTORY}" RETURN_VALUE res @CTEST_MEMCHECK_ARGS@)
+
+ at CTEST_SUFFIX_CODE@
diff --git a/Tests/RunCMake/ctest_memcheck/testAddressLeakSanitizer.cmake b/Tests/RunCMake/ctest_memcheck/testAddressLeakSanitizer.cmake
new file mode 100644
index 0000000..ca36a7c
--- /dev/null
+++ b/Tests/RunCMake/ctest_memcheck/testAddressLeakSanitizer.cmake
@@ -0,0 +1,47 @@
+# this file simulates a program that has been built with AddressSanitizer
+# 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 AddressSanitizer don't do it
+if(NOT "$ENV{ASAN_OPTIONS}]" MATCHES "simulate_sanitizer.1")
+  return()
+endif()
+
+# clear the log files
+file(REMOVE "${LOG_FILE}.2343")
+file(REMOVE "${LOG_FILE}.2344")
+
+# create an error of each type of LeakSanitizer
+
+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/RunCMake/ctest_memcheck/testAddressSanitizer.cmake b/Tests/RunCMake/ctest_memcheck/testAddressSanitizer.cmake
index 3082e4b..1219666 100644
--- a/Tests/RunCMake/ctest_memcheck/testAddressSanitizer.cmake
+++ b/Tests/RunCMake/ctest_memcheck/testAddressSanitizer.cmake
@@ -2,7 +2,7 @@
 # options
 
 message("ASAN_OPTIONS = [$ENV{ASAN_OPTIONS}]")
-string(REGEX REPLACE ".*log_path=\"([^\"]*)\".*" "\\1" LOG_FILE "$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
diff --git a/Tests/RunCMake/ctest_memcheck/testLeakSanitizer.cmake b/Tests/RunCMake/ctest_memcheck/testLeakSanitizer.cmake
index 02030be..6d51f83 100644
--- a/Tests/RunCMake/ctest_memcheck/testLeakSanitizer.cmake
+++ b/Tests/RunCMake/ctest_memcheck/testLeakSanitizer.cmake
@@ -1,20 +1,20 @@
-# this file simulates a program that has been built with thread sanitizer
+# this file simulates a program that has been built with LeakSanitizer
 # options
 
-message("ASAN_OPTIONS = [$ENV{ASAN_OPTIONS}]")
-string(REGEX REPLACE ".*log_path=\"([^\"]*)\".*" "\\1" LOG_FILE "$ENV{ASAN_OPTIONS}")
+message("LSAN_OPTIONS = [$ENV{LSAN_OPTIONS}]")
+string(REGEX REPLACE ".*log_path=\'([^\']*)\'.*" "\\1" LOG_FILE "$ENV{LSAN_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")
+
+# if we are not asked to simulate LeakSanitizer don't do it
+if(NOT "$ENV{LSAN_OPTIONS}]" MATCHES "simulate_sanitizer.1")
   return()
 endif()
 
-# clear the log file
+# clear the log files
 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
+# create an error of each type of LeakSanitizer
 
 file(APPEND "${LOG_FILE}.2343"
 "=================================================================
@@ -25,7 +25,7 @@ Direct leak of 4360 byte(s) in 1 object(s) allocated from:
     #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).
+SUMMARY: LeakSanitizer: 4436 byte(s) leaked in 2 allocation(s).
 ")
 file(APPEND "${LOG_FILE}.2342"
 "=================================================================
@@ -43,5 +43,5 @@ Indirect leak of 76 byte(s) in 1 object(s) allocated from:
     #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).
+SUMMARY: LeakSanitizer: 4436 byte(s) leaked in 2 allocation(s).
 ")
diff --git a/Tests/RunCMake/ctest_memcheck/testMemorySanitizer.cmake b/Tests/RunCMake/ctest_memcheck/testMemorySanitizer.cmake
index c87af9a..3b3ac22 100644
--- a/Tests/RunCMake/ctest_memcheck/testMemorySanitizer.cmake
+++ b/Tests/RunCMake/ctest_memcheck/testMemorySanitizer.cmake
@@ -1,8 +1,8 @@
-# this file simulates a program that has been built with thread sanitizer
+# this file simulates a program that has been built with MemorySanitizer
 # options
 
 message("MSAN_OPTIONS = [$ENV{MSAN_OPTIONS}]")
-string(REGEX REPLACE ".*log_path=\"([^\"]*)\".*" "\\1" LOG_FILE "$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
diff --git a/Tests/RunCMake/ctest_memcheck/testThreadSanitizer.cmake b/Tests/RunCMake/ctest_memcheck/testThreadSanitizer.cmake
index d591931..e7a5c9f 100644
--- a/Tests/RunCMake/ctest_memcheck/testThreadSanitizer.cmake
+++ b/Tests/RunCMake/ctest_memcheck/testThreadSanitizer.cmake
@@ -1,8 +1,8 @@
-# this file simulates a program that has been built with thread sanitizer
+# this file simulates a program that has been built with ThreadSanitizer
 # options
 
 message("TSAN_OPTIONS = [$ENV{TSAN_OPTIONS}]")
-string(REGEX REPLACE ".*log_path=\"([^\"]*)\".*" "\\1" LOG_FILE "$ENV{TSAN_OPTIONS}")
+string(REGEX REPLACE ".*log_path=\'([^\']*)\'.*" "\\1" LOG_FILE "$ENV{TSAN_OPTIONS}")
 message("LOG_FILE=[${LOG_FILE}]")
 
 set(error_types
diff --git a/Tests/RunCMake/ctest_memcheck/testUndefinedBehaviorSanitizer.cmake b/Tests/RunCMake/ctest_memcheck/testUndefinedBehaviorSanitizer.cmake
index 8ef3c0a..ba6122d 100644
--- a/Tests/RunCMake/ctest_memcheck/testUndefinedBehaviorSanitizer.cmake
+++ b/Tests/RunCMake/ctest_memcheck/testUndefinedBehaviorSanitizer.cmake
@@ -1,8 +1,8 @@
-# this file simulates a program that has been built with undefined behavior
-# sanitizer options
+# this file simulates a program that has been built with
+# UndefinedBehaviorSanitizer options
 
 message("UBSAN_OPTIONS = [$ENV{UBSAN_OPTIONS}]")
-string(REGEX REPLACE ".*log_path=\"([^\"]*)\".*" "\\1" LOG_FILE "$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
diff --git a/Tests/RunCMake/ctest_submit/CDashUploadRETRY_COUNT-result.txt b/Tests/RunCMake/ctest_submit/CDashUploadMissingFile-result.txt
similarity index 100%
copy from Tests/RunCMake/ctest_submit/CDashUploadRETRY_COUNT-result.txt
copy to Tests/RunCMake/ctest_submit/CDashUploadMissingFile-result.txt
diff --git a/Tests/RunCMake/ctest_submit/CDashUploadMissingFile-stderr.txt b/Tests/RunCMake/ctest_submit/CDashUploadMissingFile-stderr.txt
new file mode 100644
index 0000000..364ecde
--- /dev/null
+++ b/Tests/RunCMake/ctest_submit/CDashUploadMissingFile-stderr.txt
@@ -0,0 +1 @@
+Upload file not found: 'bad-upload'
diff --git a/Tests/RunCMake/ctest_submit/CDashUploadRETRY_COUNT-stderr.txt b/Tests/RunCMake/ctest_submit/CDashUploadRETRY_COUNT-stderr.txt
deleted file mode 100644
index 21621d4..0000000
--- a/Tests/RunCMake/ctest_submit/CDashUploadRETRY_COUNT-stderr.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-CMake Error at .*/Tests/RunCMake/ctest_submit/CDashUploadRETRY_COUNT/test.cmake:[0-9]+ \(ctest_submit\):
-  ctest_submit called with unknown argument "RETRY_COUNT".
diff --git a/Tests/RunCMake/ctest_submit/CDashUploadRETRY_DELAY-stderr.txt b/Tests/RunCMake/ctest_submit/CDashUploadRETRY_DELAY-stderr.txt
deleted file mode 100644
index f726674..0000000
--- a/Tests/RunCMake/ctest_submit/CDashUploadRETRY_DELAY-stderr.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-CMake Error at .*/Tests/RunCMake/ctest_submit/CDashUploadRETRY_DELAY/test.cmake:[0-9]+ \(ctest_submit\):
-  ctest_submit called with unknown argument "RETRY_DELAY".
diff --git a/Tests/RunCMake/ctest_submit/CDashUploadRETRY_COUNT-result.txt b/Tests/RunCMake/ctest_submit/CDashUploadRetry-result.txt
similarity index 100%
rename from Tests/RunCMake/ctest_submit/CDashUploadRETRY_COUNT-result.txt
rename to Tests/RunCMake/ctest_submit/CDashUploadRetry-result.txt
diff --git a/Tests/RunCMake/ctest_submit/CDashUploadRetry-stderr.txt b/Tests/RunCMake/ctest_submit/CDashUploadRetry-stderr.txt
new file mode 100644
index 0000000..6780c17
--- /dev/null
+++ b/Tests/RunCMake/ctest_submit/CDashUploadRetry-stderr.txt
@@ -0,0 +1 @@
+error uploading to CDash.
diff --git a/Tests/RunCMake/ctest_submit/CDashUploadRetry-stdout.txt b/Tests/RunCMake/ctest_submit/CDashUploadRetry-stdout.txt
new file mode 100644
index 0000000..a5459ac
--- /dev/null
+++ b/Tests/RunCMake/ctest_submit/CDashUploadRetry-stdout.txt
@@ -0,0 +1,4 @@
+   Upload failed, waiting 1 seconds...
+   Retry upload: Attempt 1 of 2
+   Upload failed, waiting 1 seconds...
+   Retry upload: Attempt 2 of 2
diff --git a/Tests/RunCMake/ctest_submit/RunCMakeTest.cmake b/Tests/RunCMake/ctest_submit/RunCMakeTest.cmake
index a81bc96..e104f8a 100644
--- a/Tests/RunCMake/ctest_submit/RunCMakeTest.cmake
+++ b/Tests/RunCMake/ctest_submit/RunCMakeTest.cmake
@@ -21,9 +21,9 @@ run_ctest_submit(PARTSCDashUpload PARTS Configure CDASH_UPLOAD)
 run_ctest_submit(PARTSCDashUploadType PARTS Configure CDASH_UPLOAD_TYPE)
 run_ctest_submit(CDashUploadPARTS CDASH_UPLOAD bad-upload PARTS)
 run_ctest_submit(CDashUploadFILES CDASH_UPLOAD bad-upload FILES)
-run_ctest_submit(CDashUploadRETRY_COUNT CDASH_UPLOAD bad-upload RETRY_COUNT)
-run_ctest_submit(CDashUploadRETRY_DELAY CDASH_UPLOAD bad-upload RETRY_DELAY)
 run_ctest_submit(CDashUploadNone CDASH_UPLOAD)
+run_ctest_submit(CDashUploadMissingFile CDASH_UPLOAD bad-upload)
+run_ctest_submit(CDashUploadRetry CDASH_UPLOAD ${CMAKE_CURRENT_LIST_FILE} CDASH_UPLOAD_TYPE foo RETRY_COUNT 2 RETRY_DELAY 1 INTERNAL_TEST_CHECKSUM)
 run_ctest_submit(CDashSubmitQuiet QUIET)
 
 function(run_ctest_CDashUploadFTP)
diff --git a/Tests/RunCMake/execute_process/CMakeLists.txt b/Tests/RunCMake/execute_process/CMakeLists.txt
new file mode 100644
index 0000000..a640c56
--- /dev/null
+++ b/Tests/RunCMake/execute_process/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.7)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/execute_process/Encoding.cmake b/Tests/RunCMake/execute_process/Encoding.cmake
new file mode 100644
index 0000000..3dc7c39
--- /dev/null
+++ b/Tests/RunCMake/execute_process/Encoding.cmake
@@ -0,0 +1,6 @@
+execute_process(
+  COMMAND ${TEST_ENCODING_EXE} ${TEST_ENCODING} ${CMAKE_CURRENT_LIST_DIR}/EncodingUTF8-stderr.txt
+  OUTPUT_VARIABLE out
+  ENCODING ${TEST_ENCODING}
+  )
+message("${out}")
diff --git a/Tests/RunCMake/execute_process/EncodingMissing-result.txt b/Tests/RunCMake/execute_process/EncodingMissing-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EncodingMissing-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/execute_process/EncodingMissing-stderr.txt b/Tests/RunCMake/execute_process/EncodingMissing-stderr.txt
new file mode 100644
index 0000000..1a69579
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EncodingMissing-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at EncodingMissing.cmake:[0-9]+ \(execute_process\):
+  execute_process called with no value for ENCODING.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/execute_process/EncodingMissing.cmake b/Tests/RunCMake/execute_process/EncodingMissing.cmake
new file mode 100644
index 0000000..ae97480
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EncodingMissing.cmake
@@ -0,0 +1 @@
+execute_process(ENCODING)
diff --git a/Tests/RunCMake/execute_process/EncodingUTF8-stderr.txt b/Tests/RunCMake/execute_process/EncodingUTF8-stderr.txt
new file mode 100644
index 0000000..0ac68de
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EncodingUTF8-stderr.txt
@@ -0,0 +1 @@
+यूनिकोड είναι very здорово!
diff --git a/Tests/RunCMake/execute_process/RunCMakeTest.cmake b/Tests/RunCMake/execute_process/RunCMakeTest.cmake
index 2080437..62e18c6 100644
--- a/Tests/RunCMake/execute_process/RunCMakeTest.cmake
+++ b/Tests/RunCMake/execute_process/RunCMakeTest.cmake
@@ -6,3 +6,8 @@ unset(RunCMake_TEST_OUTPUT_MERGE)
 
 run_cmake_command(MergeOutputFile ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR}/MergeOutputFile.cmake)
 run_cmake_command(MergeOutputVars ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR}/MergeOutputVars.cmake)
+
+run_cmake(EncodingMissing)
+if(TEST_ENCODING_EXE)
+  run_cmake_command(EncodingUTF8 ${CMAKE_COMMAND} -DTEST_ENCODING=UTF8 -DTEST_ENCODING_EXE=${TEST_ENCODING_EXE} -P ${RunCMake_SOURCE_DIR}/Encoding.cmake)
+endif()
diff --git a/Tests/RunCMake/file/GLOB-noexp-LIST_DIRECTORIES.cmake b/Tests/RunCMake/file/GLOB-noexp-LIST_DIRECTORIES.cmake
new file mode 100644
index 0000000..37a9d54
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-noexp-LIST_DIRECTORIES.cmake
@@ -0,0 +1 @@
+file(GLOB CONTENT_LIST LIST_DIRECTORIES false)
diff --git a/Tests/RunCMake/file/RunCMakeTest.cmake b/Tests/RunCMake/file/RunCMakeTest.cmake
index 48fa757..7497544 100644
--- a/Tests/RunCMake/file/RunCMakeTest.cmake
+++ b/Tests/RunCMake/file/RunCMakeTest.cmake
@@ -31,6 +31,7 @@ run_cmake(GLOB_RECURSE)
 run_cmake(GLOB-error-LIST_DIRECTORIES-not-boolean)
 # test is valid both for GLOB and GLOB_RECURSE
 run_cmake(GLOB-error-LIST_DIRECTORIES-no-arg)
+run_cmake(GLOB-noexp-LIST_DIRECTORIES)
 
 if(NOT WIN32 OR CYGWIN)
   run_cmake(GLOB_RECURSE-cyclic-recursion)
diff --git a/Tests/RunCMake/find_library/LibArchLink-stderr.txt b/Tests/RunCMake/find_library/LibArchLink-stderr.txt
new file mode 100644
index 0000000..139e077
--- /dev/null
+++ b/Tests/RunCMake/find_library/LibArchLink-stderr.txt
@@ -0,0 +1,2 @@
+TOP_LIBRARY='[^']*/Tests/RunCMake/find_library/LibArchLink-build/lib/libtop.a'
+SUB_LIBRARY='[^']*/Tests/RunCMake/find_library/LibArchLink-build/lib/sub/libsub.a'
diff --git a/Tests/RunCMake/find_library/LibArchLink.cmake b/Tests/RunCMake/find_library/LibArchLink.cmake
new file mode 100644
index 0000000..c91381d
--- /dev/null
+++ b/Tests/RunCMake/find_library/LibArchLink.cmake
@@ -0,0 +1,24 @@
+set(CMAKE_SIZEOF_VOID_P 4)
+set_property(GLOBAL PROPERTY FIND_LIBRARY_USE_LIB32_PATHS ON)
+list(APPEND CMAKE_FIND_LIBRARY_PREFIXES lib)
+list(APPEND CMAKE_FIND_LIBRARY_SUFFIXES .a)
+
+file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/lib)
+execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink lib ${CMAKE_CURRENT_BINARY_DIR}/lib32)
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/lib/libtop.a" "top")
+find_library(TOP_LIBRARY
+  NAMES top
+  PATHS ${CMAKE_CURRENT_BINARY_DIR}/lib
+  NO_DEFAULT_PATH
+  )
+message("TOP_LIBRARY='${TOP_LIBRARY}'")
+
+file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/lib/sub)
+execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink . ${CMAKE_CURRENT_BINARY_DIR}/lib/sub/32)
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/lib/sub/libsub.a" "sub")
+find_library(SUB_LIBRARY
+  NAMES sub
+  PATHS ${CMAKE_CURRENT_BINARY_DIR}/lib/sub
+  NO_DEFAULT_PATH
+  )
+message("SUB_LIBRARY='${SUB_LIBRARY}'")
diff --git a/Tests/RunCMake/find_library/RunCMakeTest.cmake b/Tests/RunCMake/find_library/RunCMakeTest.cmake
index 5733965..e7e8db3 100644
--- a/Tests/RunCMake/find_library/RunCMakeTest.cmake
+++ b/Tests/RunCMake/find_library/RunCMakeTest.cmake
@@ -1,6 +1,9 @@
 include(RunCMake)
 
 run_cmake(Created)
+if(CMAKE_HOST_UNIX)
+  run_cmake(LibArchLink)
+endif()
 if(WIN32 OR CYGWIN)
   run_cmake(PrefixInPATH)
 endif()
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value-result.txt b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value-stderr.txt b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value-stderr.txt
new file mode 100644
index 0000000..454c655
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value-stderr.txt
@@ -0,0 +1,44 @@
+^CMake Error at IMPORTED_LIBNAME-bad-value.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME property value
+
+    -flag
+
+  may not start with '-'.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-bad-value.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME property value
+
+    item1;item2
+
+  may not contain ';'.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-bad-value.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME property value
+
+    /path/to/item1
+
+  may not contain '/'.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-bad-value.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME property value
+
+    \\path\\to\\item1
+
+  may not contain '\\'.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-bad-value.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME property value
+
+    c:\\path\\to\\item1
+
+  may not contain ':'.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value.cmake b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value.cmake
new file mode 100644
index 0000000..1af65b4
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-bad-value.cmake
@@ -0,0 +1,6 @@
+add_library(MyTarget INTERFACE IMPORTED)
+set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME -flag)
+set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME item1 item2)
+set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME /path/to/item1)
+set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME \\path\\to\\item1)
+set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME c:\\path\\to\\item1)
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface-result.txt b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface-stderr.txt b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface-stderr.txt
new file mode 100644
index 0000000..3a329d2
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface-stderr.txt
@@ -0,0 +1,45 @@
+^CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME property may be set only on imported INTERFACE library
+  targets.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME property may not be APPENDed.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME_DEBUG property may be set only on imported INTERFACE
+  library targets.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME_DEBUG property may not be APPENDed.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME property may be set only on imported INTERFACE library
+  targets.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME property may be set only on imported INTERFACE library
+  targets.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME property may be set only on imported INTERFACE library
+  targets.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-iface.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME property may be set only on imported INTERFACE library
+  targets.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface.cmake b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface.cmake
new file mode 100644
index 0000000..fe6841a
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-iface.cmake
@@ -0,0 +1,17 @@
+add_custom_target(MyCustom)
+set_property(TARGET MyCustom PROPERTY IMPORTED_LIBNAME item1)
+set_property(TARGET MyCustom APPEND PROPERTY IMPORTED_LIBNAME item2)
+set_property(TARGET MyCustom PROPERTY IMPORTED_LIBNAME_DEBUG item1)
+set_property(TARGET MyCustom APPEND PROPERTY IMPORTED_LIBNAME_DEBUG item2)
+
+add_library(MyStatic STATIC IMPORTED)
+set_property(TARGET MyStatic PROPERTY IMPORTED_LIBNAME item1)
+
+add_library(MyShared SHARED IMPORTED)
+set_property(TARGET MyShared PROPERTY IMPORTED_LIBNAME item1)
+
+add_library(MyModule MODULE IMPORTED)
+set_property(TARGET MyModule PROPERTY IMPORTED_LIBNAME item1)
+
+add_executable(MyExe IMPORTED)
+set_property(TARGET MyExe PROPERTY IMPORTED_LIBNAME item1)
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported-result.txt b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported-stderr.txt b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported-stderr.txt
new file mode 100644
index 0000000..e9d94cf
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported-stderr.txt
@@ -0,0 +1,21 @@
+^CMake Error at IMPORTED_LIBNAME-non-imported.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME property may be set only on imported INTERFACE library
+  targets.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-imported.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME property may not be APPENDed.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-imported.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME_DEBUG property may be set only on imported INTERFACE
+  library targets.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Error at IMPORTED_LIBNAME-non-imported.cmake:[0-9]+ \(set_property\):
+  IMPORTED_LIBNAME_DEBUG property may not be APPENDed.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported.cmake b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported.cmake
new file mode 100644
index 0000000..07a67d7
--- /dev/null
+++ b/Tests/RunCMake/interface_library/IMPORTED_LIBNAME-non-imported.cmake
@@ -0,0 +1,5 @@
+add_library(MyTarget INTERFACE)
+set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME item1)
+set_property(TARGET MyTarget APPEND PROPERTY IMPORTED_LIBNAME item2)
+set_property(TARGET MyTarget PROPERTY IMPORTED_LIBNAME_DEBUG item1)
+set_property(TARGET MyTarget APPEND PROPERTY IMPORTED_LIBNAME_DEBUG item2)
diff --git a/Tests/RunCMake/interface_library/RunCMakeTest.cmake b/Tests/RunCMake/interface_library/RunCMakeTest.cmake
index 201daa7..5a6af1d 100644
--- a/Tests/RunCMake/interface_library/RunCMakeTest.cmake
+++ b/Tests/RunCMake/interface_library/RunCMakeTest.cmake
@@ -8,3 +8,6 @@ run_cmake(invalid_signature)
 run_cmake(global-interface)
 run_cmake(genex_link)
 run_cmake(add_custom_command-TARGET)
+run_cmake(IMPORTED_LIBNAME-bad-value)
+run_cmake(IMPORTED_LIBNAME-non-iface)
+run_cmake(IMPORTED_LIBNAME-non-imported)
diff --git a/Tests/RunCMake/pseudo_cpplint.c b/Tests/RunCMake/pseudo_cpplint.c
new file mode 100644
index 0000000..8b9ebf4
--- /dev/null
+++ b/Tests/RunCMake/pseudo_cpplint.c
@@ -0,0 +1,21 @@
+#include <stdio.h>
+#include <string.h>
+
+int main(int argc, char* argv[])
+{
+  int error = 0;
+  int i;
+  for (i = 1; i < argc; ++i) {
+    if (strcmp(argv[i], "--error") == 0) {
+      error = 1;
+    }
+    if (argv[i][0] != '-') {
+      if (error) {
+        fprintf(stderr, "%s:0:  message  [category/category] [0]\n", argv[i]);
+      }
+      fprintf(stdout, "Done processing %s\nTotal errors found: %i\n", argv[i],
+              error);
+    }
+  }
+  return error;
+}
diff --git a/Tests/RunCMake/pseudo_emulator_custom_command.c b/Tests/RunCMake/pseudo_emulator_custom_command.c
index 760e83c..3a94795 100644
--- a/Tests/RunCMake/pseudo_emulator_custom_command.c
+++ b/Tests/RunCMake/pseudo_emulator_custom_command.c
@@ -14,7 +14,8 @@
 int main(int argc, const char* argv[])
 {
   const char* substring_failure = "generated_exe_emulator_unexpected";
-  const char* substring_success = "generated_exe_emulator_expected";
+  // Require a slash to make sure it is a path and not a target name.
+  const char* substring_success = "/generated_exe_emulator_expected";
   const char* str = argv[1];
   if (argc < 2) {
     return EXIT_FAILURE;
diff --git a/Tests/RunCMake/pseudo_iwyu.c b/Tests/RunCMake/pseudo_iwyu.c
index 1e25de7..c761741 100644
--- a/Tests/RunCMake/pseudo_iwyu.c
+++ b/Tests/RunCMake/pseudo_iwyu.c
@@ -3,5 +3,6 @@
 int main(void)
 {
   fprintf(stderr, "should add these lines:\n#include <...>\n");
-  return 0;
+  /* include-what-you-use always returns failure */
+  return 1;
 }
diff --git a/Tests/RunCMake/pseudo_tidy.c b/Tests/RunCMake/pseudo_tidy.c
index c950d03..2feeb0f 100644
--- a/Tests/RunCMake/pseudo_tidy.c
+++ b/Tests/RunCMake/pseudo_tidy.c
@@ -1,9 +1,15 @@
 #include <stdio.h>
+#include <string.h>
 
 int main(int argc, char* argv[])
 {
   int i;
   for (i = 1; i < argc; ++i) {
+    if (strcmp(argv[i], "-bad") == 0) {
+      fprintf(stdout, "stdout from bad command line arg '-bad'\n");
+      fprintf(stderr, "stderr from bad command line arg '-bad'\n");
+      return 1;
+    }
     if (argv[i][0] != '-') {
       fprintf(stdout, "%s:0:0: warning: message [checker]\n", argv[i]);
       break;
diff --git a/Tests/RunCMake/set_property/RunCMakeTest.cmake b/Tests/RunCMake/set_property/RunCMakeTest.cmake
index 37c7124..1ddacee 100644
--- a/Tests/RunCMake/set_property/RunCMakeTest.cmake
+++ b/Tests/RunCMake/set_property/RunCMakeTest.cmake
@@ -6,4 +6,5 @@ run_cmake(COMPILE_OPTIONS)
 run_cmake(INCLUDE_DIRECTORIES)
 run_cmake(LINK_LIBRARIES)
 run_cmake(SOURCES)
+run_cmake(TYPE)
 run_cmake(USER_PROP)
diff --git a/Tests/RunCMake/set_property/TYPE-result.txt b/Tests/RunCMake/set_property/TYPE-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/set_property/TYPE-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/set_property/TYPE-stderr.txt b/Tests/RunCMake/set_property/TYPE-stderr.txt
new file mode 100644
index 0000000..fbc8653
--- /dev/null
+++ b/Tests/RunCMake/set_property/TYPE-stderr.txt
@@ -0,0 +1 @@
+TYPE property is read-only
diff --git a/Tests/RunCMake/set_property/TYPE.cmake b/Tests/RunCMake/set_property/TYPE.cmake
new file mode 100644
index 0000000..8481266
--- /dev/null
+++ b/Tests/RunCMake/set_property/TYPE.cmake
@@ -0,0 +1,2 @@
+add_custom_target(CustomTarget)
+set_property(TARGET CustomTarget PROPERTY TYPE foo)
diff --git a/Tests/RunCMake/string/RunCMakeTest.cmake b/Tests/RunCMake/string/RunCMakeTest.cmake
index 8067d9d..38a77b0 100644
--- a/Tests/RunCMake/string/RunCMakeTest.cmake
+++ b/Tests/RunCMake/string/RunCMakeTest.cmake
@@ -6,6 +6,11 @@ run_cmake(AppendNoArgs)
 run_cmake(Concat)
 run_cmake(ConcatNoArgs)
 
+run_cmake(Timestamp)
+run_cmake(TimestampEmpty)
+run_cmake(TimestampInvalid)
+run_cmake(TimestampInvalid2)
+
 run_cmake(Uuid)
 run_cmake(UuidMissingNamespace)
 run_cmake(UuidMissingNamespaceValue)
diff --git a/Tests/RunCMake/string/Timestamp-result.txt b/Tests/RunCMake/string/Timestamp-result.txt
new file mode 100644
index 0000000..573541a
--- /dev/null
+++ b/Tests/RunCMake/string/Timestamp-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/string/Timestamp-stderr.txt b/Tests/RunCMake/string/Timestamp-stderr.txt
new file mode 100644
index 0000000..653974c
--- /dev/null
+++ b/Tests/RunCMake/string/Timestamp-stderr.txt
@@ -0,0 +1 @@
+RESULT=2005-08-07 23:19:49 Sun Aug 05 day=219 wd=0 week=32 %I=11 epoch=1123456789
diff --git a/Tests/RunCMake/string/Timestamp.cmake b/Tests/RunCMake/string/Timestamp.cmake
new file mode 100644
index 0000000..d242039
--- /dev/null
+++ b/Tests/RunCMake/string/Timestamp.cmake
@@ -0,0 +1,3 @@
+set(ENV{SOURCE_DATE_EPOCH} "1123456789")
+string(TIMESTAMP RESULT "%Y-%m-%d %H:%M:%S %a %b %y day=%j wd=%w week=%U %%I=%I epoch=%s" UTC)
+message("RESULT=${RESULT}")
diff --git a/Tests/RunCMake/string/TimestampEmpty-result.txt b/Tests/RunCMake/string/TimestampEmpty-result.txt
new file mode 100644
index 0000000..573541a
--- /dev/null
+++ b/Tests/RunCMake/string/TimestampEmpty-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/string/TimestampEmpty-stderr.txt b/Tests/RunCMake/string/TimestampEmpty-stderr.txt
new file mode 100644
index 0000000..35cbd3c
--- /dev/null
+++ b/Tests/RunCMake/string/TimestampEmpty-stderr.txt
@@ -0,0 +1 @@
+RESULT=2
diff --git a/Tests/RunCMake/string/TimestampEmpty.cmake b/Tests/RunCMake/string/TimestampEmpty.cmake
new file mode 100644
index 0000000..21b770f
--- /dev/null
+++ b/Tests/RunCMake/string/TimestampEmpty.cmake
@@ -0,0 +1,3 @@
+set(ENV{SOURCE_DATE_EPOCH} "")
+string(TIMESTAMP RESULT "%Y-%m-%d %H:%M:%S" UTC)
+message("RESULT=${RESULT}")
diff --git a/Tests/RunCMake/string/TimestampInvalid-result.txt b/Tests/RunCMake/string/TimestampInvalid-result.txt
new file mode 100644
index 0000000..f64f5d8
--- /dev/null
+++ b/Tests/RunCMake/string/TimestampInvalid-result.txt
@@ -0,0 +1 @@
+27
diff --git a/Tests/RunCMake/string/TimestampInvalid-stderr.txt b/Tests/RunCMake/string/TimestampInvalid-stderr.txt
new file mode 100644
index 0000000..75566da
--- /dev/null
+++ b/Tests/RunCMake/string/TimestampInvalid-stderr.txt
@@ -0,0 +1 @@
+CMake Error: Cannot parse SOURCE_DATE_EPOCH as integer
diff --git a/Tests/RunCMake/string/TimestampInvalid.cmake b/Tests/RunCMake/string/TimestampInvalid.cmake
new file mode 100644
index 0000000..ab36270
--- /dev/null
+++ b/Tests/RunCMake/string/TimestampInvalid.cmake
@@ -0,0 +1,3 @@
+set(ENV{SOURCE_DATE_EPOCH} "invalid-integer")
+string(TIMESTAMP RESULT "%Y-%m-%d %H:%M:%S" UTC)
+message("RESULT=${RESULT}")
diff --git a/Tests/RunCMake/string/TimestampInvalid2-result.txt b/Tests/RunCMake/string/TimestampInvalid2-result.txt
new file mode 100644
index 0000000..f64f5d8
--- /dev/null
+++ b/Tests/RunCMake/string/TimestampInvalid2-result.txt
@@ -0,0 +1 @@
+27
diff --git a/Tests/RunCMake/string/TimestampInvalid2-stderr.txt b/Tests/RunCMake/string/TimestampInvalid2-stderr.txt
new file mode 100644
index 0000000..75566da
--- /dev/null
+++ b/Tests/RunCMake/string/TimestampInvalid2-stderr.txt
@@ -0,0 +1 @@
+CMake Error: Cannot parse SOURCE_DATE_EPOCH as integer
diff --git a/Tests/RunCMake/string/TimestampInvalid2.cmake b/Tests/RunCMake/string/TimestampInvalid2.cmake
new file mode 100644
index 0000000..5cc61b8
--- /dev/null
+++ b/Tests/RunCMake/string/TimestampInvalid2.cmake
@@ -0,0 +1,3 @@
+set(ENV{SOURCE_DATE_EPOCH} "123trailing-garbage")
+string(TIMESTAMP RESULT "%Y-%m-%d %H:%M:%S" UTC)
+message("RESULT=${RESULT}")
diff --git a/Tests/RunCMake/try_compile/CMP0067-stderr.txt b/Tests/RunCMake/try_compile/CMP0067-stderr.txt
new file mode 100644
index 0000000..e2677ed
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CMP0067-stderr.txt
@@ -0,0 +1,25 @@
+before try_compile with CMP0067 WARN-enabled but no variables
+after try_compile with CMP0067 WARN-enabled but no variables
+before try_compile with CMP0067 WARN-default
+after try_compile with CMP0067 WARN-default
+before try_compile with CMP0067 WARN-enabled
+CMake Warning \(dev\) at CMP0067.cmake:[0-9]+ \(try_compile\):
+  Policy CMP0067 is not set: Honor language standard in try_compile\(\)
+  source-file signature.  Run "cmake --help-policy CMP0067" for policy
+  details.  Use the cmake_policy command to set the policy and suppress this
+  warning.
+
+  For compatibility with older versions of CMake, try_compile is not honoring
+  language standard variables in the test project:
+
+    CMAKE_C_STANDARD
+
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)
+This warning is for project developers.  Use -Wno-dev to suppress it.
+
+after try_compile with CMP0067 WARN-enabled
+before try_compile with CMP0067 OLD
+after try_compile with CMP0067 OLD
+before try_compile with CMP0067 NEW
+after try_compile with CMP0067 NEW
diff --git a/Tests/RunCMake/try_compile/CMP0067.cmake b/Tests/RunCMake/try_compile/CMP0067.cmake
new file mode 100644
index 0000000..dd05d96
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CMP0067.cmake
@@ -0,0 +1,40 @@
+enable_language(C)
+
+set(CMAKE_POLICY_WARNING_CMP0067 ON)
+message("before try_compile with CMP0067 WARN-enabled but no variables")
+try_compile(RESULT ${CMAKE_CURRENT_BINARY_DIR}
+  ${CMAKE_CURRENT_SOURCE_DIR}/src.c
+  )
+message("after try_compile with CMP0067 WARN-enabled but no variables")
+set(CMAKE_POLICY_WARNING_CMP0067 OFF)
+
+#-----------------------------------------------------------------------------
+
+set(CMAKE_C_STANDARD 90)
+
+message("before try_compile with CMP0067 WARN-default")
+try_compile(RESULT ${CMAKE_CURRENT_BINARY_DIR}
+  ${CMAKE_CURRENT_SOURCE_DIR}/src.c
+  )
+message("after try_compile with CMP0067 WARN-default")
+
+set(CMAKE_POLICY_WARNING_CMP0067 ON)
+message("before try_compile with CMP0067 WARN-enabled")
+try_compile(RESULT ${CMAKE_CURRENT_BINARY_DIR}
+  ${CMAKE_CURRENT_SOURCE_DIR}/src.c
+  )
+message("after try_compile with CMP0067 WARN-enabled")
+
+cmake_policy(SET CMP0067 OLD)
+message("before try_compile with CMP0067 OLD")
+try_compile(RESULT ${CMAKE_CURRENT_BINARY_DIR}
+  ${CMAKE_CURRENT_SOURCE_DIR}/src.c
+  )
+message("after try_compile with CMP0067 OLD")
+
+cmake_policy(SET CMP0066 NEW)
+message("before try_compile with CMP0067 NEW")
+try_compile(RESULT ${CMAKE_CURRENT_BINARY_DIR}
+  ${CMAKE_CURRENT_SOURCE_DIR}/src.c
+  )
+message("after try_compile with CMP0067 NEW")
diff --git a/Tests/RunCMake/try_compile/CStandard-result.txt b/Tests/RunCMake/try_compile/CStandard-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CStandard-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/try_compile/CStandard-stderr.txt b/Tests/RunCMake/try_compile/CStandard-stderr.txt
new file mode 100644
index 0000000..209afcc
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CStandard-stderr.txt
@@ -0,0 +1,7 @@
+^CMake Error at .*/Tests/RunCMake/try_compile/CStandard-build/CMakeFiles/CMakeTmp/CMakeLists.txt:[0-9]+ \(add_executable\):
+  C_STANDARD is set to invalid value '3'
++
+CMake Error at CStandard.cmake:[0-9]+ \(try_compile\):
+  Failed to generate test project build system.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/try_compile/CStandard.cmake b/Tests/RunCMake/try_compile/CStandard.cmake
new file mode 100644
index 0000000..2849ed4
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CStandard.cmake
@@ -0,0 +1,7 @@
+enable_language(C)
+try_compile(result ${CMAKE_CURRENT_BINARY_DIR}
+  SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src.c
+  C_STANDARD 3
+  OUTPUT_VARIABLE out
+  )
+message("try_compile output:\n${out}")
diff --git a/Tests/RunCMake/try_compile/CStandardGNU.c b/Tests/RunCMake/try_compile/CStandardGNU.c
new file mode 100644
index 0000000..ac26c15
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CStandardGNU.c
@@ -0,0 +1,10 @@
+#if __STDC_VERSION__ != 199901L
+#error "Not GNU C 99 mode!"
+#endif
+#ifndef __STRICT_ANSI__
+#error "Not GNU C strict ANSI!"
+#endif
+int main(void)
+{
+  return 0;
+}
diff --git a/Tests/RunCMake/try_compile/CStandardGNU.cmake b/Tests/RunCMake/try_compile/CStandardGNU.cmake
new file mode 100644
index 0000000..79ae874
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CStandardGNU.cmake
@@ -0,0 +1,23 @@
+enable_language(C)
+try_compile(result ${CMAKE_CURRENT_BINARY_DIR}
+  SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/CStandardGNU.c
+  C_STANDARD 99
+  C_STANDARD_REQUIRED 1
+  C_EXTENSIONS 0
+  OUTPUT_VARIABLE out
+  )
+if(NOT result)
+  message(FATAL_ERROR "try_compile failed:\n${out}")
+endif()
+
+cmake_policy(SET CMP0067 NEW)
+set(CMAKE_C_STANDARD 99)
+set(CMAKE_C_STANDARD_REQUIRED 1)
+set(CMAKE_C_EXTENSIONS 0)
+try_compile(result ${CMAKE_CURRENT_BINARY_DIR}
+  SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/CStandardGNU.c
+  OUTPUT_VARIABLE out
+  )
+if(NOT result)
+  message(FATAL_ERROR "try_compile failed:\n${out}")
+endif()
diff --git a/Tests/RunCMake/try_compile/CStandardNoDefault.cmake b/Tests/RunCMake/try_compile/CStandardNoDefault.cmake
new file mode 100644
index 0000000..97e72ea
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CStandardNoDefault.cmake
@@ -0,0 +1,9 @@
+enable_language(C)
+try_compile(result ${CMAKE_CURRENT_BINARY_DIR}
+  SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src.c
+  C_STANDARD 3 # bogus, but not used
+  OUTPUT_VARIABLE out
+  )
+if(NOT result)
+  message(FATAL_ERROR "try_compile failed:\n${out}")
+endif()
diff --git a/Tests/RunCMake/try_compile/CudaStandard-result.txt b/Tests/RunCMake/try_compile/CudaStandard-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CudaStandard-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/try_compile/CudaStandard-stderr.txt b/Tests/RunCMake/try_compile/CudaStandard-stderr.txt
new file mode 100644
index 0000000..3c6bdf6
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CudaStandard-stderr.txt
@@ -0,0 +1,7 @@
+^CMake Error at .*/Tests/RunCMake/try_compile/CudaStandard-build/CMakeFiles/CMakeTmp/CMakeLists.txt:[0-9]+ \(add_executable\):
+  CUDA_STANDARD is set to invalid value '3'
++
+CMake Error at CudaStandard.cmake:[0-9]+ \(try_compile\):
+  Failed to generate test project build system.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/try_compile/CudaStandard.cmake b/Tests/RunCMake/try_compile/CudaStandard.cmake
new file mode 100644
index 0000000..96da422
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CudaStandard.cmake
@@ -0,0 +1,7 @@
+enable_language(CUDA)
+try_compile(result ${CMAKE_CURRENT_BINARY_DIR}
+  SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src.cu
+  CUDA_STANDARD 3
+  OUTPUT_VARIABLE out
+  )
+message("try_compile output:\n${out}")
diff --git a/Tests/RunCMake/try_compile/CudaStandardNoDefault.cmake b/Tests/RunCMake/try_compile/CudaStandardNoDefault.cmake
new file mode 100644
index 0000000..ea22152
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CudaStandardNoDefault.cmake
@@ -0,0 +1,9 @@
+enable_language(CUDA)
+try_compile(result ${CMAKE_CURRENT_BINARY_DIR}
+  SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src.cu
+  CUDA_STANDARD 3 # bogus, but not used
+  OUTPUT_VARIABLE out
+  )
+if(NOT result)
+  message(FATAL_ERROR "try_compile failed:\n${out}")
+endif()
diff --git a/Tests/RunCMake/try_compile/CxxStandard-result.txt b/Tests/RunCMake/try_compile/CxxStandard-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CxxStandard-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/try_compile/CxxStandard-stderr.txt b/Tests/RunCMake/try_compile/CxxStandard-stderr.txt
new file mode 100644
index 0000000..ec7245f
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CxxStandard-stderr.txt
@@ -0,0 +1,7 @@
+^CMake Error at .*/Tests/RunCMake/try_compile/CxxStandard-build/CMakeFiles/CMakeTmp/CMakeLists.txt:[0-9]+ \(add_executable\):
+  CXX_STANDARD is set to invalid value '3'
++
+CMake Error at CxxStandard.cmake:[0-9]+ \(try_compile\):
+  Failed to generate test project build system.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/try_compile/CxxStandard.cmake b/Tests/RunCMake/try_compile/CxxStandard.cmake
new file mode 100644
index 0000000..bcb49b9
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CxxStandard.cmake
@@ -0,0 +1,7 @@
+enable_language(CXX)
+try_compile(result ${CMAKE_CURRENT_BINARY_DIR}
+  SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src.cxx
+  CXX_STANDARD 3
+  OUTPUT_VARIABLE out
+  )
+message("try_compile output:\n${out}")
diff --git a/Tests/RunCMake/try_compile/CxxStandardGNU.cmake b/Tests/RunCMake/try_compile/CxxStandardGNU.cmake
new file mode 100644
index 0000000..e714fe4
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CxxStandardGNU.cmake
@@ -0,0 +1,23 @@
+enable_language(CXX)
+try_compile(result ${CMAKE_CURRENT_BINARY_DIR}
+  SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/CxxStandardGNU.cxx
+  CXX_STANDARD 11
+  CXX_STANDARD_REQUIRED 1
+  CXX_EXTENSIONS 0
+  OUTPUT_VARIABLE out
+  )
+if(NOT result)
+  message(FATAL_ERROR "try_compile failed:\n${out}")
+endif()
+
+cmake_policy(SET CMP0067 NEW)
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CXX_STANDARD_REQUIRED 1)
+set(CMAKE_CXX_EXTENSIONS 0)
+try_compile(result ${CMAKE_CURRENT_BINARY_DIR}
+  SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/CxxStandardGNU.cxx
+  OUTPUT_VARIABLE out
+  )
+if(NOT result)
+  message(FATAL_ERROR "try_compile failed:\n${out}")
+endif()
diff --git a/Tests/RunCMake/try_compile/CxxStandardGNU.cxx b/Tests/RunCMake/try_compile/CxxStandardGNU.cxx
new file mode 100644
index 0000000..7990a78
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CxxStandardGNU.cxx
@@ -0,0 +1,11 @@
+#if __cplusplus != 201103L &&                                                 \
+  !(__cplusplus < 201103L && defined(__GXX_EXPERIMENTAL_CXX0X__))
+#error "Not GNU C++ 11 mode!"
+#endif
+#ifndef __STRICT_ANSI__
+#error "Not GNU C++ strict ANSI!"
+#endif
+int main()
+{
+  return 0;
+}
diff --git a/Tests/RunCMake/try_compile/CxxStandardNoDefault.cmake b/Tests/RunCMake/try_compile/CxxStandardNoDefault.cmake
new file mode 100644
index 0000000..35caa9d
--- /dev/null
+++ b/Tests/RunCMake/try_compile/CxxStandardNoDefault.cmake
@@ -0,0 +1,9 @@
+enable_language(CXX)
+try_compile(result ${CMAKE_CURRENT_BINARY_DIR}
+  SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src.cxx
+  CXX_STANDARD 3 # bogus, but not used
+  OUTPUT_VARIABLE out
+  )
+if(NOT result)
+  message(FATAL_ERROR "try_compile failed:\n${out}")
+endif()
diff --git a/Tests/RunCMake/try_compile/RunCMakeTest.cmake b/Tests/RunCMake/try_compile/RunCMakeTest.cmake
index 522433a..6a1bc64 100644
--- a/Tests/RunCMake/try_compile/RunCMakeTest.cmake
+++ b/Tests/RunCMake/try_compile/RunCMakeTest.cmake
@@ -18,14 +18,40 @@ run_cmake(NonSourceCompileDefinitions)
 
 set(RunCMake_TEST_OPTIONS --debug-trycompile)
 run_cmake(PlatformVariables)
+run_cmake(WarnDeprecated)
 unset(RunCMake_TEST_OPTIONS)
 
 run_cmake(TargetTypeExe)
 run_cmake(TargetTypeInvalid)
 run_cmake(TargetTypeStatic)
 
+if(CMAKE_C_STANDARD_DEFAULT)
+  run_cmake(CStandard)
+elseif(DEFINED CMAKE_C_STANDARD_DEFAULT)
+  run_cmake(CStandardNoDefault)
+endif()
+if(CMAKE_CXX_STANDARD_DEFAULT)
+  run_cmake(CxxStandard)
+elseif(DEFINED CMAKE_CXX_STANDARD_DEFAULT)
+  run_cmake(CxxStandardNoDefault)
+endif()
+if(CMake_TEST_CUDA)
+  if(CMAKE_HOST_WIN32)
+    run_cmake(CudaStandardNoDefault)
+  else()
+    run_cmake(CudaStandard)
+  endif()
+endif()
+if(CMAKE_C_COMPILER_ID STREQUAL "GNU" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.4)
+  run_cmake(CStandardGNU)
+endif()
+if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.4)
+  run_cmake(CxxStandardGNU)
+endif()
+
 run_cmake(CMP0056)
 run_cmake(CMP0066)
+run_cmake(CMP0067)
 
 if(RunCMake_GENERATOR MATCHES "Make|Ninja")
   # Use a single build tree for a few tests without cleaning.
diff --git a/Tests/RunCMake/try_compile/WarnDeprecated.cmake b/Tests/RunCMake/try_compile/WarnDeprecated.cmake
new file mode 100644
index 0000000..dfcb5f9
--- /dev/null
+++ b/Tests/RunCMake/try_compile/WarnDeprecated.cmake
@@ -0,0 +1,19 @@
+enable_language(C)
+
+set(CMAKE_WARN_DEPRECATED SOME_VALUE)
+
+try_compile(result ${CMAKE_CURRENT_BINARY_DIR}
+  SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src.c
+  OUTPUT_VARIABLE out
+  )
+if(NOT result)
+  message(FATAL_ERROR "try_compile failed:\n${out}")
+endif()
+
+# Check that the cache was populated with our custom variable.
+file(STRINGS ${CMAKE_BINARY_DIR}/CMakeFiles/CMakeTmp/CMakeCache.txt entries
+  REGEX CMAKE_WARN_DEPRECATED:UNINITIALIZED=${CMAKE_WARN_DEPRECATED}
+  )
+if(NOT entries)
+  message(FATAL_ERROR "try_compile did not populate cache as expected")
+endif()
diff --git a/Tests/RunCMake/try_compile/src.cu b/Tests/RunCMake/try_compile/src.cu
new file mode 100644
index 0000000..f8b643a
--- /dev/null
+++ b/Tests/RunCMake/try_compile/src.cu
@@ -0,0 +1,4 @@
+int main()
+{
+  return 0;
+}
diff --git a/Tests/RunCMake/try_compile/src.cxx b/Tests/RunCMake/try_compile/src.cxx
new file mode 100644
index 0000000..f8b643a
--- /dev/null
+++ b/Tests/RunCMake/try_compile/src.cxx
@@ -0,0 +1,4 @@
+int main()
+{
+  return 0;
+}
diff --git a/Tests/RunCMake/while/EndAlone-stderr.txt b/Tests/RunCMake/while/EndAlone-stderr.txt
index cd98687..5fe6655 100644
--- a/Tests/RunCMake/while/EndAlone-stderr.txt
+++ b/Tests/RunCMake/while/EndAlone-stderr.txt
@@ -1,5 +1,5 @@
 ^CMake Error at EndAlone.cmake:1 \(endwhile\):
   endwhile An ENDWHILE command was found outside of a proper WHILE ENDWHILE
-  structure.
+  structure.  Or its arguments did not match the opening WHILE command.
 Call Stack \(most recent call first\):
   CMakeLists.txt:3 \(include\)$
diff --git a/Tests/Server/CMakeLists.txt b/Tests/Server/CMakeLists.txt
index 8913406..e7eaa8d 100644
--- a/Tests/Server/CMakeLists.txt
+++ b/Tests/Server/CMakeLists.txt
@@ -5,6 +5,7 @@ find_package(PythonInterp REQUIRED)
 
 macro(do_test bsname file)
   execute_process(COMMAND ${PYTHON_EXECUTABLE}
+    -B # no .pyc files
     "${CMAKE_SOURCE_DIR}/server-test.py"
     "${CMAKE_COMMAND}"
     "${CMAKE_SOURCE_DIR}/${file}"
diff --git a/Tests/Server/cmakelib.pyc b/Tests/Server/cmakelib.pyc
deleted file mode 100644
index 49a40d9..0000000
Binary files a/Tests/Server/cmakelib.pyc and /dev/null differ
diff --git a/Tests/SourceGroups/CMakeLists.txt b/Tests/SourceGroups/CMakeLists.txt
index 6573c82..9289e84 100644
--- a/Tests/SourceGroups/CMakeLists.txt
+++ b/Tests/SourceGroups/CMakeLists.txt
@@ -30,6 +30,17 @@ source_group(Base\\Sub1\\Base FILES bar.c)
 # a group without files, is currently not created
 source_group(EmptyGroup)
 
+set(root ${CMAKE_CURRENT_SOURCE_DIR})
 
-add_executable(SourceGroups main.c bar.c foo.c sub1/foo.c sub1/foobar.c baz.c README.txt)
+set(tree_files_without_prefix ${root}/sub1/tree_bar.c
+                              ${root}/sub1/tree_baz.c
+                              ${root}/sub1/tree_subdir/tree_foobar.c)
 
+set(tree_files_with_prefix ${root}/tree_foo.c)
+
+source_group(TREE ${root} FILES ${tree_files_without_prefix})
+
+source_group(TREE ${root} PREFIX tree_root/subgroup FILES ${tree_files_with_prefix})
+
+add_executable(SourceGroups main.c bar.c foo.c sub1/foo.c sub1/foobar.c baz.c
+                            ${tree_files_with_prefix} ${tree_files_without_prefix} README.txt)
diff --git a/Tests/SourceGroups/main.c b/Tests/SourceGroups/main.c
index f259f98..b88f2f8 100644
--- a/Tests/SourceGroups/main.c
+++ b/Tests/SourceGroups/main.c
@@ -5,10 +5,17 @@ extern int bar(void);
 extern int foobar(void);
 extern int barbar(void);
 extern int baz(void);
+extern int tree_foo(void);
+extern int tree_bar(void);
+extern int tree_foobar(void);
+extern int tree_baz(void);
 
 int main()
 {
   printf("foo: %d bar: %d foobar: %d barbar: %d baz: %d\n", foo(), bar(),
          foobar(), barbar(), baz());
+
+  printf("tree_foo: %d tree_bar: %d tree_foobar: %d tree_baz: %d\n",
+         tree_foo(), tree_bar(), tree_foobar(), tree_baz());
   return 0;
 }
diff --git a/Tests/SourceGroups/sub1/tree_bar.c b/Tests/SourceGroups/sub1/tree_bar.c
new file mode 100644
index 0000000..6b79239
--- /dev/null
+++ b/Tests/SourceGroups/sub1/tree_bar.c
@@ -0,0 +1,4 @@
+int tree_bar(void)
+{
+  return 8;
+}
diff --git a/Tests/SourceGroups/sub1/tree_baz.c b/Tests/SourceGroups/sub1/tree_baz.c
new file mode 100644
index 0000000..27ff5ab
--- /dev/null
+++ b/Tests/SourceGroups/sub1/tree_baz.c
@@ -0,0 +1,4 @@
+int tree_baz(void)
+{
+  return 9;
+}
diff --git a/Tests/SourceGroups/sub1/tree_subdir/tree_foobar.c b/Tests/SourceGroups/sub1/tree_subdir/tree_foobar.c
new file mode 100644
index 0000000..e955e04
--- /dev/null
+++ b/Tests/SourceGroups/sub1/tree_subdir/tree_foobar.c
@@ -0,0 +1,4 @@
+int tree_foobar(void)
+{
+  return 7;
+}
diff --git a/Tests/SourceGroups/tree_foo.c b/Tests/SourceGroups/tree_foo.c
new file mode 100644
index 0000000..d392e41
--- /dev/null
+++ b/Tests/SourceGroups/tree_foo.c
@@ -0,0 +1,4 @@
+int tree_foo(void)
+{
+  return 6;
+}
diff --git a/Tests/SwiftMix/ObjCMain.m b/Tests/SwiftMix/ObjCMain.m
index 7fa90ae..20f0bf1 100644
--- a/Tests/SwiftMix/ObjCMain.m
+++ b/Tests/SwiftMix/ObjCMain.m
@@ -1,4 +1,4 @@
 #import "SwiftMix-Swift.h"
 int ObjCMain(int argc, char const* const argv[]) {
-  return [SwiftMainClass SwiftMain:argc argv:argv];
+  return [SwiftMainClass SwiftMain];
 }
diff --git a/Tests/SwiftMix/SwiftMain.swift b/Tests/SwiftMix/SwiftMain.swift
index 3629ac8..a4a0a62 100644
--- a/Tests/SwiftMix/SwiftMain.swift
+++ b/Tests/SwiftMix/SwiftMain.swift
@@ -1,12 +1,8 @@
 import Foundation
 
 @objc class SwiftMainClass : NSObject {
-  class func SwiftMain(argc:Int, argv:UnsafePointer<UnsafePointer<CChar>>) -> Int32 {
-    dump("argc: \(argc)")
-    for (var i = 0; i < argc; ++i) {
-      let argi = String.fromCString(argv[i])
-      dump("arg[\(i)]: \(argi)");
-    }
+  class func SwiftMain() -> Int32 {
+    dump("Hello World!");
     return 0;
   }
 }
diff --git a/Tests/SwigTest/CMakeLists.txt b/Tests/SwigTest/CMakeLists.txt
index 17a502d..65f5c93 100644
--- a/Tests/SwigTest/CMakeLists.txt
+++ b/Tests/SwigTest/CMakeLists.txt
@@ -7,6 +7,7 @@ project(example_${language}_class)
 find_package(SWIG REQUIRED)
 include(${SWIG_USE_FILE})
 
+unset(SWIG_LANG_TYPE)
 if(${language} MATCHES python)
   find_package(PythonLibs)
   include_directories(${PYTHON_INCLUDE_PATH})
@@ -38,6 +39,12 @@ if(${language} MATCHES pike)
   include_directories(${PIKE_INCLUDE_PATH})
   set(SWIG_LANG_LIBRARIES ${PIKE_LIBRARY})
 endif()
+if(${language} MATCHES lua)
+  find_package(Lua)
+  include_directories(${LUA_INCLUDE_DIR})
+  set(SWIG_LANG_TYPE TYPE SHARED)
+  set(SWIG_LANG_LIBRARIES ${LUA_LIBRARIES})
+endif()
 
 include_directories(${CMAKE_CURRENT_SOURCE_DIR})
 
@@ -45,6 +52,8 @@ set(CMAKE_SWIG_FLAGS "")
 
 set_source_files_properties(example.i PROPERTIES CPLUSPLUS ON)
 set_source_files_properties(example.i PROPERTIES SWIG_FLAGS "-includeall")
-SWIG_ADD_MODULE(example "${language}"
-  example.i example.cxx)
+SWIG_ADD_LIBRARY(example
+                 LANGUAGE "${language}"
+                 ${SWIG_LANG_TYPE}
+                 SOURCES example.i example.cxx)
 SWIG_LINK_LIBRARIES(example ${SWIG_LANG_LIBRARIES})
diff --git a/Utilities/.gitattributes b/Utilities/.gitattributes
index e3a9e61..bd97802 100644
--- a/Utilities/.gitattributes
+++ b/Utilities/.gitattributes
@@ -1,2 +1,7 @@
 /Git                    export-ignore
+/GitSetup               export-ignore
 SetupForDevelopment.sh  export-ignore
+
+# Do not format third-party sources.
+/KWIML/**       -format.clang-format
+/cm*/**         -format.clang-format
diff --git a/Utilities/CMakeLists.txt b/Utilities/CMakeLists.txt
index 1e51ea2..014204b 100644
--- a/Utilities/CMakeLists.txt
+++ b/Utilities/CMakeLists.txt
@@ -1,7 +1,7 @@
 # Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
 # file Copyright.txt or https://cmake.org/licensing for details.
 
-subdirs(Doxygen KWStyle)
+subdirs(Doxygen)
 
 if(CMAKE_DOC_TARBALL)
   # Undocumented option to extract and install pre-built documentation.
diff --git a/Utilities/Git/pre-commit b/Utilities/Git/pre-commit
index d3c149c..b63ae5e 100755
--- a/Utilities/Git/pre-commit
+++ b/Utilities/Git/pre-commit
@@ -29,6 +29,19 @@ die 'The following changes add lines too long for our C++ style:
 
 Use lines strictly less than '"$line_too_long"' characters in C++ code.'
 
+#-----------------------------------------------------------------------------
+
+# Check that development setup is up-to-date.
+lastSetupForDevelopment=$(git config --get hooks.SetupForDevelopment || echo 0)
+eval $(grep '^SetupForDevelopment_VERSION=' "${BASH_SOURCE%/*}/../SetupForDevelopment.sh")
+test -n "$SetupForDevelopment_VERSION" || SetupForDevelopment_VERSION=0
+if test $lastSetupForDevelopment -lt $SetupForDevelopment_VERSION; then
+  die 'Developer setup in this work tree is out of date.  Please re-run
+
+  Utilities/SetupForDevelopment.sh
+'
+fi
+
 #-------------------------------------------------------------------------------
 if test -z "$HOOKS_ALLOW_KWSYS"; then
   # Disallow changes to KWSys
@@ -41,7 +54,7 @@ if test -z "$HOOKS_ALLOW_KWSYS"; then
 should not be made directly in CMake.  KWSys is kept in its own Git
 repository and shared by several projects.  Please visit
 
-  http://public.kitware.com/Wiki/KWSys/Git
+  https://gitlab.kitware.com/utils/kwsys
 
 to contribute changes directly to KWSys.  Run
 
diff --git a/Utilities/GitSetup/.gitattributes b/Utilities/GitSetup/.gitattributes
index facbbb2..e96d1f8 100644
--- a/Utilities/GitSetup/.gitattributes
+++ b/Utilities/GitSetup/.gitattributes
@@ -1,7 +1,6 @@
 .git*            export-ignore
 
-# Exclude from source archives files specific to Git work tree.
-*                export-ignore
-
+config*          eol=lf         whitespace=indent-with-non-tab
+git-*            eol=lf         whitespace=indent-with-non-tab
 tips             eol=lf         whitespace=indent-with-non-tab
 setup-*          eol=lf         whitespace=indent-with-non-tab
diff --git a/Utilities/GitSetup/README b/Utilities/GitSetup/README
index cf468fb..2f9f1ec 100644
--- a/Utilities/GitSetup/README
+++ b/Utilities/GitSetup/README
@@ -37,6 +37,13 @@ Commit the merge with an informative message:
  the general GitSetup repository "setup" branch.
  ------------------------------------------------------------------------
 
+Optionally add to the project ".gitattributes" file the line
+
+ /Utilities/GitSetup export-ignore
+
+to exclude the GitSetup directory from inclusion by "git archive"
+since it does not make sense in source tarballs.
+
 
 Configuration
 -------------
diff --git a/Utilities/GitSetup/config b/Utilities/GitSetup/config
index b7d5423..d69a679 100644
--- a/Utilities/GitSetup/config
+++ b/Utilities/GitSetup/config
@@ -1,5 +1,5 @@
 [hooks]
-	url = http://cmake.org/cmake.git
+	url = https://cmake.org/cmake.git
 [ssh]
 	host = cmake.org
 	key = id_git_cmake
diff --git a/Utilities/GitSetup/config.sample b/Utilities/GitSetup/config.sample
index bba2382..eeb468b 100644
--- a/Utilities/GitSetup/config.sample
+++ b/Utilities/GitSetup/config.sample
@@ -20,3 +20,13 @@
 	site = http://review.source.kitware.com
 	# pushurl placeholder "$username" is literal
 	pushurl = $username at review.source.kitware.com:Project
+
+[upstream]
+	url = git://public.kitware.com/Project.git
+
+[gitlab]
+	host = gitlab.kitware.com
+	group-path = group
+	group-name = Group
+	project-path = project
+	project-name = Project
diff --git a/Utilities/GitSetup/git-gerrit-push b/Utilities/GitSetup/git-gerrit-push
new file mode 100755
index 0000000..b46f753
--- /dev/null
+++ b/Utilities/GitSetup/git-gerrit-push
@@ -0,0 +1,74 @@
+#!/usr/bin/env bash
+#=============================================================================
+# Copyright 2010-2015 Kitware, Inc.
+#
+# 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.
+#=============================================================================
+
+USAGE="[<remote>] [--no-topic] [--dry-run] [--]"
+OPTIONS_SPEC=
+SUBDIRECTORY_OK=Yes
+. "$(git --exec-path)/git-sh-setup"
+
+#-----------------------------------------------------------------------------
+
+remote=''
+refspecs=''
+no_topic=''
+dry_run=''
+
+# Parse the command line options.
+while test $# != 0; do
+	case "$1" in
+		--no-topic) no_topic=1 ;;
+		--dry-run)  dry_run=--dry-run ;;
+		--) shift; break ;;
+		-*) usage ;;
+		*) test -z "$remote" || usage ; remote="$1" ;;
+	esac
+	shift
+done
+test $# = 0 || usage
+
+# Default remote.
+test -n "$remote" || remote="gerrit"
+
+if test -z "$no_topic"; then
+	# Identify and validate the topic branch name.
+	head="$(git symbolic-ref HEAD)" && topic="${head#refs/heads/}" || topic=''
+	if test -z "$topic" -o "$topic" = "master"; then
+		die 'Please name your topic:
+		git checkout -b descriptive-name'
+	fi
+	# The topic branch will be pushed by name.
+	refspecs="HEAD:refs/for/master/$topic $refspecs"
+fi
+
+# Fetch the current upstream master branch head.
+# This helps computation of a minimal pack to push.
+echo "Fetching $remote master"
+fetch_out=$(git fetch "$remote" master 2>&1) || die "$fetch_out"
+
+# Exit early if we have nothing to push.
+if test -z "$refspecs"; then
+	echo 'Nothing to push!'
+	exit 0
+fi
+
+# Push.  Save output and exit code.
+echo "Pushing to $remote"
+push_stdout=$(git push --porcelain $dry_run "$remote" $refspecs); push_exit=$?
+echo "$push_stdout"
+
+# Reproduce the push exit code.
+exit $push_exit
diff --git a/Utilities/GitSetup/git-gitlab-push b/Utilities/GitSetup/git-gitlab-push
new file mode 100755
index 0000000..768f853
--- /dev/null
+++ b/Utilities/GitSetup/git-gitlab-push
@@ -0,0 +1,177 @@
+#!/usr/bin/env bash
+#=============================================================================
+# Copyright 2010-2015 Kitware, Inc.
+#
+# 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.
+#=============================================================================
+
+USAGE='[<remote>] [<options>...] [--]
+
+OPTIONS
+
+--dry-run
+    Show what would be pushed without actually updating the destination
+
+-f,--force
+    Force-push the topic HEAD to rewrite the destination branch
+
+--no-default
+    Do not push the default branch (e.g. master)
+
+--no-topic
+    Do not push the topic HEAD.
+'
+OPTIONS_SPEC=
+SUBDIRECTORY_OK=Yes
+. "$(git --exec-path)/git-sh-setup"
+
+egrep-q() {
+	egrep "$@" >/dev/null 2>/dev/null
+}
+
+# Load the project configuration.
+gitlab_upstream='' &&
+gitlab_configured='' &&
+config="${BASH_SOURCE%/*}/config" &&
+protocol=$(git config -f "$config" --get gitlab.protocol ||
+	   echo "https") &&
+host=$(git config -f "$config" --get gitlab.host) &&
+site=$(git config -f "$config" --get gitlab.site ||
+       echo "$protocol://$host") &&
+group_path=$(git config -f "$config" --get gitlab.group-path) &&
+project_path=$(git config -f "$config" --get gitlab.project-path) &&
+gitlab_upstream="$site/$group_path/$project_path.git" &&
+gitlab_pushurl=$(git config --get remote.gitlab.pushurl ||
+		 git config --get remote.gitlab.url) &&
+gitlab_configured=1
+
+#-----------------------------------------------------------------------------
+
+remote=''
+refspecs=''
+force=''
+lease=false
+lease_flag=''
+no_topic=''
+no_default=''
+dry_run=''
+
+# Parse the command line options.
+while test $# != 0; do
+	case "$1" in
+		-f|--force)   force='+'; lease=true ;;
+		--no-topic)   no_topic=1 ;;
+		--dry-run)    dry_run=--dry-run ;;
+		--no-default) no_default=1 ;;
+		--) shift; break ;;
+		-*) usage ;;
+		*) test -z "$remote" || usage ; remote="$1" ;;
+	esac
+	shift
+done
+test $# = 0 || usage
+
+# Default remote.
+test -n "$remote" || remote="gitlab"
+
+if test -z "$no_topic"; then
+	# Identify and validate the topic branch name.
+	head="$(git symbolic-ref HEAD)" && topic="${head#refs/heads/}" || topic=''
+	if test -z "$topic" -o "$topic" = "master"; then
+		die 'Please name your topic:
+		git checkout -b descriptive-name'
+	fi
+
+	if $lease; then
+		have_ref=false
+		remoteref="refs/remotes/$remote/$topic"
+		if git rev-parse --verify -q "$remoteref"; then
+			have_ref=true
+		else
+			die "It seems that a local ref for the branch is
+missing; forcing a push is dangerous and may overwrite
+previous work.  Fetch from the $remote remote first or
+push without '-f' or '--force'."
+		fi
+
+		have_lease_flag=false
+		if git push -h | egrep-q -e '--force-with-lease'; then
+			have_lease_flag=true
+		fi
+
+		if $have_lease_flag && $have_ref; then
+			# Set the lease flag.
+			lease_flag="--force-with-lease=$topic:$remoteref"
+			# Clear the force string.
+			force=''
+		fi
+	fi
+
+	# The topic branch will be pushed by name.
+	refspecs="${force}HEAD:refs/heads/$topic $refspecs"
+fi
+
+# Fetch the current remote master branch head.
+# This helps computation of a minimal pack to push.
+echo "Fetching $remote master"
+fetch_out=$(git fetch "$remote" master 2>&1) || die "$fetch_out"
+gitlab_head=$(git rev-parse FETCH_HEAD) || exit
+
+# Fetch the current upstream master branch head.
+if origin_fetchurl=$(git config --get remote.origin.url) &&
+   test "$origin_fetchurl" = "$gitlab_upstream"; then
+	upstream_remote='origin'
+else
+	upstream_remote="$gitlab_upstream"
+fi
+echo "Fetching $upstream_remote master"
+fetch_out=$(git fetch "$upstream_remote" master 2>&1) || die "$fetch_out"
+upstream_head=$(git rev-parse FETCH_HEAD) || exit
+
+# Add a refspec to keep the remote master up to date if possible.
+if test -z "$no_default" &&
+   base=$(git merge-base "$gitlab_head" "$upstream_head") &&
+   test "$base" = "$gitlab_head"; then
+	refspecs="$upstream_head:refs/heads/master $refspecs"
+fi
+
+# Exit early if we have nothing to push.
+if test -z "$refspecs"; then
+	echo 'Nothing to push!'
+	exit 0
+fi
+
+# Push.  Save output and exit code.
+echo "Pushing to $remote"
+push_config='-c advice.pushUpdateRejected=false'
+push_stdout=$(git $push_config push $lease_flag --porcelain $dry_run "$remote" $refspecs); push_exit=$?
+echo "$push_stdout"
+
+if test "$push_exit" -ne 0 && test -z "$force"; then
+	# Advise the user to fetch if needed.
+	if echo "$push_stdout" | egrep-q 'stale info'; then
+		echo "
+You have pushed to your branch from another machine; you may be overwriting
+commits unintentionally.  Fetch from the $remote remote and check that you are
+not pushing an outdated branch."
+	fi
+
+	# Advise the user to force-push if needed.
+	if echo "$push_stdout" | egrep-q 'non-fast-forward'; then
+		echo '
+Add "-f" or "--force" to push a rewritten topic.'
+	fi
+fi
+
+# Reproduce the push exit code.
+exit $push_exit
diff --git a/Utilities/GitSetup/setup-gerrit b/Utilities/GitSetup/setup-gerrit
index 9e8fa62..6d46e3c 100755
--- a/Utilities/GitSetup/setup-gerrit
+++ b/Utilities/GitSetup/setup-gerrit
@@ -28,6 +28,7 @@
 #    gerrit.pushurl = Review site push URL with "$username" placeholder
 #    gerrit.remote = Gerrit remote name, if not "gerrit"
 #    gerrit.url = Gerrit project URL, if not "$site/p/$project"
+#                 optionally with "$username" placeholder
 
 die() {
 	echo 1>&2 "$@" ; exit 1
@@ -39,11 +40,12 @@ cd "${BASH_SOURCE%/*}" &&
 # Load the project configuration.
 site=$(git config -f config --get gerrit.site) &&
 project=$(git config -f config --get gerrit.project) &&
-pushurl_=$(git config -f config --get gerrit.pushurl) &&
 remote=$(git config -f config --get gerrit.remote ||
 	 echo "gerrit") &&
-fetchurl=$(git config -f config --get gerrit.url ||
-	   echo "$site/p/$project") ||
+fetchurl_=$(git config -f config --get gerrit.url ||
+	    echo "$site/p/$project") &&
+pushurl_=$(git config -f config --get gerrit.pushurl ||
+	   git config -f config --get gerrit.url) ||
 die 'This project is not configured to use Gerrit.'
 
 # Get current gerrit push URL.
@@ -67,7 +69,7 @@ else
 
 '"$project"' changes must be pushed to our Gerrit Code Review site:
 
-  '"$fetchurl"'
+  '"$site/p/$project"'
 
 Register a Gerrit account and select a username (used below).
 You will need an OpenID:
@@ -96,13 +98,16 @@ Add your SSH public keys at
 	if test -z "$gu"; then
 		gu="$USER"
 	fi &&
+	fetchurl="${fetchurl_/\$username/$gu}" &&
 	if test -z "$pushurl"; then
 		git remote add "$remote" "$fetchurl"
 	else
 		git config remote."$remote".url "$fetchurl"
 	fi &&
 	pushurl="${pushurl_/\$username/$gu}" &&
-	git config remote."$remote".pushurl "$pushurl" &&
+	if test "$pushurl" != "$fetchurl"; then
+		git config remote."$remote".pushurl "$pushurl"
+	fi &&
 	echo 'Remote "'"$remote"'" is now configured to push to
 
   '"$pushurl"'
diff --git a/Utilities/GitSetup/setup-gitlab b/Utilities/GitSetup/setup-gitlab
new file mode 100755
index 0000000..9c7574d
--- /dev/null
+++ b/Utilities/GitSetup/setup-gitlab
@@ -0,0 +1,140 @@
+#!/usr/bin/env bash
+#=============================================================================
+# Copyright 2010-2015 Kitware, Inc.
+#
+# 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.
+#=============================================================================
+
+# Run this script to set up the local Git repository to push to
+# a personal fork for this project in GitLab.
+
+# Project configuration instructions:
+#
+# - Run a GitLab server
+#
+# - Populate adjacent "config" file with:
+#    gitlab.protocol = Top GitLab protocol, if not 'https'
+#    gitlab.host = Top GitLab fully qualified host name
+#    gitlab.site = Top GitLab URL, if not "<protocol>://<host>"
+#    gitlab.group-name = Name of group containing project in GitLab
+#    gitlab.group-path = Path of group containing project in GitLab
+#    gitlab.project-name = Name of project within GitLab group
+#    gitlab.project-path = Path of project within GitLab group
+#    gitlab.url = GitLab push URL with "$username" placeholder,
+#                 if not "<site>/$username/<project-path>.git"
+#    gitlab.pushurl = GitLab push URL with "$username" placeholder,
+#                     if not "git@<host>:$username/<project-path>.git"
+#    gitlab.remote = GitLab remote name, if not "gitlab"
+
+die() {
+	echo 1>&2 "$@" ; exit 1
+}
+
+# Make sure we are inside the repository.
+cd "${BASH_SOURCE%/*}" &&
+
+# Load the project configuration.
+protocol=$(git config -f config --get gitlab.protocol ||
+	   echo "https") &&
+host=$(git config -f config --get gitlab.host) &&
+site=$(git config -f config --get gitlab.site ||
+       echo "$protocol://$host") &&
+group_path=$(git config -f config --get gitlab.group-path) &&
+group_name=$(git config -f config --get gitlab.group-name) &&
+project_name=$(git config -f config --get gitlab.project-name) &&
+project_path=$(git config -f config --get gitlab.project-path) &&
+pushurl_=$(git config -f config --get gitlab.pushurl ||
+	   echo "git@$host:\$username/$project_path.git") &&
+remote=$(git config -f config --get gitlab.remote ||
+	 echo "gitlab") &&
+fetchurl_=$(git config -f config --get gitlab.url ||
+	    echo "$site/\$username/$project_path.git") ||
+die 'This project is not configured to use GitLab.'
+
+# Get current gitlab push URL.
+pushurl=$(git config --get remote."$remote".pushurl ||
+	  git config --get remote."$remote".url || echo '') &&
+
+# Tell user about current configuration.
+if test -n "$pushurl"; then
+	echo 'Remote "'"$remote"'" is currently configured to push to
+
+  '"$pushurl"'
+' &&
+	read -ep 'Reconfigure GitLab? [y/N]: ' ans &&
+	if [ "$ans" == "y" ] || [ "$ans" == "Y" ]; then
+		setup=1
+	else
+		setup=''
+	fi
+else
+	echo 'Remote "'"$remote"'" is not yet configured.
+' &&
+	read -ep 'Configure GitLab to contribute to '"$project_name"'? [Y/n]: ' ans &&
+	if [ "$ans" == "n" ] || [ "$ans" == "N" ]; then
+		exit 0
+	else
+		setup=1
+	fi
+fi &&
+
+setup_instructions='Add your SSH public keys at
+
+  '"$site"'/profile/keys
+
+Then visit the main repository at:
+
+  '"$site/$group_path/$project_path"'
+
+and use the Fork button in the upper right.
+'
+
+# Perform setup if necessary.
+if test -n "$setup"; then
+	echo 'Sign-in to GitLab to get/set your username at
+
+  '"$site/profile/account"'
+
+'"$setup_instructions" &&
+	read -ep "GitLab username? [$USER]: " gu &&
+	if test -z "$gu"; then
+		gu="$USER"
+	fi &&
+	fetchurl="${fetchurl_/\$username/$gu}" &&
+	if test -z "$pushurl"; then
+		git remote add "$remote" "$fetchurl"
+	else
+		git config remote."$remote".url "$fetchurl"
+	fi &&
+	pushurl="${pushurl_/\$username/$gu}" &&
+	git config remote."$remote".pushurl "$pushurl" &&
+	echo 'Remote "'"$remote"'" is now configured to push to
+
+  '"$pushurl"'
+'
+fi &&
+
+# Optionally test GitLab access.
+if test -n "$pushurl"; then
+	read -ep 'Test access to GitLab (SSH)? [y/N]: ' ans &&
+	if [ "$ans" == "y" ] || [ "$ans" == "Y" ]; then
+		echo -n 'Testing GitLab access by SSH...'
+		if git ls-remote --heads "$pushurl" >/dev/null; then
+			echo 'passed.'
+		else
+			echo 'failed.' &&
+			die 'Could not access your GitLab fork of this project.
+'"$setup_instructions"
+		fi
+	fi
+fi
diff --git a/Utilities/GitSetup/setup-hooks b/Utilities/GitSetup/setup-hooks
index c07985a..ca07712 100755
--- a/Utilities/GitSetup/setup-hooks
+++ b/Utilities/GitSetup/setup-hooks
@@ -55,6 +55,7 @@ fi &&
 # Populate ".git/hooks".
 echo 'Setting up git hooks...' &&
 git_dir=$(git rev-parse --git-dir) &&
+mkdir -p "$git_dir/hooks" &&
 cd "$git_dir/hooks" &&
 if ! test -e .git; then
 	git init -q || die 'Could not run git init for hooks.'
diff --git a/Utilities/GitSetup/setup-stage b/Utilities/GitSetup/setup-stage
index 323e47a..ce6ec45 100755
--- a/Utilities/GitSetup/setup-stage
+++ b/Utilities/GitSetup/setup-stage
@@ -37,8 +37,8 @@ die() {
 cd "${BASH_SOURCE%/*}" &&
 
 # Load the project configuration.
-fetchurl=$(git config -f config --get stage.url) &&
-pushurl_=$(git config -f config --get stage.pushurl || echo '') &&
+fetchurl_=$(git config -f config --get stage.url) &&
+pushurl_=$(git config -f config --get stage.pushurl || echo "$fetchurl_") &&
 remote=$(git config -f config --get stage.remote || echo 'stage') ||
 die 'This project is not configured to use a topic stage.'
 
@@ -65,13 +65,16 @@ fi
 # Perform setup if necessary.
 if test -n "$setup"; then
 	echo 'Setting up the topic stage...' &&
+	fetchurl="${fetchurl_}" &&
 	if test -z "$pushurl"; then
 		git remote add "$remote" "$fetchurl"
 	else
 		git config remote."$remote".url "$fetchurl"
 	fi &&
 	pushurl="${pushurl_}" &&
-	git config remote."$remote".pushurl "$pushurl" &&
+	if test "$pushurl" != "$fetchurl"; then
+		git config remote."$remote".pushurl "$pushurl"
+	fi &&
 	echo 'Remote "'"$remote"'" is now configured to push to
 
   '"$pushurl"'
diff --git a/Utilities/GitSetup/setup-upstream b/Utilities/GitSetup/setup-upstream
new file mode 100755
index 0000000..92ce1da
--- /dev/null
+++ b/Utilities/GitSetup/setup-upstream
@@ -0,0 +1,104 @@
+#!/usr/bin/env bash
+#=============================================================================
+# Copyright 2010-2015 Kitware, Inc.
+#
+# 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.
+#=============================================================================
+
+# Run this script to set up the local Git repository to use the
+# preferred upstream repository URLs.
+
+# Project configuration instructions:
+#
+# - Populate adjacent "config" file with:
+#    upstream.url = Preferred fetch url for upstream remote
+#    upstream.remote = Preferred name for upstream remote, if not "origin"
+
+die() {
+	echo 1>&2 "$@" ; exit 1
+}
+
+# Make sure we are inside the repository.
+cd "${BASH_SOURCE%/*}" &&
+
+# Load the project configuration.
+url=$(git config -f config --get upstream.url) &&
+remote=$(git config -f config --get upstream.remote ||
+	 echo 'origin') ||
+die 'This project is not configured to use a preferred upstream repository.'
+
+# Get current upstream URLs.
+fetchurl=$(git config --get remote."$remote".url || echo '') &&
+pushurl=$(git config --get remote."$remote".pushurl || echo '') &&
+
+if test "$fetchurl" = "$url"; then
+	echo 'Remote "'"$remote"'" already uses recommended upstream repository.'
+	exit 0
+fi
+
+upstream_recommend='
+We recommended configuring the "'"$remote"'" remote to fetch from upstream at
+
+  '"$url"'
+'
+
+# Tell user about current configuration.
+if test -n "$fetchurl"; then
+	echo 'Remote "'"$remote"'" is currently configured to fetch from
+
+  '"$fetchurl"'
+' &&
+	if test -n "$pushurl"; then
+		echo 'and push to
+
+  '"$pushurl"
+	fi &&
+	echo "$upstream_recommend" &&
+	if test -n "$pushurl"; then
+		echo 'and to never push to it directly.
+'
+	fi &&
+
+	read -ep 'Reconfigure "'"$remote"'" remote as recommended? [y/N]: ' ans &&
+	if [ "$ans" == "y" ] || [ "$ans" == "Y" ]; then
+		setup=1
+	else
+		setup=''
+	fi
+else
+	echo 'Remote "'"$remote"'" is not yet configured.' &&
+	echo "$upstream_recommend" &&
+	read -ep 'Configure "'"$remote"'" remote as recommended? [Y/n]: ' ans &&
+	if [ "$ans" == "n" ] || [ "$ans" == "N" ]; then
+		exit 0
+	else
+		setup=1
+	fi
+fi &&
+
+# Perform setup if necessary.
+if test -n "$setup"; then
+	if test -z "$fetchurl"; then
+		git remote add "$remote" "$url"
+	else
+		git config remote."$remote".url "$url" &&
+		if old=$(git config --get remote."$remote".pushurl); then
+			git config --unset remote."$remote".pushurl ||
+			echo 'Warning: failed to unset remote.'"$remote"'.pushurl'
+		fi
+	fi &&
+	echo 'Remote "'"$remote"'" is now configured to fetch from
+
+  '"$url"'
+'
+fi
diff --git a/Utilities/KWIML/test/CMakeLists.txt b/Utilities/KWIML/test/CMakeLists.txt
index 4f6f37b..1bf93bb 100644
--- a/Utilities/KWIML/test/CMakeLists.txt
+++ b/Utilities/KWIML/test/CMakeLists.txt
@@ -10,7 +10,7 @@ endif()
 # Suppress printf/scanf format warnings; we test if the sizes match.
 foreach(lang C CXX)
   if(KWIML_LANGUAGE_${lang} AND CMAKE_${lang}_COMPILER_ID STREQUAL "GNU")
-    set(CMAKE_${lang}_FLAGS "${CMAKE_${lang}_FLAGS} -Wno-format")
+    set(CMAKE_${lang}_FLAGS "${CMAKE_${lang}_FLAGS} -Wno-format -Wno-format-security")
   endif()
 endforeach()
 
diff --git a/Utilities/KWStyle/CMake.kws.xml.in b/Utilities/KWStyle/CMake.kws.xml.in
deleted file mode 100644
index c2b4429..0000000
--- a/Utilities/KWStyle/CMake.kws.xml.in
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<Description>
-<LineLength>79</LineLength>
-<!--
-<Header>"@CMake_SOURCE_DIR@/Utilities/KWStyle/Headers",false,true</Header>
-<Functions>
-<regex>[A-Z]</regex>
-<length>100</length>
-</Functions>
--->
-</Description>
diff --git a/Utilities/KWStyle/CMakeFiles.txt.in b/Utilities/KWStyle/CMakeFiles.txt.in
deleted file mode 100644
index a95aac6..0000000
--- a/Utilities/KWStyle/CMakeFiles.txt.in
+++ /dev/null
@@ -1,15 +0,0 @@
-"@CMake_SOURCE_DIR@/Source/*.txx"
-"@CMake_SOURCE_DIR@/Source/*.cxx"
-"@CMake_SOURCE_DIR@/Source/*.h*"
-"@CMake_SOURCE_DIR@/Source/CPack/*.txx"
-"@CMake_SOURCE_DIR@/Source/CPack/*.cxx"
-"@CMake_SOURCE_DIR@/Source/CPack/*.h*"
-"@CMake_SOURCE_DIR@/Source/CTest/*.txx"
-"@CMake_SOURCE_DIR@/Source/CTest/*.cxx"
-"@CMake_SOURCE_DIR@/Source/CTest/*.h*"
-"@CMake_SOURCE_DIR@/Source/CurseDialog/*.h*"
-"@CMake_SOURCE_DIR@/Source/CurseDialog/*.cxx"
-"@CMake_SOURCE_DIR@/Source/CurseDialog/*.txx"
--f (Lexer\.h)
--f (Lexer\.cxx)
--f (Parser\.cxx)
diff --git a/Utilities/KWStyle/CMakeLists.txt b/Utilities/KWStyle/CMakeLists.txt
deleted file mode 100644
index 3e96c33..0000000
--- a/Utilities/KWStyle/CMakeLists.txt
+++ /dev/null
@@ -1,69 +0,0 @@
-# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
-# file Copyright.txt or https://cmake.org/licensing for details.
-
-#-----------------------------------------------------------------------------
-# CMake uses KWStyle for checking the coding style
-
-# Search for a built-from-source KWStyle under Dashboards/Support on a typical
-# dashboard machines:
-#
-set(home "$ENV{HOME}")
-if(NOT home)
-  string(REPLACE "\\" "/" home "$ENV{USERPROFILE}")
-endif()
-
-find_program(KWSTYLE_EXECUTABLE
-  NAMES KWStyle
-  PATHS
-  "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Kitware Inc.\\KWStyle 1.0.0]/bin"
-  "${home}/Dashboards/Support/KWStyle/bin"
-  )
-mark_as_advanced(KWSTYLE_EXECUTABLE)
-
-set(CMAKE_USE_KWSTYLE_DEFAULT OFF)
-if(KWSTYLE_EXECUTABLE)
-  set(CMAKE_USE_KWSTYLE_DEFAULT ON)
-endif()
-
-option(CMAKE_USE_KWSTYLE
-  "Add StyleCheck target and KWStyle test: run KWStyle to check for coding standard violations."
-  ${CMAKE_USE_KWSTYLE_DEFAULT})
-mark_as_advanced(CMAKE_USE_KWSTYLE)
-
-if(CMAKE_USE_KWSTYLE)
-  option(KWSTYLE_USE_VIM_FORMAT "Set KWStyle to generate errors with a VIM-compatible format." OFF)
-  option(KWSTYLE_USE_MSVC_FORMAT "Set KWStyle to generate errors with a VisualStudio-compatible format." OFF)
-  mark_as_advanced(KWSTYLE_USE_VIM_FORMAT)
-  mark_as_advanced(KWSTYLE_USE_MSVC_FORMAT)
-
-  if(KWSTYLE_USE_VIM_FORMAT)
-    set(KWSTYLE_ARGUMENTS -vim ${KWSTYLE_ARGUMENTS})
-  endif()
-
-  if(KWSTYLE_USE_MSVC_FORMAT)
-    set(KWSTYLE_ARGUMENTS -msvc ${KWSTYLE_ARGUMENTS})
-  endif()
-
-  configure_file(${CMake_SOURCE_DIR}/Utilities/KWStyle/CMake.kws.xml.in
-               ${CMake_BINARY_DIR}/CMake.kws.xml)
-  configure_file(${CMake_SOURCE_DIR}/Utilities/KWStyle/CMakeMoreChecks.kws.xml.in
-               ${CMake_BINARY_DIR}/CMakeMoreChecks.kws.xml)
-
-  configure_file(${CMake_SOURCE_DIR}/Utilities/KWStyle/CMakeFiles.txt.in
-                 ${CMake_BINARY_DIR}/CMakeKWSFiles.txt)
-
-  add_custom_command(
-    OUTPUT ${CMake_BINARY_DIR}/KWStyleReport.txt
-    COMMAND ${KWSTYLE_EXECUTABLE}
-    ARGS    -xml ${CMake_BINARY_DIR}/CMake.kws.xml -o ${CMake_SOURCE_DIR}/Utilities/KWStyle/CMakeOverwrite.txt -v ${KWSTYLE_ARGUMENTS} -D ${CMake_BINARY_DIR}/CMakeKWSFiles.txt
-    COMMENT "Coding Style Checker"
-    )
-
-  add_custom_target(MoreStyleChecks
-    COMMAND ${KWSTYLE_EXECUTABLE}
-    -xml ${CMake_BINARY_DIR}/CMakeMoreChecks.kws.xml -html ${CMake_BINARY_DIR}/html -o ${CMake_SOURCE_DIR}/Utilities/KWStyle/CMakeOverwrite.txt -v ${KWSTYLE_ARGUMENTS} -D ${CMake_BINARY_DIR}/CMakeKWSFiles.txt
-    COMMENT "Coding Style Checker, more checks enabled"
-    )
-
-  add_custom_target(StyleCheck DEPENDS ${CMake_BINARY_DIR}/KWStyleReport.txt)
-endif()
diff --git a/Utilities/KWStyle/CMakeMoreChecks.kws.xml.in b/Utilities/KWStyle/CMakeMoreChecks.kws.xml.in
deleted file mode 100644
index c48e92f..0000000
--- a/Utilities/KWStyle/CMakeMoreChecks.kws.xml.in
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<Description>
-  <ErrorThreshold>10</ErrorThreshold>
-  <LineLength>79</LineLength>
-  <Header>"@CMake_SOURCE_DIR@/Utilities/KWStyle/Headers",false,true</Header>
-  <Functions>
-    <regex>^(cm)?[A-Z]</regex>
-    <length>200</length>
-  </Functions>
-  <InternalVariables>
-    <regex>^[A-Z]</regex>
-    <alignment>0</alignment>
-  </InternalVariables>
-  <SemicolonSpace>0</SemicolonSpace>
-  <DeclarationOrder>
-    <public>0</public>
-    <protected>1</protected>
-    <private>2</private>
-  </DeclarationOrder>
-  <Tabs>1</Tabs>
-  <EmptyLines>4</EmptyLines>
-  <StatementPerLine>
-    <maxNumber>1</maxNumber>
-    <checkInline>0</checkInline>
-  </StatementPerLine>
-  <VariablePerLine>
-    <maxNumber>1</maxNumber>
-  </VariablePerLine>
-  <BadCharacters>true</BadCharacters>
-</Description>
diff --git a/Utilities/Release/README b/Utilities/Release/README
index ed1d52e..11de1c3 100644
--- a/Utilities/Release/README
+++ b/Utilities/Release/README
@@ -1,7 +1,7 @@
 To create a cmake release, make sure the "release" tag is pointing to the
 expected git commit:
 
-http://cmake.org/gitweb?p=cmake.git;a=shortlog;h=refs/heads/release
+https://cmake.org/gitweb?p=cmake.git;a=shortlog;h=refs/heads/release
 
 Then as kitware at hythloth, using an up-to-date CMake:
 
diff --git a/Utilities/Release/WiX/WIX.template.in b/Utilities/Release/WiX/WIX.template.in
index 094999f..fe176ca 100644
--- a/Utilities/Release/WiX/WIX.template.in
+++ b/Utilities/Release/WiX/WIX.template.in
@@ -36,7 +36,18 @@
         <WixVariable Id="WixUIDialogBmp" Value="$(var.CPACK_WIX_UI_DIALOG)"/>
         <?endif?>
 
-        <FeatureRef Id="ProductFeature"/>
+        <DirectoryRef Id="TARGETDIR">
+            <Component Id="CMakeRegistry">
+                <RegistryKey Root="HKLM" Key="Software\Kitware\CMake">
+                    <RegistryValue Type="string" Name="InstallDir"
+                        Value="[INSTALL_ROOT]" KeyPath="yes"/>
+                 </RegistryKey>
+            </Component>
+        </DirectoryRef>
+
+        <FeatureRef Id="ProductFeature">
+            <ComponentRef Id="CMakeRegistry"/>
+        </FeatureRef>
 
         <UIRef Id="$(var.CPACK_WIX_UI_REF)" />
 
diff --git a/Utilities/Release/linux64_release.cmake b/Utilities/Release/linux64_release.cmake
index b72fc12..feba2a5 100644
--- a/Utilities/Release/linux64_release.cmake
+++ b/Utilities/Release/linux64_release.cmake
@@ -2,6 +2,7 @@ set(PROCESSORS 4)
 set(BOOTSTRAP_ARGS "--docdir=doc/cmake")
 set(HOST linux64)
 set(MAKE_PROGRAM "make")
+set(CPACK_BINARY_GENERATORS "STGZ TGZ")
 set(CC /opt/gcc-6.1.0/bin/gcc)
 set(CXX /opt/gcc-6.1.0/bin/g++)
 set(CFLAGS   "")
@@ -28,9 +29,9 @@ CURSES_LIBRARY:FILEPATH=/home/kitware/ncurses-5.9/lib/libncurses.a
 CURSES_INCLUDE_PATH:PATH=/home/kitware/ncurses-5.9/include
 FORM_LIBRARY:FILEPATH=/home/kitware/ncurses-5.9/lib/libform.a
 CMAKE_USE_OPENSSL:BOOL=ON
-OPENSSL_CRYPTO_LIBRARY:FILEPATH=/home/kitware/openssl-1.0.2h/lib/libcrypto.a
-OPENSSL_INCLUDE_DIR:PATH=/home/kitware/openssl-1.0.2h/include
-OPENSSL_SSL_LIBRARY:FILEPATH=/home/kitware/openssl-1.0.2h/lib/libssl.a
+OPENSSL_CRYPTO_LIBRARY:FILEPATH=/home/kitware/openssl-1.0.2j/lib/libcrypto.a
+OPENSSL_INCLUDE_DIR:PATH=/home/kitware/openssl-1.0.2j/include
+OPENSSL_SSL_LIBRARY:FILEPATH=/home/kitware/openssl-1.0.2j/lib/libssl.a
 PYTHON_EXECUTABLE:FILEPATH=/usr/bin/python3
 CPACK_SYSTEM_NAME:STRING=Linux-x86_64
 BUILD_QtDialog:BOOL:=TRUE
diff --git a/Utilities/Release/osx_release.cmake b/Utilities/Release/osx_release.cmake
index 27c820f..88ea39b 100644
--- a/Utilities/Release/osx_release.cmake
+++ b/Utilities/Release/osx_release.cmake
@@ -4,7 +4,7 @@ set(BOOTSTRAP_ARGS "--prefix=/ --docdir=doc/cmake")
 set(HOST dragnipur)
 set(MAKE_PROGRAM "make")
 set(MAKE "${MAKE_PROGRAM} -j5")
-set(CPACK_BINARY_GENERATORS "DragNDrop TGZ TZ")
+set(CPACK_BINARY_GENERATORS "DragNDrop TGZ")
 set(CPACK_SOURCE_GENERATORS "TGZ TZ")
 set(CPACK_DMG_FORMAT "UDBZ") #build using bzip2 for smaller package size
 set(CC clang)
diff --git a/Utilities/Release/upload_release.cmake b/Utilities/Release/upload_release.cmake
index 1485d9c..c49cb4f 100644
--- a/Utilities/Release/upload_release.cmake
+++ b/Utilities/Release/upload_release.cmake
@@ -1,6 +1,6 @@
 set(CTEST_RUN_CURRENT_SCRIPT 0)
 if(NOT VERSION)
- set(VERSION 3.7)
+ set(VERSION 3.8)
 endif()
 if(NOT DEFINED PROJECT_PREFIX)
   set(PROJECT_PREFIX cmake-${VERSION})
diff --git a/Utilities/Scripts/clang-format.bash b/Utilities/Scripts/clang-format.bash
index a7080fc..edcda77 100755
--- a/Utilities/Scripts/clang-format.bash
+++ b/Utilities/Scripts/clang-format.bash
@@ -1,6 +1,6 @@
 #!/usr/bin/env bash
 #=============================================================================
-# Copyright 2015-2016 Kitware, Inc.
+# Copyright 2015-2017 Kitware, Inc.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
@@ -106,33 +106,12 @@ case "$mode" in
     *) die "invalid mode: $mode" ;;
 esac
 
-# Filter sources to which our style should apply.
-$git_ls -z -- '*.c' '*.cc' '*.cpp' '*.cxx' '*.h' '*.hh' '*.hpp' '*.hxx' |
+# List files as selected above.
+$git_ls |
 
-  # Exclude lexer/parser generator input and output.
-  egrep -z -v '^Source/cmCommandArgumentLexer\.' |
-  egrep -z -v '^Source/cmCommandArgumentParser(\.y|\.cxx|Tokens\.h)' |
-  egrep -z -v '^Source/cmDependsJavaLexer\.' |
-  egrep -z -v '^Source/cmDependsJavaParser(\.y|\.cxx|Tokens\.h)' |
-  egrep -z -v '^Source/cmExprLexer\.' |
-  egrep -z -v '^Source/cmExprParser(\.y|\.cxx|Tokens\.h)' |
-  egrep -z -v '^Source/cmFortranLexer\.' |
-  egrep -z -v '^Source/cmFortranParser(\.y|\.cxx|Tokens\.h)' |
-  egrep -z -v '^Source/cmListFileLexer(\.in\.l|\.c)' |
-
-  # Exclude third-party sources.
-  egrep -z -v '^Source/(cm_sha2|bindexplib)' |
-  egrep -z -v '^Source/(kwsys|CursesDialog/form)/' |
-  egrep -z -v '^Utilities/(KW|cm).*/' |
-
-  # Exclude reference content.
-  egrep -z -v '^Tests/RunCMake/GenerateExportHeader/reference/' |
-
-  # Exclude manually-formatted sources (e.g. with long lines).
-  egrep -z -v '^Tests/PositionIndependentTargets/pic_test.h' |
-
-  # Exclude sources with encoding not suported by clang-format.
-  egrep -z -v '^Tests/RunCMake/CommandLine/cmake_depends/test_UTF-16LE.h' |
+  # Select sources with our attribute.
+  git check-attr --stdin format.clang-format |
+  sed -n '/: format\.clang-format: set$/ {s/:[^:]*:[^:]*$//p}'  |
 
   # Update sources in-place.
-  xargs -0 "$clang_format" -i
+  xargs -d '\n' "$clang_format" -i
diff --git a/Utilities/Scripts/update-curl.bash b/Utilities/Scripts/update-curl.bash
index 590bd44..22d1d8a 100755
--- a/Utilities/Scripts/update-curl.bash
+++ b/Utilities/Scripts/update-curl.bash
@@ -8,7 +8,7 @@ readonly name="curl"
 readonly ownership="Curl Upstream <curl-library at cool.haxx.se>"
 readonly subtree="Utilities/cmcurl"
 readonly repo="https://github.com/curl/curl.git"
-readonly tag="curl-7_50_1"
+readonly tag="curl-7_51_0"
 readonly shortlog=false
 readonly paths="
   CMake/*
diff --git a/Utilities/Scripts/update-gitsetup.bash b/Utilities/Scripts/update-gitsetup.bash
new file mode 100755
index 0000000..8f0da76
--- /dev/null
+++ b/Utilities/Scripts/update-gitsetup.bash
@@ -0,0 +1,20 @@
+#!/usr/bin/env bash
+
+set -e
+set -x
+shopt -s dotglob
+
+readonly name="GitSetup"
+readonly ownership="GitSetup Upstream <kwrobot at kitware.com>"
+readonly subtree="Utilities/GitSetup"
+readonly repo="https://gitlab.kitware.com/utils/gitsetup.git"
+readonly tag="setup"
+readonly shortlog=false
+readonly paths="
+"
+
+extract_source () {
+    git_archive
+}
+
+. "${BASH_SOURCE%/*}/update-third-party.bash"
diff --git a/Utilities/Scripts/update-kwsys.bash b/Utilities/Scripts/update-kwsys.bash
index 650841f..83da8a4 100755
--- a/Utilities/Scripts/update-kwsys.bash
+++ b/Utilities/Scripts/update-kwsys.bash
@@ -7,7 +7,7 @@ shopt -s dotglob
 readonly name="KWSys"
 readonly ownership="KWSys Upstream <kwrobot at kitware.com>"
 readonly subtree="Source/kwsys"
-readonly repo="http://public.kitware.com/KWSys.git"
+readonly repo="https://gitlab.kitware.com/utils/kwsys.git"
 readonly tag="master"
 readonly shortlog=true
 readonly paths="
diff --git a/Utilities/Scripts/update-librhash.bash b/Utilities/Scripts/update-librhash.bash
new file mode 100755
index 0000000..009ce32
--- /dev/null
+++ b/Utilities/Scripts/update-librhash.bash
@@ -0,0 +1,45 @@
+#!/usr/bin/env bash
+
+set -e
+set -x
+shopt -s dotglob
+
+readonly name="librhash"
+readonly ownership="librhash upstream <kwrobot at kitware.com>"
+readonly subtree="Utilities/cmlibrhash"
+readonly repo="https://github.com/rhash/rhash.git"
+readonly tag="master"
+readonly shortlog=false
+readonly paths="
+  COPYING
+  README
+  librhash/algorithms.c
+  librhash/algorithms.h
+  librhash/byte_order.c
+  librhash/byte_order.h
+  librhash/hex.c
+  librhash/hex.h
+  librhash/md5.c
+  librhash/md5.h
+  librhash/rhash.c
+  librhash/rhash.h
+  librhash/sha1.c
+  librhash/sha1.h
+  librhash/sha256.c
+  librhash/sha256.h
+  librhash/sha3.c
+  librhash/sha3.h
+  librhash/sha512.c
+  librhash/sha512.h
+  librhash/ustd.h
+  librhash/util.h
+"
+
+extract_source () {
+    git_archive
+    pushd "${extractdir}/${name}-reduced"
+    echo "* -whitespace" > .gitattributes
+    popd
+}
+
+. "${BASH_SOURCE%/*}/update-third-party.bash"
diff --git a/Utilities/SetupForDevelopment.sh b/Utilities/SetupForDevelopment.sh
index 0a9df7e..39152bc 100755
--- a/Utilities/SetupForDevelopment.sh
+++ b/Utilities/SetupForDevelopment.sh
@@ -11,3 +11,7 @@ Utilities/GitSetup/tips
 # Rebase master by default
 git config rebase.stat true
 git config branch.master.rebase true
+
+# Record the version of this setup so Git/pre-commit can check it.
+SetupForDevelopment_VERSION=1
+git config hooks.SetupForDevelopment ${SetupForDevelopment_VERSION}
diff --git a/Utilities/Sphinx/apply_qthelp_css_workaround.cmake b/Utilities/Sphinx/apply_qthelp_css_workaround.cmake
index 8b74d12..288f370 100644
--- a/Utilities/Sphinx/apply_qthelp_css_workaround.cmake
+++ b/Utilities/Sphinx/apply_qthelp_css_workaround.cmake
@@ -1,11 +1,15 @@
 
 file(READ "${CSS_DIR}/basic.css" BasicCssContent)
 
-file(READ "${CSS_DIR}/default.css" DefaultCssContent)
-string(REPLACE
-  "@import url(\"basic.css\")" "${BasicCssContent}"
-  DefaultCssContent "${DefaultCssContent}"
-)
+if(EXISTS "${CSS_DIR}/default.css")
+  file(READ "${CSS_DIR}/default.css" DefaultCssContent)
+  string(REPLACE
+    "@import url(\"basic.css\")" "${BasicCssContent}"
+    DefaultCssContent "${DefaultCssContent}"
+  )
+else()
+  set(DefaultCssContent "${BasicCssContent}")
+endif()
 
 file(READ "${CSS_DIR}/cmake.css" CMakeCssContent)
 string(REPLACE
diff --git a/Utilities/Sphinx/cmake.py b/Utilities/Sphinx/cmake.py
index edc7667..6f273f9 100644
--- a/Utilities/Sphinx/cmake.py
+++ b/Utilities/Sphinx/cmake.py
@@ -46,7 +46,7 @@ from sphinx.directives import ObjectDescription
 from sphinx.domains import Domain, ObjType
 from sphinx.roles import XRefRole
 from sphinx.util.nodes import make_refnode
-from sphinx import addnodes
+from sphinx import addnodes, version_info
 
 class CMakeModule(Directive):
     required_arguments = 1
@@ -123,7 +123,11 @@ class _cmake_index_entry:
         self.desc = desc
 
     def __call__(self, title, targetid, main = 'main'):
-        return ('pair', u'%s ; %s' % (self.desc, title), targetid, main)
+        # See https://github.com/sphinx-doc/sphinx/issues/2673
+        if version_info < (1, 4):
+            return ('pair', u'%s ; %s' % (self.desc, title), targetid, main)
+        else:
+            return ('pair', u'%s ; %s' % (self.desc, title), targetid, main, None)
 
 _cmake_index_objs = {
     'command':    _cmake_index_entry('command'),
diff --git a/Utilities/cmThirdParty.h.in b/Utilities/cmThirdParty.h.in
index 210e727..a547f0d 100644
--- a/Utilities/cmThirdParty.h.in
+++ b/Utilities/cmThirdParty.h.in
@@ -13,6 +13,7 @@
 #cmakedefine CMAKE_USE_SYSTEM_LIBLZMA
 #cmakedefine CMAKE_USE_SYSTEM_FORM
 #cmakedefine CMAKE_USE_SYSTEM_JSONCPP
+#cmakedefine CMAKE_USE_SYSTEM_LIBRHASH
 #cmakedefine CMAKE_USE_SYSTEM_LIBUV
 #cmakedefine CTEST_USE_XMLRPC
 
diff --git a/Utilities/cm_rhash.h b/Utilities/cm_rhash.h
new file mode 100644
index 0000000..c793627
--- /dev/null
+++ b/Utilities/cm_rhash.h
@@ -0,0 +1,14 @@
+/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
+   file Copyright.txt or https://cmake.org/licensing for details.  */
+#ifndef cm_rhash_h
+#define cm_rhash_h
+
+/* Use the LibRHash library configured for CMake.  */
+#include "cmThirdParty.h"
+#ifdef CMAKE_USE_SYSTEM_LIBRHASH
+#include <rhash.h>
+#else
+#include <cmlibrhash/librhash/rhash.h>
+#endif
+
+#endif
diff --git a/Utilities/cmcurl/CMake/CurlSymbolHiding.cmake b/Utilities/cmcurl/CMake/CurlSymbolHiding.cmake
new file mode 100644
index 0000000..9f7d296
--- /dev/null
+++ b/Utilities/cmcurl/CMake/CurlSymbolHiding.cmake
@@ -0,0 +1,61 @@
+include(CheckCSourceCompiles)
+
+option(CURL_HIDDEN_SYMBOLS "Set to ON to hide libcurl internal symbols (=hide all symbols that aren't officially external)." ON)
+mark_as_advanced(CURL_HIDDEN_SYMBOLS)
+
+if(CURL_HIDDEN_SYMBOLS)
+    set(SUPPORTS_SYMBOL_HIDING FALSE)
+
+    if(CMAKE_C_COMPILER_ID MATCHES "Clang")
+        set(SUPPORTS_SYMBOL_HIDING TRUE)
+        set(_SYMBOL_EXTERN "__attribute__ ((__visibility__ (\"default\")))")
+        set(_CFLAG_SYMBOLS_HIDE "-fvisibility=hidden")
+    elseif(CMAKE_COMPILER_IS_GNUCC)
+        if(NOT CMAKE_VERSION VERSION_LESS 2.8.10)
+            set(GCC_VERSION ${CMAKE_C_COMPILER_VERSION})
+        else()
+            execute_process(COMMAND ${CMAKE_C_COMPILER} -dumpversion
+                            OUTPUT_VARIABLE GCC_VERSION)
+        endif()
+        if(NOT GCC_VERSION VERSION_LESS 3.4)
+            # note: this is considered buggy prior to 4.0 but the autotools don't care, so let's ignore that fact
+            set(SUPPORTS_SYMBOL_HIDING TRUE)
+            set(_SYMBOL_EXTERN "__attribute__ ((__visibility__ (\"default\")))")
+            set(_CFLAG_SYMBOLS_HIDE "-fvisibility=hidden")
+        endif()
+    elseif(CMAKE_C_COMPILER_ID MATCHES "SunPro" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 8.0)
+        set(SUPPORTS_SYMBOL_HIDING TRUE)
+        set(_SYMBOL_EXTERN "__global")
+        set(_CFLAG_SYMBOLS_HIDE "-xldscope=hidden")
+    elseif(CMAKE_C_COMPILER_ID MATCHES "Intel" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 9.0)
+        # note: this should probably just check for version 9.1.045 but I'm not 100% sure
+        #       so let's to it the same way autotools do.
+        set(SUPPORTS_SYMBOL_HIDING TRUE)
+        set(_SYMBOL_EXTERN "__attribute__ ((__visibility__ (\"default\")))")
+        set(_CFLAG_SYMBOLS_HIDE "-fvisibility=hidden")
+        check_c_source_compiles("#include <stdio.h>
+            int main (void) { printf(\"icc fvisibility bug test\"); return 0; }" _no_bug)
+        if(NOT _no_bug)
+            set(SUPPORTS_SYMBOL_HIDING FALSE)
+            set(_SYMBOL_EXTERN "")
+            set(_CFLAG_SYMBOLS_HIDE "")
+        endif()
+    elseif(MSVC)
+        set(SUPPORTS_SYMBOL_HIDING TRUE)
+    endif()
+
+    set(HIDES_CURL_PRIVATE_SYMBOLS ${SUPPORTS_SYMBOL_HIDING})
+elseif(MSVC)
+    if(NOT CMAKE_VERSION VERSION_LESS 3.7)
+        set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS TRUE) #present since 3.4.3 but broken
+        set(HIDES_CURL_PRIVATE_SYMBOLS FALSE)
+    else()
+        message(WARNING "Hiding private symbols regardless CURL_HIDDEN_SYMBOLS being disabled.")
+        set(HIDES_CURL_PRIVATE_SYMBOLS TRUE)
+    endif()
+elseif()
+    set(HIDES_CURL_PRIVATE_SYMBOLS FALSE)
+endif()
+
+set(CURL_CFLAG_SYMBOLS_HIDE ${_CFLAG_SYMBOLS_HIDE})
+set(CURL_EXTERN_SYMBOL ${_SYMBOL_EXTERN})
diff --git a/Utilities/cmcurl/CMake/FindNGHTTP2.cmake b/Utilities/cmcurl/CMake/FindNGHTTP2.cmake
new file mode 100644
index 0000000..4e566cf
--- /dev/null
+++ b/Utilities/cmcurl/CMake/FindNGHTTP2.cmake
@@ -0,0 +1,18 @@
+include(FindPackageHandleStandardArgs)
+
+find_path(NGHTTP2_INCLUDE_DIR "nghttp2/nghttp2.h")
+
+find_library(NGHTTP2_LIBRARY NAMES nghttp2)
+
+find_package_handle_standard_args(NGHTTP2
+    FOUND_VAR
+      NGHTTP2_FOUND
+    REQUIRED_VARS
+      NGHTTP2_LIBRARY
+      NGHTTP2_INCLUDE_DIR
+    FAIL_MESSAGE
+      "Could NOT find NGHTTP2"
+)
+
+set(NGHTTP2_INCLUDE_DIRS ${NGHTTP2_INCLUDE_DIR} )
+set(NGHTTP2_LIBRARIES ${NGHTTP2_LIBRARY})
diff --git a/Utilities/cmcurl/CMakeLists.txt b/Utilities/cmcurl/CMakeLists.txt
index 9031181..262554d 100644
--- a/Utilities/cmcurl/CMakeLists.txt
+++ b/Utilities/cmcurl/CMakeLists.txt
@@ -65,7 +65,7 @@ endif()
 #                            | (__| |_| |  _ <| |___
 #                             \___|\___/|_| \_\_____|
 #
-# Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel at haxx.se>, et al.
+# Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
 #
 # This software is licensed as described in the file COPYING, which
 # you should have received as part of this distribution. The terms
@@ -79,7 +79,7 @@ endif()
 # KIND, either express or implied.
 #
 ###########################################################################
-# cURL/libcurl CMake script
+# curl/libcurl CMake script
 # by Tetetest and Sukender (Benoit Neil)
 
 # TODO:
@@ -102,6 +102,7 @@ cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
 set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/CMake;${CMAKE_MODULE_PATH}")
 include(Utilities)
 include(Macros)
+include(CMakeDependentOption)
 
 project( CURL C )
 
@@ -135,11 +136,17 @@ set(OS "\"${CMAKE_SYSTEM_NAME}\"")
 include_directories(${PROJECT_BINARY_DIR}/include/curl)
 include_directories( ${CURL_SOURCE_DIR}/include )
 
-option(BUILD_CURL_EXE "Set to ON to build cURL executable." ON)
+option(BUILD_CURL_EXE "Set to ON to build curl executable." ON)
 option(CURL_STATICLIB "Set to ON to build libcurl with static linking." OFF)
 option(ENABLE_ARES "Set to ON to enable c-ares support" OFF)
-option(ENABLE_THREADED_RESOLVER "Set to ON to enable POSIX threaded DNS lookup" OFF)
-
+if(WIN32)
+  CMAKE_DEPENDENT_OPTION(ENABLE_THREADED_RESOLVER
+                         "Set to ON to enable threaded DNS lookup"
+                         ON "NOT ENABLE_ARES"
+                         OFF)
+else()
+  option(ENABLE_THREADED_RESOLVER "Set to ON to enable POSIX threaded DNS lookup" OFF)
+endif()
 option(ENABLE_DEBUG "Set to ON to enable curl debug features" OFF)
 option(ENABLE_CURLDEBUG "Set to ON to build with TrackMemory feature enabled" OFF)
 
@@ -176,8 +183,9 @@ if(MSVC)
   mark_as_advanced(BUILD_RELEASE_DEBUG_DIRS)
 endif()
 
-option(CURL_HIDDEN_SYMBOLS "Set to ON to hide libcurl internal symbols (=hide all symbols that aren't officially external)." ON)
-mark_as_advanced(CURL_HIDDEN_SYMBOLS)
+if(0) # This code not needed for building within CMake.
+include(CurlSymbolHiding)
+endif()
 
 option(HTTP_ONLY "disables all protocols except HTTP (This overrides all CURL_DISABLE_* options)" OFF)
 mark_as_advanced(HTTP_ONLY)
@@ -313,13 +321,17 @@ if(WIN32)
 endif(WIN32)
 
 if(ENABLE_THREADED_RESOLVER)
-  check_include_file_concat("pthread.h" HAVE_PTHREAD_H)
-  if(HAVE_PTHREAD_H)
-    set(CMAKE_THREAD_PREFER_PTHREAD 1)
-    find_package(Threads)
-    if(CMAKE_USE_PTHREADS_INIT)
-      set(CURL_LIBS ${CURL_LIBS} ${CMAKE_THREAD_LIBS_INIT})
-      set(USE_THREADS_POSIX 1)
+  if(WIN32)
+    set(USE_THREADS_WIN32 ON)
+  else()
+    check_include_file_concat("pthread.h" HAVE_PTHREAD_H)
+    if(HAVE_PTHREAD_H)
+      set(CMAKE_THREAD_PREFER_PTHREAD 1)
+      find_package(Threads)
+      if(CMAKE_USE_PTHREADS_INIT)
+        set(CURL_LIBS ${CURL_LIBS} ${CMAKE_THREAD_LIBS_INIT})
+        set(USE_THREADS_POSIX 1)
+      endif()
     endif()
   endif()
 endif()
@@ -411,6 +423,13 @@ elseif(APPLE)
   endif()
 endif()
 
+option(USE_NGHTTP2 "Use Nghttp2 library" OFF)
+if(USE_NGHTTP2)
+  find_package(NGHTTP2 REQUIRED)
+  include_directories(${NGHTTP2_INCLUDE_DIRS})
+  list(APPEND CURL_LIBS ${NGHTTP2_LIBRARIES})
+endif()
+
 if(NOT CURL_DISABLE_LDAP)
   if(WIN32)
     option(USE_WIN32_LDAP "Use Windows LDAP implementation" ON)
@@ -521,13 +540,13 @@ if(NOT CURL_DISABLE_LDAPS)
 endif()
 
 # Check for idn
-check_library_exists_concat("idn" idna_to_ascii_lz HAVE_LIBIDN)
+check_library_exists_concat("idn2" idn2_lookup_ul HAVE_LIBIDN2)
 
 # Check for symbol dlopen (same as HAVE_LIBDL)
 check_library_exists("${CURL_LIBS}" dlopen "" HAVE_DLOPEN)
 
 if(0) # This code not needed for building within CMake.
-option(CURL_ZLIB "Set to ON to enable building cURL with zlib support." ON)
+option(CURL_ZLIB "Set to ON to enable building curl with zlib support." ON)
 set(HAVE_LIBZ OFF)
 set(HAVE_ZLIB_H OFF)
 set(HAVE_ZLIB OFF)
@@ -707,7 +726,7 @@ check_include_file_concat("des.h"            HAVE_DES_H)
 check_include_file_concat("err.h"            HAVE_ERR_H)
 check_include_file_concat("errno.h"          HAVE_ERRNO_H)
 check_include_file_concat("fcntl.h"          HAVE_FCNTL_H)
-check_include_file_concat("idn-free.h"       HAVE_IDN_FREE_H)
+check_include_file_concat("idn2.h"           HAVE_IDN2_H)
 check_include_file_concat("ifaddrs.h"        HAVE_IFADDRS_H)
 check_include_file_concat("io.h"             HAVE_IO_H)
 check_include_file_concat("krb.h"            HAVE_KRB_H)
@@ -737,7 +756,6 @@ check_include_file_concat("stropts.h"        HAVE_STROPTS_H)
 check_include_file_concat("termio.h"         HAVE_TERMIO_H)
 check_include_file_concat("termios.h"        HAVE_TERMIOS_H)
 check_include_file_concat("time.h"           HAVE_TIME_H)
-check_include_file_concat("tld.h"            HAVE_TLD_H)
 check_include_file_concat("unistd.h"         HAVE_UNISTD_H)
 check_include_file_concat("utime.h"          HAVE_UTIME_H)
 check_include_file_concat("x509.h"           HAVE_X509_H)
@@ -751,9 +769,6 @@ check_include_file_concat("netinet/if_ether.h" HAVE_NETINET_IF_ETHER_H)
 check_include_file_concat("stdint.h"        HAVE_STDINT_H)
 check_include_file_concat("sockio.h"        HAVE_SOCKIO_H)
 check_include_file_concat("sys/utsname.h"   HAVE_SYS_UTSNAME_H)
-check_include_file_concat("idna.h"          HAVE_IDNA_H)
-
-
 
 check_type_size(size_t  SIZEOF_SIZE_T)
 check_type_size(ssize_t  SIZEOF_SSIZE_T)
@@ -763,7 +778,6 @@ check_type_size("short"  SIZEOF_SHORT)
 check_type_size("int"  SIZEOF_INT)
 check_type_size("__int64"  SIZEOF___INT64)
 check_type_size("time_t"  SIZEOF_TIME_T)
-check_type_size("off_t"  SIZEOF_OFF_T)
 
 # Make public versions of some type sizes for curlbuild.h.
 foreach(t INT LONG LONG_LONG SSIZE_T)
@@ -823,8 +837,6 @@ if(CMAKE_USE_OPENSSL)
   check_symbol_exists(RAND_status   "${CURL_INCLUDES}" HAVE_RAND_STATUS)
   check_symbol_exists(RAND_screen   "${CURL_INCLUDES}" HAVE_RAND_SCREEN)
   check_symbol_exists(RAND_egd      "${CURL_INCLUDES}" HAVE_RAND_EGD)
-  check_symbol_exists(CRYPTO_cleanup_all_ex_data "${CURL_INCLUDES}"
-    HAVE_CRYPTO_CLEANUP_ALL_EX_DATA)
   if(HAVE_LIBCRYPTO AND HAVE_LIBSSL)
     set(USE_OPENSSL 1)
   endif(HAVE_LIBCRYPTO AND HAVE_LIBSSL)
@@ -854,9 +866,6 @@ check_symbol_exists(pipe           "${CURL_INCLUDES}" HAVE_PIPE)
 check_symbol_exists(ftruncate      "${CURL_INCLUDES}" HAVE_FTRUNCATE)
 check_symbol_exists(getprotobyname "${CURL_INCLUDES}" HAVE_GETPROTOBYNAME)
 check_symbol_exists(getrlimit      "${CURL_INCLUDES}" HAVE_GETRLIMIT)
-check_symbol_exists(idn_free       "${CURL_INCLUDES}" HAVE_IDN_FREE)
-check_symbol_exists(idna_strerror  "${CURL_INCLUDES}" HAVE_IDNA_STRERROR)
-check_symbol_exists(tld_strerror   "${CURL_INCLUDES}" HAVE_TLD_STRERROR)
 check_symbol_exists(setlocale      "${CURL_INCLUDES}" HAVE_SETLOCALE)
 check_symbol_exists(setrlimit      "${CURL_INCLUDES}" HAVE_SETRLIMIT)
 check_symbol_exists(fcntl          "${CURL_INCLUDES}" HAVE_FCNTL)
@@ -923,9 +932,14 @@ foreach(CURL_TEST
     )
   curl_internal_test(${CURL_TEST})
 endforeach(CURL_TEST)
+
 if(HAVE_FILE_OFFSET_BITS)
   set(_FILE_OFFSET_BITS 64)
+  set(CMAKE_REQUIRED_FLAGS "-D_FILE_OFFSET_BITS=64")
 endif(HAVE_FILE_OFFSET_BITS)
+check_type_size("off_t"  SIZEOF_OFF_T)
+set(CMAKE_REQUIRED_FLAGS)
+
 foreach(CURL_TEST
     HAVE_GLIBC_STRERROR_R
     HAVE_POSIX_STRERROR_R
@@ -987,16 +1001,6 @@ if(NOT CURL_SPECIAL_LIBZ)
   endif(NOT HAVE_ZLIB_H)
 endif(NOT CURL_SPECIAL_LIBZ)
 
-if(_FILE_OFFSET_BITS)
-  set(_FILE_OFFSET_BITS 64)
-endif(_FILE_OFFSET_BITS)
-set(CMAKE_REQUIRED_FLAGS "-D_FILE_OFFSET_BITS=64")
-set(CMAKE_EXTRA_INCLUDE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/curl/curl.h")
-check_type_size("curl_off_t" SIZEOF_CURL_OFF_T)
-set(CMAKE_EXTRA_INCLUDE_FILES)
-set(CMAKE_REQUIRED_FLAGS)
-
-
 # Check for nonblocking
 set(HAVE_DISABLED_NONBLOCKING 1)
 if(HAVE_FIONBIO OR
@@ -1069,6 +1073,11 @@ if(WIN32)
   add_definitions(-D_WIN32_WINNT=0x0501)
 endif(WIN32)
 
+# For windows, all compilers used by cmake should support large files
+if(WIN32)
+  set(USE_WIN32_LARGE_FILES ON)
+endif(WIN32)
+
 if(MSVC)
   add_definitions(-D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE)
 endif(MSVC)
@@ -1133,8 +1142,10 @@ _add_if("OpenSSL"       SSL_ENABLED AND USE_OPENSSL)
 _add_if("IPv6"          ENABLE_IPV6)
 _add_if("unix-sockets"  USE_UNIX_SOCKETS)
 _add_if("libz"          HAVE_LIBZ)
-_add_if("AsynchDNS"     USE_ARES OR USE_THREADS_POSIX)
-_add_if("IDN"           HAVE_LIBIDN)
+_add_if("AsynchDNS"     USE_ARES OR USE_THREADS_POSIX OR USE_THREADS_WIN32)
+_add_if("IDN"           HAVE_LIBIDN2)
+_add_if("Largefile"     (CURL_SIZEOF_CURL_OFF_T GREATER 4) AND
+                        ((SIZEOF_OFF_T GREATER 4) OR USE_WIN32_LARGE_FILES))
 # TODO SSP1 (WinSSL) check is missing
 _add_if("SSPI"          USE_WINDOWS_SSPI)
 _add_if("GSS-API"       HAVE_GSSAPI)
@@ -1200,9 +1211,7 @@ set(CURL_CA_BUNDLE          "")
 set(CURLVERSION             "${CURL_VERSION}")
 set(ENABLE_SHARED           "yes")
 if(CURL_STATICLIB)
-  # Broken: LIBCURL_LIBS below; .a lib is not built
-  message(WARNING "Static linking is broken!")
-  set(ENABLE_STATIC         "no")
+  set(ENABLE_STATIC         "yes")
 else()
   set(ENABLE_STATIC         "no")
 endif()
@@ -1211,9 +1220,12 @@ set(includedir              "\${prefix}/include")
 set(LDFLAGS                 "${CMAKE_SHARED_LINKER_FLAGS}")
 set(LIBCURL_LIBS            "")
 set(libdir                  "${CMAKE_INSTALL_PREFIX}/lib")
-# TODO CURL_LIBS also contains absolute paths which don't work with static -l...
 foreach(_lib ${CMAKE_C_IMPLICIT_LINK_LIBRARIES} ${CURL_LIBS})
-  set(LIBCURL_LIBS          "${LIBCURL_LIBS} -l${_lib}")
+  if(_lib MATCHES ".*/.*")
+    set(LIBCURL_LIBS          "${LIBCURL_LIBS} ${_lib}")
+  else()
+    set(LIBCURL_LIBS          "${LIBCURL_LIBS} -l${_lib}")
+  endif()
 endforeach()
 # "a" (Linux) or "lib" (Windows)
 string(REPLACE "." "" libext "${CMAKE_STATIC_LIBRARY_SUFFIX}")
diff --git a/Utilities/cmcurl/include/curl/curl.h b/Utilities/cmcurl/include/curl/curl.h
index dfaea5d..aa1034b 100644
--- a/Utilities/cmcurl/include/curl/curl.h
+++ b/Utilities/cmcurl/include/curl/curl.h
@@ -30,6 +30,10 @@
  *   https://cool.haxx.se/mailman/listinfo/curl-library/
  */
 
+#ifdef CURL_NO_OLDIES
+#define CURL_STRICTER
+#endif
+
 #include "curlver.h"         /* libcurl version defines   */
 #include "cmcurl/include/curl/curlbuild.h" /* libcurl build definitions */
 #include "curlrules.h"       /* libcurl rules enforcement */
@@ -431,7 +435,7 @@ typedef enum {
   CURLE_COULDNT_RESOLVE_PROXY,   /* 5 */
   CURLE_COULDNT_RESOLVE_HOST,    /* 6 */
   CURLE_COULDNT_CONNECT,         /* 7 */
-  CURLE_FTP_WEIRD_SERVER_REPLY,  /* 8 */
+  CURLE_WEIRD_SERVER_REPLY,      /* 8 */
   CURLE_REMOTE_ACCESS_DENIED,    /* 9 a service was denied by the server
                                     due to lack of access - when login fails
                                     this is not returned. */
@@ -562,6 +566,7 @@ typedef enum {
 
 /*  compatibility with older names */
 #define CURLOPT_ENCODING CURLOPT_ACCEPT_ENCODING
+#define CURLE_FTP_WEIRD_SERVER_REPLY CURLE_WEIRD_SERVER_REPLY
 
 /* The following were added in 7.21.5, April 2011 */
 #define CURLE_UNKNOWN_TELNET_OPTION CURLE_UNKNOWN_OPTION
@@ -1695,6 +1700,10 @@ typedef enum {
   /* Set TCP Fast Open */
   CINIT(TCP_FASTOPEN, LONG, 244),
 
+  /* Continue to send data if the server responds early with an
+   * HTTP status code >= 300 */
+  CINIT(KEEP_SENDING_ON_ERROR, LONG, 245),
+
   CURLOPT_LASTENTRY /* the last unused */
 } CURLoption;
 
diff --git a/Utilities/cmcurl/include/curl/curlver.h b/Utilities/cmcurl/include/curl/curlver.h
index 09f612a..2415d1a 100644
--- a/Utilities/cmcurl/include/curl/curlver.h
+++ b/Utilities/cmcurl/include/curl/curlver.h
@@ -30,13 +30,13 @@
 
 /* This is the version number of the libcurl package from which this header
    file origins: */
-#define LIBCURL_VERSION "7.50.1"
+#define LIBCURL_VERSION "7.51.0"
 
 /* The numeric version number is also available "in parts" by using these
    defines: */
 #define LIBCURL_VERSION_MAJOR 7
-#define LIBCURL_VERSION_MINOR 50
-#define LIBCURL_VERSION_PATCH 1
+#define LIBCURL_VERSION_MINOR 51
+#define LIBCURL_VERSION_PATCH 0
 
 /* This is the numeric version of the libcurl version number, meant for easier
    parsing and comparions by programs. The LIBCURL_VERSION_NUM define will
@@ -57,7 +57,7 @@
    CURL_VERSION_BITS() macro since curl's own configure script greps for it
    and needs it to contain the full number.
 */
-#define LIBCURL_VERSION_NUM 0x073201
+#define LIBCURL_VERSION_NUM 0x073300
 
 /*
  * This is the date and time when the full source package was created. The
diff --git a/Utilities/cmcurl/lib/CMakeLists.txt b/Utilities/cmcurl/lib/CMakeLists.txt
index 0d7b717..76dd6c6 100644
--- a/Utilities/cmcurl/lib/CMakeLists.txt
+++ b/Utilities/cmcurl/lib/CMakeLists.txt
@@ -111,6 +111,11 @@ endif()
 set_target_properties(${LIB_NAME} PROPERTIES COMPILE_DEFINITIONS BUILDING_LIBCURL)
 
 if(0) # This code not needed for building within CMake.
+if(HIDES_CURL_PRIVATE_SYMBOLS)
+  set_property(TARGET ${LIB_NAME} APPEND PROPERTY COMPILE_DEFINITIONS "CURL_HIDDEN_SYMBOLS")
+  set_property(TARGET ${LIB_NAME} APPEND PROPERTY COMPILE_FLAGS ${CURL_CFLAG_SYMBOLS_HIDE})
+endif()
+
 # Remove the "lib" prefix since the library is already named "libcurl".
 set_target_properties(${LIB_NAME} PROPERTIES PREFIX "")
 set_target_properties(${LIB_NAME} PROPERTIES IMPORT_PREFIX "")
diff --git a/Utilities/cmcurl/lib/Makefile.inc b/Utilities/cmcurl/lib/Makefile.inc
index 0ed998c..1328cad 100644
--- a/Utilities/cmcurl/lib/Makefile.inc
+++ b/Utilities/cmcurl/lib/Makefile.inc
@@ -40,13 +40,13 @@ LIB_VTLS_HFILES = vtls/openssl.h vtls/vtls.h vtls/gtls.h                \
 LIB_CFILES = file.c timeval.c base64.c hostip.c progress.c formdata.c   \
   cookie.c http.c sendf.c ftp.c url.c dict.c if2ip.c speedcheck.c       \
   ldap.c version.c getenv.c escape.c mprintf.c telnet.c netrc.c         \
-  getinfo.c transfer.c strequal.c easy.c security.c curl_fnmatch.c      \
+  getinfo.c transfer.c strcase.c easy.c security.c curl_fnmatch.c       \
   fileinfo.c ftplistparser.c wildcard.c krb5.c memdebug.c http_chunks.c \
   strtok.c connect.c llist.c hash.c multi.c content_encoding.c share.c  \
   http_digest.c md4.c md5.c http_negotiate.c inet_pton.c strtoofft.c    \
   strerror.c amigaos.c hostasyn.c hostip4.c hostip6.c hostsyn.c         \
   inet_ntop.c parsedate.c select.c tftp.c splay.c strdup.c socks.c      \
-  ssh.c rawstr.c curl_addrinfo.c socks_gssapi.c socks_sspi.c            \
+  ssh.c curl_addrinfo.c socks_gssapi.c socks_sspi.c            \
   curl_sspi.c slist.c nonblock.c curl_memrchr.c imap.c pop3.c smtp.c    \
   pingpong.c rtsp.c curl_threads.c warnless.c hmac.c curl_rtmp.c        \
   openldap.c curl_gethostname.c gopher.c idn_win32.c                    \
@@ -58,13 +58,13 @@ LIB_CFILES = file.c timeval.c base64.c hostip.c progress.c formdata.c   \
 LIB_HFILES = arpa_telnet.h netrc.h file.h timeval.h hostip.h progress.h \
   formdata.h cookie.h http.h sendf.h ftp.h url.h dict.h if2ip.h         \
   speedcheck.h urldata.h curl_ldap.h escape.h telnet.h getinfo.h        \
-  strequal.h curl_sec.h memdebug.h http_chunks.h curl_fnmatch.h         \
+  strcase.h curl_sec.h memdebug.h http_chunks.h curl_fnmatch.h          \
   wildcard.h fileinfo.h ftplistparser.h strtok.h connect.h llist.h      \
   hash.h content_encoding.h share.h curl_md4.h curl_md5.h http_digest.h \
   http_negotiate.h inet_pton.h amigaos.h strtoofft.h strerror.h         \
   inet_ntop.h curlx.h curl_memory.h curl_setup.h transfer.h select.h    \
   easyif.h multiif.h parsedate.h tftp.h sockaddr.h splay.h strdup.h     \
-  socks.h ssh.h curl_base64.h rawstr.h curl_addrinfo.h curl_sspi.h      \
+  socks.h ssh.h curl_base64.h curl_addrinfo.h curl_sspi.h      \
   slist.h nonblock.h curl_memrchr.h imap.h pop3.h smtp.h pingpong.h     \
   rtsp.h curl_threads.h warnless.h curl_hmac.h curl_rtmp.h              \
   curl_gethostname.h gopher.h http_proxy.h non-ascii.h asyn.h           \
diff --git a/Utilities/cmcurl/lib/amigaos.c b/Utilities/cmcurl/lib/amigaos.c
index 5591d22..4f55b30 100644
--- a/Utilities/cmcurl/lib/amigaos.c
+++ b/Utilities/cmcurl/lib/amigaos.c
@@ -57,7 +57,7 @@ bool Curl_amiga_init()
   }
 
   if(SocketBaseTags(SBTM_SETVAL(SBTC_ERRNOPTR(sizeof(errno))), (ULONG) &errno,
-                    SBTM_SETVAL(SBTC_LOGTAGPTR), (ULONG) "cURL",
+                    SBTM_SETVAL(SBTC_LOGTAGPTR), (ULONG) "curl",
                     TAG_DONE)) {
     __request("SocketBaseTags ERROR");
     return FALSE;
diff --git a/Utilities/cmcurl/lib/base64.c b/Utilities/cmcurl/lib/base64.c
index ad25459..204a227 100644
--- a/Utilities/cmcurl/lib/base64.c
+++ b/Utilities/cmcurl/lib/base64.c
@@ -190,6 +190,11 @@ static CURLcode base64_encode(const char *table64,
   if(!insize)
     insize = strlen(indata);
 
+#if SIZEOF_SIZE_T == 4
+  if(insize > UINT_MAX/4)
+    return CURLE_OUT_OF_MEMORY;
+#endif
+
   base64data = output = malloc(insize * 4 / 3 + 4);
   if(!output)
     return CURLE_OUT_OF_MEMORY;
diff --git a/Utilities/cmcurl/lib/conncache.c b/Utilities/cmcurl/lib/conncache.c
index 32a7030..01b1b44 100644
--- a/Utilities/cmcurl/lib/conncache.c
+++ b/Utilities/cmcurl/lib/conncache.c
@@ -30,7 +30,6 @@
 #include "progress.h"
 #include "multiif.h"
 #include "sendf.h"
-#include "rawstr.h"
 #include "conncache.h"
 /* The last 3 #include files should be in this order */
 #include "curl_printf.h"
diff --git a/Utilities/cmcurl/lib/connect.c b/Utilities/cmcurl/lib/connect.c
index 0047f9a..3df34d9 100644
--- a/Utilities/cmcurl/lib/connect.c
+++ b/Utilities/cmcurl/lib/connect.c
@@ -762,7 +762,7 @@ CURLcode Curl_is_connected(struct connectdata *conn,
 #endif
 
     /* check socket for connect */
-    rc = Curl_socket_ready(CURL_SOCKET_BAD, conn->tempsock[i], 0);
+    rc = SOCKET_WRITABLE(conn->tempsock[i], 0);
 
     if(rc == 0) { /* no connection yet */
       error = 0;
@@ -1368,25 +1368,26 @@ CURLcode Curl_socket(struct connectdata *conn,
 
 }
 
-#ifdef CURLDEBUG
 /*
- * Curl_conncontrol() is used to set the conn->bits.close bit on or off. It
- * MUST be called with the connclose() or connkeep() macros with a stated
- * reason. The reason is only shown in debug builds but helps to figure out
- * decision paths when connections are or aren't re-used as expected.
+ * Curl_conncontrol() marks streams or connection for closure.
  */
-void Curl_conncontrol(struct connectdata *conn, bool closeit,
-                      const char *reason)
-{
-#if defined(CURL_DISABLE_VERBOSE_STRINGS)
-  (void) reason;
+void Curl_conncontrol(struct connectdata *conn,
+                      int ctrl /* see defines in header */
+#ifdef DEBUGBUILD
+                      , const char *reason
 #endif
-  if(closeit != conn->bits.close) {
-    infof(conn->data, "Marked for [%s]: %s\n", closeit?"closure":"keep alive",
-          reason);
-
+  )
+{
+  /* close if a connection, or a stream that isn't multiplexed */
+  bool closeit = (ctrl == CONNCTRL_CONNECTION) ||
+    ((ctrl == CONNCTRL_STREAM) && !(conn->handler->flags & PROTOPT_STREAM));
+  if((ctrl == CONNCTRL_STREAM) &&
+     (conn->handler->flags & PROTOPT_STREAM))
+    DEBUGF(infof(conn->data, "Kill stream: %s\n", reason));
+  else if(closeit != conn->bits.close) {
+    DEBUGF(infof(conn->data, "Marked for [%s]: %s\n",
+                 closeit?"closure":"keep alive", reason));
     conn->bits.close = closeit; /* the only place in the source code that
                                    should assign this bit */
   }
 }
-#endif
diff --git a/Utilities/cmcurl/lib/connect.h b/Utilities/cmcurl/lib/connect.h
index 6d60e0d..a7cbc9b 100644
--- a/Utilities/cmcurl/lib/connect.h
+++ b/Utilities/cmcurl/lib/connect.h
@@ -7,7 +7,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -104,21 +104,37 @@ CURLcode Curl_socket(struct connectdata *conn,
 
 void Curl_tcpnodelay(struct connectdata *conn, curl_socket_t sockfd);
 
-#ifdef CURLDEBUG
 /*
- * Curl_connclose() sets the bit.close bit to TRUE with an explanation.
- * Nothing else.
+ * Curl_conncontrol() marks the end of a connection/stream. The 'closeit'
+ * argument specifies if it is the end of a connection or a stream.
+ *
+ * For stream-based protocols (such as HTTP/2), a stream close will not cause
+ * a connection close. Other protocols will close the connection for both
+ * cases.
+ *
+ * It sets the bit.close bit to TRUE (with an explanation for debug builds),
+ * when the connection will close.
  */
-void Curl_conncontrol(struct connectdata *conn,
-                      bool closeit,
-                      const char *reason);
-#define connclose(x,y) Curl_conncontrol(x,TRUE, y)
-#define connkeep(x,y) Curl_conncontrol(x, FALSE, y)
-#else /* if !CURLDEBUG */
 
-#define connclose(x,y) (x)->bits.close = TRUE
-#define connkeep(x,y) (x)->bits.close = FALSE
+#define CONNCTRL_KEEP 0 /* undo a marked closure */
+#define CONNCTRL_CONNECTION 1
+#define CONNCTRL_STREAM 2
 
+void Curl_conncontrol(struct connectdata *conn,
+                      int closeit
+#ifdef DEBUGBUILD
+                      , const char *reason
+#endif
+  );
+
+#ifdef DEBUGBUILD
+#define streamclose(x,y) Curl_conncontrol(x, CONNCTRL_STREAM, y)
+#define connclose(x,y) Curl_conncontrol(x, CONNCTRL_CONNECTION, y)
+#define connkeep(x,y) Curl_conncontrol(x, CONNCTRL_KEEP, y)
+#else /* if !CURLDEBUG */
+#define streamclose(x,y) Curl_conncontrol(x, CONNCTRL_STREAM)
+#define connclose(x,y) Curl_conncontrol(x, CONNCTRL_CONNECTION)
+#define connkeep(x,y) Curl_conncontrol(x, CONNCTRL_KEEP)
 #endif
 
 #endif /* HEADER_CURL_CONNECT_H */
diff --git a/Utilities/cmcurl/lib/cookie.c b/Utilities/cmcurl/lib/cookie.c
index d5a83fd..1b3e645 100644
--- a/Utilities/cmcurl/lib/cookie.c
+++ b/Utilities/cmcurl/lib/cookie.c
@@ -90,13 +90,12 @@ Example set of cookies:
 
 #include "urldata.h"
 #include "cookie.h"
-#include "strequal.h"
 #include "strtok.h"
 #include "sendf.h"
 #include "slist.h"
 #include "share.h"
 #include "strtoofft.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "curl_memrchr.h"
 #include "inet_pton.h"
 
@@ -126,7 +125,7 @@ static bool tailmatch(const char *cooke_domain, const char *hostname)
   if(hostname_len < cookie_domain_len)
     return FALSE;
 
-  if(!Curl_raw_equal(cooke_domain, hostname+hostname_len-cookie_domain_len))
+  if(!strcasecompare(cooke_domain, hostname+hostname_len-cookie_domain_len))
     return FALSE;
 
   /* A lead char of cookie_domain is not '.'.
@@ -469,9 +468,9 @@ Curl_cookie_add(struct Curl_easy *data,
           /* this was a "<name>=" with no content, and we must allow
              'secure' and 'httponly' specified this weirdly */
           done = TRUE;
-          if(Curl_raw_equal("secure", name))
+          if(strcasecompare("secure", name))
             co->secure = TRUE;
-          else if(Curl_raw_equal("httponly", name))
+          else if(strcasecompare("httponly", name))
             co->httponly = TRUE;
           else if(sep)
             /* there was a '=' so we're not done parsing this field */
@@ -479,7 +478,7 @@ Curl_cookie_add(struct Curl_easy *data,
         }
         if(done)
           ;
-        else if(Curl_raw_equal("path", name)) {
+        else if(strcasecompare("path", name)) {
           strstore(&co->path, whatptr);
           if(!co->path) {
             badcookie = TRUE; /* out of memory bad */
@@ -491,7 +490,7 @@ Curl_cookie_add(struct Curl_easy *data,
             break;
           }
         }
-        else if(Curl_raw_equal("domain", name)) {
+        else if(strcasecompare("domain", name)) {
           bool is_ip;
           const char *dotp;
 
@@ -529,14 +528,14 @@ Curl_cookie_add(struct Curl_easy *data,
                   whatptr);
           }
         }
-        else if(Curl_raw_equal("version", name)) {
+        else if(strcasecompare("version", name)) {
           strstore(&co->version, whatptr);
           if(!co->version) {
             badcookie = TRUE;
             break;
           }
         }
-        else if(Curl_raw_equal("max-age", name)) {
+        else if(strcasecompare("max-age", name)) {
           /* Defined in RFC2109:
 
              Optional.  The Max-Age attribute defines the lifetime of the
@@ -552,7 +551,7 @@ Curl_cookie_add(struct Curl_easy *data,
             break;
           }
         }
-        else if(Curl_raw_equal("expires", name)) {
+        else if(strcasecompare("expires", name)) {
           strstore(&co->expirestr, whatptr);
           if(!co->expirestr) {
             badcookie = TRUE;
@@ -713,7 +712,7 @@ Curl_cookie_add(struct Curl_easy *data,
            As far as I can see, it is set to true when the cookie says
            .domain.com and to false when the domain is complete www.domain.com
         */
-        co->tailmatch = Curl_raw_equal(ptr, "TRUE")?TRUE:FALSE;
+        co->tailmatch = strcasecompare(ptr, "TRUE")?TRUE:FALSE;
         break;
       case 2:
         /* It turns out, that sometimes the file format allows the path
@@ -742,7 +741,7 @@ Curl_cookie_add(struct Curl_easy *data,
         fields++; /* add a field and fall down to secure */
         /* FALLTHROUGH */
       case 3:
-        co->secure = Curl_raw_equal(ptr, "TRUE")?TRUE:FALSE;
+        co->secure = strcasecompare(ptr, "TRUE")?TRUE:FALSE;
         break;
       case 4:
         co->expires = curlx_strtoofft(ptr, NULL, 10);
@@ -813,11 +812,12 @@ Curl_cookie_add(struct Curl_easy *data,
   clist = c->cookies;
   replace_old = FALSE;
   while(clist) {
-    if(Curl_raw_equal(clist->name, co->name)) {
+    if(strcasecompare(clist->name, co->name)) {
       /* the names are identical */
 
       if(clist->domain && co->domain) {
-        if(Curl_raw_equal(clist->domain, co->domain))
+        if(strcasecompare(clist->domain, co->domain) &&
+          (clist->tailmatch == co->tailmatch))
           /* The domains are identical */
           replace_old=TRUE;
       }
@@ -828,7 +828,7 @@ Curl_cookie_add(struct Curl_easy *data,
         /* the domains were identical */
 
         if(clist->spath && co->spath) {
-          if(Curl_raw_equal(clist->spath, co->spath)) {
+          if(strcasecompare(clist->spath, co->spath)) {
             replace_old = TRUE;
           }
           else
@@ -902,6 +902,35 @@ Curl_cookie_add(struct Curl_easy *data,
   return co;
 }
 
+/*
+ * get_line() makes sure to only return complete whole lines that fit in 'len'
+ * bytes and end with a newline.
+ */
+static char *get_line(char *buf, int len, FILE *input)
+{
+  bool partial = FALSE;
+  while(1) {
+    char *b = fgets(buf, len, input);
+    if(b) {
+      size_t rlen = strlen(b);
+      if(rlen && (b[rlen-1] == '\n')) {
+        if(partial) {
+          partial = FALSE;
+          continue;
+        }
+        return b;
+      }
+      else
+        /* read a partial, discard the next piece that ends with newline */
+        partial = TRUE;
+    }
+    else
+      break;
+  }
+  return NULL;
+}
+
+
 /*****************************************************************************
  *
  * Curl_cookie_init()
@@ -938,7 +967,7 @@ struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
   }
   c->running = FALSE; /* this is not running, this is init */
 
-  if(file && strequal(file, "-")) {
+  if(file && !strcmp(file, "-")) {
     fp = stdin;
     fromfile=FALSE;
   }
@@ -958,7 +987,7 @@ struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
     line = malloc(MAX_COOKIE_LINE);
     if(!line)
       goto fail;
-    while(fgets(line, MAX_COOKIE_LINE, fp)) {
+    while(get_line(line, MAX_COOKIE_LINE, fp)) {
       if(checkprefix("Set-Cookie:", line)) {
         /* This is a cookie line, get it! */
         lineptr=&line[11];
@@ -1023,6 +1052,40 @@ static int cookie_sort(const void *p1, const void *p2)
   return 0;
 }
 
+#define CLONE(field)                     \
+  do {                                   \
+    if(src->field) {                     \
+      dup->field = strdup(src->field);   \
+      if(!dup->field)                    \
+        goto fail;                       \
+    }                                    \
+  } while(0)
+
+static struct Cookie *dup_cookie(struct Cookie *src)
+{
+  struct Cookie *dup = calloc(sizeof(struct Cookie), 1);
+  if(dup) {
+    CLONE(expirestr);
+    CLONE(domain);
+    CLONE(path);
+    CLONE(spath);
+    CLONE(name);
+    CLONE(value);
+    CLONE(maxage);
+    CLONE(version);
+    dup->expires = src->expires;
+    dup->tailmatch = src->tailmatch;
+    dup->secure = src->secure;
+    dup->livecookie = src->livecookie;
+    dup->httponly = src->httponly;
+  }
+  return dup;
+
+  fail:
+  freecookie(dup);
+  return NULL;
+}
+
 /*****************************************************************************
  *
  * Curl_cookie_getlist()
@@ -1067,7 +1130,7 @@ struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
       /* now check if the domain is correct */
       if(!co->domain ||
          (co->tailmatch && !is_ip && tailmatch(co->domain, host)) ||
-         ((!co->tailmatch || is_ip) && Curl_raw_equal(host, co->domain)) ) {
+         ((!co->tailmatch || is_ip) && strcasecompare(host, co->domain)) ) {
         /* the right part of the host matches the domain stuff in the
            cookie data */
 
@@ -1078,11 +1141,8 @@ struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
           /* and now, we know this is a match and we should create an
              entry for the return-linked-list */
 
-          newco = malloc(sizeof(struct Cookie));
+          newco = dup_cookie(co);
           if(newco) {
-            /* first, copy the whole source cookie: */
-            memcpy(newco, co, sizeof(struct Cookie));
-
             /* then modify our next */
             newco->next = mainco;
 
@@ -1094,12 +1154,7 @@ struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
           else {
             fail:
             /* failure, clear up the allocated chain and return NULL */
-            while(mainco) {
-              co = mainco->next;
-              free(mainco);
-              mainco = co;
-            }
-
+            Curl_cookie_freelist(mainco);
             return NULL;
           }
         }
@@ -1151,7 +1206,7 @@ struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
 void Curl_cookie_clearall(struct CookieInfo *cookies)
 {
   if(cookies) {
-    Curl_cookie_freelist(cookies->cookies, TRUE);
+    Curl_cookie_freelist(cookies->cookies);
     cookies->cookies = NULL;
     cookies->numcookies = 0;
   }
@@ -1163,21 +1218,14 @@ void Curl_cookie_clearall(struct CookieInfo *cookies)
  *
  * Free a list of cookies previously returned by Curl_cookie_getlist();
  *
- * The 'cookiestoo' argument tells this function whether to just free the
- * list or actually also free all cookies within the list as well.
- *
  ****************************************************************************/
 
-void Curl_cookie_freelist(struct Cookie *co, bool cookiestoo)
+void Curl_cookie_freelist(struct Cookie *co)
 {
   struct Cookie *next;
   while(co) {
     next = co->next;
-    if(cookiestoo)
-      freecookie(co);
-    else
-      free(co); /* we only free the struct since the "members" are all just
-                   pointed out in the main cookie list! */
+    freecookie(co);
     co = next;
   }
 }
@@ -1232,7 +1280,7 @@ void Curl_cookie_cleanup(struct CookieInfo *c)
 {
   if(c) {
     free(c->filename);
-    Curl_cookie_freelist(c->cookies, TRUE);
+    Curl_cookie_freelist(c->cookies);
     free(c); /* free the base struct as well */
   }
 }
@@ -1290,7 +1338,7 @@ static int cookie_output(struct CookieInfo *c, const char *dumphere)
   /* at first, remove expired cookies */
   remove_expired(c);
 
-  if(strequal("-", dumphere)) {
+  if(!strcmp("-", dumphere)) {
     /* use stdout */
     out = stdout;
     use_stdout=TRUE;
diff --git a/Utilities/cmcurl/lib/cookie.h b/Utilities/cmcurl/lib/cookie.h
index cd7c54a..a9a4578 100644
--- a/Utilities/cmcurl/lib/cookie.h
+++ b/Utilities/cmcurl/lib/cookie.h
@@ -7,7 +7,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -82,7 +82,7 @@ struct Cookie *Curl_cookie_add(struct Curl_easy *data,
 
 struct Cookie *Curl_cookie_getlist(struct CookieInfo *, const char *,
                                    const char *, bool);
-void Curl_cookie_freelist(struct Cookie *cookies, bool cookiestoo);
+void Curl_cookie_freelist(struct Cookie *cookies);
 void Curl_cookie_clearall(struct CookieInfo *cookies);
 void Curl_cookie_clearsess(struct CookieInfo *cookies);
 
diff --git a/Utilities/cmcurl/lib/curl_config.h.cmake b/Utilities/cmcurl/lib/curl_config.h.cmake
index 20f212b..13f69b2 100644
--- a/Utilities/cmcurl/lib/curl_config.h.cmake
+++ b/Utilities/cmcurl/lib/curl_config.h.cmake
@@ -61,7 +61,7 @@
 #cmakedefine CURL_DISABLE_VERBOSE_STRINGS 1
 
 /* to make a symbol visible */
-#cmakedefine CURL_EXTERN_SYMBOL 1
+#cmakedefine CURL_EXTERN_SYMBOL ${CURL_EXTERN_SYMBOL}
 /* Ensure using CURL_EXTERN_SYMBOL is possible */
 #ifndef CURL_EXTERN_SYMBOL
 #define CURL_EXTERN_SYMBOL
@@ -900,6 +900,9 @@
 /* Define if you want to enable POSIX threaded DNS lookup */
 #cmakedefine USE_THREADS_POSIX 1
 
+/* Define if you want to enable WIN32 threaded DNS lookup */
+#cmakedefine USE_THREADS_WIN32 1
+
 /* Define to disable non-blocking sockets. */
 #cmakedefine USE_BLOCKING_SOCKETS 1
 
@@ -927,6 +930,9 @@
 /* if OpenSSL is in use */
 #cmakedefine USE_OPENSSL 1
 
+/* to enable NGHTTP2  */
+#cmakedefine USE_NGHTTP2 1
+
 /* if Unix domain sockets are enabled  */
 #cmakedefine USE_UNIX_SOCKETS
 
diff --git a/Utilities/cmcurl/lib/curl_ntlm_core.c b/Utilities/cmcurl/lib/curl_ntlm_core.c
index f3fb013..812a073 100644
--- a/Utilities/cmcurl/lib/curl_ntlm_core.c
+++ b/Utilities/cmcurl/lib/curl_ntlm_core.c
@@ -76,6 +76,11 @@
 #  define MD5_DIGEST_LENGTH 16
 #  define MD4_DIGEST_LENGTH 16
 
+#elif defined(USE_MBEDTLS)
+
+#  include <mbedtls/des.h>
+#  include <mbedtls/md4.h>
+
 #elif defined(USE_NSS)
 
 #  include <nss.h>
@@ -100,7 +105,7 @@
 
 #include "urldata.h"
 #include "non-ascii.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "curl_ntlm_core.h"
 #include "curl_md5.h"
 #include "curl_hmac.h"
@@ -188,6 +193,26 @@ static void setup_des_key(const unsigned char *key_56,
   gcry_cipher_setkey(*des, key, sizeof(key));
 }
 
+#elif defined(USE_MBEDTLS)
+
+static bool encrypt_des(const unsigned char *in, unsigned char *out,
+                        const unsigned char *key_56)
+{
+  mbedtls_des_context ctx;
+  char key[8];
+
+  /* Expand the 56-bit key to 64-bits */
+  extend_key_56_to_64(key_56, key);
+
+  /* Set the key parity to odd */
+  mbedtls_des_key_set_parity((unsigned char *) key);
+
+  /* Perform the encryption */
+  mbedtls_des_init(&ctx);
+  mbedtls_des_setkey_enc(&ctx, (unsigned char *) key);
+  return mbedtls_des_crypt_ecb(&ctx, in, out) == 0;
+}
+
 #elif defined(USE_NSS)
 
 /*
@@ -400,8 +425,8 @@ void Curl_ntlm_core_lm_resp(const unsigned char *keys,
   setup_des_key(keys + 14, &des);
   gcry_cipher_encrypt(des, results + 16, 8, plaintext, 8);
   gcry_cipher_close(des);
-#elif defined(USE_NSS) || defined(USE_DARWINSSL) || defined(USE_OS400CRYPTO) \
-  || defined(USE_WIN32_CRYPTO)
+#elif defined(USE_MBEDTLS) || defined(USE_NSS) || defined(USE_DARWINSSL) \
+  || defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO)
   encrypt_des(plaintext, results, keys);
   encrypt_des(plaintext, results + 8, keys + 7);
   encrypt_des(plaintext, results + 16, keys + 14);
@@ -464,8 +489,8 @@ CURLcode Curl_ntlm_core_mk_lm_hash(struct Curl_easy *data,
     setup_des_key(pw + 7, &des);
     gcry_cipher_encrypt(des, lmbuffer + 8, 8, magic, 8);
     gcry_cipher_close(des);
-#elif defined(USE_NSS) || defined(USE_DARWINSSL) || defined(USE_OS400CRYPTO) \
-  || defined(USE_WIN32_CRYPTO)
+#elif defined(USE_MBEDTLS) || defined(USE_NSS) || defined(USE_DARWINSSL) \
+  || defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO)
     encrypt_des(magic, lmbuffer, pw);
     encrypt_des(magic, lmbuffer + 8, pw + 7);
 #endif
@@ -543,6 +568,8 @@ CURLcode Curl_ntlm_core_mk_nt_hash(struct Curl_easy *data,
     gcry_md_write(MD4pw, pw, 2 * len);
     memcpy (ntbuffer, gcry_md_read (MD4pw, 0), MD4_DIGEST_LENGTH);
     gcry_md_close(MD4pw);
+#elif defined(USE_MBEDTLS)
+    mbedtls_md4(pw, 2 * len, ntbuffer);
 #elif defined(USE_NSS) || defined(USE_OS400CRYPTO)
     Curl_md4it(ntbuffer, pw, 2 * len);
 #elif defined(USE_DARWINSSL)
diff --git a/Utilities/cmcurl/lib/curl_sasl.c b/Utilities/cmcurl/lib/curl_sasl.c
index 35e9fea..6b86962 100644
--- a/Utilities/cmcurl/lib/curl_sasl.c
+++ b/Utilities/cmcurl/lib/curl_sasl.c
@@ -42,8 +42,6 @@
 #include "curl_sasl.h"
 #include "warnless.h"
 #include "strtok.h"
-#include "strequal.h"
-#include "rawstr.h"
 #include "sendf.h"
 #include "non-ascii.h" /* included for Curl_convert_... prototypes */
 /* The last 3 #include files should be in this order */
@@ -159,7 +157,7 @@ CURLcode Curl_sasl_parse_url_auth_option(struct SASL *sasl,
     sasl->prefmech = SASL_AUTH_NONE;
   }
 
-  if(strnequal(value, "*", len))
+  if(!strncmp(value, "*", len))
     sasl->prefmech = SASL_AUTH_DEFAULT;
   else {
     mechbit = Curl_sasl_decode_mech(value, len, &mechlen);
@@ -288,7 +286,8 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn,
   }
   else if(conn->bits.user_passwd) {
 #if defined(USE_KERBEROS5)
-    if(enabledmechs & SASL_MECH_GSSAPI) {
+    if((enabledmechs & SASL_MECH_GSSAPI) && Curl_auth_is_gssapi_supported() &&
+       Curl_auth_user_contains_domain(conn->user)) {
       sasl->mutual_auth = FALSE; /* TODO: Calculate mutual authentication */
       mech = SASL_MECH_STRING_GSSAPI;
       state1 = SASL_GSSAPI;
@@ -308,7 +307,8 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn,
     else
 #endif
 #ifndef CURL_DISABLE_CRYPTO_AUTH
-    if(enabledmechs & SASL_MECH_DIGEST_MD5) {
+    if((enabledmechs & SASL_MECH_DIGEST_MD5) &&
+       Curl_auth_is_digest_supported()) {
       mech = SASL_MECH_STRING_DIGEST_MD5;
       state1 = SASL_DIGESTMD5;
       sasl->authused = SASL_MECH_DIGEST_MD5;
@@ -321,7 +321,7 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn,
     else
 #endif
 #ifdef USE_NTLM
-    if(enabledmechs & SASL_MECH_NTLM) {
+    if((enabledmechs & SASL_MECH_NTLM) && Curl_auth_is_ntlm_supported()) {
       mech = SASL_MECH_STRING_NTLM;
       state1 = SASL_NTLM;
       state2 = SASL_NTLM_TYPE2MSG;
diff --git a/Utilities/cmcurl/lib/curl_setup.h b/Utilities/cmcurl/lib/curl_setup.h
index 2122220..4eb17a1 100644
--- a/Utilities/cmcurl/lib/curl_setup.h
+++ b/Utilities/cmcurl/lib/curl_setup.h
@@ -614,10 +614,9 @@ int netware_init(void);
 #endif
 #endif
 
-#if defined(HAVE_LIBIDN) && defined(HAVE_TLD_H)
-/* The lib was present and the tld.h header (which is missing in libidn 0.3.X
-   but we only work with libidn 0.4.1 or later) */
-#define USE_LIBIDN
+#if defined(HAVE_LIBIDN2) && defined(HAVE_IDN2_H)
+/* The lib and header are present */
+#define USE_LIBIDN2
 #endif
 
 #ifndef SIZEOF_TIME_T
@@ -653,6 +652,13 @@ int netware_init(void);
     defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO)
 
 #define USE_NTLM
+
+#elif defined(USE_MBEDTLS)
+#  include <mbedtls/md4.h>
+#  if defined(MBEDTLS_MD4_C)
+#define USE_NTLM
+#  endif
+
 #endif
 #endif
 
@@ -761,4 +767,14 @@ endings either CRLF or LF so 't' is appropriate.
 #  endif
 #endif /* DONT_USE_RECV_BEFORE_SEND_WORKAROUNDS */
 
+/* Detect Windows App environment which has a restricted access
+ * to the Win32 APIs. */
+# if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0602)
+#  include <winapifamily.h>
+#  if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \
+     !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
+#    define CURL_WINDOWS_APP
+#  endif
+# endif
+
 #endif /* HEADER_CURL_SETUP_H */
diff --git a/Utilities/cmcurl/lib/curl_sspi.c b/Utilities/cmcurl/lib/curl_sspi.c
index ee3f1b1..11a7120 100644
--- a/Utilities/cmcurl/lib/curl_sspi.c
+++ b/Utilities/cmcurl/lib/curl_sspi.c
@@ -64,6 +64,12 @@ PSecurityFunctionTable s_pSecFn = NULL;
  *
  * Once this function has been executed, Windows SSPI functions can be
  * called through the Security Service Provider Interface dispatch table.
+ *
+ * Parameters:
+ *
+ * None.
+ *
+ * Returns CURLE_OK on success.
  */
 CURLcode Curl_sspi_global_init(void)
 {
@@ -102,8 +108,11 @@ CURLcode Curl_sspi_global_init(void)
  * Curl_sspi_global_cleanup()
  *
  * This deinitializes the Security Service Provider Interface from libcurl.
+ *
+ * Parameters:
+ *
+ * None.
  */
-
 void Curl_sspi_global_cleanup(void)
 {
   if(s_hSecDll) {
@@ -205,6 +214,15 @@ CURLcode Curl_create_sspi_identity(const char *userp, const char *passwdp,
   return CURLE_OK;
 }
 
+/*
+ * Curl_sspi_free_identity()
+ *
+ * This is used to free the contents of a SSPI identifier structure.
+ *
+ * Parameters:
+ *
+ * identity [in/out] - The identity structure.
+ */
 void Curl_sspi_free_identity(SEC_WINNT_AUTH_IDENTITY *identity)
 {
   if(identity) {
diff --git a/Utilities/cmcurl/lib/curlx.h b/Utilities/cmcurl/lib/curlx.h
index 448a34f..6168dc1 100644
--- a/Utilities/cmcurl/lib/curlx.h
+++ b/Utilities/cmcurl/lib/curlx.h
@@ -7,7 +7,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -34,8 +34,8 @@
    functions while they still are offered publicly. They will be made library-
    private one day */
 
-#include "strequal.h"
-/* "strequal.h" provides the strequal protos */
+#include "strcase.h"
+/* "strcase.h" provides the strcasecompare protos */
 
 #include "strtoofft.h"
 /* "strtoofft.h" provides this function: curlx_strtoofft(), returns a
@@ -67,15 +67,12 @@
    be removed from a future libcurl official API:
    curlx_getenv
    curlx_mprintf (and its variations)
-   curlx_strequal
-   curlx_strnequal
+   curlx_strcasecompare
+   curlx_strncasecompare
 
 */
 
 #define curlx_getenv curl_getenv
-#define curlx_strequal curl_strequal
-#define curlx_strnequal curl_strnequal
-#define curlx_raw_equal Curl_raw_equal
 #define curlx_mvsnprintf curl_mvsnprintf
 #define curlx_msnprintf curl_msnprintf
 #define curlx_maprintf curl_maprintf
diff --git a/Utilities/cmcurl/lib/dict.c b/Utilities/cmcurl/lib/dict.c
index a7b5965..69defc4 100644
--- a/Utilities/cmcurl/lib/dict.c
+++ b/Utilities/cmcurl/lib/dict.c
@@ -5,7 +5,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -52,11 +52,10 @@
 #include <curl/curl.h>
 #include "transfer.h"
 #include "sendf.h"
-
+#include "escape.h"
 #include "progress.h"
-#include "strequal.h"
 #include "dict.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "curl_memory.h"
 /* The last #include file should be: */
 #include "memdebug.h"
@@ -96,12 +95,12 @@ static char *unescape_word(struct Curl_easy *data, const char *inputbuff)
   char *newp;
   char *dictp;
   char *ptr;
-  int len;
+  size_t len;
   char ch;
   int olen=0;
 
-  newp = curl_easy_unescape(data, inputbuff, 0, &len);
-  if(!newp)
+  CURLcode result = Curl_urldecode(data, inputbuff, 0, &newp, &len, FALSE);
+  if(!newp || result)
     return NULL;
 
   dictp = malloc(((size_t)len)*2 + 1); /* add one for terminating zero */
@@ -145,9 +144,9 @@ static CURLcode dict_do(struct connectdata *conn, bool *done)
     /* AUTH is missing */
   }
 
-  if(Curl_raw_nequal(path, DICT_MATCH, sizeof(DICT_MATCH)-1) ||
-      Curl_raw_nequal(path, DICT_MATCH2, sizeof(DICT_MATCH2)-1) ||
-      Curl_raw_nequal(path, DICT_MATCH3, sizeof(DICT_MATCH3)-1)) {
+  if(strncasecompare(path, DICT_MATCH, sizeof(DICT_MATCH)-1) ||
+     strncasecompare(path, DICT_MATCH2, sizeof(DICT_MATCH2)-1) ||
+     strncasecompare(path, DICT_MATCH3, sizeof(DICT_MATCH3)-1)) {
 
     word = strchr(path, ':');
     if(word) {
@@ -203,9 +202,9 @@ static CURLcode dict_do(struct connectdata *conn, bool *done)
     Curl_setup_transfer(conn, FIRSTSOCKET, -1, FALSE, bytecount,
                         -1, NULL); /* no upload */
   }
-  else if(Curl_raw_nequal(path, DICT_DEFINE, sizeof(DICT_DEFINE)-1) ||
-           Curl_raw_nequal(path, DICT_DEFINE2, sizeof(DICT_DEFINE2)-1) ||
-           Curl_raw_nequal(path, DICT_DEFINE3, sizeof(DICT_DEFINE3)-1)) {
+  else if(strncasecompare(path, DICT_DEFINE, sizeof(DICT_DEFINE)-1) ||
+          strncasecompare(path, DICT_DEFINE2, sizeof(DICT_DEFINE2)-1) ||
+          strncasecompare(path, DICT_DEFINE3, sizeof(DICT_DEFINE3)-1)) {
 
     word = strchr(path, ':');
     if(word) {
diff --git a/Utilities/cmcurl/lib/easy.c b/Utilities/cmcurl/lib/easy.c
index dc7139f..eee1061 100644
--- a/Utilities/cmcurl/lib/easy.c
+++ b/Utilities/cmcurl/lib/easy.c
@@ -50,7 +50,6 @@
 #include <sys/param.h>
 #endif
 
-#include "strequal.h"
 #include "urldata.h"
 #include <curl/curl.h>
 #include "transfer.h"
@@ -144,28 +143,6 @@ static CURLcode win32_init(void)
   return CURLE_OK;
 }
 
-#ifdef USE_LIBIDN
-/*
- * Initialise use of IDNA library.
- * It falls back to ASCII if $CHARSET isn't defined. This doesn't work for
- * idna_to_ascii_lz().
- */
-static void idna_init (void)
-{
-#ifdef WIN32
-  char buf[60];
-  UINT cp = GetACP();
-
-  if(!getenv("CHARSET") && cp > 0) {
-    snprintf(buf, sizeof(buf), "CHARSET=cp%u", cp);
-    putenv(buf);
-  }
-#else
-  /* to do? */
-#endif
-}
-#endif  /* USE_LIBIDN */
-
 /* true globals -- for curl_global_init() and curl_global_cleanup() */
 static unsigned int  initialized;
 static long          init_flags;
@@ -217,7 +194,7 @@ curl_calloc_callback Curl_ccalloc;
 #endif
 
 /**
- * curl_global_init() globally initializes cURL given a bitwise set of the
+ * curl_global_init() globally initializes curl given a bitwise set of the
  * different features of what to initialize.
  */
 static CURLcode global_init(long flags, bool memoryfuncs)
@@ -262,10 +239,6 @@ static CURLcode global_init(long flags, bool memoryfuncs)
   }
 #endif
 
-#ifdef USE_LIBIDN
-  idna_init();
-#endif
-
   if(Curl_resolver_global_init()) {
     DEBUGF(fprintf(stderr, "Error: resolver_global_init failed\n"));
     return CURLE_FAILED_INIT;
@@ -292,7 +265,7 @@ static CURLcode global_init(long flags, bool memoryfuncs)
 
 
 /**
- * curl_global_init() globally initializes cURL given a bitwise set of the
+ * curl_global_init() globally initializes curl given a bitwise set of the
  * different features of what to initialize.
  */
 CURLcode curl_global_init(long flags)
@@ -301,7 +274,7 @@ CURLcode curl_global_init(long flags)
 }
 
 /*
- * curl_global_init_mem() globally initializes cURL and also registers the
+ * curl_global_init_mem() globally initializes curl and also registers the
  * user provided callback routines.
  */
 CURLcode curl_global_init_mem(long flags, curl_malloc_callback m,
@@ -333,7 +306,7 @@ CURLcode curl_global_init_mem(long flags, curl_malloc_callback m,
 }
 
 /**
- * curl_global_cleanup() globally cleanups cURL, uses the value of
+ * curl_global_cleanup() globally cleanups curl, uses the value of
  * "init_flags" to determine what needs to be cleaned up and what doesn't.
  */
 void curl_global_cleanup(void)
@@ -995,6 +968,9 @@ void curl_easy_reset(struct Curl_easy *data)
   /* zero out Progress data: */
   memset(&data->progress, 0, sizeof(struct Progress));
 
+  /* zero out PureInfo data: */
+  Curl_initinfo(data);
+
   data->progress.flags |= PGRS_HIDE;
   data->state.current_speed = -1; /* init to negative == impossible */
 }
@@ -1044,7 +1020,7 @@ CURLcode curl_easy_pause(struct Curl_easy *data, int action)
   if(!result &&
      ((newstate&(KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) !=
       (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) )
-    Curl_expire(data, 1); /* get this handle going again */
+    Curl_expire(data, 0); /* get this handle going again */
 
   return result;
 }
diff --git a/Utilities/cmcurl/lib/escape.c b/Utilities/cmcurl/lib/escape.c
index 04230b4..6657007 100644
--- a/Utilities/cmcurl/lib/escape.c
+++ b/Utilities/cmcurl/lib/escape.c
@@ -78,15 +78,21 @@ char *curl_unescape(const char *string, int length)
 char *curl_easy_escape(struct Curl_easy *data, const char *string,
                        int inlength)
 {
-  size_t alloc = (inlength?(size_t)inlength:strlen(string))+1;
+  size_t alloc;
   char *ns;
   char *testing_ptr = NULL;
   unsigned char in; /* we need to treat the characters unsigned */
-  size_t newlen = alloc;
+  size_t newlen;
   size_t strindex=0;
   size_t length;
   CURLcode result;
 
+  if(inlength < 0)
+    return NULL;
+
+  alloc = (inlength?(size_t)inlength:strlen(string))+1;
+  newlen = alloc;
+
   ns = malloc(alloc);
   if(!ns)
     return NULL;
@@ -211,14 +217,22 @@ char *curl_easy_unescape(struct Curl_easy *data, const char *string,
                          int length, int *olen)
 {
   char *str = NULL;
-  size_t inputlen = length;
-  size_t outputlen;
-  CURLcode res = Curl_urldecode(data, string, inputlen, &str, &outputlen,
-                                FALSE);
-  if(res)
-    return NULL;
-  if(olen)
-    *olen = curlx_uztosi(outputlen);
+  if(length >= 0) {
+    size_t inputlen = length;
+    size_t outputlen;
+    CURLcode res = Curl_urldecode(data, string, inputlen, &str, &outputlen,
+                                  FALSE);
+    if(res)
+      return NULL;
+
+    if(olen) {
+      if(outputlen <= (size_t) INT_MAX)
+        *olen = curlx_uztosi(outputlen);
+      else
+        /* too large to return in an int, fail! */
+        Curl_safefree(str);
+    }
+  }
   return str;
 }
 
diff --git a/Utilities/cmcurl/lib/file.c b/Utilities/cmcurl/lib/file.c
index b534ec1..272289e 100644
--- a/Utilities/cmcurl/lib/file.c
+++ b/Utilities/cmcurl/lib/file.c
@@ -190,14 +190,15 @@ static CURLcode file_connect(struct connectdata *conn, bool *done)
   struct FILEPROTO *file = data->req.protop;
   int fd;
 #ifdef DOS_FILESYSTEM
-  int i;
+  size_t i;
   char *actual_path;
 #endif
-  int real_path_len;
+  size_t real_path_len;
 
-  real_path = curl_easy_unescape(data, data->state.path, 0, &real_path_len);
-  if(!real_path)
-    return CURLE_OUT_OF_MEMORY;
+  CURLcode result = Curl_urldecode(data, data->state.path, 0, &real_path,
+                                   &real_path_len, FALSE);
+  if(result)
+    return result;
 
 #ifdef DOS_FILESYSTEM
   /* If the first character is a slash, and there's
diff --git a/Utilities/cmcurl/lib/formdata.c b/Utilities/cmcurl/lib/formdata.c
index 673759d..785f1a6 100644
--- a/Utilities/cmcurl/lib/formdata.c
+++ b/Utilities/cmcurl/lib/formdata.c
@@ -33,7 +33,7 @@
 #include "urldata.h" /* for struct Curl_easy */
 #include "formdata.h"
 #include "vtls/vtls.h"
-#include "strequal.h"
+#include "strcase.h"
 #include "sendf.h"
 #include "strdup.h"
 /* The last 3 #include files should be in this order */
@@ -201,9 +201,9 @@ static const char *ContentTypeForFilename(const char *filename,
   if(filename) { /* in case a NULL was passed in */
     for(i=0; i<sizeof(ctts)/sizeof(ctts[0]); i++) {
       if(strlen(filename) >= strlen(ctts[i].extension)) {
-        if(strequal(filename +
-                    strlen(filename) - strlen(ctts[i].extension),
-                    ctts[i].extension)) {
+        if(strcasecompare(filename +
+                          strlen(filename) - strlen(ctts[i].extension),
+                          ctts[i].extension)) {
           contenttype = ctts[i].type;
           break;
         }
@@ -845,16 +845,23 @@ static CURLcode AddFormData(struct FormData **formp,
       goto error;
     }
 #endif
+    if(type != FORM_DATAMEM) {
+      newform->line = malloc((size_t)length+1);
+      if(!newform->line) {
+        result = CURLE_OUT_OF_MEMORY;
+        goto error;
+      }
+      alloc2 = newform->line;
+      memcpy(newform->line, line, (size_t)length);
 
-    newform->line = malloc((size_t)length+1);
-    if(!newform->line) {
-      result = CURLE_OUT_OF_MEMORY;
-      goto error;
+      /* zero terminate for easier debugging */
+      newform->line[(size_t)length]=0;
+    }
+    else {
+      newform->line = (char *)line;
+      type = FORM_DATA; /* in all other aspects this is just FORM_DATA */
     }
-    alloc2 = newform->line;
-    memcpy(newform->line, line, (size_t)length);
     newform->length = (size_t)length;
-    newform->line[(size_t)length]=0; /* zero terminate for easier debugging */
   }
   else
     /* For callbacks and files we don't have any actual data so we just keep a
@@ -863,13 +870,6 @@ static CURLcode AddFormData(struct FormData **formp,
 
   newform->type = type;
 
-  if(*formp) {
-    (*formp)->next = newform;
-    *formp = newform;
-  }
-  else
-    *formp = newform;
-
   if(size) {
     if(type != FORM_FILE)
       /* for static content as well as callback data we add the size given
@@ -878,7 +878,7 @@ static CURLcode AddFormData(struct FormData **formp,
     else {
       /* Since this is a file to be uploaded here, add the size of the actual
          file */
-      if(!strequal("-", newform->line)) {
+      if(strcmp("-", newform->line)) {
         struct_stat file;
         if(!stat(newform->line, &file) && !S_ISDIR(file.st_mode))
           *size += filesize(newform->line, file);
@@ -889,6 +889,14 @@ static CURLcode AddFormData(struct FormData **formp,
       }
     }
   }
+
+  if(*formp) {
+    (*formp)->next = newform;
+    *formp = newform;
+  }
+  else
+    *formp = newform;
+
   return CURLE_OK;
   error:
   if(newform)
@@ -906,13 +914,21 @@ static CURLcode AddFormDataf(struct FormData **formp,
                              curl_off_t *size,
                              const char *fmt, ...)
 {
-  char s[4096];
+  char *s;
+  CURLcode result;
   va_list ap;
   va_start(ap, fmt);
-  vsnprintf(s, sizeof(s), fmt, ap);
+  s = curl_mvaprintf(fmt, ap);
   va_end(ap);
 
-  return AddFormData(formp, FORM_DATA, s, 0, size);
+  if(!s)
+    return CURLE_OUT_OF_MEMORY;
+
+  result = AddFormData(formp, FORM_DATAMEM, s, 0, size);
+  if(result)
+    free(s);
+
+  return result;
 }
 
 /*
@@ -1289,7 +1305,7 @@ CURLcode Curl_getformdata(struct Curl_easy *data,
         /* we should include the contents from the specified file */
         FILE *fileread;
 
-        fileread = strequal("-", file->contents)?
+        fileread = !strcmp("-", file->contents)?
           stdin:fopen(file->contents, "rb"); /* binary read for win32  */
 
         /*
diff --git a/Utilities/cmcurl/lib/formdata.h b/Utilities/cmcurl/lib/formdata.h
index 6eb7c6c..200470b 100644
--- a/Utilities/cmcurl/lib/formdata.h
+++ b/Utilities/cmcurl/lib/formdata.h
@@ -23,6 +23,7 @@
  ***************************************************************************/
 
 enum formtype {
+  FORM_DATAMEM, /* already allocated FORM_DATA memory */
   FORM_DATA,    /* form metadata (convert to network encoding if necessary) */
   FORM_CONTENT, /* form content  (never convert) */
   FORM_CALLBACK, /* 'line' points to the custom pointer we pass to the callback
diff --git a/Utilities/cmcurl/lib/ftp.c b/Utilities/cmcurl/lib/ftp.c
index b0165bc..9d0a03c 100644
--- a/Utilities/cmcurl/lib/ftp.c
+++ b/Utilities/cmcurl/lib/ftp.c
@@ -61,7 +61,7 @@
 #include "ftplistparser.h"
 #include "curl_sec.h"
 #include "strtoofft.h"
-#include "strequal.h"
+#include "strcase.h"
 #include "vtls/vtls.h"
 #include "connect.h"
 #include "strerror.h"
@@ -72,7 +72,7 @@
 #include "sockaddr.h" /* required for Curl_sockaddr_storage */
 #include "multiif.h"
 #include "url.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "speedcheck.h"
 #include "warnless.h"
 #include "http_proxy.h"
@@ -475,7 +475,7 @@ static CURLcode ReceivedServerConnect(struct connectdata *conn, bool *received)
       if(ftpcode/100 > 3)
         return CURLE_FTP_ACCEPT_FAILED;
 
-      return CURLE_FTP_WEIRD_SERVER_REPLY;
+      return CURLE_WEIRD_SERVER_REPLY;
     }
 
     break;
@@ -741,7 +741,7 @@ CURLcode Curl_GetFTPResponse(ssize_t *nreadp, /* return number of bytes read */
        */
     }
     else {
-      switch (Curl_socket_ready(sockfd, CURL_SOCKET_BAD, interval_ms)) {
+      switch (SOCKET_READABLE(sockfd, interval_ms)) {
       case -1: /* select() error, stop reading */
         failf(data, "FTP response aborted due to select/poll error: %d",
               SOCKERRNO);
@@ -911,7 +911,7 @@ static int ftp_domore_getsock(struct connectdata *conn, curl_socket_t *socks,
     }
     else {
       socks[1] = conn->sock[SECONDARYSOCKET];
-      bits |= GETSOCK_WRITESOCK(1);
+      bits |= GETSOCK_WRITESOCK(1) | GETSOCK_READSOCK(1);
     }
 
     return bits;
@@ -1835,7 +1835,7 @@ static CURLcode ftp_epsv_disable(struct connectdata *conn)
   if(conn->bits.ipv6) {
     /* We can't disable EPSV when doing IPv6, so this is instead a fail */
     failf(conn->data, "Failed EPSV attempt, exiting\n");
-    return CURLE_FTP_WEIRD_SERVER_REPLY;
+    return CURLE_WEIRD_SERVER_REPLY;
   }
 
   infof(conn->data, "Failed EPSV attempt. Disabling EPSV\n");
@@ -2742,7 +2742,7 @@ static CURLcode ftp_statemach_act(struct connectdata *conn)
       else if(ftpcode != 220) {
         failf(data, "Got a %03d ftp-server response when 220 was expected",
               ftpcode);
-        return CURLE_FTP_WEIRD_SERVER_REPLY;
+        return CURLE_WEIRD_SERVER_REPLY;
       }
 
       /* We have received a 220 response fine, now we proceed. */
@@ -2999,7 +2999,7 @@ static CURLcode ftp_statemach_act(struct connectdata *conn)
 
         /* Check for special servers here. */
 
-        if(strequal(os, "OS/400")) {
+        if(strcasecompare(os, "OS/400")) {
           /* Force OS400 name format 1. */
           result = Curl_pp_sendf(&ftpc->pp, "%s", "SITE NAMEFMT 1");
           if(result) {
@@ -3165,7 +3165,7 @@ static CURLcode ftp_multi_statemach(struct connectdata *conn,
   struct ftp_conn *ftpc = &conn->proto.ftpc;
   CURLcode result = Curl_pp_statemach(&ftpc->pp, FALSE);
 
-  /* Check for the state outside of the Curl_socket_ready() return code checks
+  /* Check for the state outside of the Curl_socket_check() return code checks
      since at times we are in fact already in this state when this function
      gets called. */
   *done = (ftpc->state == FTP_STOP) ? TRUE : FALSE;
@@ -3250,7 +3250,6 @@ static CURLcode ftp_done(struct connectdata *conn, CURLcode status,
   ssize_t nread;
   int ftpcode;
   CURLcode result = CURLE_OK;
-  bool was_ctl_valid = ftpc->ctl_valid;
   char *path;
   const char *path_to_use = data->state.path;
 
@@ -3274,10 +3273,9 @@ static CURLcode ftp_done(struct connectdata *conn, CURLcode status,
     /* the connection stays alive fine even though this happened */
     /* fall-through */
   case CURLE_OK: /* doesn't affect the control connection's status */
-    if(!premature) {
-      ftpc->ctl_valid = was_ctl_valid;
+    if(!premature)
       break;
-    }
+
     /* until we cope better with prematurely ended requests, let them
      * fallback as if in complete failure */
   default:       /* by default, an error means the control connection is
@@ -3300,13 +3298,12 @@ static CURLcode ftp_done(struct connectdata *conn, CURLcode status,
     ftpc->known_filesize = -1;
   }
 
-  /* get the "raw" path */
-  path = curl_easy_unescape(data, path_to_use, 0, NULL);
-  if(!path) {
-    /* out of memory, but we can limp along anyway (and should try to
-     * since we may already be in the out of memory cleanup path) */
-    if(!result)
-      result = CURLE_OUT_OF_MEMORY;
+  if(!result)
+    /* get the "raw" path */
+    result = Curl_urldecode(data, path_to_use, 0, &path, NULL, FALSE);
+  if(result) {
+    /* We can limp along anyway (and should try to since we may already be in
+     * the error path) */
     ftpc->ctl_valid = FALSE; /* mark control connection as bad */
     connclose(conn, "FTP: out of memory!"); /* mark for connection closure */
     ftpc->prevpath = NULL; /* no path remembering */
@@ -4094,8 +4091,7 @@ static CURLcode ftp_do(struct connectdata *conn, bool *done)
 }
 
 
-CURLcode Curl_ftpsendf(struct connectdata *conn,
-                       const char *fmt, ...)
+CURLcode Curl_ftpsend(struct connectdata *conn, const char *cmd)
 {
   ssize_t bytes_written;
 #define SBUF_SIZE 1024
@@ -4107,10 +4103,9 @@ CURLcode Curl_ftpsendf(struct connectdata *conn,
   enum protection_level data_sec = conn->data_prot;
 #endif
 
-  va_list ap;
-  va_start(ap, fmt);
-  write_len = vsnprintf(s, SBUF_SIZE-3, fmt, ap);
-  va_end(ap);
+  write_len = strlen(cmd);
+  if(write_len > (sizeof(s) -3))
+    return CURLE_BAD_FUNCTION_ARGUMENT;
 
   strcpy(&s[write_len], "\r\n"); /* append a trailing CRLF */
   write_len +=2;
@@ -4292,6 +4287,7 @@ CURLcode ftp_parse_url_path(struct connectdata *conn)
     slash_pos=strrchr(cur_pos, '/');
     if(slash_pos || !*cur_pos) {
       size_t dirlen = slash_pos-cur_pos;
+      CURLcode result;
 
       ftpc->dirs = calloc(1, sizeof(ftpc->dirs[0]));
       if(!ftpc->dirs)
@@ -4300,12 +4296,13 @@ CURLcode ftp_parse_url_path(struct connectdata *conn)
       if(!dirlen)
         dirlen++;
 
-      ftpc->dirs[0] = curl_easy_unescape(conn->data, slash_pos ? cur_pos : "/",
-                                         slash_pos ? curlx_uztosi(dirlen) : 1,
-                                         NULL);
-      if(!ftpc->dirs[0]) {
+      result = Curl_urldecode(conn->data, slash_pos ? cur_pos : "/",
+                              slash_pos ? dirlen : 1,
+                              &ftpc->dirs[0], NULL,
+                              FALSE);
+      if(result) {
         freedirs(ftpc);
-        return CURLE_OUT_OF_MEMORY;
+        return result;
       }
       ftpc->dirdepth = 1; /* we consider it to be a single dir */
       filename = slash_pos ? slash_pos+1 : cur_pos; /* rest is file name */
@@ -4323,7 +4320,7 @@ CURLcode ftp_parse_url_path(struct connectdata *conn)
       return CURLE_OUT_OF_MEMORY;
 
     /* we have a special case for listing the root dir only */
-    if(strequal(path_to_use, "/")) {
+    if(!strcmp(path_to_use, "/")) {
       cur_pos++; /* make it point to the zero byte */
       ftpc->dirs[0] = strdup("/");
       ftpc->dirdepth++;
@@ -4340,18 +4337,15 @@ CURLcode ftp_parse_url_path(struct connectdata *conn)
           /* we skip empty path components, like "x//y" since the FTP command
              CWD requires a parameter and a non-existent parameter a) doesn't
              work on many servers and b) has no effect on the others. */
-          int len = curlx_sztosi(slash_pos - cur_pos + absolute_dir);
-          ftpc->dirs[ftpc->dirdepth] =
-            curl_easy_unescape(conn->data, cur_pos - absolute_dir, len, NULL);
-          if(!ftpc->dirs[ftpc->dirdepth]) { /* run out of memory ... */
-            failf(data, "no memory");
-            freedirs(ftpc);
-            return CURLE_OUT_OF_MEMORY;
-          }
-          if(isBadFtpString(ftpc->dirs[ftpc->dirdepth])) {
+          size_t len = slash_pos - cur_pos + absolute_dir;
+          CURLcode result =
+            Curl_urldecode(conn->data, cur_pos - absolute_dir, len,
+                           &ftpc->dirs[ftpc->dirdepth], NULL,
+                           TRUE);
+          if(result) {
             free(ftpc->dirs[ftpc->dirdepth]);
             freedirs(ftpc);
-            return CURLE_URL_MALFORMAT;
+            return result;
           }
         }
         else {
@@ -4387,15 +4381,12 @@ CURLcode ftp_parse_url_path(struct connectdata *conn)
   } /* switch */
 
   if(filename && *filename) {
-    ftpc->file = curl_easy_unescape(conn->data, filename, 0, NULL);
-    if(NULL == ftpc->file) {
-      freedirs(ftpc);
-      failf(data, "no memory");
-      return CURLE_OUT_OF_MEMORY;
-    }
-    if(isBadFtpString(ftpc->file)) {
+    CURLcode result =
+      Curl_urldecode(conn->data, filename, 0,  &ftpc->file, NULL, TRUE);
+
+    if(result) {
       freedirs(ftpc);
-      return CURLE_URL_MALFORMAT;
+      return result;
     }
   }
   else
@@ -4413,16 +4404,18 @@ CURLcode ftp_parse_url_path(struct connectdata *conn)
   if(ftpc->prevpath) {
     /* prevpath is "raw" so we convert the input path before we compare the
        strings */
-    int dlen;
-    char *path = curl_easy_unescape(conn->data, data->state.path, 0, &dlen);
-    if(!path) {
+    size_t dlen;
+    char *path;
+    CURLcode result =
+      Curl_urldecode(conn->data, data->state.path, 0, &path, &dlen, FALSE);
+    if(result) {
       freedirs(ftpc);
-      return CURLE_OUT_OF_MEMORY;
+      return result;
     }
 
-    dlen -= ftpc->file?curlx_uztosi(strlen(ftpc->file)):0;
-    if((dlen == curlx_uztosi(strlen(ftpc->prevpath))) &&
-       strnequal(path, ftpc->prevpath, dlen)) {
+    dlen -= ftpc->file?strlen(ftpc->file):0;
+    if((dlen == strlen(ftpc->prevpath)) &&
+       !strncmp(path, ftpc->prevpath, dlen)) {
       infof(data, "Request has same path as previous transfer\n");
       ftpc->cwddone = TRUE;
     }
diff --git a/Utilities/cmcurl/lib/ftp.h b/Utilities/cmcurl/lib/ftp.h
index 2ed5b43..dbd8567 100644
--- a/Utilities/cmcurl/lib/ftp.h
+++ b/Utilities/cmcurl/lib/ftp.h
@@ -7,7 +7,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -31,7 +31,7 @@ extern const struct Curl_handler Curl_handler_ftp;
 extern const struct Curl_handler Curl_handler_ftps;
 #endif
 
-CURLcode Curl_ftpsendf(struct connectdata *, const char *fmt, ...);
+CURLcode Curl_ftpsend(struct connectdata *, const char *cmd);
 CURLcode Curl_GetFTPResponse(ssize_t *nread, struct connectdata *conn,
                              int *ftpcode);
 #endif /* CURL_DISABLE_FTP */
diff --git a/Utilities/cmcurl/lib/ftplistparser.c b/Utilities/cmcurl/lib/ftplistparser.c
index abbf76e..747dbba 100644
--- a/Utilities/cmcurl/lib/ftplistparser.c
+++ b/Utilities/cmcurl/lib/ftplistparser.c
@@ -5,7 +5,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -45,7 +45,6 @@
 #include "fileinfo.h"
 #include "llist.h"
 #include "strtoofft.h"
-#include "rawstr.h"
 #include "ftp.h"
 #include "ftplistparser.h"
 #include "curl_fnmatch.h"
diff --git a/Utilities/cmcurl/lib/getenv.c b/Utilities/cmcurl/lib/getenv.c
index 50bb79f..89d181d 100644
--- a/Utilities/cmcurl/lib/getenv.c
+++ b/Utilities/cmcurl/lib/getenv.c
@@ -30,7 +30,8 @@
 static
 char *GetEnv(const char *variable)
 {
-#ifdef _WIN32_WCE
+#if defined(_WIN32_WCE) || defined(CURL_WINDOWS_APP)
+  (void)variable;
   return NULL;
 #else
 #ifdef WIN32
diff --git a/Utilities/cmcurl/lib/getinfo.c b/Utilities/cmcurl/lib/getinfo.c
index 262cd93..9641d79 100644
--- a/Utilities/cmcurl/lib/getinfo.c
+++ b/Utilities/cmcurl/lib/getinfo.c
@@ -36,8 +36,8 @@
 #include "memdebug.h"
 
 /*
- * This is supposed to be called in the beginning of a perform() session
- * and should reset all session-info variables
+ * This is supposed to be called in the beginning of a perform() session and
+ * in curl_easy_reset() and should reset all session-info variables.
  */
 CURLcode Curl_initinfo(struct Curl_easy *data)
 {
@@ -58,18 +58,27 @@ CURLcode Curl_initinfo(struct Curl_easy *data)
   info->filetime = -1; /* -1 is an illegal time and thus means unknown */
   info->timecond = FALSE;
 
-  free(info->contenttype);
-  info->contenttype = NULL;
-
   info->header_size = 0;
   info->request_size = 0;
+  info->proxyauthavail = 0;
+  info->httpauthavail = 0;
   info->numconnects = 0;
 
+  free(info->contenttype);
+  info->contenttype = NULL;
+
+  free(info->wouldredirect);
+  info->wouldredirect = NULL;
+
   info->conn_primary_ip[0] = '\0';
   info->conn_local_ip[0] = '\0';
   info->conn_primary_port = 0;
   info->conn_local_port = 0;
 
+#ifdef USE_SSL
+  Curl_ssl_free_certinfo(data);
+#endif
+
   return CURLE_OK;
 }
 
diff --git a/Utilities/cmcurl/lib/gopher.c b/Utilities/cmcurl/lib/gopher.c
index f1efb60..a073d0b 100644
--- a/Utilities/cmcurl/lib/gopher.c
+++ b/Utilities/cmcurl/lib/gopher.c
@@ -5,7 +5,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -28,13 +28,11 @@
 #include <curl/curl.h>
 #include "transfer.h"
 #include "sendf.h"
-
 #include "progress.h"
-#include "strequal.h"
 #include "gopher.h"
-#include "rawstr.h"
 #include "select.h"
 #include "url.h"
+#include "escape.h"
 #include "warnless.h"
 #include "curl_memory.h"
 /* The last #include file should be: */
@@ -83,7 +81,7 @@ static CURLcode gopher_do(struct connectdata *conn, bool *done)
   char *sel;
   char *sel_org = NULL;
   ssize_t amount, k;
-  int len;
+  size_t len;
 
   *done = TRUE; /* unconditionally */
 
@@ -107,7 +105,7 @@ static CURLcode gopher_do(struct connectdata *conn, bool *done)
         newp[i] = '\x09';
 
     /* ... and finally unescape */
-    sel = curl_easy_unescape(data, newp, 0, &len);
+    result = Curl_urldecode(data, newp, 0, &sel, &len, FALSE);
     if(!sel)
       return CURLE_OUT_OF_MEMORY;
     sel_org = sel;
@@ -121,20 +119,17 @@ static CURLcode gopher_do(struct connectdata *conn, bool *done)
     result = Curl_write(conn, sockfd, sel, k, &amount);
     if(!result) { /* Which may not have written it all! */
       result = Curl_client_write(conn, CLIENTWRITE_HEADER, sel, amount);
-      if(result) {
-        free(sel_org);
-        return result;
-      }
+      if(result)
+        break;
+
       k -= amount;
       sel += amount;
       if(k < 1)
         break; /* but it did write it all */
     }
-    else {
-      failf(data, "Failed sending Gopher request");
-      free(sel_org);
-      return result;
-    }
+    else
+      break;
+
     /* Don't busyloop. The entire loop thing is a work-around as it causes a
        BLOCKING behavior which is a NO-NO. This function should rather be
        split up in a do and a doing piece where the pieces that aren't
@@ -144,14 +139,18 @@ static CURLcode gopher_do(struct connectdata *conn, bool *done)
        Wait a while for the socket to be writable. Note that this doesn't
        acknowledge the timeout.
     */
-    Curl_socket_ready(CURL_SOCKET_BAD, sockfd, 100);
+    if(SOCKET_WRITABLE(sockfd, 100) < 0) {
+      result = CURLE_SEND_ERROR;
+      break;
+    }
   }
 
   free(sel_org);
 
-  /* We can use Curl_sendf to send the terminal \r\n relatively safely and
-     save allocing another string/doing another _write loop. */
-  result = Curl_sendf(sockfd, conn, "\r\n");
+  if(!result)
+    /* We can use Curl_sendf to send the terminal \r\n relatively safely and
+       save allocing another string/doing another _write loop. */
+    result = Curl_sendf(sockfd, conn, "\r\n");
   if(result) {
     failf(data, "Failed sending Gopher request");
     return result;
diff --git a/Utilities/cmcurl/lib/hostcheck.c b/Utilities/cmcurl/lib/hostcheck.c
index 4db9e6b..f545254 100644
--- a/Utilities/cmcurl/lib/hostcheck.c
+++ b/Utilities/cmcurl/lib/hostcheck.c
@@ -30,7 +30,7 @@
 #endif
 
 #include "hostcheck.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "inet_pton.h"
 
 #include "curl_memory.h"
@@ -77,7 +77,7 @@ static int hostmatch(char *hostname, char *pattern)
 
   pattern_wildcard = strchr(pattern, '*');
   if(pattern_wildcard == NULL)
-    return Curl_raw_equal(pattern, hostname) ?
+    return strcasecompare(pattern, hostname) ?
       CURL_HOST_MATCH : CURL_HOST_NOMATCH;
 
   /* detect IP address as hostname and fail the match if so */
@@ -94,16 +94,16 @@ static int hostmatch(char *hostname, char *pattern)
   pattern_label_end = strchr(pattern, '.');
   if(pattern_label_end == NULL || strchr(pattern_label_end+1, '.') == NULL ||
      pattern_wildcard > pattern_label_end ||
-     Curl_raw_nequal(pattern, "xn--", 4)) {
+     strncasecompare(pattern, "xn--", 4)) {
     wildcard_enabled = 0;
   }
   if(!wildcard_enabled)
-    return Curl_raw_equal(pattern, hostname) ?
+    return strcasecompare(pattern, hostname) ?
       CURL_HOST_MATCH : CURL_HOST_NOMATCH;
 
   hostname_label_end = strchr(hostname, '.');
   if(hostname_label_end == NULL ||
-     !Curl_raw_equal(pattern_label_end, hostname_label_end))
+     !strcasecompare(pattern_label_end, hostname_label_end))
     return CURL_HOST_NOMATCH;
 
   /* The wildcard must match at least one character, so the left-most
@@ -114,8 +114,8 @@ static int hostmatch(char *hostname, char *pattern)
 
   prefixlen = pattern_wildcard - pattern;
   suffixlen = pattern_label_end - (pattern_wildcard+1);
-  return Curl_raw_nequal(pattern, hostname, prefixlen) &&
-    Curl_raw_nequal(pattern_wildcard+1, hostname_label_end - suffixlen,
+  return strncasecompare(pattern, hostname, prefixlen) &&
+    strncasecompare(pattern_wildcard+1, hostname_label_end - suffixlen,
                     suffixlen) ?
     CURL_HOST_MATCH : CURL_HOST_NOMATCH;
 }
diff --git a/Utilities/cmcurl/lib/hostip.c b/Utilities/cmcurl/lib/hostip.c
index f2d9841..24a922e 100644
--- a/Utilities/cmcurl/lib/hostip.c
+++ b/Utilities/cmcurl/lib/hostip.c
@@ -603,11 +603,14 @@ int Curl_resolv_timeout(struct connectdata *conn,
     /* USE_ALARM_TIMEOUT defined, but no timeout actually requested */
     return Curl_resolv(conn, hostname, port, entry);
 
-  if(timeout < 1000)
+  if(timeout < 1000) {
     /* The alarm() function only provides integer second resolution, so if
        we want to wait less than one second we must bail out already now. */
+    failf(data,
+        "remaining timeout of %ld too small to resolve via SIGALRM method",
+        timeout);
     return CURLRESOLV_TIMEDOUT;
-
+  }
   /* This allows us to time-out from the name resolver, as the timeout
      will generate a signal and we will siglongjmp() from that here.
      This technique has problems (see alarmfunc).
diff --git a/Utilities/cmcurl/lib/http.c b/Utilities/cmcurl/lib/http.c
index 378d8f7..e7788e7 100644
--- a/Utilities/cmcurl/lib/http.c
+++ b/Utilities/cmcurl/lib/http.c
@@ -53,7 +53,6 @@
 #include "progress.h"
 #include "curl_base64.h"
 #include "cookie.h"
-#include "strequal.h"
 #include "vauth/vauth.h"
 #include "vtls/vtls.h"
 #include "http_digest.h"
@@ -68,7 +67,7 @@
 #include "parsedate.h" /* for the week day and month names */
 #include "strtoofft.h"
 #include "multiif.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "content_encoding.h"
 #include "http_proxy.h"
 #include "warnless.h"
@@ -182,7 +181,7 @@ char *Curl_checkheaders(const struct connectdata *conn,
   struct Curl_easy *data = conn->data;
 
   for(head = data->set.headers;head; head=head->next) {
-    if(Curl_raw_nequal(head->data, thisheader, thislen))
+    if(strncasecompare(head->data, thisheader, thislen))
       return head->data;
   }
 
@@ -208,7 +207,7 @@ char *Curl_checkProxyheaders(const struct connectdata *conn,
   for(head = (conn->bits.proxy && data->set.sep_headers) ?
         data->set.proxyheaders : data->set.headers;
       head; head=head->next) {
-    if(Curl_raw_nequal(head->data, thisheader, thislen))
+    if(strncasecompare(head->data, thisheader, thislen))
       return head->data;
   }
 
@@ -462,7 +461,7 @@ static CURLcode http_perhapsrewind(struct connectdata *conn)
 #endif
 
     /* This is not NTLM or many bytes left to send: close */
-    connclose(conn, "Mid-auth HTTP and much data left to send");
+    streamclose(conn, "Mid-auth HTTP and much data left to send");
     data->req.size = 0; /* don't download any more than 0 bytes */
 
     /* There still is data left to send, but this connection is marked for
@@ -726,7 +725,7 @@ Curl_http_output_auth(struct connectdata *conn,
      conn->bits.netrc ||
      !data->state.first_host ||
      data->set.http_disable_hostname_check_before_authentication ||
-     Curl_raw_equal(data->state.first_host, conn->host.name)) {
+     strcasecompare(data->state.first_host, conn->host.name)) {
     result = output_auth_headers(conn, authhost, request, path, FALSE);
   }
   else
@@ -784,23 +783,27 @@ CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy,
   while(*auth) {
 #ifdef USE_SPNEGO
     if(checkprefix("Negotiate", auth)) {
-      *availp |= CURLAUTH_NEGOTIATE;
-      authp->avail |= CURLAUTH_NEGOTIATE;
-
-      if(authp->picked == CURLAUTH_NEGOTIATE) {
-        if(negdata->state == GSS_AUTHSENT || negdata->state == GSS_AUTHNONE) {
-          CURLcode result = Curl_input_negotiate(conn, proxy, auth);
-          if(!result) {
-            DEBUGASSERT(!data->req.newurl);
-            data->req.newurl = strdup(data->change.url);
-            if(!data->req.newurl)
-              return CURLE_OUT_OF_MEMORY;
-            data->state.authproblem = FALSE;
-            /* we received a GSS auth token and we dealt with it fine */
-            negdata->state = GSS_AUTHRECV;
+      if((authp->avail & CURLAUTH_NEGOTIATE) ||
+         Curl_auth_is_spnego_supported()) {
+        *availp |= CURLAUTH_NEGOTIATE;
+        authp->avail |= CURLAUTH_NEGOTIATE;
+
+        if(authp->picked == CURLAUTH_NEGOTIATE) {
+          if(negdata->state == GSS_AUTHSENT ||
+             negdata->state == GSS_AUTHNONE) {
+            CURLcode result = Curl_input_negotiate(conn, proxy, auth);
+            if(!result) {
+              DEBUGASSERT(!data->req.newurl);
+              data->req.newurl = strdup(data->change.url);
+              if(!data->req.newurl)
+                return CURLE_OUT_OF_MEMORY;
+              data->state.authproblem = FALSE;
+              /* we received a GSS auth token and we dealt with it fine */
+              negdata->state = GSS_AUTHRECV;
+            }
+            else
+              data->state.authproblem = TRUE;
           }
-          else
-            data->state.authproblem = TRUE;
         }
       }
     }
@@ -809,39 +812,44 @@ CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy,
 #ifdef USE_NTLM
       /* NTLM support requires the SSL crypto libs */
       if(checkprefix("NTLM", auth)) {
-        *availp |= CURLAUTH_NTLM;
-        authp->avail |= CURLAUTH_NTLM;
-        if(authp->picked == CURLAUTH_NTLM ||
-           authp->picked == CURLAUTH_NTLM_WB) {
-          /* NTLM authentication is picked and activated */
-          CURLcode result = Curl_input_ntlm(conn, proxy, auth);
-          if(!result) {
-            data->state.authproblem = FALSE;
+        if((authp->avail & CURLAUTH_NTLM) ||
+           (authp->avail & CURLAUTH_NTLM_WB) ||
+           Curl_auth_is_ntlm_supported()) {
+          *availp |= CURLAUTH_NTLM;
+          authp->avail |= CURLAUTH_NTLM;
+
+          if(authp->picked == CURLAUTH_NTLM ||
+             authp->picked == CURLAUTH_NTLM_WB) {
+            /* NTLM authentication is picked and activated */
+            CURLcode result = Curl_input_ntlm(conn, proxy, auth);
+            if(!result) {
+              data->state.authproblem = FALSE;
 #ifdef NTLM_WB_ENABLED
-            if(authp->picked == CURLAUTH_NTLM_WB) {
-              *availp &= ~CURLAUTH_NTLM;
-              authp->avail &= ~CURLAUTH_NTLM;
-              *availp |= CURLAUTH_NTLM_WB;
-              authp->avail |= CURLAUTH_NTLM_WB;
-
-              /* Get the challenge-message which will be passed to
-               * ntlm_auth for generating the type 3 message later */
-              while(*auth && ISSPACE(*auth))
-                auth++;
-              if(checkprefix("NTLM", auth)) {
-                auth += strlen("NTLM");
+              if(authp->picked == CURLAUTH_NTLM_WB) {
+                *availp &= ~CURLAUTH_NTLM;
+                authp->avail &= ~CURLAUTH_NTLM;
+                *availp |= CURLAUTH_NTLM_WB;
+                authp->avail |= CURLAUTH_NTLM_WB;
+
+                /* Get the challenge-message which will be passed to
+                 * ntlm_auth for generating the type 3 message later */
                 while(*auth && ISSPACE(*auth))
                   auth++;
-                if(*auth)
-                  if((conn->challenge_header = strdup(auth)) == NULL)
-                    return CURLE_OUT_OF_MEMORY;
+                if(checkprefix("NTLM", auth)) {
+                  auth += strlen("NTLM");
+                  while(*auth && ISSPACE(*auth))
+                    auth++;
+                  if(*auth)
+                    if((conn->challenge_header = strdup(auth)) == NULL)
+                      return CURLE_OUT_OF_MEMORY;
+                }
               }
-            }
 #endif
-          }
-          else {
-            infof(data, "Authentication problem. Ignoring this.\n");
-            data->state.authproblem = TRUE;
+            }
+            else {
+              infof(data, "Authentication problem. Ignoring this.\n");
+              data->state.authproblem = TRUE;
+            }
           }
         }
       }
@@ -849,18 +857,18 @@ CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy,
 #endif
 #ifndef CURL_DISABLE_CRYPTO_AUTH
         if(checkprefix("Digest", auth)) {
-          if((authp->avail & CURLAUTH_DIGEST) != 0) {
+          if((authp->avail & CURLAUTH_DIGEST) != 0)
             infof(data, "Ignoring duplicate digest auth header.\n");
-          }
-          else {
+          else if(Curl_auth_is_digest_supported()) {
             CURLcode result;
+
             *availp |= CURLAUTH_DIGEST;
             authp->avail |= CURLAUTH_DIGEST;
 
             /* We call this function on input Digest headers even if Digest
              * authentication isn't activated yet, as we need to store the
-             * incoming data from this header in case we are gonna use
-             * Digest. */
+             * incoming data from this header in case we are going to use
+             * Digest */
             result = Curl_input_digest(conn, proxy, auth);
             if(result) {
               infof(data, "Authentication problem. Ignoring this.\n");
@@ -1296,7 +1304,7 @@ Curl_compareheader(const char *headerline, /* line to check */
   const char *start;
   const char *end;
 
-  if(!Curl_raw_nequal(headerline, header, hlen))
+  if(!strncasecompare(headerline, header, hlen))
     return FALSE; /* doesn't start with header */
 
   /* pass the header */
@@ -1322,7 +1330,7 @@ Curl_compareheader(const char *headerline, /* line to check */
 
   /* find the content string in the rest of the line */
   for(;len>=clen;len--, start++) {
-    if(Curl_raw_nequal(start, content, clen))
+    if(strncasecompare(start, content, clen))
       return TRUE; /* match! */
   }
 
@@ -1443,9 +1451,8 @@ CURLcode Curl_http_done(struct connectdata *conn,
 {
   struct Curl_easy *data = conn->data;
   struct HTTP *http = data->req.protop;
-#ifdef USE_NGHTTP2
-  struct http_conn *httpc = &conn->proto.httpc;
-#endif
+
+  infof(data, "Curl_http_done: called premature == %d\n", premature);
 
   Curl_unencode_cleanup(conn);
 
@@ -1458,7 +1465,7 @@ CURLcode Curl_http_done(struct connectdata *conn,
      * Do not close CONNECT_ONLY connections. */
     if((data->req.httpcode != 401) && (data->req.httpcode != 407) &&
        !data->set.connect_only)
-      connclose(conn, "Negotiate transfer completed");
+      streamclose(conn, "Negotiate transfer completed");
     Curl_cleanup_negotiate(data);
   }
 #endif
@@ -1475,27 +1482,7 @@ CURLcode Curl_http_done(struct connectdata *conn,
     http->send_buffer = NULL; /* clear the pointer */
   }
 
-#ifdef USE_NGHTTP2
-  if(http->header_recvbuf) {
-    DEBUGF(infof(data, "free header_recvbuf!!\n"));
-    Curl_add_buffer_free(http->header_recvbuf);
-    http->header_recvbuf = NULL; /* clear the pointer */
-    Curl_add_buffer_free(http->trailer_recvbuf);
-    http->trailer_recvbuf = NULL; /* clear the pointer */
-    if(http->push_headers) {
-      /* if they weren't used and then freed before */
-      for(; http->push_headers_used > 0; --http->push_headers_used) {
-        free(http->push_headers[http->push_headers_used - 1]);
-      }
-      free(http->push_headers);
-      http->push_headers = NULL;
-    }
-  }
-  if(http->stream_id) {
-    nghttp2_session_set_stream_user_data(httpc->h2, http->stream_id, 0);
-    http->stream_id = 0;
-  }
-#endif
+  Curl_http2_done(conn, premature);
 
   if(HTTPREQ_POST_FORM == data->set.httpreq) {
     data->req.bytecount = http->readbytecount + http->writebytecount;
@@ -1660,6 +1647,10 @@ CURLcode Curl_add_custom_headers(struct connectdata *conn,
                      Connection: */
                   checkprefix("Connection", headers->data))
             ;
+          else if((conn->httpversion == 20) &&
+                  checkprefix("Transfer-Encoding:", headers->data))
+            /* HTTP/2 doesn't support chunked requests */
+            ;
           else {
             CURLcode result = Curl_add_bufferf(req_buffer, "%s\r\n",
                                                headers->data);
@@ -1946,47 +1937,42 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
   }
 #endif
 
-  if(conn->httpversion == 20)
-    /* In HTTP2 forbids Transfer-Encoding: chunked */
-    ptr = NULL;
+  ptr = Curl_checkheaders(conn, "Transfer-Encoding:");
+  if(ptr) {
+    /* Some kind of TE is requested, check if 'chunked' is chosen */
+    data->req.upload_chunky =
+      Curl_compareheader(ptr, "Transfer-Encoding:", "chunked");
+  }
   else {
-    ptr = Curl_checkheaders(conn, "Transfer-Encoding:");
-    if(ptr) {
-      /* Some kind of TE is requested, check if 'chunked' is chosen */
-      data->req.upload_chunky =
-        Curl_compareheader(ptr, "Transfer-Encoding:", "chunked");
-    }
-    else {
-      if((conn->handler->protocol&PROTO_FAMILY_HTTP) &&
-         data->set.upload &&
-         (data->state.infilesize == -1)) {
-        if(conn->bits.authneg)
-          /* don't enable chunked during auth neg */
-          ;
-        else if(use_http_1_1plus(data, conn)) {
-          /* HTTP, upload, unknown file size and not HTTP 1.0 */
-          data->req.upload_chunky = TRUE;
-        }
-        else {
-          failf(data, "Chunky upload is not supported by HTTP 1.0");
-          return CURLE_UPLOAD_FAILED;
-        }
+    if((conn->handler->protocol&PROTO_FAMILY_HTTP) &&
+       data->set.upload &&
+       (data->state.infilesize == -1)) {
+      if(conn->bits.authneg)
+        /* don't enable chunked during auth neg */
+        ;
+      else if(use_http_1_1plus(data, conn)) {
+        /* HTTP, upload, unknown file size and not HTTP 1.0 */
+        data->req.upload_chunky = TRUE;
       }
       else {
-        /* else, no chunky upload */
-        data->req.upload_chunky = FALSE;
+        failf(data, "Chunky upload is not supported by HTTP 1.0");
+        return CURLE_UPLOAD_FAILED;
       }
-
-      if(data->req.upload_chunky)
-        te = "Transfer-Encoding: chunked\r\n";
     }
+    else {
+      /* else, no chunky upload */
+      data->req.upload_chunky = FALSE;
+    }
+
+    if(data->req.upload_chunky)
+      te = "Transfer-Encoding: chunked\r\n";
   }
 
   Curl_safefree(conn->allocptr.host);
 
   ptr = Curl_checkheaders(conn, "Host:");
   if(ptr && (!data->state.this_is_a_follow ||
-             Curl_raw_equal(data->state.first_host, conn->host.name))) {
+             strcasecompare(data->state.first_host, conn->host.name))) {
 #if !defined(CURL_DISABLE_COOKIES)
     /* If we have a given custom Host: header, we extract the host name in
        order to possibly use it for cookie reasons later on. We only allow the
@@ -2305,6 +2291,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
                      "%s" /* TE: */
                      "%s" /* accept-encoding */
                      "%s" /* referer */
+                     "%s" /* Proxy-Connection */
                      "%s",/* transfer-encoding */
 
                      ftp_typecode,
@@ -2327,6 +2314,10 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
                      conn->allocptr.accept_encoding:"",
                      (data->change.referer && conn->allocptr.ref)?
                      conn->allocptr.ref:"" /* Referer: <data> */,
+                     (conn->bits.httpproxy &&
+                      !conn->bits.tunnel_proxy &&
+                      !Curl_checkProxyheaders(conn, "Proxy-Connection:"))?
+                     "Proxy-Connection: Keep-Alive\r\n":"",
                      te
       );
 
@@ -2392,7 +2383,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
         }
         co = co->next; /* next cookie please */
       }
-      Curl_cookie_freelist(store, FALSE); /* free the cookie list */
+      Curl_cookie_freelist(store);
     }
     if(addcookies && !result) {
       if(!count)
@@ -2768,6 +2759,11 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
     }
   }
 
+  if((conn->httpversion == 20) && data->req.upload_chunky)
+    /* upload_chunky was set above to set up the request in a chunky fashion,
+       but is disabled here again to avoid that the chunked encoded version is
+       actually used when sending the request body over h2 */
+    data->req.upload_chunky = FALSE;
   return result;
 }
 
@@ -3040,19 +3036,19 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
 #endif /* CURL_DOES_CONVERSIONS */
 
       if(100 <= k->httpcode && 199 >= k->httpcode) {
-        /*
-         * We have made a HTTP PUT or POST and this is 1.1-lingo
-         * that tells us that the server is OK with this and ready
-         * to receive the data.
-         * However, we'll get more headers now so we must get
-         * back into the header-parsing state!
-         */
-        k->header = TRUE;
-        k->headerline = 0; /* restart the header line counter */
-
         /* "A user agent MAY ignore unexpected 1xx status responses." */
         switch(k->httpcode) {
         case 100:
+          /*
+           * We have made a HTTP PUT or POST and this is 1.1-lingo
+           * that tells us that the server is OK with this and ready
+           * to receive the data.
+           * However, we'll get more headers now so we must get
+           * back into the header-parsing state!
+           */
+          k->header = TRUE;
+          k->headerline = 0; /* restart the header line counter */
+
           /* if we did wait for this do enable write now! */
           if(k->exp100 > EXP100_SEND_DATA) {
             k->exp100 = EXP100_SEND_DATA;
@@ -3062,9 +3058,14 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
         case 101:
           /* Switching Protocols */
           if(k->upgr101 == UPGR101_REQUESTED) {
+            /* Switching to HTTP/2 */
             infof(data, "Received 101\n");
             k->upgr101 = UPGR101_RECEIVED;
 
+            /* we'll get more headers (HTTP/2 response) */
+            k->header = TRUE;
+            k->headerline = 0; /* restart the header line counter */
+
             /* switch to http2 now. The bytes after response headers
                are also processed here, otherwise they are lost. */
             result = Curl_http2_switched(conn, k->str, *nread);
@@ -3072,8 +3073,16 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
               return result;
             *nread = 0;
           }
+          else {
+            /* Switching to another protocol (e.g. WebSocket) */
+            k->header = FALSE; /* no more header to parse! */
+          }
           break;
         default:
+          /* the status code 1xx indicates a provisional response, so
+             we'll get another set of headers */
+          k->header = TRUE;
+          k->headerline = 0; /* restart the header line counter */
           break;
         }
       }
@@ -3091,7 +3100,7 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
              signal the end of the document. */
           infof(data, "no chunk, no close, no size. Assume close to "
                 "signal end\n");
-          connclose(conn, "HTTP: No end-of-message indicator");
+          streamclose(conn, "HTTP: No end-of-message indicator");
         }
       }
 
@@ -3171,12 +3180,21 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
              * connection for closure after we've read the entire response.
              */
             if(!k->upload_done) {
-              infof(data, "HTTP error before end of send, stop sending\n");
-              connclose(conn, "Stop sending data before everything sent");
-              k->upload_done = TRUE;
-              k->keepon &= ~KEEP_SEND; /* don't send */
-              if(data->state.expect100header)
-                k->exp100 = EXP100_FAILED;
+              if(data->set.http_keep_sending_on_error) {
+                infof(data, "HTTP error before end of send, keep sending\n");
+                if(k->exp100 > EXP100_SEND_DATA) {
+                  k->exp100 = EXP100_SEND_DATA;
+                  k->keepon |= KEEP_SEND;
+                }
+              }
+              else {
+                infof(data, "HTTP error before end of send, stop sending\n");
+                streamclose(conn, "Stop sending data before everything sent");
+                k->upload_done = TRUE;
+                k->keepon &= ~KEEP_SEND; /* don't send */
+                if(data->state.expect100header)
+                  k->exp100 = EXP100_FAILED;
+              }
             }
             break;
 
@@ -3476,7 +3494,7 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
         /* Negative Content-Length is really odd, and we know it
            happens for example when older Apache servers send large
            files */
-        connclose(conn, "negative content-length");
+        streamclose(conn, "negative content-length");
         infof(data, "Negative content-length: %" CURL_FORMAT_CURL_OFF_T
               ", closing after transfer\n", contentlength);
       }
@@ -3549,7 +3567,7 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
        * the connection will close when this request has been
        * served.
        */
-      connclose(conn, "Connection: close used");
+      streamclose(conn, "Connection: close used");
     }
     else if(checkprefix("Transfer-Encoding:", k->p)) {
       /* One or more encodings. We check for chunked and/or a compression
diff --git a/Utilities/cmcurl/lib/http.h b/Utilities/cmcurl/lib/http.h
index 6529005..9fb669c 100644
--- a/Utilities/cmcurl/lib/http.h
+++ b/Utilities/cmcurl/lib/http.h
@@ -168,6 +168,7 @@ struct HTTP {
   const uint8_t *pausedata; /* pointer to data received in on_data_chunk */
   size_t pauselen; /* the number of bytes left in data */
   bool closed; /* TRUE on HTTP2 stream close */
+  bool close_handled; /* TRUE if stream closure is handled by libcurl */
   uint32_t error_code; /* HTTP/2 error code */
 
   char *mem;     /* points to a buffer in memory to store received data */
diff --git a/Utilities/cmcurl/lib/http2.c b/Utilities/cmcurl/lib/http2.c
index efc082d..cfdb327 100644
--- a/Utilities/cmcurl/lib/http2.c
+++ b/Utilities/cmcurl/lib/http2.c
@@ -29,7 +29,7 @@
 #include "http.h"
 #include "sendf.h"
 #include "curl_base64.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "multiif.h"
 #include "conncache.h"
 #include "url.h"
@@ -92,8 +92,9 @@ static int http2_perform_getsock(const struct connectdata *conn,
      because of renegotiation. */
   sock[0] = conn->sock[FIRSTSOCKET];
 
-  if(nghttp2_session_want_read(c->h2))
-    bitmap |= GETSOCK_READSOCK(FIRSTSOCKET);
+  /* in a HTTP/2 connection we can basically always get a frame so we should
+     always be ready for one */
+  bitmap |= GETSOCK_READSOCK(FIRSTSOCKET);
 
   if(nghttp2_session_want_write(c->h2))
     bitmap |= GETSOCK_WRITESOCK(FIRSTSOCKET);
@@ -150,6 +151,7 @@ void Curl_http2_setup_req(struct Curl_easy *data)
   http->pauselen = 0;
   http->error_code = NGHTTP2_NO_ERROR;
   http->closed = FALSE;
+  http->close_handled = FALSE;
   http->mem = data->state.buffer;
   http->len = BUFSIZE;
   http->memlen = 0;
@@ -184,7 +186,7 @@ const struct Curl_handler Curl_handler_http2 = {
   ZERO_NULL,                            /* readwrite */
   PORT_HTTP,                            /* defport */
   CURLPROTO_HTTP,                       /* protocol */
-  PROTOPT_NONE                          /* flags */
+  PROTOPT_STREAM                        /* flags */
 };
 
 const struct Curl_handler Curl_handler_http2_ssl = {
@@ -204,7 +206,7 @@ const struct Curl_handler Curl_handler_http2_ssl = {
   ZERO_NULL,                            /* readwrite */
   PORT_HTTP,                            /* defport */
   CURLPROTO_HTTPS,                      /* protocol */
-  PROTOPT_SSL                           /* flags */
+  PROTOPT_SSL | PROTOPT_STREAM          /* flags */
 };
 
 /*
@@ -317,7 +319,7 @@ char *curl_pushheader_byname(struct curl_pushheaders *h, const char *header)
      the middle of header, it could be matched in middle of the value,
      this is because we do prefix match.*/
   if(!h || !GOOD_EASY_HANDLE(h->data) || !header || !header[0] ||
-     Curl_raw_equal(header, ":") || strchr(header + 1, ':'))
+     !strcmp(header, ":") || strchr(header + 1, ':'))
     return NULL;
   else {
     struct HTTP *stream = h->data->req.protop;
@@ -488,8 +490,11 @@ static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame,
   }
 
   stream = data_s->req.protop;
-  if(!stream)
+  if(!stream) {
+    DEBUGF(infof(conn->data, "No proto pointer for stream: %x\n",
+                 stream_id));
     return NGHTTP2_ERR_CALLBACK_FAILURE;
+  }
 
   DEBUGF(infof(data_s, "on_frame_recv() header %x stream %x\n",
                frame->hd.type, stream_id));
@@ -547,7 +552,7 @@ static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame,
 
       /* if we receive data for another handle, wake that up */
       if(conn_s->data != data_s)
-        Curl_expire(data_s, 1);
+        Curl_expire(data_s, 0);
     }
     break;
   case NGHTTP2_PUSH_PROMISE:
@@ -621,8 +626,7 @@ static int on_data_chunk_recv(nghttp2_session *session, uint8_t flags,
 
   /* if we receive data for another handle, wake that up */
   if(conn->data != data_s)
-    Curl_expire(data_s, 1); /* TODO: fix so that this can be set to 0 for
-                               immediately? */
+    Curl_expire(data_s, 0);
 
   DEBUGF(infof(data_s, "%zu data received for stream %u "
                "(%zu left in buffer %p, total %zu)\n",
@@ -883,7 +887,7 @@ static int on_header(nghttp2_session *session, const nghttp2_frame *frame,
     Curl_add_buffer(stream->header_recvbuf, " \r\n", 3);
     /* if we receive data for another handle, wake that up */
     if(conn->data != data_s)
-      Curl_expire(data_s, 1);
+      Curl_expire(data_s, 0);
 
     DEBUGF(infof(data_s, "h2 status: HTTP/2 %03d (easy %p)\n",
                  stream->status_code, data_s));
@@ -899,7 +903,7 @@ static int on_header(nghttp2_session *session, const nghttp2_frame *frame,
   Curl_add_buffer(stream->header_recvbuf, "\r\n", 2);
   /* if we receive data for another handle, wake that up */
   if(conn->data != data_s)
-    Curl_expire(data_s, 1);
+    Curl_expire(data_s, 0);
 
   DEBUGF(infof(data_s, "h2 header: %.*s: %.*s\n", namelen, name, valuelen,
                value));
@@ -941,11 +945,12 @@ static ssize_t data_source_read_callback(nghttp2_session *session,
     memcpy(buf, stream->upload_mem, nread);
     stream->upload_mem += nread;
     stream->upload_len -= nread;
-    stream->upload_left -= nread;
+    if(data_s->state.infilesize != -1)
+      stream->upload_left -= nread;
   }
 
   if(stream->upload_left == 0)
-    *data_flags = 1;
+    *data_flags = NGHTTP2_DATA_FLAG_EOF;
   else if(nread == 0)
     return NGHTTP2_ERR_DEFERRED;
 
@@ -979,6 +984,43 @@ static int error_callback(nghttp2_session *session,
 }
 #endif
 
+void Curl_http2_done(struct connectdata *conn, bool premature)
+{
+  struct Curl_easy *data = conn->data;
+  struct HTTP *http = data->req.protop;
+  struct http_conn *httpc = &conn->proto.httpc;
+
+  if(http->header_recvbuf) {
+    DEBUGF(infof(data, "free header_recvbuf!!\n"));
+    Curl_add_buffer_free(http->header_recvbuf);
+    http->header_recvbuf = NULL; /* clear the pointer */
+    Curl_add_buffer_free(http->trailer_recvbuf);
+    http->trailer_recvbuf = NULL; /* clear the pointer */
+    if(http->push_headers) {
+      /* if they weren't used and then freed before */
+      for(; http->push_headers_used > 0; --http->push_headers_used) {
+        free(http->push_headers[http->push_headers_used - 1]);
+      }
+      free(http->push_headers);
+      http->push_headers = NULL;
+    }
+  }
+
+  if(premature) {
+    /* RST_STREAM */
+    nghttp2_submit_rst_stream(httpc->h2, NGHTTP2_FLAG_NONE, http->stream_id,
+                              NGHTTP2_STREAM_CLOSED);
+    if(http->stream_id == httpc->pause_stream_id) {
+      infof(data, "stopped the pause stream!\n");
+      httpc->pause_stream_id = 0;
+    }
+  }
+  if(http->stream_id) {
+    nghttp2_session_set_stream_user_data(httpc->h2, http->stream_id, 0);
+    http->stream_id = 0;
+  }
+}
+
 /*
  * Initialize nghttp2 for a Curl connection
  */
@@ -1091,9 +1133,10 @@ CURLcode Curl_http2_request_upgrade(Curl_send_buffer *req,
 /*
  * Returns nonzero if current HTTP/2 session should be closed.
  */
-static int should_close_session(struct http_conn *httpc) {
+static int should_close_session(struct http_conn *httpc)
+{
   return httpc->drain_total == 0 && !nghttp2_session_want_read(httpc->h2) &&
-         !nghttp2_session_want_write(httpc->h2);
+    !nghttp2_session_want_write(httpc->h2);
 }
 
 static int h2_session_send(struct Curl_easy *data,
@@ -1107,7 +1150,8 @@ static int h2_session_send(struct Curl_easy *data,
  */
 static int h2_process_pending_input(struct Curl_easy *data,
                                     struct http_conn *httpc,
-                                    CURLcode *err) {
+                                    CURLcode *err)
+{
   ssize_t nread;
   char *inbuf;
   ssize_t rv;
@@ -1155,9 +1199,41 @@ static int h2_process_pending_input(struct Curl_easy *data,
   return 0;
 }
 
+/*
+ * Called from transfer.c:done_sending when we stop uploading.
+ */
+CURLcode Curl_http2_done_sending(struct connectdata *conn)
+{
+  CURLcode result = CURLE_OK;
+
+  if((conn->handler == &Curl_handler_http2_ssl) ||
+     (conn->handler == &Curl_handler_http2)) {
+    /* make sure this is only attempted for HTTP/2 transfers */
+
+    struct HTTP *stream = conn->data->req.protop;
+
+    if(stream->upload_left) {
+      /* If the stream still thinks there's data left to upload. */
+      struct http_conn *httpc = &conn->proto.httpc;
+      nghttp2_session *h2 = httpc->h2;
+
+      stream->upload_left = 0; /* DONE! */
+
+      /* resume sending here to trigger the callback to get called again so
+         that it can signal EOF to nghttp2 */
+      (void)nghttp2_session_resume_data(h2, stream->stream_id);
+
+      (void)h2_process_pending_input(conn->data, httpc, &result);
+    }
+  }
+  return result;
+}
+
+
 static ssize_t http2_handle_stream_close(struct connectdata *conn,
                                          struct Curl_easy *data,
-                                         struct HTTP *stream, CURLcode *err) {
+                                         struct HTTP *stream, CURLcode *err)
+{
   char *trailer_pos, *trailer_end;
   CURLcode result;
   struct http_conn *httpc = &conn->proto.httpc;
@@ -1178,8 +1254,7 @@ static ssize_t http2_handle_stream_close(struct connectdata *conn,
 
   DEBUGASSERT(data->state.drain == 0);
 
-  /* Reset to FALSE to prevent infinite loop in readwrite_data
-   function. */
+  /* Reset to FALSE to prevent infinite loop in readwrite_data function. */
   stream->closed = FALSE;
   if(stream->error_code != NGHTTP2_NO_ERROR) {
     failf(data, "HTTP/2 stream %u was not closed cleanly: %s (err %d)",
@@ -1216,6 +1291,8 @@ static ssize_t http2_handle_stream_close(struct connectdata *conn,
     }
   }
 
+  stream->close_handled = TRUE;
+
   DEBUGF(infof(data, "http2_recv returns 0, http2_handle_stream_close\n"));
   return 0;
 }
@@ -1268,10 +1345,6 @@ static int h2_session_send(struct Curl_easy *data,
   return nghttp2_session_send(h2);
 }
 
-/*
- * If the read would block (EWOULDBLOCK) we return -1. Otherwise we return
- * a regular CURLcode value.
- */
 static ssize_t http2_recv(struct connectdata *conn, int sockindex,
                           char *mem, size_t len, CURLcode *err)
 {
@@ -1382,6 +1455,8 @@ static ssize_t http2_recv(struct connectdata *conn, int sockindex,
        socket is not read.  But it seems that usually streams are
        notified with its drain property, and socket is read again
        quickly. */
+    DEBUGF(infof(data, "stream %x is paused, pause id: %x\n",
+                 stream->stream_id, httpc->pause_stream_id));
     *err = CURLE_AGAIN;
     return -1;
   }
@@ -1497,7 +1572,6 @@ static ssize_t http2_recv(struct connectdata *conn, int sockindex,
 #define HEADER_OVERFLOW(x) \
   (x.namelen > (uint16_t)-1 || x.valuelen > (uint16_t)-1 - x.namelen)
 
-/* return number of received (decrypted) bytes */
 static ssize_t http2_send(struct connectdata *conn, int sockindex,
                           const void *mem, size_t len, CURLcode *err)
 {
@@ -1525,6 +1599,14 @@ static ssize_t http2_send(struct connectdata *conn, int sockindex,
   DEBUGF(infof(conn->data, "http2_send len=%zu\n", len));
 
   if(stream->stream_id != -1) {
+    if(stream->close_handled) {
+      infof(conn->data, "stream %d closed\n", stream->stream_id);
+      *err = CURLE_HTTP2_STREAM;
+      return -1;
+    }
+    else if(stream->closed) {
+      return http2_handle_stream_close(conn, conn->data, stream, err);
+    }
     /* If stream_id != -1, we have dispatched request HEADERS, and now
        are going to send or sending request body in DATA frame */
     stream->upload_mem = mem;
@@ -1661,12 +1743,12 @@ static ssize_t http2_send(struct connectdata *conn, int sockindex,
       goto fail;
     hlen = end - hdbuf;
 
-    if(hlen == 10 && Curl_raw_nequal("connection", hdbuf, 10)) {
+    if(hlen == 10 && strncasecompare("connection", hdbuf, 10)) {
       /* skip Connection: headers! */
       skip = 1;
       --nheader;
     }
-    else if(hlen == 4 && Curl_raw_nequal("host", hdbuf, 4)) {
+    else if(hlen == 4 && strncasecompare("host", hdbuf, 4)) {
       authority_idx = i;
       nva[i].name = (unsigned char *)":authority";
       nva[i].namelen = strlen((char *)nva[i].name);
@@ -1687,28 +1769,6 @@ static ssize_t http2_send(struct connectdata *conn, int sockindex,
         failf(conn->data, "Failed sending HTTP request: Header overflow");
         goto fail;
       }
-      /* Inspect Content-Length header field and retrieve the request
-         entity length so that we can set END_STREAM to the last DATA
-         frame. */
-      if(nva[i].namelen == 14 &&
-         Curl_raw_nequal("content-length", (char*)nva[i].name, 14)) {
-        size_t j;
-        stream->upload_left = 0;
-        if(!nva[i].valuelen)
-          goto fail;
-        for(j = 0; j < nva[i].valuelen; ++j) {
-          if(nva[i].value[j] < '0' || nva[i].value[j] > '9')
-            goto fail;
-          if(stream->upload_left >= CURL_OFF_T_MAX / 10)
-            goto fail;
-          stream->upload_left *= 10;
-          stream->upload_left += nva[i].value[j] - '0';
-        }
-        DEBUGF(infof(conn->data,
-                     "request content-length=%"
-                     CURL_FORMAT_CURL_OFF_T
-                     "\n", stream->upload_left));
-      }
       ++i;
     }
   }
@@ -1736,6 +1796,10 @@ static ssize_t http2_send(struct connectdata *conn, int sockindex,
       if(nva[i].valuelen > max_acc - acc)
         break;
       acc += nva[i].valuelen;
+
+      DEBUGF(infof(conn->data, "h2 header: %.*s:%.*s\n",
+                   nva[i].namelen, nva[i].name,
+                   nva[i].valuelen, nva[i].value));
     }
 
     if(i != nheader) {
@@ -1751,6 +1815,12 @@ static ssize_t http2_send(struct connectdata *conn, int sockindex,
   case HTTPREQ_POST:
   case HTTPREQ_POST_FORM:
   case HTTPREQ_PUT:
+    if(conn->data->state.infilesize != -1)
+      stream->upload_left = conn->data->state.infilesize;
+    else
+      /* data sending without specifying the data amount up front */
+      stream->upload_left = -1; /* unknown, but not zero */
+
     data_prd.read_callback = data_source_read_callback;
     data_prd.source.ptr = NULL;
     stream_id = nghttp2_submit_request(h2, &pri_spec, nva, nheader,
@@ -1850,10 +1920,6 @@ CURLcode Curl_http2_setup(struct connectdata *conn)
   infof(conn->data, "Connection state changed (HTTP/2 confirmed)\n");
   Curl_multi_connchanged(conn->data->multi);
 
-  /* switch on TCP_NODELAY as we need to send off packets without delay for
-     maximum throughput */
-  Curl_tcpnodelay(conn, conn->sock[FIRSTSOCKET]);
-
   return CURLE_OK;
 }
 
diff --git a/Utilities/cmcurl/lib/http2.h b/Utilities/cmcurl/lib/http2.h
index bedbebf..8917535 100644
--- a/Utilities/cmcurl/lib/http2.h
+++ b/Utilities/cmcurl/lib/http2.h
@@ -7,7 +7,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -51,6 +51,8 @@ CURLcode Curl_http2_switched(struct connectdata *conn,
 /* called from Curl_http_setup_conn */
 void Curl_http2_setup_conn(struct connectdata *conn);
 void Curl_http2_setup_req(struct Curl_easy *data);
+void Curl_http2_done(struct connectdata *conn, bool premature);
+CURLcode Curl_http2_done_sending(struct connectdata *conn);
 #else /* USE_NGHTTP2 */
 #define Curl_http2_init(x) CURLE_UNSUPPORTED_PROTOCOL
 #define Curl_http2_send_request(x) CURLE_UNSUPPORTED_PROTOCOL
@@ -61,6 +63,8 @@ void Curl_http2_setup_req(struct Curl_easy *data);
 #define Curl_http2_setup_req(x)
 #define Curl_http2_init_state(x)
 #define Curl_http2_init_userset(x)
+#define Curl_http2_done(x,y)
+#define Curl_http2_done_sending(x)
 #endif
 
 #endif /* HEADER_CURL_HTTP2_H */
diff --git a/Utilities/cmcurl/lib/http_digest.c b/Utilities/cmcurl/lib/http_digest.c
index 97230e7..184d00b 100644
--- a/Utilities/cmcurl/lib/http_digest.c
+++ b/Utilities/cmcurl/lib/http_digest.c
@@ -25,7 +25,7 @@
 #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH)
 
 #include "urldata.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "vauth/vauth.h"
 #include "http_digest.h"
 /* The last 3 #include files should be in this order */
diff --git a/Utilities/cmcurl/lib/http_negotiate.c b/Utilities/cmcurl/lib/http_negotiate.c
index c39d6f3..eb17ed4 100644
--- a/Utilities/cmcurl/lib/http_negotiate.c
+++ b/Utilities/cmcurl/lib/http_negotiate.c
@@ -26,7 +26,6 @@
 
 #include "urldata.h"
 #include "sendf.h"
-#include "rawstr.h"
 #include "http_negotiate.h"
 #include "vauth/vauth.h"
 
diff --git a/Utilities/cmcurl/lib/http_ntlm.c b/Utilities/cmcurl/lib/http_ntlm.c
index 935df25..e424040 100644
--- a/Utilities/cmcurl/lib/http_ntlm.c
+++ b/Utilities/cmcurl/lib/http_ntlm.c
@@ -35,7 +35,7 @@
 
 #include "urldata.h"
 #include "sendf.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "http_ntlm.h"
 #include "curl_ntlm_wb.h"
 #include "vauth/vauth.h"
diff --git a/Utilities/cmcurl/lib/http_proxy.c b/Utilities/cmcurl/lib/http_proxy.c
index c6b05e3..8f5e9b4 100644
--- a/Utilities/cmcurl/lib/http_proxy.c
+++ b/Utilities/cmcurl/lib/http_proxy.c
@@ -31,7 +31,6 @@
 #include "http.h"
 #include "url.h"
 #include "select.h"
-#include "rawstr.h"
 #include "progress.h"
 #include "non-ascii.h"
 #include "connect.h"
@@ -160,6 +159,7 @@ CURLcode Curl_proxyCONNECT(struct connectdata *conn,
 
       if(!result) {
         char *host=(char *)"";
+        const char *proxyconn="";
         const char *useragent="";
         const char *http = (conn->proxytype == CURLPROXY_HTTP_1_0) ?
           "1.0" : "1.1";
@@ -185,6 +185,9 @@ CURLcode Curl_proxyCONNECT(struct connectdata *conn,
             return CURLE_OUT_OF_MEMORY;
           }
         }
+        if(!Curl_checkProxyheaders(conn, "Proxy-Connection:"))
+          proxyconn = "Proxy-Connection: Keep-Alive\r\n";
+
         if(!Curl_checkProxyheaders(conn, "User-Agent:") &&
            data->set.str[STRING_USERAGENT])
           useragent = conn->allocptr.uagent;
@@ -194,13 +197,15 @@ CURLcode Curl_proxyCONNECT(struct connectdata *conn,
                            "CONNECT %s HTTP/%s\r\n"
                            "%s"  /* Host: */
                            "%s"  /* Proxy-Authorization */
-                           "%s", /* User-Agent */
+                           "%s"  /* User-Agent */
+                           "%s", /* Proxy-Connection */
                            hostheader,
                            http,
                            host,
                            conn->allocptr.proxyuserpwd?
                            conn->allocptr.proxyuserpwd:"",
-                           useragent);
+                           useragent,
+                           proxyconn);
 
         if(host && *host)
           free(host);
@@ -239,7 +244,7 @@ CURLcode Curl_proxyCONNECT(struct connectdata *conn,
     }
 
     if(!blocking) {
-      if(0 == Curl_socket_ready(tunnelsocket, CURL_SOCKET_BAD, 0))
+      if(0 == SOCKET_READABLE(tunnelsocket, 0))
         /* return so we'll be called again polling-style */
         return CURLE_OK;
       else {
@@ -274,8 +279,7 @@ CURLcode Curl_proxyCONNECT(struct connectdata *conn,
         }
 
         /* loop every second at least, less if the timeout is near */
-        switch (Curl_socket_ready(tunnelsocket, CURL_SOCKET_BAD,
-                                  check<1000L?check:1000)) {
+        switch (SOCKET_READABLE(tunnelsocket, check<1000L?check:1000)) {
         case -1: /* select() error, stop reading */
           error = SELECT_ERROR;
           failf(data, "Proxy CONNECT aborted due to select/poll error");
@@ -568,7 +572,7 @@ CURLcode Curl_proxyCONNECT(struct connectdata *conn,
       free(data->req.newurl);
       data->req.newurl = NULL;
       /* failure, close this connection to avoid re-use */
-      connclose(conn, "proxy CONNECT failure");
+      streamclose(conn, "proxy CONNECT failure");
       Curl_closesocket(conn, conn->sock[sockindex]);
       conn->sock[sockindex] = CURL_SOCKET_BAD;
     }
diff --git a/Utilities/cmcurl/lib/if2ip.c b/Utilities/cmcurl/lib/if2ip.c
index 2f92b2d..e6faa4b 100644
--- a/Utilities/cmcurl/lib/if2ip.c
+++ b/Utilities/cmcurl/lib/if2ip.c
@@ -51,7 +51,7 @@
 #endif
 
 #include "inet_ntop.h"
-#include "strequal.h"
+#include "strcase.h"
 #include "if2ip.h"
 /* The last 3 #include files should be in this order */
 #include "curl_printf.h"
@@ -102,7 +102,7 @@ bool Curl_if_is_interface_name(const char *interf)
 
   if(getifaddrs(&head) >= 0) {
     for(iface=head; iface != NULL; iface=iface->ifa_next) {
-      if(curl_strequal(iface->ifa_name, interf)) {
+      if(strcasecompare(iface->ifa_name, interf)) {
         result = TRUE;
         break;
       }
@@ -132,7 +132,7 @@ if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope,
     for(iface = head; iface != NULL; iface=iface->ifa_next) {
       if(iface->ifa_addr != NULL) {
         if(iface->ifa_addr->sa_family == af) {
-          if(curl_strequal(iface->ifa_name, interf)) {
+          if(strcasecompare(iface->ifa_name, interf)) {
             void *addr;
             char *ip;
             char scope[12] = "";
@@ -180,7 +180,7 @@ if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope,
           }
         }
         else if((res == IF2IP_NOT_FOUND) &&
-                curl_strequal(iface->ifa_name, interf)) {
+                strcasecompare(iface->ifa_name, interf)) {
           res = IF2IP_AF_NOT_SUPPORTED;
         }
       }
diff --git a/Utilities/cmcurl/lib/imap.c b/Utilities/cmcurl/lib/imap.c
index 123ea3b..4aa7dcc 100644
--- a/Utilities/cmcurl/lib/imap.c
+++ b/Utilities/cmcurl/lib/imap.c
@@ -68,16 +68,15 @@
 #include "http.h" /* for HTTP proxy tunnel stuff */
 #include "socks.h"
 #include "imap.h"
-
 #include "strtoofft.h"
-#include "strequal.h"
+#include "strcase.h"
 #include "vtls/vtls.h"
 #include "connect.h"
 #include "strerror.h"
 #include "select.h"
 #include "multiif.h"
 #include "url.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "curl_sasl.h"
 #include "warnless.h"
 
@@ -271,7 +270,7 @@ static bool imap_matchresp(const char *line, size_t len, const char *cmd)
 
   /* Does the command name match and is it followed by a space character or at
      the end of line? */
-  if(line + cmd_len <= end && Curl_raw_nequal(line, cmd, cmd_len) &&
+  if(line + cmd_len <= end && strncasecompare(line, cmd, cmd_len) &&
      (line[cmd_len] == ' ' || line + cmd_len + 2 == end))
     return TRUE;
 
@@ -846,7 +845,7 @@ static CURLcode imap_state_servergreet_resp(struct connectdata *conn,
 
   if(imapcode != 'O') {
     failf(data, "Got unexpected imap-server response");
-    result = CURLE_FTP_WEIRD_SERVER_REPLY; /* TODO: fix this code */
+    result = CURLE_WEIRD_SERVER_REPLY;
   }
   else
     result = imap_perform_capability(conn);
@@ -1179,7 +1178,7 @@ static CURLcode imap_state_fetch_resp(struct connectdata *conn, int imapcode,
   else {
     /* We don't know how to parse this line */
     failf(pp->conn->data, "Failed to parse FETCH response.");
-    result = CURLE_FTP_WEIRD_SERVER_REPLY; /* TODO: fix this code */
+    result = CURLE_WEIRD_SERVER_REPLY;
   }
 
   /* End of DO phase */
@@ -1198,7 +1197,7 @@ static CURLcode imap_state_fetch_final_resp(struct connectdata *conn,
   (void)instate; /* No use for this yet */
 
   if(imapcode != 'O')
-    result = CURLE_FTP_WEIRD_SERVER_REPLY; /* TODO: Fix error code */
+    result = CURLE_WEIRD_SERVER_REPLY;
   else
     /* End of DONE phase */
     state(conn, IMAP_STOP);
@@ -1275,7 +1274,7 @@ static CURLcode imap_statemach_act(struct connectdata *conn)
 
     /* Was there an error parsing the response line? */
     if(imapcode == -1)
-      return CURLE_FTP_WEIRD_SERVER_REPLY;
+      return CURLE_WEIRD_SERVER_REPLY;
 
     if(!imapcode)
       break;
@@ -1935,7 +1934,7 @@ static CURLcode imap_parse_url_options(struct connectdata *conn)
     while(*ptr && *ptr != ';')
       ptr++;
 
-    if(strnequal(key, "AUTH=", 5))
+    if(strncasecompare(key, "AUTH=", 5))
       result = Curl_sasl_parse_url_auth_option(&imapc->sasl,
                                                value, ptr - value);
     else
@@ -2031,28 +2030,28 @@ static CURLcode imap_parse_url_path(struct connectdata *conn)
        PARTIAL) stripping of the trailing slash character if it is present.
 
        Note: Unknown parameters trigger a URL_MALFORMAT error. */
-    if(Curl_raw_equal(name, "UIDVALIDITY") && !imap->uidvalidity) {
+    if(strcasecompare(name, "UIDVALIDITY") && !imap->uidvalidity) {
       if(valuelen > 0 && value[valuelen - 1] == '/')
         value[valuelen - 1] = '\0';
 
       imap->uidvalidity = value;
       value = NULL;
     }
-    else if(Curl_raw_equal(name, "UID") && !imap->uid) {
+    else if(strcasecompare(name, "UID") && !imap->uid) {
       if(valuelen > 0 && value[valuelen - 1] == '/')
         value[valuelen - 1] = '\0';
 
       imap->uid = value;
       value = NULL;
     }
-    else if(Curl_raw_equal(name, "SECTION") && !imap->section) {
+    else if(strcasecompare(name, "SECTION") && !imap->section) {
       if(valuelen > 0 && value[valuelen - 1] == '/')
         value[valuelen - 1] = '\0';
 
       imap->section = value;
       value = NULL;
     }
-    else if(Curl_raw_equal(name, "PARTIAL") && !imap->partial) {
+    else if(strcasecompare(name, "PARTIAL") && !imap->partial) {
       if(valuelen > 0 && value[valuelen - 1] == '/')
         value[valuelen - 1] = '\0';
 
diff --git a/Utilities/cmcurl/lib/krb5.c b/Utilities/cmcurl/lib/krb5.c
index 87ce8ee..5d5c003 100644
--- a/Utilities/cmcurl/lib/krb5.c
+++ b/Utilities/cmcurl/lib/krb5.c
@@ -182,7 +182,7 @@ krb5_auth(void *app_data, struct connectdata *conn)
   for(;;) {
     /* this really shouldn't be repeated here, but can't help it */
     if(service == srv_host) {
-      result = Curl_ftpsendf(conn, "AUTH GSSAPI");
+      result = Curl_ftpsend(conn, "AUTH GSSAPI");
       if(result)
         return -2;
 
@@ -243,16 +243,22 @@ krb5_auth(void *app_data, struct connectdata *conn)
       }
 
       if(output_buffer.length != 0) {
+        char *cmd;
+
         result = Curl_base64_encode(data, (char *)output_buffer.value,
                                     output_buffer.length, &p, &base64_sz);
         if(result) {
           Curl_infof(data, "base64-encoding: %s\n",
                      curl_easy_strerror(result));
-          ret = AUTH_CONTINUE;
+          ret = AUTH_ERROR;
           break;
         }
 
-        result = Curl_ftpsendf(conn, "ADAT %s", p);
+        cmd = aprintf("ADAT %s", p);
+        if(cmd)
+          result = Curl_ftpsend(conn, cmd);
+        else
+          result = CURLE_OUT_OF_MEMORY;
 
         free(p);
 
diff --git a/Utilities/cmcurl/lib/ldap.c b/Utilities/cmcurl/lib/ldap.c
index a164627..7dbc1b0 100644
--- a/Utilities/cmcurl/lib/ldap.c
+++ b/Utilities/cmcurl/lib/ldap.c
@@ -69,12 +69,11 @@
 #include "escape.h"
 #include "progress.h"
 #include "transfer.h"
-#include "strequal.h"
+#include "strcase.h"
 #include "strtok.h"
 #include "curl_ldap.h"
 #include "curl_multibyte.h"
 #include "curl_base64.h"
-#include "rawstr.h"
 #include "connect.h"
 /* The last 3 #include files should be in this order */
 #include "curl_printf.h"
@@ -284,7 +283,7 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
       /* Novell SDK supports DER or BASE64 files. */
       int cert_type = LDAPSSL_CERT_FILETYPE_B64;
       if((data->set.str[STRING_CERT_TYPE]) &&
-         (Curl_raw_equal(data->set.str[STRING_CERT_TYPE], "DER")))
+         (strcasecompare(data->set.str[STRING_CERT_TYPE], "DER")))
         cert_type = LDAPSSL_CERT_FILETYPE_DER;
       if(!ldap_ca) {
         failf(data, "LDAP local: ERROR %s CA cert not set!",
@@ -325,7 +324,7 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
     if(data->set.ssl.verifypeer) {
       /* OpenLDAP SDK supports BASE64 files. */
       if((data->set.str[STRING_CERT_TYPE]) &&
-         (!Curl_raw_equal(data->set.str[STRING_CERT_TYPE], "PEM"))) {
+         (!strcasecompare(data->set.str[STRING_CERT_TYPE], "PEM"))) {
         failf(data, "LDAP local: ERROR OpenLDAP only supports PEM cert-type!");
         result = CURLE_SSL_CERTPROBLEM;
         goto quit;
@@ -708,16 +707,16 @@ static void _ldap_trace (const char *fmt, ...)
  */
 static int str2scope (const char *p)
 {
-  if(strequal(p, "one"))
-     return LDAP_SCOPE_ONELEVEL;
-  if(strequal(p, "onetree"))
-     return LDAP_SCOPE_ONELEVEL;
-  if(strequal(p, "base"))
-     return LDAP_SCOPE_BASE;
-  if(strequal(p, "sub"))
-     return LDAP_SCOPE_SUBTREE;
-  if(strequal(p, "subtree"))
-     return LDAP_SCOPE_SUBTREE;
+  if(strcasecompare(p, "one"))
+    return LDAP_SCOPE_ONELEVEL;
+  if(strcasecompare(p, "onetree"))
+    return LDAP_SCOPE_ONELEVEL;
+  if(strcasecompare(p, "base"))
+    return LDAP_SCOPE_BASE;
+  if(strcasecompare(p, "sub"))
+    return LDAP_SCOPE_SUBTREE;
+  if(strcasecompare(p, "subtree"))
+    return LDAP_SCOPE_SUBTREE;
   return (-1);
 }
 
@@ -767,7 +766,7 @@ static bool split_str(char *str, char ***out, size_t *count)
  *
  * Defined in RFC4516 section 2.
  */
-static int _ldap_url_parse2 (const struct connectdata *conn, LDAPURLDesc *ludp)
+static int _ldap_url_parse2(const struct connectdata *conn, LDAPURLDesc *ludp)
 {
   int rc = LDAP_SUCCESS;
   char *path;
@@ -776,9 +775,9 @@ static int _ldap_url_parse2 (const struct connectdata *conn, LDAPURLDesc *ludp)
   size_t i;
 
   if(!conn->data ||
-      !conn->data->state.path ||
-      conn->data->state.path[0] != '/' ||
-      !checkprefix("LDAP", conn->data->change.url))
+     !conn->data->state.path ||
+     conn->data->state.path[0] != '/' ||
+     !checkprefix("LDAP", conn->data->change.url))
     return LDAP_INVALID_SYNTAX;
 
   ludp->lud_scope = LDAP_SCOPE_BASE;
@@ -798,12 +797,13 @@ static int _ldap_url_parse2 (const struct connectdata *conn, LDAPURLDesc *ludp)
   if(*p) {
     char *dn = p;
     char *unescaped;
+    CURLcode result;
 
     LDAP_TRACE (("DN '%s'\n", dn));
 
     /* Unescape the DN */
-    unescaped = curl_easy_unescape(conn->data, dn, 0, NULL);
-    if(!unescaped) {
+    result = Curl_urldecode(conn->data, dn, 0, &unescaped, NULL, FALSE);
+    if(result) {
       rc = LDAP_NO_MEMORY;
 
       goto quit;
@@ -862,12 +862,14 @@ static int _ldap_url_parse2 (const struct connectdata *conn, LDAPURLDesc *ludp)
 
     for(i = 0; i < count; i++) {
       char *unescaped;
+      CURLcode result;
 
       LDAP_TRACE (("attr[%d] '%s'\n", i, attributes[i]));
 
       /* Unescape the attribute */
-      unescaped = curl_easy_unescape(conn->data, attributes[i], 0, NULL);
-      if(!unescaped) {
+      result = Curl_urldecode(conn->data, attributes[i], 0, &unescaped, NULL,
+                              FALSE);
+      if(result) {
         free(attributes);
 
         rc = LDAP_NO_MEMORY;
@@ -930,12 +932,13 @@ static int _ldap_url_parse2 (const struct connectdata *conn, LDAPURLDesc *ludp)
   if(*p) {
     char *filter = p;
     char *unescaped;
+    CURLcode result;
 
     LDAP_TRACE (("filter '%s'\n", filter));
 
     /* Unescape the filter */
-    unescaped = curl_easy_unescape(conn->data, filter, 0, NULL);
-    if(!unescaped) {
+    result = Curl_urldecode(conn->data, filter, 0, &unescaped, NULL, FALSE);
+    if(result) {
       rc = LDAP_NO_MEMORY;
 
       goto quit;
@@ -971,8 +974,8 @@ quit:
   return rc;
 }
 
-static int _ldap_url_parse (const struct connectdata *conn,
-                            LDAPURLDesc **ludpp)
+static int _ldap_url_parse(const struct connectdata *conn,
+                           LDAPURLDesc **ludpp)
 {
   LDAPURLDesc *ludp = calloc(1, sizeof(*ludp));
   int rc;
@@ -981,7 +984,7 @@ static int _ldap_url_parse (const struct connectdata *conn,
   if(!ludp)
      return LDAP_NO_MEMORY;
 
-  rc = _ldap_url_parse2 (conn, ludp);
+  rc = _ldap_url_parse2(conn, ludp);
   if(rc != LDAP_SUCCESS) {
     _ldap_free_urldesc(ludp);
     ludp = NULL;
@@ -990,7 +993,7 @@ static int _ldap_url_parse (const struct connectdata *conn,
   return (rc);
 }
 
-static void _ldap_free_urldesc (LDAPURLDesc *ludp)
+static void _ldap_free_urldesc(LDAPURLDesc *ludp)
 {
   size_t i;
 
diff --git a/Utilities/cmcurl/lib/libcurl.rc b/Utilities/cmcurl/lib/libcurl.rc
index 50b365d..c1efbad 100644
--- a/Utilities/cmcurl/lib/libcurl.rc
+++ b/Utilities/cmcurl/lib/libcurl.rc
@@ -5,7 +5,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -44,12 +44,12 @@ BEGIN
   BEGIN
     BLOCK "040904b0"
     BEGIN
-      VALUE "CompanyName",      "The cURL library, https://curl.haxx.se/\0"
+      VALUE "CompanyName",      "The curl library, https://curl.haxx.se/\0"
       VALUE "FileDescription",  "libcurl Shared Library\0"
       VALUE "FileVersion",      LIBCURL_VERSION "\0"
       VALUE "InternalName",     "libcurl\0"
       VALUE "OriginalFilename", "libcurl.dll\0"
-      VALUE "ProductName",      "The cURL library\0"
+      VALUE "ProductName",      "The curl library\0"
       VALUE "ProductVersion",   LIBCURL_VERSION "\0"
       VALUE "LegalCopyright",   "� " LIBCURL_COPYRIGHT "\0"
       VALUE "License",          "https://curl.haxx.se/docs/copyright.html\0"
diff --git a/Utilities/cmcurl/lib/md5.c b/Utilities/cmcurl/lib/md5.c
index 84adb99..f818d32 100644
--- a/Utilities/cmcurl/lib/md5.c
+++ b/Utilities/cmcurl/lib/md5.c
@@ -124,7 +124,7 @@ static void MD5_Final(unsigned char digest[16], MD5_CTX *ctx)
   CC_MD5_Final(digest, ctx);
 }
 
-#elif defined(_WIN32)
+#elif defined(_WIN32) && !defined(CURL_WINDOWS_APP)
 
 #include <wincrypt.h>
 #include "curl_memory.h"
diff --git a/Utilities/cmcurl/lib/mprintf.c b/Utilities/cmcurl/lib/mprintf.c
index 380c3d6..3cdd41a 100644
--- a/Utilities/cmcurl/lib/mprintf.c
+++ b/Utilities/cmcurl/lib/mprintf.c
@@ -223,10 +223,12 @@ static bool dprintf_IsQualifierNoDollar(const char *fmt)
  * Create an index with the type of each parameter entry and its
  * value (may vary in size)
  *
+ * Returns zero on success.
+ *
  ******************************************************************/
 
-static long dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos,
-                          va_list arglist)
+static int dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos,
+                         va_list arglist)
 {
   char *fmt = (char *)format;
   int param_num = 0;
@@ -389,6 +391,10 @@ static long dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos,
 
       i = this_param - 1;
 
+      if((i < 0) || (i >= MAX_PARAMETERS))
+        /* out of allowed range */
+        return 1;
+
       switch (*fmt) {
       case 'S':
         flags |= FLAGS_ALT;
@@ -545,7 +551,7 @@ static long dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos,
     }
   }
 
-  return max_param;
+  return 0;
 
 }
 
@@ -583,7 +589,8 @@ static int dprintf_formatf(
   char *workend = &work[sizeof(work) - 2];
 
   /* Do the actual %-code parsing */
-  dprintf_Pass1(format, vto, endpos, ap_save);
+  if(dprintf_Pass1(format, vto, endpos, ap_save))
+    return -1;
 
   end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1()
                        created for us */
@@ -988,7 +995,7 @@ int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format,
   info.max = maxlength;
 
   retcode = dprintf_formatf(&info, addbyter, format, ap_save);
-  if(info.max) {
+  if((retcode != -1) && info.max) {
     /* we terminate this with a zero byte */
     if(info.max == info.length)
       /* we're at maximum, scrap the last letter */
@@ -1025,16 +1032,19 @@ static int alloc_addbyter(int output, FILE *data)
     infop->len =0;
   }
   else if(infop->len+1 >= infop->alloc) {
-    char *newptr;
+    char *newptr = NULL;
+    size_t newsize = infop->alloc*2;
 
-    newptr = realloc(infop->buffer, infop->alloc*2);
+    /* detect wrap-around or other overflow problems */
+    if(newsize > infop->alloc)
+      newptr = realloc(infop->buffer, newsize);
 
     if(!newptr) {
       infop->fail = 1;
       return -1; /* fail */
     }
     infop->buffer = newptr;
-    infop->alloc *= 2;
+    infop->alloc = newsize;
   }
 
   infop->buffer[ infop->len ] = outc;
diff --git a/Utilities/cmcurl/lib/multi.c b/Utilities/cmcurl/lib/multi.c
index 8bb9366..2432b15 100644
--- a/Utilities/cmcurl/lib/multi.c
+++ b/Utilities/cmcurl/lib/multi.c
@@ -42,6 +42,7 @@
 #include "multihandle.h"
 #include "pipeline.h"
 #include "sigpipe.h"
+#include "connect.h"
 /* The last 3 #include files should be in this order */
 #include "curl_printf.h"
 #include "curl_memory.h"
@@ -442,7 +443,7 @@ CURLMcode curl_multi_add_handle(struct Curl_multi *multi,
      sockets that time-out or have actions will be dealt with. Since this
      handle has no action yet, we make sure it times out to get things to
      happen. */
-  Curl_expire(data, 1);
+  Curl_expire(data, 0);
 
   /* increase the node-counter */
   multi->num_easy++;
@@ -462,6 +463,14 @@ CURLMcode curl_multi_add_handle(struct Curl_multi *multi,
      handle is added */
   memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
 
+  /* The closure handle only ever has default timeouts set. To improve the
+     state somewhat we clone the timeouts from each added handle so that the
+     closure handle always has the same timeouts as the most recently added
+     easy handle. */
+  multi->closure_handle->set.timeout = data->set.timeout;
+  multi->closure_handle->set.server_response_timeout =
+    data->set.server_response_timeout;
+
   update_timer(multi);
   return CURLM_OK;
 }
@@ -569,12 +578,12 @@ static CURLcode multi_done(struct connectdata **connp,
       result = CURLE_ABORTED_BY_CALLBACK;
   }
 
-  if((!premature &&
-      conn->send_pipe->size + conn->recv_pipe->size != 0 &&
-      !data->set.reuse_forbid &&
-      !conn->bits.close)) {
+  if(conn->send_pipe->size + conn->recv_pipe->size != 0 &&
+     !data->set.reuse_forbid &&
+     !conn->bits.close) {
     /* Stop if pipeline is not empty and we do not have to close
        connection. */
+    data->easy_conn = NULL;
     DEBUGF(infof(data, "Connection still in use, no more multi_done now!\n"));
     return CURLE_OK;
   }
@@ -685,7 +694,7 @@ CURLMcode curl_multi_remove_handle(struct Curl_multi *multi,
     /* If the handle is in a pipeline and has started sending off its
        request but not received its response yet, we need to close
        connection. */
-    connclose(data->easy_conn, "Removed with partial response");
+    streamclose(data->easy_conn, "Removed with partial response");
     /* Set connection owner so that the DONE function closes it.  We can
        safely do this here since connection is killed. */
     data->easy_conn->data = easy;
@@ -695,7 +704,7 @@ CURLMcode curl_multi_remove_handle(struct Curl_multi *multi,
   /* The timer must be shut down before data->multi is set to NULL,
      else the timenode will remain in the splay tree after
      curl_easy_cleanup is called. */
-  Curl_expire(data, 0);
+  Curl_expire_clear(data);
 
   if(data->dns.hostcachetype == HCACHE_MULTI) {
     /* stop using the multi handle's DNS cache */
@@ -1298,7 +1307,9 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
     return CURLM_BAD_EASY_HANDLE;
 
   do {
-    bool disconnect_conn = FALSE;
+    /* A "stream" here is a logical stream if the protocol can handle that
+       (HTTP/2), or the full connection for older protocols */
+    bool stream_error = FALSE;
     rc = CURLM_OK;
 
     /* Handle the case when the pipe breaks, i.e., the connection
@@ -1376,8 +1387,8 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
 
         /* Force connection closed if the connection has indeed been used */
         if(data->mstate > CURLM_STATE_DO) {
-          connclose(data->easy_conn, "Disconnected with pending data");
-          disconnect_conn = TRUE;
+          streamclose(data->easy_conn, "Disconnected with pending data");
+          stream_error = TRUE;
         }
         result = CURLE_OPERATION_TIMEDOUT;
         (void)multi_done(&data->easy_conn, result, TRUE);
@@ -1426,7 +1437,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
         /* Add this handle to the send or pend pipeline */
         result = Curl_add_handle_to_pipeline(data, data->easy_conn);
         if(result)
-          disconnect_conn = TRUE;
+          stream_error = TRUE;
         else {
           if(async)
             /* We're now waiting for an asynchronous name lookup */
@@ -1518,7 +1529,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
 
       if(result) {
         /* failure detected */
-        disconnect_conn = TRUE;
+        stream_error = TRUE;
         break;
       }
     }
@@ -1558,7 +1569,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
       else if(result) {
         /* failure detected */
         /* Just break, the cleaning up is handled all in one place */
-        disconnect_conn = TRUE;
+        stream_error = TRUE;
         break;
       }
       break;
@@ -1578,7 +1589,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
         /* failure detected */
         Curl_posttransfer(data);
         multi_done(&data->easy_conn, result, TRUE);
-        disconnect_conn = TRUE;
+        stream_error = TRUE;
       }
       break;
 
@@ -1595,7 +1606,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
         /* failure detected */
         Curl_posttransfer(data);
         multi_done(&data->easy_conn, result, TRUE);
-        disconnect_conn = TRUE;
+        stream_error = TRUE;
       }
       break;
 
@@ -1670,7 +1681,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
           if(drc) {
             /* a failure here pretty much implies an out of memory */
             result = drc;
-            disconnect_conn = TRUE;
+            stream_error = TRUE;
           }
           else
             retry = (newurl)?TRUE:FALSE;
@@ -1703,7 +1714,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
           }
           else {
             /* Have error handler disconnect conn if we can't retry */
-            disconnect_conn = TRUE;
+            stream_error = TRUE;
             free(newurl);
           }
         }
@@ -1712,7 +1723,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
           Curl_posttransfer(data);
           if(data->easy_conn)
             multi_done(&data->easy_conn, result, FALSE);
-          disconnect_conn = TRUE;
+          stream_error = TRUE;
         }
       }
       break;
@@ -1734,7 +1745,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
         /* failure detected */
         Curl_posttransfer(data);
         multi_done(&data->easy_conn, result, FALSE);
-        disconnect_conn = TRUE;
+        stream_error = TRUE;
       }
       break;
 
@@ -1763,7 +1774,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
         /* failure detected */
         Curl_posttransfer(data);
         multi_done(&data->easy_conn, result, FALSE);
-        disconnect_conn = TRUE;
+        stream_error = TRUE;
       }
       break;
 
@@ -1800,9 +1811,17 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
         result = Curl_speedcheck(data, now);
 
       if(( (data->set.max_send_speed == 0) ||
-           (data->progress.ulspeed < data->set.max_send_speed))  &&
+           (Curl_pgrsLimitWaitTime(data->progress.uploaded,
+                                   data->progress.ul_limit_size,
+                                   data->set.max_send_speed,
+                                   data->progress.ul_limit_start,
+                                   now) <= 0))  &&
          ( (data->set.max_recv_speed == 0) ||
-           (data->progress.dlspeed < data->set.max_recv_speed)))
+           (Curl_pgrsLimitWaitTime(data->progress.downloaded,
+                                   data->progress.dl_limit_size,
+                                   data->set.max_recv_speed,
+                                   data->progress.dl_limit_start,
+                                   now) <= 0)))
         multistate(data, CURLM_STATE_PERFORM);
       break;
 
@@ -1810,41 +1829,38 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
     {
       char *newurl = NULL;
       bool retry = FALSE;
+      bool comeback = FALSE;
 
       /* check if over send speed */
-      if((data->set.max_send_speed > 0) &&
-         (data->progress.ulspeed > data->set.max_send_speed)) {
-        int buffersize;
-
-        multistate(data, CURLM_STATE_TOOFAST);
-
-        /* calculate upload rate-limitation timeout. */
-        buffersize = (int)(data->set.buffer_size ?
-                           data->set.buffer_size : BUFSIZE);
-        timeout_ms = Curl_sleep_time(data->set.max_send_speed,
-                                     data->progress.ulspeed, buffersize);
-        Curl_expire_latest(data, timeout_ms);
-        break;
+      if(data->set.max_send_speed > 0) {
+        timeout_ms = Curl_pgrsLimitWaitTime(data->progress.uploaded,
+                                            data->progress.ul_limit_size,
+                                            data->set.max_send_speed,
+                                            data->progress.ul_limit_start,
+                                            now);
+        if(timeout_ms > 0) {
+          multistate(data, CURLM_STATE_TOOFAST);
+          Curl_expire_latest(data, timeout_ms);
+          break;
+        }
       }
 
       /* check if over recv speed */
-      if((data->set.max_recv_speed > 0) &&
-         (data->progress.dlspeed > data->set.max_recv_speed)) {
-        int buffersize;
-
-        multistate(data, CURLM_STATE_TOOFAST);
-
-        /* Calculate download rate-limitation timeout. */
-        buffersize = (int)(data->set.buffer_size ?
-                           data->set.buffer_size : BUFSIZE);
-        timeout_ms = Curl_sleep_time(data->set.max_recv_speed,
-                                     data->progress.dlspeed, buffersize);
-        Curl_expire_latest(data, timeout_ms);
-        break;
+      if(data->set.max_recv_speed > 0) {
+        timeout_ms = Curl_pgrsLimitWaitTime(data->progress.downloaded,
+                                            data->progress.dl_limit_size,
+                                            data->set.max_recv_speed,
+                                            data->progress.dl_limit_start,
+                                            now);
+        if(timeout_ms > 0) {
+          multistate(data, CURLM_STATE_TOOFAST);
+          Curl_expire_latest(data, timeout_ms);
+          break;
+        }
       }
 
       /* read/write data if it is ready to do so */
-      result = Curl_readwrite(data->easy_conn, data, &done);
+      result = Curl_readwrite(data->easy_conn, data, &done, &comeback);
 
       k = &data->req;
 
@@ -1884,10 +1900,10 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
 
         if(!(data->easy_conn->handler->flags & PROTOPT_DUAL) &&
            result != CURLE_HTTP2_STREAM)
-          connclose(data->easy_conn, "Transfer returned error");
+          streamclose(data->easy_conn, "Transfer returned error");
 
         Curl_posttransfer(data);
-        multi_done(&data->easy_conn, result, FALSE);
+        multi_done(&data->easy_conn, result, TRUE);
       }
       else if(done) {
         followtype follow=FOLLOW_NONE;
@@ -1900,7 +1916,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
 
         /* expire the new receiving pipeline head */
         if(data->easy_conn->recv_pipe->head)
-          Curl_expire_latest(data->easy_conn->recv_pipe->head->ptr, 1);
+          Curl_expire_latest(data->easy_conn->recv_pipe->head->ptr, 0);
 
         /* Check if we can move pending requests to send pipe */
         Curl_multi_process_pending_handles(multi);
@@ -1943,13 +1959,15 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
             if(!result)
               newurl = NULL; /* allocation was handed over Curl_follow() */
             else
-              disconnect_conn = TRUE;
+              stream_error = TRUE;
           }
 
           multistate(data, CURLM_STATE_DONE);
           rc = CURLM_CALL_MULTI_PERFORM;
         }
       }
+      else if(comeback)
+        rc = CURLM_CALL_MULTI_PERFORM;
 
       free(newurl);
       break;
@@ -2008,7 +2026,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
          that could be freed anytime */
       data->easy_conn = NULL;
 
-      Curl_expire(data, 0); /* stop all timers */
+      Curl_expire_clear(data); /* stop all timers */
       break;
 
     case CURLM_STATE_MSGSENT:
@@ -2042,7 +2060,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
           Curl_removeHandleFromPipeline(data, data->easy_conn->send_pipe);
           Curl_removeHandleFromPipeline(data, data->easy_conn->recv_pipe);
 
-          if(disconnect_conn) {
+          if(stream_error) {
             /* Don't attempt to send data over a connection that timed out */
             bool dead_connection = result == CURLE_OPERATION_TIMEDOUT;
             /* disconnect properly */
@@ -2066,7 +2084,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
         /* aborted due to progress callback return code must close the
            connection */
         result = CURLE_ABORTED_BY_CALLBACK;
-        connclose(data->easy_conn, "Aborted by callback");
+        streamclose(data->easy_conn, "Aborted by callback");
 
         /* if not yet in DONE state, go there, otherwise COMPLETED */
         multistate(data, (data->mstate < CURLM_STATE_DONE)?
@@ -2160,6 +2178,7 @@ static void close_all_connections(struct Curl_multi *multi)
     conn->data->easy_conn = NULL; /* clear the easy handle's connection
                                      pointer */
     /* This will remove the connection from the cache */
+    connclose(conn, "kill all");
     (void)Curl_disconnect(conn, FALSE);
     sigpipe_restore(&pipe_st);
 
@@ -2876,92 +2895,59 @@ multi_addtimeout(struct curl_llist *timeoutlist,
  * given a number of milliseconds from now to use to set the 'act before
  * this'-time for the transfer, to be extracted by curl_multi_timeout()
  *
- * Note that the timeout will be added to a queue of timeouts if it defines a
- * moment in time that is later than the current head of queue.
- *
- * Pass zero to clear all timeout values for this handle.
-*/
+ * The timeout will be added to a queue of timeouts if it defines a moment in
+ * time that is later than the current head of queue.
+ */
 void Curl_expire(struct Curl_easy *data, long milli)
 {
   struct Curl_multi *multi = data->multi;
   struct timeval *nowp = &data->state.expiretime;
   int rc;
+  struct timeval set;
 
   /* this is only interesting while there is still an associated multi struct
      remaining! */
   if(!multi)
     return;
 
-  if(!milli) {
-    /* No timeout, clear the time data. */
-    if(nowp->tv_sec || nowp->tv_usec) {
-      /* Since this is an cleared time, we must remove the previous entry from
-         the splay tree */
-      struct curl_llist *list = data->state.timeoutlist;
-
-      rc = Curl_splayremovebyaddr(multi->timetree,
-                                  &data->state.timenode,
-                                  &multi->timetree);
-      if(rc)
-        infof(data, "Internal error clearing splay node = %d\n", rc);
-
-      /* flush the timeout list too */
-      while(list->size > 0)
-        Curl_llist_remove(list, list->tail, NULL);
+  set = Curl_tvnow();
+  set.tv_sec += milli/1000;
+  set.tv_usec += (milli%1000)*1000;
 
-#ifdef DEBUGBUILD
-      infof(data, "Expire cleared\n");
-#endif
-      nowp->tv_sec = 0;
-      nowp->tv_usec = 0;
-    }
+  if(set.tv_usec >= 1000000) {
+    set.tv_sec++;
+    set.tv_usec -= 1000000;
   }
-  else {
-    struct timeval set;
-
-    set = Curl_tvnow();
-    set.tv_sec += milli/1000;
-    set.tv_usec += (milli%1000)*1000;
-
-    if(set.tv_usec >= 1000000) {
-      set.tv_sec++;
-      set.tv_usec -= 1000000;
-    }
-
-    if(nowp->tv_sec || nowp->tv_usec) {
-      /* This means that the struct is added as a node in the splay tree.
-         Compare if the new time is earlier, and only remove-old/add-new if it
-         is. */
-      long diff = curlx_tvdiff(set, *nowp);
-      if(diff > 0) {
-        /* the new expire time was later so just add it to the queue
-           and get out */
-        multi_addtimeout(data->state.timeoutlist, &set);
-        return;
-      }
 
-      /* the new time is newer than the presently set one, so add the current
-         to the queue and update the head */
-      multi_addtimeout(data->state.timeoutlist, nowp);
-
-      /* Since this is an updated time, we must remove the previous entry from
-         the splay tree first and then re-add the new value */
-      rc = Curl_splayremovebyaddr(multi->timetree,
-                                  &data->state.timenode,
-                                  &multi->timetree);
-      if(rc)
-        infof(data, "Internal error removing splay node = %d\n", rc);
+  if(nowp->tv_sec || nowp->tv_usec) {
+    /* This means that the struct is added as a node in the splay tree.
+       Compare if the new time is earlier, and only remove-old/add-new if it
+       is. */
+    long diff = curlx_tvdiff(set, *nowp);
+    if(diff > 0) {
+      /* the new expire time was later so just add it to the queue
+         and get out */
+      multi_addtimeout(data->state.timeoutlist, &set);
+      return;
     }
 
-    *nowp = set;
-    data->state.timenode.payload = data;
-    multi->timetree = Curl_splayinsert(*nowp,
-                                       multi->timetree,
-                                       &data->state.timenode);
+    /* the new time is newer than the presently set one, so add the current
+       to the queue and update the head */
+    multi_addtimeout(data->state.timeoutlist, nowp);
+
+    /* Since this is an updated time, we must remove the previous entry from
+       the splay tree first and then re-add the new value */
+    rc = Curl_splayremovebyaddr(multi->timetree,
+                                &data->state.timenode,
+                                &multi->timetree);
+    if(rc)
+      infof(data, "Internal error removing splay node = %d\n", rc);
   }
-#if 0
-  Curl_splayprint(multi->timetree, 0, TRUE);
-#endif
+
+  *nowp = set;
+  data->state.timenode.payload = data;
+  multi->timetree = Curl_splayinsert(*nowp, multi->timetree,
+                                     &data->state.timenode);
 }
 
 /*
@@ -3004,6 +2990,49 @@ void Curl_expire_latest(struct Curl_easy *data, long milli)
   Curl_expire(data, milli);
 }
 
+
+/*
+ * Curl_expire_clear()
+ *
+ * Clear ALL timeout values for this handle.
+ */
+void Curl_expire_clear(struct Curl_easy *data)
+{
+  struct Curl_multi *multi = data->multi;
+  struct timeval *nowp = &data->state.expiretime;
+  int rc;
+
+  /* this is only interesting while there is still an associated multi struct
+     remaining! */
+  if(!multi)
+    return;
+
+  if(nowp->tv_sec || nowp->tv_usec) {
+    /* Since this is an cleared time, we must remove the previous entry from
+       the splay tree */
+    struct curl_llist *list = data->state.timeoutlist;
+
+    rc = Curl_splayremovebyaddr(multi->timetree,
+                                &data->state.timenode,
+                                &multi->timetree);
+    if(rc)
+      infof(data, "Internal error clearing splay node = %d\n", rc);
+
+    /* flush the timeout list too */
+    while(list->size > 0)
+      Curl_llist_remove(list, list->tail, NULL);
+
+#ifdef DEBUGBUILD
+    infof(data, "Expire cleared\n");
+#endif
+    nowp->tv_sec = 0;
+    nowp->tv_usec = 0;
+  }
+}
+
+
+
+
 CURLMcode curl_multi_assign(struct Curl_multi *multi, curl_socket_t s,
                             void *hashp)
 {
@@ -3064,7 +3093,7 @@ void Curl_multi_process_pending_handles(struct Curl_multi *multi)
       Curl_llist_remove(multi->pending, e, NULL);
 
       /* Make sure that the handle will be processed soonish. */
-      Curl_expire_latest(data, 1);
+      Curl_expire_latest(data, 0);
     }
 
     e = next; /* operate on next handle */
diff --git a/Utilities/cmcurl/lib/multiif.h b/Utilities/cmcurl/lib/multiif.h
index fd2df55..eaff496 100644
--- a/Utilities/cmcurl/lib/multiif.h
+++ b/Utilities/cmcurl/lib/multiif.h
@@ -26,6 +26,7 @@
  * Prototypes for library-wide functions provided by multi.c
  */
 void Curl_expire(struct Curl_easy *data, long milli);
+void Curl_expire_clear(struct Curl_easy *data);
 void Curl_expire_latest(struct Curl_easy *data, long milli);
 bool Curl_pipeline_wanted(const struct Curl_multi* multi, int bits);
 void Curl_multi_handlePipeBreak(struct Curl_easy *data);
diff --git a/Utilities/cmcurl/lib/netrc.c b/Utilities/cmcurl/lib/netrc.c
index 46f427a..996711d 100644
--- a/Utilities/cmcurl/lib/netrc.c
+++ b/Utilities/cmcurl/lib/netrc.c
@@ -28,10 +28,8 @@
 
 #include <curl/curl.h>
 #include "netrc.h"
-
-#include "strequal.h"
 #include "strtok.h"
-#include "rawstr.h"
+#include "strcase.h"
 
 /* The last 3 #include files should be in this order */
 #include "curl_printf.h"
@@ -130,20 +128,20 @@ int Curl_parsenetrc(const char *host,
 
         switch(state) {
         case NOTHING:
-          if(Curl_raw_equal("machine", tok)) {
+          if(strcasecompare("machine", tok)) {
             /* the next tok is the machine name, this is in itself the
                delimiter that starts the stuff entered for this machine,
                after this we need to search for 'login' and
                'password'. */
             state=HOSTFOUND;
           }
-          else if(Curl_raw_equal("default", tok)) {
+          else if(strcasecompare("default", tok)) {
             state=HOSTVALID;
             retcode=0; /* we did find our host */
           }
           break;
         case HOSTFOUND:
-          if(Curl_raw_equal(host, tok)) {
+          if(strcasecompare(host, tok)) {
             /* and yes, this is our host! */
             state=HOSTVALID;
             retcode=0; /* we did find our host */
@@ -156,7 +154,7 @@ int Curl_parsenetrc(const char *host,
           /* we are now parsing sub-keywords concerning "our" host */
           if(state_login) {
             if(specific_login) {
-              state_our_login = Curl_raw_equal(*loginp, tok);
+              state_our_login = strcasecompare(*loginp, tok);
             }
             else {
               free(*loginp);
@@ -179,11 +177,11 @@ int Curl_parsenetrc(const char *host,
             }
             state_password=0;
           }
-          else if(Curl_raw_equal("login", tok))
+          else if(strcasecompare("login", tok))
             state_login=1;
-          else if(Curl_raw_equal("password", tok))
+          else if(strcasecompare("password", tok))
             state_password=1;
-          else if(Curl_raw_equal("machine", tok)) {
+          else if(strcasecompare("machine", tok)) {
             /* ok, there's machine here go => */
             state = HOSTFOUND;
             state_our_login = FALSE;
diff --git a/Utilities/cmcurl/lib/parsedate.c b/Utilities/cmcurl/lib/parsedate.c
index dfcf855..3c783be 100644
--- a/Utilities/cmcurl/lib/parsedate.c
+++ b/Utilities/cmcurl/lib/parsedate.c
@@ -5,7 +5,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -80,7 +80,7 @@
 #endif
 
 #include <curl/curl.h>
-#include "rawstr.h"
+#include "strcase.h"
 #include "warnless.h"
 #include "parsedate.h"
 
@@ -211,7 +211,7 @@ static int checkday(const char *check, size_t len)
   else
     what = &Curl_wkday[0];
   for(i=0; i<7; i++) {
-    if(Curl_raw_equal(check, what[0])) {
+    if(strcasecompare(check, what[0])) {
       found=TRUE;
       break;
     }
@@ -228,7 +228,7 @@ static int checkmonth(const char *check)
 
   what = &Curl_month[0];
   for(i=0; i<12; i++) {
-    if(Curl_raw_equal(check, what[0])) {
+    if(strcasecompare(check, what[0])) {
       found=TRUE;
       break;
     }
@@ -248,7 +248,7 @@ static int checktz(const char *check)
 
   what = tz;
   for(i=0; i< sizeof(tz)/sizeof(tz[0]); i++) {
-    if(Curl_raw_equal(check, what->name)) {
+    if(strcasecompare(check, what->name)) {
       found=TRUE;
       break;
     }
@@ -386,15 +386,17 @@ static int parsedate(const char *date, time_t *output)
       /* a digit */
       int val;
       char *end;
+      int len=0;
       if((secnum == -1) &&
-         (3 == sscanf(date, "%02d:%02d:%02d", &hournum, &minnum, &secnum))) {
+         (3 == sscanf(date, "%02d:%02d:%02d%n",
+                      &hournum, &minnum, &secnum, &len))) {
         /* time stamp! */
-        date += 8;
+        date += len;
       }
       else if((secnum == -1) &&
-              (2 == sscanf(date, "%02d:%02d", &hournum, &minnum))) {
+              (2 == sscanf(date, "%02d:%02d%n", &hournum, &minnum, &len))) {
         /* time stamp without seconds */
-        date += 5;
+        date += len;
         secnum = 0;
       }
       else {
diff --git a/Utilities/cmcurl/lib/pingpong.c b/Utilities/cmcurl/lib/pingpong.c
index 92ff84b..bf2c8fd 100644
--- a/Utilities/cmcurl/lib/pingpong.c
+++ b/Utilities/cmcurl/lib/pingpong.c
@@ -108,7 +108,8 @@ CURLcode Curl_pp_statemach(struct pingpong *pp, bool block)
     /* We are receiving and there is data ready in the SSL library */
     rc = 1;
   else
-    rc = Curl_socket_ready(pp->sendleft?CURL_SOCKET_BAD:sock, /* reading */
+    rc = Curl_socket_check(pp->sendleft?CURL_SOCKET_BAD:sock, /* reading */
+                           CURL_SOCKET_BAD,
                            pp->sendleft?sock:CURL_SOCKET_BAD, /* writing */
                            interval_ms);
 
diff --git a/Utilities/cmcurl/lib/pipeline.c b/Utilities/cmcurl/lib/pipeline.c
index 0ff82f0..40a5e82 100644
--- a/Utilities/cmcurl/lib/pipeline.c
+++ b/Utilities/cmcurl/lib/pipeline.c
@@ -6,7 +6,7 @@
  *                             \___|\___/|_| \_\_____|
  *
  * Copyright (C) 2013, Linus Nielsen Feltzing, <linus at haxx.se>
- * Copyright (C) 2013-2015, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 2013-2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -31,7 +31,7 @@
 #include "multiif.h"
 #include "pipeline.h"
 #include "sendf.h"
-#include "rawstr.h"
+#include "strcase.h"
 
 #include "curl_memory.h"
 /* The last #include file should be: */
@@ -114,7 +114,7 @@ CURLcode Curl_add_handle_to_pipeline(struct Curl_easy *handle,
   if(pipeline == conn->send_pipe && sendhead != conn->send_pipe->head) {
     /* this is a new one as head, expire it */
     Curl_pipeline_leave_write(conn); /* not in use yet */
-    Curl_expire(conn->send_pipe->head->ptr, 1);
+    Curl_expire(conn->send_pipe->head->ptr, 0);
   }
 
 #if 0 /* enable for pipeline debugging */
@@ -149,7 +149,7 @@ void Curl_move_handle_from_send_to_recv_pipe(struct Curl_easy *handle,
         infof(conn->data, "%p is at send pipe head B!\n",
               (void *)conn->send_pipe->head->ptr);
 #endif
-        Curl_expire(conn->send_pipe->head->ptr, 1);
+        Curl_expire(conn->send_pipe->head->ptr, 0);
       }
 
       /* The receiver's list is not really interesting here since either this
@@ -177,7 +177,7 @@ bool Curl_pipeline_site_blacklisted(struct Curl_easy *handle,
         struct site_blacklist_entry *site;
 
         site = curr->ptr;
-        if(Curl_raw_equal(site->hostname, conn->host.name) &&
+        if(strcasecompare(site->hostname, conn->host.name) &&
            site->port == conn->remote_port) {
           infof(handle, "Site %s:%d is pipeline blacklisted\n",
                 conn->host.name, conn->remote_port);
@@ -269,7 +269,7 @@ bool Curl_pipeline_server_blacklisted(struct Curl_easy *handle,
         char *bl_server_name;
 
         bl_server_name = curr->ptr;
-        if(Curl_raw_nequal(bl_server_name, server_name,
+        if(strncasecompare(bl_server_name, server_name,
                            strlen(bl_server_name))) {
           infof(handle, "Server %s is blacklisted\n", server_name);
           return TRUE;
diff --git a/Utilities/cmcurl/lib/pop3.c b/Utilities/cmcurl/lib/pop3.c
index 591e877..8486519 100644
--- a/Utilities/cmcurl/lib/pop3.c
+++ b/Utilities/cmcurl/lib/pop3.c
@@ -70,16 +70,14 @@
 #include "http.h" /* for HTTP proxy tunnel stuff */
 #include "socks.h"
 #include "pop3.h"
-
 #include "strtoofft.h"
-#include "strequal.h"
+#include "strcase.h"
 #include "vtls/vtls.h"
 #include "connect.h"
 #include "strerror.h"
 #include "select.h"
 #include "multiif.h"
 #include "url.h"
-#include "rawstr.h"
 #include "curl_sasl.h"
 #include "curl_md5.h"
 #include "warnless.h"
@@ -663,7 +661,7 @@ static CURLcode pop3_state_servergreet_resp(struct connectdata *conn,
 
   if(pop3code != '+') {
     failf(data, "Got unexpected pop3-server response");
-    result = CURLE_FTP_WEIRD_SERVER_REPLY;
+    result = CURLE_WEIRD_SERVER_REPLY;
   }
   else {
     /* Does the server support APOP authentication? */
@@ -1412,11 +1410,11 @@ static CURLcode pop3_parse_url_options(struct connectdata *conn)
     while(*ptr && *ptr != ';')
       ptr++;
 
-    if(strnequal(key, "AUTH=", 5)) {
+    if(strncasecompare(key, "AUTH=", 5)) {
       result = Curl_sasl_parse_url_auth_option(&pop3c->sasl,
                                                value, ptr - value);
 
-      if(result && strnequal(value, "+APOP", ptr - value)) {
+      if(result && strncasecompare(value, "+APOP", ptr - value)) {
         pop3c->preftype = POP3_TYPE_APOP;
         pop3c->sasl.prefmech = SASL_AUTH_NONE;
         result = CURLE_OK;
diff --git a/Utilities/cmcurl/lib/progress.c b/Utilities/cmcurl/lib/progress.c
index 760ca1c..0f67ef2 100644
--- a/Utilities/cmcurl/lib/progress.c
+++ b/Utilities/cmcurl/lib/progress.c
@@ -216,18 +216,93 @@ void Curl_pgrsStartNow(struct Curl_easy *data)
 {
   data->progress.speeder_c = 0; /* reset the progress meter display */
   data->progress.start = Curl_tvnow();
+  data->progress.ul_limit_start.tv_sec = 0;
+  data->progress.ul_limit_start.tv_usec = 0;
+  data->progress.dl_limit_start.tv_sec = 0;
+  data->progress.dl_limit_start.tv_usec = 0;
   /* clear all bits except HIDE and HEADERS_OUT */
   data->progress.flags &= PGRS_HIDE|PGRS_HEADERS_OUT;
 }
 
+/*
+ * This is used to handle speed limits, calculating how much milliseconds we
+ * need to wait until we're back under the speed limit, if needed.
+ *
+ * The way it works is by having a "starting point" (time & amount of data
+ * transfered by then) used in the speed computation, to be used instead of the
+ * start of the transfer.
+ * This starting point is regularly moved as transfer goes on, to keep getting
+ * accurate values (instead of average over the entire tranfer).
+ *
+ * This function takes the current amount of data transfered, the amount at the
+ * starting point, the limit (in bytes/s), the time of the starting point and
+ * the current time.
+ *
+ * Returns -1 if no waiting is needed (not enough data transfered since
+ * starting point yet), 0 when no waiting is needed but the starting point
+ * should be reset (to current), or the number of milliseconds to wait to get
+ * back under the speed limit.
+ */
+long Curl_pgrsLimitWaitTime(curl_off_t cursize,
+                            curl_off_t startsize,
+                            curl_off_t limit,
+                            struct timeval start,
+                            struct timeval now)
+{
+    curl_off_t size = cursize - startsize;
+    long minimum, actual;
+
+    /* we don't have a starting point yet -- return 0 so it gets (re)set */
+    if(start.tv_sec == 0 && start.tv_usec == 0)
+        return 0;
+
+    /* not enough data yet */
+    if(size < limit)
+      return -1;
+
+    minimum = (long) (CURL_OFF_T_C(1000) * size / limit);
+    actual = Curl_tvdiff(now, start);
+
+    if(actual < minimum)
+      return minimum - actual;
+    else
+      return 0;
+}
+
 void Curl_pgrsSetDownloadCounter(struct Curl_easy *data, curl_off_t size)
 {
+  struct timeval now = Curl_tvnow();
+
   data->progress.downloaded = size;
+
+  /* download speed limit */
+  if((data->set.max_recv_speed > 0) &&
+     (Curl_pgrsLimitWaitTime(data->progress.downloaded,
+                             data->progress.dl_limit_size,
+                             data->set.max_recv_speed,
+                             data->progress.dl_limit_start,
+                             now) == 0)) {
+    data->progress.dl_limit_start = now;
+    data->progress.dl_limit_size = size;
+  }
 }
 
 void Curl_pgrsSetUploadCounter(struct Curl_easy *data, curl_off_t size)
 {
+  struct timeval now = Curl_tvnow();
+
   data->progress.uploaded = size;
+
+  /* upload speed limit */
+  if((data->set.max_send_speed > 0) &&
+     (Curl_pgrsLimitWaitTime(data->progress.uploaded,
+                             data->progress.ul_limit_size,
+                             data->set.max_send_speed,
+                             data->progress.ul_limit_start,
+                             now) == 0)) {
+    data->progress.ul_limit_start = now;
+    data->progress.ul_limit_size = size;
+  }
 }
 
 void Curl_pgrsSetDownloadSize(struct Curl_easy *data, curl_off_t size)
diff --git a/Utilities/cmcurl/lib/progress.h b/Utilities/cmcurl/lib/progress.h
index a77b7ce..155ff04 100644
--- a/Utilities/cmcurl/lib/progress.h
+++ b/Utilities/cmcurl/lib/progress.h
@@ -49,7 +49,11 @@ void Curl_pgrsSetUploadCounter(struct Curl_easy *data, curl_off_t size);
 int Curl_pgrsUpdate(struct connectdata *);
 void Curl_pgrsResetTimesSizes(struct Curl_easy *data);
 void Curl_pgrsTime(struct Curl_easy *data, timerid timer);
-
+long Curl_pgrsLimitWaitTime(curl_off_t cursize,
+                            curl_off_t startsize,
+                            curl_off_t limit,
+                            struct timeval start,
+                            struct timeval now);
 
 /* Don't show progress for sizes smaller than: */
 #define LEAST_SIZE_PROGRESS BUFSIZE
diff --git a/Utilities/cmcurl/lib/rawstr.c b/Utilities/cmcurl/lib/rawstr.c
deleted file mode 100644
index 5665ebd..0000000
--- a/Utilities/cmcurl/lib/rawstr.c
+++ /dev/null
@@ -1,148 +0,0 @@
-/***************************************************************************
- *                                  _   _ ____  _
- *  Project                     ___| | | |  _ \| |
- *                             / __| | | | |_) | |
- *                            | (__| |_| |  _ <| |___
- *                             \___|\___/|_| \_\_____|
- *
- * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel at haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
- * are also available at https://curl.haxx.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#include "rawstr.h"
-
-/* Portable, consistent toupper (remember EBCDIC). Do not use toupper() because
-   its behavior is altered by the current locale. */
-char Curl_raw_toupper(char in)
-{
-#if !defined(CURL_DOES_CONVERSIONS)
-  if(in >= 'a' && in <= 'z')
-    return (char)('A' + in - 'a');
-#else
-  switch (in) {
-  case 'a':
-    return 'A';
-  case 'b':
-    return 'B';
-  case 'c':
-    return 'C';
-  case 'd':
-    return 'D';
-  case 'e':
-    return 'E';
-  case 'f':
-    return 'F';
-  case 'g':
-    return 'G';
-  case 'h':
-    return 'H';
-  case 'i':
-    return 'I';
-  case 'j':
-    return 'J';
-  case 'k':
-    return 'K';
-  case 'l':
-    return 'L';
-  case 'm':
-    return 'M';
-  case 'n':
-    return 'N';
-  case 'o':
-    return 'O';
-  case 'p':
-    return 'P';
-  case 'q':
-    return 'Q';
-  case 'r':
-    return 'R';
-  case 's':
-    return 'S';
-  case 't':
-    return 'T';
-  case 'u':
-    return 'U';
-  case 'v':
-    return 'V';
-  case 'w':
-    return 'W';
-  case 'x':
-    return 'X';
-  case 'y':
-    return 'Y';
-  case 'z':
-    return 'Z';
-  }
-#endif
-
-  return in;
-}
-
-/*
- * Curl_raw_equal() is for doing "raw" case insensitive strings. This is meant
- * to be locale independent and only compare strings we know are safe for
- * this.  See https://daniel.haxx.se/blog/2008/10/15/strcasecmp-in-turkish/ for
- * some further explanation to why this function is necessary.
- *
- * The function is capable of comparing a-z case insensitively even for
- * non-ascii.
- */
-
-int Curl_raw_equal(const char *first, const char *second)
-{
-  while(*first && *second) {
-    if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second))
-      /* get out of the loop as soon as they don't match */
-      break;
-    first++;
-    second++;
-  }
-  /* we do the comparison here (possibly again), just to make sure that if the
-     loop above is skipped because one of the strings reached zero, we must not
-     return this as a successful match */
-  return (Curl_raw_toupper(*first) == Curl_raw_toupper(*second));
-}
-
-int Curl_raw_nequal(const char *first, const char *second, size_t max)
-{
-  while(*first && *second && max) {
-    if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) {
-      break;
-    }
-    max--;
-    first++;
-    second++;
-  }
-  if(0 == max)
-    return 1; /* they are equal this far */
-
-  return Curl_raw_toupper(*first) == Curl_raw_toupper(*second);
-}
-
-/* Copy an upper case version of the string from src to dest.  The
- * strings may overlap.  No more than n characters of the string are copied
- * (including any NUL) and the destination string will NOT be
- * NUL-terminated if that limit is reached.
- */
-void Curl_strntoupper(char *dest, const char *src, size_t n)
-{
-  if(n < 1)
-    return;
-
-  do {
-    *dest++ = Curl_raw_toupper(*src);
-  } while(*src++ && --n);
-}
diff --git a/Utilities/cmcurl/lib/rawstr.h b/Utilities/cmcurl/lib/rawstr.h
deleted file mode 100644
index 4af00f1..0000000
--- a/Utilities/cmcurl/lib/rawstr.h
+++ /dev/null
@@ -1,47 +0,0 @@
-#ifndef HEADER_CURL_RAWSTR_H
-#define HEADER_CURL_RAWSTR_H
-/***************************************************************************
- *                                  _   _ ____  _
- *  Project                     ___| | | |  _ \| |
- *                             / __| | | | |_) | |
- *                            | (__| |_| |  _ <| |___
- *                             \___|\___/|_| \_\_____|
- *
- * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel at haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
- * are also available at https://curl.haxx.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include <curl/curl.h>
-
-/*
- * Curl_raw_equal() is for doing "raw" case insensitive strings. This is meant
- * to be locale independent and only compare strings we know are safe for
- * this.
- *
- * The function is capable of comparing a-z case insensitively even for
- * non-ascii.
- */
-int Curl_raw_equal(const char *first, const char *second);
-int Curl_raw_nequal(const char *first, const char *second, size_t max);
-
-char Curl_raw_toupper(char in);
-
-/* checkprefix() is a shorter version of the above, used when the first
-   argument is zero-byte terminated */
-#define checkprefix(a,b)    Curl_raw_nequal(a,b,strlen(a))
-
-void Curl_strntoupper(char *dest, const char *src, size_t n);
-
-#endif /* HEADER_CURL_RAWSTR_H */
-
diff --git a/Utilities/cmcurl/lib/rtsp.c b/Utilities/cmcurl/lib/rtsp.c
index 27955bc..d1bad19 100644
--- a/Utilities/cmcurl/lib/rtsp.c
+++ b/Utilities/cmcurl/lib/rtsp.c
@@ -33,7 +33,7 @@
 #include "url.h"
 #include "progress.h"
 #include "rtsp.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "select.h"
 #include "connect.h"
 /* The last 3 #include files should be in this order */
@@ -147,7 +147,7 @@ bool Curl_rtsp_connisdead(struct connectdata *check)
   int sval;
   bool ret_val = TRUE;
 
-  sval = Curl_socket_ready(check->sock[FIRSTSOCKET], CURL_SOCKET_BAD, 0);
+  sval = SOCKET_READABLE(check->sock[FIRSTSOCKET], 0);
   if(sval == 0) {
     /* timeout */
     ret_val = FALSE;
@@ -796,19 +796,15 @@ CURLcode Curl_rtsp_parseheader(struct connectdata *conn,
       }
     }
     else {
-      /* If the Session ID is not set, and we find it in a response, then
-         set it */
-
-      /* The session ID can be an alphanumeric or a 'safe' character
+      /* If the Session ID is not set, and we find it in a response, then set
+       * it.
        *
-       * RFC 2326 15.1 Base Syntax:
-       * safe =  "\$" | "-" | "_" | "." | "+"
-       * */
+       * Allow any non whitespace content, up to the field seperator or end of
+       * line. RFC 2326 isn't 100% clear on the session ID and for example
+       * gstreamer does url-encoded session ID's not covered by the standard.
+       */
       char *end = start;
-      while(*end &&
-            (ISALNUM(*end) || *end == '-' || *end == '_' || *end == '.' ||
-             *end == '+' ||
-             (*end == '\\' && *(end + 1) && *(end + 1) == '$' && (++end, 1))))
+      while(*end && *end != ';' && !ISSPACE(*end))
         end++;
 
       /* Copy the id substring into a new buffer */
diff --git a/Utilities/cmcurl/lib/security.c b/Utilities/cmcurl/lib/security.c
index a0bcaea..ff26066 100644
--- a/Utilities/cmcurl/lib/security.c
+++ b/Utilities/cmcurl/lib/security.c
@@ -60,7 +60,7 @@
 #include "curl_sec.h"
 #include "ftp.h"
 #include "sendf.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "warnless.h"
 
 /* The last #include file should be: */
@@ -122,7 +122,7 @@ static int ftp_send_command(struct connectdata *conn, const char *message, ...)
   vsnprintf(print_buffer, sizeof(print_buffer), message, args);
   va_end(args);
 
-  if(Curl_ftpsendf(conn, print_buffer)) {
+  if(Curl_ftpsend(conn, print_buffer)) {
     ftp_code = -1;
   }
   else {
@@ -192,15 +192,18 @@ static CURLcode read_data(struct connectdata *conn,
                           struct krb5buffer *buf)
 {
   int len;
-  void* tmp;
+  void *tmp = NULL;
   CURLcode result;
 
   result = socket_read(fd, &len, sizeof(len));
   if(result)
     return result;
 
-  len = ntohl(len);
-  tmp = realloc(buf->data, len);
+  if(len) {
+    /* only realloc if there was a length */
+    len = ntohl(len);
+    tmp = realloc(buf->data, len);
+  }
   if(tmp == NULL)
     return CURLE_OUT_OF_MEMORY;
 
diff --git a/Utilities/cmcurl/lib/select.c b/Utilities/cmcurl/lib/select.c
index 2002349..d5caa70 100644
--- a/Utilities/cmcurl/lib/select.c
+++ b/Utilities/cmcurl/lib/select.c
@@ -5,7 +5,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -51,15 +51,14 @@
 #include "warnless.h"
 
 /* Convenience local macros */
-
-#define elapsed_ms  (int)curlx_tvdiff(curlx_tvnow(), initial_tv)
+#define ELAPSED_MS()  (int)curlx_tvdiff(curlx_tvnow(), initial_tv)
 
 int Curl_ack_eintr = 0;
-#define error_not_EINTR (Curl_ack_eintr || error != EINTR)
+#define ERROR_NOT_EINTR(error) (Curl_ack_eintr || error != EINTR)
 
 /*
  * Internal function used for waiting a specific amount of ms
- * in Curl_socket_ready() and Curl_poll() when no file descriptor
+ * in Curl_socket_check() and Curl_poll() when no file descriptor
  * is provided to wait on, just being used to delay execution.
  * WinSock select() and poll() timeout mechanisms need a valid
  * socket descriptor in a not null file descriptor set to work.
@@ -109,9 +108,9 @@ int Curl_wait_ms(int timeout_ms)
     if(r != -1)
       break;
     error = SOCKERRNO;
-    if(error && error_not_EINTR)
+    if(error && ERROR_NOT_EINTR(error))
       break;
-    pending_ms = timeout_ms - elapsed_ms;
+    pending_ms = timeout_ms - ELAPSED_MS();
     if(pending_ms <= 0) {
       r = 0;  /* Simulate a "call timed out" case */
       break;
@@ -165,6 +164,12 @@ int Curl_socket_check(curl_socket_t readfd0, /* two sockets to read from */
   int r;
   int ret;
 
+#if SIZEOF_LONG != SIZEOF_INT
+  /* wrap-around precaution */
+  if(timeout_ms >= INT_MAX)
+    timeout_ms = INT_MAX;
+#endif
+
   if((readfd0 == CURL_SOCKET_BAD) && (readfd1 == CURL_SOCKET_BAD) &&
      (writefd == CURL_SOCKET_BAD)) {
     /* no sockets, just wait */
@@ -213,10 +218,10 @@ int Curl_socket_check(curl_socket_t readfd0, /* two sockets to read from */
     if(r != -1)
       break;
     error = SOCKERRNO;
-    if(error && error_not_EINTR)
+    if(error && ERROR_NOT_EINTR(error))
       break;
     if(timeout_ms > 0) {
-      pending_ms = (int)(timeout_ms - elapsed_ms);
+      pending_ms = (int)(timeout_ms - ELAPSED_MS());
       if(pending_ms <= 0) {
         r = 0;  /* Simulate a "call timed out" case */
         break;
@@ -328,10 +333,10 @@ int Curl_socket_check(curl_socket_t readfd0, /* two sockets to read from */
     if(r != -1)
       break;
     error = SOCKERRNO;
-    if(error && error_not_EINTR)
+    if(error && ERROR_NOT_EINTR(error))
       break;
     if(timeout_ms > 0) {
-      pending_ms = timeout_ms - elapsed_ms;
+      pending_ms = (int)(timeout_ms - ELAPSED_MS());
       if(pending_ms <= 0) {
         r = 0;  /* Simulate a "call timed out" case */
         break;
@@ -434,10 +439,10 @@ int Curl_poll(struct pollfd ufds[], unsigned int nfds, int timeout_ms)
     if(r != -1)
       break;
     error = SOCKERRNO;
-    if(error && error_not_EINTR)
+    if(error && ERROR_NOT_EINTR(error))
       break;
     if(timeout_ms > 0) {
-      pending_ms = timeout_ms - elapsed_ms;
+      pending_ms = (int)(timeout_ms - ELAPSED_MS());
       if(pending_ms <= 0) {
         r = 0;  /* Simulate a "call timed out" case */
         break;
@@ -521,10 +526,10 @@ int Curl_poll(struct pollfd ufds[], unsigned int nfds, int timeout_ms)
     if(r != -1)
       break;
     error = SOCKERRNO;
-    if(error && error_not_EINTR)
+    if(error && ERROR_NOT_EINTR(error))
       break;
     if(timeout_ms > 0) {
-      pending_ms = timeout_ms - elapsed_ms;
+      pending_ms = timeout_ms - ELAPSED_MS();
       if(pending_ms <= 0) {
         r = 0;  /* Simulate a "call timed out" case */
         break;
diff --git a/Utilities/cmcurl/lib/select.h b/Utilities/cmcurl/lib/select.h
index 695bb69..1d26f49 100644
--- a/Utilities/cmcurl/lib/select.h
+++ b/Utilities/cmcurl/lib/select.h
@@ -7,7 +7,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -75,9 +75,10 @@ int Curl_socket_check(curl_socket_t readfd, curl_socket_t readfd2,
                       curl_socket_t writefd,
                       long timeout_ms);
 
-/* provide the former API internally */
-#define Curl_socket_ready(x,y,z) \
-  Curl_socket_check(x, CURL_SOCKET_BAD, y, z)
+#define SOCKET_READABLE(x,z) \
+  Curl_socket_check(x, CURL_SOCKET_BAD, CURL_SOCKET_BAD, z)
+#define SOCKET_WRITABLE(x,z) \
+  Curl_socket_check(CURL_SOCKET_BAD, CURL_SOCKET_BAD, x, z)
 
 int Curl_poll(struct pollfd ufds[], unsigned int nfds, int timeout_ms);
 
diff --git a/Utilities/cmcurl/lib/smb.c b/Utilities/cmcurl/lib/smb.c
index 56a38c2..7cb0c96 100644
--- a/Utilities/cmcurl/lib/smb.c
+++ b/Utilities/cmcurl/lib/smb.c
@@ -673,7 +673,7 @@ static CURLcode smb_connection_state(struct connectdata *conn, bool *done)
 
   switch(smbc->state) {
   case SMB_NEGOTIATE:
-    if(h->status) {
+    if(h->status || smbc->got < sizeof(*nrsp) + sizeof(smbc->challenge) - 1) {
       connclose(conn, "SMB: negotiation failed");
       return CURLE_COULDNT_CONNECT;
     }
@@ -712,6 +712,7 @@ static CURLcode smb_request_state(struct connectdata *conn, bool *done)
 {
   struct smb_request *req = conn->data->req.protop;
   struct smb_header *h;
+  struct smb_conn *smbc = &conn->proto.smbc;
   enum smb_req_state next_state = SMB_DONE;
   unsigned short len;
   unsigned short off;
@@ -754,7 +755,7 @@ static CURLcode smb_request_state(struct connectdata *conn, bool *done)
     break;
 
   case SMB_OPEN:
-    if(h->status) {
+    if(h->status || smbc->got < sizeof(struct smb_nt_create_response)) {
       req->result = CURLE_REMOTE_FILE_NOT_FOUND;
       next_state = SMB_TREE_DISCONNECT;
       break;
@@ -775,7 +776,7 @@ static CURLcode smb_request_state(struct connectdata *conn, bool *done)
     break;
 
   case SMB_DOWNLOAD:
-    if(h->status) {
+    if(h->status || smbc->got < sizeof(struct smb_header) + 14) {
       req->result = CURLE_RECV_ERROR;
       next_state = SMB_CLOSE;
       break;
@@ -785,7 +786,6 @@ static CURLcode smb_request_state(struct connectdata *conn, bool *done)
     off = Curl_read16_le(((unsigned char *) msg) +
                          sizeof(struct smb_header) + 13);
     if(len > 0) {
-      struct smb_conn *smbc = &conn->proto.smbc;
       if(off + sizeof(unsigned int) + len > smbc->got) {
         failf(conn->data, "Invalid input packet");
         result = CURLE_RECV_ERROR;
@@ -807,7 +807,7 @@ static CURLcode smb_request_state(struct connectdata *conn, bool *done)
     break;
 
   case SMB_UPLOAD:
-    if(h->status) {
+    if(h->status || smbc->got < sizeof(struct smb_header) + 6) {
       req->result = CURLE_UPLOAD_FAILED;
       next_state = SMB_CLOSE;
       break;
diff --git a/Utilities/cmcurl/lib/smtp.c b/Utilities/cmcurl/lib/smtp.c
index d203b53..a4fc2c2 100644
--- a/Utilities/cmcurl/lib/smtp.c
+++ b/Utilities/cmcurl/lib/smtp.c
@@ -69,16 +69,14 @@
 #include "http.h" /* for HTTP proxy tunnel stuff */
 #include "socks.h"
 #include "smtp.h"
-
 #include "strtoofft.h"
-#include "strequal.h"
+#include "strcase.h"
 #include "vtls/vtls.h"
 #include "connect.h"
 #include "strerror.h"
 #include "select.h"
 #include "multiif.h"
 #include "url.h"
-#include "rawstr.h"
 #include "curl_gethostname.h"
 #include "curl_sasl.h"
 #include "warnless.h"
@@ -674,7 +672,7 @@ static CURLcode smtp_state_servergreet_resp(struct connectdata *conn,
 
   if(smtpcode/100 != 2) {
     failf(data, "Got unexpected smtp-server response: %d", smtpcode);
-    result = CURLE_FTP_WEIRD_SERVER_REPLY;
+    result = CURLE_WEIRD_SERVER_REPLY;
   }
   else
     result = smtp_perform_ehlo(conn);
@@ -1512,7 +1510,7 @@ static CURLcode smtp_parse_url_options(struct connectdata *conn)
     while(*ptr && *ptr != ';')
       ptr++;
 
-    if(strnequal(key, "AUTH=", 5))
+    if(strncasecompare(key, "AUTH=", 5))
       result = Curl_sasl_parse_url_auth_option(&smtpc->sasl,
                                                value, ptr - value);
     else
diff --git a/Utilities/cmcurl/lib/socks.c b/Utilities/cmcurl/lib/socks.c
index fccb16d..742d411 100644
--- a/Utilities/cmcurl/lib/socks.c
+++ b/Utilities/cmcurl/lib/socks.c
@@ -33,7 +33,6 @@
 
 #include "urldata.h"
 #include "sendf.h"
-#include "strequal.h"
 #include "select.h"
 #include "connect.h"
 #include "timeval.h"
@@ -67,7 +66,7 @@ int Curl_blockread_all(struct connectdata *conn, /* connection data */
       result = CURLE_OPERATION_TIMEDOUT;
       break;
     }
-    if(Curl_socket_ready(sockfd, CURL_SOCKET_BAD, timeleft) <= 0) {
+    if(SOCKET_READABLE(sockfd, timeleft) <= 0) {
       result = ~CURLE_OK;
       break;
     }
@@ -170,24 +169,26 @@ CURLcode Curl_SOCKS4(const char *proxy_name,
       hp=dns->addr;
     if(hp) {
       char buf[64];
-      unsigned short ip[4];
       Curl_printable_address(hp, buf, sizeof(buf));
 
-      if(4 == sscanf(buf, "%hu.%hu.%hu.%hu",
-                     &ip[0], &ip[1], &ip[2], &ip[3])) {
-        /* Set DSTIP */
-        socksreq[4] = (unsigned char)ip[0];
-        socksreq[5] = (unsigned char)ip[1];
-        socksreq[6] = (unsigned char)ip[2];
-        socksreq[7] = (unsigned char)ip[3];
+      if(hp->ai_family == AF_INET) {
+        struct sockaddr_in *saddr_in;
+
+        saddr_in = (struct sockaddr_in*)(void*)hp->ai_addr;
+        socksreq[4] = ((unsigned char*)&saddr_in->sin_addr.s_addr)[0];
+        socksreq[5] = ((unsigned char*)&saddr_in->sin_addr.s_addr)[1];
+        socksreq[6] = ((unsigned char*)&saddr_in->sin_addr.s_addr)[2];
+        socksreq[7] = ((unsigned char*)&saddr_in->sin_addr.s_addr)[3];
+
+        infof(data, "SOCKS4 connect to IPv4 %s (locally resolved)\n", buf);
       }
-      else
+      else {
         hp = NULL; /* fail! */
 
-      infof(data, "SOCKS4 connect to %s (locally resolved)\n", buf);
+        failf(data, "SOCKS4 connection to %s not supported\n", buf);
+      }
 
       Curl_resolv_unlock(data, dns); /* not used anymore from now on */
-
     }
     if(!hp) {
       failf(data, "Failed to resolve \"%s\" for SOCKS4 connect.",
@@ -399,7 +400,7 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
   (void)curlx_nonblock(sock, TRUE);
 
   /* wait until socket gets connected */
-  result = Curl_socket_ready(CURL_SOCKET_BAD, sock, timeout);
+  result = SOCKET_WRITABLE(sock, timeout);
 
   if(-1 == result) {
     failf(conn->data, "SOCKS5: no connection here");
@@ -429,6 +430,8 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
 
   (void)curlx_nonblock(sock, FALSE);
 
+  infof(data, "SOCKS5 communication to %s:%d\n", hostname, remote_port);
+
   code = Curl_write_plain(conn, sock, (char *)socksreq, (2 + (int)socksreq[1]),
                           &written);
   if(code || (written != (2 + (int)socksreq[1]))) {
@@ -438,7 +441,7 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
 
   (void)curlx_nonblock(sock, TRUE);
 
-  result = Curl_socket_ready(sock, CURL_SOCKET_BAD, timeout);
+  result = SOCKET_READABLE(sock, timeout);
 
   if(-1 == result) {
     failf(conn->data, "SOCKS5 nothing to read");
@@ -594,34 +597,40 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
     if(dns)
       hp=dns->addr;
     if(hp) {
-      struct sockaddr_in *saddr_in;
-#ifdef ENABLE_IPV6
-      struct sockaddr_in6 *saddr_in6;
-#endif
       int i;
+      char buf[64];
+      Curl_printable_address(hp, buf, sizeof(buf));
 
       if(hp->ai_family == AF_INET) {
+        struct sockaddr_in *saddr_in;
         socksreq[len++] = 1; /* ATYP: IPv4 = 1 */
 
         saddr_in = (struct sockaddr_in*)(void*)hp->ai_addr;
         for(i = 0; i < 4; i++) {
           socksreq[len++] = ((unsigned char*)&saddr_in->sin_addr.s_addr)[i];
-          infof(data, "%d\n", socksreq[len-1]);
         }
+
+        infof(data, "SOCKS5 connect to IPv4 %s (locally resolved)\n", buf);
       }
 #ifdef ENABLE_IPV6
       else if(hp->ai_family == AF_INET6) {
+        struct sockaddr_in6 *saddr_in6;
         socksreq[len++] = 4; /* ATYP: IPv6 = 4 */
 
         saddr_in6 = (struct sockaddr_in6*)(void*)hp->ai_addr;
         for(i = 0; i < 16; i++) {
           socksreq[len++] = ((unsigned char*)&saddr_in6->sin6_addr.s6_addr)[i];
         }
+
+        infof(data, "SOCKS5 connect to IPv6 %s (locally resolved)\n", buf);
       }
 #endif
-      else
+      else {
         hp = NULL; /* fail! */
 
+        failf(data, "SOCKS5 connection to %s not supported\n", buf);
+      }
+
       Curl_resolv_unlock(data, dns); /* not used anymore from now on */
     }
     if(!hp) {
@@ -668,39 +677,6 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
           "SOCKS5 reply has wrong version, version should be 5.");
     return CURLE_COULDNT_CONNECT;
   }
-  if(socksreq[1] != 0) { /* Anything besides 0 is an error */
-    if(socksreq[3] == 1) {
-      failf(data,
-            "Can't complete SOCKS5 connection to %d.%d.%d.%d:%d. (%d)",
-            (unsigned char)socksreq[4], (unsigned char)socksreq[5],
-            (unsigned char)socksreq[6], (unsigned char)socksreq[7],
-            (((unsigned char)socksreq[8] << 8) | (unsigned char)socksreq[9]),
-            (unsigned char)socksreq[1]);
-    }
-    else if(socksreq[3] == 3) {
-      failf(data,
-            "Can't complete SOCKS5 connection to %s:%d. (%d)",
-            hostname,
-            (((unsigned char)socksreq[8] << 8) | (unsigned char)socksreq[9]),
-            (unsigned char)socksreq[1]);
-    }
-    else if(socksreq[3] == 4) {
-      failf(data,
-            "Can't complete SOCKS5 connection to %02x%02x:%02x%02x:"
-            "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%d. (%d)",
-            (unsigned char)socksreq[4], (unsigned char)socksreq[5],
-            (unsigned char)socksreq[6], (unsigned char)socksreq[7],
-            (unsigned char)socksreq[8], (unsigned char)socksreq[9],
-            (unsigned char)socksreq[10], (unsigned char)socksreq[11],
-            (unsigned char)socksreq[12], (unsigned char)socksreq[13],
-            (unsigned char)socksreq[14], (unsigned char)socksreq[15],
-            (unsigned char)socksreq[16], (unsigned char)socksreq[17],
-            (unsigned char)socksreq[18], (unsigned char)socksreq[19],
-            (((unsigned char)socksreq[8] << 8) | (unsigned char)socksreq[9]),
-            (unsigned char)socksreq[1]);
-    }
-    return CURLE_COULDNT_CONNECT;
-  }
 
   /* Fix: in general, returned BND.ADDR is variable length parameter by RFC
      1928, so the reply packet should be read until the end to avoid errors at
@@ -735,10 +711,9 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
     /* decrypt_gssapi_blockread already read the whole packet */
 #endif
     if(len > 10) {
-      len -= 10;
       result = Curl_blockread_all(conn, sock, (char *)&socksreq[10],
-                                  len, &actualread);
-      if(result || (len != actualread)) {
+                                  len - 10, &actualread);
+      if(result || ((len - 10) != actualread)) {
         failf(data, "Failed to receive SOCKS5 connect request ack.");
         return CURLE_COULDNT_CONNECT;
       }
@@ -747,6 +722,49 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
   }
 #endif
 
+  if(socksreq[1] != 0) { /* Anything besides 0 is an error */
+    if(socksreq[3] == 1) {
+      failf(data,
+            "Can't complete SOCKS5 connection to %d.%d.%d.%d:%d. (%d)",
+            (unsigned char)socksreq[4], (unsigned char)socksreq[5],
+            (unsigned char)socksreq[6], (unsigned char)socksreq[7],
+            (((unsigned char)socksreq[8] << 8) |
+             (unsigned char)socksreq[9]),
+            (unsigned char)socksreq[1]);
+    }
+    else if(socksreq[3] == 3) {
+      unsigned char port_upper = (unsigned char)socksreq[len - 2];
+      socksreq[len - 2] = 0;
+      failf(data,
+            "Can't complete SOCKS5 connection to %s:%d. (%d)",
+            (char *)&socksreq[5],
+            ((port_upper << 8) |
+             (unsigned char)socksreq[len - 1]),
+            (unsigned char)socksreq[1]);
+      socksreq[len - 2] = port_upper;
+    }
+    else if(socksreq[3] == 4) {
+      failf(data,
+            "Can't complete SOCKS5 connection to %02x%02x:%02x%02x:"
+            "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%d. (%d)",
+            (unsigned char)socksreq[4], (unsigned char)socksreq[5],
+            (unsigned char)socksreq[6], (unsigned char)socksreq[7],
+            (unsigned char)socksreq[8], (unsigned char)socksreq[9],
+            (unsigned char)socksreq[10], (unsigned char)socksreq[11],
+            (unsigned char)socksreq[12], (unsigned char)socksreq[13],
+            (unsigned char)socksreq[14], (unsigned char)socksreq[15],
+            (unsigned char)socksreq[16], (unsigned char)socksreq[17],
+            (unsigned char)socksreq[18], (unsigned char)socksreq[19],
+            (((unsigned char)socksreq[20] << 8) |
+             (unsigned char)socksreq[21]),
+            (unsigned char)socksreq[1]);
+    }
+    return CURLE_COULDNT_CONNECT;
+  }
+  else {
+    infof(data, "SOCKS5 request granted.\n");
+  }
+
   (void)curlx_nonblock(sock, TRUE);
   return CURLE_OK; /* Proxy was successful! */
 }
diff --git a/Utilities/cmcurl/lib/ssh.c b/Utilities/cmcurl/lib/ssh.c
index 7bc3136..43c8283 100644
--- a/Utilities/cmcurl/lib/ssh.c
+++ b/Utilities/cmcurl/lib/ssh.c
@@ -72,7 +72,7 @@
 #include "speedcheck.h"
 #include "getinfo.h"
 
-#include "strequal.h"
+#include "strcase.h"
 #include "vtls/vtls.h"
 #include "connect.h"
 #include "strerror.h"
@@ -416,12 +416,12 @@ static CURLcode ssh_getworkingpath(struct connectdata *conn,
   struct Curl_easy *data = conn->data;
   char *real_path = NULL;
   char *working_path;
-  int working_path_len;
-
-  working_path = curl_easy_unescape(data, data->state.path, 0,
-                                    &working_path_len);
-  if(!working_path)
-    return CURLE_OUT_OF_MEMORY;
+  size_t working_path_len;
+  CURLcode result =
+    Curl_urldecode(data, data->state.path, 0, &working_path,
+                   &working_path_len, FALSE);
+  if(result)
+    return result;
 
   /* Check for /~/, indicating relative to the user's home directory */
   if(conn->handler->protocol & CURLPROTO_SCP) {
@@ -676,7 +676,7 @@ static CURLcode ssh_check_fingerprint(struct connectdata *conn)
    * against a known fingerprint, if available.
    */
   if(pubkey_md5 && strlen(pubkey_md5) == 32) {
-    if(!fingerprint || !strequal(md5buffer, pubkey_md5)) {
+    if(!fingerprint || strcmp(md5buffer, pubkey_md5)) {
       if(fingerprint)
         failf(data,
             "Denied establishing ssh session: mismatch md5 fingerprint. "
@@ -1233,7 +1233,7 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
         sshc->acceptfail = TRUE;
       }
 
-      if(curl_strequal("pwd", cmd)) {
+      if(strcasecompare("pwd", cmd)) {
         /* output debug output if that is requested */
         char *tmp = aprintf("257 \"%s\" is current directory.\n",
                             sftp_scp->path);
@@ -1297,9 +1297,9 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
          * OpenSSH's sftp program and call the appropriate libssh2
          * functions.
          */
-        if(curl_strnequal(cmd, "chgrp ", 6) ||
-           curl_strnequal(cmd, "chmod ", 6) ||
-           curl_strnequal(cmd, "chown ", 6) ) {
+        if(strncasecompare(cmd, "chgrp ", 6) ||
+           strncasecompare(cmd, "chmod ", 6) ||
+           strncasecompare(cmd, "chown ", 6) ) {
           /* attribute change */
 
           /* sshc->quote_path1 contains the mode to set */
@@ -1321,8 +1321,8 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
           state(conn, SSH_SFTP_QUOTE_STAT);
           break;
         }
-        else if(curl_strnequal(cmd, "ln ", 3) ||
-                curl_strnequal(cmd, "symlink ", 8)) {
+        else if(strncasecompare(cmd, "ln ", 3) ||
+                strncasecompare(cmd, "symlink ", 8)) {
           /* symbolic linking */
           /* sshc->quote_path1 is the source */
           /* get the destination */
@@ -1342,12 +1342,12 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
           state(conn, SSH_SFTP_QUOTE_SYMLINK);
           break;
         }
-        else if(curl_strnequal(cmd, "mkdir ", 6)) {
+        else if(strncasecompare(cmd, "mkdir ", 6)) {
           /* create dir */
           state(conn, SSH_SFTP_QUOTE_MKDIR);
           break;
         }
-        else if(curl_strnequal(cmd, "rename ", 7)) {
+        else if(strncasecompare(cmd, "rename ", 7)) {
           /* rename file */
           /* first param is the source path */
           /* second param is the dest. path */
@@ -1366,17 +1366,17 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
           state(conn, SSH_SFTP_QUOTE_RENAME);
           break;
         }
-        else if(curl_strnequal(cmd, "rmdir ", 6)) {
+        else if(strncasecompare(cmd, "rmdir ", 6)) {
           /* delete dir */
           state(conn, SSH_SFTP_QUOTE_RMDIR);
           break;
         }
-        else if(curl_strnequal(cmd, "rm ", 3)) {
+        else if(strncasecompare(cmd, "rm ", 3)) {
           state(conn, SSH_SFTP_QUOTE_UNLINK);
           break;
         }
 #ifdef HAS_STATVFS_SUPPORT
-        else if(curl_strnequal(cmd, "statvfs ", 8)) {
+        else if(strncasecompare(cmd, "statvfs ", 8)) {
           state(conn, SSH_SFTP_QUOTE_STATVFS);
           break;
         }
@@ -1431,7 +1431,7 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
         sshc->acceptfail = TRUE;
       }
 
-      if(!curl_strnequal(cmd, "chmod", 5)) {
+      if(!strncasecompare(cmd, "chmod", 5)) {
         /* Since chown and chgrp only set owner OR group but libssh2 wants to
          * set them both at once, we need to obtain the current ownership
          * first.  This takes an extra protocol round trip.
@@ -1457,7 +1457,7 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
       }
 
       /* Now set the new attributes... */
-      if(curl_strnequal(cmd, "chgrp", 5)) {
+      if(strncasecompare(cmd, "chgrp", 5)) {
         sshc->quote_attrs.gid = strtoul(sshc->quote_path1, NULL, 10);
         sshc->quote_attrs.flags = LIBSSH2_SFTP_ATTR_UIDGID;
         if(sshc->quote_attrs.gid == 0 && !ISDIGIT(sshc->quote_path1[0]) &&
@@ -1471,7 +1471,7 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
           break;
         }
       }
-      else if(curl_strnequal(cmd, "chmod", 5)) {
+      else if(strncasecompare(cmd, "chmod", 5)) {
         sshc->quote_attrs.permissions = strtoul(sshc->quote_path1, NULL, 8);
         sshc->quote_attrs.flags = LIBSSH2_SFTP_ATTR_PERMISSIONS;
         /* permissions are octal */
@@ -1486,7 +1486,7 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
           break;
         }
       }
-      else if(curl_strnequal(cmd, "chown", 5)) {
+      else if(strncasecompare(cmd, "chown", 5)) {
         sshc->quote_attrs.uid = strtoul(sshc->quote_path1, NULL, 10);
         sshc->quote_attrs.flags = LIBSSH2_SFTP_ATTR_UIDGID;
         if(sshc->quote_attrs.uid == 0 && !ISDIGIT(sshc->quote_path1[0]) &&
@@ -1895,7 +1895,7 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
         /* since we don't really wait for anything at this point, we want the
            state machine to move on as soon as possible so we set a very short
            timeout here */
-        Curl_expire(data, 1);
+        Curl_expire(data, 0);
 
         state(conn, SSH_STOP);
       }
@@ -2860,7 +2860,7 @@ static CURLcode ssh_block_statemach(struct connectdata *conn,
       if(LIBSSH2_SESSION_BLOCK_OUTBOUND & dir)
         fd_write = sock;
       /* wait for the socket to become ready */
-      Curl_socket_ready(fd_read, fd_write,
+      Curl_socket_check(fd_read, CURL_SOCKET_BAD, fd_write,
                         left>1000?1000:left); /* ignore result */
     }
 #endif
@@ -3109,7 +3109,6 @@ static CURLcode scp_done(struct connectdata *conn, CURLcode status,
 
 }
 
-/* return number of received (decrypted) bytes */
 static ssize_t scp_send(struct connectdata *conn, int sockindex,
                         const void *mem, size_t len, CURLcode *err)
 {
@@ -3134,10 +3133,6 @@ static ssize_t scp_send(struct connectdata *conn, int sockindex,
   return nwrite;
 }
 
-/*
- * If the read would block (EWOULDBLOCK) we return -1. Otherwise we return
- * a regular CURLcode value.
- */
 static ssize_t scp_recv(struct connectdata *conn, int sockindex,
                         char *mem, size_t len, CURLcode *err)
 {
diff --git a/Utilities/cmcurl/lib/strcase.c b/Utilities/cmcurl/lib/strcase.c
new file mode 100644
index 0000000..807689e
--- /dev/null
+++ b/Utilities/cmcurl/lib/strcase.c
@@ -0,0 +1,166 @@
+/***************************************************************************
+ *                                  _   _ ____  _
+ *  Project                     ___| | | |  _ \| |
+ *                             / __| | | | |_) | |
+ *                            | (__| |_| |  _ <| |___
+ *                             \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at https://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include <curl/curl.h>
+
+#include "strcase.h"
+
+/* Portable, consistent toupper (remember EBCDIC). Do not use toupper() because
+   its behavior is altered by the current locale. */
+char Curl_raw_toupper(char in)
+{
+#if !defined(CURL_DOES_CONVERSIONS)
+  if(in >= 'a' && in <= 'z')
+    return (char)('A' + in - 'a');
+#else
+  switch (in) {
+  case 'a':
+    return 'A';
+  case 'b':
+    return 'B';
+  case 'c':
+    return 'C';
+  case 'd':
+    return 'D';
+  case 'e':
+    return 'E';
+  case 'f':
+    return 'F';
+  case 'g':
+    return 'G';
+  case 'h':
+    return 'H';
+  case 'i':
+    return 'I';
+  case 'j':
+    return 'J';
+  case 'k':
+    return 'K';
+  case 'l':
+    return 'L';
+  case 'm':
+    return 'M';
+  case 'n':
+    return 'N';
+  case 'o':
+    return 'O';
+  case 'p':
+    return 'P';
+  case 'q':
+    return 'Q';
+  case 'r':
+    return 'R';
+  case 's':
+    return 'S';
+  case 't':
+    return 'T';
+  case 'u':
+    return 'U';
+  case 'v':
+    return 'V';
+  case 'w':
+    return 'W';
+  case 'x':
+    return 'X';
+  case 'y':
+    return 'Y';
+  case 'z':
+    return 'Z';
+  }
+#endif
+
+  return in;
+}
+
+/*
+ * Curl_raw_equal() is for doing "raw" case insensitive strings. This is meant
+ * to be locale independent and only compare strings we know are safe for
+ * this.  See https://daniel.haxx.se/blog/2008/10/15/strcasecmp-in-turkish/ for
+ * some further explanation to why this function is necessary.
+ *
+ * The function is capable of comparing a-z case insensitively even for
+ * non-ascii.
+ *
+ * @unittest: 1301
+ */
+
+int Curl_strcasecompare(const char *first, const char *second)
+{
+  while(*first && *second) {
+    if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second))
+      /* get out of the loop as soon as they don't match */
+      break;
+    first++;
+    second++;
+  }
+  /* we do the comparison here (possibly again), just to make sure that if the
+     loop above is skipped because one of the strings reached zero, we must not
+     return this as a successful match */
+  return (Curl_raw_toupper(*first) == Curl_raw_toupper(*second));
+}
+
+/*
+ * @unittest: 1301
+ */
+int Curl_strncasecompare(const char *first, const char *second, size_t max)
+{
+  while(*first && *second && max) {
+    if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) {
+      break;
+    }
+    max--;
+    first++;
+    second++;
+  }
+  if(0 == max)
+    return 1; /* they are equal this far */
+
+  return Curl_raw_toupper(*first) == Curl_raw_toupper(*second);
+}
+
+/* Copy an upper case version of the string from src to dest.  The
+ * strings may overlap.  No more than n characters of the string are copied
+ * (including any NUL) and the destination string will NOT be
+ * NUL-terminated if that limit is reached.
+ */
+void Curl_strntoupper(char *dest, const char *src, size_t n)
+{
+  if(n < 1)
+    return;
+
+  do {
+    *dest++ = Curl_raw_toupper(*src);
+  } while(*src++ && --n);
+}
+
+/* --- public functions --- */
+
+int curl_strequal(const char *first, const char *second)
+{
+  return Curl_strcasecompare(first, second);
+}
+int curl_strnequal(const char *first, const char *second, size_t max)
+{
+  return Curl_strncasecompare(first, second, max);
+}
diff --git a/Utilities/cmcurl/lib/strcase.h b/Utilities/cmcurl/lib/strcase.h
new file mode 100644
index 0000000..bf057b1
--- /dev/null
+++ b/Utilities/cmcurl/lib/strcase.h
@@ -0,0 +1,50 @@
+#ifndef HEADER_CURL_STRCASE_H
+#define HEADER_CURL_STRCASE_H
+/***************************************************************************
+ *                                  _   _ ____  _
+ *  Project                     ___| | | |  _ \| |
+ *                             / __| | | | |_) | |
+ *                            | (__| |_| |  _ <| |___
+ *                             \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at https://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include <curl/curl.h>
+
+/*
+ * Only "raw" case insensitive strings. This is meant to be locale independent
+ * and only compare strings we know are safe for this.
+ *
+ * The function is capable of comparing a-z case insensitively even for
+ * non-ascii.
+ */
+
+#define strcasecompare(a,b) Curl_strcasecompare(a,b)
+#define strncasecompare(a,b,c) Curl_strncasecompare(a,b,c)
+
+int Curl_strcasecompare(const char *first, const char *second);
+int Curl_strncasecompare(const char *first, const char *second, size_t max);
+
+char Curl_raw_toupper(char in);
+
+/* checkprefix() is a shorter version of the above, used when the first
+   argument is zero-byte terminated */
+#define checkprefix(a,b)    curl_strnequal(a,b,strlen(a))
+
+void Curl_strntoupper(char *dest, const char *src, size_t n);
+char Curl_raw_toupper(char in);
+
+#endif /* HEADER_CURL_STRCASE_H */
diff --git a/Utilities/cmcurl/lib/strdup.c b/Utilities/cmcurl/lib/strdup.c
index 23f554e..5a15c2b 100644
--- a/Utilities/cmcurl/lib/strdup.c
+++ b/Utilities/cmcurl/lib/strdup.c
@@ -65,9 +65,9 @@ char *curlx_strdup(const char *str)
  * Returns the new pointer or NULL on failure.
  *
  ***************************************************************************/
-char *Curl_memdup(const char *src, size_t length)
+void *Curl_memdup(const void *src, size_t length)
 {
-  char *buffer = malloc(length);
+  void *buffer = malloc(length);
   if(!buffer)
     return NULL; /* fail */
 
diff --git a/Utilities/cmcurl/lib/strdup.h b/Utilities/cmcurl/lib/strdup.h
index 4c48ca4..c74a3b7 100644
--- a/Utilities/cmcurl/lib/strdup.h
+++ b/Utilities/cmcurl/lib/strdup.h
@@ -7,7 +7,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -26,6 +26,6 @@
 #ifndef HAVE_STRDUP
 extern char *curlx_strdup(const char *str);
 #endif
-char *Curl_memdup(const char *src, size_t buffer_length);
+void *Curl_memdup(const void *src, size_t buffer_length);
 
 #endif /* HEADER_CURL_STRDUP_H */
diff --git a/Utilities/cmcurl/lib/strequal.c b/Utilities/cmcurl/lib/strequal.c
deleted file mode 100644
index 01c3784..0000000
--- a/Utilities/cmcurl/lib/strequal.c
+++ /dev/null
@@ -1,79 +0,0 @@
-/***************************************************************************
- *                                  _   _ ____  _
- *  Project                     ___| | | |  _ \| |
- *                             / __| | | | |_) | |
- *                            | (__| |_| |  _ <| |___
- *                             \___|\___/|_| \_\_____|
- *
- * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel at haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
- * are also available at https://curl.haxx.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include "curl_setup.h"
-
-#ifdef HAVE_STRINGS_H
-#include <strings.h>
-#endif
-
-#include "strequal.h"
-
-/*
- * @unittest: 1301
- */
-int curl_strequal(const char *first, const char *second)
-{
-#if defined(HAVE_STRCASECMP)
-  return !(strcasecmp)(first, second);
-#elif defined(HAVE_STRCMPI)
-  return !(strcmpi)(first, second);
-#elif defined(HAVE_STRICMP)
-  return !(stricmp)(first, second);
-#else
-  while(*first && *second) {
-    if(toupper(*first) != toupper(*second)) {
-      break;
-    }
-    first++;
-    second++;
-  }
-  return toupper(*first) == toupper(*second);
-#endif
-}
-
-/*
- * @unittest: 1301
- */
-int curl_strnequal(const char *first, const char *second, size_t max)
-{
-#if defined(HAVE_STRNCASECMP)
-  return !strncasecmp(first, second, max);
-#elif defined(HAVE_STRNCMPI)
-  return !strncmpi(first, second, max);
-#elif defined(HAVE_STRNICMP)
-  return !strnicmp(first, second, max);
-#else
-  while(*first && *second && max) {
-    if(toupper(*first) != toupper(*second)) {
-      break;
-    }
-    max--;
-    first++;
-    second++;
-  }
-  if(0 == max)
-    return 1; /* they are equal this far */
-
-  return toupper(*first) == toupper(*second);
-#endif
-}
diff --git a/Utilities/cmcurl/lib/strequal.h b/Utilities/cmcurl/lib/strequal.h
deleted file mode 100644
index ff56df5..0000000
--- a/Utilities/cmcurl/lib/strequal.h
+++ /dev/null
@@ -1,31 +0,0 @@
-#ifndef HEADER_CURL_STREQUAL_H
-#define HEADER_CURL_STREQUAL_H
-/***************************************************************************
- *                                  _   _ ____  _
- *  Project                     ___| | | |  _ \| |
- *                             / __| | | | |_) | |
- *                            | (__| |_| |  _ <| |___
- *                             \___|\___/|_| \_\_____|
- *
- * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel at haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
- * are also available at https://curl.haxx.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-#include <curl/curl.h>
-
-#define strequal(a,b) curl_strequal(a,b)
-#define strnequal(a,b,c) curl_strnequal(a,b,c)
-
-#endif /* HEADER_CURL_STREQUAL_H */
-
diff --git a/Utilities/cmcurl/lib/strerror.c b/Utilities/cmcurl/lib/strerror.c
index 0e268d5..db50c7d 100644
--- a/Utilities/cmcurl/lib/strerror.c
+++ b/Utilities/cmcurl/lib/strerror.c
@@ -35,8 +35,8 @@
 
 #include <curl/curl.h>
 
-#ifdef USE_LIBIDN
-#include <idna.h>
+#ifdef USE_LIBIDN2
+#include <idn2.h>
 #endif
 
 #ifdef USE_WINDOWS_SSPI
@@ -79,8 +79,8 @@ curl_easy_strerror(CURLcode error)
   case CURLE_COULDNT_CONNECT:
     return "Couldn't connect to server";
 
-  case CURLE_FTP_WEIRD_SERVER_REPLY:
-    return "FTP: weird server reply";
+  case CURLE_WEIRD_SERVER_REPLY:
+    return "Weird server reply";
 
   case CURLE_REMOTE_ACCESS_DENIED:
     return "Access denied to remote resource";
@@ -427,7 +427,7 @@ curl_share_strerror(CURLSHcode error)
 
 #ifdef USE_WINSOCK
 
-/* This function handles most / all (?) Winsock errors cURL is able to produce.
+/* This function handles most / all (?) Winsock errors curl is able to produce.
  */
 static const char *
 get_winsock_error (int err, char *buf, size_t len)
@@ -726,83 +726,6 @@ const char *Curl_strerror(struct connectdata *conn, int err)
   return buf;
 }
 
-#ifdef USE_LIBIDN
-/*
- * Return error-string for libidn status as returned from idna_to_ascii_lz().
- */
-const char *Curl_idn_strerror (struct connectdata *conn, int err)
-{
-#ifdef HAVE_IDNA_STRERROR
-  (void)conn;
-  return idna_strerror((Idna_rc) err);
-#else
-  const char *str;
-  char *buf;
-  size_t max;
-
-  DEBUGASSERT(conn);
-
-  buf = conn->syserr_buf;
-  max = sizeof(conn->syserr_buf)-1;
-  *buf = '\0';
-
-#ifndef CURL_DISABLE_VERBOSE_STRINGS
-  switch ((Idna_rc)err) {
-    case IDNA_SUCCESS:
-      str = "No error";
-      break;
-    case IDNA_STRINGPREP_ERROR:
-      str = "Error in string preparation";
-      break;
-    case IDNA_PUNYCODE_ERROR:
-      str = "Error in Punycode operation";
-      break;
-    case IDNA_CONTAINS_NON_LDH:
-      str = "Illegal ASCII characters";
-      break;
-    case IDNA_CONTAINS_MINUS:
-      str = "Contains minus";
-      break;
-    case IDNA_INVALID_LENGTH:
-      str = "Invalid output length";
-      break;
-    case IDNA_NO_ACE_PREFIX:
-      str = "No ACE prefix (\"xn--\")";
-      break;
-    case IDNA_ROUNDTRIP_VERIFY_ERROR:
-      str = "Round trip verify error";
-      break;
-    case IDNA_CONTAINS_ACE_PREFIX:
-      str = "Already have ACE prefix (\"xn--\")";
-      break;
-    case IDNA_ICONV_ERROR:
-      str = "Locale conversion failed";
-      break;
-    case IDNA_MALLOC_ERROR:
-      str = "Allocation failed";
-      break;
-    case IDNA_DLOPEN_ERROR:
-      str = "dlopen() error";
-      break;
-    default:
-      snprintf(buf, max, "error %d", err);
-      str = NULL;
-      break;
-  }
-#else
-  if((Idna_rc)err == IDNA_SUCCESS)
-    str = "No error";
-  else
-    str = "Error";
-#endif
-  if(str)
-    strncpy(buf, str, max);
-  buf[max] = '\0';
-  return (buf);
-#endif
-}
-#endif  /* USE_LIBIDN */
-
 #ifdef USE_WINDOWS_SSPI
 const char *Curl_sspi_strerror (struct connectdata *conn, int err)
 {
diff --git a/Utilities/cmcurl/lib/strerror.h b/Utilities/cmcurl/lib/strerror.h
index ae8c96b..627273e 100644
--- a/Utilities/cmcurl/lib/strerror.h
+++ b/Utilities/cmcurl/lib/strerror.h
@@ -7,7 +7,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -26,7 +26,7 @@
 
 const char *Curl_strerror (struct connectdata *conn, int err);
 
-#ifdef USE_LIBIDN
+#ifdef USE_LIBIDN2
 const char *Curl_idn_strerror (struct connectdata *conn, int err);
 #endif
 
diff --git a/Utilities/cmcurl/lib/system_win32.c b/Utilities/cmcurl/lib/system_win32.c
index d6a998b..7873759 100644
--- a/Utilities/cmcurl/lib/system_win32.c
+++ b/Utilities/cmcurl/lib/system_win32.c
@@ -83,7 +83,39 @@ bool Curl_verify_windows_version(const unsigned int majorVersion,
 {
   bool matched = FALSE;
 
-#if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_WIN2K) || \
+#if defined(CURL_WINDOWS_APP)
+  /* We have no way to determine the Windows version from Windows apps,
+     so let's assume we're running on the target Windows version. */
+  const WORD fullVersion = MAKEWORD(minorVersion, majorVersion);
+  const WORD targetVersion = (WORD)_WIN32_WINNT;
+
+  switch(condition) {
+  case VERSION_LESS_THAN:
+    matched = targetVersion < fullVersion;
+    break;
+
+  case VERSION_LESS_THAN_EQUAL:
+    matched = targetVersion <= fullVersion;
+    break;
+
+  case VERSION_EQUAL:
+    matched = targetVersion == fullVersion;
+    break;
+
+  case VERSION_GREATER_THAN_EQUAL:
+    matched = targetVersion >= fullVersion;
+    break;
+
+  case VERSION_GREATER_THAN:
+    matched = targetVersion > fullVersion;
+    break;
+  }
+
+  if(matched && (platform == PLATFORM_WINDOWS)) {
+    /* we're always running on PLATFORM_WINNT */
+    matched = FALSE;
+  }
+#elif !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_WIN2K) || \
     (_WIN32_WINNT < _WIN32_WINNT_WIN2K)
   OSVERSIONINFO osver;
 
@@ -128,7 +160,7 @@ bool Curl_verify_windows_version(const unsigned int majorVersion,
     }
 
     /* Verify the platform identifier (if necessary) */
-    if(matched && platform != PLATFORM_DONT_CARE) {
+    if(matched) {
       switch(platform) {
       case PLATFORM_WINDOWS:
         if(osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS)
@@ -138,6 +170,9 @@ bool Curl_verify_windows_version(const unsigned int majorVersion,
       case PLATFORM_WINNT:
         if(osver.dwPlatformId != VER_PLATFORM_WIN32_NT)
           matched = FALSE;
+
+      default: /* like platform == PLATFORM_DONT_CARE */
+        break;
       }
     }
   }
diff --git a/Utilities/cmcurl/lib/telnet.c b/Utilities/cmcurl/lib/telnet.c
index cc705cf..c37242d 100644
--- a/Utilities/cmcurl/lib/telnet.c
+++ b/Utilities/cmcurl/lib/telnet.c
@@ -58,8 +58,7 @@
 
 #include "arpa_telnet.h"
 #include "select.h"
-#include "strequal.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "warnless.h"
 
 /* The last 3 #include files should be in this order */
@@ -846,7 +845,7 @@ static CURLcode check_telnet_options(struct connectdata *conn)
               option_keyword, option_arg) == 2) {
 
       /* Terminal type */
-      if(Curl_raw_equal(option_keyword, "TTYPE")) {
+      if(strcasecompare(option_keyword, "TTYPE")) {
         strncpy(tn->subopt_ttype, option_arg, 31);
         tn->subopt_ttype[31] = 0; /* String termination */
         tn->us_preferred[CURL_TELOPT_TTYPE] = CURL_YES;
@@ -854,7 +853,7 @@ static CURLcode check_telnet_options(struct connectdata *conn)
       }
 
       /* Display variable */
-      if(Curl_raw_equal(option_keyword, "XDISPLOC")) {
+      if(strcasecompare(option_keyword, "XDISPLOC")) {
         strncpy(tn->subopt_xdisploc, option_arg, 127);
         tn->subopt_xdisploc[127] = 0; /* String termination */
         tn->us_preferred[CURL_TELOPT_XDISPLOC] = CURL_YES;
@@ -862,7 +861,7 @@ static CURLcode check_telnet_options(struct connectdata *conn)
       }
 
       /* Environment variable */
-      if(Curl_raw_equal(option_keyword, "NEW_ENV")) {
+      if(strcasecompare(option_keyword, "NEW_ENV")) {
         beg = curl_slist_append(tn->telnet_vars, option_arg);
         if(!beg) {
           result = CURLE_OUT_OF_MEMORY;
@@ -874,7 +873,7 @@ static CURLcode check_telnet_options(struct connectdata *conn)
       }
 
           /* Window Size */
-      if(Curl_raw_equal(option_keyword, "WS")) {
+      if(strcasecompare(option_keyword, "WS")) {
         if(sscanf(option_arg, "%hu%*[xX]%hu",
                   &tn->subopt_wsx, &tn->subopt_wsy) == 2)
           tn->us_preferred[CURL_TELOPT_NAWS] = CURL_YES;
@@ -887,7 +886,7 @@ static CURLcode check_telnet_options(struct connectdata *conn)
       }
 
       /* To take care or not of the 8th bit in data exchange */
-      if(Curl_raw_equal(option_keyword, "BINARY")) {
+      if(strcasecompare(option_keyword, "BINARY")) {
         binary_option=atoi(option_arg);
         if(binary_option!=1) {
           tn->us_preferred[CURL_TELOPT_BINARY] = CURL_NO;
diff --git a/Utilities/cmcurl/lib/tftp.c b/Utilities/cmcurl/lib/tftp.c
index d7ff94f..deee394 100644
--- a/Utilities/cmcurl/lib/tftp.c
+++ b/Utilities/cmcurl/lib/tftp.c
@@ -55,9 +55,10 @@
 #include "sockaddr.h" /* required for Curl_sockaddr_storage */
 #include "multiif.h"
 #include "url.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "speedcheck.h"
 #include "select.h"
+#include "escape.h"
 
 /* The last 3 #include files should be in this order */
 #include "curl_printf.h"
@@ -484,10 +485,10 @@ static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
     /* As RFC3617 describes the separator slash is not actually part of the
        file name so we skip the always-present first letter of the path
        string. */
-    filename = curl_easy_unescape(data, &state->conn->data->state.path[1], 0,
-                                  NULL);
-    if(!filename)
-      return CURLE_OUT_OF_MEMORY;
+    result = Curl_urldecode(data, &state->conn->data->state.path[1], 0,
+                            &filename, NULL, FALSE);
+    if(result)
+      return result;
 
     snprintf((char *)state->spacket.data+2,
              state->blksize,
@@ -705,6 +706,7 @@ static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
   int rblock;
   CURLcode result = CURLE_OK;
   struct SingleRequest *k = &data->req;
+  int cb; /* Bytes currently read */
 
   switch(event) {
 
@@ -762,9 +764,20 @@ static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
       return CURLE_OK;
     }
 
-    result = Curl_fillreadbuffer(state->conn, state->blksize, &state->sbytes);
-    if(result)
-      return result;
+    /* TFTP considers data block size < 512 bytes as an end of session. So
+     * in some cases we must wait for additional data to build full (512 bytes)
+     * data block.
+     * */
+    state->sbytes = 0;
+    state->conn->data->req.upload_fromhere = (char *)state->spacket.data+4;
+    do {
+      result = Curl_fillreadbuffer(state->conn, state->blksize - state->sbytes,
+                                   &cb);
+      if(result)
+        return result;
+      state->sbytes += cb;
+      state->conn->data->req.upload_fromhere += cb;
+    } while(state->sbytes < state->blksize && cb != 0);
 
     sbytes = sendto(state->sockfd, (void *) state->spacket.data,
                     4 + state->sbytes, SEND_4TH_ARG,
@@ -1221,7 +1234,7 @@ static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done)
   }
   else {
     /* no timeouts to handle, check our socket */
-    rc = Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD, 0);
+    rc = SOCKET_READABLE(state->sockfd, 0);
 
     if(rc == -1) {
       /* bail out */
diff --git a/Utilities/cmcurl/lib/transfer.c b/Utilities/cmcurl/lib/transfer.c
index f5987fe..6245ee4 100644
--- a/Utilities/cmcurl/lib/transfer.c
+++ b/Utilities/cmcurl/lib/transfer.c
@@ -21,10 +21,7 @@
  ***************************************************************************/
 
 #include "curl_setup.h"
-
 #include "strtoofft.h"
-#include "strequal.h"
-#include "rawstr.h"
 
 #ifdef HAVE_NETINET_IN_H
 #include <netinet/in.h>
@@ -75,6 +72,7 @@
 #include "multiif.h"
 #include "connect.h"
 #include "non-ascii.h"
+#include "http2.h"
 
 /* The last 3 #include files should be in this order */
 #include "curl_printf.h"
@@ -384,11 +382,15 @@ bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc)
  * Go ahead and do a read if we have a readable socket or if
  * the stream was rewound (in which case we have data in a
  * buffer)
+ *
+ * return '*comeback' TRUE if we didn't properly drain the socket so this
+ * function should get called again without select() or similar in between!
  */
 static CURLcode readwrite_data(struct Curl_easy *data,
                                struct connectdata *conn,
                                struct SingleRequest *k,
-                               int *didwhat, bool *done)
+                               int *didwhat, bool *done,
+                               bool *comeback)
 {
   CURLcode result = CURLE_OK;
   ssize_t nread; /* number of bytes read */
@@ -398,6 +400,7 @@ static CURLcode readwrite_data(struct Curl_easy *data,
   int maxloops = 100;
 
   *done = FALSE;
+  *comeback = FALSE;
 
   /* This is where we loop until we have read everything there is to
      read or we get a CURLE_AGAIN */
@@ -529,6 +532,13 @@ static CURLcode readwrite_data(struct Curl_easy *data,
        is non-headers. */
     if(k->str && !k->header && (nread > 0 || is_empty_data)) {
 
+      if(data->set.opt_no_body) {
+        /* data arrives although we want none, bail out */
+        streamclose(conn, "ignoring body");
+        *done = TRUE;
+        return CURLE_WEIRD_SERVER_REPLY;
+      }
+
 #ifndef CURL_DISABLE_HTTP
       if(0 == k->bodywrites && !is_empty_data) {
         /* These checks are only made the first time we are about to
@@ -804,6 +814,12 @@ static CURLcode readwrite_data(struct Curl_easy *data,
 
   } while(data_pending(conn) && maxloops--);
 
+  if(maxloops <= 0) {
+    /* we mark it as read-again-please */
+    conn->cselect_bits = CURL_CSELECT_IN;
+    *comeback = TRUE;
+  }
+
   if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) &&
      conn->bits.close) {
     /* When we've read the entire thing and the close bit is set, the server
@@ -821,6 +837,8 @@ static CURLcode done_sending(struct connectdata *conn,
 {
   k->keepon &= ~KEEP_SEND; /* we're done writing */
 
+  Curl_http2_done_sending(conn);
+
   if(conn->bits.rewindaftersend) {
     CURLcode result = Curl_readrewind(conn);
     if(result)
@@ -1029,10 +1047,14 @@ static CURLcode readwrite_upload(struct Curl_easy *data,
 /*
  * Curl_readwrite() is the low-level function to be called when data is to
  * be read and written to/from the connection.
+ *
+ * return '*comeback' TRUE if we didn't properly drain the socket so this
+ * function should get called again without select() or similar in between!
  */
 CURLcode Curl_readwrite(struct connectdata *conn,
                         struct Curl_easy *data,
-                        bool *done)
+                        bool *done,
+                        bool *comeback)
 {
   struct SingleRequest *k = &data->req;
   CURLcode result;
@@ -1064,7 +1086,7 @@ CURLcode Curl_readwrite(struct connectdata *conn,
 
   if(!select_res) /* Call for select()/poll() only, if read/write/error
                      status is not known. */
-    select_res = Curl_socket_ready(fd_read, fd_write, 0);
+    select_res = Curl_socket_check(fd_read, CURL_SOCKET_BAD, fd_write, 0);
 
   if(select_res == CURL_CSELECT_ERR) {
     failf(data, "select/poll returned error");
@@ -1077,7 +1099,7 @@ CURLcode Curl_readwrite(struct connectdata *conn,
   if((k->keepon & KEEP_RECV) &&
      ((select_res & CURL_CSELECT_IN) || conn->bits.stream_was_rewound)) {
 
-    result = readwrite_data(data, conn, k, &didwhat, done);
+    result = readwrite_data(data, conn, k, &didwhat, done, comeback);
     if(result || *done)
       return result;
   }
@@ -1249,60 +1271,6 @@ int Curl_single_getsock(const struct connectdata *conn,
   return bitmap;
 }
 
-/*
- * Determine optimum sleep time based on configured rate, current rate,
- * and packet size.
- * Returns value in milliseconds.
- *
- * The basic idea is to adjust the desired rate up/down in this method
- * based on whether we are running too slow or too fast.  Then, calculate
- * how many milliseconds to wait for the next packet to achieve this new
- * rate.
- */
-long Curl_sleep_time(curl_off_t rate_bps, curl_off_t cur_rate_bps,
-                             int pkt_size)
-{
-  curl_off_t min_sleep = 0;
-  curl_off_t rv = 0;
-
-  if(rate_bps == 0)
-    return 0;
-
-  /* If running faster than about .1% of the desired speed, slow
-   * us down a bit.  Use shift instead of division as the 0.1%
-   * cutoff is arbitrary anyway.
-   */
-  if(cur_rate_bps > (rate_bps + (rate_bps >> 10))) {
-    /* running too fast, decrease target rate by 1/64th of rate */
-    rate_bps -= rate_bps >> 6;
-    min_sleep = 1;
-  }
-  else if(cur_rate_bps < (rate_bps - (rate_bps >> 10))) {
-    /* running too slow, increase target rate by 1/64th of rate */
-    rate_bps += rate_bps >> 6;
-  }
-
-  /* Determine number of milliseconds to wait until we do
-   * the next packet at the adjusted rate.  We should wait
-   * longer when using larger packets, for instance.
-   */
-  rv = ((curl_off_t)(pkt_size * 1000) / rate_bps);
-
-  /* Catch rounding errors and always slow down at least 1ms if
-   * we are running too fast.
-   */
-  if(rv < min_sleep)
-    rv = min_sleep;
-
-  /* Bound value to fit in 'long' on 32-bit platform.  That's
-   * plenty long enough anyway!
-   */
-  if(rv > 0x7fffffff)
-    rv = 0x7fffffff;
-
-  return (long)rv;
-}
-
 /* Curl_init_CONNECT() gets called each time the handle switches to CONNECT
    which means this gets called once for each subsequent redirect etc */
 void Curl_init_CONNECT(struct Curl_easy *data)
@@ -1875,13 +1843,12 @@ CURLcode Curl_retry_request(struct connectdata *conn,
     return CURLE_OK;
 
   if((data->req.bytecount + data->req.headerbytecount == 0) &&
-      conn->bits.reuse &&
-      !data->set.opt_no_body &&
-      (data->set.rtspreq != RTSPREQ_RECEIVE)) {
-    /* We got no data, we attempted to re-use a connection and yet we want a
-       "body". This might happen if the connection was left alive when we were
-       done using it before, but that was closed when we wanted to read from
-       it again. Bad luck. Retry the same request on a fresh connect! */
+     conn->bits.reuse &&
+     (data->set.rtspreq != RTSPREQ_RECEIVE)) {
+    /* We didn't get a single byte when we attempted to re-use a
+       connection. This might happen if the connection was left alive when we
+       were done using it before, but that was closed when we wanted to use it
+       again. Bad luck. Retry the same request on a fresh connect! */
     infof(conn->data, "Connection died, retrying a fresh connect\n");
     *url = strdup(conn->data->change.url);
     if(!*url)
diff --git a/Utilities/cmcurl/lib/transfer.h b/Utilities/cmcurl/lib/transfer.h
index 0e253e3..5189672 100644
--- a/Utilities/cmcurl/lib/transfer.h
+++ b/Utilities/cmcurl/lib/transfer.h
@@ -40,10 +40,9 @@ typedef enum {
 
 CURLcode Curl_follow(struct Curl_easy *data, char *newurl,
                      followtype type);
-
-
 CURLcode Curl_readwrite(struct connectdata *conn,
-                        struct Curl_easy *data, bool *done);
+                        struct Curl_easy *data, bool *done,
+                        bool *comeback);
 int Curl_single_getsock(const struct connectdata *conn,
                         curl_socket_t *socks,
                         int numsocks);
@@ -65,8 +64,5 @@ Curl_setup_transfer (struct connectdata *data,
                curl_off_t *writecountp /* return number of bytes written */
 );
 
-long Curl_sleep_time(curl_off_t rate_bps, curl_off_t cur_rate_bps,
-                     int pkt_size);
-
 #endif /* HEADER_CURL_TRANSFER_H */
 
diff --git a/Utilities/cmcurl/lib/url.c b/Utilities/cmcurl/lib/url.c
index e547e5c..b997f41 100644
--- a/Utilities/cmcurl/lib/url.c
+++ b/Utilities/cmcurl/lib/url.c
@@ -59,24 +59,13 @@
 #include <limits.h>
 #endif
 
-#ifdef USE_LIBIDN
-#include <idna.h>
-#include <tld.h>
-#include <stringprep.h>
-#ifdef HAVE_IDN_FREE_H
-#include <idn-free.h>
-#else
-/* prototype from idn-free.h, not provided by libidn 0.4.5's make install! */
-void idn_free (void *ptr);
-#endif
-#ifndef HAVE_IDN_FREE
-/* if idn_free() was not found in this version of libidn use free() instead */
-#define idn_free(x) (free)(x)
-#endif
+#ifdef USE_LIBIDN2
+#include <idn2.h>
+
 #elif defined(USE_WIN32_IDN)
 /* prototype for curl_win32_idn_to_ascii() */
 bool curl_win32_idn_to_ascii(const char *in, char **out);
-#endif  /* USE_LIBIDN */
+#endif  /* USE_LIBIDN2 */
 
 #include "urldata.h"
 #include "netrc.h"
@@ -88,7 +77,7 @@ bool curl_win32_idn_to_ascii(const char *in, char **out);
 #include "sendf.h"
 #include "progress.h"
 #include "cookie.h"
-#include "strequal.h"
+#include "strcase.h"
 #include "strerror.h"
 #include "escape.h"
 #include "strtok.h"
@@ -100,7 +89,6 @@ bool curl_win32_idn_to_ascii(const char *in, char **out);
 #include "multiif.h"
 #include "easyif.h"
 #include "speedcheck.h"
-#include "rawstr.h"
 #include "warnless.h"
 #include "non-ascii.h"
 #include "inet_pton.h"
@@ -405,7 +393,7 @@ CURLcode Curl_close(struct Curl_easy *data)
   if(!data)
     return CURLE_OK;
 
-  Curl_expire(data, 0); /* shut off timers */
+  Curl_expire_clear(data); /* shut off timers */
 
   m = data->multi;
 
@@ -602,6 +590,7 @@ CURLcode Curl_init_userdefined(struct UserDefined *set)
   set->tcp_keepintvl = 60;
   set->tcp_keepidle = 60;
   set->tcp_fastopen = FALSE;
+  set->tcp_nodelay = TRUE;
 
   set->ssl_enable_npn = TRUE;
   set->ssl_enable_alpn = TRUE;
@@ -781,6 +770,10 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
      */
     data->set.http_fail_on_error = (0 != va_arg(param, long)) ? TRUE : FALSE;
     break;
+  case CURLOPT_KEEP_SENDING_ON_ERROR:
+    data->set.http_keep_sending_on_error = (0 != va_arg(param, long)) ?
+                                           TRUE : FALSE;
+    break;
   case CURLOPT_UPLOAD:
   case CURLOPT_PUT:
     /*
@@ -1225,23 +1218,23 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
     if(argptr == NULL)
       break;
 
-    if(Curl_raw_equal(argptr, "ALL")) {
+    if(strcasecompare(argptr, "ALL")) {
       /* clear all cookies */
       Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
       Curl_cookie_clearall(data->cookies);
       Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
     }
-    else if(Curl_raw_equal(argptr, "SESS")) {
+    else if(strcasecompare(argptr, "SESS")) {
       /* clear session cookies */
       Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
       Curl_cookie_clearsess(data->cookies);
       Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
     }
-    else if(Curl_raw_equal(argptr, "FLUSH")) {
+    else if(strcasecompare(argptr, "FLUSH")) {
       /* flush cookies to file, takes care of the locking */
       Curl_flush_cookies(data, 0);
     }
-    else if(Curl_raw_equal(argptr, "RELOAD")) {
+    else if(strcasecompare(argptr, "RELOAD")) {
       /* reload cookies from file */
       Curl_cookie_loadfiles(data);
       break;
@@ -2614,7 +2607,7 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
       data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
     break;
   case CURLOPT_TLSAUTH_TYPE:
-    if(strnequal((char *)va_arg(param, char *), "SRP", strlen("SRP")))
+    if(strncasecompare((char *)va_arg(param, char *), "SRP", strlen("SRP")))
       data->set.ssl.authtype = CURL_TLSAUTH_SRP;
     else
       data->set.ssl.authtype = CURL_TLSAUTH_NONE;
@@ -2829,6 +2822,17 @@ CURLcode Curl_disconnect(struct connectdata *conn, bool dead_connection)
     return CURLE_OK;
   }
 
+  /*
+   * If this connection isn't marked to force-close, leave it open if there
+   * are other users of it
+   */
+  if(!conn->bits.close &&
+     (conn->send_pipe->size + conn->recv_pipe->size)) {
+    DEBUGF(infof(data, "Curl_disconnect, usecounter: %d\n",
+                 conn->send_pipe->size + conn->recv_pipe->size));
+    return CURLE_OK;
+  }
+
   if(conn->dns_entry != NULL) {
     Curl_resolv_unlock(data, conn->dns_entry);
     conn->dns_entry = NULL;
@@ -2876,7 +2880,7 @@ static bool SocketIsDead(curl_socket_t sock)
   int sval;
   bool ret_val = TRUE;
 
-  sval = Curl_socket_ready(sock, CURL_SOCKET_BAD, 0);
+  sval = SOCKET_READABLE(sock, 0);
   if(sval == 0)
     /* timeout */
     ret_val = FALSE;
@@ -2892,7 +2896,8 @@ static bool IsPipeliningPossible(const struct Curl_easy *handle,
                                  const struct connectdata *conn)
 {
   /* If a HTTP protocol and pipelining is enabled */
-  if(conn->handler->protocol & PROTO_FAMILY_HTTP) {
+  if((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
+     (!conn->bits.protoconnstart || !conn->bits.close)) {
 
     if(Curl_pipeline_wanted(handle->multi, CURLPIPE_HTTP1) &&
        (handle->set.httpversion != CURL_HTTP_VERSION_1_0) &&
@@ -3267,6 +3272,8 @@ ConnectionExists(struct Curl_easy *data,
       pipeLen = check->send_pipe->size + check->recv_pipe->size;
 
       if(canPipeline) {
+        if(check->bits.protoconnstart && check->bits.close)
+          continue;
 
         if(!check->bits.multiplex) {
           /* If not multiplexing, make sure the pipe has only GET requests */
@@ -3341,7 +3348,7 @@ ConnectionExists(struct Curl_easy *data,
          (needle->proxytype != check->proxytype ||
           needle->bits.httpproxy != check->bits.httpproxy ||
           needle->bits.tunnel_proxy != check->bits.tunnel_proxy ||
-          !Curl_raw_equal(needle->proxy.name, check->proxy.name) ||
+          !strcasecompare(needle->proxy.name, check->proxy.name) ||
           needle->port != check->port))
         /* don't mix connections that use different proxies */
         continue;
@@ -3384,8 +3391,8 @@ ConnectionExists(struct Curl_easy *data,
       if(!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) {
         /* This protocol requires credentials per connection,
            so verify that we're using the same name and password as well */
-        if(!strequal(needle->user, check->user) ||
-           !strequal(needle->passwd, check->passwd)) {
+        if(strcmp(needle->user, check->user) ||
+           strcmp(needle->passwd, check->passwd)) {
           /* one of them was different */
           continue;
         }
@@ -3396,14 +3403,14 @@ ConnectionExists(struct Curl_easy *data,
         /* The requested connection does not use a HTTP proxy or it uses SSL or
            it is a non-SSL protocol tunneled over the same HTTP proxy name and
            port number */
-        if((Curl_raw_equal(needle->handler->scheme, check->handler->scheme) ||
+        if((strcasecompare(needle->handler->scheme, check->handler->scheme) ||
             (get_protocol_family(check->handler->protocol) ==
              needle->handler->protocol && check->tls_upgraded)) &&
-           (!needle->bits.conn_to_host || Curl_raw_equal(
+           (!needle->bits.conn_to_host || strcasecompare(
             needle->conn_to_host.name, check->conn_to_host.name)) &&
            (!needle->bits.conn_to_port ||
              needle->conn_to_port == check->conn_to_port) &&
-           Curl_raw_equal(needle->host.name, check->host.name) &&
+           strcasecompare(needle->host.name, check->host.name) &&
            needle->remote_port == check->remote_port) {
           /* The schemes match or the the protocol family is the same and the
              previous connection was TLS upgraded, and the hostname and host
@@ -3445,8 +3452,8 @@ ConnectionExists(struct Curl_easy *data,
            possible. (Especially we must not reuse the same connection if
            partway through a handshake!) */
         if(wantNTLMhttp) {
-          if(!strequal(needle->user, check->user) ||
-             !strequal(needle->passwd, check->passwd))
+          if(strcmp(needle->user, check->user) ||
+             strcmp(needle->passwd, check->passwd))
             continue;
         }
         else if(check->ntlm.state != NTLMSTATE_NONE) {
@@ -3460,8 +3467,8 @@ ConnectionExists(struct Curl_easy *data,
           if(!check->proxyuser || !check->proxypasswd)
             continue;
 
-          if(!strequal(needle->proxyuser, check->proxyuser) ||
-             !strequal(needle->proxypasswd, check->proxypasswd))
+          if(strcmp(needle->proxyuser, check->proxyuser) ||
+             strcmp(needle->proxypasswd, check->proxypasswd))
             continue;
         }
         else if(check->proxyntlm.state != NTLMSTATE_NONE) {
@@ -3752,58 +3759,15 @@ static bool is_ASCII_name(const char *hostname)
   return TRUE;
 }
 
-#ifdef USE_LIBIDN
-/*
- * Check if characters in hostname is allowed in Top Level Domain.
- */
-static bool tld_check_name(struct Curl_easy *data,
-                           const char *ace_hostname)
-{
-  size_t err_pos;
-  char *uc_name = NULL;
-  int rc;
-#ifndef CURL_DISABLE_VERBOSE_STRINGS
-  const char *tld_errmsg = "<no msg>";
-#else
-  (void)data;
-#endif
-
-  /* Convert (and downcase) ACE-name back into locale's character set */
-  rc = idna_to_unicode_lzlz(ace_hostname, &uc_name, 0);
-  if(rc != IDNA_SUCCESS)
-    return FALSE;
-
-  /* Warning: err_pos receives "the decoded character offset rather than the
-     byte position in the string." And as of libidn 1.32 that character offset
-     is for UTF-8, even if the passed in string is another locale. */
-  rc = tld_check_lz(uc_name, &err_pos, NULL);
-#ifndef CURL_DISABLE_VERBOSE_STRINGS
-#ifdef HAVE_TLD_STRERROR
-  if(rc != TLD_SUCCESS)
-    tld_errmsg = tld_strerror((Tld_rc)rc);
-#endif
-  if(rc != TLD_SUCCESS)
-    infof(data, "WARNING: TLD check for %s failed; %s\n",
-          uc_name, tld_errmsg);
-#endif /* CURL_DISABLE_VERBOSE_STRINGS */
-  if(uc_name)
-     idn_free(uc_name);
-  if(rc != TLD_SUCCESS)
-    return FALSE;
-
-  return TRUE;
-}
-#endif
-
 /*
  * Perform any necessary IDN conversion of hostname
  */
-static void fix_hostname(struct Curl_easy *data,
-                         struct connectdata *conn, struct hostname *host)
+static void fix_hostname(struct connectdata *conn, struct hostname *host)
 {
   size_t len;
+  struct Curl_easy *data = conn->data;
 
-#ifndef USE_LIBIDN
+#ifndef USE_LIBIDN2
   (void)data;
   (void)conn;
 #elif defined(CURL_DISABLE_VERBOSE_STRINGS)
@@ -3821,25 +3785,18 @@ static void fix_hostname(struct Curl_easy *data,
 
   /* Check name for non-ASCII and convert hostname to ACE form if we can */
   if(!is_ASCII_name(host->name)) {
-#ifdef USE_LIBIDN
-    if(stringprep_check_version(LIBIDN_REQUIRED_VERSION)) {
+#ifdef USE_LIBIDN2
+    if(idn2_check_version(IDN2_VERSION)) {
       char *ace_hostname = NULL;
-
-      int rc = idna_to_ascii_lz(host->name, &ace_hostname, 0);
-      infof(data, "Input domain encoded as `%s'\n",
-            stringprep_locale_charset());
-      if(rc == IDNA_SUCCESS) {
-        /* tld_check_name() displays a warning if the host name contains
-           "illegal" characters for this TLD */
-        (void)tld_check_name(data, ace_hostname);
-
-        host->encalloc = ace_hostname;
+      int rc = idn2_lookup_ul((const char *)host->name, &ace_hostname, 0);
+      if(rc == IDN2_OK) {
+        host->encalloc = (char *)ace_hostname;
         /* change the name pointer to point to the encoded hostname */
         host->name = host->encalloc;
       }
       else
         infof(data, "Failed to convert %s to ACE; %s\n", host->name,
-              Curl_idn_strerror(conn, rc));
+              idn2_strerror(rc));
     }
 #elif defined(USE_WIN32_IDN)
     char *ace_hostname = NULL;
@@ -3862,9 +3819,9 @@ static void fix_hostname(struct Curl_easy *data,
  */
 static void free_fixed_hostname(struct hostname *host)
 {
-#if defined(USE_LIBIDN)
+#if defined(USE_LIBIDN2)
   if(host->encalloc) {
-    idn_free(host->encalloc); /* must be freed with idn_free() since this was
+    idn2_free(host->encalloc); /* must be freed with idn2_free() since this was
                                  allocated by libidn */
     host->encalloc = NULL;
   }
@@ -4022,7 +3979,7 @@ static CURLcode findprotocol(struct Curl_easy *data,
      variables based on the URL. Now that the handler may be changed later
      when the protocol specific setup function is called. */
   for(pp = protocols; (p = *pp) != NULL; pp++) {
-    if(Curl_raw_equal(p->scheme, protostr)) {
+    if(strcasecompare(p->scheme, protostr)) {
       /* Protocol found in table. Check if allowed */
       if(!(data->set.allowed_protocols & p->protocol))
         /* nope, get out */
@@ -4091,7 +4048,7 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
    ************************************************************/
   if((2 == sscanf(data->change.url, "%15[^:]:%[^\n]",
                   protobuf, path)) &&
-     Curl_raw_equal(protobuf, "file")) {
+     strcasecompare(protobuf, "file")) {
     if(path[0] == '/' && path[1] == '/') {
       /* Allow omitted hostname (e.g. file:/<path>).  This is not strictly
        * speaking a valid file: URL by RFC 1738, but treating file:/<path> as
@@ -4145,7 +4102,7 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
     path[0]=0;
 
     rc = sscanf(data->change.url,
-                "%15[^\n:]:%3[/]%[^\n/?]%[^\n]",
+                "%15[^\n:]:%3[/]%[^\n/?#]%[^\n]",
                 protobuf, slashbuf, conn->host.name, path);
     if(2 == rc) {
       failf(data, "Bad URL");
@@ -4157,7 +4114,7 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
        * The URL was badly formatted, let's try the browser-style _without_
        * protocol specified like 'http://'.
        */
-      rc = sscanf(data->change.url, "%[^\n/?]%[^\n]", conn->host.name, path);
+      rc = sscanf(data->change.url, "%[^\n/?#]%[^\n]", conn->host.name, path);
       if(1 > rc) {
         /*
          * We couldn't even get this format.
@@ -4262,10 +4219,10 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
   }
 
   /* If the URL is malformatted (missing a '/' after hostname before path) we
-   * insert a slash here. The only letter except '/' we accept to start a path
-   * is '?'.
+   * insert a slash here. The only letters except '/' that can start a path is
+   * '?' and '#' - as controlled by the two sscanf() patterns above.
    */
-  if(path[0] == '?') {
+  if(path[0] != '/') {
     /* We need this function to deal with overlapping memory areas. We know
        that the memory area 'path' points to is 'urllen' bytes big and that
        is bigger than the path. Use +1 to move the zero byte too. */
@@ -4531,7 +4488,7 @@ static bool check_noproxy(const char* name, const char* no_proxy)
   char *endptr;
 
   if(no_proxy && no_proxy[0]) {
-    if(Curl_raw_equal("*", no_proxy)) {
+    if(strcasecompare("*", no_proxy)) {
       return TRUE;
     }
 
@@ -4569,7 +4526,7 @@ static bool check_noproxy(const char* name, const char* no_proxy)
       if((tok_end - tok_start) <= namelen) {
         /* Match the last part of the name to the domain we are checking. */
         const char *checkn = name + namelen - (tok_end - tok_start);
-        if(Curl_raw_nequal(no_proxy + tok_start, checkn,
+        if(strncasecompare(no_proxy + tok_start, checkn,
                            tok_end - tok_start)) {
           if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
             /* We either have an exact match, or the previous character is a .
@@ -4648,7 +4605,7 @@ static char *detect_proxy(struct connectdata *conn)
      * This can cause 'internal' http/ftp requests to be
      * arbitrarily redirected by any external attacker.
      */
-    if(!prox && !Curl_raw_equal("http_proxy", proxy_env)) {
+    if(!prox && !strcasecompare("http_proxy", proxy_env)) {
       /* There was no lowercase variable, try the uppercase version: */
       Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
       prox=curl_getenv(proxy_env);
@@ -4705,7 +4662,13 @@ static CURLcode parse_proxy(struct Curl_easy *data,
       conn->proxytype = CURLPROXY_SOCKS4A;
     else if(checkprefix("socks4", proxy) || checkprefix("socks", proxy))
       conn->proxytype = CURLPROXY_SOCKS4;
-    /* Any other xxx:// : change to http proxy */
+    else if(checkprefix("http:", proxy))
+      ; /* leave it as HTTP or HTTP/1.0 */
+    else {
+      /* Any other xxx:// reject! */
+      failf(data, "Unsupported proxy scheme for \'%s\'", proxy);
+      return CURLE_COULDNT_CONNECT;
+    }
   }
   else
     proxyptr = proxy; /* No xxx:// head: It's a HTTP proxy */
@@ -4725,21 +4688,24 @@ static CURLcode parse_proxy(struct Curl_easy *data,
          them. */
       Curl_safefree(conn->proxyuser);
       if(proxyuser && strlen(proxyuser) < MAX_CURL_USER_LENGTH)
-        conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
-      else
+        result = Curl_urldecode(data, proxyuser, 0, &conn->proxyuser, NULL,
+                                FALSE);
+      else {
         conn->proxyuser = strdup("");
+        if(!conn->proxyuser)
+          result = CURLE_OUT_OF_MEMORY;
+      }
 
-      if(!conn->proxyuser)
-        result = CURLE_OUT_OF_MEMORY;
-      else {
+      if(!result) {
         Curl_safefree(conn->proxypasswd);
         if(proxypasswd && strlen(proxypasswd) < MAX_CURL_PASSWORD_LENGTH)
-          conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
-        else
+          result = Curl_urldecode(data, proxypasswd, 0,
+                                  &conn->proxypasswd, NULL, FALSE);
+        else {
           conn->proxypasswd = strdup("");
-
-        if(!conn->proxypasswd)
-          result = CURLE_OUT_OF_MEMORY;
+          if(!conn->proxypasswd)
+            result = CURLE_OUT_OF_MEMORY;
+        }
       }
 
       if(!result) {
@@ -4846,6 +4812,7 @@ static CURLcode parse_proxy_auth(struct Curl_easy *data,
 {
   char proxyuser[MAX_CURL_USER_LENGTH]="";
   char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
+  CURLcode result;
 
   if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
     strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
@@ -4858,15 +4825,11 @@ static CURLcode parse_proxy_auth(struct Curl_easy *data,
     proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
   }
 
-  conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
-  if(!conn->proxyuser)
-    return CURLE_OUT_OF_MEMORY;
-
-  conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
-  if(!conn->proxypasswd)
-    return CURLE_OUT_OF_MEMORY;
-
-  return CURLE_OK;
+  result = Curl_urldecode(data, proxyuser, 0, &conn->proxyuser, NULL, FALSE);
+  if(!result)
+    result = Curl_urldecode(data, proxypasswd, 0, &conn->proxypasswd, NULL,
+                            FALSE);
+  return result;
 }
 #endif /* CURL_DISABLE_PROXY */
 
@@ -4940,9 +4903,8 @@ static CURLcode parse_url_login(struct Curl_easy *data,
     conn->bits.user_passwd = TRUE; /* enable user+password */
 
     /* Decode the user */
-    newname = curl_easy_unescape(data, userp, 0, NULL);
-    if(!newname) {
-      result = CURLE_OUT_OF_MEMORY;
+    result = Curl_urldecode(data, userp, 0, &newname, NULL, FALSE);
+    if(result) {
       goto out;
     }
 
@@ -4952,9 +4914,9 @@ static CURLcode parse_url_login(struct Curl_easy *data,
 
   if(passwdp) {
     /* We have a password in the URL so decode it */
-    char *newpasswd = curl_easy_unescape(data, passwdp, 0, NULL);
-    if(!newpasswd) {
-      result = CURLE_OUT_OF_MEMORY;
+    char *newpasswd;
+    result = Curl_urldecode(data, passwdp, 0, &newpasswd, NULL, FALSE);
+    if(result) {
       goto out;
     }
 
@@ -4964,9 +4926,9 @@ static CURLcode parse_url_login(struct Curl_easy *data,
 
   if(optionsp) {
     /* We have an options list in the URL so decode it */
-    char *newoptions = curl_easy_unescape(data, optionsp, 0, NULL);
-    if(!newoptions) {
-      result = CURLE_OUT_OF_MEMORY;
+    char *newoptions;
+    result = Curl_urldecode(data, optionsp, 0, &newoptions, NULL, FALSE);
+    if(result) {
       goto out;
     }
 
@@ -5457,7 +5419,8 @@ static CURLcode parse_connect_to_string(struct Curl_easy *data,
     if(!hostname_to_match)
       return CURLE_OUT_OF_MEMORY;
     hostname_to_match_len = strlen(hostname_to_match);
-    host_match = curl_strnequal(ptr, hostname_to_match, hostname_to_match_len);
+    host_match = strncasecompare(ptr, hostname_to_match,
+                                 hostname_to_match_len);
     free(hostname_to_match);
     ptr += hostname_to_match_len;
 
@@ -6021,18 +5984,18 @@ static CURLcode create_conn(struct Curl_easy *data,
   /*************************************************************
    * IDN-fix the hostnames
    *************************************************************/
-  fix_hostname(data, conn, &conn->host);
+  fix_hostname(conn, &conn->host);
   if(conn->bits.conn_to_host)
-    fix_hostname(data, conn, &conn->conn_to_host);
+    fix_hostname(conn, &conn->conn_to_host);
   if(conn->proxy.name && *conn->proxy.name)
-    fix_hostname(data, conn, &conn->proxy);
+    fix_hostname(conn, &conn->proxy);
 
   /*************************************************************
    * Check whether the host and the "connect to host" are equal.
    * Do this after the hostnames have been IDN-fixed .
    *************************************************************/
   if(conn->bits.conn_to_host &&
-      Curl_raw_equal(conn->conn_to_host.name, conn->host.name)) {
+     strcasecompare(conn->conn_to_host.name, conn->host.name)) {
     conn->bits.conn_to_host = FALSE;
   }
 
diff --git a/Utilities/cmcurl/lib/urldata.h b/Utilities/cmcurl/lib/urldata.h
index 3cf7ed9..7c7bf1b 100644
--- a/Utilities/cmcurl/lib/urldata.h
+++ b/Utilities/cmcurl/lib/urldata.h
@@ -330,6 +330,7 @@ struct ssl_connect_data {
   CURLcode recv_unrecoverable_err; /* schannel_recv had an unrecoverable err */
   bool recv_sspi_close_notify; /* true if connection closed by close_notify */
   bool recv_connection_closed; /* true if connection closed, regardless how */
+  bool use_alpn; /* true if ALPN is used for this connection */
 #elif defined(USE_DARWINSSL)
   SSLContextRef ssl_ctx;
   curl_socket_t ssl_sockfd;
@@ -373,6 +374,7 @@ struct ssl_config_data {
 struct curl_ssl_session {
   char *name;       /* host name for which this ID was used */
   char *conn_to_host; /* host name for the connection (may be NULL) */
+  const char *scheme; /* protocol scheme used */
   void *sessionid;  /* as returned from the SSL layer */
   size_t idsize;    /* if known, otherwise 0 */
   long age;         /* just a number, the higher the more recent */
@@ -817,6 +819,7 @@ struct Curl_handler {
 #define PROTOPT_CREDSPERREQUEST (1<<7) /* requires login credentials per
                                           request instead of per connection */
 #define PROTOPT_ALPN_NPN (1<<8) /* set ALPN and/or NPN for this */
+#define PROTOPT_STREAM (1<<9) /* a protocol with individual logical streams */
 
 /* return the count of bytes sent, or -1 on error */
 typedef ssize_t (Curl_send)(struct connectdata *conn, /* connection data */
@@ -1102,9 +1105,10 @@ struct connectdata {
 
 /*
  * Struct to keep statistical and informational data.
+ * All variables in this struct must be reset in Curl_initinfo().
  */
 struct PureInfo {
-  int httpcode;  /* Recent HTTP, FTP, or RTSP response code */
+  int httpcode;  /* Recent HTTP, FTP, RTSP or SMTP response code */
   int httpproxycode; /* response code from proxy when received separate */
   int httpversion; /* the http version number X.Y = X*10+Y */
   long filetime; /* If requested, this is might get set. Set to -1 if the time
@@ -1171,6 +1175,14 @@ struct Progress {
   struct timeval t_startsingle;
   struct timeval t_startop;
   struct timeval t_acceptdata;
+
+  /* upload speed limit */
+  struct timeval ul_limit_start;
+  curl_off_t ul_limit_size;
+  /* download speed limit */
+  struct timeval dl_limit_start;
+  curl_off_t dl_limit_size;
+
 #define CURR_TIME (5+1) /* 6 entries for 5 seconds */
 
   curl_off_t speeder[ CURR_TIME ];
@@ -1600,6 +1612,7 @@ struct UserDefined {
   bool ftp_use_port;     /* use the FTP PORT command */
   bool hide_progress;    /* don't use the progress meter */
   bool http_fail_on_error;  /* fail on HTTP error codes >= 400 */
+  bool http_keep_sending_on_error; /* for HTTP status codes >= 300 */
   bool http_follow_location; /* follow HTTP redirects */
   bool http_transfer_encoding; /* request compressed HTTP transfer-encoding */
   bool http_disable_hostname_check_before_authentication;
diff --git a/Utilities/cmcurl/lib/vauth/cleartext.c b/Utilities/cmcurl/lib/vauth/cleartext.c
index 4e906bc..6df419a 100644
--- a/Utilities/cmcurl/lib/vauth/cleartext.c
+++ b/Utilities/cmcurl/lib/vauth/cleartext.c
@@ -33,8 +33,6 @@
 #include "curl_md5.h"
 #include "warnless.h"
 #include "strtok.h"
-#include "strequal.h"
-#include "rawstr.h"
 #include "sendf.h"
 #include "curl_printf.h"
 
diff --git a/Utilities/cmcurl/lib/vauth/digest.c b/Utilities/cmcurl/lib/vauth/digest.c
index 26ea7b5..0a11a30 100644
--- a/Utilities/cmcurl/lib/vauth/digest.c
+++ b/Utilities/cmcurl/lib/vauth/digest.c
@@ -37,7 +37,7 @@
 #include "vtls/vtls.h"
 #include "warnless.h"
 #include "strtok.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "non-ascii.h" /* included for Curl_convert_... prototypes */
 #include "curl_printf.h"
 
@@ -217,11 +217,11 @@ static CURLcode auth_digest_get_qop_values(const char *options, int *value)
 
   token = strtok_r(tmp, ",", &tok_buf);
   while(token != NULL) {
-    if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH))
+    if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH))
       *value |= DIGEST_QOP_VALUE_AUTH;
-    else if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH_INT))
+    else if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH_INT))
       *value |= DIGEST_QOP_VALUE_AUTH_INT;
-    else if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH_CONF))
+    else if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH_CONF))
       *value |= DIGEST_QOP_VALUE_AUTH_CONF;
 
     token = strtok_r(NULL, ",", &tok_buf);
@@ -306,6 +306,20 @@ static CURLcode auth_decode_digest_md5_message(const char *chlg64,
 }
 
 /*
+ * Curl_auth_is_digest_supported()
+ *
+ * This is used to evaluate if DIGEST is supported.
+ *
+ * Parameters: None
+ *
+ * Returns TRUE as DIGEST as handled by libcurl.
+ */
+bool Curl_auth_is_digest_supported(void)
+{
+  return TRUE;
+}
+
+/*
  * Curl_auth_create_digest_md5_message()
  *
  * This is used to generate an already encoded DIGEST-MD5 response message
@@ -524,31 +538,31 @@ CURLcode Curl_auth_decode_digest_http_message(const char *chlg,
 
     /* Extract a value=content pair */
     if(Curl_auth_digest_get_pair(chlg, value, content, &chlg)) {
-      if(Curl_raw_equal(value, "nonce")) {
+      if(strcasecompare(value, "nonce")) {
         free(digest->nonce);
         digest->nonce = strdup(content);
         if(!digest->nonce)
           return CURLE_OUT_OF_MEMORY;
       }
-      else if(Curl_raw_equal(value, "stale")) {
-        if(Curl_raw_equal(content, "true")) {
+      else if(strcasecompare(value, "stale")) {
+        if(strcasecompare(content, "true")) {
           digest->stale = TRUE;
           digest->nc = 1; /* we make a new nonce now */
         }
       }
-      else if(Curl_raw_equal(value, "realm")) {
+      else if(strcasecompare(value, "realm")) {
         free(digest->realm);
         digest->realm = strdup(content);
         if(!digest->realm)
           return CURLE_OUT_OF_MEMORY;
       }
-      else if(Curl_raw_equal(value, "opaque")) {
+      else if(strcasecompare(value, "opaque")) {
         free(digest->opaque);
         digest->opaque = strdup(content);
         if(!digest->opaque)
           return CURLE_OUT_OF_MEMORY;
       }
-      else if(Curl_raw_equal(value, "qop")) {
+      else if(strcasecompare(value, "qop")) {
         char *tok_buf;
         /* Tokenize the list and choose auth if possible, use a temporary
            clone of the buffer since strtok_r() ruins it */
@@ -558,10 +572,10 @@ CURLcode Curl_auth_decode_digest_http_message(const char *chlg,
 
         token = strtok_r(tmp, ",", &tok_buf);
         while(token != NULL) {
-          if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH)) {
+          if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH)) {
             foundAuth = TRUE;
           }
-          else if(Curl_raw_equal(token, DIGEST_QOP_VALUE_STRING_AUTH_INT)) {
+          else if(strcasecompare(token, DIGEST_QOP_VALUE_STRING_AUTH_INT)) {
             foundAuthInt = TRUE;
           }
           token = strtok_r(NULL, ",", &tok_buf);
@@ -583,15 +597,15 @@ CURLcode Curl_auth_decode_digest_http_message(const char *chlg,
             return CURLE_OUT_OF_MEMORY;
         }
       }
-      else if(Curl_raw_equal(value, "algorithm")) {
+      else if(strcasecompare(value, "algorithm")) {
         free(digest->algorithm);
         digest->algorithm = strdup(content);
         if(!digest->algorithm)
           return CURLE_OUT_OF_MEMORY;
 
-        if(Curl_raw_equal(content, "MD5-sess"))
+        if(strcasecompare(content, "MD5-sess"))
           digest->algo = CURLDIGESTALGO_MD5SESS;
-        else if(Curl_raw_equal(content, "MD5"))
+        else if(strcasecompare(content, "MD5"))
           digest->algo = CURLDIGESTALGO_MD5;
         else
           return CURLE_BAD_CONTENT_ENCODING;
@@ -730,7 +744,7 @@ CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data,
 
   md5this = (unsigned char *) aprintf("%s:%s", request, uripath);
 
-  if(digest->qop && Curl_raw_equal(digest->qop, "auth-int")) {
+  if(digest->qop && strcasecompare(digest->qop, "auth-int")) {
     /* We don't support auth-int for PUT or POST at the moment.
        TODO: replace md5 of empty string with entity-body for PUT/POST */
     unsigned char *md5this2 = (unsigned char *)
@@ -806,7 +820,7 @@ CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data,
                        digest->qop,
                        request_digest);
 
-    if(Curl_raw_equal(digest->qop, "auth"))
+    if(strcasecompare(digest->qop, "auth"))
       digest->nc++; /* The nc (from RFC) has to be a 8 hex digit number 0
                        padded which tells to the server how many times you are
                        using the same nonce in the qop=auth mode */
diff --git a/Utilities/cmcurl/lib/vauth/digest_sspi.c b/Utilities/cmcurl/lib/vauth/digest_sspi.c
index 6a7315e..29526fc 100644
--- a/Utilities/cmcurl/lib/vauth/digest_sspi.c
+++ b/Utilities/cmcurl/lib/vauth/digest_sspi.c
@@ -37,13 +37,34 @@
 #include "curl_multibyte.h"
 #include "sendf.h"
 #include "strdup.h"
-#include "rawstr.h"
+#include "strcase.h"
 
 /* The last #include files should be: */
 #include "curl_memory.h"
 #include "memdebug.h"
 
 /*
+* Curl_auth_is_digest_supported()
+*
+* This is used to evaluate if DIGEST is supported.
+*
+* Parameters: None
+*
+* Returns TRUE if DIGEST is supported by Windows SSPI.
+*/
+bool Curl_auth_is_digest_supported(void)
+{
+  PSecPkgInfo SecurityPackage;
+  SECURITY_STATUS status;
+
+  /* Query the security package for Digest */
+  status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_DIGEST),
+                                              &SecurityPackage);
+
+  return (status == SEC_E_OK ? TRUE : FALSE);
+}
+
+/*
  * Curl_auth_create_digest_md5_message()
  *
  * This is used to generate an already encoded DIGEST-MD5 response message
@@ -256,7 +277,7 @@ CURLcode Curl_override_sspi_http_realm(const char *chlg,
 
       /* Extract a value=content pair */
       if(Curl_auth_digest_get_pair(chlg, value, content, &chlg)) {
-        if(Curl_raw_equal(value, "realm")) {
+        if(strcasecompare(value, "realm")) {
 
           /* Setup identity's domain and length */
           domain.tchar_ptr = Curl_convert_UTF8_to_tchar((char *) content);
diff --git a/Utilities/cmcurl/lib/vauth/krb5_gssapi.c b/Utilities/cmcurl/lib/vauth/krb5_gssapi.c
index 31c8c7d..c754fae 100644
--- a/Utilities/cmcurl/lib/vauth/krb5_gssapi.c
+++ b/Utilities/cmcurl/lib/vauth/krb5_gssapi.c
@@ -42,6 +42,20 @@
 #include "memdebug.h"
 
 /*
+ * Curl_auth_is_gssapi_supported()
+ *
+ * This is used to evaluate if GSSAPI (Kerberos V5) is supported.
+ *
+ * Parameters: None
+ *
+ * Returns TRUE if Kerberos V5 is supported by the GSS-API library.
+ */
+bool Curl_auth_is_gssapi_supported(void)
+{
+  return TRUE;
+}
+
+/*
  * Curl_auth_create_gssapi_user_message()
  *
  * This is used to generate an already encoded GSSAPI (Kerberos V5) user token
diff --git a/Utilities/cmcurl/lib/vauth/krb5_sspi.c b/Utilities/cmcurl/lib/vauth/krb5_sspi.c
index 08774f6..151794e 100644
--- a/Utilities/cmcurl/lib/vauth/krb5_sspi.c
+++ b/Utilities/cmcurl/lib/vauth/krb5_sspi.c
@@ -40,6 +40,28 @@
 #include "memdebug.h"
 
 /*
+ * Curl_auth_is_gssapi_supported()
+ *
+ * This is used to evaluate if GSSAPI (Kerberos V5) is supported.
+ *
+ * Parameters: None
+ *
+ * Returns TRUE if Kerberos V5 is supported by Windows SSPI.
+ */
+bool Curl_auth_is_gssapi_supported(void)
+{
+  PSecPkgInfo SecurityPackage;
+  SECURITY_STATUS status;
+
+  /* Query the security package for Kerberos */
+  status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *)
+                                              TEXT(SP_NAME_KERBEROS),
+                                              &SecurityPackage);
+
+  return (status == SEC_E_OK ? TRUE : FALSE);
+}
+
+/*
  * Curl_auth_create_gssapi_user_message()
  *
  * This is used to generate an already encoded GSSAPI (Kerberos V5) user token
diff --git a/Utilities/cmcurl/lib/vauth/ntlm.c b/Utilities/cmcurl/lib/vauth/ntlm.c
index c85fe42..b484a01 100644
--- a/Utilities/cmcurl/lib/vauth/ntlm.c
+++ b/Utilities/cmcurl/lib/vauth/ntlm.c
@@ -217,6 +217,20 @@ static CURLcode ntlm_decode_type2_target(struct Curl_easy *data,
 */
 
 /*
+ * Curl_auth_is_ntlm_supported()
+ *
+ * This is used to evaluate if NTLM is supported.
+ *
+ * Parameters: None
+ *
+ * Returns TRUE as NTLM as handled by libcurl.
+ */
+bool Curl_auth_is_ntlm_supported(void)
+{
+  return TRUE;
+}
+
+/*
  * Curl_auth_decode_ntlm_type2_message()
  *
  * This is used to decode an already encoded NTLM type-2 message. The message
diff --git a/Utilities/cmcurl/lib/vauth/ntlm_sspi.c b/Utilities/cmcurl/lib/vauth/ntlm_sspi.c
index 982a9d3..c330517 100644
--- a/Utilities/cmcurl/lib/vauth/ntlm_sspi.c
+++ b/Utilities/cmcurl/lib/vauth/ntlm_sspi.c
@@ -38,6 +38,27 @@
 #include "memdebug.h"
 
 /*
+ * Curl_auth_is_ntlm_supported()
+ *
+ * This is used to evaluate if NTLM is supported.
+ *
+ * Parameters: None
+ *
+ * Returns TRUE if NTLM is supported by Windows SSPI.
+ */
+bool Curl_auth_is_ntlm_supported(void)
+{
+  PSecPkgInfo SecurityPackage;
+  SECURITY_STATUS status;
+
+  /* Query the security package for NTLM */
+  status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *) TEXT(SP_NAME_NTLM),
+                                              &SecurityPackage);
+
+  return (status == SEC_E_OK ? TRUE : FALSE);
+}
+
+/*
  * Curl_auth_create_ntlm_type1_message()
  *
  * This is used to generate an already encoded NTLM type-1 message ready for
diff --git a/Utilities/cmcurl/lib/vauth/spnego_gssapi.c b/Utilities/cmcurl/lib/vauth/spnego_gssapi.c
index b256ee6..8840db8 100644
--- a/Utilities/cmcurl/lib/vauth/spnego_gssapi.c
+++ b/Utilities/cmcurl/lib/vauth/spnego_gssapi.c
@@ -41,6 +41,20 @@
 #include "memdebug.h"
 
 /*
+ * Curl_auth_is_spnego_supported()
+ *
+ * This is used to evaluate if SPNEGO (Negotiate) is supported.
+ *
+ * Parameters: None
+ *
+ * Returns TRUE if Negotiate supported by the GSS-API library.
+ */
+bool Curl_auth_is_spnego_supported(void)
+{
+  return TRUE;
+}
+
+/*
  * Curl_auth_decode_spnego_message()
  *
  * This is used to decode an already encoded SPNEGO (Negotiate) challenge
diff --git a/Utilities/cmcurl/lib/vauth/spnego_sspi.c b/Utilities/cmcurl/lib/vauth/spnego_sspi.c
index b6176ec..672b43f 100644
--- a/Utilities/cmcurl/lib/vauth/spnego_sspi.c
+++ b/Utilities/cmcurl/lib/vauth/spnego_sspi.c
@@ -40,6 +40,28 @@
 #include "memdebug.h"
 
 /*
+ * Curl_auth_is_spnego_supported()
+ *
+ * This is used to evaluate if SPNEGO (Negotiate) is supported.
+ *
+ * Parameters: None
+ *
+ * Returns TRUE if Negotiate is supported by Windows SSPI.
+ */
+bool Curl_auth_is_spnego_supported(void)
+{
+  PSecPkgInfo SecurityPackage;
+  SECURITY_STATUS status;
+
+  /* Query the security package for Negotiate */
+  status = s_pSecFn->QuerySecurityPackageInfo((TCHAR *)
+                                              TEXT(SP_NAME_NEGOTIATE),
+                                              &SecurityPackage);
+
+  return (status == SEC_E_OK ? TRUE : FALSE);
+}
+
+/*
  * Curl_auth_decode_spnego_message()
  *
  * This is used to decode an already encoded SPNEGO (Negotiate) challenge
@@ -249,8 +271,10 @@ CURLcode Curl_auth_create_spnego_message(struct Curl_easy *data,
   if(result)
     return result;
 
-  if(!*outptr || !*outlen)
+  if(!*outptr || !*outlen) {
+    free(*outptr);
     return CURLE_REMOTE_ACCESS_DENIED;
+  }
 
   return CURLE_OK;
 }
diff --git a/Utilities/cmcurl/lib/vauth/vauth.c b/Utilities/cmcurl/lib/vauth/vauth.c
index 702e2d4..b995f34 100644
--- a/Utilities/cmcurl/lib/vauth/vauth.c
+++ b/Utilities/cmcurl/lib/vauth/vauth.c
@@ -104,3 +104,44 @@ TCHAR *Curl_auth_build_spn(const char *service, const char *host,
 }
 #endif /* USE_WINDOWS_SSPI */
 
+/*
+* Curl_auth_user_contains_domain()
+*
+* This is used to test if the specified user contains a Windows domain name as
+* follows:
+*
+* User\Domain (Down-level Logon Name)
+* User/Domain (curl Down-level format - for compatibility with existing code)
+* User at Domain (User Principal Name)
+*
+* Note: The user name may be empty when using a GSS-API library or Windows SSPI
+* as the user and domain are either obtained from the credientals cache when
+* using GSS-API or via the currently logged in user's credientals when using
+* Windows SSPI.
+*
+* Parameters:
+*
+* user  [in] - The user name.
+*
+* Returns TRUE on success; otherwise FALSE.
+*/
+bool Curl_auth_user_contains_domain(const char *user)
+{
+  bool valid = FALSE;
+
+  if(user && *user) {
+    /* Check we have a domain name or UPN present */
+    char *p = strpbrk(user, "\\/@");
+
+    valid = (p != NULL && p > user && p < user + strlen(user) - 1 ? TRUE :
+                                                                    FALSE);
+  }
+#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
+  else
+    /* User and domain are obtained from the GSS-API credientials cache or the
+       currently logged in user from Windows */
+    valid = TRUE;
+#endif
+
+  return valid;
+}
diff --git a/Utilities/cmcurl/lib/vauth/vauth.h b/Utilities/cmcurl/lib/vauth/vauth.h
index 38806ee..9d61228 100644
--- a/Utilities/cmcurl/lib/vauth/vauth.h
+++ b/Utilities/cmcurl/lib/vauth/vauth.h
@@ -55,6 +55,9 @@ TCHAR *Curl_auth_build_spn(const char *service, const char *host,
                            const char *realm);
 #endif
 
+/* This is used to test if the user contains a Windows domain name */
+bool Curl_auth_user_contains_domain(const char *user);
+
 /* This is used to generate a base64 encoded PLAIN cleartext message */
 CURLcode Curl_auth_create_plain_message(struct Curl_easy *data,
                                         const char *userp,
@@ -83,6 +86,9 @@ CURLcode Curl_auth_create_cram_md5_message(struct Curl_easy *data,
                                            const char *passwdp,
                                            char **outptr, size_t *outlen);
 
+/* This is used to evaluate if DIGEST is supported */
+bool Curl_auth_is_digest_supported(void);
+
 /* This is used to generate a base64 encoded DIGEST-MD5 response message */
 CURLcode Curl_auth_create_digest_md5_message(struct Curl_easy *data,
                                              const char *chlg64,
@@ -109,6 +115,9 @@ void Curl_auth_digest_cleanup(struct digestdata *digest);
 #endif /* !CURL_DISABLE_CRYPTO_AUTH */
 
 #if defined(USE_NTLM)
+/* This is used to evaluate if NTLM is supported */
+bool Curl_auth_is_ntlm_supported(void);
+
 /* This is used to generate a base64 encoded NTLM type-1 message */
 CURLcode Curl_auth_create_ntlm_type1_message(const char *userp,
                                              const char *passwdp,
@@ -140,6 +149,9 @@ CURLcode Curl_auth_create_oauth_bearer_message(struct Curl_easy *data,
                                                const char *bearer,
                                                char **outptr, size_t *outlen);
 #if defined(USE_KERBEROS5)
+/* This is used to evaluate if GSSAPI (Kerberos V5) is supported */
+bool Curl_auth_is_gssapi_supported(void);
+
 /* This is used to generate a base64 encoded GSSAPI (Kerberos V5) user token
    message */
 CURLcode Curl_auth_create_gssapi_user_message(struct Curl_easy *data,
@@ -165,6 +177,9 @@ void Curl_auth_gssapi_cleanup(struct kerberos5data *krb5);
 #endif /* USE_KERBEROS5 */
 
 #if defined(USE_SPNEGO)
+/* This is used to evaluate if SPNEGO (Negotiate) is supported */
+bool Curl_auth_is_spnego_supported(void);
+
 /* This is used to decode a base64 encoded SPNEGO (Negotiate) challenge
    message */
 CURLcode Curl_auth_decode_spnego_message(struct Curl_easy *data,
diff --git a/Utilities/cmcurl/lib/version.c b/Utilities/cmcurl/lib/version.c
index 1292445..a434a62 100644
--- a/Utilities/cmcurl/lib/version.c
+++ b/Utilities/cmcurl/lib/version.c
@@ -36,8 +36,8 @@
 #  include <ares.h>
 #endif
 
-#ifdef USE_LIBIDN
-#include <stringprep.h>
+#ifdef USE_LIBIDN2
+#include <idn2.h>
 #endif
 
 #ifdef USE_LIBPSL
@@ -111,9 +111,9 @@ char *curl_version(void)
   left -= len;
   ptr += len;
 #endif
-#ifdef USE_LIBIDN
-  if(stringprep_check_version(LIBIDN_REQUIRED_VERSION)) {
-    len = snprintf(ptr, left, " libidn/%s", stringprep_check_version(NULL));
+#ifdef USE_LIBIDN2
+  if(idn2_check_version(IDN2_VERSION)) {
+    len = snprintf(ptr, left, " libidn2/%s", idn2_check_version(NULL));
     left -= len;
     ptr += len;
   }
@@ -365,10 +365,10 @@ curl_version_info_data *curl_version_info(CURLversion stamp)
     version_info.ares_num = aresnum;
   }
 #endif
-#ifdef USE_LIBIDN
+#ifdef USE_LIBIDN2
   /* This returns a version string if we use the given version or later,
      otherwise it returns NULL */
-  version_info.libidn = stringprep_check_version(LIBIDN_REQUIRED_VERSION);
+  version_info.libidn = idn2_check_version(IDN2_VERSION);
   if(version_info.libidn)
     version_info.features |= CURL_VERSION_IDN;
 #elif defined(USE_WIN32_IDN)
diff --git a/Utilities/cmcurl/lib/vtls/axtls.c b/Utilities/cmcurl/lib/vtls/axtls.c
index b6c69ad..85b8bc4 100644
--- a/Utilities/cmcurl/lib/vtls/axtls.c
+++ b/Utilities/cmcurl/lib/vtls/axtls.c
@@ -579,8 +579,7 @@ int Curl_axtls_shutdown(struct connectdata *conn, int sockindex)
   */
 
   if(connssl->ssl) {
-    int what = Curl_socket_ready(conn->sock[sockindex],
-                                 CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
+    int what = SOCKET_READABLE(conn->sock[sockindex], SSL_SHUTDOWN_TIMEOUT);
     if(what > 0) {
       /* Something to read, let's do it and hope that it is the close
          notify alert from the server.  buf is managed internally by
diff --git a/Utilities/cmcurl/lib/vtls/cyassl.c b/Utilities/cmcurl/lib/vtls/cyassl.c
index 7994b3e..5d6dbfb 100644
--- a/Utilities/cmcurl/lib/vtls/cyassl.c
+++ b/Utilities/cmcurl/lib/vtls/cyassl.c
@@ -55,7 +55,7 @@ and that's a problem since options.h hasn't been included yet. */
 #include "parsedate.h"
 #include "connect.h" /* for the connect timeout */
 #include "select.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "x509asn1.h"
 #include "curl_printf.h"
 
@@ -118,9 +118,9 @@ static int do_file_type(const char *type)
 {
   if(!type || !type[0])
     return SSL_FILETYPE_PEM;
-  if(Curl_raw_equal(type, "PEM"))
+  if(strcasecompare(type, "PEM"))
     return SSL_FILETYPE_PEM;
-  if(Curl_raw_equal(type, "DER"))
+  if(strcasecompare(type, "DER"))
     return SSL_FILETYPE_ASN1;
   return -1;
 }
@@ -803,7 +803,8 @@ cyassl_connect_common(struct connectdata *conn,
       curl_socket_t readfd = ssl_connect_2_reading==
         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
 
-      what = Curl_socket_ready(readfd, writefd, nonblocking?0:timeout_ms);
+      what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
+                               nonblocking?0:timeout_ms);
       if(what < 0) {
         /* fatal error */
         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
diff --git a/Utilities/cmcurl/lib/vtls/darwinssl.c b/Utilities/cmcurl/lib/vtls/darwinssl.c
index ebb9e30..66e74f1 100644
--- a/Utilities/cmcurl/lib/vtls/darwinssl.c
+++ b/Utilities/cmcurl/lib/vtls/darwinssl.c
@@ -6,7 +6,7 @@
  *                             \___|\___/|_| \_\_____|
  *
  * Copyright (C) 2012 - 2014, Nick Zitzmann, <nickzman at gmail.com>.
- * Copyright (C) 2012 - 2015, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -920,7 +920,7 @@ static OSStatus CopyIdentityWithLabel(char *label,
 #if CURL_SUPPORT_MAC_10_6
     /* On Leopard and Snow Leopard, fall back to SecKeychainSearch. */
     status = CopyIdentityWithLabelOldSchool(label, out_cert_and_key);
-#endif /* CURL_SUPPORT_MAC_10_7 */
+#endif /* CURL_SUPPORT_MAC_10_6 */
   }
 #elif CURL_SUPPORT_MAC_10_6
   /* For developers building on older cats, we have no choice but to fall back
@@ -955,7 +955,7 @@ static OSStatus CopyIdentityFromPKCS12File(const char *cPath,
 
     /* Here we go: */
     status = SecPKCS12Import(pkcs_data, options, &items);
-    if(status == noErr && items && CFArrayGetCount(items)) {
+    if(status == errSecSuccess && items && CFArrayGetCount(items)) {
       CFDictionaryRef identity_and_trust = CFArrayGetValueAtIndex(items, 0L);
       const void *temp_identity = CFDictionaryGetValue(identity_and_trust,
         kSecImportItemIdentity);
@@ -1438,6 +1438,16 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
         /* Disable IDEA: */
         case SSL_RSA_WITH_IDEA_CBC_SHA:
         case SSL_RSA_WITH_IDEA_CBC_MD5:
+        /* Disable RC4: */
+        case SSL_RSA_WITH_RC4_128_MD5:
+        case SSL_RSA_WITH_RC4_128_SHA:
+        case 0xC002: /* TLS_ECDH_ECDSA_WITH_RC4_128_SHA */
+        case 0xC007: /* TLS_ECDHE_ECDSA_WITH_RC4_128_SHA*/
+        case 0xC00C: /* TLS_ECDH_RSA_WITH_RC4_128_SHA */
+        case 0xC011: /* TLS_ECDHE_RSA_WITH_RC4_128_SHA */
+        case 0x008A: /* TLS_PSK_WITH_RC4_128_SHA */
+        case 0x008E: /* TLS_DHE_PSK_WITH_RC4_128_SHA */
+        case 0x0092: /* TLS_RSA_PSK_WITH_RC4_128_SHA */
           break;
         default: /* enable everything else */
           allowed_ciphers[allowed_ciphers_count++] = all_ciphers[i];
@@ -2140,7 +2150,8 @@ darwinssl_connect_common(struct connectdata *conn,
       curl_socket_t readfd = ssl_connect_2_reading ==
       connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
 
-      what = Curl_socket_ready(readfd, writefd, nonblocking?0:timeout_ms);
+      what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
+                               nonblocking?0:timeout_ms);
       if(what < 0) {
         /* fatal error */
         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
@@ -2262,8 +2273,7 @@ int Curl_darwinssl_shutdown(struct connectdata *conn, int sockindex)
 
   rc = 0;
 
-  what = Curl_socket_ready(conn->sock[sockindex],
-                           CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
+  what = SOCKET_READABLE(conn->sock[sockindex], SSL_SHUTDOWN_TIMEOUT);
 
   for(;;) {
     if(what < 0) {
@@ -2291,7 +2301,7 @@ int Curl_darwinssl_shutdown(struct connectdata *conn, int sockindex)
     if(nread <= 0)
       break;
 
-    what = Curl_socket_ready(conn->sock[sockindex], CURL_SOCKET_BAD, 0);
+    what = SOCKET_READABLE(conn->sock[sockindex], 0);
   }
 
   return rc;
diff --git a/Utilities/cmcurl/lib/vtls/gskit.c b/Utilities/cmcurl/lib/vtls/gskit.c
index 55a55ef..3b0cfd5 100644
--- a/Utilities/cmcurl/lib/vtls/gskit.c
+++ b/Utilities/cmcurl/lib/vtls/gskit.c
@@ -5,7 +5,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  *
  * This software is licensed as described in the file COPYING, which
  * you should have received as part of this distribution. The terms
@@ -72,7 +72,7 @@
 #include "vtls.h"
 #include "connect.h" /* for the connect timeout */
 #include "select.h"
-#include "strequal.h"
+#include "strcase.h"
 #include "x509asn1.h"
 #include "curl_printf.h"
 
@@ -1001,8 +1001,8 @@ int Curl_gskit_shutdown(struct connectdata *conn, int sockindex)
 
   close_one(connssl, data);
   rc = 0;
-  what = Curl_socket_ready(conn->sock[sockindex],
-                           CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
+  what = SOCKET_READABLE(conn->sock[sockindex],
+                         SSL_SHUTDOWN_TIMEOUT);
 
   for(;;) {
     if(what < 0) {
@@ -1031,7 +1031,7 @@ int Curl_gskit_shutdown(struct connectdata *conn, int sockindex)
     if(nread <= 0)
       break;
 
-    what = Curl_socket_ready(conn->sock[sockindex], CURL_SOCKET_BAD, 0);
+    what = SOCKET_READABLE(conn->sock[sockindex], 0);
   }
 
   return rc;
diff --git a/Utilities/cmcurl/lib/vtls/gtls.c b/Utilities/cmcurl/lib/vtls/gtls.c
index 1c3e6b1..5c87c7f 100644
--- a/Utilities/cmcurl/lib/vtls/gtls.c
+++ b/Utilities/cmcurl/lib/vtls/gtls.c
@@ -52,7 +52,7 @@
 #include "parsedate.h"
 #include "connect.h" /* for the connect timeout */
 #include "select.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "warnless.h"
 #include "x509asn1.h"
 #include "curl_printf.h"
@@ -289,7 +289,7 @@ static CURLcode handshake(struct connectdata *conn,
       curl_socket_t readfd = ssl_connect_2_reading==
         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
 
-      what = Curl_socket_ready(readfd, writefd,
+      what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
                                nonblocking?0:
                                timeout_ms?timeout_ms:1000);
       if(what < 0) {
@@ -356,9 +356,9 @@ static gnutls_x509_crt_fmt_t do_file_type(const char *type)
 {
   if(!type || !type[0])
     return GNUTLS_X509_FMT_PEM;
-  if(Curl_raw_equal(type, "PEM"))
+  if(strcasecompare(type, "PEM"))
     return GNUTLS_X509_FMT_PEM;
-  if(Curl_raw_equal(type, "DER"))
+  if(strcasecompare(type, "DER"))
     return GNUTLS_X509_FMT_DER;
   return -1;
 }
@@ -1445,8 +1445,8 @@ int Curl_gtls_shutdown(struct connectdata *conn, int sockindex)
 
   if(conn->ssl[sockindex].session) {
     while(!done) {
-      int what = Curl_socket_ready(conn->sock[sockindex],
-                                   CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
+      int what = SOCKET_READABLE(conn->sock[sockindex],
+                                 SSL_SHUTDOWN_TIMEOUT);
       if(what > 0) {
         /* Something to read, let's do it and hope that it is the close
            notify alert from the server */
diff --git a/Utilities/cmcurl/lib/vtls/mbedtls.c b/Utilities/cmcurl/lib/vtls/mbedtls.c
index a1e7d23..24249dd 100644
--- a/Utilities/cmcurl/lib/vtls/mbedtls.c
+++ b/Utilities/cmcurl/lib/vtls/mbedtls.c
@@ -31,7 +31,7 @@
 
 #ifdef USE_MBEDTLS
 
-#include <mbedtls/net.h>
+#include <mbedtls/net_sockets.h>
 #include <mbedtls/ssl.h>
 #include <mbedtls/certs.h>
 #include <mbedtls/x509.h>
@@ -50,7 +50,6 @@
 #include "parsedate.h"
 #include "connect.h" /* for the connect timeout */
 #include "select.h"
-#include "rawstr.h"
 #include "polarssl_threadlock.h"
 
 /* The last 3 #include files should be in this order */
@@ -420,7 +419,15 @@ mbed_connect_step1(struct connectdata *conn,
 #endif
 
 #ifdef MBEDTLS_DEBUG
+  /* In order to make that work in mbedtls MBEDTLS_DEBUG_C must be defined. */
   mbedtls_ssl_conf_dbg(&connssl->config, mbed_debug, data);
+  /* - 0 No debug
+   * - 1 Error
+   * - 2 State change
+   * - 3 Informational
+   * - 4 Verbose
+   */
+  mbedtls_debug_set_threshold(4);
 #endif
 
   connssl->connecting_state = ssl_connect_2;
@@ -765,7 +772,8 @@ mbed_connect_common(struct connectdata *conn,
       curl_socket_t readfd = ssl_connect_2_reading==
         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
 
-      what = Curl_socket_ready(readfd, writefd, nonblocking ? 0 : timeout_ms);
+      what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
+                               nonblocking ? 0 : timeout_ms);
       if(what < 0) {
         /* fatal error */
         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
diff --git a/Utilities/cmcurl/lib/vtls/nss.c b/Utilities/cmcurl/lib/vtls/nss.c
index e467360..dff1575 100644
--- a/Utilities/cmcurl/lib/vtls/nss.c
+++ b/Utilities/cmcurl/lib/vtls/nss.c
@@ -34,7 +34,7 @@
 #include "formdata.h" /* for the boundary function */
 #include "url.h" /* for the ssl config check function */
 #include "connect.h"
-#include "strequal.h"
+#include "strcase.h"
 #include "select.h"
 #include "vtls.h"
 #include "llist.h"
@@ -64,7 +64,7 @@
 #include <ocsp.h>
 #endif
 
-#include "rawstr.h"
+#include "strcase.h"
 #include "warnless.h"
 #include "x509asn1.h"
 
@@ -78,13 +78,12 @@
 #define SLOTSIZE 13
 
 PRFileDesc *PR_ImportTCPSocket(PRInt32 osfd);
-
-PRLock * nss_initlock = NULL;
-PRLock * nss_crllock = NULL;
-struct curl_llist *nss_crl_list = NULL;
-NSSInitContext * nss_context = NULL;
-
-volatile int initialized = 0;
+static PRLock *nss_initlock = NULL;
+static PRLock *nss_crllock = NULL;
+static PRLock *nss_findslot_lock = NULL;
+static struct curl_llist *nss_crl_list = NULL;
+static NSSInitContext *nss_context = NULL;
+static volatile int initialized = 0;
 
 typedef struct {
   const char *name;
@@ -150,7 +149,7 @@ static const cipher_s cipherlist[] = {
   {"ecdh_rsa_3des_sha",          TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA},
   {"ecdh_rsa_aes_128_sha",       TLS_ECDH_RSA_WITH_AES_128_CBC_SHA},
   {"ecdh_rsa_aes_256_sha",       TLS_ECDH_RSA_WITH_AES_256_CBC_SHA},
-  {"echde_rsa_null",             TLS_ECDHE_RSA_WITH_NULL_SHA},
+  {"ecdhe_rsa_null",             TLS_ECDHE_RSA_WITH_NULL_SHA},
   {"ecdhe_rsa_rc4_128_sha",      TLS_ECDHE_RSA_WITH_RC4_128_SHA},
   {"ecdhe_rsa_3des_sha",         TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA},
   {"ecdhe_rsa_aes_128_sha",      TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
@@ -180,10 +179,29 @@ static const cipher_s cipherlist[] = {
   {"ecdhe_rsa_aes_128_gcm_sha_256",   TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
   {"ecdh_rsa_aes_128_gcm_sha_256",    TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256},
 #endif
+#ifdef TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
+  /* cipher suites using SHA384 */
+  {"rsa_aes_256_gcm_sha_384",         TLS_RSA_WITH_AES_256_GCM_SHA384},
+  {"dhe_rsa_aes_256_gcm_sha_384",     TLS_DHE_RSA_WITH_AES_256_GCM_SHA384},
+  {"dhe_dss_aes_256_gcm_sha_384",     TLS_DHE_DSS_WITH_AES_256_GCM_SHA384},
+  {"ecdhe_ecdsa_aes_256_sha_384",     TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384},
+  {"ecdhe_rsa_aes_256_sha_384",       TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384},
+  {"ecdhe_ecdsa_aes_256_gcm_sha_384", TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384},
+  {"ecdhe_rsa_aes_256_gcm_sha_384",   TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384},
+#endif
+#ifdef TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
+  /* chacha20-poly1305 cipher suites */
+ {"ecdhe_rsa_chacha20_poly1305_sha_256",
+     TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
+ {"ecdhe_ecdsa_chacha20_poly1305_sha_256",
+     TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256},
+ {"dhe_rsa_chacha20_poly1305_sha_256",
+     TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
+#endif
 };
 
 static const char* pem_library = "libnsspem.so";
-SECMODModule* mod = NULL;
+static SECMODModule* mod = NULL;
 
 /* NSPR I/O layer we use to detect blocking direction during SSL handshake */
 static PRDescIdentity nspr_io_identity = PR_INVALID_IO_LAYER;
@@ -243,7 +261,7 @@ static SECStatus set_ciphers(struct Curl_easy *data, PRFileDesc * model,
     found = PR_FALSE;
 
     for(i=0; i<NUM_OF_CIPHERS; i++) {
-      if(Curl_raw_equal(cipher, cipherlist[i].name)) {
+      if(strcasecompare(cipher, cipherlist[i].name)) {
         cipher_state[i] = PR_TRUE;
         found = PR_TRUE;
         break;
@@ -340,6 +358,19 @@ static char* dup_nickname(struct Curl_easy *data, enum dupstring cert_kind)
   return NULL;
 }
 
+/* Lock/unlock wrapper for PK11_FindSlotByName() to work around race condition
+ * in nssSlot_IsTokenPresent() causing spurious SEC_ERROR_NO_TOKEN.  For more
+ * details, go to <https://bugzilla.mozilla.org/1297397>.
+ */
+static PK11SlotInfo* nss_find_slot_by_name(const char *slot_name)
+{
+  PK11SlotInfo *slot;
+  PR_Lock(nss_initlock);
+  slot = PK11_FindSlotByName(slot_name);
+  PR_Unlock(nss_initlock);
+  return slot;
+}
+
 /* Call PK11_CreateGenericObject() with the given obj_class and filename.  If
  * the call succeeds, append the object handle to the list of objects so that
  * the object can be destroyed in Curl_nss_close(). */
@@ -362,7 +393,7 @@ static CURLcode nss_create_object(struct ssl_connect_data *ssl,
   if(!slot_name)
     return CURLE_OUT_OF_MEMORY;
 
-  slot = PK11_FindSlotByName(slot_name);
+  slot = nss_find_slot_by_name(slot_name);
   free(slot_name);
   if(!slot)
     return result;
@@ -563,7 +594,7 @@ static CURLcode nss_load_key(struct connectdata *conn, int sockindex,
     return result;
   }
 
-  slot = PK11_FindSlotByName("PEM Token #1");
+  slot = nss_find_slot_by_name("PEM Token #1");
   if(!slot)
     return CURLE_SSL_CERTPROBLEM;
 
@@ -1013,7 +1044,7 @@ static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
     struct CERTCertificateStr *cert;
     struct SECKEYPrivateKeyStr *key;
 
-    PK11SlotInfo *slot = PK11_FindSlotByName(pem_slotname);
+    PK11SlotInfo *slot = nss_find_slot_by_name(pem_slotname);
     if(NULL == slot) {
       failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
       return SECFailure;
@@ -1249,6 +1280,7 @@ int Curl_nss_init(void)
     PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256);
     nss_initlock = PR_NewLock();
     nss_crllock = PR_NewLock();
+    nss_findslot_lock = PR_NewLock();
   }
 
   /* We will actually initialize NSS later */
@@ -1303,6 +1335,7 @@ void Curl_nss_cleanup(void)
 
   PR_DestroyLock(nss_initlock);
   PR_DestroyLock(nss_crllock);
+  PR_DestroyLock(nss_findslot_lock);
   nss_initlock = NULL;
 
   initialized = 0;
@@ -1888,8 +1921,11 @@ static CURLcode nss_connect_common(struct connectdata *conn, int sockindex,
   const bool blocking = (done == NULL);
   CURLcode result;
 
-  if(connssl->state == ssl_connection_complete)
+  if(connssl->state == ssl_connection_complete) {
+    if(!blocking)
+      *done = TRUE;
     return CURLE_OK;
+  }
 
   if(connssl->connecting_state == ssl_connect_1) {
     result = nss_setup_connect(conn, sockindex);
diff --git a/Utilities/cmcurl/lib/vtls/openssl.c b/Utilities/cmcurl/lib/vtls/openssl.c
index 3027ca3..c040928 100644
--- a/Utilities/cmcurl/lib/vtls/openssl.c
+++ b/Utilities/cmcurl/lib/vtls/openssl.c
@@ -46,10 +46,9 @@
 #include "openssl.h"
 #include "connect.h"
 #include "slist.h"
-#include "strequal.h"
 #include "select.h"
 #include "vtls.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "hostcheck.h"
 #include "curl_printf.h"
 
@@ -95,11 +94,6 @@
 
 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
 #define HAVE_ERR_REMOVE_THREAD_STATE 1
-#if (OPENSSL_VERSION_NUMBER >= 0x10100004L) && \
-  !defined(LIBRESSL_VERSION_NUMBER)
-/* OpenSSL 1.1.0 deprecates the function */
-#define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1
-#endif
 #endif
 
 #if !defined(HAVE_SSLV2_CLIENT_METHOD) || \
@@ -110,11 +104,28 @@
 
 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && /* OpenSSL 1.1.0+ */ \
   !defined(LIBRESSL_VERSION_NUMBER)
-#define SSLeay_add_ssl_algorithms() SSL_library_init()
 #define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER
 #define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */
 #define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */
 #define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */
+#define CONST_EXTS const
+#define CONST_ASN1_BIT_STRING const
+#define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1
+#else
+/* For OpenSSL before 1.1.0 */
+#define ASN1_STRING_get0_data(x) ASN1_STRING_data(x)
+#define X509_get0_notBefore(x) X509_get_notBefore(x)
+#define X509_get0_notAfter(x) X509_get_notAfter(x)
+#define CONST_EXTS /* nope */
+#define CONST_ASN1_BIT_STRING /* nope */
+#ifdef LIBRESSL_VERSION_NUMBER
+static unsigned long OpenSSL_version_num(void)
+{
+  return LIBRESSL_VERSION_NUMBER;
+}
+#else
+#define OpenSSL_version_num() SSLeay()
+#endif
 #endif
 
 #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* 1.0.2 or later */ \
@@ -278,13 +289,13 @@ static int do_file_type(const char *type)
 {
   if(!type || !type[0])
     return SSL_FILETYPE_PEM;
-  if(Curl_raw_equal(type, "PEM"))
+  if(strcasecompare(type, "PEM"))
     return SSL_FILETYPE_PEM;
-  if(Curl_raw_equal(type, "DER"))
+  if(strcasecompare(type, "DER"))
     return SSL_FILETYPE_ASN1;
-  if(Curl_raw_equal(type, "ENG"))
+  if(strcasecompare(type, "ENG"))
     return SSL_FILETYPE_ENGINE;
-  if(Curl_raw_equal(type, "P12"))
+  if(strcasecompare(type, "P12"))
     return SSL_FILETYPE_PKCS12;
   return -1;
 }
@@ -711,6 +722,10 @@ int Curl_ossl_init(void)
                          CONF_MFLAGS_DEFAULT_SECTION|
                          CONF_MFLAGS_IGNORE_MISSING_FILE);
 
+#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
+    !defined(LIBRESSL_VERSION_NUMBER)
+  /* OpenSSL 1.1.0+ takes care of initialization itself */
+#else
   /* Lets get nice error messages */
   SSL_load_error_strings();
 
@@ -719,6 +734,7 @@ int Curl_ossl_init(void)
     return 0;
 
   OpenSSL_add_all_algorithms();
+#endif
 
   return 1;
 }
@@ -726,6 +742,11 @@ int Curl_ossl_init(void)
 /* Global cleanup */
 void Curl_ossl_cleanup(void)
 {
+#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
+    !defined(LIBRESSL_VERSION_NUMBER)
+  /* OpenSSL 1.1 deprecates all these cleanup functions and
+     turns them into no-ops in OpenSSL 1.0 compatibility mode */
+#else
   /* Free ciphers and digests lists */
   EVP_cleanup();
 
@@ -734,18 +755,11 @@ void Curl_ossl_cleanup(void)
   ENGINE_cleanup();
 #endif
 
-#ifdef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
-  /* Free OpenSSL ex_data table */
-  CRYPTO_cleanup_all_ex_data();
-#endif
-
   /* Free OpenSSL error strings */
   ERR_free_strings();
 
   /* Free thread local error state, destroying hash upon zero refcount */
-#ifdef HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED
-
-#elif defined(HAVE_ERR_REMOVE_THREAD_STATE)
+#ifdef HAVE_ERR_REMOVE_THREAD_STATE
   ERR_remove_thread_state(NULL);
 #else
   ERR_remove_state(0);
@@ -757,6 +771,7 @@ void Curl_ossl_cleanup(void)
 #ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS
   SSL_COMP_free_compression_methods();
 #endif
+#endif
 }
 
 /*
@@ -949,8 +964,8 @@ int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
   if(connssl->handle) {
     buffsize = (int)sizeof(buf);
     while(!done) {
-      int what = Curl_socket_ready(conn->sock[sockindex],
-                                   CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
+      int what = SOCKET_READABLE(conn->sock[sockindex],
+                                 SSL_SHUTDOWN_TIMEOUT);
       if(what > 0) {
         ERR_clear_error();
 
@@ -1043,6 +1058,14 @@ void Curl_ossl_close_all(struct Curl_easy *data)
 #else
   (void)data;
 #endif
+#if !defined(HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED) && \
+  defined(HAVE_ERR_REMOVE_THREAD_STATE)
+  /* OpenSSL 1.0.1 and 1.0.2 build an error queue that is stored per-thread
+     so we need to clean it here in case the thread will be killed. All OpenSSL
+     code should extract the error in association with the error so clearing
+     this queue here should be harmless at worst. */
+  ERR_remove_thread_state(NULL);
+#endif
 }
 
 /* ====================================================== */
@@ -1083,6 +1106,7 @@ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
 #endif
   CURLcode result = CURLE_OK;
   bool dNSName = FALSE; /* if a dNSName field exists in the cert */
+  bool iPAddress = FALSE; /* if a iPAddress field exists in the cert */
 
 #ifdef ENABLE_IPV6
   if(conn->bits.ipv6_ip &&
@@ -1115,15 +1139,15 @@ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
       /* get a handle to alternative name number i */
       const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
 
-      /* If a subjectAltName extension of type dNSName is present, that MUST
-         be used as the identity. / RFC2818 section 3.1 */
       if(check->type == GEN_DNS)
         dNSName = TRUE;
+      else if(check->type == GEN_IPADD)
+        iPAddress = TRUE;
 
       /* only check alternatives of the same type the target is */
       if(check->type == target) {
         /* get data and length */
-        const char *altptr = (char *)ASN1_STRING_data(check->d.ia5);
+        const char *altptr = (char *)ASN1_STRING_get0_data(check->d.ia5);
         size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);
 
         switch(target) {
@@ -1164,18 +1188,14 @@ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
     }
     GENERAL_NAMES_free(altnames);
 
-    if(dnsmatched || (!dNSName && ipmatched)) {
-      /* count as a match if the dnsname matched or if there was no dnsname
-         fields at all AND there was an IP field match */
+    if(dnsmatched || ipmatched)
       matched = TRUE;
-    }
   }
 
   if(matched)
     /* an alternative name matched */
     ;
-  else if(dNSName) {
-    /* an dNSName field existed, but didn't match and then we MUST fail */
+  else if(dNSName || iPAddress) {
     infof(data, " subjectAltName does not match %s\n", conn->host.dispname);
     failf(data, "SSL: no alternative certificate subject name matches "
           "target host name '%s'", conn->host.dispname);
@@ -1215,7 +1235,7 @@ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
           if(j >= 0) {
             peer_CN = OPENSSL_malloc(j+1);
             if(peer_CN) {
-              memcpy(peer_CN, ASN1_STRING_data(tmp), j);
+              memcpy(peer_CN, ASN1_STRING_get0_data(tmp), j);
               peer_CN[j] = '\0';
             }
           }
@@ -2178,6 +2198,7 @@ static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex)
 
         lerr = SSL_get_verify_result(connssl->handle);
         if(lerr != X509_V_OK) {
+          data->set.ssl.certverifyresult = lerr;
           snprintf(error_buffer, sizeof(error_buffer),
                    "SSL certificate problem: %s",
                    X509_verify_cert_error_string(lerr));
@@ -2309,7 +2330,7 @@ do {                              \
 
 static int X509V3_ext(struct Curl_easy *data,
                       int certnum,
-                      STACK_OF(X509_EXTENSION) *exts)
+                      CONST_EXTS STACK_OF(X509_EXTENSION) *exts)
 {
   int i;
   size_t j;
@@ -2391,7 +2412,7 @@ static CURLcode get_cert_chain(struct connectdata *conn,
     EVP_PKEY *pubkey=NULL;
     int j;
     char *ptr;
-    ASN1_BIT_STRING *psig = NULL;
+    CONST_ASN1_BIT_STRING ASN1_BIT_STRING *psig = NULL;
 
     X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
     push_certinfo("Subject", i);
@@ -2411,7 +2432,7 @@ static CURLcode get_cert_chain(struct connectdata *conn,
 
 #if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS)
     {
-      X509_ALGOR *palg = NULL;
+      const X509_ALGOR *palg = NULL;
       ASN1_STRING *a = ASN1_STRING_new();
       if(a) {
         X509_get0_signature(&psig, &palg, x);
@@ -2442,10 +2463,10 @@ static CURLcode get_cert_chain(struct connectdata *conn,
     }
 #endif
 
-    ASN1_TIME_print(mem, X509_get_notBefore(x));
+    ASN1_TIME_print(mem, X509_get0_notBefore(x));
     push_certinfo("Start date", i);
 
-    ASN1_TIME_print(mem, X509_get_notAfter(x));
+    ASN1_TIME_print(mem, X509_get0_notAfter(x));
     push_certinfo("Expire date", i);
 
     pubkey = X509_get_pubkey(x);
@@ -2629,7 +2650,7 @@ static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert,
       break; /* failed */
 
     /* https://www.openssl.org/docs/crypto/buffer.html */
-    buff1 = temp = OPENSSL_malloc(len1);
+    buff1 = temp = malloc(len1);
     if(!buff1)
       break; /* failed */
 
@@ -2652,7 +2673,7 @@ static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert,
 
   /* https://www.openssl.org/docs/crypto/buffer.html */
   if(buff1)
-    OPENSSL_free(buff1);
+    free(buff1);
 
   return result;
 }
@@ -2698,12 +2719,12 @@ static CURLcode servercert(struct connectdata *conn,
                          buffer, BUFSIZE);
   infof(data, " subject: %s\n", rc?"[NONE]":buffer);
 
-  ASN1_TIME_print(mem, X509_get_notBefore(connssl->server_cert));
+  ASN1_TIME_print(mem, X509_get0_notBefore(connssl->server_cert));
   len = BIO_get_mem_data(mem, (char **) &ptr);
   infof(data, " start date: %.*s\n", len, ptr);
   rc = BIO_reset(mem);
 
-  ASN1_TIME_print(mem, X509_get_notAfter(connssl->server_cert));
+  ASN1_TIME_print(mem, X509_get0_notAfter(connssl->server_cert));
   len = BIO_get_mem_data(mem, (char **) &ptr);
   infof(data, " expire date: %.*s\n", len, ptr);
   rc = BIO_reset(mem);
@@ -2945,7 +2966,8 @@ static CURLcode ossl_connect_common(struct connectdata *conn,
       curl_socket_t readfd = ssl_connect_2_reading==
         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
 
-      what = Curl_socket_ready(readfd, writefd, nonblocking?0:timeout_ms);
+      what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
+                               nonblocking?0:timeout_ms);
       if(what < 0) {
         /* fatal error */
         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
@@ -3142,7 +3164,7 @@ size_t Curl_ossl_version(char *buffer, size_t size)
   unsigned long ssleay_value;
   sub[2]='\0';
   sub[1]='\0';
-  ssleay_value=SSLeay();
+  ssleay_value=OpenSSL_version_num();
   if(ssleay_value < 0x906000) {
     ssleay_value=SSLEAY_VERSION_NUMBER;
     sub[0]='\0';
diff --git a/Utilities/cmcurl/lib/vtls/polarssl.c b/Utilities/cmcurl/lib/vtls/polarssl.c
index d33f548..18b564e 100644
--- a/Utilities/cmcurl/lib/vtls/polarssl.c
+++ b/Utilities/cmcurl/lib/vtls/polarssl.c
@@ -54,7 +54,7 @@
 #include "parsedate.h"
 #include "connect.h" /* for the connect timeout */
 #include "select.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "polarssl_threadlock.h"
 #include "curl_printf.h"
 #include "curl_memory.h"
@@ -75,6 +75,11 @@
 #define THREADING_SUPPORT
 #endif
 
+#ifndef POLARSSL_ERROR_C
+#define error_strerror(x,y,z)
+#endif /* POLARSSL_ERROR_C */
+
+
 #if defined(THREADING_SUPPORT)
 static entropy_context entropy;
 
@@ -96,13 +101,13 @@ static void entropy_init_mutex(entropy_context *ctx)
 /* start of entropy_func_mutex() */
 static int entropy_func_mutex(void *data, unsigned char *output, size_t len)
 {
-    int ret;
-    /* lock 1 = entropy_func_mutex() */
-    Curl_polarsslthreadlock_lock_function(1);
-    ret = entropy_func(data, output, len);
-    Curl_polarsslthreadlock_unlock_function(1);
+  int ret;
+  /* lock 1 = entropy_func_mutex() */
+  Curl_polarsslthreadlock_lock_function(1);
+  ret = entropy_func(data, output, len);
+  Curl_polarsslthreadlock_unlock_function(1);
 
-    return ret;
+  return ret;
 }
 /* end of entropy_func_mutex() */
 
@@ -138,18 +143,11 @@ static Curl_send polarssl_send;
 
 static CURLcode
 polarssl_connect_step1(struct connectdata *conn,
-                     int sockindex)
+                       int sockindex)
 {
   struct Curl_easy *data = conn->data;
   struct ssl_connect_data* connssl = &conn->ssl[sockindex];
-
-  bool sni = TRUE; /* default is SNI enabled */
   int ret = -1;
-#ifdef ENABLE_IPV6
-  struct in6_addr addr;
-#else
-  struct in_addr addr;
-#endif
   char errorbuf[128];
   errorbuf[0]=0;
 
@@ -158,30 +156,24 @@ polarssl_connect_step1(struct connectdata *conn,
     failf(data, "PolarSSL does not support SSLv2");
     return CURLE_SSL_CONNECT_ERROR;
   }
-  else if(data->set.ssl.version == CURL_SSLVERSION_SSLv3)
-    sni = FALSE; /* SSLv3 has no SNI */
 
 #ifdef THREADING_SUPPORT
   entropy_init_mutex(&entropy);
 
   if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func_mutex, &entropy,
                           NULL, 0)) != 0) {
-#ifdef POLARSSL_ERROR_C
-     error_strerror(ret, errorbuf, sizeof(errorbuf));
-#endif /* POLARSSL_ERROR_C */
-     failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n",
-                                                            -ret, errorbuf);
+    error_strerror(ret, errorbuf, sizeof(errorbuf));
+    failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n",
+          -ret, errorbuf);
   }
 #else
   entropy_init(&connssl->entropy);
 
   if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func, &connssl->entropy,
                           NULL, 0)) != 0) {
-#ifdef POLARSSL_ERROR_C
-     error_strerror(ret, errorbuf, sizeof(errorbuf));
-#endif /* POLARSSL_ERROR_C */
-     failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n",
-                                                            -ret, errorbuf);
+    error_strerror(ret, errorbuf, sizeof(errorbuf));
+    failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n",
+          -ret, errorbuf);
   }
 #endif /* THREADING_SUPPORT */
 
@@ -193,9 +185,7 @@ polarssl_connect_step1(struct connectdata *conn,
                               data->set.str[STRING_SSL_CAFILE]);
 
     if(ret<0) {
-#ifdef POLARSSL_ERROR_C
       error_strerror(ret, errorbuf, sizeof(errorbuf));
-#endif /* POLARSSL_ERROR_C */
       failf(data, "Error reading ca cert file %s - PolarSSL: (-0x%04X) %s",
             data->set.str[STRING_SSL_CAFILE], -ret, errorbuf);
 
@@ -209,9 +199,7 @@ polarssl_connect_step1(struct connectdata *conn,
                               data->set.str[STRING_SSL_CAPATH]);
 
     if(ret<0) {
-#ifdef POLARSSL_ERROR_C
       error_strerror(ret, errorbuf, sizeof(errorbuf));
-#endif /* POLARSSL_ERROR_C */
       failf(data, "Error reading ca cert path %s - PolarSSL: (-0x%04X) %s",
             data->set.str[STRING_SSL_CAPATH], -ret, errorbuf);
 
@@ -228,9 +216,7 @@ polarssl_connect_step1(struct connectdata *conn,
                               data->set.str[STRING_CERT]);
 
     if(ret) {
-#ifdef POLARSSL_ERROR_C
       error_strerror(ret, errorbuf, sizeof(errorbuf));
-#endif /* POLARSSL_ERROR_C */
       failf(data, "Error reading client cert file %s - PolarSSL: (-0x%04X) %s",
             data->set.str[STRING_CERT], -ret, errorbuf);
 
@@ -253,9 +239,7 @@ polarssl_connect_step1(struct connectdata *conn,
     pk_free(&pk);
 
     if(ret) {
-#ifdef POLARSSL_ERROR_C
       error_strerror(ret, errorbuf, sizeof(errorbuf));
-#endif /* POLARSSL_ERROR_C */
       failf(data, "Error reading private key %s - PolarSSL: (-0x%04X) %s",
             data->set.str[STRING_KEY], -ret, errorbuf);
 
@@ -271,9 +255,7 @@ polarssl_connect_step1(struct connectdata *conn,
                               data->set.str[STRING_SSL_CRLFILE]);
 
     if(ret) {
-#ifdef POLARSSL_ERROR_C
       error_strerror(ret, errorbuf, sizeof(errorbuf));
-#endif /* POLARSSL_ERROR_C */
       failf(data, "Error reading CRL file %s - PolarSSL: (-0x%04X) %s",
             data->set.str[STRING_SSL_CRLFILE], -ret, errorbuf);
 
@@ -344,13 +326,14 @@ polarssl_connect_step1(struct connectdata *conn,
     Curl_ssl_sessionid_lock(conn);
     if(!Curl_ssl_getsessionid(conn, &old_session, NULL)) {
       ret = ssl_set_session(&connssl->ssl, old_session);
-      Curl_ssl_sessionid_unlock(conn);
       if(ret) {
+        Curl_ssl_sessionid_unlock(conn);
         failf(data, "ssl_set_session returned -0x%x", -ret);
         return CURLE_SSL_CONNECT_ERROR;
       }
       infof(data, "PolarSSL re-using session\n");
     }
+    Curl_ssl_sessionid_unlock(conn);
   }
 
   ssl_set_ca_chain(&connssl->ssl,
@@ -401,7 +384,7 @@ polarssl_connect_step1(struct connectdata *conn,
 
 static CURLcode
 polarssl_connect_step2(struct connectdata *conn,
-                     int sockindex)
+                       int sockindex)
 {
   int ret;
   struct Curl_easy *data = conn->data;
@@ -429,9 +412,7 @@ polarssl_connect_step2(struct connectdata *conn,
     return CURLE_OK;
 
   default:
-#ifdef POLARSSL_ERROR_C
     error_strerror(ret, errorbuf, sizeof(errorbuf));
-#endif /* POLARSSL_ERROR_C */
     failf(data, "ssl_handshake returned - PolarSSL: (-0x%04X) %s",
           -ret, errorbuf);
     return CURLE_SSL_CONNECT_ERROR;
@@ -538,9 +519,9 @@ polarssl_connect_step2(struct connectdata *conn,
       }
       else
 #endif
-      if(!strncmp(next_protocol, ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH)) {
-        conn->negnpn = CURL_HTTP_VERSION_1_1;
-      }
+        if(!strncmp(next_protocol, ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH)) {
+          conn->negnpn = CURL_HTTP_VERSION_1_1;
+        }
     }
     else
       infof(data, "ALPN, server did not agree to a protocol\n");
@@ -555,7 +536,7 @@ polarssl_connect_step2(struct connectdata *conn,
 
 static CURLcode
 polarssl_connect_step3(struct connectdata *conn,
-                     int sockindex)
+                       int sockindex)
 {
   CURLcode retcode = CURLE_OK;
   struct ssl_connect_data *connssl = &conn->ssl[sockindex];
@@ -727,7 +708,8 @@ polarssl_connect_common(struct connectdata *conn,
       curl_socket_t readfd = ssl_connect_2_reading==
         connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
 
-      what = Curl_socket_ready(readfd, writefd, nonblocking?0:timeout_ms);
+      what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
+                               nonblocking?0:timeout_ms);
       if(what < 0) {
         /* fatal error */
         failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
@@ -786,8 +768,8 @@ polarssl_connect_common(struct connectdata *conn,
 
 CURLcode
 Curl_polarssl_connect_nonblocking(struct connectdata *conn,
-                                int sockindex,
-                                bool *done)
+                                  int sockindex,
+                                  bool *done)
 {
   return polarssl_connect_common(conn, sockindex, TRUE, done);
 }
@@ -795,7 +777,7 @@ Curl_polarssl_connect_nonblocking(struct connectdata *conn,
 
 CURLcode
 Curl_polarssl_connect(struct connectdata *conn,
-                    int sockindex)
+                      int sockindex)
 {
   CURLcode result;
   bool done = FALSE;
diff --git a/Utilities/cmcurl/lib/vtls/polarssl_threadlock.c b/Utilities/cmcurl/lib/vtls/polarssl_threadlock.c
index 3b0ebf8..b1eb7b7 100644
--- a/Utilities/cmcurl/lib/vtls/polarssl_threadlock.c
+++ b/Utilities/cmcurl/lib/vtls/polarssl_threadlock.c
@@ -5,7 +5,7 @@
  *                            | (__| |_| |  _ <| |___
  *                             \___|\___/|_| \_\_____|
  *
- * Copyright (C) 2013-2015, Daniel Stenberg, <daniel at haxx.se>, et al.
+ * Copyright (C) 2013-2016, Daniel Stenberg, <daniel at haxx.se>, et al.
  * Copyright (C) 2010, 2011, Hoi-Ho Chan, <hoiho.chan at gmail.com>
  *
  * This software is licensed as described in the file COPYING, which
@@ -52,7 +52,7 @@ int Curl_polarsslthreadlock_thread_setup(void)
   int i;
   int ret;
 
-  mutex_buf = malloc(NUMT * sizeof(POLARSSL_MUTEX_T));
+  mutex_buf = calloc(NUMT * sizeof(POLARSSL_MUTEX_T), 1);
   if(!mutex_buf)
     return 0;     /* error, no number of threads defined */
 
diff --git a/Utilities/cmcurl/lib/vtls/schannel.c b/Utilities/cmcurl/lib/vtls/schannel.c
index f991ec9..f731eeb 100644
--- a/Utilities/cmcurl/lib/vtls/schannel.c
+++ b/Utilities/cmcurl/lib/vtls/schannel.c
@@ -127,6 +127,18 @@ schannel_connect_step1(struct connectdata *conn, int sockindex)
   infof(data, "schannel: SSL/TLS connection with %s port %hu (step 1/3)\n",
         conn->host.name, conn->remote_port);
 
+#ifdef HAS_ALPN
+  /* ALPN is only supported on Windows 8.1 / Server 2012 R2 and above.
+     Also it doesn't seem to be supported for Wine, see curl bug #983. */
+  connssl->use_alpn = conn->bits.tls_enable_alpn &&
+                      !GetProcAddress(GetModuleHandleA("ntdll"),
+                                      "wine_get_version") &&
+                      Curl_verify_windows_version(6, 3, PLATFORM_WINNT,
+                                                  VERSION_GREATER_THAN_EQUAL);
+#else
+  connssl->use_alpn = false;
+#endif
+
   connssl->cred = NULL;
 
   /* check for an existing re-usable credential handle */
@@ -250,10 +262,7 @@ schannel_connect_step1(struct connectdata *conn, int sockindex)
   }
 
 #ifdef HAS_ALPN
-  /* ALPN is only supported on Windows 8.1 / Server 2012 R2 and above */
-  if(conn->bits.tls_enable_alpn &&
-     Curl_verify_windows_version(6, 3, PLATFORM_WINNT,
-                                 VERSION_GREATER_THAN_EQUAL)) {
+  if(connssl->use_alpn) {
     int cur = 0;
     int list_start_index = 0;
     unsigned int* extension_len = NULL;
@@ -328,11 +337,17 @@ schannel_connect_step1(struct connectdata *conn, int sockindex)
   if(!host_name)
     return CURLE_OUT_OF_MEMORY;
 
-  /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx */
+  /* Schannel InitializeSecurityContext:
+     https://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx
 
+     At the moment we don't pass inbuf unless we're using ALPN since we only
+     use it for that, and Wine (for which we currently disable ALPN) is giving
+     us problems with inbuf regardless. https://github.com/curl/curl/issues/983
+  */
   sspi_status = s_pSecFn->InitializeSecurityContext(
-    &connssl->cred->cred_handle, NULL, host_name,
-    connssl->req_flags, 0, 0, &inbuf_desc, 0, &connssl->ctxt->ctxt_handle,
+    &connssl->cred->cred_handle, NULL, host_name, connssl->req_flags, 0, 0,
+    (connssl->use_alpn ? &inbuf_desc : NULL),
+    0, &connssl->ctxt->ctxt_handle,
     &outbuf_desc, &connssl->ret_flags, &connssl->ctxt->time_stamp);
 
   Curl_unicodefree(host_name);
@@ -651,10 +666,7 @@ schannel_connect_step3(struct connectdata *conn, int sockindex)
   }
 
 #ifdef HAS_ALPN
-  /* ALPN is only supported on Windows 8.1 / Server 2012 R2 and above */
-  if(conn->bits.tls_enable_alpn &&
-     Curl_verify_windows_version(6, 3, PLATFORM_WINNT,
-                                 VERSION_GREATER_THAN_EQUAL)) {
+  if(connssl->use_alpn) {
     sspi_status = s_pSecFn->QueryContextAttributes(&connssl->ctxt->ctxt_handle,
       SECPKG_ATTR_APPLICATION_PROTOCOL, &alpn_result);
 
@@ -803,7 +815,8 @@ schannel_connect_common(struct connectdata *conn, int sockindex,
       curl_socket_t readfd = ssl_connect_2_reading ==
         connssl->connecting_state ? sockfd : CURL_SOCKET_BAD;
 
-      what = Curl_socket_ready(readfd, writefd, nonblocking ? 0 : timeout_ms);
+      what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
+                               nonblocking ? 0 : timeout_ms);
       if(what < 0) {
         /* fatal error */
         failf(data, "select/poll on SSL/TLS socket, errno: %d", SOCKERRNO);
@@ -959,8 +972,7 @@ schannel_send(struct connectdata *conn, int sockindex,
         break;
       }
 
-      what = Curl_socket_ready(CURL_SOCKET_BAD, conn->sock[sockindex],
-                               timeleft);
+      what = SOCKET_WRITABLE(conn->sock[sockindex], timeleft);
       if(what < 0) {
         /* fatal error */
         failf(conn->data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
diff --git a/Utilities/cmcurl/lib/vtls/vtls.c b/Utilities/cmcurl/lib/vtls/vtls.c
index 3863777..56a8823 100644
--- a/Utilities/cmcurl/lib/vtls/vtls.c
+++ b/Utilities/cmcurl/lib/vtls/vtls.c
@@ -61,7 +61,7 @@
 #include "vtls.h" /* generic SSL protos etc */
 #include "slist.h"
 #include "sendf.h"
-#include "rawstr.h"
+#include "strcase.h"
 #include "url.h"
 #include "progress.h"
 #include "share.h"
@@ -84,7 +84,7 @@ static bool safe_strequal(char* str1, char* str2)
 {
   if(str1 && str2)
     /* both pointers point to something then compare them */
-    return (0 != Curl_raw_equal(str1, str2)) ? TRUE : FALSE;
+    return (0 != strcasecompare(str1, str2)) ? TRUE : FALSE;
   else
     /* if both pointers are NULL then treat them as equal */
     return (!str1 && !str2) ? TRUE : FALSE;
@@ -100,8 +100,6 @@ Curl_ssl_config_matches(struct ssl_config_data* data,
      safe_strequal(data->CApath, needle->CApath) &&
      safe_strequal(data->CAfile, needle->CAfile) &&
      safe_strequal(data->clientcert, needle->clientcert) &&
-     safe_strequal(data->random_file, needle->random_file) &&
-     safe_strequal(data->egdsocket, needle->egdsocket) &&
      safe_strequal(data->cipher_list, needle->cipher_list))
     return TRUE;
 
@@ -392,14 +390,15 @@ bool Curl_ssl_getsessionid(struct connectdata *conn,
     if(!check->sessionid)
       /* not session ID means blank entry */
       continue;
-    if(Curl_raw_equal(conn->host.name, check->name) &&
+    if(strcasecompare(conn->host.name, check->name) &&
        ((!conn->bits.conn_to_host && !check->conn_to_host) ||
-         (conn->bits.conn_to_host && check->conn_to_host &&
-           Curl_raw_equal(conn->conn_to_host.name, check->conn_to_host))) &&
+        (conn->bits.conn_to_host && check->conn_to_host &&
+         strcasecompare(conn->conn_to_host.name, check->conn_to_host))) &&
        ((!conn->bits.conn_to_port && check->conn_to_port == -1) ||
-         (conn->bits.conn_to_port && check->conn_to_port != -1 &&
-           conn->conn_to_port == check->conn_to_port)) &&
+        (conn->bits.conn_to_port && check->conn_to_port != -1 &&
+         conn->conn_to_port == check->conn_to_port)) &&
        (conn->remote_port == check->remote_port) &&
+       strcasecompare(conn->handler->scheme, check->scheme) &&
        Curl_ssl_config_matches(&conn->ssl_config, &check->ssl_config)) {
       /* yes, we have a session ID! */
       (*general_age)++;          /* increase general age */
@@ -530,6 +529,7 @@ CURLcode Curl_ssl_addsessionid(struct connectdata *conn,
   store->conn_to_host = clone_conn_to_host; /* clone connect to host name */
   store->conn_to_port = conn_to_port; /* connect to port number */
   store->remote_port = conn->remote_port; /* port number */
+  store->scheme = conn->handler->scheme;
 
   if(!Curl_clone_ssl_config(&conn->ssl_config, &store->ssl_config)) {
     store->sessionid = NULL; /* let caller free sessionid */
diff --git a/Utilities/cmcurl/lib/x509asn1.c b/Utilities/cmcurl/lib/x509asn1.c
index e17bcd9..74a511b 100644
--- a/Utilities/cmcurl/lib/x509asn1.c
+++ b/Utilities/cmcurl/lib/x509asn1.c
@@ -27,7 +27,7 @@
 
 #include <curl/curl.h>
 #include "urldata.h"
-#include "strequal.h"
+#include "strcase.h"
 #include "hostcheck.h"
 #include "vtls/vtls.h"
 #include "sendf.h"
@@ -178,7 +178,7 @@ static const curl_OID * searchOID(const char * oid)
      Return the table entry pointer or NULL if not found. */
 
   for(op = OIDtable; op->numoid; op++)
-    if(!strcmp(op->numoid, oid) || curl_strequal(op->textoid, oid))
+    if(!strcmp(op->numoid, oid) || strcasecompare(op->textoid, oid))
       return op;
 
   return (const curl_OID *) NULL;
@@ -817,7 +817,7 @@ static void do_pubkey(struct Curl_easy * data, int certnum,
   /* Get the public key (single element). */
   Curl_getASN1Element(&pk, pubkey->beg + 1, pubkey->end);
 
-  if(curl_strequal(algo, "rsaEncryption")) {
+  if(strcasecompare(algo, "rsaEncryption")) {
     p = Curl_getASN1Element(&elem, pk.beg, pk.end);
     /* Compute key length. */
     for(q = elem.beg; !*q && q < elem.end; q++)
@@ -842,7 +842,7 @@ static void do_pubkey(struct Curl_easy * data, int certnum,
     Curl_getASN1Element(&elem, p, pk.end);
     do_pubkey_field(data, certnum, "rsa(e)", &elem);
   }
-  else if(curl_strequal(algo, "dsa")) {
+  else if(strcasecompare(algo, "dsa")) {
     p = Curl_getASN1Element(&elem, param->beg, param->end);
     do_pubkey_field(data, certnum, "dsa(p)", &elem);
     p = Curl_getASN1Element(&elem, p, param->end);
@@ -851,7 +851,7 @@ static void do_pubkey(struct Curl_easy * data, int certnum,
     do_pubkey_field(data, certnum, "dsa(g)", &elem);
     do_pubkey_field(data, certnum, "dsa(pub_key)", &pk);
   }
-  else if(curl_strequal(algo, "dhpublicnumber")) {
+  else if(strcasecompare(algo, "dhpublicnumber")) {
     p = Curl_getASN1Element(&elem, param->beg, param->end);
     do_pubkey_field(data, certnum, "dh(p)", &elem);
     Curl_getASN1Element(&elem, param->beg, param->end);
@@ -859,7 +859,7 @@ static void do_pubkey(struct Curl_easy * data, int certnum,
     do_pubkey_field(data, certnum, "dh(pub_key)", &pk);
   }
 #if 0 /* Patent-encumbered. */
-  else if(curl_strequal(algo, "ecPublicKey")) {
+  else if(strcasecompare(algo, "ecPublicKey")) {
     /* Left TODO. */
   }
 #endif
diff --git a/Utilities/cmlibarchive/libarchive/archive_random.c b/Utilities/cmlibarchive/libarchive/archive_random.c
index a20b9b1..fcea6c6 100644
--- a/Utilities/cmlibarchive/libarchive/archive_random.c
+++ b/Utilities/cmlibarchive/libarchive/archive_random.c
@@ -222,7 +222,7 @@ arc4_stir(void)
 	 * Discard early keystream, as per recommendations in:
 	 * "(Not So) Random Shuffles of RC4" by Ilya Mironov.
 	 */
-	for (i = 0; i < 1024; i++)
+	for (i = 0; i < 3072; i++)
 		(void)arc4_getbyte();
 	arc4_count = 1600000;
 }
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c
index c50ba84..8df52c3 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c
@@ -850,29 +850,33 @@ zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
 		zip_entry->mode |= AE_IFREG;
 	}
 
-	if ((zip_entry->mode & AE_IFMT) == 0) {
-		/* Especially in streaming mode, we can end up
-		   here without having seen proper mode information.
-		   Guess from the filename. */
+	/* If the mode is totally empty, set some sane default. */
+	if (zip_entry->mode == 0) {
+		zip_entry->mode |= 0664;
+	}
+
+	/* Make sure that entries with a trailing '/' are marked as directories
+	 * even if the External File Attributes contains bogus values.  If this
+	 * is not a directory and there is no type, assume regularfile. */
+	if ((zip_entry->mode & AE_IFMT) != AE_IFDIR) {
+		int has_slash;
+
 		wp = archive_entry_pathname_w(entry);
 		if (wp != NULL) {
 			len = wcslen(wp);
-			if (len > 0 && wp[len - 1] == L'/')
-				zip_entry->mode |= AE_IFDIR;
-			else
-				zip_entry->mode |= AE_IFREG;
+			has_slash = len > 0 && wp[len - 1] == L'/';
 		} else {
 			cp = archive_entry_pathname(entry);
 			len = (cp != NULL)?strlen(cp):0;
-			if (len > 0 && cp[len - 1] == '/')
-				zip_entry->mode |= AE_IFDIR;
-			else
-				zip_entry->mode |= AE_IFREG;
+			has_slash = len > 0 && cp[len - 1] == '/';
 		}
-		if (zip_entry->mode == AE_IFDIR) {
-			zip_entry->mode |= 0775;
-		} else if (zip_entry->mode == AE_IFREG) {
-			zip_entry->mode |= 0664;
+		/* Correct file type as needed. */
+		if (has_slash) {
+			zip_entry->mode &= ~AE_IFMT;
+			zip_entry->mode |= AE_IFDIR;
+			zip_entry->mode |= 0111;
+		} else if ((zip_entry->mode & AE_IFMT) == 0) {
+			zip_entry->mode |= AE_IFREG;
 		}
 	}
 
diff --git a/Utilities/cmlibrhash/.gitattributes b/Utilities/cmlibrhash/.gitattributes
new file mode 100644
index 0000000..562b12e
--- /dev/null
+++ b/Utilities/cmlibrhash/.gitattributes
@@ -0,0 +1 @@
+* -whitespace
diff --git a/Utilities/cmlibrhash/CMakeLists.txt b/Utilities/cmlibrhash/CMakeLists.txt
new file mode 100644
index 0000000..aa28055
--- /dev/null
+++ b/Utilities/cmlibrhash/CMakeLists.txt
@@ -0,0 +1,40 @@
+project(librhash C)
+
+# 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 STREQUAL "PathScale")
+  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -woffall")
+endif()
+
+set(librhash_sources
+  librhash/algorithms.c
+  librhash/algorithms.h
+  librhash/byte_order.c
+  librhash/byte_order.h
+  librhash/hex.c
+  librhash/hex.h
+  librhash/md5.c
+  librhash/md5.h
+  librhash/rhash.c
+  librhash/rhash.h
+  librhash/sha1.c
+  librhash/sha1.h
+  librhash/sha256.c
+  librhash/sha256.h
+  librhash/sha3.c
+  librhash/sha3.h
+  librhash/sha512.c
+  librhash/sha512.h
+  librhash/ustd.h
+  librhash/util.h
+  )
+
+include_directories(
+  ${KWSYS_HEADER_ROOT}
+  )
+
+add_library(cmlibrhash ${librhash_sources})
+
+install(FILES COPYING README DESTINATION ${CMAKE_DOC_DIR}/cmlibrhash)
diff --git a/Utilities/cmlibrhash/COPYING b/Utilities/cmlibrhash/COPYING
new file mode 100644
index 0000000..bf65ee1
--- /dev/null
+++ b/Utilities/cmlibrhash/COPYING
@@ -0,0 +1,15 @@
+
+                                RHash License
+
+Copyright (c) 2005-2014 Aleksey Kravchenko <rhash.admin at gmail.com>
+
+Permission is hereby granted, free of charge,  to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction,  including without limitation the rights
+to  use,  copy,  modify,  merge, publish, distribute, sublicense, and/or sell
+copies  of  the Software,  and  to permit  persons  to whom  the Software  is
+furnished to do so.
+
+The Software  is distributed in the hope that it will be useful,  but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE.  Use  this  program  at  your  own  risk!
diff --git a/Utilities/cmlibrhash/README b/Utilities/cmlibrhash/README
new file mode 100644
index 0000000..4ea492f
--- /dev/null
+++ b/Utilities/cmlibrhash/README
@@ -0,0 +1,7 @@
+                       === Notes on RHash License ===
+
+The RHash program and LibRHash library are distributed under  RHash License,
+see the COPYING file for details.  In particular,  the program,  the library
+and  source code  can be  used  free of charge  under  the  MIT,  BSD,  GPL,
+commercial or freeware license without additional restrictions.  In the case
+the OSI-approved license is required the  MIT license should be used.
diff --git a/Utilities/cmlibrhash/librhash/algorithms.c b/Utilities/cmlibrhash/librhash/algorithms.c
new file mode 100644
index 0000000..fc01690
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/algorithms.c
@@ -0,0 +1,220 @@
+/* algorithms.c - the algorithms supported by the rhash library
+ *
+ * Copyright: 2011-2012 Aleksey Kravchenko <rhash.admin at gmail.com>
+ *
+ * Permission is hereby granted,  free of charge,  to any person  obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction,  including without limitation
+ * the rights to  use, copy, modify,  merge, publish, distribute, sublicense,
+ * and/or sell copies  of  the Software,  and to permit  persons  to whom the
+ * Software is furnished to do so.
+ *
+ * This program  is  distributed  in  the  hope  that it will be useful,  but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  Use this program  at  your own risk!
+ */
+
+#include <stdio.h>
+#include <assert.h>
+
+#include "byte_order.h"
+#include "rhash.h"
+#include "algorithms.h"
+
+/* header files of all supported hash sums */
+#if 0
+#include "aich.h"
+#include "crc32.h"
+#include "ed2k.h"
+#include "edonr.h"
+#include "gost.h"
+#include "has160.h"
+#include "md4.h"
+#endif
+#include "md5.h"
+#if 0
+#include "ripemd-160.h"
+#include "snefru.h"
+#endif
+#include "sha1.h"
+#include "sha256.h"
+#include "sha512.h"
+#include "sha3.h"
+#if 0
+#include "tiger.h"
+#include "tth.h"
+#include "whirlpool.h"
+#endif
+
+#ifdef USE_OPENSSL
+/* note: BTIH and AICH depends on the used SHA1 algorithm */
+# define NEED_OPENSSL_INIT (RHASH_MD4 | RHASH_MD5 | \
+	RHASH_SHA1 | RHASH_SHA224 | RHASH_SHA256 | RHASH_SHA384 | RHASH_SHA512 | \
+	RHASH_BTIH | RHASH_AICH | RHASH_RIPEMD160 | RHASH_WHIRLPOOL)
+#else
+# define NEED_OPENSSL_INIT 0
+#endif /* USE_OPENSSL */
+#ifdef GENERATE_GOST_LOOKUP_TABLE
+# define NEED_GOST_INIT (RHASH_GOST | RHASH_GOST_CRYPTOPRO)
+#else
+# define NEED_GOST_INIT 0
+#endif /* GENERATE_GOST_LOOKUP_TABLE */
+#ifdef GENERATE_CRC32_TABLE
+# define NEED_CRC32_INIT RHASH_CRC32
+#else
+# define NEED_CRC32_INIT 0
+#endif /* GENERATE_CRC32_TABLE */
+
+#define RHASH_NEED_INIT_ALG (NEED_CRC32_INIT | NEED_GOST_INIT | NEED_OPENSSL_INIT)
+unsigned rhash_uninitialized_algorithms = RHASH_NEED_INIT_ALG;
+
+rhash_hash_info* rhash_info_table = rhash_hash_info_default;
+int rhash_info_size = RHASH_HASH_COUNT;
+
+#if 0
+static void rhash_crc32_init(uint32_t* crc32);
+static void rhash_crc32_update(uint32_t* crc32, const unsigned char* msg, size_t size);
+static void rhash_crc32_final(uint32_t* crc32, unsigned char* result);
+#endif
+
+#if 0
+rhash_info info_crc32 = { RHASH_CRC32, F_BE32, 4, "CRC32", "crc32" };
+rhash_info info_md4 = { RHASH_MD4, F_LE32, 16, "MD4", "md4" };
+#endif
+rhash_info info_md5 = { RHASH_MD5, F_LE32, 16, "MD5", "md5" };
+rhash_info info_sha1 = { RHASH_SHA1,      F_BE32, 20, "SHA1", "sha1" };
+#if 0
+rhash_info info_tiger = { RHASH_TIGER,    F_LE64, 24, "TIGER", "tiger" };
+rhash_info info_tth  = { RHASH_TTH,       F_BS32, 24, "TTH", "tree:tiger" };
+rhash_info info_btih = { RHASH_BTIH,      0, 20, "BTIH", "btih" };
+rhash_info info_ed2k = { RHASH_ED2K,      F_LE32, 16, "ED2K", "ed2k" };
+rhash_info info_aich = { RHASH_AICH,      F_BS32, 20, "AICH", "aich" };
+rhash_info info_whirlpool = { RHASH_WHIRLPOOL, F_BE64, 64, "WHIRLPOOL", "whirlpool" };
+rhash_info info_rmd160 = { RHASH_RIPEMD160,  F_LE32, 20, "RIPEMD-160", "ripemd160" };
+rhash_info info_gost =   { RHASH_GOST,       F_LE32, 32, "GOST", "gost" };
+rhash_info info_gostpro = { RHASH_GOST_CRYPTOPRO, F_LE32, 32, "GOST-CRYPTOPRO", "gost-cryptopro" };
+rhash_info info_has160 = { RHASH_HAS160,     F_LE32, 20, "HAS-160", "has160" };
+rhash_info info_snf128 = { RHASH_SNEFRU128,  F_BE32, 16, "SNEFRU-128", "snefru128" };
+rhash_info info_snf256 = { RHASH_SNEFRU256,  F_BE32, 32, "SNEFRU-256", "snefru256" };
+#endif
+rhash_info info_sha224 = { RHASH_SHA224,     F_BE32, 28, "SHA-224", "sha224" };
+rhash_info info_sha256 = { RHASH_SHA256,     F_BE32, 32, "SHA-256", "sha256" };
+rhash_info info_sha384 = { RHASH_SHA384,     F_BE64, 48, "SHA-384", "sha384" };
+rhash_info info_sha512 = { RHASH_SHA512,     F_BE64, 64, "SHA-512", "sha512" };
+#if 0
+rhash_info info_edr256 = { RHASH_EDONR256,   F_LE32, 32, "EDON-R256", "edon-r256" };
+rhash_info info_edr512 = { RHASH_EDONR512,   F_LE64, 64, "EDON-R512", "edon-r512" };
+#endif
+rhash_info info_sha3_224 = { RHASH_SHA3_224, F_LE64, 28, "SHA3-224", "sha3-224" };
+rhash_info info_sha3_256 = { RHASH_SHA3_256, F_LE64, 32, "SHA3-256", "sha3-256" };
+rhash_info info_sha3_384 = { RHASH_SHA3_384, F_LE64, 48, "SHA3-384", "sha3-384" };
+rhash_info info_sha3_512 = { RHASH_SHA3_512, F_LE64, 64, "SHA3-512", "sha3-512" };
+
+/* some helper macros */
+#define dgshft(name) (((char*)&((name##_ctx*)0)->hash) - (char*)0)
+#define dgshft2(name, field) (((char*)&((name##_ctx*)0)->field) - (char*)0)
+#define ini(name) ((pinit_t)(name##_init))
+#define upd(name) ((pupdate_t)(name##_update))
+#define fin(name) ((pfinal_t)(name##_final))
+#define iuf(name) ini(name), upd(name), fin(name)
+#define diuf(name) dgshft(name), ini(name), upd(name), fin(name)
+
+/* information about all hashes */
+rhash_hash_info rhash_hash_info_default[RHASH_HASH_COUNT] =
+{
+#if 0
+	{ &info_crc32, sizeof(uint32_t), 0, iuf(rhash_crc32), 0 }, /* 32 bit */
+	{ &info_md4, sizeof(md4_ctx), dgshft(md4), iuf(rhash_md4), 0 }, /* 128 bit */
+#endif
+	{ &info_md5, sizeof(md5_ctx), dgshft(md5), iuf(rhash_md5), 0 }, /* 128 bit */
+	{ &info_sha1, sizeof(sha1_ctx), dgshft(sha1), iuf(rhash_sha1), 0 }, /* 160 bit */
+#if 0
+	{ &info_tiger, sizeof(tiger_ctx), dgshft(tiger), iuf(rhash_tiger), 0 }, /* 192 bit */
+	{ &info_tth, sizeof(tth_ctx), dgshft2(tth, tiger.hash), iuf(rhash_tth), 0 }, /* 192 bit */
+	{ &info_ed2k, sizeof(ed2k_ctx), dgshft2(ed2k, md4_context_inner.hash), iuf(rhash_ed2k), 0 }, /* 128 bit */
+	{ &info_aich, sizeof(aich_ctx), dgshft2(aich, sha1_context.hash), iuf(rhash_aich), (pcleanup_t)rhash_aich_cleanup }, /* 160 bit */
+	{ &info_whirlpool, sizeof(whirlpool_ctx), dgshft(whirlpool), iuf(rhash_whirlpool), 0 }, /* 512 bit */
+	{ &info_rmd160, sizeof(ripemd160_ctx), dgshft(ripemd160), iuf(rhash_ripemd160), 0 }, /* 160 bit */
+	{ &info_gost, sizeof(gost_ctx), dgshft(gost), iuf(rhash_gost), 0 }, /* 256 bit */
+	{ &info_gostpro, sizeof(gost_ctx), dgshft(gost), ini(rhash_gost_cryptopro), upd(rhash_gost), fin(rhash_gost), 0 }, /* 256 bit */
+	{ &info_has160, sizeof(has160_ctx), dgshft(has160), iuf(rhash_has160), 0 }, /* 160 bit */
+	{ &info_snf128, sizeof(snefru_ctx), dgshft(snefru), ini(rhash_snefru128), upd(rhash_snefru), fin(rhash_snefru), 0 }, /* 128 bit */
+	{ &info_snf256, sizeof(snefru_ctx), dgshft(snefru), ini(rhash_snefru256), upd(rhash_snefru), fin(rhash_snefru), 0 }, /* 256 bit */
+#endif
+	{ &info_sha224, sizeof(sha256_ctx), dgshft(sha256), ini(rhash_sha224), upd(rhash_sha256), fin(rhash_sha256), 0 }, /* 224 bit */
+	{ &info_sha256, sizeof(sha256_ctx), dgshft(sha256), iuf(rhash_sha256), 0 },  /* 256 bit */
+	{ &info_sha384, sizeof(sha512_ctx), dgshft(sha512), ini(rhash_sha384), upd(rhash_sha512), fin(rhash_sha512), 0 }, /* 384 bit */
+	{ &info_sha512, sizeof(sha512_ctx), dgshft(sha512), iuf(rhash_sha512), 0 },  /* 512 bit */
+#if 0
+	{ &info_edr256, sizeof(edonr_ctx), dgshft2(edonr, u.data256.hash) + 32, iuf(rhash_edonr256), 0 },  /* 256 bit */
+	{ &info_edr512, sizeof(edonr_ctx), dgshft2(edonr, u.data512.hash) + 64, iuf(rhash_edonr512), 0 },  /* 512 bit */
+#endif
+	{ &info_sha3_224, sizeof(sha3_ctx), dgshft(sha3), ini(rhash_sha3_224), upd(rhash_sha3), fin(rhash_sha3), 0 }, /* 224 bit */
+	{ &info_sha3_256, sizeof(sha3_ctx), dgshft(sha3), ini(rhash_sha3_256), upd(rhash_sha3), fin(rhash_sha3), 0 }, /* 256 bit */
+	{ &info_sha3_384, sizeof(sha3_ctx), dgshft(sha3), ini(rhash_sha3_384), upd(rhash_sha3), fin(rhash_sha3), 0 }, /* 384 bit */
+	{ &info_sha3_512, sizeof(sha3_ctx), dgshft(sha3), ini(rhash_sha3_512), upd(rhash_sha3), fin(rhash_sha3), 0 }, /* 512 bit */
+};
+
+/**
+ * Initialize requested algorithms.
+ */
+void rhash_init_algorithms(unsigned mask)
+{
+	(void)mask; /* unused now */
+
+	/* verify that RHASH_HASH_COUNT is the index of the major bit of RHASH_ALL_HASHES */
+	assert(1 == (RHASH_ALL_HASHES >> (RHASH_HASH_COUNT - 1)));
+
+#ifdef GENERATE_CRC32_TABLE
+	rhash_crc32_init_table();
+#endif
+#ifdef GENERATE_GOST_LOOKUP_TABLE
+	rhash_gost_init_table();
+#endif
+	rhash_uninitialized_algorithms = 0;
+}
+
+#if 0
+/* CRC32 helper functions */
+
+/**
+ * Initialize crc32 hash.
+ *
+ * @param crc32 pointer to the hash to initialize
+ */
+static void rhash_crc32_init(uint32_t* crc32)
+{
+	*crc32 = 0; /* note: context size is sizeof(uint32_t) */
+}
+
+/**
+ * Calculate message CRC32 hash.
+ * Can be called repeatedly with chunks of the message to be hashed.
+ *
+ * @param crc32 pointer to the hash
+ * @param msg message chunk
+ * @param size length of the message chunk
+ */
+static void rhash_crc32_update(uint32_t* crc32, const unsigned char* msg, size_t size)
+{
+	*crc32 = rhash_get_crc32(*crc32, msg, size);
+}
+
+/**
+ * Store calculated hash into the given array.
+ *
+ * @param crc32 pointer to the current hash value
+ * @param result calculated hash in binary form
+ */
+static void rhash_crc32_final(uint32_t* crc32, unsigned char* result)
+{
+#if defined(CPU_IA32) || defined(CPU_X64)
+	/* intel CPUs support assigment with non 32-bit aligned pointers */
+	*(unsigned*)result = be2me_32(*crc32);
+#else
+	/* correct saving BigEndian integer on all archs */
+	result[0] = (unsigned char)(*crc32 >> 24), result[1] = (unsigned char)(*crc32 >> 16);
+	result[2] = (unsigned char)(*crc32 >> 8), result[3] = (unsigned char)(*crc32);
+#endif
+}
+#endif
diff --git a/Utilities/cmlibrhash/librhash/algorithms.h b/Utilities/cmlibrhash/librhash/algorithms.h
new file mode 100644
index 0000000..4db2517
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/algorithms.h
@@ -0,0 +1,120 @@
+/* algorithms.h - rhash library algorithms */
+#ifndef RHASH_ALGORITHMS_H
+#define RHASH_ALGORITHMS_H
+
+#include <stddef.h> /* for ptrdiff_t */
+#include "rhash.h"
+#include "byte_order.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef RHASH_API
+/* modifier for RHash library functions */
+# define RHASH_API
+#endif
+
+typedef void (*pinit_t)(void*);
+typedef void (*pupdate_t)(void *ctx, const void* msg, size_t size);
+typedef void (*pfinal_t)(void*, unsigned char*);
+typedef void (*pcleanup_t)(void*);
+
+/**
+ * Information about a hash function
+ */
+typedef struct rhash_hash_info
+{
+	rhash_info *info;
+	size_t context_size;
+	ptrdiff_t  digest_diff;
+	pinit_t    init;
+	pupdate_t  update;
+	pfinal_t   final;
+	pcleanup_t cleanup;
+} rhash_hash_info;
+
+/**
+ * Information on a hash function and its context
+ */
+typedef struct rhash_vector_item
+{
+	struct rhash_hash_info* hash_info;
+	void *context;
+} rhash_vector_item;
+
+/**
+ * The rhash context containing contexts for several hash functions
+ */
+typedef struct rhash_context_ext
+{
+	struct rhash_context rc;
+	unsigned hash_vector_size; /* number of contained hash sums */
+	unsigned flags;
+	unsigned state;
+	void *callback, *callback_data;
+	void *bt_ctx;
+	rhash_vector_item vector[1]; /* contexts of contained hash sums */
+} rhash_context_ext;
+
+extern rhash_hash_info rhash_hash_info_default[RHASH_HASH_COUNT];
+extern rhash_hash_info* rhash_info_table;
+extern int rhash_info_size;
+extern unsigned rhash_uninitialized_algorithms;
+
+extern rhash_info info_crc32;
+extern rhash_info info_md4;
+extern rhash_info info_md5;
+extern rhash_info info_sha1;
+extern rhash_info info_tiger;
+extern rhash_info info_tth ;
+extern rhash_info info_btih;
+extern rhash_info info_ed2k;
+extern rhash_info info_aich;
+extern rhash_info info_whirlpool;
+extern rhash_info info_rmd160;
+extern rhash_info info_gost;
+extern rhash_info info_gostpro;
+extern rhash_info info_has160;
+extern rhash_info info_snf128;
+extern rhash_info info_snf256;
+extern rhash_info info_sha224;
+extern rhash_info info_sha256;
+extern rhash_info info_sha384;
+extern rhash_info info_sha512;
+extern rhash_info info_sha3_224;
+extern rhash_info info_sha3_256;
+extern rhash_info info_sha3_384;
+extern rhash_info info_sha3_512;
+extern rhash_info info_edr256;
+extern rhash_info info_edr512;
+
+/* rhash_info flags */
+#define F_BS32 1   /* default output in base32 */
+#define F_SWAP32 2 /* Big endian flag */
+#define F_SWAP64 4
+
+/* define endianness flags */
+#ifndef CPU_BIG_ENDIAN
+#define F_LE32 0
+#define F_LE64 0
+#define F_BE32 F_SWAP32
+#define F_BE64 F_SWAP64
+#else
+#define F_LE32 F_SWAP32
+#define F_LE64 F_SWAP64
+#define F_BE32 0
+#define F_BE64 0
+#endif
+
+void rhash_init_algorithms(unsigned mask);
+
+#if defined(OPENSSL_RUNTIME) && !defined(USE_OPENSSL)
+# define USE_OPENSSL
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* RHASH_ALGORITHMS_H */
diff --git a/Utilities/cmlibrhash/librhash/byte_order.c b/Utilities/cmlibrhash/librhash/byte_order.c
new file mode 100644
index 0000000..8ce6fc8
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/byte_order.c
@@ -0,0 +1,150 @@
+/* byte_order.c - byte order related platform dependent routines,
+ *
+ * Copyright: 2008-2012 Aleksey Kravchenko <rhash.admin at gmail.com>
+ *
+ * Permission is hereby granted,  free of charge,  to any person  obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction,  including without limitation
+ * the rights to  use, copy, modify,  merge, publish, distribute, sublicense,
+ * and/or sell copies  of  the Software,  and to permit  persons  to whom the
+ * Software is furnished to do so.
+ *
+ * This program  is  distributed  in  the  hope  that it will be useful,  but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  Use this program  at  your own risk!
+ */
+#include "byte_order.h"
+
+#if !(__GNUC__ >= 4 || (__GNUC__ ==3 && __GNUC_MINOR__ >= 4)) /* if !GCC or GCC < 4.3 */
+
+#  if _MSC_VER >= 1300 && (_M_IX86 || _M_AMD64 || _M_IA64) /* if MSVC++ >= 2002 on x86/x64 */
+#  include <intrin.h>
+#  pragma intrinsic(_BitScanForward)
+
+/**
+ * Returns index of the trailing bit of x.
+ *
+ * @param x the number to process
+ * @return zero-based index of the trailing bit
+ */
+unsigned rhash_ctz(unsigned x)
+{
+	unsigned long index;
+	unsigned char isNonzero = _BitScanForward(&index, x); /* MSVC intrinsic */
+	return (isNonzero ? (unsigned)index : 0);
+}
+#  else /* _MSC_VER >= 1300... */
+
+/**
+ * Returns index of the trailing bit of a 32-bit number.
+ * This is a plain C equivalent for GCC __builtin_ctz() bit scan.
+ *
+ * @param x the number to process
+ * @return zero-based index of the trailing bit
+ */
+unsigned rhash_ctz(unsigned x)
+{
+	/* array for conversion to bit position */
+	static unsigned char bit_pos[32] =  {
+		0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
+		31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
+	};
+
+	/* The De Bruijn bit-scan was devised in 1997, according to Donald Knuth
+	 * by Martin Lauter. The constant 0x077CB531UL is a De Bruijn sequence,
+	 * which produces a unique pattern of bits into the high 5 bits for each
+	 * possible bit position that it is multiplied against.
+	 * See http://graphics.stanford.edu/~seander/bithacks.html
+	 * and http://chessprogramming.wikispaces.com/BitScan */
+	return (unsigned)bit_pos[((uint32_t)((x & -x) * 0x077CB531U)) >> 27];
+}
+#  endif /* _MSC_VER >= 1300... */
+#endif /* !(GCC >= 4.3) */
+
+/**
+ * Copy a memory block with simultaneous exchanging byte order.
+ * The byte order is changed from little-endian 32-bit integers
+ * to big-endian (or vice-versa).
+ *
+ * @param to the pointer where to copy memory block
+ * @param index the index to start writing from
+ * @param from  the source block to copy
+ * @param length length of the memory block
+ */
+void rhash_swap_copy_str_to_u32(void* to, int index, const void* from, size_t length)
+{
+	/* if all pointers and length are 32-bits aligned */
+	if ( 0 == (( (int)((char*)to - (char*)0) | ((char*)from - (char*)0) | index | length ) & 3) ) {
+		/* copy memory as 32-bit words */
+		const uint32_t* src = (const uint32_t*)from;
+		const uint32_t* end = (const uint32_t*)((const char*)src + length);
+		uint32_t* dst = (uint32_t*)((char*)to + index);
+		while (src < end) *(dst++) = bswap_32( *(src++) );
+	} else {
+		const char* src = (const char*)from;
+		for (length += index; (size_t)index < length; index++) ((char*)to)[index ^ 3] = *(src++);
+	}
+}
+
+/**
+ * Copy a memory block with changed byte order.
+ * The byte order is changed from little-endian 64-bit integers
+ * to big-endian (or vice-versa).
+ *
+ * @param to     the pointer where to copy memory block
+ * @param index  the index to start writing from
+ * @param from   the source block to copy
+ * @param length length of the memory block
+ */
+void rhash_swap_copy_str_to_u64(void* to, int index, const void* from, size_t length)
+{
+	/* if all pointers and length are 64-bits aligned */
+	if ( 0 == (( (int)((char*)to - (char*)0) | ((char*)from - (char*)0) | index | length ) & 7) ) {
+		/* copy aligned memory block as 64-bit integers */
+		const uint64_t* src = (const uint64_t*)from;
+		const uint64_t* end = (const uint64_t*)((const char*)src + length);
+		uint64_t* dst = (uint64_t*)((char*)to + index);
+		while (src < end) *(dst++) = bswap_64( *(src++) );
+	} else {
+		const char* src = (const char*)from;
+		for (length += index; (size_t)index < length; index++) ((char*)to)[index ^ 7] = *(src++);
+	}
+}
+
+/**
+ * Copy data from a sequence of 64-bit words to a binary string of given length,
+ * while changing byte order.
+ *
+ * @param to     the binary string to receive data
+ * @param from   the source sequence of 64-bit words
+ * @param length the size in bytes of the data being copied
+ */
+void rhash_swap_copy_u64_to_str(void* to, const void* from, size_t length)
+{
+	/* if all pointers and length are 64-bits aligned */
+	if ( 0 == (( (int)((char*)to - (char*)0) | ((char*)from - (char*)0) | length ) & 7) ) {
+		/* copy aligned memory block as 64-bit integers */
+		const uint64_t* src = (const uint64_t*)from;
+		const uint64_t* end = (const uint64_t*)((const char*)src + length);
+		uint64_t* dst = (uint64_t*)to;
+		while (src < end) *(dst++) = bswap_64( *(src++) );
+	} else {
+		size_t index;
+		char* dst = (char*)to;
+		for (index = 0; index < length; index++) *(dst++) = ((char*)from)[index ^ 7];
+	}
+}
+
+/**
+ * Exchange byte order in the given array of 32-bit integers.
+ *
+ * @param arr    the array to process
+ * @param length array length
+ */
+void rhash_u32_mem_swap(unsigned *arr, int length)
+{
+	unsigned* end = arr + length;
+	for (; arr < end; arr++) {
+		*arr = bswap_32(*arr);
+	}
+}
diff --git a/Utilities/cmlibrhash/librhash/byte_order.h b/Utilities/cmlibrhash/librhash/byte_order.h
new file mode 100644
index 0000000..d34a020
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/byte_order.h
@@ -0,0 +1,156 @@
+/* byte_order.h */
+#ifndef BYTE_ORDER_H
+#define BYTE_ORDER_H
+#include "ustd.h"
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* if x86 compatible cpu */
+#if defined(i386) || defined(__i386__) || defined(__i486__) || \
+	defined(__i586__) || defined(__i686__) || defined(__pentium__) || \
+	defined(__pentiumpro__) || defined(__pentium4__) || \
+	defined(__nocona__) || defined(prescott) || defined(__core2__) || \
+	defined(__k6__) || defined(__k8__) || defined(__athlon__) || \
+	defined(__amd64) || defined(__amd64__) || \
+	defined(__x86_64) || defined(__x86_64__) || defined(_M_IX86) || \
+	defined(_M_AMD64) || defined(_M_IA64) || defined(_M_X64)
+/* detect if x86-64 instruction set is supported */
+# if defined(_LP64) || defined(__LP64__) || defined(__x86_64) || \
+	defined(__x86_64__) || defined(_M_AMD64) || defined(_M_X64)
+#  define CPU_X64
+# else
+#  define CPU_IA32
+# endif
+#endif
+
+
+/* detect CPU endianness */
+#include <cm_kwiml.h>
+#if KWIML_ABI_ENDIAN_ID == KWIML_ABI_ENDIAN_ID_LITTLE
+# define CPU_LITTLE_ENDIAN
+# define IS_BIG_ENDIAN 0
+# define IS_LITTLE_ENDIAN 1
+#elif KWIML_ABI_ENDIAN_ID == KWIML_ABI_ENDIAN_ID_BIG
+# define CPU_BIG_ENDIAN
+# define IS_BIG_ENDIAN 1
+# define IS_LITTLE_ENDIAN 0
+#else
+# error "Can't detect CPU architechture"
+#endif
+
+#define IS_ALIGNED_32(p) (0 == (3 & ((const char*)(p) - (const char*)0)))
+#define IS_ALIGNED_64(p) (0 == (7 & ((const char*)(p) - (const char*)0)))
+
+#if defined(_MSC_VER)
+#define ALIGN_ATTR(n) __declspec(align(n))
+#elif defined(__GNUC__)
+#define ALIGN_ATTR(n) __attribute__((aligned (n)))
+#else
+#define ALIGN_ATTR(n) /* nothing */
+#endif
+
+
+#if defined(_MSC_VER) || defined(__BORLANDC__)
+#define I64(x) x##ui64
+#else
+#define I64(x) x##LL
+#endif
+
+/* convert a hash flag to index */
+#if __GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) /* GCC < 3.4 */
+# define rhash_ctz(x) __builtin_ctz(x)
+#else
+unsigned rhash_ctz(unsigned); /* define as function */
+#endif
+
+void rhash_swap_copy_str_to_u32(void* to, int index, const void* from, size_t length);
+void rhash_swap_copy_str_to_u64(void* to, int index, const void* from, size_t length);
+void rhash_swap_copy_u64_to_str(void* to, const void* from, size_t length);
+void rhash_u32_mem_swap(unsigned *p, int length_in_u32);
+
+#ifndef __has_builtin
+# define __has_builtin(x) 0
+#endif
+
+/* define bswap_32 */
+#if defined(__GNUC__) && defined(CPU_IA32) && !defined(__i386__)
+/* for intel x86 CPU */
+static inline uint32_t bswap_32(uint32_t x) {
+	__asm("bswap\t%0" : "=r" (x) : "0" (x));
+	return x;
+}
+#elif defined(__GNUC__)  && (__GNUC__ >= 4) && (__GNUC__ > 4 || __GNUC_MINOR__ >= 3)
+/* for GCC >= 4.3 */
+# define bswap_32(x) __builtin_bswap32(x)
+#elif defined(__clang__) && __has_builtin(__builtin_bswap32)
+# define bswap_32(x) __builtin_bswap32(x)
+#elif (_MSC_VER > 1300) && (defined(CPU_IA32) || defined(CPU_X64)) /* MS VC */
+# define bswap_32(x) _byteswap_ulong((unsigned long)x)
+#else
+/* general bswap_32 definition */
+static uint32_t bswap_32(uint32_t x) {
+	x = ((x << 8) & 0xFF00FF00) | ((x >> 8) & 0x00FF00FF);
+	return (x >> 16) | (x << 16);
+}
+#endif /* bswap_32 */
+
+#if defined(__GNUC__) && (__GNUC__ >= 4) && (__GNUC__ > 4 || __GNUC_MINOR__ >= 3)
+# define bswap_64(x) __builtin_bswap64(x)
+#elif defined(__clang__) && __has_builtin(__builtin_bswap64)
+# define bswap_64(x) __builtin_bswap64(x)
+#elif (_MSC_VER > 1300) && (defined(CPU_IA32) || defined(CPU_X64)) /* MS VC */
+# define bswap_64(x) _byteswap_uint64((__int64)x)
+#else
+static uint64_t bswap_64(uint64_t x) {
+	union {
+		uint64_t ll;
+		uint32_t l[2];
+	} w, r;
+	w.ll = x;
+	r.l[0] = bswap_32(w.l[1]);
+	r.l[1] = bswap_32(w.l[0]);
+	return r.ll;
+}
+#endif
+
+#ifdef CPU_BIG_ENDIAN
+# define be2me_32(x) (x)
+# define be2me_64(x) (x)
+# define le2me_32(x) bswap_32(x)
+# define le2me_64(x) bswap_64(x)
+
+# define be32_copy(to, index, from, length) memcpy((to) + (index), (from), (length))
+# define le32_copy(to, index, from, length) rhash_swap_copy_str_to_u32((to), (index), (from), (length))
+# define be64_copy(to, index, from, length) memcpy((to) + (index), (from), (length))
+# define le64_copy(to, index, from, length) rhash_swap_copy_str_to_u64((to), (index), (from), (length))
+# define me64_to_be_str(to, from, length) memcpy((to), (from), (length))
+# define me64_to_le_str(to, from, length) rhash_swap_copy_u64_to_str((to), (from), (length))
+
+#else /* CPU_BIG_ENDIAN */
+# define be2me_32(x) bswap_32(x)
+# define be2me_64(x) bswap_64(x)
+# define le2me_32(x) (x)
+# define le2me_64(x) (x)
+
+# define be32_copy(to, index, from, length) rhash_swap_copy_str_to_u32((to), (index), (from), (length))
+# define le32_copy(to, index, from, length) memcpy((to) + (index), (from), (length))
+# define be64_copy(to, index, from, length) rhash_swap_copy_str_to_u64((to), (index), (from), (length))
+# define le64_copy(to, index, from, length) memcpy((to) + (index), (from), (length))
+# define me64_to_be_str(to, from, length) rhash_swap_copy_u64_to_str((to), (from), (length))
+# define me64_to_le_str(to, from, length) memcpy((to), (from), (length))
+#endif /* CPU_BIG_ENDIAN */
+
+/* ROTL/ROTR macros rotate a 32/64-bit word left/right by n bits */
+#define ROTL32(dword, n) ((dword) << (n) ^ ((dword) >> (32 - (n))))
+#define ROTR32(dword, n) ((dword) >> (n) ^ ((dword) << (32 - (n))))
+#define ROTL64(qword, n) ((qword) << (n) ^ ((qword) >> (64 - (n))))
+#define ROTR64(qword, n) ((qword) >> (n) ^ ((qword) << (64 - (n))))
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* BYTE_ORDER_H */
diff --git a/Utilities/cmlibrhash/librhash/hex.c b/Utilities/cmlibrhash/librhash/hex.c
new file mode 100644
index 0000000..c941149
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/hex.c
@@ -0,0 +1,188 @@
+/* hex.c - conversion for hexadecimal and base32 strings.
+ *
+ * Copyright: 2008-2012 Aleksey Kravchenko <rhash.admin at gmail.com>
+ *
+ * Permission is hereby granted,  free of charge,  to any person  obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction,  including without limitation
+ * the rights to  use, copy, modify,  merge, publish, distribute, sublicense,
+ * and/or sell copies  of  the Software,  and to permit  persons  to whom the
+ * Software is furnished to do so.
+ *
+ * This program  is  distributed  in  the  hope  that it will be useful,  but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  Use this program  at  your own risk!
+ */
+#include <string.h>
+#include <ctype.h>
+#include "hex.h"
+
+/**
+* Convert a byte to a hexadecimal number. The result, consisting of two
+* hexadecimal digits is stored into a buffer.
+ *
+ * @param dest  the buffer to receive two symbols of hex representation
+ * @param byte the byte to decode
+ * @param upper_case flag to print string in uppercase
+ * @return pointer to the chararcter just after the written number (dest + 2)
+ */
+char* rhash_print_hex_byte(char *dest, const unsigned char byte, int upper_case)
+{
+	const char add = (upper_case ? 'A' - 10 : 'a' - 10);
+	unsigned char c = (byte >> 4) & 15;
+	*dest++ = (c > 9 ? c + add : c + '0');
+	c = byte & 15;
+	*dest++ = (c > 9 ? c + add : c + '0');
+	return dest;
+}
+
+/**
+ * Store hexadecimal representation of a binary string to given buffer.
+ *
+ * @param dest the buffer to receive hexadecimal representation
+ * @param src binary string
+ * @param len string length
+ * @param upper_case flag to print string in uppercase
+ */
+void rhash_byte_to_hex(char *dest, const unsigned char *src, unsigned len, int upper_case)
+{
+	while (len-- > 0) {
+		dest = rhash_print_hex_byte(dest, *src++, upper_case);
+	}
+	*dest = '\0';
+}
+
+/**
+ * Encode a binary string to base32.
+ *
+ * @param dest the buffer to store result
+ * @param src binary string
+ * @param len string length
+ * @param upper_case flag to print string in uppercase
+ */
+void rhash_byte_to_base32(char* dest, const unsigned char* src, unsigned len, int upper_case)
+{
+	const char a = (upper_case ? 'A' : 'a');
+	unsigned shift = 0;
+	unsigned char word;
+	const unsigned char* e = src + len;
+	while (src < e) {
+		if (shift > 3) {
+			word = (*src & (0xFF >> shift));
+			shift = (shift + 5) % 8;
+			word <<= shift;
+			if (src + 1 < e)
+				word |= *(src + 1) >> (8 - shift);
+			++src;
+		} else {
+			shift = (shift + 5) % 8;
+			word = ( *src >> ( (8 - shift) & 7 ) ) & 0x1F;
+			if (shift == 0) src++;
+		}
+		*dest++ = ( word < 26 ? word + a : word + '2' - 26 );
+	}
+	*dest = '\0';
+}
+
+/**
+ * Encode a binary string to base64.
+ * Encoded output length is always a multiple of 4 bytes.
+ *
+ * @param dest the buffer to store result
+ * @param src binary string
+ * @param len string length
+ */
+void rhash_byte_to_base64(char* dest, const unsigned char* src, unsigned len)
+{
+	static const char* tail = "0123456789+/";
+	unsigned shift = 0;
+	unsigned char word;
+	const unsigned char* e = src + len;
+	while (src < e) {
+		if (shift > 2) {
+			word = (*src & (0xFF >> shift));
+			shift = (shift + 6) % 8;
+			word <<= shift;
+			if (src + 1 < e)
+				word |= *(src + 1) >> (8 - shift);
+			++src;
+		} else {
+			shift = (shift + 6) % 8;
+			word = ( *src >> ( (8 - shift) & 7 ) ) & 0x3F;
+			if (shift == 0) src++;
+		}
+		*dest++ = ( word < 52 ? (word < 26 ? word + 'A' : word - 26 + 'a') : tail[word - 52]);
+	}
+	if (shift > 0) {
+		*dest++ = '=';
+		if (shift == 4) *dest++ = '=';
+	}
+	*dest = '\0';
+}
+
+/* unsafe characters are "<>{}[]%#/|\^~`@:;?=&+ */
+#define IS_GOOD_URL_CHAR(c) (isalnum((unsigned char)c) || strchr("$-_.!'(),", c))
+
+/**
+ * URL-encode a string.
+ *
+ * @param dst buffer to receive result or NULL to calculate
+ *    the lengths of encoded string
+ * @param filename the file name
+ * @return the length of the result string
+ */
+int rhash_urlencode(char *dst, const char *name)
+{
+	const char *start;
+	if (!dst) {
+		int len;
+		for (len = 0; *name; name++) len += (IS_GOOD_URL_CHAR(*name) ? 1 : 3);
+		return len;
+	}
+	/* encode URL as specified by RFC 1738 */
+	for (start = dst; *name; name++) {
+		if ( IS_GOOD_URL_CHAR(*name) ) {
+			*dst++ = *name;
+		} else {
+			*dst++ = '%';
+			dst = rhash_print_hex_byte(dst, *name, 'A');
+		}
+	}
+	*dst = 0;
+	return (int)(dst - start);
+}
+
+/**
+ * Print 64-bit number with trailing '\0' to a string buffer.
+ * if dst is NULL, then just return the length of the number.
+ *
+ * @param dst output buffer
+ * @param number the number to print
+ * @return length of the printed number (without trailing '\0')
+ */
+int rhash_sprintI64(char *dst, uint64_t number)
+{
+	/* The biggest number has 20 digits: 2^64 = 18 446 744 073 709 551 616 */
+	char buf[24], *p;
+	size_t length;
+
+	if (dst == NULL) {
+		/* just calculate the length of the number */
+		if (number == 0) return 1;
+		for (length = 0; number != 0; number /= 10) length++;
+		return (int)length;
+	}
+
+	p = buf + 23;
+	*p = '\0'; /* last symbol should be '\0' */
+	if (number == 0) {
+		*(--p) = '0';
+	} else {
+		for (; p >= buf && number != 0; number /= 10) {
+			*(--p) = '0' + (char)(number % 10);
+		}
+	}
+	length = buf + 23 - p;
+	memcpy(dst, p, length + 1);
+	return (int)length;
+}
diff --git a/Utilities/cmlibrhash/librhash/hex.h b/Utilities/cmlibrhash/librhash/hex.h
new file mode 100644
index 0000000..2b365e2
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/hex.h
@@ -0,0 +1,25 @@
+/* hex.h - conversion for hexadecimal and base32 strings. */
+#ifndef HEX_H
+#define HEX_H
+
+#include "ustd.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void rhash_byte_to_hex(char *dest, const unsigned char *src, unsigned len, int upper_case);
+void rhash_byte_to_base32(char* dest, const unsigned char* src, unsigned len, int upper_case);
+void rhash_byte_to_base64(char* dest, const unsigned char* src, unsigned len);
+char* rhash_print_hex_byte(char *dest, const unsigned char byte, int upper_case);
+int  rhash_urlencode(char *dst, const char *name);
+int  rhash_sprintI64(char *dst, uint64_t number);
+
+#define BASE32_LENGTH(bytes) (((bytes) * 8 + 4) / 5)
+#define BASE64_LENGTH(bytes) ((((bytes) + 2) / 3) * 4)
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* HEX_H */
diff --git a/Utilities/cmlibrhash/librhash/md5.c b/Utilities/cmlibrhash/librhash/md5.c
new file mode 100644
index 0000000..b20de45
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/md5.c
@@ -0,0 +1,236 @@
+/* md5.c - an implementation of the MD5 algorithm, based on RFC 1321.
+ *
+ * Copyright: 2007-2012 Aleksey Kravchenko <rhash.admin at gmail.com>
+ *
+ * Permission is hereby granted,  free of charge,  to any person  obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction,  including without limitation
+ * the rights to  use, copy, modify,  merge, publish, distribute, sublicense,
+ * and/or sell copies  of  the Software,  and to permit  persons  to whom the
+ * Software is furnished to do so.
+ *
+ * This program  is  distributed  in  the  hope  that it will be useful,  but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  Use this program  at  your own risk!
+ */
+
+#include <string.h>
+#include "byte_order.h"
+#include "md5.h"
+
+/**
+ * Initialize context before calculaing hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_md5_init(md5_ctx *ctx)
+{
+	ctx->length = 0;
+
+	/* initialize state */
+	ctx->hash[0] = 0x67452301;
+	ctx->hash[1] = 0xefcdab89;
+	ctx->hash[2] = 0x98badcfe;
+	ctx->hash[3] = 0x10325476;
+}
+
+/* First, define four auxiliary functions that each take as input
+ * three 32-bit words and returns a 32-bit word.*/
+
+/* F(x,y,z) = ((y XOR z) AND x) XOR z - is faster then original version */
+#define MD5_F(x, y, z) ((((y) ^ (z)) & (x)) ^ (z))
+#define MD5_G(x, y, z) (((x) & (z)) | ((y) & (~z)))
+#define MD5_H(x, y, z) ((x) ^ (y) ^ (z))
+#define MD5_I(x, y, z) ((y) ^ ((x) | (~z)))
+
+/* transformations for rounds 1, 2, 3, and 4. */
+#define MD5_ROUND1(a, b, c, d, x, s, ac) { \
+	(a) += MD5_F((b), (c), (d)) + (x) + (ac); \
+	(a) = ROTL32((a), (s)); \
+	(a) += (b); \
+}
+#define MD5_ROUND2(a, b, c, d, x, s, ac) { \
+	(a) += MD5_G((b), (c), (d)) + (x) + (ac); \
+	(a) = ROTL32((a), (s)); \
+	(a) += (b); \
+}
+#define MD5_ROUND3(a, b, c, d, x, s, ac) { \
+	(a) += MD5_H((b), (c), (d)) + (x) + (ac); \
+	(a) = ROTL32((a), (s)); \
+	(a) += (b); \
+}
+#define MD5_ROUND4(a, b, c, d, x, s, ac) { \
+	(a) += MD5_I((b), (c), (d)) + (x) + (ac); \
+	(a) = ROTL32((a), (s)); \
+	(a) += (b); \
+}
+
+/**
+ * The core transformation. Process a 512-bit block.
+ * The function has been taken from RFC 1321 with little changes.
+ *
+ * @param state algorithm state
+ * @param x the message block to process
+ */
+static void rhash_md5_process_block(unsigned state[4], const unsigned* x)
+{
+	register unsigned a, b, c, d;
+	a = state[0];
+	b = state[1];
+	c = state[2];
+	d = state[3];
+
+	MD5_ROUND1(a, b, c, d, x[ 0],  7, 0xd76aa478);
+	MD5_ROUND1(d, a, b, c, x[ 1], 12, 0xe8c7b756);
+	MD5_ROUND1(c, d, a, b, x[ 2], 17, 0x242070db);
+	MD5_ROUND1(b, c, d, a, x[ 3], 22, 0xc1bdceee);
+	MD5_ROUND1(a, b, c, d, x[ 4],  7, 0xf57c0faf);
+	MD5_ROUND1(d, a, b, c, x[ 5], 12, 0x4787c62a);
+	MD5_ROUND1(c, d, a, b, x[ 6], 17, 0xa8304613);
+	MD5_ROUND1(b, c, d, a, x[ 7], 22, 0xfd469501);
+	MD5_ROUND1(a, b, c, d, x[ 8],  7, 0x698098d8);
+	MD5_ROUND1(d, a, b, c, x[ 9], 12, 0x8b44f7af);
+	MD5_ROUND1(c, d, a, b, x[10], 17, 0xffff5bb1);
+	MD5_ROUND1(b, c, d, a, x[11], 22, 0x895cd7be);
+	MD5_ROUND1(a, b, c, d, x[12],  7, 0x6b901122);
+	MD5_ROUND1(d, a, b, c, x[13], 12, 0xfd987193);
+	MD5_ROUND1(c, d, a, b, x[14], 17, 0xa679438e);
+	MD5_ROUND1(b, c, d, a, x[15], 22, 0x49b40821);
+
+	MD5_ROUND2(a, b, c, d, x[ 1],  5, 0xf61e2562);
+	MD5_ROUND2(d, a, b, c, x[ 6],  9, 0xc040b340);
+	MD5_ROUND2(c, d, a, b, x[11], 14, 0x265e5a51);
+	MD5_ROUND2(b, c, d, a, x[ 0], 20, 0xe9b6c7aa);
+	MD5_ROUND2(a, b, c, d, x[ 5],  5, 0xd62f105d);
+	MD5_ROUND2(d, a, b, c, x[10],  9,  0x2441453);
+	MD5_ROUND2(c, d, a, b, x[15], 14, 0xd8a1e681);
+	MD5_ROUND2(b, c, d, a, x[ 4], 20, 0xe7d3fbc8);
+	MD5_ROUND2(a, b, c, d, x[ 9],  5, 0x21e1cde6);
+	MD5_ROUND2(d, a, b, c, x[14],  9, 0xc33707d6);
+	MD5_ROUND2(c, d, a, b, x[ 3], 14, 0xf4d50d87);
+	MD5_ROUND2(b, c, d, a, x[ 8], 20, 0x455a14ed);
+	MD5_ROUND2(a, b, c, d, x[13],  5, 0xa9e3e905);
+	MD5_ROUND2(d, a, b, c, x[ 2],  9, 0xfcefa3f8);
+	MD5_ROUND2(c, d, a, b, x[ 7], 14, 0x676f02d9);
+	MD5_ROUND2(b, c, d, a, x[12], 20, 0x8d2a4c8a);
+
+	MD5_ROUND3(a, b, c, d, x[ 5],  4, 0xfffa3942);
+	MD5_ROUND3(d, a, b, c, x[ 8], 11, 0x8771f681);
+	MD5_ROUND3(c, d, a, b, x[11], 16, 0x6d9d6122);
+	MD5_ROUND3(b, c, d, a, x[14], 23, 0xfde5380c);
+	MD5_ROUND3(a, b, c, d, x[ 1],  4, 0xa4beea44);
+	MD5_ROUND3(d, a, b, c, x[ 4], 11, 0x4bdecfa9);
+	MD5_ROUND3(c, d, a, b, x[ 7], 16, 0xf6bb4b60);
+	MD5_ROUND3(b, c, d, a, x[10], 23, 0xbebfbc70);
+	MD5_ROUND3(a, b, c, d, x[13],  4, 0x289b7ec6);
+	MD5_ROUND3(d, a, b, c, x[ 0], 11, 0xeaa127fa);
+	MD5_ROUND3(c, d, a, b, x[ 3], 16, 0xd4ef3085);
+	MD5_ROUND3(b, c, d, a, x[ 6], 23,  0x4881d05);
+	MD5_ROUND3(a, b, c, d, x[ 9],  4, 0xd9d4d039);
+	MD5_ROUND3(d, a, b, c, x[12], 11, 0xe6db99e5);
+	MD5_ROUND3(c, d, a, b, x[15], 16, 0x1fa27cf8);
+	MD5_ROUND3(b, c, d, a, x[ 2], 23, 0xc4ac5665);
+
+	MD5_ROUND4(a, b, c, d, x[ 0],  6, 0xf4292244);
+	MD5_ROUND4(d, a, b, c, x[ 7], 10, 0x432aff97);
+	MD5_ROUND4(c, d, a, b, x[14], 15, 0xab9423a7);
+	MD5_ROUND4(b, c, d, a, x[ 5], 21, 0xfc93a039);
+	MD5_ROUND4(a, b, c, d, x[12],  6, 0x655b59c3);
+	MD5_ROUND4(d, a, b, c, x[ 3], 10, 0x8f0ccc92);
+	MD5_ROUND4(c, d, a, b, x[10], 15, 0xffeff47d);
+	MD5_ROUND4(b, c, d, a, x[ 1], 21, 0x85845dd1);
+	MD5_ROUND4(a, b, c, d, x[ 8],  6, 0x6fa87e4f);
+	MD5_ROUND4(d, a, b, c, x[15], 10, 0xfe2ce6e0);
+	MD5_ROUND4(c, d, a, b, x[ 6], 15, 0xa3014314);
+	MD5_ROUND4(b, c, d, a, x[13], 21, 0x4e0811a1);
+	MD5_ROUND4(a, b, c, d, x[ 4],  6, 0xf7537e82);
+	MD5_ROUND4(d, a, b, c, x[11], 10, 0xbd3af235);
+	MD5_ROUND4(c, d, a, b, x[ 2], 15, 0x2ad7d2bb);
+	MD5_ROUND4(b, c, d, a, x[ 9], 21, 0xeb86d391);
+
+	state[0] += a;
+	state[1] += b;
+	state[2] += c;
+	state[3] += d;
+}
+
+/**
+ * Calculate message hash.
+ * Can be called repeatedly with chunks of the message to be hashed.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param msg message chunk
+ * @param size length of the message chunk
+ */
+void rhash_md5_update(md5_ctx *ctx, const unsigned char* msg, size_t size)
+{
+	unsigned index = (unsigned)ctx->length & 63;
+	ctx->length += size;
+
+	/* fill partial block */
+	if (index) {
+		unsigned left = md5_block_size - index;
+		le32_copy((char*)ctx->message, index, msg, (size < left ? size : left));
+		if (size < left) return;
+
+		/* process partial block */
+		rhash_md5_process_block(ctx->hash, ctx->message);
+		msg  += left;
+		size -= left;
+	}
+	while (size >= md5_block_size) {
+		unsigned* aligned_message_block;
+		if (IS_LITTLE_ENDIAN && IS_ALIGNED_32(msg)) {
+			/* the most common case is processing a 32-bit aligned message
+			on a little-endian CPU without copying it */
+			aligned_message_block = (unsigned*)msg;
+		} else {
+			le32_copy(ctx->message, 0, msg, md5_block_size);
+			aligned_message_block = ctx->message;
+		}
+
+		rhash_md5_process_block(ctx->hash, aligned_message_block);
+		msg  += md5_block_size;
+		size -= md5_block_size;
+	}
+	if (size) {
+		/* save leftovers */
+		le32_copy(ctx->message, 0, msg, size);
+	}
+}
+
+/**
+ * Store calculated hash into the given array.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param result calculated hash in binary form
+ */
+void rhash_md5_final(md5_ctx *ctx, unsigned char* result)
+{
+	unsigned index = ((unsigned)ctx->length & 63) >> 2;
+	unsigned shift = ((unsigned)ctx->length & 3) * 8;
+
+	/* pad message and run for last block */
+
+	/* append the byte 0x80 to the message */
+	ctx->message[index]   &= ~(0xFFFFFFFFu << shift);
+	ctx->message[index++] ^= 0x80u << shift;
+
+	/* if no room left in the message to store 64-bit message length */
+	if (index > 14) {
+		/* then fill the rest with zeros and process it */
+		while (index < 16) {
+			ctx->message[index++] = 0;
+		}
+		rhash_md5_process_block(ctx->hash, ctx->message);
+		index = 0;
+	}
+	while (index < 14) {
+		ctx->message[index++] = 0;
+	}
+	ctx->message[14] = (unsigned)(ctx->length << 3);
+	ctx->message[15] = (unsigned)(ctx->length >> 29);
+	rhash_md5_process_block(ctx->hash, ctx->message);
+
+	if (result) le32_copy(result, 0, &ctx->hash, 16);
+}
diff --git a/Utilities/cmlibrhash/librhash/md5.h b/Utilities/cmlibrhash/librhash/md5.h
new file mode 100644
index 0000000..1af6f13
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/md5.h
@@ -0,0 +1,31 @@
+/* md5.h */
+#ifndef MD5_HIDER
+#define MD5_HIDER
+#include "ustd.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define md5_block_size 64
+#define md5_hash_size  16
+
+/* algorithm context */
+typedef struct md5_ctx
+{
+	unsigned message[md5_block_size / 4]; /* 512-bit buffer for leftovers */
+	uint64_t length;   /* number of processed bytes */
+	unsigned hash[4];  /* 128-bit algorithm internal hashing state */
+} md5_ctx;
+
+/* hash functions */
+
+void rhash_md5_init(md5_ctx *ctx);
+void rhash_md5_update(md5_ctx *ctx, const unsigned char* msg, size_t size);
+void rhash_md5_final(md5_ctx *ctx, unsigned char result[16]);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* MD5_HIDER */
diff --git a/Utilities/cmlibrhash/librhash/rhash.c b/Utilities/cmlibrhash/librhash/rhash.c
new file mode 100644
index 0000000..ad6249b
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/rhash.c
@@ -0,0 +1,872 @@
+/* rhash.c - implementation of LibRHash library calls
+ *
+ * Copyright: 2008-2012 Aleksey Kravchenko <rhash.admin at gmail.com>
+ *
+ * Permission is hereby granted,  free of charge,  to any person  obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction,  including without limitation
+ * the rights to  use, copy, modify,  merge, publish, distribute, sublicense,
+ * and/or sell copies  of  the Software,  and to permit  persons  to whom the
+ * Software is furnished to do so.
+ *
+ * This program  is  distributed  in  the  hope  that it will be useful,  but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  Use this program  at  your own risk!
+ */
+
+/* macros for large file support, must be defined before any include file */
+#define _LARGEFILE64_SOURCE
+#define _FILE_OFFSET_BITS 64
+
+#include <string.h> /* memset() */
+#include <stdlib.h> /* free() */
+#include <stddef.h> /* ptrdiff_t */
+#include <stdio.h>
+#include <assert.h>
+#include <errno.h>
+
+/* modifier for Windows DLL */
+#if defined(_WIN32) && defined(RHASH_EXPORTS)
+# define RHASH_API __declspec(dllexport)
+#endif
+
+#include "byte_order.h"
+#include "algorithms.h"
+#include "util.h"
+#include "hex.h"
+#include "rhash.h" /* RHash library interface */
+
+#define STATE_ACTIVE  0xb01dbabe
+#define STATE_STOPED  0xdeadbeef
+#define STATE_DELETED 0xdecea5ed
+#define RCTX_AUTO_FINAL 0x1
+#define RCTX_FINALIZED  0x2
+#define RCTX_FINALIZED_MASK (RCTX_AUTO_FINAL | RCTX_FINALIZED)
+#define RHPR_FORMAT (RHPR_RAW | RHPR_HEX | RHPR_BASE32 | RHPR_BASE64)
+#define RHPR_MODIFIER (RHPR_UPPERCASE | RHPR_REVERSE)
+
+/**
+ * Initialize static data of rhash algorithms
+ */
+void rhash_library_init(void)
+{
+	rhash_init_algorithms(RHASH_ALL_HASHES);
+#ifdef USE_OPENSSL
+	rhash_plug_openssl();
+#endif
+}
+
+/**
+ * Returns the number of supported hash algorithms.
+ *
+ * @return the number of supported hash functions
+ */
+int RHASH_API rhash_count(void)
+{
+	return rhash_info_size;
+}
+
+/* Lo-level rhash library functions */
+
+/**
+ * Allocate and initialize RHash context for calculating hash(es).
+ * After initializing rhash_update()/rhash_final() functions should be used.
+ * Then the context must be freed by calling rhash_free().
+ *
+ * @param hash_id union of bit flags, containing ids of hashes to calculate.
+ * @return initialized rhash context, NULL on error and errno is set
+ */
+RHASH_API rhash rhash_init(unsigned hash_id)
+{
+	unsigned tail_bit_index; /* index of hash_id trailing bit */
+	unsigned num = 0;        /* number of hashes to compute */
+	rhash_context_ext *rctx = NULL; /* allocated rhash context */
+	size_t hash_size_sum = 0;   /* size of hash contexts to store in rctx */
+
+	unsigned i, bit_index, id;
+	struct rhash_hash_info* info;
+	size_t aligned_size;
+	char* phash_ctx;
+
+	hash_id &= RHASH_ALL_HASHES;
+	if (hash_id == 0) {
+		errno = EINVAL;
+		return NULL;
+	}
+
+	tail_bit_index = rhash_ctz(hash_id); /* get trailing bit index */
+	assert(tail_bit_index < RHASH_HASH_COUNT);
+
+	id = 1 << tail_bit_index;
+
+	if (hash_id == id) {
+		/* handle the most common case of only one hash */
+		num = 1;
+		info = &rhash_info_table[tail_bit_index];
+		hash_size_sum = info->context_size;
+	} else {
+		/* another case: hash_id contains several hashes */
+		for (bit_index = tail_bit_index; id <= hash_id; bit_index++, id = id << 1) {
+			assert(id != 0);
+			assert(bit_index < RHASH_HASH_COUNT);
+			info = &rhash_info_table[bit_index];
+			if (hash_id & id) {
+				/* align sizes by 8 bytes */
+				aligned_size = (info->context_size + 7) & ~7;
+				hash_size_sum += aligned_size;
+				num++;
+			}
+		}
+		assert(num > 1);
+	}
+
+	/* align the size of the rhash context common part */
+	aligned_size = (offsetof(rhash_context_ext, vector[num]) + 7) & ~7;
+	assert(aligned_size >= sizeof(rhash_context_ext));
+
+	/* allocate rhash context with enough memory to store contexts of all used hashes */
+	rctx = (rhash_context_ext*)malloc(aligned_size + hash_size_sum);
+	if (rctx == NULL) return NULL;
+
+	/* initialize common fields of the rhash context */
+	memset(rctx, 0, sizeof(rhash_context_ext));
+	rctx->rc.hash_id = hash_id;
+	rctx->flags = RCTX_AUTO_FINAL; /* turn on auto-final by default */
+	rctx->state = STATE_ACTIVE;
+	rctx->hash_vector_size = num;
+
+	/* aligned hash contexts follows rctx->vector[num] in the same memory block */
+	phash_ctx = (char*)rctx + aligned_size;
+	assert(phash_ctx >= (char*)&rctx->vector[num]);
+
+	/* initialize context for every hash in a loop */
+	for (bit_index = tail_bit_index, id = 1 << tail_bit_index, i = 0;
+		id <= hash_id; bit_index++, id = id << 1)
+	{
+		/* check if a hash function with given id shall be included into rctx */
+		if ((hash_id & id) != 0) {
+			info = &rhash_info_table[bit_index];
+			assert(info->context_size > 0);
+			assert(((phash_ctx - (char*)0) & 7) == 0); /* hash context is aligned */
+			assert(info->init != NULL);
+
+			rctx->vector[i].hash_info = info;
+			rctx->vector[i].context = phash_ctx;
+
+#if 0
+			/* BTIH initialization is complex, save pointer for later */
+			if ((id & RHASH_BTIH) != 0) rctx->bt_ctx = phash_ctx;
+#endif
+			phash_ctx += (info->context_size + 7) & ~7;
+
+			/* initialize the i-th hash context */
+			info->init(rctx->vector[i].context);
+			i++;
+		}
+	}
+
+	return &rctx->rc; /* return allocated and initialized rhash context */
+}
+
+/**
+ * Free RHash context memory.
+ *
+ * @param ctx the context to free.
+ */
+void rhash_free(rhash ctx)
+{
+	rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
+	unsigned i;
+
+	if (ctx == 0) return;
+	assert(ectx->hash_vector_size <= RHASH_HASH_COUNT);
+	ectx->state = STATE_DELETED; /* mark memory block as being removed */
+
+	/* clean the hash functions, which require additional clean up */
+	for (i = 0; i < ectx->hash_vector_size; i++) {
+		struct rhash_hash_info* info = ectx->vector[i].hash_info;
+		if (info->cleanup != 0) {
+			info->cleanup(ectx->vector[i].context);
+		}
+	}
+
+	free(ectx);
+}
+
+/**
+ * Re-initialize RHash context to reuse it.
+ * Useful to speed up processing of many small messages.
+ *
+ * @param ctx context to reinitialize
+ */
+RHASH_API void rhash_reset(rhash ctx)
+{
+	rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
+	unsigned i;
+
+	assert(ectx->hash_vector_size > 0);
+	assert(ectx->hash_vector_size <= RHASH_HASH_COUNT);
+	ectx->state = STATE_ACTIVE; /* re-activate the structure */
+
+	/* re-initialize every hash in a loop */
+	for (i = 0; i < ectx->hash_vector_size; i++) {
+		struct rhash_hash_info* info = ectx->vector[i].hash_info;
+		if (info->cleanup != 0) {
+			info->cleanup(ectx->vector[i].context);
+		}
+
+		assert(info->init != NULL);
+		info->init(ectx->vector[i].context);
+	}
+	ectx->flags &= ~RCTX_FINALIZED; /* clear finalized state */
+}
+
+/**
+ * Calculate hashes of message.
+ * Can be called repeatedly with chunks of the message to be hashed.
+ *
+ * @param ctx the rhash context
+ * @param message message chunk
+ * @param length length of the message chunk
+ * @return 0 on success; On fail return -1 and set errno
+ */
+RHASH_API int rhash_update(rhash ctx, const void* message, size_t length)
+{
+	rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
+	unsigned i;
+
+	assert(ectx->hash_vector_size <= RHASH_HASH_COUNT);
+	if (ectx->state != STATE_ACTIVE) return 0; /* do nothing if canceled */
+
+	ctx->msg_size += length;
+
+	/* call update method for every algorithm */
+	for (i = 0; i < ectx->hash_vector_size; i++) {
+		struct rhash_hash_info* info = ectx->vector[i].hash_info;
+		assert(info->update != 0);
+		info->update(ectx->vector[i].context, message, length);
+	}
+	return 0; /* no error processing at the moment */
+}
+
+/**
+ * Finalize hash calculation and optionally store the first hash.
+ *
+ * @param ctx the rhash context
+ * @param first_result optional buffer to store a calculated hash with the lowest available id
+ * @return 0 on success; On fail return -1 and set errno
+ */
+RHASH_API int rhash_final(rhash ctx, unsigned char* first_result)
+{
+	unsigned i = 0;
+	unsigned char buffer[130];
+	unsigned char* out = (first_result ? first_result : buffer);
+	rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
+	assert(ectx->hash_vector_size <= RHASH_HASH_COUNT);
+
+	/* skip final call if already finalized and auto-final is on */
+	if ((ectx->flags & RCTX_FINALIZED_MASK) ==
+		(RCTX_AUTO_FINAL | RCTX_FINALIZED)) return 0;
+
+	/* call final method for every algorithm */
+	for (i = 0; i < ectx->hash_vector_size; i++) {
+		struct rhash_hash_info* info = ectx->vector[i].hash_info;
+		assert(info->final != 0);
+		assert(info->info->digest_size < sizeof(buffer));
+		info->final(ectx->vector[i].context, out);
+		out = buffer;
+	}
+	ectx->flags |= RCTX_FINALIZED;
+	return 0; /* no error processing at the moment */
+}
+
+/**
+ * Store digest for given hash_id.
+ * If hash_id is zero, function stores digest for a hash with the lowest id found in the context.
+ * For nonzero hash_id the context must contain it, otherwise function silently does nothing.
+ *
+ * @param ctx rhash context
+ * @param hash_id id of hash to retrieve or zero for hash with the lowest available id
+ * @param result buffer to put the hash into
+ */
+static void rhash_put_digest(rhash ctx, unsigned hash_id, unsigned char* result)
+{
+	rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
+	unsigned i;
+	rhash_vector_item *item;
+	struct rhash_hash_info* info;
+	unsigned char* digest;
+
+	assert(ectx);
+	assert(ectx->hash_vector_size > 0 && ectx->hash_vector_size <= RHASH_HASH_COUNT);
+
+	/* finalize context if not yet finalized and auto-final is on */
+	if ((ectx->flags & RCTX_FINALIZED_MASK) == RCTX_AUTO_FINAL) {
+		rhash_final(ctx, NULL);
+	}
+
+	if (hash_id == 0) {
+		item = &ectx->vector[0]; /* get the first hash */
+		info = item->hash_info;
+	} else {
+		for (i = 0;; i++) {
+			if (i >= ectx->hash_vector_size) {
+				return; /* hash_id not found, do nothing */
+			}
+			item = &ectx->vector[i];
+			info = item->hash_info;
+			if (info->info->hash_id == hash_id) break;
+		}
+	}
+	digest = ((unsigned char*)item->context + info->digest_diff);
+	if (info->info->flags & F_SWAP32) {
+		assert((info->info->digest_size & 3) == 0);
+		/* NB: the next call is correct only for multiple of 4 byte size */
+		rhash_swap_copy_str_to_u32(result, 0, digest, info->info->digest_size);
+	} else if (info->info->flags & F_SWAP64) {
+		rhash_swap_copy_u64_to_str(result, digest, info->info->digest_size);
+	} else {
+		memcpy(result, digest, info->info->digest_size);
+	}
+}
+
+/**
+ * Set the callback function to be called from the
+ * rhash_file() and rhash_file_update() functions
+ * on processing every file block. The file block
+ * size is set internally by rhash and now is 8 KiB.
+ *
+ * @param ctx rhash context
+ * @param callback pointer to the callback function
+ * @param callback_data pointer to data passed to the callback
+ */
+RHASH_API void rhash_set_callback(rhash ctx, rhash_callback_t callback, void* callback_data)
+{
+	((rhash_context_ext*)ctx)->callback = callback;
+	((rhash_context_ext*)ctx)->callback_data = callback_data;
+}
+
+
+/* hi-level message hashing interface */
+
+/**
+ * Compute a hash of the given message.
+ *
+ * @param hash_id id of hash sum to compute
+ * @param message the message to process
+ * @param length message length
+ * @param result buffer to receive binary hash string
+ * @return 0 on success, -1 on error
+ */
+RHASH_API int rhash_msg(unsigned hash_id, const void* message, size_t length, unsigned char* result)
+{
+	rhash ctx;
+	hash_id &= RHASH_ALL_HASHES;
+	ctx = rhash_init(hash_id);
+	if (ctx == NULL) return -1;
+	rhash_update(ctx, message, length);
+	rhash_final(ctx, result);
+	rhash_free(ctx);
+	return 0;
+}
+
+/**
+ * Hash a file or stream. Multiple hashes can be computed.
+ * First, inintialize ctx parameter with rhash_init() before calling
+ * rhash_file_update(). Then use rhash_final() and rhash_print()
+ * to retrive hash values. Finaly call rhash_free() on ctx
+ * to free allocated memory or call rhash_reset() to reuse ctx.
+ *
+ * @param ctx rhash context
+ * @param fd descriptor of the file to hash
+ * @return 0 on success, -1 on error and errno is set
+ */
+RHASH_API int rhash_file_update(rhash ctx, FILE* fd)
+{
+	rhash_context_ext* const ectx = (rhash_context_ext*)ctx;
+	const size_t block_size = 8192;
+	unsigned char *buffer, *pmem;
+	size_t length = 0, align8;
+	int res = 0;
+	if (ectx->state != STATE_ACTIVE) return 0; /* do nothing if canceled */
+
+	if (ctx == NULL) {
+		errno = EINVAL;
+		return -1;
+	}
+
+	pmem = (unsigned char*)malloc(block_size + 8);
+	if (!pmem) return -1; /* errno is set to ENOMEM according to UNIX 98 */
+
+	align8 = ((unsigned char*)0 - pmem) & 7;
+	buffer = pmem + align8;
+
+	while (!feof(fd)) {
+		/* stop if canceled */
+		if (ectx->state != STATE_ACTIVE) break;
+
+		length = fread(buffer, 1, block_size, fd);
+
+		if (ferror(fd)) {
+			res = -1; /* note: errno contains error code */
+			break;
+		} else if (length) {
+			rhash_update(ctx, buffer, length);
+
+			if (ectx->callback) {
+				((rhash_callback_t)ectx->callback)(ectx->callback_data, ectx->rc.msg_size);
+			}
+		}
+	}
+
+	free(buffer);
+	return res;
+}
+
+/**
+ * Compute a single hash for given file.
+ *
+ * @param hash_id id of hash sum to compute
+ * @param filepath path to the file to hash
+ * @param result buffer to receive hash value with the lowest requested id
+ * @return 0 on success, -1 on error and errno is set
+ */
+RHASH_API int rhash_file(unsigned hash_id, const char* filepath, unsigned char* result)
+{
+	FILE* fd;
+	rhash ctx;
+	int res;
+
+	hash_id &= RHASH_ALL_HASHES;
+	if (hash_id == 0) {
+		errno = EINVAL;
+		return -1;
+	}
+
+	if ((fd = fopen(filepath, "rb")) == NULL) return -1;
+
+	if ((ctx = rhash_init(hash_id)) == NULL) return -1;
+
+	res = rhash_file_update(ctx, fd); /* hash the file */
+	fclose(fd);
+
+	rhash_final(ctx, result);
+	rhash_free(ctx);
+	return res;
+}
+
+#ifdef _WIN32 /* windows only function */
+#include <share.h>
+
+/**
+ * Compute a single hash for given file.
+ *
+ * @param hash_id id of hash sum to compute
+ * @param filepath path to the file to hash
+ * @param result buffer to receive hash value with the lowest requested id
+ * @return 0 on success, -1 on error, -1 on error and errno is set
+ */
+RHASH_API int rhash_wfile(unsigned hash_id, const wchar_t* filepath, unsigned char* result)
+{
+	FILE* fd;
+	rhash ctx;
+	int res;
+
+	hash_id &= RHASH_ALL_HASHES;
+	if (hash_id == 0) {
+		errno = EINVAL;
+		return -1;
+	}
+
+	if ((fd = _wfsopen(filepath, L"rb", _SH_DENYWR)) == NULL) return -1;
+
+	if ((ctx = rhash_init(hash_id)) == NULL) return -1;
+
+	res = rhash_file_update(ctx, fd); /* hash the file */
+	fclose(fd);
+
+	rhash_final(ctx, result);
+	rhash_free(ctx);
+	return res;
+}
+#endif
+
+/* RHash information functions */
+
+/**
+ * Returns information about a hash function by its hash_id.
+ *
+ * @param hash_id the id of hash algorithm
+ * @return pointer to the rhash_info structure containing the information
+ */
+const rhash_info* rhash_info_by_id(unsigned hash_id)
+{
+	hash_id &= RHASH_ALL_HASHES;
+	/* check that only one bit is set */
+	if (hash_id != (hash_id & -(int)hash_id)) return NULL;
+	/* note: alternative condition is (hash_id == 0 || (hash_id & (hash_id - 1)) != 0) */
+	return rhash_info_table[rhash_ctz(hash_id)].info;
+}
+
+#if 0
+/**
+ * Detect default digest output format for given hash algorithm.
+ *
+ * @param hash_id the id of hash algorithm
+ * @return 1 for base32 format, 0 for hexadecimal
+ */
+RHASH_API int rhash_is_base32(unsigned hash_id)
+{
+	/* fast method is just to test a bit-mask */
+	return ((hash_id & (RHASH_TTH | RHASH_AICH)) != 0);
+}
+#endif
+
+/**
+ * Returns size of binary digest for given hash algorithm.
+ *
+ * @param hash_id the id of hash algorithm
+ * @return digest size in bytes
+ */
+RHASH_API int rhash_get_digest_size(unsigned hash_id)
+{
+	hash_id &= RHASH_ALL_HASHES;
+	if (hash_id == 0 || (hash_id & (hash_id - 1)) != 0) return -1;
+	return (int)rhash_info_table[rhash_ctz(hash_id)].info->digest_size;
+}
+
+/**
+ * Returns length of digest hash string in default output format.
+ *
+ * @param hash_id the id of hash algorithm
+ * @return the length of hash string
+ */
+RHASH_API int rhash_get_hash_length(unsigned hash_id)
+{
+	const rhash_info* info = rhash_info_by_id(hash_id);
+	return (int)(info ? (info->flags & F_BS32 ?
+		BASE32_LENGTH(info->digest_size) : info->digest_size * 2) : 0);
+}
+
+/**
+ * Returns a name of given hash algorithm.
+ *
+ * @param hash_id the id of hash algorithm
+ * @return algorithm name
+ */
+RHASH_API const char* rhash_get_name(unsigned hash_id)
+{
+	const rhash_info* info = rhash_info_by_id(hash_id);
+	return (info ? info->name : 0);
+}
+
+/**
+ * Returns a name part of magnet urn of the given hash algorithm.
+ * Such magnet_name is used to generate a magnet link of the form
+ * urn:<magnet_name>=<hash_value>.
+ *
+ * @param hash_id the id of hash algorithm
+ * @return name
+ */
+RHASH_API const char* rhash_get_magnet_name(unsigned hash_id)
+{
+	const rhash_info* info = rhash_info_by_id(hash_id);
+	return (info ? info->magnet_name : 0);
+}
+
+#if 0
+static size_t rhash_get_magnet_url_size(const char* filepath,
+	rhash context, unsigned hash_mask, int flags)
+{
+	size_t size = 0; /* count terminating '\0' */
+	unsigned bit, hash = context->hash_id & hash_mask;
+
+	/* RHPR_NO_MAGNET, RHPR_FILESIZE */
+	if ((flags & RHPR_NO_MAGNET) == 0) {
+		size += 8;
+	}
+
+	if ((flags & RHPR_FILESIZE) != 0) {
+		uint64_t num = context->msg_size;
+
+		size += 4;
+		if (num == 0) size++;
+		else {
+			for (; num; num /= 10, size++);
+		}
+	}
+
+	if (filepath) {
+		size += 4 + rhash_urlencode(NULL, filepath);
+	}
+
+	/* loop through hash values */
+	for (bit = hash & -(int)hash; bit <= hash; bit <<= 1) {
+		const char* name;
+		if ((bit & hash) == 0) continue;
+		if ((name = rhash_get_magnet_name(bit)) == 0) continue;
+
+		size += (7 + 2) + strlen(name);
+		size += rhash_print(NULL, context, bit,
+			(bit & (RHASH_SHA1 | RHASH_BTIH) ? RHPR_BASE32 : 0));
+	}
+
+	return size;
+}
+
+/**
+ * Print magnet link with given filepath and calculated hash sums into the
+ * output buffer. The hash_mask can limit which hash values will be printed.
+ * The function returns the size of the required buffer.
+ * If output is NULL the .
+ *
+ * @param output a string buffer to receive the magnet link or NULL
+ * @param filepath the file path to be printed or NULL
+ * @param context algorithms state
+ * @param hash_mask bit mask of the hash sums to add to the link
+ * @param flags   can be combination of bits RHPR_UPPERCASE, RHPR_NO_MAGNET,
+ *                RHPR_FILESIZE
+ * @return number of written characters, including terminating '\0' on success, 0 on fail
+ */
+RHASH_API size_t rhash_print_magnet(char* output, const char* filepath,
+	rhash context, unsigned hash_mask, int flags)
+{
+	int i;
+	const char* begin = output;
+
+	if (output == NULL) return rhash_get_magnet_url_size(
+		filepath, context, hash_mask, flags);
+
+	/* RHPR_NO_MAGNET, RHPR_FILESIZE */
+	if ((flags & RHPR_NO_MAGNET) == 0) {
+		strcpy(output, "magnet:?");
+		output += 8;
+	}
+
+	if ((flags & RHPR_FILESIZE) != 0) {
+		strcpy(output, "xl=");
+		output += 3;
+		output += rhash_sprintI64(output, context->msg_size);
+		*(output++) = '&';
+	}
+
+	if (filepath) {
+		strcpy(output, "dn=");
+		output += 3;
+		output += rhash_urlencode(output, filepath);
+		*(output++) = '&';
+	}
+	flags &= RHPR_UPPERCASE;
+
+	for (i = 0; i < 2; i++) {
+		unsigned bit;
+		unsigned hash = context->hash_id & hash_mask;
+		hash = (i == 0 ? hash & (RHASH_ED2K | RHASH_AICH)
+			: hash & ~(RHASH_ED2K | RHASH_AICH));
+		if (!hash) continue;
+
+		/* loop through hash values */
+		for (bit = hash & -(int)hash; bit <= hash; bit <<= 1) {
+			const char* name;
+			if ((bit & hash) == 0) continue;
+			if (!(name = rhash_get_magnet_name(bit))) continue;
+
+			strcpy(output, "xt=urn:");
+			output += 7;
+			strcpy(output, name);
+			output += strlen(name);
+			*(output++) = ':';
+			output += rhash_print(output, context, bit,
+				(bit & (RHASH_SHA1 | RHASH_BTIH) ? flags | RHPR_BASE32 : flags));
+			*(output++) = '&';
+		}
+	}
+	output[-1] = '\0'; /* terminate the line */
+
+	return (output - begin);
+}
+
+/* hash sum output */
+
+/**
+ * Print a text presentation of a given hash sum to the specified buffer,
+ *
+ * @param output a buffer to print the hash to
+ * @param bytes a hash sum to print
+ * @param size a size of hash sum in bytes
+ * @param flags  a bit-mask controlling how to format the hash sum,
+ *               can be a mix of the flags: RHPR_RAW, RHPR_HEX, RHPR_BASE32,
+ *               RHPR_BASE64, RHPR_UPPERCASE, RHPR_REVERSE
+ * @return the number of written characters
+ */
+size_t rhash_print_bytes(char* output, const unsigned char* bytes,
+	size_t size, int flags)
+{
+	size_t str_len;
+	int upper_case = (flags & RHPR_UPPERCASE);
+	int format = (flags & ~RHPR_MODIFIER);
+
+	switch (format) {
+	case RHPR_HEX:
+		str_len = size * 2;
+		rhash_byte_to_hex(output, bytes, (unsigned)size, upper_case);
+		break;
+	case RHPR_BASE32:
+		str_len = BASE32_LENGTH(size);
+		rhash_byte_to_base32(output, bytes, (unsigned)size, upper_case);
+		break;
+	case RHPR_BASE64:
+		str_len = BASE64_LENGTH(size);
+		rhash_byte_to_base64(output, bytes, (unsigned)size);
+		break;
+	default:
+		str_len = size;
+		memcpy(output, bytes, size);
+		break;
+	}
+	return str_len;
+}
+
+/**
+ * Print text presentation of a hash sum with given hash_id to the specified
+ * output buffer. If the hash_id is zero, then print the hash sum with
+ * the lowest id stored in the hash context.
+ * The function call fails if the context doesn't include a hash with the
+ * given hash_id.
+ *
+ * @param output a buffer to print the hash to
+ * @param context algorithms state
+ * @param hash_id id of the hash sum to print or 0 to print the first hash
+ *                saved in the context.
+ * @param flags  a bitmask controlling how to print the hash. Can contain flags
+ *               RHPR_UPPERCASE, RHPR_HEX, RHPR_BASE32, RHPR_BASE64, etc.
+ * @return the number of written characters on success or 0 on fail
+ */
+size_t RHASH_API rhash_print(char* output, rhash context, unsigned hash_id, int flags)
+{
+	const rhash_info* info;
+	unsigned char digest[80];
+	size_t digest_size;
+
+	info = (hash_id != 0 ? rhash_info_by_id(hash_id) :
+		((rhash_context_ext*)context)->vector[0].hash_info->info);
+
+	if (info == NULL) return 0;
+	digest_size = info->digest_size;
+	assert(digest_size <= 64);
+
+	flags &= (RHPR_FORMAT | RHPR_MODIFIER);
+	if ((flags & RHPR_FORMAT) == 0) {
+		/* use default format if not specified by flags */
+		flags |= (info->flags & RHASH_INFO_BASE32 ? RHPR_BASE32 : RHPR_HEX);
+	}
+
+	if (output == NULL) {
+		switch (flags & RHPR_FORMAT) {
+		case RHPR_HEX:
+			return (digest_size * 2);
+		case RHPR_BASE32:
+			return BASE32_LENGTH(digest_size);
+		case RHPR_BASE64:
+			return BASE64_LENGTH(digest_size);
+		default:
+			return digest_size;
+		}
+	}
+
+	/* note: use info->hash_id, cause hash_id can be 0 */
+	rhash_put_digest(context, info->hash_id, digest);
+
+	if ((flags & ~RHPR_UPPERCASE) == (RHPR_REVERSE | RHPR_HEX)) {
+		/* reverse the digest */
+		unsigned char *p = digest, *r = digest + digest_size - 1;
+		char tmp;
+		for (; p < r; p++, r--) {
+			tmp = *p;
+			*p = *r;
+			*r = tmp;
+		}
+	}
+
+	return rhash_print_bytes(output, digest, digest_size, flags);
+}
+
+#if defined(_WIN32) && defined(RHASH_EXPORTS)
+#include <windows.h>
+BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID reserved);
+BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID reserved)
+{
+	(void)hModule;
+	(void)reserved;
+	switch (reason) {
+	case DLL_PROCESS_ATTACH:
+		rhash_library_init();
+		break;
+	case DLL_PROCESS_DETACH:
+		/*rhash_library_free();*/
+	case DLL_THREAD_ATTACH:
+	case DLL_THREAD_DETACH:
+		break;
+	}
+	return TRUE;
+}
+#endif
+
+#define PVOID2UPTR(p) ((rhash_uptr_t)((char*)p - 0))
+
+/**
+ * Process a rhash message.
+ *
+ * @param msg_id message identifier
+ * @param dst message destination (can be NULL for generic messages)
+ * @param ldata data depending on message
+ * @param rdata data depending on message
+ * @return message-specific data
+ */
+RHASH_API rhash_uptr_t rhash_transmit(unsigned msg_id, void* dst, rhash_uptr_t ldata, rhash_uptr_t rdata)
+{
+	/* for messages working with rhash context */
+	rhash_context_ext* const ctx = (rhash_context_ext*)dst;
+
+	switch (msg_id) {
+	case RMSG_GET_CONTEXT:
+		{
+			unsigned i;
+			for (i = 0; i < ctx->hash_vector_size; i++) {
+				struct rhash_hash_info* info = ctx->vector[i].hash_info;
+				if (info->info->hash_id == (unsigned)ldata)
+					return PVOID2UPTR(ctx->vector[i].context);
+			}
+			return (rhash_uptr_t)0;
+		}
+
+	case RMSG_CANCEL:
+		/* mark rhash context as canceled, in a multithreaded program */
+		atomic_compare_and_swap(&ctx->state, STATE_ACTIVE, STATE_STOPED);
+		return 0;
+
+	case RMSG_IS_CANCELED:
+		return (ctx->state == STATE_STOPED);
+
+	case RMSG_GET_FINALIZED:
+		return ((ctx->flags & RCTX_FINALIZED) != 0);
+	case RMSG_SET_AUTOFINAL:
+		ctx->flags &= ~RCTX_AUTO_FINAL;
+		if (ldata) ctx->flags |= RCTX_AUTO_FINAL;
+		break;
+
+	/* OpenSSL related messages */
+#ifdef USE_OPENSSL
+	case RMSG_SET_OPENSSL_MASK:
+		rhash_openssl_hash_mask = (unsigned)ldata;
+		break;
+	case RMSG_GET_OPENSSL_MASK:
+		return rhash_openssl_hash_mask;
+#endif
+
+	default:
+		return RHASH_ERROR; /* unknown message */
+	}
+	return 0;
+}
+#endif
diff --git a/Utilities/cmlibrhash/librhash/rhash.h b/Utilities/cmlibrhash/librhash/rhash.h
new file mode 100644
index 0000000..cee0e25
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/rhash.h
@@ -0,0 +1,288 @@
+/** @file rhash.h LibRHash interface */
+#ifndef RHASH_H
+#define RHASH_H
+
+#include <stdio.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef RHASH_API
+/* modifier for LibRHash functions */
+# define RHASH_API
+#endif
+
+/**
+ * Identifiers of supported hash functions.
+ * The rhash_init() function allows mixing several ids using
+ * binary OR, to calculate several hash functions for one message.
+ */
+enum rhash_ids
+{
+#if 0
+	RHASH_CRC32 = 0x01,
+	RHASH_MD4   = 0x02,
+	RHASH_MD5   = 0x04,
+	RHASH_SHA1  = 0x08,
+	RHASH_TIGER = 0x10,
+	RHASH_TTH   = 0x20,
+	RHASH_BTIH  = 0x40,
+	RHASH_ED2K  = 0x80,
+	RHASH_AICH  = 0x100,
+	RHASH_WHIRLPOOL = 0x200,
+	RHASH_RIPEMD160 = 0x400,
+	RHASH_GOST      = 0x800,
+	RHASH_GOST_CRYPTOPRO = 0x1000,
+	RHASH_HAS160    = 0x2000,
+	RHASH_SNEFRU128 = 0x4000,
+	RHASH_SNEFRU256 = 0x8000,
+	RHASH_SHA224    = 0x10000,
+	RHASH_SHA256    = 0x20000,
+	RHASH_SHA384    = 0x40000,
+	RHASH_SHA512    = 0x80000,
+	RHASH_EDONR256  = 0x0100000,
+	RHASH_EDONR512  = 0x0200000,
+	RHASH_SHA3_224  = 0x0400000,
+	RHASH_SHA3_256  = 0x0800000,
+	RHASH_SHA3_384  = 0x1000000,
+	RHASH_SHA3_512  = 0x2000000,
+
+	/** The bit-mask containing all supported hashe functions */
+	RHASH_ALL_HASHES = RHASH_CRC32 | RHASH_MD4 | RHASH_MD5 | RHASH_ED2K | RHASH_SHA1 |
+		RHASH_TIGER | RHASH_TTH | RHASH_GOST | RHASH_GOST_CRYPTOPRO |
+		RHASH_BTIH | RHASH_AICH | RHASH_WHIRLPOOL | RHASH_RIPEMD160 |
+		RHASH_HAS160 | RHASH_SNEFRU128 | RHASH_SNEFRU256 |
+		RHASH_SHA224 | RHASH_SHA256 | RHASH_SHA384 | RHASH_SHA512 |
+		RHASH_SHA3_224 | RHASH_SHA3_256 | RHASH_SHA3_384 | RHASH_SHA3_512 |
+		RHASH_EDONR256 | RHASH_EDONR512,
+
+	/** The number of supported hash functions */
+	RHASH_HASH_COUNT = 26
+#else
+	RHASH_MD5        = 0x01,
+	RHASH_SHA1       = 0x02,
+	RHASH_SHA224     = 0x04,
+	RHASH_SHA256     = 0x08,
+	RHASH_SHA384     = 0x10,
+	RHASH_SHA512     = 0x20,
+	RHASH_SHA3_224   = 0x40,
+	RHASH_SHA3_256   = 0x80,
+	RHASH_SHA3_384   = 0x100,
+	RHASH_SHA3_512   = 0x200,
+	RHASH_ALL_HASHES =
+		RHASH_MD5 |
+		RHASH_SHA1 |
+		RHASH_SHA224 |
+		RHASH_SHA256 |
+		RHASH_SHA384 |
+		RHASH_SHA512 |
+		RHASH_SHA3_224 |
+		RHASH_SHA3_256 |
+		RHASH_SHA3_384 |
+		RHASH_SHA3_512,
+	RHASH_HASH_COUNT = 10
+#endif
+};
+
+/**
+ * The rhash context structure contains contexts for several hash functions
+ */
+typedef struct rhash_context
+{
+	/** The size of the hashed message */
+	unsigned long long msg_size;
+
+	/**
+	 * The bit-mask containing identifiers of the hashes being calculated
+	 */
+	unsigned hash_id;
+} rhash_context;
+
+#ifndef LIBRHASH_RHASH_CTX_DEFINED
+#define LIBRHASH_RHASH_CTX_DEFINED
+/**
+ * Hashing context.
+ */
+typedef struct rhash_context* rhash;
+#endif /* LIBRHASH_RHASH_CTX_DEFINED */
+
+/** type of a callback to be called periodically while hashing a file */
+typedef void (*rhash_callback_t)(void* data, unsigned long long offset);
+
+RHASH_API void rhash_library_init(void); /* initialize static data */
+
+/* hi-level hashing functions */
+RHASH_API int rhash_msg(unsigned hash_id, const void* message, size_t length, unsigned char* result);
+RHASH_API int rhash_file(unsigned hash_id, const char* filepath, unsigned char* result);
+RHASH_API int rhash_file_update(rhash ctx, FILE* fd);
+
+#ifdef _WIN32 /* windows only function */
+RHASH_API int rhash_wfile(unsigned hash_id, const wchar_t* filepath, unsigned char* result);
+#endif
+
+/* lo-level interface */
+RHASH_API rhash rhash_init(unsigned hash_id);
+/*RHASH_API rhash rhash_init_by_ids(unsigned hash_ids[], unsigned count);*/
+RHASH_API int  rhash_update(rhash ctx, const void* message, size_t length);
+RHASH_API int  rhash_final(rhash ctx, unsigned char* first_result);
+RHASH_API void rhash_reset(rhash ctx); /* reinitialize the context */
+RHASH_API void rhash_free(rhash ctx);
+
+/* additional lo-level functions */
+RHASH_API void  rhash_set_callback(rhash ctx, rhash_callback_t callback, void* callback_data);
+
+/** bit-flag: default hash output format is base32 */
+#define RHASH_INFO_BASE32 1
+
+/**
+ * Information about a hash function.
+ */
+typedef struct rhash_info
+{
+	/** hash function indentifier */
+	unsigned hash_id;
+	/** flags bit-mask, including RHASH_INFO_BASE32 bit */
+	unsigned flags;
+	/** size of binary message digest in bytes */
+	size_t digest_size;
+	const char* name;
+	const char* magnet_name;
+} rhash_info;
+
+/* information functions */
+RHASH_API int  rhash_count(void); /* number of supported hashes */
+RHASH_API int  rhash_get_digest_size(unsigned hash_id); /* size of binary message digest */
+RHASH_API int  rhash_get_hash_length(unsigned hash_id); /* length of formatted hash string */
+RHASH_API int  rhash_is_base32(unsigned hash_id); /* default digest output format */
+RHASH_API const char* rhash_get_name(unsigned hash_id); /* get hash function name */
+RHASH_API const char* rhash_get_magnet_name(unsigned hash_id); /* get name part of magnet urn */
+
+/* note, that rhash_info_by_id() is not exported to a shared library or DLL */
+const rhash_info* rhash_info_by_id(unsigned hash_id); /* get hash sum info by hash id */
+
+#if 0
+/**
+ * Flags for printing a hash sum
+ */
+enum rhash_print_sum_flags
+{
+	/** print in a default format */
+	RHPR_DEFAULT   = 0x0,
+	/** output as binary message digest */
+	RHPR_RAW       = 0x1,
+	/** print as a hexadecimal string */
+	RHPR_HEX       = 0x2,
+	/** print as a base32-encoded string */
+	RHPR_BASE32    = 0x3,
+	/** print as a base64-encoded string */
+	RHPR_BASE64    = 0x4,
+
+	/**
+	 * Print as an uppercase string. Can be used
+	 * for base32 or hexadecimal format only.
+	 */
+	RHPR_UPPERCASE = 0x8,
+
+	/**
+	 * Reverse hash bytes. Can be used for GOST hash.
+	 */
+	RHPR_REVERSE   = 0x10,
+
+	/** don't print 'magnet:?' prefix in rhash_print_magnet */
+	RHPR_NO_MAGNET  = 0x20,
+	/** print file size in rhash_print_magnet */
+	RHPR_FILESIZE  = 0x40,
+};
+#endif
+
+/* output hash into the given buffer */
+RHASH_API size_t rhash_print_bytes(char* output,
+	const unsigned char* bytes, size_t size, int flags);
+
+RHASH_API size_t rhash_print(char* output, rhash ctx, unsigned hash_id,
+	int flags);
+
+/* output magnet URL into the given buffer */
+RHASH_API size_t rhash_print_magnet(char* output, const char* filepath,
+	rhash context, unsigned hash_mask, int flags);
+
+/* macros for message API */
+
+/** The type of an unsigned integer large enough to hold a pointer */
+#if defined(UINTPTR_MAX)
+typedef uintptr_t rhash_uptr_t;
+#elif defined(_LP64) || defined(__LP64__) || defined(__x86_64) || \
+	defined(__x86_64__) || defined(_M_AMD64) || defined(_M_X64)
+typedef unsigned long long rhash_uptr_t;
+#else
+typedef unsigned long rhash_uptr_t;
+#endif
+
+/** The value returned by rhash_transmit on error */
+#define RHASH_ERROR ((rhash_uptr_t)-1)
+/** Convert a pointer to rhash_uptr_t */
+#define RHASH_STR2UPTR(str) ((rhash_uptr_t)(char*)(str))
+/** Convert a rhash_uptr_t to a void* pointer */
+#define RHASH_UPTR2PVOID(u) ((void*)((char*)0 + (u)))
+
+/* rhash API to set/get data via messages */
+RHASH_API rhash_uptr_t rhash_transmit(
+	unsigned msg_id, void* dst, rhash_uptr_t ldata, rhash_uptr_t rdata);
+
+/* rhash message constants */
+
+#define RMSG_GET_CONTEXT 1
+#define RMSG_CANCEL      2
+#define RMSG_IS_CANCELED 3
+#define RMSG_GET_FINALIZED 4
+#define RMSG_SET_AUTOFINAL 5
+#define RMSG_SET_OPENSSL_MASK 10
+#define RMSG_GET_OPENSSL_MASK 11
+
+/* helper macros */
+
+/** Get a pointer to context of the specified hash function */
+#define rhash_get_context_ptr(ctx, hash_id) RHASH_UPTR2PVOID(rhash_transmit(RMSG_GET_CONTEXT, ctx, hash_id, 0))
+/** Cancel hash calculation of a file */
+#define rhash_cancel(ctx) rhash_transmit(RMSG_CANCEL, ctx, 0, 0)
+/** Return non-zero if hash calculation was canceled, zero otherwise */
+#define rhash_is_canceled(ctx) rhash_transmit(RMSG_IS_CANCELED, ctx, 0, 0)
+/** Return non-zero if rhash_final was called for rhash_context */
+#define rhash_get_finalized(ctx) rhash_transmit(RMSG_GET_FINALIZED, ctx, 0, 0)
+
+/**
+ * Turn on/off the auto-final flag for the given rhash_context. By default
+ * auto-final is on, which means rhash_final is called automatically, if
+ * needed when a hash value is retrived by rhash_print call.
+ */
+#define rhash_set_autofinal(ctx, on) rhash_transmit(RMSG_SET_AUTOFINAL, ctx, on, 0)
+
+/**
+ * Set the bit-mask of hash algorithms to be calculated by OpenSSL library.
+ * The call rhash_set_openssl_mask(0) made before rhash_library_init(),
+ * turns off loading of the OpenSSL dynamic library.
+ * This call works if the LibRHash was compiled with OpenSSL support.
+ */
+#define rhash_set_openssl_mask(mask) rhash_transmit(RMSG_SET_OPENSSL_MASK, NULL, mask, 0)
+
+/**
+ * Return current bit-mask of hash algorithms selected to be calculated
+ * by OpenSSL library.
+ */
+#define rhash_get_openssl_mask() rhash_transmit(RMSG_GET_OPENSSL_MASK, NULL, 0, 0)
+
+/** The bit mask of hash algorithms implemented by OpenSSL */
+#if defined(USE_OPENSSL) || defined(OPENSSL_RUNTIME)
+# define RHASH_OPENSSL_SUPPORTED_HASHES (RHASH_MD4 | RHASH_MD5 | \
+	RHASH_SHA1 | RHASH_SHA224 | RHASH_SHA256 | RHASH_SHA384 | \
+	RHASH_SHA512 | RHASH_RIPEMD160 | RHASH_WHIRLPOOL)
+#else
+# define RHASH_OPENSSL_SUPPORTED_HASHES 0
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* RHASH_H */
diff --git a/Utilities/cmlibrhash/librhash/sha1.c b/Utilities/cmlibrhash/librhash/sha1.c
new file mode 100644
index 0000000..f5a053b
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha1.c
@@ -0,0 +1,196 @@
+/* sha1.c - an implementation of Secure Hash Algorithm 1 (SHA1)
+ * based on RFC 3174.
+ *
+ * Copyright: 2008-2012 Aleksey Kravchenko <rhash.admin at gmail.com>
+ *
+ * Permission is hereby granted,  free of charge,  to any person  obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction,  including without limitation
+ * the rights to  use, copy, modify,  merge, publish, distribute, sublicense,
+ * and/or sell copies  of  the Software,  and to permit  persons  to whom the
+ * Software is furnished to do so.
+ *
+ * This program  is  distributed  in  the  hope  that it will be useful,  but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  Use this program  at  your own risk!
+ */
+
+#include <string.h>
+#include "byte_order.h"
+#include "sha1.h"
+
+/**
+ * Initialize context before calculaing hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha1_init(sha1_ctx *ctx)
+{
+	ctx->length = 0;
+
+	/* initialize algorithm state */
+	ctx->hash[0] = 0x67452301;
+	ctx->hash[1] = 0xefcdab89;
+	ctx->hash[2] = 0x98badcfe;
+	ctx->hash[3] = 0x10325476;
+	ctx->hash[4] = 0xc3d2e1f0;
+}
+
+/**
+ * The core transformation. Process a 512-bit block.
+ * The function has been taken from RFC 3174 with little changes.
+ *
+ * @param hash algorithm state
+ * @param block the message block to process
+ */
+static void rhash_sha1_process_block(unsigned* hash, const unsigned* block)
+{
+	int           t;                 /* Loop counter */
+	uint32_t      temp;              /* Temporary word value */
+	uint32_t      W[80];             /* Word sequence */
+	uint32_t      A, B, C, D, E;     /* Word buffers */
+
+	/* initialize the first 16 words in the array W */
+	for (t = 0; t < 16; t++) {
+		/* note: it is much faster to apply be2me here, then using be32_copy */
+		W[t] = be2me_32(block[t]);
+	}
+
+	/* initialize the rest */
+	for (t = 16; t < 80; t++) {
+		W[t] = ROTL32(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
+	}
+
+	A = hash[0];
+	B = hash[1];
+	C = hash[2];
+	D = hash[3];
+	E = hash[4];
+
+	for (t = 0; t < 20; t++) {
+		/* the following is faster than ((B & C) | ((~B) & D)) */
+		temp =  ROTL32(A, 5) + (((C ^ D) & B) ^ D)
+			+ E + W[t] + 0x5A827999;
+		E = D;
+		D = C;
+		C = ROTL32(B, 30);
+		B = A;
+		A = temp;
+	}
+
+	for (t = 20; t < 40; t++) {
+		temp = ROTL32(A, 5) + (B ^ C ^ D) + E + W[t] + 0x6ED9EBA1;
+		E = D;
+		D = C;
+		C = ROTL32(B, 30);
+		B = A;
+		A = temp;
+	}
+
+	for (t = 40; t < 60; t++) {
+		temp = ROTL32(A, 5) + ((B & C) | (B & D) | (C & D))
+			+ E + W[t] + 0x8F1BBCDC;
+		E = D;
+		D = C;
+		C = ROTL32(B, 30);
+		B = A;
+		A = temp;
+	}
+
+	for (t = 60; t < 80; t++) {
+		temp = ROTL32(A, 5) + (B ^ C ^ D) + E + W[t] + 0xCA62C1D6;
+		E = D;
+		D = C;
+		C = ROTL32(B, 30);
+		B = A;
+		A = temp;
+	}
+
+	hash[0] += A;
+	hash[1] += B;
+	hash[2] += C;
+	hash[3] += D;
+	hash[4] += E;
+}
+
+/**
+ * Calculate message hash.
+ * Can be called repeatedly with chunks of the message to be hashed.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param msg message chunk
+ * @param size length of the message chunk
+ */
+void rhash_sha1_update(sha1_ctx *ctx, const unsigned char* msg, size_t size)
+{
+	unsigned index = (unsigned)ctx->length & 63;
+	ctx->length += size;
+
+	/* fill partial block */
+	if (index) {
+		unsigned left = sha1_block_size - index;
+		memcpy(ctx->message + index, msg, (size < left ? size : left));
+		if (size < left) return;
+
+		/* process partial block */
+		rhash_sha1_process_block(ctx->hash, (unsigned*)ctx->message);
+		msg  += left;
+		size -= left;
+	}
+	while (size >= sha1_block_size) {
+		unsigned* aligned_message_block;
+		if (IS_ALIGNED_32(msg)) {
+			/* the most common case is processing of an already aligned message
+			without copying it */
+			aligned_message_block = (unsigned*)msg;
+		} else {
+			memcpy(ctx->message, msg, sha1_block_size);
+			aligned_message_block = (unsigned*)ctx->message;
+		}
+
+		rhash_sha1_process_block(ctx->hash, aligned_message_block);
+		msg  += sha1_block_size;
+		size -= sha1_block_size;
+	}
+	if (size) {
+		/* save leftovers */
+		memcpy(ctx->message, msg, size);
+	}
+}
+
+/**
+ * Store calculated hash into the given array.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param result calculated hash in binary form
+ */
+void rhash_sha1_final(sha1_ctx *ctx, unsigned char* result)
+{
+	unsigned  index = (unsigned)ctx->length & 63;
+	unsigned* msg32 = (unsigned*)ctx->message;
+
+	/* pad message and run for last block */
+	ctx->message[index++] = 0x80;
+	while ((index & 3) != 0) {
+		ctx->message[index++] = 0;
+	}
+	index >>= 2;
+
+	/* if no room left in the message to store 64-bit message length */
+	if (index > 14) {
+		/* then fill the rest with zeros and process it */
+		while (index < 16) {
+			msg32[index++] = 0;
+		}
+		rhash_sha1_process_block(ctx->hash, msg32);
+		index = 0;
+	}
+	while (index < 14) {
+		msg32[index++] = 0;
+	}
+	msg32[14] = be2me_32( (unsigned)(ctx->length >> 29) );
+	msg32[15] = be2me_32( (unsigned)(ctx->length << 3) );
+	rhash_sha1_process_block(ctx->hash, msg32);
+
+	if (result) be32_copy(result, 0, &ctx->hash, sha1_hash_size);
+}
diff --git a/Utilities/cmlibrhash/librhash/sha1.h b/Utilities/cmlibrhash/librhash/sha1.h
new file mode 100644
index 0000000..74b2f94
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha1.h
@@ -0,0 +1,31 @@
+/* sha1.h */
+#ifndef SHA1_H
+#define SHA1_H
+#include "ustd.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define sha1_block_size 64
+#define sha1_hash_size  20
+
+/* algorithm context */
+typedef struct sha1_ctx
+{
+	unsigned char message[sha1_block_size]; /* 512-bit buffer for leftovers */
+	uint64_t length;   /* number of processed bytes */
+	unsigned hash[5];  /* 160-bit algorithm internal hashing state */
+} sha1_ctx;
+
+/* hash functions */
+
+void rhash_sha1_init(sha1_ctx *ctx);
+void rhash_sha1_update(sha1_ctx *ctx, const unsigned char* msg, size_t size);
+void rhash_sha1_final(sha1_ctx *ctx, unsigned char* result);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* SHA1_H */
diff --git a/Utilities/cmlibrhash/librhash/sha256.c b/Utilities/cmlibrhash/librhash/sha256.c
new file mode 100644
index 0000000..af5b0fe
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha256.c
@@ -0,0 +1,241 @@
+/* sha256.c - an implementation of SHA-256/224 hash functions
+ * based on FIPS 180-3 (Federal Information Processing Standart).
+ *
+ * Copyright: 2010-2012 Aleksey Kravchenko <rhash.admin at gmail.com>
+ *
+ * Permission is hereby granted,  free of charge,  to any person  obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction,  including without limitation
+ * the rights to  use, copy, modify,  merge, publish, distribute, sublicense,
+ * and/or sell copies  of  the Software,  and to permit  persons  to whom the
+ * Software is furnished to do so.
+ *
+ * This program  is  distributed  in  the  hope  that it will be useful,  but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  Use this program  at  your own risk!
+ */
+
+#include <string.h>
+#include "byte_order.h"
+#include "sha256.h"
+
+/* SHA-224 and SHA-256 constants for 64 rounds. These words represent
+ * the first 32 bits of the fractional parts of the cube
+ * roots of the first 64 prime numbers. */
+static const unsigned rhash_k256[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
+};
+
+/* The SHA256/224 functions defined by FIPS 180-3, 4.1.2 */
+/* Optimized version of Ch(x,y,z)=((x & y) | (~x & z)) */
+#define Ch(x,y,z)  ((z) ^ ((x) & ((y) ^ (z))))
+/* Optimized version of Maj(x,y,z)=((x & y) ^ (x & z) ^ (y & z)) */
+#define Maj(x,y,z) (((x) & (y)) ^ ((z) & ((x) ^ (y))))
+
+#define Sigma0(x) (ROTR32((x), 2) ^ ROTR32((x), 13) ^ ROTR32((x), 22))
+#define Sigma1(x) (ROTR32((x), 6) ^ ROTR32((x), 11) ^ ROTR32((x), 25))
+#define sigma0(x) (ROTR32((x), 7) ^ ROTR32((x), 18) ^ ((x) >>  3))
+#define sigma1(x) (ROTR32((x),17) ^ ROTR32((x), 19) ^ ((x) >> 10))
+
+/* Recalculate element n-th of circular buffer W using formula
+ *   W[n] = sigma1(W[n - 2]) + W[n - 7] + sigma0(W[n - 15]) + W[n - 16]; */
+#define RECALCULATE_W(W,n) (W[n] += \
+	(sigma1(W[(n - 2) & 15]) + W[(n - 7) & 15] + sigma0(W[(n - 15) & 15])))
+
+#define ROUND(a,b,c,d,e,f,g,h,k,data) { \
+	unsigned T1 = h + Sigma1(e) + Ch(e,f,g) + k + (data); \
+	d += T1, h = T1 + Sigma0(a) + Maj(a,b,c); }
+#define ROUND_1_16(a,b,c,d,e,f,g,h,n) \
+	ROUND(a,b,c,d,e,f,g,h, rhash_k256[n], W[n] = be2me_32(block[n]))
+#define ROUND_17_64(a,b,c,d,e,f,g,h,n) \
+	ROUND(a,b,c,d,e,f,g,h, k[n], RECALCULATE_W(W, n))
+
+/**
+ * Initialize context before calculaing hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha256_init(sha256_ctx *ctx)
+{
+	/* Initial values. These words were obtained by taking the first 32
+	 * bits of the fractional parts of the square roots of the first
+	 * eight prime numbers. */
+	static const unsigned SHA256_H0[8] = {
+		0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
+		0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
+	};
+
+	ctx->length = 0;
+	ctx->digest_length = sha256_hash_size;
+
+	/* initialize algorithm state */
+	memcpy(ctx->hash, SHA256_H0, sizeof(ctx->hash));
+}
+
+/**
+ * Initialize context before calculaing hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha224_init(struct sha256_ctx *ctx)
+{
+	/* Initial values from FIPS 180-3. These words were obtained by taking
+	 * bits from 33th to 64th of the fractional parts of the square
+	 * roots of ninth through sixteenth prime numbers. */
+	static const unsigned SHA224_H0[8] = {
+		0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
+		0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
+	};
+
+	ctx->length = 0;
+	ctx->digest_length = sha224_hash_size;
+
+	memcpy(ctx->hash, SHA224_H0, sizeof(ctx->hash));
+}
+
+/**
+ * The core transformation. Process a 512-bit block.
+ *
+ * @param hash algorithm state
+ * @param block the message block to process
+ */
+static void rhash_sha256_process_block(unsigned hash[8], unsigned block[16])
+{
+	unsigned A, B, C, D, E, F, G, H;
+	unsigned W[16];
+	const unsigned *k;
+	int i;
+
+	A = hash[0], B = hash[1], C = hash[2], D = hash[3];
+	E = hash[4], F = hash[5], G = hash[6], H = hash[7];
+
+	/* Compute SHA using alternate Method: FIPS 180-3 6.1.3 */
+	ROUND_1_16(A, B, C, D, E, F, G, H, 0);
+	ROUND_1_16(H, A, B, C, D, E, F, G, 1);
+	ROUND_1_16(G, H, A, B, C, D, E, F, 2);
+	ROUND_1_16(F, G, H, A, B, C, D, E, 3);
+	ROUND_1_16(E, F, G, H, A, B, C, D, 4);
+	ROUND_1_16(D, E, F, G, H, A, B, C, 5);
+	ROUND_1_16(C, D, E, F, G, H, A, B, 6);
+	ROUND_1_16(B, C, D, E, F, G, H, A, 7);
+	ROUND_1_16(A, B, C, D, E, F, G, H, 8);
+	ROUND_1_16(H, A, B, C, D, E, F, G, 9);
+	ROUND_1_16(G, H, A, B, C, D, E, F, 10);
+	ROUND_1_16(F, G, H, A, B, C, D, E, 11);
+	ROUND_1_16(E, F, G, H, A, B, C, D, 12);
+	ROUND_1_16(D, E, F, G, H, A, B, C, 13);
+	ROUND_1_16(C, D, E, F, G, H, A, B, 14);
+	ROUND_1_16(B, C, D, E, F, G, H, A, 15);
+
+	for (i = 16, k = &rhash_k256[16]; i < 64; i += 16, k += 16) {
+		ROUND_17_64(A, B, C, D, E, F, G, H,  0);
+		ROUND_17_64(H, A, B, C, D, E, F, G,  1);
+		ROUND_17_64(G, H, A, B, C, D, E, F,  2);
+		ROUND_17_64(F, G, H, A, B, C, D, E,  3);
+		ROUND_17_64(E, F, G, H, A, B, C, D,  4);
+		ROUND_17_64(D, E, F, G, H, A, B, C,  5);
+		ROUND_17_64(C, D, E, F, G, H, A, B,  6);
+		ROUND_17_64(B, C, D, E, F, G, H, A,  7);
+		ROUND_17_64(A, B, C, D, E, F, G, H,  8);
+		ROUND_17_64(H, A, B, C, D, E, F, G,  9);
+		ROUND_17_64(G, H, A, B, C, D, E, F, 10);
+		ROUND_17_64(F, G, H, A, B, C, D, E, 11);
+		ROUND_17_64(E, F, G, H, A, B, C, D, 12);
+		ROUND_17_64(D, E, F, G, H, A, B, C, 13);
+		ROUND_17_64(C, D, E, F, G, H, A, B, 14);
+		ROUND_17_64(B, C, D, E, F, G, H, A, 15);
+	}
+
+	hash[0] += A, hash[1] += B, hash[2] += C, hash[3] += D;
+	hash[4] += E, hash[5] += F, hash[6] += G, hash[7] += H;
+}
+
+/**
+ * Calculate message hash.
+ * Can be called repeatedly with chunks of the message to be hashed.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param msg message chunk
+ * @param size length of the message chunk
+ */
+void rhash_sha256_update(sha256_ctx *ctx, const unsigned char *msg, size_t size)
+{
+	size_t index = (size_t)ctx->length & 63;
+	ctx->length += size;
+
+	/* fill partial block */
+	if (index) {
+		size_t left = sha256_block_size - index;
+		memcpy((char*)ctx->message + index, msg, (size < left ? size : left));
+		if (size < left) return;
+
+		/* process partial block */
+		rhash_sha256_process_block(ctx->hash, (unsigned*)ctx->message);
+		msg  += left;
+		size -= left;
+	}
+	while (size >= sha256_block_size) {
+		unsigned* aligned_message_block;
+		if (IS_ALIGNED_32(msg)) {
+			/* the most common case is processing of an already aligned message
+			without copying it */
+			aligned_message_block = (unsigned*)msg;
+		} else {
+			memcpy(ctx->message, msg, sha256_block_size);
+			aligned_message_block = (unsigned*)ctx->message;
+		}
+
+		rhash_sha256_process_block(ctx->hash, aligned_message_block);
+		msg  += sha256_block_size;
+		size -= sha256_block_size;
+	}
+	if (size) {
+		memcpy(ctx->message, msg, size); /* save leftovers */
+	}
+}
+
+/**
+ * Store calculated hash into the given array.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param result calculated hash in binary form
+ */
+void rhash_sha256_final(sha256_ctx *ctx, unsigned char* result)
+{
+	size_t index = ((unsigned)ctx->length & 63) >> 2;
+	unsigned shift = ((unsigned)ctx->length & 3) * 8;
+
+	/* pad message and run for last block */
+
+	/* append the byte 0x80 to the message */
+	ctx->message[index]   &= le2me_32(~(0xFFFFFFFFu << shift));
+	ctx->message[index++] ^= le2me_32(0x80u << shift);
+
+	/* if no room left in the message to store 64-bit message length */
+	if (index > 14) {
+		/* then fill the rest with zeros and process it */
+		while (index < 16) {
+			ctx->message[index++] = 0;
+		}
+		rhash_sha256_process_block(ctx->hash, ctx->message);
+		index = 0;
+	}
+	while (index < 14) {
+		ctx->message[index++] = 0;
+	}
+	ctx->message[14] = be2me_32( (unsigned)(ctx->length >> 29) );
+	ctx->message[15] = be2me_32( (unsigned)(ctx->length << 3) );
+	rhash_sha256_process_block(ctx->hash, ctx->message);
+
+	if (result) be32_copy(result, 0, ctx->hash, ctx->digest_length);
+}
diff --git a/Utilities/cmlibrhash/librhash/sha256.h b/Utilities/cmlibrhash/librhash/sha256.h
new file mode 100644
index 0000000..f87ebaa
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha256.h
@@ -0,0 +1,32 @@
+/* sha.h sha256 and sha224 hash functions */
+#ifndef SHA256_H
+#define SHA256_H
+#include "ustd.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define sha256_block_size 64
+#define sha256_hash_size  32
+#define sha224_hash_size  28
+
+/* algorithm context */
+typedef struct sha256_ctx
+{
+	unsigned message[16];   /* 512-bit buffer for leftovers */
+	uint64_t length;        /* number of processed bytes */
+	unsigned hash[8];       /* 256-bit algorithm internal hashing state */
+	unsigned digest_length; /* length of the algorithm digest in bytes */
+} sha256_ctx;
+
+void rhash_sha224_init(sha256_ctx *ctx);
+void rhash_sha256_init(sha256_ctx *ctx);
+void rhash_sha256_update(sha256_ctx *ctx, const unsigned char* data, size_t length);
+void rhash_sha256_final(sha256_ctx *ctx, unsigned char result[32]);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* SHA256_H */
diff --git a/Utilities/cmlibrhash/librhash/sha3.c b/Utilities/cmlibrhash/librhash/sha3.c
new file mode 100644
index 0000000..e4a845f
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha3.c
@@ -0,0 +1,356 @@
+/* sha3.c - an implementation of Secure Hash Algorithm 3 (Keccak).
+ * based on the
+ * The Keccak SHA-3 submission. Submission to NIST (Round 3), 2011
+ * by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche
+ *
+ * Copyright: 2013 Aleksey Kravchenko <rhash.admin at gmail.com>
+ *
+ * Permission is hereby granted,  free of charge,  to any person  obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction,  including without limitation
+ * the rights to  use, copy, modify,  merge, publish, distribute, sublicense,
+ * and/or sell copies  of  the Software,  and to permit  persons  to whom the
+ * Software is furnished to do so.
+ *
+ * This program  is  distributed  in  the  hope  that it will be useful,  but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  Use this program  at  your own risk!
+ */
+
+#include <assert.h>
+#include <string.h>
+#include "byte_order.h"
+#include "sha3.h"
+
+/* constants */
+#define NumberOfRounds 24
+
+/* SHA3 (Keccak) constants for 24 rounds */
+static uint64_t keccak_round_constants[NumberOfRounds] = {
+	I64(0x0000000000000001), I64(0x0000000000008082), I64(0x800000000000808A), I64(0x8000000080008000),
+	I64(0x000000000000808B), I64(0x0000000080000001), I64(0x8000000080008081), I64(0x8000000000008009),
+	I64(0x000000000000008A), I64(0x0000000000000088), I64(0x0000000080008009), I64(0x000000008000000A),
+	I64(0x000000008000808B), I64(0x800000000000008B), I64(0x8000000000008089), I64(0x8000000000008003),
+	I64(0x8000000000008002), I64(0x8000000000000080), I64(0x000000000000800A), I64(0x800000008000000A),
+	I64(0x8000000080008081), I64(0x8000000000008080), I64(0x0000000080000001), I64(0x8000000080008008)
+};
+
+/* Initializing a sha3 context for given number of output bits */
+static void rhash_keccak_init(sha3_ctx *ctx, unsigned bits)
+{
+	/* NB: The Keccak capacity parameter = bits * 2 */
+	unsigned rate = 1600 - bits * 2;
+
+	memset(ctx, 0, sizeof(sha3_ctx));
+	ctx->block_size = rate / 8;
+	assert(rate <= 1600 && (rate % 64) == 0);
+}
+
+/**
+ * Initialize context before calculating hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha3_224_init(sha3_ctx *ctx)
+{
+	rhash_keccak_init(ctx, 224);
+}
+
+/**
+ * Initialize context before calculating hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha3_256_init(sha3_ctx *ctx)
+{
+	rhash_keccak_init(ctx, 256);
+}
+
+/**
+ * Initialize context before calculating hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha3_384_init(sha3_ctx *ctx)
+{
+	rhash_keccak_init(ctx, 384);
+}
+
+/**
+ * Initialize context before calculating hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha3_512_init(sha3_ctx *ctx)
+{
+	rhash_keccak_init(ctx, 512);
+}
+
+/* Keccak theta() transformation */
+static void keccak_theta(uint64_t *A)
+{
+	unsigned int x;
+	uint64_t C[5], D[5];
+
+	for (x = 0; x < 5; x++) {
+		C[x] = A[x] ^ A[x + 5] ^ A[x + 10] ^ A[x + 15] ^ A[x + 20];
+	}
+	D[0] = ROTL64(C[1], 1) ^ C[4];
+	D[1] = ROTL64(C[2], 1) ^ C[0];
+	D[2] = ROTL64(C[3], 1) ^ C[1];
+	D[3] = ROTL64(C[4], 1) ^ C[2];
+	D[4] = ROTL64(C[0], 1) ^ C[3];
+
+	for (x = 0; x < 5; x++) {
+		A[x]      ^= D[x];
+		A[x + 5]  ^= D[x];
+		A[x + 10] ^= D[x];
+		A[x + 15] ^= D[x];
+		A[x + 20] ^= D[x];
+	}
+}
+
+/* Keccak pi() transformation */
+static void keccak_pi(uint64_t *A)
+{
+	uint64_t A1;
+	A1 = A[1];
+	A[ 1] = A[ 6];
+	A[ 6] = A[ 9];
+	A[ 9] = A[22];
+	A[22] = A[14];
+	A[14] = A[20];
+	A[20] = A[ 2];
+	A[ 2] = A[12];
+	A[12] = A[13];
+	A[13] = A[19];
+	A[19] = A[23];
+	A[23] = A[15];
+	A[15] = A[ 4];
+	A[ 4] = A[24];
+	A[24] = A[21];
+	A[21] = A[ 8];
+	A[ 8] = A[16];
+	A[16] = A[ 5];
+	A[ 5] = A[ 3];
+	A[ 3] = A[18];
+	A[18] = A[17];
+	A[17] = A[11];
+	A[11] = A[ 7];
+	A[ 7] = A[10];
+	A[10] = A1;
+	/* note: A[ 0] is left as is */
+}
+
+/* Keccak chi() transformation */
+static void keccak_chi(uint64_t *A)
+{
+	int i;
+	for (i = 0; i < 25; i += 5) {
+		uint64_t A0 = A[0 + i], A1 = A[1 + i];
+		A[0 + i] ^= ~A1 & A[2 + i];
+		A[1 + i] ^= ~A[2 + i] & A[3 + i];
+		A[2 + i] ^= ~A[3 + i] & A[4 + i];
+		A[3 + i] ^= ~A[4 + i] & A0;
+		A[4 + i] ^= ~A0 & A1;
+	}
+}
+
+static void rhash_sha3_permutation(uint64_t *state)
+{
+	int round;
+	for (round = 0; round < NumberOfRounds; round++)
+	{
+		keccak_theta(state);
+
+		/* apply Keccak rho() transformation */
+		state[ 1] = ROTL64(state[ 1],  1);
+		state[ 2] = ROTL64(state[ 2], 62);
+		state[ 3] = ROTL64(state[ 3], 28);
+		state[ 4] = ROTL64(state[ 4], 27);
+		state[ 5] = ROTL64(state[ 5], 36);
+		state[ 6] = ROTL64(state[ 6], 44);
+		state[ 7] = ROTL64(state[ 7],  6);
+		state[ 8] = ROTL64(state[ 8], 55);
+		state[ 9] = ROTL64(state[ 9], 20);
+		state[10] = ROTL64(state[10],  3);
+		state[11] = ROTL64(state[11], 10);
+		state[12] = ROTL64(state[12], 43);
+		state[13] = ROTL64(state[13], 25);
+		state[14] = ROTL64(state[14], 39);
+		state[15] = ROTL64(state[15], 41);
+		state[16] = ROTL64(state[16], 45);
+		state[17] = ROTL64(state[17], 15);
+		state[18] = ROTL64(state[18], 21);
+		state[19] = ROTL64(state[19],  8);
+		state[20] = ROTL64(state[20], 18);
+		state[21] = ROTL64(state[21],  2);
+		state[22] = ROTL64(state[22], 61);
+		state[23] = ROTL64(state[23], 56);
+		state[24] = ROTL64(state[24], 14);
+
+		keccak_pi(state);
+		keccak_chi(state);
+
+		/* apply iota(state, round) */
+		*state ^= keccak_round_constants[round];
+	}
+}
+
+/**
+ * The core transformation. Process the specified block of data.
+ *
+ * @param hash the algorithm state
+ * @param block the message block to process
+ * @param block_size the size of the processed block in bytes
+ */
+static void rhash_sha3_process_block(uint64_t hash[25], const uint64_t *block, size_t block_size)
+{
+	/* expanded loop */
+	hash[ 0] ^= le2me_64(block[ 0]);
+	hash[ 1] ^= le2me_64(block[ 1]);
+	hash[ 2] ^= le2me_64(block[ 2]);
+	hash[ 3] ^= le2me_64(block[ 3]);
+	hash[ 4] ^= le2me_64(block[ 4]);
+	hash[ 5] ^= le2me_64(block[ 5]);
+	hash[ 6] ^= le2me_64(block[ 6]);
+	hash[ 7] ^= le2me_64(block[ 7]);
+	hash[ 8] ^= le2me_64(block[ 8]);
+	/* if not sha3-512 */
+	if (block_size > 72) {
+		hash[ 9] ^= le2me_64(block[ 9]);
+		hash[10] ^= le2me_64(block[10]);
+		hash[11] ^= le2me_64(block[11]);
+		hash[12] ^= le2me_64(block[12]);
+		/* if not sha3-384 */
+		if (block_size > 104) {
+			hash[13] ^= le2me_64(block[13]);
+			hash[14] ^= le2me_64(block[14]);
+			hash[15] ^= le2me_64(block[15]);
+			hash[16] ^= le2me_64(block[16]);
+			/* if not sha3-256 */
+			if (block_size > 136) {
+				hash[17] ^= le2me_64(block[17]);
+#ifdef FULL_SHA3_FAMILY_SUPPORT
+				/* if not sha3-224 */
+				if (block_size > 144) {
+					hash[18] ^= le2me_64(block[18]);
+					hash[19] ^= le2me_64(block[19]);
+					hash[20] ^= le2me_64(block[20]);
+					hash[21] ^= le2me_64(block[21]);
+					hash[22] ^= le2me_64(block[22]);
+					hash[23] ^= le2me_64(block[23]);
+					hash[24] ^= le2me_64(block[24]);
+				}
+#endif
+			}
+		}
+	}
+	/* make a permutation of the hash */
+	rhash_sha3_permutation(hash);
+}
+
+#define SHA3_FINALIZED 0x80000000
+
+/**
+ * Calculate message hash.
+ * Can be called repeatedly with chunks of the message to be hashed.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param msg message chunk
+ * @param size length of the message chunk
+ */
+void rhash_sha3_update(sha3_ctx *ctx, const unsigned char *msg, size_t size)
+{
+	size_t index = (size_t)ctx->rest;
+	size_t block_size = (size_t)ctx->block_size;
+
+	if (ctx->rest & SHA3_FINALIZED) return; /* too late for additional input */
+	ctx->rest = (unsigned)((ctx->rest + size) % block_size);
+
+	/* fill partial block */
+	if (index) {
+		size_t left = block_size - index;
+		memcpy((char*)ctx->message + index, msg, (size < left ? size : left));
+		if (size < left) return;
+
+		/* process partial block */
+		rhash_sha3_process_block(ctx->hash, ctx->message, block_size);
+		msg  += left;
+		size -= left;
+	}
+	while (size >= block_size) {
+		uint64_t* aligned_message_block;
+		if (IS_ALIGNED_64(msg)) {
+			/* the most common case is processing of an already aligned message
+			without copying it */
+			aligned_message_block = (uint64_t*)msg;
+		} else {
+			memcpy(ctx->message, msg, block_size);
+			aligned_message_block = ctx->message;
+		}
+
+		rhash_sha3_process_block(ctx->hash, aligned_message_block, block_size);
+		msg  += block_size;
+		size -= block_size;
+	}
+	if (size) {
+		memcpy(ctx->message, msg, size); /* save leftovers */
+	}
+}
+
+/**
+ * Store calculated hash into the given array.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param result calculated hash in binary form
+ */
+void rhash_sha3_final(sha3_ctx *ctx, unsigned char* result)
+{
+	size_t digest_length = 100 - ctx->block_size / 2;
+	const size_t block_size = ctx->block_size;
+
+	if (!(ctx->rest & SHA3_FINALIZED))
+	{
+		/* clear the rest of the data queue */
+		memset((char*)ctx->message + ctx->rest, 0, block_size - ctx->rest);
+		((char*)ctx->message)[ctx->rest] |= 0x06;
+		((char*)ctx->message)[block_size - 1] |= 0x80;
+
+		/* process final block */
+		rhash_sha3_process_block(ctx->hash, ctx->message, block_size);
+		ctx->rest = SHA3_FINALIZED; /* mark context as finalized */
+	}
+
+	assert(block_size > digest_length);
+	if (result) me64_to_le_str(result, ctx->hash, digest_length);
+}
+
+#ifdef USE_KECCAK
+/**
+* Store calculated hash into the given array.
+*
+* @param ctx the algorithm context containing current hashing state
+* @param result calculated hash in binary form
+*/
+void rhash_keccak_final(sha3_ctx *ctx, unsigned char* result)
+{
+	size_t digest_length = 100 - ctx->block_size / 2;
+	const size_t block_size = ctx->block_size;
+
+	if (!(ctx->rest & SHA3_FINALIZED))
+	{
+		/* clear the rest of the data queue */
+		memset((char*)ctx->message + ctx->rest, 0, block_size - ctx->rest);
+		((char*)ctx->message)[ctx->rest] |= 0x01;
+		((char*)ctx->message)[block_size - 1] |= 0x80;
+
+		/* process final block */
+		rhash_sha3_process_block(ctx->hash, ctx->message, block_size);
+		ctx->rest = SHA3_FINALIZED; /* mark context as finalized */
+	}
+
+	assert(block_size > digest_length);
+	if (result) me64_to_le_str(result, ctx->hash, digest_length);
+}
+#endif /* USE_KECCAK */
diff --git a/Utilities/cmlibrhash/librhash/sha3.h b/Utilities/cmlibrhash/librhash/sha3.h
new file mode 100644
index 0000000..2831997
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha3.h
@@ -0,0 +1,54 @@
+/* sha3.h */
+#ifndef RHASH_SHA3_H
+#define RHASH_SHA3_H
+#include "ustd.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define sha3_224_hash_size  28
+#define sha3_256_hash_size  32
+#define sha3_384_hash_size  48
+#define sha3_512_hash_size  64
+#define sha3_max_permutation_size 25
+#define sha3_max_rate_in_qwords 24
+
+/**
+ * SHA3 Algorithm context.
+ */
+typedef struct sha3_ctx
+{
+	/* 1600 bits algorithm hashing state */
+	uint64_t hash[sha3_max_permutation_size];
+	/* 1536-bit buffer for leftovers */
+	uint64_t message[sha3_max_rate_in_qwords];
+	/* count of bytes in the message[] buffer */
+	unsigned rest;
+	/* size of a message block processed at once */
+	unsigned block_size;
+} sha3_ctx;
+
+/* methods for calculating the hash function */
+
+void rhash_sha3_224_init(sha3_ctx *ctx);
+void rhash_sha3_256_init(sha3_ctx *ctx);
+void rhash_sha3_384_init(sha3_ctx *ctx);
+void rhash_sha3_512_init(sha3_ctx *ctx);
+void rhash_sha3_update(sha3_ctx *ctx, const unsigned char* msg, size_t size);
+void rhash_sha3_final(sha3_ctx *ctx, unsigned char* result);
+
+#ifdef USE_KECCAK
+#define rhash_keccak_224_init rhash_sha3_224_init
+#define rhash_keccak_256_init rhash_sha3_256_init
+#define rhash_keccak_384_init rhash_sha3_384_init
+#define rhash_keccak_512_init rhash_sha3_512_init
+#define rhash_keccak_update rhash_sha3_update
+void rhash_keccak_final(sha3_ctx *ctx, unsigned char* result);
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* RHASH_SHA3_H */
diff --git a/Utilities/cmlibrhash/librhash/sha512.c b/Utilities/cmlibrhash/librhash/sha512.c
new file mode 100644
index 0000000..a3e681d
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha512.c
@@ -0,0 +1,255 @@
+/* sha512.c - an implementation of SHA-384/512 hash functions
+ * based on FIPS 180-3 (Federal Information Processing Standart).
+ *
+ * Copyright: 2010-2012 Aleksey Kravchenko <rhash.admin at gmail.com>
+ *
+ * Permission is hereby granted,  free of charge,  to any person  obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction,  including without limitation
+ * the rights to  use, copy, modify,  merge, publish, distribute, sublicense,
+ * and/or sell copies  of  the Software,  and to permit  persons  to whom the
+ * Software is furnished to do so.
+ *
+ * This program  is  distributed  in  the  hope  that it will be useful,  but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  Use this program  at  your own risk!
+ */
+
+#include <string.h>
+#include "byte_order.h"
+#include "sha512.h"
+
+/* SHA-384 and SHA-512 constants for 80 rounds. These qwords represent
+ * the first 64 bits of the fractional parts of the cube
+ * roots of the first 80 prime numbers. */
+static const uint64_t rhash_k512[80] = {
+	I64(0x428a2f98d728ae22), I64(0x7137449123ef65cd), I64(0xb5c0fbcfec4d3b2f),
+	I64(0xe9b5dba58189dbbc), I64(0x3956c25bf348b538), I64(0x59f111f1b605d019),
+	I64(0x923f82a4af194f9b), I64(0xab1c5ed5da6d8118), I64(0xd807aa98a3030242),
+	I64(0x12835b0145706fbe), I64(0x243185be4ee4b28c), I64(0x550c7dc3d5ffb4e2),
+	I64(0x72be5d74f27b896f), I64(0x80deb1fe3b1696b1), I64(0x9bdc06a725c71235),
+	I64(0xc19bf174cf692694), I64(0xe49b69c19ef14ad2), I64(0xefbe4786384f25e3),
+	I64(0x0fc19dc68b8cd5b5), I64(0x240ca1cc77ac9c65), I64(0x2de92c6f592b0275),
+	I64(0x4a7484aa6ea6e483), I64(0x5cb0a9dcbd41fbd4), I64(0x76f988da831153b5),
+	I64(0x983e5152ee66dfab), I64(0xa831c66d2db43210), I64(0xb00327c898fb213f),
+	I64(0xbf597fc7beef0ee4), I64(0xc6e00bf33da88fc2), I64(0xd5a79147930aa725),
+	I64(0x06ca6351e003826f), I64(0x142929670a0e6e70), I64(0x27b70a8546d22ffc),
+	I64(0x2e1b21385c26c926), I64(0x4d2c6dfc5ac42aed), I64(0x53380d139d95b3df),
+	I64(0x650a73548baf63de), I64(0x766a0abb3c77b2a8), I64(0x81c2c92e47edaee6),
+	I64(0x92722c851482353b), I64(0xa2bfe8a14cf10364), I64(0xa81a664bbc423001),
+	I64(0xc24b8b70d0f89791), I64(0xc76c51a30654be30), I64(0xd192e819d6ef5218),
+	I64(0xd69906245565a910), I64(0xf40e35855771202a), I64(0x106aa07032bbd1b8),
+	I64(0x19a4c116b8d2d0c8), I64(0x1e376c085141ab53), I64(0x2748774cdf8eeb99),
+	I64(0x34b0bcb5e19b48a8), I64(0x391c0cb3c5c95a63), I64(0x4ed8aa4ae3418acb),
+	I64(0x5b9cca4f7763e373), I64(0x682e6ff3d6b2b8a3), I64(0x748f82ee5defb2fc),
+	I64(0x78a5636f43172f60), I64(0x84c87814a1f0ab72), I64(0x8cc702081a6439ec),
+	I64(0x90befffa23631e28), I64(0xa4506cebde82bde9), I64(0xbef9a3f7b2c67915),
+	I64(0xc67178f2e372532b), I64(0xca273eceea26619c), I64(0xd186b8c721c0c207),
+	I64(0xeada7dd6cde0eb1e), I64(0xf57d4f7fee6ed178), I64(0x06f067aa72176fba),
+	I64(0x0a637dc5a2c898a6), I64(0x113f9804bef90dae), I64(0x1b710b35131c471b),
+	I64(0x28db77f523047d84), I64(0x32caab7b40c72493), I64(0x3c9ebe0a15c9bebc),
+	I64(0x431d67c49c100d4c), I64(0x4cc5d4becb3e42b6), I64(0x597f299cfc657e2a),
+	I64(0x5fcb6fab3ad6faec), I64(0x6c44198c4a475817)
+};
+
+/* The SHA512/384 functions defined by FIPS 180-3, 4.1.3 */
+/* Optimized version of Ch(x,y,z)=((x & y) | (~x & z)) */
+#define Ch(x,y,z)  ((z) ^ ((x) & ((y) ^ (z))))
+/* Optimized version of Maj(x,y,z)=((x & y) ^ (x & z) ^ (y & z)) */
+#define Maj(x,y,z) (((x) & (y)) ^ ((z) & ((x) ^ (y))))
+
+#define Sigma0(x) (ROTR64((x), 28) ^ ROTR64((x), 34) ^ ROTR64((x), 39))
+#define Sigma1(x) (ROTR64((x), 14) ^ ROTR64((x), 18) ^ ROTR64((x), 41))
+#define sigma0(x) (ROTR64((x),  1) ^ ROTR64((x),  8) ^ ((x) >> 7))
+#define sigma1(x) (ROTR64((x), 19) ^ ROTR64((x), 61) ^ ((x) >> 6))
+
+/* Recalculate element n-th of circular buffer W using formula
+ *   W[n] = sigma1(W[n - 2]) + W[n - 7] + sigma0(W[n - 15]) + W[n - 16]; */
+#define RECALCULATE_W(W,n) (W[n] += \
+	(sigma1(W[(n - 2) & 15]) + W[(n - 7) & 15] + sigma0(W[(n - 15) & 15])))
+
+#define ROUND(a,b,c,d,e,f,g,h,k,data) { \
+	uint64_t T1 = h + Sigma1(e) + Ch(e,f,g) + k + (data); \
+	d += T1, h = T1 + Sigma0(a) + Maj(a,b,c); }
+#define ROUND_1_16(a,b,c,d,e,f,g,h,n) \
+	ROUND(a,b,c,d,e,f,g,h, rhash_k512[n], W[n] = be2me_64(block[n]))
+#define ROUND_17_80(a,b,c,d,e,f,g,h,n) \
+	ROUND(a,b,c,d,e,f,g,h, k[n], RECALCULATE_W(W, n))
+
+/**
+ * Initialize context before calculating hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha512_init(sha512_ctx *ctx)
+{
+	/* Initial values. These words were obtained by taking the first 32
+	 * bits of the fractional parts of the square roots of the first
+	 * eight prime numbers. */
+	static const uint64_t SHA512_H0[8] = {
+		I64(0x6a09e667f3bcc908), I64(0xbb67ae8584caa73b), I64(0x3c6ef372fe94f82b),
+		I64(0xa54ff53a5f1d36f1), I64(0x510e527fade682d1), I64(0x9b05688c2b3e6c1f),
+		I64(0x1f83d9abfb41bd6b), I64(0x5be0cd19137e2179)
+	};
+
+	ctx->length = 0;
+	ctx->digest_length = sha512_hash_size;
+
+	/* initialize algorithm state */
+	memcpy(ctx->hash, SHA512_H0, sizeof(ctx->hash));
+}
+
+/**
+ * Initialize context before calculaing hash.
+ *
+ * @param ctx context to initialize
+ */
+void rhash_sha384_init(struct sha512_ctx *ctx)
+{
+	/* Initial values from FIPS 180-3. These words were obtained by taking
+	 * the first sixty-four bits of the fractional parts of the square
+	 * roots of ninth through sixteenth prime numbers. */
+	static const uint64_t SHA384_H0[8] = {
+		I64(0xcbbb9d5dc1059ed8), I64(0x629a292a367cd507), I64(0x9159015a3070dd17),
+		I64(0x152fecd8f70e5939), I64(0x67332667ffc00b31), I64(0x8eb44a8768581511),
+		I64(0xdb0c2e0d64f98fa7), I64(0x47b5481dbefa4fa4)
+	};
+
+	ctx->length = 0;
+	ctx->digest_length = sha384_hash_size;
+
+	memcpy(ctx->hash, SHA384_H0, sizeof(ctx->hash));
+}
+
+/**
+ * The core transformation. Process a 512-bit block.
+ *
+ * @param hash algorithm state
+ * @param block the message block to process
+ */
+static void rhash_sha512_process_block(uint64_t hash[8], uint64_t block[16])
+{
+	uint64_t A, B, C, D, E, F, G, H;
+	uint64_t W[16];
+	const uint64_t *k;
+	int i;
+
+	A = hash[0], B = hash[1], C = hash[2], D = hash[3];
+	E = hash[4], F = hash[5], G = hash[6], H = hash[7];
+
+	/* Compute SHA using alternate Method: FIPS 180-3 6.1.3 */
+	ROUND_1_16(A, B, C, D, E, F, G, H, 0);
+	ROUND_1_16(H, A, B, C, D, E, F, G, 1);
+	ROUND_1_16(G, H, A, B, C, D, E, F, 2);
+	ROUND_1_16(F, G, H, A, B, C, D, E, 3);
+	ROUND_1_16(E, F, G, H, A, B, C, D, 4);
+	ROUND_1_16(D, E, F, G, H, A, B, C, 5);
+	ROUND_1_16(C, D, E, F, G, H, A, B, 6);
+	ROUND_1_16(B, C, D, E, F, G, H, A, 7);
+	ROUND_1_16(A, B, C, D, E, F, G, H, 8);
+	ROUND_1_16(H, A, B, C, D, E, F, G, 9);
+	ROUND_1_16(G, H, A, B, C, D, E, F, 10);
+	ROUND_1_16(F, G, H, A, B, C, D, E, 11);
+	ROUND_1_16(E, F, G, H, A, B, C, D, 12);
+	ROUND_1_16(D, E, F, G, H, A, B, C, 13);
+	ROUND_1_16(C, D, E, F, G, H, A, B, 14);
+	ROUND_1_16(B, C, D, E, F, G, H, A, 15);
+
+	for (i = 16, k = &rhash_k512[16]; i < 80; i += 16, k += 16) {
+		ROUND_17_80(A, B, C, D, E, F, G, H,  0);
+		ROUND_17_80(H, A, B, C, D, E, F, G,  1);
+		ROUND_17_80(G, H, A, B, C, D, E, F,  2);
+		ROUND_17_80(F, G, H, A, B, C, D, E,  3);
+		ROUND_17_80(E, F, G, H, A, B, C, D,  4);
+		ROUND_17_80(D, E, F, G, H, A, B, C,  5);
+		ROUND_17_80(C, D, E, F, G, H, A, B,  6);
+		ROUND_17_80(B, C, D, E, F, G, H, A,  7);
+		ROUND_17_80(A, B, C, D, E, F, G, H,  8);
+		ROUND_17_80(H, A, B, C, D, E, F, G,  9);
+		ROUND_17_80(G, H, A, B, C, D, E, F, 10);
+		ROUND_17_80(F, G, H, A, B, C, D, E, 11);
+		ROUND_17_80(E, F, G, H, A, B, C, D, 12);
+		ROUND_17_80(D, E, F, G, H, A, B, C, 13);
+		ROUND_17_80(C, D, E, F, G, H, A, B, 14);
+		ROUND_17_80(B, C, D, E, F, G, H, A, 15);
+	}
+
+	hash[0] += A, hash[1] += B, hash[2] += C, hash[3] += D;
+	hash[4] += E, hash[5] += F, hash[6] += G, hash[7] += H;
+}
+
+/**
+ * Calculate message hash.
+ * Can be called repeatedly with chunks of the message to be hashed.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param msg message chunk
+ * @param size length of the message chunk
+ */
+void rhash_sha512_update(sha512_ctx *ctx, const unsigned char *msg, size_t size)
+{
+	size_t index = (size_t)ctx->length & 127;
+	ctx->length += size;
+
+	/* fill partial block */
+	if (index) {
+		size_t left = sha512_block_size - index;
+		memcpy((char*)ctx->message + index, msg, (size < left ? size : left));
+		if (size < left) return;
+
+		/* process partial block */
+		rhash_sha512_process_block(ctx->hash, ctx->message);
+		msg  += left;
+		size -= left;
+	}
+	while (size >= sha512_block_size) {
+		uint64_t* aligned_message_block;
+		if (IS_ALIGNED_64(msg)) {
+			/* the most common case is processing of an already aligned message
+			without copying it */
+			aligned_message_block = (uint64_t*)msg;
+		} else {
+			memcpy(ctx->message, msg, sha512_block_size);
+			aligned_message_block = ctx->message;
+		}
+
+		rhash_sha512_process_block(ctx->hash, aligned_message_block);
+		msg  += sha512_block_size;
+		size -= sha512_block_size;
+	}
+	if (size) {
+		memcpy(ctx->message, msg, size); /* save leftovers */
+	}
+}
+
+/**
+ * Store calculated hash into the given array.
+ *
+ * @param ctx the algorithm context containing current hashing state
+ * @param result calculated hash in binary form
+ */
+void rhash_sha512_final(sha512_ctx *ctx, unsigned char* result)
+{
+	size_t index = ((unsigned)ctx->length & 127) >> 3;
+	unsigned shift = ((unsigned)ctx->length & 7) * 8;
+
+	/* pad message and process the last block */
+
+	/* append the byte 0x80 to the message */
+	ctx->message[index]   &= le2me_64( ~(I64(0xFFFFFFFFFFFFFFFF) << shift) );
+	ctx->message[index++] ^= le2me_64( I64(0x80) << shift );
+
+	/* if no room left in the message to store 128-bit message length */
+	if (index >= 15) {
+		if (index == 15) ctx->message[index] = 0;
+		rhash_sha512_process_block(ctx->hash, ctx->message);
+		index = 0;
+	}
+	while (index < 15) {
+		ctx->message[index++] = 0;
+	}
+	ctx->message[15] = be2me_64(ctx->length << 3);
+	rhash_sha512_process_block(ctx->hash, ctx->message);
+
+	if (result) be64_copy(result, 0, ctx->hash, ctx->digest_length);
+}
diff --git a/Utilities/cmlibrhash/librhash/sha512.h b/Utilities/cmlibrhash/librhash/sha512.h
new file mode 100644
index 0000000..7c689be
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/sha512.h
@@ -0,0 +1,32 @@
+/* sha.h sha512 and sha384 hash functions */
+#ifndef SHA512_H
+#define SHA512_H
+#include "ustd.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define sha512_block_size 128
+#define sha512_hash_size  64
+#define sha384_hash_size  48
+
+/* algorithm context */
+typedef struct sha512_ctx
+{
+	uint64_t message[16];   /* 1024-bit buffer for leftovers */
+	uint64_t length;        /* number of processed bytes */
+	uint64_t hash[8];       /* 512-bit algorithm internal hashing state */
+	unsigned digest_length; /* length of the algorithm digest in bytes */
+} sha512_ctx;
+
+void rhash_sha384_init(sha512_ctx *ctx);
+void rhash_sha512_init(sha512_ctx *ctx);
+void rhash_sha512_update(sha512_ctx *ctx, const unsigned char* data, size_t length);
+void rhash_sha512_final(sha512_ctx *ctx, unsigned char* result);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* SHA512_H */
diff --git a/Utilities/cmlibrhash/librhash/ustd.h b/Utilities/cmlibrhash/librhash/ustd.h
new file mode 100644
index 0000000..019b931
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/ustd.h
@@ -0,0 +1,39 @@
+/* ustd.h common macros and includes */
+#ifndef LIBRHASH_USTD_H
+#define LIBRHASH_USTD_H
+
+/* Include KWSys Large File Support configuration. */
+#include <cmsys/Configure.h>
+
+#if defined(_MSC_VER)
+# pragma warning(push,1)
+#endif
+
+#include <cm_kwiml.h>
+
+#ifndef KWIML_INT_HAVE_INT64_T
+# define int64_t KWIML_INT_int64_t
+#endif
+#ifndef KWIML_INT_HAVE_INT32_T
+# define int32_t KWIML_INT_int32_t
+#endif
+#ifndef KWIML_INT_HAVE_INT16_T
+# define int16_t KWIML_INT_int16_t
+#endif
+#ifndef KWIML_INT_HAVE_INT8_T
+# define int8_t KWIML_INT_int8_t
+#endif
+#ifndef KWIML_INT_HAVE_UINT64_T
+# define uint64_t KWIML_INT_uint64_t
+#endif
+#ifndef KWIML_INT_HAVE_UINT32_T
+# define uint32_t KWIML_INT_uint32_t
+#endif
+#ifndef KWIML_INT_HAVE_UINT16_T
+# define uint16_t KWIML_INT_uint16_t
+#endif
+#ifndef KWIML_INT_HAVE_UINT8_T
+# define uint8_t KWIML_INT_uint8_t
+#endif
+
+#endif /* LIBRHASH_USTD_H */
diff --git a/Utilities/cmlibrhash/librhash/util.h b/Utilities/cmlibrhash/librhash/util.h
new file mode 100644
index 0000000..9f37157
--- /dev/null
+++ b/Utilities/cmlibrhash/librhash/util.h
@@ -0,0 +1,31 @@
+/* util.h */
+#ifndef UTIL_H
+#define UTIL_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if (defined(__GNUC__) && __GNUC__ >= 4 && (__GNUC__ > 4 || __GNUC_MINOR__ >= 1) \
+	&& defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)) \
+	|| (defined(__INTEL_COMPILER) && !defined(_WIN32))
+/* atomic operations are defined by ICC and GCC >= 4.1, but by the later one supposedly not for ARM */
+/* note: ICC on ia64 platform possibly require ia64intrin.h, need testing */
+# define atomic_compare_and_swap(ptr, oldval, newval) __sync_val_compare_and_swap(ptr, oldval, newval)
+#elif defined(_MSC_VER)
+# include <windows.h>
+# define atomic_compare_and_swap(ptr, oldval, newval) InterlockedCompareExchange(ptr, newval, oldval)
+#elif defined(__sun)
+# include <atomic.h>
+# define atomic_compare_and_swap(ptr, oldval, newval) atomic_cas_32(ptr, oldval, newval)
+#else
+/* pray that it will work */
+# define atomic_compare_and_swap(ptr, oldval, newval) { if(*(ptr) == (oldval)) *(ptr) = (newval); }
+# define NO_ATOMIC_BUILTINS
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* UTIL_H */
diff --git a/Utilities/cmlibuv/CMakeLists.txt b/Utilities/cmlibuv/CMakeLists.txt
index 1b384b5..a8e25ba 100644
--- a/Utilities/cmlibuv/CMakeLists.txt
+++ b/Utilities/cmlibuv/CMakeLists.txt
@@ -218,8 +218,16 @@ if(CMAKE_SYSTEM_NAME STREQUAL "SunOS")
     )
   list(APPEND uv_defines
     __EXTENSIONS__
-    _XOPEN_SOURCE=500
     )
+  if(CMAKE_SYSTEM_VERSION STREQUAL "5.10")
+    list(APPEND uv_defines
+      _XOPEN_SOURCE=500
+      )
+  else()
+    list(APPEND uv_defines
+      _XOPEN_SOURCE=600
+      )
+  endif()
   list(APPEND uv_sources
     src/unix/sunos.c
     )
diff --git a/Utilities/cmvssetup/.gitattributes b/Utilities/cmvssetup/.gitattributes
new file mode 100644
index 0000000..562b12e
--- /dev/null
+++ b/Utilities/cmvssetup/.gitattributes
@@ -0,0 +1 @@
+* -whitespace
diff --git a/Utilities/cmvssetup/Setup.Configuration.h b/Utilities/cmvssetup/Setup.Configuration.h
new file mode 100644
index 0000000..6c9d8f9
--- /dev/null
+++ b/Utilities/cmvssetup/Setup.Configuration.h
@@ -0,0 +1,991 @@
+// <copyright file="Setup.Configuration.h" company="Microsoft Corporation">
+// Copyright (C) Microsoft Corporation. All rights reserved.
+// </copyright>
+
+// This file is licensed under "The MIT License(MIT)".
+// This file is released by Visual Studio setup team for consumption by external applications.
+// For more information please look at this git repo https://github.com/microsoft/vs-setup-samples
+
+#ifndef SetupConfiguration_h
+#define SetupConfiguration_h
+
+#include <objbase.h>
+
+// Constants
+//
+#ifndef E_NOTFOUND
+#define E_NOTFOUND HRESULT_FROM_WIN32(ERROR_NOT_FOUND)
+#endif
+
+#ifndef E_FILENOTFOUND
+#define E_FILENOTFOUND HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)
+#endif
+
+#if defined(_WIN32) && !defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
+
+#ifndef _Outptr_result_maybenull_
+#define _Outptr_result_maybenull_
+#endif
+#ifndef _Out_writes_to_
+#define _Out_writes_to_(x,y)
+#endif
+#ifndef _Reserved_
+#define _Reserved_
+#endif
+#ifndef MAXUINT
+#define MAXUINT     ((UINT)~((UINT)0))
+#endif
+
+// Enumerations
+//
+/// <summary>
+/// The state of an instance.
+/// </summary>
+enum InstanceState
+{
+    /// <summary>
+    /// The instance state has not been determined.
+    /// </summary>
+    eNone = 0,
+
+    /// <summary>
+    /// The instance installation path exists.
+    /// </summary>
+    eLocal = 1,
+
+    /// <summary>
+    /// A product is registered to the instance.
+    /// </summary>
+    eRegistered = 2,
+
+    /// <summary>
+    /// No reboot is required for the instance.
+    /// </summary>
+    eNoRebootRequired = 4,
+
+    /// <summary>
+    /// The instance represents a complete install.
+    /// </summary>
+    eComplete = MAXUINT,
+};
+
+// Forward interface declarations
+//
+#ifndef __ISetupInstance_FWD_DEFINED__
+#define __ISetupInstance_FWD_DEFINED__
+typedef struct ISetupInstance ISetupInstance;
+#endif
+
+#ifndef __ISetupInstance2_FWD_DEFINED__
+#define __ISetupInstance2_FWD_DEFINED__
+typedef struct ISetupInstance2 ISetupInstance2;
+#endif
+
+#ifndef __IEnumSetupInstances_FWD_DEFINED__
+#define __IEnumSetupInstances_FWD_DEFINED__
+typedef struct IEnumSetupInstances IEnumSetupInstances;
+#endif
+
+#ifndef __ISetupConfiguration_FWD_DEFINED__
+#define __ISetupConfiguration_FWD_DEFINED__
+typedef struct ISetupConfiguration ISetupConfiguration;
+#endif
+
+#ifndef __ISetupConfiguration2_FWD_DEFINED__
+#define __ISetupConfiguration2_FWD_DEFINED__
+typedef struct ISetupConfiguration2 ISetupConfiguration2;
+#endif
+
+#ifndef __ISetupPackageReference_FWD_DEFINED__
+#define __ISetupPackageReference_FWD_DEFINED__
+typedef struct ISetupPackageReference ISetupPackageReference;
+#endif
+
+#ifndef __ISetupHelper_FWD_DEFINED__
+#define __ISetupHelper_FWD_DEFINED__
+typedef struct ISetupHelper ISetupHelper;
+#endif
+
+// Forward class declarations
+//
+#ifndef __SetupConfiguration_FWD_DEFINED__
+#define __SetupConfiguration_FWD_DEFINED__
+
+#ifdef __cplusplus
+typedef class SetupConfiguration SetupConfiguration;
+#endif
+
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// Interface definitions
+//
+EXTERN_C const IID IID_ISetupInstance;
+
+#if defined(__cplusplus) && !defined(CINTERFACE)
+/// <summary>
+/// Information about an instance of a product.
+/// </summary>
+struct DECLSPEC_UUID("B41463C3-8866-43B5-BC33-2B0676F7F42E") DECLSPEC_NOVTABLE ISetupInstance : public IUnknown
+{
+    /// <summary>
+    /// Gets the instance identifier (should match the name of the parent instance directory).
+    /// </summary>
+    /// <param name="pbstrInstanceId">The instance identifier.</param>
+    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist.</returns>
+    STDMETHOD(GetInstanceId)(
+        _Out_ BSTR* pbstrInstanceId
+        ) = 0;
+
+    /// <summary>
+    /// Gets the local date and time when the installation was originally installed.
+    /// </summary>
+    /// <param name="pInstallDate">The local date and time when the installation was originally installed.</param>
+    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
+    STDMETHOD(GetInstallDate)(
+        _Out_ LPFILETIME pInstallDate
+        ) = 0;
+
+    /// <summary>
+    /// Gets the unique name of the installation, often indicating the branch and other information used for telemetry.
+    /// </summary>
+    /// <param name="pbstrInstallationName">The unique name of the installation, often indicating the branch and other information used for telemetry.</param>
+    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
+    STDMETHOD(GetInstallationName)(
+        _Out_ BSTR* pbstrInstallationName
+        ) = 0;
+
+    /// <summary>
+    /// Gets the path to the installation root of the product.
+    /// </summary>
+    /// <param name="pbstrInstallationPath">The path to the installation root of the product.</param>
+    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
+    STDMETHOD(GetInstallationPath)(
+        _Out_ BSTR* pbstrInstallationPath
+        ) = 0;
+
+    /// <summary>
+    /// Gets the version of the product installed in this instance.
+    /// </summary>
+    /// <param name="pbstrInstallationVersion">The version of the product installed in this instance.</param>
+    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
+    STDMETHOD(GetInstallationVersion)(
+        _Out_ BSTR* pbstrInstallationVersion
+        ) = 0;
+
+    /// <summary>
+    /// Gets the display name (title) of the product installed in this instance.
+    /// </summary>
+    /// <param name="lcid">The LCID for the display name.</param>
+    /// <param name="pbstrDisplayName">The display name (title) of the product installed in this instance.</param>
+    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
+    STDMETHOD(GetDisplayName)(
+        _In_ LCID lcid,
+        _Out_ BSTR* pbstrDisplayName
+        ) = 0;
+
+    /// <summary>
+    /// Gets the description of the product installed in this instance.
+    /// </summary>
+    /// <param name="lcid">The LCID for the description.</param>
+    /// <param name="pbstrDescription">The description of the product installed in this instance.</param>
+    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
+    STDMETHOD(GetDescription)(
+        _In_ LCID lcid,
+        _Out_ BSTR* pbstrDescription
+        ) = 0;
+
+    /// <summary>
+    /// Resolves the optional relative path to the root path of the instance.
+    /// </summary>
+    /// <param name="pwszRelativePath">A relative path within the instance to resolve, or NULL to get the root path.</param>
+    /// <param name="pbstrAbsolutePath">The full path to the optional relative path within the instance. If the relative path is NULL, the root path will always terminate in a backslash.</param>
+    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
+    STDMETHOD(ResolvePath)(
+        _In_opt_z_ LPCOLESTR pwszRelativePath,
+        _Out_ BSTR* pbstrAbsolutePath
+        ) = 0;
+};
+#endif
+
+EXTERN_C const IID IID_ISetupInstance2;
+
+#if defined(__cplusplus) && !defined(CINTERFACE)
+/// <summary>
+/// Information about an instance of a product.
+/// </summary>
+struct DECLSPEC_UUID("89143C9A-05AF-49B0-B717-72E218A2185C") DECLSPEC_NOVTABLE ISetupInstance2 : public ISetupInstance
+{
+    /// <summary>
+    /// Gets the state of the instance.
+    /// </summary>
+    /// <param name="pState">The state of the instance.</param>
+    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist.</returns>
+    STDMETHOD(GetState)(
+        _Out_ InstanceState* pState
+        ) = 0;
+
+    /// <summary>
+    /// Gets an array of package references registered to the instance.
+    /// </summary>
+    /// <param name="ppsaPackages">Pointer to an array of <see cref="ISetupPackageReference"/>.</param>
+    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the packages property is not defined.</returns>
+    STDMETHOD(GetPackages)(
+        _Out_ LPSAFEARRAY* ppsaPackages
+        ) = 0;
+
+    /// <summary>
+    /// Gets a pointer to the <see cref="ISetupPackageReference"/> that represents the registered product.
+    /// </summary>
+    /// <param name="ppPackage">Pointer to an instance of <see cref="ISetupPackageReference"/>. This may be NULL if <see cref="GetState"/> does not return <see cref="eComplete"/>.</param>
+    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the packages property is not defined.</returns>
+    STDMETHOD(GetProduct)(
+        _Outptr_result_maybenull_ ISetupPackageReference** ppPackage
+        ) = 0;
+
+    /// <summary>
+    /// Gets the relative path to the product application, if available.
+    /// </summary>
+    /// <param name="pbstrProductPath">The relative path to the product application, if available.</param>
+    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist.</returns>
+    STDMETHOD(GetProductPath)(
+        _Outptr_result_maybenull_ BSTR* pbstrProductPath
+        ) = 0;
+};
+#endif
+
+EXTERN_C const IID IID_IEnumSetupInstances;
+
+#if defined(__cplusplus) && !defined(CINTERFACE)
+/// <summary>
+/// A enumerator of installed <see cref="ISetupInstance"/> objects.
+/// </summary>
+struct DECLSPEC_UUID("6380BCFF-41D3-4B2E-8B2E-BF8A6810C848") DECLSPEC_NOVTABLE IEnumSetupInstances : public IUnknown
+{
+    /// <summary>
+    /// Retrieves the next set of product instances in the enumeration sequence.
+    /// </summary>
+    /// <param name="celt">The number of product instances to retrieve.</param>
+    /// <param name="rgelt">A pointer to an array of <see cref="ISetupInstance"/>.</param>
+    /// <param name="pceltFetched">A pointer to the number of product instances retrieved. If celt is 1 this parameter may be NULL.</param>
+    /// <returns>S_OK if the number of elements were fetched, S_FALSE if nothing was fetched (at end of enumeration), E_INVALIDARG if celt is greater than 1 and pceltFetched is NULL, or E_OUTOFMEMORY if an <see cref="ISetupInstance"/> could not be allocated.</returns>
+    STDMETHOD(Next)(
+        _In_ ULONG celt,
+        _Out_writes_to_(celt, *pceltFetched) ISetupInstance** rgelt,
+        _Out_opt_ _Deref_out_range_(0, celt) ULONG* pceltFetched
+        ) = 0;
+
+    /// <summary>
+    /// Skips the next set of product instances in the enumeration sequence.
+    /// </summary>
+    /// <param name="celt">The number of product instances to skip.</param>
+    /// <returns>S_OK if the number of elements could be skipped; otherwise, S_FALSE;</returns>
+    STDMETHOD(Skip)(
+        _In_ ULONG celt
+        ) = 0;
+
+    /// <summary>
+    /// Resets the enumeration sequence to the beginning.
+    /// </summary>
+    /// <returns>Always returns S_OK;</returns>
+    STDMETHOD(Reset)(void) = 0;
+
+    /// <summary>
+    /// Creates a new enumeration object in the same state as the current enumeration object: the new object points to the same place in the enumeration sequence.
+    /// </summary>
+    /// <param name="ppenum">A pointer to a pointer to a new <see cref="IEnumSetupInstances"/> interface. If the method fails, this parameter is undefined.</param>
+    /// <returns>S_OK if a clone was returned; otherwise, E_OUTOFMEMORY.</returns>
+    STDMETHOD(Clone)(
+        _Deref_out_opt_ IEnumSetupInstances** ppenum
+        ) = 0;
+};
+#endif
+
+EXTERN_C const IID IID_ISetupConfiguration;
+
+#if defined(__cplusplus) && !defined(CINTERFACE)
+/// <summary>
+/// Gets information about product instances set up on the machine.
+/// </summary>
+struct DECLSPEC_UUID("42843719-DB4C-46C2-8E7C-64F1816EFD5B") DECLSPEC_NOVTABLE ISetupConfiguration : public IUnknown
+{
+    /// <summary>
+    /// Enumerates all completed product instances installed.
+    /// </summary>
+    /// <param name="ppEnumInstances">An enumeration of completed, installed product instances.</param>
+    /// <returns>Standard HRESULT indicating success or failure.</returns>
+    STDMETHOD(EnumInstances)(
+        _Out_ IEnumSetupInstances** ppEnumInstances
+        ) = 0;
+
+    /// <summary>
+    /// Gets the instance for the current process path.
+    /// </summary>
+    /// <param name="ppInstance">The instance for the current process path.</param>
+    /// <returns>The instance for the current process path, or E_NOTFOUND if not found.</returns>
+    STDMETHOD(GetInstanceForCurrentProcess)(
+        _Out_ ISetupInstance** ppInstance
+        ) = 0;
+
+    /// <summary>
+    /// Gets the instance for the given path.
+    /// </summary>
+    /// <param name="ppInstance">The instance for the given path.</param>
+    /// <returns>The instance for the given path, or E_NOTFOUND if not found.</returns>
+    STDMETHOD(GetInstanceForPath)(
+        _In_z_ LPCWSTR wzPath,
+        _Out_ ISetupInstance** ppInstance
+        ) = 0;
+};
+#endif
+
+EXTERN_C const IID IID_ISetupConfiguration2;
+
+#if defined(__cplusplus) && !defined(CINTERFACE)
+/// <summary>
+/// Gets information about product instances.
+/// </summary>
+struct DECLSPEC_UUID("26AAB78C-4A60-49D6-AF3B-3C35BC93365D") DECLSPEC_NOVTABLE ISetupConfiguration2 : public ISetupConfiguration
+{
+    /// <summary>
+    /// Enumerates all product instances.
+    /// </summary>
+    /// <param name="ppEnumInstances">An enumeration of all product instances.</param>
+    /// <returns>Standard HRESULT indicating success or failure.</returns>
+    STDMETHOD(EnumAllInstances)(
+        _Out_ IEnumSetupInstances** ppEnumInstances
+        ) = 0;
+};
+#endif
+
+EXTERN_C const IID IID_ISetupPackageReference;
+
+#if defined(__cplusplus) && !defined(CINTERFACE)
+/// <summary>
+/// A reference to a package.
+/// </summary>
+struct DECLSPEC_UUID("da8d8a16-b2b6-4487-a2f1-594ccccd6bf5") DECLSPEC_NOVTABLE ISetupPackageReference : public IUnknown
+{
+    /// <summary>
+    /// Gets the general package identifier.
+    /// </summary>
+    /// <param name="pbstrId">The general package identifier.</param>
+    /// <returns>Standard HRESULT indicating success or failure.</returns>
+    STDMETHOD(GetId)(
+        _Out_ BSTR* pbstrId
+        ) = 0;
+
+    /// <summary>
+    /// Gets the version of the package.
+    /// </summary>
+    /// <param name="pbstrVersion">The version of the package.</param>
+    /// <returns>Standard HRESULT indicating success or failure.</returns>
+    STDMETHOD(GetVersion)(
+        _Out_ BSTR* pbstrVersion
+        ) = 0;
+
+    /// <summary>
+    /// Gets the target process architecture of the package.
+    /// </summary>
+    /// <param name="pbstrChip">The target process architecture of the package.</param>
+    /// <returns>Standard HRESULT indicating success or failure.</returns>
+    STDMETHOD(GetChip)(
+        _Out_ BSTR* pbstrChip
+        ) = 0;
+
+    /// <summary>
+    /// Gets the language and optional region identifier.
+    /// </summary>
+    /// <param name="pbstrLanguage">The language and optional region identifier.</param>
+    /// <returns>Standard HRESULT indicating success or failure.</returns>
+    STDMETHOD(GetLanguage)(
+        _Out_ BSTR* pbstrLanguage
+        ) = 0;
+
+    /// <summary>
+    /// Gets the build branch of the package.
+    /// </summary>
+    /// <param name="pbstrBranch">The build branch of the package.</param>
+    /// <returns>Standard HRESULT indicating success or failure.</returns>
+    STDMETHOD(GetBranch)(
+        _Out_ BSTR* pbstrBranch
+        ) = 0;
+
+    /// <summary>
+    /// Gets the type of the package.
+    /// </summary>
+    /// <param name="pbstrType">The type of the package.</param>
+    /// <returns>Standard HRESULT indicating success or failure.</returns>
+    STDMETHOD(GetType)(
+        _Out_ BSTR* pbstrType
+        ) = 0;
+
+    /// <summary>
+    /// Gets the unique identifier consisting of all defined tokens.
+    /// </summary>
+    /// <param name="pbstrUniqueId">The unique identifier consisting of all defined tokens.</param>
+    /// <returns>Standard HRESULT indicating success or failure, including E_UNEXPECTED if no Id was defined (required).</returns>
+    STDMETHOD(GetUniqueId)(
+        _Out_ BSTR* pbstrUniqueId
+        ) = 0;
+};
+#endif
+
+EXTERN_C const IID IID_ISetupHelper;
+
+#if defined(__cplusplus) && !defined(CINTERFACE)
+/// <summary>
+/// Helper functions.
+/// </summary>
+/// <remarks>
+/// You can query for this interface from the <see cref="SetupConfiguration"/> class.
+/// </remarks>
+struct DECLSPEC_UUID("42b21b78-6192-463e-87bf-d577838f1d5c") DECLSPEC_NOVTABLE ISetupHelper : public IUnknown
+{
+    /// <summary>
+    /// Parses a dotted quad version string into a 64-bit unsigned integer.
+    /// </summary>
+    /// <param name="pwszVersion">The dotted quad version string to parse, e.g. 1.2.3.4.</param>
+    /// <param name="pullVersion">A 64-bit unsigned integer representing the version. You can compare this to other versions.</param>
+    /// <returns>Standard HRESULT indicating success or failure.</returns>
+    STDMETHOD(ParseVersion)(
+        _In_ LPCOLESTR pwszVersion,
+        _Out_ PULONGLONG pullVersion
+        ) = 0;
+
+    /// <summary>
+    /// Parses a dotted quad version string into a 64-bit unsigned integer.
+    /// </summary>
+    /// <param name="pwszVersionRange">The string containing 1 or 2 dotted quad version strings to parse, e.g. [1.0,) that means 1.0.0.0 or newer.</param>
+    /// <param name="pullMinVersion">A 64-bit unsigned integer representing the minimum version, which may be 0. You can compare this to other versions.</param>
+    /// <param name="pullMaxVersion">A 64-bit unsigned integer representing the maximum version, which may be MAXULONGLONG. You can compare this to other versions.</param>
+    /// <returns>Standard HRESULT indicating success or failure.</returns>
+    STDMETHOD(ParseVersionRange)(
+        _In_ LPCOLESTR pwszVersionRange,
+        _Out_ PULONGLONG pullMinVersion,
+        _Out_ PULONGLONG pullMaxVersion
+        ) = 0;
+};
+#endif
+
+// Class declarations
+//
+EXTERN_C const CLSID CLSID_SetupConfiguration;
+
+#ifdef __cplusplus
+/// <summary>
+/// This class implements <see cref="ISetupConfiguration"/>, <see cref="ISetupConfiguration2"/>, and <see cref="ISetupHelper"/>.
+/// </summary>
+class DECLSPEC_UUID("177F0C4A-1CD3-4DE7-A32C-71DBBB9FA36D") SetupConfiguration;
+#endif
+
+// Function declarations
+//
+/// <summary>
+/// Gets an <see cref="ISetupConfiguration"/> that provides information about product instances installed on the machine.
+/// </summary>
+/// <param name="ppConfiguration">The <see cref="ISetupConfiguration"/> that provides information about product instances installed on the machine.</param>
+/// <param name="pReserved">Reserved for future use.</param>
+/// <returns>Standard HRESULT indicating success or failure.</returns>
+STDMETHODIMP GetSetupConfiguration(
+    _Out_ ISetupConfiguration** ppConfiguration,
+    _Reserved_ LPVOID pReserved
+);
+
+#ifdef __cplusplus
+}
+#endif
+
+#else
+
+#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
+#define VS_SETUP_GCC_DIAGNOSTIC_PUSHED
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
+#endif
+
+#ifndef MAXUINT
+#define MAXUINT     ((UINT)~((UINT)0))
+#endif
+
+#ifndef DECLSPEC_NOVTABLE
+#if (_MSC_VER >= 1100) && defined(__cplusplus)
+#define DECLSPEC_NOVTABLE   __declspec(novtable)
+#else
+#define DECLSPEC_NOVTABLE
+#endif
+#endif
+
+// Enumerations
+//
+/// <summary>
+/// The state of an instance.
+/// </summary>
+enum InstanceState
+{
+  /// <summary>
+  /// The instance state has not been determined.
+  /// </summary>
+  eNone = 0,
+
+  /// <summary>
+  /// The instance installation path exists.
+  /// </summary>
+  eLocal = 1,
+
+  /// <summary>
+  /// A product is registered to the instance.
+  /// </summary>
+  eRegistered = 2,
+
+  /// <summary>
+  /// No reboot is required for the instance.
+  /// </summary>
+  eNoRebootRequired = 4,
+
+  /// <summary>
+  /// The instance represents a complete install.
+  /// </summary>
+  eComplete = MAXUINT,
+};
+
+// Forward interface declarations
+//
+#ifndef __ISetupInstance_FWD_DEFINED__
+#define __ISetupInstance_FWD_DEFINED__
+typedef struct ISetupInstance ISetupInstance;
+#endif
+
+#ifndef __ISetupInstance2_FWD_DEFINED__
+#define __ISetupInstance2_FWD_DEFINED__
+typedef struct ISetupInstance2 ISetupInstance2;
+#endif
+
+#ifndef __IEnumSetupInstances_FWD_DEFINED__
+#define __IEnumSetupInstances_FWD_DEFINED__
+typedef struct IEnumSetupInstances IEnumSetupInstances;
+#endif
+
+#ifndef __ISetupConfiguration_FWD_DEFINED__
+#define __ISetupConfiguration_FWD_DEFINED__
+typedef struct ISetupConfiguration ISetupConfiguration;
+#endif
+
+#ifndef __ISetupConfiguration2_FWD_DEFINED__
+#define __ISetupConfiguration2_FWD_DEFINED__
+typedef struct ISetupConfiguration2 ISetupConfiguration2;
+#endif
+
+#ifndef __ISetupPackageReference_FWD_DEFINED__
+#define __ISetupPackageReference_FWD_DEFINED__
+typedef struct ISetupPackageReference ISetupPackageReference;
+#endif
+
+#ifndef __ISetupHelper_FWD_DEFINED__
+#define __ISetupHelper_FWD_DEFINED__
+typedef struct ISetupHelper ISetupHelper;
+#endif
+
+// Forward class declarations
+//
+#ifndef __SetupConfiguration_FWD_DEFINED__
+#define __SetupConfiguration_FWD_DEFINED__
+
+#ifdef __cplusplus
+typedef class SetupConfiguration SetupConfiguration;
+#endif
+
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+  // Interface definitions
+  //
+  EXTERN_C const IID IID_ISetupInstance;
+
+#if defined(__cplusplus) && !defined(CINTERFACE)
+  /// <summary>
+  /// Information about an instance of a product.
+  /// </summary>
+  struct DECLSPEC_UUID("B41463C3-8866-43B5-BC33-2B0676F7F42E") DECLSPEC_NOVTABLE ISetupInstance : public IUnknown
+  {
+    /// <summary>
+    /// Gets the instance identifier (should match the name of the parent instance directory).
+    /// </summary>
+    /// <param name="pbstrInstanceId">The instance identifier.</param>
+    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist.</returns>
+    STDMETHOD(GetInstanceId)(
+      BSTR* pbstrInstanceId
+      ) = 0;
+
+  /// <summary>
+  /// Gets the local date and time when the installation was originally installed.
+  /// </summary>
+  /// <param name="pInstallDate">The local date and time when the installation was originally installed.</param>
+  /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
+  STDMETHOD(GetInstallDate)(
+    LPFILETIME pInstallDate
+    ) = 0;
+
+  /// <summary>
+  /// Gets the unique name of the installation, often indicating the branch and other information used for telemetry.
+  /// </summary>
+  /// <param name="pbstrInstallationName">The unique name of the installation, often indicating the branch and other information used for telemetry.</param>
+  /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
+  STDMETHOD(GetInstallationName)(
+    BSTR* pbstrInstallationName
+    ) = 0;
+
+  /// <summary>
+  /// Gets the path to the installation root of the product.
+  /// </summary>
+  /// <param name="pbstrInstallationPath">The path to the installation root of the product.</param>
+  /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
+  STDMETHOD(GetInstallationPath)(
+    BSTR* pbstrInstallationPath
+    ) = 0;
+
+  /// <summary>
+  /// Gets the version of the product installed in this instance.
+  /// </summary>
+  /// <param name="pbstrInstallationVersion">The version of the product installed in this instance.</param>
+  /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
+  STDMETHOD(GetInstallationVersion)(
+    BSTR* pbstrInstallationVersion
+    ) = 0;
+
+  /// <summary>
+  /// Gets the display name (title) of the product installed in this instance.
+  /// </summary>
+  /// <param name="lcid">The LCID for the display name.</param>
+  /// <param name="pbstrDisplayName">The display name (title) of the product installed in this instance.</param>
+  /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
+  STDMETHOD(GetDisplayName)(
+    LCID lcid,
+    BSTR* pbstrDisplayName
+    ) = 0;
+
+  /// <summary>
+  /// Gets the description of the product installed in this instance.
+  /// </summary>
+  /// <param name="lcid">The LCID for the description.</param>
+  /// <param name="pbstrDescription">The description of the product installed in this instance.</param>
+  /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
+  STDMETHOD(GetDescription)(
+    LCID lcid,
+    BSTR* pbstrDescription
+    ) = 0;
+
+  /// <summary>
+  /// Resolves the optional relative path to the root path of the instance.
+  /// </summary>
+  /// <param name="pwszRelativePath">A relative path within the instance to resolve, or NULL to get the root path.</param>
+  /// <param name="pbstrAbsolutePath">The full path to the optional relative path within the instance. If the relative path is NULL, the root path will always terminate in a backslash.</param>
+  /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the property is not defined.</returns>
+  STDMETHOD(ResolvePath)(
+    LPCOLESTR pwszRelativePath,
+    BSTR* pbstrAbsolutePath
+    ) = 0;
+  };
+#endif
+
+  EXTERN_C const IID IID_ISetupInstance2;
+
+#if defined(__cplusplus) && !defined(CINTERFACE)
+  /// <summary>
+  /// Information about an instance of a product.
+  /// </summary>
+  struct DECLSPEC_UUID("89143C9A-05AF-49B0-B717-72E218A2185C") DECLSPEC_NOVTABLE ISetupInstance2 : public ISetupInstance
+  {
+    /// <summary>
+    /// Gets the state of the instance.
+    /// </summary>
+    /// <param name="pState">The state of the instance.</param>
+    /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist.</returns>
+    STDMETHOD(GetState)(
+      InstanceState* pState
+      ) = 0;
+
+  /// <summary>
+  /// Gets an array of package references registered to the instance.
+  /// </summary>
+  /// <param name="ppsaPackages">Pointer to an array of <see cref="ISetupPackageReference"/>.</param>
+  /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the packages property is not defined.</returns>
+  STDMETHOD(GetPackages)(
+    LPSAFEARRAY* ppsaPackages
+    ) = 0;
+
+  /// <summary>
+  /// Gets a pointer to the <see cref="ISetupPackageReference"/> that represents the registered product.
+  /// </summary>
+  /// <param name="ppPackage">Pointer to an instance of <see cref="ISetupPackageReference"/>. This may be NULL if <see cref="GetState"/> does not return <see cref="eComplete"/>.</param>
+  /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist and E_NOTFOUND if the packages property is not defined.</returns>
+  STDMETHOD(GetProduct)(
+    ISetupPackageReference** ppPackage
+    ) = 0;
+
+  /// <summary>
+  /// Gets the relative path to the product application, if available.
+  /// </summary>
+  /// <param name="pbstrProductPath">The relative path to the product application, if available.</param>
+  /// <returns>Standard HRESULT indicating success or failure, including E_FILENOTFOUND if the instance state does not exist.</returns>
+  STDMETHOD(GetProductPath)(
+    BSTR* pbstrProductPath
+    ) = 0;
+  };
+#endif
+
+  EXTERN_C const IID IID_IEnumSetupInstances;
+
+#if defined(__cplusplus) && !defined(CINTERFACE)
+  /// <summary>
+  /// A enumerator of installed <see cref="ISetupInstance"/> objects.
+  /// </summary>
+  struct DECLSPEC_UUID("6380BCFF-41D3-4B2E-8B2E-BF8A6810C848") DECLSPEC_NOVTABLE IEnumSetupInstances : public IUnknown
+  {
+    /// <summary>
+    /// Retrieves the next set of product instances in the enumeration sequence.
+    /// </summary>
+    /// <param name="celt">The number of product instances to retrieve.</param>
+    /// <param name="rgelt">A pointer to an array of <see cref="ISetupInstance"/>.</param>
+    /// <param name="pceltFetched">A pointer to the number of product instances retrieved. If celt is 1 this parameter may be NULL.</param>
+    /// <returns>S_OK if the number of elements were fetched, S_FALSE if nothing was fetched (at end of enumeration), E_INVALIDARG if celt is greater than 1 and pceltFetched is NULL, or E_OUTOFMEMORY if an <see cref="ISetupInstance"/> could not be allocated.</returns>
+    STDMETHOD(Next)(
+      ULONG celt,
+      ISetupInstance** rgelt,
+      ULONG* pceltFetched
+      ) = 0;
+
+  /// <summary>
+  /// Skips the next set of product instances in the enumeration sequence.
+  /// </summary>
+  /// <param name="celt">The number of product instances to skip.</param>
+  /// <returns>S_OK if the number of elements could be skipped; otherwise, S_FALSE;</returns>
+  STDMETHOD(Skip)(
+    ULONG celt
+    ) = 0;
+
+  /// <summary>
+  /// Resets the enumeration sequence to the beginning.
+  /// </summary>
+  /// <returns>Always returns S_OK;</returns>
+  STDMETHOD(Reset)(void) = 0;
+
+  /// <summary>
+  /// Creates a new enumeration object in the same state as the current enumeration object: the new object points to the same place in the enumeration sequence.
+  /// </summary>
+  /// <param name="ppenum">A pointer to a pointer to a new <see cref="IEnumSetupInstances"/> interface. If the method fails, this parameter is undefined.</param>
+  /// <returns>S_OK if a clone was returned; otherwise, E_OUTOFMEMORY.</returns>
+  STDMETHOD(Clone)(
+    IEnumSetupInstances** ppenum
+    ) = 0;
+  };
+#endif
+
+  EXTERN_C const IID IID_ISetupConfiguration;
+
+#if defined(__cplusplus) && !defined(CINTERFACE)
+  /// <summary>
+  /// Gets information about product instances set up on the machine.
+  /// </summary>
+  struct DECLSPEC_UUID("42843719-DB4C-46C2-8E7C-64F1816EFD5B") DECLSPEC_NOVTABLE ISetupConfiguration : public IUnknown
+  {
+    /// <summary>
+    /// Enumerates all completed product instances installed.
+    /// </summary>
+    /// <param name="ppEnumInstances">An enumeration of completed, installed product instances.</param>
+    /// <returns>Standard HRESULT indicating success or failure.</returns>
+    STDMETHOD(EnumInstances)(
+      IEnumSetupInstances** ppEnumInstances
+      ) = 0;
+
+  /// <summary>
+  /// Gets the instance for the current process path.
+  /// </summary>
+  /// <param name="ppInstance">The instance for the current process path.</param>
+  /// <returns>The instance for the current process path, or E_NOTFOUND if not found.</returns>
+  STDMETHOD(GetInstanceForCurrentProcess)(
+    ISetupInstance** ppInstance
+    ) = 0;
+
+  /// <summary>
+  /// Gets the instance for the given path.
+  /// </summary>
+  /// <param name="ppInstance">The instance for the given path.</param>
+  /// <returns>The instance for the given path, or E_NOTFOUND if not found.</returns>
+  STDMETHOD(GetInstanceForPath)(
+    LPCWSTR wzPath,
+    ISetupInstance** ppInstance
+    ) = 0;
+  };
+#endif
+
+  EXTERN_C const IID IID_ISetupConfiguration2;
+
+#if defined(__cplusplus) && !defined(CINTERFACE)
+  /// <summary>
+  /// Gets information about product instances.
+  /// </summary>
+  struct DECLSPEC_UUID("26AAB78C-4A60-49D6-AF3B-3C35BC93365D") DECLSPEC_NOVTABLE ISetupConfiguration2 : public ISetupConfiguration
+  {
+    /// <summary>
+    /// Enumerates all product instances.
+    /// </summary>
+    /// <param name="ppEnumInstances">An enumeration of all product instances.</param>
+    /// <returns>Standard HRESULT indicating success or failure.</returns>
+    STDMETHOD(EnumAllInstances)(
+      IEnumSetupInstances** ppEnumInstances
+      ) = 0;
+  };
+#endif
+
+  EXTERN_C const IID IID_ISetupPackageReference;
+
+#if defined(__cplusplus) && !defined(CINTERFACE)
+  /// <summary>
+  /// A reference to a package.
+  /// </summary>
+  struct DECLSPEC_UUID("da8d8a16-b2b6-4487-a2f1-594ccccd6bf5") DECLSPEC_NOVTABLE ISetupPackageReference : public IUnknown
+  {
+    /// <summary>
+    /// Gets the general package identifier.
+    /// </summary>
+    /// <param name="pbstrId">The general package identifier.</param>
+    /// <returns>Standard HRESULT indicating success or failure.</returns>
+    STDMETHOD(GetId)(
+      BSTR* pbstrId
+      ) = 0;
+
+  /// <summary>
+  /// Gets the version of the package.
+  /// </summary>
+  /// <param name="pbstrVersion">The version of the package.</param>
+  /// <returns>Standard HRESULT indicating success or failure.</returns>
+  STDMETHOD(GetVersion)(
+    BSTR* pbstrVersion
+    ) = 0;
+
+  /// <summary>
+  /// Gets the target process architecture of the package.
+  /// </summary>
+  /// <param name="pbstrChip">The target process architecture of the package.</param>
+  /// <returns>Standard HRESULT indicating success or failure.</returns>
+  STDMETHOD(GetChip)(
+    BSTR* pbstrChip
+    ) = 0;
+
+  /// <summary>
+  /// Gets the language and optional region identifier.
+  /// </summary>
+  /// <param name="pbstrLanguage">The language and optional region identifier.</param>
+  /// <returns>Standard HRESULT indicating success or failure.</returns>
+  STDMETHOD(GetLanguage)(
+    BSTR* pbstrLanguage
+    ) = 0;
+
+  /// <summary>
+  /// Gets the build branch of the package.
+  /// </summary>
+  /// <param name="pbstrBranch">The build branch of the package.</param>
+  /// <returns>Standard HRESULT indicating success or failure.</returns>
+  STDMETHOD(GetBranch)(
+    BSTR* pbstrBranch
+    ) = 0;
+
+  /// <summary>
+  /// Gets the type of the package.
+  /// </summary>
+  /// <param name="pbstrType">The type of the package.</param>
+  /// <returns>Standard HRESULT indicating success or failure.</returns>
+  STDMETHOD(GetType)(
+    BSTR* pbstrType
+    ) = 0;
+
+  /// <summary>
+  /// Gets the unique identifier consisting of all defined tokens.
+  /// </summary>
+  /// <param name="pbstrUniqueId">The unique identifier consisting of all defined tokens.</param>
+  /// <returns>Standard HRESULT indicating success or failure, including E_UNEXPECTED if no Id was defined (required).</returns>
+  STDMETHOD(GetUniqueId)(
+    BSTR* pbstrUniqueId
+    ) = 0;
+  };
+#endif
+
+  EXTERN_C const IID IID_ISetupHelper;
+
+#if defined(__cplusplus) && !defined(CINTERFACE)
+  /// <summary>
+  /// Helper functions.
+  /// </summary>
+  /// <remarks>
+  /// You can query for this interface from the <see cref="SetupConfiguration"/> class.
+  /// </remarks>
+  struct DECLSPEC_UUID("42b21b78-6192-463e-87bf-d577838f1d5c") DECLSPEC_NOVTABLE ISetupHelper : public IUnknown
+  {
+    /// <summary>
+    /// Parses a dotted quad version string into a 64-bit unsigned integer.
+    /// </summary>
+    /// <param name="pwszVersion">The dotted quad version string to parse, e.g. 1.2.3.4.</param>
+    /// <param name="pullVersion">A 64-bit unsigned integer representing the version. You can compare this to other versions.</param>
+    /// <returns>Standard HRESULT indicating success or failure.</returns>
+    STDMETHOD(ParseVersion)(
+      LPCOLESTR pwszVersion,
+      PULONGLONG pullVersion
+      ) = 0;
+
+  /// <summary>
+  /// Parses a dotted quad version string into a 64-bit unsigned integer.
+  /// </summary>
+  /// <param name="pwszVersionRange">The string containing 1 or 2 dotted quad version strings to parse, e.g. [1.0,) that means 1.0.0.0 or newer.</param>
+  /// <param name="pullMinVersion">A 64-bit unsigned integer representing the minimum version, which may be 0. You can compare this to other versions.</param>
+  /// <param name="pullMaxVersion">A 64-bit unsigned integer representing the maximum version, which may be MAXULONGLONG. You can compare this to other versions.</param>
+  /// <returns>Standard HRESULT indicating success or failure.</returns>
+  STDMETHOD(ParseVersionRange)(
+    LPCOLESTR pwszVersionRange,
+    PULONGLONG pullMinVersion,
+    PULONGLONG pullMaxVersion
+    ) = 0;
+  };
+#endif
+
+  // Class declarations
+  //
+  EXTERN_C const CLSID CLSID_SetupConfiguration;
+
+#ifdef __cplusplus
+  /// <summary>
+  /// This class implements <see cref="ISetupConfiguration"/>, <see cref="ISetupConfiguration2"/>, and <see cref="ISetupHelper"/>.
+  /// </summary>
+  class DECLSPEC_UUID("177F0C4A-1CD3-4DE7-A32C-71DBBB9FA36D") SetupConfiguration;
+#endif
+
+  // Function declarations
+  //
+  /// <summary>
+  /// Gets an <see cref="ISetupConfiguration"/> that provides information about product instances installed on the machine.
+  /// </summary>
+  /// <param name="ppConfiguration">The <see cref="ISetupConfiguration"/> that provides information about product instances installed on the machine.</param>
+  /// <param name="pReserved">Reserved for future use.</param>
+  /// <returns>Standard HRESULT indicating success or failure.</returns>
+  STDMETHODIMP GetSetupConfiguration(
+    ISetupConfiguration** ppConfiguration,
+    LPVOID pReserved
+  );
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef VS_SETUP_GCC_DIAGNOSTIC_PUSHED
+#pragma GCC diagnostic pop
+#undef VS_SETUP_GCC_DIAGNOSTIC_PUSHED
+#endif
+
+#endif
+#endif
diff --git a/bootstrap b/bootstrap
index 889cc33..8063edb 100755
--- a/bootstrap
+++ b/bootstrap
@@ -240,87 +240,173 @@ CMAKE_UNUSED_SOURCES="\
 "
 
 CMAKE_CXX_SOURCES="\
-  cmake  \
-  cmakemain \
-  cmcmd  \
+  cmAddCustomCommandCommand \
+  cmAddCustomTargetCommand \
+  cmAddDefinitionsCommand \
+  cmAddDependenciesCommand \
+  cmAddExecutableCommand \
+  cmAddLibraryCommand \
+  cmAddSubDirectoryCommand \
+  cmAddTestCommand \
+  cmBreakCommand \
+  cmBuildCommand \
+  cmCMakeMinimumRequired \
+  cmCMakePolicyCommand \
+  cmCPackPropertiesGenerator \
+  cmCacheManager \
+  cmCommand \
   cmCommandArgumentLexer \
   cmCommandArgumentParser \
   cmCommandArgumentParserHelper \
+  cmCommandArgumentsHelper \
+  cmCommands \
   cmCommonTargetGenerator \
-  cmCPackPropertiesGenerator \
+  cmComputeComponentGraph \
+  cmComputeLinkDepends \
+  cmComputeLinkInformation \
+  cmComputeTargetDepends \
+  cmConditionEvaluator \
+  cmConfigureFileCommand \
+  cmContinueCommand \
+  cmCoreTryCompile \
+  cmCreateTestSourceList \
+  cmCustomCommand \
+  cmCustomCommandGenerator \
+  cmDefinePropertyCommand \
   cmDefinitions \
   cmDepends \
   cmDependsC \
   cmDocumentationFormatter \
-  cmPolicies \
-  cmProperty \
-  cmPropertyMap \
-  cmPropertyDefinition \
-  cmPropertyDefinitionMap \
-  cmMakefile \
-  cmMessenger \
+  cmEnableLanguageCommand \
+  cmEnableTestingCommand \
+  cmExecProgramCommand \
+  cmExecuteProcessCommand \
+  cmExpandedCommandArgument \
   cmExportBuildFileGenerator \
   cmExportFileGenerator \
   cmExportInstallFileGenerator \
-  cmExportTryCompileFileGenerator \
   cmExportSet \
   cmExportSetMap \
+  cmExportTryCompileFileGenerator \
+  cmExprLexer \
+  cmExprParser \
+  cmExprParserHelper \
   cmExternalMakefileProjectGenerator \
-  cmGeneratorExpressionEvaluationFile \
+  cmFileCommand \
+  cmFileTimeComparison \
+  cmFindBase \
+  cmFindCommon \
+  cmFindFileCommand \
+  cmFindLibraryCommand \
+  cmFindPackageCommand \
+  cmFindPathCommand \
+  cmFindProgramCommand \
+  cmForEachCommand \
+  cmFunctionCommand \
   cmGeneratedFileStream \
-  cmGeneratorTarget \
+  cmGeneratorExpression \
   cmGeneratorExpressionContext \
   cmGeneratorExpressionDAGChecker \
+  cmGeneratorExpressionEvaluationFile \
   cmGeneratorExpressionEvaluator \
   cmGeneratorExpressionLexer \
   cmGeneratorExpressionNode \
   cmGeneratorExpressionParser \
-  cmGeneratorExpression \
+  cmGeneratorTarget \
+  cmGetCMakePropertyCommand \
+  cmGetDirectoryPropertyCommand \
+  cmGetFilenameComponentCommand \
+  cmGetPropertyCommand \
+  cmGetSourceFilePropertyCommand \
+  cmGetTargetPropertyCommand \
+  cmGetTestPropertyCommand \
   cmGlobalCommonGenerator \
   cmGlobalGenerator \
+  cmGlobalUnixMakefileGenerator3 \
+  cmHexFileConverter \
+  cmIfCommand \
+  cmIncludeCommand \
+  cmIncludeDirectoryCommand \
+  cmIncludeRegularExpressionCommand \
+  cmInstallCommand \
+  cmInstallCommandArguments \
   cmInstallDirectoryGenerator \
-  cmLocalCommonGenerator \
-  cmLocalGenerator \
-  cmInstalledFile \
-  cmInstallGenerator \
   cmInstallExportGenerator \
+  cmInstallFilesCommand \
   cmInstallFilesGenerator \
+  cmInstallGenerator \
   cmInstallScriptGenerator \
   cmInstallTargetGenerator \
-  cmScriptGenerator \
-  cmSourceFile \
-  cmSourceFileLocation \
-  cmState \
-  cmSystemTools \
-  cmTestGenerator \
-  cmVersion \
-  cmFileTimeComparison \
-  cmGlobalUnixMakefileGenerator3 \
+  cmInstallTargetsCommand \
+  cmInstalledFile \
+  cmLinkDirectoriesCommand \
+  cmLinkLineComputer \
+  cmListCommand \
+  cmListFileCache \
+  cmLocalCommonGenerator \
+  cmLocalGenerator \
   cmLocalUnixMakefileGenerator3 \
+  cmMSVC60LinkLineComputer \
+  cmMacroCommand \
+  cmMakeDirectoryCommand \
+  cmMakefile \
   cmMakefileExecutableTargetGenerator \
   cmMakefileLibraryTargetGenerator \
   cmMakefileTargetGenerator \
   cmMakefileUtilityTargetGenerator \
-  cmOutputConverter \
-  cmOSXBundleGenerator \
+  cmMarkAsAdvancedCommand \
+  cmMathCommand \
+  cmMessageCommand \
+  cmMessenger \
   cmNewLineStyle \
-  cmBootstrapCommands1 \
-  cmBootstrapCommands2 \
-  cmCommandsForBootstrap \
+  cmOSXBundleGenerator \
+  cmOptionCommand \
+  cmOrderDirectories \
+  cmOutputConverter \
+  cmParseArgumentsCommand \
+  cmPathLabel \
+  cmPolicies \
+  cmProcessOutput \
+  cmProjectCommand \
+  cmProperty \
+  cmPropertyDefinition \
+  cmPropertyDefinitionMap \
+  cmPropertyMap \
+  cmReturnCommand \
+  cmRulePlaceholderExpander \
+  cmScriptGenerator \
+  cmSearchPath \
+  cmSeparateArgumentsCommand \
+  cmSetCommand \
+  cmSetDirectoryPropertiesCommand \
+  cmSetPropertyCommand \
+  cmSetSourceFilesPropertiesCommand \
+  cmSetTargetPropertiesCommand \
+  cmSetTestsPropertiesCommand \
+  cmSiteNameCommand \
+  cmSourceFile \
+  cmSourceFileLocation \
+  cmState \
+  cmStateDirectory \
+  cmStateSnapshot \
+  cmStringCommand \
+  cmSubdirCommand \
+  cmSystemTools \
   cmTarget \
+  cmTargetLinkLibrariesCommand \
+  cmTargetPropertyComputer \
   cmTest \
-  cmCustomCommand \
-  cmCustomCommandGenerator \
-  cmCacheManager \
-  cmListFileCache \
-  cmComputeLinkDepends \
-  cmComputeLinkInformation \
-  cmOrderDirectories \
-  cmComputeTargetDepends \
-  cmComputeComponentGraph \
-  cmExprLexer \
-  cmExprParser \
-  cmExprParserHelper \
+  cmTestGenerator \
+  cmTimestamp \
+  cmTryCompileCommand \
+  cmTryRunCommand \
+  cmUnexpectedCommand \
+  cmUnsetCommand \
+  cmVersion \
+  cmWhileCommand \
+  cmake  \
+  cmakemain \
+  cmcmd  \
 "
 
 if ${cmake_system_mingw}; then
@@ -403,6 +489,8 @@ Configuration:
   --no-system-liblzma     use cmake-provided liblzma library (default)
   --system-libarchive     use system-installed libarchive library
   --no-system-libarchive  use cmake-provided libarchive library (default)
+  --system-librhash       use system-installed librhash library
+  --no-system-librhash    use cmake-provided librhash library (default)
 
   --qt-gui                build the Qt-based GUI (requires Qt >= 4.2)
   --no-qt-gui             do not build the Qt-based GUI (default)
@@ -636,10 +724,10 @@ while test $# != 0; do
   --init=*) cmake_init_file=`cmake_arg "$1"` ;;
   --system-libs) cmake_bootstrap_system_libs="${cmake_bootstrap_system_libs} -DCMAKE_USE_SYSTEM_LIBRARIES=1" ;;
   --no-system-libs) cmake_bootstrap_system_libs="${cmake_bootstrap_system_libs} -DCMAKE_USE_SYSTEM_LIBRARIES=0" ;;
-  --system-bzip2|--system-curl|--system-expat|--system-jsoncpp|--system-libarchive|--system-zlib|--system-liblzma)
+  --system-bzip2|--system-curl|--system-expat|--system-jsoncpp|--system-libarchive|--system-librhash|--system-zlib|--system-liblzma)
     lib=`cmake_arg "$1" "--system-"`
     cmake_bootstrap_system_libs="${cmake_bootstrap_system_libs} -DCMAKE_USE_SYSTEM_LIBRARY_`cmake_toupper $lib`=1" ;;
-  --no-system-bzip2|--no-system-curl|--no-system-expat|--no-system-jsoncpp|--no-system-libarchive|--no-system-zlib|--no-system-liblzma)
+  --no-system-bzip2|--no-system-curl|--no-system-expat|--no-system-jsoncpp|--no-system-libarchive|--no-system-librhash|--no-system-zlib|--no-system-liblzma)
     lib=`cmake_arg "$1" "--no-system-"`
     cmake_bootstrap_system_libs="${cmake_bootstrap_system_libs} -DCMAKE_USE_SYSTEM_LIBRARY_`cmake_toupper $lib`=0" ;;
   --qt-gui) cmake_bootstrap_qt_gui="1" ;;
@@ -1316,16 +1404,6 @@ for a in ${CMAKE_CXX_SOURCES} ${CMAKE_C_SOURCES} ${KWSYS_CXX_SOURCES} ${KWSYS_C_
   objs="${objs} ${a}.o"
 done
 
-# Generate dependencies for cmBootstrapCommands1.cxx
-for file in `grep "#include.*cm[^.]*.cxx" "${cmake_source_dir}/Source/cmBootstrapCommands1.cxx" | sed "s/.* \"\(.*\)\"/\1/"`; do
-  cmBootstrapCommands1Deps="${cmBootstrapCommands1Deps} `cmake_escape "${cmake_source_dir}/Source/$file"`"
-done
-cmBootstrapCommands1Deps=`echo $cmBootstrapCommands1Deps`
-for file in `grep "#include.*cm[^.]*.cxx" "${cmake_source_dir}/Source/cmBootstrapCommands2.cxx" | sed "s/.* \"\(.*\)\"/\1/"`; do
-  cmBootstrapCommands2Deps="${cmBootstrapCommands2Deps} `cmake_escape "${cmake_source_dir}/Source/$file"`"
-done
-cmBootstrapCommands2Deps=`echo $cmBootstrapCommands2Deps`
-
 if [ "x${cmake_ansi_cxx_flags}" != "x" ]; then
   cmake_cxx_flags="${cmake_ansi_cxx_flags} ${cmake_cxx_flags}"
 fi
@@ -1341,6 +1419,7 @@ fi
 cmake_c_flags_String="-DKWSYS_STRING_C"
 if ${cmake_system_mingw}; then
   cmake_c_flags_EncodingC="-DKWSYS_ENCODING_DEFAULT_CODEPAGE=CP_ACP"
+  cmake_cxx_flags_cmProcessOutput="${cmake_c_flags_EncodingC}"
 fi
 cmake_cxx_flags_SystemTools="
   -DKWSYS_CXX_HAS_SETENV=${KWSYS_CXX_HAS_SETENV}
@@ -1357,8 +1436,9 @@ echo "cmake: ${objs}" > "${cmake_bootstrap_dir}/Makefile"
 echo "	${cmake_cxx_compiler} ${cmake_ld_flags} ${cmake_cxx_flags} ${objs} -o cmake" >> "${cmake_bootstrap_dir}/Makefile"
 for a in ${CMAKE_CXX_SOURCES}; do
   src=`cmake_escape "${cmake_source_dir}/Source/${a}.cxx"`
+  src_flags=`eval echo \\${cmake_cxx_flags_\${a}}`
   echo "${a}.o : ${src} ${dep}" >> "${cmake_bootstrap_dir}/Makefile"
-  echo "	${cmake_cxx_compiler} ${cmake_cxx_flags} -c ${src} -o ${a}.o" >> "${cmake_bootstrap_dir}/Makefile"
+  echo "	${cmake_cxx_compiler} ${cmake_cxx_flags} ${src_flags} -c ${src} -o ${a}.o" >> "${cmake_bootstrap_dir}/Makefile"
 done
 echo "cmBootstrapCommands1.o : $cmBootstrapCommands1Deps" >> "${cmake_bootstrap_dir}/Makefile"
 echo "cmBootstrapCommands2.o : $cmBootstrapCommands2Deps" >> "${cmake_bootstrap_dir}/Makefile"

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-cmake/cmake.git



More information about the Pkg-cmake-commits mailing list