function circconvdemo2(x,h, N, nlen, offset)
% Circular convolution demo revised from convdemo2

% Displays x, h, xrev, prod, and y  given x, h, supports, 
%   and offset for calculation
% Supports equal for x,h, and y

% N refers to size of circular convolution
% nlen refers to number of points plotted

% offset refers to how many samples the origin is to the right of the
% edge of the plot  

% The fact that MATLAB works with origin 1 vectors makes for many fudges 
% to enable the indices to look right.

% last revised 10/18/05, rms

x = x(1:N);
h = h(1:N);
n = 0-offset:nlen-1-offset;

xper = x(1+mod(n-1,N));
hper = h(1+mod(n-1,N));


subplot(5,1,1),stem(n-1,xper,'k')
xlabel('k')
ylabel('x[k]')
axis([min(n) max(n) floor(min(xper)) ceil(max(xper))]); 

subplot(5,1,2),stem(n-1,hper,'r')
xlabel('k')
ylabel('h[k]')
axis([min(n) max(n) floor(min(h)) ceil(max(h))]); 

% Performing actual convolution


subplot(5,1,5),hold off

for m = min(n):max(n)

xrevper = 	x(1+mod(N+m-n+1,N));	
subplot(5,1,3),stem(n-1,xrevper,'g')	
xlabel('k')
ylabel('x[n-k]')
axis([min(n) max(n) floor(min(xper)) ceil(max(xper))]); 

prod = hper.*xrevper;
subplot(5,1,4),stem(n-1,prod)		
xlabel('k')
ylabel('h[k]*x[n-k]')
proddft = real(ifft(fft(x).*fft(x)));
axis([min(n) max(n) 0 1]); % Need to generalize later
	
temp = sum(prod(1:N));
y(m+offset+1) = temp;	
subplot(5,1,5),stem(m,y(m+offset+1),'m')
hold on
xlabel('n')
ylabel('y[n]')
axis([min(n) max(n) 0 ceil(max(proddft))]); 

is = num2str(m);
in = num2str(N);
subplot(5,1,1)
title(['Circular convolution, N = ',in,';  n = ',is],'fontsize',14)
	
pause

end
