function [stat,crit] = lrtest(wu,wr,level)
% lrtest  Likelihood ratio test for VAR models.
%
% Syntax
% =======
%
%     [stat,crit] = lrtest(V1,V2,level)
%
% Input arguments
% ================
%
% * `V1` [ VAR ] - Unrestricted VAR model.
%
% * `V2` [ VAR ] - Restricted VAR model.
%
% * `level` [ numeric ] - Significance level; if not specified, 0.05 is
% used.
%
% Output arguments
% =================
%
% * `stat` [ numeric ] - LR test stastic.
%
% * `crit` [ numeric ] - LR test critical value based on chi-square
% distribution.
%
% Description
% ============
%
% Example
% ========

% -IRIS Toolbox.
% -Copyright (c) 2007-2012 Jaromir Benes.

if ~exist('level','var')
   level = 0.05;
end

%**************************************************************************

naltr = size(wr.A,3);
naltu = size(wu.A,3);
nloop = max([naltu,naltr]);

if wu.nhyper == wr.nhyper
   VAR.warning(3);
end

% Check the number of hyperparameters, and swap restricted and unrestricted
% VARs if needed.
if wu.nhyper < wr.nhyper
   [wu,wr] = deal(wr,wu);
end

% Fitted periods must the same in both VARs.
flag = true;
nper = nan(1,nloop);
for iloop = 1 : nloop
   rangeR = wr.range(wr.fitted(1,:,min([end,iloop])));
   rangeU = wu.range(wu.fitted(1,:,min([end,iloop])));
   if length(rangeR) ~= length(rangeU) || ~all(datcmp(rangeR,rangeU))
      flag = false;
      break
   end
   nper(iloop) = length(rangeR);
end
if ~flag
   VAR.error(33);
end

stat = nan(1,nloop);
for iloop = 1 : nloop
   if iloop <= naltr
      logdet_Omegar = log(det(wr.Omega(:,:,iloop)));
   end
   if iloop <= naltu
      logdet_Omegau = log(det(wu.Omega(:,:,iloop)));    
   end
   % Check if explained samples are the same in both VARs.
   stat(iloop) = nper(iloop)*(logdet_Omegar - logdet_Omegau);
end

% Critical value.
if nargout > 1
   crit = chi2inv(1-level,wu.nhyper-wr.nhyper);
end

end