program Tdump

  ! Dump the "tape" created by -t using Autocoder.
  ! Input from argument 1 if present, else from stdin, output to stdout.
  ! The tape is plain text, not SimH, so don't use tpdump

  use ISO_Fortran_Env, only: Input_Unit, E => Error_Unit

  implicit NONE

  integer :: I                     ! Index in Line
  integer :: IT                    ! Index in Pt, Pwm
  logical :: LIB = .false.          ! Don't indent between ]]]]] and ;;;;;
                                   ! to dump Fortran compiler tape
  integer :: IOStat
  character(127) :: IOMsg
  character(128) :: Line           ! Input line
  character(80) :: Pt, Pwm         ! Buffers to print text, word marks
  integer :: U = input_unit
  character, parameter :: WM = "~" ! Word mark character

  call get_command_argument ( 1, line )
  if ( line /= '' ) then
    u = 10
    open ( u, file=trim(line), status='old', iostat=iostat, iomsg=iomsg )
    if ( iostat /= 0 ) then
      write ( e, '(3a/a,i0/a)' ) 'Unable to open input file "', &
        & trim(line), '"', 'Status ', iostat, trim(iomsg)
      stop
    end if
  end if

  do i = 1, 80
    pt(i:i) = '.'
    pt(1:1) = '1'
  end do
  do i = 9, 79, 10
    write ( pt(i:i+1), '(i2.2)' ) i + 1
  end do
  write ( *, '(a)' ) pt

  do
    read ( u, '(a)', end=9 ) line
    if ( line(1:5) == ']]]]]' ) lib = .true. ! Start of Fortran tape's lib
    pt = ''
    pwm = ''
    it = 1
    do i = 1, len_trim(line)
      if ( line(i:i) == wm ) then
        pwm(it:it) = '1'
      else
        if ( it > 80 ) exit ! The first line has GMWM in 101
        pt(it:it) = line(i:i)
        it = it + 1
      end if
    end do
    if ( pt(1:1) == 'B' .or. pt(1:1) == 'U' .or. lib) then
      write ( *, '(a)' ) trim(pt)
      if ( .not. lib ) write ( *, '(a)' ) trim(pwm)
    else                               
      write ( *, '(19x,a)' ) trim(pt)  
      write ( *, '(19x,a)' ) trim(pwm)  
    end if                             
    if ( line(1:5) == ';;;;;' ) lib = .false. ! End of Fortran tape's lib
  end do

9 continue

end program Tdump
