function mse = aamlib_calcPMError(varargin)
% function mse = aamlib_calcPMError(varargin)
%
%
% mse = aamlib_calcPMError('verbose', 1);
%
% Dr. A. I. Hanna (2007)
if mod(length(varargin),2) ~= 0
    % input args have not com in pairs, woe is me
    error(['Arguments to ', mfilename,' must come param/value in pairs.'])
end
files = [];
model = [];
mse = [];
X = [];
pcind = [];
verbose = 1;
for i=1:2:length(varargin)
    switch lower(varargin{i})
        case 'files'
            files = varargin{i+1};
        case 'model'
            model = varargin{i+1};
        case 'pointmodels'
            X = varargin{i+1};
        case 'pcind'
            pcind = varargin{i+1};
        case 'verbose'
            verbose = varargin{i+1};
        otherwise
            error(['Unknown parameter name passed to ', mfilename, '.  Name was ' varargin{i}])
    end
end
if isempty(model)
    [model] = aamio_loadModel;
    if isempty(model)
        return;
    end
    Xm = model.Xm;
    P = model.pca.P;
    if isempty(pcind)
        [P, pcind] = choosePCs(P);
        if isempty(P)
            fprintf('User cancelled operation\n');
            return;
        end
    end
end
if isempty(X)
    if isempty(files)
        [X, files] = aamio_loadPointModels;
        if isempty(X)
            return;
        end
    end
end

if size(Xm,1)~=size(X,1)
    error('Number of points must agree');
end
opts.scaling = 0;
opts.rotation = 1;
opts.translation = 1;
[X] = pcalib_GPA('data',X, 'template', Xm, 'opts', opts);
Xstar = X;
for i=1:size(X,2)
    Xstar(:,i) = Xm + P*(P'*(X(:,i)-Xm));
end
mse = aamlib_pointModelMSE('PM1', X, 'PM2', Xstar);
if verbose
    plotData(Xm, X, 'Original Aligned Shapes');
    plotData(Xm, Xstar, 'Model Approximated Shapes');
end
excel = questdlg('Would you like to save the result to Excel?', ...
                         'Save?', 'Yes', 'No', 'Yes');
if isempty(excel)
    return;
end
if strcmpi(excel, 'yes')

    [filename, pathname] = uiputfile('*.xls', 'Save as...');
    if isequal(filename,0) || isequal(pathname,0)
        disp('User pressed cancel');
        return
    end
    sheet = createExcelFormat(mse, files);
    xlswrite(fullfile(pathname, filename), sheet);
end
return
%%%
%
%%%
function plotData(Xm, X, str)
figure; 
hold on;
plot(Xm(1:2:end), Xm(2:2:end), 'r');
for i=1:size(X,2)
    plot(X(1:2:end, i), X(2:2:end, i), 'b:');
end
axis image xy;
title(str);
return
%%%
%
%%%
function sheet = createExcelFormat(mse, files)
sheet = {};
num_files = length(files);
for i=1:num_files
    [junk, filename] = fileparts(files{i});
    sheet{i,1} = filename;
    sheet{i,2} = mse(i);
end
return
%%%
%
%%% 
function [P, s] = choosePCs(P)
N = size(P,2);
str = cell(N,1);
for i=1:N
    str{i} = num2str(i);
end
[s,v] = listdlg('Name', 'PC Selection', 'PromptString','Select PCs to use in reconstruction:',...
                      'SelectionMode','multiple',...
                      'ListString',str, 'ListSize', [600, 300]);
P = P(:,s); 
return