%begin
%include "inc:fs.imp"
%include "inc:util.imp"
%ownbytearray b(0:540)=0(*)
%integer rs,rp,lp,i,j,k
%integer expect=0
  %integerfn bit(%integer word)
  %integer i=0
    %cycle
      %result=i %if 1<<i&word#0
      i = i+1
    %repeat
  %end
  %routine rec(%integer port)
  %integer skew=0,i
    j = etherread(port,b(0),256)
    %unless port=0 %start
      printstring("Port "); phex2(port); printsymbol(':'); %return
    %finish
    %returnunless port=0
    %if b(0)=0 %start
      printstring("Channel "); phex2(b(1)); space
      j = j-2; skew = 2
    %finish
    printstring("From "); phex2(b(i+skew)) %for i=0,1,5
    printsymbol(':')
    j = j-6; skew = skew+6
    b(i) = b(i+skew) %for i=0,1,j-1
  %end
  %routine trans(%integer port)
    etherwrite(port,b(0),j)
    expect = expecT!1<<port
  %end
printstring("O to Open, S to Send, anything else to stop"); newline
%cycle
  i = testsymbol; i = i!32 %if i!31=95
  %if i='`' %start
    prompt("Station address:"); rhex(i)
    twait; ethc = 16_07 {ssa}; twait; ethd = i
    twait; ethc = 2; twait
  %elseif i='o' 
    prompt("Open port:"); rhex(lp)
    prompt("To remote address (sspp):"); rhex(i)
    etheropen(lp,i)
  %elseif i='s' 
    prompt("Send on port:"); rhex(lp); readsymbol(i)
    prompt("Data (_ escapes to hex):"); j = 0
    %cycle
      readsymbol(i); %exitif i=nl
      rhex(i) %if i='_' %and nextsymbol#'_'
      b(j) = i; j = j+1
    %repeat
    trans(lp)
  %elseif dtx#0 
    rec(bit(dtx))
    %for i=0,1,j-1 %cycle
      k = b(i)
      %if ' '<=k<=126 %start
        printsymbol(k); printsymbol('_') %if k='_'
      %else
        printsymbol('_'); phex2(k)
      %finish
    %repeat
    newline
  %elseif ack&expect#0
    i = bit(ack&expect); j = 1<<i
    expect = expect-j
    printstring("Port "); phex2(i); printsymbol(':')
    %if nak&j#0 %start
      nak = nak-j; printstring(" Nak"); newline
    %else
      printstring(" Ack"); newline
    %finish
  %else
    %stopif i>=' '
  %finish
%repeat
%endofprogram
