function i = linecircleintersect( a1, a2, c, r, doplot)
% intersecting = linecircleintersect( a1, a2, c, r)
% 
% Find if a line segment 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: a1 : first point of linesegment
%       a2 : second point of linesegment
%       c  : circle centre
%       r  : circle radius

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


% orientation vector for line segment a
a = (a2-a1);
% normal to a:
n = [ -a(2), a(1) ];

% normalize n
nn = n ./ sqrt(sum(n.^2));

% make n oriented vector of length r
nr = r * nn;

% Define a second line segment b, of circle diameter, perpendicular to a:
b1 = c - nr;
b2 = c + nr;

[int, onboth] = intersecting( a1, a2, b1, b2, doplot)
if doplot,
    t = 0:0.05*pi:2*pi;
    x = c(1) + r * sin(t);
    y = c(2) + r * cos(t);
    hold on;
    plot(x,y, 'k-');
end;

i = onboth;
