
MACRO(CONFIGURE_DOXYGEN_FILE DOXYGEN_CONFIG_FILE FILE_NAME_SUFFIX)
  IF(EXISTS ${PROJECT_SOURCE_DIR}/${DOXYGEN_CONFIG_FILE})
    FILE(REMOVE ${CMAKE_CURRENT_BINARY_DIR}/doxy-${FILE_NAME_SUFFIX}.conf)
    FILE(READ ${PROJECT_SOURCE_DIR}/${DOXYGEN_CONFIG_FILE} DOXYFILE_CONTENTS)
    STRING(REGEX REPLACE ";" "\\\\;" DOXYFILE_CONTENTS "${DOXYFILE_CONTENTS}")
    STRING(REGEX REPLACE "\n" ";" DOXYFILE_LINES "${DOXYFILE_CONTENTS}")
    LIST(LENGTH DOXYFILE_LINES ROW)
    MATH(EXPR ROW "${ROW} - 1")
    FOREACH(I RANGE ${ROW})
      LIST(GET DOXYFILE_LINES ${I} LINE)
      IF(LINE STRGREATER "")
        STRING(REGEX MATCH "^[a-zA-Z]([^ ])+" DOXY_PARAM ${LINE})
        IF(DEFINED DOXY_${DOXY_PARAM})
          STRING(REGEX REPLACE "=([^\n])+" "= ${DOXY_${DOXY_PARAM}}" LINE ${LINE})
        ENDIF(DEFINED DOXY_${DOXY_PARAM})
      ENDIF()
      FILE(APPEND ${CMAKE_CURRENT_BINARY_DIR}/doxy-${FILE_NAME_SUFFIX}.conf "${LINE}\n")
    ENDFOREACH()
  ELSE()
    MESSAGE(SEND_ERROR "Doxygen configuration file '${DOXYGEN_CONFIG_FILE}' not found. Documentation will not be generated")
  ENDIF()
ENDMACRO(CONFIGURE_DOXYGEN_FILE)

MACRO(ADD_DOCUMENTATION TARGET DOXYGEN_CONFIG_FILE)
  FIND_PACKAGE(Doxygen)
  IF(DOXYGEN_FOUND)
    CONFIGURE_DOXYGEN_FILE(${DOXYGEN_CONFIG_FILE} ${TARGET})
    get_filename_component(doxygen_outdir "${DOXYGEN_CONFIG_FILE}" PATH)
    set(doxygen_outdir ${PROJECT_SOURCE_DIR}/${doxygen_outdir})
    ADD_CUSTOM_TARGET(${TARGET}
            COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/doxy-${TARGET}.conf
            COMMAND moxygen --pages --anchors --output=${doxygen_outdir}/../docs/api.md ${doxygen_outdir}/xml
            )
  ELSE(DOXYGEN_FOUND)
    MESSAGE(STATUS "Doxygen not found. Documentation will not be generated")
  ENDIF(DOXYGEN_FOUND)
ENDMACRO(ADD_DOCUMENTATION)