function test = white_test(result_ols,X,P);
%  PURPOSE: White's General Test 
% ---------------------------------------------------------------------
%  USAGE: test = white_test(result_ols)
%  where: result_ols = a structure returned by function OLS
%         X = independent variables matrix (nobs x nvar)   
%         P = level of significance (optional) by default P=0.95
% ---------------------------------------------------------------------
%  RETURNS: a structure
%         test.meth     = 'White'
%         test.chi2test = empirical value
%         test.chi2crit = critical value
%         test.result = 'hypothesis of homoscedasticity (not) rejected'
%         test.homosc = 1 (not rejected)or 0
% ---------------------------------------------------------------------
 
nIn = nargin;

if nIn < 2
  error('Not enough input arguments.');
elseif nIn > 3
  error('Too many input arguments.');
end

if nIn == 2
  P = 0.95;
end
 
%White's test
test.meth = 'White';
    [nobs,nvar] = size(X);
    for i=1:nvar;
        for j=1:nvar;
           XXkron(:,j,i) =X(:,i).*X(:,j);
        end
    end
    XX = reshape(XXkron,nobs,nvar^2);
    XX = (unique(XX','rows'))';
    [nobs,nvar] = size(XX);
    yy = result_ols.resid.^2;
    resid2_ols = ols(yy,XX);
    test.chi2test = nobs*resid2_ols.rsqr;
    test.chi2crit = chi2inv(P,nvar-1);
    
    if test.chi2test < test.chi2crit
        test.result = 'hypothesis of homoscedasticity NOT REJECTED';
        test.homosc = 1; 
    else
        test.result = 'hypothesis of homoscedasticity REJECTED';
        test.homosc = 0;
    end