function [nbr, degree] = findnbr(tri)
%
% The function finds the first order neighbors and degree from a given a triangle element.  
% tri    : list of triangle elements obtained from an isosurface algorithm
% nbr    : first order neihbor vertex list 
% degree : degree of each vertex
%
%(C) Moo K. Chung
% Update history Feb 5, 2004; Nov 14, 2007.
% mkchung@wisc.edu
% http://www.stat.wisc.edu/~mchung/softwares/softwares.html
%
% Mesh topology:
%
% V = number of vertices
% F = number of faces
% It is assumed that the input mesh is topologically equvalent to a sphere, i.e.
% F = 2V - 4: Euler characteristic equation.

%degree computation

n_tri=size(tri,1);
n_vertex = (n_tri+4)/2;
degree=zeros(n_vertex,1);

for j=1:n_tri
degree(tri(j,:))=degree(tri(j,:))+1;
end

max_degree=max(degree);

% find out the neighboring vertices

nbr=zeros(n_vertex,max_degree);

for i_tri=1:n_tri
    for j=1:3
        cur_point = tri(i_tri,j);
        for k=1:3
            if (j ~= k)
                nbr_point= tri(i_tri,k);
                if find(nbr(cur_point,:)==nbr_point)
                    ;
                else
                    n_nbr = min(find(nbr(cur_point,:) == 0));
                    nbr(cur_point,n_nbr) = nbr_point;
                end;
            end;
        end;
    end;
end;
