%% init
clc;
clear all;
close all;

fc = 1e6;
fvz = 8.82e6;
fm = 2e3;
width = 24;
t = (0:1/fvz:1100/fm);
Um = cos(2*pi*fm*t);
phase = (0:(2*pi/(1e6)):2*pi);
LUTcos = cos(phase);
accumulator = 0;
length_out = 60000;
out(1:length_out) = 0;


%% modulate2

for i=1:length_out
    accumulator = round( accumulator + (113378/4+15000*Um(i)) + 1);
    if (accumulator>length(LUTcos))
        accumulator = accumulator - length(LUTcos);
    end
    
    out(i) = LUTcos(accumulator);
end

%% quadrature
carier =  cos(2*pi*fc/4*t);
cariersin =  sin(2*pi*fc/4*t);

I_part = out .* carier(1:60000);
Q_part = out .* cariersin(1:60000);

I_part = filter(low_pass_fm_demod,I_part);
Q_part = filter(low_pass_fm_demod,Q_part);

I_part2(1:1000)= 0;
Q_part2(1:1000)= 0;

for i = 2:(length(I_part)-1)
    I_part2(i) = I_part(i)*Q_part(i-1);
    Q_part2(i) = Q_part(i)*I_part(i-1);
end
    
outfm = filter(lp2,(I_part2 - Q_part2)) ;

figure(3)
subplot(2,1,1);
plot(t(1:length(I_part)),I_part);
subplot(2,1,2);
plot(t(1:length(Q_part)),Q_part);

figure(4)
plot(abs(fft(I_part)));

figure(5)
subplot(2,1,1);
plot(t(1:length(I_part2)),I_part2);
subplot(2,1,2);
plot(t(1:length(Q_part2)),Q_part2);

figure (6);
subplot(2,1,1);
plot(t(1:length(outfm)),outfm);
subplot(2,1,2);
plot(t(1:length(outfm)),Um(1:59999));

figure (7);
Sfm = abs(fft(outfm));
frekv = (0:fvz/length(Sfm):fvz-fvz/length(Sfm));
plot(frekv,Sfm);

%% plots
figure(1)
subplot(2,1,1)
plot(t(1:length(out)),out);
subplot(2,1,2)
plot(t(1:length(outfm)),Um(1:59999));
figure(2)
frekv = (0:(fvz/length(out)):(fvz-fvz/length(out)));
plot(frekv,abs(fft(out)));

