function data=ellipse_fit2d(X,Y);
%E=fit_ellipse(X);   Fit best ellipse to set of points.
%        For set or points X returns E.
%         X  : column of [x y] vectors
%
%E=fit_ellipse(X,Y);
%         X  : vector of x coordinates
%         Y  : vector of y coordinates
%         
%        Returns
%         E  : [angle;length;width]        (angle is in degress)
%
%        See also: sector_to_details, regress.
%
%        (c) Stephen Impey, 1996
%

if nargin<1,
	error('Insufficient arguments');
end

if nargin>1,
	X=[X(:) Y(:)];
end

% Find angle of elipse
if size(X,1)==1,
   a=0;
else
   a=atan2(regress(X),1);
end

x=X(:,1);
y=X(:,2);
mx = mean(x);
my = mean(y);
% Align ellipse with origin.
x=x-mean(x);
y=y-mean(y);

% Align elipse with x-axis
X=turn([x y],a);

%plot(X(:,1),X(:,2),'o');axis('image');

l=max(X(:,1))-min(X(:,1));
w=max(X(:,2))-min(X(:,2));
%a=180*a/pi;
%E=[a;l;w];

G = gtlib_growthParams2Tensor(l, w, a);
%G = gtlib_growthParams2Tensor(smax(1), smax(2), acos(V(1,1)));
data.growthTensor = G;
data.Centroid(1) = mx;
data.Centroid(2) = my;
data.ellipArea = pi*l*w;
data.Area = polyarea(x, y);
return;

data.Orientation = a;
data.MajorAxisLength = l;
data.MinorAxisLength = w;
data.Centroid(1) = mx;
data.Centroid(2) = my;
data.Area = length(x);



function [b,a]=regress(z)
%[b,a]=regress(z)
%          Find regression coefficients for points in z.
%          z  is a column of [x y] vectors.
%
%          (c) Stephen Impey, 1996
%

% Taken from: E.Kreyszig - Advanced Engineering Maths. p.936  (4th edition)

x=z(:,1);
y=z(:,2);
n=size(x,1);

mx=mean(x);
my=mean(y);

sxy=sum((x-mx).*(y-my))/(n-1);
s12=sum((x-mx).^2)/(n-1);

if s12==0,
   b=inf;
else
   b=sxy/s12;
end
a=my-b*mx;