function OUT = dist_wts_k(X,k)

%DIST_WTS_k computes the values of the k nearest neighbors to points.

%INPUTS: X = (Nx3) matrix (Xi,Yi,Zi),i=1:N (Xi,Yi) = coords, Zi = value
%        
%   		k = number of nearest neighbors to be considered.
%        
%
%OUTPUTS: OUT = [Nx(k+3)] matrix 
%                   specified.
%         OUT(i,1:2)   = coordinates of i
%			 OUT(i,3)     = Z-value of i
%			 OUT(i,4:k+3) = Z-values of k nearest neighbors

L = X(:,1:2) ;

OUT(:,1:3) = X ;

N = length(L(:,1)) ;

k = min(k,N) ; %guarantees k not too big


i = 1 ;

p = k + 3 ;

while (i <= N)
   
   D = sqrt( (L(i,1)-L(:,1)).^2 + (L(i,2) - L(:,2)).^2 ) %distances to i
   
   D(i)= max(D) + 1 ; %Eliminate diagonal elements as n-neighbors.   
    
   Y(:,1) = [1:N]' ;
   
   Y(:,2) = D ;
   
   Y = sortrows(Y,2) ; %orders distances to i
   
   nn = Y(1:k,1) ; %list of k nearest neighbors
   
   OUT(i,4:p) = X(nn,3)' ;
   
   i = i + 1 
   
end

   
  
