function hout = slice(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8)
%SLICE	Volumetric slice plot.
%	SLICE(X,Y,Z,V,XI,YI,ZI,N) draws slices along the x, y, or z
%	planes at the volume locations specified by the triples
%	(xi,yi,zi).  N is the number of columns in the M-by-N-by-P
%	volume array V.
%
%	SLICE(V,XI,YI,ZI,N) assumes X = 1:N, Y = 1:M, Z = 1:P.
%
%	For example, to evaluate the function x*exp(-x^2-y^2-z^2)
%	over the range -2 < x < 2, -2 < y < 2, - 2 < z < 2,
%
%	   [x,y,z] = meshgrid(-2:.2:2, -2:.25:2, -2:.16:2);
%	   v = x .* exp(-x.^2 - y.^2 - z.^2); % V is 17-by-21-by-26
%	   slice(x,y,z,v,[-1.2 .8 2],2,[-2 -.2],21)
%
%	SLICE returns a vector of handles to SURFACE objects.
%
%	See MESHGRID.

% 	J.N. Little 1-23-92
%	Revised 4-27-93, 2-10-94
%	Revised 6-17-94 by Clay M. Thompson
%	Copyright (c) 1984-93 by The MathWorks, Inc.

cax = newplot;
next = lower(get(cax,'NextPlot'));
hold_state = ishold;

if nargin == 5, % slice(v,sx,sy,sz,nx)
	v = arg1; nx = arg5;
	sx = floor(arg2); sy = floor(arg3); sz = floor(arg4);
    [m,nz] = size(v); ny = m/nx;
	[x,y,z] = meshgrid(1:nx,1:ny,1:nz);
elseif nargin == 8, % slice(x,y,z,v,sx,sy,sz,nx)
	v = arg4; nx = arg8;
	if min(size(arg1))==1 | min(size(arg2))==1 | min(size(arg3))==1,
		[x,y,z] = meshgrid(arg1,arg2,arg3);
	else
		x = arg1; y = arg2; z = arg3;
	end
	mx = prod(size(arg1)); my = prod(size(arg2)); mz = prod(size(arg3));
	[m,nz] = size(v); ny = m/nx;

	% Map sx,sy,sz into matrix indices
	sx = floor(1 + (arg5-arg1(1))*((nx-1)/(arg1(mx)-arg1(1))));
	sy = floor(1 + (arg6-arg2(1))*((ny-1)/(arg2(my)-arg2(1))));
	sz = floor(1 + (arg7-arg3(1))*((nz-1)/(arg3(mz)-arg3(1))));
end

% Remove out of range values of sx,sy,sz
d = find((sx<1)|(sx>nx)); if ~isempty(d), sx(d) = []; end
d = find((sy<1)|(sy>ny)); if ~isempty(d), sy(d) = []; end
d = find((sz<1)|(sz>nz)); if ~isempty(d), sz(d) = []; end

h = [];
for i = 1:length(sx)
	n = sx(i);
	h = [h; surface(x((1:ny)+ny*(n-1),:),y((1:ny)+ny*(n-1),:), ...
	                z((1:ny)+ny*(n-1),:),v((1:ny)+ny*(n-1),:))];
end

for i = 1:length(sy)
	n = sy(i);
	h = [h; surface(x(n:ny:m,:),y(n:ny:m,:),z(n:ny:m,:),v(n:ny:m,:))];
end

for i = 1:length(sz)
	n = sz(i);
	h = [h; surface(reshape(x(:,n),ny,nx),reshape(y(:,n),ny,nx),...
        reshape(z(:,n),ny,nx),reshape(v(:,n),ny,nx))];
end

if nargout > 0
	hout = h;
end
if ~hold_state
	view(3)
end

% Use FINITE to make sure no NaNs or Infs get passed to CAXIS
u=v(finite(v)); u = u(:);
caxis([min(u) max(u)])
