%begin {SUBTRACT: Print brief details of differences between 2 (binary) files.

%option "-nocheck-nodiag"
%include "inc:util.imp"

%string(31)file1,file2
%integer start1,start2,size1,size2,dif
%bytename b1,b2

%integerfn difpos(%bytename a,b,%integer n)
%integer pos=0
  %cycle
    %result=-1 %if n<=0; n = n-1
    %result = pos %unless a=b; a == a[1]; b == b[1]; pos = pos+1
  %repeat
%end

defineparam("File1",file1,pamnodefault)
defineparam("File2",file2,pamnodefault)
processparameters(cliparam)
connectfile(file1,0,start1,size1)
connectfile(file2,0,start2,size2)
b1 == byte(start1)
b2 == byte(start2)
dif = size1-size2
%if dif=0 %start
  printstring(file1;" and ";file2;" are ")
  dif = difpos(b1,b2,size1)
  %if dif<0 %start
    printstring("identical")
  %else
    printstring("the same size,")
    newline; printstring("but differ at "); phex(dif)
  %finish
%elseif dif>0
  printstring(file1;" is "); phex(dif)
  printstring(" bytes longer than ";file2)
  printsymbol(','); newline
  dif = difpos(b1,b2,size2)
  %if dif<0 %or difpos(b1[size1-size2],b2,size2)<0 %start
    printstring("they are almost identical")
  %else
    printstring("they differ at "); phex(dif)
  %finish
%else
  printstring(file1;" is "); phex(-dif)
  printstring(" bytes shorter than ";file2)
  printsymbol(','); newline
  dif = difpos(b1,b2,size1)
  %if dif<0 %or difpos(b1,b2[size2-size1],size1)<0 %start
    printstring("they are almost identical")
  %else
    printstring("they differ at "); phex(dif)
  %finish
%finish
newline

%end
