clear all, close all, clc
fs = 1000; % sampling rate
period = 1;
N = fs * period; % num of samples in one period

t = 1/fs:1/fs:period;

% Generate data 
data = [1 0 1 0]; % x_square represents 1 0 1 0 in binary
M = 1; % modulation order (bits per symbol)
num_symbols = length(data)/M;
symbol_duration = period/num_symbols;
samples_per_symbol = fs *symbol_duration;

f_signal = 2; % 2Hz (2 cycles per period)
x = sin(2*pi*2*t); % modulating analog signal is in 2 Hz
s = sign(x);
x_square = sign(x)*0.5+0.5; % modulating square signal

x_square_polar = 2*x_square -1; % contains -1, 1 only
figure;
subplot(2,1,1);
plot(t, x_square_polar, 'LineWidth', 2.5, 'Color', 'blue', ...
    'DisplayName', 'Polarized Square Modulating signal'); 
hold on;


N = length(t);

fc = 16; % carrier frequency is in 16 Hz
carrier_signal = cos(2 * pi * fc * t);

plot(t, carrier_signal, 'LineWidth', 0.5, 'Color', 'cyan', ...
    'DisplayName', 'Carrier Signal'); 
hold on;

% (2) phase shift key modulation
% Let C1 be some constant
modulated_signal_bpsk = carrier_signal .* x_square_polar; 

plot(t, modulated_signal_bpsk, 'LineWidth', 1.5, 'Color', 'red', ...
    'DisplayName', 'BPSK'); 
hold on;
hold off;
legend show;


SNR=10; %dB
rx = modulated_signal_bpsk;
%rx = awgn(modulated_signal_bpsk, SNR);

subplot(2,1,2);
plot(t, modulated_signal_bpsk, 'LineWidth', 1.5, 'Color', 'red', ...
    'DisplayName', 'BPSK'); 
hold on;

plot(t, rx, 'LineWidth', 1, 'Color', 'green', ...
    'DisplayName', 'Rx Signal with Noise'); 
hold on;

hold off;
legend show;

% % Demodulation
demodulated = rx .* carrier_signal; % what is the equation?
 
figure;
plot(t, demodulated);

% Decoding 
rsum = zeros(size(data)); 
% rsum(i) = approximation of intergral for each symbol_i
decoded_data = zeros(size(data));
for i=1:length(data)
    rsum(i) = sum(demodulated((i-1)*samples_per_symbol+1:i*samples_per_symbol))/fs;
    if(rsum(i)) >= 0
        decoded_data(i) = 1;
    else 
        decoded_data(i) = 0;
    end
end
