function OUT = ce_test(pts,a,m,test)

% CE_TEST.M performs the Clark-Evans tests.
%         
% NOTE: These tests use a random subsample (size = m) of the 
%       full sample of n nearest-neighbor distances, and 
%       ignore edge effects.

% Written by: TONY E. SMITH, 12/28/99

% INPUTS: 
%      (i)  pts  = file of point locations (xi,yi), i=1..n
%     (ii)    a  = area of region
%    (iii)    m  = sample size (m <= n)
%     (iv)  test = indicator of test to be used
%                  0 = two-sided test for randomness
%                  1 = one-sided test for clustering
%                  2 = one-sided test for dispersion
%
% OUTPUTS: Dist = vector of all nearest-neighbor distances
%
% SCREEN OUTPUT: critical z-value and p-value for test


%Construct Nearest-Neighbor Distances

[n,junk] = size(pts);  %number of points

M = distance_mat(pts);

area = a;

mx = max(max(M));

M = M + mx*eye(n) ; %add to diagonal to avoid zero case

DD = min(M);

%Take subsample

r_list = randperm(n);

list = r_list(1:m);

D = DD(list);

%Construct Clark-Evans Statistic

lam = n/area; %based on full set of points 

mu = 1/(2*sqrt(lam));

var = (4 - pi)/(m*4*lam*pi); %based on sample

sig = sqrt(var);

Dbar = (1/m)*sum(D); 

Z = (Dbar - mu)/sig;

if exist('normcdf') == 2
   
   if test == 0
      
      P = 2*normcdf(-abs(Z),0,1);
      
   elseif test == 1
      
      P = normcdf(Z,0,1);
      
   elseif test == 2
      
      P = 1 - normcdf(Z,0,1);
      
   else 
      
      error('input value for test is wrong') 
      
   end
   
end

   
%Make screen output    
    
if test == 0
   
   disp(' '); 
   disp('RESULTS OF TEST FOR RANDOMNESS')
   disp(' '); 
   disp(['Z_Value = ',num2str(Z)]);
   disp(' ');
   
   
   if exist('normcdf') == 2 
      
      disp(['P_Value = ',num2str(P)]); 
      disp(' ');
      
   end
   
elseif test == 1
   
   disp(' '); 
   disp('RESULTS OF TEST FOR CLUSTERING')
   disp(' '); 
   disp(['Z_Value = ',num2str(Z)]);
   disp(' ');
   
   
   if exist('normcdf') == 2 
      
      disp(['P_Value = ',num2str(P)]);
      disp(' ');
      
   end
   
      
else
   
   disp(' '); 
   disp('RESULTS OF TEST FOR UNIFORMITY')
   disp(' '); 
   disp(['Z_Value = ',num2str(Z)]);
   disp(' ');
   
   
   if exist('normcdf') == 2 
      
      disp(['P_Value = ',num2str(P)]);       
      disp(' ');
      
   end

   disp(' ');
   
end

OUT = full(DD)';



