% sort vertices into a standard order

function sortvertices = sortvert(vertices)

   sortvertices = zeros(8,2);
   
   rows=vertices(:,1);
   [sortrows,ind] = sort(rows);

   % get top left and right
   
   if vertices(ind(1),2) < vertices(ind(2),2)
        sortvertices(1,:) = vertices(ind(1),:);
        sortvertices(2,:) = vertices(ind(2),:);
   else
        sortvertices(1,:) = vertices(ind(2),:);
        sortvertices(2,:) = vertices(ind(1),:);
   end
         
   % get foot
   
   if vertices(ind(7),2) > vertices(ind(8),2)
        sortvertices(5,:) = vertices(ind(7),:);
        sortvertices(6,:) = vertices(ind(8),:);
   else
        sortvertices(5,:) = vertices(ind(8),:);
        sortvertices(6,:) = vertices(ind(7),:);
   end
   
   % middle bar
   
   restind = [ind(3),ind(4),ind(5),ind(6)];
   restcols = [vertices(ind(3),2),vertices(ind(4),2),vertices(ind(5),2),vertices(ind(6),2)];
   for i = 1 : 3
     for j = i+1 : 4
       if restcols(i) > restcols(j)
          tmpc = restcols(i);
          restcols(i) = restcols(j);
          restcols(j) = tmpc;
          tmp1 = restind(i);
          restind(i) = restind(j);
          restind(j) = tmp1;
       end
     end
   end   
   sortvertices(8,:) = vertices(restind(1),:);
   sortvertices(7,:) = vertices(restind(2),:);
   sortvertices(4,:) = vertices(restind(3),:);
   sortvertices(3,:) = vertices(restind(4),:);
   
