% Problem 2

close all; 
clear all;

% Load the various vectors
load preamble.mat; 
load pulse.mat; 
load rxSamples.mat;
load txSymbols.mat;

% Define parameters
L = length(pulse);

% Q1
% create the waveform corresponding to the preamble
preambleWaveform = kron(preamble, pulse);

% search for the preamble
R = xcorr(rxSamples, preambleWaveform);
R = R(length(rxSamples):end-length(preambleWaveform)+1);

% plot the xcorr
figure;
plot(abs(R),'-*'); grid on; title('Correlation at Rx with the preamble')

[~,ind] = max(abs(R))
Rmax = R(ind);
phi0 = angle(Rmax)

% there could be more bits before the preamble
startFirstBit = mod(ind, L)

% Q2
rxSamplesCut = rxSamples(startFirstBit:end);
rxSamplesCut = rxSamplesCut(1:end-mod(length(rxSamplesCut),L));

% Q3
rxSamplesCut = rxSamplesCut*exp(-1i*phi0); % phase correction

% Q4
% here we do the inner products (MF) in one shot
rxMatrix = reshape(rxSamplesCut, L,[]).';
suffstat = rxMatrix*pulse';

% plot the resulting constellation
figure;
plot(suffstat,'*');
grid on; xlabel('Real'); ylabel('Imag'); title('Output of the MF')
% correct the yrange
tmp = max(abs(suffstat));
ylim([-tmp, tmp]);

% Q5
% decode the bits
decSymbols = 2*(real(suffstat)>0) - 1;

% compute the SER
ser = sum(decSymbols(:) ~= txSymbols(:))/length(decSymbols)