%DISNORM Normalization of a dissimilarity matrix
%
% 	V = disnorm(D,OPT)
%   F = E*V
%
% INPUT
%   D 	 NxN dissimilarity matrix or dataset, which sets the norm
%   E    Matrix to be normalized
% 	OPT  'max' : maximum dissimilarity is set to 1 by global rescaling
% 		   'mean': average dissimilarity is set to 1 by global rescaling (default)
%
% OUTPUT
%   V 	Fixed mapping
%   F  	Normalized dissimilarity data
%
% DEFAULT
%   OPT = 'mean'
%

% Copyright: Elzbieta Pekalska, ela.pekalska@googlemail.com
% Faculty EWI, Delft University of Technology and
% School of Computer Science, University of Manchester


function V = disnorm(D,opt)
if nargin < 2,
	opt = 'mean';
end

if nargin == 0 | isempty(D)
  V = mapping(mfilename,{opt});
  V = setname(V,'Disnorm');
  return
end

if ~isdataset(D)
	D = dataset(D,1);
	D = setfeatlab(D,getlabels(D));
end

%DEFINE mapping
if isstr(opt)
	discheck(D);
	opt = lower(opt);
	if strcmp(opt,'mean')
		n = size(D,1);
		m = sum(sum(+D))/(n*(n-1));
	elseif strcmp(opt,'max')
		m = max(D(:));
	else
		error('Wrong OPT.')
	end
	if nargout > 1
		D = D./m;
	end	
    V = mapping(mfilename,'trained',{m},[],size(D,2),size(D,2));
	return;
end


% APPLY mapping
if ismapping(opt)
	opt = getdata(opt,1);
	V = D./opt;
	return;
end			
	
