include(FindPackageHandleStandardArgs)
include(SelectLibraryConfigurations)

find_path(
	EIGEN3_INCLUDE_DIR
	NAMES Eigen/Core
	PATH_SUFFIXES eigen3
)

if(EIGEN3_INCLUDE_DIR AND EXISTS "${EIGEN3_INCLUDE_DIR}/Eigen/src/Core/util/Macros.h")
	file(STRINGS "${EIGEN3_INCLUDE_DIR}/Eigen/src/Core/util/Macros.h" _EIGEN3_VERSION_WORLD_DEFINE REGEX "[\t ]*#define[\t ]+EIGEN_WORLD_VERSION[\t ]+[0-9]+.*")
	string(REGEX REPLACE "[\t ]*#define[\t ]+EIGEN_WORLD_VERSION[\t ]+([0-9]+).*" "\\1" EIGEN3_VERSION_WORLD "${_EIGEN3_VERSION_WORLD_DEFINE}")
	file(STRINGS "${EIGEN3_INCLUDE_DIR}/Eigen/src/Core/util/Macros.h" _EIGEN3_VERSION_MAJOR_DEFINE REGEX "[\t ]*#define[\t ]+EIGEN_MAJOR_VERSION[\t ]+[0-9]+.*")
	string(REGEX REPLACE "[\t ]*#define[\t ]+EIGEN_MAJOR_VERSION[\t ]+([0-9]+).*" "\\1" EIGEN3_VERSION_MAJOR "${_EIGEN3_VERSION_MAJOR_DEFINE}")
	file(STRINGS "${EIGEN3_INCLUDE_DIR}/Eigen/src/Core/util/Macros.h" _EIGEN3_VERSION_MINOR_DEFINE REGEX "[\t ]*#define[\t ]+EIGEN_MINOR_VERSION[\t ]+[0-9]+.*")
	string(REGEX REPLACE "[\t ]*#define[\t ]+EIGEN_MINOR_VERSION[\t ]+([0-9]+).*" "\\1" EIGEN3_VERSION_MINOR "${_EIGEN3_VERSION_MINOR_DEFINE}")
	if(NOT EIGEN3_VERSION_WORLD STREQUAL "" AND NOT EIGEN3_VERSION_MAJOR STREQUAL "" AND NOT EIGEN3_VERSION_MINOR STREQUAL "")
		set(EIGEN3_VERSION "${EIGEN3_VERSION_WORLD}.${EIGEN3_VERSION_MAJOR}.${EIGEN3_VERSION_MINOR}")
	endif()
	unset(_EIGEN3_VERSION_WORLD_DEFINE)
	unset(_EIGEN3_VERSION_MAJOR_DEFINE)
	unset(_EIGEN3_VERSION_MINOR_DEFINE)
endif()

set(EIGEN3_INCLUDE_DIRS ${EIGEN3_INCLUDE_DIR})

find_package_handle_standard_args(
	Eigen3
	FOUND_VAR Eigen3_FOUND
	REQUIRED_VARS EIGEN3_INCLUDE_DIR
	VERSION_VAR EIGEN3_VERSION
)

if(Eigen3_FOUND AND NOT TARGET Eigen3::Eigen)
	add_library(Eigen3::Eigen INTERFACE IMPORTED)
	set_target_properties(Eigen3::Eigen PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${EIGEN3_INCLUDE_DIRS}")
endif()

mark_as_advanced(EIGEN3_INCLUDE_DIR)
