function [u,v,rgb] = impixel(x,y,a,cm,u,v)
%IMPIXEL Color of a pixel.
%	RGB = IMPIXEL prompts you to define the desired pixels
%	using the mouse in the current figure.  The pixel colors 
%	are returned in the M-by-3 matrix RGB. Left mouse button
%	adds new points, right mouse button (shift-click on the 
%	Macintosh) or a key adds the last point and returns.  IMPIXEL
%	without input arguments only works if the current axis 
%	contains an image.
%
%	RGB = IMPIXEL(X,MAP,Xi,Yi) returns the RGB values in the
%	indexed image X with colormap MAP at the points (xi,yi).  
%	If Xi and Yi are vectors of length M, then RGB will be M-by-3.
%
%	RGB = IMPIXEL(I,Xi,Yi) returns the gray-level RGB value in the 
%	intensity image I at the points (xi,yi).
%
%	RGB = IMPIXEL(x,y,X,MAP,Xi,Yi) or RGB = IMPIXEL(x,y,I,Xi,Yi)
%	accounts for non-default axis limits.
%
%	[X,Y,RGB] = IMPIXEL(...) returns the (X,Y) position of the
%	selected points in the image.
%
%	See also IMPROFILE.

%	Clay M. Thompson 1-27-93
%	Copyright (c) 1993 by The MathWorks, Inc.
%	$Revision: 1.18 $  $Date: 1993/09/24 22:02:05 $

% Determine which IMAGE coordinate system is being used.
s = [version '    ']; k = find(s<46 & s>58);
if ~isempty(k), s = s(1:min(k)); end
[ver,count,msg,next] = sscanf(s,'%f',1);
if ver > 4.1,
  useNew = 1;
elseif ver < 4.1,
  useNew = 0;
else
  if s(next)>='a', useNew = 1; else useNew = 0; end
end

if nargin==0, % Get information from the current figure
  [x,y,a,kind] = getimage;
  if ~kind, 
    error('The current axes must contain an image.');
  end
  if kind==1, cm = colormap; else cm = []; end

  % Get info from user
  [u,v] = getpts(gcf);

elseif nargin==1 | nargin==2,
  error('Wrong number of input arguments.');

elseif nargin==3, % impixel(I,xi,yi)
  v = a; a = x; u = y;
  if useNew,
    x = [1 size(a,2)]; y = [1 size(a,1)];
  else
    x = [1 size(a,2)+1]; y = [1 size(a,1)+1];
  end
  cm = [];

elseif nargin==4, % impixel(a,cm,xi,yi)
  v = cm;  u = a; a = x; cm = y;
  if useNew,
    x = [1 size(a,2)]; y = [1 size(a,1)];
  else
    x = [1 size(a,2)+1]; y = [1 size(a,1)+1];
  end

elseif nargin==5, % impixel(x,y,I,xi,yi)
  v = u; u = cm;
  cm = [];

end

[m,n] = size(a);

xmin = min(min(x)); ymin = min(min(y));
xmax = max(max(x)); ymax = max(max(y));
if useNew,
  dx = (xmax-xmin)/max(n-1,1);
  dy = (ymax-ymin)/max(m-1,1);
  xx = xmin:dx:xmax;
  yy = ymin:dy:ymax;
else
  % Fix-up coordinates to deal with coordinates extending from pixel
  % boundaries rather than pixel centers.
  dx = (xmax-xmin)/n;
  dy = (ymax-ymin)/m;
  xx = (xmin+dx/2):dx:(xmax-dx/2);
  yy = (ymin+dy/2):dy:(ymax-dy/2);
end

if max(size(a))~=1,
  rgb = interp6(xx,yy,a,u,v);
else
  rgb = a(ones(length(u),1));
end

if isempty(cm),
  rgb = [rgb(:) rgb(:) rgb(:)];
else
  d = find(isnan(rgb));
  if ~isempty(d), rgb(d) = ones(size(d)); end
  rgb = cm(rgb(:),:);
  if ~isempty(d), rgb(d,:) = NaN*ones(size(d),3); end
end

if nargout<=1,
  u = rgb;
end


