-- The Great Computer Language Shootout
-- http://shootout.alioth.debian.org/
--
-- contributed by Christian L. Jacobsen

#INCLUDE "course.module"

VAL INT n IS 150: -- FIXME: From cmd line
VAL INT t IS 3000:

PROC thread(CHAN INT in?, out!)
  SEQ i = 0 FOR n
    INT num:
    SEQ
      in ? num
      out ! (num + 1)
:

PROC startthread(CHAN INT out!)
  SEQ i = 0 FOR n
    out ! 0
:

PROC endthread(CHAN INT in?, CHAN BYTE out!)
  INITIAL INT total IS 0:
  SEQ
    SEQ i = 0 FOR n
      INT num:
      SEQ
        in ? num
        total := total + num
    out.int(total, 0, out!)
:
  
PROC threads.flow(CHAN BYTE kyb?, scr!, err!)
  [t + 1]CHAN INT channels:
  PAR
    startthread(channels[0]!)
    PAR i = 0 FOR t
      thread(channels[i]?, channels[i + 1]!)
    endthread(channels[t]?, scr!)
:

