function [loci] = detect_perimeter_individuals (M, d)

% M is a matrix indexed with line numbers, which lists the x and y coordinates in the second 
% and third columns.  detect_perimeter_individuals(M,d) will find the individuals that are
% within .5*(d) of the perimeter, where d is the individual's body size.  This will be used
% in several indices, e.g. fuzzyswarm.

% Finds those that are near the perimeter.
% Created by Jim Work, University of South Carolina, August 13, 2003


% First generate a convex hull of the matrix, finding the perimeter individuals.
bodysize = d;
size(M,1);
K = convhull(M(:,2),M(:,3));
size(K,1);
% The convhull function is used to find the
in = [];                         %  perimeter individuals.
perimeter_count = (size(K,1)-1); 
itsthere = 0;

for j = 1:(size(K,1)-1)         % This will loop over all perimeter segments.
   
   P = M(K(j,1),:);  
   
   P2 = M(K(j+1,1),:);  
   
   for qq = 1:size(M,1)
      Q=[M(qq,1),M(qq,2),M(qq,3)];
      dist_point_to_line(P(1,2),P(1,3),P2(1,2),P2(1,3),M(qq,2),M(qq,3));
      if (dist_point_to_line(P(1,2),P(1,3),P2(1,2),P2(1,3),M(qq,2),M(qq,3))<.5*bodysize)
         in = [in;M(qq,1),M(qq,2),M(qq,3)];
      end
   end   
end

last = [];

if isempty(in) == 0;
   last = in(1,:);
end

for i = 1:size(in,1)
   for j = 1:size(last,1)
      if (in(i,1)==last(j,1))
         itsthere = 1;
      end
   end
   if (itsthere == 0);
      last = [last;in(i,:)];
   end
   itsthere = 0;
end


last;


loci = last;
