function [i,j]=closest(X,Y,xi,yi)
%       [I,J]=CLOSEST(X,Y,XI,YI)
%	finds indicies of coordinate arrays X and Y that give the 
%	point(s) closest to the input points(s) XI,YI.
%       I returns the index into XI,YI
%       J returns the corresponding index of the closest point in X,Y. 
%       I,J may be longer than XI,YI if for any of those positions there is
%       more than one equal closest point in X,Y. 
%	The point(s) of interest XI,YI may be specified as a pair
%	points, a pair of vectors, or a matrix XY with two columns
%	i.e. [I,J]=CLOSEST(X,Y,XY).  This last option allows the
%	direct output of GINPUT to be used as the input XY,
%	e.g. [I,J]=CLOSEST(X,Y,GINPUT)
%
%	John Wilkin, 4 November 93    Jeff Dunn 18 March 1996

if nargin == 3
  yi = xi(:,2);
  xi = xi(:,1);
end

i = []; j = [];

for k=1:length(xi)
  dist = abs( (xi(k)-X) + sqrt(-1)*(yi(k)-Y));
  [ii,jj] = findm(dist==min(dist(:)));
  i = [i k*ones(1,length(ii))];
  j = [j jj'];
end
