# this is the macro to use in all subdirs CMakeLists
macro(pml_tool)
  get_directory_name(${CMAKE_CURRENT_SOURCE_DIR} PMLTOOL_NAME)

  parse_arguments(${PMLTOOL_NAME_CMAKE} 
    ""  # possible lists
    "NEEDS_LML" # possible options
    ${ARGN}
  )

  # if this extension is enabled, do everything needed
  # otherwise... do nothing
  if (PML_TOOLS)
    gather_headers_and_sources(PMLTOOL_NAME)

    if (${PMLTOOL_NAME_CMAKE}_NEEDS_LML)        
        set(NEEDED_LML_DEPENDENCIES ${LML_DEPENDENCY} ${LMLSCHEMA_DEPENDENCY})
        set(NEEDED_LML_DEPENDENCY ${LML_DEPENDENCY})
    endif()

    # check for target name
    set(PML_TOOLS_TARGET_NAME pml-tool-${PMLTOOL_NAME})
    
    include_directories(${CAMITK_INCLUDE_DIR}/libraries)
    link_directories(${CAMITK_LINK_DIRECTORIES})
    add_executable(${PML_TOOLS_TARGET_NAME} ${PMLTOOL_NAME_SOURCES})
    target_link_libraries(${PML_TOOLS_TARGET_NAME} ${PML_DEPENDENCIES} ${NEEDED_LML_DEPENDENCIES}) # pml, pmlschema, lml and lmlschema are all needed at link time
    
    # target properties
    set_target_properties(${PML_TOOLS_TARGET_NAME} 
                          PROPERTIES OUTPUT_NAME ${PMLTOOL_NAME}
    )
    add_dependencies(${PML_TOOLS_TARGET_NAME} ${PML_DEPENDENCY} ${NEEDED_LML_DEPENDENCY}) # pml and lml are needed, lmlschema/pmlschema are not as lml/pml depends on lmlschema already

    # installation
    install(TARGETS ${PML_TOOLS_TARGET_NAME}
            RUNTIME DESTINATION bin
            COMPONENT pml-tools
    )
  endif()

endmacro()

# if this is the first run
if(NOT PML_TOOLS_INTERNAL)
  message(STATUS "Checking for pml tools")
  # add option to enable/disable this pml tools 
  set(PML_TOOLS FALSE CACHE BOOL "Build all pml tools")
  set(PML_TOOLS_INTERNAL TRUE CACHE INTERNAL "Is PML_TOOLS already created?")
  mark_as_advanced(PML_TOOLS_INTERNAL)
endif()

# select possible tools
include_directories( ${PML_INCLUDE_DIRECTORIES})
set(PMLTOOLS_SOURCE_DIR ${PML_SOURCE_DIR}/tools)

# use CamiTK macro to detect the subdirectories
# find components
get_subdirectories(PMLTOOLS_LIST)

message(STATUS "Building pml tools: ${PML_TOOLS}")

# --- add every given/valid tools
# using the FOREACH statement allows the case where tools_SUBDIRS is empty!
foreach(PMLTOOL_NAME ${PMLTOOLS_LIST})
   add_subdirectory(${PMLTOOL_NAME})
endforeach()