clear all; close all; clc;

% load the data (code, signalTx, signalRx)
load signals

% sampling period (sec)
Ts=1e-6;

% speed of light (m/sec)
c=3*1e8; 

% Q1
% for checking purposes, let us correlate with the transmitted signal
rTx = xcorr(signalTx,code);
rTx = rTx(length(signalTx):end-length(code)+1); % remove ramp up/down
figure; plot(abs(rTx),'*'); grid on; title('xcorr with the PRN code at Tx')

% now we do what is asked
rRx = xcorr(signalRx,code);
rRx = rRx(length(signalRx):end-length(code)+1);
figure; plot(abs(rRx),'*'); grid on; title('xcorr with the PRN code at Rx')

% detect the peaks, 80% of the max value
% (simpler versions where we detect the max also work, but rounding errors
% might cause the second peak to be larger than the first)
indTx = find(abs(rTx) > 0.8*max(abs(rTx)), 2)
indRx = find(abs(rRx) > 0.8*max(abs(rTx)), 2)

tof1 = (indRx(1)-indTx(1))*Ts
tof2 = (indRx(2)-indTx(2))*Ts

% Q2
d1 = tof1*c/2
d2 = tof2*c/2

% Q3
t1 = (indTx(1)-1)*Ts + tof1/2 % time transmitted plus half time of flight
t2 = (indTx(2)-1)*Ts + tof2/2 % ditto for the second pulse

% Q4
speed = (d2-d1)/(t2-t1)

% Q5
d0 = d1 - speed*t1


