function SVEs = DSGESVEDistribution(DSGEModel,CurrINI,Selector,SelectedParameters,NumDraws,TotalDraws,CurrChain)
% DSGESVEDistribution: Computes the mean value of X as well as quantiles by loading data from disk.
%                      X is here either 1-step ahead forecasts, state variables, state shocks, or
%                      measurement errors.
%
% USAGE:
%
%       SVEs = DSGESVEDistribution(DSGEModel,CurrINI,Selector,SelectedParameters,NumDraws,TotalDraws,CurrChain)
%
% REQUIRED INPUT:  DSGEModel (structure) with fields containing all the information about a DSGE Model for YADA.
%
%                  CurrINI (structure) with initialization information.
%
%                  Selector (integer) that is:
%                                            1 - if the function should work with 1-step ahead forecasts;
%                                            2 - if the function should work with state variable estimates;
%                                            3 - if the function should work with state shock estimates; and
%                                            4 - if the function should work with measurement error estimates.
%                                            5 - if the function should work with observed variable correlations.
%                                            6 - if the function should work with state variable correlations.
%                                            7 - if the function should work with state shock correlations.
%                                            8 - if the function should work with measurement error correlations.
%
%                  SelectedParameters (vector) of dimension NumParam which indicates which parameters can vary from
%                                     one draw to the next (1) and which parameters are fixed at posterior mode (0).
%
%                  NumDraws (integer) with the number of effective draws from the posterior distribution of the
%                                     parameters.
%
%                  TotalDraws (integer) with the number of draws from the posterior distribution of the parameters
%                                     that could have been used.
%
%                  CurrChain (integer) with the number for the current Markov chain.
%
% REQUIRED OUTPUT: SVEs (structure) with fields that depend on Selector. For 1-step ahead forecasts the fields are:
%                                     "Yhat" and "Y", where Yhat is a matrix with the mean forecasts and Y the observed
%                                     data. For the state variable estimates the fields are: "Ksitt1", "Ksitt", and
%                                     "KsitT". These are the mean estimates of the forecast, update, and smooth
%                                     estimates of the states. For the state shock estimates fhe fields are: "etatt"
%                                     and "etatT", the update and smooth estimates of the shocks. Moreover, the field
%                                     "ShockNames" gives the names of the shocks that have a non-zero effect on the
%                                     observed variables. For the measuremente rrors the fields are: "wtt", "wtT",
%                                     the update and smooth estimates of the measurement errors. Moreover, the field
%                                     "ErrorIndicator" is a vector that indicates which equations have a positive
%                                     measurement error variance (1) and which don't (0). In addition, the vector
%                                     field "Quantiles" is used, with subfields "percent" and field names determined
%                                     by the Selector. For the 1-step ahead forecasts we again have "Yhat", etc.
%                                     The field "DateVector" is included for all thse 4 cases. For the observed
%                                     variable correlations the fields are: "MeanY", "StdY", and "CorrY". In addition, it
%                                     yields the fields "DateMeanY", "DataStdY", and "DataCorrY". For the state variable
%                                     correlations the fields are "StdKsi" and "CorrKsi". For the state shock correlations
%                                     the fields are "Meaneta", "Stdeta", and "Correta". Finally, for the measurement error
%                                     correlations, the fields are "Meanw", "Stdw", and "Corrw".
%
%
%                       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: November 21, 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:
%
% * 22-11-2007: Finished the function.
%
% * 26-11-2007: Added a few line end ";" characters.
%
% * 27-11-2007: Aded the code for state shock correlations.
%
% * 28-11-2007: Added the code for the state variable correlations and the measurement error correlations.
%
% * 29-11-2007: Added the code for the autocorrelations for the observed variables.
%
% * 30-11-2007: Added the field "AutoCovHorizon" to the output under the autocorrelation calculations.
%
% * 10-01-2008: Changed the last drawnow call to pause(0.02).
%
% * 28-02-2008: Updated the documentation.
%
% * 29-02-2008: Made some changes to the text-messages shown to the user during computations.
%
% * 03-03-2008: Made sure that the number of exogenous variables is properly taken into account for the observed
%               variable correlations.
%
% * 23-05-2008: Updated the documentation.
%
% * 22-01-2009: Updated the documentation.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

%
% initialize
%
SVEs = [];
%
% fix the information needed to setup the file names
%
SelParamStr = strrep(num2str(SelectedParameters),' ','');
%
NumFiles = ceil(NumDraws/min(NumDraws,1000));
NumQuants = length(DSGEModel.Percentiles);
%
% we need to first determine the size of the data
%
file = [DSGEModel.OutputDirectory '\state\DSGE-SVE-' DSGEModel.NameOfModel '-' num2str(CurrChain,'%0.0f') '-' SelParamStr '-1-' num2str(NumFiles,'%0.0f') '.' num2str(NumDraws,'%0.0f') '-' num2str(TotalDraws,'%0.0f') '.mat'];
SVEData = load(file);
if Selector<=4;
   SVEs.DateVector = SVEData.DateVector;
end;
%
if Selector==1;
   %
   % we have the 1-step ahead forecasts
   %
   SVEs.Y = SVEData.Y;
   [n T] = size(SVEs.Y);
   SVEs.Yhat = zeros(n,T);
   for i=1:NumQuants;
      SVEs.Quantiles(i).Yhat = zeros(n,T);
      SVEs.Quantiles(i).percent = DSGEModel.Percentiles(i);
   end;
   %
   % setup a wait dialog
   %
   txt = ['Please wait while YADA computes the mean 1-step ahead forecast paths as well as percentile values for the 1-step ahead forecast paths. The data are loaded sequentially from disk and it may therefore take some time. Current variable: ' StringTrim(DSGEModel.VariableNames(1,:)) '.'];
   WaitHandle = WaitDLG(txt,'information','1-Step Ahead Forecast Distribution',500,200,CurrINI,0);
   WaitControls = get(WaitHandle,'UserData');
   %
   for i=1:n;
      %
      % update the wait dialog
      %
      txt = ['Please wait while YADA computes the mean 1-step ahead forecast paths as well as percentile values for the 1-step ahead forecast paths. The data are loaded sequentially from disk and it may therefore take some time. Current variable: ' StringTrim(DSGEModel.VariableNames(i,:)) '.'];
      set(WaitControls.text,'String',txt);
      drawnow;
      %
      % set up a matrix for the data
      %
      Temp =zeros(NumDraws,T);
      CurrSaves = 0;
      for ThisSave=1:NumFiles;
         file = [DSGEModel.OutputDirectory '\state\DSGE-SVE-' DSGEModel.NameOfModel '-' num2str(CurrChain,'%0.0f') '-' SelParamStr '-' num2str(ThisSave,'%0.0f') '-' num2str(NumFiles,'%0.0f') '.' num2str(NumDraws,'%0.0f') '-' num2str(TotalDraws,'%0.0f') '.mat'];
         SVEData = load(file);
         SVE = SVEData.SVE;
         NumSaves = length(SVE);
         %
         % load data from CurrSaves to NumSaves+1-CurrSaves
         %
         for s=1:NumSaves;
            Temp(CurrSaves+s,:) = SVE(s).Yhat(i,:);
         end;
         CurrSaves = CurrSaves+NumSaves;
         drawnow;
      end;
      %
      % we can now calculate the mean
      %
      SVEs.Yhat(i,:) = (1/NumDraws)*sum(Temp,1);
      %
      % now we can sort these and create the quantiles from the sorted
      %
      Temp = sort(Temp);
      for l=1:NumQuants;
         if DSGEModel.Percentiles(l)<50;
            QuantVal = ceil((DSGEModel.Percentiles(l)/100)*NumDraws);
         else;
            QuantVal = floor((DSGEModel.Percentiles(l)/100)*NumDraws);
         end;
         SVEs.Quantiles(l).Yhat(i,:) = Temp(QuantVal,:);
      end;
      drawnow;
   end;
elseif Selector==2;
   %
   % we have the state variables
   %
   [r T] = size(SVEData.SVE(1).Ksitt);
   SVEs.Ksitt1 = zeros(r,T);
   SVEs.Ksitt = zeros(r,T);
   SVEs.KsitT = zeros(r,T);
   for i=1:NumQuants;
      SVEs.Quantiles(i).Ksitt1 = zeros(r,T);
      SVEs.Quantiles(i).Ksitt = zeros(r,T);
      SVEs.Quantiles(i).KsitT = zeros(r,T);
      SVEs.Quantiles(i).percent = DSGEModel.Percentiles(i);
   end;
   %
   % setup a wait dialog
   %
   txt = ['Please wait while YADA computes the mean state variable paths under smoothing as well as percentile values for the state variable paths. The data are loaded sequentially from disk and it may therefore take some time. Current variable: ' StringTrim(DSGEModel.StateVariableNames(1,:)) '.'];
   WaitHandle = WaitDLG(txt,'information','State Variable Distribution',500,200,CurrINI,0);
   WaitControls = get(WaitHandle,'UserData');
   %
   for i=1:r;
      %
      % update the wait dialog
      %
      txt = ['Please wait while YADA computes the mean state variable paths under smoothing as well as percentile values for the state variable paths. The data are loaded sequentially from disk and it may therefore take some time. Current variable: ' StringTrim(DSGEModel.StateVariableNames(i,:)) '.'];
      set(WaitControls.text,'String',txt);
      drawnow;
      %
      % set up matrices for storing the data
      %
      TempT = zeros(NumDraws,T);
      Tempt = zeros(NumDraws,T);
      Tempt1 = zeros(NumDraws,T);
      CurrSaves = 0;
      for ThisSave=1:NumFiles;
         file = [DSGEModel.OutputDirectory '\state\DSGE-SVE-' DSGEModel.NameOfModel '-' num2str(CurrChain,'%0.0f') '-' SelParamStr '-' num2str(ThisSave,'%0.0f') '-' num2str(NumFiles,'%0.0f') '.' num2str(NumDraws,'%0.0f') '-' num2str(TotalDraws,'%0.0f') '.mat'];
         SVEData = load(file);
         SVE = SVEData.SVE;
         NumSaves = length(SVE);
         %
         % load data from CurrSaves to NumSaves+1-CurrSaves
         %
         for s=1:NumSaves;
            TempT(CurrSaves+s,:) = SVE(s).KsitT(i,:);
            Tempt(CurrSaves+s,:) = SVE(s).Ksitt(i,:);
            Tempt1(CurrSaves+s,:) = SVE(s).Ksitt1(i,:);
         end;
         CurrSaves = CurrSaves+NumSaves;
         drawnow;
      end;
      %
      % we can now calculate the mean
      %
      SVEs.KsitT(i,:) = (1/NumDraws)*sum(TempT,1);
      SVEs.Ksitt(i,:) = (1/NumDraws)*sum(Tempt,1);
      SVEs.Ksitt1(i,:) = (1/NumDraws)*sum(Tempt1,1);
      %
      % now we can sort these and create the quantiles from the sorted
      %
      TempT = sort(TempT);
      Tempt = sort(Tempt);
      Tempt1 = sort(Tempt1);
      for l=1:NumQuants;
         if DSGEModel.Percentiles(l)<50;
            QuantVal = ceil((DSGEModel.Percentiles(l)/100)*NumDraws);
         else;
            QuantVal = floor((DSGEModel.Percentiles(l)/100)*NumDraws);
         end;
         SVEs.Quantiles(l).KsitT(i,:) = TempT(QuantVal,:);
         SVEs.Quantiles(l).Ksitt(i,:) = Tempt(QuantVal,:);
         SVEs.Quantiles(l).Ksitt1(i,:) = Tempt1(QuantVal,:);
      end;
      drawnow;
   end;
elseif Selector==3;
   %
   % we have the state shocks to sort out
   %
   [q T] = size(SVEData.SVE(1).etatT);
   SVEs.etatT = zeros(q,T);
   SVEs.etatt = zeros(q,T);
   for i=1:NumQuants;
      SVEs.Quantiles(i).etatT = zeros(q,T);
      SVEs.Quantiles(i).etatt = zeros(q,T);
      SVEs.Quantiles(i).percent = DSGEModel.Percentiles(i);
   end;
   SVEs.ShockNames = DSGEModel.StateShockNames(SVEData.KeepShocks,:);
   %
   % setup a wait dialog
   %
   txt = ['Please wait while YADA computes the mean state shock paths under smoothing as well as percentile values for the state shock paths. The data are loaded sequentially from disk and it may therefore take some time. Current variable: ' StringTrim(SVEs.ShockNames(1,:)) '.'];
   WaitHandle = WaitDLG(txt,'information','State Shock Distribution',500,200,CurrINI,0);
   WaitControls = get(WaitHandle,'UserData');
   %
   for i=1:q;
      %
      % update the wait dialog
      %
      txt = ['Please wait while YADA computes the mean state shock paths under smoothing as well as percentile values for the state shock paths. The data are loaded sequentially from disk and it may therefore take some time. Current variable: ' StringTrim(SVEs.ShockNames(i,:)) '.'];
      set(WaitControls.text,'String',txt);
      drawnow;
      %
      % set up matrices for storing the data
      %
      TempT = zeros(NumDraws,T);
      Tempt = zeros(NumDraws,T);
      CurrSaves = 0;
      for ThisSave=1:NumFiles;
         file = [DSGEModel.OutputDirectory '\state\DSGE-SVE-' DSGEModel.NameOfModel '-' num2str(CurrChain,'%0.0f') '-' SelParamStr '-' num2str(ThisSave,'%0.0f') '-' num2str(NumFiles,'%0.0f') '.' num2str(NumDraws,'%0.0f') '-' num2str(TotalDraws,'%0.0f') '.mat'];
         SVEData = load(file);
         SVE = SVEData.SVE;
         NumSaves = length(SVE);
         %
         % load data from CurrSaves to NumSaves+1-CurrSaves
         %
         for s=1:NumSaves;
            TempT(CurrSaves+s,:) = SVE(s).etatT(i,:);
            Tempt(CurrSaves+s,:) = SVE(s).etatt(i,:);
         end;
         CurrSaves = CurrSaves+NumSaves;
         drawnow;
      end;
      %
      % we can now calculate the mean
      %
      SVEs.etatT(i,:) = (1/NumDraws)*sum(TempT,1);
      SVEs.etatt(i,:) = (1/NumDraws)*sum(Tempt,1);
      %
      % now we can sort these and create the quantiles from the sorted
      %
      TempT = sort(TempT);
      Tempt = sort(Tempt);
      for l=1:NumQuants;
         if DSGEModel.Percentiles(l)<50;
            QuantVal = ceil((DSGEModel.Percentiles(l)/100)*NumDraws);
         else;
            QuantVal = floor((DSGEModel.Percentiles(l)/100)*NumDraws);
         end;
         SVEs.Quantiles(l).etatT(i,:) = TempT(QuantVal,:);
         SVEs.Quantiles(l).etatt(i,:) = Tempt(QuantVal,:);
      end;
      drawnow;
   end;
elseif Selector==4;
   %
   % we have the measurement errors
   %
   if isfield(SVEData.SVE(1),'wtT')==0;
      return;
   end;
   [n T] = size(SVEData.SVE(1).wtT);
   SVEs.wtT = zeros(n,T);
   SVEs.wtt = zeros(n,T);
   for i=1:NumQuants;
      SVEs.Quantiles(i).wtT = zeros(n,T);
      SVEs.Quantiles(i).wtt = zeros(n,T);
      SVEs.Quantiles(i).percent = DSGEModel.Percentiles(i);
   end;
   R = SVEData.R;
   SVEs.ErrorIndicator = zeros(n,1);
   %
   % setup a wait dialog
   %
   txt = ['Please wait while YADA computes the mean measurement error paths under smoothing as well as percentile values for the measurement error paths. The data are loaded sequentially from disk and it may therefore take some time. Measurement error for variable: ' StringTrim(DSGEModel.VariableNames(1,:)) '.'];
   WaitHandle = WaitDLG(txt,'information','Measurement Error Distribution',500,200,CurrINI,0);
   WaitControls = get(WaitHandle,'UserData');
   %
   for i=1:n;
      %
      % update the wait dialog
      %
      txt = ['Please wait while YADA computes the mean measurement error paths under smoothing as well as percentile values for the measurement error paths. The data are loaded sequentially from disk and it may therefore take some time. Measurement error for variable: ' StringTrim(DSGEModel.VariableNames(i,:)) '.'];
      set(WaitControls.text,'String',txt);
      drawnow;
      %
      % check if the measurement error matters or not
      %
      if R(i,i)>0;
         SVEs.ErrorIndicator(i,1) = 1;
         %
         % set up matrices for storing the data
         %
         TempT = zeros(NumDraws,T);
         Tempt = zeros(NumDraws,T);
         CurrSaves = 0;
         for ThisSave=1:NumFiles;
            file = [DSGEModel.OutputDirectory '\state\DSGE-SVE-' DSGEModel.NameOfModel '-' num2str(CurrChain,'%0.0f') '-' SelParamStr '-' num2str(ThisSave,'%0.0f') '-' num2str(NumFiles,'%0.0f') '.' num2str(NumDraws,'%0.0f') '-' num2str(TotalDraws,'%0.0f') '.mat'];
            SVEData = load(file);
            SVE = SVEData.SVE;
            NumSaves = length(SVE);
            %
            % load data from CurrSaves to NumSaves+1-CurrSaves
            %
            for s=1:NumSaves;
               TempT(CurrSaves+s,:) = SVE(s).wtT(i,:);
               Tempt(CurrSaves+s,:) = SVE(s).wtt(i,:);
            end;
            CurrSaves = CurrSaves+NumSaves;
            drawnow;
         end;
         %
         % we can now calculate the mean
         %
         SVEs.wtT(i,:) = (1/NumDraws)*sum(TempT,1);
         SVEs.wtt(i,:) = (1/NumDraws)*sum(Tempt,1);
         %
         % now we can sort these and create the quantiles from the sorted
         %
         TempT = sort(TempT);
         Tempt = sort(Tempt);
         for l=1:NumQuants;
            if DSGEModel.Percentiles(l)<50;
               QuantVal = ceil((DSGEModel.Percentiles(l)/100)*NumDraws);
            else;
               QuantVal = floor((DSGEModel.Percentiles(l)/100)*NumDraws);
            end;
            SVEs.Quantiles(l).wtT(i,:) = TempT(QuantVal,:);
            SVEs.Quantiles(l).wtt(i,:) = Tempt(QuantVal,:);
         end;
         drawnow;
      end;
   end;
elseif Selector==5;
   %
   % we have the observed variable correlations
   %
   Y = SVEData.Y;
   [n T] = size(Y);
   %
   % compute the data based mean, standard deviation, and autocorrelation
   %
   X = SVEData.X;
   k = min(size(X));
   if isempty(X)==0;
      SVEs.Data.Mean = (Y*X')/(X*X');
      %
      % de-mean Y using estimate of the mean from the data rather than A'.
      %
      Y = Y-(SVEs.Data.Mean*X);
   else;
      SVEs.Data.Mean = (1/T)*sum(Y,2);
      Y = Y-(SVEs.Data.Mean*ones(1,T));
   end;
   SVEs.Data.Std = sqrt(diag((1/T)*Y*Y'));
   AutoCovHorizon = size(SVEData.SVE(1).CorrY,3)-1;
   SVEs.Data.Corr = zeros((n*(n+1))/2,1+(2*AutoCovHorizon));
   SVEs.Data.Corr(:,AutoCovHorizon+1) = vech(((1/T)*Y*Y')./(SVEs.Data.Std*SVEs.Data.Std'));
   for i=1:AutoCovHorizon;
      Y = SVEData.Y(:,1+i:size(SVEData.Y,2));
      YL = SVEData.Y(:,1:length(SVEData.Y)-i);
%      T = size(Y,2);
      if isempty(X)==0;
         X = SVEData.X(:,1+i:size(SVEData.X,2));
         Y = Y-(((Y*X')/(X*X'))*X);
         XL = SVEData.X(:,1:size(SVEData.X,2)-i);
         YL = YL-(((Y*X')/(X*X'))*XL);
      else;
         Y = Y-(SVEs.Data.Mean*ones(1,size(Y,2)));
         YL = YL--(SVEs.Data.Mean*ones(1,size(YL,2)));
      end;
      Corr = ((1/T)*Y*YL')./(SVEs.Data.Std*SVEs.Data.Std');
      %
      % first vector is lagged and second is leaded.
      %
      SVEs.Data.Corr(:,AutoCovHorizon+1+i) = vech(Corr');
      SVEs.Data.Corr(:,AutoCovHorizon+1-i) = vech(Corr);
   end;
   %
   % initialize model based mean, standard deviation, and autocorrelations
   %
   if k>0;
      SVEs.Mean = zeros(n,k);
   else;
      SVEs.Mean = [];
   end;
   SVEs.Std = zeros(n,1);
   SVEs.Corr = zeros((n*(n+1))/2,1+(2*AutoCovHorizon));
   for i=1:NumQuants;
      if k>0;
         SVEs.Quantiles(i).Mean = zeros(n,k);
      else;
         SVEs.Quantiles(i).Mean = [];
      end;
      SVEs.Quantiles(i).Std = zeros(n,1);
      SVEs.Quantiles(i).Corr = zeros((n*(n+1))/2,1+(2*AutoCovHorizon));
      SVEs.Quantiles(i).percent = DSGEModel.Percentiles(i);
   end;
   %
   % setup a wait dialog
   %
   txt = ['Please wait while YADA computes the distributions for the model based population means and autocorrelations of the observed variables. The data are loaded sequentially from disk and it may therefore take some time. Current variable: ' StringTrim(DSGEModel.VariableNames(1,:)) '.'];
   WaitHandle = WaitDLG(txt,'information','Autocorrelation Distribution',500,200,CurrINI,0);
   WaitControls = get(WaitHandle,'UserData');
   %
   Total = 0;
   for i=1:n;
      %
      % setup a wait dialog
      %
      txt = ['Please wait while YADA computes the distributions for the model based population means and autocorrelations of the observed variables. The data are loaded sequentially from disk and it may therefore take some time. Current variable: ' StringTrim(DSGEModel.VariableNames(i,:)) '.'];
      set(WaitControls.text,'String',txt);
      drawnow;
      %
      % set up a matrix for the data
      %
      if k>0;
         TempMean = zeros(NumDraws,k);
      end;
      TempStd = zeros(NumDraws,1);
      CurrSaves = 0;
      for ThisSave=1:NumFiles;
         file = [DSGEModel.OutputDirectory '\state\DSGE-SVE-' DSGEModel.NameOfModel '-' num2str(CurrChain,'%0.0f') '-' SelParamStr '-' num2str(ThisSave,'%0.0f') '-' num2str(NumFiles,'%0.0f') '.' num2str(NumDraws,'%0.0f') '-' num2str(TotalDraws,'%0.0f') '.mat'];
         SVEData = load(file);
         SVE = SVEData.SVE;
         NumSaves = length(SVE);
         %
         % load data from CurrSaves to NumSaves+1-CurrSaves
         %
         if k>0;
            for s=1:NumSaves;
               TempMean(CurrSaves+s,:) = SVE(s).MeanY(i,:);
               TempStd(CurrSaves+s,1) = SVE(s).StdY(i,1);
            end;
         else;
            for s=1:NumSaves;
               TempStd(CurrSaves+s,1) = SVE(s).StdY(i,1);
            end;
         end;
         CurrSaves = CurrSaves+NumSaves;
         drawnow;
      end;
      %
      % we can now calculate the mean
      %
      if k>0;
         SVEs.Mean(i,:) = (1/NumDraws)*sum(TempMean,1);
      end;
      SVEs.Std(i,1) = (1/NumDraws)*sum(TempStd,1);
      %
      % now we can sort these and create the quantiles from the sorted
      %
      TempStd = sort(TempStd);
      for l=1:NumQuants;
         if DSGEModel.Percentiles(l)<50;
            QuantVal = ceil((DSGEModel.Percentiles(l)/100)*NumDraws);
         else;
            QuantVal = floor((DSGEModel.Percentiles(l)/100)*NumDraws);
         end;
         SVEs.Quantiles(l).Std(i,1) = TempStd(QuantVal,1);
      end;
      drawnow;
      %
      for j=1:size(TempMean,2);
         TempMeanj = sort(TempMean(:,j));
         for l=1:NumQuants;
            if DSGEModel.Percentiles(l)<50;
               QuantVal = ceil((DSGEModel.Percentiles(l)/100)*NumDraws);
            else;
               QuantVal = floor((DSGEModel.Percentiles(l)/100)*NumDraws);
            end;
            SVEs.Quantiles(l).Mean(i,j) = TempMeanj(QuantVal,1);
         end;
         drawnow;
      end;

   end;
   %
   % now we need to deal with the autocorrelations
   %
   SVEs.AutoCovHorizon = (-AutoCovHorizon:1:AutoCovHorizon);
   for j=1:(2*AutoCovHorizon)+1;
      %
      % setup a wait dialog
      %
      txt = ['Please wait while YADA computes the distributions for the model based population means and autocorrelations of the observed variables. The data are loaded sequentially from disk and it may therefore take some time. Current autocorrelation horizon: ' int2str(j-(AutoCovHorizon+1)) '.'];
      set(WaitControls.text,'String',txt);
      drawnow;
      %
      TempCorr = zeros(NumDraws,(n*(n+1))/2);
      CurrSaves = 0;
      for ThisSave=1:NumFiles;
         file = [DSGEModel.OutputDirectory '\state\DSGE-SVE-' DSGEModel.NameOfModel '-' num2str(CurrChain,'%0.0f') '-' SelParamStr '-' num2str(ThisSave,'%0.0f') '-' num2str(NumFiles,'%0.0f') '.' num2str(NumDraws,'%0.0f') '-' num2str(TotalDraws,'%0.0f') '.mat'];
         SVEData = load(file);
         SVE = SVEData.SVE;
         NumSaves = length(SVE);
         %
         % load data from CurrSaves to NumSaves+1-CurrSaves
         %
         for s=1:NumSaves;
            if j<=AutoCovHorizon;
               TempCorr(CurrSaves+s,:) = vech(SVE(s).CorrY(:,:,AutoCovHorizon+2-j)')';
            else;
               TempCorr(CurrSaves+s,:) = vech(SVE(s).CorrY(:,:,j-(AutoCovHorizon)))';
            end;
         end;
         CurrSaves = CurrSaves+NumSaves;
         drawnow;
      end;
      %
      % compute the mean
      %
      SVEs.Corr(:,j) = (1/NumDraws)*sum(TempCorr,1)';
      %
      % sort the data and determine the quantile values
      %
      TempCorr = sort(TempCorr);
      for l=1:NumQuants;
         if DSGEModel.Percentiles(l)<50;
            QuantVal = ceil((DSGEModel.Percentiles(l)/100)*NumDraws);
         else;
            QuantVal = floor((DSGEModel.Percentiles(l)/100)*NumDraws);
         end;
         SVEs.Quantiles(l).Corr(:,j) = TempCorr(QuantVal,:)';
      end;
      drawnow;
   end;
elseif Selector==6;
   %
   % we have the state variable correlations
   %
   r = length(SVEData.SVE(1).StdKsi);
   SVEs.StdKsi = zeros(r,1);
   SVEs.CorrKsi = zeros(r,r);
   for i=1:NumQuants;
      SVEs.Quantiles(i).StdKsi = zeros(r,1);
      SVEs.Quantiles(i).CorrKsi = zeros(r,r);
      SVEs.Quantiles(i).percent = DSGEModel.Percentiles(i);
   end;
   %
   % setup a wait dialog
   %
   txt = ['Please wait while YADA computes the mean state variable correlations for model-based population moments as well as percentile values for the state variable correlations. The data are loaded sequentially from disk and it may therefore take some time. Current variable: ' StringTrim(DSGEModel.StateVariableNames(1,:)) '.'];
   WaitHandle = WaitDLG(txt,'information','State Variable Distribution',500,200,CurrINI,0);
   WaitControls = get(WaitHandle,'UserData');
   %
   for i=1:r;
      %
      % update the wait dialog
      %
      txt = ['Please wait while YADA computes the mean state variable correlations for model-based population moments as well as percentile values for the state variable correlations. The data are loaded sequentially from disk and it may therefore take some time. Current variable: ' StringTrim(DSGEModel.StateVariableNames(i,:)) '.'];
      set(WaitControls.text,'String',txt);
      drawnow;
      %
      % set up matrices for storing the data
      %
      TempStd = zeros(NumDraws,1);
      TempCorr = zeros(NumDraws,r);
      CurrSaves = 0;
      for ThisSave=1:NumFiles;
         file = [DSGEModel.OutputDirectory '\state\DSGE-SVE-' DSGEModel.NameOfModel '-' num2str(CurrChain,'%0.0f') '-' SelParamStr '-' num2str(ThisSave,'%0.0f') '-' num2str(NumFiles,'%0.0f') '.' num2str(NumDraws,'%0.0f') '-' num2str(TotalDraws,'%0.0f') '.mat'];
         SVEData = load(file);
         SVE = SVEData.SVE;
         NumSaves = length(SVE);
         %
         % load data from CurrSaves to NumSaves+1-CurrSaves
         %
         for s=1:NumSaves;
            TempStd(CurrSaves+s,:) = SVE(s).StdKsi(i,1);
            TempCorr(CurrSaves+s,:) = SVE(s).CorrKsi(i,:);
         end;
         CurrSaves = CurrSaves+NumSaves;
         drawnow;
      end;
      %
      % we can now calculate the mean
      %
      SVEs.StdKsi(i,1) = (1/NumDraws)*sum(TempStd);
      SVEs.CorrKsi(i,:) = (1/NumDraws)*sum(TempCorr,1);
      %
      % now we can sort these and create the quantiles from the sorted
      %
      TempStd = sort(TempStd);
      TempCorr = sort(TempCorr);
      for l=1:NumQuants;
         if DSGEModel.Percentiles(l)<50;
            QuantVal = ceil((DSGEModel.Percentiles(l)/100)*NumDraws);
         else;
            QuantVal = floor((DSGEModel.Percentiles(l)/100)*NumDraws);
         end;
         SVEs.Quantiles(l).StdKsi(i,1) = TempStd(QuantVal,1);
         SVEs.Quantiles(l).CorrKsi(i,:) = TempCorr(QuantVal,:);
      end;
      drawnow;
   end;
elseif Selector==7;
   %
   % we have state shock correlations
   %
   [q T] = size(SVEData.SVE(1).etatT);
   SVEs.Meaneta = zeros(q,1);
   SVEs.Stdeta = zeros(q,1);
   SVes.Correta = zeros(q,q);
   for i=1:NumQuants;
      SVEs.Quantiles(i).Meaneta = zeros(q,1);
      SVEs.Quantiles(i).Stdeta = zeros(q,1);
      SVEs.Quantiles(i).Correta = zeros(q,q);
      SVEs.Quantiles(i).percent = DSGEModel.Percentiles(i);
   end;
   SVEs.ShockNames = DSGEModel.StateShockNames(SVEData.KeepShocks,:);
   %
   % setup a wait dialog
   %
   txt = ['Please wait while YADA computes the average state shock means and correlations under smoothing as well as percentile values. The data are loaded sequentially from disk and it may therefore take some time. Current variable: ' StringTrim(SVEs.ShockNames(1,:)) '.'];
   WaitHandle = WaitDLG(txt,'information','State Shock Correlation Distribution',500,200,CurrINI,0);
   WaitControls = get(WaitHandle,'UserData');
   %
   for i=1:q;
      %
      % update the wait dialog
      %
      txt = ['Please wait while YADA computes the average state shock means and correlations under smoothing as well as percentile values. The data are loaded sequentially from disk and it may therefore take some time. Current variable: ' StringTrim(SVEs.ShockNames(i,:)) '.'];
      set(WaitControls.text,'String',txt);
      drawnow;
      %
      % set up matrices for storing the data
      %
      TempMean = zeros(NumDraws,1);
      TempStd = zeros(NumDraws,1);
      TempCorr = zeros(NumDraws,q);
      CurrSaves = 0;
      for ThisSave=1:NumFiles;
         file = [DSGEModel.OutputDirectory '\state\DSGE-SVE-' DSGEModel.NameOfModel '-' num2str(CurrChain,'%0.0f') '-' SelParamStr '-' num2str(ThisSave,'%0.0f') '-' num2str(NumFiles,'%0.0f') '.' num2str(NumDraws,'%0.0f') '-' num2str(TotalDraws,'%0.0f') '.mat'];
         SVEData = load(file);
         SVE = SVEData.SVE;
         NumSaves = length(SVE);
         %
         % load data from CurrSaves to NumSaves+1-CurrSaves
         %
         for s=1:NumSaves;
            TempMean(CurrSaves+s,:) = SVE(s).Meaneta(i,1);
            TempStd(CurrSaves+s,:) = sqrt(abs(SVE(s).Coveta(i,i)));
            TempCorr(CurrSaves+s,:) = SVE(s).Correta(i,:);
         end;
         CurrSaves = CurrSaves+NumSaves;
         drawnow;
      end;
      %
      % we can now calculate the mean
      %
      SVEs.Meaneta(i,1) = (1/NumDraws)*sum(TempMean);
      SVEs.Stdeta(i,1) = (1/NumDraws)*sum(TempStd);
      SVEs.Correta(i,:) = (1/NumDraws)*sum(TempCorr,1);
      %
      % now we can sort these and create the quantiles from the sorted
      %
      TempMean = sort(TempMean);
      TempStd = sort(TempStd);
      TempCorr = sort(TempCorr);
      for l=1:NumQuants;
         if DSGEModel.Percentiles(l)<50;
            QuantVal = ceil((DSGEModel.Percentiles(l)/100)*NumDraws);
         else;
            QuantVal = floor((DSGEModel.Percentiles(l)/100)*NumDraws);
         end;
         SVEs.Quantiles(l).Meaneta(i,1) = TempMean(QuantVal,1);
         SVEs.Quantiles(l).Stdeta(i,1) = TempStd(QuantVal,1);
         SVEs.Quantiles(l).Correta(i,:) = TempCorr(QuantVal,:);
      end;
      drawnow;
   end;
elseif Selector==8;
   %
   % we have the measurement error correlations
   %
   R = SVEData.R;
   SVEs.ErrorIndicator = (diag(R)>0);
   n = length(SVEs.ErrorIndicator);
   SVEs.Meanw = zeros(n,1);
   SVEs.Stdw = zeros(n,1);
   SVEs.Corrw = zeros(n,n);
   for i=1:NumQuants;
      SVEs.Quantiles(i).Mean = zeros(n,1);
      SVEs.Quantiles(i).Stdw = zeros(n,1);
      SVEs.Quantiles(i).Corrw = zeros(n,n);
      SVEs.Quantiles(i).percent = DSGEModel.Percentiles(i);
   end;
   %
   % setup a wait dialog
   %
   txt = ['Please wait while YADA computes the average measurement error means and correlations under smoothing as well as percentile values. The data are loaded sequentially from disk and it may therefore take some time. Measurement error for variable: ' StringTrim(DSGEModel.VariableNames(1,:)) '.'];
   WaitHandle = WaitDLG(txt,'information','Measurement Error Distribution',500,200,CurrINI,0);
   WaitControls = get(WaitHandle,'UserData');
   %
   for i=1:n;
      %
      % update the wait dialog
      %
      txt = ['Please wait while YADA computes the average measurement error means and correlations under smoothing as well as percentile values. The data are loaded sequentially from disk and it may therefore take some time. Measurement error for variable: ' StringTrim(DSGEModel.VariableNames(i,:)) '.'];
      set(WaitControls.text,'String',txt);
      drawnow;
      %
      % check if the measurement error matters or not
      %
      if R(i,i)>0;
         %
         % set up matrices for storing the data
         %
         TempMean = zeros(NumDraws,1);
         TempStd = zeros(NumDraws,1);
         TempCorr = zeros(NumDraws,n);
         CurrSaves = 0;
         for ThisSave=1:NumFiles;
            file = [DSGEModel.OutputDirectory '\state\DSGE-SVE-' DSGEModel.NameOfModel '-' num2str(CurrChain,'%0.0f') '-' SelParamStr '-' num2str(ThisSave,'%0.0f') '-' num2str(NumFiles,'%0.0f') '.' num2str(NumDraws,'%0.0f') '-' num2str(TotalDraws,'%0.0f') '.mat'];
            SVEData = load(file);
            SVE = SVEData.SVE;
            NumSaves = length(SVE);
            %
            % load data from CurrSaves to NumSaves+1-CurrSaves
            %
            for s=1:NumSaves;
               TempMean(CurrSaves+s,:) = SVE(s).Meanw(i,1);
               TempStd(CurrSaves+s,:) = sqrt(abs(SVE(s).Covw(i,i)));
               TempCorr(CurrSaves+s,:) = SVE(s).Corrw(i,:);
            end;
            CurrSaves = CurrSaves+NumSaves;
            drawnow;
         end;
         %
         % we can now calculate the mean
         %
         SVEs.Meanw(i,1) = (1/NumDraws)*sum(TempMean);
         SVEs.Stdw(i,1) = (1/NumDraws)*sum(TempStd);
         SVEs.Corrw(i,:) = (1/NumDraws)*sum(TempCorr,1);
         %
         % now we can sort these and create the quantiles from the sorted
         %
         TempMean = sort(TempMean);
         TempStd = sort(TempStd);
         TempCorr = sort(TempCorr);
         for l=1:NumQuants;
            if DSGEModel.Percentiles(l)<50;
               QuantVal = ceil((DSGEModel.Percentiles(l)/100)*NumDraws);
            else;
               QuantVal = floor((DSGEModel.Percentiles(l)/100)*NumDraws);
            end;
            SVEs.Quantiles(l).Meanw(i,1) = TempMean(QuantVal,1);
            SVEs.Quantiles(l).Stdw(i,1) = TempStd(QuantVal,1);
            SVEs.Quantiles(l).Corrw(i,:) = TempCorr(QuantVal,:);
         end;
         drawnow;
      end;
   end;
   %
   % remeber to set all outputs such that only those variables with measurement errors are given
   %
   SelectVariables = SVEs.ErrorIndicator .* (1:n)';
   SelectVariables = SelectVariables(SelectVariables>0);
   %
   SVEs.Meanw = SVEs.Meanw(SelectVariables,1);
   SVEs.Stdw = SVEs.Stdw(SelectVariables,1);
   SVEs.Corrw = SVEs.Corrw(SelectVariables,SelectVariables);
   for l=1:NumQuants;
      SVEs.Quantiles(l).Meanw = SVEs.Quantiles(l).Meanw(SelectVariables,1);
      SVEs.Quantiles(l).Stdw = SVEs.Quantiles(l).Stdw(SelectVariables,1);
      SVEs.Quantiles(l).Corrw = SVEs.Quantiles(l).Corrw(SelectVariables,SelectVariables);
   end;
end;
%
% close the wait dialog
%
set(WaitControls.text,'UserData','done');
delete(WaitHandle);
drawnow;
pause(0.02);

%
% end of DSGESVEDistribution.m
%
