%function convdemo2(x,h,n, offset)
% Displays x, h, xrev, prod, and y  given x, h, supports, 
%   and offset for calculation
% Supports equal for x,h, and y

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

% last revised 9/2/97, rms

n1 = min(n);
n2 = max(n);
numn = length(n);
initn = sum((1:numn).*(n==0)); %Shift of first point
y = zeros(1,numn);
minn = min(n);
maxn = max(n)-(offset);
a = gcf;


%Flipping and shifting x

xrev = [zeros(1,numn) x];
xrev = xrev(2*numn:-1:1);
xrev = [xrev((2*numn)-(initn-1):2*numn) xrev(1:(2*numn)-initn)];

subplot(5,1,2),stem(n,h,'g')	
xlabel('k')
ylabel('h[k]')
axis([minn maxn floor(min(h)) ceil(max(h))]);

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




% Setting and fixing max amplitudes

min3 = 0; max3 = 0; min4 = 0; max4 = 0; y = zeros(1,numn);

for i = 1:numn-offset

xrevp = xrev(numn+1:2*numn);  
y(i) = sum(x.*xrevp);	
	
max3 = max(max3, ceil(max(h.*xrevp)));
min3 = min(min3, floor(min(h.*xrevp)));


end


min2 = floor(min(x));
max2 = ceil(max(x));

y = conv(x,h);
max4 = ceil(max(y));
min4 = floor(min(y));

% Performing actual convolution

y = zeros(1,numn);
for i = 1:numn-offset
is = num2str(i+minn-1);	% marks current value of n

xrevp = xrev(numn+1:2*numn);  
subplot(5,1,3),stem(n,xrevp,'r')	
xlabel('k')
ylabel('x[n-k]')
axis([minn maxn min2 max2]);

ntemp = minn:maxn;
ytemp = h.*xrevp;
subplot(5,1,4),stem(ntemp,ytemp(1:length(ntemp)))	
xlabel('k')
ylabel('h[k]*x[n-k]')
%axis([minn maxn [] []]);
	
y(i) = sum(h.*xrevp);	
subplot(5,1,5),stem(n,y,'m')	
xlabel('n')
ylabel('y[n]')
axis([minn maxn min4 max4]);

subplot(5,1,1)
title(['n = ',is],'fontsize',18)
	
pause
xrev = [xrev(2*numn) xrev(1:(2*numn)-1)];

end
