% problem 2

close all;
clear all;

% number of samples per symbol (upsampling factor)
SPS = 50;

load mf_output.mat

% x-axis for one trace
traceLine = 0:2*SPS-1;

% remove excess samples to full traces
mf_output = mf_output(1:end-mod(length(mf_output),length(traceLine)));

% reshape the data
y = reshape(mf_output, length(traceLine), []);

figure;
subplot(3,1,1);
plot(traceLine, real(y)); grid on;
xlabel('Time'); ylabel('Amplitude'); title('Eye Diagram: In-phase');
subplot(3,1,2);
plot(traceLine, imag(y)); grid on;
xlabel('Time'); ylabel('Amplitude'); title('Eye Diagram: Quadrature');
subplot(3,1,3);
plot(traceLine, abs(y)); grid on;
xlabel('Time'); ylabel('Amplitude'); title('Eye Diagram: Absolute value');

% find the minimum opening of the eye for each time index (that is, over rows)
[minValue, ~] = min(abs(y), [], 2);

% find the maximal opening of the eye and its corresponding time index
[~, d] = max(minValue);

% the delay is d-1
channel_delay = d-1

scatterplot(mf_output(d:SPS:end)); grid on;
title('Received symbols at the output of the MF');