function a=fit_ellipse(x,y,m)

% Code extracted from: 
% 

if m==1;

D = [x.*x x.*y y.*y x y ones(size(x))];
S = D'*D;
C(6,6)=0; C(1,3)=2; C(2,2)=-1;C(3,1)=2;
[gevec, geval] = eig(inv(S)*C);
[PosR, PosC] = find(geval > 0 & isinf(geval));
a = gevec(:, PosC);	% corresponding eigenvector


% MATLAB implementation of the direct ellipse-specific fitting algorithm proposed by Fitzgib- bon et al. in [Fitzg96b]
% [Fitzg96b] Fitzgibbon, A. W., Pilu, M and Fischer, R. B.: Direct least squares fitting of ellipses. In Proc. of the 13th 
% International Conference on Pattern Recognition, pages 253?257, Vienna, September 1996.

elseif m==2;
     D1=[x.^2,x.*y,y.^2];           % quadratic part of the design matrix 
     D2 = [x, y, ones(size(x))];    % linear part of the design matrix 
     S1 = D1'* D1;                  % quadratic part of the scatter matrix 
     S2 = D1'* D2;                  % combined part of the scatter matrix
     S3 = D2'* D2;                  % linear part of the scatter matrix
     T = - inv(S3) * S2'; 
     M = S1 + S2 * T; 
     M = [M(3, :) ./ 2; - M(2, :); M(1, :) ./ 2];       % premultiply by inv(C1)
     [evec, eval] = eig(M);                             % solve eigensystem 
     cond = 4 * evec(1,:).* evec(3,:) - evec(2,:).^2; 	% evaluate a?Ca 
     a1 = evec(:,find(cond > 0));                      % eigenvector for min. pos. eigenvalue 
     a = [a1; T * a1];                                 % ellipse coefficients
end
