program Make_Deck

! Make the first two phases of the Fortran deck by putting the PARAM card
! and the program deck BEFORE the clear-me overlay at the end of phase 2.
! Phase 2 looks for a card with SCANNER in columns 1-7, but it needs to
! be AFTER the branch-to-this overlay card, and BEFORE the setup-for-next
! overlay cards, but Autocoder can't put it there, so we move it here.
! 

! Command line arguments are Phase 0, Phase 1-2, Program file

! Output is on stdout

  use ISO_Fortran_Env, only: E => Error_Unit

  implicit NONE

  character(80) :: IOMsg
  integer :: IOStat, N
  character(80) :: Line, Param, Prog
  character(*), parameter :: Look = ',040040B' ! Overlay card

  ! Open Phase 1

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

  ! Copy phase 0

  do
    read ( 10, '(a)', end=1 ) line
    write ( *, '(a)' ) trim(line)
    if ( index(line, look) /= 0 ) exit
  end do

1 close ( 10 )

  ! Open phase 2

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

  ! Copy phase 1-2 through the third overlay card: Phase 1-2 loader,
  ! Phase 1, Phase 2.

  do n = 1, 3
    do
      read ( 10, '(a)', end=6663 ) line
      write ( *, '(a)' ) trim(line)
      if ( index(line, look) /= 0 ) exit
    end do
  end do

  ! Open the program file

  call get_command_argument ( 3, prog )
  open ( 11, file=trim(prog), status='old', iostat=iostat, iomsg=iomsg )
  if ( iostat /= 0 ) then
    write ( e, '(3a/i0,a/a)' ) 'Unable to open Program "', trim(prog), '"', &
      & 'Status ', iostat, trim(iomsg)
    stop
  end if

  ! Copy the program file

  do
    read ( 11, '(a)', end=2 ) prog
    write ( *, '(a)' ) trim(prog)
  end do
2 close ( 11 )

  ! Copy the rest of phase 1-2. The next card should have colon in column 1

  read ( 10, '(a)' ) line
  if ( line(1:1) /= ':' ) then
    write ( e, '(a)' ) 'Expected colon in column 1'
    stop
  end if
  write ( *, '(a)' ) trim(line)
  do
    read ( 10, '(a)', end=3 ) line
    write ( *, '(a)' ) trim(line)
  end do

3 close ( 10 )
  stop

6663 write ( e, '(a)' ) 'Phase 1-2 ended before the signal before the Clear-Me overlay'
  stop 3

end program Make_Deck
