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

file(GLOB_RECURSE examples *.py)

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}
        COMMAND erb -T - ${CMAKE_CURRENT_SOURCE_DIR}/publicmode.erb ${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}
        COMMAND erb -T - ${CMAKE_CURRENT_SOURCE_DIR}/testmode.erb ${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}
        COMMAND erb -T - ${CMAKE_CURRENT_SOURCE_DIR}/figuremode.erb ${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})
