function prediction = zeroth(x, m, tau, min_neighbors, r, r_factor, s)
%
% This function is an implementation of the zeroth function for the TISEAN
% package.  
%
% arguments
%  x: observed data
%  m: embedding dimensions
%  tau: embedding delay
%  min_neighbors: minimum number of neighbors
%  r: neighborhood radius
%  r_factor: factor to increase the neighborhood size
%  s: number of steps to forecast
%

% length of the original observed data
%
lenx = length(x);

% we must first estimate the state space using embedding 
%
X = delay_reconstruct(x, tau, m);

lenX = length(X(:,1));

prediction = [];
    
% first, we find the state closest to the last state in our
% reconstructed phase space
%
state = 0;
distance = inf;
    
% find neighbors
%
neighbors = [];
    
while (length(neighbors) < min_neighbors+1)
      
    for j=1:length(X(:,1))
            
        dim = [];
        
        for k=1:length(X(1,:))
            dim = [dim, (X(lenX,k)-X(j,k))^2]; 
        end
        
        sumdim = sum(dim);
        distance = sumdim^(1/2);
            
        if (distance < r)
            if (length(find(neighbors==j,1)) == 0)
                neighbors = [neighbors, j];
            end
        end
    end        
    
    r = r * r_factor;
end
    
% convert the indices to match with observed time series.
% the current neighbor indices are for the state space
%
new_neighbors = [];

for j=1:length(neighbors)        

    temp = neighbors(j) + ((m-1)*tau);     
    
    % make sure we didn't pick up neighbors too close to our
    % reference state
    %
    if (temp + s < lenx)
        new_neighbors = [new_neighbors, temp];
    end
end
    
neighbors = new_neighbors;

for i=1:s
    
    % now we average the values at the neighbor indices
    %
    avg = mean(x([neighbors+i]));
    
    prediction = [prediction,avg];
end