%EX_SLICE   Extracts one slice from an n-D image
%
% SYNOPSIS:
%  out = ex_slice(in, plane, dim)
%
%  plane:  0..size(in,dim)-1   % index into image
%  dim:    0..ndims(in)-1      % dimension along which to index
%          -ndims(in)..-1      % negative dimension counts from the end
%
% DEFAULTS:
%  dim = -1; % last dimension
%
% EXAMPLE:
%  ex_slice(readim('chromo3d'),3)
%  ex_slice(readim('chromo3d'),0,0)
%  ex_slice(readim,3,1)

% (C) Copyright 1999-2007               Pattern Recognition Group
%     All rights reserved               Faculty of Applied Physics
%                                       Delft University of Technology
%                                       Lorentzweg 1
%                                       2628 CJ Delft
%                                       The Netherlands
%
% Bernd Rieger, September 2004
% 16 September 2004, Extended use of negative dimensions (CL)
% Feb 2005, added support for color images (BR)
% 9 April 2007, Rewrote to use SUBSREF instead of EVAL. (CL)

function out = ex_slice(in,slice,dim)

if nargin == 1 & ischar(in) & strcmp(in,'DIP_GetParamList') % Avoid being in menu
   out = struct('menu','none');
   return
end
if nargin<2
   error('Usage: ex_slice(in, plane, dim)');
end
if nargin <3
   dim = -1;
end
N = ndims(in{1});
if dim<0
   dim = N+dim;
end
if dim<0 | dim>N-1
   error('Dimension out of bounds.');
end
if slice<0 | slice>size(in{1},dim+1)-1
   error('Slice out of bounds.');
end

s = substruct('()',repmat({':'},1,N));
s.subs{dim+1} = slice;
if istensor(in)
   out = newimar(imarsize(in));
   for ii=1:prod(imarsize(in))
      out{ii} = squeeze(subsref(in{ii},s));
   end
   if iscolor(in)
      out = colorspace(out,colorspace(in));
   end
else
   out = squeeze(subsref(in,s));
end
