begin ; !FROMBIN: Convert binary file to Motorola object

include  "inc:util.imp"

owninteger  loc=0

routine  dump(integer  byte)
constinteger  max=16
ownintegerarray  buf(1:max)
owninteger  open=0,nextloc,p,checksum

  routine  put(integer  byte)
    phex2(byte)
    checksum=checksum+byte
  end 

  routine  flush
  integer  i
    printstring("S1"); checksum=0
    put(p+3); put((nextloc-p)>>8); put((nextloc-p)&255)
    put(buf(i)) for  i=1,1,p
    phex2(¬checksum)
    newline
    p=0
  end 

  if  open=0 start 
    open=1
    printstring("S00600004844521B"); newline
    nextloc=loc; p=0
  finish 

  if  byte<0 start ; ! Closing
    flush unless  p=0
    printstring("S9030000FC"); newline
    return 
  finish 

  flush if  p=max or  nextloc#loc
  loc=loc+1; nextloc=loc
  p=p+1; buf(p)=byte
end 

routine  frombin
integer  sym
  onevent  3,9 start 
    dump(-1)
    stop 
  finish 
  cycle 
    readsymbol(sym); dump(sym)
  repeat 
end 

string (255)parm,in,out

  onevent  3,4,9 start 
    selectoutput(0)
    printstring(event_message); newline
    stop 
  finish 

  parm = cliparam
  in = parm and  out = parm unless  parm -> in.("/").out
  selectinput(1); openinput(1,in)
  selectoutput(1); openoutput(1,out)
  frombin

endofprogram