
function DAT = k2ct_glo(loc,D)

% This program computes k-counts for k2_glob and k2_local

% Written by: TONY E. SMITH, 6/18/99

% INPUTS:
%     (i)   loc  = file of locations (xi,yi), i=1..m
%     (ii)    D  = vector of distance values (ordered low to high)

% OUTPUTS: DAT = (D x 1) vector of counts

%compiling initialization

mbrealvector(D);

m = length(loc(:,1)) ;

%Compute pairwise distances

Dist = zeros(m*(m-1)/2, 3) ; %Matrix of loc-dist pairs

i = 1 ;

k = 1 ;  %counter for D.

while i < m
   
   j = i + 1 ;
   
   while j <= m
      
      Dist(k,1) = sqrt((loc(i,1) - loc(j,1))^2 + ...
         (loc(i,2) - loc(j,2))^2);

      Dist(k,2) = i ;
      
      Dist(k,3) = j ;  
                
      j = j + 1 ;
      
      k = k + 1 ;
      
   end
   
   i = i + 1 ;
   
end

%Count point frequencies

B = length(D);

C = zeros(m,B) ;

[M,junk] = size(Dist) ;

Dmax = max(D); %maximum relevant distance

mbrealscalar(Dmax);

Dmin = min(D); %minimum relevant distance

mbrealscalar(Dmin);


k = 1 ;

while k <= M 
   
  
   if Dist(k,1) <= Dmax
                        
      i = Dist(k,2) ;
      
      j = Dist(k,3) ; 
      
      if Dist(k,1) <= Dmin
         
         C(i,:) = C(i,:) + 1;
         
         C(j,:) = C(j,:) + 1;
         
      else
         
         dist = max([Dist(k,1),Dmin]);
         
         mbrealscalar(dist);
         
         b = B ;
         
         while D(b) >= dist
         
         	C(i,b) = C(i,b) + 1 ;
         
         	C(j,b) = C(j,b) + 1 ; %add to both i and j 
         
         	b = b - 1 ;
         
         end
         
      end %end if >=
      
   end %end if <=
   
   k = k + 1 ;
   
end

%Compute Output

   
DAT = sum(C) ; %sum columns of C to get total counts
   


