macro(initialize_submodules)
  if(GIT_FOUND AND EXISTS "${PROJECT_SOURCE_DIR}/.git")
    set(git_modules_file "${PROJECT_SOURCE_DIR}/.gitmodules")
    if (EXISTS ${git_modules_file})
      file(STRINGS ${git_modules_file} file_lines)
      foreach(line ${file_lines})
        if (${line} MATCHES "url =")
          string(REGEX REPLACE "\\s*url = .*/(.*).git" "\\1" submodule "${line}")
          string(STRIP "${submodule}" submodule)
          if(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${submodule}")
            message(FATAL_ERROR "Submodule directory \"${CMAKE_CURRENT_SOURCE_DIR}/${submodule}\" does not exist")
          endif()
          # Initialize submodule if it hasn't already been cloned
          if(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${submodule}/.git")
            message(STATUS "Initialize ${submodule} submodule")
            execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive "${CMAKE_CURRENT_SOURCE_DIR}/${submodule}"
              WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
              RESULT_VARIABLE GIT_SUBMOD_RESULT)
            if(NOT GIT_SUBMOD_RESULT EQUAL "0")
              message(FATAL_ERROR "git submodule update --init --recursive ${CMAKE_CURRENT_SOURCE_DIR}/${submodule} failed with ${GIT_SUBMOD_RESULT}, please checkout submodules")
            endif()
          endif()
        endif()
      endforeach()
    endif()
  endif()
endmacro()