function in_out = insideTriangle( A, B, C, p )
% The insideTri function determines whether the point with
% coordinates (p(1),p(2)) is inside or outside of the triangle 
% given by the three vertex points with coordinates (A(1),A(2)),
% (B(1),B(2)), and (C(1),C(2)).
%
% The method used is to compute the barycentric coordinates
% of the point relative to the three vertex points. The array
% coord contains the barycentric coordinates. If all of the
% barycentric coordinates are nonnegative, then the point is
% said to be inside the triangle.
% If in_out is 1, the point is inside,
% if in_out is 0, the point is outside,and
% if in_out is 0.5, the point is on the edge.

x = p(1) ;
y = p(2) ;

a = [A(1) B(1) C(1)];      % get x-coordinates
b = [A(2) B(2) C(2)];      % get y-coordinates

AA = [ 1, 1, 1 ; a ; b ] ; % Set up the matrix for the system.
coord = AA\[1 ; x ; y ] ;  % Solve the linear system.

if all( coord > 0 )       % If all barycentric coordinates are
    in_out = 1 ;          % non-negative, the point is inside.
elseif any( coord < 0 )   % If any coordinate is negative,
    in_out = 0 ;          % the point is outside.
else                      % Otherwise,
    in_out = 0.5 ;        % it is on the boundary.
end