function UIShapeCreator(shapedir, templatename, iminfo)
if ~exist(templatename)
    fprintf('makeCircle: the given template name doesn''t exist');
    return;
end

fig = openfig('UIShapeCreator', 'reuse');
movegui(fig, 'center');
set(fig, 'visible', 'on');
handles = guihandles(fig);

set(handles.place_landmarks_btn, 'callback', {@doPlaceLandmarks});

% Initialize the application data structure
ad.figMain = fig;
ad.handles = handles;
ad.shapedir = shapedir;
ad.templatename = templatename;
template = load(templatename, '-mat');
ad.template = template.PMTemplate;
ad.shapepts = get(ad.template, 'pts');

ad.iminfo = iminfo;
setappdata(0,'UIShapeCreatorData',ad);
initshape;
initgui;
try
    uiwait(fig);
catch
    if ishandle(fig)
        delete(fig)
    end
end
if isappdata(0,'UIShapeCreatorData')
    ad = getappdata(0,'UIShapeCreatorData');
    rmappdata(0,'UIShapeCreatorData')
else
    % figure was deleted
    selection = [];
    value = 0;
end
return;
%%%%%
%
%
%%%%%
function initshape
ad =getappdata(0, 'UIShapeCreatorData');
N = max(ad.iminfo.Height, ad.iminfo.Width);
rad = N/3;
[x, y] = meshgrid(1:N);
I = sqrt((x-N/2).^2 + (y-N/2).^2);
ad.I = I<rad;
setappdata(0, 'UIShapeCreatorData', ad);

%%%%%
%
%
%%%%%
function initgui
ad =getappdata(0, 'UIShapeCreatorData');
plottemplate(ad.template, ad.handles.template_axis);
plotshape(ad.I, ad.shapepts, ad.handles.shape_axis);
return;
%%%%%
%
%
%%%%%
function doPlaceLandmarks(landmarksbtn, evd)
ad =getappdata(0, 'UIShapeCreatorData');
pts = get(ad.template, 'pts');
for i=1:size(pts,2)
    [x, y] = ginput(1);
    ad.shapepts = [ad.shapepts, [x; y]];
    setappdata(0, 'UIShapeCreatorData', ad);
    plotshape(ad.I, ad.shapepts, ad.handles.shape_axis);
end
%%%%%%
%
%
%%%%%%
function plotshape(I, pts, axis_h)
cla(axis_h);
imagesc(I, 'Parent', axis_h); hold(axis_h, 'on');
if ~isempty(pts)
    plot(axis_h, pts(1,:), pts(2,:),'wo');
    s = {};
    for i=1:size(pts,2); s{end+1} = num2str(i); end;
    text(pts(1,:), pts(2,:), s, 'Parent', axis_h, 'Background', [1 1 1]);
end
axis(axis_h, 'image');
colormap gray;
%%%%%%
%
%
%%%%%%
function plottemplate(template, axis_h)
pts = get(template, 'pts');
image = get(template, 'image');
primaries = get(template, 'primaries');
imagesc(image, 'Parent', axis_h); hold(axis_h, 'on');
plot(axis_h, pts(1,:), pts(2,:),'wo');
plot(axis_h, pts(1,primaries), pts(2,primaries),'go');
s = {};
for i=1:size(pts,2); s{end+1} = num2str(i); end;
text(pts(1,:), pts(2,:), s, 'Parent', axis_h, 'Background', [1 1 1]);
axis(axis_h, 'image');

