#INCLUDE "semaphore.inc"
#INCLUDE "crew.inc"

#INCLUDE "display.inc"
#INCLUDE "control_info.inc"

PROC controller (CHAN OF BYTE in, CREW.CONTROL.INFO control.info,
                 CHAN OF DISPLAY out, SEMAPHORE out.s)

  VAL INT max.seconds IS 1000000:
  VAL INT min.seconds IS 10:
  VAL INT shift.seconds IS 1:

  VAL INT max.read.percentage IS 100:
  VAL INT min.read.percentage IS 0:
  VAL INT delta.read.percentage IS 10:

  INITIAL BOOL running IS TRUE:

  WHILE running
    INITIAL BOOL change IS TRUE:
    BYTE ch:
    SEQ
      in ? ch
      CASE ch
        --{{{  'S'
        'S'
          SEQ
            claim.write.crew (control.info[crew])
            control.info[seconds] := control.info[seconds] << shift.seconds
            IF
              control.info[seconds] > max.seconds
                control.info[seconds] := max.seconds
              TRUE
                SKIP
            release.write.crew (control.info[crew])
        --}}}
        --{{{  's'
        's'
          SEQ
            claim.write.crew (control.info[crew])
            control.info[seconds] := control.info[seconds] >> shift.seconds
            IF
              control.info[seconds] < min.seconds
                control.info[seconds] := min.seconds
              TRUE
                SKIP
            release.write.crew (control.info[crew])
        --}}}
        --{{{  'R'
        'R'
          SEQ
            claim.write.crew (control.info[crew])
            IF
              control.info[read.percentage] < max.read.percentage
                control.info[read.percentage] := control.info[read.percentage] +
                                                 delta.read.percentage
              TRUE
                SKIP
            release.write.crew (control.info[crew])
        --}}}
        --{{{  'r'
        'r'
          SEQ
            claim.write.crew (control.info[crew])
            IF
              control.info[read.percentage] > min.read.percentage
                control.info[read.percentage] := control.info[read.percentage] -
                                                 delta.read.percentage
              TRUE
                SKIP
            release.write.crew (control.info[crew])
        --}}}
        --{{{  'f', 'F'
        'f', 'F'
          SEQ
            claim.semaphore (out.s)
            in ? ch
            release.semaphore (out.s)
            change := FALSE
        --}}}
        --{{{  'd'
        'd'
          SEQ
            running := FALSE
            change := FALSE
        --}}}
        ELSE
          change := FALSE
      IF
        change
          SEQ
            claim.semaphore (out.s)
            out ! control
            release.semaphore (out.s)
        TRUE
          SKIP

:
