function [triang1,next_triang] = mk_nxt_tri(triangles)
% [TRIANG1,NEXT_TRIANG] = mk_nxt_tri(TRIANGLES)
%
% Given an m x 3 array TRIANGLES of vertex indices, construct
% a list defined by TRIANG1 and NEXT_TRIANG for identifying
% the triangles touching a given vertex.
%
% Note: idx = TRIANG1(i) is the index into NEXT_TRIANG
%	indicating the first triangle in the list touching vertex i;
%	The actual index into TRIANGLES is k = NEXT_TRIANG(idx,1).
%	That is, i is one of the values TRIANGLES(k,1:3).
%	The next triangle touching vertex i is indicated by
%	idx2 = NEXT_TRIANG(idx,2); if k2 = NEXT_TRIANG(idx2,1) then
%	i is one of the values TRIANGLE(k2,1:3).
%
% Zero is used as the "null" pointer.
%
% Code to use these structures follows:
%
% % Find all triangles touching vertex # i
% tri_index = triang1(i);
% while tri_index > 0
%   k = next_triang(tri_index,1);
%   % Process triangle # k
%     ..... triangle(k,1) ....
%   tri_index = next_triang(tri_index,2);
% end

triang1 = zeros(length(triangles),1);
next_triang = zeros(3*length(triangles),2);
idx = 0;

for k = 1:length(triangles)
  for j = 1:3
    i = triangles(k,j);
    idx = idx + 1;
    next_triang(idx,1) = k;
    next_triang(idx,2) = triang1(i);
    triang1(i) = idx;
  end
end

