function ALLX = normalise_variance(ALLX, norm_opt)
% function ALLX = normalise_variance(ALLX, norm_opt)
%
% Takes a cell structure where each cell is a NxM matrix, where each column
% is an observation and each row is a variable, i.e. each column of the matrix
% corresponds to 1 particular shape
%
% norm_opt - if norm_opt is 0 (default) then the shapes are normalised to the mean
% variance amongst them, if opt = 1 then the shapes will be normalised to
% unit variance.
%
% Dr. A. I. Hanna (2007)
if nargin<2
    norm_opt = 0;
end
fprintf('\n\nVariances BEFORE normalization\n');
fprintf('------------------------------\n');
[variances, meanshapes] = calculateVariances(ALLX);
switch norm_opt
    case 0
        mvar = mean(variances);
    case 1
        mvar = 1;
    otherwise
        fprintf('Invalid value for norm_opt\n');
end
for j=1:length(ALLX)
    X = ALLX{j};
    X = X./sqrt(variances(j));
    X = X.*sqrt(mvar);
    ALLX{j} = X;
end
fprintf('\n\nVariances AFTER normalization\n');
fprintf('------------------------------\n');
[variances, meanshapes] = calculateVariances(ALLX);
return;
%%%
%
%%%
function [variances, meanshapes] = calculateVariances(ALLX)
num_shapes = length(ALLX);
meanshapes = cell(num_shapes,1);
variances = zeros(num_shapes,1);
for j=1:num_shapes
    X = ALLX{j};
    [variance, meanshape] = calculatePointModelSetVariance(X);
    meanshapes{j} = meanshape;
    variances(j) = variance;
    fprintf('\t- Shape %d, variance: %f\n', j, variance);
end
return