file(MAKE_DIRECTORY ${X86T_AUTOGENERATED_SRC_DIR_ASM_NASM_INC})

set(X86T_ASM_NASM_INC_SUFFIX "inc")

set(X86T_AUTOGENERATED_OUTPUT_SOURCES)

set(X86T_AUTOGENERATED_C_HEADER_ASM_INC)
foreach(C_HEADER ${X86T_C_HEADERS_CONVERT_NASM})
    get_filename_component(C_HEADER_FILENAME ${C_HEADER} NAME_WE)
    set(NASM_OUTPUT_SOURCE ${X86T_AUTOGENERATED_SRC_DIR_ASM_NASM_INC}/${C_HEADER_FILENAME}.${X86T_ASM_NASM_INC_SUFFIX})
    set(X86T_AUTOGENERATED_OUTPUT_SOURCES ${X86T_AUTOGENERATED_OUTPUT_SOURCES} ${NASM_OUTPUT_SOURCE})
    set(X86T_AUTOGENERATED_C_HEADER_ASM_INC ${X86T_AUTOGENERATED_C_HEADER_ASM_INC} "${C_HEADER}:${NASM_OUTPUT_SOURCE}")
endforeach()

#This function is copy-paste from https://stackoverflow.com/a/7216542/2786156
function(JOIN VALUES GLUE OUTPUT)
  string (REGEX REPLACE "([^\\]|^);" "\\1${GLUE}" _TMP_STR "${VALUES}")
  string (REGEX REPLACE "[\\](.)" "\\1" _TMP_STR "${_TMP_STR}") #fixes escaping
  set (${OUTPUT} "${_TMP_STR}" PARENT_SCOPE)
endfunction()

JOIN("${X86T_AUTOGENERATED_C_HEADER_ASM_INC}" "," X86T_AUTOGENERATED_C_HEADER_ASM_INC)

#TODO: Add check that python3.7 is installed
message(${X86T_AUTOGENERATED_OUTPUT_SOURCES})
message(${X86T_AUTOGENERATED_C_HEADER_ASM_INC})
add_custom_command(
    OUTPUT ${X86T_AUTOGENERATED_OUTPUT_SOURCES} 
    COMMAND python3.7 ${CMAKE_CURRENT_SOURCE_DIR}/generate_source.py
        --c-header-nasm-inc-pairs ${X86T_AUTOGENERATED_C_HEADER_ASM_INC} 
    DEPENDS 
)