# include modules
include(CheckCCompilerFlag)
include(CheckCXXCompilerFlag)
include(${CMAKE_CURRENT_LIST_DIR}/append_option.cmake)

macro(check_flag)
  foreach(flag ${ARGN})
    check_c_compiler_flag(${flag} CC${flag})
    if(CC${flag})
      append_cflag(${flag})
    endif()
    check_cxx_compiler_flag(${flag} CXX${flag})
    if(CXX${flag})
      append_cxxflag(${flag})
    endif()
  endforeach()
endmacro()

macro(check_cflag)
  foreach(flag ${ARGN})
    check_c_compiler_flag(${flag} CC${flag})
    if(CC${flag})
      append_cflag(${flag})
    endif()
  endforeach()
endmacro()

macro(check_cxx_flag)
  foreach(flag ${ARGN})
    check_cxx_compiler_flag(${flag} CXX${flag})
    if(CXX${flag})
      append_cxxflag(${flag})
    endif()
  endforeach()
endmacro()

if("${CMAKE_C_COMPILER_ID}" MATCHES "GNU" OR "${CMAKE_C_COMPILER_ID}" MATCHES "(Apple)?[Cc]lang" OR
  "${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "(Apple)?[Cc]lang")
  append_flag(-Wall -Wextra -Wpedantic)
  check_flag(-Wdouble-promotion)
  check_flag(-Wnull-dereference)
  check_flag(-Wmissing-include-dirs)
  check_flag(-Wswitch-default -Wswitch-enum)
  check_flag(-Walloca)
  check_flag(-Wattributes)
  check_flag(-Wfloat-equal)
  check_flag(-Wshadow)
  check_flag(-Wundef)
  check_flag(-Wunused -Wunused-macros)
  check_flag(-Wcast-qual -Wcast-align)
  check_flag(-Wconversion)
  check_flag(-Wdate-time)
  check_flag(-Waggregate-return)
  check_flag(-Wmissing-declarations)
  check_flag(-Wpacked -Wpadded)
  check_flag(-Wredundant-decls)
  check_flag(-Winline)
  check_flag(-Winvalid-pch)
  check_flag(-Wdisabled-optimization)
  check_flag(-Wstack-protector)
  check_cflag(-Winit-self)
  check_cflag(-Wbad-function-cast)
  check_cflag(-Wc++-compat)
  check_cflag(-Wstrict-prototypes)
  check_cflag(-Wold-style-definition)
  check_cflag(-Wmissing-prototypes)
  check_cflag(-Wnested-externs)
elseif("${CMAKE_C_COMPILER_ID}" MATCHES "MSVC" OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "MSVC")
  add_compile_definitions(_CRT_SECURE_NO_WARNINGS)
  append_cflag(/nologo /W4 /sdl)
  append_cxxflag(/nologo /W4 /sdl)
endif()
# GNU
if("${CMAKE_C_COMPILER_ID}" MATCHES "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU")
  check_flag(-Wstringop-overflow -Wstringop-truncation)
  check_flag(-Walloc-zero)
  check_flag(-Wduplicated-branches -Wduplicated-cond)
  check_flag(-Wzero-length-bounds)
  check_flag(-Wtrampolines)
  check_flag(-Wunsafe-loop-optimizations)
  check_flag(-Wno-pedantic-ms-format)
  check_flag(-Wlogical-op)
endif()
# Clang
if("${CMAKE_C_COMPILER_ID}" MATCHES "(Apple)?[Cc]lang" OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "(Apple)?[Cc]lang")
  check_flag(-Wshadow-all)
  check_flag(-Wzero-length-array)
endif()
