function [DoneCalc,MPSRF] = MultiANOVA(NumChains,ComputeSequential,DSGEModel,CurrINI,controls)
% MultiANOVA: Calculates the multivariate potential scale reduction factor from multiple
%             parallel MCMC chains for the original parameters of the DSGE model.
%
% USAGE:
%
%       [DoneCalc,MPSRF] = MultiANOVA(NumChains,ComputeSequential,DSGEModel,CurrINI)
%
% REQUIRED INPUT:  NumChains (integer) with the number of parallel MCMC chains.
%
%                  ComputeSequential (boolean) which is 1 if sequantial estimates should
%                                    be performed and 0 otherwise.
%
%                  DSGEModel (structure)  whose fields contain all required information
%                                    about the model, such as input files, variable and
%                                    sample data. Actual observations are not stored in
%                                    this file.
%
%                  CurrINI (structure) with initialization information.
%
%                  controls (structure), whose fields provide handles to all the UI
%                                    controls in YADA's main dialog.
%
% REQUIRED OUTPUT: DoneCalc (boolean) which is 1 if all calculations were performed and 0
%                                    otherwise.
%
%                  MPSRF (matrix) of dimension NumSeqEst x 4, where NumSeqEst is the number
%                                    of sequential estimates. The first column contains the
%                                    number of observations included in the sequatial
%                                    estimation, the second the Multivariate Potential Scale
%                                    Reduction Factor, the third column the determinant of
%                                    V (the total covariance matrix for the parameters),
%                                    and the fourth column the determinant of  W (the within-chain
%                                    covariance matrix for the parameters).
%
%
%                       Written by: Anders Warne
%                                   New Area Wide Model Project
%                                   DG-R/EMO
%                                   European Central Bank (ECB)
%                                   Email: anders.warne@ecb.europa.eu
%                                   Copyright © 2006-2009 European Central Bank.
%
%                       First version: April 23, 2007.
%                        This version: January 22, 2009.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LICENSE INFORMATION:
%
%      YADA is free software: you can redistribute it and/or modify
%      it under the terms of the GNU General Public License as published by
%      the Free Software Foundation, either version 3 of the License, or
%      (at your option) any later version.
%
%      This program is distributed in the hope that it will be useful,
%      but WITHOUT ANY WARRANTY; without even the implied warranty of
%      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%      GNU General Public License for more details.
%
%      You should have received a copy of the GNU General Public License
%      along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%      YADA is released under the GNU General Public License, Version 3,
%      29 June 2007 <http://www.gnu.org/licenses/>. The current release of
%      the program was last modified by the ECB on the "This version" date
%      above.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CHANGELOG:
%
% * 24-04-2007: Finished the function.
%
% * 20-06-2007: Changed the examined parameter draws from the original to the transformed since
%               the latter should be better described as approximately normal.
%
% * 13-11-2007: Updated the documentation.
%
% * 10-01-2008: Changed the last drawnow call to pause(0.02).
%
% * 27-03-2008: Made sure that the sequential grid has at least 2 values.
%
% * 23-05-2008: Updated the documentation.
%
% * 22-01-2009: Updated the documentation.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

%
% initialize
%
DoneCalc = 0;
MPSRF = [];
%
% set up a wait dialog
%
txt = ['Please wait while YADA computes the multivariate potential scale reduction factors. Estimation started at: ' StringTrim(datestr(now,14)) '.'];
WaitHandle = WaitDLG(txt,'information',['Multivariate ANOVA - ' num2str(NumChains,'%0.0f') ' MCMC Chains'],500,150,CurrINI,1);
WaitControls = get(WaitHandle,'UserData');
StopEstimation = 0;
%
% loop around all MCMC chains
%
for CurrChain=1:NumChains;
   %
   % check if user aborted
   %
   if strcmp(get(WaitControls.cancel,'UserData'),'cancel')==1;
      StopEstimation = 1;
      break;
   end;
   %
   % Now we try to load the posterior draws from MCMC chain number CurrChain
   %
   if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
      [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
      clear('thetaPostSample','LogPost','AcceptedDraws');
      drawnow;
      %
      % determine the total number of draws
      %
      if CurrChain==1;
         [NumIter,NumParam] = size(PostSample);
         NumIter = NumIter-NumBurnin;
         %
         % create a sequential grid
         %
         if ComputeSequential==1;
            %
            % sequential estimation start value and step length
            %
            SeqStartStr = get(controls.dsge.sequentialstart,'String');
            Origin = str2num(strrep(StringTrim(SeqStartStr(DSGEModel.SequentialStartIteration,:)),',',''));
            %
            % make sure that Origin is less than NumIter
            %
            if Origin==NumIter;
               Origin = floor(NumIter/10);
            end;
            SeqStepStr = get(controls.dsge.sequentialstep,'String');
            StepLength = str2num(strrep(StringTrim(SeqStepStr(DSGEModel.SequentialStepLength,:)),',',''));;
         else;
            Origin = NumIter;
            StepLength = 1;
         end;
         %
         % Create the sequential grid over which we will compute the marginal likelihood
         %
         SeqGrid = (Origin:StepLength:NumIter);
         if isempty(SeqGrid)==1;
            SeqGrid = NumIter;
         elseif SeqGrid(length(SeqGrid))<NumIter;
            SeqGrid = [SeqGrid NumIter];
         end;
      end;
      %
      % compute over the sequential grid
      %
      ChainData(CurrChain).Sbarj = zeros(NumParam,length(SeqGrid));
      ChainData(CurrChain).SjSquare = zeros(NumParam,NumParam,length(SeqGrid));
      NumSums = 1;
      OldN = 0;
      for N=SeqGrid;
         if strcmp(get(WaitControls.cancel,'UserData'),'cancel')==1;
            StopEstimation = 1;
            break;
         end;
         Data = PostSample(OldN+1+NumBurnin:N+NumBurnin,:);
         if NumSums>1;
            ChainData(CurrChain).Sbarj(:,NumSums) = (OldN/N)*ChainData(CurrChain).Sbarj(:,NumSums-1)+((1/N)*sum(Data,1)');
            DataDiff = Data'-(ChainData(CurrChain).Sbarj(:,NumSums)*ones(1,size(Data,1)));
            ChainData(CurrChain).SjSquare(:,:,NumSums) = (((OldN-1)/(N-1))*ChainData(CurrChain).SjSquare(:,:,NumSums-1))+((1/(N-1))*DataDiff*DataDiff');
         else;
            ChainData(CurrChain).Sbarj(:,NumSums) = (1/N)*sum(Data,1)';
            DataDiff = Data'-(ChainData(CurrChain).Sbarj(:,NumSums)*ones(1,size(Data,1)));
            ChainData(CurrChain).SjSquare(:,:,NumSums) = (1/(N-1))*DataDiff*DataDiff';
         end;
         OldN = N;
         NumSums = NumSums+1;
         drawnow;
      end;
      if StopEstimation==1;
         break;
      end;
   else;
      %
      % first we need to shut down the wait dialog
      %
      set(WaitControls.text,'UserData','done');
      delete(WaitHandle);
      drawnow;
      pause(0.02);
      %
      % display error message
      %
      txt = ['There are missing data for MCMC chain number ' num2str(CurrChain,'%0.0f') ' out of ' num2str(NumChains,'%0.0f') ' chains. Unable to calculate the multivariate potential scale reduction factor.'];
      About(txt,'information','YADA - Missing Posterior Draws',180,500,CurrINI);
      return;
   end;
end;
%
% shut down the wait dialog
%
set(WaitControls.text,'UserData','done');
delete(WaitHandle);
drawnow;
pause(0.02);
%
% check if the user aborted
%
if StopEstimation==1;
   return;
end;
%
% compute the overall means
%
Sbar = zeros(NumParam,length(SeqGrid));
for CurrChain=1:NumChains;
   Sbar = Sbar+((1/NumChains)*ChainData(CurrChain).Sbarj);
end;
%
% we can now calculate with within-chain variance W and the between-chain variance B
%
W = zeros(NumParam,NumParam,length(SeqGrid));
B = W;
for CurrChain=1:NumChains;
   NumSums = 1;
   for N=SeqGrid;
      B(:,:,NumSums) = B(:,:,NumSums)+(( N/(NumChains-1) )*( ChainData(CurrChain).Sbarj(:,NumSums)-Sbar(:,NumSums) )*( ChainData(CurrChain).Sbarj(:,NumSums)-Sbar(:,NumSums) )');
      W(:,:,NumSums) = W(:,:,NumSums)+( (1/NumChains)*ChainData(CurrChain).SjSquare(:,:,NumSums) );
      NumSums = NumSums+1;
   end;
end;
%
% compute the over-estimate of the variance
%
MPSRF = zeros(length(SeqGrid),4);
MPSRF(:,1) = SeqGrid';
NumSums = 1;
for N=SeqGrid;
   V = (((N-1)/N)*W(:,:,NumSums))+(((NumChains+1)/(NumChains*N))*B(:,:,NumSums));
   MPSRF(NumSums,3) = det(V);
   MPSRF(NumSums,4) = det(W(:,:,NumSums));
   lambda = max(abs(eig((N*W(:,:,NumSums))\B(:,:,NumSums))));
   MPSRF(NumSums,2) = sqrt(((N-1)/N)+(((NumChains+1)/NumChains)*lambda));
   NumSums = NumSums+1;
end;
%
% save to disk
%
if MakeDir(DSGEModel.OutputDirectory,'manova')==1;
   ResFile = [DSGEModel.OutputDirectory '\manova\MANOVA-' DSGEModel.NameOfModel '-' num2str(NumChains,'%0.0f') '.' num2str(NumBurnin,'%0.0f') '.' num2str(NumIter+NumBurnin,'%0.0f') '.mat'];
   save(ResFile,'MPSRF');
end;
DoneCalc = 1;

%
% end of MultiANOVA.m
%
