function ind=contour_maker(index,x,y,node_on_boundary,element_on_boundary);
%CONTOUR_MAKER - ???
%
%   This program takes element_on_boundary and node_on_boundary 
%   x and  y and index and makes an ordered boundary with it,
%   turning counter clockwise.
%
%   Usage:
%      ind=contour_maker(index,x,y,node_on_boundary,element_on_boundary);

pos=find(node_on_boundary);
boundary_chaos=[x(pos) y(pos)];
ind=convhull(boundary_chaos(:,1),boundary_chaos(:,2));

xa=boundary_chaos(ind(1),1);
xb=boundary_chaos(ind(2),1);
ya=boundary_chaos(ind(1),2);
yb=boundary_chaos(ind(2),2);


   
n00=find(x==xa & y==ya);
n10=find(x==xb & y==yb);
n1=n10;
n0=n00;
cont=[n0 n1];

   
while (n1~=n00),
   
   els=find(index(:,1)==n1 | index(:,2)==n1 | index(:,3)==n1);
   possible_nodes=zeros(2*length(els),1);
   for n=1:length(els),
   other_pos=find(index(els(n),:)~=n1);
   possible_nodes(2*n-1,:)= index(els(n),other_pos(1));
   possible_nodes(2*n,:)=index(els(n),other_pos(2));
	end
potential_node=possible_nodes(1);

n0n1=[x(n1)-x(n0)
   y(n1)-y(n0)];
n0n1_unit=n0n1/norm(n0n1);
ny=flipud(n0n1_unit);
ny(1)=-ny(1);
possible_angles=zeros(length(possible_nodes),1);

for n=1:length(possible_nodes),
   if (possible_nodes(n)~=n0),
	    u=[x(possible_nodes(n))-x(n1)
  	    y(possible_nodes(n))-y(n1)];
  	    ux=sum(u.*n0n1_unit);
  	    uy=sum((u-ux*n0n1_unit).*ny);
         possible_angles(n)=atan2(uy,ux);
      else
         possible_angles(n)=NaN;
   end
end
pos=find(possible_angles==min(possible_angles));
potential_node=possible_nodes(pos(1));

cont=[cont
   [n1 potential_node]];
n0=n1;
n1=potential_node;
end

ind=cont(2:length(cont),1);


