%% init
clc;
clear all;
close all;

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


%% read data
inputusbharm = csvread('ssb_harm_usb.csv');
inputusb = csvread('ssb_signal_usb.csv');
carier = csvread('ssbcarier.csv');
modulate = csvread('ssbmodulate.csv');
t = (0:(1/fvz):(length(inputusbharm)/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 = inputusbharm'.*carier_ssb;
secondbranchr_dem = inputusbharm'.*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;

demodusbharm = 4* (firstbranchr3_dem + secondbranchr3_dem);

figure(7)
subplot(2,1,2);
plot(taux,demodusbharm);
subplot(2,1,1);
plot(t,inputusbharm);

figure(8)
Smodul = fftshift(abs(fft(demodusbharm)));
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 usb

t = (0:(1/fvz):(length(inputusb)/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 = inputusb'.*carier_ssb;
secondbranchr_dem = inputusb'.*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;

demodusb = (-4)* (firstbranchr3_dem + secondbranchr3_dem);

figure(11)
subplot(3,1,3);
plot(taux,modulate);
subplot(3,1,2);
plot(taux,demodusb);
subplot(3,1,1);
plot(t,inputusb);

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(demodusb)));
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(demodusb,fs,'demod_usb.wav');
wavwrite(modulate,fs,'orig.wav');

