MODULE MPL_ABORT_MOD

USE MPL_DATA_MODULE
USE MPL_MPIF
USE OML_MOD
USE YOMABRT
USE SDL_MOD, ONLY : SDL_TRACEBACK, SDL_DISABORT

USE PARKIND1  ,ONLY : JPIM     ,JPRB

PUBLIC MPL_ABORT

CONTAINS 

SUBROUTINE MPL_ABORT(CDMESSAGE)

IMPLICIT NONE

CHARACTER*(*),INTENT(IN),OPTIONAL :: CDMESSAGE
INTEGER(KIND=JPIM) :: IRETURN_CODE,IERROR,ITID
ITID=OML_MY_THREAD()

CLOSE(MPL_UNIT)
CALL FLUSH(0)
CALL ec_sleep(1) ! This rather than 'CALL SYSTEM("sleep 1")' ; see code ../support/env.c

!------Traceback from only one thread
CALL OML_SET_LOCK(MYLOCK=MAB_LOCK(1))
IF(MAB_CNT == 0) THEN
  WRITE(MPL_ERRUNIT,'(A,I6,A,I6)') 'MPL_ABORT: CALLED FROM PROCESSOR ',MPL_RANK,' THRD',ITID
  IF(PRESENT(CDMESSAGE)) THEN
    WRITE(MPL_ERRUNIT,*) 'MPL_ABORT: THRD',ITID,"  ",CDMESSAGE
  ENDIF
  MAB_CNT=1
  CALL SDL_TRACEBACK(ITID)
  CALL FLUSH(0)
  CALL ec_sleep(1) ! This rather than 'CALL SYSTEM("sleep 1")' ; see code ../support/env.c
ENDIF
CALL OML_UNSET_LOCK(MYLOCK=MAB_LOCK(1))
! ------All threads wait till traceback done
CALL FLUSH(0)
CALL ec_sleep(1) ! This rather than 'CALL SYSTEM("sleep 1")' ; see code ../support/env.c

CALL SDL_DISABORT(MPL_COMM_OML(ITID))

END SUBROUTINE MPL_ABORT

END MODULE MPL_ABORT_MOD
