function DAT = cdf_env(loc,n1,sims,bins)

%CDF_ENV computes cdf for pop 1 in a two-population point pattern,
%and in addition, computes the outer envelopes of the cdf's for 
%a set of random relabelings of the pattern.

%Written by: TONY E. SMITH, 2/4/98

%Programs Called: LCDF.m
%
% INPUTS:
%     (i)   loc  = combined location file [loc(i)=(Xi, Yi),i=1..n]
%                  where n = n1 + n2. It is assumed that points for
%                  pop 1 are in the first n1 rows.]
%     (ii)  n1   = size of pop 1.
%     (iii) sims = number of relabelings
%      (iv) bins = number of point values to use in distance range.

% OUTPUTS: (1x4)-cell array, DAT
%     (i)   DAT{1} = (n1 x bins) array of CDF's for pop 1 points.
%     (ii)  DAT{2} = (n1 x bins) array of Upper Envelopes.
%     (iii) DAT{3} = (n1 x bins) array of Lower Envelopes.
%     (iv)  DAT{4} = (1 x bins) array of distance values.
%           [Here the max pairwise distance, Dmax, is computed
%           and distance, d = Dmax/2, then defines the distance 
%           range. Hence each bin, k = 1,.., bins, is associated 
%           with distance value, dist(k) = (k/(bins - 1))*d.] 


[n,m] = size(loc) ;

%Compute Dmax

i = 1 ;

Dmax = 0 ;

while i < n
   
   j = i + 1 ;
   
   while j <= n
      
      Dis = norm(loc(i,:) - loc(j,:));
          
      if Dis > Dmax
         
         Dmax = Dis ;
         
      end
               
      j = j + 1 ;
               
   end
   
   i = i + 1 ;
   
end

%Compute Upper and Lower Envelopes

U = zeros(n1,bins) ; %Upper envelopes

L = ones(n1,bins) ;  %Lower envelopes

i = 1 ;

while i <= sims
   
   %Form random relabeled sample
   
   list = randperm(n) ;
   
   sample = list(1:n1) ;
   
   LL = zeros(n1,2) ;
   
   for j = 1:n1
      
      LL(j,:) = loc(sample(j),:) ;
      
   end
   
   %Construct Envelopes
   
   X = LCDF(LL,bins,Dmax) ;
        
   U = max(U,X) ;
   
   L = min(L,X) ;
   
   i = i + 1 ;
   
end

%Compute CDF's for Pop 1

LL = loc(1:n1,:) ;

CDF = LCDF(LL,bins,Dmax) ;


%Compute Distances

d = Dmax/2 ;

inc = d/(bins - 1) ;

D = 0:inc:d ;


%Finally, define output

DAT = cell(1,4) ;

DAT{1} = CDF ;

DAT{2} = U ;

DAT{3} = L ;

DAT{4} = D ;
