IF(NOT ChibiOS_Contrib_FIND_COMPONENTS)
    SET(ChibiOS_Contrib_FIND_COMPONENTS hal)
    MESSAGE(STATUS "No ChibiOS Contrib components specified, using default: ${ChibiOS_Contrib_FIND_COMPONENTS}")
ENDIF()

SET (CHIBIOS_CONTRIB_COMPONENTS hal)
LIST(FIND ChibiOS_Contrib_FIND_COMPONENTS hal ChibiOS_Contrib_FIND_COMPONENTS_hal)

IF(${ChibiOS_FIND_COMPONENTS_hal} LESS 0)
  LIST(APPEND ChibiOS_Contrib_FIND_COMPONENTS hal)
ENDIF()

IF(NOT CHIBIOS_CONTRIB_HALCONF_FILE)
    MESSAGE(STATUS "No ChibiOS Contrib halconf_community.h specified, trying to find it...")
    FILE(GLOB CHIBIOS_HALCONF_FILE "halconf_community.h")
    IF (CHIBIOS_CONTRIB_HALCONF_FILE STREQUAL "")
        MESSAGE(FATAL_ERROR "Cannot find halconf_community.h, please specify it using CHIBIOS_CONTRIB_HALCONF_FILE variable")
    ELSE()
        MESSAGE(STATUS "Found halconf_community.h: ${CHIBIOS_CONTRIB_HALCONF_FILE}")
    ENDIF()
ENDIF()

FILE(STRINGS ${CHIBIOS_CONTRIB_HALCONF_FILE} HALCONF_CONTRIB_LINES REGEX "#define HAL_USE_([a-zA-Z_0-9]+) +TRUE")
FOREACH(LINE ${HALCONF_CONTRIB_LINES})
    STRING(REGEX REPLACE "#define HAL_USE_([a-zA-Z_0-9]+) +TRUE" "\\1" COMP ${LINE})
    LIST(APPEND CHIBIOS_CONTRIB_HAL_COMPONENTS ${COMP})
ENDFOREACH()

MESSAGE(STATUS "Detected ChibiOS Contrib HAL components:")
FOREACH(COMP ${CHIBIOS_CONTRIB_HAL_COMPONENTS})
    MESSAGE(STATUS "\t${COMP}")
ENDFOREACH()

INCLUDE(ChibiOS/contrib/ChibiOS_CONTRIB_HAL)

MESSAGE(STATUS "Contrib HAL sources: ")
FOREACH(SOURCE ${CHIBIOS_CONTRIB_SOURCES_hal})
    MESSAGE(STATUS "\t${SOURCE}")
ENDFOREACH()

FOREACH(comp ${ChibiOS_Contrib_FIND_COMPONENTS})
    LIST(FIND CHIBIOS_CONTRIB_COMPONENTS ${comp} INDEX)
    IF(INDEX EQUAL -1)
        MESSAGE(FATAL_ERROR "Unknown ChibiOS Contrib component: ${comp}\nSupported ChibiOS Contrib components: ${CHIBIOS_CONTRIB_COMPONENTS}")
    ENDIF()
    FOREACH(source ${CHIBIOS_CONTRIB_SOURCES_${comp}})
        FIND_FILE(CHIBIOS_CONTRIB_${comp}_${source} NAMES ${source} PATHS ${CHIBIOS_CONTRIB_ROOT} NO_DEFAULT_PATH CMAKE_FIND_ROOT_PATH_BOTH)
        LIST(APPEND ChibiOS_Contrib_SOURCES ${CHIBIOS_CONTRIB_${comp}_${source}})
    ENDFOREACH()
    FOREACH(incl ${CHIBIOS_CONTRIB_INCLUDES_${comp}})
        LIST(APPEND ChibiOS_Contrib_INCLUDE_DIRS ${CHIBIOS_CONTRIB_ROOT}/${incl})
    ENDFOREACH()
ENDFOREACH()
