program Intercom_1000

  use Exec
  use Memory

  implicit None

  integer :: CC ! CommandCounter
  integer :: Chan
  logical :: Continuable = .false.
  logical :: Error
  integer :: I
  character(120) :: Line, Word
  logical :: Single_FP = .true.
  integer :: WhyReturn

1 format (2a)

  do
    read ( *, '(a)', end=9 ) line
    if ( line == '' ) cycle
    line = adjustl(line)
    i = index(line,' ')
    word = line(1:i-1)
    line = adjustl(line(i+1:))
    i = index(line,' ')
    select case ( lowerCase(word(1:1)) )
    case ( 'c' )
      if ( continuable ) then
        call execute ( cc, Single_FP, .true., whyReturn )
        continuable = whyReturn == why_pause
      else
        print 1, 'Cannot continue here'
      end if
    case ( 'i' )
      call read_instruction ( line(:i-1), instructions(19,00), error )
      if ( error ) cycle
      cc = 1900
      call execute ( cc, Single_FP, .true., whyReturn )
      continuable = whyReturn == why_pause
    case ( 'p' )
      select case ( lowerCase(line(1:1)) )
      case ( 'd' )
        single_fp = .false.
      case ( 's' )
        single_fp = .true.
      case default
        print *, 'Precision selection must be S or D'
      end select
    case ( 'q' )
      exit
    case ( 's' )
      word = line(:i-1)
      line = adjustl(line(i+1:))
      read ( word, *, iostat=i ) chan
      if ( i /= 0 ) then
        print 1, 'Invalid channel number'
      else if ( chan > 18 .or. chan < merge(7,9,single_fp) ) then
        print 1, 'Invalid channel number'
      else
        i = index(names,trim(lowerCase(line)))
        if ( i == 0 ) then
          print 1, 'Invalid subroutine name'
        else
          subroutines(chan) = i / 6
          what(chan,:) = w_none
        end if
      end if
    case default
      print 1, 'C => continue after breakpoint pause'
      print 1, 'I instruction => Execute one instruction'
      print 1, 'P D or P S => Select precision'
      print 1, 'S channel subroutine => Load subroutine in specified channel'
      print 1, '  subroutine must be one of'
      print 1, '  ', trim(names)
      print 1, 'Use "I 69addr" to compute automatically'
      print 1, 'Use "I 55chwd" to read "wd" words of paper tape into channel "ch"'
      print 1, '    You will be prompted to provide a file name'
      print 1, '    Format: one per line, "I instruction", "D data", "N" for neither'
    end select
  end do

9 continue

contains

  function LowerCase ( String )
    character(len=*), intent(in) :: String
    character(len=len(string)) :: LowerCase
    integer, parameter :: Conv = iachar('a') - iachar('A')
    integer :: I
    do i = 1, len(string)
      lowerCase(i:i) = string(i:i)
      if ( string(i:i) >= 'A' .and. string(i:i) <= 'Z' ) &
        lowerCase(i:i) = achar(iachar(string(i:i)) + conv)
    end do
  end function LowerCase
end program Intercom_1000
