function con = greedyice(con, im, alpha, beta, gamma, delta)
% GREEDYICE Image contour extraction algorithm
% Usage: greedyice(con, im, alpha, beta, gamma);
%  con   - initial contour nx2 matrix of image coordinates
%  im    - 2D grayscale matrix of pixel values in the range [0,1]
%          (should be inverted to converge to dark areas).
%  alpha - (optional) weight for continuity term in energy functional.
%  beta  - (optional) weight for curvature term in energy functional.
%  gamma - (optional) weight for image intensity term.
%  delta - (optional) default weight for central attraction term.

%% set optional parameters to default values
if nargin < 6, delta = 0; end
if nargin < 5, gamma = 1.2; end
if nargin < 4, beta = 1.0; end
if nargin < 3, alpha = 1.0; end
if nargin < 2
    help greedyice
    error('wrong number of arguments')
end

%% constants
sz = size(im);
n = length(con);
threshold3 = 5; %% points moved threshold

%% init variables
iter = 0;
alpha = alpha * ones(n,1); % continuity coeffs
beta = beta * ones(n,1); % curvature coeffs
gamma = gamma * ones(n,1); % intensity coeffs
delta = delta * ones(n,1);
ptsmoved = threshold3; % num points moved in iteration

%% loop until few points moved
while ptsmoved >= threshold3
    % prevent infinate loop
    if iter > 500, break; end
    
    % move contour to new local optima
    [con, ptsmoved] = greedyice_movecontour(con, im, alpha, beta, gamma, delta);
   
    % higher level process to allow corners in contour
    beta = greedyice_choosebeta(con, im, beta);
    
    % turn on or off central attraction term
    %for i = 1:n
    %    vi = con(i,:);
    %    if im(vi(1), vi(2)) > 0.6
    %        delta(i) = 0.7;
    %    else 
    %        delta(i) = 0;
    %    end
    %end
    
    %% display so far
    displaysnake(im, con); 
    iter = iter + 1;
end

%iter