%-------------------------------------------------------------------------%
%         This software is licensed by Creative Commons BY-NC-SA:         %
%      http://creativecommons.org/licenses/by-nc-sa/3.0/it/legalcode      %
%-------------------------------------------------------------------------%
%
% File: normnd(A)
%
% Goal: computes the normal vector to a given point 
%
% Inputs: A: the point and its neighbors
%  
% Outputs: V: normal vector associated to the point 
%
% Remark:  the original routine comes from matlab central file exchange, 
%          provided by J. Wells, 03/05/13. This program has been 
%          modified in order to take into account the case of zero vectors
%
%-------------------------------------------------------------------------%
function V = normnd(A)
% Center the input indicies (center of mass computation)
A = A - repmat(mean(A,1),size(A,1),1);
% Compute the covariance matrix A
A = cov(A);
% Find the eigenvector corresponding to the minimum eigenvalue in A
[V,lambda] = eig(A);
[a idx] = min(diag(lambda));
% Normalize
V = V(:,idx);
if norm(V) == 0 
    V = [0 0 0];
else
V = V(:,idx)/norm(V);
end