%Hanna, 2005
function [Edgs, removed_ind, order, value] = EditEdgePoints(varargin)
error(nargchk(0,inf,nargin));
ad.value = 0;
ad.Edgs = [];
ad.Spr = [];
ad.toremove = [];
ad.xyreg = [];
ad.order = [];
ad.R = [];
if (mod(length(varargin),2) ~= 0) & (length(varargin)<6)
    % input args have not com in pairs, woe is me
    error('Arguments to LISTDLG must come param/value in pairs.')
end
for i=1:2:length(varargin)
    switch lower(varargin{i})
        case 'springs'
            ad.Spr = varargin{i+1};
        case 'edges'
            ad.Edgs = varargin{i+1};
        case 'xyregs'
            ad.xyreg = varargin{i+1};
        case 'removed_indices'
            ad.toremove = varargin{i+1};
        case 'order'
            ad.order = varargin{i+1};
        case 'layers'
            ad.R = varargin{i+1};
        otherwise
            error(['Unknown parameter name passed to LISTDLG.  Name was ' varargin{i}])
    end
end
if isempty(ad.Spr)
    error('Springs parameter is required.')
end
if isempty(ad.Edgs)
    error('Edges parameter is required.')
end
if isempty(ad.xyreg)
    error('XY Region parameter is required.')
end

%if isempty(ad.order)
    T = size(ad.Spr,1);
    NEdg =  ad.Edgs(:,1:T);
    Q = ad.Edgs;
    Q(ad.toremove,:) = [];
    NEdg =  Q(:,1:T);
    for i=1:T
        indx=find(NEdg(:,i));
        ad.order{i} =indx;
    end
    
%end

% Open, move, and get the handles from the figure file.
fig = openfig(mfilename, 'reuse');
% Move the gui and then show it, rather than have it jump all over the
% place.
movegui(fig, 'center');
set(fig, 'visible', 'on');
handles = guihandles(fig);
% Set all the callback functions
set(handles.finished_btn, 'callback', {@doOk});
set(handles.cancel_btn, 'callback', {@doCancel});
set(handles.image_axis, 'ButtonDownFcn', {@doAxisClicked});

% Initialize the application data structure
ad.figMain = fig;
ad.handles = handles;
setappdata(0,'EditEdgePointsData',ad);
init_gui;

try
    uiwait(fig);
catch
    if ishandle(fig)
        delete(fig)
    end
end



if isappdata(0,'EditEdgePointsData')
    ad = getappdata(0,'EditEdgePointsData');
    value = ad.value;
    Edgs = ad.Edgs;
    removed_ind = ad.toremove;
    order = ad.order;
    rmappdata(0,'EditEdgePointsData')
else
    % figure was deleted
    value = 0;
    Edgs = [];
    order = [];
    removed_ind = [];
end
return;

function init_gui()
ad =getappdata(0, 'EditEdgePointsData');
Spr = ad.Spr;
Edgs = ad.Edgs;
xyreg = ad.xyreg;
nx=size(Edgs,2)-1;
ny=size(Edgs,2);
if ~isempty(ad.R)
    imagesc(ad.R, 'Parent', ad.handles.image_axis, 'HitTest', 'off');
end
hold(ad.handles.image_axis, 'on');
if (ceil(size(Edgs,2)/2)-floor(size(Edgs,2)/2))>0,
    nx=nx-1;
    ny=ny-1;
end;
ad.nx = nx;
ad.ny = ny;
T=size(Spr,1);
NEdg=Edgs(:,1:T);
for i=1:T,
    ctour=[xyreg{i}(:,1) xyreg{i}(:,2)];
    ctx=ctour(:,1);
    cty=ctour(:,2);
    ctx = [ctx; ctx(1)];
    cty = [cty; cty(1)];
    plot(ad.handles.image_axis, ctx, cty, '-', 'Color', 'k', 'LineWidth', 2, 'HitTest', 'off');
end
ad.marker_handle = [];
for k=1:size(Edgs,1)
    ad.marker_handle(end+1)=plot(ad.handles.image_axis, Edgs(k,nx),Edgs(k,ny),'o', 'MarkerEdgeColor', 'g', 'MarkerFaceColor', 'r', 'HitTest', 'off');
end
axis(ad.handles.image_axis, 'image', 'ij');
set(ad.marker_handle(ad.toremove),  'MarkerEdgeColor', 'r', 'MarkerFaceColor', 'g');
setappdata(0, 'EditEdgePointsData', ad);
return;



function doOk(ok_btn, evd)
ad =getappdata(0, 'EditEdgePointsData');
ad.value = 1;
ad.Edgs(ad.toremove, :) = [];

setappdata(0, 'EditEdgePointsData', ad);
delete(gcbf);


function doCancel(cancel_btn, evd)
ad =getappdata(0, 'EditEdgePointsData');
ad.selection = [];
ad.value = 0;
setappdata(0, 'EditEdgePointsData', ad);
delete(gcbf);

function doAxisClicked(ok_btn, evd)
ad =getappdata(0, 'EditEdgePointsData');
pt = get(ad.handles.image_axis, 'CurrentPoint');
pt = pt(1,1:2);
x = ad.Edgs(:, ad.nx);
y = ad.Edgs(:, ad.ny);
d = sqrt(sum(([x, y] - ones(size(ad.Edgs,1),1)*pt).^2, 2));
[val, ind] = min(d);
isset = find(ad.toremove == ind);

Edgs_updated = ad.Edgs(:,end-1:end);
Edgs_updated(ad.toremove,:) = [];
ind_to_change = ind;
if isempty(isset)
    ad.toremove = [ad.toremove(:); ind];
    for i=1:length(ad.order)
        o= ad.order{i};
        d = sqrt(sum((Edgs_updated - ones(size(Edgs_updated,1),1)*pt).^2, 2));
        [val, ind] = min(d);
       % indx=find(NEdg(:,i));
        index = find(o==ind);
        o(index) = [];
        index = find(o>ind);
        o(index) = o(index)-1;
        ad.order{i} = o;
    end
    set(ad.marker_handle(ind_to_change), 'MarkerFaceColor', 'g', 'MarkerEdgeColor', 'r');
else
    ad.toremove(isset) = [];
    for i=1:length(ad.order)
        o= ad.order{i};
        d = sqrt(sum((Edgs_updated - ones(size(Edgs_updated,1),1)*pt).^2, 2));
        [val, ind] = min(d);
       % indx=find(NEdg(:,i));
        index = find(o==ind);
        if ~isempty(index);
            o(index) = [];
            index = find(o>ind);
            o(index) = o(index)+1;
            ad.order{i} = o;
        end
    end
    set(ad.marker_handle(ind_to_change), 'MarkerFaceColor', 'r', 'MarkerEdgeColor', 'g');
end
setappdata(0, 'EditEdgePointsData', ad);
