function [sorted]=sortbydistance(M)

% takes a standard (indexed) 3d input and sorts it into a list with the top
% of the list nearest the group's center.  This is a bubblesort, which,
% while dreadfully expensive, is quick to program (and if we were concerned
% with efficiency, we'd not be using Matlab in the first place).

% find the center of mass, using the center_of_mass function

%Created by Jim Work, University of South Carolina, August 13th, 2003


center = [];
center = center_of_mass(M);
centerX = center(1,1);
centerY = center(1,2);
centerZ = center(1,3);



% sort the array, with those closest to the center at the top of the array
temp = [];
N=[];
N=M;
K=[];
for i = 1:size(N,1)
   K = [K;(dist3d(N(i,2), N(i,3), N(i,4),centerX, centerY, centerZ))];
end
K;

for i = 1:(size(M,1)-1)
    for j = 1:(size(M,1)-i)
        k = j+1;
        if (dist3d(N(j,2),N(j,3),N(j,4),centerX, centerY, centerZ)>dist3d(N(k,2), N(k,3), N(k,4), centerX, centerY, centerZ))
            temp = [N(j,1),N(j,2),N(j,3),N(j,4)];
            N(j,1) = N(k,1);
            N(j,2) = N(k,2);
            N(j,3) = N(k,3);
            N(j,4) = N(k,4);
            N(k,1) = temp(1,1);
            N(k,2) = temp(1,2);
            N(k,3) = temp(1,3);
            N(k,4) = temp(1,4);
        end
    end
end

M=N;
K=[];
for i = 1:size(N,1)
   K = [K;(dist3d(N(i,2), N(i,3), N(i,4),centerX, centerY, centerZ))];
end
K;

M=remIndex(M);
M=addIndex(M);
sorted = M;


