function DoneCalc = DSGEStateVariableSimulation(theta,thetaPostSample,thetaPositions,ModelParameters,SelectedParameters,EstType,TotalDraws,CurrChain,NumPaths,DSGEModel,CurrINI)
% DSGEStateVariableSimulation: Estimates state variable correlations and observed variable correlations for a DSGE model
%                              for draws from the posterior distribution of the structural parameters. The function relies
%                              on simulated data and, hence, provides simulation based estimates of the sample moments rather
%                              than of the population equivalents.
%
% USAGE:
%
%       DoneCalc = DSGEStateVariableSimulation(theta,thetaPostSample,thetaPositions,ModelParameters,SelectedParameters,EstType,TotalDraws,CurrChain,NumPaths,DSGEModel,CurrINI)
%
%
% REQUIRED INPUT:  theta (vector) with the posterior mode estimates of the parameters.
%
%                  thetaPostSample (matrix) of dimension NumDrawsxNumParam with draws from the posterior distribution
%                                  of the original DSGE model parameters.
%
%                  thetaPositions (structure) where thetaPositions(i).parameter is a string vector giving the name
%                                  of the model parameter in position i of theta. The field "distribution" has a string
%                                  vector giving the assumed prior distribution of the parameter.
%
%                  ModelParameters (structure) whose fields have names given by the parameter names in the
%                                 DSGE model.
%
%                  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).
%
%                  EstType (string vector) that describes what type of estimation is the main estimation.
%
%                  TotalDraws (integer) with the total number of parameter draws that could have been used.
%
%                  CurrChain (integer) with the number for the current Markov chain.
%
%                  NumPaths (integer) with the number of data paths to simulate per parameter value.
%
%                  DSGEModel (structure) with fields containing all the information about a DSGE Model for YADA.
%
%                  CurrINI (structure), with initialization information.
%
% REQUIRED OUTPUT: DoneCalc (boolean) that is 1 if the calculations were completed and 0 otherwise.
%
%
%                       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: February 28, 2008.
%                        This version: March 9, 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:
%
% * 29-02-2008: The function no longer stores results on economic shocks and measurement errors.
%
% * 01-04-2008: Changed the variable SaveAfterDraws from min(NumDraws,1000) to 1. Changed the AutoCovHorizon
%               value to "min([SampleFreq*3 T-20 18])".
%
% * 16-04-2008: The code now checks if the model has a unique convergent solution also at the posterior mode
%               estimates.
%
% * 23-05-2008: Updated the documentation.
%
% * 29-05-2008: Added a test to check if the model can be solved at the mode.
%
% * 09-07-2008: Added code to handle a time-varying measurement matrix H.
%
% * 22-01-2009: Updated the documentation.
%
% * 13-02-2009: The mcode values 7 and 8 are now properly mentioned when encountered.
%
% * 09-03-2009: Added quotation marks around paths for the dos copy commands.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

%
% initialize
%
DoneCalc = 0;
%
% Prepare variables for selecting the parameters that are updated through the
% posterior draws
%
ScenarioParameters = SelectedParameters .* (1:length(theta));
ScenarioParameters = ScenarioParameters(ScenarioParameters>0);
SelParamStr = strrep(num2str(SelectedParameters),' ','');
thetaMode = theta;
%
% copy files to the tmp folder
%
[stat,msg] = dos(['copy /Y "' GetPath(DSGEModel.AIMDataFile) 'compute_aim_matrices.m" "' pwd '\tmp"']);
[stat,msg] = dos(['copy /Y "' DSGEModel.MeasurementEquationFile '" "' pwd '\tmp"']);
if FileExist(DSGEModel.UpdateParameterFile)==1;
   [stat,msg] = dos(['copy /Y "' DSGEModel.UpdateParameterFile '" "' pwd '\tmp"']);
end;
%
% load the AIMData file
%
ErrorStr = '';
try;
   AIMData = load(DSGEModel.AIMDataFile);
catch;
   ErrorStr = ['Unable to load the file "' DSGEModel.AIMDataFile '". Message caught is: ' lasterr];
end;
if isempty(ErrorStr)==0;
   About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
   return;
end;
%
% create the output directory
%
stat = MakeDir(DSGEModel.OutputDirectory,'state');
if stat~=1;
   txt = ['YADA was for some reason unable to create the directory "' DSGEModel.OutputDirectory '\state". The computation of ' lower(EstType) ' distributions has therefore been aborted.'];
   About(txt,'information','YADA - Directory Creation Problem',180,500,CurrINI);
   return;
end;
%
% set the InitialStateVector value
%
if DSGEModel.UseOwnInitialState==1;
   if length(DSGEModel.InitialStateValues)==size(AIMData.endog,1);
      DSGEModel.InitialStateVector = DSGEModel.InitialStateValues(DSGEModel.StateVariablePositions);
   else;
      DSGEModel.InitialStateVector = zeros(length(DSGEModel.StateVariablePositions),1);
   end;
else;
   DSGEModel.InitialStateVector = zeros(length(DSGEModel.StateVariablePositions),1);
end;
%
% Get the sub-sample
%
[DSGEModel.FirstPeriod,DSGEModel.LastPeriod] = CreateSubSample(DSGEModel);
%
% set up Y and X
%
Y = DSGEModel.Y(:,DSGEModel.FirstPeriod+DSGEModel.KalmanFirstObservation-1:DSGEModel.LastPeriod);
if isempty(DSGEModel.X)==0;
   X = DSGEModel.X(:,DSGEModel.FirstPeriod+DSGEModel.KalmanFirstObservation-1:DSGEModel.LastPeriod);
   XSim = DSGEModel.X(:,DSGEModel.FirstPeriod:DSGEModel.LastPeriod);
else;
   X = [];
   XSim = [];
end;
T = DSGEModel.LastPeriod-DSGEModel.FirstPeriod+1;
Tsum = T-DSGEModel.KalmanFirstObservation+1;
%
% initialize index for saving
%
NumDraws = size(thetaPostSample,1);
SaveAfterDraws = 1;
NumFiles = ceil(NumDraws/SaveAfterDraws);
%
% solve the model for the posterior mode estimate
%
ErrorStr = '';
try;
   [A,H,R,F,B0,mcode] = SolveDSGEModel(DSGEModel,theta,thetaPositions,ModelParameters,AIMData);
catch;
   ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is:' lasterr];
end;
if isempty(ErrorStr)==0;
   About(ErrorStr,'information','YADA - Error Message',200,500,CurrINI);
   return;
end;
if mcode~=1;
   if mcode==2;
      mcodeStr = 'Roots are not correctly computed by real_schur.'
   elseif mcode==3;
      mcodeStr = 'Too many big roots.';
   elseif mcode==35;
      mcodeStr = 'Too many big roots, and q(:,right) is singular.';
   elseif mcode==4;
      mcodeStr = 'Too few big roots.';
   elseif mcode==45;
      mcodeStr = 'Too few big roots, and q(:,right) is singular.';
   elseif mcode==5;
      mcodeStr = 'q(:,right) is singular.';
   elseif mcode==61;
      mcodeStr = 'Too many exact shiftrights.';
   elseif mcode==62;
      mcodeStr = 'Too many numeric shiftrights.';
   elseif mcode==7;
      mcodeStr = 'Infinite or NaN values detected.';
   elseif mcode==8;
      mcodeStr = 'The function "compute_aim_matrices" returns complex numbers.';
   else;
      mcodeStr = 'Return code not properly specified.';
   end;
   txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '"'];
   About(txt,'information','YADA - AiM Solver Error',200,500,CurrINI);
   return;
end;
%
% check if we have a time-varying measurement matrix H
%
if length(size(H))==3;
   %
   % check if H has the required size
   %
   if size(H,3)<DSGEModel.LastPeriod;
      ErrorStr = ['The number of time periods for the time-varying measurement matrix H (' int2str(size(H,3)) ') is lower than the number of observations (T = ' int2str(DSGEModel.LastPeriod) '). YADA has therefore aborted from computing the simulated data.'];
      About(ErrorStr,'error','Error - Measurement Equation',200,500,CurrINI);
      return;
   end;
end;
%
% make sure that only non-zero shocks are kept
%
[B0,KeepShocks] = RemoveRedundantColumns(B0);
n = DSGEModel.n;
k = DSGEModel.k;
[r,q] = size(B0);
%
% set up the autocovariance horizon
%
if strcmp(DSGEModel.DataFrequency,'q')==1;
   SampleFreq = 4;
elseif strcmp(DSGEModel.DataFrequency,'m')==1;
   SampleFreq = 12;
else;
   SampleFreq = 1;
end;
AutoCovHorizon = min([SampleFreq*3 Tsum-20 18]);
%
% set up the date vector
%
DateVector = MakeDateVector(DSGEModel.BeginYear,DSGEModel.BeginPeriod,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.DataFrequency);
DateVector = DateVector(DSGEModel.FirstPeriod+DSGEModel.KalmanFirstObservation-1:DSGEModel.LastPeriod);
%
% initialize the random number generator
%
if DSGEModel.RandomNumberValue==1;
   randn('state',0);
   rand('state',0);
else;
   randn('state',sum(100*clock));
   rand('state',sum(100*clock));
end;
%
% begin the loop
%
abort = '';
LastDraw = 0;
MeanEstimationTime = 0;
ThisSave = 0;
SVE = [];
CorrType = strcmp(lower(EstType),'autocorrelation');
%
% check if we should setup a wait handle
%
if DSGEModel.ShowProgress==1;
   ProgressStructure.title = ['Progress for ' num2str(NumDraws*NumPaths,'%0.0f') ' simulation paths'];
   ProgressStructure.facecolor = CurrINI.progress_facecolor;
   ProgressStructure.startfacecolor = CurrINI.progress_startfacecolor;
   ProgressStructure.edgecolor = CurrINI.progress_edgecolor;
   ProgressStructure.bgcolor = CurrINI.progress_bgcolor;
   ProgressStructure.stop = 0;
   ProgressStructure.clock = DSGEModel.ShowProgressClock;
   ProgressStructure.label = 'Mean estimation time:';
   %
   ProgressStructure.name = [EstType ' Distribution'];
   ProgressStructure.CurrINI = CurrINI;
   WaitHandle = ProgressDLG(0,ProgressStructure);
   set(WaitHandle,'Color',get(0,'defaultuicontrolbackgroundcolor'));
   drawnow;
else;
   txt = ['Please wait while YADA computes the sample based ' lower(EstType) ' distribution. Computations started at: ' StringTrim(datestr(now,14))];
   WaitHandle = WaitDLG(txt,'information',[EstType ' Distribution'],500,150,CurrINI,0);
   WaitControls = get(WaitHandle,'UserData');
end;
%
% start the simulation
%
StopSimulation = 0;
if length(size(H))==2;
   for it=1:NumDraws;
      LastDraw = LastDraw+1;
      %
      % Solve the model for the current parameter vector
      %
      theta(ScenarioParameters) = thetaPostSample(it,ScenarioParameters)';
      tic;
      [A,H,R,F,B0,status] = SolveDSGEModel(DSGEModel,theta,thetaPositions,ModelParameters,AIMData);
      if status~=1;
         %
         % use posterior mode estimate as a backup
         %
         [A,H,R,F,B0,status] = SolveDSGEModel(DSGEModel,thetaMode,thetaPositions,ModelParameters,AIMData);
      end;
      B0 = B0(:,KeepShocks);
      %
      % initial values for the mean and covariance matrix of the distribution of the state variables
      %
      if isempty(DSGEModel.UnitRootStates)==1;
         [P0,stat] = DoublingAlgorithmLyapunov(F,B0*B0',DSGEModel.DAMaximumIterationsValue*100,10^(-(DSGEModel.DAToleranceValue+1)));
      else;
         StationaryPos = GetPosition(DSGEModel.StateVariablePositions,DSGEModel.UnitRootStates);
         P0 = DSGEModel.StateCovConstValue*eye(r,r);
         F1 = F(StationaryPos,StationaryPos);
         Q1 = B0(StationaryPos,:)*B0(StationaryPos,:)';
         [Pstat,stat] = DoublingAlgorithmLyapunov(F1,Q1,DSGEModel.DAMaximumIterationsValue*100,10^(-(DSGEModel.DAToleranceValue+1)));
         P0(StationaryPos,StationaryPos) = Pstat;
      end;
      Ksi0 = DSGEModel.InitialStateVector;
      [S,L] = SchurDecomposition(P0);
      %
      % deal with measurement errors
      %
      if rank(R)>0;
         [Rm,Lm] = SchurDecomposition(R);
         Rmeasure = Rm*sqrt(Lm);
         NumMeasure = size(Lm,1);
      else;
         Rmeasure = [];
         wSim = 0;
         NumMeasure = 0;
      end;
      %
      % start the simulation of data
      %
      for p=1:NumPaths;
         %
         % fix the progress dialog is necessary
         %
         NumIter = p+(NumPaths*(it-1));
         if DSGEModel.ShowProgress==1;
            abort = get(WaitHandle,'UserData');
            if strcmp(abort,'cancel')==1;
               StopSimulation = 1;
               break;
            else;
               ProgressDLG([NumIter/(NumDraws*NumPaths) MeanEstimationTime]);
            end;
         end;
         %
         % draw the economic shocks
         %
         etaSim = randn(q,T);
         %
         % draw the measurement errors
         %
         if isempty(Rmeasure)==0;
            wSim = Rmeasure*randn(NumMeasure,T);
         end;
         %
         % draw an initial state
         %
         StateSim = zeros(r,T+1);
         StateSim(:,1) = Ksi0+(S*sqrt(L)*randn(size(L,2),1));
         %
         % generate the state matrix
         %
         for t=1:T;
            StateSim(:,t+1) = (F*StateSim(:,t))+(B0*etaSim(:,t));
         end;
         drawnow;
         %
         % remove the initial value of the state vector
         %
         StateSim = StateSim(:,2:T+1);
         %
         if CorrType==1;
            %
            % create the observed variables
            %
            if k>0;
               YSim = (A'*XSim)+(H'*StateSim)+wSim;
            else;
               YSim = (H'*StateSim)+wSim;
            end;
            %
            % compute the sample moments based on the simulated data
            %
            YTmp = YSim(:,DSGEModel.KalmanFirstObservation:T);
            if k>0;
               XTmp = XSim(:,DSGEModel.KalmanFirstObservation:T);
               MeanY = (YTmp*XTmp')/(XTmp*XTmp');
               YTmp = YTmp-(MeanY*XTmp);
            else;
               MeanY = (1/Tsum)*sum(YTmp,2);
               YTmp = YTmp-MeanY;
            end;
            SVE.CorrData(LastDraw,p).MeanY = MeanY;
            SVE.CorrData(LastDraw,p).StdY = sqrt(diag((1/Tsum)*YTmp*YTmp'));
            %
            % and now for the autocovariances
            %
            SVE.CorrData(LastDraw,p).CorrY = zeros((n*(n+1))/2,1+(2*AutoCovHorizon));
            SVE.CorrData(LastDraw,p).CorrY(:,AutoCovHorizon+1) = vech(((1/Tsum)*YTmp*YTmp')./(SVE.CorrData(LastDraw,p).StdY*SVE.CorrData(LastDraw,p).StdY'));
            for i=1:AutoCovHorizon;
               Yt = YTmp(:,1+i:Tsum);
               YtL = YTmp(:,1:Tsum-i);
               if k>0;
                  Xt = XTmp(:,1+i:Tsum);
                  Yt = Yt-(((Yt*Xt')/(Xt*Xt'))*Xt);
                  XtL = XTmp(:,1:Tsum-i);
                  YtL = YtL-(((Yt*Xt')/(Xt*Xt'))*XtL);
               else;
                  Yt = Yt-MeanY;
                  YtL = YtL-MeanY;
               end;
               Corr = ((1/Tsum)*Yt*YtL')./(SVE.CorrData(LastDraw,p).StdY*SVE.CorrData(LastDraw,p).StdY');
               SVE.CorrData(LastDraw,p).CorrY(:,AutoCovHorizon+1+i) = vech(Corr');
               SVE.CorrData(LastDraw,p).CorrY(:,AutoCovHorizon+1-i) = vech(Corr);         
            end;
         else;
            %
            % compute the sample mean, standard deviation, and correlations for the state variables
            %
            StateTmp = StateSim(:,DSGEModel.KalmanFirstObservation:T);
            SVE.CorrState(LastDraw,p).MeanKsi = (1/Tsum)*sum(StateTmp,2);
            StateTmp = StateTmp-(SVE.CorrState(LastDraw,p).MeanKsi*ones(1,Tsum));
            SVE.CorrState(LastDraw,p).StdKsi = sqrt(diag((1/Tsum)*StateTmp*StateTmp'));
            SVE.CorrState(LastDraw,p).CorrKsi = ((1/Tsum)*StateTmp*StateTmp')./(SVE.CorrState(LastDraw,p).StdKsi*SVE.CorrState(LastDraw,p).StdKsi');
         end;
         %
         MeanEstimationTime = (((NumIter-1)/NumIter)*MeanEstimationTime)+((1/NumIter)*toc);
         drawnow;
      end;
      if StopSimulation==1;
         break;
      end;
      %
      % check if we should save to disk
      %
      if (LastDraw==SaveAfterDraws)|(it==NumDraws);
         ThisSave = ThisSave+1;
         LastDraw = 0;
         %
         % set up the file name and then save
         %
         if CorrType==1;
            file = [DSGEModel.OutputDirectory '\state\DSGE-OVE-' DSGEModel.NameOfModel '-' num2str(CurrChain,'%0.0f') '-' SelParamStr '-' num2str(ThisSave,'%0.0f') '-' num2str(NumFiles,'%0.0f') '.' num2str(NumDraws,'%0.0f') '-' num2str(TotalDraws,'%0.0f') '-' num2str(NumPaths,'%0.0f') '.mat'];
         else;
            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') '-' num2str(NumPaths,'%0.0f') '.mat'];
         end;
         save(file,'SVE','Y','X','DateVector');
         %
         % restore the data structure
         %
         SVE = [];
      end;
      drawnow;
   end;
else;
   for it=1:NumDraws;
      LastDraw = LastDraw+1;
      %
      % Solve the model for the current parameter vector
      %
      theta(ScenarioParameters) = thetaPostSample(it,ScenarioParameters)';
      tic;
      [A,H,R,F,B0,status] = SolveDSGEModel(DSGEModel,theta,thetaPositions,ModelParameters,AIMData);
      if status~=1;
         %
         % use posterior mode estimate as a backup
         %
         [A,H,R,F,B0,status] = SolveDSGEModel(DSGEModel,thetaMode,thetaPositions,ModelParameters,AIMData);
      end;
      B0 = B0(:,KeepShocks);
      %
      % initial values for the mean and covariance matrix of the distribution of the state variables
      %
      if isempty(DSGEModel.UnitRootStates)==1;
         [P0,stat] = DoublingAlgorithmLyapunov(F,B0*B0',DSGEModel.DAMaximumIterationsValue*100,10^(-(DSGEModel.DAToleranceValue+1)));
      else;
         StationaryPos = GetPosition(DSGEModel.StateVariablePositions,DSGEModel.UnitRootStates);
         P0 = DSGEModel.StateCovConstValue*eye(r,r);
         F1 = F(StationaryPos,StationaryPos);
         Q1 = B0(StationaryPos,:)*B0(StationaryPos,:)';
         [Pstat,stat] = DoublingAlgorithmLyapunov(F1,Q1,DSGEModel.DAMaximumIterationsValue*100,10^(-(DSGEModel.DAToleranceValue+1)));
         P0(StationaryPos,StationaryPos) = Pstat;
      end;
      Ksi0 = DSGEModel.InitialStateVector;
      [S,L] = SchurDecomposition(P0);
      %
      % deal with measurement errors
      %
      if rank(R)>0;
         [Rm,Lm] = SchurDecomposition(R);
         Rmeasure = Rm*sqrt(Lm);
         NumMeasure = size(Lm,1);
      else;
         Rmeasure = [];
         wSim = 0;
         NumMeasure = 0;
      end;
      %
      % start the simulation of data
      %
      for p=1:NumPaths;
         %
         % fix the progress dialog is necessary
         %
         NumIter = p+(NumPaths*(it-1));
         if DSGEModel.ShowProgress==1;
            abort = get(WaitHandle,'UserData');
            if strcmp(abort,'cancel')==1;
               StopSimulation = 1;
               break;
            else;
               ProgressDLG([NumIter/(NumDraws*NumPaths) MeanEstimationTime]);
            end;
         end;
         %
         % draw the economic shocks
         %
         etaSim = randn(q,T);
         %
         % draw the measurement errors
         %
         if isempty(Rmeasure)==0;
            wSim = Rmeasure*randn(NumMeasure,T);
         else;
            wSim = zeros(n,T);
         end;
         %
         % draw an initial state
         %
         StateSim = zeros(r,T+1);
         StateSim(:,1) = Ksi0+(S*sqrt(L)*randn(size(L,2),1));
         %
         % generate the state matrix
         %
         for t=1:T;
            StateSim(:,t+1) = (F*StateSim(:,t))+(B0*etaSim(:,t));
         end;
         drawnow;
         %
         % remove the initial value of the state vector
         %
         StateSim = StateSim(:,2:T+1);
         %
         if CorrType==1;
            %
            % create the observed variables
            %
            if k>0;
               for t=DSGEModel.FirstPeriod:DSGEModel.LastPeriod;
                  YSim(:,t-DSGEModel.FirstPeriod+1) = (A'*XSim(:,t-DSGEModel.FirstPeriod+1))+(H(:,:,t)'*StateSim(:,t-DSGEModel.FirstPeriod+1))+wSim(:,t-DSGEModel.FirstPeriod+1);
               end;
            else;
               for t=DSGEModel.FirstPeriod:DSGEModel.LastPeriod;
                  YSim(:,t-DSGEModel.FirstPeriod+1) = (H(:,:,t)'*StateSim(:,t-DSGEModel.FirstPeriod+1))+wSim(:,t-DSGEModel.FirstPeriod+1);
               end;
            end;
            %
            % compute the sample moments based on the simulated data
            %
            YTmp = YSim(:,DSGEModel.KalmanFirstObservation:T);
            if k>0;
               XTmp = XSim(:,DSGEModel.KalmanFirstObservation:T);
               MeanY = (YTmp*XTmp')/(XTmp*XTmp');
               YTmp = YTmp-(MeanY*XTmp);
            else;
               MeanY = (1/Tsum)*sum(YTmp,2);
               YTmp = YTmp-MeanY;
            end;
            SVE.CorrData(LastDraw,p).MeanY = MeanY;
            SVE.CorrData(LastDraw,p).StdY = sqrt(diag((1/Tsum)*YTmp*YTmp'));
            %
            % and now for the autocovariances
            %
            SVE.CorrData(LastDraw,p).CorrY = zeros((n*(n+1))/2,1+(2*AutoCovHorizon));
            SVE.CorrData(LastDraw,p).CorrY(:,AutoCovHorizon+1) = vech(((1/Tsum)*YTmp*YTmp')./(SVE.CorrData(LastDraw,p).StdY*SVE.CorrData(LastDraw,p).StdY'));
            for i=1:AutoCovHorizon;
               Yt = YTmp(:,1+i:Tsum);
               YtL = YTmp(:,1:Tsum-i);
               if k>0;
                  Xt = XTmp(:,1+i:Tsum);
                  Yt = Yt-(((Yt*Xt')/(Xt*Xt'))*Xt);
                  XtL = XTmp(:,1:Tsum-i);
                  YtL = YtL-(((Yt*Xt')/(Xt*Xt'))*XtL);
               else;
                  Yt = Yt-MeanY;
                  YtL = YtL-MeanY;
               end;
               Corr = ((1/Tsum)*Yt*YtL')./(SVE.CorrData(LastDraw,p).StdY*SVE.CorrData(LastDraw,p).StdY');
               SVE.CorrData(LastDraw,p).CorrY(:,AutoCovHorizon+1+i) = vech(Corr');
               SVE.CorrData(LastDraw,p).CorrY(:,AutoCovHorizon+1-i) = vech(Corr);         
            end;
         else;
            %
            % compute the sample mean, standard deviation, and correlations for the state variables
            %
            StateTmp = StateSim(:,DSGEModel.KalmanFirstObservation:T);
            SVE.CorrState(LastDraw,p).MeanKsi = (1/Tsum)*sum(StateTmp,2);
            StateTmp = StateTmp-(SVE.CorrState(LastDraw,p).MeanKsi*ones(1,Tsum));
            SVE.CorrState(LastDraw,p).StdKsi = sqrt(diag((1/Tsum)*StateTmp*StateTmp'));
            SVE.CorrState(LastDraw,p).CorrKsi = ((1/Tsum)*StateTmp*StateTmp')./(SVE.CorrState(LastDraw,p).StdKsi*SVE.CorrState(LastDraw,p).StdKsi');
         end;
         %
         MeanEstimationTime = (((NumIter-1)/NumIter)*MeanEstimationTime)+((1/NumIter)*toc);
         drawnow;
      end;
      if StopSimulation==1;
         break;
      end;
      %
      % check if we should save to disk
      %
      if (LastDraw==SaveAfterDraws)|(it==NumDraws);
         ThisSave = ThisSave+1;
         LastDraw = 0;
         %
         % set up the file name and then save
         %
         if CorrType==1;
            file = [DSGEModel.OutputDirectory '\state\DSGE-OVE-' DSGEModel.NameOfModel '-' num2str(CurrChain,'%0.0f') '-' SelParamStr '-' num2str(ThisSave,'%0.0f') '-' num2str(NumFiles,'%0.0f') '.' num2str(NumDraws,'%0.0f') '-' num2str(TotalDraws,'%0.0f') '-' num2str(NumPaths,'%0.0f') '.mat'];
         else;
            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') '-' num2str(NumPaths,'%0.0f') '.mat'];
         end;
         save(file,'SVE','Y','X','DateVector');
         %
         % restore the data structure
         %
         SVE = [];
      end;
      drawnow;
   end;
end;
%
% close the wait dialog
%
if DSGEModel.ShowProgress==1;
   if ishandle(WaitHandle)==1;
      set(WaitHandle,'UserData','done');
      close(WaitHandle);
      drawnow;
      pause(0.02);
   end;
else;
   set(WaitControls.text,'UserData','done');
   delete(WaitHandle);
   drawnow;
   pause(0.02);
end;
%
% check if we have computed all output
%
if strcmp(abort,'cancel')==0;
   DoneCalc = 1;
end;

%
% end of DSGEStateVariableSimulation.m
%
