function R = lyngby_cons_main(X, varargin)

% lyngby_cons_main     - Consensus modeling
%
%       function R = lyngby_cons_main(X, ...
%          'PropertyName', 'PropertyValue')
%
%       Input:    X         Matrix. 
%
%       Property: Scaling   [ {HistEq} | None ] 
%
%       Output:	  R.mean    Mean across summary images
%                 R.std     Standard desviation across summary images 
%                 R.labels  Labels for the summary images included.
%                 R.svdU    Singular model batches
%                 R.svdL    Singular values
%                 R.svdV    Eigenimages 
%
%       This function performs 'consensus modeling' were the consensus
%       (mean) of several summary images are computed.
%
%       If histogram equalization scaling is applied then it is
%       performed with respect to the first volume in 'X', ie, the
%       histogram of the other volumes X(2:end,:) are converted to
%       match the first volume X(1,:). 
%
%       See also LYNGBY, LYNGBY_HISTEQ, LYNGBY_CONS_INIT.
%
% $Id: lyngby_cons_main.m,v 1.3 2002/05/08 15:14:01 fnielsen Exp $


    % Check arguments
    if nargin < 1
      error('Wrong number of arguments')
    end			
    if size(X,1) < 1
      error('X did not contain any volumes')
    end
    
    % Default values
    scaling = 'histeq';
    labels  = {};
    
    % Parse properties
    n = 1;
    while n < nargin-1
      arg = lower(varargin{n}); 

      if strcmp(arg, 'labels')
	n = n + 1;
	arg = varargin{n};
	if iscellstr(arg) 
	  labels = arg;
	else
	  error('The argument with ''Labels'' should be cell strings');
	end

      elseif strcmp(arg, 'scaling')
	n = n + 1;
	arg = lower(varargin{n});
	if isstr(arg) & ( strcmp(arg, 'histeq') | strcmp(arg, 'none') )
	  scaling = arg;
	else
	  error('The argument with ''Scaling'' should be a string');
	end
	
      else
	error('Invalid property');
      end
      n = n + 1;
    end

    
    [rX, cX] = size(X);

    if strcmp(scaling, 'histeq');
      X = lyngby_histeq(X, 'Reference', X(1,:));
    elseif strcmp(scaling, 'none');
      % Do nothing
    else 
      error('Internal error');
    end

    R.mean   = mean(X);
    R.std    = std(X);
    R.labels = labels;

    [U,L,V] = lyngby_svd(X);
    R.svdU = U;
    R.svdL = L;
    R.svdV = V';

