function [varxV,dtV] = GrowVarianceFB(xV)
% [varxV,dtV] = GrowVarianceFB(xV)
% GrowVariance computes the variance growth as a function of time segment.
% The segments are powers of 2 and if the time series length is not
% exactly a power of 2 then segments are formed both in forward and
% backward direction and the statistics are computed on all these segments.
% INPUT 
% - xV      : the time series
% OUTPUT 
% - varxV   : the mean variance for the given segment lengths.
% - dtV     : the array of increasing time segment lengths.

n = length(xV);
dtV = 2.^(2:log2(n))';
ndt = length(dtV);
if dtV(ndt)==n
    varxV = NaN*ones(ndt,1);
else
    varxV = NaN*ones(2*ndt,1);
    zV = flipud(xV);
end
for i=1:ndt
    w = dtV(i);
    nseg=floor(n/w);  % number of segments of the given length
    xM=reshape(xV(1:w*nseg),w,nseg); % a segment at each column
    varxV(i) = mean(var(xM)); % variance for each segment and then mean of variances
end
if dtV(ndt)<n
    for i=1:ndt
        w = dtV(i);
        nseg=floor(n/w);  % number of segments of the given length
        zM=reshape(zV(1:w*nseg),w,nseg); % a segment at each column
        varxV(ndt+i) = mean(var(zM)); % variance for each segment and then mean of variances
    end
    varxM = reshape(varxV,ndt,2);
    varxV = (mean(varxM'))';
end
