%/*** Compute lag length for AR(p) using BIC ***/
function [p]=bic(x,maxp)

% local n, T, i, Y, Z, v, crit, mincrit, p;

%/* Set up matrices for regression */

n = size(x,1);
T = n-maxp;

Y = x(maxp+1:n);
Z = ones(T,1);

for i=1:maxp;
    if i==1;
        Z = [Z,x(maxp:n-1)];
    else
        Z = [Z,(x(maxp-i+2:n-i+1)-x(maxp-i+1:n-i))];
    end
end

% /* Minimize information criterion */

for i=1:maxp
    v = Y-Z(:,1:(i+1))*(Z(:,1:(i+1))\Y);
    crit = log((v'*v)/T)+(i+1)*log(T)/T;

    if i==1
        p = i;
        mincrit = crit;
    elseif crit < mincrit
        p = i;
        mincrit = crit;
    end
end

end
