function PVal = k2_glob(loc,n1,sims,D)

%K2_GLOB compares two point populations, and computes p-values for 
%clustering of pop1 relative to pop1 + pop2.

%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 ;

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;
         
      else
         
         inc(j) = 0;
         
      end
      
   end
   
   
   count = count + inc; 
   
   
    if 100*(i/sims)>= index
      
      percent_done = index
      
      index = index + 10;
     
   end

   
   i = i + 1 ;
   
end


%Compute p-values

u = ones(1,B);

PVal = (count+u) ./ ((sims+1)*u) ;


