# This script is called from AddBenchmark in Macros.cmake
# It deletes the benchmark output files and then runs the benchmark.
IF (WIN32)

	SEPARATE_ARGUMENTS(FILES_TO_DELETE_VARS WINDOWS_COMMAND ${FILES_TO_DELETE})

	EXECUTE_PROCESS (
		COMMAND del /S /Q ${FILES_TO_DELETE_VARS}
		WORKING_DIRECTORY ${BENCHMARK_DIR_FOUND})

	EXECUTE_PROCESS (
		COMMAND ${EXECUTABLE_OUTPUT_PATH}/Release/ogs ${benchmarkStrippedName}
		WORKING_DIRECTORY ${BENCHMARK_DIR_FOUND}/${benchmarkDir}
		TIMEOUT ${BENCHMARK_TIMEOUT}
		RESULT_VARIABLE EXIT_CODE)

ELSE (WIN32)

	SEPARATE_ARGUMENTS(FILES_TO_DELETE_VARS UNIX_COMMAND ${FILES_TO_DELETE})

	IF(OGS_FEM_CONFIG STREQUAL "OGS_FEM_PETSC")
		#SET(NUM_PROCESSES 2)
		SET(MPI_RUN_COMMAND "mpirun" "-np" "${NUM_PROCESSES}")
	ELSE()
		SET(MPI_RUN_COMMAND "")
	ENDIF()

	MESSAGE(STATUS "WORKING_DIRECTORY is ${BENCHMARK_DIR_FOUND}")
	EXECUTE_PROCESS (
		COMMAND rm -f ${FILES_TO_DELETE_VARS}
		WORKING_DIRECTORY ${BENCHMARK_DIR_FOUND})
	IF(OGS_PROFILE AND NOT (OGS_FEM_CONFIG STREQUAL "OGS_FEM_PETSC" OR OGS_FEM_CONFIG STREQUAL "OGS_FEM_MPI"))
		MESSAGE(STATUS "Profiling benchmark")
		IF(OGS_OUTPUT_PROFILE)
			MESSAGE(STATUS "Executing gprof2dot.py")
			EXECUTE_PROCESS (
				COMMAND ${EXECUTABLE_OUTPUT_PATH}/ogs ${benchmarkStrippedName}
				WORKING_DIRECTORY ${BENCHMARK_DIR_FOUND}/${benchmarkDir}
				TIMEOUT ${BENCHMARK_TIMEOUT}
				RESULT_VARIABLE EXIT_CODE)

			# Run gprof2dot.py
			EXECUTE_PROCESS (
				COMMAND ${GPROF_PATH} ${EXECUTABLE_OUTPUT_PATH}/ogs
				COMMAND ${PROJECT_SOURCE_DIR}/scripts/gprof2dot.py -s -n 5.0 -e 1.0
				COMMAND ${DOT_TOOL_PATH} -Tpng -o ${BENCHMARK_DIR_FOUND}/results/${benchmarkStrippedName}.png
				WORKING_DIRECTORY ${BENCHMARK_DIR_FOUND}/${benchmarkDir})

		ELSE()
			EXECUTE_PROCESS (
				COMMAND ${GPROF_PATH} ${EXECUTABLE_OUTPUT_PATH}/ogs ${benchmarkStrippedName}
				WORKING_DIRECTORY ${BENCHMARK_DIR_FOUND}/${benchmarkDir}
				TIMEOUT ${BENCHMARK_TIMEOUT}
				RESULT_VARIABLE EXIT_CODE)
		ENDIF()
	ELSE()
		EXECUTE_PROCESS (
			COMMAND ${MPI_RUN_COMMAND} ${EXECUTABLE_OUTPUT_PATH}/ogs ${benchmarkStrippedName}
			WORKING_DIRECTORY ${BENCHMARK_DIR_FOUND}/${benchmarkDir}
			OUTPUT_FILE ${benchmarkStrippedName}.log
			TIMEOUT ${BENCHMARK_TIMEOUT}
			RESULT_VARIABLE EXIT_CODE)
	ENDIF()

ENDIF (WIN32)

IF(EXIT_CODE GREATER 0)
	MESSAGE(FATAL_ERROR "Benchmark exited with code: ${EXIT_CODE}")
ENDIF()
