function theResult = trisense(tri, x, y)

% trisense -- Sense of index rotation for triangles.
%  trisense(tri, x, y) returns +1 for the counter-
%   clockwise triangles of tri, and -1 for the
%   clockwise ones.  The data are (x, y).
%  trisense('demo') demonstrates itself.
 
% Copyright (C) 1999 Dr. Charles R. Denham, ZYDECO.
%  All Rights Reserved.
%   Disclosure without explicit written consent from the
%    copyright owner does not constitute publication.
 
% Version of 29-Apr-1999 08:05:16.
% Updated    12-Jul-1999 08:33:28.

if nargin < 1, help(mfilename), tri = 'demo'; end
if isequal(tri, 'demo'), tri = 10; end
if isstr(tri), tri = eval(tri); end

if length(tri) == 1
	npoints = tri;
	rad = 1 + rand(npoints, 1);
	ang = sort(rand(size(rad)) * 2 * pi);
	xy = rad .* exp(ang*sqrt(-1));
	x = real(xy); y = imag(xy);
	tri = delaunay(x, y);
	hull = convhull(x, y, tri);
	tri = trisort(tri);
	s = trisense(tri, x, y);
	hold off
	i = s < 0;
	theColor = [1 0 0];
	z = zeros(size(x));
	for k = 1:2
		if any(i)
			h = trimesh(tri(i, :), x, y, z, 'Tag', mfilename);
			set(h, 'FaceColor', theColor)
			hold on
		end
		i = s > 0;
		theColor = [0 1 0];
	end
	theButtonDownFcn = ['trisense ' int2str(npoints)];
	h = findobj(gcf, 'Tag', mfilename);
	set(h, 'ButtonDownFcn', theButtonDownFcn)
	x(end+1) = x(1);
	y(end+1) = y(1);
	plot(x, y, '-', 'LineWidth', 2.5)
	plot(x(hull), y(hull), 'o', 'MarkerSize', 10)
	hold off
	view(2)
	title(theButtonDownFcn)
	set(gcf, 'Name', 'TriSense Demo')
	zoomsafe
	figure(gcf)
	return
end

[m, n] = size(tri);
if n == 1, tri = tri.'; end

t = tri(:, [1 2 3 1]);

x = x(t);
y = y(t);

[m, n] = size(x);
if n == 1, x = x.'; y = y.'; end

areas = 0.5 .* (x(:, 1:3).*y(:, 2:4) - x(:, 2:4).*y(:, 1:3)) * ones(3, 1);

result = sign(areas);

if nargout > 0
	theResult = result;
else
	disp(result)
end
