function [Y,r,c] = stack_crop(h,X)

% stack_crop - crop a displayed stack
% -----------------------------------
%
% [Y,r,c] = stack_crop(h,X)
% 
% Input:
% ------
%  h - axes handle for displayed stack (def: gca)
%  X - stack to crop (def: displayed stack)
%
% Output:
% -------
%  Y - cropped stack
%  r - row limits
%  c - column limits

%--
% set handle
%--

if (~nargin)
	h = gca;
end 

%--
% set stack
%--

if (nargin < 2)
	X = get(findobj(h,'type','image'),'userdata');
	X = X.X;
end

%--
% get indexing from axes handle
%--

p = get(h);

r = p.YLim + [0.5 -0.5];
r = [ceil(r(1)), floor(r(2))];

c = p.XLim + [0.5 -0.5];
c = [ceil(c(1)), floor(c(2))];

%--
% create cropped image
%--

for k = 1:length(X)
	Y{k} = X{k}(r(1):r(2),c(1):c(2),:);
end
