function x=hipsread(ImgNam,RowList,ColList,SeqIdx)
% HIPSREAD  Load a HIPS-2 image into a Matlab matrix.
%       x=hipsread(ImgNam,RowList,ColList)
%       x=hipsread(ImgNam,RowList,ColList,SequenceIndex)
%       
%       Example: load subimage from pixel 50 to 100 in vertical direction and
%       40 to 90 in horizontal direction 
%         HipsFile='/home/signal/tranden/datafiler/textures/brodatz/D36.hips';
%         D36=hipsread(HipsFile,50:100,40:90);

MaxNumReTry=10;

NumReTry=0;
while (NumReTry>=0) & (NumReTry<MaxNumReTry)
  % Parameter setup
  TmpFileName=tempnam;
  if exist('RowList')~=1, RowList=[]; end
  if exist('ColList')~=1, ColList=[]; end
  if exist('SeqIdx') ~=1, SeqIdx=0;   end
  HSize='hsize';
  [dummy,rows]=unix(sprintf('%s -rows %s',HSize,ImgNam)); rows=str2num(rows);
  [dummy,cols]=unix(sprintf('%s -cols %s',HSize,ImgNam)); cols=str2num(cols);
  if isempty(RowList), RowList=0:rows-1; end
  if isempty(ColList), ColList=0:cols-1; end
  % Extract dataset into temporary file
  subseq=sprintf('subseq -f %d %d',SeqIdx,SeqIdx);
  extract=sprintf('extract -p %d %d -s %d %d',min(RowList),min(ColList), ...
    max(RowList)-min(RowList)+1,max(ColList)-min(ColList)+1);
  eval(sprintf('!%s %s | htof | %s | stripheader > %s\n',...
    subseq,ImgNam,extract,TmpFileName));
  % Read the image into Matlab
  fid=fopen(TmpFileName,'r');
  if fid~=-1
    x=fread(fid,[max(ColList)-min(ColList)+1 max(RowList)-min(RowList)+1],...
      'float')';
    fclose(fid);
    if isempty(x) & ~(isempty(ColList) | isempty(RowList))
      NumReTry=NumReTry+1;
    else
      NumReTry=-1;
    end
  else
    fprintf(2,'Error reading HIPS file, will retry in 10 seconds\n');
    NumReTry=NumReTry+1;
  end
  if NumReTry==MaxNumReTry
    error('Reading HIPS image');
  elseif NumReTry~=-1
    pause(10);
  end
  % Clean up in the temporary files
  eval(['!rm -f ' TmpFileName]);
end
 

% Subsample
x=x(RowList-min(RowList)+1,ColList-min(ColList)+1);