function [bout,rect] = imcrop(x,y,a,rect)
%IMCROP	Crop image.
%	B = IMCROP prompts you to define a rectangular subimage
%	of the current figure using the mouse and returns in B the
%	interior of the bounded area.  IMCROP only works if the 
%	current	axis contains an image (i.e., created using IMSHOW,
%	IMAGE, or, IMAGESC).  Example:
%	   imshow(X,map) % Display image
%	   b = imcrop;
%
%	B = IMCROP(A,RECT) returns the submatrix with the bounding
%	rectangle RECT = [left, bottom, width, height] in image
%	coordinates (i.e., [1 N+1 1 M+1] for an M-by-N image).
%
%	B = IMCROP(x,y,A,RECT) accounts for non-default axis limits.
%
%	[B,RECT] = IMCROP(...) returns the selection rectangle.
%	IMCROP without output arguments displays the cropped image.
%
%	See also IMZOOM.

%	Clay M. Thompson 1-22-93
%	Copyright (c) 1993 by The MathWorks, Inc.
%	$Revision: 1.20 $  $Date: 1993/09/24 21:59:35 $

% 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,hasimage] = getimage;
  if ~hasimage,
    error('The current figure must contain an image to use IMCROP.');
  end
  rect = getrect(gcf); % Get rect info from the user.

elseif nargin==2,
  a = x;
  [m,n] = size(a);
  rect = y;
  if useNew,
    x = 1:n; y = 1:m;
  else
    x = 1:n+1; y = 1:m+1;
  end
end

[m,n] = size(a);
xmin = min(min(x)); ymin = min(min(y));
xmax = max(max(x)); ymax = max(max(y));
if useNew,
  % Transform rectangle into row and column indices.
  kx = n-1; ky = m-1;
  i1 = max(ceil((rect(2)-ymin)/(ymax-ymin)*ky+1),1);
  j1 = max(ceil((rect(1)-xmin)/(xmax-xmin)*kx+1),1);
  i2 = min(floor((rect(2)+rect(4)-ymin)/(ymax-ymin)*ky+1),m);
  j2 = min(floor((rect(1)+rect(3)-xmin)/(xmax-xmin)*kx+1),n);
else
  % Transform rectangle into row and column indices.  Fix-up coordinates
  % to deal with coordinates extending from pixel boundaries rather
  % than pixel centers.
  dx = max( (xmax-xmin)/size(a,2), eps );
  dy = max( (ymax-ymin)/size(a,1), eps );
  kx = (n-1+dx); ky = (m-1+dy);
  i1 = max(ceil((rect(2)-ymin)/(ymax-ymin)*ky+(1-dy/2)),1);
  j1 = max(ceil((rect(1)-xmin)/(xmax-xmin)*kx+(1-dx/2)),1);
  i2 = min(floor((rect(2)+rect(4)-ymin)/(ymax-ymin)*ky+(1-dy/2)),m);
  j2 = min(floor((rect(1)+rect(3)-xmin)/(xmax-xmin)*kx+(1-dx/2)),n);
end

b = a(i1:i2,j1:j2);

if nargout==0,
  imshow(b)
  return
end
bout = b;
