function [Nf info]=dalconvert(fn,ofn,remove)
% dalraw2img Convert dalsa format to img format. 
% usage:: [Nf info]=dalraw2img(fn,ofn,remove)
%
% Convert dalsa format to img format. 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. Return values Nf:
%   1 ==> sucess! bin delete;
%   2 ==> sucess! bin retained;
% -99 ==> File does not exist!
% -98 ==> File length not multiple of imgsize!
% or Nf ==> Number of frames if no conversion needed.
% dalinfo structure is returned as info

% revision history:
% 09/22/96 Mark D. Shattuck <mds>   dalraw2img.m
% 10/30/96 mds add remove option
% 12/24/00 mds add dalinfo return
% 03/12/01 mds add return diagnostics
% 11/12/09 mds create dalconvert.m

Nx=260;
Ny=260;
NI=4;  % number of interlace channels
head=4;
tail=44;
NIMG=512;

imgsize=Nx*Ny+head+tail;
bufsize=imgsize*NIMG;

if (nargin==1)
  ifn=sprintf('%s.bin',fn);
  ofn=sprintf('%s.img',fn);
  remove=0;
elseif(nargin==2)
  if(ischar(ofn))
    remove=0;
  else
    remove=ofn;
    ifn=sprintf('%s.bin',fn);
    ofn=sprintf('%s.img',fn);
  end    
end

fdesc=dir(ofn);
if (~isempty(fdesc))
  [Nf info]=dalinfo(ofn);
  if(info.idsize==2)
    return
  end
end

fdesc=dir(ifn);
if (isempty(fdesc))
    info='Dalsa:NotExist';
    warning(info,'File does not exist!');
    Nf=-99;
    return
end

N=fdesc.bytes/imgsize;

if (N~=fix(N))
    info='Dalsa:ImgSizeProb';
    warning(info,'File length not multiple of imgsize!');
    Nf=-98;
    return
end

Nbuf=fix(fdesc.bytes/bufsize);

ht=zeros(head+tail,N);

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

Nc=length(sprintf('%d',Nbuf));
fprintf(1,'converting (bin-->img)...');
fmt=sprintf('[%%0%dd/%%0%dd]',Nc,Nc);
fprintf(1,fmt,0,Nbuf);
nn=0;
for n=1:Nbuf
    buf=reshape(fread(ifid,bufsize,'*uint8'),imgsize,NIMG);
    ht(1:head+tail,nn+(1:NIMG))=buf([1:head (1-tail:0)+end],:);
    nn=nn+NIMG;
    buf=buf((head+1):(end-tail),:);
    buf=reshape(permute(reshape(buf,NI,Nx/NI,Ny,NIMG),[2 1 3 4]),Nx,Ny,NIMG);
    fwrite(ofid,buf,'uint8');
    backspace(1,fmt,n,Nbuf);
    fprintf(1,fmt,n,Nbuf);
end
fprintf(1,'  Remainder...');
buf=reshape(fread(ifid,bufsize,'*uint8'),imgsize,NRimg);
ht(1:head+tail,nn+(1:NRimg))=buf([1:head (1-tail:0)+end],:);
buf=buf((head+1):(end-tail),:);
buf=reshape(permute(reshape(buf,NI,Nx/NI,Ny,NRimg),[2 1 3 4]),Nx,Ny,NRimg);
fwrite(ofid,buf,'uint8');
fwrite(ofid,ht,'uint8');
fwrite(ofid,hex2dec('fee3'),'uint16');  %File format magic number 0xfee3 is current nothing for old format
fprintf(1,'Done.\n');

fclose(ifid);
fclose(ofid);

[Nf info]=dalinfo(ofn);

if (remove==1)
  fprintf(1,'deleting bin file...');
  delete(ifn);
  fprintf(1,'Done.\n');
  Nf=1;
else
  fprintf('retaining bin file.\n');
  Nf=2;
end


