function P = k2_local(loc,n1,sims,D)

%K2_LOCAL compares two point populations, and computes P-values for 
%clustering at EACH POINT of pop1 relative to pop1 + pop2. 

%NOTE: All "ties" are assumed to contribute half above and half below 
%the given target count.


%Written by: TONY E. SMITH, 6/18/99

%Programs Called: dist_vec, k2ct_loc, rand_perm
%
% INPUTS:
%     (i)   loc  = combined location file [loc(i)=(Xi, Yi),i=1..n]
%                  where n = n1 + n2. It is assumed that points for
%                  pop1 are in the first n1 rows.]
%     (ii)  n1   = size of pop1.
%     (iii) sims = number of relabelings
%     (iv)  D = vector of distance values at which to measure clustering.

% OUTPUTS: Matrix of P-values (Pij) for each point i at distance j.


%compiling initializations

%mbintscalar(n1);

%mbintscalar(sims);


%seed value

s = 897; %yields .02

rand('seed',s);

[n,junk] = size(loc) ;

B = length(D);


%Compute counts for Pop1

LL = loc(1:n1,:) ;

C0 = k2ct_loc(LL,D,0) ;

count = zeros(n1,B);

%Start Simulations

index = 10;

for k = 1:sims
   
   %Form random relabeled sample
   
   list = randperm(n) ;
   
   sample = list(1:n1) ;
   
   LL = loc(sample,:);
   
     
   %Add to order counts
   
   c = k2ct_loc(LL,D,1) ;
        
   for i = 1:n1      
   
	   inc = zeros(1,B);
   
   	for j = 1:B
      
      	if c(j) > C0(i,j)
         
         	inc(j) = 1;
         
         elseif c(j) == C0(i,j);
            
            inc(j) = .5;
            
         else
            
         	inc(j) = 0;
         
      	end
      
   	end
   
     	count(i,:) = count(i,:) + inc;  
      
     end %end k-counts
              

end %end simulations


%Compute p-values

U = ones(n1,B);

P = (count+U) ./ ((sims+1)*U) ;

