function [zi,tri_ret,out_ret] = griddata_jvm(x,y,z,xi,yi,method,tri_in,out_in)
%GRIDDATA_JVM Data gridding and surface fitting.
%   This is a modified version of GRIDDATA, the standard matlab routine.
%   It can only be called with:
%     [ZI,TRI_RET,OUT_RET] = GRIDDATA_JVM(X,Y,Z,XI,YI,METHOD,TRI_IN,OUT_IN)

%   GRIDDATA_JVM returns the same answers as GRIDDATA but in some circumstances
%   is much quicker. Specifically, if the method is 'linear' then the arrays
%   TRI_IN & OUT_IN can be used in doing the linear interpolation. TRI_IN &
%   OUT_IN depend only on the grids specified by X, Y, XI & YI. Thus we could
%   imagine that if we have to do numerous interpolations on the same grids then
%   we might do one first with TRI_IN == OUT_IN == []. This will then work the
%   same as a normal call to GRIDDATA (involving the calculation of TRI & OUT)
%   but return TRI_RET & OUT_RET. These can then be used as the input arrays in
%   future calls to GRIDDATA_JVM. In some tests as much as 90% of the time taken
%   by a call to GRIDDATA is taken up in the calculation of these 2 arrays. (For
%   historical reasons ests were done where size(xi) == 762x836 and size(x) ==
%   51x167.)
  
% $Id: startup-xemacs.el,v 1.1 2003/08/20 01:56:32 man133 Exp man133 $
% Copyright J. V. Mansbridge, CSIRO, Thu Aug 28 17:39:35 EST 2003

% The following comments are from the original GRIDDATA function.  
  
%   ZI = GRIDDATA(X,Y,Z,XI,YI) fits a surface of the form Z = F(X,Y)
%   to the data in the (usually) nonuniformly-spaced vectors (X,Y,Z)
%   GRIDDATA interpolates this surface at the points specified by
%   (XI,YI) to produce ZI.  The surface always goes through the data
%   points.  XI and YI are usually a uniform grid (as produced by
%   MESHGRID) and is where GRIDDATA gets its name.
%
%   XI can be a row vector, in which case it specifies a matrix with
%   constant columns. Similarly, YI can be a column vector and it 
%   specifies a matrix with constant rows. 
%
%   [XI,YI,ZI] = GRIDDATA(X,Y,Z,XI,YI) also returns the XI and YI
%   formed this way (the results of [XI,YI] = MESHGRID(XI,YI)).
%
%   [...] = GRIDDATA(...,'method') where 'method' is one of
%       'linear'    - Triangle-based linear interpolation (default).
%       'cubic'     - Triangle-based cubic interpolation.
%       'nearest'   - Nearest neighbor interpolation.
%       'v4'        - MATLAB 4 griddata method.
%   defines the type of surface fit to the data. The 'cubic' and 'v4'
%   methods produce smooth surfaces while 'linear' and 'nearest' have
%   discontinuities in the first and zero-th derivative respectively.  All
%   the methods except 'v4' are based on a Delaunay triangulation of the
%   data.
%
%   See also GRIDDATA3, GRIDDATAN, DELAUNAY, INTERP2, MESHGRID.

%   Clay M. Thompson 8-21-95
%   Copyright 1984-2002 The MathWorks, Inc. 
%   $Revision: 5.33 $  $Date: 2002/04/09 00:14:22 $

% t2_st = now;

error(nargchk(5,8,nargin))

[msg,x,y,z,xi,yi] = xyzchk(x,y,z,xi,yi);
if ~isempty(msg), error(msg); end

if nargin<6, method = 'linear'; end
if ~isstr(method), 
  error('METHOD must be one of ''linear'',''cubic'',''nearest'', or ''v4''.');
end

if nargin<7, tri_in = []; end
if nargin<8, out_in = []; end

% Sort x and y so duplicate points can be averaged before passing to delaunay

% Need x,y and z to be column vectors
sz = prod(size(x));
x = reshape(x,sz,1);
y = reshape(y,sz,1);
z = reshape(z,sz,1);
sxyz = sortrows([x y z],[2 1]);
x = sxyz(:,1);
y = sxyz(:,2);
z = sxyz(:,3);
myeps = max(max(abs(x)),max(abs(y)))*eps^(1/3);
ind = [0; ((abs(diff(y)) < myeps) & (abs(diff(x)) < myeps)); 0];
if sum(ind) > 0
  warning('MATLAB:griddata:DuplicateDataPoints',['Duplicate x-y data points ' ...
            'detected: using average of the z values.']);
  fs = find(ind(1:end-1) == 0 & ind(2:end) == 1);
  fe = find(ind(1:end-1) == 1 & ind(2:end) == 0);
  for i = 1 : length(fs)
    % averaging z values
    z(fe(i)) = mean(z(fs(i):fe(i)));
  end
  x = x(~ind(2:end));
  y = y(~ind(2:end));
  z = z(~ind(2:end));
end

switch lower(method),
  case 'linear'
    [zi,tri_ret,out_ret] = linear(x,y,z,xi,yi,tri_in,out_in);
  case 'cubic'
    zi = cubic(x,y,z,xi,yi);
  case 'nearest'
    zi = nearest(x,y,z,xi,yi);
  case {'invdist','v4'}
    zi = gdatav4(x,y,z,xi,yi);
  otherwise
    error('Unknown method.');
end
  
% t2_fi = now;
% disp(['griddata_jvm took ' num2str((t2_fi - t2_st)*86400) ' secs'])

%------------------------------------------------------------
function [zi,tri_ret,out_ret] = linear(x,y,z,xi,yi,tri,out)
%LINEAR Triangle-based linear interpolation

%   Reference: David F. Watson, "Contouring: A guide
%   to the analysis and display of spacial data", Pergamon, 1994.

siz = size(xi);
xi = xi(:); yi = yi(:); % Treat these as columns
x = x(:); y = y(:); % Treat these as columns

if isempty(tri)
  % Triangularize the data
  tri = delaunayn([x y]);
  if isempty(tri),
    warning('MATLAB:griddata:CannotTriangulate','Data cannot be triangulated.');
    zi = repmat(NaN,size(xi));
    return
  end
  
  % Find the nearest triangle (t)
  t = tsearch(x,y,tri,xi,yi);
  
  % Only keep the relevant triangles.
  out = find(isnan(t));
  if ~isempty(out), t(out) = ones(size(out)); end
  tri = tri(t,:);
  tri_ret = tri;
  out_ret = out;
else
  tri_ret = [];
  out_ret = [];
end

% Compute Barycentric coordinates (w).  P. 78 in Watson.
del = (x(tri(:,2))-x(tri(:,1))) .* (y(tri(:,3))-y(tri(:,1))) - ...
      (x(tri(:,3))-x(tri(:,1))) .* (y(tri(:,2))-y(tri(:,1)));
w(:,3) = ((x(tri(:,1))-xi).*(y(tri(:,2))-yi) - ...
          (x(tri(:,2))-xi).*(y(tri(:,1))-yi)) ./ del;
w(:,2) = ((x(tri(:,3))-xi).*(y(tri(:,1))-yi) - ...
          (x(tri(:,1))-xi).*(y(tri(:,3))-yi)) ./ del;
w(:,1) = ((x(tri(:,2))-xi).*(y(tri(:,3))-yi) - ...
          (x(tri(:,3))-xi).*(y(tri(:,2))-yi)) ./ del;
w(out,:) = zeros(length(out),3);

z = z(:).'; % Treat z as a row so that code below involving
            % z(tri) works even when tri is 1-by-3.
zi = sum(z(tri) .* w,2);

zi = reshape(zi,siz);

if ~isempty(out), zi(out) = NaN; end
%------------------------------------------------------------

%------------------------------------------------------------
function zi = cubic(x,y,z,xi,yi)
%TRIANGLE Triangle-based cubic interpolation

%   Reference: T. Y. Yang, "Finite Element Structural Analysis",
%   Prentice Hall, 1986.  pp. 446-449.
%
%   Reference: David F. Watson, "Contouring: A guide
%   to the analysis and display of spacial data", Pergamon, 1994.

% Triangularize the data
tri = delaunayn([x(:) y(:)]);
if isempty(tri), 
  warning('MATLAB:griddata:CannotTriangulate','Data cannot be triangulated.');
  zi = repmat(NaN,size(xi));
  return
end

% Find the nearest triangle (t)
t = tsearch(x,y,tri,xi,yi);

zi = cubicmx(x,y,z,xi,yi,tri,t);
%------------------------------------------------------------

%------------------------------------------------------------
function zi = nearest(x,y,z,xi,yi)
%NEAREST Triangle-based nearest neightbor interpolation

%   Reference: David F. Watson, "Contouring: A guide
%   to the analysis and display of spacial data", Pergamon, 1994.

siz = size(xi);
xi = xi(:); yi = yi(:); % Treat these a columns
x = x(:); y = y(:); z = z(:); % Treat these as columns

% Triangularize the data
tri = delaunayn([x y]);
if isempty(tri), 
  warning('MATLAB:griddata:CannotTriangulate','Data cannot be triangulated.');
  zi = repmat(NaN,size(xi));
  return
end

% Find the nearest vertex
k = dsearch(x,y,tri,xi,yi);

zi = k;
d = find(isfinite(k));
zi(d) = z(k(d));
zi = reshape(zi,siz);
%----------------------------------------------------------


%----------------------------------------------------------
function [xi,yi,zi] = gdatav4(x,y,z,xi,yi)
%GDATAV4 MATLAB 4 GRIDDATA interpolation

%   Reference:  David T. Sandwell, Biharmonic spline
%   interpolation of GEOS-3 and SEASAT altimeter
%   data, Geophysical Research Letters, 2, 139-142,
%   1987.  Describes interpolation using value or
%   gradient of value in any dimension.

xy = x(:) + y(:)*sqrt(-1);

% Determine distances between points
d = xy(:,ones(1,length(xy)));
d = abs(d - d.');
n = size(d,1);
% Replace zeros along diagonal with ones (so these don't show up in the
% find below or in the Green's function calculation).
d(1:n+1:prod(size(d))) = ones(1,n);

non = find(d == 0);
if ~isempty(non),
  % If we've made it to here, then some points aren't distinct.  Remove
  % the non-distinct points by averaging.
  [r,c] = find(d == 0);
  k = find(r < c);
  r = r(k); c = c(k); % Extract unique (row,col) pairs
  v = (z(r) + z(c))/2; % Average non-distinct pairs
  
  rep = find(diff(c)==0);
  if ~isempty(rep), % More than two points need to be averaged.
    runs = find(diff(diff(c)==0)==1)+1;
    for i=1:length(runs),
      k = find(c==c(runs(i))); % All the points in a run
      v(runs(i)) = mean(z([r(k);c(runs(i))])); % Average (again)
    end
  end
  z(r) = v;
  if ~isempty(rep),
    z(r(runs)) = v(runs); % Make sure average is in the dataset
  end

  % Now remove the extra points.
  x(c) = [];
  y(c) = [];
  z(c) = [];
  xy(c,:) = [];
  xy(:,c) = [];
  d(c,:) = [];
  d(:,c) = [];
  
  % Determine the non distinct points
  ndp = sort([r;c]);
  ndp(find(ndp(1:length(ndp)-1)==ndp(2:length(ndp)))) = [];

  warning('MATLAB:griddata:NonDistinctPoints',['Averaged %d non-distinct ' ...
            'points.\n         Indices are: %s.'],length(ndp),num2str(ndp'))
end

% Determine weights for interpolation
g = (d.^2) .* (log(d)-1);   % Green's function.
% Fixup value of Green's function along diagonal
g(1:size(d,1)+1:prod(size(d))) = zeros(size(d,1),1);
weights = g \ z(:);

[m,n] = size(xi);
zi = zeros(size(xi));
jay = sqrt(-1);
xy = xy.';

% Evaluate at requested points (xi,yi).  Loop to save memory.
for i=1:m
  for j=1:n
    d = abs(xi(i,j)+jay*yi(i,j) - xy);
    mask = find(d == 0);
    if length(mask)>0, d(mask) = ones(length(mask),1); end
    g = (d.^2) .* (log(d)-1);   % Green's function.
    % Value of Green's function at zero
    if length(mask)>0, g(mask) = zeros(length(mask),1); end
    zi(i,j) = g * weights;
  end
end

if nargout<=1,
  xi = zi;
end
%----------------------------------------------------------

