IF(NOT FreeRTOS_PORT)
	MESSAGE(FATAL_ERROR "FreeRTOS_PORT not specified. You must specify the port of FreeRTOS")
ENDIF()

# Get all ports
FILE(GLOB_RECURSE FRTOS_PORT port.c)
FOREACH(FRTOS_P ${FRTOS_PORT})
	# Get parent directory path to the port
	GET_FILENAME_COMPONENT(FRTOS_P_PAR_DIR ${FRTOS_P} DIRECTORY)
	# Extract only the name of the parent directory
	GET_FILENAME_COMPONENT(FRTOS_P_PAR_DIR_NAME ${FRTOS_P_PAR_DIR} NAME)
	# If it equals the port name then we've found our port
	IF(${FRTOS_P_PAR_DIR_NAME} STREQUAL ${FreeRTOS_PORT})
		SET(FREERTOS_PORT_DIR ${FRTOS_P_PAR_DIR})
		BREAK()
	ENDIF()
ENDFOREACH()
IF(NOT FREERTOS_PORT_DIR)
	MESSAGE(FATAL_ERROR "Could not find port ${FreeRTOS_PORT}")
ENDIF()

# Find path to FreeRTOS.h file
FILE(GLOB_RECURSE FREERTOS_MAIN_FPATH_LIST FreeRTOS.h)
LIST(LENGTH FREERTOS_MAIN_FPATH_LIST FREERTOS_MAIN_FPATH_LIST_LEN)
IF(FREERTOS_MAIN_FPATH_LIST_LEN EQUAL 0)
	MESSAGE(FATAL_ERROR "FreeRTOS path not found")
ENDIF()
# Set the path to the first path found
LIST(GET FREERTOS_MAIN_FPATH_LIST 0 FREERTOS_MAIN_FPATH)
IF(NOT FREERTOS_MAIN_FPATH_LIST_LEN EQUAL 1)
	MESSAGE(WARNING "Multiple FreeRTOS implementations found. Choosing first: ${FREERTOS_MAIN_FPATH}")
ENDIF()

# The parent directory is 'include' directory
GET_FILENAME_COMPONENT(FREERTOS_INC_DIR ${FREERTOS_MAIN_FPATH} DIRECTORY)
# The parent directory of 'include' directory contains FreeRTOS source files
GET_FILENAME_COMPONENT(FREERTOS_SRC_DIR ${FREERTOS_INC_DIR} DIRECTORY)
FILE(GLOB FREERTOS_SRCS ${FREERTOS_SRC_DIR}/*.c)

IF(NOT FreeRTOS_HEAP_IMPL)
	MESSAGE(FATAL_ERROR "FreeRTOS_HEAP_IMPL not defined. Define it to include proper heap implementation file.")
ELSE()
	SET(HEAP_IMP_FILE heap_${FreeRTOS_HEAP_IMPL}.c)
ENDIF()

IF(FreeRTOS_FIND_COMPONENTS)
	FOREACH(CMP ${FreeRTOS_FIND_COMPONENTS})
		IF(${CMP} STREQUAL "CMSIS")
			IF(EXISTS ${FREERTOS_SRC_DIR}/CMSIS_RTOS)
				SET(CMSIS_FREERTOS_INC_DIR ${FREERTOS_SRC_DIR}/CMSIS_RTOS)
				FILE(GLOB CMSIS_FREERTOS_SOURCES ${CMSIS_FREERTOS_INC_DIR}/*.c)
			ELSE()
				IF(FreeRTOS_FIND_REQUIRED_${CMP})
					MESSAGE(FATAL_ERROR "Could not find CMSIS_RTOS directory within FreeRTOS directory tree")
				ENDIF()
			ENDIF()
		ENDIF()
	ENDFOREACH()
ENDIF()

# Find heap implementation file
FILE(GLOB_RECURSE HEAP_IMP_SOURCE ${HEAP_IMP_FILE})

SET(FreeRTOS_INCLUDE_DIRS
	${FREERTOS_INC_DIR}
	${CMSIS_FREERTOS_INC_DIR}
	${FREERTOS_PORT_DIR}
)

SET(FreeRTOS_SOURCES
	${FREERTOS_SRCS}
	${CMSIS_FREERTOS_SOURCES}
	${FREERTOS_PORT_DIR}/port.c
	${HEAP_IMP_SOURCE}
)

INCLUDE(FindPackageHandleStandardArgs)

FIND_PACKAGE_HANDLE_STANDARD_ARGS(FreeRTOS DEFAULT_MSG FreeRTOS_INCLUDE_DIRS FreeRTOS_SOURCES)
