% Generation of AM - FM and Demodulation 
clear;clc;clf
tstart = 0;tend = 0.1;
fm = 100 ;fc = 5e3;Ac = 1.0;Am = 0.5;fs = 4*fc;fi = 0;fi = 0.1*pi;
t = tstart:1/fs:tend;
mt = Am*cos(2*pi*fm*t);
ct = Ac*cos(2*pi*fc*t);c1t = Ac*cos(2*pi*fc*t + fi);
yt = (1+mt).*ct;
subplot(2,1,1);plot(t,mt)
ylabel('Amplitude');title('Message Signal  m(t)')
subplot(2,1,2);plot(t,ct)
xlabel('t (Time - Second)'); ylabel('Amplitude')
title('Carrier  c(t)')
set(gcf,'Color',[1 1 1]);pause;clf reset
plot(t,yt)
axis ([-(max(t)-min(t))*0.05 max(t)*1.05 min(yt)*1.1 max(yt)*1.1])
title(['Full AM Waveform f_c = ',num2str(fc), ' Hz', '  f_m = ',num2str(fm),' Hz'])
xlabel('t (Time)'); ylabel('Amplitude')
line([min(t) max(t)] , [0 0] , 'LineWidth',4,'Color','Red');
line([min(t) min(t)] , [min(yt) max(yt)] , 'LineWidth',4,'Color','Green');
set(gcf,'Color',[1 1 1]);pause
Yf = fft(yt,512); Yff = Yf.*conj(Yf)/512;Yff = sqrt(Yff/max(Yff));
f = fs*(0:256)/512;
plot(f,Yff(1:257))
title('Frequency Spectrum for Y(f)')
xlabel('frequency (Hz)');ylabel('Normalized Amplitude');pause;
rt = yt.*c1t;
Rf = fft(rt,512); Rff = Rf.*conj(Rf)/512;Rff = sqrt(Rff/max(Rff));
f = fs*(0:256)/512;
plot(f,Rff(1:257))
title('FT [y(t) x c(t)]')
xlabel('frequency (Hz)');ylabel('Normalized Amplitude');pause;
plot(t,rt)
axis ([min(t)*1.1 max(t)*1.1 min(rt)*1.1 max(rt)*1.1])
title(['Time Waveform of r(t) = y(t)*c(t)'])
xlabel('t (Time)'); ylabel('Amplitude')
line([min(t) max(t)] , [0 0] , 'LineWidth',4,'Color','Red');
line([min(t) min(t)] , [min(rt) max(rt)] , 'LineWidth',4,'Color','Green');
set(gcf,'Color',[1 1 1]);pause
%[ymod, tmod] = modulate(mt,fc,fs,'amdsb-tc',-1);
%plot(tmod,ymod)
n = 2;Wn = [2*pi*5 2*pi*140];
[bd,ad] = butter(n,Wn/(2*pi*500));
freqz(bd,ad,128,1000);tit = ['Frequency Response Butterworth Banspass Filter n = ',num2str(n)];
title(tit )
pause;clf reset
mpt = filter(bd,ad,rt);
Mpf = fft(mpt,512); Mff = Mpf.*conj(Mpf)/512;Mff = sqrt(Mff/max(Mff));
f = fs*(0:256)/512;
plot(f,Mff(1:257));set(gcf,'Color',[1 1 1])
title('Frequency Spectrum of m"(t) After Banspass Filtering')
xlabel('frequency (Hz)');pause;
subplot(2,1,1);plot(t,mt)
ylabel('Amplitude')
title('Original Message Signal')
subplot(2,1,2);plot(t(1:end),mpt(1:end))
xlabel('t (Time - Second)'); ylabel('Amplitude')
title('Demodulated and Filtered Message Signal')
set(gcf,'Color',[1 1 1])