
!
! ------------------------ trmpi_openlog --------------------
! Open a logmod log file.  
! Uses data in trmpi so assumes trmpi_runid, trmpi_myid, trmpi_numprocs has been set.
! 'transp' code will open log file in <runid>_log directory.
!
subroutine trmpi_openlog(zcode)
  use trmpi
  use logmod
  
  implicit none

  character*(*) :: zcode   ! name of code, child processes are only allowed to call this
                           ! subroutine with the code 'transp'

  character(len=max(len(zcode),3)) :: ztag   ! tag name for file

  character*180 :: logfile_level  ! log file level from environment variable.  This can
                                  ! be either a name ('WARN' ...) or number (0,1,2,3)
  character*180 :: log_file       ! name of log file

  integer :: id,ip    ! processor rank and max processors
  integer :: istat    ! nonzero on error
  

  call trmpi_check('trmpi_openlog')

  if (len_trim(trmpi_runid)==0) then
     write(0,'(a)') '?trmpi_openlog: trmpi_runid has not been set'
     call bad_exit
  end if

  call mpi_sget_env('LOGFILE_LEVEL',logfile_level,istat)  ! setup in trmpi_init

  if (istat/=0 .or. len_trim(logfile_level)==0) then
     if (trmpi_myid==0)  write(trmpi_lunmsg,'(a)') ' %trmpi_openlog: log level defaulted to WARN'
     logfile_level = 'warn'
  else if (trmpi_myid==0) then
     write(trmpi_lunmsg,'(a)') ' %trmpi_openlog: LOGFILE_LEVEL = '//trim(logfile_level)
  end if

  ztag = adjustl(zcode)

  call ulower(ztag)
  call ulower(logfile_level)   ! should be lower case anyway

  if (ztag == 'transp') then
     id = trmpi_myid
     ip = trmpi_numprocs

     write(log_file,'(a)') trim(adjustl(trmpi_runid))//'_log/'// &
          &       trim(adjustl(trmpi_runid))//'_cpu.log'
  else if (trmpi_myid==0) then
     id = -1   ! don't change log file name
     ip = -1

     write(log_file,'(a)') trim(adjustl(trmpi_runid))//'_'//trim(ztag)//'.log'
  else
     write(0,*) '?trmpi_openlog: attempt to open non-transp log file on child node'
     call bad_exit
  end if

  if(trim(logfile_level).ne.'nomsg' .and. trim(logfile_level).ne.'3') then
     call openLog(file=trim(log_file), status='RENAME', iostat=istat, icpu=id, numcpu=ip)

     if(istat/=0) then
        write(0,*) '?trmpi_openlog: error opening logmod log file'
        call bad_exit
     endif
  endif

  call setLogLevel(trim(logfile_level)) 
  
end  subroutine trmpi_openlog

