function PVal = k12_shift(L1,L2,xmin,xmax,ymin,ymax,sims,D,s)

% K12_SHIFT compares two point populations L1,L2 in a (len x hgt) box by
% simulating many random shifts of L2 (with L1 fixed) and computing
% K12-values for a range D of distance values. P-values are then computed,
% reflect significant attraction and/or repulsion between these patterns.
% 
% NOTE 0: Must have Dmax <= min( xmax - xmin, ymax - ymin)/2 so that counts
%         are well defined.
% 
% NOTE 1: By convention, low P-Values here correspond to significant
%         ATTRACTION between patterns.
% 
% NOTE 2: Ties are treated neutrally, adding .5 rather 1 to rankings.
% 
% Written by: TONY E. SMITH, 12/2/01 [modified 1/4/07]
% 
% INPUTS:
%     (i)   L1,L2  = locations,(xi,yi), of pops 1 and 2
%     (ii)  n1,n2  = sizes of pops 1 and 2
%     (iii) xmin,xmax,ymin,ymax = box limits
%     (iv)  sims = number of simulations
%     (v)   D  = vector of distance values (ordered low to high)
%     (vi)  s  = (optional) random seed
%     
% OUTPUTS:  PVal = Vector of P-Values at each distance in D .
%
% SCREEN OUTPUT:  A plot of P-Values against distances in D.

%Check Dmax

len = xmax - xmin;

hgt = ymax - ymin;

Dmax = max(D);

if Dmax > min(len,hgt)/2
    
    error('MUST have Dmax <= min( xmax - xmin, ymax - ymin)/2')
    
end

% Initial Calculations

B = length(D);
n1 = size(L1,1);

%Construct Tiling of L2

L20 = L2;

L21 = [L2(:,1)+len,L2(:,2)];

L22 = [L2(:,1)-len,L2(:,2)];

L23 = [L2(:,1)    ,L2(:,2)+hgt];

L24 = [L2(:,1)+len,L2(:,2)+hgt];

L25 = [L2(:,1)-len,L2(:,2)+hgt];

L26 = [L2(:,1)    ,L2(:,2)-hgt];

L27 = [L2(:,1)+len,L2(:,2)-hgt];

L28 = [L2(:,1)-len,L2(:,2)-hgt];

LL2 = [L20;L21;L22;L23;L24;L25;L26;L27;L28]; %Full Tiling

n2 = size(LL2,1);

%************************
%COMPUTE COUNTS for Pop1
%************************

%Compute pairwise distances

C = point_counts(L1,LL2,D);

%Compute Output

C0 = sum(C) ; %sum columns of C to get total counts

count = ones(1,B); % start with C0 >= C0 count [1/4/07]

%Start Simulations

if exist('s')
    
    rand('seed',s);
    
end

i = 1 ;

index = 10 ;

while i <= sims   
      
   C = k12_shift_count(L1,LL2,n1,n2,len,hgt,D);
        
   inc = zeros(1,B);
   
   for j = 1:B
      
      if C(j) > C0(j)
         
         inc(j) = 1;
         
      elseif C(j) == C0(j)
            
         inc(j) = .5;
            
      else  
         
         inc(j) = 0;
         
      end
      
   end
   
   
   count = count + inc; 
   
   
    if 100*(i/sims)>= index
      
      disp(['percent_done = ', num2str(index)]);
      
      index = index + 10;
     
    end

   
   i = i + 1 ;
   
end %while


%Compute p-values 

PVal = count ./ (sims+1) ; %Small if attraction is strong 


