%CROPIM   Crop an image
%
% SYNOPSIS:
%  image_out = cropim(image_in, [origin,] cropsize)
%
% PARAMETERS:
%    origin:   (optional) the origin of the crop region, if not explicitly
%              given: origin=floor(0.5*(size(image_in)-cropsize))
%    cropsize: size of the crop region
%
% SEE ALSO:
%  cut, extend

% Copyright 2007-2010, Michael van Ginkel, Cris Luengo.
% July 2010: Added parameter checking & more gentle error recovery,
%            Using SUBSREF instead of DIP_CROP for better speed &
%            conservation of pixel dimensions. (CL)

function [imo,ima] = cropim(imi,origin,cropsize)

if nargin==1 & ischar(imi) & strcmp(imi,'DIP_GetParamList')
   imo = struct('menu','none');
   return;
end

if nargin<2
   error('CROPSIZE must be given.');
elseif nargin==2
   cropsize = origin;
   origin = [];
end

sz = imsize(imi);
n = length(sz);

if length(cropsize)>n
   cropsize = cropsize(1:n);
else
   cropsize(end+1:n) = 1;
end
cropsize = min(cropsize,sz);

if length(origin)>n
   origin = origin(1:n);
else
   def_orig = floor(0.5*(sz-cropsize));
   k = length(origin)+1;
   origin(k:n) = def_orig(k:n);
end

s.type = '()';
s.subs = cell(1,n);
for ii=1:n
   s.subs{ii} = origin(ii)+(0:cropsize(ii)-1);
end
ima = subsref(imi,s);
