function lyngby_write_volumes(M, varargin)

% lyngby_write_volumes - Write volumes to file
%
%       lyngby_write_volumes(M, 'PropertyName', 'PropertyValue') 
%
%       Input:    M         'mat' structure
% 
%       Property: Datatype  [ {float32} | uchar | uint8 | int16 ]
%                 VolMask   'Vol' structure with volume mask
%
%       Writes ANALYZE files from the volumes contained in the M 'mat'
%       structure.
%
%       See also LYNGBY, LYNGBY_READ_VOLUMES.
%
% $Id: lyngby_write_volumes.m,v 1.2 2003/05/22 15:10:10 fnielsen Exp $


    % Check input arguments
    if nargin < 1
      error('Too few input arguments')
    end
    if ~isstruct(M);
      error('First input argument should be a structure')
    end
    
    
    % Default values
    datatype  = 'float32';
    endian    = 'big';
    filenames = '';
    scale     = '';
    Vmask     = []; 
    
    
    % Read properties
    for n = 1:2:length(varargin)
      arg = lower(varargin{n});

      if strcmp(arg, 'datatype') 
      	arg = varargin{n+1};
	if isstr(arg) & ismember(arg, { 'uchar' 'uint8', 'int16', ...
	      'float32' 'float64' }) 
	  datatype = arg;
	else
	  error('Argument with ''Datatype'' should be a string');
	end

      elseif strcmp(arg, 'volmask') 
      	arg = varargin{n+1};
	if isstruct(arg) 
	  Vmask = arg;
	else
	  error('Argument with ''VolMask'' should be a structure');
	end
	
      else
	error(sprintf('Invalid property: %s', arg));
      end
    end


    % Generate filenames
    if isempty(filenames)
      if iscellstr(M.rows)
	% Filenames from row fields of 'mat' structure
	filenames = M.rows;
      else
	% Generate default filenames
	for n = 1:size(M.matrix,1)
	  filenames{n} = sprintf('volume%d', n);
	end
      end
    end
    
    
    % Set 'scale' depending on datatype
    if ismember(datatype, { 'uchar' 'uint8' 'int16' })
      scale = 'on';
    else
      scale = 'off';
    end
      
    
    % Iterate over volumes
    for n = 1:size(M.matrix,1)
      if ~isempty(Vmask)
	% Apply a voxel mask
	origin   = Vmask.origin;
	voxelDim = Vmask.voxelSize;
	siz      = size(Vmask.volume); 
	v = zeros(1, length(Vmask.volume(:)));
	v(find(Vmask.volume(:))) = M.matrix(n,:);
      else
	error('Not implement yet - use VolMask')
      end
 
      lyngby_write_ana(filenames{n}, v, siz, 'datatype', datatype, ...
	  'endian', endian, 'origin', origin, 'scale', scale, ...
	  'voxeldim', voxelDim);
      
    end







