% getAsynchronousError
%   :PROPERTIES:
%   :header-args:matlab+: :tangle src/getAsynchronousError.m
%   :header-args:matlab+: :comments org :mkdirp yes
%   :END:
%   <<sec:getAsynchronousError>>

% This Matlab function is accessible [[file:src/getAsynchronousError.m][here]].


function [Wxdec] = getAsynchronousError(data, NbTurn)
%%
    L = length(data);
    res_per_rev = L/NbTurn;

    P = 0:(res_per_rev*NbTurn-1);
    Pos = P' * 360/res_per_rev;

    % Temperature correction
    x1 = myfit2(Pos, data);

    % Convert data to frequency domain and scale accordingly
    X2 = 2/(res_per_rev*NbTurn)*fft(x1);
    f2 = (0:L-1)./NbTurn; %upr -> once per revolution

    %%
    X2dec = zeros(size(X2));
    % Get only the non integer data
    X2dec(mod(f2(:), 1) ~= 0) = X2(mod(f2(:), 1) ~= 0);

    Wxdec = real((res_per_rev*NbTurn)/2 * ifft(X2dec));

    %%
    function Y =  myfit2(x,y)
        A = [x ones(size(x))]\y;
        a = A(1); b = A(2);
        Y = y - (a*x + b);
    end
end
