string(TOLOWER ${STM32_FAMILY} STM32_FAMILY_LOWER)

set(CMSIS_COMMON_HEADER arm_common_tables.h)
set(CMSIS_DEVICE_HEADER stm32${STM32_FAMILY_LOWER}xx.h)

file(GLOB_RECURSE CMSIS_COMMON_HEADER_PATH ${CMSIS_COMMON_HEADER})
if(CMSIS_COMMON_HEADER_PATH)
    get_filename_component(CMSIS_COMMON_INCLUDE_DIR ${CMSIS_COMMON_HEADER_PATH} DIRECTORY)
endif()

file(GLOB_RECURSE CMSIS_DEVICE_HEADER_PATH ${CMSIS_DEVICE_HEADER})
if(CMSIS_DEVICE_HEADER_PATH)
    get_filename_component(CMSIS_DEVICE_INCLUDE_DIR ${CMSIS_DEVICE_HEADER_PATH} DIRECTORY)
endif()

file(GLOB_RECURSE CMSIS_STARTUP_SOURCE startup_stm32*.s)

set(CMSIS_INCLUDE_DIRS
    ${CMSIS_COMMON_INCLUDE_DIR}
    ${CMSIS_DEVICE_INCLUDE_DIR}
)
set(CMSIS_SOURCES
    ${CMSIS_STARTUP_SOURCE}
)

if(CMSIS_FIND_REQUIRED)
    if(NOT CMSIS_DEVICE_INCLUDE_DIR)
        message(FATAL_ERROR "CMSIS: Could not find device include directory")
    elseif(NOT CMSIS_COMMON_INCLUDE_DIR)
        message(FATAL_ERROR "CMSIS: Could not find common include directory")
    elseif(NOT CMSIS_STARTUP_SOURCE)
        message(FATAL_ERROR "CMSIS: Could not find startup source file")
    endif()
endif()

INCLUDE(FindPackageHandleStandardArgs)

FIND_PACKAGE_HANDLE_STANDARD_ARGS(CMSIS DEFAULT_MSG CMSIS_INCLUDE_DIRS CMSIS_SOURCES)
