
function C = count(loc,b,Dmax)

% COUNT.M computes the raw k-Function for k_env.m

% Written by: TONY E. SMITH, 5/11/99

% INPUTS:
%     (i)   loc = file of locations (xi,yi), i=1..m
%     (ii)  b   = number of bins to use in CDF
%     (iii) Dmax = max pairwise distance to be considered
%              (this is usually half the max pairwise dist) 
%
% OUTPUTS: C = (1:b) vector containing Point Count

% List of Variables:
% m,D,k,ub,C,n,bb,bin,Tot

% Assertions for compiling

%mbrealscalar(Dmax);
%mbintscalar(b) ;


% start

m = length(loc(:,1)) ;

%Compute pairwise distances

D = zeros(m*(m-1)/2, 1) ; %Matrix of loc-dist pairs

i = 1 ;

k = 1 ;  %counter for D.

while i < m
   
   j = i + 1 ;
   
   while j <= m
      
      D(k) = sqrt((loc(i,1) - loc(j,1))^2 + ...
         (loc(i,2) - loc(j,2))^2);
                   
      j = j + 1 ;
      
      k = k + 1 ;
      
   end
   
   i = i + 1 ;
   
end

%Count of point frequencies

ub = ones(b,1);

C = zeros(1,b) ;

n = length(D) ; %number of distinct point pairs

k = 1 ;

while k <= n 
   
   if D(k) <= Dmax
      
      bb = ceil((D(k)/Dmax)*b);
      
      bin = max([1,bb]); %allows zero dists
      
      C(bin) = C(bin) + 2 ; %adds (ij) and (ji)      
               
   end
                  
   k = k + 1 ;
   
end

%Construct Cumulative Counts

k = 1 ;

while k < b
   
   C(k + 1) = C(k + 1) + C(k) ;
   
   k = k + 1 ;
   
end

DAT = C ;



