%begin; !BSEND: Convert binary file to Motorola object and send to Stag PPZ

%include "inc:util.imp"

%owninteger defaultloc=16_100800      {* Start address for program *}

%integer loc
%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("S2"); checksum=0
    put(p+4); put((nextloc-p)>>16); 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

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


%ownstring(255) infile,outfilename,ans
%owninteger     startaddr


  infile = cliparam
  %if exists(infile) %andc
    length(infile) > 3 %and charno(infile,length(infile)-3) = 46 %start 
      outfilename = substring(infile,0,length(infile)-4)
    %else
      outfilename = infile
    %finish
    outfilename = outfilename.".dat"
    %if length(infile) > 0 %start
      printline("Input from file - ".infile)
      printline("Output to file  - ".outfilename)
      printstring("Alter program start address (Y/N) ? (default = ")
      phex(defaultloc)
      printstring(")")
      readline(ans)
      %if ans = "y" %or ans = "Y" %start
        printstring("Enter program start address ")
        rhex(loc)
      %else
        loc = defaultloc
      %finish
      printstring("Using start address of ")
      phex(loc)
      newlines(1)
      printline("Starting Conversion")
      selectinput(1); openinput(1,infile)
      openoutput(1,outfilename)
      selectoutput(1); set terminalmode(nopage);
      frombin
  %else
    printline("No such input file")
  %finish

%endofprogram
