function PVal = k2_global(loc,n1,sims,D,s)

%K2_GLOBAL compares two point populations, and computes P-values for 
%clustering of pop1 relative to pop1 + pop2.

%NOTE 1: By convention, P-Values at each distance h are here defined to be  
%        the probability of a frequency count greater than the observed
%        value IF pop1 were a random draw from pop1 + pop2. So low P-Values 
%        correspond to significant CLUSTERING of pop1 vs the combined pop.

%NOTE 2: Ties are treated neutrally, adding .5 rather 1 to rankings.

%Written by: TONY E. SMITH, 6/18/99

%Programs Called: k2ct_glo, 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.
%     (v)   s    = seed for random number generator

% OUTPUTS:  PVal = Vector of P-Values at each distance.


%compiling initializations

%mbintscalar(n1);

%mbintscalar(sims);

%mbintscalar(s);


[n,junk] = size(loc) ;

B = length(D);


%Compute counts for Pop1

LL = loc(1:n1,:) ;

C0 = k2ct_glo(LL,D) ;

count = zeros(1,B);

%Start Simulations

i = 1 ;

index = 10 ;

rand('seed',s);

while i <= sims
   
   %Form random relabeled sample
   
   list = randperm(n) ;
   
   sample = list(1:n1) ;
   
   LL = loc(sample,:);
   
     
   %Add to order counts
   
   C = k2ct_glo(LL,D) ;
        
   inc = zeros(1,B);
   
   for j = 1:B
      
      if C(j) > C0(j)
         
         inc(j) = 1;
         
      elseif C(j) == C0(j)
         
         inc(j) = 0.5;
         
      else
         
         inc(j) = 0;
         
      end
      
   end
   
   
   count = count + inc; 
   
   
    if 100*(i/sims)>= index
      
      disp(['percent_done = ', num2str(index)]);
      
      index = index + 10;
     
   end

   
   i = i + 1 ;
   
end


%Compute p-values

u = ones(1,B);

PVal = count ./ ((sims+1)*u) ;


