function [D, normVec] = satlib_triDist2OppEdge(varargin)
% function [D, normVec] = satlib_triDist2OppEdge(varargin)
%
% Calculates the distance and normal vector to the opposite edge of a
% triangle for each point in the mesh defined by T.
%
% Inputs: 
%  xy - the NxD matrix of points in the mesh, each point is of dimension D
%  T  - the Mx3 matrix defining the triangulation of the mesh.
%
% Outputs:
%  D - the cell array of distances 
%  normVec - the cell of unit normal vectors from the point P to the
%            opposite edge.
%
% Dr. A. I. Hanna, CMP, 2008.

[xy, T] = parseargs(varargin);
N = size(xy,1);
D = cell(N,1);
normVec = cell(N,1);
for i=1:N
    rowind = getTriRows(T, i);
    q = xy(i,:);
    d = [];
    nv = [];
    for r = rowind
        t = T(r,:);
        t = setdiff(t, i);
        p1 = xy(t(1),:);
        p2 = xy(t(2),:);
        [dist, n] = ptdist(q, p1, p2);
        d = cat(2, d, dist);
        nv = cat(2, nv, n);
    end
    D{i} = d;
    normVec{i} = nv;
end
return;
%%
%
function rowind = getTriRows(T, i)
rowind = find(((T(:,1)==i) + (T(:,2)==i) + (T(:,3)==i))>0)';
return
%%
%
function [d, n] = ptdist(q, p1, p2)
v = [p2(2) - p1(2); -(p2(1) - p1(1))];
r = [p1(1) - q(1); p1(2) - q(2)];
n = v./norm(v);
d = (n'*r);
return

%%
%
function [xy, T] = parseargs(varargin)
varargin = varargin{1};
error(nargchk(0,inf,nargin));
if mod(length(varargin),2) ~= 0
    % input args have not com in pairs, woe is me
    error(['Arguments to ', mfilename, ' must come param/value in pairs.'])
end
xy = [];
T = [];
for i=1:2:length(varargin)
    switch lower(varargin{i})
        case 'pts'
            xy = varargin{i+1};
        case 't'
            T = varargin{i+1};
        otherwise
            error(['Unknown parameter name passed to ', mfilename, '.  Name was ' varargin{i}])
    end
end
if isempty(T)
    error('Parameter T sets must be supplied');
end
if isempty(xy)
    error('Parameter xy sets must be supplied');
end
return