program Post_1_80

! Read a deck produced by Autocoder.  Strip off the number of cards specified
! by the command line parameter (default zero)

! If the destination address is less than 81, and less than the previous
! destination, punch the accumulated card.  Otherwise, if he destination
! address is less than 81put the data into the card.  Otherwise just copy
! the card.

! Put a four-digit sequence number in 72-75.

! Copy the deck ID in 76-80.

  character(80) :: Input
  character(80) :: ReadArea = '' ! 1-80

  integer :: From, To            ! Addresses in load instruction
  integer :: I
  integer :: PrevMax = 0
  integer :: Seq = 0
  integer :: Strip = 0

  call get_command_argument ( 1, input )
  if ( input /= '' ) read ( input, *, err=666 ) strip

  ! Strip the boot loader
  do i = 1, strip
    read ( *, '(a)', end=9 ) input
  end do

  ! Read the deck
  do
    read ( *, '(a)', end=9 ) input
    if ( ( input(40:40) == 'l' .or. input(40:40) == 'L' ) .and. &
       & verify(input(44:46),'0123456789') == 0 ) then  ! Destination is digits
      read ( input(41:46), '(2i3)' ) from, to
      if ( to < 81 ) then
        if ( to <= prevMax ) then
          seq = seq + 1
          write ( *, 1 ) trim(readArea), seq, trim(input(76:80))
        1 format (a,t72,i4.4,a)
          readArea = ''
        end if
        prevMax = to
        readArea(to-from+1:to) = input(1:from)
      elseif ( prevMax > 0 ) then
        seq = seq + 1
        write ( *, 1 ) trim(readArea), seq, trim(input(76:80))
        readArea = ''
        prevMax = 0
        seq = seq + 1
        write ( *, 1 ) trim(input), seq, trim(input(76:80))
      end if
    elseif ( prevMax > 0 ) then
      seq = seq + 1
      write ( *, 1 ) trim(readArea), seq, trim(input(76:80))
      readArea = ''
      prevMax = 0
      seq = seq + 1
      write ( *, 1 ) trim(input), seq, trim(input(76:80))
    end if
  end do

9 if ( prevMax > 0 ) then
    seq = seq + 1
    write ( *, 1 ) trim(readArea), seq, trim(input(76:80))
  end if
  stop

666 call get_command_argument ( 0, input )
  print '(3a)', 'Usage: ', trim(input), ' [skip] <input > output'
  print '(2a,i0)',  '  where "skip" is the number of cards to skip at the beginning', &
               & ', default ', strip

end program Post_1_80
