function img = gtCrop(img, gtbbox)
% GTCROP.M Crops an image given a bounding box
% Usage:
%       im=gtCrop(imorig,bbox)
%       The input image, imorig, is cropped by bbox, and the result is im
%       bbox has a format [x1 y1 xsize ysize] where x1 and y1 are the top
%       left pixel to be INCLUDED and x/y sizes are the dimensions of the
%       resulting image.
% 
%       If the bounding box is bigger than the original image, it is
%       reduced to fit.
%
% Example:
%   imorig=reshape(1:25,5,5)   % produce a 10x10 matrix
%   bbox=[3 2 2 3];
%   im=gtCrop(imorig, bbox)
%
%   imorig = 
%     1     6    11    16    21
%     2     7    12    17    22
%     3     8    13    18    23
%     4     9    14    19    24
%     5    10    15    20    25
%  im =
%    12    17
%    13    18
%    14    19

% Greg Johnson, September 2006
% Modified to work also with 3D volumes W. Ludwig,   March 2012

    [size_img(1), size_img(2), size_img(3), size_img(4)] = size(img);

    switch (length(gtbbox))
        case 4  %  2D case
            minLims = gtbbox(1:2);
            maxLims = minLims + gtbbox(3:4) - 1;
            % if bbox is too large, crop to image extent
            minLims = max(minLims, 1);
            maxLims = min(size_img(1:2), maxLims);

            img = img(minLims(2):maxLims(2), minLims(1):maxLims(1));
        case 6
            % 3D case, uses different conventions from 2D case: x and y are not
            % inverted
            minLims = gtbbox(1:3);
            maxLims = minLims + gtbbox(4:6) - 1;
            % if bbox is too large, crop to image extent
            minLims = max(minLims, 1);
            maxLims = min(size_img(1:3), maxLims);

            img = img(minLims(1):maxLims(1), minLims(2):maxLims(2), minLims(3):maxLims(3));
        case 8
            % 4D case, uses different conventions from 2D case: x and y are not
            % inverted
            minLims = gtbbox(1:4);
            maxLims = minLims + gtbbox(5:8) - 1;
            % if bbox is too large, crop to image extent
            minLims = max(minLims, 1);
            maxLims = min(size_img(1:4), maxLims);

            img = img(minLims(1):maxLims(1), minLims(2):maxLims(2), minLims(3):maxLims(3), minLims(4):maxLims(4));
        otherwise
            error('gtCrop:wrongInput', ...
                  'Argument bbox needs either to be a 4 (2D) or 6 (3D) element vector');
    end
end
