% @author Pascal Gollor
% @date 2018-10-18
% 
% create two signals with random phase offset and try to reduce the offset
% via fft analysis
%


clear all;
clear figures;
clc;

%% values
% samples
N = 1000;

% signal periods
periods = 2;

% amplitude signal 1
amp1 = 1;

% amplitude signal 2
amp2 = 1.4;


%% signal generation
Fs = N / periods;
T = 1 / Fs;
t = 0:T:periods - T;
freq = 1;
phase_offset = rand(1)*(pi/2);


% signal
s1 = 2 + amp1 * sin(2* pi * freq * t);
s2 = 1 + amp2 * sin(2* pi * freq * t + phase_offset);

% noise
hi = 0.05;
lo = -0.05;
n1 = lo + (hi-lo) * rand([1 N]);
n2 = lo + (hi-lo) * rand([1 N]);

s1 = s1 + n1;
s2 = s2 + n2;


% true phase ofset
phase_offset


%% calculation

% fft
fft_s1 = fft(s1);
fft_s2 = fft(s2);

% remove dc component
offset1 = fft_s1(1) / N;
fft_s1(1) = 0;
fft_s2(1) = 0;

% calculated offset
phase_rad = angle(fft_s1(1:end/2)/fft_s2(1:end/2))

% signal shiftig
fft_s2_shift = fft_s2 .* exp(-j*t*phase_rad);
s2_shift_comp = ifft(fft_s2_shift);
s2_phase = angle(s2_shift_comp);
s2_phase(s2_phase > 0) = 1;
s2_phase(s2_phase < 0) = -1;
s2_shift = abs(s2_shift_comp) .* s2_phase + offset1;


%% plotting
figure(1);
plot(t, s1);
hold on;
plot(t, s2);
plot(t, s2_shift);
hold off;
legend('original signal', 'shifted signal', 'back shifted signal')
