function i = linecircleintersect2( a, b, c, r, doplot)
% intersecting = linecircleintersect( a, b, c, r, doplot)
% 
% Find if a line segment a-b intersects a circle. If it does, the lenght of
% a vector from the circle centre to the linesegment, normal to the line
% segment is smaller than the radius of the circle. 
% With: a : first point of linesegment
%       b : second point of linesegment
%       c  : circle centre
%       r  : circle radius

if nargin == 4, 
    doplot = false; 
end;


Dx = -b(1) + a(1);
Dy = -b(2) + a(2);
Ex = c(1)-a(1);
Ey = c(2)-a(2);

Aabc = (Dx^2 + Dy^2);
Babc = (2*Ex*Dx + 2*Ey*Dy);
Cabc = (Ex^2 + Ey^2 - r^2);

% ABC formula
Dis = Babc^2 - 4*Aabc*Cabc;




if Dis>=0 , % Discriminant <0, so no solutions to |ac|<=r,
    t1 = (- Babc + sqrt(Dis) )/ (2*Aabc);
    t2 = (- Babc - sqrt(Dis) )/ (2*Aabc);
    
    if (t1>=0 && t1<=1) || (t2>=0 && t2<=1),
        i = true;
    else
        i = false;
    end;
else
    i = false; % todo check if 0<=r<=1
end;
    


if doplot,
    t = 0:0.05*pi:2*pi;
    x = c(1) + r * sin(t);
    y = c(2) + r * cos(t);    
    plot(x,y, 'b-');
    hold on;
    vectorplot2( a, b, 'r-');
end;


