# Check for system jpeglib:
# ===================================================
SET(CMAKE_MRPT_HAS_JPEG 1)	# Always present: system or built-in
IF(MSVC OR APPLE)
	SET(CMAKE_MRPT_HAS_JPEG_SYSTEM 0)
ELSE(MSVC OR APPLE)
	FIND_PACKAGE(JPEG)
	IF(JPEG_FOUND)
		#MESSAGE(STATUS "Found library: jpeg  - Include: ${JPEG_INCLUDE_DIR}")
		INCLUDE_DIRECTORIES("${JPEG_INCLUDE_DIR}")

		SET(CMAKE_MRPT_HAS_JPEG_SYSTEM 1)
	ELSE(JPEG_FOUND)
		SET(CMAKE_MRPT_HAS_JPEG_SYSTEM 0)
	ENDIF(JPEG_FOUND)
ENDIF(MSVC OR APPLE)

IF(NOT CMAKE_MRPT_HAS_JPEG_SYSTEM)
	include(ExternalProject)

	FIND_PROGRAM(NASM_PATH nasm)
	if(NASM_PATH)
		SET(JPEG_ENABLE_SIMD 1)
	else(NASM_PATH)
		SET(JPEG_ENABLE_SIMD 0)
	endif(NASM_PATH)

	ExternalProject_Add(EP_JPEG
		URL               "https://github.com/libjpeg-turbo/libjpeg-turbo/archive/1.5.90.tar.gz"
		URL_MD5           "85f7f9c377b70cbf48e61726097d4efa"
		SOURCE_DIR        "${MRPT_BINARY_DIR}/otherlibs/libjpeg-turbo/"
		CMAKE_ARGS
			-DENABLE_SHARED=OFF
			-DCMAKE_POSITION_INDEPENDENT_CODE=ON
			-DWITH_SIMD=${JPEG_ENABLE_SIMD}
			-DWITH_CRT_DLL=ON
		INSTALL_COMMAND   ""
	)
	
	ExternalProject_Get_Property(EP_JPEG BINARY_DIR)
	SET(JPEG_LIBRARY_NAME jpeg)
	if(MSVC)
		SET(JPEG_LIBRARY_NAME jpeg-static)
		SET(OBJDIR "$<CONFIG>/")
	endif()

	SET(JPEG_INCLUDE_DIRS
		"${MRPT_BINARY_DIR}/otherlibs/libjpeg-turbo/"
		"${BINARY_DIR}")
	SET(JPEG_LIBRARIES ${BINARY_DIR}/${OBJDIR}${CMAKE_STATIC_LIBRARY_PREFIX}${JPEG_LIBRARY_NAME}${CMAKE_STATIC_LIBRARY_SUFFIX})

	add_library(JPEG STATIC IMPORTED)
	set_property(TARGET JPEG PROPERTY IMPORTED_LOCATION ${JPEG_LIBRARIES})
	add_dependencies(JPEG EP_JPEG)


	INCLUDE_DIRECTORIES("${JPEG_INCLUDE_DIRS}")
ENDIF(NOT CMAKE_MRPT_HAS_JPEG_SYSTEM)
