% Problem 2

close all;
clear all;

% Load the samples
load rx_preambleSequence.mat
load preambleSequence.mat

% Define parameters
Ts = 1/4092000; % sampling time [seconds]
doppler_step = 10; % [Hz]

maxDoppler = 1000;

% vector of tentative Doppler frequencies to search
doppler = (-maxDoppler: doppler_step: maxDoppler);

y = rx_preambleSequence;
p = preambleSequence;

% generate the time axis
t = (0 : length(y)-1) * Ts;

% initialize values
IP_result = -inf;
doppler_estim = -inf;
tau_estim = - inf;

% loop over tentative Doppler
for fd = doppler
    
    ydc = y .* exp(-1i*2*pi*fd*t); % y corrected for tentative Doppler
    
    R = xcorr(ydc, p); % actual correlation
    R = R(length(ydc):end); % remove zero padding and ramp-up, see doc xcorr
    R = R(1:end-length(p)+1); % remove ramp-down
     
    [Rmax, tau] = max(abs(R)); % find the maximum and its position
    if Rmax > IP_result
        IP_result = Rmax;
        doppler_estim = fd;
        tau_estim = tau;
    end
    
end

estimatedDelay = tau_estim - 1
estimatedDoppler = doppler_estim

% correct the Doppler, remove the delay, and do a scatterplot
ydc = y .* exp(-1i*2*pi*estimatedDoppler*t);
scatterplot(ydc(tau_estim:end)); grid on;
title('Received samples');
