function V = lyngby_read_volume(filename)

% lyngby_read_volume   - Reads a volume from a recognized file
%
%	function V = lyngby_read_volume(filename)
%
%	Input:  filename  Filename
%
%	Output: V         The volume in a row vector, if recognized filetype
%
%	The filetypes, that are recongnized, are:
%		o ANALYZE	- Widely used in brain imaging
%		o vapet		- From VA PET Medical Center, Minneapolis.
%
%	If the file is an ANALYZE file the filename should have no
%	extension because '.img' and '.hdr' is assumed. 
%	If neither the file <filename> or <filename>'.img' is found
%	the extensions: .Z' and '.gz' will be tried. If a file with
%	such an extension is found the file will be decompressed with
%	the UNIX command 'uncompress' or 'gunzip', respectively. 
%
%	See also LYNGBY, LYNGBY_GETVOLUME, LYNGBY_READANAVOL,
%	         LYNGBY_READVAPETVOL, LYNGBY_READ_ANALYZE.
%
% $Id: lyngby_read_volume.m,v 1.7 2003/05/21 15:57:16 fnielsen Exp $ 


    
    if  ~(length(filename) - findstr(filename, '.gz') - length('gz'))
      filename = filename(1:end-length('.gz'));
    elseif ~(length(filename) - findstr(filename, '.Z') - length('Z'))
      filename = filename(1:end-length('.Z'));
    end

    file = filename;
    filename_hdr = file;

    fid = fopen(file);
    if fid ~= -1
      fclose(fid);
    else
      fid = fopen([file '.img']);
      if fid ~= -1
	fclose(fid);
      else

	% Z Compression

	fid = fopen([file '.Z']);
	if fid ~= -1
	  fclose(fid);
	  s = sprintf('uncompress -c %s > temp.vapet', file);
	  status = unix(s);
	  if status
	    error(sprintf('Could not perform %s', s));
	  end
	  file = 'temp.vapet';
	  filename_hdr = 'temp.vapet';
	else
	  fid = fopen([file '.img.Z']);
	  if fid~= -1
	    fclose(fid);
	    s = sprintf('uncompress -c %s.img.Z > temp.img', file);
	    status = unix(s);
	    if status
	      error(sprintf('Could not perform %s', s));
	    end
	    file = 'temp';
	  else
	    % gzip compression

	    fid = fopen([file '.gz']);
	    if fid~= -1
	      fclose(fid);
	      s = sprintf('gunzip -c %s > temp.vapet', file);
	      status = unix(s);
	      if status
		error(sprintf('Could not perform %s', s));
	      end
	      file = 'temp.vapet';
	    else
	      fid = fopen([file '.img.gz']);
	      if fid~= -1
		fclose(fid);
		s = sprintf('gunzip -c %s.img.gz > temp.img', file);
		status = unix(s);
		if status
		  error(sprintf('Could not perform %s', s));
		end
		file = 'temp';
	      end
	    end
	  end
	end
      end
    end

    % Try ANALYZE first
    [siz, vdim, datatype] = lyngby_readanahdr(filename_hdr);
    if ~isempty(siz), 
      V = lyngby_readanavol(file, siz, datatype);
    else
      % else Try VAPET
      
      [siz, vdim, datatype] = lyngby_readvapethdr(filename_hdr);
      if ~isempty(siz),
	V = lyngby_readvapetvol(file, siz, datatype);
      else
	error(sprintf('Could not open file: %s', filename_hdr));
      end
    end












