function V = lyngby_readanavol(file, siz, datatype)

% lyngby_readanavol    - Reads an ANALYZE img file
%
%       function V = lyngby_readanavol(file, siz, datatype)
%
%       Input:  file       Filename, with or without the '.img' of
%                          '.hdr' extension
%               siz        Volume dimension. Obtained from
%                          lyngby_readanahdr
%               datatype   String with precision, for example 'uint16'
%                          or 'float32'. Obtained from
%                          lyngby_readanahdr
%
%       Output:	V	   The volume in a row vector
%
%       This function reads a volume from an ANALYZE file. It works
%       together with lyngby_readanahdr, which obtains the 'siz' and
%       'datatype' parameter.
%
%       See also: lyngby_readanahdr, fread

% cvs : $Id: lyngby_readanavol.m,v 1.7 1998/03/24 10:59:12 fnielsen Exp $
%       $Revision: 1.7 $

    if length(siz) ~= 3
      error(sprintf(['The length of the ''siz'' argument should be 3.\n' ...
	    'It was %dx%d'], size(siz)));
    end

    
    
    filename = [ file '.img' ];
    fid = fopen(filename, 'rb', 'ieee-be');
    if fid < 0 
      index = findstr(file, '.hdr');
      if ~isempty(index) & index == (length(file) - 3)
	filename = [file(1:index) 'img'];
	fid = fopen(filename ,'rb', 'ieee-be');
	if fid < 0
	  error(sprintf('Files could not be opened: %s, %s', ...
	      [ file '.img' ], file, filename));
	end
      else
	filename = file;
	fid = fopen(filename, 'rb', 'ieee-be');
	if fid < 0
	  error(sprintf('Files could not be opened: %s, %s', ...
	      [ file '.img' ], file));
	end
      end
    end

    [V, count] = fread(fid, prod(siz), datatype);
    V = V';
    if count ~= prod(siz),
      error(sprintf([ ...
	    'Could not read all bytes from: %s\n' ...
	    'Read: %d, Requested: %dx%dx%d = %d'], ...
	  filename, count, siz, prod(siz))); 
    end  

    fclose(fid);































