function [Xm, P, b, pcaDat] = aam_pca(AAM, indices, filenames,FractionPCs, meanshape, in_context_flag, lda_shape_flag)
%function [Xm, P, b, pcaDat] = aam_pca(AAM, indices, filenames,FractionPCs, meanshape, in_context_flag, lda_shape_flag)
%
% Dr. A. I. Hanna (2006)
if nargin<4
    FractionPCs=0.95;
end
%v = 0.95;
v = FractionPCs;
% if(nargin < 1) error('No data defined for PCA'); end
elements = get(AAM, 'elements');
activeElements = get(AAM, 'activeElements');
indx = 1;
pmt = get(AAM, 'PointModelTemplate');
templatename = get(pmt, 'name');
templatename = templatename(1:length(templatename)-9);
modelDirec=get(AAM,'modelDirec');
X = [];
for e =1:length(elements)
    name = get(elements{e}, 'imagefilename');
    %name = filenames{e};
    name = name(1:length(name)-4);
    fprintf('loading %s\n', name);
    aligned_filename = fullfile(modelDirec,[name,'_aligned.mat']);
    if exist(aligned_filename)
        pts = load(aligned_filename);
        pts = pts.pts;
        pts = reshape(pts, 2, length(pts)/2);
        if in_context_flag
            ind = setdiff(1:size(pts,2), indices);
            pts(:, ind) = meanshape(:, ind);
        else
            pts = pts(:, indices);
        end
        X(:, indx) = pts(:);
        indx = indx+1;
    end
end
if isempty(X)
    uiwait(msgbox('There are not point models to process. Exiting.','No Point Models','modal'));
    Xm = [];
    P = [];
    b = [];
    pcaDat = [];
    return;
else
    [Xm, P, b, pcaDat] = principle_component_analysis(X, v);
end
return;
