
#INCLUDE "course.module"
#INCLUDE "dynproc.module"

PROC testdyn2 (CHAN OF BYTE kyb, scr, err)


  PROC do.sort.cell (VAL INT libhandle, CHAN OF INT in, out)
    [1]CHAN OF ANY t.in RETYPES [in]:
    [1]CHAN OF ANY t.out RETYPES [out]:
    INT res:
    ccsp.run ("test.sort.cell", libhandle, t.in, t.out, res)
  :

  PROC display (CHAN OF INT in, CHAN OF BYTE out)
    INITIAL BOOL running IS TRUE:
    WHILE running
      INT v:
      SEQ
        in ? v
        IF
          v = (-1)
            running := FALSE
          TRUE
            SEQ
              out.int (v, 0, out)
              out ! '*n'
  :

  PROC keyboard (CHAN OF BYTE in, CHAN OF INT out)
    INITIAL BOOL running IS TRUE:
    WHILE running
      BYTE ch:
      SEQ
        in ? ch
        IF
          (ch = 'q') OR (ch = 'Q')
            SEQ
              out ! (-1)
              running := FALSE
          TRUE
            out ! INT ch
  :

  VAL INT num.cells IS 10:

  PROC do.network (VAL INT libhandle, CHAN OF BYTE in, out)
    [num.cells + 1]CHAN OF INT links:
    PAR
      keyboard (in, links[0])
      PAR i = 0 FOR num.cells
        do.sort.cell (libhandle, links[i], links[i+1])
      display (links[num.cells - 1], out)
  :

  INT handle:
  SEQ
    out.string ("about to start*n", 0, scr)
    ccsp.openlib ("./testlib.so", handle)
    IF
      handle = 0
        out.string ("unable to open testlib.so :(*n", 0, scr)
      TRUE
        SEQ
          do.network (handle, kyb, scr)
          ccsp.closelib (handle)
    out.string ("all done*n", 0, scr)
:


