code:
# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

#[=======================================================================[.rst:
FindCurses
----------

Find the curses or ncurses include file and library.

Result Variables
^^^^^^^^^^^^^^^^

This module defines the following variables:

``CURSES_FOUND``
  True if Curses is found.
``CURSES_INCLUDE_DIRS``
  The include directories needed to use Curses.
``CURSES_LIBRARIES``
  The libraries needed to use Curses.
``CURSES_CFLAGS``
  .. versionadded:: 3.16

  Parameters which ought be given to C/C++ compilers when using Curses.
``CURSES_HAVE_CURSES_H``
  True if curses.h is available.
``CURSES_HAVE_NCURSES_H``
  True if ncurses.h is available.
``CURSES_HAVE_NCURSES_NCURSES_H``
  True if ``ncurses/ncurses.h`` is available.
``CURSES_HAVE_NCURSES_CURSES_H``
  True if ``ncurses/curses.h`` is available.

Set ``CURSES_NEED_NCURSES`` to ``TRUE`` before the
``find_package(Curses)`` call if NCurses functionality is required.

.. versionadded:: 3.10
  Set ``CURSES_NEED_WIDE`` to ``TRUE`` before the
  ``find_package(Curses)`` call if unicode functionality is required.

Backward Compatibility
^^^^^^^^^^^^^^^^^^^^^^

The following variable are provided for backward compatibility:

``CURSES_INCLUDE_DIR``
  Path to Curses include.  Use ``CURSES_INCLUDE_DIRS`` instead.
``CURSES_LIBRARY``
  Path to Curses library.  Use ``CURSES_LIBRARIES`` instead.
#]=======================================================================]

include(${CMAKE_CURRENT_LIST_DIR}/CheckLibraryExists.cmake)

# we don't know anything about cursesw, so only ncurses
# may be ncursesw
if(NOT CURSES_NEED_WIDE)
  set(NCURSES_LIBRARY_NAME "ncurses")
  set(CURSES_FORM_LIBRARY_NAME "form")
else()
  set(NCURSES_LIBRARY_NAME "ncursesw")
  set(CURSES_FORM_LIBRARY_NAME "formw")
  # Also, if we are searching for wide curses - we are actually searching
  # for ncurses, we don't know about any other unicode version.
  set(CURSES_NEED_NCURSES TRUE)
endif()

find_library(CURSES_CURSES_LIBRARY NAMES curses)

find_library(CURSES_NCURSES_LIBRARY NAMES "${NCURSES_LIBRARY_NAME}" )
set(CURSES_USE_NCURSES FALSE)

if(CURSES_NCURSES_LIBRARY  AND ((NOT CURSES_CURSES_LIBRARY) OR CURSES_NEED_NCURSES))
  set(CURSES_USE_NCURSES TRUE)
endif()
# http://cygwin.com/ml/cygwin-announce/2010-01/msg00002.html
# cygwin ncurses stopped providing curses.h symlinks see above
# message.  Cygwin is an ncurses package, so force ncurses on
# cygwin if the curses.h is missing
if(CURSES_NCURSES_LIBRARY AND CYGWIN)
  if (CURSES_NEED_WIDE)
    if(NOT EXISTS /usr/include/ncursesw/curses.h)
      set(CURSES_USE_NCURSES TRUE)
    endif()
  else()
    if(NOT EXISTS /usr/include/curses.h)
      set(CURSES_USE_NCURSES TRUE)
    endif()
  endif()
endif()

# Not sure the logic is correct here.
# If NCurses is required, use the function wsyncup() to check if the library
# has NCurses functionality (at least this is where it breaks on NetBSD).
# If wsyncup is in curses, use this one.
# If not, try to find ncurses and check if this has the symbol.
# Once the ncurses library is found, search the ncurses.h header first, but
# some web pages also say that even with ncurses there is not always a ncurses.h:
# http://osdir.com/ml/gnome.apps.mc.devel/2002-06/msg00029.html
# So at first try ncurses.h, if not found, try to find curses.h under the same
# prefix as the library was found, if still not found, try curses.h with the
# default search paths.
if(CURSES_CURSES_LIBRARY  AND  CURSES_NEED_NCURSES)
  include(${CMAKE_CURRENT_LIST_DIR}/CMakePushCheckState.cmake)
  cmake_push_check_state()
  set(CMAKE_REQUIRED_QUIET ${Curses_FIND_QUIETLY})
  CHECK_LIBRARY_EXISTS("${CURSES_CURSES_LIBRARY}"
    wsyncup "" CURSES_CURSES_HAS_WSYNCUP)

  if(CURSES_NCURSES_LIBRARY  AND NOT  CURSES_CURSES_HAS_WSYNCUP)
    CHECK_LIBRARY_EXISTS("${CURSES_NCURSES_LIBRARY}"
      wsyncup "" CURSES_NCURSES_HAS_WSYNCUP)
    if( CURSES_NCURSES_HAS_WSYNCUP)
      set(CURSES_USE_NCURSES TRUE)
    endif()
  endif()
  cmake_pop_check_state()

endif()

if(CURSES_USE_NCURSES)
  get_filename_component(_cursesLibDir "${CURSES_NCURSES_LIBRARY}" PATH)
  get_filename_component(_cursesParentDir "${_cursesLibDir}" PATH)

  # Use CURSES_NCURSES_INCLUDE_PATH if set, for compatibility.
  if(CURSES_NCURSES_INCLUDE_PATH)
    if (CURSES_NEED_WIDE)
      find_path(CURSES_INCLUDE_PATH
        NAMES ncursesw/ncurses.h ncursesw/curses.h ncursesw.h cursesw.h
        PATHS ${CURSES_NCURSES_INCLUDE_PATH}
        NO_DEFAULT_PATH
        )
    else()
      find_path(CURSES_INCLUDE_PATH
        NAMES ncurses/ncurses.h ncurses/curses.h ncurses.h curses.h
        PATHS ${CURSES_NCURSES_INCLUDE_PATH}
        NO_DEFAULT_PATH
        )
    endif()
  endif()

  if (CURSES_NEED_WIDE)
    set(CURSES_TINFO_LIBRARY_NAME tinfow)
    find_path(CURSES_INCLUDE_PATH
      NAMES ncursesw/ncurses.h ncursesw/curses.h ncursesw.h cursesw.h
      HINTS "${_cursesParentDir}/include"
      )
  else()
    set(CURSES_TINFO_LIBRARY_NAME tinfo)
    find_path(CURSES_INCLUDE_PATH
      NAMES ncurses/ncurses.h ncurses/curses.h ncurses.h curses.h
      HINTS "${_cursesParentDir}/include"
      )
  endif()

  # Previous versions of FindCurses provided these values.
  if(NOT DEFINED CURSES_LIBRARY)
    set(CURSES_LIBRARY "${CURSES_NCURSES_LIBRARY}")
  endif()

  CHECK_LIBRARY_EXISTS("${CURSES_NCURSES_LIBRARY}"
    cbreak "" CURSES_NCURSES_HAS_CBREAK)
  CHECK_LIBRARY_EXISTS("${CURSES_NCURSES_LIBRARY}"
    nodelay "" CURSES_NCURSES_HAS_NODELAY)
  if(NOT CURSES_NCURSES_HAS_CBREAK OR NOT CURSES_NCURSES_HAS_NODELAY)
    find_library(CURSES_EXTRA_LIBRARY "${CURSES_TINFO_LIBRARY_NAME}" HINTS "${_cursesLibDir}")
    find_library(CURSES_EXTRA_LIBRARY "${CURSES_TINFO_LIBRARY_NAME}" )

    mark_as_advanced(
      CURSES_EXTRA_LIBRARY
      )
  endif()
else()
  get_filename_component(_cursesLibDir "${CURSES_CURSES_LIBRARY}" PATH)
  get_filename_component(_cursesParentDir "${_cursesLibDir}" PATH)

  #We can't find anything with CURSES_NEED_WIDE because we know
  #only about ncursesw unicode curses version
  if(NOT CURSES_NEED_WIDE)
    find_path(CURSES_INCLUDE_PATH
      NAMES curses.h
      HINTS "${_cursesParentDir}/include"
      )
  endif()

  # Previous versions of FindCurses provided these values.
  if(NOT DEFINED CURSES_CURSES_H_PATH)
    set(CURSES_CURSES_H_PATH "${CURSES_INCLUDE_PATH}")
  endif()
  if(NOT DEFINED CURSES_LIBRARY)
    set(CURSES_LIBRARY "${CURSES_CURSES_LIBRARY}")
  endif()
endif()

# Report whether each possible header name exists in the include directory.
if(NOT DEFINED CURSES_HAVE_NCURSES_NCURSES_H)
  if(CURSES_NEED_WIDE)
    if(EXISTS "${CURSES_INCLUDE_PATH}/ncursesw/ncurses.h")
      set(CURSES_HAVE_NCURSES_NCURSES_H "${CURSES_INCLUDE_PATH}/ncursesw/ncurses.h")
    endif()
  elseif(EXISTS "${CURSES_INCLUDE_PATH}/ncurses/ncurses.h")
    set(CURSES_HAVE_NCURSES_NCURSES_H "${CURSES_INCLUDE_PATH}/ncurses/ncurses.h")
  endif()
  if(NOT DEFINED CURSES_HAVE_NCURSES_NCURSES_H)
    set(CURSES_HAVE_NCURSES_NCURSES_H "CURSES_HAVE_NCURSES_NCURSES_H-NOTFOUND")
  endif()
endif()
if(NOT DEFINED CURSES_HAVE_NCURSES_CURSES_H)
  if(CURSES_NEED_WIDE)
    if(EXISTS "${CURSES_INCLUDE_PATH}/ncursesw/curses.h")
      set(CURSES_HAVE_NCURSES_CURSES_H "${CURSES_INCLUDE_PATH}/ncursesw/curses.h")
    endif()
  elseif(EXISTS "${CURSES_INCLUDE_PATH}/ncurses/curses.h")
    set(CURSES_HAVE_NCURSES_CURSES_H "${CURSES_INCLUDE_PATH}/ncurses/curses.h")
  endif()
  if(NOT DEFINED CURSES_HAVE_NCURSES_CURSES_H)
    set(CURSES_HAVE_NCURSES_CURSES_H "CURSES_HAVE_NCURSES_CURSES_H-NOTFOUND")
  endif()
endif()
if(NOT CURSES_NEED_WIDE)
  #ncursesw can't be found for this paths
  if(NOT DEFINED CURSES_HAVE_NCURSES_H)
    if(EXISTS "${CURSES_INCLUDE_PATH}/ncurses.h")
      set(CURSES_HAVE_NCURSES_H "${CURSES_INCLUDE_PATH}/ncurses.h")
    else()
      set(CURSES_HAVE_NCURSES_H "CURSES_HAVE_NCURSES_H-NOTFOUND")
    endif()
  endif()
  if(NOT DEFINED CURSES_HAVE_CURSES_H)
    if(EXISTS "${CURSES_INCLUDE_PATH}/curses.h")
      set(CURSES_HAVE_CURSES_H "${CURSES_INCLUDE_PATH}/curses.h")
    else()
      set(CURSES_HAVE_CURSES_H "CURSES_HAVE_CURSES_H-NOTFOUND")
    endif()
  endif()
endif()

find_library(CURSES_FORM_LIBRARY "${CURSES_FORM_LIBRARY_NAME}" HINTS "${_cursesLibDir}")
find_library(CURSES_FORM_LIBRARY "${CURSES_FORM_LIBRARY_NAME}" )

# Previous versions of FindCurses provided these values.
if(NOT DEFINED FORM_LIBRARY)
  set(FORM_LIBRARY "${CURSES_FORM_LIBRARY}")
endif()

# Need to provide the *_LIBRARIES
set(CURSES_LIBRARIES ${CURSES_LIBRARY})

if(CURSES_EXTRA_LIBRARY)
  set(CURSES_LIBRARIES ${CURSES_LIBRARIES} ${CURSES_EXTRA_LIBRARY})
endif()

if(CURSES_FORM_LIBRARY)
  set(CURSES_LIBRARIES ${CURSES_LIBRARIES} ${CURSES_FORM_LIBRARY})
endif()

# Provide the *_INCLUDE_DIRS and *_CFLAGS results.
set(CURSES_INCLUDE_DIRS ${CURSES_INCLUDE_PATH})
set(CURSES_INCLUDE_DIR ${CURSES_INCLUDE_PATH}) # compatibility

find_package(PkgConfig QUIET)
if(PKG_CONFIG_FOUND)
  pkg_check_modules(NCURSES QUIET ${NCURSES_LIBRARY_NAME})
  set(CURSES_CFLAGS ${NCURSES_CFLAGS_OTHER})
endif()

include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Curses DEFAULT_MSG
  CURSES_LIBRARY CURSES_INCLUDE_PATH)

mark_as_advanced(
  CURSES_INCLUDE_PATH
  CURSES_CURSES_LIBRARY
  CURSES_NCURSES_LIBRARY
  CURSES_FORM_LIBRARY
  )


code:
# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

#[=======================================================================[.rst:
FindCxxTest
-----------

Find CxxTest unit testing framework.

Find the `CxxTest`_ suite and declare a helper macro for creating
unit tests and integrating them with CTest.

.. _`CxxTest`: https://github.com/CxxTest/cxxtest

Input Variables
^^^^^^^^^^^^^^^

``CXXTEST_USE_PYTHON``
  .. deprecated:: 1.3

  Only used in the case both Python & Perl
  are detected on the system to control
  which CxxTest code generator is used.
  Valid only for CxxTest version 3.

  In older versions of this Find Module,
  this variable controlled if the Python test
  generator was used instead of the Perl one,
  regardless of which scripting language the
  user had installed.

``CXXTEST_TESTGEN_ARGS``
  .. versionadded:: 2.8.3

  Specify a list of options to pass to the CxxTest code
  generator.  If not defined, ``--error-printer`` is passed.

Result Variables
^^^^^^^^^^^^^^^^

``CXXTEST_FOUND``
  True if the CxxTest framework was found

``CXXTEST_INCLUDE_DIRS``
  Where to find the CxxTest include directory

``CXXTEST_PERL_TESTGEN_EXECUTABLE``
  The perl-based test generator

``CXXTEST_PYTHON_TESTGEN_EXECUTABLE``
  The python-based test generator

``CXXTEST_TESTGEN_EXECUTABLE``
  .. versionadded:: 2.8.3

  The test generator that is actually used (chosen using user preferences
  and interpreters found in the system)

``CXXTEST_TESTGEN_INTERPRETER``
  .. versionadded:: 2.8.3

  The full path to the Perl or Python executable on the system, on
  platforms where the script cannot be executed using its shebang line.

Module Commands
^^^^^^^^^^^^^^^

.. command:: cxxtest_add_test

  Create a CxxTest runner and adds it to the CTest testing suite::

    CXXTEST_ADD_TEST(<test_name> <gen_source_file>
                     <input_files_to_testgen>...)

  Parameters:

  ``test_name``
    The name of the test

  ``gen_source_file``
    The generated source filename to be generated by CxxTest

  ``input_files_to_testgen``
    The list of header files containing the CxxTest::TestSuite's
    to be included in this runner

Example Usage
^^^^^^^^^^^^^

The following example, if CxxTest is found, will:

* Invoke the testgen executable to autogenerate foo_test.cc in the
  binary tree from "foo_test.h" in the current source directory.
* Create an executable and test called unittest_foo.

.. code-block:: cmake

  find_package(CxxTest)
  if(CXXTEST_FOUND)
    include_directories(${CXXTEST_INCLUDE_DIR})
    enable_testing()
    CXXTEST_ADD_TEST(unittest_foo foo_test.cc
                     ${CMAKE_CURRENT_SOURCE_DIR}/foo_test.h)
    target_link_libraries(unittest_foo foo) # as needed
  endif()

``foo_test.h`` contains:

.. code-block:: c++

  #include <cxxtest/TestSuite.h>
  class MyTestSuite : public CxxTest::TestSuite
  {
  public:
     void testAddition( void )
     {
        TS_ASSERT( 1 + 1 > 1 );
        TS_ASSERT_EQUALS( 1 + 1, 2 );
     }
  };

#]=======================================================================]

# Version 1.4 (11/18/10) (CMake 2.8.4)
#     Issue 11384: Added support to the CXX_ADD_TEST macro so header
#                  files (containing the tests themselves) show up in
#                  Visual Studio and other IDEs.
#
# Version 1.3 (8/19/10) (CMake 2.8.3)
#     Included patch by Simone Rossetto to check if either Python or Perl
#     are present in the system.  Whichever interpreter that is detected
#     is now used to run the test generator program.  If both interpreters
#     are detected, the CXXTEST_USE_PYTHON variable is obeyed.
#
#     Also added support for CXXTEST_TESTGEN_ARGS, for manually specifying
#     options to the CxxTest code generator.
# Version 1.2 (3/2/08)
#     Included patch from Tyler Roscoe to have the perl & python binaries
#     detected based on CXXTEST_INCLUDE_DIR
# Version 1.1 (2/9/08)
#     Clarified example to illustrate need to call target_link_libraries()
#     Changed commands to lowercase
#     Added licensing info
# Version 1.0 (1/8/08)
#     Fixed CXXTEST_INCLUDE_DIRS so it will work properly
#     Eliminated superfluous CXXTEST_FOUND assignment
#     Cleaned up and added more documentation

#=============================================================
# CXXTEST_ADD_TEST (public macro)
#=============================================================
macro(CXXTEST_ADD_TEST _cxxtest_testname _cxxtest_outfname)
    set(_cxxtest_real_outfname ${CMAKE_CURRENT_BINARY_DIR}/${_cxxtest_outfname})

    add_custom_command(
        OUTPUT  ${_cxxtest_real_outfname}
        DEPENDS ${ARGN}
        COMMAND ${CXXTEST_TESTGEN_INTERPRETER}
        ${CXXTEST_TESTGEN_EXECUTABLE} ${CXXTEST_TESTGEN_ARGS} -o ${_cxxtest_real_outfname} ${ARGN}
    )

    set_source_files_properties(${_cxxtest_real_outfname} PROPERTIES GENERATED true)
    add_executable(${_cxxtest_testname} ${_cxxtest_real_outfname} ${ARGN})

    if(CMAKE_RUNTIME_OUTPUT_DIRECTORY)
        add_test(${_cxxtest_testname} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${_cxxtest_testname})
    elseif(EXECUTABLE_OUTPUT_PATH)
        add_test(${_cxxtest_testname} ${EXECUTABLE_OUTPUT_PATH}/${_cxxtest_testname})
    else()
        add_test(${_cxxtest_testname} ${CMAKE_CURRENT_BINARY_DIR}/${_cxxtest_testname})
    endif()

endmacro()

#=============================================================
# main()
#=============================================================
if(NOT DEFINED CXXTEST_TESTGEN_ARGS)
  set(CXXTEST_TESTGEN_ARGS --error-printer)
endif()

find_package(Python QUIET)
find_package(Perl QUIET)

find_path(CXXTEST_INCLUDE_DIR cxxtest/TestSuite.h)
find_program(CXXTEST_PYTHON_TESTGEN_EXECUTABLE
         NAMES cxxtestgen cxxtestgen.py
         PATHS ${CXXTEST_INCLUDE_DIR})
find_program(CXXTEST_PERL_TESTGEN_EXECUTABLE cxxtestgen.pl
         PATHS ${CXXTEST_INCLUDE_DIR})

if(PYTHON_FOUND OR PERL_FOUND)
  include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)

  if(PYTHON_FOUND AND (CXXTEST_USE_PYTHON OR NOT PERL_FOUND OR NOT DEFINED CXXTEST_USE_PYTHON))
    set(CXXTEST_TESTGEN_EXECUTABLE ${CXXTEST_PYTHON_TESTGEN_EXECUTABLE})
    execute_process(COMMAND ${CXXTEST_PYTHON_TESTGEN_EXECUTABLE} --version
      OUTPUT_VARIABLE _CXXTEST_OUT ERROR_VARIABLE _CXXTEST_OUT RESULT_VARIABLE _CXXTEST_RESULT)
    if(_CXXTEST_RESULT EQUAL 0)
      set(CXXTEST_TESTGEN_INTERPRETER "")
    else()
      set(CXXTEST_TESTGEN_INTERPRETER ${Python_EXECUTABLE})
    endif()
    FIND_PACKAGE_HANDLE_STANDARD_ARGS(CxxTest DEFAULT_MSG
        CXXTEST_INCLUDE_DIR CXXTEST_PYTHON_TESTGEN_EXECUTABLE)

  elseif(PERL_FOUND)
    set(CXXTEST_TESTGEN_EXECUTABLE ${CXXTEST_PERL_TESTGEN_EXECUTABLE})
    set(CXXTEST_TESTGEN_INTERPRETER ${PERL_EXECUTABLE})
    FIND_PACKAGE_HANDLE_STANDARD_ARGS(CxxTest DEFAULT_MSG
        CXXTEST_INCLUDE_DIR CXXTEST_PERL_TESTGEN_EXECUTABLE)
  endif()

  if(CXXTEST_FOUND)
    set(CXXTEST_INCLUDE_DIRS ${CXXTEST_INCLUDE_DIR})
  endif()

else()

  set(CXXTEST_FOUND false)
  if(NOT CxxTest_FIND_QUIETLY)
    if(CxxTest_FIND_REQUIRED)
      message(FATAL_ERROR "Neither Python nor Perl found, cannot use CxxTest, aborting!")
    else()
      message(STATUS "Neither Python nor Perl found, CxxTest will not be used.")
    endif()
  endif()

endif()

repo_name: lazytadpole/codenamesilverfish

license: mit


code:
# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

#[=======================================================================[.rst:
FindCygwin
----------

Find Cygwin, a POSIX-compatible environment that runs natively
on Microsoft Windows
#]=======================================================================]

if (WIN32)
  if(CYGWIN_INSTALL_PATH)
    set(CYGWIN_BAT "${CYGWIN_INSTALL_PATH}/cygwin.bat")
  endif()

  find_program(CYGWIN_BAT
    NAMES cygwin.bat
    PATHS
      "C:/Cygwin"
      "C:/Cygwin64"
      "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Cygwin\\setup;rootdir]"
      "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Cygnus Solutions\\Cygwin\\mounts v2\\/;native]"
  )
  get_filename_component(CYGWIN_INSTALL_PATH "${CYGWIN_BAT}" DIRECTORY)
  mark_as_advanced(CYGWIN_BAT)

endif ()


code:
# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

#[=======================================================================[.rst:
FindDCMTK
---------

Find DICOM ToolKit (DCMTK) libraries and applications

The module defines the following variables::

 DCMTK_INCLUDE_DIRS  - Directories to include to use DCMTK
 DCMTK_LIBRARIES     - Files to link against to use DCMTK
 DCMTK_FOUND         - If false, don't try to use DCMTK
 DCMTK_DIR           - (optional) Source directory for DCMTK

Compatibility
^^^^^^^^^^^^^

This module is able to find a version of DCMTK that does or does not export
a ``DCMTKConfig.cmake`` file. It applies a two step process:

* Step 1:  Attempt to find DCMTK version providing a ``DCMTKConfig.cmake`` file.
* Step 2:  If step 1 failed, rely on ``FindDCMTK.cmake`` to set ``DCMTK_*``
  variables details below.

`Recent DCMTK
<https://git.dcmtk.org/?p=dcmtk.git;a=commit;h=662ae187c493c6b9a73dd5e3875372cebd0c11fe>`_
provides a ``DCMTKConfig.cmake`` :manual:`package configuration file
<cmake-packages(7)>`. To exclusively use the package configuration file
(recommended when possible), pass the `NO_MODULE` option to
:command:`find_package`. For example, `find_package(DCMTK NO_MODULE)`.
This requires official DCMTK snapshot *3.6.1_20140617* or newer.

Until all clients update to the more recent DCMTK, build systems will need
to support different versions of DCMTK.

On any given system, the following combinations of DCMTK versions could be
considered:

+--------+---------------------+-----------------------+-------------------+
|        |   SYSTEM DCMTK      |      LOCAL DCMTK      |     Supported ?   |
+--------+---------------------+-----------------------+-------------------+
| Case A |   NA                |      [ ] DCMTKConfig  |         YES       |
+--------+---------------------+-----------------------+-------------------+
| Case B |   NA                |      [X] DCMTKConfig  |         YES       |
+--------+---------------------+-----------------------+-------------------+
| Case C |   [ ] DCMTKConfig   |      NA               |         YES       |
+--------+---------------------+-----------------------+-------------------+
| Case D |   [X] DCMTKConfig   |      NA               |         YES       |
+--------+---------------------+-----------------------+-------------------+
| Case E |   [ ] DCMTKConfig   |      [ ] DCMTKConfig  |         YES (*)   |
+--------+---------------------+-----------------------+-------------------+
| Case F |   [X] DCMTKConfig   |      [ ] DCMTKConfig  |         NO        |
+--------+---------------------+-----------------------+-------------------+
| Case G |   [ ] DCMTKConfig   |      [X] DCMTKConfig  |         YES       |
+--------+---------------------+-----------------------+-------------------+
| Case H |   [X] DCMTKConfig   |      [X] DCMTKConfig  |         YES       |
+--------+---------------------+-----------------------+-------------------+

 (*) See Troubleshooting section.

Legend:

  NA ...............: Means that no System or Local DCMTK is available

  [ ] DCMTKConfig ..: Means that the version of DCMTK does NOT export a DCMTKConfig.cmake file.

  [X] DCMTKConfig ..: Means that the version of DCMTK exports a DCMTKConfig.cmake file.

Troubleshooting
^^^^^^^^^^^^^^^

What to do if my project finds a different version of DCMTK?

Remove DCMTK entry from the CMake cache per :command:`find_package`
documentation.
#]=======================================================================]

#
# Written for VXL by Amitha Perera.
# Upgraded for GDCM by Mathieu Malaterre.
# Modified for EasyViz by Thomas Sondergaard.
#

set(_dcmtk_dir_description "The directory of DCMTK build or install tree.")

# Ensure that DCMTK_DIR is set to a reasonable default value
# so that DCMTK libraries can be found on a standard Unix distribution.
# It also overwrite the value of DCMTK_DIR after this one has been
# set by a successful discovery of DCMTK by the unpatched FindDCMTK.cmake module
# distributed with CMake (as of 0167cea)
if(NOT DCMTK_DIR OR DCMTK_DIR STREQUAL "/usr/include/dcmtk")
  set(DCMTK_DIR "/usr" CACHE PATH ${_dcmtk_dir_description} FORCE)
endif()

set(_SAVED_DCMTK_DIR ${DCMTK_DIR})

#
# Step1: Attempt to find a version of DCMTK providing a DCMTKConfig.cmake file.
#
if(NOT DCMTK_FIND_QUIETLY)
  message(CHECK_START "Trying to find DCMTK expecting DCMTKConfig.cmake")
endif()
find_package(DCMTK QUIET NO_MODULE)
if(DCMTK_FOUND
    AND NOT "x" STREQUAL "x${DCMTK_LIBRARIES}"
    AND NOT "x" STREQUAL "x${DCMTK_INCLUDE_DIRS}")

  if(NOT DCMTK_FIND_QUIETLY)
    message(CHECK_PASS "ok")
  endif()
  return()
else()
  if(NOT DCMTK_FIND_QUIETLY)
    message(CHECK_FAIL "failed")
  endif()
endif()

if(NOT DCMTK_FIND_QUIETLY)
  message(STATUS "Trying to find DCMTK relying on FindDCMTK.cmake")
endif()

# Restore the value reset by the previous call to 'find_package(DCMTK QUIET NO_MODULE)'
set(DCMTK_DIR ${_SAVED_DCMTK_DIR} CACHE PATH ${_dcmtk_dir_description} FORCE)

#
# Step2: Attempt to find a version of DCMTK that does NOT provide a DCMTKConfig.cmake file.
#

# prefer DCMTK_DIR over default system paths like /usr/lib
if(DCMTK_DIR)
  set(CMAKE_PREFIX_PATH ${DCMTK_DIR}/lib ${CMAKE_PREFIX_PATH}) # this is given to FIND_LIBRARY or FIND_PATH
endif()

# Find all libraries, store debug and release separately
foreach(lib
    dcmpstat
    dcmsr
    dcmsign
    dcmtls
    dcmqrdb
    dcmnet
    dcmjpeg
    dcmimage
    dcmimgle
    dcmdata
    oflog
    ofstd
    ijg12
    ijg16
    ijg8
    )

  # Find Release libraries
  find_library(DCMTK_${lib}_LIBRARY_RELEASE
    ${lib}
    PATHS
    ${DCMTK_DIR}/${lib}/libsrc
    ${DCMTK_DIR}/${lib}/libsrc/Release
    ${DCMTK_DIR}/${lib}/Release
    ${DCMTK_DIR}/lib
    ${DCMTK_DIR}/lib/Release
    ${DCMTK_DIR}/dcmjpeg/lib${lib}/Release
    NO_DEFAULT_PATH
    )

  # Find Debug libraries
  find_library(DCMTK_${lib}_LIBRARY_DEBUG
    ${lib}${DCMTK_CMAKE_DEBUG_POSTFIX}
    PATHS
    ${DCMTK_DIR}/${lib}/libsrc
    ${DCMTK_DIR}/${lib}/libsrc/Debug
    ${DCMTK_DIR}/${lib}/Debug
    ${DCMTK_DIR}/lib
    ${DCMTK_DIR}/lib/Debug
    ${DCMTK_DIR}/dcmjpeg/lib${lib}/Debug
    NO_DEFAULT_PATH
    )

  mark_as_advanced(DCMTK_${lib}_LIBRARY_RELEASE)
  mark_as_advanced(DCMTK_${lib}_LIBRARY_DEBUG)

  # Add libraries to variable according to build type
  if(DCMTK_${lib}_LIBRARY_RELEASE)
    list(APPEND DCMTK_LIBRARIES optimized ${DCMTK_${lib}_LIBRARY_RELEASE})
  endif()

  if(DCMTK_${lib}_LIBRARY_DEBUG)
    list(APPEND DCMTK_LIBRARIES debug ${DCMTK_${lib}_LIBRARY_DEBUG})
  endif()

endforeach()

set(CMAKE_THREAD_LIBS_INIT)
if(DCMTK_oflog_LIBRARY_RELEASE OR DCMTK_oflog_LIBRARY_DEBUG)
  # Hack - Not having a DCMTKConfig.cmake file to read the settings from, we will attempt to
  # find the library in all cases.
  # Ideally, pthread library should be discovered only if DCMTK_WITH_THREADS is enabled.
  find_package(Threads)
endif()

if(CMAKE_THREAD_LIBS_INIT)
  list(APPEND DCMTK_LIBRARIES ${CMAKE_THREAD_LIBS_INIT})
endif()

#
# SPECIFIC CASE FOR DCMTK BUILD DIR as DCMTK_DIR
# (as opposed to a DCMTK install dir)
# Have to find the source directory.
if(EXISTS ${DCMTK_DIR}/CMakeCache.txt)
          load_cache(${DCMTK_DIR} READ_WITH_PREFIX "EXT"
          DCMTK_SOURCE_DIR)
  if(NOT EXISTS ${EXTDCMTK_SOURCE_DIR})
    message(FATAL_ERROR
      "DCMTK build directory references
nonexistent DCMTK source directory ${EXTDCMTK_SOURCE_DIR}")
  endif()
endif()

set(DCMTK_config_TEST_HEADER osconfig.h)
set(DCMTK_dcmdata_TEST_HEADER dctypes.h)
set(DCMTK_dcmimage_TEST_HEADER dicoimg.h)
set(DCMTK_dcmimgle_TEST_HEADER dcmimage.h)
set(DCMTK_dcmjpeg_TEST_HEADER djdecode.h)
set(DCMTK_dcmnet_TEST_HEADER assoc.h)
set(DCMTK_dcmpstat_TEST_HEADER dcmpstat.h)
set(DCMTK_dcmqrdb_TEST_HEADER dcmqrdba.h)
set(DCMTK_dcmsign_TEST_HEADER sicert.h)
set(DCMTK_dcmsr_TEST_HEADER dsrtree.h)
set(DCMTK_dcmtls_TEST_HEADER tlslayer.h)
set(DCMTK_ofstd_TEST_HEADER ofstdinc.h)
set(DCMTK_oflog_TEST_HEADER oflog.h)
set(DCMTK_dcmjpls_TEST_HEADER djlsutil.h)

set(DCMTK_INCLUDE_DIR_NAMES)

foreach(dir
    config
    dcmdata
    dcmimage
    dcmimgle
    dcmjpeg
    dcmjpls
    dcmnet
    dcmpstat
    dcmqrdb
    dcmsign
    dcmsr
    dcmtls
    ofstd
    oflog)
  if(EXTDCMTK_SOURCE_DIR)
    set(SOURCE_DIR_PATH
      ${EXTDCMTK_SOURCE_DIR}/${dir}/include/dcmtk/${dir})
  endif()
  find_path(DCMTK_${dir}_INCLUDE_DIR
    ${DCMTK_${dir}_TEST_HEADER}
    PATHS
    ${DCMTK_DIR}/${dir}/include
    ${DCMTK_DIR}/${dir}
    ${DCMTK_DIR}/include/dcmtk/${dir}
    ${DCMTK_DIR}/${dir}/include/dcmtk/${dir}
    ${DCMTK_DIR}/include/${dir}
    ${SOURCE_DIR_PATH}
    )
  mark_as_advanced(DCMTK_${dir}_INCLUDE_DIR)
  list(APPEND DCMTK_INCLUDE_DIR_NAMES DCMTK_${dir}_INCLUDE_DIR)

  if(DCMTK_${dir}_INCLUDE_DIR)
    # add the 'include' path so eg
    #include "dcmtk/dcmimgle/dcmimage.h"
    # works
    get_filename_component(_include ${DCMTK_${dir}_INCLUDE_DIR} PATH)
    get_filename_component(_include ${_include} PATH)
    list(APPEND
      DCMTK_INCLUDE_DIRS
      ${DCMTK_${dir}_INCLUDE_DIR}
      ${_include})
  endif()
endforeach()

list(APPEND DCMTK_INCLUDE_DIRS ${DCMTK_DIR}/include)

if(WIN32)
  list(APPEND DCMTK_LIBRARIES netapi32 wsock32)
endif()

if(DCMTK_ofstd_INCLUDE_DIR)
  get_filename_component(DCMTK_dcmtk_INCLUDE_DIR
    ${DCMTK_ofstd_INCLUDE_DIR}
    PATH
    CACHE)
  list(APPEND DCMTK_INCLUDE_DIRS ${DCMTK_dcmtk_INCLUDE_DIR})
  mark_as_advanced(DCMTK_dcmtk_INCLUDE_DIR)
endif()

# Compatibility: This variable is deprecated
set(DCMTK_INCLUDE_DIR ${DCMTK_INCLUDE_DIRS})

include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(DCMTK
  REQUIRED_VARS ${DCMTK_INCLUDE_DIR_NAMES} DCMTK_LIBRARIES
  FAIL_MESSAGE "Please set DCMTK_DIR and re-run configure")

# Workaround bug in packaging of DCMTK 3.6.0 on Debian.
# See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=637687
if(DCMTK_FOUND AND UNIX AND NOT APPLE)
  include(${CMAKE_CURRENT_LIST_DIR}/CheckIncludeFiles.cmake)
  set(CMAKE_REQUIRED_FLAGS )
  set(CMAKE_REQUIRED_DEFINITIONS )
  set(CMAKE_REQUIRED_INCLUDES ${DCMTK_INCLUDE_DIRS})
  set(CMAKE_REQUIRED_LIBRARIES ${DCMTK_LIBRARIES})
  set(CMAKE_REQUIRED_QUIET ${DCMTK_FIND_QUIETLY})
  check_include_files("dcmtk/config/osconfig.h;dcmtk/ofstd/ofstream.h" DCMTK_HAVE_CONFIG_H_OPTIONAL LANGUAGE CXX)
  if(NOT DCMTK_HAVE_CONFIG_H_OPTIONAL)
    set(DCMTK_DEFINITIONS "HAVE_CONFIG_H")
  endif()
endif()


code:
# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

#[=======================================================================[.rst:
FindDart
--------

.. deprecated:: 3.27
  This module is available only if policy :policy:`CMP0145` is not set to ``NEW``.

Find DART

This module looks for the dart testing software and sets DART_ROOT to
point to where it found it.
#]=======================================================================]

if(_FindDart_testing)
  set(_FindDart_included TRUE)
  return()
endif()

find_path(DART_ROOT README.INSTALL
    HINTS
      ENV DART_ROOT
    PATHS
      ${PROJECT_SOURCE_DIR}
      /usr/share
      C:/
      "C:/Program Files"
      ${PROJECT_SOURCE_DIR}/..
      [HKEY_LOCAL_MACHINE\\SOFTWARE\\Dart\\InstallPath]
      ENV ProgramFiles
    PATH_SUFFIXES
      Dart
    DOC "If you have Dart installed, where is it located?"
    )

include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Dart DEFAULT_MSG DART_ROOT)

mark_as_advanced(DART_ROOT)


code:
# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

#[=======================================================================[.rst:
FindDevIL
---------

This module locates the developer's image library.
https://openil.sourceforge.net/

IMPORTED Targets
^^^^^^^^^^^^^^^^

.. versionadded:: 3.21

This module defines the :prop_tgt:`IMPORTED` targets:

``DevIL::IL``
 Defined if the system has DevIL.

``DevIL::ILU``
 Defined if the system has DevIL Utilities.

``DevIL::ILUT``
 Defined if the system has DevIL Utility Toolkit.

Result Variables
^^^^^^^^^^^^^^^^

This module sets:

``IL_LIBRARIES``
  The name of the IL library. These include the full path to
  the core DevIL library. This one has to be linked into the
  application.

``ILU_LIBRARIES``
  The name of the ILU library. Again, the full path. This
  library is for filters and effects, not actual loading. It
  doesn't have to be linked if the functionality it provides
  is not used.

``ILUT_LIBRARIES``
  The name of the ILUT library. Full path. This part of the
  library interfaces with OpenGL. It is not strictly needed
  in applications.

``IL_INCLUDE_DIR``
  where to find the il.h, ilu.h and ilut.h files.

``DevIL_FOUND``
  This is set to TRUE if all the above variables were set.
  This will be set to false if ILU or ILUT are not found,
  even if they are not needed. In most systems, if one
  library is found all the others are as well. That's the
  way the DevIL developers release it.

``DevIL_ILUT_FOUND``
  .. versionadded:: 3.21

  This is set to TRUE if the ILUT library is found.
#]=======================================================================]

# TODO: Add version support.
# Tested under Linux and Windows (MSVC)

include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)

find_path(IL_INCLUDE_DIR il.h
  PATH_SUFFIXES include IL
  DOC "The path to the directory that contains il.h"
)

#message("IL_INCLUDE_DIR is ${IL_INCLUDE_DIR}")

find_library(IL_LIBRARIES
  NAMES IL DEVIL
  PATH_SUFFIXES libx32 lib64 lib lib32
  DOC "The file that corresponds to the base il library."
)

#message("IL_LIBRARIES is ${IL_LIBRARIES}")

find_library(ILUT_LIBRARIES
  NAMES ILUT
  PATH_SUFFIXES libx32 lib64 lib lib32
  DOC "The file that corresponds to the il (system?) utility library."
)

#message("ILUT_LIBRARIES is ${ILUT_LIBRARIES}")

find_library(ILU_LIBRARIES
  NAMES ILU
  PATH_SUFFIXES libx32 lib64 lib lib32
  DOC "The file that corresponds to the il utility library."
)

#message("ILU_LIBRARIES is ${ILU_LIBRARIES}")

FIND_PACKAGE_HANDLE_STANDARD_ARGS(DevIL DEFAULT_MSG
                                  IL_LIBRARIES ILU_LIBRARIES
                                  IL_INCLUDE_DIR)
# provide legacy variable for compatibility
set(IL_FOUND ${DevIL_FOUND})

# create imported targets ONLY if we found DevIL.
if(DevIL_FOUND)
  # Report the ILUT found if ILUT_LIBRARIES contains valid path.
  if (ILUT_LIBRARIES)
    set(DevIL_ILUT_FOUND TRUE)
  else()
    set(DevIL_ILUT_FOUND FALSE)
  endif()

  if(NOT TARGET DevIL::IL)
    add_library(DevIL::IL UNKNOWN IMPORTED)
    set_target_properties(DevIL::IL PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${IL_INCLUDE_DIR}"
      IMPORTED_LOCATION "${IL_LIBRARIES}")
  endif()

  # DevIL Utilities target
  if(NOT TARGET DevIL::ILU)
    add_library(DevIL::ILU UNKNOWN IMPORTED)
    set_target_properties(DevIL::ILU PROPERTIES
      IMPORTED_LOCATION "${ILU_LIBRARIES}")
    target_link_libraries(DevIL::ILU INTERFACE DevIL::IL)
  endif()

  # ILUT (if found)
  if(NOT TARGET DevIL::ILUT AND DevIL_ILUT_FOUND)
    add_library(DevIL::ILUT UNKNOWN IMPORTED)
    set_target_properties(DevIL::ILUT PROPERTIES
      IMPORTED_LOCATION "${ILUT_LIBRARIES}")
    target_link_libraries(DevIL::ILUT INTERFACE DevIL::ILU)
  endif()
endif()


code:
# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

#[=======================================================================[.rst:
FindDoxygen
-----------

Doxygen is a documentation generation tool (see https://www.doxygen.nl).
This module looks for Doxygen and some optional tools it supports:

``dot``
  `Graphviz <https://graphviz.org>`_ ``dot`` utility used to render various
  graphs.
``mscgen``
  `Message Chart Generator <https://www.mcternan.me.uk/mscgen/>`_ utility used
  by Doxygen's ``\msc`` and ``\mscfile`` commands.
``dia``
  `Dia <https://wiki.gnome.org/Apps/Dia>`_ the diagram editor used by Doxygen's
  ``\diafile`` command.

.. versionadded:: 3.9
  These tools are available as components in the :command:`find_package` command.
  For example:

.. code-block:: cmake

  # Require dot, treat the other components as optional
  find_package(Doxygen
               REQUIRED dot
               OPTIONAL_COMPONENTS mscgen dia)

The following variables are defined by this module:

.. variable:: DOXYGEN_FOUND

  True if the ``doxygen`` executable was found.

.. variable:: DOXYGEN_VERSION

  The version reported by ``doxygen --version``.

.. versionadded:: 3.9
  The module defines ``IMPORTED`` targets for Doxygen and each component found.
  These can be used as part of custom commands, etc. and should be preferred over
  old-style (and now deprecated) variables like ``DOXYGEN_EXECUTABLE``. The
  following import targets are defined if their corresponding executable could be
  found (the component import targets will only be defined if that component was
  requested):

::

  Doxygen::doxygen
  Doxygen::dot
  Doxygen::mscgen
  Doxygen::dia

Functions
^^^^^^^^^

.. command:: doxygen_add_docs

  .. versionadded:: 3.9

  This function is intended as a convenience for adding a target for generating
  documentation with Doxygen. It aims to provide sensible defaults so that
  projects can generally just provide the input files and directories and that
  will be sufficient to give sensible results. The function supports the
  ability to customize the Doxygen configuration used to build the
  documentation.

  ::

    doxygen_add_docs(targetName
        [filesOrDirs...]
        [ALL]
        [USE_STAMP_FILE]
        [WORKING_DIRECTORY dir]
        [COMMENT comment]
        [CONFIG_FILE filename])

  The function constructs a ``Doxyfile`` and defines a custom target that runs
  Doxygen on that generated file. The listed files and directories are used as
  the ``INPUT`` of the generated ``Doxyfile`` and they can contain wildcards.
  Any files that are listed explicitly will also be added as ``SOURCES`` of the
  custom target so they will show up in an IDE project's source list.

  So that relative input paths work as expected, by default the working
  directory of the Doxygen command will be the current source directory (i.e.
  :variable:`CMAKE_CURRENT_SOURCE_DIR`). This can be overridden with the
  ``WORKING_DIRECTORY`` option to change the directory used as the relative
  base point. Note also that Doxygen's default behavior is to strip the working
  directory from relative paths in the generated documentation (see the
  ``STRIP_FROM_PATH`` `Doxygen config option
  <https://www.doxygen.nl/manual/config.html>`_ for details).

  If provided, the optional ``comment`` will be passed as the ``COMMENT`` for
  the :command:`add_custom_target` command used to create the custom target
  internally.

  .. versionadded:: 3.27
    If ``CONFIG_FILE`` is set, the given file provided with full-path
    will be used as doxygen configuration file

  .. versionadded:: 3.12
    If ``ALL`` is set, the target will be added to the default build target.

  .. versionadded:: 3.16
    If ``USE_STAMP_FILE`` is set, the custom command defined by this function will
    create a stamp file with the name ``<targetName>.stamp`` in the current
    binary directory whenever doxygen is re-run.  With this option present, all
    items in ``<filesOrDirs>`` must be files (i.e. no directories, symlinks or
    wildcards) and each of the files must exist at the time
    ``doxygen_add_docs()`` is called.  An error will be raised if any of the
    items listed is missing or is not a file when ``USE_STAMP_FILE`` is given.
    A dependency will be created on each of the files so that doxygen will only
    be re-run if one of the files is updated.  Without the ``USE_STAMP_FILE``
    option, doxygen will always be re-run if the ``<targetName>`` target is built
    regardless of whether anything listed in ``<filesOrDirs>`` has changed.

  The contents of the generated ``Doxyfile`` can be customized by setting CMake
  variables before calling ``doxygen_add_docs()``. Any variable with a name of
  the form ``DOXYGEN_<tag>`` will have its value substituted for the
  corresponding ``<tag>`` configuration option in the ``Doxyfile``. See the
  `Doxygen documentation <https://www.doxygen.nl/manual/config.html>`_ for the
  full list of supported configuration options.

  Some of Doxygen's defaults are overridden to provide more appropriate
  behavior for a CMake project. Each of the following will be explicitly set
  unless the variable already has a value before ``doxygen_add_docs()`` is
  called (with some exceptions noted):

  .. variable:: DOXYGEN_HAVE_DOT

    Set to ``YES`` if the ``dot`` component was requested and it was found,
    ``NO`` otherwise. Any existing value of ``DOXYGEN_HAVE_DOT`` is ignored.

  .. variable:: DOXYGEN_DOT_MULTI_TARGETS

    Set to ``YES`` by this module (note that this requires a ``dot`` version
    newer than 1.8.10). This option is only meaningful if ``DOXYGEN_HAVE_DOT``
    is also set to ``YES``.

  .. variable:: DOXYGEN_GENERATE_LATEX

    Set to ``NO`` by this module.

  .. variable:: DOXYGEN_WARN_FORMAT

    For Visual Studio based generators, this is set to the form recognized by
    the Visual Studio IDE: ``$file($line) : $text``. For all other generators,
    Doxygen's default value is not overridden.

  .. variable:: DOXYGEN_PROJECT_NAME

    Populated with the name of the current project (i.e.
    :variable:`PROJECT_NAME`).

  .. variable:: DOXYGEN_PROJECT_NUMBER

    Populated with the version of the current project (i.e.
    :variable:`PROJECT_VERSION`).

  .. variable:: DOXYGEN_PROJECT_BRIEF

    Populated with the description of the current project (i.e.
    :variable:`PROJECT_DESCRIPTION`).

  .. variable:: DOXYGEN_INPUT

    Projects should not set this variable. It will be populated with the set of
    files and directories passed to ``doxygen_add_docs()``, thereby providing
    consistent behavior with the other built-in commands like
    :command:`add_executable`, :command:`add_library` and
    :command:`add_custom_target`. If a variable named ``DOXYGEN_INPUT`` is set
    by the project, it will be ignored and a warning will be issued.

  .. variable:: DOXYGEN_RECURSIVE

    Set to ``YES`` by this module.

  .. variable:: DOXYGEN_EXCLUDE_PATTERNS

    If the set of inputs includes directories, this variable will specify
    patterns used to exclude files from them. The following patterns are added
    by ``doxygen_add_docs()`` to ensure CMake-specific files and directories
    are not included in the input. If the project sets
    ``DOXYGEN_EXCLUDE_PATTERNS``, those contents are merged with these
    additional patterns rather than replacing them:

    ::

      */.git/*
      */.svn/*
      */.hg/*
      */CMakeFiles/*
      */_CPack_Packages/*
      DartConfiguration.tcl
      CMakeLists.txt
      CMakeCache.txt

  .. variable:: DOXYGEN_OUTPUT_DIRECTORY

    Set to :variable:`CMAKE_CURRENT_BINARY_DIR` by this module. Note that if
    the project provides its own value for this and it is a relative path, it
    will be converted to an absolute path relative to the current binary
    directory. This is necessary because doxygen will normally be run from a
    directory within the source tree so that relative source paths work as
    expected. If this directory does not exist, it will be recursively created
    prior to executing the doxygen commands.

To change any of these defaults or override any other Doxygen config option,
set relevant variables before calling ``doxygen_add_docs()``. For example:

  .. code-block:: cmake

    set(DOXYGEN_GENERATE_HTML NO)
    set(DOXYGEN_GENERATE_MAN YES)

    doxygen_add_docs(
        doxygen
        ${PROJECT_SOURCE_DIR}
        COMMENT "Generate man pages"
    )

A number of Doxygen config options accept lists of values, but Doxygen requires
them to be separated by whitespace. CMake variables hold lists as a string with
items separated by semi-colons, so a conversion needs to be performed. The
``doxygen_add_docs()`` command specifically checks the following Doxygen config
options and will convert their associated CMake variable's contents into the
required form if set. CMake variables are named ``DOXYGEN_<name>`` for the
Doxygen settings specified here.

::

  ABBREVIATE_BRIEF
  ALIASES
  CITE_BIB_FILES
  DIAFILE_DIRS
  DOTFILE_DIRS
  DOT_FONTPATH
  ENABLED_SECTIONS
  EXAMPLE_PATH
  EXAMPLE_PATTERNS
  EXCLUDE
  EXCLUDE_PATTERNS
  EXCLUDE_SYMBOLS
  EXPAND_AS_DEFINED
  EXTENSION_MAPPING
  EXTRA_PACKAGES
  EXTRA_SEARCH_MAPPINGS
  FILE_PATTERNS
  FILTER_PATTERNS
  FILTER_SOURCE_PATTERNS
  HTML_EXTRA_FILES
  HTML_EXTRA_STYLESHEET
  IGNORE_PREFIX
  IMAGE_PATH
  INCLUDE_FILE_PATTERNS
  INCLUDE_PATH
  INPUT
  LATEX_EXTRA_FILES
  LATEX_EXTRA_STYLESHEET
  MATHJAX_EXTENSIONS
  MSCFILE_DIRS
  PLANTUML_INCLUDE_PATH
  PREDEFINED
  QHP_CUST_FILTER_ATTRS
  QHP_SECT_FILTER_ATTRS
  STRIP_FROM_INC_PATH
  STRIP_FROM_PATH
  TAGFILES
  TCL_SUBST

The following single value Doxygen options will be quoted automatically
if they contain at least one space:

::

  CHM_FILE
  DIA_PATH
  DOCBOOK_OUTPUT
  DOCSET_FEEDNAME
  DOCSET_PUBLISHER_NAME
  DOT_FONTNAME
  DOT_PATH
  EXTERNAL_SEARCH_ID
  FILE_VERSION_FILTER
  GENERATE_TAGFILE
  HHC_LOCATION
  HTML_FOOTER
  HTML_HEADER
  HTML_OUTPUT
  HTML_STYLESHEET
  INPUT_FILTER
  LATEX_FOOTER
  LATEX_HEADER
  LATEX_OUTPUT
  LAYOUT_FILE
  MAN_OUTPUT
  MAN_SUBDIR
  MATHJAX_CODEFILE
  MSCGEN_PATH
  OUTPUT_DIRECTORY
  PERL_PATH
  PLANTUML_JAR_PATH
  PROJECT_BRIEF
  PROJECT_LOGO
  PROJECT_NAME
  QCH_FILE
  QHG_LOCATION
  QHP_CUST_FILTER_NAME
  QHP_VIRTUAL_FOLDER
  RTF_EXTENSIONS_FILE
  RTF_OUTPUT
  RTF_STYLESHEET_FILE
  SEARCHDATA_FILE
  USE_MDFILE_AS_MAINPAGE
  WARN_FORMAT
  WARN_LOGFILE
  XML_OUTPUT

.. versionadded:: 3.11
  There are situations where it may be undesirable for a particular config option
  to be automatically quoted by ``doxygen_add_docs()``, such as ``ALIASES`` which
  may need to include its own embedded quoting.  The ``DOXYGEN_VERBATIM_VARS``
  variable can be used to specify a list of Doxygen variables (including the
  leading ``DOXYGEN_`` prefix) which should not be quoted.  The project is then
  responsible for ensuring that those variables' values make sense when placed
  directly in the Doxygen input file.  In the case of list variables, list items
  are still separated by spaces, it is only the automatic quoting that is
  skipped.  For example, the following allows ``doxygen_add_docs()`` to apply
  quoting to ``DOXYGEN_PROJECT_BRIEF``, but not each item in the
  ``DOXYGEN_ALIASES`` list (:ref:`bracket syntax <Bracket Argument>` can also
  be used to make working with embedded quotes easier):

.. code-block:: cmake

  set(DOXYGEN_PROJECT_BRIEF "String with spaces")
  set(DOXYGEN_ALIASES
      [[somealias="@some_command param"]]
      "anotherAlias=@foobar"
  )
  set(DOXYGEN_VERBATIM_VARS DOXYGEN_ALIASES)

The resultant ``Doxyfile`` will contain the following lines:

.. code-block:: text

  PROJECT_BRIEF = "String with spaces"
  ALIASES       = somealias="@some_command param" anotherAlias=@foobar

Deprecated Result Variables
^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. deprecated:: 3.9

For compatibility with previous versions of CMake, the following variables
are also defined but they are deprecated and should no longer be used:

.. variable:: DOXYGEN_EXECUTABLE

  The path to the ``doxygen`` command. If projects need to refer to the
  ``doxygen`` executable directly, they should use the ``Doxygen::doxygen``
  import target instead.

.. variable:: DOXYGEN_DOT_FOUND

  True if the ``dot`` executable was found.

.. variable:: DOXYGEN_DOT_EXECUTABLE

  The path to the ``dot`` command. If projects need to refer to the ``dot``
  executable directly, they should use the ``Doxygen::dot`` import target
  instead.

.. variable:: DOXYGEN_DOT_PATH

  The path to the directory containing the ``dot`` executable as reported in
  ``DOXYGEN_DOT_EXECUTABLE``. The path may have forward slashes even on Windows
  and is not suitable for direct substitution into a ``Doxyfile.in`` template.
  If you need this value, get the :prop_tgt:`IMPORTED_LOCATION` property of the
  ``Doxygen::dot`` target and use :command:`get_filename_component` to extract
  the directory part of that path. You may also want to consider using
  :command:`file(TO_NATIVE_PATH)` to prepare the path for a Doxygen
  configuration file.

Deprecated Hint Variables
^^^^^^^^^^^^^^^^^^^^^^^^^

.. deprecated:: 3.9

.. variable:: DOXYGEN_SKIP_DOT

  This variable has no effect for the component form of ``find_package``.
  In backward compatibility mode (i.e. without components list) it prevents
  the finder module from searching for Graphviz's ``dot`` utility.

#]=======================================================================]

cmake_policy(PUSH)
cmake_policy(SET CMP0054 NEW) # quoted if arguments
cmake_policy(SET CMP0057 NEW) # if IN_LIST

# For backwards compatibility support
if(Doxygen_FIND_QUIETLY)
    set(DOXYGEN_FIND_QUIETLY TRUE)
endif()

# ===== Rationale for OS X AppBundle mods below =====
#  With the OS X GUI version, Doxygen likes to be installed to /Applications
#  and it contains the doxygen executable in the bundle. In the versions I've
#  seen, it is located in Resources, but in general, more often binaries are
#  located in MacOS.
#
#  NOTE: The official Doxygen.app distributed for OS X uses non-standard
#  conventions. Instead of the command-line "doxygen" tool being placed in
#  Doxygen.app/Contents/MacOS, "Doxywizard" is placed there instead and
#  "doxygen" is placed in Contents/Resources.  This is most likely done
#  so that something happens when people double-click on the Doxygen.app
#  package. Unfortunately, CMake gets confused by this as when it sees the
#  bundle it uses "Doxywizard" as the executable to use instead of
#  "doxygen". Therefore to work-around this issue we temporarily disable
#  the app-bundle feature, just for this CMake module:
#
if(APPLE)
    # Save the old setting
    set(TEMP_DOXYGEN_SAVE_CMAKE_FIND_APPBUNDLE ${CMAKE_FIND_APPBUNDLE})
    # Disable the App-bundle detection feature
    set(CMAKE_FIND_APPBUNDLE "NEVER")
endif()
# FYI:
# In older versions of OS X Doxygen, dot was included with the Doxygen bundle,
# but newer versions require you to download Graphviz.app which contains "dot"
# or use something like homebrew.
# ============== End OSX stuff ================

include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)

#
# Find Doxygen...
#
function(_Doxygen_get_version doxy_version result_var doxy_path)
        execute_process(
            COMMAND "${doxy_path}" --version
            OUTPUT_VARIABLE full_doxygen_version
            OUTPUT_STRIP_TRAILING_WHITESPACE
            RESULT_VARIABLE version_result
        )

        # Ignore any commit hashes, etc.
        string(REGEX MATCH [[^[0-9]+\.[0-9]+\.[0-9]+]] sem_doxygen_version "${full_doxygen_version}")

        set(${result_var} ${version_result} PARENT_SCOPE)
        set(${doxy_version} ${sem_doxygen_version} PARENT_SCOPE)
endfunction()

function(_Doxygen_version_validator version_match doxy_path)
    if(NOT DEFINED Doxygen_FIND_VERSION)
        set(${is_valid_version} TRUE PARENT_SCOPE)
    else()
        _Doxygen_get_version(candidate_version version_result "${doxy_path}")

        find_package_check_version("${candidate_version}" valid_doxy_version
            HANDLE_VERSION_RANGE
        )

        set(${version_match} "${valid_doxy_version}" PARENT_SCOPE)
    endif()
endfunction()

macro(_Doxygen_find_doxygen)
    find_program(
        DOXYGEN_EXECUTABLE
        NAMES doxygen
        PATHS
            "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\doxygen_is1;Inno Setup: App Path]/bin"
            /Applications/Doxygen.app/Contents/Resources
            /Applications/Doxygen.app/Contents/MacOS
            /Applications/Utilities/Doxygen.app/Contents/Resources
            /Applications/Utilities/Doxygen.app/Contents/MacOS
        DOC "Doxygen documentation generation tool (https://www.doxygen.nl)"
        VALIDATOR _Doxygen_version_validator
    )
    mark_as_advanced(DOXYGEN_EXECUTABLE)

    if(DOXYGEN_EXECUTABLE)
        _Doxygen_get_version(DOXYGEN_VERSION _Doxygen_version_result "${DOXYGEN_EXECUTABLE}")

        if(_Doxygen_version_result)
            if(NOT Doxygen_FIND_QUIETLY)
                message(WARNING "Doxygen executable failed unexpected while determining version (exit status: ${_Doxygen_version_result}). Disabling Doxygen.")
            endif()
            set(DOXYGEN_EXECUTABLE "${DOXYGEN_EXECUTABLE}-FAILED_EXECUTION-NOTFOUND")
        else()
            # Create an imported target for Doxygen
            if(NOT TARGET Doxygen::doxygen)
                add_executable(Doxygen::doxygen IMPORTED GLOBAL)
                set_target_properties(Doxygen::doxygen PROPERTIES
                    IMPORTED_LOCATION "${DOXYGEN_EXECUTABLE}"
                )
            endif()
        endif()
    endif()
endmacro()

#
# Find Diagram Editor...
#
macro(_Doxygen_find_dia)
    set(_x86 "(x86)")
    find_program(
        DOXYGEN_DIA_EXECUTABLE
        NAMES dia
        PATHS
            "$ENV{ProgramFiles}/Dia"
            "$ENV{ProgramFiles${_x86}}/Dia"
        DOC "Diagram Editor tool for use with Doxygen"
    )
    mark_as_advanced(DOXYGEN_DIA_EXECUTABLE)

    if(DOXYGEN_DIA_EXECUTABLE)
        # The Doxyfile wants the path to the utility, not the entire path
        # including file name
        get_filename_component(DOXYGEN_DIA_PATH
                              "${DOXYGEN_DIA_EXECUTABLE}"
                              DIRECTORY)
        if(WIN32)
            file(TO_NATIVE_PATH "${DOXYGEN_DIA_PATH}" DOXYGEN_DIA_PATH)
        endif()

        # Create an imported target for component
        if(NOT TARGET Doxygen::dia)
            add_executable(Doxygen::dia IMPORTED GLOBAL)
            set_target_properties(Doxygen::dia PROPERTIES
                IMPORTED_LOCATION "${DOXYGEN_DIA_EXECUTABLE}"
            )
        endif()
    endif()

    unset(_x86)
endmacro()

#
# Find Graphviz Dot...
#
macro(_Doxygen_find_dot)
    if(WIN32)
        set(_x86 "(x86)")
        file(
            GLOB _Doxygen_GRAPHVIZ_BIN_DIRS
            "$ENV{ProgramFiles}/Graphviz*/bin"
            "$ENV{ProgramFiles${_x86}}/Graphviz*/bin"
        )
        unset(_x86)
    else()
        set(_Doxygen_GRAPHVIZ_BIN_DIRS "")
    endif()

    find_program(
        DOXYGEN_DOT_EXECUTABLE
        NAMES dot
        PATHS
            ${_Doxygen_GRAPHVIZ_BIN_DIRS}
            "$ENV{ProgramFiles}/ATT/Graphviz/bin"
            "C:/Program Files/ATT/Graphviz/bin"
            [HKEY_LOCAL_MACHINE\\SOFTWARE\\ATT\\Graphviz;InstallPath]/bin
            /Applications/Graphviz.app/Contents/MacOS
            /Applications/Utilities/Graphviz.app/Contents/MacOS
            /Applications/Doxygen.app/Contents/Resources
            /Applications/Doxygen.app/Contents/MacOS
            /Applications/Utilities/Doxygen.app/Contents/Resources
            /Applications/Utilities/Doxygen.app/Contents/MacOS
        DOC "Dot tool for use with Doxygen"
    )
    mark_as_advanced(DOXYGEN_DOT_EXECUTABLE)

    if(DOXYGEN_DOT_EXECUTABLE)
        # The Doxyfile wants the path to the utility, not the entire path
        # including file name
        get_filename_component(DOXYGEN_DOT_PATH
                               "${DOXYGEN_DOT_EXECUTABLE}"
                               DIRECTORY)
        if(WIN32)
            file(TO_NATIVE_PATH "${DOXYGEN_DOT_PATH}" DOXYGEN_DOT_PATH)
        endif()

        # Create an imported target for component
        if(NOT TARGET Doxygen::dot)
            add_executable(Doxygen::dot IMPORTED GLOBAL)
            set_target_properties(Doxygen::dot PROPERTIES
                IMPORTED_LOCATION "${DOXYGEN_DOT_EXECUTABLE}"
            )
        endif()
    endif()

    unset(_Doxygen_GRAPHVIZ_BIN_DIRS)
endmacro()

#
# Find Message Sequence Chart...
#
macro(_Doxygen_find_mscgen)
    set(_x86 "(x86)")
    find_program(
        DOXYGEN_MSCGEN_EXECUTABLE
        NAMES mscgen
        PATHS
            "$ENV{ProgramFiles}/Mscgen"
            "$ENV{ProgramFiles${_x86}}/Mscgen"
        DOC "Message sequence chart tool for use with Doxygen"
    )
    mark_as_advanced(DOXYGEN_MSCGEN_EXECUTABLE)

    if(DOXYGEN_MSCGEN_EXECUTABLE)
        # The Doxyfile wants the path to the utility, not the entire path
        # including file name
        get_filename_component(DOXYGEN_MSCGEN_PATH
                               "${DOXYGEN_MSCGEN_EXECUTABLE}"
                               DIRECTORY)
        if(WIN32)
            file(TO_NATIVE_PATH "${DOXYGEN_MSCGEN_PATH}" DOXYGEN_MSCGEN_PATH)
        endif()

        # Create an imported target for component
        if(NOT TARGET Doxygen::mscgen)
            add_executable(Doxygen::mscgen IMPORTED GLOBAL)
            set_target_properties(Doxygen::mscgen PROPERTIES
                IMPORTED_LOCATION "${DOXYGEN_MSCGEN_EXECUTABLE}"
            )
        endif()
    endif()

    unset(_x86)
endmacro()

# Make sure `doxygen` is one of the components to find
set(_Doxygen_keep_backward_compat FALSE)
if(NOT Doxygen_FIND_COMPONENTS)
    # Search at least for `doxygen` executable
    set(Doxygen_FIND_COMPONENTS doxygen)
    # Preserve backward compatibility:
    # search for `dot` also if `DOXYGEN_SKIP_DOT` is not explicitly disable this.
    if(NOT DOXYGEN_SKIP_DOT)
        list(APPEND Doxygen_FIND_COMPONENTS dot)
    endif()
    set(_Doxygen_keep_backward_compat TRUE)
elseif(NOT doxygen IN_LIST Doxygen_FIND_COMPONENTS)
    list(INSERT Doxygen_FIND_COMPONENTS 0 doxygen)
endif()

#
# Find all requested components of Doxygen...
#
foreach(_comp IN LISTS Doxygen_FIND_COMPONENTS)
    if(_comp STREQUAL "doxygen")
        _Doxygen_find_doxygen()
    elseif(_comp STREQUAL "dia")
        _Doxygen_find_dia()
    elseif(_comp STREQUAL "dot")
        _Doxygen_find_dot()
    elseif(_comp STREQUAL "mscgen")
        _Doxygen_find_mscgen()
    else()
        message(WARNING "${_comp} is not a valid Doxygen component")
        set(Doxygen_${_comp}_FOUND FALSE)
        continue()
    endif()

    if(TARGET Doxygen::${_comp})
        set(Doxygen_${_comp}_FOUND TRUE)
    else()
        set(Doxygen_${_comp}_FOUND FALSE)
    endif()
endforeach()
unset(_comp)

# Verify find results
find_package_handle_standard_args(
    Doxygen
    REQUIRED_VARS DOXYGEN_EXECUTABLE
    VERSION_VAR DOXYGEN_VERSION
    HANDLE_VERSION_RANGE
    HANDLE_COMPONENTS
)

#
# Backwards compatibility...
#
if(APPLE)
    # Restore the old app-bundle setting
    set(CMAKE_FIND_APPBUNDLE ${TEMP_DOXYGEN_SAVE_CMAKE_FIND_APPBUNDLE})
endif()

# Maintain the _FOUND variables as "YES" or "NO" for backwards
# compatibility. This allows people to substitute them directly into
# Doxyfile with configure_file().
if(DOXYGEN_FOUND)
    set(DOXYGEN_FOUND "YES")
else()
    set(DOXYGEN_FOUND "NO")
endif()
if(_Doxygen_keep_backward_compat)
    if(Doxygen_dot_FOUND)
        set(DOXYGEN_DOT_FOUND "YES")
    else()
        set(DOXYGEN_DOT_FOUND "NO")
    endif()

    # For backwards compatibility support for even older CMake versions
    set(DOXYGEN ${DOXYGEN_EXECUTABLE})
    set(DOT ${DOXYGEN_DOT_EXECUTABLE})

    # No need to keep any backward compatibility for `DOXYGEN_MSCGEN_XXX`
    # and `DOXYGEN_DIA_XXX` since they were not supported before component
    # support was added
endif()
unset(_Doxygen_keep_backward_compat)

#
# Allow full control of Doxygen from CMakeLists.txt
#

# Prepare a template Doxyfile and Doxygen's default values CMake file
if(TARGET Doxygen::doxygen)
    # If doxygen was found, use it to generate a minimal default Doxyfile.
    # We will delete this file after we have finished using it below to
    # generate the other files that doxygen_add_docs() will use.
    set(_Doxygen_tpl "${CMAKE_BINARY_DIR}/CMakeDoxyfile.tpl")
    execute_process(
        COMMAND "${DOXYGEN_EXECUTABLE}" -s -g "${_Doxygen_tpl}"
        OUTPUT_QUIET
        RESULT_VARIABLE _Doxygen_tpl_result
    )
    if(_Doxygen_tpl_result)
        message(FATAL_ERROR
                "Unable to generate Doxyfile template: ${_Doxygen_tpl_result}")
    elseif(NOT EXISTS "${_Doxygen_tpl}")
        message(FATAL_ERROR
                "Doxygen has failed to generate a Doxyfile template")
    endif()

    # Write a do-not-edit header to files we are going to generate...
    set(_Doxygen_dne_header
[[
#
# DO NOT EDIT! THIS FILE WAS GENERATED BY CMAKE!
#

]]
    )
    # We only need one copy of these across the whole build, since their
    # content is only dependent on the version of Doxygen being used. Therefore
    # we always put them at the top of the build tree so that they are in a
    # predictable location.
    set(_doxyfile_in       "${CMAKE_BINARY_DIR}/CMakeDoxyfile.in")
    set(_doxyfile_defaults "${CMAKE_BINARY_DIR}/CMakeDoxygenDefaults.cmake")

    set(_doxyfile_in_contents "")
    set(_doxyfile_defaults_contents "")

    # Get strings containing a configuration key from the template Doxyfile
    # we obtained from this version of Doxygen. Because some options are split
    # across multiple lines by ending lines with backslashes, we cannot just
    # use file(STRINGS...) with a REGEX. Instead, read lines without a REGEX
    # so that file(STRINGS...) handles the trailing backslash as a line
    # continuation. It stores multi-lines as lists, so we then have to replace
    # the ";" list separator with backslashed newlines again so that we get the
    # original content stored back as the value part.
    file(STRINGS "${_Doxygen_tpl}" _file_lines)
    unset(_Doxygen_tpl_params)
    foreach(_line IN LISTS _file_lines)
        if(_line MATCHES "([A-Z][A-Z0-9_]+)( *=)(.*)")
            set(_key "${CMAKE_MATCH_1}")
            set(_eql "${CMAKE_MATCH_2}")
            set(_value "${CMAKE_MATCH_3}")
            string(REPLACE "\\" "\\\\" _value "${_value}")
            string(REPLACE ";" "\\\n" _value "${_value}")
            list(APPEND _Doxygen_tpl_params "${_key}${_eql}${_value}")
        endif()
    endforeach()

    # Build up a Doxyfile that provides @configVar@ substitutions for each
    # Doxygen config option as well as a separate CMake script which provides
    # the default value for each of those options if the project doesn't supply
    # them. Each config option will support substitution of a CMake variable
    # of the same name except with DOXYGEN_ prepended.
    foreach(_Doxygen_param IN LISTS _Doxygen_tpl_params)
        if(_Doxygen_param MATCHES "([A-Z][A-Z0-9_]+)( *)=( (.*))?")
            # Ok, this is a config key with a value
            if(CMAKE_MATCH_COUNT EQUAL 4)
                string(APPEND _doxyfile_in_contents
                       "${CMAKE_MATCH_1}${CMAKE_MATCH_2}= @DOXYGEN_${CMAKE_MATCH_1}@\n")
                # Remove the backslashes we had to preserve to handle newlines
                string(REPLACE "\\\n" "\n" _value "${CMAKE_MATCH_4}")
                string(APPEND _doxyfile_defaults_contents
"if(NOT DEFINED DOXYGEN_${CMAKE_MATCH_1})
    set(DOXYGEN_${CMAKE_MATCH_1} ${_value})
endif()
")
            # Ok, this is a config key with empty default value
            elseif(CMAKE_MATCH_COUNT EQUAL 2)
                string(APPEND _doxyfile_in_contents
                       "${CMAKE_MATCH_1}${CMAKE_MATCH_2}= @DOXYGEN_${CMAKE_MATCH_1}@\n")
            else()
                message(AUTHOR_WARNING
"Unexpected line format! Code review required!\nFault line: ${_Doxygen_param}")
            endif()
        else()
            message(AUTHOR_WARNING
"Unexpected line format! Code review required!\nFault line: ${_Doxygen_param}")
        endif()
    endforeach()
    file(WRITE "${_doxyfile_defaults}" "${_Doxygen_dne_header}"
                                       "${_doxyfile_defaults_contents}")
    file(WRITE "${_doxyfile_in}"       "${_Doxygen_dne_header}"
                                       "${_doxyfile_in_contents}")

    # Ok, dumped defaults are not needed anymore...
    file(REMOVE "${_Doxygen_tpl}")

    unset(_Doxygen_param)
    unset(_Doxygen_tpl_params)
    unset(_Doxygen_dne_header)
    unset(_Doxygen_tpl)

endif()

function(doxygen_quote_value VARIABLE)
    # Quote a value of the given variable if:
    # - VARIABLE parameter was really given
    # - the variable it names is defined and is not present in the list
    #   specified by DOXYGEN_VERBATIM_VARS (if set)
    # - the value of the named variable isn't already quoted
    # - the value has spaces
    if(VARIABLE AND DEFINED ${VARIABLE} AND
       NOT ${VARIABLE} MATCHES "^\".* .*\"$" AND ${VARIABLE} MATCHES " " AND
       NOT (DEFINED DOXYGEN_VERBATIM_VARS AND
            "${VARIABLE}" IN_LIST DOXYGEN_VERBATIM_VARS))
        set(${VARIABLE} "\"${${VARIABLE}}\"" PARENT_SCOPE)
    endif()
endfunction()

function(doxygen_list_to_quoted_strings LIST_VARIABLE)
    if(LIST_VARIABLE AND DEFINED ${LIST_VARIABLE})
        unset(_inputs)
        unset(_sep)
        unset(_verbatim)
        # Have to test if list items should be treated as verbatim here
        # because we lose the variable name when we pass just one list item
        # to doxygen_quote_value() below
        if(DEFINED DOXYGEN_VERBATIM_VARS AND
           "${LIST_VARIABLE}" IN_LIST DOXYGEN_VERBATIM_VARS)
            set(_verbatim True)
        endif()
        foreach(_in IN LISTS ${LIST_VARIABLE})
            if(NOT _verbatim)
                doxygen_quote_value(_in)
            endif()
            string(APPEND _inputs "${_sep}${_in}")
            set(_sep " ")
        endforeach()
        set(${LIST_VARIABLE} "${_inputs}" PARENT_SCOPE)
    endif()
endfunction()

function(doxygen_add_docs targetName)
    set(_options ALL USE_STAMP_FILE)
    set(_one_value_args WORKING_DIRECTORY COMMENT CONFIG_FILE)
    set(_multi_value_args)
    cmake_parse_arguments(_args
                          "${_options}"
                          "${_one_value_args}"
                          "${_multi_value_args}"
                          ${ARGN})

    if(NOT _args_COMMENT)
        set(_args_COMMENT "Generate API documentation for ${targetName}")
    endif()

    if(NOT _args_WORKING_DIRECTORY)
        set(_args_WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
    endif()

    if(DEFINED DOXYGEN_INPUT)
        message(WARNING
"DOXYGEN_INPUT is set but it will be ignored. Pass the files and directories \
directly to the doxygen_add_docs() command instead.")
    endif()
    set(DOXYGEN_INPUT ${_args_UNPARSED_ARGUMENTS})

    if(NOT TARGET Doxygen::doxygen)
        message(FATAL_ERROR "Doxygen was not found, needed by \
doxygen_add_docs() for target ${targetName}")
    endif()

    # If not already defined, set some relevant defaults based on the
    # assumption that the documentation is for the whole project. Details
    # specified in the project() command will be used to populate a number of
    # these defaults.

    if(NOT DEFINED DOXYGEN_PROJECT_NAME)
        # The PROJECT_NAME tag is a single word (or a sequence of words
        # surrounded by double-quotes, unless you are using Doxywizard) that
        # should identify the project for which the documentation is generated.
        # This name is used in the title of most generated pages and in a few
        # other places. The default value is: My Project.
        set(DOXYGEN_PROJECT_NAME ${PROJECT_NAME})
    endif()

    if(NOT DEFINED DOXYGEN_PROJECT_NUMBER)
        # The PROJECT_NUMBER tag can be used to enter a project or revision
        # number. This could be handy for archiving the generated documentation
        # or if some version control system is used.
        set(DOXYGEN_PROJECT_NUMBER ${PROJECT_VERSION})
    endif()

    if(NOT DEFINED DOXYGEN_PROJECT_BRIEF)
        # Using the PROJECT_BRIEF tag one can provide an optional one line
        # description for a project that appears at the top of each page and
        # should give viewer a quick idea about the purpose of the project.
        # Keep the description short.
        set(DOXYGEN_PROJECT_BRIEF "${PROJECT_DESCRIPTION}")
    endif()

    if(NOT DEFINED DOXYGEN_RECURSIVE)
        # The RECURSIVE tag can be used to specify whether or not
        # subdirectories should be searched for input files as well. CMake
        # projects generally evolve to span multiple directories, so it makes
        # more sense for this to be on by default. Doxygen's default value
        # has this setting turned off, so we override it.
        set(DOXYGEN_RECURSIVE YES)
    endif()

    if(NOT DEFINED DOXYGEN_OUTPUT_DIRECTORY)
        # The OUTPUT_DIRECTORY tag is used to specify the (relative or
        # absolute) path into which the generated documentation will be
        # written. If a relative path is used, Doxygen will interpret it as
        # being relative to the location where doxygen was started, but we need
        # to run Doxygen in the source tree so that relative input paths work
        # intuitively. Therefore, we ensure that the output directory is always
        # an absolute path and if the project provided a relative path, we
        # treat it as relative to the current BINARY directory so that output
        # is not generated inside the source tree.
        set(DOXYGEN_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}")
    elseif(NOT IS_ABSOLUTE "${DOXYGEN_OUTPUT_DIRECTORY}")
        get_filename_component(DOXYGEN_OUTPUT_DIRECTORY
                               "${DOXYGEN_OUTPUT_DIRECTORY}"
                               ABSOLUTE
                               BASE_DIR "${CMAKE_CURRENT_BINARY_DIR}")
    endif()

    if(NOT DEFINED DOXYGEN_HAVE_DOT)
        # If you set the HAVE_DOT tag to YES then doxygen will assume the dot
        # tool is available from the path. This tool is part of Graphviz (see:
        # https://www.graphviz.org/), a graph visualization toolkit from AT&T
        # and Lucent Bell Labs. The other options in this section have no
        # effect if this option is set to NO.
        # Doxygen's default value is: NO.
        if(Doxygen_dot_FOUND)
          set(DOXYGEN_HAVE_DOT "YES")
        else()
          set(DOXYGEN_HAVE_DOT "NO")
        endif()
    endif()

    if(NOT DEFINED DOXYGEN_DOT_MULTI_TARGETS)
        # Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate
        # multiple output files in one run (i.e. multiple -o and -T options on
        # the command line). This makes dot run faster, but since only newer
        # versions of dot (>1.8.10) support this, Doxygen disables this feature
        # by default.
        # This tag requires that the tag HAVE_DOT is set to YES.
        set(DOXYGEN_DOT_MULTI_TARGETS YES)
    endif()

    if(NOT DEFINED DOXYGEN_GENERATE_LATEX)
        # If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX
        # output. We only want the HTML output enabled by default, so we turn
        # this off if the project hasn't specified it.
        set(DOXYGEN_GENERATE_LATEX NO)
    endif()

    if(NOT DEFINED DOXYGEN_WARN_FORMAT)
        if(CMAKE_VS_MSBUILD_COMMAND OR CMAKE_VS_DEVENV_COMMAND)
            # The WARN_FORMAT tag determines the format of the warning messages
            # that doxygen can produce. The string should contain the $file,
            # $line and $text tags, which will be replaced by the file and line
            # number from which the warning originated and the warning text.
            # Optionally, the format may contain $version, which will be
            # replaced by the version of the file (if it could be obtained via
            # FILE_VERSION_FILTER).
            # Doxygen's default value is: $file:$line: $text
            set(DOXYGEN_WARN_FORMAT "$file($line) : $text ")
        endif()
    endif()

    if(DEFINED DOXYGEN_WARN_LOGFILE AND NOT IS_ABSOLUTE "${DOXYGEN_WARN_LOGFILE}")
        # The WARN_LOGFILE tag can be used to specify a file to which warning and error
        # messages should be written. If left blank the output is written to standard
        # error (stderr).
        get_filename_component(DOXYGEN_WARN_LOGFILE
                               "${DOXYGEN_WARN_LOGFILE}"
                               ABSOLUTE
                               BASE_DIR "${CMAKE_CURRENT_BINARY_DIR}")
    endif()

    # Any files from the INPUT that match any of the EXCLUDE_PATTERNS will be
    # excluded from the set of input files. We provide some additional patterns
    # to prevent commonly unwanted things from CMake builds being pulled in.
    #
    # Note that the wildcards are matched against the file with absolute path,
    # so to exclude all test directories for example use the pattern */test/*
    list(
        APPEND
        DOXYGEN_EXCLUDE_PATTERNS
        "*/.git/*"
        "*/.svn/*"
        "*/.hg/*"
        "*/CMakeFiles/*"
        "*/_CPack_Packages/*"
        "DartConfiguration.tcl"
        "CMakeLists.txt"
        "CMakeCache.txt"
    )

    # Now bring in Doxgen's defaults for those things the project has not
    # already set and we have not provided above
    include("${CMAKE_BINARY_DIR}/CMakeDoxygenDefaults.cmake" OPTIONAL)

    # Cleanup built HTMLs on "make clean"
    # TODO Any other dirs?
    if(DOXYGEN_GENERATE_HTML)
        if(IS_ABSOLUTE "${DOXYGEN_HTML_OUTPUT}")
            set(_args_clean_html_dir "${DOXYGEN_HTML_OUTPUT}")
        else()
            set(_args_clean_html_dir
                "${DOXYGEN_OUTPUT_DIRECTORY}/${DOXYGEN_HTML_OUTPUT}")
        endif()
        set_property(DIRECTORY APPEND PROPERTY
            ADDITIONAL_CLEAN_FILES "${_args_clean_html_dir}")
    endif()

    # Build up a list of files we can identify from the inputs so we can list
    # them as DEPENDS and SOURCES in the custom command/target (the latter
    # makes them display in IDEs). This must be done before we transform the
    # various DOXYGEN_... variables below because we need to process
    # DOXYGEN_INPUT as a list first.
    unset(_sources)
    foreach(_item IN LISTS DOXYGEN_INPUT)
        get_filename_component(_abs_item "${_item}" ABSOLUTE
                               BASE_DIR "${_args_WORKING_DIRECTORY}")
        get_source_file_property(_isGenerated "${_abs_item}" GENERATED)
        if(_isGenerated OR
           (EXISTS "${_abs_item}" AND
            NOT IS_DIRECTORY "${_abs_item}" AND
            NOT IS_SYMLINK "${_abs_item}"))
            list(APPEND _sources "${_abs_item}")
        elseif(_args_USE_STAMP_FILE)
            message(FATAL_ERROR "Source does not exist or is not a file:\n"
                "    ${_abs_item}\n"
                "Only existing files may be specified when the "
                "USE_STAMP_FILE option is given.")
        endif()
    endforeach()

    # Transform known list type options into space separated strings.
    set(_doxygen_list_options
        ABBREVIATE_BRIEF
        ALIASES
        CITE_BIB_FILES
        DIAFILE_DIRS
        DOTFILE_DIRS
        DOT_FONTPATH
        ENABLED_SECTIONS
        EXAMPLE_PATH
        EXAMPLE_PATTERNS
        EXCLUDE
        EXCLUDE_PATTERNS
        EXCLUDE_SYMBOLS
        EXPAND_AS_DEFINED
        EXTENSION_MAPPING
        EXTRA_PACKAGES
        EXTRA_SEARCH_MAPPINGS
        FILE_PATTERNS
        FILTER_PATTERNS
        FILTER_SOURCE_PATTERNS
        HTML_EXTRA_FILES
        HTML_EXTRA_STYLESHEET
        IGNORE_PREFIX
        IMAGE_PATH
        INCLUDE_FILE_PATTERNS
        INCLUDE_PATH
        INPUT
        LATEX_EXTRA_FILES
        LATEX_EXTRA_STYLESHEET
        MATHJAX_EXTENSIONS
        MSCFILE_DIRS
        PLANTUML_INCLUDE_PATH
        PREDEFINED
        QHP_CUST_FILTER_ATTRS
        QHP_SECT_FILTER_ATTRS
        STRIP_FROM_INC_PATH
        STRIP_FROM_PATH
        TAGFILES
        TCL_SUBST
    )
    foreach(_item IN LISTS _doxygen_list_options)
        doxygen_list_to_quoted_strings(DOXYGEN_${_item})
    endforeach()

    # Transform known single value variables which may contain spaces, such as
    # paths or description strings.
    set(_doxygen_quoted_options
        CHM_FILE
        DIA_PATH
        DOCBOOK_OUTPUT
        DOCSET_FEEDNAME
        DOCSET_PUBLISHER_NAME
        DOT_FONTNAME
        DOT_PATH
        EXTERNAL_SEARCH_ID
        FILE_VERSION_FILTER
        GENERATE_TAGFILE
        HHC_LOCATION
        HTML_FOOTER
        HTML_HEADER
        HTML_OUTPUT
        HTML_STYLESHEET
        INPUT_FILTER
        LATEX_FOOTER
        LATEX_HEADER
        LATEX_OUTPUT
        LAYOUT_FILE
        MAN_OUTPUT
        MAN_SUBDIR
        MATHJAX_CODEFILE
        MSCGEN_PATH
        OUTPUT_DIRECTORY
        PERL_PATH
        PLANTUML_JAR_PATH
        PROJECT_BRIEF
        PROJECT_LOGO
        PROJECT_NAME
        QCH_FILE
        QHG_LOCATION
        QHP_CUST_FILTER_NAME
        QHP_VIRTUAL_FOLDER
        RTF_EXTENSIONS_FILE
        RTF_OUTPUT
        RTF_STYLESHEET_FILE
        SEARCHDATA_FILE
        USE_MDFILE_AS_MAINPAGE
        WARN_FORMAT
        WARN_LOGFILE
        XML_OUTPUT
    )

    # Store the unmodified value of DOXYGEN_OUTPUT_DIRECTORY prior to invoking
    # doxygen_quote_value() below. This will mutate the string specifically for
    # consumption by Doxygen's config file, which we do not want when we use it
    # later in the custom target's commands.
    set( _original_doxygen_output_dir ${DOXYGEN_OUTPUT_DIRECTORY} )

    foreach(_item IN LISTS _doxygen_quoted_options)
        doxygen_quote_value(DOXYGEN_${_item})
    endforeach()

    # Prepare doxygen configuration file
    set(_doxyfile_template "${CMAKE_BINARY_DIR}/CMakeDoxyfile.in")
    if(_args_CONFIG_FILE)
        if(NOT EXISTS "${_args_CONFIG_FILE}")
            message(FATAL_ERROR "Option CONFIG_FILE specifies file:\n ${_args_CONFIG_FILE}\nbut it does not exist.")
        endif()
        set(_target_doxyfile "${_args_CONFIG_FILE}")
    else()
        set(_target_doxyfile "${CMAKE_CURRENT_BINARY_DIR}/Doxyfile.${targetName}")
        configure_file("${_doxyfile_template}" "${_target_doxyfile}")
    endif()

    unset(_all)
    if(${_args_ALL})
        set(_all ALL)
    endif()

    # Only create the stamp file if asked to. If we don't create it,
    # the target will always be considered out-of-date.
    if(_args_USE_STAMP_FILE)
        set(__stamp_file "${CMAKE_CURRENT_BINARY_DIR}/${targetName}.stamp")
        add_custom_command(
            VERBATIM
            OUTPUT ${__stamp_file}
            COMMAND ${CMAKE_COMMAND} -E make_directory ${_original_doxygen_output_dir}
            COMMAND "${DOXYGEN_EXECUTABLE}" "${_target_doxyfile}"
            COMMAND ${CMAKE_COMMAND} -E touch ${__stamp_file}
            WORKING_DIRECTORY "${_args_WORKING_DIRECTORY}"
            DEPENDS "${_target_doxyfile}" ${_sources}
            COMMENT "${_args_COMMENT}"
        )
        add_custom_target(${targetName} ${_all}
            DEPENDS ${__stamp_file}
            SOURCES ${_sources}
        )
        unset(__stamp_file)
    else()
        add_custom_target( ${targetName} ${_all} VERBATIM
            COMMAND ${CMAKE_COMMAND} -E make_directory ${_original_doxygen_output_dir}
            COMMAND "${DOXYGEN_EXECUTABLE}" "${_target_doxyfile}"
            WORKING_DIRECTORY "${_args_WORKING_DIRECTORY}"
            DEPENDS "${_target_doxyfile}" ${_sources}
            COMMENT "${_args_COMMENT}"
            SOURCES ${_sources}
        )
    endif()

endfunction()

cmake_policy(POP)


code:
# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

#[=======================================================================[.rst:
FindEXPAT
---------

Find the native Expat headers and library.
Expat is a stream-oriented XML parser library written in C.

Imported Targets
^^^^^^^^^^^^^^^^

.. versionadded:: 3.10

This module defines the following :prop_tgt:`IMPORTED` targets:

``EXPAT::EXPAT``
  The Expat ``expat`` library, if found.

Result Variables
^^^^^^^^^^^^^^^^

This module will set the following variables in your project:

``EXPAT_INCLUDE_DIRS``
  where to find expat.h, etc.
``EXPAT_LIBRARIES``
  the libraries to link against to use Expat.
``EXPAT_FOUND``
  true if the Expat headers and libraries were found.

Hints
^^^^^

``EXPAT_USE_STATIC_LIBS``

  .. versionadded:: 3.28

  Set to ``TRUE`` to use static libraries.

#]=======================================================================]

find_package(PkgConfig QUIET)

pkg_check_modules(PC_EXPAT QUIET expat)

# Look for the header file.
find_path(EXPAT_INCLUDE_DIR NAMES expat.h HINTS ${PC_EXPAT_INCLUDE_DIRS})

set(EXPAT_NAMES expat expatw)
set(EXPAT_NAMES_DEBUG expatd expatwd)

if(WIN32)
  if(EXPAT_USE_STATIC_LIBS)
    list(APPEND EXPAT_NAMES expatMT expatwMT)
    list(APPEND EXPAT_NAMES_DEBUG expatdMT expatwdMT)
  else()
    list(APPEND EXPAT_NAMES expatMT expatMD expatwMT expatwMD)
    list(APPEND EXPAT_NAMES_DEBUG expatdMT expatdMD expatwdMT expatwdMD)
  endif()
endif()

# Allow EXPAT_LIBRARY to be set manually, as the location of the expat library
if(NOT EXPAT_LIBRARY)
  if(DEFINED CMAKE_FIND_LIBRARY_PREFIXES)
    set(_expat_ORIG_CMAKE_FIND_LIBRARY_PREFIXES "${CMAKE_FIND_LIBRARY_PREFIXES}")
  else()
    set(_expat_ORIG_CMAKE_FIND_LIBRARY_PREFIXES)
  endif()

  if(WIN32)
    list(APPEND CMAKE_FIND_LIBRARY_PREFIXES "" "lib")
  endif()

  # Look for the library.
  find_library(EXPAT_LIBRARY_RELEASE NAMES ${EXPAT_NAMES} NAMES_PER_DIR HINTS ${PC_EXPAT_LIBRARY_DIRS} PATH_SUFFIXES lib)
  find_library(EXPAT_LIBRARY_DEBUG NAMES ${EXPAT_NAMES_DEBUG} NAMES_PER_DIR HINTS ${PC_EXPAT_LIBRARY_DIRS} PATH_SUFFIXES lib)

  # Restore the original find library ordering
  if(DEFINED _expat_ORIG_CMAKE_FIND_LIBRARY_PREFIXES)
    set(CMAKE_FIND_LIBRARY_PREFIXES "${_expat_ORIG_CMAKE_FIND_LIBRARY_PREFIXES}")
  else()
    set(CMAKE_FIND_LIBRARY_PREFIXES)
  endif()

  include(${CMAKE_CURRENT_LIST_DIR}/SelectLibraryConfigurations.cmake)
  select_library_configurations(EXPAT)
endif()

unset(EXPAT_NAMES)
unset(EXPAT_NAMES_DEBUG)

if(EXPAT_INCLUDE_DIR AND EXISTS "${EXPAT_INCLUDE_DIR}/expat.h")
  file(STRINGS "${EXPAT_INCLUDE_DIR}/expat.h" expat_version_str
    REGEX "^#[\t ]*define[\t ]+XML_(MAJOR|MINOR|MICRO)_VERSION[\t ]+[0-9]+$")

  unset(EXPAT_VERSION_STRING)
  foreach(VPART MAJOR MINOR MICRO)
    foreach(VLINE ${expat_version_str})
      if(VLINE MATCHES "^#[\t ]*define[\t ]+XML_${VPART}_VERSION[\t ]+([0-9]+)$")
        set(EXPAT_VERSION_PART "${CMAKE_MATCH_1}")
        if(EXPAT_VERSION_STRING)
          string(APPEND EXPAT_VERSION_STRING ".${EXPAT_VERSION_PART}")
        else()
          set(EXPAT_VERSION_STRING "${EXPAT_VERSION_PART}")
        endif()
      endif()
    endforeach()
  endforeach()
endif()

include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(EXPAT
                                  REQUIRED_VARS EXPAT_LIBRARY EXPAT_INCLUDE_DIR
                                  VERSION_VAR EXPAT_VERSION_STRING)

# Copy the results to the output variables and target.
if(EXPAT_FOUND)
  set(EXPAT_INCLUDE_DIRS ${EXPAT_INCLUDE_DIR})

  if(NOT EXPAT_LIBRARIES)
    set(EXPAT_LIBRARIES ${EXPAT_LIBRARY})
  endif()

  if(NOT TARGET EXPAT::EXPAT)
    add_library(EXPAT::EXPAT UNKNOWN IMPORTED)
    set_target_properties(EXPAT::EXPAT PROPERTIES
      IMPORTED_LINK_INTERFACE_LANGUAGES "C"
      INTERFACE_INCLUDE_DIRECTORIES "${EXPAT_INCLUDE_DIRS}")

    if(EXPAT_USE_STATIC_LIBS)
      set_property(TARGET EXPAT::EXPAT APPEND PROPERTY
                   INTERFACE_COMPILE_DEFINITIONS "XML_STATIC")
    endif()

    if(EXPAT_LIBRARY_RELEASE)
      set_property(TARGET EXPAT::EXPAT APPEND PROPERTY
        IMPORTED_CONFIGURATIONS RELEASE)
      set_target_properties(EXPAT::EXPAT PROPERTIES
        IMPORTED_LOCATION_RELEASE "${EXPAT_LIBRARY_RELEASE}")
    endif()

    if(EXPAT_LIBRARY_DEBUG)
      set_property(TARGET EXPAT::EXPAT APPEND PROPERTY
        IMPORTED_CONFIGURATIONS DEBUG)
      set_target_properties(EXPAT::EXPAT PROPERTIES
        IMPORTED_LOCATION_DEBUG "${EXPAT_LIBRARY_DEBUG}")
    endif()

    if(NOT EXPAT_LIBRARY_RELEASE AND NOT EXPAT_LIBRARY_DEBUG)
      set_property(TARGET EXPAT::EXPAT APPEND PROPERTY
        IMPORTED_LOCATION "${EXPAT_LIBRARY}")
    endif()
  endif()
endif()

mark_as_advanced(EXPAT_INCLUDE_DIR EXPAT_LIBRARY)


code:
# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

#[=======================================================================[.rst:
FindEnvModules
--------------

.. versionadded:: 3.15

Locate an environment module implementation and make commands available to
CMake scripts to use them.  This is compatible with both Lua-based Lmod
and TCL-based EnvironmentModules.

This module is intended for the use case of setting up the compiler and library
environment within a :ref:`CTest Script <CTest Script>` (``ctest -S``).  It can
also be used in a :ref:`CMake Script <Script Processing Mode>` (``cmake -P``).

.. note::

  The loaded environment will not survive past the end of the calling process.
  Do not use this module in project code (``CMakeLists.txt`` files) to load
  a compiler environment; it will not be available during the build.  Instead
  load the environment manually before running CMake or using the generated
  build system.

Example Usage
^^^^^^^^^^^^^

.. code-block:: cmake

  set(CTEST_BUILD_NAME "CrayLinux-CrayPE-Cray-dynamic")
  set(CTEST_BUILD_CONFIGURATION Release)
  set(CTEST_BUILD_FLAGS "-k -j8")
  set(CTEST_CMAKE_GENERATOR "Unix Makefiles")

  ...

  find_package(EnvModules REQUIRED)

  env_module(purge)
  env_module(load modules)
  env_module(load craype)
  env_module(load PrgEnv-cray)
  env_module(load craype-knl)
  env_module(load cray-mpich)
  env_module(load cray-libsci)

  set(ENV{CRAYPE_LINK_TYPE} dynamic)

  ...

Result Variables
^^^^^^^^^^^^^^^^

This module will set the following variables in your project:

``EnvModules_FOUND``
  True if a compatible environment modules framework was found.

Cache Variables
^^^^^^^^^^^^^^^

The following cache variable will be set:

``EnvModules_COMMAND``
  The low level module command to use.  Currently supported
  implementations are the Lua based Lmod and TCL based EnvironmentModules.

Environment Variables
^^^^^^^^^^^^^^^^^^^^^

``ENV{MODULESHOME}``
  Usually set by the module environment implementation, used as a hint to
  locate the module command to execute.

Provided Functions
^^^^^^^^^^^^^^^^^^

This defines the following CMake functions for interacting with environment
modules:

.. command:: env_module

  Execute an arbitrary module command:

  .. code-block:: cmake

    env_module(cmd arg1 ... argN)
    env_module(
      COMMAND cmd arg1 ... argN
      [OUTPUT_VARIABLE <out-var>]
      [RESULT_VARIABLE <ret-var>]
    )

  The options are:

  ``cmd arg1 ... argN``
    The module sub-command and arguments to execute as if they were
    passed directly to the module command in your shell environment.

  ``OUTPUT_VARIABLE <out-var>``
    The standard output from executing the module command.

  ``RESULT_VARIABLE <ret-var>``
    The return code from executing the module command.

.. command:: env_module_swap

  Swap one module for another:

  .. code-block:: cmake

    env_module_swap(out_mod in_mod
      [OUTPUT_VARIABLE <out-var>]
      [RESULT_VARIABLE <ret-var>]
    )

  This is functionally equivalent to the ``module swap out_mod in_mod`` shell
  command.  The options are:

  ``OUTPUT_VARIABLE <out-var>``
    The standard output from executing the module command.

  ``RESULT_VARIABLE <ret-var>``
    The return code from executing the module command.

.. command:: env_module_list

  Retrieve the list of currently loaded modules:

  .. code-block:: cmake

    env_module_list(<out-var>)

  This is functionally equivalent to the ``module list`` shell command.
  The result is stored in ``<out-var>`` as a properly formatted CMake
  :ref:`semicolon-separated list <CMake Language Lists>` variable.

.. command:: env_module_avail

  Retrieve the list of available modules:

  .. code-block:: cmake

    env_module_avail([<mod-prefix>] <out-var>)

  This is functionally equivalent to the ``module avail <mod-prefix>`` shell
  command.  The result is stored in ``<out-var>`` as a properly formatted
  CMake :ref:`semicolon-separated list <CMake Language Lists>` variable.

#]=======================================================================]

function(env_module)
  if(NOT EnvModules_COMMAND)
    message(FATAL_ERROR "Failed to process module command.  EnvModules_COMMAND not found")
    return()
  endif()

  set(options)
  set(oneValueArgs OUTPUT_VARIABLE RESULT_VARIABLE)
  set(multiValueArgs COMMAND)
  cmake_parse_arguments(MOD_ARGS
    "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGV}
  )
  if(NOT MOD_ARGS_COMMAND)
    # If no explicit command argument was given, then treat the calling syntax
    # as: module(cmd args...)
    set(exec_cmd ${ARGV})
  else()
    set(exec_cmd ${MOD_ARGS_COMMAND})
  endif()

  if(MOD_ARGS_OUTPUT_VARIABLE)
    set(err_var_args ERROR_VARIABLE err_var)
  endif()

  execute_process(
    COMMAND mktemp -t module.cmake.XXXXXXXXXXXX
    OUTPUT_VARIABLE tempfile_name
  )
  string(STRIP "${tempfile_name}" tempfile_name)

  # If the $MODULESHOME/init/cmake file exists then assume that the CMake
  # "shell" functionality exits
  if(EXISTS "$ENV{MODULESHOME}/init/cmake")
    execute_process(
      COMMAND ${EnvModules_COMMAND} cmake ${exec_cmd}
      OUTPUT_FILE ${tempfile_name}
      ${err_var_args}
      RESULT_VARIABLE ret_var
    )

  else() # fallback to the sh shell and manually convert to CMake
    execute_process(
      COMMAND ${EnvModules_COMMAND} sh ${exec_cmd}
      OUTPUT_VARIABLE out_var
      ${err_var_args}
      RESULT_VARIABLE ret_var
    )
  endif()

  # If we executed successfully then process and cleanup the temp file
  if(ret_var EQUAL 0)
    # No CMake shell so we need to process the sh output into CMake code
    if(NOT EXISTS "$ENV{MODULESHOME}/init/cmake")
      file(WRITE ${tempfile_name} "")
      string(REPLACE "\n" ";" out_var "${out_var}")
      foreach(sh_cmd IN LISTS out_var)
        if(sh_cmd MATCHES "^ *unset *([^ ]*)")
          set(cmake_cmd "unset(ENV{${CMAKE_MATCH_1}})")
        elseif(sh_cmd MATCHES "^ *export *([^ ]*)")
          set(cmake_cmd "set(ENV{${CMAKE_MATCH_1}} \"\${${CMAKE_MATCH_1}}\")")
        elseif(sh_cmd MATCHES " *([^ =]*) *= *(.*)")
          set(var_name "${CMAKE_MATCH_1}")
          set(var_value "${CMAKE_MATCH_2}")
          if(var_value MATCHES "^\"(.*[^\\])\"")
            # If it's in quotes, take the value as is
            set(var_value "${CMAKE_MATCH_1}")
          else()
            # Otherwise, strip trailing spaces
            string(REGEX REPLACE "([^\\])? +$" "\\1" var_value "${var_value}")
          endif()
          string(REPLACE "\\ " " " var_value "${var_value}")
          set(cmake_cmd "set(${var_name} \"${var_value}\")")
        else()
          continue()
        endif()
        file(APPEND ${tempfile_name} "${cmake_cmd}\n")
      endforeach()
    endif()

    # Process the change in environment variables
    include(${tempfile_name})
    file(REMOVE ${tempfile_name})
  endif()

  # Push the output back out to the calling scope
  if(MOD_ARGS_OUTPUT_VARIABLE)
    set(${MOD_ARGS_OUTPUT_VARIABLE} "${err_var}" PARENT_SCOPE)
  endif()
  if(MOD_ARGS_RESULT_VARIABLE)
    set(${MOD_ARGS_RESULT_VARIABLE} ${ret_var} PARENT_SCOPE)
  endif()
endfunction(env_module)

#------------------------------------------------------------------------------
function(env_module_swap out_mod in_mod)
  set(options)
  set(oneValueArgs OUTPUT_VARIABLE RESULT_VARIABLE)
  set(multiValueArgs)

  cmake_parse_arguments(MOD_ARGS
    "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGV}
  )

  env_module(COMMAND -t swap ${out_mod} ${in_mod}
    OUTPUT_VARIABLE tmp_out
    RETURN_VARIABLE tmp_ret
  )

  if(MOD_ARGS_OUTPUT_VARIABLE)
    set(${MOD_ARGS_OUTPUT_VARIABLE} "${tmp_out}" PARENT_SCOPE)
  endif()
  if(MOD_ARGS_RESULT_VARIABLE)
    set(${MOD_ARGS_RESULT_VARIABLE} ${tmp_ret} PARENT_SCOPE)
  endif()
endfunction()

#------------------------------------------------------------------------------
function(env_module_list out_var)
  cmake_policy(SET CMP0007 NEW)
  env_module(COMMAND -t list OUTPUT_VARIABLE tmp_out)

  # Convert output into a CMake list
  string(REPLACE "\n" ";" ${out_var} "${tmp_out}")

  # Remove title headers and empty entries
  list(REMOVE_ITEM ${out_var} "No modules loaded")
  if(${out_var})
    list(FILTER ${out_var} EXCLUDE REGEX "^(.*:)?$")
  endif()
  list(FILTER ${out_var} EXCLUDE REGEX "^(.*:)?$")

  set(${out_var} ${${out_var}} PARENT_SCOPE)
endfunction()

#------------------------------------------------------------------------------
function(env_module_avail)
  cmake_policy(SET CMP0007 NEW)

  if(ARGC EQUAL 1)
    set(mod_prefix)
    set(out_var ${ARGV0})
  elseif(ARGC EQUAL 2)
    set(mod_prefix ${ARGV0})
    set(out_var ${ARGV1})
  else()
    message(FATAL_ERROR "Usage: env_module_avail([mod_prefix] out_var)")
  endif()
  env_module(COMMAND -t avail ${mod_prefix} OUTPUT_VARIABLE tmp_out)

  # Convert output into a CMake list
  string(REPLACE "\n" ";" tmp_out "${tmp_out}")

  set(${out_var})
  foreach(MOD IN LISTS tmp_out)
    # Remove directory entries and empty values
    if(MOD MATCHES "^(.*:)?$")
      continue()
    endif()

    # Convert default modules
    if(MOD MATCHES "^(.*)/$" ) # "foo/"
      list(APPEND ${out_var} ${CMAKE_MATCH_1})
    elseif(MOD MATCHES "^((.*)/.*)\\(default\\)$") # "foo/1.2.3(default)"
      list(APPEND ${out_var} ${CMAKE_MATCH_2})
      list(APPEND ${out_var} ${CMAKE_MATCH_1})
    else()
      list(APPEND ${out_var} ${MOD})
    endif()
  endforeach()

  set(${out_var} ${${out_var}} PARENT_SCOPE)
endfunction()

#------------------------------------------------------------------------------
# Make sure we know where the underlying module command is
find_program(EnvModules_COMMAND
  NAMES lmod modulecmd
  HINTS ENV MODULESHOME
  PATH_SUFFIXES libexec
)

include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(EnvModules DEFAULT_MSG EnvModules_COMMAND)