function [X] = mean_group_image(templatename, pm_files, Xm)

pmprefix = [pwd, filesep, 'PointModels', filesep, templatename, filesep];
images_dir = 'Cropped';
prefix = [pwd, filesep, images_dir, filesep];
X = [];
Xm = (reshape(Xm, 2, length(Xm)/2))';
indices = 1:size(Xm,1);
msiz = [round(max(Xm)), 3];

Xm = Xm - repmat(min(Xm), [size(Xm,1),1]);


for i=1:length(pm_files)
    file = pm_files{i};
    pmfile = [pmprefix, file];
    if exist(pmfile)
        pts = load(pmfile);
        pts = pts.pts;
        pts = (reshape(pts, 2, length(pts)/2))';
        [path, file, ext, vers] = fileparts(file);
        file = [file(1:end-3), '.jpg'];
        if exist([prefix, file])
            I = imread([prefix, file]);
            [wimg]=warp_to_mean_shape(pts', Xm, I);
            if isempty(X)
                X = double(wimg(:));
            else
                X = X + double(wimg(:));
            end
        else
            fprintf('Could not file file %s\n', [prefix, pm_files{i}]);
        end
    end
end

X = X./length(pm_files);
X = mean(X,2);
X = uint8(reshape(X, size(wimg)));
boundary_filename = [pwd, filesep, 'Templates', filesep, templatename, '.boundary'];

if exist(boundary_filename, 'file')
    boundary_index = load(boundary_filename, '-mat');
    boundary_index = boundary_index.boundary_index;
    fprintf(' - using boundary mask file\n');
else
    fprintf(' - could not find a suitable boundary mask file\n');
    boundary_index = [];
end
img = X;
ptsx = Xm(:,1);
ptsy = Xm(:,2);

if ~isempty(boundary_index)
    if iscell(boundary_index)
        mask  = zeros(size(img,1), size(img,2));
        for i=1:length(boundary_index)
            mask_x = ptsx(boundary_index{i});
            mask_y = ptsy(boundary_index{i});
            b = roipoly(img, mask_x, mask_y);
            mask = mask | b;
        end
        mask = uint8(mask);
        for i=1:size(img,3)
            img(:,:,i) = img(:,:,i).*mask;
        end
    end
X(:,:,1) = uint8(X(:,:,1).*mask);
X(:,:,2) = uint8(X(:,:,2).*mask);
X(:,:,3) = uint8(X(:,:,3).*mask);
end

