function PVALS = space_time_local_pvals(LT,D,T,sims)

%SPACE_TIME_LOCAL_PVALS computes space-time K-function at each point for a given 
%space-time pattern, and in addition, computes the (cluster) P-values for these
%points relative to a sample of random time relabelings. 

%Written by: TONY E. SMITH, 2/7/05

%Functions called: space_time_localct.m
%
%INPUTS:
%        (i)    LT = (N x 3)-matrix of N loc-times (Xi,Yi,Ti)
%        (ii)    D = (nD x 1)-vector of nD distance values
%        (iii)   T = (nT x 1)-vector of nT time values
%        (iv) sims = number of simulated relabelings

% OUTPUTS: PVALS = (nD x nT x N) array of P-values 


% rand_seed = 100000*rand(1,1)
% 
% rand('seed',rand_seed);

%Compute pairwise distances and Dmax

loc = LT(:,1:2);

DIST = distance_mat(loc) ; %Matrix of pairwise distances

%Compute counts for observed space-time pattern

disp(' ');
disp('COMPUTE OBSERVED COUNTS');
disp(' ');

F0 = space_time_local(LT,D,T,DIST);

N = size(LT,1) ;

nD = length(D);

nT = length(T);

COUNT = ones(nD,nT,N);

disp('START SIMULATION');
disp(' ');
index = 10;

for i = 1:sims
    
    I = randperm(N);
    
    LTi = LT;
    
    LTi(:,3) = LT(I,3);
    
    Fi = space_time_local(LTi,D,T,DIST);
    
    GREATER = (Fi > F0);
    
    EQUAL = (Fi == F0);
    
    COUNT = COUNT + GREATER + .5*EQUAL;
    
    if 100*(i/sims)>= index
      
      disp(['percent_done = ', num2str(index)]);
      
      index = index + 10;
     
    end
    
end

PVALS = COUNT/(1 + sims);


    
    
    
     




