function [outl,index]=outl2(p,A,xa,ya,dgrid,ddata)

% OUTL2       Calculates the distance of points outside a p% contour level.
%
%             OUTL2(P,DENSITY) calculates contour levels for the
%             percentages in P and the (pre-calculated) densities 
%             in DENSITY.
%
%             Christian C. Beardah 1994

n=length(ddata);

x=A(:,1);
y=A(:,2);

p=100-p;

[order index]=sort(ddata);

m=ceil(n*p/100);

if m==0,
  w=0.9*order(1); 
end;

if m>0 & m<n,
  w=(order(m)+order(m+1))/2;
end;

if m==n,
  w=(order(n-1)+order(n))/2;
end;

dtest=(dgrid>w);

[ip,jp]=find(dtest);

for k=1:length(ip),
  hpt(k,:)=[xa(jp(k)) ya(ip(k))];
end;

for k=1:m,
  vec=ones(length(ip),1)*A(index(k),:)-hpt(1:length(ip),:);
  for l=1:length(ip),
    nvec(l,1)=norm(vec(l,:));
  end;
  mvec(k,1)=min(nvec);
end;

outl=[index(1:m), x(index(1:m)), y(index(1:m)), ddata(index(1:m)), mvec];

hold off;