function h = swaterfall(n,delay,x,y,z,c)
%SLOW WATERFALL Waterfall plot.
%   SWATERFALL(n,delay...) is the same as WATERFALL(...)
%   but plot appears in "chunks" defined by n 
%   with delay (in seconds) between each "chunk" along Y axis.
%   n is the number of points in each chunk.
%   Note that swaterfall will reverse Ydir, so that the plot starts from Y=0.
%   Example: swaterfall(5,1,peaks);
%   The resulting plot will be equivalent to waterfall(flipud(peaks));
%   	
%   Modified from waterfall.m by Igor Kagan, Aug. 23, 2000		 
%   File: swaterfall.m						 				 				 
%					 
%   kigor@tx.technion.ac.il
%   http://igoresha.virtualave.net/Matlab/Matlab.html

a = newplot;
if nargin == 3
    z = x;
    c = z;
    x = 1:size(z,2);
    y = 1:size(z,1);
elseif nargin == 4
    z = x;
    c = y;
    x = 1:size(z,2);
    y = 1:size(z,1);
elseif nargin == 5
    c = z;
end
if min(size(x)) == 1 | min(size(y)) == 1
    [x,y]=meshgrid(x,y);
end

if n>size(y,1),
	errordlg('Number of chunks exceed number of Y values!','swaterfall error');
	close;
	return;
end

% Add 2 data points to the beginning and three data points at the end
% of each row for a patch.  Two of the points on each side are used
% to make sure the curtain is a constant color under 'interp' or
% 'flat' edge color.  The final point on the right is used to
% make bottom edge invisible.
x = [x(:,[1 1]) x x(:,size(x,2)*[1 1 1])];
y = [y(:,[1 1]) y y(:,size(y,2)*[1 1 1])];
c0 = (max(max(c))+min(min(c)))/2;
z0 = min(min(z));
if z0==max(max(z)), % Special case for a constant surface
  if z0==0, z0 = -1; else, z0 = z0 - abs(z0)/2; end
end

z = [z0*ones(size(x,1),1) z(:,1) z z(:,size(z,2)) z0*ones(size(x,1),2) ];
c = [c0*ones(size(c,1),2)  c c0*ones(size(c,1),2) repmat(NaN,size(x,1),1)];
fc = get(gca,'color');
if strcmp(fc,'none'), fc = get(gcf,'color'); end

%set(gca,'YLim',[min(min(y)) max(max(y))],'Ydir','reverse','Drawmode','fast','NextPlot','add');
set(gca,'Drawmode','fast','NextPlot','add','Ydir','reverse');
set(gcf,'Visible','off');
hp = patch(x',y',z',c','facecolor',fc,'edgecolor','flat','EraseMode','background','visible','on');
view(3), grid on

Xlim = get(gca,'Xlim');
Ylim = get(gca,'Ylim');
Zlim = get(gca,'Zlim');
set(hp,'visible','off');
set(gcf,'Visible','on');

xd = get(hp,'xdata');
yd = get(hp,'ydata');
zd = get(hp,'zdata');
cd = get(hp,'cdata');
set(gca,'Xlim',xlim,'Ylim',Ylim','Zlim',Zlim);
chunk = floor(size(y,1)/n);
add2last = rem(size(y,1),n);
for i=1:n,
	
        y1 = 1+(i-1)*chunk;
	y2 = i*chunk;
	if i==n, y2=y2+add2last; end;

	xx = xd(:,y1:y2);
	yy = yd(:,y1:y2);
	zz = zd(:,y1:y2);
	cc = cd(:,y1:y2);
	hh(i) = patch('facecolor',fc,'edgecolor','flat','EraseMode','background','visible','off');
	set(hh(i),'Xdata',xx,'Ydata',yy,'Zdata',zz,'Cdata',cc,'visible','on'); 
	pause(delay);
end


% return handles, if requested
if nargout > 0
    h = hh;
end
