function [Edgs2,toterr]= relax_edges_NM(Edg,S, animate, image_axis)
%[S2,toterr]=relax_springs_NM(S,animate, image_axis)
%          Relax 2D springs in S indexed by n.
%          uses fmins to minimise error between spring length and equilibrium 
%          spring length. %used fiminunc on siganim2, but does not exist on image14pc so use fminsearch
%           Finishes when no changes made, or 1000 iterations.
%           S    : 2D spring description
%           image_axis : handle to the axis where the image shoudl be drawn
%
%          Returns:
%           S2   : relaxed version of S
%           iter : number of iterations used
%
%          See also: make_springs
%
%          (c) ag_rolland 2000
%           re-written Dr. A. I. Hanna (2005)

if nargin<1
	error('Insufficient arguments');
end
if nargin<2
    animate = 0;
end
if animate & (nargin<3)
    image_axis = gca;
end


T=size(S,1);
nE = size(Edg,1);
n=1:nE;

nr=n;
xy=S(:,2*T+(1:2));
NEdg = Edg(:,1:T);
DEdg = Edg(:,T+(1:T));
xyEdg = Edg(:,2*T+(1:2));
xyEdg1=xyEdg;
% find error associated with current points location
vecteur=[];
vecteur=reshape(xyEdg,size(xyEdg,1)*2,1);

options=optimset('MaxFunEvals',10000,'Maxiter',10000);
[xy,toterr,exitflag,nbite]=fminsearch('cost_function_edge', vecteur ,options, NEdg, DEdg, nr, xy);
Edgs2 = Edg;
xy = reshape(xy, length(xy)/2, 2);
Edgs2(:,end-1:end) =xy;
