%% init
clc;
clear all;
close all;

fvz = 8.82e6;
fs = 44100;
fc = 1e6;
Uc = 0.5;
faux = 1500;


%% read data
inputlsbharm = csvread('ssb_harm_lsb.csv');
inputlsb = csvread('ssb_signal_lsb.csv');
carier = csvread('ssbcarier.csv');
modulate = csvread('ssbmodulate.csv');
t = (0:(1/fvz):(length(inputlsbharm)/fvz)-1/fvz);
taux = (0:(1/fs):(10000/fs)-1/fs);

%% demodulate harmonic signal lsb
carier_ssb = Uc* cos(2*pi*(fc+faux)*t);
carier_ssbsin = Uc* sin(2*pi*(fc+faux)*t);

carier_auxr =  Uc* cos(2*pi*faux*taux);
carier_aux_sinr =  Uc* sin(2*pi*faux*taux);

firstbranchr_dem = inputlsbharm'.*carier_ssb;
secondbranchr_dem = inputlsbharm'.*carier_ssbsin;

firstbranchr_dem = downsample(firstbranchr_dem,200);
secondbranchr_dem = downsample(secondbranchr_dem,200);

firstbranchr2_dem = 10* filter(lp2,firstbranchr_dem);
secondbranchr2_dem = 10* filter(lp2,secondbranchr_dem);

firstbranchr3_dem = firstbranchr2_dem .* carier_auxr;
secondbranchr3_dem = secondbranchr2_dem .* carier_aux_sinr;

demodlsbharm = 4* (firstbranchr3_dem + secondbranchr3_dem);

figure(7)
subplot(2,1,2);
plot(taux,demodlsbharm);
subplot(2,1,1);
plot(t,inputlsbharm);

figure(8)
Smodul = fftshift(abs(fft(demodlsbharm)));
frekv = ((-(fs-fs/length(Smodul))/2):(fs/length(Smodul)):((fs-fs/length(Smodul))/2));
plot (frekv,Smodul);

figure(9)
Smodulf = fftshift(abs(fft(firstbranchr2_dem)));
frekv = ((-(fs-fs/length(Smodulf))/2):(fs/length(Smodulf)):((fs-fs/length(Smodulf))/2));
plot (frekv,Smodulf);


%% demodulate real signal lsb

t = (0:(1/fvz):(length(inputlsb)/fvz)-1/fvz);
taux = (0:(1/fs):(length(modulate)/fs)-1/fs);

carier_ssb = Uc* cos(2*pi*(fc+faux)*t);
carier_ssbsin = Uc* sin(2*pi*(fc+faux)*t);

carier_auxr =  Uc* cos(2*pi*faux*taux);
carier_aux_sinr =  Uc* sin(2*pi*faux*taux);

firstbranchr_dem = inputlsb'.*carier_ssb;
secondbranchr_dem = inputlsb'.*carier_ssbsin;

firstbranchr_dem = downsample(firstbranchr_dem,200);
secondbranchr_dem = downsample(secondbranchr_dem,200);

firstbranchr2_dem = 10* filter(lp2,firstbranchr_dem);
secondbranchr2_dem = 10* filter(lp2,secondbranchr_dem);

firstbranchr3_dem = firstbranchr2_dem .* carier_auxr;
secondbranchr3_dem = secondbranchr2_dem .* carier_aux_sinr;

demodlsb = 4* (firstbranchr3_dem + secondbranchr3_dem);

figure(11)
subplot(3,1,3);
plot(taux,modulate);
subplot(3,1,2);
plot(taux,demodlsb);
subplot(3,1,1);
plot(t,inputlsb);

figure(12)
Smod = fftshift(abs(fft(modulate)));
frekv = ((-(fs-fs/length(Smod))/2):(fs/length(Smod)):((fs-fs/length(Smod))/2));
plot (frekv,Smod);

figure(13)
Smodul = fftshift(abs(fft(demodlsb)));
frekv = ((-(fs-fs/length(Smodul))/2):(fs/length(Smodul)):((fs-fs/length(Smodul))/2));
plot (frekv,Smodul);

figure(14)
Smodulf = fftshift(abs(fft(firstbranchr2_dem)));
frekv = ((-(fs-fs/length(Smodulf))/2):(fs/length(Smodulf)):((fs-fs/length(Smodulf))/2));
plot (frekv,Smodulf);


%% writte to wav
wavwrite(modulate,fs,'orig.wav');
wavwrite(demodlsb,fs,'demod_lsb.wav');