module module_bigdft_errors
  use dictionaries, only: f_err_raise, f_err_throw, f_err_check, f_err_pop, f_err_open_try, f_err_close_try
  use yaml_strings, only: yaml_toa, operator(//), operator(+)
  use f_utils, only: f_assert

  implicit none

  public

  !> Error codes, to be documented little by little
  integer, save :: BIGDFT_RUNTIME_ERROR         !< Error during runtime
  integer, save :: BIGDFT_MPI_ERROR             !< See error definitions below
  integer, save :: BIGDFT_LINALG_ERROR          !< To be moved to linalg wrappers
  integer, save :: BIGDFT_INPUT_VARIABLES_ERROR !< Problems in parsing or in consistency of input variables
  integer, save :: BIGDFT_INPUT_FILE_ERROR      !< The file does not exist!
  
contains

  !> Define the BigDFT errors
  subroutine bigdft_init_errors()
    use dictionaries
    implicit none
    external :: bigdft_severe_abort

    call f_err_define('BIGDFT_RUNTIME_ERROR',&
         'An invalid operation has been done during runtime',&
         BIGDFT_RUNTIME_ERROR,&
         err_action='Check the exact unrolling of runtime operations,'//&
         ' likely something has been initialized/finalized twice')

    call f_err_define('BIGDFT_MPI_ERROR',&
         'An error of MPI library occurred',&
         BIGDFT_MPI_ERROR,&
         err_action='Check if the error is related to MPI library or runtime conditions')

    call f_err_define('BIGDFT_LINALG_ERROR',&
         'An error of linear algebra occurred',&
         BIGDFT_LINALG_ERROR,&
         err_action='Check if the matrix is correct at input, also look at the info value')

    !The structure of input file is correct but the input variables have some trouble
    call f_err_define('BIGDFT_INPUT_VARIABLES_ERROR',&
         'An error while parsing the input variables occured',&
         BIGDFT_INPUT_VARIABLES_ERROR,&
         err_action='Check above which input variable has been not correctly parsed, or check their values')

!!$    !define the errors of internal modules
!!$    call input_keys_errors()

    !If the file does not exist, we use the INPUT_OUTPUT_ERROR from futile
    !This error is used when the input file is incorrect
    call f_err_define('BIGDFT_INPUT_FILE_ERROR',&
         'The input file is not correct',&
         BIGDFT_INPUT_FILE_ERROR,&
         err_action='Check the input file')

    !define the severe operation via MPI_ABORT
    call f_err_severe_override(bigdft_severe_abort)
  end subroutine bigdft_init_errors

end module module_bigdft_errors
