function generateMeanAugmentedShapes
% function generateMeanAugmentedShapes
%
% A. I. Hanna + A. Green, 2007

% open and check the template file
pointmodeldir = 'PointModels';
template = openTemplate;
if isempty(template)
    fprintf('Invalid template file\n');
    return;
end

% open and check the groups file
groups = openGroups;
if isempty(groups)
    fprintf('Invalid groups file\n');
    return;
end

% make sure it is not empty
group_names = {groups.name};
if isempty(group_names)
    fprintf('Empty groups file\n');
    return;
end

% let the user select which groups to draw
[s,v] = listdlg('PromptString', 'Select the groups:', 'SelectionMode', 'multiple', 'ListSize', [300 300], 'ListString', group_names);
if isempty(s)
    fprintf('Invalid image repository\n');
    return;
end
image_directory = uigetdir(pwd, 'Pick a Directory to Store the Images');
if image_directory==0
    return;
end
X = loadMeanPts(s, groups, template, pointmodeldir);
xvals = X(1:2:end,:);
yvals = X(2:2:end,:);
xlim = [min(xvals(:)), max(xvals(:))];
ylim = [min(yvals(:)), max(yvals(:))];
plot_options.xlim = xlim;
plot_options.ylim = ylim;
plot_options.fillcol = 'r';
plot_options.edgecol = 'b';
plot_options.show_axis = 'off';
plot_options.figcol = [1 1 1];
fh = figure;
drawMeanAugmentedShapes(X, template, groups, plot_options, image_directory, gca); 
close(fh);
return;
%%%
%
%%%
function X = loadMeanPts(s, groups, template, pointmodeldir)
mean_pm_extension = 'MEAN_GROUP_';
[split_idx, o] = isAugmentedProject;
template_name = get(template, 'name');
[p, template_name] = fileparts(template_name);
pm_dir = [pwd, filesep, pointmodeldir, filesep, template_name];
template_pts = get(template, 'pts');
template_pts = template_pts(:);
template_pts = reshape(template_pts, 2, length(template_pts)/2);
template_pts = splitPoints(template_pts', split_idx, o)';
template_pts = center_pts(template_pts);
num_template_pts = length(template_pts(:));
X = zeros(num_template_pts, length(s));
for i=1:length(s)
    group_name = groups(s(i)).name;
    mean_group_pm_name = [mean_pm_extension, group_name, '_pm.mat'];
    if exist([pm_dir, filesep, mean_group_pm_name], 'file')
        pts = load([pm_dir, filesep, mean_group_pm_name]);
        pts = pts.pts;
        pts = reshape(pts, 2, length(pts)/2);
        pts = splitPoints(pts', split_idx, o)';
        pts = pts(:);
        pts = center_pts(pts);
        if length(pts)~= num_template_pts
            X(:,i) = template_pts(:);
            fprintf('MEAN POINT MODEL FILE IS THE WRONG SIZE IN GROUP %s\n', group_name);
        else
            X(:,i) = pts;
        end
    else
        X(:,i) = template_pts(:);
        fprintf('MEAN POINT MODEL FILE NOT FOUND FOR GROUP %s\n', group_name);
    end

end
%%%
%
%%%
function pts = center_pts(pts)
dim = 2;
pts = pts(:);
pts = reshape(pts, dim, length(pts)/dim);
mu = mean(pts,2);
pts = pts - mu*ones(1, size(pts,2));
pts = pts(:);
return
%%%
%
%%%
function groups = openGroups
groups = [];
[filename, pathname] = uigetfile('*.mat', 'Open a Group File');
if isequal(filename,0) || isequal(pathname,0)
    return;
end
groups = load([pathname, filesep, filename]);
if ~isfield(groups, 'groups')
    return;
end
groups = groups.groups;
return

%%%
%
%%%
function drawMeanAugmentedShapes(X, template, groups, plot_options, image_directory, axish)
set(gcf, 'Color', plot_options.figcol);
pri = get(template, 'primaries');
edge = get(template, 'loops');
if iscell(edge)
    edge = edge{1};
end
for i=1:size(X,2)
    cla(axish);
    plotshape(X(:,i), pri, edge, [0 0], axish, plot_options.fillcol, 0, plot_options.edgecol);
    set(axish, 'XLim', plot_options.xlim, 'YLim', plot_options.ylim);
    set(axish, 'Visible', plot_options.show_axis);
    axis(axish, 'ij', 'image');
    I = getframe(gca);
    I = frame2im(I);
    imwrite(I, [image_directory, filesep, groups(i).name, '.tif'], 'TIFF', 'Compression', 'none');
end
return

%%%%%
%
%
%%%%%
function plotshape(pts, pri, edge, offset, axish, fillcol, fillflag, edgecol)

facecol = [1 1 1];
priedgecol = [0 0 0];
prifacecol = [0 0 0];
if nargin<8
    edgecol = [0 0 0];
end
pts = reshape(pts, 2, length(pts)/2);
pts(1,:) = pts(1,:) + offset(1);
pts(2,:) = pts(2,:) + offset(2);

hold(axish, 'on');
if fillflag
    fillcol = [0.7529    0.7529    0.7529];
    fill(pts(1,:),pts(2,:),fillcol)
end 
for i=1:length(edge)
    xp = [pts(1,edge(i,1)) pts(1,edge(i,2))];
    yp = [pts(2,edge(i,1)) pts(2,edge(i,2))];
    plot(axish, xp, yp, '-', 'Color', edgecol, 'LineWidth', 2);
end

%%%
%
%%%
function template = openTemplate

template = [];
[filename, pathname] = uigetfile('*.temp_dat', 'Open a Template File');
if isequal(filename,0) || isequal(pathname,0)
    return;
end
template = load([pathname, filesep, filename], '-mat');
if ~isfield(template, 'PMTemplate')
    return;
end
template = template.PMTemplate;
return