if(NOT CONFIGURE_EXAMPLES)
    message(FATAL_ERROR "Invalid call w/o CONFIGURE_EXAMPLES")
endif()

file(GLOB_RECURSE all_examples "${CMAKE_CURRENT_SOURCE_DIR}/*.py")
set(examples "")
foreach(f ${all_examples})
    if(NOT f MATCHES "^${CMAKE_CURRENT_SOURCE_DIR}/template")
        list(APPEND examples "${f}")
    endif()
endforeach()

unset(outputs)
foreach(ex ${examples})
    cmake_path(GET ex FILENAME ex_name )
    cmake_path(GET ex PARENT_PATH in_path)

    # Configure the public version of examples.
    string(REPLACE ${EXAMPLES_SRC_DIR} ${EXAMPLES_PUBL_DIR} out_path ${in_path})
    file(MAKE_DIRECTORY ${out_path})
    set(ex_out ${out_path}/${ex_name})
    add_custom_command(
        OUTPUT ${ex_out}
        WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
        COMMAND ./processor.rb d ${ex} > ${ex_out}
        COMMAND chmod a+x ${ex_out}
        DEPENDS ${ex}
    )
    list(APPEND outputs ${ex_out})

    # Configure testable version of examples.
    # Tests will be configured by <ba>/Tests/Examples/CMakeLists.txt.
    string(REPLACE ${EXAMPLES_SRC_DIR} ${EXAMPLES_TEST_DIR} out_path ${in_path})
    file(MAKE_DIRECTORY ${out_path})
    set(ex_out ${out_path}/${ex_name})
    add_custom_command(
        OUTPUT ${ex_out}
        WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
        COMMAND ./processor.rb t ${ex} > ${ex_out}
        COMMAND chmod a+x ${ex_out}
        DEPENDS ${ex}
    )
    list(APPEND outputs ${ex_out})

    # Configure the version of examples to produce documentation figures.
    string(REPLACE ${EXAMPLES_SRC_DIR} ${EXAMPLES_FIGURES_DIR} out_path ${in_path})
    file(MAKE_DIRECTORY ${out_path})
    set(ex_out ${out_path}/${ex_name})
    add_custom_command(
        OUTPUT ${ex_out}
        WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
        COMMAND ./processor.rb f ${ex} > ${ex_out}
        COMMAND chmod a+x ${ex_out}
        DEPENDS ${ex}
    )
    list(APPEND outputs ${ex_out})

endforeach()

add_custom_target(configured_examples ALL DEPENDS ${outputs})
