include(FindPackageHandleStandardArgs)
include(SelectLibraryConfigurations)

find_path(
	EIGEN3_INCLUDE_DIRS
	NAMES
	Eigen/Core
	PATH_SUFFIXES
	eigen3
)

mark_as_advanced(EIGEN3_INCLUDE_DIRS)

if(EIGEN3_INCLUDE_DIRS AND EXISTS "${EIGEN3_INCLUDE_DIRS}/Eigen/src/Core/util/Macros.h")
	file(STRINGS "${EIGEN3_INCLUDE_DIRS}/Eigen/src/Core/util/Macros.h" _EIGEN3_VERSION_WORLD_DEFINE REGEX "#define[\t ]+EIGEN_WORLD_VERSION[\t ]+[0-9]+.*")
	string(REGEX REPLACE "#define[\t ]+EIGEN_WORLD_VERSION[\t ]+([0-9]+).*" "\\1" EIGEN3_VERSION_WORLD "${_EIGEN3_VERSION_WORLD_DEFINE}")
	file(STRINGS "${EIGEN3_INCLUDE_DIRS}/Eigen/src/Core/util/Macros.h" _EIGEN3_VERSION_MAJOR_DEFINE REGEX "#define[\t ]+EIGEN_MAJOR_VERSION[\t ]+[0-9]+.*")
	string(REGEX REPLACE "#define[\t ]+EIGEN_MAJOR_VERSION[\t ]+([0-9]+).*" "\\1" EIGEN3_VERSION_MAJOR "${_EIGEN3_VERSION_MAJOR_DEFINE}")
	file(STRINGS "${EIGEN3_INCLUDE_DIRS}/Eigen/src/Core/util/Macros.h" _EIGEN3_VERSION_MINOR_DEFINE REGEX "#define[\t ]+EIGEN_MINOR_VERSION[\t ]+[0-9]+.*")
	string(REGEX REPLACE "#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()

find_package_handle_standard_args(
	Eigen3
	FOUND_VAR EIGEN3_FOUND
	REQUIRED_VARS EIGEN3_INCLUDE_DIRS
	VERSION_VAR EIGEN3_VERSION
)

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