% script for problem 3

close all; clear all; clc;

load preamble.mat; load pulse.mat; load rxSamples.mat; 

L = length(pulse);

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

% another version of creating preambleWaveform by using conv()
% preambleWaveform = conv(upsample(preamble, L), 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 corrrection

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

% another version of getting the sufficient statistics by using conv()
% MFtmp = conv(rxSamplesCut, conj(fliplr(pulse)));
% suffstat = MFtmp(L:L:end-L+1);

% 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;

load txSymbols.mat

% compute the BER
ber = sum(decSymbols(:) ~= txSymbols(:))/length(decSymbols)