program Split59

  ! Split the object deck for phase 59 into 59ABC consisting of everything
  ! up to but not including the line with five underscores, and then
  ! starting again with the line containing five semicolons. Put the lines
  ! starting with five underscores, up to but not including the line with
  ! five semicolons into 59D.

  ! Input phase 59 in arg 1, output 59ABC in arg2, output 59D in arg3.

  use ISO_Fortran_Env, only: E => Error_Unit

  integer :: IOStat
  character(127) :: IOMsg
  character(80) :: Line

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

  call get_command_argument ( 2, line )
  open ( 11, file=trim(line), iostat=iostat, iomsg=iomsg )
  if ( iostat /= 0 ) then
    write ( e, '(4a/a,i0/a)' ) 'Unable to open output file "', trim(line), &
      '"', 'Status ', iostat, trim(iomsg)
    stop 2
  end if

  call get_command_argument ( 3, line )
  open ( 12, file=trim(line), iostat=iostat, iomsg=iomsg )
  if ( iostat /= 0 ) then
    write ( e, '(4a/a,i0/a)' ) 'Unable to open output file "', trim(line), &
      '"', 'Status ', iostat, trim(iomsg)
    stop 3
  end if

  ! Copy everything up to but not including the line beginning with
  ! underscores to phase-59ABC.
  do
    read ( 10, '(a)', end=6 ) line
    if ( line(1:5) == '_____' ) exit
    write ( 11, '(a)' ) trim(line)
  end do

  ! Copy starting with the line beginning with underscores up to but not
  ! including the line beginning with semicolons to phase-59D.
  do
    write ( 12, '(a)' ) trim(line)
    read ( 10, '(a)', end=6 ) line
    if ( line(1:5) == ';;;;;' ) exit
  end do

  ! Copy starting with the line beginning with semicolons through the end
  ! of the file to phase-59ABC.
  do
    write ( 11, '(a)' ) trim(line)
    read ( 10, '(a)', end=1 ) line
  end do

1 stop

6 write ( e, '(a)' ) 'End of file before finding the signals in phase-59'
  stop 6

end program split59
