macro(setup_conan)
  set(options Release Debug RelWithDebInfo TARGETS)
  set(oneValueArgs PROFILE)
  cmake_parse_arguments(MARGS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} )
  if(MARGS_Release)
  	set (CONAN_BUILD_TYPE Release)
  elseif(MARGS_Debug)
    set (CONAN_BUILD_TYPE Debug)
  elseif(MARGS_RelWithDebInfo)
    set (CONAN_BUILD_TYPE RelWithDebInfo) 
  endif()

  find_program(conan conan)
  if(NOT EXISTS ${conan})
    message(FATAL_ERROR "Conan is required. Please see README.md")
    return()
  endif()

  if(${CMAKE_HOST_SYSTEM_NAME} STREQUAL Darwin)
    set(os Macos)
  else()
    set(os ${CMAKE_HOST_SYSTEM_NAME})
  endif()

  if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
    set(compiler gcc)
  elseif(CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang")
    set(compiler apple-clang)
  else()
    message(FATAL_ERROR "Unknown compiler: ${CMAKE_CXX_COMPILER_ID}")
  endif()

  if (NOT "$ENV{CONAN_PROFILE_NAME}" STREQUAL "")
    set(CONAN_PROFILE "-pr" "$ENV{CONAN_PROFILE_NAME}" CACHE INTERNAL "Copied from environment variable")
  else()
    set(CONAN_PROFILE "-pr" "default" CACHE INTERNAL "Copied from environment variable")
  endif()

  set(conanfile ${CMAKE_SOURCE_DIR}/conanfile.txt)
  set(conanfile_cmake ${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
  set(conanfile_cmake_paths ${CMAKE_BINARY_DIR}/conan_paths.cmake)
  set(compiler_libcxx libstdc++11)
  
  if(NOT CONAN_BUILD_TYPE)
    if("${CMAKE_BUILD_TYPE}" STREQUAL "")
	  set(CONAN_BUILD_TYPE Debug)
    elseif("${CMAKE_BUILD_TYPE}" STREQUAL "RelWithDebInfo")
	  set(CONAN_BUILD_TYPE Release)
    else()
	  set(CONAN_BUILD_TYPE ${CMAKE_BUILD_TYPE})
    endif()
  endif()

  if(CMAKE_CXX_STANDARD EQUAL 98)
    execute_process(COMMAND ${conan} install --build=missing ${CONAN_PROFILE}
	    -s build_type=${CONAN_BUILD_TYPE} -s compiler.libcxx=${compiler_libcxx}
	    ${CMAKE_SOURCE_DIR} RESULT_VARIABLE return_code)
  else()
    execute_process(COMMAND ${conan} install --build=missing ${CONAN_PROFILE}
        -s build_type=${CONAN_BUILD_TYPE}
	    ${CMAKE_SOURCE_DIR} RESULT_VARIABLE return_code)
  endif()
  if(NOT ${return_code} EQUAL 0)
    message(FATAL_ERROR "conan install command failed.")
  endif()

  if(EXISTS "${conanfile_cmake_paths}")
  	include(${conanfile_cmake_paths})
  elseif(EXISTS "${conanfile_cmake}")
    include(${conanfile_cmake})
    if( MARGS_TARGETS)
  	  conan_basic_setup(TARGETS)
    else()
      conan_basic_setup()
    endif()
  endif()
endmacro()
