function [swarming_ind] = compswarm3d(M);
% COMPSWARM(M) ----  This is a computational version of the Swarming Index 
% presented in Watt et al. (1997), calculated for the array 'M', if M is in the 
% standard format.  This is essentially the mean of the ratios for each group of
% the number in the group to the surface area of the group.  
%
% Utilizing findgroups3d, we can isolate each group, perform a convhull
% openration, and determine the surface area of the convex hull of the
% group.  The number in the group is ratioed to this surface area, and the
% mean of the ratios is the final index.
%
% As groups get more compact (towards having an average nnd of zero), the
% index increases (towards positive infinity).

% Ratio of number of individuals in a group to the surface area of the group's convex hull.
% Based on compswarm by Ian McFarland, University of Washington
% Modified to handle 3-D case by Jim Work, University of South Carolina, August 13, 2003

% First, a matrix to hold to groups' swarming values is initialized.
[count, barn]=findgroups3d(M);
G=[];
final = 0;
% barn is a structure housing the various groups of animals 
% (hence, "barn").

for i = 1:count
    if ((size(barn(i).members,2))>3),
        for j=1:size(barn(i).members,2),
            herd = barn(i).members(j);
            A = [M(herd,2), M(herd,3), M(herd,4)];
            if (isempty(G)==1)
                G = A;
            else
                G = [G;A];
            end
        end
        sa = area3d(G);
        swarmindex = (size(barn(i).members,2))/sa;
        final = final + swarmindex;
        G=[];
    end
end
fini = final/count;
swarming_ind = fini;
    
    