%%%============================================================
%%% Function aaft() -- Microsaccade Toolbox 0.9
%%% (R-language Version)
%%% Authors: Ralf Engbert, Petra Sinn, Konstantin Mergenthaler, 
%%% and Hans Trukenbrod
%%% Date: February 20th, 2014
%%%
%%% Converted to Matlab by Anna-Katharina Hauperich, 20th June 2019
%%%============================================================
%%%------------------------------------------------------------
%%% Amplitude-adjusted Fourier Transform (Theiler et al., 1992)
%%%------------------------------------------------------------
function [xs] = aaftMSR(x) 
  %% adjust to uneven length
  N = length(x);
  if floor(N/2)==N/2
    x = x(1:(N-1));
    N = N-1;
  end
  %% AAFT algorithm
  %% 1. Ranking
  [h.x, h.ix] = sort(x);
  Sx = h.x;
  Rx = h.ix;
  %% 2. Random Gaussian data
  g = normrnd(0,1,N,1);
  %% 3. Sort Gaussian data
  Sg = sort(g);
  %% 4. Rearrange Gaussian data
  y = g;
  y(Rx) = Sg;
  %% 5. Create phase-randomized surrogate
  y1 = ftprMSR(y);
  %% 6. Ranked time series
  [h.x, h.ix] = sort(y1);
  Ry1 = h.ix;
  %% 7. AAFT surrogate time series
  xs = x;
  xs(Ry1) = Sx;
