function [hV,pV,QV] = portmanteauLB(xV,tmax,alpha,tittxt)
% function [hV,pV,QV] = portmanteauLB(xV,tmax,alpha,tittxt)
% PORTMANTEAU hypothesis test (H0) for independence of time series:
% tests jointly that several autocorrelations are zero.
% It computes the Ljung-Box statistic of the modified sum of 
% autocorrelations up to a maximum lag, for maximum lags 
% 1,2,...,'tmax'. 
% INPUTS:
% - xV      : vector of a scalar time series
% - tmax    : largest delay time to compute autocorrelation for
% - alpha   : significance lavel (default 0.05)
% - tittxt  : string to be displayed in the title of the plot of
%             the p-values vs lag. If empty or not specified, no 
%             plots are displayed.
% OUTPUT:
% - hV      : vector of length 'tmax' of test decision values (0,1) 
%             for the given significance level maximum lags 1,2,...,tmax.
%             h=0 -> "do not reject H0", h=1 -> "reject H0"
% - pV      : vector of length 'tmax' of the corresponding p-values.
% - QV      : vector of length 'tmax' of the corresponding Q statistics
%             that follow Chi-square distribution under H0.
% References:
% Ljung, G. and Box, GEP (1978) "On a measure of lack of fit in time 
% series models", Biometrika, Vol 66, 67-72.

sizeofmark = 15;
if nargin == 3
    tittxt = [];
elseif nargin == 2
    tittxt = [];
    alpha = 0.05;
end
if isempty(alpha), alpha=0.05; end
if (prod(size(alpha))>1), error('ALPHA must be a scalar.'); end
if (alpha<=0 | alpha>=1), error('ALPHA must be between 0 and 1'); end
n = length(xV);
mx = mean(xV);
tmpV = xcorr(xV-mx,tmax);
xcovV = tmpV(tmax+1:2*tmax+1);
xautV = xcovV / xcovV(1);
xautsqV = xautV(2:tmax+1).^2;
sumxautsq = 0;
pV = NaN*ones(tmax,1);
QV = NaN*ones(tmax,1);
for t=1:tmax
    sumxautsq = sumxautsq + xautsqV(t)/(n-t);
    QV(t) = n*(n+2)*sumxautsq;
    pV(t) = 1-chi2cdf(QV(t),t);
end
hV = (pV <= alpha);
if ~isempty(tittxt)
    figure(gcf)
    clf
    plot([1:tmax]',pV,'k')
    hold on
    plot([1:tmax]',pV,'k.','markersize',sizeofmark)
    xlabel('lag \tau')
    ylabel('p-value')
    title([tittxt,' Ljung-Box Portmanteau test'])
end