# --------------- runs clazy-standalone  ---------------

if(PUGS_SOURCE_DIR AND CLAZY_STANDALONE)
  # get C++ sources file list (ignoring packages)
  file(GLOB_RECURSE ALL_SOURCE_FILES
    ${PUGS_SOURCE_DIR}/src/**.[hc]pp
    ${PUGS_SOURCE_DIR}/tests/**.[hc]pp)

  # ignore ${PUGS_SOURCE_DIR}/packages/* directories
  set(ENV{CLAZY_IGNORE_DIRS} "${PUGS_SOURCE_DIR}/packages/.*")

  # checks if VERBOSE was set
  set(ECHO_CMD_TO "NONE")
  if (DEFINED ENV{VERBOSE})
    set(ECHO_CMD_TO "STDOUT")
  endif()

  # Trick to continue on error using make
  if(DEFINED ENV{MAKEFLAGS})
    string(FIND $ENV{MAKEFLAGS} "k" K_POSITION)
    if (NOT(${K_POSITION} EQUAL "-1"))
      set (CONTINUE_ON_ERROR "continue")
    endif()
  endif()

  list(LENGTH ALL_SOURCE_FILES LIST_SIZE)

  set(SOURCE_ID 1)
  # apply style to the file list
  foreach(SOURCE_FILE ${ALL_SOURCE_FILES})
    string(REGEX REPLACE "^${PUGS_SOURCE_DIR}/" "" BASE_SOURCE_FILE "${SOURCE_FILE}")

    math(EXPR PROGRESS "(100*${SOURCE_ID})/${LIST_SIZE}")
    string(LENGTH ${PROGRESS} PROGRESS_SIZE )

    math(EXPR NBSPC "3-${PROGRESS_SIZE}")
    string(SUBSTRING "   " 0 ${NBSPC} PRESPC)

    execute_process(
      COMMAND "${CMAKE_COMMAND}" -E env CLICOLOR_FORCE=1
      "${CMAKE_COMMAND}" -E cmake_echo_color --no-newline "[${PRESPC}${PROGRESS}%] " --green "Analyzing ${BASE_SOURCE_FILE}")
    execute_process(COMMAND "${CMAKE_COMMAND}" -E echo "")
    math(EXPR SOURCE_ID "${SOURCE_ID}+1")

    execute_process(
      COMMAND "${CLAZY_STANDALONE}" "-p=${PUGS_BINARY_DIR}" "${SOURCE_FILE}"
      COMMAND_ECHO ${ECHO_CMD_TO}
      RESULT_VARIABLE CLAZY_RESULT)

    if (NOT ("${CLAZY_RESULT}" EQUAL "0"))
      set(CLAZY_FAILED "1")
      message("CLAZY_FAILED ${CLAZY_FAILED}")
      if (NOT DEFINED CONTINUE_ON_ERROR)
	break()
      endif()
    endif()
  endforeach()

  if(CLAZY_FAILED)
    message(FATAL_ERROR "Clazy encountered errors!")
  endif()
endif()
