function [enm]=me_rev(x,n,t0,tol)
% me_rev computes the matching energy of the input time series x, using
% embedding vectors of length n, with a delay time of t0 and a noise
% tolerance tol.
% 
% Reference: J. S. Armand Eyebe Fouda, The matching energy: A novel 
% approach for measuring complexity in time series, 
% Nonlinear Dyn. 86 (2016) 2049-2060
%
% Input
%       x:= data series
%       n:= embedding dimension
%      t0:= delay time for embedding vectors
%     tol:= noise level tolerance
% Output
%     enm:= matching energy value
% -----------------------------------------------------------------------
%                COPYRIGHT (2016): J. S. Armand EYEBE FOUDA
% -----------------------------------------------------------------------

if n<t0
    t0=n;
end
[N,n0]=size(x);
if N<n0
    x=x';
end
N=length(x);
xm=max(abs(x))+eps;
x=x/xm;
if tol~=0
    x=DDQ(x,tol);
end
v=sort(x,'ascend');
vd=sort(x,'descend');
Kj=floor((N-n)/t0)+1;
en=0;
for j=1:t0:N-(n-1)
    xx=x(j:j+(n-1));
    vv=v(j:j+(n-1))-sort(xx,'ascend');
    vvd=vd(j:j+(n-1))-sort(xx,'descend');
    s=find(vv==0,1);
    s1=find(vvd==0,1);
    if (isempty(s))&&(isempty(s1))
        en=en+std(xx)+(sqrt(sum((vv.^2))/n)+sqrt(sum((vvd.^2))/n))/2;
    end
end
enm=en/Kj;

% =====================================================

function yq=DDQ(x,th)
[m,n]=size(x);
if n>m
    x=x';
    m=n;
end
[zc1 Index1]=sort(x,1,'ascend');%
mini=zc1(1);kj=1;zz=zc1;
    for jj=2:m
        stt=abs(zc1(jj)-zc1(jj-1));
        if stt>=th
            zz(jj-1)=mini;
            kj=kj+1;
            mini=zc1(jj);
        else
            zz(jj-1)=mini;
            zz(jj)=mini;
        end
    end
yq(Index1)=zz;