% Problem 1

close all;
clear all;

% Load the files
load rx_signal.mat
load pn_sequence.mat

% Define parameters
num_carriers = 256;    % total number of carriers
prefix_length = 20;    % length of the cyclic prefix

% Correlate the received signal with the P/N sequence in order to find this
% sequence within the received signal
R = conv(rx_signal, fliplr(conj(pn_sequence)), 'valid');

% Plot to check if we find a clear peak
figure;
plot(abs(R),'-*');
grid on; xlabel('Index'); ylabel('abs(correlation)');
title('Correlation at Rx');

[~, index_start_pn_sequence] = max(abs(R))

% Trim the received signal and keep the "full" OFDM data blocks
rx_symbols = rx_signal(index_start_pn_sequence + length(pn_sequence):end);
rx_symbols = rx_symbols(1:end-mod(length(rx_symbols), prefix_length+num_carriers));

% Process the OFDM blocks
rx_withCP = reshape(rx_symbols, prefix_length+num_carriers, []); 
rx_noCP = rx_withCP(prefix_length+(1:num_carriers), :); % remove the rows corresponding to cyclic prefix

% Go to the frequency domain
Rf = fft(rx_noCP, num_carriers);

% Plot the received constellation
figure();
plot(real(Rf(:)), imag(Rf(:)), '*');
grid on;
title('Constellation at Rx');

% Decode the first block
first_block = Rf(:,1).';
first_block_decoded = 2*(real(first_block) > 0) - 1 + 1j*(2*(imag(first_block) > 0) - 1);

% Estimate the lambdas with LS
lambdas = first_block./first_block_decoded;

% Plot the lambdas
figure;
plot(abs(lambdas),'-*');
grid on; xlabel('Index'); ylabel('Magnitude');
title('Estimated Lambdas');
