%begin; !RL86: Convert 8086.IOB file to Motorola format PROM file

%include "inc:util.imp"
%constinteger setcode=1,setdata=2,setloc=3,append=4,endfile=10

%integer codeloc=0,dataloc=0
%integername loc == codeloc

%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

%string(255)in,out=""
%integer i,k

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

  defineparam("IOB file",in,pamnodefault)
  defineparam("PROM file",out,pamnewgroup)
  processparameters(cliparam)
  out = in %if out=""
  selectinput(1); openinput(1,in.".iob")
  selectoutput(1); openoutput(1,out.".rom")
  %cycle
    readsymbol(k)
    %if k=append %start
      readsymbol(k); readsymbol(i); i = i<<8+k
      %while i>0 %cycle
        i = i-1; readsymbol(k); dump(k)
      %repeat
    %elseif k=setloc
      readsymbol(k); readsymbol(i); loc = i<<8+k
    %elseif k=setcode
      loc == codeloc
    %elseif k=setdata
      loc == dataloc
    %else
      %exitif k=endfile
      %signal 15,,k,"Invalid code directive"
    %finish
  %repeat
  dump(-1)

%endofprogram
