function [nn,bb]=himage4(ifn,N,Ni)
% convert dalsa format to img format: dalraw2img(fn) fn=basename fn.bin
% is raw data. fn.img is processed data.  This is 1-1 conversion fn.bin 
% can be deleted once fn.img is created and checked.
MINPIXVAL=0;
MAXPIXVAL=255;
Nx=260;
Ny=260;

NIMG=128;

imgsize=Nx*Ny;
bufsize=imgsize*NIMG;


fdesc=dir(ifn);
if (isempty(fdesc.bytes))
    disp('File does not exist!');
    return
end

if (nargin==1)
  Ni=1;
  N=fdesc.bytes/imgsize;
elseif (nargin==2)
  Ni=1;
end

if isempty(N)
  N=fdesc.bytes/imgsize-Ni-1;
end

if (N~=fix(N))
    disp('File length not multiple of imgsize');
    return
end

Nbuf=fix(N/NIMG);

NRimg=N-Nbuf*NIMG;
ifid=fopen(ifn,'r');

Nc=length(sprintf('%d',Nbuf));
fmt=sprintf('[%%0%dd/%%0%dd]',Nc,Nc);
fprintf('processing...');
fprintf(1,fmt,0,Nbuf);
bb=(MINPIXVAL:MAXPIXVAL);
nn=zeros(Nx,Ny,length(bb));
fseek(ifid,(Ni-1)*imgsize,'bof');
inx=(1:(Nx*Ny))';
for n=1:Nbuf
  tmp=Nx*Ny*double(reshape(fread(ifid,bufsize,'*uint8'),Nx*Ny,NIMG));
  for k=1:NIMG
    nn(inx+tmp(:,k))=nn(inx+tmp(:,k))+1;
  end
  backspace(1,fmt,n,Nbuf);
  fprintf(1,fmt,n,Nbuf);
end
fprintf(1,'  Remainder...');
tmp=Nx*Ny*double(reshape(fread(ifid,Nx*Ny*NRimg,'*uint8'),Nx*Ny,NRimg));
for k=1:NRimg
  nn(inx+tmp(:,k))=nn(inx+tmp(:,k))+1;
end
fprintf(1,'Done.\n');
fclose(ifid);
