module cubetools_cmessaging
  use cubetools_parameters
  !---------------------------------------------------------------------
  ! Support module for general CUBE messaging
  !---------------------------------------------------------------------
  !
  integer(kind=4), parameter :: command_length=16  ! Duplicate of SIC parameter
  logical :: debug_mode=.false.
  logical :: active_command=.false.
  character(len=command_length) :: current_command=strg_unk
  !
  public :: cubetools_cmessage
  public :: cubetools_cmessaging_debug
  public :: cubetools_cmessaging_command,cubetools_cmessaging_nocommand
  private
  !
contains
  !
  subroutine cubetools_cmessage(id,mkind,procname,message)
    use gkernel_interfaces
    !-------------------------------------------------------------------
    !-------------------------------------------------------------------
    integer(kind=4),  intent(in) :: id
    integer(kind=4),  intent(in) :: mkind
    character(len=*), intent(in) :: procname
    character(len=*), intent(in) :: message
    !
    character(len=64) :: prefix
    !
    if (debug_mode) then
      if (active_command) then
        prefix = trim(current_command)//'['//trim(procname)//']'
      else
        prefix = procname
      endif
    else
      if (active_command) then
        prefix = current_command
      else
        prefix = procname
      endif
    endif
    !
    call gmessage_write(id,mkind,prefix,message)
  end subroutine cubetools_cmessage
  !
  subroutine cubetools_cmessaging_command(command,error)
    !-------------------------------------------------------------------
    ! Declare the current command being executed from now on
    !-------------------------------------------------------------------
    character(len=*), intent(in)    :: command
    logical,          intent(inout) :: error
    active_command = .true.
    current_command = command
  end subroutine cubetools_cmessaging_command
  !
  subroutine cubetools_cmessaging_nocommand(error)
    !-------------------------------------------------------------------
    ! No command is being executed from now on
    !-------------------------------------------------------------------
    logical, intent(inout) :: error
    active_command = .false.
  end subroutine cubetools_cmessaging_nocommand
  !
  subroutine cubetools_cmessaging_debug(onoff)
    !-------------------------------------------------------------------
    !-------------------------------------------------------------------
    logical, intent(in) :: onoff
    debug_mode = onoff
  end subroutine cubetools_cmessaging_debug
  !
end module cubetools_cmessaging
