function varargout = shepards(X,x,v,n);
%SHEPARDS - (X,x,v,n); 3D nearest-neighbor interpolation using Shepard's weighting
% function varargout = shepards(X,x,v,n);
%
% Inputs
% v : Nxt array of data to be interpolated
% x : Nx3 array of original locations 
% X : NN x 3 array of locations onto v will be interpolated
% n : Number of nearest neighbors to be considered in the interpolation (default is 8)
%
% Outputs
% V : NN x t array of interpolated measures

%<autobegin> ---------------------- 26-May-2004 11:34:22 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Utility - Numeric
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\norlig.m
%
% At Check-in: $Author: Mosher $  $Revision: 12 $  $Date: 5/26/04 10:02a $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 24-May-2004
% 
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
%    University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
%    Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
%    CNRS, Hopital de la Salpetriere, Paris, France
% 
% See BrainStorm website at http://neuroimage.usc.edu for further information.
% 
% Copyright (c) 2004 BrainStorm by the University of Southern California
% This software distributed  under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
% 
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 26-May-2004 11:34:22 -----------------------


if nargin == 3
    n = 8; % Default number of neighbors for interpolation
end

varargout{1} = zeros(size(X,1),size(v,2));

%Wmat = sparse(size(X,1),size(v,1));
Wmat = spalloc(size(X,1),size(v,1),n*size(X,1));

for node = 1:size(X,1)
     
    dist2grid = norlig(x - ones(size(x,1),1)*X(node,:));
    [dist2grid isort] = sort(dist2grid);
    icube = isort(1:n); 
    dist2cube = dist2grid(1:n); 
    clear dist2grid isort

    R = max(dist2cube);
    W = power((R - dist2cube)./ (R*dist2cube),2); % Interpolation weights from Shepards method
    W = W/sum(W);
    
    Wmat(node,icube) = W; 
    
end

varargout{1} = Wmat * v;

if nargout > 1
    varargout{2} = Wmat;
end
