function BuildAugmentedPointModels
% function BuildAugmentedPointModels
%
%
% Dr. A. I. Hanna (2007)

% This is the default directory where we keep general project data
augmentdir = [pwd, filesep, 'Data'];

% Get the augmentation information
augmentinfoname = [augmentdir filesep, 'augment_info.mat'];
if ~exist(augmentinfoname, 'file');
    fprintf('There is no augmentation information file in <project_dir>/Data directory\n');
    return;
end

% We need the template from which to build the point models.
templatename = getTemplateName;
if isempty(templatename)
    fprintf('User clicked cancel, aborting build.\n');
    return;
end

% if a directory of point models doesn't exist for this template, create
% it.
pmdir = [pwd, filesep, 'PointModels', filesep, templatename];
if ~exist(pmdir, 'dir')
    mkdir(pmdir);
end

% This is where all the data is stored. 
augment_info = load(augmentinfoname);
augment_info = augment_info.augment_info;
if ~isfield(augment_info, 'ordered_pmfiles')
    str = sprintf('You have not ordered your Point Model files, please do this first.');
    uiwait(msgbox(str,'Order Point Models First','modal'));
    return;
end

[ordered_pmfiles, N] = getAugmentedOrderedPMFiles(augmentdir);
ALLP = {};
dim = 2;
if isProject3D(pwd)
    dim = 3;
end
opts.scaling = 0;
opts.rotation = 1;
opts.translation = 1;
[option, customscalingflag] = BuildAugmentedPointModelsDialog;
if isempty(option)
    return;
end
if option==3
    opts.scaling = 1;
end
all_names = {};
for p=1:length(augment_info)
    ainfo = augment_info(p);
    [projdir, projname, ext, vers] = fileparts(ainfo.projectdir);
    P = [];
    if isfield(ainfo, 'scale')
        scale = ainfo.scale;
    else
        scale = 1;
    end
    if isempty(scale)
        scale = 1;
    end
    pmfiles = ordered_pmfiles{p};
    names = {ainfo.pmfiles.filename};
    waitbar_h = waitbar(0, sprintf('Building augmented PM files\nfor %s...', projname));
    set(findall(waitbar_h,'type','text'),'Interpreter','none');
    for i=1:N
        waitbar(i/N, waitbar_h);
        indx = find(strcmp(pmfiles{i}, names));
        if ~isempty(indx)
            fprintf('Build with filename %s\n', pmfiles{i});
            if customscalingflag==1
                P(:,end+1) = scalePts(ainfo.pmfiles(indx).pts, scale, dim);
            else
             	P(:,end+1) = ainfo.pmfiles(indx).pts;
            end
            all_names = cat(1, all_names, pmfiles{i});
        end
    end
    close(waitbar_h);
    [PAligned, template] = pcalib_GPA('data',P, 'opts', opts);
    ALLP{end+1} = PAligned;
end
% Center all the shapes around (0,0) by subtracting off the mean xy value
% of the mean shape.
for j=1:length(ALLP)
    ALLP{j} = centerPointModels(ALLP{j});
end

if option ==2
	% this option sets the variance of the groups to the mean variance of
	% all the groups.
    ALLP = normalise_variance(ALLP,0);
    % this one sets the variance of each group to unity
    % ALLP = normalise_variance(ALLP,1);
end
[variances, meanshapes] = calculateVariances(ALLP)
showdata(ALLP, ordered_pmfiles);
pmnames = ordered_pmfiles{1};
for i=1:N
    allpts = [];
    pmname = [pmnames{i}];
    for p=1:length(ALLP)
        pts = ALLP{p}(:,i);
        pts = reshape(pts, 2, length(pts)/2);
        allpts = [allpts, pts];
    end
    pts = allpts(:);
    save([pmdir, filesep, pmname], 'pts');
end
%%%
%
%%%
function pts = scalePts(pts, scale, dim)
%figure(1); clf; hold on;
pts = reshape(pts, dim, length(pts)/dim);
%plot(pts(1,:), pts(2,:), '.-')
mu = mean(pts, 2);
pts = pts - mu*ones(1, size(pts,2));
pts = pts.*scale;
pts = pts + mu*ones(1, size(pts,2));
%plot(pts(1,:), pts(2,:), 'r.-')
pts = pts(:);
return
%%%%%%
%
%
%
%%%%%%
function showdata(ALLP, all_names)
for j=1:length(ALLP)
    X = ALLP{j};
    prj_names = all_names{j};
    figh = figure; hold on;
    shapeuimenu = uicontextmenu('Parent', figh);
    uimenu(shapeuimenu,'Label','Name','callback',{@showShapeName});




    for i=1:size(X,2)
        x = X(:,i);
        x = reshape(x, 2, length(x)/2);
        plot(x(1,:), x(2,:), 'ro-', 'UIContextMenu', shapeuimenu, 'UserData', prj_names{i});
    end
    meanshape = mean(X, 2);
    meanshape = reshape(meanshape, 2, length(meanshape)/2);
    centroid = mean(meanshape, 2);
    centered_meanshape = meanshape - centroid*ones(1, size(meanshape,2));
    sz = norm(centered_meanshape(:));
    plot(meanshape(1,:), meanshape(2,:), 'go-');
    axis image;
end
return;
%%%
%
%%%
function showShapeName(shape, evd)
data = get(gco, 'UserData');
disp(data);
return
%%%%%%
%
%
%
%%%%%%
function ALLX = normalise_mean_size(ALLX)
% Here we assume that each column is an observation and each row is a
% variable.
for j=1:length(ALLX)
    X = ALLX{j};
    meanshape = mean(X, 2);
    meanshape = reshape(meanshape, 2, length(meanshape)/2);
    centroid = mean(meanshape, 2);
    centered_meanshape = meanshape - centroid*ones(1, size(meanshape,2));
    sz(j) = norm(centered_meanshape(:));
end
newsz = mean(sz);
for j=1:length(ALLX)
    X = ALLX{j};
    scale = newsz/sz(j);
    for i=1:size(X, 2)
        x = X(:,i);
        x = reshape(x, 2, length(x)/2);
        mu = mean(x, 2);
        x = x - mu*ones(1, size(x, 2));
        x = x.*scale;
        X(:,i) = x(:);
    end
    ALLX{j} = X;
end
return;

%%%%%%
%
%
%
%%%%%%
function templatename = getTemplateName
templatename = [];
[filename, pathname] = uigetfile('*.temp_dat', 'Pick a Template-file', ['Templates', filesep]);
if isequal(filename,0) || isequal(pathname,0)
    disp('User pressed cancel')
else
    [pathname, templatename, ext, vers] = fileparts(filename);
    disp(['User selected ', fullfile(pathname, filename)])
end