function ALL = allequid(ARRAY);

% allequid(<array>) -- Find nearest neighbors for all points in an array.
%
% The allnn3d() function takes the array <array>, and finds all the individuals
% in the array's nearest neighbors.
%
% ALL points that are equidistant from a given point are returned.

% Returns a sparse matrix with the entries being all the nearest neighbors of each point.
% Created by Jim Work, University of South Carolina, August 13, 2003


DIST = [];  						% initialize the DISTance matrix

N = size(ARRAY,1);			  

for n = 1:N							% loop over every point and find distance
   for m = 1:N						% for each other point in the group
      if (m == n)
         DIST(n,m) = inf;
      else
         x1 = ARRAY(n,2);
         y1 = ARRAY(n,3);
         z1 = ARRAY(n,4);
         x2 = ARRAY(m,2);
         y2 = ARRAY(m,3);
         z2 = ARRAY(m,4);
         DIST(n,m) = dist3d(x1,y1,z1,x2,y2,z2);
      end		
   end
end

currentlow = inf;
longlist = [];
zerowidth = 0;
q = 0;

% believe it or not, this is all just to find out how wide to make our zeros array

for i = 1:size(DIST,1)
   for j = 1:size(DIST,2)  
      if (DIST(i,j) < currentlow)   % if the jth element of the ith row is less than
         currentlow = DIST(i,j);		% our current lowest element, change currentlow
      end
   end
   for j = 1:size(DIST,2)
      if (DIST(i,j) == currentlow)  % if the cell holds the currentlow value
         q = q+1;							% increment our counter		
      end
      if (q > zerowidth)
         zerowidth = q;					% update the width of our final array
      end
      q = 0;
   end
   currentlow = inf;
end

final = zeros(size(ARRAY,1), zerowidth); % build our zeros matrix

for i = 1:size(DIST,1)
   for j = 1:size(DIST,2)
      
      if (DIST(i,j) < currentlow)
         currentlow = DIST(i,j);
      end
   end
   available = 1;
   for j = 1:size(DIST,2)
      if (DIST(i,j) == currentlow)	% put the neighbors (at long, excruciating last)
         final (i,available) = j;	% into their proper place in the final array.
         available = available + 1;
      end
   end
   
   currentlow = inf;
end

% i rule.

ALL = final;
