function [result, Logdet, vsig] = acfilter(mSeries, vMean, vParameters, nAR, nMA, mXBeta, mZGamma)
% PURPOSE: computes the autocorrelation function of the columns of series up to lag ilag
% -----------------------------------------------------
% USAGE:     [result, Logdet, vsig] = acfilter(mSeries, vMean, vParameters, nAR, nMA, mXBeta, mZGamma)
%  where:    mSeries = a matrix, the series data variable
%            vMean = a vector of the series
%            vParameters = a matrix with all coefficients, in order:d, AR, MA, beta, gamma
%            nAR, nMA = the order number of AR, MA
%            mXBeta, mZGamma = a matrix of the result for X*Beta and X*Gamma 
% -----------------------------------------------------
% RETURNS:  result: the residual from applying the ARFIMA(vParameters) filter to each column of mSeries
%           Logdet: the log-likelihood
%           vsig:   the correlogram produced by the autocovariance function of ARFIMA
% -----------------------------------------------------             
% NOTE: The core function in ARFIMA package
% -----------------------------------------------------
% ACKNOWLEDGEMENT: The original ARFIMA code was written by Jurgen A Doornik
% -----------------------------------------------------

% The matlab port written and changed by
% Ying Ma
% yingma@email.com

    [nT nY] = size(mSeries);
    
    vsig    = acv(vParameters, nAR, nMA, nT);
      
    mSResidual = mSeries - ones(nT,1)*vMean;
    
    if ~isempty(mXBeta)
        mSResidual =mSResidual - mXBeta; % remove additive regressors before filtering
    end
    
    [mSResidual, Logdet] = pacf(vsig, mSResidual); % apply filter to the residual of y
    
      
    if ~isempty(mZGamma)
        mSResidual = mSResidual - mZGamma; % remove innovative regressors 
    end
    
    result  =   mSResidual;
