program List_to_Source

! Convert an Autocoder listing back to source code.

! If PAGE appears in columns 106-109, columns 86-90 go into columns 76-80
! of subsequent cards.

! The interesting lines are ones with a sequence number field (columns 1-4).

! The pg lin fields 6-7, 9-11 go to columns 1-5.

! If column 14 is an asterisk the line is a comment, and columns 14-79
! go to columns 6-71.

! Otherwise, the label field (columns 14-19) goes to columns 6-11,
! the OP field (columns 21-25) goes to columns 16-20, and the operands
! field (columns 27-79) goes to columns 21-73.

  character(11) :: Digits = '0123456789 '
  character(132) :: File, Line
  character(80) :: Out
  logical :: Stdin = .false., Stdout = .false.

  call getarg ( 1, file )
  if ( file == "--help" ) then
    call getarg ( 0, file )
    print *, 'Usage: ' // trim(file) // ' [input [output]]'
    print *, '  If input or output is omitted, standard input [output] is used'
    stop
  end if

  stdin = file == ''
  stdout = stdin
  if ( .not. stdin ) then
    open ( 10, file=file, status='old', form='formatted', access='sequential' )
    call getarg ( 2, file )
    stdout = file == ''
    if ( .not. stdout ) &
      & open ( 11, file=file, form='formatted', access='sequential' )
  end if

  do
    if ( stdin ) then
      read ( *, '(a)', end=9 ) line
    else
      read ( 10, '(a)', end=9 ) line
    end if

    if ( line(106:109) == 'PAGE' ) then
      out(76:80) = line(86:90)  ! Page heading, save ID
      cycle
    end if

    if ( line(1:5) == '' ) cycle  ! Not code if blank

    if ( verify(line(1:5),digits) /= 0 ) cycle  ! Not code if not digits

    out(1:5) = line(6:7) // line(9:11)
    if ( line(14:14) == '*' ) then
      out(6:75) = line(14:79)
    else
      out(6:15) = line(14:19)
      out(16:20) = line(21:25)
      out(21:75) = line(27:79)
    end if

    if ( stdout ) then
      write ( *, '(a)' ) trim(out)
    else
      write ( 11, '(a)' ) trim(out)
    end if

  end do

9 if ( .not. stdin ) close ( 10 )
  if ( .not. stdout ) close ( 11 )

end program List_to_Source
