
function C = count_loc(loc,ref,b,Dmax)

% COUNT_LOC.M computes local K-Functions for k_count_loc.m

% Written by: TONY E. SMITH, 5/11/99

% INPUTS:
%     (i)   loc  = file of point locations (xi,yi), i=1:N
%		(ii)  ref  = file of reference locations (xk,yk), k =1:n
%     (iii)  b   = number of bins to use in CDF
%     (iv)  Dmax = max distance to be considered (this will
%                  usually be half the max pairwise dists in loc) 
%
% OUTPUTS: DAT = (n:b) vector containing Point Counts

% List of Variables:
% N,n,D,k,ub,C,n,bb,bin,Tot

% Assertions for compiling

mbrealscalar(Dmax);
mbintscalar(b) ;

% Initialize values

N = length(loc(:,1)) ;

n = length(ref(:,1)) ;

C = zeros(n,b) ;%Matrix of counts

ub = ones(b,1);

Freq = zeros(1,b) ; %Vector of frequency counts

% Start

for i = 1:n
   
   % Compute distances from i to loc points
   
   for k = 1:N
      
      Dist = sqrt((ref(i,1) - loc(k,1))^2 + ...
         (ref(i,2) - loc(k,2))^2);                 
            
   end   
   
	%Count of point frequencies

   
   if Dist <= Dmax
      
      bb = ceil((Dist/Dmax)*b);
      
      bin = max([1,bb]); %allows zero dists
      
      Freq(bin) = Freq(bin) + 1 ; %adds to frequency count     
               
   end
                  

	%Construct Cumulative Frequencies

	
   for k = 1:b-1
      
      Freq(k + 1) = Freq(k + 1) + Freq(k) ;
      
   end
   
   C(i,:) = Freq ;
   
end




