
function DAT = k12_perm_count(loc,n1,Dist,D)

% This program computes k12-counts for k12_perm 

% Written by: TONY E. SMITH, 6/18/99

% INPUTS:
%     (i)   loc  = locations,(xi,yi), of pops 1 and 2 (pop 1 on top)
%     (ii)   n1  = size of pop 1
%     (iii) Dist = vector of distance values from loc
%     (iv)     s = randon seed


% OUTPUTS: (i)  DAT = (D x 1) vector of k12-counts
%          (ii)   s = new random seed


%compiling initialization

%mbrealvector(Dist);
%mbrealvector(D);

n = length(loc);

n2 = n - n1;

%random permutation of pops

list = randperm(n);

I1 = list(1:n1);

I2 = list(n1+1:n);


%Count point frequencies


B = length(D);

C = zeros(n1,B) ;

Dmax = D(B); %maximum relevant distance

%mbrealscalar(Dmax);

Dmin = D(1); %minimum relevant distance

%mbrealscalar(Dmin);


for i = 1:n1
   
   I = I1(i);
   
   for j = 1:n2
      
      J = I2(j);
      
      K = n*(I-1) - (I*(I-1)/2) + (J-I); %Counting rule for finding d(I,J) in Dist
      
      dist = Dist(K);
      
      %mbrealscalar(dist);
      
      if dist <= Dmax
         
         if dist <= Dmin %j in all rings
            
            C(i,:) = C(i,:) + 1;
            
         else
            
            b = B;
            
            while D(b) >= dist
               
               C(i,b) = C(i,b) + 1;
               
               b = b -1; %b = 1 already done
               
            end
            
         end %if <= Dmin
         
      end %if <= Dmax 
      
   end % for j
   
end %for i


%Compute Output

DAT = sum(C) ; %sum columns of C to get total counts


   

   
       

