!> @file
!! @brief External routines of the BigDFT library.
!! @details
!! To be documented in detail once stabilized
!! All the call to BigDFT code should be performed from these routines
!! No interface should be required to manipulate these routines
!! Non-intrinsic objects should be mapped to addresses which have to be manipulated
!! @author
!!    Copyright (C) 2007-2015 BigDFT group <br>
!!    This file is distributed under the terms of the
!!    GNU General Public License, see ~/COPYING file
!!    or http://www.gnu.org/copyleft/gpl.txt .
!!    For the list of contributors, see ~/AUTHORS


subroutine bigdft_finalize(ierr)
  use BigDFT_API
  use module_bigdft_mpi
  implicit none
  integer, intent(out) :: ierr

  ierr=0

  call bigdft_python_finalize()

  call bigdft_mpi_release()
end subroutine bigdft_finalize


function bigdft_error_ret(err_signal,err_message) result (ierr)
  implicit none
  character(len=*), intent(in) :: err_message
  integer, intent(in) :: err_signal
  integer :: ierr

  ierr=err_signal
  
end function bigdft_error_ret


!> Abort bigdft program
subroutine bigdft_severe_abort()
  use module_bigdft_output
  use module_bigdft_mpi
  use module_bigdft_arrays
  use module_bigdft_profiling
  use f_utils
  implicit none
  integer :: ierr
  !local variables
  character(len=128) :: filename,debugdir
  !the MPI_ABORT works only in MPI_COMM_WORLD
  if (bigdft_mpi%ngroup > 1) then
     call f_strcpy(src='bigdft-err-'+bigdft_mpi%iproc+'-'+bigdft_mpi%igroup+'.yaml',&
       dest=filename)
  else
     call f_strcpy(src='bigdft-err-'+bigdft_mpi%iproc+'.yaml',&
          dest=filename)
  end if
  !create the directory debug if it does not exists
  call f_mkdir('debug',debugdir) !this in principle should not crash if multiple cores are doing it simultaneously
  call f_strcpy(dest=filename,src=debugdir+filename)
  call f_malloc_dump_status(filename=filename)
  if (bigdft_mpi%iproc ==0) then
     call f_dump_all_errors(-1)
     call yaml_comment('Error raised!',hfill='^')
     call yaml_comment('Messages are above, dumping run status in file(s) '//&
          'bigdft-err-*.yaml of directory debug/',hfill='^')
     call yaml_comment('Exiting...',hfill='~')
     call yaml_flush_document() !might help, sometimes..
  end if
  !call f_lib_finalize()
  call f_pause(1) !< wait one second
  call MPI_ABORT(MPI_COMM_WORLD,816437,ierr)
  !call mpifinalize()
  !stop
  if (ierr/=0) stop 'Problem in MPI_ABORT'

end subroutine bigdft_severe_abort
