function [siz, datatype, dim] = lyngby_readxpihdr(filename);

% lyngby_readxpihdr   - Read header from EC flexible format
% 
%        [siz, datatype, dim] = lyngby_readxpihdr(filename);
%
%        Input:  filename   With or without extension (.xpi) 
% 
%        Output: siz        Number of voxels and time step 
%                           4 element vector
%                datatype   String identifying the date type
%                dim        Voxel dimensions and sampleinterval
%                           4 element vector
%
%        See also: lyngby_readxpivol

%        $Id: lyngby_readxpihdr.m,v 1.3 1997/07/22 16:01:57 fnielsen Exp $
%        $Revision: 1.3 $

    
    filenamex = filename;
    fid = fopen(filenamex, 'rb');
    if fid < 0
      filenamex = [ filename '.xpi' ];
      fid = fopen(filenamex, 'rb');
      if fid < 0, 
	dim = []; datatype = ''; siz = []; % File not found!
	return
	% error(sprintf('Neither %s or %s found', filename, filenamex))
	if fid > 0,
	  fclose(fid);
	end
	return
      end
    end

    % Find end of header
    searchstr = '#_End_of_Header.';
    
    fid = fopen(filenamex);
    
      endofh = lyngby_filefind(filenamex, searchstr) + max(size(searchstr))-1;
      if ~endofh
	dim = []; datatype = ''; siz = []; % File not found!
	return
	%error(sprintf([ 'The file %s is corrupted or not an xprime ' ...
	%      'file (%s not found)'], filenamex, searchstr));
      end
      
      fseek(fid, 0, -1);
      filehead = setstr(fread(fid, endofh, 'char')');
      
      px = findstr(filehead, 'Data_Xsize') - 1;
      py = findstr(filehead, 'Data_Ysize') - 1;
      pDim = findstr(filehead, 'Data_Size(Increment)') -1;
      pTe = findstr(filehead, 'MR_Te_(sec)') -1;
      pformat = findstr(filehead, 'Data_Type : ');
      nframes = size(px,2);
  
    fclose(fid);  
  
    for f=1:nframes
      xdim = sscanf(filehead(px(f):px(f)+50), '%*s : %i\n'); 
      ydim = sscanf(filehead(py(f):px(f)+50), '%*s : %i\n');
      siz = [xdim ydim 1 nframes];
    
      vdim = sscanf(filehead(pDim(f):pDim(f)+100), ...
	  '%*s : %f %f %f')'; 
      tdim = sscanf(filehead(pTe(f):pTe(f)+50), '%*s : %f\n');
      dim = [vdim tdim];
      
      tmp = filehead(pformat(f)+13:pformat(f)+40);
      if findstr(tmp, 'Integer 8 Bit Unsigned') 
	datatype='uchar';
      elseif findstr(tmp, 'Integer 16 Bit Signed')
	datatype='short';
      elseif findstr(tmp, 'Integer 32 Bit Signed')
	datatype='long';
      elseif findstr(tmp, 'FloatingPointReal 64 Bit') 
	datatype='float64';
      elseif findstr(tmp, 'FloatingPointReal 32 Bit') 
	datatype='float32';    
      elseif findstr(tmp, 'Complex 64 Bit') 
	datatype='float32';    
	is_cmplx = 1;
      else
	datatype='unknown';
	fprintf('Warning: %s\n', datatype);
      end
    end
    
    
    










