function YADAHandle = YADAGUI(selector)
% YADAGUI: Creates the Graphical User Interface for YADA.
%
% USAGE:
%
%       YADAHandle = YADAGUI(selector)
%
% where selector is a string and YADAHandle a handle to the figure.
%
% REQUIRED INPUT:  selector (string vector) for a case switch function.
%
% OPTIONAL OUTPUT: YADAHandle (integer) with the handle to the GUI.
%
%
%                       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: July 21, 2006.
%                        This version: March 12, 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-7-2006 -
%   05-01-2009: Added major GUI functionality.
%
% * 12-01-2009: Added conditional correlations for posterior mode
%               and initial values.
%
% * 13-01-2009: Started working on conditional correlations for
%               the posterior draws.
%
% * 15-01-2009: Additional data can now be stored when running the conditional
%               and unconditional predictions for fixed parameter values.
%
% * 29-01-2009: Added the control controls.optimize.initcsminwel for choosing
%               the initial value for the inverse Hessian when running the
%               csminwel optimization routine.
%
% * 30-01-2009: Made sure that error messages from running the "SolveDSGEModel" function are
%               always caught.
%
% * 12-02-2009: Added the function to estimate the parameter covariance matrix from draws
%               from the posterior distribution. The option to use a user specified parameter
%               covariance matrix for the proposal density in the random-walk Metropolis
%               algorithm was also added.
%
% * 14-02-2009: Moved the function "Parameter Covariance Matrix" from the Actions menu
%               to the View menu.
%
% * 19-02-2009: Added code on the conditional correlations function for the posterior
%               draws. Fixed a bug where deselecting certain state shocks could make the
%               used length of shocks and variables for conditional forecasts and/or observed
%               variable scenarios different.
%
% * 24-02-2009: Added code for computing impulse responses based on shocks groups.
%
% * 25-02-2009: Added code for preparing graphs of the posterior densities for the
%               parameters that are function of the estimated parameters.
%
% * 26-02-2009: Took into account that the function "GetUpdatePosteriorDraws" takes
%               an additional variable as input. View conditioning data code was also
%               added.
%
% * 27-02-2009: Added code for estimating the prior densities of the parameters
%               that are a function of the estimated parameters.
%
% * 02-03-2009: Added code for displaying the prior densities of the parameters
%               that are a function of the estimated parameters. The functions for
%               saving the state-space matrices to disk were also added.
%
% * 03-03-2009: Added code for saving and viewing marginal predictive densties based
%               on kernel density estimation for each prediction period.
%
% * 09-03-2009: Added quotation marks around paths for the dos del and copy commands.
%
% * 12-03-2009: Updated the documentation.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

%
% Initialize the GUI
%
if strcmp(selector,'init')==1;
   %
   % create the initialization structure
   %
   CurrINI = InitializeINIFile;
   %
   % Read CDATA information for creating images on toolbar button and pushbuttons
   %
   ButtonImages = ReadImages;
   %
   % add some things to this structure that are never stored on disk
   %
   CurrINI.scrsz = get(0,'ScreenSize');
   CurrINI.images = ButtonImages;
   %
   % The GUI is painted in the upper right corner of the screen!
   %
   StatusStr = 'Welcome to YADA!';
   %
   % Setting up a structure with model information
   %
   DSGEModel = InitializeDSGEModel;
   [DSGEModel.SubBeginYearValue,DSGEModel.SubBeginPeriodValue,DSGEModel.SubEndYearValue,DSGEModel.SubEndPeriodValue,DSGEModel.YearStrMatrix,DSGEModel.PeriodStrMatrix] = CreateEstimationSampleValues(DSGEModel);
   CurrINI.CurrentModelFile = '';
   CurrINI.ModelFiles = '';
   %
   % Now we should try to read any model-file that was recorded in the INI-file
   %
   CurrINI = ReadINIFile(CurrINI);
   %
   % if CurrINI.CurrentModelFile exists we load all information from this file given
   % that it can be verified
   %
   if FileExist(CurrINI.CurrentModelFile)==1;
      NewDSGEModel = ReadDSGEModel(CurrINI.CurrentModelFile);
      [NewDSGEModel.SubBeginYearValue,NewDSGEModel.SubBeginPeriodValue,NewDSGEModel.SubEndYearValue,NewDSGEModel.SubEndPeriodValue,NewDSGEModel.YearStrMatrix,NewDSGEModel.PeriodStrMatrix] = CreateEstimationSampleValues(NewDSGEModel);
      [ModelStatus,NewDSGEModel] = VerifyDSGEModel(NewDSGEModel,CurrINI.CurrentModelFile,DSGEModel.DataConstructionFile,CurrINI);
      if ModelStatus==1;
         [NewDSGEModel.SubBeginYearValue,NewDSGEModel.SubBeginPeriodValue,NewDSGEModel.SubEndYearValue,NewDSGEModel.SubEndPeriodValue,NewDSGEModel.YearStrMatrix,NewDSGEModel.PeriodStrMatrix] = CreateEstimationSampleValues(NewDSGEModel);
         DSGEModel = NewDSGEModel;
         if (exist('YADAbetarnd')~=2)|(exist('betarnd')~=2);
            if DSGEModel.InitializeHessian==8;
               DSGEModel.InitializeHessian = 5;
            end;
         end;
      else;
         %
         % make sure that CurrINI.CurrentModelFile is removed from CurrINI.ModelFiles
         %
         CurrINI.ModelFiles = RemoveFromModelFiles(CurrINI.ModelFiles,CurrINI.CurrentModelFile);
         CurrINI.CurrentModelFile = '';
      end;
   end;
   %
   if FileExist(DSGEModel.AIMDataFile)==1;
      StateEnable = 'on';
   else;
      StateEnable = 'off';
   end;
   %
   %
   YADAName = 'YADA';
   if strcmp(DSGEModel.NameOfModel,'')==0;
      YADAName = ['YADA - ' DSGEModel.NameOfModel ' - [' GetFilename(CurrINI.CurrentModelFile) ']'];
   end;
   if FileExist(DSGEModel.AIMFile)==1;
      AiMEnable = 'on';
   else;
      AiMEnable = 'off';
   end;
   if DSGEModel.T>0;
      DataEnable = 'on';
   else;
      DataEnable = 'off';
   end;
   [FirstPeriod,LastPeriod,EstSample] = CreateSubSample(DSGEModel);
   if (DSGEModel.InitializeKalman>1)&(DSGEModel.KalmanFirstObservation==1);
      DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
   end;
   if FileExist([pwd '\addons\wz\DSGECondPredictionPathsWZ.m'])==0;
      DSGEModel.ShockControlMethod = 1;
   end;
   if FileExist([pwd '\addons\wz\CondPredictionKalmanSmoother.m'])==0;
      DSGEModel.KsiUseCondData = 0;
   end;
   OrigDSGEModel = DSGEModel;
else;
   maingui = findobj('Type','figure','Tag','YADA');
   controls = get(maingui,'UserData');
   CurrINI = get(controls.filemenu,'UserData');
   DSGEModel = get(controls.open,'UserData');
   OrigDSGEModel = get(controls.openmenu,'UserData');
end;

switch selector
   case 'init'
      %
      % create main dialog
      %
      maingui = figure('Color',get(0,'defaultuicontrolbackgroundcolor'), ...
         'FileName','YADAGUI.m', ...
         'MenuBar','none', ...
         'PaperUnits','points', ...
         'Units','pixels', ...
         'Position',[max(CurrINI.scrsz(3)-702,3) 32 700 660], ...
         'Tag','YADA', ...
         'Resize','off', ...
         'Visible','off', ...
         'Name',YADAName, ...
         'NumberTitle','off', ...
         'CloseRequestFcn','YADAGUI quit', ...
         'DeleteFcn','YADAGUI done', ...
         'Toolbar','none');
      %
      % make sure the GUI dialog cannot be docked under matlab 7 and later
      %
      if MatlabNumber>=7.0;
         set(maingui,'DockControl','off');
         controls = [];
      else;
         controls.Xline = XLine([1 659 700],[0.5 1],CurrINI,maingui);
      end;
      %
      % Now we create a new Toolbar for the GUI
      %
      flds = cellstr(strvcat('toolbar','open','save','reload','close','runaim','postmode','postsampling','viewgraphics','statevar','stateshock','shockgroup','helpfile','license','about','leave'));
      buttons.type = cellstr(strvcat('push','push','push','push','push','push','push','push','push','push','push','push','push','push','push'));
      buttons.tooltipstr = cellstr(strvcat('Open Model','Save Model','Reload Model','Close Model','Run AiM Parser','Estimate Posterior Mode','Posterior Sampling','Open Graphics','Set State Variables','Set State Shocks','Set Shock Groups','Help','License','About','Quit'));
      buttons.callbackstr = cellstr(strvcat('YADAGUI open','YADAGUI savemodel','YADAGUI reloadmodel','YADAGUI closemodel','YADAGUI runaim','YADAGUI postmode','YADAGUI metropolis_hastings','YADAGUI viewgraphics','YADAGUI setstatevars','YADAGUI setstateshocks','YADAGUI setshockgroups','YADAGUI helpfile','YADAGUI license','YADAGUI about','YADAGUI quit'));
      buttons.enablestr = cellstr(strvcat('on','on','on','on',AiMEnable,'off','off','on',StateEnable,StateEnable,'off','on','on','on','on'));
      buttons.separatorstr = cellstr(strvcat('off','off','on','on','on','off','off','on','on','off','off','on','on','off','on'));
      buttons.statestr = cellstr(strvcat(' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '));
      buttons.tagstr = cellstr(strvcat('OpenButton','SaveButton','ReloadButton','CloseButton','RunAIMButton','EstimatePostModeButton','PosteriorSamplingButton','ViewGraphicsButton','StateVariableButton','StateShockButton','ShockGroupButton','HelpFileButton','LicenseButton','AboutButton','QuitButton'));
      %
      btndata(1).cdata = ButtonImages.open;
      btndata(1).userdata = DSGEModel;
      btndata(2).cdata = ButtonImages.save;
      btndata(2).userdata = [];
      btndata(3).cdata = ButtonImages.reload;
      btndata(3).userdata = [];
      btndata(4).cdata = ButtonImages.clear;
      btndata(4).userdata = [];
      btndata(5).cdata = ButtonImages.runaim;
      btndata(5).userdata = [];
      btndata(6).cdata = ButtonImages.postmode;
      btndata(6).userdata = [];
      btndata(7).cdata = ButtonImages.simulate;
      btndata(7).userdata = [];
      btndata(8).cdata = ButtonImages.viewgraphics;
      btndata(8).userdata = [];
      btndata(9).cdata = ButtonImages.statevar;
      btndata(9).userdata = [];
      btndata(10).cdata = ButtonImages.stateshock;
      btndata(10).userdata = [];
      btndata(11).cdata = ButtonImages.shockgroups;
      btndata(11).userdata = [];
      btndata(12).cdata = ButtonImages.help;
      btndata(12).userdata = [];
      btndata(13).cdata = ButtonImages.YADAlicense;
      btndata(13).userdata = 0;
      btndata(14).cdata = ButtonImages.about;
      btndata(14).userdata = 0;
      btndata(15).cdata = ButtonImages.close;
      btndata(15).userdata = 'waiting';
      %
      % Now we create the toolbar
      %
      controls = MakeToolbar(controls,maingui,flds,btndata,buttons);
      %
      % Create menus
      %
      %
      % 1. File menu
      %
      controls.filemenu = uimenu('Parent',maingui, ...
         'Label','&File', ...
         'UserData',CurrINI, ...
         'Tag','FileMenu');
      %
      % Objects on the File menu
      %
      controls.openmenu = uimenu('Parent',controls.filemenu, ...
         'Label','&Open Model...', ...
         'Callback','YADAGUI open', ...
         'Enable','on', ...
         'UserData',OrigDSGEModel, ...
         'Accelerator','O', ...
         'Tag','OpenMenu');
      %
      controls.savemenu = uimenu('Parent',controls.filemenu, ...
         'Label','&Save Model...', ...
         'Callback','YADAGUI savemodel', ...
         'Enable','on', ...
         'Accelerator','S', ...
         'Tag','SaveMenu');
      %
      controls.reloadmenu = uimenu('Parent',controls.filemenu, ...
         'Label','&Reload Model', ...
         'Callback','YADAGUI reloadmodel', ...
         'Enable','on', ...
         'Accelerator','R', ...
         'Tag','ReloadMenu');
      %
      controls.reopenmenu = uimenu('Parent',controls.filemenu, ...
         'Label','Reopen &Model', ...
         'Separator','on', ...
         'Enable','on', ...
         'Tag','ReopenMenu');
      %
      % Create a sub-menu for this task
      %
      if isempty(CurrINI.ModelFiles)==0;
         controls = MakeModelFilesMenu(controls,CurrINI.ModelFiles,CurrINI.CurrentModelFile,'YADAGUI','openmodel');
      end;
      %
      controls.closemenu = uimenu('Parent',controls.filemenu, ...
         'Label','&Close Model', ...
         'Callback','YADAGUI closemodel', ...
         'Separator','on', ...
         'Enable','on', ...
         'Tag','CloseMenu');
      %
      controls.quitmenu = uimenu('Parent',controls.filemenu, ...
         'Label','&Quit', ...
         'Callback','YADAGUI quit', ...
         'Separator','on', ...
         'Enable','on', ...
         'Accelerator','Q', ...
         'Tag','QuitMenu');
      %
      % 2. Edit menu
      %
      if MatlabNumber<7;
         controls.editmenu = uimenu('Parent',maingui, ...
            'Label','&Edit', ...
            'Tag','EditMenu');
         %
         % Objects on the Edit menu
         %
         controls.editundomenu = uimenu('Parent',controls.editmenu, ...
            'Label','&Undo', ...
            'Callback','YADAGUI editundo', ...
            'Accelerator','Z', ...
            'Enable','on', ...
            'Tag','EditUndoMenu');
         %
         controls.editcutmenu = uimenu('Parent',controls.editmenu, ...
            'Label','Cu&t', ...
            'Callback','YADAGUI editcut', ...
            'Accelerator','X', ...
            'Separator','on', ...
            'Enable','on', ...
            'Tag','EditCutMenu');
         %
         controls.editcopymenu = uimenu('Parent',controls.editmenu, ...
            'Label','&Copy', ...
            'Callback','YADAGUI editcopy', ...
            'Accelerator','C', ...
            'Enable','on', ...
            'Tag','EditCopyMenu');
         %
         controls.editpastemenu = uimenu('Parent',controls.editmenu, ...
            'Label','&Paste', ...
            'Callback','YADAGUI editpaste', ...
            'Accelerator','V', ...
            'Enable','on', ...
            'Tag','EditPasteMenu');
         %
         controls.editselectallmenu = uimenu('Parent',controls.editmenu, ...
            'Label','Select &All', ...
            'Callback','YADAGUI editselectall', ...
            'Accelerator','A', ...
            'Separator','on', ...
            'Enable','on', ...
            'Tag','EditSelectAllMenu');
      end;
      %
      % 3. View menu
      %
      controls.viewmenu = uimenu('Parent',maingui, ...
         'Label','&View', ...
         'Tag','ViewMenu');
      %
      controls.viewgraphicsmenu = uimenu('Parent',controls.viewmenu, ...
         'Label','Open &Graphics...', ...
         'Callback','YADAGUI viewgraphics', ...
         'Enable','on', ...
         'Tag','ViewGraphicsMenu');
      %
      % Objects on the View menu
      %
      controls.datainfo = uimenu('Parent',controls.viewmenu, ...
         'Label','&Data Construction Information...', ...
         'Callback','YADAGUI datainfo', ...
         'Separator','on', ...
         'Enable',DataEnable, ...
         'Tag','DataInfoMenu');
      %
      % View AiM Model file with notepad
      %
      controls.aimmodelinfo = uimenu('Parent',controls.viewmenu, ...
         'Label','&AiM Model File...', ...
         'Callback','YADAGUI aimmodelinfo', ...
         'Enable',AiMEnable, ...
         'Tag','AiMModelInfoMenu');
      %
      % View prior information
      %
      controls.priorinfo = uimenu('Parent',controls.viewmenu, ...
         'Label','Prior Distrib&ution Information...', ...
         'Callback','YADAGUI priorinfo', ...
         'Enable','off', ...
         'Tag','PriorInfoMenu');
      %
      % view state-space form
      %
      controls.statespaceparent = uimenu('Parent',controls.viewmenu, ...
         'Label','State-Space &Form', ...
         'Separator','on', ...
         'Tag','StateSpaceParentMenu');
      %
      controls.statespacesaveparent = uimenu('Parent',controls.statespaceparent, ...
         'Label','&Save State-Space Matrices', ...
         'Enable','on', ...
         'Tag','StateSpaceSaveParentMenu');
      %
      % at initial values
      %
      controls.statespacesaveinitialvalues = uimenu('Parent',controls.statespacesaveparent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI statespacesave_init_values', ...
         'Enable','off', ...
         'Tag','StateSpaceSaveInitialValuesMenu');
      %
      % at posterior mode
      %
      controls.statespacesavemode = uimenu('Parent',controls.statespacesaveparent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI statespacesave_postmode', ...
         'Enable','off', ...
         'Tag','StateSpaceSaveModeMenu');
      %
      % at initial values
      %
      controls.statespaceinitialvalues = uimenu('Parent',controls.statespaceparent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI statespace_init_values', ...
         'Enable','off', ...
         'Tag','StateSpaceInitialValuesMenu');
      %
      % at posterior mode
      %
      controls.statespacemode = uimenu('Parent',controls.statespaceparent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI statespace_postmode', ...
         'Enable','off', ...
         'Tag','StateSpaceModeMenu');
      %
      % estimate the parameter covariance matrix
      %
      controls.estimateparamcovmat = uimenu('Parent',controls.viewmenu, ...
         'Label','Parameter Covariance Matri&x...', ...
         'Callback','YADAGUI estimateparamcovmat', ...
         'Separator','on', ...
         'Enable','off', ...
         'Tag','EstimateParameterCovarianceMatrixMenu');
      %
      % posterior mode results
      %
      controls.modeinfo = uimenu('Parent',controls.viewmenu, ...
         'Label','&Posterior Mode Results...', ...
         'Callback','YADAGUI modeinfo', ...
         'Separator','on', ...
         'Enable','off', ...
         'Tag','ModeInfoMenu');
      %
      % posterior mode results summary
      %
      controls.modesummary = uimenu('Parent',controls.viewmenu, ...
         'Label','Posterior &Mode Summary...', ...
         'Callback','YADAGUI modesummaryinfo', ...
         'Enable','off', ...
         'Tag','ModeSummaryInfoMenu');
      %
      % optimization error summary
      %
      controls.opterrorsummary = uimenu('Parent',controls.viewmenu, ...
         'Label','Optimi&zation Error Summary...', ...
         'Callback','YADAGUI opterrorsummaryinfo', ...
         'Enable','off', ...
         'Tag','OptErrorSummaryInfoMenu');
      %
      % posterior sampling summary
      %
      controls.postsamplesummary.parent = uimenu('Parent',controls.viewmenu, ...
         'Label','Posterior &Sampling Summary', ...
         'Separator','on', ...
         'Enable','on', ...
         'Tag','PostSampleSummaryMenu');
      %
      %
      for i=1:10;
         ModHandle = uimenu('Parent',controls.postsamplesummary.parent, ...
            'Label',['Chain &' num2str(i,'%0.0f') '...'], ...
            'Callback','YADAGUI postsamplesummary', ...
            'Enable','off', ...
            'UserData','', ...
            'Tag',['PostSampleSummaryChain' num2str(i,'%0.0f') 'Menu']);
         if i==10;
            set(ModHandle,'Label','Chain 1&0...');
         end;
         controls.postsamplesummary = setfield(controls.postsamplesummary,['chain' num2str(i,'%0.0f')],ModHandle);
      end;
      %
      % posterior plots - raw draws
      %
      controls.postsample.rawplots = uimenu('Parent',controls.viewmenu, ...
         'Label','Ra&w Posterior Draws', ...
         'Enable','on', ...
         'Tag','PostSampleRawPlotsMenu');
      %
      controls.postsample.rawplots_original = uimenu('Parent',controls.postsample.rawplots, ...
         'Label','&Original Parameters...', ...
         'Callback','YADAGUI rawplots', ...
         'Enable','off', ...
         'Tag','PostSampleOriginalRawPlotsMenu');
      %
      controls.postsample.rawplots_transformed = uimenu('Parent',controls.postsample.rawplots, ...
         'Label','&Transformed Parameters...', ...
         'Callback','YADAGUI rawplots', ...
         'Enable','off', ...
         'Tag','PostSampleTransformedRawPlotsMenu');
      %
      % scatter plot posterior draws
      %
      controls.postsample.scatterplots = uimenu('Parent',controls.viewmenu, ...
         'Label','Scatt&er-plot Posterior Draws', ...
         'Enable','on', ...
         'Tag','PostSampleScatterPlotsMenu');
      %
      controls.postsample.scatterplots_original = uimenu('Parent',controls.postsample.scatterplots, ...
         'Label','&Original Parameters...', ...
         'Callback','YADAGUI scatterplots', ...
         'Enable','off', ...
         'Tag','PostSampleOriginalScatterPlotsMenu');
      %
      controls.postsample.scatterplots_transformed = uimenu('Parent',controls.postsample.scatterplots, ...
         'Label','&Transformed Parameters...', ...
         'Callback','YADAGUI scatterplots', ...
         'Enable','off', ...
         'Tag','PostSampleTransformedScatterPlotsMenu');
      %
      % marginal likelihood estimation
      %
      controls.postsample.marglike = uimenu('Parent',controls.viewmenu, ...
         'Label','Se&quential Marginal Likelihood', ...
         'Enable','on', ...
         'Tag','MargLikeMenu');
      %
      % Chib and Jeliazkov
      %
      controls.postsample.chibjeliazkov = uimenu('Parent',controls.postsample.marglike, ...
         'Label','&Chib and Jeliazkov...', ...
         'Callback','YADAGUI postsample_cj', ...
         'Enable','off', ...
         'Tag','PostSampleCJMenu');
      %
      % Geweke's modified harmonic mean
      %
      controls.postsample.mhm = uimenu('Parent',controls.postsample.marglike, ...
         'Label','&Modified Harmonic Mean...', ...
         'Callback','YADAGUI postsample_mhm', ...
         'Enable','off', ...
         'Tag','PostSampleMHMMenu');
      %
      % convergence
      %
      controls.postsample.convergence = uimenu('Parent',controls.viewmenu, ...
         'Label','Con&vergence', ...
         'Enable','on', ...
         'Tag','ConvergenceMenu');
      %
      controls.postsample.cusumplots.parent = uimenu('Parent',controls.postsample.convergence, ...
         'Label','&CUSUM Plots', ...
         'Enable','on', ...
         'Tag','CusumPlotsMenu');
      %
      controls.postsample.cusumplots.logposterior = uimenu('Parent',controls.postsample.cusumplots.parent, ...
         'Label','&Log Posterior...', ...
         'Callback','YADAGUI cusum_logpost', ...
         'Enable','off', ...
         'Tag','CusumPlotsLogPosteriorMenu');
      %
      controls.postsample.cusumplots.original = uimenu('Parent',controls.postsample.cusumplots.parent, ...
         'Label','&Original Parameters...', ...
         'Callback','YADAGUI cusum_parameters', ...
         'Enable','off', ...
         'Tag','CusumPlotsOriginalParametersMenu');
      %
      controls.postsample.cusumplots.transformed = uimenu('Parent',controls.postsample.cusumplots.parent, ...
         'Label','&Transformed Parameters...', ...
         'Callback','YADAGUI cusum_parameters', ...
         'Enable','off', ...
         'Tag','CusumPlotsTransformedParametersMenu');
      %
      controls.postsample.spmt.parent = uimenu('Parent',controls.postsample.convergence, ...
         'Label','&Separated Partial Means Test', ...
         'Enable','on', ...
         'Tag','SeparatedPartialMeansTestMenu');
      %
      controls.postsample.spmt.logposterior = uimenu('Parent',controls.postsample.spmt.parent, ...
         'Label','&Log Posterior...', ...
         'Callback','YADAGUI spmt_logpost', ...
         'Enable','off', ...
         'Tag','SPMTLogPosteriorMenu');
      %
      controls.postsample.spmt.original = uimenu('Parent',controls.postsample.spmt.parent, ...
         'Label','&Original Parameters...', ...
         'Callback','YADAGUI spmt_parameters', ...
         'Enable','off', ...
         'Tag','CusumPlotsOriginalParametersMenu');
      %
      controls.postsample.spmt.transformed = uimenu('Parent',controls.postsample.spmt.parent, ...
         'Label','&Transformed Parameters...', ...
         'Callback','YADAGUI spmt_parameters', ...
         'Enable','off', ...
         'Tag','CusumPlotsTransformedParametersMenu');
      %
      controls.postsample.acceptancerate = uimenu('Parent',controls.postsample.convergence, ...
         'Label','Acceptance &Ratio...', ...
         'Callback','YADAGUI converge_acceptance', ...
         'Separator','on', ...
         'Enable','off', ...
         'Tag','AcceptanceRatioConvergeMenu');
      %
      controls.postsample.manova = uimenu('Parent',controls.postsample.convergence, ...
         'Label','Multivariate &ANOVA...', ...
         'Callback','YADAGUI converge_manova', ...
         'Enable','off', ...
         'Tag','MANOVAConvergeMenu');
      %
      controls.postsample.mean = uimenu('Parent',controls.postsample.convergence, ...
         'Label','&Posterior Mean...', ...
         'Callback','YADAGUI converge_mean', ...
         'Enable','off', ...
         'Tag','PostSampleConvergeMeanMenu');
      %
      controls.postsample.median = uimenu('Parent',controls.postsample.convergence, ...
         'Label','Posterior &Median...', ...
         'Callback','YADAGUI converge_median', ...
         'Enable','off', ...
         'Tag','PostSampleConvergeMedianMenu');
      %
      % modesty statistics
      %
      controls.modesty.parent = uimenu('Parent',controls.viewmenu, ...
         'Label','Modest&y Statistics', ...
         'Separator','on', ...
         'Enable','on', ...
         'Tag','ModestyMenu');
      %
      % initial values
      %
      controls.modesty.initialvalues = uimenu('Parent',controls.modesty.parent, ...
            'Label','&Initial Values...', ...
            'Callback','YADAGUI viewmodestystat', ...
            'Enable','off', ...
            'UserData','', ...
            'Tag','ModestyInitialValuesMenu');
      %
      % posterior mode
      %
      controls.modesty.postmode = uimenu('Parent',controls.modesty.parent, ...
            'Label','&Posterior Mode...', ...
            'Callback','YADAGUI viewmodestystat', ...
            'Enable','off', ...
            'UserData','', ...
            'Tag','ModestyPosteriorModeMenu');
      %
      for i=1:10;
         ModHandle = uimenu('Parent',controls.modesty.parent, ...
            'Label',['Chain &' num2str(i,'%0.0f') '...'], ...
            'Callback','YADAGUI viewmodestystat', ...
            'Enable','off', ...
            'UserData','', ...
            'Tag',['ModestyChain' num2str(i,'%0.0f') 'Menu']);
         if i==1;
            set(ModHandle,'Separator','on');
         end;
         if i==10;
            set(ModHandle,'Label','Chain 1&0...');
         end;
         controls.modesty = setfield(controls.modesty,['chain' num2str(i,'%0.0f')],ModHandle);
      end;
      %
      % view iterative parameter estimates
      %
      controls.iteratedparameters = uimenu('Parent',controls.viewmenu, ...
         'Label','&Iterated Parameter Estimates...', ...
         'Callback','YADAGUI iteratedparameters', ...
         'Separator','on', ...
         'Enable','off', ...
         'Tag','IteratedParametersMenu');
      %
      % check optimum
      %
      controls.checkpostmode = uimenu('Parent',controls.viewmenu, ...
         'Label','C&heck Posterior Mode...', ...
         'Callback','YADAGUI checkpostmode', ...
         'Enable','off', ...
         'Tag','CheckPosteriorModeMenu');
      %
      % 3D plots of posterior mode
      %
      controls.threedeepostmode.parent = uimenu('Parent',controls.viewmenu, ...
         'Label','Posterior Mode Surfa&ce', ...
         'Enable','on', ...
         'Tag','PosteriorModeSurfaceMenu');
      %
      % original parameters
      %
      controls.threedeepostmode.original = uimenu('Parent',controls.threedeepostmode.parent, ...
         'Label','&Original Parameters...', ...
         'Callback','YADAGUI threedeepostmode', ...
         'Enable','off', ...
         'Tag','OriginalPosteriorModeSurfaceMenu');
      %
      % transformed parameteres
      %
      controls.threedeepostmode.transformed = uimenu('Parent',controls.threedeepostmode.parent, ...
         'Label','&Transformed Parameters...', ...
         'Callback','YADAGUI threedeepostmode', ...
         'Enable','off', ...
         'Tag','TransformedPosteriorModeSurfaceMenu');
      %
      % Graph the prior
      %
      controls.viewprior = uimenu('Parent',controls.viewmenu, ...
         'Label','P&rior Densities...', ...
         'Callback','YADAGUI viewprior', ...
         'Separator','on', ...
         'Enable','off', ...
         'Tag','ViewPriorMenu');
      %
      % Graph the posterior
      %
      controls.viewposterior = uimenu('Parent',controls.viewmenu, ...
         'Label','Pos&terior Densities...', ...
         'Callback','YADAGUI viewposterior', ...
         'Enable','off', ...
         'Tag','ViewPosteriorMenu');
      %
      % show prior value and value of log jacobian
      %
      controls.viewpriorvalue.parent = uimenu('Parent',controls.viewmenu, ...
         'Label','Prior and Log &Jacobian Value', ...
         'Enable','on', ...
         'Tag','ViewPriorValueMenu');
      % 
      controls.viewpriorvalue.initialvalues = uimenu('Parent',controls.viewpriorvalue.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI viewpriorvalue_init_values', ...
         'Enable','off', ...
         'Tag','ViewPriorValueInitialValuesMenu');
      %
      controls.viewpriorvalue.postmode = uimenu('Parent',controls.viewpriorvalue.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI viewpriorvalue_postmode', ...
         'Enable','off', ...
         'Tag','ViewPriorValuePosteriorModeMenu');
      %
      % Graph data
      %
      controls.viewdata = uimenu('Parent',controls.viewmenu, ...
         'Label','&Observed Variables...', ...
         'Callback','YADAGUI viewdata', ...
         'Separator','on', ...
         'Enable','off', ...
         'Tag','ViewDataMenu');
      %
      % Graph annualized data
      %
      controls.viewannualdata = uimenu('Parent',controls.viewmenu, ...
         'Label','A&nnualized Observed Variables...', ...
         'Callback','YADAGUI viewannualdata', ...
         'Enable','off', ...
         'Tag','ViewAnnualizedDataMenu');
      %
      % graph transformed data
      %
      controls.viewtransdata = uimenu('Parent',controls.viewmenu, ...
         'Label','Transformed Observed Variab&les...', ...
         'Callback','YADAGUI viewtransdata', ...
         'Enable','off', ...
         'Tag','ViewTransDataMenu');
      %
      % save annualized data to disk
      %
      controls.saveannualdata = uimenu('Parent',controls.viewmenu, ...
         'Label','Save Annualized O&bserved Variables...', ...
         'Callback','YADAGUI saveannualdata', ...
         'Enable','off', ...
         'Tag','SaveAnnualizedDataMenu');
      %
      % 4. Tools menu
      %
      controls.toolsmenu = uimenu('Parent',maingui, ...
         'Label','&Tools', ...
         'Tag','ToolsMenu');
      %
      % Displaye eigenvalues of the DSGE model
      %
      controls.dsgeeigenvalues.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','DS&GE Model Eigenvalues', ...
         'Enable','on', ...
         'Tag','ViewDSGEEigenvaluesMenu');
      %
      controls.dsgeeigenvalues.initialvalues = uimenu('Parent',controls.dsgeeigenvalues.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI dsgeeigenvalues_init_values', ...
         'Enable','off', ...
         'Tag','DSGEEigenvaluesInitialValuesMenu');
      %
      controls.dsgeeigenvalues.postmode = uimenu('Parent',controls.dsgeeigenvalues.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI dsgeeigenvalues_postmode', ...
         'Enable','off', ...
         'Tag','DSGEEigenvaluesPosteriorModeMenu');
      %
      % Check invertibility condition of the DSGE model relative to an infinite order VAR
      %
      controls.dsgetovareigenvalues.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','Poor Man''s Invertibilit&y Condition', ...
         'Enable','on', ...
         'Tag','ViewDSGEtoVAREigenvaluesMenu');
      %
      controls.dsgetovareigenvalues.initialvalues = uimenu('Parent',controls.dsgetovareigenvalues.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI dsgevareigenvalues_init_values', ...
         'Enable','off', ...
         'Tag','DSGEtoVAREigenvaluesInitialValuesMenu');
      %
      controls.dsgetovareigenvalues.postmode = uimenu('Parent',controls.dsgetovareigenvalues.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI dsgevareigenvalues_postmode', ...
         'Enable','off', ...
         'Tag','DSGEtoVAREigenvaluesPosteriorModeMenu');
      %
      % check the information matrix
      %
      controls.informationmatrix.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','Information Matri&x', ...
         'Enable','on', ...
         'Tag','InformationMatrixMenu');
      %
      controls.informationmatrix.initialvalues = uimenu('Parent',controls.informationmatrix.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI informationmatrix_init_values', ...
         'Enable','off', ...
         'Tag','InformationMatrixInitialValuesMenu');
      %
      controls.informationmatrix.postmode  = uimenu('Parent',controls.informationmatrix.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI informationmatrix_postmode', ...
         'Enable','off', ...
         'Tag','InformationMatrixPosteriorModeMenu');
      %
      % Simulate data
      %
      controls.simulatedata.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','Sim&ulate Data', ...
         'Separator','on', ...
         'Enable','on', ...
         'Tag','SimulateDataMenu');
      %
      controls.simulatedata.initialvalues = uimenu('Parent',controls.simulatedata.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI simulatedata_init_values', ...
         'Enable','off', ...
         'Tag','SimulateDataInitialValuesMenu');
      %
      controls.simulatedata.postmode = uimenu('Parent',controls.simulatedata.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI simulatedata_postmode', ...
         'Enable','off', ...
         'Tag','SimulateDataPosteriorModeMenu');
      %
      % Display observed variables correlations
      %
      controls.obsvarcorrs.parent = uimenu('Parent',controls.toolsmenu, ...
         'Separator','on', ...
         'Label','&Observed Variable Correlations', ...
         'Tag','ObsVariableCorrelationsMenu');
      %
      controls.obsvarcorrs.initialvalues = uimenu('Parent',controls.obsvarcorrs.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI obsvar_init_values', ...
         'Enable','off', ...
         'Tag','ObsVariableCorrelationsInitialValuesMenu');
      %
      controls.obsvarcorrs.postmode = uimenu('Parent',controls.obsvarcorrs.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI obsvar_postmode', ...
         'Enable','off', ...
         'Tag','ObsVariableCorrelationsPosteriorModeMenu');
      %
      controls.obsvarcorrs.posterior = uimenu('Parent',controls.obsvarcorrs.parent, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI obsvar_dist', ...
         'Enable','off', ...
         'Tag','ObsVariableCorrelationsDistMenu');
      %
      % Display conditional correlations
      %
      if FileExist([pwd '\addons\ovs\OVSControls.m'])==1;
         controls.condcorrs.parent = uimenu('Parent',controls.toolsmenu, ...
            'Label','Conditional &Quarrelations', ...
            'Tag','ConditionalCorrelationsMenu');
      else;
         controls.condcorrs.parent = uimenu('Parent',controls.toolsmenu, ...
            'Label','Conditional Corr&elations', ...
            'Tag','ConditionalCorrelationsMenu');
      end;
      %
      controls.condcorrs.initialvalues = uimenu('Parent',controls.condcorrs.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI condcorr_init_values', ...
         'Enable','off', ...
         'Tag','ConditionalCorrelationsInitialValuesMenu');
      %
      controls.condcorrs.postmode = uimenu('Parent',controls.condcorrs.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI condcorr_postmode', ...
         'Enable','off', ...
         'Tag','ConditionalCorrelationsPosteriorModeMenu');
      %
      controls.condcorrs.posterior = uimenu('Parent',controls.condcorrs.parent, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI condcorr_dist', ...
         'Enable','off', ...
         'Tag','ConditionalCorrelationsDistMenu');
      %
      % Display state variable  correlations
      %
      controls.statevarcorrs.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','State Variable &Correlations', ...
         'Tag','StateVariableCorrelationsMenu');
      %
      controls.statevarcorrs.initialvalues = uimenu('Parent',controls.statevarcorrs.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI statevar_init_values', ...
         'Enable','off', ...
         'Tag','StateVariableCorrelationsInitialValuesMenu');
      %
      controls.statevarcorrs.postmode = uimenu('Parent',controls.statevarcorrs.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI statevar_postmode', ...
         'Enable','off', ...
         'Tag','StateVariableCorrelationsPosteriorModeMenu');
      %
      controls.statevarcorrs.posterior = uimenu('Parent',controls.statevarcorrs.parent, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI statevar_dist', ...
         'Enable','off', ...
         'Tag','StateVariableCorrelationsDistMenu');
      %
      % Displays state shock correlations
      %
      controls.stateshockcorrs.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','S&tate Shock Correlations', ...
         'Tag','StateShockCorrelationsMenu');
      %
      controls.stateshockcorrs.initialvalues = uimenu('Parent',controls.stateshockcorrs.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI sscorr_init_values', ...
         'Enable','off', ...
         'Tag','StateShockCorrelationsInitialValuesMenu');
      %
      controls.stateshockcorrs.postmode = uimenu('Parent',controls.stateshockcorrs.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI sscorr_post_mode', ...
         'Enable','off', ...
         'Tag','StateShockCorrelationsPosteriorModeMenu');
      %
      controls.stateshockcorrs.posterior = uimenu('Parent',controls.stateshockcorrs.parent, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI sscorr_dist', ...
         'Enable','off', ...
         'Tag','StateShockCorrelationsDistMenu');
      %
      % Displays measurement error correlations
      %
      controls.measurementerrorcorrs.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','Me&asurement Error Correlations', ...
         'Tag','MeasurementErrorCorrelationsMenu');
      %
      controls.measurementerrorcorrs.initialvalues = uimenu('Parent',controls.measurementerrorcorrs.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI mecorr_init_values', ...
         'Enable','off', ...
         'Tag','MeasurementErrorCorrelationsInitialValuesMenu');
      %
      controls.measurementerrorcorrs.postmode = uimenu('Parent',controls.measurementerrorcorrs.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI mecorr_post_mode', ...
         'Enable','off', ...
         'Tag','MeasurementErrorCorrelationsPosteriorModeMenu');
      %
      controls.measurementerrorcorrs.posterior = uimenu('Parent',controls.measurementerrorcorrs.parent, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI mecorr_dist', ...
         'Enable','off', ...
         'Tag','MeasurementErrorCorrelationsDistMenu');
      %
      % Graph forecasts of observed variables
      %
      controls.obsvar.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','&1-Step Ahead Forecasts', ...
         'Separator','on', ...
         'Tag','ObsVariablesForecast1Menu');
      %
      % Initial values
      %
      controls.obsvar.initialvalues = uimenu('Parent',controls.obsvar.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI ob_init_values', ...
         'Enable','off', ...
         'Tag','ObsVariablesForecast1InitialValuesMenu');
      %
      % Posterior mode
      %
      controls.obsvar.postmode = uimenu('Parent',controls.obsvar.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI ob_post_mode', ...
         'Enable','off', ...
         'Tag','ObsVariablesForecast1PosteriorModeMenu');
      %
      controls.obsvar.posterior = uimenu('Parent',controls.obsvar.parent, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI ob_dist', ...
         'Enable','off', ...
         'Tag','ObsVariablesForecast1DistMenu');
      %
      % Graph state variables
      %
      controls.statevariables.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','&State Variables', ...
         'Tag','StateVariablesMenu');
      %
      controls.statevariables.initialvalues = uimenu('Parent',controls.statevariables.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI sv_init_values', ...
         'Enable','off', ...
         'Tag','StateVariablesInitialValuesMenu');
      %
      controls.statevariables.postmode = uimenu('Parent',controls.statevariables.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI sv_post_mode', ...
         'Enable','off', ...
         'Tag','StateVariablesPosteriorModeMenu');
      %
      controls.statevariables.posterior = uimenu('Parent',controls.statevariables.parent, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI sv_dist', ...
         'Enable','off', ...
         'Tag','StateVariablesDistMenu');
      %
      % Graph state shocks
      %
      controls.stateshocks.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','State Shoc&ks', ...
         'Tag','StateShocksParentMenu');
      %
      controls.stateshocks.initialvalues = uimenu('Parent',controls.stateshocks.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI ss_init_values', ...
         'Enable','off', ...
         'Tag','StateShocksInitialValuesMenu');
      %
      controls.stateshocks.postmode = uimenu('Parent',controls.stateshocks.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI ss_post_mode', ...
         'Enable','off', ...
         'Tag','StateShocksPosteriorModeMenu');
      %
      controls.stateshocks.posterior = uimenu('Parent',controls.stateshocks.parent, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI ss_dist', ...
         'Enable','off', ...
         'Tag','StateShocksDistMenu');
      %
      % Graph measurement errors
      %
      controls.measurementerror.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','&Measurement Errors', ...
         'Tag','MeasurementErrorParentMenu');
      %
      controls.measurementerror.initialvalues = uimenu('Parent',controls.measurementerror.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI me_init_values', ...
         'Enable','off', ...
         'Tag','MeasurementErrorInitialValuesMenu');
      %
      controls.measurementerror.postmode = uimenu('Parent',controls.measurementerror.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI me_post_mode', ...
         'Enable','off', ...
         'Tag','MeasurementErrorPosteriorModeMenu');
      %
      controls.measurementerror.posterior = uimenu('Parent',controls.measurementerror.parent, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI me_dist', ...
         'Enable','off', ...
         'Tag','MeasurementErrorDistMenu');
      %
      % Graph the log-likelihood function
      %
      controls.loglikelihood.parent = uimenu('Parent',controls.toolsmenu, ...
         'Separator','on', ...
         'Label','&Log-likelihood Function', ...
         'Tag','LogLikelihoodMenu');
      %
      controls.loglikelihood.initialvalues = uimenu('Parent',controls.loglikelihood.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI loglike_init_values', ...
         'Enable','off', ...
         'Tag','LogLikelihoodInitialValuesMenu');
      %
      controls.loglikelihood.postmode = uimenu('Parent',controls.loglikelihood.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI loglike_post_mode', ...
         'Enable','off', ...
         'Tag','LogLikelihoodPosteriorModeMenu');
      %
      % Shock scenarios
      %
      if FileExist([pwd '\addons\sss\ShockScenarioControls.m'])==1;
         controls = ShockScenarioControls(controls);
         SepStr = 'off';
      else;
         SepStr = 'on';
      end;
      %
      % Observed variable scenarios
      %
      if FileExist([pwd '\addons\ovs\OVSControls.m'])==1;
         controls = OVSControls(controls,'toolsmenu');
      end;
      %
      % Parameter scenarios
      %
      controls.ps.parent = uimenu('Parent',controls.toolsmenu, ...
         'Separator',SepStr, ...
         'Label','Parameter Sce&narios', ...
         'Tag','ParameterScenariosParentMenu');
      %
      % original data
      %
      controls.ps.original = uimenu('Parent',controls.ps.parent, ...
         'Label','&Original Data', ...
         'Tag','ParameterScenariosOriginalMenu');
      %
      % Initial values 
      %
      controls.ps.initialvalues = uimenu('Parent',controls.ps.original, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI parameterscenarios_init_values', ...
         'Enable','off', ...
         'Tag','ParameterScenarioInitialValuesMenu');
      %
      % posterior mode estimates
      %
      controls.ps.postmode = uimenu('Parent',controls.ps.original, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI parameterscenarios_postmode', ...
         'Enable','off', ...
         'Tag','ParameterScenarioPosteriorModeMenu');
      %
      % annualized data
      %
      controls.ps.annual = uimenu('Parent',controls.ps.parent, ...
         'Label','&Annualized Data', ...
         'Tag','ParameterScenariosAnnualMenu');
      %
      % initial values
      %
      controls.ps.anninitialvalues = uimenu('Parent',controls.ps.annual, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI parameterscenarios_init_values', ...
         'Enable','off', ...
         'Tag','AnnualParameterScenarioPosteriorModeMenu');
      %
      % posterior mode estimates
      %
      controls.ps.annpostmode = uimenu('Parent',controls.ps.annual, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI parameterscenarios_postmode', ...
         'Enable','off', ...
         'Tag','AnnualParameterScenarioPosteriorModeMenu');
      %
      % Predictive distributions
      %
      controls.predict.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','&Predictive Distributions', ...
         'Tag','PredictiveDistParentMenu');
      %
      % unconditional
      %
      controls.predict.unconditional = uimenu('Parent',controls.predict.parent, ...
         'Label','&Unconditional', ...
         'Tag','UnconditionalPredictiveDistMenu');
      %
      % conditional
      %
      controls.predict.conditional = uimenu('Parent',controls.predict.parent, ...
         'Label','&Conditional', ...
         'Tag','ConditionalPredictiveDistMenu');
      %
      % original data
      %
      controls.predict.unconditional_original = uimenu('Parent',controls.predict.unconditional, ...
         'Label','&Original Data', ...
         'Tag','UnconditionalOriginalPredictiveDistMenu');
      %
      controls.predict.conditional_original = uimenu('Parent',controls.predict.conditional, ...
         'Label','&Original Data', ...
         'Tag','ConditionalOriginalPredictiveDistMenu');
      %
      % annualized data
      %
      controls.predict.unconditional_annual = uimenu('Parent',controls.predict.unconditional, ...
         'Label','&Annualized Data', ...
         'Tag','UnconditionalAnnualizedPredictiveDistMenu');
      %
      controls.predict.conditional_annual = uimenu('Parent',controls.predict.conditional, ...
         'Label','&Annualized Data', ...
         'Tag','ConditionalAnnualizedPredictiveDistMenu');
      %
      % transformed data
      %
      controls.predict.unconditional_transformed = uimenu('Parent',controls.predict.unconditional, ...
         'Label','&Transformed Data', ...
         'Tag','UnConditionalTransformedPredictiveDistMenu');
      %
      controls.predict.conditional_transformed = uimenu('Parent',controls.predict.conditional, ...
         'Label','&Transformed Data', ...
         'Tag','ConditionalTransformedPredictiveDistMenu');
      %
      % initial values
      %
      controls.predict.unconditional_original_initialvalues = uimenu('Parent',controls.predict.unconditional_original, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI uncon_pred_init_values', ...
         'Enable','off', ...
         'Tag','UnconditionalPredictiveDistOriginalInitialValuesMenu');
      %
      controls.predict.conditional_original_initialvalues = uimenu('Parent',controls.predict.conditional_original, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI con_pred_init_values', ...
         'Enable','off', ...
         'Tag','ConditionalPredictiveDistOriginalInitialValuesMenu');
      %
      % posterior mode
      %
      controls.predict.unconditional_original_postmode = uimenu('Parent',controls.predict.unconditional_original, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI uncon_pred_post_mode', ...
         'Enable','off', ...
         'Tag','UnconditionalPredictiveDistOriginalPostModeMenu');
      %
      controls.predict.conditional_original_postmode = uimenu('Parent',controls.predict.conditional_original, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI con_pred_post_mode', ...
         'Enable','off', ...
         'Tag','ConditionalPredictiveDistOriginalPostModeMenu');
      %
      % posterior distribution
      %
      controls.predict.unconditional_original_posterior = uimenu('Parent',controls.predict.unconditional_original, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI uncon_pred_posterior', ...
         'Enable','off', ...
         'Tag','UnconditionalPredictiveDistOriginalPosteriorMenu');
      %
      controls.predict.conditional_original_posterior = uimenu('Parent',controls.predict.conditional_original, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI con_pred_posterior', ...
         'Enable','off', ...
         'Tag','ConditionalPredictiveDistOriginalPosteriorMenu');
      %
      % predictive events
      %
      controls.predict.unconditional_original_predevent = uimenu('Parent',controls.predict.unconditional_original, ...
         'Label','Prediction &Event...', ...
         'Callback','YADAGUI uncon_pred_event', ...
         'Separator','on', ...
         'Enable','off', ...
         'Tag','UnconditionalPredictiveEventOriginalPosteriorMenu');
      %
      controls.predict.conditional_original_predevent = uimenu('Parent',controls.predict.conditional_original, ...
         'Label','Prediction &Event...', ...
         'Callback','YADAGUI con_pred_event', ...
         'Separator','on', ...
         'Enable','off', ...
         'Tag','ConditionalPredictiveEventOriginalPosteriorMenu');
      %
      % annualized data
      %
      controls.predict.unconditional_annual_initialvalues = uimenu('Parent',controls.predict.unconditional_annual, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI uncon_pred_init_values', ...
         'Enable','off', ...
         'Tag','UnconditionalPredictiveDistAnnualizedInitialValuesMenu');
      %
      controls.predict.conditional_annual_initialvalues = uimenu('Parent',controls.predict.conditional_annual, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI con_pred_init_values', ...
         'Enable','off', ...
         'Tag','ConditionalPredictiveDistAnnualizedInitialValuesMenu');
      %
      controls.predict.unconditional_annual_postmode = uimenu('Parent',controls.predict.unconditional_annual, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI uncon_pred_post_mode', ...
         'Enable','off', ...
         'Tag','UnconditionalPredictiveDistAnnualizedPostModeMenu');
      %
      controls.predict.conditional_annual_postmode = uimenu('Parent',controls.predict.conditional_annual, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI con_pred_post_mode', ...
         'Enable','off', ...
         'Tag','ConditionalPredictiveDistAnnualizedPostModeMenu');
      %
      controls.predict.unconditional_annual_posterior = uimenu('Parent',controls.predict.unconditional_annual, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI uncon_pred_posterior', ...
         'Enable','off', ...
         'Tag','UnconditionalPredictiveDistAnnualizedPosteriorMenu');
      %
      controls.predict.conditional_annual_posterior = uimenu('Parent',controls.predict.conditional_annual, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI con_pred_posterior', ...
         'Enable','off', ...
         'Tag','ConditionalPredictiveDistAnnualizedPosteriorMenu');
      %
      controls.predict.unconditional_annual_predevent = uimenu('Parent',controls.predict.unconditional_annual, ...
         'Label','Prediction &Event...', ...
         'Callback','YADAGUI uncon_pred_event', ...
         'Separator','on', ...
         'Enable','off', ...
         'Tag','UnconditionalPredictiveEventAnnualizedPosteriorMenu');
      %
      controls.predict.conditional_annual_predevent = uimenu('Parent',controls.predict.conditional_annual, ...
         'Label','Prediction &Event...', ...
         'Callback','YADAGUI con_pred_event', ...
         'Separator','on', ...
         'Enable','off', ...
         'Tag','ConditionalPredictiveEventAnnualizedPosteriorMenu');
      %
      % transformed data
      %
      % initial values
      %
      controls.predict.unconditional_transformed_initialvalues = uimenu('Parent',controls.predict.unconditional_transformed, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI uncon_pred_init_values', ...
         'Enable','off', ...
         'Tag','UnconditionalPredictiveDistTransformedInitialValuesMenu');
      %
      controls.predict.conditional_transformed_initialvalues = uimenu('Parent',controls.predict.conditional_transformed, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI con_pred_init_values', ...
         'Enable','off', ...
         'Tag','ConditionalPredictiveDistTransformedInitialValuesMenu');
      %
      % posterior mode values
      %
      controls.predict.unconditional_transformed_postmode = uimenu('Parent',controls.predict.unconditional_transformed, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI uncon_pred_post_mode', ...
         'Enable','off', ...
         'Tag','UnconditionalPredictiveDistTransformedPostModeMenu');
      %
      controls.predict.conditional_transformed_postmode = uimenu('Parent',controls.predict.conditional_transformed, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI con_pred_post_mode', ...
         'Enable','off', ...
         'Tag','ConditionalPredictiveDistTransformedPostModeMenu');
      %
      % posterior distribution
      %
      controls.predict.unconditional_transformed_posterior = uimenu('Parent',controls.predict.unconditional_transformed, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI uncon_pred_posterior', ...
         'Enable','off', ...
         'Tag','UnconditionalPredictiveDistTransformedPosteriorMenu');
      %
      controls.predict.conditional_transformed_posterior = uimenu('Parent',controls.predict.conditional_transformed, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI con_pred_posterior', ...
         'Enable','off', ...
         'Tag','ConditionalPredictiveDistTransformedPosteriorMenu');
      %
      % predictive events
      %
      controls.predict.unconditional_transformed_predevent = uimenu('Parent',controls.predict.unconditional_transformed, ...
         'Label','Prediction &Event...', ...
         'Callback','YADAGUI uncon_pred_event', ...
         'Separator','on', ...
         'Enable','off', ...
         'Tag','UnconditionalPredictiveEventTransformedPosteriorMenu');
      %
      controls.predict.conditional_transformed_predevent = uimenu('Parent',controls.predict.conditional_transformed, ...
         'Label','Prediction &Event...', ...
         'Callback','YADAGUI con_pred_event', ...
         'Separator','on', ...
         'Enable','off', ...
         'Tag','ConditionalPredictiveEventTransformedPosteriorMenu');
      %
      % Historical decompositions
      %
      controls.hd.parent = uimenu('Parent',controls.toolsmenu, ...
         'Separator','on', ...
         'Label','&Forecast Error Decompositions', ...
         'Tag','HDMenu');
      %
      % initial values
      %
      controls.hd.initialvalues = uimenu('Parent',controls.hd.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI hd_init_values', ...
         'Enable','off', ...
         'Tag','HDInitialValuesMenu');
      %
      % posterior mode
      %
      controls.hd.postmode = uimenu('Parent',controls.hd.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI hd_post_mode', ...
         'Enable','off', ...
         'Tag','HDPosteriorModeMenu');
      %
      % posterior distribution
      %
      controls.hd.posterior = uimenu('Parent',controls.hd.parent, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI hd_posterior', ...
         'Enable','off', ...
         'Tag','HDPosteriorDistMenu');
      %
      % Observed variable decompositions
      %
      controls.ovd.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','O&bserved Variable Decompositions', ...
         'Tag','OVDMenu');
      %
      % original values
      %
      controls.ovd.original = uimenu('Parent',controls.ovd.parent, ...
         'Label','&Original Data', ...
         'Tag','OVDOriginalMenu');
      %
      % annualized values
      %
      controls.ovd.annual = uimenu('Parent',controls.ovd.parent, ...
         'Label','&Annualized Data', ...
         'Tag','OVDAnnualMenu');
      %
      % initial values
      %
      controls.ovd.initialvalues = uimenu('Parent',controls.ovd.original, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI ovd_init_values', ...
         'Enable','off', ...
         'Tag','OVDInitialValuesMenu');
      %
      controls.ovd.anninitialvalues = uimenu('Parent',controls.ovd.annual, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI ovd_init_values', ...
         'Enable','off', ...
         'Tag','OVDAnnualInitialValuesMenu');
      %
      % posterior mode
      %
      controls.ovd.postmode = uimenu('Parent',controls.ovd.original, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI ovd_post_mode', ...
         'Enable','off', ...
         'Tag','OVDPosteriorModeMenu');
      %
      controls.ovd.annpostmode = uimenu('Parent',controls.ovd.annual, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI ovd_post_mode', ...
         'Enable','off', ...
         'Tag','OVDAnnualPosteriorModeMenu');
      %
      % State variable decompositions
      %
      controls.svd.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','State Va&riable Decompositions', ...
         'Tag','SVDMenu');
      %
      % Initial values
      %
      controls.svd.initialvalues = uimenu('Parent',controls.svd.parent, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI svd_init_values', ...
         'Enable','off', ...
         'Tag','SVDInitialValuesMenu');
      %
      % posterior mode
      %
      controls.svd.postmode = uimenu('Parent',controls.svd.parent, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI svd_post_mode', ...
         'Enable','off', ...
         'Tag','SVDPosteriorModeMenu');
      %
      % impulse responses
      %
      controls.irfunctions.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','&Impulse Responses', ...
         'Tag','IRMenu');
      %
      controls.irfunctions.original = uimenu('Parent',controls.irfunctions.parent, ...
         'Label','&Original Data', ...
         'Tag','IROriginalMenu');
      %
      controls.irfunctions.annual = uimenu('Parent',controls.irfunctions.parent, ...
         'Label','&Annualized Data', ...
         'Tag','IRAnnualMenu');
      %
      controls.irfunctions.levels = uimenu('Parent',controls.irfunctions.parent, ...
         'Label','&Levels Data', ...
         'Tag','IRLevelsMenu');
      %
      % Initial values
      %
      controls.irfunctions.initialvalues = uimenu('Parent',controls.irfunctions.original, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI irs_init_values', ...
         'Enable','off', ...
         'Tag','IRInitialValuesMenu');
      %
      controls.irfunctions.ann_initialvalues = uimenu('Parent',controls.irfunctions.annual, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI irs_annual_init_values', ...
         'Enable','off', ...
         'Tag','IRInitialValuesMenu');
      %
      controls.irfunctions.lev_initialvalues = uimenu('Parent',controls.irfunctions.levels, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI irs_levels_init_values', ...
         'Enable','off', ...
         'Tag','IRLevelsInitialValuesMenu');
      %
      % posterior mode
      %
      controls.irfunctions.postmode = uimenu('Parent',controls.irfunctions.original, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI irs_post_mode', ...
         'Enable','off', ...
         'Tag','IRPosteriorModeMenu');
      % 
      controls.irfunctions.ann_postmode = uimenu('Parent',controls.irfunctions.annual, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI irs_annual_post_mode', ...
         'Enable','off', ...
         'Tag','IRAnnualPosteriorModeMenu');
      %
      controls.irfunctions.lev_postmode = uimenu('Parent',controls.irfunctions.levels, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI irs_levels_post_mode', ...
         'Enable','off', ...
         'Tag','IRLevelsPosteriorModeMenu');
      %
      % posterior distributions
      %
      controls.irfunctions.posterior = uimenu('Parent',controls.irfunctions.original, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI irs_post_dist', ...
         'Enable','off', ...
         'Tag','IRPosteriorDistMenu');
      %
      controls.irfunctions.ann_posterior = uimenu('Parent',controls.irfunctions.annual, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI irs_post_dist', ...
         'Enable','off', ...
         'Tag','IRAnnualPosteriorDistMenu');
      %
      controls.irfunctions.lev_posterior = uimenu('Parent',controls.irfunctions.levels, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI irs_post_dist', ...
         'Enable','off', ...
         'Tag','IRLevelsPosteriorDistMenu');
      %
      % Forecast error variance decompositions
      %
      controls.fevd.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','&Variance Decompositions', ...
         'Tag','FEVDMenu');
      %
      % original data
      %
      controls.fevd.original = uimenu('Parent',controls.fevd.parent, ...
         'Label','&Original Data', ...
         'Tag','FEVDOriginalMenu');
      %
      % levels data
      %
      controls.fevd.levels = uimenu('Parent',controls.fevd.parent, ...
         'Label','&Levels Data', ...
         'Tag','FVDLevelsMenu');
      %
      % Initial values
      %
      controls.fevd.initialvalues = uimenu('Parent',controls.fevd.original, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI fevd_init_values', ...
         'Enable','off', ...
         'Tag','FEVDInitialValuesMenu');
      %
      controls.fevd.lev_initialvalues = uimenu('Parent',controls.fevd.levels, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI fevd_levels_init_values', ...
         'Enable','off', ...
         'Tag','FEVDLevelsInitialValuesMenu');
      %
      % posterior mode
      %
      controls.fevd.postmode = uimenu('Parent',controls.fevd.original, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI fevd_post_mode', ...
         'Enable','off', ...
         'Tag','FEVDPosteriorModeMenu');
      %
      controls.fevd.lev_postmode = uimenu('Parent',controls.fevd.levels, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI fevd_levels_post_mode', ...
         'Enable','off', ...
         'Tag','FEVDLevelsPosteriorModeMenu');
      %
      % posterior distribution
      %
      controls.fevd.posterior = uimenu('Parent',controls.fevd.original, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI fevd_post_dist', ...
         'Enable','off', ...
         'Tag','FEVDPosteriorDistMenu');
      %
      controls.fevd.lev_posterior = uimenu('Parent',controls.fevd.levels, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI fevd_post_dist', ...
         'Enable','off', ...
         'Tag','FEVDLevelsPosteriorDistMenu');
      %
      % Conditional forecast error variance decomposition
      %
      controls.cvd.parent = uimenu('Parent',controls.toolsmenu, ...
         'Label','Conditional Variance &Decompositions', ...
         'Tag','CVDMenu');
      %
      controls.cvd.original = uimenu('Parent',controls.cvd.parent, ...
         'Label','&Original Data', ...
         'Tag','CVDOriginalMenu');
      %
      controls.cvd.annual = uimenu('Parent',controls.cvd.parent, ...
         'Label','&Annualized Data', ...
         'Tag','CVDAnnualMenu');
      %
      controls.cvd.levels = uimenu('Parent',controls.cvd.parent, ...
         'Label','&Levels Data', ...
         'Tag','CVDLevelsMenu');
      %
      % Initial values
      %
      controls.cvd.initialvalues = uimenu('Parent',controls.cvd.original, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI cvd_init_values', ...
         'Enable','off', ...
         'Tag','CVDOrigInitialValuesMenu');
      %
      controls.cvd.ann_initialvalues = uimenu('Parent',controls.cvd.annual, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI cvd_annual_init_values', ...
         'Enable','off', ...
         'Tag','CVDAnnualInitialValuesMenu');
      %
      controls.cvd.lev_initialvalues = uimenu('Parent',controls.cvd.levels, ...
         'Label','&Initial Values...', ...
         'Callback','YADAGUI cvd_levels_init_values', ...
         'Enable','off', ...
         'Tag','CVDLevelsInitialValuesMenu');
      %
      % posterior mode
      %
      controls.cvd.postmode = uimenu('Parent',controls.cvd.original, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI cvd_post_mode', ...
         'Enable','off', ...
         'Tag','CVDOrigPosteriorModeMenu');
      %
      controls.cvd.ann_postmode = uimenu('Parent',controls.cvd.annual, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI cvd_annual_post_mode', ...
         'Enable','off', ...
         'Tag','CVDAnnualPosteriorModeMenu');
      %
      controls.cvd.lev_postmode = uimenu('Parent',controls.cvd.levels, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI cvd_levels_post_mode', ...
         'Enable','off', ...
         'Tag','CVDLevelsPosteriorModeMenu');
      %
      % posterior distribution
      %
      controls.cvd.posterior = uimenu('Parent',controls.cvd.original, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI cvd_post_dist', ...
         'Enable','off', ...
         'Tag','CVDOrigPosteriorDistMenu');
      %
      controls.cvd.ann_posterior = uimenu('Parent',controls.cvd.annual, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI cvd_post_dist', ...
         'Enable','off', ...
         'Tag','CVDAnnualPosteriorDistMenu');
      %
      controls.cvd.lev_posterior = uimenu('Parent',controls.cvd.levels, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI cvd_post_dist', ...
         'Enable','off', ...
         'Tag','CVDLevelsPosteriorDistMenu');
      %
      % 5. Actions menu
      %
      controls.actionsmenu = uimenu('Parent',maingui, ...
         'Label','&Actions', ...
         'Tag','ActionsMenu');
      %
      % Objects on the Actions menu
      %
      controls.runaimmenu = uimenu('Parent',controls.actionsmenu, ...
         'Label','Run &AiM Parser...', ...
         'Callback','YADAGUI runaim', ...
         'Enable',AiMEnable, ...
         'Tag','RunAIMMenu');
      %
      controls.postmodemenu = uimenu('Parent',controls.actionsmenu, ...
         'Label','&Estimate Posterior Mode...', ...
         'Callback','YADAGUI postmode', ...
         'Enable','off', ...
         'Tag','EstimatePostModeMenu');
      %
      controls.postsamplingmenu = uimenu('Parent',controls.actionsmenu, ...
         'Label','&Posterior Sampling...', ...
         'Callback','YADAGUI metropolis_hastings', ...
         'Enable','off', ...
         'Tag','PosteriorSamplingMenu');
      %
      controls.statevarmenu = uimenu('Parent',controls.actionsmenu, ...
         'Label','Set State &Variables...', ...
         'Callback','YADAGUI setstatevars', ...
         'Separator','on', ...
         'Enable',StateEnable, ...
         'Tag','StateVarsMenu');
      %
      controls.stateshockmenu = uimenu('Parent',controls.actionsmenu, ...
         'Label','&Set State Shocks...', ...
         'Callback','YADAGUI setstateshocks', ...
         'Enable',StateEnable, ...
         'Tag','StateShocksMenu');
      %
      controls.shockgroupmenu = uimenu('Parent',controls.actionsmenu, ...
         'Label','Set Shock &Groups...', ...
         'Callback','YADAGUI setshockgroups', ...
         'Enable','off', ...
         'Tag','ShockGroupMenu');
      %
      controls.initialstatevaluesmenu = uimenu('Parent',controls.actionsmenu, ...
         'Label','Set &Initial State Values...', ...
         'Callback','YADAGUI setinitialstatevalues', ...
         'Separator','on', ...
         'Enable','off', ...
         'Tag','InitialStateValuesMenu');
      %
      controls.unitrootstatemenu = uimenu('Parent',controls.actionsmenu, ...
         'Label','Specify &Unit Root State Variables...', ...
         'Callback','YADAGUI setunitrootstatevars', ...
         'Enable','off', ...
         'Tag','StateVarsMenu');
      %
      controls.confbandcolor = uimenu('Parent',controls.actionsmenu, ...
         'Label','&Confidence Band Base Color...', ...
         'Callback','YADAGUI setconfbandbasecolor', ...
         'Separator','on', ...
         'Enable','on', ...
         'Tag','ConfidenceBandBaseColorMenu');
      %
      controls.viewconditionalvars = uimenu('Parent',controls.actionsmenu, ...
         'Label','Vie&w Conditioning Variables...', ...
         'Callback','YADAGUI viewconditionalvars', ...
         'Separator','on', ...
         'Enable','off', ...
         'Tag','ViewConditionalVariablesMenu');
      %
      controls.setconditionalvars = uimenu('Parent',controls.actionsmenu, ...
         'Label','Se&lect Conditioning Variables...', ...
         'Callback','YADAGUI setconditionalvars', ...
         'Separator','off', ...
         'Enable','off', ...
         'Tag','SetConditionalVariablesMenu');
      %
      controls.setconditionalshocks = uimenu('Parent',controls.actionsmenu, ...
         'Label','Select C&onditioning Shocks...', ...
         'Callback','YADAGUI setconditionalshocks', ...
         'Enable','off', ...
         'Tag','SetConditionalShocksMenu');
      %
%      controls.reorderconditionalshocks = uimenu('Parent',controls.actionsmenu, ...
%         'Label','Reorder Co&nditioning Shocks...', ...
%         'Callback','YADAGUI reorderconditionalshocks', ...
%         'Enable','off', ...
%         'Tag','ReorderConditionalShocksMenu');
      %
      if FileExist([pwd '\addons\ovs\OVSControls.m'])==1;
         controls = OVSControls(controls,'actionsmenu');
      end;
      %
      % BVAR menu
      %
      controls.bvarmenu = uimenu('Parent',maingui, ...
         'Label','&BVAR', ...
         'Tag','BVARMenu');
      %
      % Estimate the posterior mode
      %
      controls.bvarmodemenu = uimenu('Parent',controls.bvarmenu, ...
         'Label','&Estimate Posterior Mode...', ...
         'Callback','YADAGUI bvarpostmode', ...
         'Enable','off', ...
         'Tag','BVARPosteriorModeMenu');
      %
      % Run the Gibbs sampler
      %
      controls.gibbssamplingmenu = uimenu('Parent',controls.bvarmenu, ...
         'Label','&Posterior Sampling...', ...
         'Callback','YADAGUI gibbs', ...
         'Enable','off', ...
         'Tag','BVARPosteriorSamplingMenu');
      %
      % Display BVAR posterior mode results
      %
      controls.bvarmoderesultsmenu = uimenu('Parent',controls.bvarmenu, ...
         'Label','Posterior &Mode Results...', ...
         'Callback','YADAGUI bvarpostmode_results', ...
         'Separator','on', ...
         'Enable','off', ...
         'Tag','BVARPosteriorModeResultsMenu');
      %
      % display BVAR posterior sampling results
      %
      controls.bvargibbsresultsmenu = uimenu('Parent',controls.bvarmenu, ...
         'Label','Posterior &Sampling Results...', ...
         'Callback','YADAGUI bvargibbs_results', ...
         'Enable','off', ...
         'Tag','BVARPosteriorModeResultsMenu');
      %
      % Compute forecasts from the BVAR
      %
%      controls.bvarforecast.parent = uimenu('Parent',controls.bvarmenu, ...
%         'Label','&Forecasting', ...
%         'Separator','on', ...
%         'Tag','BVARForecastingMenu');
      %
      % Posterior Mode estimates for original data
      %
%      controls.bvarforecast.postmode = uimenu('Parent',controls.bvarforecast.parent, ...
%         'Label','&Posterior Mode - Original Data...', ...
%         'Callback','YADAGUI bvar_forecast_postmode', ...
%         'Enable','off', ...
%         'Tag','BVARPosteriorModeForecastingMenu');
      %
      % Posterior mode estimates for annualized data
      %
%      controls.bvarforecast.annpostmode = uimenu('Parent',controls.bvarforecast.parent, ...
%         'Label','Posterior &Mode - Annualized Data...', ...
%         'Callback','YADAGUI bvar_forecast_postmode', ...
%         'Enable','off', ...
%         'Tag','BVARAnnualPosteriorModeForecastingMenu');
      %
      % Predictive distributions from the BVAR
      %
      controls.bvarpredict.parent = uimenu('Parent',controls.bvarmenu, ...
         'Label','Predi&ctive Distributions', ...
         'Separator','on', ...
         'Tag','BVARPredictionMenu');
      %
      % original data
      %
      controls.bvarpredict.original = uimenu('Parent',controls.bvarpredict.parent, ...
         'Label','&Original Data', ...
         'Tag','BVARPredictionOriginalDataMenu');
      %
      % posterior mode
      %
      controls.bvarpredict.original_postmode = uimenu('Parent',controls.bvarpredict.original, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI bvar_predict_postmode', ...
         'Enable','off', ...
         'Tag','BVARPredictionOriginalDataPostModeMenu');
      %
      % posterior distribution
      %
      controls.bvarpredict.original_posterior = uimenu('Parent',controls.bvarpredict.original, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI bvar_predict_posterior', ...
         'Enable','off', ...
         'Tag','BVARPredictionOriginalDataPostDistMenu');
      %
      % prediction event
      %
      controls.bvarpredict.original_predevent = uimenu('Parent',controls.bvarpredict.original, ...
         'Label','Prediction &Event...', ...
         'Callback','YADAGUI bvar_pred_event', ...
         'Enable','off', ...
         'Separator','on', ...
         'Tag','BVARPredictionEventOriginalDataPostDistMenu');
      %
      % annualized data
      %
      controls.bvarpredict.annual = uimenu('Parent',controls.bvarpredict.parent, ...
         'Label','&Annualized Data', ...
         'Tag','BVARPredictionAnnualizedDataMenu');
      %
      % posterior mode
      %
      controls.bvarpredict.annual_postmode = uimenu('Parent',controls.bvarpredict.annual, ...
         'Label','&Posterior Mode...', ...
         'Callback','YADAGUI bvar_predict_postmode', ...
         'Enable','off', ...
         'Tag','BVARPredictionAnnualDataPostModeMenu');
      %
      % posterior distribution
      %
      controls.bvarpredict.annual_posterior = uimenu('Parent',controls.bvarpredict.annual, ...
         'Label','&Distribution...', ...
         'Callback','YADAGUI bvar_predict_posterior', ...
         'Enable','off', ...
         'Tag','BVARPredictionAnnualDataPostDistMenu');
      %
      % prediction event
      %
      controls.bvarpredict.annual_predevent = uimenu('Parent',controls.bvarpredict.annual, ...
         'Label','Prediction &Event...', ...
         'Callback','YADAGUI bvar_pred_event', ...
         'Enable','off', ...
         'Separator','on', ...
         'Tag','BVARPredictionEventAnnualDataPostDistMenu');
      %
      % Various plots from the posterior draws
      %
      controls.bvarrawdraws = uimenu('Parent',controls.bvarmenu, ...
         'Label','&Raw Posterior Draws...', ...
         'Separator','on', ...
         'Enable','on', ...
         'Tag','BVARRawPosteriorDrawsMenu');
      %
      % submenus for raw posterior draws
      %
      controls.bvarrawdrawspsi = uimenu('Parent',controls.bvarrawdraws, ...
         'Label','&Psi...', ...
         'Callback','YADAGUI bvar_psi_raw_draws', ...
         'Enable','off', ...
         'Tag','BVARPsiRawPosteriorDrawsMenu');
      %
      controls.bvarrawdrawspi = uimenu('Parent',controls.bvarrawdraws, ...
         'Label','P&i...', ...
         'Callback','YADAGUI bvar_pi_raw_draws', ...
         'Enable','off', ...
         'Tag','BVARPiRawPosteriorDrawsMenu');
      % 
      controls.bvarrawdrawsomega = uimenu('Parent',controls.bvarrawdraws, ...
         'Label','&Omega...', ...
         'Callback','YADAGUI bvar_omega_raw_draws', ...
         'Enable','off', ...
         'Tag','BVAROmegaRawPosteriorDrawsMenu');
      %
      % Sequential marginal likelihood
      %
      controls.bvarmarglike = uimenu('Parent',controls.bvarmenu, ...
         'Label','Sequential Marginal &Likelihood...', ...
         'Callback','YADAGUI postsample_chib', ...
         'Enable','on', ...
         'Tag','BVARMarginalLikelihhodMenu');
      %
      % convergence tools
      %
      controls.bvarconvergence = uimenu('Parent',controls.bvarmenu, ...
         'Label','Con&vergence', ...
         'Enable','on', ...
         'Tag','BVARConvergenceMenu');
      %
      % posterior mean estimates for the BVAR
      %
      controls.bvarpostmean = uimenu('Parent',controls.bvarconvergence, ...
         'Label','&Posterior Mean...', ...
         'Enable','on', ...
         'Tag','BVARPPosteriorMeanConvergenceMenu');
      %
      controls.bvarpsimeanconvergence = uimenu('Parent',controls.bvarpostmean, ...
         'Label','&Psi...', ...
         'Callback','YADAGUI bvar_mean_median_convergence', ...
         'Enable','off', ...
         'Tag','BVARPsiPosteriorMeanConvergenceMenu');
      %
      controls.bvarpimeanconvergence = uimenu('Parent',controls.bvarpostmean, ...
         'Label','P&i...', ...
         'Callback','YADAGUI bvar_mean_median_convergence', ...
         'Enable','off', ...
         'Tag','BVARPiPosteriorMeanConvergenceMenu');
      %
      controls.bvaromegameanconvergence = uimenu('Parent',controls.bvarpostmean, ...
         'Label','&Omega...', ...
         'Callback','YADAGUI bvar_mean_median_convergence', ...
         'Enable','off', ...
         'Tag','BVAROmegaPosteriorMeanConvergenceMenu');
      %
      % posterior median estimates for the BVAR
      %
      controls.bvarpostmedian = uimenu('Parent',controls.bvarconvergence, ...
         'Label','Posterior &Median...', ...
         'Enable','on', ...
         'Tag','BVARPPosteriorMedianConvergenceMenu');
      %
      controls.bvarpsimedianconvergence = uimenu('Parent',controls.bvarpostmedian, ...
         'Label','&Psi...', ...
         'Callback','YADAGUI bvar_mean_median_convergence', ...
         'Enable','off', ...
         'Tag','BVARPsiPosteriorMedianConvergenceMenu');
      %
      controls.bvarpimedianconvergence = uimenu('Parent',controls.bvarpostmedian, ...
         'Label','P&i...', ...
         'Callback','YADAGUI bvar_mean_median_convergence', ...
         'Enable','off', ...
         'Tag','BVARPiPosteriorMedianConvergenceMenu');
      %
      controls.bvaromegamedianconvergence = uimenu('Parent',controls.bvarpostmedian, ...
         'Label','&Omega...', ...
         'Callback','YADAGUI bvar_mean_median_convergence', ...
         'Enable','off', ...
         'Tag','BVAROmegaPosteriorMedianConvergenceMenu');
      %
      % prior densities
      %
      controls.bvarpriordensity = uimenu('Parent',controls.bvarmenu, ...
         'Label','Pr&ior Densities', ...
         'Separator','on', ...
         'Enable','on', ...
         'Tag','BVARPriorDensitiesMenu');
      %
      controls.bvarpriordensitypsi = uimenu('Parent',controls.bvarpriordensity, ...
         'Label','&Psi...', ...
         'Callback','YADAGUI bvar_psi_prior_density', ...
         'Enable','off', ...
         'Tag','BVARPsiPriorDensitiesMenu');
      %
      controls.bvarpriordensitypi = uimenu('Parent',controls.bvarpriordensity, ...
         'Label','P&i...', ...
         'Callback','YADAGUI bvar_pi_prior_density', ...
         'Enable','off', ...
         'Tag','BVARPiPriorDensitiesMenu');
      %
      controls.bvarpriordensityomega = uimenu('Parent',controls.bvarpriordensity, ...
         'Label','&Omega...', ...
         'Callback','YADAGUI bvar_omega_prior_density', ...
         'Enable','off', ...
         'Tag','BVAROmegaPriorDensitiesMenu');
      %
      % posterior densities
      %
      controls.bvarpostdensity = uimenu('Parent',controls.bvarmenu, ...
         'Label','Posterior &Densities', ...
         'Enable','on', ...
         'Tag','BVARPosteriorDensitiesMenu');
      %
      controls.bvarpostdensitypsi = uimenu('Parent',controls.bvarpostdensity, ...
         'Label','&Psi...', ...
         'Callback','YADAGUI bvar_psi_post_density', ...
         'Enable','off', ...
         'Tag','BVARPsiPosteriorDensitiesMenu');
      %
      controls.bvarpostdensitypi = uimenu('Parent',controls.bvarpostdensity, ...
         'Label','P&i...', ...
         'Callback','YADAGUI bvar_pi_post_density', ...
         'Enable','off', ...
         'Tag','BVARPiPosteriorDensitiesMenu');
      %
      controls.bvarpostdensityomega = uimenu('Parent',controls.bvarpostdensity, ...
         'Label','&Omega...', ...
         'Callback','YADAGUI bvar_omega_post_density', ...
         'Enable','off', ...
         'Tag','BVAROmegaPosteriorDensitiesMenu');
      %
      % 7. Help Menu
      %
      controls.helpmenu = uimenu('Parent',maingui, ...
         'Label','&Help', ...
         'Tag','HelpMenu');
      %
      % Objects on Help menu
      %
      controls.helpfilemenu = uimenu('Parent',controls.helpmenu, ...
         'Label','&Help', ...
         'Callback','YADAGUI helpfile', ...
         'Enable','on', ...
         'Tag','HelpFileMenu');
      %
      controls.yadamanual = uimenu('Parent',controls.helpmenu, ...
         'Label','&Manual - Computational Details (PDF)', ...
         'Callback','YADAGUI mathmanual', ...
         'Enable','on', ...
         'Tag','ManualMenu');
      %
      controls.license = uimenu('Parent',controls.helpmenu, ...
         'Label','&License', ...
         'Callback','YADAGUI license', ...
         'Separator','on', ...
         'Enable','on', ...
         'Tag','LicenseMenu');
      %
      controls.aboutmenu = uimenu('Parent',controls.helpmenu, ...
         'Label','&About', ...
         'Callback','YADAGUI about', ...
         'Separator','on', ...
         'Enable','on', ...
         'Tag','AboutMenu');
      %
      % Outer axis
      %
      AxesBox([2 21 698 625],'YADA Specifications',96,[0.5 1],'on',CurrINI);
      %
      % Setting up the tabbed dialog
      %
      input_var.fldnames = {'tab1' 'tab2' 'tab3' 'tab4' 'tab5' 'tab6'};
      input_var.tags = {'tab1' 'tab2' 'tab3' 'tab4' 'tab5' 'tab6'};
      input_var.strings = {'DSGE Data' 'Settings' 'Options' 'Miscellaneous' 'Bayesian VAR' 'Output'};
      input_var.visible = {'on' 'on' 'on' 'on' 'on' 'on'};
      input_var.callbackstr = {'YADAGUI tab' 'YADAGUI tab' 'YADAGUI tab' 'YADAGUI tab' 'YADAGUI tab' 'YADAGUI tab'};
      controls = TabDialog(controls,CurrINI,[14 34 672 570],6,input_var,[104 102]);
      %
      % Controls on the DSGE data tab
      %
      %
      % Frame for Observation data
      %
      controls.dsge.obsfilesbox = AxesBox([28 450 644 140],'Observation Data',90,[0.5 1],'on',CurrINI);
      %
      % The DSGE data file
      %
      controls.dsge.datafiletext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 555 522 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Visible','on', ...
         'HorizontalAlignment','left', ...
         'String','Data construction file:', ...
         'Tag','DataFileText');
      %
      controls.dsge.datafile = uicontrol('Units','pixels', ...
            'BackgroundColor',[1 1 1], ...
            'Position',[44 531 522 25], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','edit', ...
            'Visible','on', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI checkdatafile', ...
            'String',DSGEModel.DataConstructionFile, ...
            'Enable','on', ...
            'Tag','dataFileEditBox');
      %
      % browse for the data file
      %
      controls.dsge.datafilebutton = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[576 531 80 25], ...
         'TooltipString','Browse', ...
         'Visible','on', ...
         'CData',ButtonImages.browse, ...
         'Callback','YADAGUI browsedatafile', ...
         'Enable','on', ...
         'Tag','DataFileButton');
      %
      % The DSGE measurement equation file
      %
      controls.dsge.measurefiletext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 494 522 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Visible','on', ...
         'HorizontalAlignment','left', ...
         'String','Measurement equation file:', ...
         'Tag','MeasurementFileText');
      %
      controls.dsge.measurefile = uicontrol('Units','pixels', ...
            'BackgroundColor',[1 1 1], ...
            'Position',[44 470 522 25], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','edit', ...
            'Visible','on', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI checkmeasurefile', ...
            'String',DSGEModel.MeasurementEquationFile, ...
            'Enable','on', ...
            'Tag','MeasurementFileEditBox');
      %
      % browse for the measurement file
      %
      controls.dsge.measurefilebutton = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[576 470 80 25], ...
         'TooltipString','Browse', ...
         'Visible','on', ...
         'CData',ButtonImages.browse, ...
         'Callback','YADAGUI browsemeasurefile', ...
         'Enable','on', ...
         'Tag','MeasurementFileButton');
      %
      % Frame for Prior distribution data
      %
      controls.dsge.priorfilesbox = AxesBox([28 336 644 100],'Prior Distribution Data',90,[0.5 1],'on',CurrINI);
      %
      % The DSGE prior information file
      %
      controls.dsge.priorfiletext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 396 522 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Visible','on', ...
         'HorizontalAlignment','left', ...
         'String','Prior distribution specification file:', ...
         'Tag','PriorFileText');
      %
      controls.dsge.priorfile = uicontrol('Units','pixels', ...
            'BackgroundColor',[1 1 1], ...
            'Position',[44 372 522 25], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','edit', ...
            'Visible','on', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI checkpriorfile', ...
            'String',DSGEModel.PriorFile, ...
            'Enable','on', ...
            'Tag','PriorFileEditBox');
      %
      % browse for the prior distribution specification file
      %
      controls.dsge.priorfilebutton = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[576 372 80 25], ...
         'TooltipString','Browse', ...
         'Visible','on', ...
         'CData',ButtonImages.browse, ...
         'Callback','YADAGUI browsepriorfile', ...
         'Enable','on', ...
         'Tag','PriorFileButton');
      %
      % The selected data sheet for the file if any
      %
      controls.dsge.priorfilesheet = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 349 522 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Visible','on', ...
         'HorizontalAlignment','right', ...
         'String',['Sheet: ' DSGEModel.PriorFileSheet], ...
         'Tag','PriorFileSheetText');
      %
      % Frame for additional parameters data
      %
      controls.dsge.parameterfilesbox = AxesBox([28 172 644 150],'Parameter Data',90,[0.5 1],'on',CurrINI);
      %
      % File with additional parameters to update
      %
      controls.dsge.updateparameterfiletext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 284 522 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Visible','on', ...
         'HorizontalAlignment','left', ...
         'String','File with parameters to update:', ...
         'Tag','UpdateParemeterFileText');
      %
      controls.dsge.updateparameterfile = uicontrol('Units','pixels', ...
            'BackgroundColor',[1 1 1], ...
            'Position',[44 260 522 25], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','edit', ...
            'Visible','on', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI checkparameterfile', ...
            'String',DSGEModel.UpdateParameterFile, ...
            'Enable','on', ...
            'Tag','UpdateParameterFileEditBox');
      %
      % browse for the update parameter file
      %
      controls.dsge.updateparameterfilebutton = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[576 260 80 25], ...
         'TooltipString','Browse', ...
         'Visible','on', ...
         'CData',ButtonImages.browse, ...
         'Callback','YADAGUI browseparameterfile', ...
         'Enable','on', ...
         'Tag','UpdateParameterFileButton');
      %
      %
      % File with additional parameters to initialize
      %
      controls.dsge.initialparameterfiletext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 234 522 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Visible','on', ...
         'HorizontalAlignment','left', ...
         'String','File with parameters to initialize:', ...
         'Tag','InitializeParemeterFileText');
      %
      controls.dsge.initialparameterfile = uicontrol('Units','pixels', ...
            'BackgroundColor',[1 1 1], ...
            'Position',[44 210 522 25], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','edit', ...
            'Visible','on', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI checkparameterfile', ...
            'String',DSGEModel.InitializeParameterFile, ...
            'Enable','on', ...
            'Tag','InitializeParameterFileEditBox');
      %
      % browse for the initialzie parameter file
      %
      controls.dsge.initialparameterfilebutton = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[576 210 80 25], ...
         'TooltipString','Browse', ...
         'Visible','on', ...
         'CData',ButtonImages.browse, ...
         'Callback','YADAGUI browseparameterfile', ...
         'Enable','on', ...
         'Tag','InitializeParameterFileButton');
      %
      % Check box with option to run file with parameters that need to be initialized
      % only before running the file with the parameters that will be updated
      %
      controls.dsge.runinitialfirst = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[44 185 522 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','on', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI initializefirst', ...
            'String','Run file with parameters to initialize before file with parameters to update', ...
            'Value',DSGEModel.RunInitializeFirst, ...
            'Enable','off', ...
            'Tag','RunInitializeFirstCheckBox');
      %
      if FileExist(DSGEModel.InitializeParameterFile)==1;
         set(controls.dsge.runinitialfirst,'Enable','on');
      end;
      %
      % Frame for AiM Data
      %
      controls.dsge.aimfilesbox = AxesBox([28 48 644 110],'AiM Data',90,[0.5 1],'on',CurrINI);
      %
      % The DSGE AiM model file
      %
      controls.dsge.aimfiletext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 123 522 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Visible','on', ...
         'HorizontalAlignment','left', ...
         'String','AiM model file:', ...
         'Tag','AIMModelFileText');
      %
      % the edit box for the output file
      %
      controls.dsge.aimfile = uicontrol('Units','pixels', ...
            'BackgroundColor',[1 1 1], ...
            'Position',[44 99 522 25], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','edit', ...
            'Visible','on', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI checkaimfile', ...
            'String',DSGEModel.AIMFile, ...
            'Enable','on', ...
            'Tag','AIMModelFileEditBox');
      %
      % browse for the AiM model file
      %
      controls.dsge.aimfilebutton = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[576 99 80 25], ...
         'TooltipString','Browse', ...
         'Visible','on', ...
         'CData',ButtonImages.browse, ...
         'Callback','YADAGUI browseaim', ...
         'Enable','on', ...
         'Tag','AIMModelFileButton');
      %
      % Set the name of the model
      %
      controls.dsge.modelnametext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 64 106 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Visible','on', ...
         'HorizontalAlignment','left', ...
         'String','Name of model:', ...
         'Tag','ModelNameText');
      %
      % Axes for text controls
      %
      controls.dsge.modelnameaxes = axes('Units','pixels', ...
         'Box','on', ...
         'TickLength',[0 0], ...
         'CameraUpVector',[0 1 0], ...
         'Color',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[150 64 416 30], ...
         'XTickLabelMode','manual', ...
         'YTickLabelMode','manual', ...
         'Tag','ModelNameAxes', ...
         'XColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'YColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'ZColor',get(0,'defaultuicontrolbackgroundcolor'));
      %
      % The text controls for holding the model name
      %
      controls.dsge.modelname = text('Parent',controls.dsge.modelnameaxes, ...
         'Position',[0 0.5], ...
         'String',DSGEModel.NameOfModel, ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'HorizontalAlignment','left', ...
         'Interpreter','none', ...
         'Color',CurrINI.gui_foreground_color, ...
         'ButtonDownFcn','YADAGUI editmodelname', ...
         'Tag','ModelNameText');
      %
      % Button for editing model name
      %
      controls.dsge.modelnamebutton = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[576 64 80 25], ...
         'TooltipString','Edit Model Name', ...
         'Visible','on', ...
         'Callback','YADAGUI editmodelname', ...
         'CData',ButtonImages.rename, ...
         'Enable','on', ...
         'Tag','ModelNameButton');
      %
      % Controls on the Settings tab
      %
      controls.dsge.posteriorsamplingbox = AxesBox([28 443 644 147],'DSGE Posterior Sampling',50,[0.5 1],'off',CurrINI);
      %
      % Selection of marginal likelihood algorithm
      %
      controls.dsge.marginallikelihoodtext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 547 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Marginal likelihood algorithm:', ...
         'Tag','MarginalLikelihoodText');
      %
      controls.dsge.marginallikelihood = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 552 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI marginallikelihood', ...
         'String','All|Geweke''s Modified Harmonic Mean|Chib and Jeliazkov|None', ...
         'Value',DSGEModel.MarginalLikelihoodValue, ...
         'Tag','MarginalLikelihoodPopup');
      %
      % StartIteration value and StepLength value for sequential marginal likelihood
      % estimation.
      %
      controls.dsge.sequantialmltext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 518 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Sequential estimation [StartIteration StepLength]:', ...
         'Tag','SequentialMarginalLikelihoodText');
      %
      controls.dsge.sequentialstart = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 523 120.5 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI sequentialstartiteration', ...
         'String','10|50|100|200|300|400|500|600|700|800|900|1,000|5,000|10,000|15,000|20,000|25,000|30,000|35,000|40,000|45,000|50,000|55,000|60,000|65,000|70,000|75,000|80,000|85,000|90,000|95,000|100,000', ...
         'Value',DSGEModel.SequentialStartIteration, ...
         'Tag','SequentialStartIterationPopup');
      %
      controls.dsge.sequentialstep = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[535.5 523 120.5 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI sequentialsteplength', ...
         'String','1|10|50|100|200|300|400|500|600|700|800|900|1,000|5,000|10,000|15,000|20,000|25,000|30,000|35,000|40,000|45,000|50,000|55,000|60,000|65,000|70,000|75,000|80,000|85,000|90,000|95,000|100,000', ...
         'Value',DSGEModel.SequentialStepLength, ...
         'Tag','SequentialStepLengthPopup');
      %
      % Coverage probability (used by the Modified Harmonic Mean estimator)
      %
      controls.dsge.coverageprobtext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 489 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Coverage probability (Start:Increment:End):', ...
         'Tag','CoverageProbabilityText');
      %
      controls.dsge.coveragestart = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 494 77.333 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI coverageprobability', ...
         'String','0.05|0.10|0.15|0.20|0.25|0.30|0.35|0.40|0.45|0.50', ...
         'Value',DSGEModel.CoverageStart, ...
         'Tag','CoverageStartPopup');
      %
      controls.dsge.coverageincrement = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[492.333 494 77.333 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI coverageprobability', ...
         'String','0.05|0.10|0.15|0.20|0.25', ...
         'Value',DSGEModel.CoverageIncrement, ...
         'Tag','CoverageIncrementPopup');
      %
      controls.dsge.coverageend = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[578.667 494 77.333 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI coverageprobability', ...
         'String','0.50|0.55|0.60|0.65|0.70|0.75|0.80|0.85|0.90|0.95', ...
         'Value',DSGEModel.CoverageEnd, ...
         'Tag','CoverageEndPopup');
      %
      % Determine if the marginal likelihood should be computed sequentially,
      % directly after having computed all posterior draws
      %
      controls.dsge.sequentialml = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[44 459 362 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI sequentialml', ...
            'String','Compute the marginal likelihood sequentially', ...
            'Value',DSGEModel.SequentialML, ...
            'Enable','on', ...
            'Tag','SequentialMLCheckBox');
      %
      % Overwrite previous draws. If checked, then yes, if unchecked then previous draws are used.
      %
      controls.dsge.overwritedraws = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[406 459 160 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI overwritedraws', ...
            'String','Overwrite old draws', ...
            'Value',DSGEModel.OverwriteDraws, ...
            'Enable','on', ...
            'Tag','OverwriteCheckBox');
      %
      % settings for progress dialogs
      %
      controls.dsge.progressbox = AxesBox([28 379 644 50],'Progress Dialog Selections',90,[0.5 1],'off',CurrINI);
      %
      % Show progress dialog
      %
      controls.dsge.progress = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[44 393 362 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI showprogress', ...
            'String','Show dialog during optimization and posterior sampling', ...
            'Value',DSGEModel.ShowProgress, ...
            'Enable','on', ...
            'Tag','ShowProgressCheckBox');
      %
      % Show clock on progress dialog
      %
      controls.dsge.progressclock = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[406 393 160 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI showprogressclock', ...
            'String','Show clock on dialog', ...
            'Value',DSGEModel.ShowProgressClock, ...
            'Enable','on', ...
            'Tag','ShowProgressClockCheckBox');
      %
      if DSGEModel.ShowProgress==0;
         set(controls.dsge.progressclock,'Enable','off');
      end;
      %
      % settings for the Kalman filter
      %
      controls.dsge.kalmanbox = AxesBox([28 122 644 243],'Kalman Filter Selections',90,[0.5 1],'off',CurrINI);
      %
      % Select algorithm for computing the covariance matrix of the initial state forecast
      %
      if DSGEModel.UseDoublingAlgorithm==0;
         DSGEModel.UseDoublingAlgorithm = 1;
         OrigDSGEModel.UseDoublingAlgorithm = 1;
      end;
      %
      controls.dsge.usedoublingalgorithmtext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 322 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Visible','off', ...
         'Enable','on', ...
         'HorizontalAlignment','left', ...
         'String','Select method for initializing the state covariance matrix:', ...
         'Tag','UseDoublingAlgorithmText');
      %
      controls.dsge.usedoublingalgorithm = uicontrol('Units','pixels', ...
            'BackgroundColor',[1 1 1], ...
            'Position',[406 327 250 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','popup', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI usedoublingalgorithm', ...
            'String','Analytically through vectorization (slow)|Engage the doubling algorithm|Use constant times identity', ...
            'Value',DSGEModel.UseDoublingAlgorithm, ...
            'Enable','on', ...
            'Tag','UseDoublingAlgorithmCheckBox');
      %
      % number of maximum iterations for the doubling algorithm
      %
      controls.dsge.doublingalgorithmtext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 293 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Visible','off', ...
         'Enable','on', ...
         'HorizontalAlignment','left', ...
         'String','Maximum number of iterations for the doubling algorithm:', ...
         'Tag','DoublingAlgorithmText');
      %
      controls.dsge.doublingalgorithm = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 298 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI doublingalgorithm', ...
         'String','100|200|300|400|500|600|700|800|900|1,000|1,100|1,200|1,300|1,400|1,500|1,600|1,700|1,800|1,900|2,000', ...
         'Value',DSGEModel.DAMaximumIterationsValue, ...
         'Tag','DoublingAlgorithmMaxIterationsPopup');
      %
      % Tolerance level for doubling algorithm
      %
      controls.dsge.doublingtolerancetext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 264 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Visible','off', ...
         'Enable','on', ...
         'HorizontalAlignment','left', ...
         'String','Tolerance level for the doubling algorithm:', ...
         'Tag','DoublingToleranceText');
      %
      controls.dsge.doublingtolerance = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 269 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI da_tolerance', ...
         'String','0.01|0.001|0.0001|0.00001|0.000001|0.0000001|0.00000001|0.000000001|0.0000000001|0.00000000001', ...
         'Value',DSGEModel.DAToleranceValue, ...
         'Tag','DAToleranceValuePopup');
      %
      % Constant for initial state covariance matrix
      %
      controls.dsge.statecovariancetext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 235 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Visible','off', ...
         'Enable','on', ...
         'HorizontalAlignment','left', ...
         'String','Constant for initial state covariance matrix:', ...
         'Tag','StateCovarianceConstantText');
      %
      controls.dsge.statecovariance = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 240 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI statecov', ...
         'String','1|2|3|4|5|6|7|8|9|10|20|30|40|50|60|70|80|90|100|150|200|250|300|350|400|450|500|550|600|650|700|750|800|850|900|950|1,000|1,100|1,200|1,300|1,400|1,500|1,600|1,700|1,800|1,900|2,000|3,000|4,000|5,000|6,000|7,000|8,000|9,000|10,000', ...
         'Value',DSGEModel.StateCovConst, ...
         'Tag','StateCovarianceConstantPopup');
      %
      StateCStr = get(controls.dsge.statecovariance,'String');
      DSGEModel.StateCovConstValue = str2num(strrep(StringTrim(StateCStr(DSGEModel.StateCovConst,:)),',',''));
      OrigDSGEModel.StateCovConstValue = DSGEModel.StateCovConstValue;
      set(controls.open,'UserData',DSGEModel);
      %
      % Enable and disable controls depending on the value of UseDoublingAlgorithm
      %
      if DSGEModel.UseDoublingAlgorithm==2;
         set(controls.dsge.doublingalgorithmtext,'Enable','on');
         set(controls.dsge.doublingalgorithm,'Enable','on');
         set(controls.dsge.doublingtolerancetext,'Enable','on');
         set(controls.dsge.doublingtolerance,'Enable','on');
         set(controls.dsge.statecovariancetext,'Enable','off');
         set(controls.dsge.statecovariance,'Enable','off');
      elseif DSGEModel.UseDoublingAlgorithm==3;
         set(controls.dsge.doublingalgorithmtext,'Enable','off');
         set(controls.dsge.doublingalgorithm,'Enable','off');
         set(controls.dsge.doublingtolerancetext,'Enable','off');
         set(controls.dsge.doublingtolerance,'Enable','off');
         set(controls.dsge.statecovariancetext,'Enable','on');
         set(controls.dsge.statecovariance,'Enable','on');
      else;
         set(controls.dsge.doublingalgorithmtext,'Enable','off');
         set(controls.dsge.doublingalgorithm,'Enable','off');
         set(controls.dsge.doublingtolerancetext,'Enable','off');
         set(controls.dsge.doublingtolerance,'Enable','off');
         set(controls.dsge.statecovariancetext,'Enable','off');
         set(controls.dsge.statecovariance,'Enable','off');
      end;
      %
      % Initialization period for Kalman filter
      %
      controls.dsge.initializekalmantext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 206 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Visible','off', ...
         'Enable','on', ...
         'HorizontalAlignment','left', ...
         'String','First observation after Kalman filter training sample:', ...
         'Tag','InitializeKalmanText');
      %
      controls.dsge.initializekalman = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 211 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI initializekalman', ...
         'String',EstSample, ...
         'Value',DSGEModel.KalmanFirstObservation, ...
         'Tag','InitializeKalmanPopup');
      %
      % Numerical tolerance for AiM
      %
      controls.dsge.aimtolerancetext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 177 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Visible','off', ...
         'Enable','on', ...
         'HorizontalAlignment','left', ...
         'String','Numerical tolerance for AiM:', ...
         'Tag','AiMToleranceText');
      %
      controls.dsge.aimtolerance = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 182 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI aimtolerance', ...
         'String','0.01|0.001|0.0001|0.00001|0.000001|0.0000001|0.00000001|0.000000001|0.0000000001|0.00000000001', ...
         'Value',DSGEModel.AIMTolerance-1, ...
         'Tag','AiMTolerancePopup');
      %
      % Select to use own initial values for the state vector
      % 
      controls.dsge.useowninitialstate = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[44 136 362 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI useowninitialstate', ...
            'String','Use own initial values for the state variables', ...
            'Value',DSGEModel.UseOwnInitialState, ...
            'Enable','on', ...
            'Tag','UseOwnInitialStateCheckBox');
      %
      controls.dsge.allowunitroot = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[406 136 250 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI allowunitroot', ...
            'String','Allow for undefined unit roots', ...
            'Value',DSGEModel.AllowUnitRoot, ...
            'Enable','on', ...
            'Tag','AllowUnitRootCheckBox');
      %
      % the DSGE sample selection axes box
      %
      controls.dsge.sampleselect = AxesBox([28 48 644 60],'Sample Selection',90,[0.5 1],'off',CurrINI);
      %
      % Control for selecting estimation sample
      %
      controls.dsge.subsample = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 61 150 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Selected Sample:', ...
         'Tag','SubSampleText1');
      %
      controls.dsge.subbeginyear = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[226 66 110 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'HorizontalAlignment','left', ...
         'String',DSGEModel.YearStrMatrix, ...
         'Value',DSGEModel.SubBeginYearValue, ...
         'Callback','YADAGUI checksample', ...
         'Enable','on', ...
         'Visible','off', ...
         'Tag','SubPopupYear1');
      %
      controls.dsge.subbeginperiod = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[341 66 95 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'HorizontalAlignment','left', ...
         'String',DSGEModel.PeriodStrMatrix, ...
         'Value',DSGEModel.SubBeginPeriodValue, ...
         'Callback','YADAGUI checksample', ...
         'Visible','off', ...
         'Enable','on', ...
         'Tag','SubPopupPeriod1');
      %
      controls.dsge.subsampleseparator = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[436 66 10 20], ...
         'FontSize',10, ...
         'Style','text', ...
         'HorizontalAlignment','center', ...
         'String','-', ...
         'Visible','off', ...
         'Tag','SubSampleText2');
      %
      controls.dsge.subendyear = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[446 66 110 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'HorizontalAlignment','left', ...
         'String',DSGEModel.YearStrMatrix, ...
         'Value',DSGEModel.SubEndYearValue, ...
         'Callback','YADAGUI checksample', ...
         'Enable','on', ...
         'Visible','off', ...
         'Tag','SubEditYear2');
      %
      controls.dsge.subendperiod = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[561 66 95 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'HorizontalAlignment','left', ...
         'String',DSGEModel.PeriodStrMatrix, ...
         'Value',DSGEModel.SubEndPeriodValue, ...
         'Callback','YADAGUI checksample', ...
         'Enable','on', ...
         'Visible','off', ...
         'Tag','SubEditPeriod2');
      %
      % Controls on the Options tab
      %
      controls.posteriorsamplingbox = AxesBox([28 254 644 336],'Posterior Sampling',50,[0.5 1],'off',CurrINI);
      %
      % Number of posterior draws
      %
      controls.posterior.drawstext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 547 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Number of posterior draws per chain:', ...
         'Tag','NumberPosteriorDrawsText');
      %
      controls.posterior.draws = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 552 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI posteriordraws', ...
         'String','1,000|5,000|10,000|15,000|20,000|25,000|30,000|35,000|40,000|45,000|50,000|75,000|100,000|105,000|110,000|115,000|120,000|125,000|130,000|135,000|140,000|145,000|150,000|155,000|160,000|165,000|170,000|175,000|180,000|185,000|190,000|195,000|200,000|205,000|210,000|215,000|220,000|225,000|230,000|235,000|240,000|245,000|250,000|255,000|260,000|265,000|270,000|275,000|280,000|285,000|290,000|295,000|300,000|305,000|310,000|315,000|320,000|325,000|330,000|335,000|340,000|345,000|350,000|355,000|360,000|365,000|370,000|375,000|380,000|385,000|390,000|395,000|400,000|405,000|410,000|415,000|420,000|425,000|430,000|435,000|440,000|445,000|450,000|455,000|460,000|465,000|470,000|475,000|480,000|485,000|490,000|495,000|500,000|510,000|520,000|525,000|530,000|540,000|550,000|560,000|570,000|575,000|580,000|590,000|600,000|610,000|620,000|625,000|630,000|640,000|650,000|660,000|670,000|675,000|680,000|690,000|700,000|710,000|720,000|725,000|730,000|740,000|750,000|760,000|770,000|775,000|780,000|790,000|800,000|810,000|820,000|825,000|830,000|840,000|850,000|860,000|870,000|875,000|880,000|890,000|900,000|910,000|920,000|925,000|930,000|940,000|950,000|960,000|970,000|975,000|980,000|990,000|1,000,000', ...
         'Value',DSGEModel.PosteriorDrawsValue, ...
         'Tag','NumberPosteriorDrawsPopup');
      %
      % Number of sample batches with draws to save to disk
      %
      controls.posterior.batchtext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 519 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Number of posterior sample batches to save per chain:', ...
         'Tag','NumberSampleBatchesText');
      %
      controls.posterior.batch = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 524 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI samplebatches', ...
         'String','1|10|50|100|500|1,000|5,000|10,000', ...
         'Value',DSGEModel.SampleBatchValue, ...
         'Tag','NumberSampleBatchesPopup');
      %
      % Number of posterior chains
      %
      controls.posterior.chainstext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 491 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Number of parallel chains:', ...
         'Tag','NumberParallelChainsText');
      %
      NumChainsStr = '1';
      for i=2:50;
         NumChainsStr = [NumChainsStr '|' num2str(i,'%0.0f')];
      end;
      %
      controls.posterior.chains = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 496 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI parallelchains', ...
         'String',NumChainsStr, ...
         'Value',DSGEModel.ParallelChainsValue, ...
         'Tag','NumberParallelChainsPopup');
      %
      % Number of burn-in draws for the posterior sampler
      %
      controls.posterior.burnintext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 463 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Number of posterior draws discarded as burn-in period:', ...
         'Tag','NumberBurnInText');
      %
      % this fix is needed since the change of using percentage into absolute numbers
      % for the length of the burn-in period
      %
      if DSGEModel.BurnInValue>91;
         DSGEModel.BurnInValue = 1;
         OrigDSGEModel.BurnInValue = 1;
      end;
      %
      controls.posterior.burnin = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 468 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI burnin', ...
         'String','0|100|200|300|400|500|1,000|1,500|2,000|2,500|3,000|3,500|4,000|4,500|5,000|7,500|10,000|12,500|15,000|17,500|20,000|22,500|25,000|27,500|30,000|32,500|35,000|37,500|40,000|42,500|45,000|47,500|50,000|55,000|60,000|65,000|70,000|75,000|80,000|85,000|90,000|95,000|100,000|110,000|120,000|125,000|130,000|140,000|150,000|160,000|170,000|175,000|180,000|190,000|200,000|210,000|220,000|225,000|230,000|240,000|250,000|260,000|270,000|275,000|280,000|290,000|300,000|310,000|320,000|325,000|330,000|340,000|350,000|360,000|370,000|375,000|380,000|390,000|400,000|410,000|420,000|425,000|430,000|440,000|450,000|460,000|470,000|475,000|480,000|490,000|500,000', ...
         'Value',DSGEModel.BurnInValue, ...
         'Tag','NumberBurnInPopup');
      %
      % inverse Hessian estimator
      %
      controls.posterior.invhessiantext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 435 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Method for estimating the inverse Hessian:', ...
         'Tag','InverseHessianEstimatorText');
      %
      controls.posterior.invhessian = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 440 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI invhessian', ...
         'String',['Output from optimization routine|Fit quadratic to evaluated log posterior|Finite difference|My estimate ("' GetName(DSGEModel.ParameterCovMatrix) '")'], ...
         'Value',DSGEModel.InverseHessianEstimator, ...
         'Tag','InverseHessianEstimatorPopup');
      %
      % maximum correlation for the inverse Hessian estimator
      %
      controls.posterior.maxcorrelationtext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 407 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Maximum absolute correlation for inverse Hessian estimator:', ...
         'Tag','MaximumCorrelationText');
      %
      controls.posterior.maxcorrelation = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 412 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI maxhesscorrelation', ...
         'String','No restriction|0.95|0.90|0.85|0.80|0.75|0.70|0.65|0.60|0.55|0.50|0.45|0.40|0.35|0.30|0.25|0.20|0.15|0.10|0.05|0.00', ...
         'Value',DSGEModel.MaxCorrelationValue, ...
         'Tag','MaximumCorrelationPopup');
      %
      % Scale factor for initialization of random walk Metropolis
      %
      controls.posterior.initialscaletext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 379 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Scale factor for initializing the random walk Metropolis algorithm:', ...
         'Tag','InitialScaleFactorText');
      %
      controls.posterior.initialscale = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 384 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI initialscalefactor', ...
         'String','0.00|0.01|0.02|0.03|0.04|0.05|0.06|0.07|0.08|0.09|0.10|0.11|0.12|0.13|0.14|0.15|0.16|0.17|0.18|0.19|0.20|0.21|0.22|0.23|0.24|0.25|0.26|0.27|0.28|0.29|0.30|0.31|0.32|0.33|0.34|0.35|0.36|0.37|0.38|0.39|0.40|0.41|0.42|0.43|0.44|0.45|0.46|0.47|0.48|0.49|0.50|0.51|0.52|0.53|0.54|0.55|0.56|0.57|0.58|0.59|0.60|0.61|0.62|0.63|0.64|0.65|0.66|0.67|0.68|0.69|0.70|0.71|0.72|0.73|0.74|0.75|0.76|0.77|0.78|0.79|0.80|0.81|0.82|0.83|0.84|0.85|0.86|0.87|0.88|0.89|0.90|0.91|0.92|0.93|0.94|0.95|0.96|0.97|0.98|0.99|1.00|1.05|1.10|1.15|1.20|1.25|1.30|1.35|1.40|1.45|1.50|1.55|1.60|1.65|1.70|1.75|1.80|1.85|1.90|1.95|2.00|2.05|2.10|2.15|2.20|2.25|2.30|2.35|2.40|2.45|2.50|2.55|2.60|2.65|2.70|2.75|2.80|2.85|2.90|2.95|3.00|3.05|3.10|3.15|3.20|3.25|3.30|3.35|3.40|3.45|3.50|3.55|3.60|3.65|3.70|3.75|3.80|3.85|3.90|3.95|4.00', ...
         'Value',DSGEModel.MHInitialScaleFactor, ...
         'Tag','InitialScaleFactorPopup');
      %
      % Scale factor for the random walk Metropolis algorithm
      %
      controls.posterior.scalefactortext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 351 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Scale factor for the random walk Metropolis algorithm:', ...
         'Tag','ScaleFactorText');
      %
      controls.posterior.scalefactor = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 356 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI scalefactor', ...
         'String','0.05|0.06|0.07|0.08|0.09|0.10|0.11|0.12|0.13|0.14|0.15|0.16|0.17|0.18|0.19|0.20|0.21|0.22|0.23|0.24|0.25|0.26|0.27|0.28|0.29|0.30|0.31|0.32|0.33|0.34|0.35|0.36|0.37|0.38|0.39|0.40|0.41|0.42|0.43|0.44|0.45|0.46|0.47|0.48|0.49|0.50|0.51|0.52|0.53|0.54|0.55|0.56|0.57|0.58|0.59|0.60|0.61|0.62|0.63|0.64|0.65|0.66|0.67|0.68|0.69|0.70|0.71|0.72|0.73|0.74|0.75|0.76|0.77|0.78|0.79|0.80|0.81|0.82|0.83|0.84|0.85|0.86|0.87|0.88|0.89|0.90|0.91|0.92|0.93|0.94|0.95|0.96|0.97|0.98|0.99|1.00|1.05|1.10|1.15|1.20|1.25|1.30|1.35|1.40|1.45|1.50|1.55|1.60|1.65|1.70|1.75|1.80|1.85|1.90|1.95|2.00|2.05|2.10|2.15|2.20|2.25|2.30|2.35|2.40|2.45|2.50|2.55|2.60|2.65|2.70|2.75|2.80|2.85|2.90|2.95|3.00|3.05|3.10|3.15|3.20|3.25|3.30|3.35|3.40|3.45|3.50|3.55|3.60|3.65|3.70|3.75|3.80|3.85|3.90|3.95|4.00', ...
         'Value',DSGEModel.MHScaleFactor, ...
         'Tag','ScaleFactorPopup');
      %
      % Weight on randomization when initial values are generated under several chains. A zero value means that the
      % posterior mode is given full weight. A value of 1, means that initial values are drawn "completely" random.
      %
      controls.posterior.randomweighttext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 323 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Weight on randomization for initial values (multiple chains):', ...
         'Tag','RandomizationWeightText');
      %
      controls.posterior.randomweight = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 328 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI randomweight', ...
         'String','0.00|0.05|0.10|0.15|0.20|0.25|0.30|0.35|0.40|0.45|0.50|0.55|0.60|0.65|0.70|0.75|0.80|0.85|0.90|0.95|1.00', ...
         'Value',DSGEModel.RandomWeightValue, ...
         'Tag','ScaleFactorPopup');
      %
      % percent draws from posterior to use for prediction
      %
      controls.posterior.postdrawsusagetext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 295 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Maximum number of posterior draws to use for prediction:', ...
         'Tag','PostDrawsUsageText');
      %
      controls.posterior.postdrawsusage = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 300 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI postdrawsusage', ...
         'String','100|200|300|400|500|600|700|800|900|1,000|1,500|2,000|2,500|3,000|3,500|4,000|4,500|5,000|6,000|7,000|8,000|9,000|10,000|11,000|12,000|13,000|14,000|15,000|16,000|17,000|18,000|19,000|20,000|25,000|30,000|35,000|40,000|45,000|50,000', ...
         'Value',DSGEModel.PostDrawsUsageValue, ...
         'Tag','PostDrawsUsagePopup');
      %
      % percent draws from posterior to use for prediction, etc.
      %
      controls.posterior.usepostdrawstext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 267 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Percentage use of posterior draws for impulse responses, etc.:', ...
         'Tag','UsePostDrawsText');
      %
      controls.posterior.usepostdraws = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 272 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI usepostdraws', ...
         'String','0.1%|0.2%|0.3%|0.4%|0.5%|0.6%|0.7%|0.8%|0.9%|1%|2%|3%|4%|5%|6%|7%|8%|9%|10%|11%|12%|13%|14%|15%|16%|17%|18%|19%|20%|21%|22%|23%|24%|25%|26%|27%|28%|29%|30%|31%|32%|33%|34%|35%|36%|37%|38%|39%|40%|41%|42%|43%|44%|45%|46%|47%|48%|49%|50%|51%|52%|53%|54%|55%|56%|57%|58%|59%|60%|61%|62%|63%|64%|65%|66%|67%|68%|69%|70%|71%|72%|73%|74%|75%|76%|77%|78%|79%|80%|81%|82%|83%|84%|85%|86%|87%|88%|89%|90%|91%|92%|93%|94%|95%|96%|97%|98%|99%|100%', ...
         'Value',DSGEModel.PostDrawsPercentValue, ...
         'Tag','UsePostDrawsPopup');
      %
      % The optimization axes box
      %
      controls.optimizationbox = AxesBox([28 48 644 193],'Optimization',75,[0.5 1],'off',CurrINI);
      %
      % Optimization routine
      %
      controls.optimize.maxroutinetext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 200 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Posterior maximization algorithm:', ...
         'Tag','MaximizationAlgorithmText');
      %
      controls.optimize.maxroutine = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 205 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI maxroutine', ...
         'String','Christopher Sims'' csminwel|Matlab''s fminunc', ...
         'Value',DSGEModel.MaximizeAlgorithmValue, ...
         'Tag','MaximizationAlgorithmPopup');
      %
      if FileExist([pwd '\optim\fmin\matlab7\YADAfminunc7.m'])==0;
         DSGEModel.MaximizeAlgorithmValue = 1;
         set(controls.optimize.maxroutinetext,'Enable','off');
         set(controls.optimize.maxroutine,'Enable','off','Value',DSGEModel.MaximizeAlgorithmValue);
      end;
      %
      % Tolerance level
      %
      controls.optimize.tolerancetext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 172 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Tolerance level:', ...
         'Tag','ToleranceText');
      %
      controls.optimize.tolerance = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 177 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI tolerance', ...
         'String','0.01|0.001|0.0001|0.00001|0.000001|0.0000001|0.00000001|0.000000001|0.0000000001|0.00000000001', ...
         'Value',DSGEModel.OptToleranceValue, ...
         'Tag','TolerancePopup');
      %
      % maximum number of iterations
      %
      controls.optimize.maximumiterationstext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 144 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Maximum number of iterations:', ...
         'Tag','MaxIterationsText');
      %
      controls.optimize.maximumiterations = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 149 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI maximumiterations', ...
         'String','1,000|5,000|10,000|50,000|100,000|500,000|1,000,000|5,000,000|10,000,000|50,000,000|100,000,000|500,000,000|1,000,000,000', ...
         'Value',DSGEModel.OptMaxIterationsValue, ...
         'Tag','MaxIterationsPopup');
      %
      % Initialization of Hessian for csminwel
      %
      if (exist('YADAbetarnd')~=2)|(exist('betarnd')~=2);
         AddInvHessianStr = '';
      else;
         AddInvHessianStr = '|Diagonal matrix using draws from prior';
      end;
      controls.optimize.initcsminweltext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 116 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Method for initializing inverse Hessian (csminwel only):', ...
         'Tag','InitialHessianCSMinWelText');
      %
      controls.optimize.initcsminwel = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 121 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI initcsminwel', ...
         'String',['10 times identity matrix|Identity matrix|0.1 times identity matrix|0.01 times identity matrix|0.001 times identity matrix|0.0001 times identity matrix|0.00001 times identity matrix' AddInvHessianStr], ...
         'Value',DSGEModel.InitializeHessian, ...
         'Tag','InitialHessianCSMinWelPopup');
      %
      % grid width for checking the optimum
      %
      controls.optimize.gridwidthtext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 88 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Grid width when checking the optimum:', ...
         'Tag','GridWidthText');
      %
      controls.optimize.gridwidth = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 93 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI gridwidth', ...
         'String','+/-1 standard deviation|+/-2 standard deviations|+/-3 standard deviations|+/-4 standard deviations|+/-5 standard deviations', ...
         'Value',DSGEModel.GridWidth, ...
         'Tag','GridWidthPopup');
      %
      controls.optimize.numbergridpointstext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 60 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Number of points in grid when checking the optimum:', ...
         'Tag','NumberOfGridPointsText');
      %
      controls.optimize.numbergridpoints = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 65 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI numbergridpoints', ...
         'String','10|15|20|25|30|35|40|45|50|55|60|65|70|75|80|85|90|95|100', ...
         'Value',DSGEModel.NumberOfGridPoints, ...
         'Tag','NumberOfGridPointsPopup');
      %
      % Controls on the Miscellaneous tab
      %
      controls.forecastbox = AxesBox([28 442 644 148],'Forecasting',50,[0.5 1],'off',CurrINI);
      %
      % Max forecast horizon
      %
      controls.forecast.maxhorizontext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 545 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Maximum forecast horizon:', ...
         'Tag','MaximumForecastHorizonText');
      %
      ForecastStr.annual = '1 year|2 years|3 years|4 years|5 years|6 years|7 years|8 years|9 years|10 years|11 years|12 years|13 years|14 years|15 years|16 years|17 years|18 years|19 years|20 years';
      ForecastStr.month = '1 month';
      for i=2:240;
         ForecastStr.month = [ForecastStr.month '|' int2str(i) ' months'];
      end;
      ForecastStr.quarter = '1 quarter';
      for i=2:80;
         ForecastStr.quarter = [ForecastStr.quarter '|' int2str(i) ' quarters'];
      end;
      %
      controls.forecast.maxhorizon = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 550 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI maxforecasthorizon', ...
         'UserData',ForecastStr, ...
         'String',ForecastStr.annual, ...
         'Value',DSGEModel.MaxForecastHorizon, ...
         'Tag','MaximumForecastHorizonPopup');
      %
      if strcmp(lower(DSGEModel.DataFrequency),'q')==1;
         set(controls.forecast.maxhorizon,'String',ForecastStr.quarter);
      elseif strcmp(lower(DSGEModel.DataFrequency),'m')==1;
         set(controls.forecast.maxhorizon,'String',ForecastStr.month);
      end;
      %
      % number of prediction paths per parameter value
      %
      controls.forecast.predpathstext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 516 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Number of observed variables paths per parameter value:', ...
         'Tag','NumberPredictionPathsText');
      %
      controls.forecast.predpaths = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 521 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI predpaths', ...
         'String','100 paths|200 paths|300 paths|400 paths|500 paths|600 paths|700 paths|800 paths|900 paths|1,000 paths|1,500 paths|2,000 paths|2,500 paths|3,000 paths|3,500 paths|4,000 paths|4,500 paths|5,000 paths|6,000 paths|7,000 paths|8,000 paths|9,000 paths|10,000 paths|11,000 paths|12,000 paths|13,000 paths|14,000 paths|15,000 paths|16,000 paths|17,000 paths|18,000 paths|19,000 paths|20,000 paths|22,500 paths|25,000 paths|27,500 paths|30,000 paths|32,500 paths|35,000 paths|37,500 paths|40,000 paths|42,500 paths|45,000 paths|47,500 paths|50,000 paths|55,000 paths|60,000 paths|65,000 paths|70,000 paths|75,000 paths|80,000 paths|85,000 paths|90,000 paths|95,000 paths|100,000 paths|105,000 paths|110,000 paths|115,000 paths|120,000 paths|125,000 paths|130,000 paths|135,000 paths|140,000 paths|145,000 paths|150,000 paths|155,000 paths|160,000 paths|165,000 paths|170,000 paths|175,000 paths|180,000 paths|185,000 paths|190,000 paths|195,000 paths|200,000 paths|205,000 paths|210,000 paths|215,000 paths|220,000 paths|225,000 paths|230,000 paths|235,000 paths|240,000 paths|245,000 paths|250,000 paths|255,000 paths|260,000 paths|265,000 paths|270,000 paths|275,000 paths|280,000 paths|285,000 paths|290,000 paths|295,000 paths|300,000 paths|305,000 paths|310,000 paths|315,000 paths|320,000 paths|325,000 paths|330,000 paths|335,000 paths|340,000 paths|345,000 paths|350,000 paths|355,000 paths|360,000 paths|365,000 paths|370,000 paths|375,000 paths|380,000 paths|385,000 paths|390,000 paths|395,000 paths|400,000 paths|405,000 paths|410,000 paths|415,000 paths|420,000 paths|425,000 paths|430,000 paths|435,000 paths|440,000 paths|445,000 paths|450,000 paths|455,000 paths|460,000 paths|465,000 paths|470,000 paths|475,000 paths|480,000 paths|485,000 paths|490,000 paths|495,000 paths|500,000 paths|510,000 paths|520,000 paths|530,000 paths|540,000 paths|550,000 paths|560,000 paths|570,000 paths|580,000 paths|590,000 paths|600,000 paths|610,000 paths|620,000 paths|630,000 paths|640,000 paths|650,000 paths|660,000 paths|670,000 paths|680,000 paths|690,000 paths|700,000 paths|710,000 paths|720,000 paths|730,000 paths|740,000 paths|750,000 paths|760,000 paths|770,000 paths|780,000 paths|790,000 paths|800,000 paths|810,000 paths|820,000 paths|830,000 paths|840,000 paths|850,000 paths|860,000 paths|870,000 paths|880,000 paths|890,000 paths|900,000 paths|910,000 paths|920,000 paths|930,000 paths|940,000 paths|950,000 paths|960,000 paths|970,000 paths|980,000 paths|990,000 paths|1,000,000 paths', ...
         'Value',DSGEModel.NumPredPathsValue, ...
         'Tag','NumberPredictionPathsPopup');
      %
      % method for controlling shocks in conditional forecasting
      %
      controls.forecast.shockcontroltext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 487 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','off', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Method for controlling conditional forecasts:', ...
         'Tag','ShockControlMethodText');
      %
      controls.forecast.shockcontrol = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 492 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','off', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI shockcontrol', ...
         'String','Values for shocks|Distribution of shocks (Waggoner-Zha)', ...
         'Value',DSGEModel.ShockControlMethod, ...
         'Tag','ShockControlMethodPopup');
      %
      % check if we should enable controls
      %
      if FileExist([pwd '\addons\wz\DSGECondPredictionPathsWZ.m'])==1;
         set(controls.forecast.shockcontroltext,'Enable','on');
         set(controls.forecast.shockcontrol,'Enable','on');
      end;
      %
      % How frequently should the parameters be updated when forecasting
      %
%      controls.forecast.freqreesttext = uicontrol('Units','pixels', ...
%         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
%         'Position',[44 487 312 20], ...
%         'FontSize',CurrINI.gui_fontsize, ...
%         'FontName',CurrINI.gui_fontname, ...
%         'FontWeight',CurrINI.gui_fontweight, ...
%         'FontAngle',CurrINI.gui_fontangle, ...
%         'Style','text', ...
%         'Enable','on', ...
%         'Visible','off', ...
%         'HorizontalAlignment','left', ...
%         'String','Frequency of parameter re-estimation:', ...
%         'Tag','FrequencyParameterReestimationText');
      %
%      controls.forecast.freqreest = uicontrol('Units','pixels', ...
%         'BackgroundColor',[1 1 1], ...
%         'Position',[356 492 250 20], ...
%         'FontSize',CurrINI.gui_fontsize, ...
%         'FontName',CurrINI.gui_fontname, ...
%         'FontWeight',CurrINI.gui_fontweight, ...
%         'FontAngle',CurrINI.gui_fontangle, ...
%         'Style','popup', ...
%         'Enable','on', ...
%         'Visible','off', ...
%         'HorizontalAlignment','left', ...
%         'Callback','YADAGUI freqreest', ...
%         'String','1 period|2 periods|3 periods|4 periods|5 periods|6 periods|7 periods|8 periods|9 periods|10 periods|11 periods|12 periods|13 periods|14 periods|15 periods|16 periods|17 periods|18 periods|19 periods|20 periods|21 periods|22 periods|23 periods|24 periods|25 periods|26 periods|27 periods|28 periods|29 periods|30 periods', ...
%         'Value',DSGEModel.FreqParameterReest, ...
%         'Tag','FrequencyParameterReestimationPopup');

      %
      % controls for automatically adjusting sample means for prediction to population means
      %
      controls.forecast.adjustpredictionpaths = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[44 458 362 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI checkadjustpredictionpaths', ...
            'String','Adjust prediction paths (sample mean = population mean)', ...
            'Value',DSGEModel.AdjustPredictionPaths, ...
            'Enable','on', ...
            'Tag','AdjustPredictionPathsCheckBox');
      %
      % use conditioning data for smooth estimation of time T state
      %
      controls.forecast.ksiuseconddata = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[406 458 250 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI checkksiuseconddata', ...
            'String','Use conditioning data for state distribution', ...
            'Value',DSGEModel.KsiUseCondData, ...
            'Enable','off', ...
            'Tag','KsiUseCondDataCheckBox');
      %
      if FileExist([pwd '\addons\wz\CondPredictionKalmanSmoother.m'])==1;
         set(controls.forecast.ksiuseconddata,'Enable','on');
      end;
      %
      % The tools axes box
      %
      controls.toolsbox = AxesBox([28 180 644 248],'Tools',50,[0.5 1],'off',CurrINI);
      %
      % maximum number of iterations for the Riccati solver when calculating the
      % forecast error variance decompositions.
      %
      controls.tools.riccatiiterationtext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 383 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Maximum number of iterations for the Riccati solver:', ...
         'Tag','RiccatiIterationText');
      %
      controls.tools.riccatiiteration = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 388 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI riccati_maximumiterations', ...
         'String','1,000|2,000|3,000|4,000|5,000|6,000|7,000|8,000|9,000|10,000|11,000|12,000|13,000|14,000|15,000|16,000|17,000|18,000|19,000|20,000|21,000|22,000|23,000|24,000|25,000', ...
         'Value',DSGEModel.RiccatiMaxIterations, ...
         'Tag','RiccatiIterationsPopup');
      %
      % Tolerance value for the Riccati solver when calculating the
      % forecast error variance decompositions
      %
      controls.tools.riccatitolerancetext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 354 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Tolerance value for the Riccati solver:', ...
         'Tag','RiccatiToleranceValueText');
      %
      controls.tools.riccatitolerance = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 359 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI riccati_tolerance', ...
         'String','0.01|0.001|0.0001|0.00001|0.000001|0.0000001|0.00000001|0.000000001|0.0000000001|0.00000000001', ...
         'Value',DSGEModel.RiccatiToleranceValue, ...
         'Tag','RiccatiToleranceValuePopup');
      %
      % Impulse response horizon
      %
      controls.tools.irhorizontext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 325 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Length of impulse response function horizon:', ...
         'Tag','IRHorizonText');
      %
      ir_str = '1 year';
      for i=2:50;
         ir_str = [ir_str '|' num2str(i,'%0.0f') ' years'];
      end;
      controls.tools.irhorizon = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 330 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI irhorizon', ...
         'String',ir_str, ...
         'Value',DSGEModel.IRHorizon, ...
         'Tag','IRHorizonPopup');
      %
      % step length for inverse hessian
      %
      controls.optimize.steplengthtext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 296 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Step length for finite difference approx. of inverse Hessian:', ...
         'Tag','StepLengthHessianText');
      %
      controls.optimize.steplength = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 301 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI hessiansteplength', ...
         'String','0.0001|0.001|0.01|0.02|0.03|0.04|0.05|0.06|0.07|0.08|0.09|0.10|0.15|0.20|0.25|0.30|0.35|0.40|0.45|0.50|0.55|0.60|0.65|0.70|0.75|0.80|0.85|0.90|0.95|1.00', ...
         'Value',DSGEModel.StepLengthHessian, ...
         'Tag','StepLengthHessianPopup');
      %
      % Option to check the optimum
      %
      controls.optimize.checkoptimum = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[44 265 360 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI checkoptimum', ...
            'String','Check the optimum', ...
            'Value',DSGEModel.CheckOptimum, ...
            'Enable','on', ...
            'Tag','CheckOptimumCheckBox');
      %
      % check optimum for transformed only [44 64 310 20], [356 64 250 20]
      %
      controls.optimize.checktransformed = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[406 265 250 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI checktransformedoptimum', ...
            'String','Check only for transformed parameters', ...
            'Value',DSGEModel.CheckTransformedOptimum, ...
            'Enable','on', ...
            'Tag','CheckTransformedOptimumCheckBox');
      %
      % check box for transforming the conditional modified Hessian estimates
      % to unconditional estimates
      %
      controls.optimize.modifiedhessian = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[44 241.667 612 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI checkmodifiedhessian', ...
            'String','Transform conditional standard deviations for modified Hessian to marginal using correlations from Hessian', ...
            'Value',DSGEModel.ModifiedHessian, ...
            'Enable','on', ...
            'Tag','FiniteDifferenceHessianCheckBox');
      %
      if DSGEModel.CheckOptimum==0;
         set(controls.optimize.gridwidth,'Enable','off');
         set(controls.optimize.gridwidthtext,'Enable','off');
         set(controls.optimize.numbergridpoints,'Enable','off');
         set(controls.optimize.numbergridpointstext,'Enable','off');
         set(controls.optimize.checktransformed,'Enable','off');
         set(controls.optimize.modifiedhessian,'Enable','off');
      end;
      %
      % check box for dealing with the random number generator
      %
      controls.tools.randomnumber = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[44 218.333 362 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI randomnumbervalue', ...
            'String','Use fixed state to initialize random number generators', ...
            'Value',DSGEModel.RandomNumberValue, ...
            'Enable','on', ...
            'Tag','RandomNumberCheckBox');
      %
      controls.tools.randomizedraws = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[406 218.333 250 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI randomizedraws', ...
            'String','Randomize draws from posterior distribution', ...
            'Value',DSGEModel.RandomizeDraws, ...
            'Enable','on', ...
            'Tag','RandomizeDrawsCheckBox');
      %
      % Option to compute posterior standard deviations using finite difference methods
      %
      controls.optimize.finitediffhessian = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[44 195 522 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI finitediffhessian', ...
            'String','Compute posterior standard deviations from inverse Hessian using finite differences', ...
            'Value',DSGEModel.FiniteDifferenceHessian, ...
            'Enable','on', ...
            'Tag','FiniteDifferenceHessianCheckBox');
      %
      % kernel density estimation controls
      %
      controls.kerneldensitybox = AxesBox([28 48 644 118],'Kernel Density Estimation',75,[0.5 1],'off',CurrINI);
      %
      % selection of kernel density estimator for the posterior
      %
      controls.graphics.posteriorkerneltext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 123 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Select kernel density estimator for the posterior density:', ...
         'Tag','PosteriorKernelDensityText');
      %
      controls.graphics.posteriorkernel = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 128 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI posteriorkerneldensity', ...
         'String','Gaussian|Silverman-type and Sköld-Roberts correction|Sheather-Jones bandwidth|Bump killing bandwidth', ...
         'Value',DSGEModel.PosteriorDensityValue, ...
         'Tag','PosteriorKernelDensityPopup');
      %
      % Selection of Kernel density estimator for the prior
      %
      controls.graphics.kerneldensitytext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 94 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','off', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Select kernel density estimator for the prior density:', ...
         'Tag','KernelDensityText');
      %
      controls.graphics.kerneldensity = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 99 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','off', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI kerneldensity', ...
         'String','Normal kernel|Epanechnikov kernel|Rectangular kernel|Triangular kernel|Bi-weight kernel|Tri-weight kernel|Laplace kernel|Logistic kernel', ...
         'Value',DSGEModel.KernelDensityValue, ...
         'Tag','KernelDensityPopup');
      %
      % Show Kernel density estimates of the prior distribution instead of grid density PriorKernel
      %
      controls.graphics.priorkernel = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[44 64 522 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI priorkernel', ...
            'String','Compute kernel density estimates of prior densities instead of grid density estimates', ...
            'Value',DSGEModel.PriorKernel, ...
            'Enable','on', ...
            'Tag','PriorKernelCheckBox');
      %
      % check if statistics toolbox is available
      %
      if (exist('YADAbetarnd')~=2)|(exist('betarnd')~=2);
         DSGEModel.PriorKernel = 0;
         set(controls.graphics.priorkernel,'Enable','off','Value',DSGEModel.PriorKernel);
      end;
      %
      if DSGEModel.PriorKernel==1;
         set(controls.graphics.kerneldensitytext,'Enable','on');
         set(controls.graphics.kerneldensity,'Enable','on');
      end;
      %
      % Controls on the VAR tab
      %
      controls.steadystatebox = AxesBox([28 508 644 82],'Prior - Steady State Parameters',75,[0.5 1],'off',CurrINI);
      %
      % the text control for selecting the file with the steady state prior
      %
      controls.bvar.steadystatefiletext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 555 522 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Steady state parameter prior file:', ...
         'Tag','SteadyStateFileText');
      %
      % the edit box for the steady state prior file
      %
      controls.bvar.steadystatefile = uicontrol('Units','pixels', ...
            'BackgroundColor',[1 1 1], ...
            'Position',[44 531 522 25], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','edit', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI checksteadystatefile', ...
            'String',DSGEModel.SteadyStatePriorFile, ...
            'Enable','on', ...
            'Tag','SteadyStateFileEditBox');
      %
      % browse for the steady state prior file
      %
      controls.bvar.steadystatefilebutton = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[576 531 80 25], ...
         'TooltipString','Browse', ...
         'Visible','off', ...
         'CData',ButtonImages.browse, ...
         'Callback','YADAGUI browsesteadystatefile', ...
         'Enable','on', ...
         'Tag','SteadyStateFileButton');
      %
      % Box for prior for parameters on lagged variables
      %
      controls.bvarpriorbox = AxesBox([28 287 644 207],'Prior - Parameters on Lags',75,[0.5 1],'off',CurrINI);
      %
      % Prior type
      %
      controls.bvar.priortypetext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 449 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Prior type:', ...
         'Tag','PriorTypeText');
      %
      controls.bvar.priortype = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 454 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI priortype', ...
         'String','Minnesota-style|Normal conditional on covariance matrix|Diffuse', ...
         'Value',DSGEModel.PriorType, ...
         'Tag','PriorTypePopup');
      %
      % Prior mean for parameters on own first lag for levels variables
      %
      controls.bvar.priorlevelmeantext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 420 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Prior mean for own first lag parameter on levels variables:', ...
         'Tag','PriorLevelMeanText');
      %
      controls.bvar.priorlevelmean = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 425 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI priorlevelmean', ...
         'String','0.00|0.05|0.10|0.15|0.20|0.30|0.35|0.40|0.45|0.50|0.55|0.60|0.65|0.70|0.75|0.80|0.85|0.90|0.95', ...
         'Value',DSGEModel.PriorLevelMeanValue, ...
         'Tag','PriorLevelMeanPopup');
      %
      % Prior mean for parameters on own first lag for first difference
      %
      controls.bvar.priordiffmeantext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 391 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Prior mean for own first lag parameter on first diff variables:', ...
         'Tag','PriorDiffMeanText');
      %
      controls.bvar.priordiffmean = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 396 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI priordiffmean', ...
         'String','0.00|0.05|0.10|0.15|0.20|0.30|0.35|0.40|0.45|0.50|0.55|0.60|0.65|0.70|0.75|0.80|0.85|0.90|0.95', ...
         'Value',DSGEModel.PriorDiffMeanValue, ...
         'Tag','PriorDiffMeanPopup');
      %
      % Overall tightness
      %
      controls.bvar.overalltightnesstext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 362 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Overall tightness hyperparameter:', ...
         'Tag','OverallTightnessText');
      %
      controls.bvar.overalltightness = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 367 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI overalltightness', ...
         'String','0.05|0.10|0.15|0.20|0.25|0.30|0.35|0.40|0.45|0.50|0.55|0.60|0.65|0.70|0.75|0.80|0.85|0.90|0.95|1.00|1.10|1.20|1.30|1.40|1.50|1.60|1.70|1.80|1.90|2.00|2.-10|2.20|2.30|2.40|2.50|2.70|2.80|2.90|3.00|3.10|3.20|3.30|3.40|3.50|3.60|3.70|3.80|3.90|4.00|4.10|4.20|4.30|4.40|4.50|4.60|4.70|4.80|4.90|5.00', ...
         'Value',DSGEModel.OverallTightnessValue, ...
         'Tag','OverallTightnessPopup');
      %
      % Cross-equation tightness
      %
      controls.bvar.crosseqtightnesstext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 333 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Cross-equation tightness hyperparameter:', ...
         'Tag','CrossEquationTightnessText');
      %
      controls.bvar.crosseqtightness = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 338 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI crossequationtightness', ...
         'String','0.05|0.10|0.15|0.20|0.25|0.30|0.35|0.40|0.45|0.50|0.55|0.60|0.65|0.70|0.75|0.80|0.85|0.90|0.95', ...
         'Value',DSGEModel.CrossEqTightnessValue, ...
         'Tag','CrossEquationTightnessPopup');
      %
      % Harmonic lag decay parameter
      %
      controls.bvar.harmoniclagdecaytext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 304 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Harmonic lag decay hyperparameter:', ...
         'Tag','HarmonicLagDecayText');
      %
      controls.bvar.harmoniclagdecay = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 309 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI harmoniclagdecay', ...
         'String','0.5|1.0|1.5|2.0|2.5|3.0|3.5|4.0|4.5|5.0|5.5|6.0', ...
         'Value',DSGEModel.HarmonicLagDecayValue, ...
         'Tag','HarmonicLagDecayPopup');
      %
      if DSGEModel.PriorType==3;
         set(controls.bvar.priorlevelmeantext,'Enable','off');
         set(controls.bvar.priorlevelmean,'Enable','off');
         set(controls.bvar.priordiffmeantext,'Enable','off');
         set(controls.bvar.priordiffmean,'Enable','off');
         set(controls.bvar.overalltightnesstext,'Enable','off');
         set(controls.bvar.overalltightness,'Enable','off');
         set(controls.bvar.crosseqtightnesstext,'Enable','off');
         set(controls.bvar.crosseqtightness,'Enable','off');
         set(controls.bvar.harmoniclagdecaytext,'Enable','off');
         set(controls.bvar.harmoniclagdecay,'Enable','off');
      end;
      %
      % Box for Omega prior
      %
      controls.omegapriorbox = AxesBox([28 124 644 149],'Prior - Covariance Parameters',75,[0.5 1],'off',CurrINI);
      %
      controls.bvar.omegapriortypetext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 228 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Prior type:', ...
         'Tag','OmegaPriorTypeText');
      %
      controls.bvar.omegapriortype = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 233 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI omegapriortype', ...
         'String','Diffuse|Inverse Wishart', ...
         'Value',DSGEModel.OmegaPriorType, ...
         'Tag','OmegaPriorTypePopup');
      %
      % A matrix determination
      %
      controls.bvar.wisharttypetext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 199 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','off', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Wishart distribution parameterization format:', ...
         'Tag','WishartTypeText');
      %
      controls.bvar.wisharttype = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 204 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','off', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI wisharttype', ...
         'String','ML estimate of covariance matrix as A|Identity times variance tightness as A', ...
         'Value',DSGEModel.WishartType, ...
         'Tag','WishartTypePopup');
      %
      % Variance tightness hyperparameter
      %
      controls.bvar.variancetightnesstext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 170 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','off', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Variance tightness hyperparameter:', ...
         'Tag','VarianceTightnessText');
      %
      controls.bvar.variancetightness = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 175 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','off', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI variancetightness', ...
         'String','0.05|0.10|0.15|0.20|0.25|0.30|0.35|0.40|0.45|0.50|0.55|0.60|0.65|0.70|0.75|0.80|0.85|0.90|0.95|1.00|1.10|1.20|1.30|1.40|1.50|1.60|1.70|1.80|1.90|2.00|2.25|2.50|2.75|3.00|3.25|3.50|3.75|4.00|4.25|4.50|4.75|5.00|5.25|5.50|5.75|6.00|6.25|6.50|6.75|7.00|7.25|7.50|7.75|8.00|8.25|8.50|8.75|9.00|9.25|9.50|9.75|10.00|11.50|12.00|12.50|13.00|13.50|14.00|14.50|15.00|15.50|16.00|16.50|17.00|17.50|18.00|18.50|19.00|19.50|20.00|21.00|22.00|23.00|24.00|25.00|26.00|27.00|28.00|29.00|30.00|35.00|40.00|45.00|50.00|55.00|60.00|65.00|70.00|75.00|80.00|85.00|90.00|95.00|100.00', ...
         'Value',DSGEModel.VarianceTightnessValue, ...
         'Tag','VarianceTightnessPopup');
      %
      % Degrees of freedom hyperparameter
      %
      controls.bvar.wishartdftext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 141 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','off', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Degrees of freedom:', ...
         'Tag','WishartDFText');
      %
      controls.bvar.wishartdf = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 146 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','off', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI wishartdf', ...
         'String','Number of endogenous variables + 2|Number of endogenous variables + 3|Number of endogenous variables + 4|Number of endogenous variables + 5|Number of endogenous variables + 6|Number of endogenous variables + 7|Number of endogenous variables + 8|Number of endogenous variables + 9|Number of endogenous variables + 10|Number of endogenous variables + 11|Number of endogenous variables + 12|Number of endogenous variables + 13|Number of endogenous variables + 14|Number of endogenous variables + 15|Number of endogenous variables + 16|Number of endogenous variables + 17|Number of endogenous variables + 18|Number of endogenous variables + 19|Number of endogenous variables + 20', ...
         'Value',DSGEModel.WishartDFValue, ...
         'Tag','WishartDFPopup');
      %
      % Enable entries that should be
      %
      if DSGEModel.OmegaPriorType==2;
         set(controls.bvar.wisharttypetext,'Enable','on');
         set(controls.bvar.wisharttype,'Enable','on');
         set(controls.bvar.wishartdftext,'Enable','on');
         set(controls.bvar.wishartdf,'Enable','on');
         if DSGEModel.WishartType==2;
            set(controls.bvar.variancetightnesstext,'Enable','on');
            set(controls.bvar.variancetightness,'Enable','on');
         end;
      end;
      %
      %
      % Box for lag order selection
      %
      controls.bvarlagbox = AxesBox([28 48 644 62],'Lag Order Selection',75,[0.5 1],'off',CurrINI);
      %
      % Lag order selection
      %
      controls.bvar.lagtext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 65 362 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Lag order of the VAR model:', ...
         'Tag','BVARLagsText');
      %
      controls.bvar.lag = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[406 70 250 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'Callback','YADAGUI bvarlags', ...
         'String','1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20', ...
         'Value',DSGEModel.BVARLags, ...
         'Tag','BVARLagsPopup');
      %
      %
      % Controls on the Output tab
      %
      % the output selection axes box
      %
      controls.outputselect = AxesBox([28 515 644 75],'Output Selection',84,[0.5 1],'off',CurrINI);
      %
      controls.outputdirtext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[44 555 522 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'Enable','off', ...
         'Visible','off', ...
         'HorizontalAlignment','left', ...
         'String','Base output directory:', ...
         'Tag','OutputFileText');
      %
      % the edit box for the output file
      %
      controls.outputdir = uicontrol('Units','pixels', ...
            'BackgroundColor',[1 1 1], ...
            'Position',[44 531 522 25], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','edit', ...
            'Visible','off', ...
            'HorizontalAlignment','left', ...
            'Callback','YADAGUI checkoutput', ...
            'String',DSGEModel.OutputDirectory, ...
            'Enable','off', ...
            'Tag','OutputFileEditBox');
      %
      % browse for the output file
      %
      controls.outputbutton = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[576 531 80 25], ...
         'TooltipString','Browse', ...
         'Visible','off', ...
         'CData',ButtonImages.browsedisable, ...
         'Callback','YADAGUI browseoutput', ...
         'Enable','off', ...
         'Tag','BrowseOutputButton');
      %
      % If AiM file exists we enable these controls
      %
      if FileExist(DSGEModel.AIMFile)==1;
         set(controls.outputdirtext,'Enable','on');
         set(controls.outputdir,'Enable','on');
         set(controls.outputbutton,'Enable','on','CData',ButtonImages.browse);
      end;
      %
      % the estimation axes box
      %
      controls.estimationlog = AxesBox([28 48 644 453],'Estimation Log',75,[0.5 1],'off',CurrINI);
      %
      % button to clear log window
      %
      controls.clearlogwindow = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[576 460 80 25], ...
         'TooltipString','Clear Log', ...
         'CData',ButtonImages.cleanup, ...
         'Visible','off', ...
         'Callback','YADAGUI clearlogwindow', ...
         'Enable','on', ...
         'Tag','ClearLogWindowButton');
      %
      % and the estimation log controls
      %
      controls.estimation_log = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[44 64 612 382], ...
         'FontSize',10, ...
         'FontName','FixedWidth', ...
         'Style','listbox', ...
         'Enable','inactive', ...
         'Visible','off', ...
         'UserData',1, ...
         'Min',0, ...
         'Max',2, ...
         'ListboxTop',1, ...
         'HorizontalAlignment','left', ...
         'String','', ...
         'Tag','EstimationLogListBox', ...
         'Value',[]);
      %
      % And finally we include a status bar
      %
      controls.status = StatusBar(CurrINI,'String',StatusStr,'Position',[2 2 698 16]);
      %
      % store all handles for the controls in the figures user data
      %
      set(maingui,'UserData',controls, ...
         'WindowButtonMotionFcn','ShowStatus', ...
         'HandleVisibility','callback');
   case 'tab'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % show and hide the various tabs
         %
         oldtab = get(controls.tab1,'UserData');
         newtab = get(gco,'Tag');
         newtab = strrep(newtab,'tab','');
         newtab = str2num(newtab);
         if abs(oldtab-newtab)>0;
            if (IsWinXP==1)&(MatlabNumber>=7);
               FixTabs(controls,oldtab,newtab);
            end;
            set(controls.tab1,'UserData',newtab);
            if newtab==1;
               %
               % DSGE Data tab
               %
               set(controls.frame3tab1,'Visible','off');
               set(controls.frame3tab2,'Visible','on');
               set(controls.frame3tab3,'Visible','on');
               set(controls.frame3tab4,'Visible','on');
               set(controls.frame3tab5,'Visible','on');
               set(controls.frame3tab6,'Visible','on');
               set(controls.frame1tab2,'Position',[118 594 102 11]);
               set(controls.frame1tab3,'Position',[221 594 102 11]);
               set(controls.frame1tab4,'Position',[324 594 102 11]);
               set(controls.frame1tab5,'Position',[427 594 102 11]);
               set(controls.frame1tab6,'Position',[530 594 102 11]);
               set(controls.tab1,'Position',[14 602 104 25]);
               set(controls.tab2,'Position',[118 602 102 23]);
               set(controls.tab3,'Position',[221 602 102 23]);
               set(controls.tab4,'Position',[324 602 102 23]);
               set(controls.tab5,'Position',[427 602 102 23]);
               set(controls.tab6,'Position',[530 602 102 23]);
               %
               set(controls.dsge.posteriorsamplingbox,'Visible','off');
               set(controls.dsge.marginallikelihoodtext,'Visible','off');
               set(controls.dsge.marginallikelihood,'Visible','off');
               set(controls.dsge.sequantialmltext,'Visible','off');
               set(controls.dsge.sequentialstart,'Visible','off');
               set(controls.dsge.sequentialstep,'Visible','off');
               set(controls.dsge.coverageprobtext,'Visible','off');
               set(controls.dsge.coveragestart,'Visible','off');
               set(controls.dsge.coverageincrement,'Visible','off');
               set(controls.dsge.coverageend,'Visible','off');
               set(controls.dsge.sequentialml,'Visible','off');
               set(controls.dsge.overwritedraws,'Visible','off');
               set(controls.dsge.progressbox,'Visible','off');
               set(controls.dsge.progress,'Visible','off');
               set(controls.dsge.progressclock,'Visible','off');
               set(controls.dsge.kalmanbox,'Visible','off');
               set(controls.dsge.doublingalgorithmtext,'Visible','off');
               set(controls.dsge.doublingalgorithm,'Visible','off');
               set(controls.dsge.doublingtolerancetext,'Visible','off');
               set(controls.dsge.doublingtolerance,'Visible','off');
               set(controls.dsge.statecovariancetext,'Visible','off');
               set(controls.dsge.statecovariance,'Visible','off');
               set(controls.dsge.initializekalmantext,'Visible','off');
               set(controls.dsge.initializekalman,'Visible','off');
               set(controls.dsge.aimtolerancetext,'Visible','off');
               set(controls.dsge.aimtolerance,'Visible','off');
               set(controls.dsge.usedoublingalgorithmtext,'Visible','off');
               set(controls.dsge.usedoublingalgorithm,'Visible','off');
               set(controls.dsge.useowninitialstate,'Visible','off');
               set(controls.dsge.allowunitroot,'Visible','off');
               set(controls.dsge.sampleselect,'Visible','off');
               set(controls.dsge.subsample,'Visible','off');
               set(controls.dsge.subbeginyear,'Visible','off');
               set(controls.dsge.subbeginperiod,'Visible','off');
               set(controls.dsge.subsampleseparator,'Visible','off');
               set(controls.dsge.subendyear,'Visible','off');
               set(controls.dsge.subendperiod,'Visible','off');
               %
               set(controls.posteriorsamplingbox,'Visible','off');
               set(controls.posterior.drawstext,'Visible','off');
               set(controls.posterior.draws,'Visible','off');
               set(controls.posterior.batchtext,'Visible','off');
               set(controls.posterior.batch,'Visible','off');
               set(controls.posterior.chainstext,'Visible','off');
               set(controls.posterior.chains,'Visible','off');
               set(controls.posterior.burnintext,'Visible','off');
               set(controls.posterior.burnin,'Visible','off');
               set(controls.posterior.invhessiantext,'Visible','off');
               set(controls.posterior.invhessian,'Visible','off');
               set(controls.posterior.maxcorrelationtext,'Visible','off');
               set(controls.posterior.maxcorrelation,'Visible','off');
               set(controls.posterior.initialscaletext,'Visible','off');
               set(controls.posterior.initialscale,'Visible','off');
               set(controls.posterior.scalefactortext,'Visible','off');
               set(controls.posterior.scalefactor,'Visible','off');
               set(controls.posterior.randomweighttext,'Visible','off');
               set(controls.posterior.randomweight,'Visible','off');
               set(controls.posterior.postdrawsusagetext,'Visible','off');
               set(controls.posterior.postdrawsusage,'Visible','off');
               set(controls.posterior.usepostdrawstext,'Visible','off');
               set(controls.posterior.usepostdraws,'Visible','off');
               set(controls.forecastbox,'Visible','off');
               set(controls.forecast.maxhorizontext,'Visible','off');
               set(controls.forecast.maxhorizon,'Visible','off');
%               set(controls.forecast.freqreesttext,'Visible','off');
%               set(controls.forecast.freqreest,'Visible','off');
               set(controls.forecast.predpathstext,'Visible','off');
               set(controls.forecast.predpaths,'Visible','off');
               set(controls.forecast.shockcontroltext,'Visible','off');
               set(controls.forecast.shockcontrol,'Visible','off');
               set(controls.forecast.adjustpredictionpaths,'Visible','off');
               set(controls.forecast.ksiuseconddata,'Visible','off');
               set(controls.toolsbox,'Visible','off');
               set(controls.tools.riccatiiterationtext,'Visible','off');
               set(controls.tools.riccatiiteration,'Visible','off');
               set(controls.tools.riccatitolerancetext,'Visible','off');
               set(controls.tools.riccatitolerance,'Visible','off');
               set(controls.tools.irhorizontext,'Visible','off');
               set(controls.tools.irhorizon,'Visible','off');
               set(controls.tools.randomnumber,'Visible','off');
               set(controls.tools.randomizedraws,'Visible','off');
               set(controls.optimizationbox,'Visible','off');
               set(controls.optimize.maxroutinetext,'Visible','off');
               set(controls.optimize.maxroutine,'Visible','off');
               set(controls.optimize.tolerancetext,'Visible','off');
               set(controls.optimize.tolerance,'Visible','off');
               set(controls.optimize.maximumiterationstext,'Visible','off');
               set(controls.optimize.maximumiterations,'Visible','off');
               set(controls.optimize.initcsminweltext,'Visible','off');
               set(controls.optimize.initcsminwel,'Visible','off');
               set(controls.optimize.steplengthtext,'Visible','off');
               set(controls.optimize.steplength,'Visible','off');
               set(controls.optimize.gridwidthtext,'Visible','off');
               set(controls.optimize.gridwidth,'Visible','off');
               set(controls.optimize.numbergridpointstext,'Visible','off');
               set(controls.optimize.numbergridpoints,'Visible','off');
               set(controls.optimize.finitediffhessian,'Visible','off');
               set(controls.optimize.checkoptimum,'Visible','off');
               set(controls.optimize.checktransformed,'Visible','off');
               set(controls.optimize.modifiedhessian,'Visible','off');
               %
               set(controls.kerneldensitybox,'Visible','off');
               set(controls.graphics.posteriorkerneltext,'Visible','off');
               set(controls.graphics.posteriorkernel,'Visible','off');
               set(controls.graphics.kerneldensitytext,'Visible','off');
               set(controls.graphics.kerneldensity,'Visible','off');
               set(controls.graphics.priorkernel,'Visible','off');
               %
               set(controls.steadystatebox,'Visible','off');
               set(controls.bvar.steadystatefiletext,'Visible','off');
               set(controls.bvar.steadystatefile,'Visible','off');
               set(controls.bvar.steadystatefilebutton,'Visible','off');
               set(controls.bvarpriorbox,'Visible','off');
               set(controls.bvar.priorlevelmeantext,'Visible','off');
               set(controls.bvar.priorlevelmean,'Visible','off');
               set(controls.bvar.priordiffmeantext,'Visible','off');
               set(controls.bvar.priordiffmean,'Visible','off');
               set(controls.bvar.priortypetext,'Visible','off');
               set(controls.bvar.priortype,'Visible','off');
               set(controls.bvar.overalltightnesstext,'Visible','off');
               set(controls.bvar.overalltightness,'Visible','off');
               set(controls.bvar.crosseqtightnesstext,'Visible','off');
               set(controls.bvar.crosseqtightness,'Visible','off');
               set(controls.bvar.harmoniclagdecaytext,'Visible','off');
               set(controls.bvar.harmoniclagdecay,'Visible','off');
               set(controls.omegapriorbox,'Visible','off');
               set(controls.bvar.omegapriortypetext,'Visible','off');
               set(controls.bvar.omegapriortype,'Visible','off');
               set(controls.bvar.wisharttypetext,'Visible','off');
               set(controls.bvar.wisharttype,'Visible','off');
               set(controls.bvar.variancetightnesstext,'Visible','off');
               set(controls.bvar.variancetightness,'Visible','off');
               set(controls.bvar.wishartdftext,'Visible','off');
               set(controls.bvar.wishartdf,'Visible','off');
               set(controls.bvarlagbox,'Visible','off');
               set(controls.bvar.lagtext,'Visible','off');
               set(controls.bvar.lag,'Visible','off');
               %
               set(controls.outputselect,'Visible','off');
               set(controls.outputdirtext,'Visible','off');
               set(controls.outputdir,'Visible','off');
               set(controls.outputbutton,'Visible','off');
               set(controls.estimationlog,'Visible','off');
               set(controls.clearlogwindow,'Visible','off');
               set(controls.estimation_log,'Visible','off');
               %
               set(controls.dsge.obsfilesbox,'Visible','on');
               set(controls.dsge.priorfilesbox,'Visible','on');
               set(controls.dsge.parameterfilesbox,'Visible','on');
               set(controls.dsge.aimfilesbox,'Visible','on');
               set(controls.dsge.datafiletext,'Visible','on');
               set(controls.dsge.datafile,'Visible','on');
               set(controls.dsge.datafilebutton,'Visible','on');
               set(controls.dsge.priorfiletext,'Visible','on');
               set(controls.dsge.priorfile,'Visible','on');
               set(controls.dsge.priorfilebutton,'Visible','on');
               set(controls.dsge.priorfilesheet,'Visible','on');
               set(controls.dsge.updateparameterfiletext,'Visible','on');
               set(controls.dsge.updateparameterfile,'Visible','on');
               set(controls.dsge.updateparameterfilebutton,'Visible','on');
               set(controls.dsge.initialparameterfiletext,'Visible','on');
               set(controls.dsge.initialparameterfile,'Visible','on');
               set(controls.dsge.initialparameterfilebutton,'Visible','on');
               set(controls.dsge.runinitialfirst,'Visible','on');
               set(controls.dsge.measurefiletext,'Visible','on');
               set(controls.dsge.measurefile,'Visible','on');
               set(controls.dsge.measurefilebutton,'Visible','on');
               set(controls.dsge.aimfiletext,'Visible','on');
               set(controls.dsge.aimfile,'Visible','on');
               set(controls.dsge.aimfilebutton,'Visible','on');
               set(controls.dsge.modelnametext,'Visible','on');
               set(controls.dsge.modelnameaxes,'Visible','on');
               set(controls.dsge.modelname,'Visible','on');
               set(controls.dsge.modelnamebutton,'Visible','on');
            elseif newtab==2;
               %
               % Settings tab
               %
               set(controls.frame3tab1,'Visible','on');
               set(controls.frame3tab2,'Visible','off');
               set(controls.frame3tab3,'Visible','on');
               set(controls.frame3tab4,'Visible','on');
               set(controls.frame3tab5,'Visible','on');
               set(controls.frame3tab6,'Visible','on');
               set(controls.frame1tab2,'Position',[117 594 104 11]);
               set(controls.frame1tab3,'Position',[221 594 102 11]);
               set(controls.frame1tab4,'Position',[324 594 102 11]);
               set(controls.frame1tab5,'Position',[427 594 102 11]);
               set(controls.frame1tab6,'Position',[530 594 102 11]);
               set(controls.tab1,'Position',[15 602 102 23]);
               set(controls.tab2,'Position',[117 602 104 25]);
               set(controls.tab3,'Position',[221 602 102 23]);
               set(controls.tab4,'Position',[324 602 102 23]);
               set(controls.tab5,'Position',[427 602 102 23]);
               set(controls.tab6,'Position',[530 602 102 23]);
               %
               set(controls.dsge.obsfilesbox,'Visible','off');
               set(controls.dsge.priorfilesbox,'Visible','off');
               set(controls.dsge.parameterfilesbox,'Visible','off');
               set(controls.dsge.aimfilesbox,'Visible','off');
               set(controls.dsge.datafiletext,'Visible','off');
               set(controls.dsge.datafile,'Visible','off');
               set(controls.dsge.datafilebutton,'Visible','off');
               set(controls.dsge.priorfiletext,'Visible','off');
               set(controls.dsge.priorfile,'Visible','off');
               set(controls.dsge.priorfilebutton,'Visible','off');
               set(controls.dsge.priorfilesheet,'Visible','off');
               set(controls.dsge.updateparameterfiletext,'Visible','off');
               set(controls.dsge.updateparameterfile,'Visible','off');
               set(controls.dsge.updateparameterfilebutton,'Visible','off');
               set(controls.dsge.initialparameterfiletext,'Visible','off');
               set(controls.dsge.initialparameterfile,'Visible','off');
               set(controls.dsge.initialparameterfilebutton,'Visible','off');
               set(controls.dsge.runinitialfirst,'Visible','off');
               set(controls.dsge.measurefiletext,'Visible','off');
               set(controls.dsge.measurefile,'Visible','off');
               set(controls.dsge.measurefilebutton,'Visible','off');
               set(controls.dsge.aimfiletext,'Visible','off');
               set(controls.dsge.aimfile,'Visible','off');
               set(controls.dsge.aimfilebutton,'Visible','off');
               set(controls.dsge.modelnametext,'Visible','off');
               set(controls.dsge.modelnameaxes,'Visible','off');
               set(controls.dsge.modelname,'Visible','off');
               set(controls.dsge.modelnamebutton,'Visible','off');
               %
               set(controls.posteriorsamplingbox,'Visible','off');
               set(controls.posterior.drawstext,'Visible','off');
               set(controls.posterior.draws,'Visible','off');
               set(controls.posterior.batchtext,'Visible','off');
               set(controls.posterior.batch,'Visible','off');
               set(controls.posterior.chainstext,'Visible','off');
               set(controls.posterior.chains,'Visible','off');
               set(controls.posterior.burnintext,'Visible','off');
               set(controls.posterior.burnin,'Visible','off');
               set(controls.posterior.invhessiantext,'Visible','off');
               set(controls.posterior.invhessian,'Visible','off');
               set(controls.posterior.maxcorrelationtext,'Visible','off');
               set(controls.posterior.maxcorrelation,'Visible','off');
               set(controls.posterior.initialscaletext,'Visible','off');
               set(controls.posterior.initialscale,'Visible','off');
               set(controls.posterior.scalefactortext,'Visible','off');
               set(controls.posterior.scalefactor,'Visible','off');
               set(controls.posterior.randomweighttext,'Visible','off');
               set(controls.posterior.randomweight,'Visible','off');
               set(controls.posterior.postdrawsusagetext,'Visible','off');
               set(controls.posterior.postdrawsusage,'Visible','off');
               set(controls.posterior.usepostdrawstext,'Visible','off');
               set(controls.posterior.usepostdraws,'Visible','off');
               set(controls.forecastbox,'Visible','off');
               set(controls.forecast.maxhorizontext,'Visible','off');
               set(controls.forecast.maxhorizon,'Visible','off');
%               set(controls.forecast.freqreesttext,'Visible','off');
%               set(controls.forecast.freqreest,'Visible','off');
               set(controls.forecast.predpathstext,'Visible','off');
               set(controls.forecast.predpaths,'Visible','off');
               set(controls.forecast.shockcontroltext,'Visible','off');
               set(controls.forecast.shockcontrol,'Visible','off');
               set(controls.forecast.adjustpredictionpaths,'Visible','off');
               set(controls.forecast.ksiuseconddata,'Visible','off');
               set(controls.toolsbox,'Visible','off');
               set(controls.tools.riccatiiterationtext,'Visible','off');
               set(controls.tools.riccatiiteration,'Visible','off');
               set(controls.tools.riccatitolerancetext,'Visible','off');
               set(controls.tools.riccatitolerance,'Visible','off');
               set(controls.tools.irhorizontext,'Visible','off');
               set(controls.tools.irhorizon,'Visible','off');
               set(controls.tools.randomnumber,'Visible','off');
               set(controls.tools.randomizedraws,'Visible','off');
               set(controls.optimizationbox,'Visible','off');
               set(controls.optimize.maxroutinetext,'Visible','off');
               set(controls.optimize.maxroutine,'Visible','off');
               set(controls.optimize.tolerancetext,'Visible','off');
               set(controls.optimize.tolerance,'Visible','off');
               set(controls.optimize.maximumiterationstext,'Visible','off');
               set(controls.optimize.maximumiterations,'Visible','off');
               set(controls.optimize.initcsminweltext,'Visible','off');
               set(controls.optimize.initcsminwel,'Visible','off');
               set(controls.optimize.steplengthtext,'Visible','off');
               set(controls.optimize.steplength,'Visible','off');
               set(controls.optimize.gridwidthtext,'Visible','off');
               set(controls.optimize.gridwidth,'Visible','off');
               set(controls.optimize.numbergridpointstext,'Visible','off');
               set(controls.optimize.numbergridpoints,'Visible','off');
               set(controls.optimize.finitediffhessian,'Visible','off');
               set(controls.optimize.checkoptimum,'Visible','off');
               set(controls.optimize.checktransformed,'Visible','off');
               set(controls.optimize.modifiedhessian,'Visible','off');
               %
               set(controls.kerneldensitybox,'Visible','off');
               set(controls.graphics.posteriorkerneltext,'Visible','off');
               set(controls.graphics.posteriorkernel,'Visible','off');
               set(controls.graphics.kerneldensitytext,'Visible','off');
               set(controls.graphics.kerneldensity,'Visible','off');
               set(controls.graphics.priorkernel,'Visible','off');
               %
               set(controls.steadystatebox,'Visible','off');
               set(controls.bvar.steadystatefiletext,'Visible','off');
               set(controls.bvar.steadystatefile,'Visible','off');
               set(controls.bvar.steadystatefilebutton,'Visible','off');
               set(controls.bvarpriorbox,'Visible','off');
               set(controls.bvar.priorlevelmeantext,'Visible','off');
               set(controls.bvar.priorlevelmean,'Visible','off');
               set(controls.bvar.priordiffmeantext,'Visible','off');
               set(controls.bvar.priordiffmean,'Visible','off');
               set(controls.bvar.priortypetext,'Visible','off');
               set(controls.bvar.priortype,'Visible','off');
               set(controls.bvar.overalltightnesstext,'Visible','off');
               set(controls.bvar.overalltightness,'Visible','off');
               set(controls.bvar.crosseqtightnesstext,'Visible','off');
               set(controls.bvar.crosseqtightness,'Visible','off');
               set(controls.bvar.harmoniclagdecaytext,'Visible','off');
               set(controls.bvar.harmoniclagdecay,'Visible','off');
               set(controls.omegapriorbox,'Visible','off');
               set(controls.bvar.omegapriortypetext,'Visible','off');
               set(controls.bvar.omegapriortype,'Visible','off');
               set(controls.bvar.wisharttypetext,'Visible','off');
               set(controls.bvar.wisharttype,'Visible','off');
               set(controls.bvar.variancetightnesstext,'Visible','off');
               set(controls.bvar.variancetightness,'Visible','off');
               set(controls.bvar.wishartdftext,'Visible','off');
               set(controls.bvar.wishartdf,'Visible','off');
               set(controls.bvarlagbox,'Visible','off');
               set(controls.bvar.lagtext,'Visible','off');
               set(controls.bvar.lag,'Visible','off');
               %
               set(controls.outputselect,'Visible','off');
               set(controls.outputdirtext,'Visible','off');
               set(controls.outputdir,'Visible','off');
               set(controls.outputbutton,'Visible','off');
               set(controls.estimationlog,'Visible','off');
               set(controls.clearlogwindow,'Visible','off');
               set(controls.estimation_log,'Visible','off');
               %
               set(controls.dsge.posteriorsamplingbox,'Visible','on');
               set(controls.dsge.marginallikelihoodtext,'Visible','on');
               set(controls.dsge.marginallikelihood,'Visible','on');
               set(controls.dsge.sequantialmltext,'Visible','on');
               set(controls.dsge.sequentialstart,'Visible','on');
               set(controls.dsge.sequentialstep,'Visible','on');
               set(controls.dsge.coverageprobtext,'Visible','on');
               set(controls.dsge.coveragestart,'Visible','on');
               set(controls.dsge.coverageincrement,'Visible','on');
               set(controls.dsge.coverageend,'Visible','on');
               set(controls.dsge.sequentialml,'Visible','on');
               set(controls.dsge.overwritedraws,'Visible','on');
               set(controls.dsge.progressbox,'Visible','on');
               set(controls.dsge.progress,'Visible','on');
               set(controls.dsge.progressclock,'Visible','on');
               set(controls.dsge.kalmanbox,'Visible','on');
               set(controls.dsge.doublingalgorithmtext,'Visible','on');
               set(controls.dsge.doublingalgorithm,'Visible','on');
               set(controls.dsge.doublingtolerancetext,'Visible','on');
               set(controls.dsge.doublingtolerance,'Visible','on');
               set(controls.dsge.statecovariancetext,'Visible','on');
               set(controls.dsge.statecovariance,'Visible','on');
               set(controls.dsge.initializekalmantext,'Visible','on');
               set(controls.dsge.initializekalman,'Visible','on');
               set(controls.dsge.aimtolerancetext,'Visible','on');
               set(controls.dsge.aimtolerance,'Visible','on');
               set(controls.dsge.usedoublingalgorithmtext,'Visible','on');
               set(controls.dsge.usedoublingalgorithm,'Visible','on');
               set(controls.dsge.useowninitialstate,'Visible','on');
               set(controls.dsge.allowunitroot,'Visible','on');
               set(controls.dsge.sampleselect,'Visible','on');
               set(controls.dsge.subsample,'Visible','on');
               set(controls.dsge.subbeginyear,'Visible','on');
               set(controls.dsge.subbeginperiod,'Visible','on');
               set(controls.dsge.subsampleseparator,'Visible','on');
               set(controls.dsge.subendyear,'Visible','on');
               set(controls.dsge.subendperiod,'Visible','on');
            elseif newtab==3;
               %
               % Options tab
               %
               set(controls.frame3tab1,'Visible','on');
               set(controls.frame3tab2,'Visible','on');
               set(controls.frame3tab3,'Visible','off');
               set(controls.frame3tab4,'Visible','on');
               set(controls.frame3tab5,'Visible','on');
               set(controls.frame3tab6,'Visible','on');
               set(controls.frame1tab2,'Position',[118 594 102 11]);
               set(controls.frame1tab3,'Position',[220 594 104 11]);
               set(controls.frame1tab4,'Position',[324 594 102 11]);
               set(controls.frame1tab5,'Position',[427 594 102 11]);
               set(controls.frame1tab6,'Position',[530 594 102 11]);
               set(controls.tab1,'Position',[15 602 102 23]);
               set(controls.tab2,'Position',[118 602 102 23]);
               set(controls.tab3,'Position',[220 602 104 25]);
               set(controls.tab4,'Position',[324 602 102 23]);
               set(controls.tab5,'Position',[427 602 102 23]);
               set(controls.tab6,'Position',[530 602 102 23]);
               %
               set(controls.dsge.obsfilesbox,'Visible','off');
               set(controls.dsge.priorfilesbox,'Visible','off');
               set(controls.dsge.parameterfilesbox,'Visible','off');
               set(controls.dsge.aimfilesbox,'Visible','off');
               set(controls.dsge.datafiletext,'Visible','off');
               set(controls.dsge.datafile,'Visible','off');
               set(controls.dsge.datafilebutton,'Visible','off');
               set(controls.dsge.priorfiletext,'Visible','off');
               set(controls.dsge.priorfile,'Visible','off');
               set(controls.dsge.priorfilebutton,'Visible','off');
               set(controls.dsge.priorfilesheet,'Visible','off');
               set(controls.dsge.updateparameterfiletext,'Visible','off');
               set(controls.dsge.updateparameterfile,'Visible','off');
               set(controls.dsge.updateparameterfilebutton,'Visible','off');
               set(controls.dsge.initialparameterfiletext,'Visible','off');
               set(controls.dsge.initialparameterfile,'Visible','off');
               set(controls.dsge.initialparameterfilebutton,'Visible','off');
               set(controls.dsge.runinitialfirst,'Visible','off');
               set(controls.dsge.measurefiletext,'Visible','off');
               set(controls.dsge.measurefile,'Visible','off');
               set(controls.dsge.measurefilebutton,'Visible','off');
               set(controls.dsge.aimfiletext,'Visible','off');
               set(controls.dsge.aimfile,'Visible','off');
               set(controls.dsge.aimfilebutton,'Visible','off');
               set(controls.dsge.modelnametext,'Visible','off');
               set(controls.dsge.modelnameaxes,'Visible','off');
               set(controls.dsge.modelname,'Visible','off');
               set(controls.dsge.modelnamebutton,'Visible','off');
               %
               set(controls.dsge.posteriorsamplingbox,'Visible','off');
               set(controls.dsge.marginallikelihoodtext,'Visible','off');
               set(controls.dsge.marginallikelihood,'Visible','off');
               set(controls.dsge.sequantialmltext,'Visible','off');
               set(controls.dsge.sequentialstart,'Visible','off');
               set(controls.dsge.sequentialstep,'Visible','off');
               set(controls.dsge.coverageprobtext,'Visible','off');
               set(controls.dsge.coveragestart,'Visible','off');
               set(controls.dsge.coverageincrement,'Visible','off');
               set(controls.dsge.coverageend,'Visible','off');
               set(controls.dsge.sequentialml,'Visible','off');
               set(controls.dsge.overwritedraws,'Visible','off');
               set(controls.dsge.progressbox,'Visible','off');
               set(controls.dsge.progress,'Visible','off');
               set(controls.dsge.progressclock,'Visible','off');
               set(controls.dsge.kalmanbox,'Visible','off');
               set(controls.dsge.doublingalgorithmtext,'Visible','off');
               set(controls.dsge.doublingalgorithm,'Visible','off');
               set(controls.dsge.doublingtolerancetext,'Visible','off');
               set(controls.dsge.doublingtolerance,'Visible','off');
               set(controls.dsge.statecovariancetext,'Visible','off');
               set(controls.dsge.statecovariance,'Visible','off');
               set(controls.dsge.initializekalmantext,'Visible','off');
               set(controls.dsge.initializekalman,'Visible','off');
               set(controls.dsge.aimtolerancetext,'Visible','off');
               set(controls.dsge.aimtolerance,'Visible','off');
               set(controls.dsge.usedoublingalgorithmtext,'Visible','off');
               set(controls.dsge.usedoublingalgorithm,'Visible','off');
               set(controls.dsge.useowninitialstate,'Visible','off');
               set(controls.dsge.allowunitroot,'Visible','off');
               set(controls.dsge.sampleselect,'Visible','off');
               set(controls.dsge.subsample,'Visible','off');
               set(controls.dsge.subbeginyear,'Visible','off');
               set(controls.dsge.subbeginperiod,'Visible','off');
               set(controls.dsge.subsampleseparator,'Visible','off');
               set(controls.dsge.subendyear,'Visible','off');
               set(controls.dsge.subendperiod,'Visible','off');
               %
               set(controls.kerneldensitybox,'Visible','off');
               set(controls.graphics.posteriorkerneltext,'Visible','off');
               set(controls.graphics.posteriorkernel,'Visible','off');
               set(controls.graphics.kerneldensitytext,'Visible','off');
               set(controls.graphics.kerneldensity,'Visible','off');
               set(controls.graphics.priorkernel,'Visible','off');
               %
               set(controls.steadystatebox,'Visible','off');
               set(controls.bvar.steadystatefiletext,'Visible','off');
               set(controls.bvar.steadystatefile,'Visible','off');
               set(controls.bvar.steadystatefilebutton,'Visible','off');
               set(controls.bvarpriorbox,'Visible','off');
               set(controls.bvar.priorlevelmeantext,'Visible','off');
               set(controls.bvar.priorlevelmean,'Visible','off');
               set(controls.bvar.priordiffmeantext,'Visible','off');
               set(controls.bvar.priordiffmean,'Visible','off');
               set(controls.bvar.priortypetext,'Visible','off');
               set(controls.bvar.priortype,'Visible','off');
               set(controls.bvar.overalltightnesstext,'Visible','off');
               set(controls.bvar.overalltightness,'Visible','off');
               set(controls.bvar.crosseqtightnesstext,'Visible','off');
               set(controls.bvar.crosseqtightness,'Visible','off');
               set(controls.bvar.harmoniclagdecaytext,'Visible','off');
               set(controls.bvar.harmoniclagdecay,'Visible','off');
               set(controls.omegapriorbox,'Visible','off');
               set(controls.bvar.omegapriortypetext,'Visible','off');
               set(controls.bvar.omegapriortype,'Visible','off');
               set(controls.bvar.wisharttypetext,'Visible','off');
               set(controls.bvar.wisharttype,'Visible','off');
               set(controls.bvar.variancetightnesstext,'Visible','off');
               set(controls.bvar.variancetightness,'Visible','off');
               set(controls.bvar.wishartdftext,'Visible','off');
               set(controls.bvar.wishartdf,'Visible','off');
               set(controls.bvarlagbox,'Visible','off');
               set(controls.bvar.lagtext,'Visible','off');
               set(controls.bvar.lag,'Visible','off');
               %
               set(controls.outputselect,'Visible','off');
               set(controls.outputdirtext,'Visible','off');
               set(controls.outputdir,'Visible','off');
               set(controls.outputbutton,'Visible','off');
               set(controls.estimationlog,'Visible','off');
               set(controls.clearlogwindow,'Visible','off');
               set(controls.estimation_log,'Visible','off');
               %
               set(controls.forecastbox,'Visible','off');
               set(controls.forecast.maxhorizontext,'Visible','off');
               set(controls.forecast.maxhorizon,'Visible','off');
%               set(controls.forecast.freqreesttext,'Visible','off');
%               set(controls.forecast.freqreest,'Visible','off');
               set(controls.forecast.predpathstext,'Visible','off');
               set(controls.forecast.predpaths,'Visible','off');
               set(controls.forecast.shockcontroltext,'Visible','off');
               set(controls.forecast.shockcontrol,'Visible','off');
               set(controls.forecast.adjustpredictionpaths,'Visible','off');
               set(controls.forecast.ksiuseconddata,'Visible','off');
               set(controls.toolsbox,'Visible','off');
               set(controls.tools.riccatiiterationtext,'Visible','off');
               set(controls.tools.riccatiiteration,'Visible','off');
               set(controls.tools.riccatitolerancetext,'Visible','off');
               set(controls.tools.riccatitolerance,'Visible','off');
               set(controls.optimize.steplengthtext,'Visible','off');
               set(controls.optimize.steplength,'Visible','off');
               set(controls.tools.irhorizontext,'Visible','off');
               set(controls.tools.irhorizon,'Visible','off');
               set(controls.tools.randomnumber,'Visible','off');
               set(controls.tools.randomizedraws,'Visible','off');
               set(controls.optimize.finitediffhessian,'Visible','off');
               set(controls.optimize.checkoptimum,'Visible','off');
               set(controls.optimize.checktransformed,'Visible','off');
               set(controls.optimize.modifiedhessian,'Visible','off');
               %
               set(controls.posteriorsamplingbox,'Visible','on');
               set(controls.posterior.drawstext,'Visible','on');
               set(controls.posterior.draws,'Visible','on');
               set(controls.posterior.batchtext,'Visible','on');
               set(controls.posterior.batch,'Visible','on');
               set(controls.posterior.chainstext,'Visible','on');
               set(controls.posterior.chains,'Visible','on');
               set(controls.posterior.burnintext,'Visible','on');
               set(controls.posterior.burnin,'Visible','on');
               set(controls.posterior.invhessiantext,'Visible','on');
               set(controls.posterior.invhessian,'Visible','on');
               set(controls.posterior.maxcorrelationtext,'Visible','on');
               set(controls.posterior.maxcorrelation,'Visible','on');
               set(controls.posterior.initialscaletext,'Visible','on');
               set(controls.posterior.initialscale,'Visible','on');
               set(controls.posterior.scalefactortext,'Visible','on');
               set(controls.posterior.scalefactor,'Visible','on');
               set(controls.posterior.randomweighttext,'Visible','on');
               set(controls.posterior.randomweight,'Visible','on');
               set(controls.posterior.postdrawsusagetext,'Visible','on');
               set(controls.posterior.postdrawsusage,'Visible','on');
               set(controls.posterior.usepostdrawstext,'Visible','on');
               set(controls.posterior.usepostdraws,'Visible','on');
               set(controls.optimizationbox,'Visible','on');
               set(controls.optimize.maxroutinetext,'Visible','on');
               set(controls.optimize.maxroutine,'Visible','on');
               set(controls.optimize.tolerancetext,'Visible','on');
               set(controls.optimize.tolerance,'Visible','on');
               set(controls.optimize.maximumiterationstext,'Visible','on');
               set(controls.optimize.maximumiterations,'Visible','on');
               set(controls.optimize.initcsminweltext,'Visible','on');
               set(controls.optimize.initcsminwel,'Visible','on');
               set(controls.optimize.gridwidthtext,'Visible','on');
               set(controls.optimize.gridwidth,'Visible','on');
               set(controls.optimize.numbergridpointstext,'Visible','on');
               set(controls.optimize.numbergridpoints,'Visible','on');
            elseif newtab==4;
               %
               % Miscellaneous tab
               %
               set(controls.frame3tab1,'Visible','on');
               set(controls.frame3tab2,'Visible','on');
               set(controls.frame3tab3,'Visible','on');
               set(controls.frame3tab4,'Visible','off');
               set(controls.frame3tab5,'Visible','on');
               set(controls.frame3tab6,'Visible','on');
               set(controls.frame1tab2,'Position',[118 594 102 11]);
               set(controls.frame1tab3,'Position',[221 594 102 11]);
               set(controls.frame1tab4,'Position',[323 594 104 11]);
               set(controls.frame1tab5,'Position',[427 594 102 11]);
               set(controls.frame1tab6,'Position',[530 594 102 11]);
               set(controls.tab1,'Position',[15 602 102 23]);
               set(controls.tab2,'Position',[118 602 102 23]);
               set(controls.tab3,'Position',[221 602 102 23]);
               set(controls.tab4,'Position',[323 602 104 25]);
               set(controls.tab5,'Position',[427 602 102 23]);
               set(controls.tab6,'Position',[530 602 102 23]);
               %
               set(controls.dsge.obsfilesbox,'Visible','off');
               set(controls.dsge.priorfilesbox,'Visible','off');
               set(controls.dsge.parameterfilesbox,'Visible','off');
               set(controls.dsge.aimfilesbox,'Visible','off');
               set(controls.dsge.datafiletext,'Visible','off');
               set(controls.dsge.datafile,'Visible','off');
               set(controls.dsge.datafilebutton,'Visible','off');
               set(controls.dsge.priorfiletext,'Visible','off');
               set(controls.dsge.priorfile,'Visible','off');
               set(controls.dsge.priorfilebutton,'Visible','off');
               set(controls.dsge.priorfilesheet,'Visible','off');
               set(controls.dsge.updateparameterfiletext,'Visible','off');
               set(controls.dsge.updateparameterfile,'Visible','off');
               set(controls.dsge.updateparameterfilebutton,'Visible','off');
               set(controls.dsge.initialparameterfiletext,'Visible','off');
               set(controls.dsge.initialparameterfile,'Visible','off');
               set(controls.dsge.initialparameterfilebutton,'Visible','off');
               set(controls.dsge.runinitialfirst,'Visible','off');
               set(controls.dsge.measurefiletext,'Visible','off');
               set(controls.dsge.measurefile,'Visible','off');
               set(controls.dsge.measurefilebutton,'Visible','off');
               set(controls.dsge.aimfiletext,'Visible','off');
               set(controls.dsge.aimfile,'Visible','off');
               set(controls.dsge.aimfilebutton,'Visible','off');
               set(controls.dsge.modelnametext,'Visible','off');
               set(controls.dsge.modelnameaxes,'Visible','off');
               set(controls.dsge.modelname,'Visible','off');
               set(controls.dsge.modelnamebutton,'Visible','off');
               %
               set(controls.dsge.posteriorsamplingbox,'Visible','off');
               set(controls.dsge.marginallikelihoodtext,'Visible','off');
               set(controls.dsge.marginallikelihood,'Visible','off');
               set(controls.dsge.sequantialmltext,'Visible','off');
               set(controls.dsge.sequentialstart,'Visible','off');
               set(controls.dsge.sequentialstep,'Visible','off');
               set(controls.dsge.coverageprobtext,'Visible','off');
               set(controls.dsge.coveragestart,'Visible','off');
               set(controls.dsge.coverageincrement,'Visible','off');
               set(controls.dsge.coverageend,'Visible','off');
               set(controls.dsge.sequentialml,'Visible','off');
               set(controls.dsge.overwritedraws,'Visible','off');
               set(controls.dsge.progressbox,'Visible','off');
               set(controls.dsge.progress,'Visible','off');
               set(controls.dsge.progressclock,'Visible','off');
               set(controls.dsge.kalmanbox,'Visible','off');
               set(controls.dsge.doublingalgorithmtext,'Visible','off');
               set(controls.dsge.doublingalgorithm,'Visible','off');
               set(controls.dsge.doublingtolerancetext,'Visible','off');
               set(controls.dsge.doublingtolerance,'Visible','off');
               set(controls.dsge.statecovariancetext,'Visible','off');
               set(controls.dsge.statecovariance,'Visible','off');
               set(controls.dsge.initializekalmantext,'Visible','off');
               set(controls.dsge.initializekalman,'Visible','off');
               set(controls.dsge.aimtolerancetext,'Visible','off');
               set(controls.dsge.aimtolerance,'Visible','off');
               set(controls.dsge.usedoublingalgorithmtext,'Visible','off');
               set(controls.dsge.usedoublingalgorithm,'Visible','off');
               set(controls.dsge.useowninitialstate,'Visible','off');
               set(controls.dsge.allowunitroot,'Visible','off');
               set(controls.dsge.sampleselect,'Visible','off');
               set(controls.dsge.subsample,'Visible','off');
               set(controls.dsge.subbeginyear,'Visible','off');
               set(controls.dsge.subbeginperiod,'Visible','off');
               set(controls.dsge.subsampleseparator,'Visible','off');
               set(controls.dsge.subendyear,'Visible','off');
               set(controls.dsge.subendperiod,'Visible','off');
               %
               set(controls.posteriorsamplingbox,'Visible','off');
               set(controls.posterior.drawstext,'Visible','off');
               set(controls.posterior.draws,'Visible','off');
               set(controls.posterior.batchtext,'Visible','off');
               set(controls.posterior.batch,'Visible','off');
               set(controls.posterior.chainstext,'Visible','off');
               set(controls.posterior.chains,'Visible','off');
               set(controls.posterior.burnintext,'Visible','off');
               set(controls.posterior.burnin,'Visible','off');
               set(controls.posterior.invhessiantext,'Visible','off');
               set(controls.posterior.invhessian,'Visible','off');
               set(controls.posterior.maxcorrelationtext,'Visible','off');
               set(controls.posterior.maxcorrelation,'Visible','off');
               set(controls.posterior.initialscaletext,'Visible','off');
               set(controls.posterior.initialscale,'Visible','off');
               set(controls.posterior.scalefactortext,'Visible','off');
               set(controls.posterior.scalefactor,'Visible','off');
               set(controls.posterior.randomweighttext,'Visible','off');
               set(controls.posterior.randomweight,'Visible','off');
               set(controls.posterior.postdrawsusagetext,'Visible','off');
               set(controls.posterior.postdrawsusage,'Visible','off');
               set(controls.posterior.usepostdrawstext,'Visible','off');
               set(controls.posterior.usepostdraws,'Visible','off');
               set(controls.optimizationbox,'Visible','off');
               set(controls.optimize.maxroutinetext,'Visible','off');
               set(controls.optimize.maxroutine,'Visible','off');
               set(controls.optimize.tolerancetext,'Visible','off');
               set(controls.optimize.tolerance,'Visible','off');
               set(controls.optimize.maximumiterationstext,'Visible','off');
               set(controls.optimize.maximumiterations,'Visible','off');
               set(controls.optimize.initcsminweltext,'Visible','off');
               set(controls.optimize.initcsminwel,'Visible','off');
               set(controls.optimize.gridwidthtext,'Visible','off');
               set(controls.optimize.gridwidth,'Visible','off');
               set(controls.optimize.numbergridpointstext,'Visible','off');
               set(controls.optimize.numbergridpoints,'Visible','off');
               %
               set(controls.steadystatebox,'Visible','off');
               set(controls.bvar.steadystatefiletext,'Visible','off');
               set(controls.bvar.steadystatefile,'Visible','off');
               set(controls.bvar.steadystatefilebutton,'Visible','off');
               set(controls.bvarpriorbox,'Visible','off');
               set(controls.bvar.priorlevelmeantext,'Visible','off');
               set(controls.bvar.priorlevelmean,'Visible','off');
               set(controls.bvar.priordiffmeantext,'Visible','off');
               set(controls.bvar.priordiffmean,'Visible','off');
               set(controls.bvar.priortypetext,'Visible','off');
               set(controls.bvar.priortype,'Visible','off');
               set(controls.bvar.overalltightnesstext,'Visible','off');
               set(controls.bvar.overalltightness,'Visible','off');
               set(controls.bvar.crosseqtightnesstext,'Visible','off');
               set(controls.bvar.crosseqtightness,'Visible','off');
               set(controls.bvar.harmoniclagdecaytext,'Visible','off');
               set(controls.bvar.harmoniclagdecay,'Visible','off');
               set(controls.omegapriorbox,'Visible','off');
               set(controls.bvar.omegapriortypetext,'Visible','off');
               set(controls.bvar.omegapriortype,'Visible','off');
               set(controls.bvar.wisharttypetext,'Visible','off');
               set(controls.bvar.wisharttype,'Visible','off');
               set(controls.bvar.variancetightnesstext,'Visible','off');
               set(controls.bvar.variancetightness,'Visible','off');
               set(controls.bvar.wishartdftext,'Visible','off');
               set(controls.bvar.wishartdf,'Visible','off');
               set(controls.bvarlagbox,'Visible','off');
               set(controls.bvar.lagtext,'Visible','off');
               set(controls.bvar.lag,'Visible','off');
               %
               set(controls.outputselect,'Visible','off');
               set(controls.outputdirtext,'Visible','off');
               set(controls.outputdir,'Visible','off');
               set(controls.outputbutton,'Visible','off');
               set(controls.estimationlog,'Visible','off');
               set(controls.clearlogwindow,'Visible','off');
               set(controls.estimation_log,'Visible','off');
               %
               set(controls.forecastbox,'Visible','on');
               set(controls.forecast.maxhorizontext,'Visible','on');
               set(controls.forecast.maxhorizon,'Visible','on');
%               set(controls.forecast.freqreesttext,'Visible','on');
%               set(controls.forecast.freqreest,'Visible','on');
               set(controls.forecast.predpathstext,'Visible','on');
               set(controls.forecast.predpaths,'Visible','on');
               set(controls.forecast.shockcontroltext,'Visible','on');
               set(controls.forecast.shockcontrol,'Visible','on');
               set(controls.forecast.adjustpredictionpaths,'Visible','on');
               set(controls.forecast.ksiuseconddata,'Visible','on');
               set(controls.toolsbox,'Visible','on');
               set(controls.tools.riccatiiterationtext,'Visible','on');
               set(controls.tools.riccatiiteration,'Visible','on');
               set(controls.tools.riccatitolerancetext,'Visible','on');
               set(controls.tools.riccatitolerance,'Visible','on');
               set(controls.tools.irhorizontext,'Visible','on');
               set(controls.tools.irhorizon,'Visible','on');
               set(controls.optimize.steplengthtext,'Visible','on');
               set(controls.optimize.steplength,'Visible','on');
               set(controls.tools.randomnumber,'Visible','on');
               set(controls.tools.randomizedraws,'Visible','on');
               set(controls.optimize.finitediffhessian,'Visible','on');
               set(controls.optimize.checkoptimum,'Visible','on');
               set(controls.optimize.checktransformed,'Visible','on');
               set(controls.optimize.modifiedhessian,'Visible','on');
               set(controls.kerneldensitybox,'Visible','on');
               set(controls.graphics.posteriorkerneltext,'Visible','on');
               set(controls.graphics.posteriorkernel,'Visible','on');
               set(controls.graphics.kerneldensitytext,'Visible','on');
               set(controls.graphics.kerneldensity,'Visible','on');
               set(controls.graphics.priorkernel,'Visible','on');
            elseif newtab==5;
               %
               % VAR tab
               %
               set(controls.frame3tab1,'Visible','on');
               set(controls.frame3tab2,'Visible','on');
               set(controls.frame3tab3,'Visible','on');
               set(controls.frame3tab4,'Visible','on');
               set(controls.frame3tab5,'Visible','off');
               set(controls.frame3tab6,'Visible','on');
               set(controls.frame1tab2,'Position',[118 594 102 11]);
               set(controls.frame1tab3,'Position',[221 594 102 11]);
               set(controls.frame1tab4,'Position',[324 594 102 11]);
               set(controls.frame1tab5,'Position',[426 594 104 11]);
               set(controls.frame1tab6,'Position',[530 594 102 11]);
               set(controls.tab1,'Position',[15 602 102 23]);
               set(controls.tab2,'Position',[118 602 102 23]);
               set(controls.tab3,'Position',[221 602 102 23]);
               set(controls.tab4,'Position',[324 602 102 23]);
               set(controls.tab5,'Position',[426 602 104 25]);
               set(controls.tab6,'Position',[530 602 102 23]);
               %
               set(controls.dsge.obsfilesbox,'Visible','off');
               set(controls.dsge.priorfilesbox,'Visible','off');
               set(controls.dsge.parameterfilesbox,'Visible','off');
               set(controls.dsge.aimfilesbox,'Visible','off');
               set(controls.dsge.datafiletext,'Visible','off');
               set(controls.dsge.datafile,'Visible','off');
               set(controls.dsge.datafilebutton,'Visible','off');
               set(controls.dsge.priorfiletext,'Visible','off');
               set(controls.dsge.priorfile,'Visible','off');
               set(controls.dsge.priorfilebutton,'Visible','off');
               set(controls.dsge.priorfilesheet,'Visible','off');
               set(controls.dsge.updateparameterfiletext,'Visible','off');
               set(controls.dsge.updateparameterfile,'Visible','off');
               set(controls.dsge.updateparameterfilebutton,'Visible','off');
               set(controls.dsge.initialparameterfiletext,'Visible','off');
               set(controls.dsge.initialparameterfile,'Visible','off');
               set(controls.dsge.initialparameterfilebutton,'Visible','off');
               set(controls.dsge.runinitialfirst,'Visible','off');
               set(controls.dsge.measurefiletext,'Visible','off');
               set(controls.dsge.measurefile,'Visible','off');
               set(controls.dsge.measurefilebutton,'Visible','off');
               set(controls.dsge.aimfiletext,'Visible','off');
               set(controls.dsge.aimfile,'Visible','off');
               set(controls.dsge.aimfilebutton,'Visible','off');
               set(controls.dsge.modelnametext,'Visible','off');
               set(controls.dsge.modelnameaxes,'Visible','off');
               set(controls.dsge.modelname,'Visible','off');
               set(controls.dsge.modelnamebutton,'Visible','off');
               %
               set(controls.dsge.posteriorsamplingbox,'Visible','off');
               set(controls.dsge.marginallikelihoodtext,'Visible','off');
               set(controls.dsge.marginallikelihood,'Visible','off');
               set(controls.dsge.sequantialmltext,'Visible','off');
               set(controls.dsge.sequentialstart,'Visible','off');
               set(controls.dsge.sequentialstep,'Visible','off');
               set(controls.dsge.coverageprobtext,'Visible','off');
               set(controls.dsge.coveragestart,'Visible','off');
               set(controls.dsge.coverageincrement,'Visible','off');
               set(controls.dsge.coverageend,'Visible','off');
               set(controls.dsge.sequentialml,'Visible','off');
               set(controls.dsge.overwritedraws,'Visible','off');
               set(controls.dsge.progressbox,'Visible','off');
               set(controls.dsge.progress,'Visible','off');
               set(controls.dsge.progressclock,'Visible','off');
               set(controls.dsge.kalmanbox,'Visible','off');
               set(controls.dsge.doublingalgorithmtext,'Visible','off');
               set(controls.dsge.doublingalgorithm,'Visible','off');
               set(controls.dsge.doublingtolerancetext,'Visible','off');
               set(controls.dsge.doublingtolerance,'Visible','off');
               set(controls.dsge.statecovariancetext,'Visible','off');
               set(controls.dsge.statecovariance,'Visible','off');
               set(controls.dsge.initializekalmantext,'Visible','off');
               set(controls.dsge.initializekalman,'Visible','off');
               set(controls.dsge.aimtolerancetext,'Visible','off');
               set(controls.dsge.aimtolerance,'Visible','off');
               set(controls.dsge.usedoublingalgorithmtext,'Visible','off');
               set(controls.dsge.usedoublingalgorithm,'Visible','off');
               set(controls.dsge.useowninitialstate,'Visible','off');
               set(controls.dsge.allowunitroot,'Visible','off');
               set(controls.dsge.sampleselect,'Visible','off');
               set(controls.dsge.subsample,'Visible','off');
               set(controls.dsge.subbeginyear,'Visible','off');
               set(controls.dsge.subbeginperiod,'Visible','off');
               set(controls.dsge.subsampleseparator,'Visible','off');
               set(controls.dsge.subendyear,'Visible','off');
               set(controls.dsge.subendperiod,'Visible','off');
               %
               set(controls.posteriorsamplingbox,'Visible','off');
               set(controls.posterior.drawstext,'Visible','off');
               set(controls.posterior.draws,'Visible','off');
               set(controls.posterior.batchtext,'Visible','off');
               set(controls.posterior.batch,'Visible','off');
               set(controls.posterior.chainstext,'Visible','off');
               set(controls.posterior.chains,'Visible','off');
               set(controls.posterior.burnintext,'Visible','off');
               set(controls.posterior.burnin,'Visible','off');
               set(controls.posterior.invhessiantext,'Visible','off');
               set(controls.posterior.invhessian,'Visible','off');
               set(controls.posterior.maxcorrelationtext,'Visible','off');
               set(controls.posterior.maxcorrelation,'Visible','off');
               set(controls.posterior.initialscaletext,'Visible','off');
               set(controls.posterior.initialscale,'Visible','off');
               set(controls.posterior.scalefactortext,'Visible','off');
               set(controls.posterior.scalefactor,'Visible','off');
               set(controls.posterior.randomweighttext,'Visible','off');
               set(controls.posterior.randomweight,'Visible','off');
               set(controls.posterior.postdrawsusagetext,'Visible','off');
               set(controls.posterior.postdrawsusage,'Visible','off');
               set(controls.posterior.usepostdrawstext,'Visible','off');
               set(controls.posterior.usepostdraws,'Visible','off');
               set(controls.forecastbox,'Visible','off');
               set(controls.forecast.maxhorizontext,'Visible','off');
               set(controls.forecast.maxhorizon,'Visible','off');
%               set(controls.forecast.freqreesttext,'Visible','off');
%               set(controls.forecast.freqreest,'Visible','off');
               set(controls.forecast.predpathstext,'Visible','off');
               set(controls.forecast.predpaths,'Visible','off');
               set(controls.forecast.shockcontroltext,'Visible','off');
               set(controls.forecast.shockcontrol,'Visible','off');
               set(controls.forecast.adjustpredictionpaths,'Visible','off');
               set(controls.forecast.ksiuseconddata,'Visible','off');
               set(controls.toolsbox,'Visible','off');
               set(controls.tools.riccatiiterationtext,'Visible','off');
               set(controls.tools.riccatiiteration,'Visible','off');
               set(controls.tools.riccatitolerancetext,'Visible','off');
               set(controls.tools.riccatitolerance,'Visible','off');
               set(controls.tools.irhorizontext,'Visible','off');
               set(controls.tools.irhorizon,'Visible','off');
               set(controls.tools.randomnumber,'Visible','off');
               set(controls.tools.randomizedraws,'Visible','off');
               set(controls.optimizationbox,'Visible','off');
               set(controls.optimize.maxroutinetext,'Visible','off');
               set(controls.optimize.maxroutine,'Visible','off');
               set(controls.optimize.tolerancetext,'Visible','off');
               set(controls.optimize.tolerance,'Visible','off');
               set(controls.optimize.maximumiterationstext,'Visible','off');
               set(controls.optimize.maximumiterations,'Visible','off');
               set(controls.optimize.initcsminweltext,'Visible','off');
               set(controls.optimize.initcsminwel,'Visible','off');
               set(controls.optimize.steplengthtext,'Visible','off');
               set(controls.optimize.steplength,'Visible','off');
               set(controls.optimize.gridwidthtext,'Visible','off');
               set(controls.optimize.gridwidth,'Visible','off');
               set(controls.optimize.numbergridpointstext,'Visible','off');
               set(controls.optimize.numbergridpoints,'Visible','off');
               set(controls.optimize.finitediffhessian,'Visible','off');
               set(controls.optimize.checkoptimum,'Visible','off');
               set(controls.optimize.checktransformed,'Visible','off');
               set(controls.optimize.modifiedhessian,'Visible','off');
               %
               set(controls.kerneldensitybox,'Visible','off');
               set(controls.graphics.posteriorkerneltext,'Visible','off');
               set(controls.graphics.posteriorkernel,'Visible','off');
               set(controls.graphics.kerneldensitytext,'Visible','off');
               set(controls.graphics.kerneldensity,'Visible','off');
               set(controls.graphics.priorkernel,'Visible','off');
               %
               set(controls.outputselect,'Visible','off');
               set(controls.outputdirtext,'Visible','off');
               set(controls.outputdir,'Visible','off');
               set(controls.outputbutton,'Visible','off');
               set(controls.estimationlog,'Visible','off');
               set(controls.clearlogwindow,'Visible','off');
               set(controls.estimation_log,'Visible','off');
               %
               set(controls.steadystatebox,'Visible','on');
               set(controls.bvar.steadystatefiletext,'Visible','on');
               set(controls.bvar.steadystatefile,'Visible','on');
               set(controls.bvar.steadystatefilebutton,'Visible','on');
               set(controls.bvarpriorbox,'Visible','on');
               set(controls.bvar.priorlevelmeantext,'Visible','on');
               set(controls.bvar.priorlevelmean,'Visible','on');
               set(controls.bvar.priordiffmeantext,'Visible','on');
               set(controls.bvar.priordiffmean,'Visible','on');
               set(controls.bvar.priortypetext,'Visible','on');
               set(controls.bvar.priortype,'Visible','on');
               set(controls.bvar.overalltightnesstext,'Visible','on');
               set(controls.bvar.overalltightness,'Visible','on');
               set(controls.bvar.crosseqtightnesstext,'Visible','on');
               set(controls.bvar.crosseqtightness,'Visible','on');
               set(controls.bvar.harmoniclagdecaytext,'Visible','on');
               set(controls.bvar.harmoniclagdecay,'Visible','on');
               set(controls.omegapriorbox,'Visible','on');
               set(controls.bvar.omegapriortypetext,'Visible','on');
               set(controls.bvar.omegapriortype,'Visible','on');
               set(controls.bvar.wisharttypetext,'Visible','on');
               set(controls.bvar.wisharttype,'Visible','on');
               set(controls.bvar.variancetightnesstext,'Visible','on');
               set(controls.bvar.variancetightness,'Visible','on');
               set(controls.bvar.wishartdftext,'Visible','on');
               set(controls.bvar.wishartdf,'Visible','on');
               set(controls.bvarlagbox,'Visible','on');
               set(controls.bvar.lagtext,'Visible','on');
               set(controls.bvar.lag,'Visible','on');
            elseif newtab==6;
               %
               % Output tab
               %
               set(controls.frame3tab1,'Visible','on');
               set(controls.frame3tab2,'Visible','on');
               set(controls.frame3tab3,'Visible','on');
               set(controls.frame3tab4,'Visible','on');
               set(controls.frame3tab5,'Visible','on');
               set(controls.frame3tab6,'Visible','off');
               set(controls.frame1tab2,'Position',[118 594 102 11]);
               set(controls.frame1tab3,'Position',[221 594 102 11]);
               set(controls.frame1tab4,'Position',[324 594 102 11]);
               set(controls.frame1tab5,'Position',[427 594 102 11]);
               set(controls.frame1tab6,'Position',[529 594 104 11]);
               set(controls.tab1,'Position',[15 602 102 23]);
               set(controls.tab2,'Position',[118 602 102 23]);
               set(controls.tab3,'Position',[221 602 102 23]);
               set(controls.tab4,'Position',[324 602 102 23]);
               set(controls.tab5,'Position',[427 602 102 23]);
               set(controls.tab6,'Position',[529 602 104 25]);
               %
               set(controls.dsge.obsfilesbox,'Visible','off');
               set(controls.dsge.priorfilesbox,'Visible','off');
               set(controls.dsge.parameterfilesbox,'Visible','off');
               set(controls.dsge.aimfilesbox,'Visible','off');
               set(controls.dsge.datafiletext,'Visible','off');
               set(controls.dsge.datafile,'Visible','off');
               set(controls.dsge.datafilebutton,'Visible','off');
               set(controls.dsge.priorfiletext,'Visible','off');
               set(controls.dsge.priorfile,'Visible','off');
               set(controls.dsge.priorfilebutton,'Visible','off');
               set(controls.dsge.priorfilesheet,'Visible','off');
               set(controls.dsge.updateparameterfiletext,'Visible','off');
               set(controls.dsge.updateparameterfile,'Visible','off');
               set(controls.dsge.updateparameterfilebutton,'Visible','off');
               set(controls.dsge.initialparameterfiletext,'Visible','off');
               set(controls.dsge.initialparameterfile,'Visible','off');
               set(controls.dsge.initialparameterfilebutton,'Visible','off');
               set(controls.dsge.runinitialfirst,'Visible','off');
               set(controls.dsge.measurefiletext,'Visible','off');
               set(controls.dsge.measurefile,'Visible','off');
               set(controls.dsge.measurefilebutton,'Visible','off');
               set(controls.dsge.aimfiletext,'Visible','off');
               set(controls.dsge.aimfile,'Visible','off');
               set(controls.dsge.aimfilebutton,'Visible','off');
               set(controls.dsge.modelnametext,'Visible','off');
               set(controls.dsge.modelnameaxes,'Visible','off');
               set(controls.dsge.modelname,'Visible','off');
               set(controls.dsge.modelnamebutton,'Visible','off');
               %
               set(controls.dsge.posteriorsamplingbox,'Visible','off');
               set(controls.dsge.marginallikelihoodtext,'Visible','off');
               set(controls.dsge.marginallikelihood,'Visible','off');
               set(controls.dsge.sequantialmltext,'Visible','off');
               set(controls.dsge.sequentialstart,'Visible','off');
               set(controls.dsge.sequentialstep,'Visible','off');
               set(controls.dsge.coverageprobtext,'Visible','off');
               set(controls.dsge.coveragestart,'Visible','off');
               set(controls.dsge.coverageincrement,'Visible','off');
               set(controls.dsge.coverageend,'Visible','off');
               set(controls.dsge.sequentialml,'Visible','off');
               set(controls.dsge.overwritedraws,'Visible','off');
               set(controls.dsge.progressbox,'Visible','off');
               set(controls.dsge.progress,'Visible','off');
               set(controls.dsge.progressclock,'Visible','off');
               set(controls.dsge.kalmanbox,'Visible','off');
               set(controls.dsge.doublingalgorithmtext,'Visible','off');
               set(controls.dsge.doublingalgorithm,'Visible','off');
               set(controls.dsge.doublingtolerancetext,'Visible','off');
               set(controls.dsge.doublingtolerance,'Visible','off');
               set(controls.dsge.statecovariancetext,'Visible','off');
               set(controls.dsge.statecovariance,'Visible','off');
               set(controls.dsge.initializekalmantext,'Visible','off');
               set(controls.dsge.initializekalman,'Visible','off');
               set(controls.dsge.aimtolerancetext,'Visible','off');
               set(controls.dsge.aimtolerance,'Visible','off');
               set(controls.dsge.usedoublingalgorithmtext,'Visible','off');
               set(controls.dsge.usedoublingalgorithm,'Visible','off');
               set(controls.dsge.useowninitialstate,'Visible','off');
               set(controls.dsge.allowunitroot,'Visible','off');
               set(controls.dsge.sampleselect,'Visible','off');
               set(controls.dsge.subsample,'Visible','off');
               set(controls.dsge.subbeginyear,'Visible','off');
               set(controls.dsge.subbeginperiod,'Visible','off');
               set(controls.dsge.subsampleseparator,'Visible','off');
               set(controls.dsge.subendyear,'Visible','off');
               set(controls.dsge.subendperiod,'Visible','off');
               %
               set(controls.posteriorsamplingbox,'Visible','off');
               set(controls.posterior.drawstext,'Visible','off');
               set(controls.posterior.draws,'Visible','off');
               set(controls.posterior.batchtext,'Visible','off');
               set(controls.posterior.batch,'Visible','off');
               set(controls.posterior.chainstext,'Visible','off');
               set(controls.posterior.chains,'Visible','off');
               set(controls.posterior.burnintext,'Visible','off');
               set(controls.posterior.burnin,'Visible','off');
               set(controls.posterior.invhessiantext,'Visible','off');
               set(controls.posterior.invhessian,'Visible','off');
               set(controls.posterior.maxcorrelationtext,'Visible','off');
               set(controls.posterior.maxcorrelation,'Visible','off');
               set(controls.posterior.initialscaletext,'Visible','off');
               set(controls.posterior.initialscale,'Visible','off');
               set(controls.posterior.scalefactortext,'Visible','off');
               set(controls.posterior.scalefactor,'Visible','off');
               set(controls.posterior.randomweighttext,'Visible','off');
               set(controls.posterior.randomweight,'Visible','off');
               set(controls.posterior.postdrawsusagetext,'Visible','off');
               set(controls.posterior.postdrawsusage,'Visible','off');
               set(controls.posterior.usepostdrawstext,'Visible','off');
               set(controls.posterior.usepostdraws,'Visible','off');
               set(controls.forecastbox,'Visible','off');
               set(controls.forecast.maxhorizontext,'Visible','off');
               set(controls.forecast.maxhorizon,'Visible','off');
%               set(controls.forecast.freqreesttext,'Visible','off');
%               set(controls.forecast.freqreest,'Visible','off');
               set(controls.forecast.predpathstext,'Visible','off');
               set(controls.forecast.predpaths,'Visible','off');
               set(controls.forecast.shockcontroltext,'Visible','off');
               set(controls.forecast.shockcontrol,'Visible','off');
               set(controls.forecast.adjustpredictionpaths,'Visible','off');
               set(controls.forecast.ksiuseconddata,'Visible','off');
               set(controls.toolsbox,'Visible','off');
               set(controls.tools.riccatiiterationtext,'Visible','off');
               set(controls.tools.riccatiiteration,'Visible','off');
               set(controls.tools.riccatitolerancetext,'Visible','off');
               set(controls.tools.riccatitolerance,'Visible','off');
               set(controls.tools.irhorizontext,'Visible','off');
               set(controls.tools.irhorizon,'Visible','off');
               set(controls.tools.randomnumber,'Visible','off');
               set(controls.tools.randomizedraws,'Visible','off');
               set(controls.optimizationbox,'Visible','off');
               set(controls.optimize.maxroutinetext,'Visible','off');
               set(controls.optimize.maxroutine,'Visible','off');
               set(controls.optimize.tolerancetext,'Visible','off');
               set(controls.optimize.tolerance,'Visible','off');
               set(controls.optimize.maximumiterationstext,'Visible','off');
               set(controls.optimize.maximumiterations,'Visible','off');
               set(controls.optimize.initcsminweltext,'Visible','off');
               set(controls.optimize.initcsminwel,'Visible','off');
               set(controls.optimize.steplengthtext,'Visible','off');
               set(controls.optimize.steplength,'Visible','off');
               set(controls.optimize.gridwidthtext,'Visible','off');
               set(controls.optimize.gridwidth,'Visible','off');
               set(controls.optimize.numbergridpointstext,'Visible','off');
               set(controls.optimize.numbergridpoints,'Visible','off');
               set(controls.optimize.finitediffhessian,'Visible','off');
               set(controls.optimize.checkoptimum,'Visible','off');
               set(controls.optimize.checktransformed,'Visible','off');
               set(controls.optimize.modifiedhessian,'Visible','off');
               %
               set(controls.kerneldensitybox,'Visible','off');
               set(controls.graphics.posteriorkerneltext,'Visible','off');
               set(controls.graphics.posteriorkernel,'Visible','off');
               set(controls.graphics.kerneldensitytext,'Visible','off');
               set(controls.graphics.kerneldensity,'Visible','off');
               set(controls.graphics.priorkernel,'Visible','off');
               %
               set(controls.steadystatebox,'Visible','off');
               set(controls.bvar.steadystatefiletext,'Visible','off');
               set(controls.bvar.steadystatefile,'Visible','off');
               set(controls.bvar.steadystatefilebutton,'Visible','off');
               set(controls.bvarpriorbox,'Visible','off');
               set(controls.bvar.priorlevelmeantext,'Visible','off');
               set(controls.bvar.priorlevelmean,'Visible','off');
               set(controls.bvar.priordiffmeantext,'Visible','off');
               set(controls.bvar.priordiffmean,'Visible','off');
               set(controls.bvar.priortypetext,'Visible','off');
               set(controls.bvar.priortype,'Visible','off');
               set(controls.bvar.overalltightnesstext,'Visible','off');
               set(controls.bvar.overalltightness,'Visible','off');
               set(controls.bvar.crosseqtightnesstext,'Visible','off');
               set(controls.bvar.crosseqtightness,'Visible','off');
               set(controls.bvar.harmoniclagdecaytext,'Visible','off');
               set(controls.bvar.harmoniclagdecay,'Visible','off');
               set(controls.omegapriorbox,'Visible','off');
               set(controls.bvar.omegapriortypetext,'Visible','off');
               set(controls.bvar.omegapriortype,'Visible','off');
               set(controls.bvar.wisharttypetext,'Visible','off');
               set(controls.bvar.wisharttype,'Visible','off');
               set(controls.bvar.variancetightnesstext,'Visible','off');
               set(controls.bvar.variancetightness,'Visible','off');
               set(controls.bvar.wishartdftext,'Visible','off');
               set(controls.bvar.wishartdf,'Visible','off');
               set(controls.bvarlagbox,'Visible','off');
               set(controls.bvar.lagtext,'Visible','off');
               set(controls.bvar.lag,'Visible','off');
               %
               set(controls.outputselect,'Visible','on');
               set(controls.outputdirtext,'Visible','on');
               set(controls.outputdir,'Visible','on');
               set(controls.outputbutton,'Visible','on');
               set(controls.estimationlog,'Visible','on');
               set(controls.clearlogwindow,'Visible','on');
               set(controls.estimation_log,'Visible','on');
            end;
         end;
         set(controls.about,'UserData',0);
      end;
   case 'editmodelname'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % make sure to disable all run controls
         %
         OldNameOfModel = DSGEModel.NameOfModel;
         AiMEnable = get(controls.runaim,'Enable');
         StateEnable = get(controls.statevar,'Enable');
         prior_enable = get(controls.priorinfo,'Enable');
         set(controls.runaim,'Enable','off');
         set(controls.runaimmenu,'Enable','off');
         set(controls.aimmodelinfo,'Enable','off');
         set(controls.priorinfo,'Enable','off');
         set(controls.statevar,'Enable','off');
         set(controls.statevarmenu,'Enable','off');
         set(controls.stateshock,'Enable','off');
         set(controls.stateshockmenu,'Enable','off');
         %
         % set editing on
         %
         set(controls.dsge.modelname,'Editing','on');
         waitfor(controls.dsge.modelname,'editing','off');
         new_name = RemoveIllegalChars(StringTrim(get(controls.dsge.modelname,'String')));
         %
         % check if name has changed
         %
         if (isempty(OldNameOfModel)==0)&(strcmp(lower(OldNameOfModel),lower(new_name))==0);
            txt = ['Are you sure you want to change the model name from "' OldNameOfModel '" to "' new_name '"?'];
            answer = Query(txt,'question',140,'Change Model Name',400,'no',CurrINI);
         else;
            answer = 'Yes';
         end;
         if strcmp(lower(answer),'yes')==1;
            if (strcmp(new_name,'')==0)&(ischar(new_name)==1);
               DSGEModel.NameOfModel = new_name;
            elseif (strcmp(new_name,'')==1)|(isempty(new_name)==1);
               %
               % check if an AiM file exists
               %
               if FileExist(DSGEModel.AIMFile)==0;
                  DSGEModel.NameOfModel = '';
               end;
            end;
            set(controls.dsge.modelname,'String',DSGEModel.NameOfModel);
            if strcmp(DSGEModel.NameOfModel,'')==0;
               if FileExist(CurrINI.CurrentModelFile)==1;
                  set(maingui,'Name',['YADA - ' DSGEModel.NameOfModel ' - [' GetFilename(CurrINI.CurrentModelFile) ']']);
               else;
                  set(maingui,'Name',['YADA - ' DSGEModel.NameOfModel]);
               end;
            else;
               set(maingui,'Name','YADA');
            end;
         else;
            set(controls.dsge.modelname,'String',DSGEModel.NameOfModel);
         end;
         %
         % make sure we enable all run controls that were diabled
         %
         set(controls.runaim,'Enable',AiMEnable);
         set(controls.runaimmenu,'Enable',AiMEnable);
         set(controls.aimmodelinfo,'Enable',AiMEnable);
         set(controls.priorinfo,'Enable',prior_enable);
         %
         % check
         %
         if FileExist(DSGEModel.AIMFile)==1;
            %
            % If the modelname has changed, then output directory will also change
            %
            if strcmp(lower(DSGEModel.NameOfModel),lower(OldNameOfModel))==0;
               DSGEModel.OutputDirectory = [GetPath(DSGEModel.AIMFile) DSGEModel.NameOfModel];
               if DirExist(DSGEModel.OutputDirectory)==0;
                  stat = dos(['mkdir ' DSGEModel.OutputDirectory]);
               end;
               set(controls.outputdir,'String',DSGEModel.OutputDirectory);
               set(controls.outputdirtext,'Enable','on');
               set(controls.outputbutton,'Enable','on','CData',CurrINI.images.browse);
               AIMDataFile = [DSGEModel.OutputDirectory '\' DSGEModel.NameOfModel '.mat'];
               if FileExist(AIMDataFile)==1;
                  DSGEModel.AIMDataFile = AIMDataFile;
                  StateEnable = 'on';
               else;
                  DSGEModel.AIMDataFile = pwd;
                  StateEnable = 'off';
               end;
            end;
            set(controls.statevar,'Enable',StateEnable);
            set(controls.statevarmenu,'Enable',StateEnable);
            set(controls.stateshock,'Enable',StateEnable);
            set(controls.stateshockmenu,'Enable',StateEnable);
         else;
            DSGEModel.OutputDirectory = pwd;
            set(controls.runaim,'Enable','off');
            set(controls.runaimmenu,'Enable','off');
            set(controls.aimmodelinfo,'Enable','off');
            set(controls.outputdirtext,'Enable','off');
            set(controls.outputdir,'Enable','off','String',DSGEModel.OutputDirectory);
            set(controls.outputbutton,'Enable','off','CData',CurrINI.images.browsedisable);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'open'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check if there's already a model loaded and if it has been changed.
         %
         if isempty(DSGEModel.NameOfModel)==0;
            status = CompareDSGEModel(DSGEModel,OrigDSGEModel);
            if status==0;
               answer = Query(['Your DSGE model settings have changed. Are you sure you want to open a new model without saving the current model "' DSGEModel.NameOfModel '" first?'],'exit',200,'Open DSGE Model File',500,'no',CurrINI);
            else;
               answer = 'Yes';
            end;
         else;
            answer = 'Yes';
         end;
         %
         % Open a valid DSGE Model File
         %
         if strcmp(lower(answer),'yes')==1;
            [status,ModelFile] = FileBrowse(CurrINI.CurrentModelFile,'Open DSGE Model File',[],'dsge',CurrINI);
            if status==1;
               NewDSGEModel = ReadDSGEModel(ModelFile);
               [NewDSGEModel.SubBeginYearValue,NewDSGEModel.SubBeginPeriodValue,NewDSGEModel.SubEndYearValue,NewDSGEModel.SubEndPeriodValue,NewDSGEModel.YearStrMatrix,NewDSGEModel.PeriodStrMatrix] = CreateEstimationSampleValues(NewDSGEModel);
               [ModelStatus,NewDSGEModel] = VerifyDSGEModel(NewDSGEModel,ModelFile,DSGEModel.DataConstructionFile,CurrINI);
               %
               % if ModelStatus=1, then we can set DSGEModel to NewDSGEModel and adjust the GUI controls!
               %
               if ModelStatus==1;
                  [NewDSGEModel.SubBeginYearValue,NewDSGEModel.SubBeginPeriodValue,NewDSGEModel.SubEndYearValue,NewDSGEModel.SubEndPeriodValue,NewDSGEModel.YearStrMatrix,NewDSGEModel.PeriodStrMatrix] = CreateEstimationSampleValues(NewDSGEModel);
                  DSGEModel = NewDSGEModel;
                  if FileExist([pwd '\addons\wz\DSGECondPredictionPathsWZ.m'])==0;
                     DSGEModel.ShockControlMethod = 1;
                  end;
                  if FileExist([pwd '\addons\wz\CondPredictionKalmanSmoother.m'])==0;
                     DSGEModel.KsiUseCondData = 0;
                  end;
                  if (exist('YADAbetarnd')~=2)|(exist('betarnd')~=2);
                     if DSGEModel.InitializeHessian==8;
                        DSGEModel.InitializeHessian = 5;
                     end;
                  end;
                  StateCStr = get(controls.dsge.statecovariance,'String');
                  DSGEModel.StateCovConstValue = str2num(strrep(StringTrim(StateCStr(DSGEModel.StateCovConst,:)),',',''));
                  set(controls.open,'UserData',DSGEModel);
                  OrigDSGEModel = DSGEModel;
                  set(controls.openmenu,'UserData',OrigDSGEModel);
                  SetYADAUIControls(maingui,DSGEModel,ModelFile,CurrINI.images);
                  %
                  % reset the CurrentModelFile field of CurrINI
                  %
                  CurrINI.CurrentModelFile = ModelFile;
                  CurrINI.ModelFiles = ReOrderModelFiles(CurrINI.ModelFiles,CurrINI.CurrentModelFile);
                  %
                  % Update the menus
                  %
                  if isempty(CurrINI.ModelFiles)==0;
                     controls = MakeModelFilesMenu(controls,CurrINI.ModelFiles,CurrINI.CurrentModelFile,'YADAGUI','openmodel');
                     set(maingui,'UserData',controls);
                  end;
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'openmodel'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check if there's already a model loaded and if it has been changed.
         %
         if isempty(DSGEModel.NameOfModel)==0;
            status = CompareDSGEModel(DSGEModel,OrigDSGEModel);
            if status==0;
               answer = Query(['Your DSGE model settings have changed. Are you sure you want to open a new model without saving the current model "' DSGEModel.NameOfModel '" first?'],'exit',200,'Reopen Model',500,'no',CurrINI);
            else;
               answer = 'Yes';
            end;
         else;
            answer = 'Yes';
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % which item was clicked on
            %
            ModelFile = get(gcbo,'UserData');
            if FileExist(ModelFile)==1;
               NewDSGEModel = ReadDSGEModel(ModelFile);
               [NewDSGEModel.SubBeginYearValue,NewDSGEModel.SubBeginPeriodValue,NewDSGEModel.SubEndYearValue,NewDSGEModel.SubEndPeriodValue,NewDSGEModel.YearStrMatrix,NewDSGEModel.PeriodStrMatrix] = CreateEstimationSampleValues(NewDSGEModel);
               [ModelStatus,NewDSGEModel] = VerifyDSGEModel(NewDSGEModel,ModelFile,DSGEModel.DataConstructionFile,CurrINI);
               %
               % if ModelStatus=1, then we can set DSGEModel to NewDSGEModel and adjust the GUI controls!
               %
               if ModelStatus==1;
                  [NewDSGEModel.SubBeginYearValue,NewDSGEModel.SubBeginPeriodValue,NewDSGEModel.SubEndYearValue,NewDSGEModel.SubEndPeriodValue,NewDSGEModel.YearStrMatrix,NewDSGEModel.PeriodStrMatrix] = CreateEstimationSampleValues(NewDSGEModel);
                  DSGEModel = NewDSGEModel;
                  if FileExist([pwd '\addons\wz\DSGECondPredictionPathsWZ.m'])==0;
                     DSGEModel.ShockControlMethod = 1;
                  end;
                  if FileExist([pwd '\addons\wz\CondPredictionKalmanSmoother.m'])==0;
                     DSGEModel.KsiUseCondData = 0;
                  end;
                  if (exist('YADAbetarnd')~=2)|(exist('betarnd')~=2);
                     if DSGEModel.InitializeHessian==8;
                        DSGEModel.InitializeHessian = 5;
                     end;
                  end;
                  StateCStr = get(controls.dsge.statecovariance,'String');
                  DSGEModel.StateCovConstValue = str2num(strrep(StringTrim(StateCStr(DSGEModel.StateCovConst,:)),',',''));
                  set(controls.open,'UserData',DSGEModel);
                  OrigDSGEModel = DSGEModel;
                  set(controls.openmenu,'UserData',OrigDSGEModel);
                  SetYADAUIControls(maingui,DSGEModel,ModelFile,CurrINI.images);
                  %
                  % reset the CurrentModelFile field of CurrINI
                  %
                  CurrINI.CurrentModelFile = ModelFile;
                  CurrINI.ModelFiles = ReOrderModelFiles(CurrINI.ModelFiles,CurrINI.CurrentModelFile);
                  %
                  % Update the menus
                  %
                  if isempty(CurrINI.ModelFiles)==0;
                     controls = MakeModelFilesMenu(controls,CurrINI.ModelFiles,CurrINI.CurrentModelFile,'YADAGUI','openmodel');
                     set(maingui,'UserData',controls);
                  end;
               else;
                  %
                  % make sure that CurrINI.CurrentModelFile is removed from CurrINI.ModelFiles
                  %
                  CurrINI.ModelFiles = RemoveFromModelFiles(CurrINI.ModelFiles,ModelFile);
                  delete(gcbo);
                  if isempty(CurrINI.ModelFiles)==0;
                     controls = MakeModelFilesMenu(controls,CurrINI.ModelFiles,CurrINI.CurrentModelFile,'YADAGUI','openmodel');
                     set(maingui,'UserData',controls);
                  end;
               end;
            else;
               %
               % the file must very recently have been deleted.
               %
               CurrINI.ModelFiles = RemoveFromModelFiles(CurrINI.ModelFiles,ModelFile);
               delete(gcbo);
               if isempty(CurrINI.ModelFiles)==0;
                  controls = MakeModelFilesMenu(controls,CurrINI.ModelFiles,CurrINI.CurrentModelFile,'YADAGUI','openmodel');
                  set(maingui,'UserData',controls);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'reloadmodel'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         if FileExist(CurrINI.CurrentModelFile)==1;
            NewDSGEModel = ReadDSGEModel(CurrINI.CurrentModelFile);
            [NewDSGEModel.SubBeginYearValue,NewDSGEModel.SubBeginPeriodValue,NewDSGEModel.SubEndYearValue,NewDSGEModel.SubEndPeriodValue,NewDSGEModel.YearStrMatrix,NewDSGEModel.PeriodStrMatrix] = CreateEstimationSampleValues(NewDSGEModel);
            [ModelStatus,NewDSGEModel] = VerifyDSGEModel(NewDSGEModel,CurrINI.CurrentModelFile,DSGEModel.DataConstructionFile,CurrINI);
            if ModelStatus==1;
               [NewDSGEModel.SubBeginYearValue,NewDSGEModel.SubBeginPeriodValue,NewDSGEModel.SubEndYearValue,NewDSGEModel.SubEndPeriodValue,NewDSGEModel.YearStrMatrix,NewDSGEModel.PeriodStrMatrix] = CreateEstimationSampleValues(NewDSGEModel);
               DSGEModel = NewDSGEModel;
               if FileExist([pwd '\addons\wz\DSGECondPredictionPathsWZ.m'])==0;
                  DSGEModel.ShockControlMethod = 1;
               end;
               if FileExist([pwd '\addons\wz\CondPredictionKalmanSmoother.m'])==0;
                  DSGEModel.KsiUseCondData = 0;
               end;
               if (exist('YADAbetarnd')~=2)|(exist('betarnd')~=2);
                  if DSGEModel.InitializeHessian==8;
                     DSGEModel.InitializeHessian = 5;
                  end;
               end;
               StateCStr = get(controls.dsge.statecovariance,'String');
               DSGEModel.StateCovConstValue = str2num(strrep(StringTrim(StateCStr(DSGEModel.StateCovConst,:)),',',''));
               set(controls.open,'UserData',DSGEModel);
               OrigDSGEModel = DSGEModel;
               set(controls.openmenu,'UserData',OrigDSGEModel);
               SetYADAUIControls(maingui,DSGEModel,CurrINI.CurrentModelFile,CurrINI.images);
            end;
         end;
         set(controls.about,'UserData',0);
      end;
   case 'savemodel'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check if we should save using a new name
         %
         if FileExist(CurrINI.CurrentModelFile)==1;
            txt = ['The current file for your DSGE model "' DSGEModel.NameOfModel '" is "' GetFilename(CurrINI.CurrentModelFile) '". Would you like to save it into a new file?'];;
            answer = Query(txt,'question',200,'Save DSGE Model File',450,'no',CurrINI);
         else;
            answer = 'Yes';
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            if FileExist(CurrINI.CurrentModelFile)==0;
               if (strcmp(DSGEModel.NameOfModel,'')==1)|(isempty(DSGEModel.NameOfModel)==1);
                  filename = '*.dsge';
               else;
                  filename = [DSGEModel.NameOfModel '.dsge'];
               end;
               filename = [DSGEModel.OutputDirectory '\' filename];
            else;
               if strcmp(lower([DSGEModel.OutputDirectory '\']),lower(GetPath(CurrINI.CurrentModelFile)))==1;
                  filename = CurrINI.CurrentModelFile;
               else;
                  %
                  % we select a new directory for the DSGE model file based on the OutputDirectory selection
                  %
                  filename = strrep(CurrINI.CurrentModelFile,GetPath(CurrINI.CurrentModelFile),[DSGEModel.OutputDirectory '\']);
               end;
            end;
            if MatlabNumber>=6;
               fileflt = {'*.dsge', 'DSGE Model Files (*.dsge)'};
               [FileName,FilePath] = uiputfile(fileflt,'Save DSGE Model File',filename);
            else;
               [FileName,FilePath] = uiputfile(filename,'Save DSGE Model File');
            end;
            drawnow;
            pause(0.02);
         else;
            FileName = GetFilename(CurrINI.CurrentModelFile);
            FilePath = GetPath(CurrINI.CurrentModelFile);
         end;
         if ischar(FileName)==1;
            NewModelFile = [FilePath FileName];
            %
            % make sure it has the file extension .dsge
            %
            if strcmp(lower(GetExt(NewModelFile)),'.dsge')==0;
               NewModelFile = [FilePath GetName(NewModelFile) '.dsge'];
            end;
            %
            % save the current model data to text file
            %
            SaveDSGEModel(NewModelFile,DSGEModel);
            %
            % update the ModelFiles structure
            %
            CurrINI.CurrentModelFile = NewModelFile;
            CurrINI.ModelFiles = ReOrderModelFiles(CurrINI.ModelFiles,CurrINI.CurrentModelFile);
            %
            % Update the menus
            %
            if isempty(CurrINI.ModelFiles)==0;
               controls = MakeModelFilesMenu(controls,CurrINI.ModelFiles,CurrINI.CurrentModelFile,'YADAGUI','openmodel');
               set(maingui,'UserData',controls);
            end;
            %
            % update the maingui name
            %
            set(maingui,'Name',['YADA - ' DSGEModel.NameOfModel ' - [' GetFilename(CurrINI.CurrentModelFile) ']']);
            %
            % Update the OrigDSGEModel structure
            %
            OrigDSGEModel = DSGEModel;
            set(controls.openmenu,'UserData',OrigDSGEModel);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'closemodel'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check if DSGEModel and OrigDSGEModel structures are equal. If not suggest that DSGE model should be saved
         %
         if isempty(DSGEModel.NameOfModel)==0;
            status = CompareDSGEModel(DSGEModel,OrigDSGEModel);
            if status==0;
               answer = Query(['Your DSGE model settings have changed. Are you sure you want to close the model "' DSGEModel.NameOfModel '"?'],'exit',200,'Close Model',500,'no',CurrINI);
            else;
               answer = 'Yes';
            end;
         else;
            answer = 'Yes';
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % Uncheck any item on the reload model menu
            %
            for i=1:size(CurrINI.ModelFiles,1);
               if (isfield(controls,['openmodel' num2str(i,'%0.0f')])==1)&(ishandle(getfield(controls,['openmodel' num2str(i,'%0.0f')]))==1);
                  set(getfield(controls,['openmodel' num2str(i,'%0.0f')]),'Checked','off');
               else;
                  break;
               end;
            end;
            %
            % reset all controls and initialize the DSGEModel structure
            %
            DSGEModel = InitializeDSGEModel;
            [DSGEModel.SubBeginYearValue,DSGEModel.SubBeginPeriodValue,DSGEModel.SubEndYearValue,DSGEModel.SubEndPeriodValue,DSGEModel.YearStrMatrix,DSGEModel.PeriodStrMatrix] = CreateEstimationSampleValues(DSGEModel);
            StateCStr = get(controls.dsge.statecovariance,'String');
            DSGEModel.StateCovConstValue = str2num(strrep(StringTrim(StateCStr(DSGEModel.StateCovConst,:)),',',''));
            OrigDSGEModel = DSGEModel;
            set(controls.openmenu,'UserData',OrigDSGEModel);
            CurrINI.CurrentModelFile = '';
            SetYADAUIControls(maingui,DSGEModel,CurrINI.CurrentModelFile,CurrINI.images);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'setconfbandbasecolor'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % open the set color dialog
         %
         NewColor = uisetcolor(DSGEModel.ConfidenceBandBaseColor,'Select Base Color');
         %
         % check if the color was changed
         %
         if (isnumeric(NewColor)==1)&(length(NewColor)==3)&(max(abs(NewColor-DSGEModel.ConfidenceBandBaseColor))>0);
            DSGEModel.ConfidenceBandBaseColor = NewColor;
         end;
         set(controls.about,'UserData',0);
      end;
   case 'setinitialstatevalues'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % load the data from AIMDataFile
         %
         ErrorStr = '';
         try;
            AIMData = load(DSGEModel.AIMDataFile);
         catch;
            ErrorStr = ['Unable to load the file "' DSGEModel.AIMDataFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            AllVars = AIMData.endog;
            %
            % which values should we use
            %
            if (isempty(DSGEModel.InitialStateValues)==1)|(isequal(size(AllVars,1),length(DSGEModel.InitialStateValues))==0);
               InitialStateValues = zeros(size(AllVars,1),1);
            else;
               InitialStateValues = DSGEModel.InitialStateValues;
            end;
            %
            % Now we can open a dialog for setting the initial values of all potential state variables
            %
            [action,InitialStateValues] = InitializeStateVarsDLG('init',AllVars,InitialStateValues,CurrINI);
            if strcmp(lower(action),'ok')==1;
               DSGEModel.InitialStateValues = InitialStateValues;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'setconditionalshocks'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % open the dialog for selecting shocks
         %
         [action,positions] = SelectCondVarShockDLG('init','Shocks','Conditioning',DSGEModel.StateShockNames,DSGEModel.ConditionalShocks,CurrINI);
         %
         % check is the action taken was OK or Cancel
         %
         if strcmp(action,'OK')==1;
            %
            % check if positions is empty
            %
            if isempty(positions)==0;
               %
               % check to make sure that the number of selected shocks doesn't exceed the number of possible
               % conditioning variables
               %
               if length(positions)<=size(DSGEModel.Z,1);
                  if (isempty(DSGEModel.ConditionalShocks)==1)|(isequal(positions,DSGEModel.ConditionalShocks)==0)
                     DSGEModel.ConditionalShocks = positions;
                     if length(DSGEModel.ConditionalShocks)>length(DSGEModel.ConditionalVariables);
                        %
                        % we need to increase the number of conditioning variables
                        %
                        OldNumVars = length(DSGEModel.ConditionalVariables);
                        AddConditionalVariables = setdiff((1:length(DSGEModel.ConditionalShocks)),DSGEModel.ConditionalVariables);
                        DSGEModel.ConditionalVariables = sort([DSGEModel.ConditionalVariables AddConditionalVariables(1:length(DSGEModel.ConditionalShocks)-length(DSGEModel.ConditionalVariables))]);
                        txt = ['The number of variables for conditioning has been increased from ' num2str(OldNumVars,'%0.0f') ' to ' num2str(length(DSGEModel.ConditionalVariables),'%0.0f') '. Please make sure that the variables you want to use are the correct ones.'];
                        About(txt,'information','Conditional Variable Changes',150,500,CurrINI);
                     elseif length(DSGEModel.ConditionalShocks)<length(DSGEModel.ConditionalVariables);
                        %
                        % we need to decrease the number of conditioning variables
                        %
                        OldNumVars = length(DSGEModel.ConditionalVariables);
                        DSGEModel.ConditionalVariables = DSGEModel.ConditionalVariables(1:length(DSGEModel.ConditionalShocks));
                        txt = ['The number of variables for conditioning has been decreased from ' num2str(OldNumVars,'%0.0f') ' to ' num2str(length(DSGEModel.ConditionalVariables),'%0.0f') '. Please make sure that the variables you want to use are the correct ones.'];
                        About(txt,'information','Conditional Variable Changes',150,500,CurrINI);
                     end;
                  end;
               else;
                  txt = ['The number of selected conditioning shocks exceeds the number of possible conditioning variables. This is not a valid choice in YADA. You can at most select ' num2str(size(DSGEModel.Z,1),'%0.0f') ' conditioning shocks.'];
                  About(txt,'information','Bad Conditional Shocks Selection',120,500,CurrINI);
               end;
            else;
               txt = 'You didn''t select any conditioning shocks. This is not a valid choice in YADA. You must at least select one conditioning shock.';
               About(txt,'information','Bad Conditional Shocks Selection',120,500,CurrINI);
            end;
         end;
         set(controls.about,'UserData',0);
      end;
   case 'setconditionalvars'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % open the dialog for selecting variables
         %
         [action,positions] = SelectCondVarShockDLG('init','Variables','Conditioning',DSGEModel.ZVariableNames,DSGEModel.ConditionalVariables,CurrINI);
         %
         % check is the action taken was OK or Cancel
         %
         if strcmp(action,'OK')==1;
            %
            % check if positions is empty
            %
            if isempty(positions)==0;
               DSGEModel.ConditionalVariables = positions;
               if length(DSGEModel.ConditionalVariables)>length(DSGEModel.ConditionalShocks);
                  %
                  % make sure that the number of shocks for conditioning is increased
                  %
                  OldNumShocks = length(DSGEModel.ConditionalShocks);
                  AddConditionalShocks = setdiff((1:length(DSGEModel.ConditionalVariables)),DSGEModel.ConditionalShocks);
                  DSGEModel.ConditionalShocks = sort([DSGEModel.ConditionalShocks AddConditionalShocks(1:length(DSGEModel.ConditionalVariables)-length(DSGEModel.ConditionalShocks))]);
                  txt = ['The number of shocks for conditioning has been increased from ' num2str(OldNumShocks,'%0.0f') ' to ' num2str(length(DSGEModel.ConditionalShocks),'%0.0f') '. Please make sure that the shocks you want to use are the correct ones.'];
                  About(txt,'information','Conditional Shock Changes',150,500,CurrINI);
               elseif length(DSGEModel.ConditionalVariables)<length(DSGEModel.ConditionalShocks);
                  %
                  % make sure that the number of shocks for conditioning is decreased
                  %
                  OldNumShocks = length(DSGEModel.ConditionalShocks);
                  DSGEModel.ConditionalShocks = DSGEModel.ConditionalShocks(1:length(DSGEModel.ConditionalVariables));
                  %
                  % inform the user about the change
                  %
                  txt = ['The number of shocks for conditioning has been decreased from ' num2str(OldNumShocks,'%0.0f') ' to ' num2str(length(DSGEModel.ConditionalShocks),'%0.0f') '. Please make sure that the shocks you want to use are the correct ones.'];
                  About(txt,'information','Conditional Shock Changes',150,500,CurrINI);
               end;
            else;
               txt = 'You didn''t select any conditioning variables. This is not a valid choice in YADA. You must at least select one conditioning variable.';
               About(txt,'information','Bad Conditional Variables Selection',120,500,CurrINI);
            end;
         end;
         set(controls.about,'UserData',0);
      end;
%   case 'reorderconditionalshocks'
%      if get(controls.about,'UserData')==0;
%         set(controls.about,'UserData',1);
%         %
%         % open the dialog for selecting shocks
%         %
%         [action,ConditionalShocks] = ReOrderShockDLG('init','Conditional',DSGEModel.ZVariableNames(DSGEModel.ConditionalVariables,:),DSGEModel.StateShockNames,DSGEModel.ConditionalShocks,CurrINI);
%         if strcmp(lower(action),'ok')==1;
%            DSGEModel.ConditionalShocks = ConditionalShocks;
%         end;
%         %
%         set(controls.about,'UserData',0);
%      end;
   case 'setunitrootstatevars'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % load the data from AIMDataFile
         %
         ErrorStr = '';
         try;
            AIMData = load(DSGEModel.AIMDataFile);
         catch;
            ErrorStr = ['Unable to load the file "' DSGEModel.AIMDataFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            AllVars = AIMData.endog;
            clear('AIMData');
            %
            % check if we should initialize the StateVariableNames string matrix and StateVariablePositions vector
            %
            if isempty(DSGEModel.UnitRootStates)==1;
               UnitRootStateNames = '';
            else;
               UnitRootStateNames = AllVars(DSGEModel.UnitRootStates,:);
            end;
            [action,NewUnitRootStateNames,NewUnitRootStates] = SetStateVarsShocksDLG('init','Unit-Root State Variables',AllVars,UnitRootStateNames,DSGEModel.UnitRootStates,CurrINI);
            if strcmp(action,'OK')==1;
               if isempty(intersect(NewUnitRootStates,DSGEModel.StateShockPositions))==1;
                  if isempty(NewUnitRootStates)==0;
                     %
                     % check if the suggested unit-root state variables are indeed unit root processes at the initial values
                     %
                     [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
                     if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
                        ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
                        if FileExist(ModeFile)==1;
                           ErrorStr = '';
                           try;
                              ModeData = load(ModeFile);
                           catch;
                              ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                           end;
                           if isempty(ErrorStr)==1;
                              theta = ModeData.theta;
                              thetaPositions = ModeData.thetaPositions;
                              ModelParameters = ModeData.ModelParameters;
                              ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                              InitStatus = 1;
                           end;
                        end;
                     end;
                     %
                     if InitStatus==1;
                        %
                        % load the AIMData file
                        %
                        AIMData = load(DSGEModel.AIMDataFile);
                        %
                        % check if we can solve the model
                        %
                        ErrorStr = '';
                        try;
                           [A,H,R,F,B0,mcode] = SolveDSGEModel(DSGEModel,theta,thetaPositions,ModelParameters,AIMData);
                           if isempty(lasterr)==0;
                              ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
                           end;
                        catch;
                           ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
                        end;
                        if strcmp(ErrorStr,'')==1;
                           if mcode==1;
                              %
                              % check first if the model has unit roots
                              %
                              EigenValuesF = abs(eig(F));
                              UnitEigenValuesF = (EigenValuesF==1);
                              UnitEigenValuesF = UnitEigenValuesF(UnitEigenValuesF>0);
                              if length(UnitEigenValuesF)==length(NewUnitRootStates);
                                 %
                                 % remove the columns and rows corresponding to Positions from F and then check the eigenvalues
                                 %
                                 KeepPositions = GetPosition(DSGEModel.StateVariablePositions,NewUnitRootStates);
                                 if isempty(KeepPositions)==0;
                                    EigenFall = abs(eig(F(KeepPositions,KeepPositions)));
                                    if max(EigenFall)<1;
                                       %
                                       % we have managed to pinpoint all unit root processes correctly
                                       %
                                       DSGEModel.UnitRootStates = NewUnitRootStates;
                                    else;
                                       UnitEigenFall = (EigenFall==1);
                                       UnitEigenFall = UnitEigenFall(UnitEigenFall>0);
                                       if length(UnitEigenFall)==1;
                                          sStr3 = '';
                                       else;
                                          sStr3 = 's';
                                       end;
                                       txt = ['The DSGE model still has ' int2str(length(UnitEigenFall)) ' unit root' sStr3 '. You must therefore change the specification of unit-root state variables.'];
                                       About(txt,'information','Specify Unit-Root State Variables',200,500,CurrINI);
                                    end;
                                 else;
                                    %
                                    % all state variables are unit root processes :)
                                    %
                                    DSGEModel.UnitRootStates = NewUnitRootStates;
                                 end;
                              else;
                                 if length(UnitEigenValuesF)==1;
                                    sStr1 = '';
                                 else;
                                    sStr1 = 's';
                                 end;
                                 if length(NewUnitRootStates)==1;
                                    sStr2 = '';
                                 else;
                                    sStr2 = 's';
                                 end;
                                 txt = ['The DSGE model has ' int2str(length(UnitEigenValuesF)) ' unit root' sStr1 ', while you have specified ' int2str(length(NewUnitRootStates)) ' state variable' sStr2 ' with a unit root. These numbers must be equal. YADA is therefore unable to accept the specified state variable' sStr2 '.'];
                                 About(txt,'information','Specify Unit-Root State Variables',200,500,CurrINI);
                              end;
                           else;
                              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 '". YADA is therefore unable to accept the specification of any state variables as unit-root processes.'];
                              About(txt,'information','Specify Unit-Root State Variables',200,500,CurrINI);
                           end;
                        else;
                           About(ErrorStr,'information','YADA - Error Message',200,500,CurrINI);
                        end;
                     end;
                  else;
                     if isempty(DSGEModel.UnitRootStates)==0;
                        %
                        % check if the model has any unit roots at the initial values
                        %
                        [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
                        if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
                           ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
                           if FileExist(ModeFile)==1;
                              ErrorStr = '';
                              try;
                                 ModeData = load(ModeFile);
                              catch;
                                 ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                              end;
                              if isempty(ErrorStr)==1;
                                 theta = ModeData.theta;
                                 thetaPositions = ModeData.thetaPositions;
                                 ModelParameters = ModeData.ModelParameters;
                                 ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                                 InitStatus = 1;
                              end;
                           end;
                        end;
                        %
                        if InitStatus==1;
                           %
                           % load the AIMData file
                           %
                           AIMData = load(DSGEModel.AIMDataFile);
                           %
                           % check if we can solve the model
                           %
                           ErrorStr = '';
                           try;
                              [A,H,R,F,B0,mcode] = SolveDSGEModel(DSGEModel,theta,thetaPositions,ModelParameters,AIMData);
                              if isempty(lasterr)==0;
                                 ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
                              end;
                           catch;
                              ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
                           end;
                           if strcmp(ErrorStr,'')==1;
                              if mcode==1;
                                 %
                                 % check if the model has unit roots
                                 %
                                 EigenValuesF = abs(eig(F));
                                 UnitEigenValuesF = (EigenValuesF==1);
                                 UnitEigenValuesF = UnitEigenValuesF(UnitEigenValuesF>0);
                                 if isempty(UnitEigenValuesF)==1;
                                    DSGEModel.UnitRootStates = [];
                                 else;
                                    if length(UnitEigenValuesF)==1;
                                       sStr = '';
                                    else;
                                       sStr = 's';
                                    end;
                                    txt = ['The DSGE model has ' int2str(length(UnitEigenValuesF)) ' unit root' sStr ', while you have specified 0 (zero) state variables with a unit root. These numbers must be equal. YADA is therefore unable to accept the choice of zero unit-root state variables.'];
                                    About(txt,'information','Specify Unit-Root State Variables',200,500,CurrINI);
                                 end;
                              else;
                                 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 '". YADA is therefore unable to accept the specification of any state variables as unit-root processes.'];
                                 About(txt,'information','Specify Unit-Root State Variables',200,500,CurrINI);
                              end;
                           else;
                              About(ErrorStr,'information','YADA - Error Message',200,500,CurrINI);
                           end;
                        end;
                     end;
                  end;
               else;
                  %
                  % display an error message
                  %
                  pos = intersect(NewUnitRootStates,DSGEModel.StateShockPositions);
                  badVars = AllVars(pos,:);
                  if size(badVars,1)>1;
                     badVars = StringTrim(vecstr(badVars,', '));
                     badVars = badVars(1,1:length(badVars)-1);
                  else;
                     badVars = StringTrim(badVars);
                  end;
                  txt = [num2str(length(pos)) ' of the variables you have specified as unit-root state variables are also set as state shocks (' badVars '). YADA requires that the sets of unit-root state variables and shocks are mutually exclusive.'];
                  About(txt,'information','Bad Unit-Root State Variables Specification',120,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'setstatevars'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % load the data from AIMDataFile
         %
         ErrorStr = '';
         try;
            AIMData = load(DSGEModel.AIMDataFile);
         catch;
            ErrorStr = ['Unable to load the file "' DSGEModel.AIMDataFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            AllVars = AIMData.endog;
            clear('AIMData');
            %
            % check if we should initialize the StateVariableNames string matrix and StateVariablePositions vector
            %
            if (isempty(DSGEModel.StateVariablePositions)==1)|(size(AllVars,1)<max(DSGEModel.StateVariablePositions));
               pos_shock = LocateStrs(AllVars,'eta');
               pos_one = LocateStr(AllVars,'one');
               pos_ONE = LocateStr(AllVars,'ONE');
               pos = (1:1:size(AllVars,1));
               StateVariablePositions = setdiff(pos,[pos_one pos_ONE pos_shock]);
               StateVariableNames = AllVars(StateVariablePositions,:);
            else;
               StateVariableNames = DSGEModel.StateVariableNames;
               StateVariablePositions = DSGEModel.StateVariablePositions;
            end;
            %
            % Open a GUI sending AllVars, DSGEModel.StateVariableNames, DSGEModel.StateVariablePositions as input
            %
            [action,NewStateVariableNames,NewStateVariablePositions] = SetStateVarsShocksDLG('init','State Variables',AllVars,StateVariableNames,StateVariablePositions,CurrINI);
            if strcmp(action,'OK')==1;
               %
               % need to check if NewStateVariablePositions and DSGEModel.StateShockPositions have common entries.
               % This is not allowed
               %
               if isempty(intersect(NewStateVariablePositions,DSGEModel.StateShockPositions))==1;
                  if (isequal(NewStateVariableNames,DSGEModel.StateVariableNames)==0)|(length(NewStateVariablePositions)~=length(DSGEModel.StateVariablePositions))|(max(abs(NewStateVariablePositions-DSGEModel.StateVariablePositions))>0);
                     %
                     % Entries were accepted and have changed
                     %
                     DSGEModel.StateVariableNames = NewStateVariableNames;
                     DSGEModel.StateVariablePositions = NewStateVariablePositions;
                     %
                     % test if the unit root state variables 
                     %
                     if isempty(DSGEModel.UnitRootStates)==0;
                        if isequal(intersect(DSGEModel.UnitRootStates,DSGEModel.StateVariablePositions),DSGEModel.UnitRootStates)==0;
                           DSGEModel.UnitRootStates = [];
                        end;
                     end;
                  end;
               else;
                  %
                  % display an error message
                  %
                  pos = intersect(NewStateVariablePositions,DSGEModel.StateShockPositions);
                  badVars = AllVars(pos,:);
                  if size(badVars,1)>1;
                     badVars = StringTrim(vecstr(badVars,', '));
                     badVars = badVars(1,1:length(badVars)-1);
                  else;
                     badVars = StringTrim(badVars);
                  end;
                  txt = [num2str(length(pos)) ' of the variables you have set as state variables are also set as state shocks (' badVars '). YADA requires that the sets of state variables and shocks are mutually exclusive.'];
                  About(txt,'information','Bad State Variables Selection',120,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'setstateshocks'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % load the data from AIMDataFile
         %
         ErrorStr = '';
         try;
            AIMData = load(DSGEModel.AIMDataFile);
         catch;
            ErrorStr = ['Unable to load the file "' DSGEModel.AIMDataFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            AllVars = AIMData.endog;
            clear('AIMData');
            %
            % check if we should initialize the StateShockNames string matrix and StateShockPositions vector
            %
            if (isempty(DSGEModel.StateShockPositions)==1)|(size(AllVars,1)<max(DSGEModel.StateShockPositions));
               StateShockPositions = LocateStrs(AllVars,'eta');
               StateShockNames = AllVars(StateShockPositions,:);
            else;
               StateShockNames = DSGEModel.StateShockNames;
               StateShockPositions = DSGEModel.StateShockPositions;
            end;
            %
            % Open a GUI sending AllVars, DSGEModel.StateShockNames, DSGEModel.StateShockPositions as input
            %
            [action,NewStateShockNames,NewStateShockPositions] = SetStateVarsShocksDLG('init','State Shocks',AllVars,StateShockNames,StateShockPositions,CurrINI);
            if strcmp(action,'OK')==1;
               %
               % need to check if NewStateShockPositions and DSGEModel.StateVariablePositions have common entries
               % This is not allowed!
               %
               if isempty(intersect(NewStateShockPositions,DSGEModel.StateVariablePositions))==1;
                  if (isequal(NewStateShockNames,DSGEModel.StateShockNames)==0)|(length(NewStateShockPositions)~=length(DSGEModel.StateShockPositions))|(max(abs(NewStateShockPositions-DSGEModel.StateShockPositions))>0);
                     %
                     % check if we need to adjust DSGEModel.ConditionalShocks
                     %
                     RemovedConditionalShocks = 0;
                     if isempty(DSGEModel.ConditionalShocks)==0;
                        if length(NewStateShockPositions)<max(DSGEModel.ConditionalShocks);
                           ConditionalShocks = DSGEModel.ConditionalShocks(DSGEModel.ConditionalShocks<=length(NewStateShockPositions));
                           RemovedConditionalShocks = length(DSGEModel.ConditionalShocks)-length(ConditionalShocks);
                           DSGEModel.ConditionalShocks = ConditionalShocks;
                           DSGEModel.ConditionalVariables = DSGEModel.ConditionalVariables(1:length(ConditionalShocks));
                        end;
                     end;
                     RemovedScenarioShocks = 0;
                     if isempty(DSGEModel.ScenarioShocks)==0;
                        if length(NewStateShockPositions)<max(DSGEModel.ScenarioShocks);
                           ScenarioShocks = DSGEModel.ScenarioShocks(DSGEModel.ScenarioShocks<=length(NewStateShockPositions));
                           RemovedScenarioShocks = length(DSGEModel.ScenarioShocks)-length(ScenarioShocks);
                           DSGEModel.ScenarioShocks = ScenarioShocks;
                           DSGEModel.ScenarioVariables = DSGEModel.ScenarioVariables(1:length(ScenarioShocks));
                        end;
                     end;
                     %
                     % Entries were accepted
                     %
                     DSGEModel.StateShockNames = NewStateShockNames;
                     DSGEModel.StateShockPositions = NewStateShockPositions;
                     DSGEModel.ShockGroups = (1:length(DSGEModel.StateShockPositions));
                     DSGEModel.ShockGroupNames = DSGEModel.StateShockNames;
                     %
                     % check if we should display an information dialog about the number of
                     % conditioning shocks/variables and scenario shocks/variables that were
                     % removed.
                     %
                     if (RemovedConditionalShocks>0)|(RemovedScenarioShocks>0);
                        RemovedDataStr = '';
                        if RemovedConditionalShocks>0;
                           sStr = '';
                           if RemovedConditionalShocks>1;
                              sStr = 's';
                           end;
                           RemovedDataStr = [int2str(RemovedConditionalShocks) ' shock' sStr ' and variable' sStr ' for the conditional forecasts'];
                        end;
                        if RemovedScenarioShocks>0;
                           sStr = '';
                           if RemovedScenarioShocks>1;
                              sStr = '';
                           end;
                           if isempty(RemovedDataStr)==1;
                              RemovedDataStr = [int2str(RemovedScenarioShocks) ' shock' sStr ' and variable' sStr ' for the observed variable scenario'];
                           else;
                              RemovedDataStr = [RemovedDataStr ' and ' int2str(RemovedScenarioShocks) ' shock' sStr ' and variable' sStr ' for the observed variable scenario'];
                           end;
                        end;
                        %
                        txt = ['Please notice that the changes you''ve made to the selected state shocks has forced YADA to change certain selections. Specifically, YADA has removed ' RemovedDataStr '.'];
                        About(txt,'information','Shocks Selection Changes',200,500,CurrINI);
                     end;
                  end;
               else;
                  %
                  % display an error message.
                  %
                  pos = intersect(NewStateShockPositions,DSGEModel.StateVariablePositions);
                  badVars = AllVars(pos,:);
                  if size(badVars,1)>1;
                     badVars = StringTrim(vecstr(badVars,', '));
                     badVars = badVars(1,1:length(badVars)-1);
                  else;
                     badVars = StringTrim(badVars);
                  end;
                  txt = [num2str(length(pos)) ' of the variables you have set as state shocks are also set as state variables (' badVars '). YADA requires that the sets of state shocks and variables are mutually exclusive.'];
                  About(txt,'information','Bad State Shocks Selection',120,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'setshockgroups'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         SelectionOptions = '1 shock group';
         for i=2:length(DSGEModel.StateShockPositions);
            SelectionOptions = strvcat(SelectionOptions,[num2str(i,'%0.0f') ' shock groups']);
         end;
         DefaultOption = size(DSGEModel.ShockGroupNames,1);
         SelectionStr = 'Select the number of shock groups';
         BoxStr = 'Shock Groups - Number of Groups';
         WindowNameStr = 'Select Shock Groups';
         %
         % Select how many groups to include
         %
         [action,SelectedOption] = SelectionDlg(SelectionOptions,DefaultOption,SelectionStr,BoxStr,WindowNameStr,'','',CurrINI);
         if strcmp(action,'OK')==1;
            %
            % check if the number of groups have changed and construct the vector ShockGroups
            % and the string matrix ShockGroupNames based on these
            %
            if SelectedOption<DefaultOption;
               ShockGroupNames = '';
               for i=1:SelectedOption;
                  ShockGroupNames = strvcat(ShockGroupNames,StringTrim(DSGEModel.ShockGroupNames(i,:)));
               end;
               ShockGroups = min(DSGEModel.ShockGroups,SelectedOption);
            elseif SelectedOption>DefaultOption;
               ShockGroupNames = '';
               for i=1:size(DSGEModel.ShockGroupNames,1);
                  ShockGroupNames = strvcat(ShockGroupNames,StringTrim(DSGEModel.ShockGroupNames(i,:)));
               end;
               for i=size(DSGEModel.ShockGroupNames,1)+1:SelectedOption;
                  ShockGroupNames = strvcat(ShockGroupNames,['Group number ' num2str(i,'%0.0f')]);
               end;
               ShockGroups = DSGEModel.ShockGroups;
            else;
               ShockGroupNames = DSGEModel.ShockGroupNames;
               ShockGroups = DSGEModel.ShockGroups;
            end;
            if isempty(DSGEModel.ShockGroupColors)==0;
               %
               % need to deal with this issue
               %
               if size(DSGEModel.ShockGroupColors,1)==SelectedOption;
                  ShockGroupColors = DSGEModel.ShockGroupColors;
               elseif size(DSGEModel.ShockGroupColors,1)>SelectedOption;
                  ShockGroupColors = DSGEModel.ShockGroupColors(1:SelectedOption,:);
               else;
                  ShockGroupColors = CreateDefaultColors(size(ShockGroupNames,1));
               end;
            else;
               ShockGroupColors = CreateDefaultColors(size(ShockGroupNames,1));
            end;
            if isempty(DSGEModel.ShockColorStart)==0;
               %
               % need to deal with this issue
               %
               if size(DSGEModel.ShockColorStart,1)==SelectedOption;
                  ShockColorStart = DSGEModel.ShockColorStart;
               elseif size(DSGEModel.ShockColorStart,1)>SelectedOption;
                  ShockColorStart = DSGEModel.ShockColorStart(1:SelectedOption,:);
               else;
                  ShockColorStart = CreateDefaultColors(size(ShockGroupNames,1));
               end;
            else;
               ShockColorStart = CreateDefaultColors(size(ShockGroupNames,1));
            end;
            if isempty(DSGEModel.ShockColorEnd)==0;
               %
               % need to deal with this issue
               %
               if size(DSGEModel.ShockColorEnd,1)==SelectedOption;
                  ShockColorEnd = DSGEModel.ShockColorEnd;
               elseif size(DSGEModel.ShockColorEnd,1)>SelectedOption;
                  ShockColorEnd = DSGEModel.ShockColorEnd(1:SelectedOption,:);
               else;
                  ShockColorEnd = CreateDefaultColors(size(ShockGroupNames,1));
               end;
            else;
               ShockColorEnd = CreateDefaultColors(size(ShockGroupNames,1));
            end;
            %
            % Open a dialog for setting the name of the shock group and select its members
            %
            ChangedGroups = 1;
            NewShockGroups = zeros(1,length(DSGEModel.StateShockPositions));
            NewShockGroupNames = '';
            SelectedShocks = zeros(1,length(DSGEModel.StateShockPositions));
            for i=1:SelectedOption;
               [action,positions,ShockGroupName,ShockGroupColor,ShockColStart,ShockColEnd] = SetShockGroupsDLG('init',i,DSGEModel.StateShockNames,(ShockGroups==i),StringTrim(ShockGroupNames(i,:)),ShockGroupColors(i,:),ShockColorStart(i,:),ShockColorEnd(i,:),CurrINI);
               %
               if strcmp(lower(action),'cancel')==1;
                  ChangedGroups = 0;
                  break;
               else;
                  %
                  % deal with the case when positions is a zero vector, i.e., no selected shock
                  %
                  NewShockGroups = NewShockGroups+(i*positions);
                  NewShockGroupNames = strvcat(NewShockGroupNames,ShockGroupName);
                  SelectedShocks = SelectedShocks+positions;
                  ShockGroupColors(i,:) = ShockGroupColor;
                  ShockColorStart(i,:) = ShockColStart;
                  ShockColorEnd(i,:) = ShockColEnd;
               end;
            end;
            if (ChangedGroups==1)&((isequal(SelectedShocks,ones(1,length(DSGEModel.StateShockPositions)))==0)|(length(unique(NewShockGroups))<SelectedOption));
               ChangedGroups = 0;
               CheckMax = 1;
               if min(SelectedShocks)==0;
                  %
                  % show the first shock that has not been selected
                  %
                  CheckMax = 0;
                  NonSelShock = (SelectedShocks==0) .* (1:length(SelectedShocks));
                  NonSelShock = NonSelShock(NonSelShock>0);
                  txt = ['The shock ' StringTrim(DSGEModel.StateShockNames(NonSelShock(1),:)) ' was not selected. Please make sure that all shocks belong to exactly one group.'];
               end;
               if (CheckMax==1)&(max(SelectedShocks)>1);
                  %
                  % show the first shock that has been selected twice
                  %
                  OverSelShock = (SelectedShocks>=2) .* (1:length(SelectedShocks));
                  OverSelShock = OverSelShock(OverSelShock>0);
                  txt = ['The shock ' StringTrim(DSGEModel.StateShockNames(OverSelShock(1),:)) ' was selected more than once. Please make sure that all shocks belong to exactly one group.'];
               end;
               if length(unique(NewShockGroups))<SelectedOption;
                  UnSelectedGroupsIndex = setdiff((1:SelectedOption),unique(NewShockGroups));
                  %
                  for i=UnSelectedGroupsIndex;
                     if i==UnSelectedGroupsIndex(1);
                        UnSelectedGroups = strrep(StringTrim(NewShockGroupNames(i,:)),'_',' ');
                     elseif (i==UnSelectedGroupsIndex(length(UnSelectedGroupsIndex)))&(length(UnSelectedGroupsIndex)>1);
                        UnSelectedGroups = [UnSelectedGroups '", and "' strrep(StringTrim(NewShockGroupNames(i,:)),'_',' ')]
                     else;
                        UnSelectedGroups = [UnSelectedGroups '", "' strrep(StringTrim(NewShockGroupNames(i,:)),'_',' ')]
                     end;
                  end;
                  if length(UnSelectedGroupsIndex)==1;
                     SStr = '';
                     ESStr = 'es';
                  else;
                     SStr = 's';
                     ESStr = '';
                  end;
                  txt = ['The shock group' SStr ' "' UnSelectedGroups '" do' ESStr ' not have any member' SStr '. Please make sure that each shock group has at least one member.'];
               end;
               About(txt,'information','YADA - Invalid Shock Group Selection',200,500,CurrINI);
            end;
            %
            % Check what may have changed
            %
            if ChangedGroups==1;
               if (isequal(NewShockGroupNames,DSGEModel.ShockGroupNames)==0)|(isequal(NewShockGroups,DSGEModel.ShockGroups)==0)|(isequal(ShockGroupColors,DSGEModel.ShockGroupColors)==0)|(isequal(ShockColorStart,DSGEModel.ShockColorStart)==0)|(isequal(ShockColorEnd,DSGEModel.ShockColorEnd)==0);
                  DSGEModel.ShockGroupNames = NewShockGroupNames;
                  DSGEModel.ShockGroups = NewShockGroups;
                  DSGEModel.ShockGroupColors = ShockGroupColors;
                  DSGEModel.ShockColorStart = ShockColorStart;
                  DSGEModel.ShockColorEnd = ShockColorEnd;
               end;
            end;
         end;
         set(controls.about,'UserData',0);
      end;
   case 'clearlogwindow'
      if get(controls.about,'Userdata')==0;
         set(controls.about,'UserData',1);
         drawnow;
         set(controls.estimation_log,'String','','ListboxTop',1,'UserData',1);
         drawnow;
         set(controls.about,'UserData',0);
      end;
   case 'runaim'
      if get(controls.about,'UserData')==0;
         %
         % Clear the log window
         %
         drawnow;
         set(controls.estimation_log,'String','','ListboxTop',1,'UserData',1);
         drawnow;
         %
         % Switch to the output tab
         %
         oldtab = get(controls.tab1,'UserData');
         set(maingui,'CurrentObject',controls.tab6);
         YADAGUI('tab');
         set(controls.about,'UserData',1);
         %
         % set log text data
         %
         SetLogText(strvcat(' ','Running the AiM Parser...','Using AiM model file:',['   ' GetFilename(DSGEModel.AIMFile)]),maingui);
         %
         % We can now run the aim parser
         %
         [stat,param,np,modname,neq,nlag,nlead,eqname,eqtype,endog,delay,vtype,DOSMessage] = AiMInitialize(DSGEModel.AIMFile,DSGEModel.NameOfModel,DSGEModel.OutputDirectory);
         if stat==0;
            %
            % set the AIMDataFile fields in the DSGEModel structure
            %
            AIMDataFile = [DSGEModel.OutputDirectory '\' DSGEModel.NameOfModel '.mat'];
            if FileExist(AIMDataFile)==1;
               DSGEModel.AIMDataFile = AIMDataFile;
               set(controls.statevar,'Enable','on');
               set(controls.statevarmenu,'Enable','on');
               set(controls.stateshock,'Enable','on');
               set(controls.stateshockmenu,'Enable','on');
            else;
               DSGEModel.AIMDataFile = pwd;
               set(controls.statevar,'Enable','off');
               set(controls.statevarmenu,'Enable','off');
               set(controls.stateshock,'Enable','off');
               set(controls.stateshockmenu,'Enable','off');
            end;
            txt = ['The AiM parser has run successfully. The Matlab m-files "compute_aim_data.m" and "compute_aim_matrices.m" are located in the directory "' DSGEModel.OutputDirectory '\". The Matlab mat-file "' GetName(DSGEModel.AIMFile) '.mat" is also located in this directory. If you remove these files you will need to run the AiM parser again.'];
            %
            % Check if we can enable estimation of posterior mode and drawing using the RW Metropolis algoritgm
            %
            About(txt,'information','AiM Parser',300,500,CurrINI);
         elseif stat==1;
            ErrFile = [DSGEModel.OutputDirectory '\AiMError-' DSGEModel.NameOfModel '.txt'];
            TxTStr = StrWrap(DOSMessage,80);
            fid = fopen(ErrFile,'wt');
            for i=1:size(TxTStr,1);
               fprintf(fid,'%s\n',TxTStr(i,:));
            end;
            fclose(fid);
            %
            txt = ['There was an error parsing the AiM model file "' GetName(DSGEModel.AIMFile) '". AiM parser error written to the file "AiMError-' DSGEModel.NameOfModel '.txt" in the directory "' DSGEModel.OutputDirectory '". Please check that the syntax is correct.'];
            About(txt,'error','AiM Parser Error',200,500,CurrINI);
         elseif stat==2;
            txt = ['The number of data variables is not equal to the number of stochastic variables in the model file "' GetName(DSGEModel.AIMFile) '".'];
            About(txt,'error','AiM Parser Error',200,500,CurrINI);
         else;
            txt = [DOSMessage ' The model file "' GetName(DSGEModel.AIMFile) '" is therefore not valid.'];
            About(txt,'error','AiM Parser Error',200,500,CurrINI);
         end;
         %
         % Now we reset the tab to its previous state.
         %
         set(maingui,'CurrentObject',getfield(controls,['tab' num2str(oldtab)]));
         set(controls.about,'UserData',0);
         YADAGUI('tab');
      end;
   case 'postmode'
      if get(controls.about,'UserData')==0;
         %
         % This case attempts to find the posterior mode through numerical optimization of the joint
         % posterior distribution
         %
         if (strcmp(lower(DSGEModel.UpdateParameterFile),lower(pwd))==1)&(strcmp(lower(DSGEModel.InitializeParameterFile),lower(pwd))==1);
            txt = 'Are you sure that you have specified all the parameters that your DSGE model requires?';
            answer = Query(txt,'logo',120,'No Additional Parameter Files',400,'no',CurrINI);
         else;
            answer = 'Yes';
         end;
         if strcmp(lower(answer),'yes')==1;
            oldtab = get(controls.tab1,'UserData');
            set(maingui,'CurrentObject',controls.tab6);
            YADAGUI('tab');
            set(controls.about,'UserData',1);
            drawnow;
            %
            % check if we should add some diving line to the log-text control
            %
            LogText = get(controls.estimation_log,'String');
            if isempty(LogText)==0;
               SetLogText(strvcat(' ','******************************************************************','*    Y    A    D    A    Y    A    D    A    Y    A    D    A    *','******************************************************************'));
            end;
            %
            % Run the Posterior mode estimation routine
            %
            PosteriorModeEstimation(DSGEModel,CurrINI,controls);
            %
            % we need to enable these things
            %
            set(controls.about,'UserData',0);
%            set(maingui,'CurrentObject',getfield(controls,['tab' num2str(oldtab)]));
%            YADAGUI('tab');
         end;
      end;
   case 'iteratedparameters'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if isempty(ErrorStr)==1;
            if isfield(ModeData,'phiEstimates')==1;
               phiEstimates = ModeData.phiEstimates;
               thetaEstimates = zeros(size(phiEstimates));
               for i=1:size(phiEstimates,2);
                  thetaEstimates(:,i) = PhiToTheta(phiEstimates(:,i),ModeData.thetaIndex,ModeData.UniformBounds,ModeData.LowerBound);
               end;
               %
               % open the graph iterated parameters dialog
               %
               IteratedParamsGraphDLG('init',CurrINI,ModeData.ParameterNames.estimated,[ModeData.theta thetaEstimates])
            else;
               txt = 'The data file with the posterior mode estimates didn''t include the iterated parameter estimates. YADA is therefore unable to display them.';
               About(txt,'information','YADA - Old MAT File',150,500,CurrINI);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'threedeepostmode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if isempty(ErrorStr)==1;
            if gcbo==controls.threedeepostmode.transformed;
               UseTransformed = 1;
            else;
               UseTransformed = 0;
            end;
            %
            % display the dialog for selecting parameters
            %
            ThreeDeeParamsGraphDLG('init',DSGEModel,CurrINI,ModeData,UseTransformed);
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'checkpostmode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % run the check optimum function
         %
         CheckPosteriorMode(DSGEModel,CurrINI,controls);
         set(controls.about,'UserData',0);
      end;
   case 'bvarpostmode'
      if get(controls.about,'UserData')==0;
         %
         % make the output tab visible
         %
         oldtab = get(controls.tab1,'UserData');
         set(maingui,'CurrentObject',controls.tab6);
         YADAGUI('tab');
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Fix the log text control
         %
         LogText = get(controls.estimation_log,'String');
         if isempty(LogText)==0;
            SetLogText(strvcat(' ','******************************************************************','*    Y    A    D    A    Y    A    D    A    Y    A    D    A    *','******************************************************************'));
         end;
         %
         % run the Gibbs sampling algorithm
         %
         BVARPosteriorModeEstimation(DSGEModel,CurrINI,controls);
         %
         set(controls.about,'UserData',0);
%         set(maingui,'CurrentObject',getfield(controls,['tab' num2str(oldtab)]));
%         YADAGUI('tab');
      end;
   case 'gibbs'
      if get(controls.about,'UserData')==0;
         %
         % make the output tab visible
         %
         oldtab = get(controls.tab1,'UserData');
         set(maingui,'CurrentObject',controls.tab6);
         YADAGUI('tab');
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Fix the log text control
         %
         LogText = get(controls.estimation_log,'String');
         if isempty(LogText)==0;
            SetLogText(strvcat(' ','******************************************************************','*    Y    A    D    A    Y    A    D    A    Y    A    D    A    *','******************************************************************'));
         end;
         %
         % run the Gibbs sampling algorithm
         %
         BVARPosteriorSampling(DSGEModel,CurrINI,controls);
         %
         set(controls.about,'UserData',0);
%         set(maingui,'CurrentObject',getfield(controls,['tab' num2str(oldtab)]));
%         YADAGUI('tab');
      end;
   case 'metropolis_hastings'
      if get(controls.about,'UserData')==0;
         %
         % make the output tab visible
         %
         oldtab = get(controls.tab1,'UserData');
         set(maingui,'CurrentObject',controls.tab6);
         YADAGUI('tab');
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Fix the log text control
         %
         LogText = get(controls.estimation_log,'String');
         if isempty(LogText)==0;
            SetLogText(strvcat(' ','******************************************************************','*    Y    A    D    A    Y    A    D    A    Y    A    D    A    *','******************************************************************'));
         end;
         %
         % run the random walk Metropolis algorithm
         %
         DSGEPosteriorSampling(DSGEModel,CurrINI,controls);
         %
         set(controls.about,'UserData',0);
%         set(maingui,'CurrentObject',getfield(controls,['tab' num2str(oldtab)]));
%         YADAGUI('tab');
      end;
   case 'statespacesave_postmode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            %
            % 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)==1;
               %
               % check if we can solve the model
               %
               ErrorStr = '';
               try;
                  [A,H,R,F,B0,mcode] = SolveDSGEModel(DSGEModel,theta,thetaPositions,ModelParameters,AIMData);
                  if isempty(lasterr)==0;
                     ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
                  end;
               catch;
                  ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
               end;
               if strcmp(ErrorStr,'')==1;
                  if mcode==1;
                     file = [DSGEModel.OutputDirectory '\StateSpaceMatrices-' DSGEModel.NameOfModel '-PosteriorMode.mat'];
                     save(file,'A','H','R','F','B0');
                     %
                     mfile = [DSGEModel.OutputDirectory '\SSM' strrep(DSGEModel.NameOfModel,'-','') 'PostMode.m'];
                     %
                     fid = fopen(mfile,'wt');
                     fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                     fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                     fprintf(fid,'%%\n%% M E A S U R E M E N T   E Q U A T I O N\n');
                     fprintf(fid,'%%\n%% matrix with parameters on exogenous variables\n%%\n');
                     fprintf(fid,'A = DataStructure.A;\n');
                     fprintf(fid,'%%\n%% matrix with parameters on state variables\n%%\n');
                     fprintf(fid,'H = DataStructure.H;\n');
                     fprintf(fid,'%%\n%% matrix with measurement error covariances\n%%\n');
                     fprintf(fid,'R = DataStructure.R;\n');
                     fprintf(fid,'%%\n%% S T A T E   E Q U A T I O N\n');
                     fprintf(fid,'%%\n%% matrix with state transition parameters\n%%\n');
                     fprintf(fid,'F = DataStructure.F;\n');
                     fprintf(fid,'%%\n%% matrix with shock parameters\n%%\n');
                     fprintf(fid,'B0 = DataStructure.B0;\n');
                     fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                     %
                     % end the script file
                     %
                     fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                     fclose(fid);
                     %
                     txt = ['The state-space matrices at posterior mode have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 5 entries: A (matrix with parameters on exogenous variables in the measurement equation), H (matrix with parameters on state variables in the measurement equation), R (matrix with measurement error covariances), F (matrix with state transition parameters), and B0 (matrix with shock parameters). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                     About(txt,'information','Save State-Space Matrices - Posterior Mode',200,500,CurrINI);
                     drawnow;
                  else;
                     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','Save State-Space Matrices - Posterior Mode',120,500,CurrINI);
                  end;
               else;
                  About(ErrorStr,'information','YADA - Error Message',200,500,CurrINI);
               end;
            else;
               About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'statespacesave_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
         %
         [InitStatus,theta,thetaPositions,ModelParameters,thetaDist,PriorDist,ParameterNames,thetaIndex,UniformBounds,LowerBound] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
         if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
            ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
            if FileExist(ModeFile)==1;
               ErrorStr = '';
               try;
                  ModeData = load(ModeFile);
               catch;
                  ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
               end;
               if isempty(ErrorStr)==1;
                  theta = ModeData.theta;
                  thetaPositions = ModeData.thetaPositions;
                  ModelParameters = ModeData.ModelParameters;
                  thetaDist = ModeData.thetaDist;
                  PriorDist = ModeData.PriorDist;
                  ParameterNames = ModeData.ParameterNames;
                  thetaIndex = ModeData.thetaIndex;
                  UniformBounds = ModeData.UniformBounds;
                  LowerBound = ModeData.LowerBound;
                  ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                  InitStatus = 1;
               end;
            end;
         end;
         if InitStatus==1;
            %
            % load the AIMData file
            %
            AIMData = load(DSGEModel.AIMDataFile);
            %
            % check if we can solve the model
            %
            ErrorStr = '';
            try;
               [A,H,R,F,B0,mcode] = SolveDSGEModel(DSGEModel,theta,thetaPositions,ModelParameters,AIMData);
               if isempty(lasterr)==0;
                  ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
               end;
            catch;
               ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
            end;
            if strcmp(ErrorStr,'')==1;
               if mcode==1;
                  file = [DSGEModel.OutputDirectory '\StateSpaceMatrices-' DSGEModel.NameOfModel '-InitialValues.mat'];
                  save(file,'A','H','R','F','B0');
                  %
                  mfile = [DSGEModel.OutputDirectory '\SSM' strrep(DSGEModel.NameOfModel,'-','') 'InitVal.m'];
                  %
                  fid = fopen(mfile,'wt');
                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                  fprintf(fid,'%%\n%% M E A S U R E M E N T   E Q U A T I O N\n');
                  fprintf(fid,'%%\n%% matrix with parameters on exogenous variables\n%%\n');
                  fprintf(fid,'A = DataStructure.A;\n');
                  fprintf(fid,'%%\n%% matrix with parameters on state variables\n%%\n');
                  fprintf(fid,'H = DataStructure.H;\n');
                  fprintf(fid,'%%\n%% matrix with measurement error covariances\n%%\n');
                  fprintf(fid,'R = DataStructure.R;\n');
                  fprintf(fid,'%%\n%% S T A T E   E Q U A T I O N\n');
                  fprintf(fid,'%%\n%% matrix with state transition parameters\n%%\n');
                  fprintf(fid,'F = DataStructure.F;\n');
                  fprintf(fid,'%%\n%% matrix with shock parameters\n%%\n');
                  fprintf(fid,'B0 = DataStructure.B0;\n');
                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                  %
                  % end the script file
                  %
                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                  fclose(fid);
                  %
                  txt = ['The state-space matrices at initial parameter values have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 5 entries: A (matrix with parameters on exogenous variables in the measurement equation), H (matrix with parameters on state variables in the measurement equation), R (matrix with measurement error covariances), F (matrix with state transition parameters), and B0 (matrix with shock parameters). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                  About(txt,'information','Save State-Space Matrices - Initial Values',200,500,CurrINI);
                  drawnow;
               else;
                  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','Save State-Space Model - Initial Values',120,500,CurrINI);
               end;
            else;
               About(ErrorStr,'information','YADA - Error Message',200,500,CurrINI);
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'statespace_postmode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            %
            % 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)==1;
               %
               % check if we can solve the model
               %
               ErrorStr = '';
               try;
                  [A,H,R,F,B0,mcode] = SolveDSGEModel(DSGEModel,theta,thetaPositions,ModelParameters,AIMData);
                  if isempty(lasterr)==0;
                     ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
                  end;
               catch;
                  ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
               end;
               if strcmp(ErrorStr,'')==1;
                  if mcode==1;
                     if length(size(H))==3;
                        %
                        % check if H has the required size
                        %
                        [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
                        if size(H,3)>=LastPeriod;
                           %
                           % pick a certain period for the H matrix
                           %
                           SubSampleMat = get(controls.dsge.initializekalman,'String');
                           SubSampleMat = SubSampleMat(DSGEModel.KalmanFirstObservation:size(SubSampleMat,1),:);
                           [action,SelectedPosition] = SelectionDlg(SubSampleMat,size(SubSampleMat,1),'Select time period for the measurement matrix H','Measurement Matrix','State-Space Form - Posterior Mode','','',CurrINI);
                           %
                           SelPos = FirstPeriod+DSGEModel.KalmanFirstObservation-1+(SelectedPosition-1);
                           H = H(:,:,SelPos);
                        else;
                           action = 'Cancel';
                           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(LastPeriod) '). YADA has therefore aborted from showing the state-space form.'];
                           About(ErrorStr,'error','Error - Measurement Equation',200,500,CurrINI);
                        end;
                     else;
                        action = 'OK';
                     end;
                     if strcmp(lower(action),'ok')==1;
                        %
                        % we can now setup the state-space form
                        %
                        file = [DSGEModel.OutputDirectory '\StateSpaceForm-' DSGEModel.NameOfModel '-PosteriorMode.txt'];
                        %
                        PrintStateSpaceForm(file,DSGEModel,CurrINI,A,H,R,F,B0,length(ModeData.theta),size(ModeData.ParameterNames.estimated,1)+size(ModeData.ParameterNames.calibrated,1)+size(ModeData.ParameterNames.additional,1),'Posterior Mode');
                        %
                        if FileExist(file)==1;
                           TextGUI(file,['State-Space Form - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,1);
                        end;
                     end;
                  else;
                     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','State-Space Form - Posterior Mode',120,500,CurrINI);
                  end;
               else;
                  About(ErrorStr,'information','YADA - Error Message',200,500,CurrINI);
               end;
            else;
               About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'statespace_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
         %
         [InitStatus,theta,thetaPositions,ModelParameters,thetaDist,PriorDist,ParameterNames,thetaIndex,UniformBounds,LowerBound] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
         if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
            ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
            if FileExist(ModeFile)==1;
               ErrorStr = '';
               try;
                  ModeData = load(ModeFile);
               catch;
                  ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
               end;
               if isempty(ErrorStr)==1;
                  theta = ModeData.theta;
                  thetaPositions = ModeData.thetaPositions;
                  ModelParameters = ModeData.ModelParameters;
                  thetaDist = ModeData.thetaDist;
                  PriorDist = ModeData.PriorDist;
                  ParameterNames = ModeData.ParameterNames;
                  thetaIndex = ModeData.thetaIndex;
                  UniformBounds = ModeData.UniformBounds;
                  LowerBound = ModeData.LowerBound;
                  ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                  InitStatus = 1;
               end;
            end;
         end;
         if InitStatus==1;
            %
            % load the AIMData file
            %
            AIMData = load(DSGEModel.AIMDataFile);
            %
            % check if we can solve the model
            %
            ErrorStr = '';
            try;
               [A,H,R,F,B0,mcode] = SolveDSGEModel(DSGEModel,theta,thetaPositions,ModelParameters,AIMData);
               if isempty(lasterr)==0;
                  ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
               end;
            catch;
               ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
            end;
            if strcmp(ErrorStr,'')==1;
               if mcode==1;
                  if length(size(H))==3;
                     %
                     % check if H has the required size
                     %
                     [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
                     if size(H,3)>=LastPeriod;
                        %
                        % pick a certain period for the H matrix
                        %
                        SubSampleMat = get(controls.dsge.initializekalman,'String');
                        SubSampleMat = SubSampleMat(DSGEModel.KalmanFirstObservation:size(SubSampleMat,1),:);
                        [action,SelectedPosition] = SelectionDlg(SubSampleMat,size(SubSampleMat,1),'Select time period for the measurement matrix H','Measurement Matrix','State-Space Form - Initial Values','','',CurrINI);
                        %
                        SelPos = FirstPeriod+DSGEModel.KalmanFirstObservation-1+(SelectedPosition-1);
                        H = H(:,:,SelPos);
                     else;
                        action = 'Cancel';
                        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(LastPeriod) '). YADA has therefore aborted from showing the state-space form.'];
                        About(ErrorStr,'error','Error - Measurement Equation',200,500,CurrINI);
                     end;
                  else;
                     action = 'OK';
                  end;
                  if strcmp(lower(action),'ok')==1;
                     %
                     % we can now setup the state-space form
                     %
                     file = [DSGEModel.OutputDirectory '\StateSpaceForm-' DSGEModel.NameOfModel '-InitValues.txt'];
                     %
                     PrintStateSpaceForm(file,DSGEModel,CurrINI,A,H,R,F,B0,length(theta),size(ParameterNames.all,1),'Initial Values');
                     %
                     if FileExist(file)==1;
                        TextGUI(file,['State-Space Form - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Initial Parameter Values',50,CurrINI,1,1);
                     end;
                  end;
               else;
                  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','State-Space Form - Initial Values',120,500,CurrINI);
               end;
            else;
               About(ErrorStr,'information','YADA - Error Message',200,500,CurrINI);
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'simulatedata_postmode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            %
            % 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)==1;
               %
               % check if we can solve the model
               %
               ErrorStr = '';
               try;
                  [A,H,R,F,B0,mcode] = SolveDSGEModel(DSGEModel,theta,thetaPositions,ModelParameters,AIMData);
                  if isempty(lasterr)==0;
                     ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
                  end;
               catch;
                  ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
               end;
               if strcmp(ErrorStr,'')==1;
                  if mcode==1;
                     %
                     % select the number of observations for the simulations
                     %
                     NumObs = (50:25:10000);
                     Tpos = (NumObs==DSGEModel.T) .* (1:length(NumObs));
                     Tpos = Tpos(Tpos>0);
                     if isempty(Tpos)==1;
                        Tpos = (NumObs>DSGEModel.T+1) .* (1:length(NumObs));
                        Tpos = Tpos(Tpos>0);
                        if isempty(Tpos)==0;
                           Tpos = Tpos(1);
                        end;
                        if Tpos==1;
                           NumObs = [DSGEModel.T NumObs];
                        elseif isempty(Tpos)==1;
                           NumObs = [NumObs DSGEModel.T];
                           Tpos = length(NumObs);
                        else;
                           NumObs = [NumObs(1:Tpos-1) DSGEModel.T NumObs(Tpos+1:length(NumObs))];
                        end;
                     end;
                     %
                     % create the string matrix with the number of observation
                     %
                     ObsStrMat = '';
                     for i=1:length(NumObs);
                        ObsStrMat = strvcat(ObsStrMat,[int2str(NumObs(i)) ' observations']);
                     end;
                     %
                     % display the selection dialog
                     %
                     [action,SelectedOption] = SelectionDlg(ObsStrMat,Tpos,'Select the number of observations to simulate','Simulate Data Selection','Simulate Data - Posterior Mode','','',CurrINI);
                     if strcmp(lower(action),'ok')==1;
                        %
                        % simulate the data
                        %
                        [SimulatedData,KeepShocks] = DSGESimulateVariables(A,H,R,F,B0,NumObs(SelectedOption),DSGEModel,CurrINI);
                        %
                        % ask if simulated data should be saved to file
                        %
                        txt = 'Would you like to save the simulated data to file?';
                        answer = Query(txt,'question',140,'Save - Simulate Data',500,'no',CurrINI);
                        drawnow;
                        if strcmp(lower(answer),'yes')==1;
                           Y = SimulatedData.Y;
                           X = SimulatedData.X;
                           ksi = SimulatedData.ksi;
                           eta = SimulatedData.eta;
                           w = SimulatedData.w;
                           H = SimulatedData.Parameters.H;
                           B0 = SimulatedData.Parameters.B0;
                           YNames = DSGEModel.VariableNames;
                           StateVariableNames = DSGEModel.StateVariableNames;
                           ShockNames = DSGEModel.StateShockNames(KeepShocks,:);
                           file = [DSGEModel.OutputDirectory '\SimulatedData-' DSGEModel.NameOfModel '-PostMode.mat'];
                           if isempty(DSGEModel.X)==0;
                              XNames = DSGEModel.XVariableNames;
                              save(file,'Y','X','ksi','eta','w','A','H','R','F','B0','YNames','XNames','StateVariableNames','ShockNames');
                              NumEntries = '14';
                           else;
                              save(file,'Y','ksi','eta','w','H','R','F','B0','YNames','StateVariableNames','ShockNames');
                              NumEntries = '11';
                           end;
                           mfile = [DSGEModel.OutputDirectory '\SimuledDataPostMode.m'];
                           fid = fopen(mfile,'wt');
                           fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                           fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                           fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                           fprintf(fid,'YNames = DataStructure.YNames;\n');
                           if isempty(DSGEModel.X)==0;
                              fprintf(fid,'%%\n%% string matrix with the names of the exogenous variables\n%%\n');
                              fprintf(fid,'XNames = DataStructure.XNames;\n');
                           end;
                           fprintf(fid,'%%\n%% string matrix with the names of the state variables\n%%\n');
                           fprintf(fid,'StateVariableNames = DataStructure.StateVariableNames;\n');
                           fprintf(fid,'%%\n%% string matrix with the names of the exonomic shocks\n%%\n');
                           fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                           fprintf(fid,'%%\n%% matrix with the simulated observed variables\n%%\n');
                           fprintf(fid,'Y = DataStructure.Y;\n');
                           if isempty(DSGEModel.X)==0;
                              fprintf(fid,'%%\n%% matrix with the generated exogenous variables\n%%\n');
                              fprintf(fid,'X = DataStructure.X;\n');
                           end;
                           fprintf(fid,'%%\n%% matrix with the simulated state variables\n%%\n');
                           fprintf(fid,'ksi = DataStructure.ksi;\n');
                           fprintf(fid,'%%\n%% matrix with the simulated standardized economic shocks\n%%\n');
                           fprintf(fid,'eta = DataStructure.eta;\n');
                           fprintf(fid,'%%\n%% matrix with the simulated measurement errors\n%%\n');
                           fprintf(fid,'w = DataStructure.w;\n');
                           if isempty(DSGEModel.X)==0;
                              fprintf(fid,'%%\n%% A-matrix for the measurement equation\n%%\n');
                              fprintf(fid,'A = DataStructure.A;\n');
                              XNameStr = 'XNames (string matrix with names of the exogenous variables), ';
                              XStr = 'X (matrix with generated data for the exogenous variables), ';
                              AStr = 'A (matrix with parameters on the exogenous variables in the measurement equation), ';
                           else;
                              XNameStr = '';
                              XStr = '';
                              AStr = '';
                           end;
                           fprintf(fid,'%%\n%% H-matrix for the measurement equation\n%%\n');
                           fprintf(fid,'H = DataStructure.H;\n');
                           fprintf(fid,'%%\n%% covariance matrix for the measurement errors\n%%\n');
                           fprintf(fid,'R = DataStructure.R;\n');
                           fprintf(fid,'%%\n%% F-matrix for the state equation\n%%\n');
                           fprintf(fid,'F = DataStructure.F;\n');
                           fprintf(fid,'%%\n%% B0-matrix for the state equation\n%%\n');
                           fprintf(fid,'B0 = DataStructure.B0;\n');
                           fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                           %
                           % end the script file
                           %
                           fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                           fclose(fid);
                           txt = ['The simulated data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains ' NumEntries ' entries: YNames (string matrix with the names of the observed variables), ' XNameStr 'StateVariableNames (string matrix with the names of the state variables), ShockNames (string matrix with the names of the economic shocks), Y (matrix with simulated data for the observed variables), ' XStr 'ksi (matrix with simulated data for the state variables), eta (matrix with simulated standardized economic shocks), w (matrix with simulated measurement errors), ' AStr 'H (measurement matrix for the state variables), R (covariance matrix for the measurement errors), F (state transition matrix), and B0 (coefficient matrix on the economic shocks in the state equation). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                           About(txt,'information','Simulated Data - Posterior Mode',400,500,CurrINI);
                           drawnow;
                        end;
                        %
                        % display the generated data
                        %
                        GraphSimulatedData('init',CurrINI,DSGEModel,SimulatedData.Y,'Posterior Mode');
                     end;
                  else;
                     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','Simulated Data - Posterior Mode',120,500,CurrINI);
                  end;
               else;
                  About(ErrorStr,'information','YADA - Error Message',200,500,CurrINI);
               end;
            else;
               About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'simulatedata_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % get the parameter data
         %
         [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
         if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
            ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
            if FileExist(ModeFile)==1;
               ErrorStr = '';
               try;
                  ModeData = load(ModeFile);
               catch;
                  ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
               end;
               if isempty(ErrorStr)==1;
                  theta = ModeData.theta;
                  thetaPositions = ModeData.thetaPositions;
                  ModelParameters = ModeData.ModelParameters;
                  ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                  InitStatus = 1;
               end;
            end;
         end;
         %
         if InitStatus==1;
            %
            % 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)==1;
               %
               % check if we can solve the model
               %
               ErrorStr = '';
               try;
                  [A,H,R,F,B0,mcode] = SolveDSGEModel(DSGEModel,theta,thetaPositions,ModelParameters,AIMData);
                  if isempty(lasterr)==0;
                     ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
                  end;
               catch;
                  ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
               end;
               if strcmp(ErrorStr,'')==1;
                  if mcode==1;
                     %
                     % select the number of observations for the simulations
                     %
                     NumObs = (50:25:10000);
                     Tpos = (NumObs==DSGEModel.T) .* (1:length(NumObs));
                     Tpos = Tpos(Tpos>0);
                     if isempty(Tpos)==1;
                        Tpos = (NumObs>DSGEModel.T+1) .* (1:length(NumObs));
                        Tpos = Tpos(Tpos>0);
                        if isempty(Tpos)==0;
                           Tpos = Tpos(1);
                        end;
                        if Tpos==1;
                           NumObs = [DSGEModel.T NumObs];
                        elseif isempty(Tpos)==1;
                           NumObs = [NumObs DSGEModel.T];
                           Tpos = length(NumObs);
                        else;
                           NumObs = [NumObs(1:Tpos-1) DSGEModel.T NumObs(Tpos+1:length(NumObs))];
                        end;
                     end;
                     %
                     % create the string matrix with the number of observation
                     %
                     ObsStrMat = '';
                     for i=1:length(NumObs);
                        ObsStrMat = strvcat(ObsStrMat,[int2str(NumObs(i)) ' observations']);
                     end;
                     %
                     % display the selection dialog
                     %
                     [action,SelectedOption] = SelectionDlg(ObsStrMat,Tpos,'Select the number of observations to simulate','Simulate Data Selection','Simulate Data - Initial Values','','',CurrINI);
                     if strcmp(lower(action),'ok')==1;
                        %
                        % simulate the data
                        %
                        [SimulatedData,KeepShocks] = DSGESimulateVariables(A,H,R,F,B0,NumObs(SelectedOption),DSGEModel,CurrINI);
                        %
                        % ask if simulated data should be saved to file
                        %
                        txt = 'Would you like to save the simulated data to file?';
                        answer = Query(txt,'question',140,'Save - Simulate Data',500,'no',CurrINI);
                        drawnow;
                        if strcmp(lower(answer),'yes')==1;
                           Y = SimulatedData.Y;
                           X = SimulatedData.X;
                           ksi = SimulatedData.ksi;
                           eta = SimulatedData.eta;
                           w = SimulatedData.w;
                           H = SimulatedData.Parameters.H;
                           B0 = SimulatedData.Parameters.B0;
                           YNames = DSGEModel.VariableNames;
                           StateVariableNames = DSGEModel.StateVariableNames;
                           ShockNames = DSGEModel.StateShockNames(KeepShocks,:);
                           file = [DSGEModel.OutputDirectory '\SimulatedData-' DSGEModel.NameOfModel '-InitialValues.mat'];
                           if isempty(DSGEModel.X)==0;
                              XNames = DSGEModel.XVariableNames;
                              save(file,'Y','X','ksi','eta','w','A','H','R','F','B0','YNames','XNames','StateVariableNames','ShockNames');
                              NumEntries = '14';
                           else;
                              save(file,'Y','ksi','eta','w','H','R','F','B0','YNames','StateVariableNames','ShockNames');
                              NumEntries = '11';
                           end;
                           mfile = [DSGEModel.OutputDirectory '\SimuledDataInitVal.m'];
                           fid = fopen(mfile,'wt');
                           fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                           fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                           fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                           fprintf(fid,'YNames = DataStructure.YNames;\n');
                           if isempty(DSGEModel.X)==0;
                              fprintf(fid,'%%\n%% string matrix with the names of the exogenous variables\n%%\n');
                              fprintf(fid,'XNames = DataStructure.XNames;\n');
                           end;
                           fprintf(fid,'%%\n%% string matrix with the names of the state variables\n%%\n');
                           fprintf(fid,'StateVariableNames = DataStructure.StateVariableNames;\n');
                           fprintf(fid,'%%\n%% string matrix with the names of the exonomic shocks\n%%\n');
                           fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                           fprintf(fid,'%%\n%% matrix with the simulated observed variables\n%%\n');
                           fprintf(fid,'Y = DataStructure.Y;\n');
                           if isempty(DSGEModel.X)==0;
                              fprintf(fid,'%%\n%% matrix with the generated exogenous variables\n%%\n');
                              fprintf(fid,'X = DataStructure.X;\n');
                           end;
                           fprintf(fid,'%%\n%% matrix with the simulated state variables\n%%\n');
                           fprintf(fid,'ksi = DataStructure.ksi;\n');
                           fprintf(fid,'%%\n%% matrix with the simulated standardized economic shocks\n%%\n');
                           fprintf(fid,'eta = DataStructure.eta;\n');
                           fprintf(fid,'%%\n%% matrix with the simulated measurement errors\n%%\n');
                           fprintf(fid,'w = DataStructure.w;\n');
                           if isempty(DSGEModel.X)==0;
                              fprintf(fid,'%%\n%% A-matrix for the measurement equation\n%%\n');
                              fprintf(fid,'A = DataStructure.A;\n');
                              XNameStr = 'XNames (string matrix with names of the exogenous variables), ';
                              XStr = 'X (matrix with generated data for the exogenous variables), ';
                              AStr = 'A (matrix with parameters on the exogenous variables in the measurement equation), ';
                           else;
                              XNameStr = '';
                              XStr = '';
                              AStr = '';
                           end;
                           fprintf(fid,'%%\n%% H-matrix for the measurement equation\n%%\n');
                           fprintf(fid,'H = DataStructure.H;\n');
                           fprintf(fid,'%%\n%% covariance matrix for the measurement errors\n%%\n');
                           fprintf(fid,'R = DataStructure.R;\n');
                           fprintf(fid,'%%\n%% F-matrix for the state equation\n%%\n');
                           fprintf(fid,'F = DataStructure.F;\n');
                           fprintf(fid,'%%\n%% B0-matrix for the state equation\n%%\n');
                           fprintf(fid,'B0 = DataStructure.B0;\n');
                           fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                           %
                           % end the script file
                           %
                           fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                           fclose(fid);
                           txt = ['The simulated data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains ' NumEntries ' entries: YNames (string matrix with the names of the observed variables), ' XNameStr 'StateVariableNames (string matrix with the names of the state variables), ShockNames (string matrix with the names of the economic shocks), Y (matrix with simulated data for the observed variables), ' XStr 'ksi (matrix with simulated data for the state variables), eta (matrix with simulated standardized economic shocks), w (matrix with simulated measurement errors), ' AStr 'H (measurement matrix for the state variables), R (covariance matrix for the measurement errors), F (state transition matrix), and B0 (coefficient matrix on the economic shocks in the state equation). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                           About(txt,'information','Simulated Data - Initial Values',400,500,CurrINI);
                           drawnow;
                        end;
                        %
                        % display the generated data
                        %
                        GraphSimulatedData('init',CurrINI,DSGEModel,SimulatedData.Y,'Initial Values');
                     end;
                  else;
                     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','Simulated Data - Initial Values',120,500,CurrINI);
                  end;
               else;
                  About(ErrorStr,'information','YADA - Error Message',200,500,CurrINI);
               end;
            else;
               About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'dsgevareigenvalues_postmode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            %
            % 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)==1;
               %
               % check if we can solve the model
               %
               ErrorStr = '';
               try;
                  [A,H,R,F,B0,mcode] = SolveDSGEModel(DSGEModel,theta,thetaPositions,ModelParameters,AIMData);
                  if isempty(lasterr)==0;
                     ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
                  end;
               catch;
                  ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
               end;
               if strcmp(ErrorStr,'')==1;
                  if mcode==1;
                     if length(size(H))==3;
                        %
                        % check if H has the required size
                        %
                        [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
                        if size(H,3)>=LastPeriod;
                           %
                           % pick a certain period for the H matrix
                           %
                           SubSampleMat = get(controls.dsge.initializekalman,'String');
                           SubSampleMat = SubSampleMat(DSGEModel.KalmanFirstObservation:size(SubSampleMat,1),:);
                           [action,SelectedPosition] = SelectionDlg(SubSampleMat,size(SubSampleMat,1),'Select time period for the measurement matrix H','Measurement Matrix','DSGE Model To VAR Model - Posterior Mode','','',CurrINI);
                           %
                           SelPos = FirstPeriod+DSGEModel.KalmanFirstObservation-1+(SelectedPosition-1);
                           H = H(:,:,SelPos);
                        else;
                           action = 'cancel';
                           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(LastPeriod) '). YADA has therefore aborted from checking the poor man''s invertibility condition.'];
                           About(ErrorStr,'error','Error - Measurement Equation',200,500,CurrINI);
                        end;
                     else;
                        action = 'OK';
                     end;
                     if strcmp(lower(action),'ok')==1;
                        %
                        % now we check the eigenvalue condition
                        %
                        [status,EigenValues] = DSGEtoVARModel(H,R,F,B0);
                        if status==1;
                           StatusStr = ['The "poor man''s invertibility condition" (see Fernández-Villaverde, Rubio-Ramírez, Sargent and Watson, 2007, AER) is satisfied, with the largest eigenvalue being equal to ' num2str(max(EigenValues)) '. The DSGE model can therefore be rewritten as an infinite order VAR model.'];
                        elseif status==0;
                           StatusStr = ['The "poor man''s invertibility condition" (see Fernández-Villaverde, Rubio-Ramírez, Sargent and Watson, 2007, AER) is not satisfied. The largest eigenvalue is equal to ' num2str(max(EigenValues)) '. The DSGE model can therefore not be rewritten as an infinite order VAR model.'];
                        else;
                           StatusStr = 'The DSGE model has too many economic shocks and unique measurement errors relative to the number of observed variables. It can therefore not be rewitten as an infinite order VAR model.';
                        end;
                        About(StatusStr,'information','DSGE Model To VAR Model - Posterior Mode',120,500,CurrINI);
                     end;
                  else;
                     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','DSGE Model To VAR Model - Posterior Mode',120,500,CurrINI);
                  end;
               else;
                  About(ErrorStr,'information','YADA - Error Message',200,500,CurrINI);
               end;
            else;
               About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'dsgevareigenvalues_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
         %
         [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
         if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
            ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
            if FileExist(ModeFile)==1;
               ErrorStr = '';
               try;
                  ModeData = load(ModeFile);
               catch;
                  ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
               end;
               if isempty(ErrorStr)==1;
                  theta = ModeData.theta;
                  thetaPositions = ModeData.thetaPositions;
                  ModelParameters = ModeData.ModelParameters;
                  ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                  InitStatus = 1;
               end;
            end;
         end;
         %
         if InitStatus==1;
            %
            % load the AIMData file
            %
            AIMData = load(DSGEModel.AIMDataFile);
            %
            % check if we can solve the model
            %
            ErrorStr = '';
            try;
               [A,H,R,F,B0,mcode] = SolveDSGEModel(DSGEModel,theta,thetaPositions,ModelParameters,AIMData);
               if isempty(lasterr)==0;
                  ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
               end;
            catch;
               ErrorStr = ['YADA caught an error when trying to solve the DSGE model. Message caught is: ' lasterr];
            end;
            if strcmp(ErrorStr,'')==1;
               if mcode==1;
                  if length(size(H))==3;
                     %
                     % check if H has the required size
                     %
                     [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
                     if size(H,3)>=LastPeriod;
                        %
                        % pick a certain period for the H matrix
                        %
                        SubSampleMat = get(controls.dsge.initializekalman,'String');
                        SubSampleMat = SubSampleMat(DSGEModel.KalmanFirstObservation:size(SubSampleMat,1),:);
                        [action,SelectedPosition] = SelectionDlg(SubSampleMat,size(SubSampleMat,1),'Select time period for the measurement matrix H','Measurement Matrix','DSGE Model To VAR Model - Initial Values','','',CurrINI);
                        %
                        SelPos = FirstPeriod+DSGEModel.KalmanFirstObservation-1+(SelectedPosition-1);
                        H = H(:,:,SelPos);
                     else;
                        action = 'Cancel';
                        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(LastPeriod) '). YADA has therefore aborted from checking the poor man''s invertibility condition.'];
                        About(ErrorStr,'error','Error - Measurement Equation',200,500,CurrINI);
                     end;
                  else;
                     action = 'OK';
                  end;
                  if strcmp(lower(action),'ok')==1;
                     %
                     % now we check the eigenvalue condition
                     %
                     [status,EigenValues] = DSGEtoVARModel(H,R,F,B0);
                     if status==1;
                        StatusStr = ['The "poor man''s invertibility condition" (see Fernández-Villaverde, Rubio-Ramírez, Sargent and Watson, 2007, AER) is satisfied, with the largest eigenvalue being equal to ' num2str(max(EigenValues)) '. The DSGE model can therefore be rewritten as an infinite order VAR model.'];
                     elseif status==0;
                        StatusStr = ['The "poor man''s invertibility condition" (see Fernández-Villaverde, Rubio-Ramírez, Sargent and Watson, 2007, AER) is not satisfied. The largest eigenvalue is equal to ' num2str(max(EigenValues)) '. The DSGE model can therefore not be rewritten as an infinite order VAR model.'];
                     else;
                        StatusStr = 'The DSGE model has too many economic shocks and unique measurement errors relative to the number of observed variables. It can therefore not be rewitten as an infinite order VAR model.';
                     end;
                     About(StatusStr,'information','DSGE Model To VAR Model - Initial Values',120,500,CurrINI);
                  end;
               else;
                  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.';
                  else;
                     mcodeStr = 'Return code not properly specified.';
                  end;
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '"'];
                  About(txt,'information','DSGE Model To VAR Model - Initial Values',120,500,CurrINI);
               end;
            else;
               About(ErrorStr,'information','YADA - Error Message',200,500,CurrINI);
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'viewpriorvalue_postmode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % load data from file
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            lnjac = logJacobian(ModeData.phiMode,ModeData.thetaIndex,ModeData.UniformBounds);
            logPrior = logPriorDSGE(ModeData.thetaMode,ModeData.thetaDist,ModeData.PriorDist,ModeData.LowerBound);
            txt = '********************************************************************************';
            txt = strvcat(txt,'*                                                                              *');
            txt = strvcat(txt,'*        V A L U E S   O F   T H E   L O G   P R I O R   D E N S I T Y         *');
            txt = strvcat(txt,'*                A N D   O F   T H E   L O G   J A C O B I A N                 *');
            txt = strvcat(txt,'*                                                                              *');
            txt = strvcat(txt,'********************************************************************************',' ');
            txt = strvcat(txt,'Parameters evaluated at the posterior mode parameter values',' ');
            prt_val = ['%' num2str(6+CurrINI.decimals,'%0.0f') '.' num2str(CurrINI.decimals,'%0.0f') 'f'];
            txt = strvcat(txt,sprintf(['log prior:                  ' prt_val],logPrior));
            txt = strvcat(txt,sprintf(['log Jacobian (dtheta/dphi): ' prt_val],lnjac),' ');
            %
            % write to file
            %
            PriorJacValueFile = [DSGEModel.OutputDirectory '\DSGE-Prior-Jacobian-' DSGEModel.NameOfModel '-PostMode.txt'];
            fid = fopen(PriorJacValueFile,'wt');
            for i=1:size(txt,1);
               fprintf(fid,'%s\n',txt(i,:));
            end;
            fprintf(fid,'================================================================================\n\n');
            %
            % bottom file data
            %
            fprintf(fid,'Directory for file: %s\n',GetPath(PriorJacValueFile));
            fprintf(fid,'Name of file:       %s\n',GetFilename(PriorJacValueFile));
            fprintf(fid,'Output created on:  %s\n\n',datestr(now,0));
            fclose(fid);
            %
            if FileExist(PriorJacValueFile)==1;
               TextGUI(PriorJacValueFile,['DSGE Model Prior and Jacobian - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-700)/2 (CurrINI.scrsz(4)-500)/2 700 500],'Posterior Mode Parameter Values',50,CurrINI,1,1);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'viewpriorvalue_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check the status of the DSGE model files
         %
         [InitStatus,theta,thetaPositions,ModelParameters,thetaDist,PriorDist,ParameterNames,thetaIndex,UniformBounds,LowerBound] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
         if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
            ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
            if FileExist(ModeFile)==1;
               ErrorStr = '';
               try;
                  ModeData = load(ModeFile);
               catch;
                  ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
               end;
               if isempty(ErrorStr)==1;
                  theta = ModeData.theta;
                  thetaPositions = ModeData.thetaPositions;
                  ModelParameters = ModeData.ModelParameters;
                  thetaDist = ModeData.thetaDist;
                  PriorDist = ModeData.PriorDist;
                  ParameterNames = ModeData.ParameterNames;
                  thetaIndex = ModeData.thetaIndex;
                  UniformBounds = ModeData.UniformBounds;
                  LowerBound = ModeData.LowerBound;
                  ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                  InitStatus = 1;
               end;
            end;
         end;
         %
         if InitStatus==1;
            logPrior = logPriorDSGE(theta,thetaDist,PriorDist,LowerBound);
            lnjac = logJacobian(ThetaToPhi(theta,thetaIndex,UniformBounds,LowerBound),thetaIndex,UniformBounds);
            txt = '********************************************************************************';
            txt = strvcat(txt,'*                                                                              *');
            txt = strvcat(txt,'*        V A L U E S   O F   T H E   L O G   P R I O R   D E N S I T Y         *');
            txt = strvcat(txt,'*                A N D   O F   T H E   L O G   J A C O B I A N                 *');
            txt = strvcat(txt,'*                                                                              *');
            txt = strvcat(txt,'********************************************************************************',' ');
            txt = strvcat(txt,'Parameters evaluated at the initial parameter values',' ');
            prt_val = ['%' num2str(6+CurrINI.decimals,'%0.0f') '.' num2str(CurrINI.decimals,'%0.0f') 'f'];
            txt = strvcat(txt,sprintf(['log prior:                  ' prt_val],logPrior));
            txt = strvcat(txt,sprintf(['log Jacobian (dtheta/dphi): ' prt_val],lnjac),' ');
            %
            % write to file
            %
            PriorJacValueFile = [DSGEModel.OutputDirectory '\DSGE-Prior-Jacobian-' DSGEModel.NameOfModel '-InitialValues.txt'];
            fid = fopen(PriorJacValueFile,'wt');
            for i=1:size(txt,1);
               fprintf(fid,'%s\n',txt(i,:));
            end;
            fprintf(fid,'================================================================================\n\n');
            %
            % bottom file data
            %
            fprintf(fid,'Directory for file: %s\n',GetPath(PriorJacValueFile));
            fprintf(fid,'Name of file:       %s\n',GetFilename(PriorJacValueFile));
            fprintf(fid,'Output created on:  %s\n\n',datestr(now,0));
            fclose(fid);
            %
            if FileExist(PriorJacValueFile)==1;
               TextGUI(PriorJacValueFile,['DSGE Model Prior and Jacobian - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-700)/2 (CurrINI.scrsz(4)-500)/2 700 500],'Initial Parameter Values',50,CurrINI,1,1);
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'dsgeeigenvalues_postmode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % load data from file
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            %
            % run AiMSolver to check the eigenvalues of the DSGE model.
            %
            AIMData = load(DSGEModel.AIMDataFile);
            %
            % Make sure that compute_aim_matrices is copied to the tmp directory
            %
            [stat,msg] = dos(['copy /Y "' GetPath(DSGEModel.AIMDataFile) 'compute_aim_matrices.m" "' pwd '\tmp"']);
            %
            [mcode,MaxAbsError,BMatrix,SMatrix,ModelEigenvalues] = AiMSolver(ModeData.ModelParameters,AIMData.neq,AIMData.nlag,AIMData.nlead,DSGEModel.AIMTolerance);
            %
            % Some generic model information
            %
            txt = strvcat(' ',['AiM Model File:                            ' GetFilename(DSGEModel.AIMFile)],' ');
            txt = strvcat(txt,['Number of equations:                       ' num2str(AIMData.neq,'%0.0f')]);
            txt = strvcat(txt,['Number of lags:                            ' num2str(AIMData.nlag,'%0.0f')]);
            txt = strvcat(txt,['Number of leads:                           ' num2str(AIMData.nlead,'%0.0f')]);
            txt = strvcat(txt,['Number of exact shiftrights:               ' num2str(ModelEigenvalues.NumExact,'%0.0f')]);
            txt = strvcat(txt,['Number of numeric shiftrights:             ' num2str(ModelEigenvalues.NumNumeric,'%0.0f')]);
            txt = strvcat(txt,['Number of large roots:                     ' num2str(ModelEigenvalues.LargeRoots,'%0.0f')]);
            txt = strvcat(txt,['Number of stability conditions:            ' num2str(ModelEigenvalues.NumExact+ModelEigenvalues.NumNumeric+ModelEigenvalues.LargeRoots,'%0.0f')]);
            txt = strvcat(txt,['Number of required stability conditions:   ' num2str(AIMData.neq*AIMData.nlead,'%0.0f')]);
            txt = strvcat(txt,['Difference:                                ' num2str(ModelEigenvalues.DimStability,'%0.0f')]);
            txt = strvcat(txt,['Dimension of DSGE state transition matrix: ' num2str(ModelEigenvalues.DimCompanion,'%0.0f')]);
            txt = strvcat(txt,['Number of parameters to estimate:          ' int2str(length(ModeData.theta))]);
            txt = strvcat(txt,['Total number of parameters:                ' int2str(size(ModeData.ParameterNames.estimated,1)+size(ModeData.ParameterNames.calibrated,1)+size(ModeData.ParameterNames.additional,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 = 'The companion matrix a has Inf or NaN entries.';
            else;
               mcodeStr = 'Return code not properly specified.';
            end;
            if mcode==1;
               txt = strvcat(txt,['Maximum absolute error:                    ' num2str(MaxAbsError)]);
            else;
               txt = strvcat(txt,['AiM return code:                           ' mcodeStr]);
            end;
            if (mcode~=7)&(mcode~=8);
               txt = strvcat(txt,' ','                           Eigenvalues','Number       Real          Imaginary      Amplitude         Period');
               %
               prt_val = ['%' num2str(6+CurrINI.decimals,'%0.0f') '.' num2str(CurrINI.decimals,'%0.0f') 'f'];
               prt_str = [' %3.0f     ' prt_val '   ' prt_val '   ' prt_val '   ' prt_val];
               for i=1:length(ModelEigenvalues.Roots);
                  if i<=length(ModelEigenvalues.Amplitude);
                     txti = sprintf(prt_str,i,real(ModelEigenvalues.Roots(i)),imag(ModelEigenvalues.Roots(i)),ModelEigenvalues.Amplitude(i),ModelEigenvalues.Period(i));
                  else;
                     txti = sprintf(prt_str,i,real(ModelEigenvalues.Roots(i)),imag(ModelEigenvalues.Roots(i)),0,NaN);
                  end;
                  txt = strvcat(txt,txti);
               end;
            end;
            %
            txt = strvcat(txt,' ');
            %
            % write to file
            %
            EigenValueFile = [DSGEModel.OutputDirectory '\DSGE-Eigenvalues-' DSGEModel.NameOfModel '-PostMode.txt'];
            fid = fopen(EigenValueFile,'wt');
            for i=1:size(txt,1);
               fprintf(fid,'%s\n',txt(i,:));
            end;
            fprintf(fid,'=========================================================================================================\n\n');
            %
            % bottom file data
            %
            fprintf(fid,'Directory for file: %s\n',GetPath(EigenValueFile));
            fprintf(fid,'Name of file:       %s\n',GetFilename(EigenValueFile));
            fprintf(fid,'Output created on:  %s\n\n',datestr(now,0));
            fclose(fid);
            %
            % Display information
            %
            if FileExist(EigenValueFile)==1;
               TextGUI(EigenValueFile,['DSGE Model Eigenvalues - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,1);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'dsgeeigenvalues_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check the status of the DSGE model files
         %
         [InitStatus,theta,thetaPositions,ModelParameters,thetaDist,PriorDist,ParameterNames,thetaIndex,UniformBounds,LowerBound] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
         if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
            ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
            if FileExist(ModeFile)==1;
               ErrorStr = '';
               try;
                  ModeData = load(ModeFile);
               catch;
                  ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
               end;
               if isempty(ErrorStr)==1;
                  theta = ModeData.theta;
                  thetaPositions = ModeData.thetaPositions;
                  ModelParameters = ModeData.ModelParameters;
                  thetaDist = ModeData.thetaDist;
                  PriorDist = ModeData.PriorDist;
                  ParameterNames = ModeData.ParameterNames;
                  thetaIndex = ModeData.thetaIndex;
                  UniformBounds = ModeData.UniformBounds;
                  LowerBound = ModeData.LowerBound;
                  ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                  InitStatus = 1;
               end;
            end;
         end;
         %
         if InitStatus==1;
            %
            % run AiMSolver to check the eigenvalues of the DSGE model.
            %
            ErrorStr = '';
            try;
               AIMData = load(DSGEModel.AIMDataFile);
            catch;
               ErrorStr = ['Unable to load the file "' DSGEModel.AIMDataFile '". Message caught is: ' lasterr];
            end;
            if strcmp(ErrorStr,'')==1;
               ErrorStr = '';
               try;
                  [mcode,MaxAbsError,BMatrix,SMatrix,ModelEigenvalues] = AiMSolver(ModelParameters,AIMData.neq,AIMData.nlag,AIMData.nlead,DSGEModel.AIMTolerance);
               catch;
                  ErrorStr = ['There was an error running AiM. YADA received the following message: ' lasterr];
               end;
               if isempty(ErrorStr)==1;
                  %
                  % Some generic model information
                  %
                  txt = strvcat(' ',['AiM Model File:                            ' GetFilename(DSGEModel.AIMFile)],' ');
                  txt = strvcat(txt,['Number of equations:                       ' num2str(AIMData.neq,'%0.0f')]);
                  txt = strvcat(txt,['Number of lags:                            ' num2str(AIMData.nlag,'%0.0f')]);
                  txt = strvcat(txt,['Number of leads:                           ' num2str(AIMData.nlead,'%0.0f')]);
                  txt = strvcat(txt,['Number of exact shiftrights:               ' num2str(ModelEigenvalues.NumExact,'%0.0f')]);
                  txt = strvcat(txt,['Number of numeric shiftrights:             ' num2str(ModelEigenvalues.NumNumeric,'%0.0f')]);
                  txt = strvcat(txt,['Number of large roots:                     ' num2str(ModelEigenvalues.LargeRoots,'%0.0f')]);
                  txt = strvcat(txt,['Number of stability conditions:            ' num2str(ModelEigenvalues.NumExact+ModelEigenvalues.NumNumeric+ModelEigenvalues.LargeRoots,'%0.0f')]);
                  txt = strvcat(txt,['Number of required stability conditions:   ' num2str(AIMData.neq*AIMData.nlead,'%0.0f')]);
                  txt = strvcat(txt,['Difference:                                ' num2str(ModelEigenvalues.DimStability,'%0.0f')]);
                  txt = strvcat(txt,['Dimension of DSGE state transition matrix: ' num2str(ModelEigenvalues.DimCompanion,'%0.0f')]);
                  txt = strvcat(txt,['Number of parameters to estimate:          ' int2str(length(theta))]);
                  txt = strvcat(txt,['Total number of parameters:                ' int2str(size(ParameterNames.all,1))]);
                  %
                  if mcode==1;
                     mcodeStr = 'Unique convergent solution.';
                  elseif 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 = 'The companion matrix a has Inf or NaN entries.';
                  else;
                     mcodeStr = 'Return code not properly specified.';
                  end;
                  txt = strvcat(txt,['AiM return code:                           ' mcodeStr]);
                  if mcode==1;
                     txt = strvcat(txt,['Maximum absolute error:                    ' num2str(MaxAbsError)]);
                  end;
                  if (mcode~=7)&(mcode~=8);
                     txt = strvcat(txt,' ','                           Eigenvalues','Number       Real          Imaginary      Amplitude         Period');
                     %
                     prt_val = ['%' num2str(6+CurrINI.decimals,'%0.0f') '.' num2str(CurrINI.decimals,'%0.0f') 'f'];
                     prt_str = [' %3.0f     ' prt_val '   ' prt_val '   ' prt_val '   ' prt_val];
                     for i=1:length(ModelEigenvalues.Roots);
                        if i<=length(ModelEigenvalues.Amplitude);
                           txti = sprintf(prt_str,i,real(ModelEigenvalues.Roots(i)),imag(ModelEigenvalues.Roots(i)),ModelEigenvalues.Amplitude(i),ModelEigenvalues.Period(i));
                        else;
                           txti = sprintf(prt_str,i,real(ModelEigenvalues.Roots(i)),imag(ModelEigenvalues.Roots(i)),0,NaN);
                        end;
                        txt = strvcat(txt,txti);
                     end;
                  end;
                  %
                  txt = strvcat(txt,' ');
                  %
                  % write to file
                  %
                  EigenValueFile = [DSGEModel.OutputDirectory '\DSGE-Eigenvalues-' DSGEModel.NameOfModel '-InitialValues.txt'];
                  fid = fopen(EigenValueFile,'wt');
                  for i=1:size(txt,1);
                     fprintf(fid,'%s\n',txt(i,:));
                  end;
                  fprintf(fid,'=========================================================================================================\n\n');
                  %
                  % bottom file data
                  %
                  fprintf(fid,'Directory for file: %s\n',GetPath(EigenValueFile));
                  fprintf(fid,'Name of file:       %s\n',GetFilename(EigenValueFile));
                  fprintf(fid,'Output created on:  %s\n\n',datestr(now,0));
                  fclose(fid);
                  %
                  % Display information
                  %
                  if FileExist(EigenValueFile)==1;
                     TextGUI(EigenValueFile,['DSGE Model Eigenvalues - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Initial Parameter Values',50,CurrINI,1,1);
                  end;
               else;
                  About(ErrorStr,'error','AiM Error',300,500,CurrINI);
               end;
            else;
               About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
            end;
         end;
         set(controls.about,'UserData',0);
      end;
   case 'viewconditionalvars'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % create a string matrix with all the dates
         %
         if strcmp(lower(DSGEModel.DataFrequency),'q')==1;
            SampleFreq = 4;
         elseif strcmp(lower(DSGEModel.DataFrequency),'m')==1;
            SampleFreq = 12;
         else;
            SampleFreq = 1;
         end;
         %
         % create a full sample string matrix
         %
         CondSampleStrMat = '';
         BeginPeriod = str2num(DSGEModel.BeginPeriod);
         DateVector = [];
         for j=BeginPeriod:SampleFreq;
            CondSampleStrMat = strvcat(CondSampleStrMat,[DSGEModel.BeginYear ':' int2str(j)]);
            if SampleFreq>1;
               DateVector = [DateVector str2num(DSGEModel.BeginYear)+((1+(2*(j-1)))/(2*SampleFreq))];
            else;
               DateVector = str2num(DSGEModel.BeginYear);
            end;
         end;
         DoLoop = 1;
         NumPeriods = 0;
         CurrYear = str2num(DSGEModel.BeginYear)+1;
         while DoLoop==1;
            for j=1:SampleFreq;
               CondSampleStrMat = strvcat(CondSampleStrMat,[int2str(CurrYear) ':' int2str(j)]);
               if SampleFreq>1;
                  DateVector = [DateVector CurrYear+((1+(2*(j-1)))/(2*SampleFreq))];
               else;
                  DateVector = [DateVector CurrYear];
               end;
            end;
            CurrYear = CurrYear+1;
            if size(CondSampleStrMat,1)>=size(DSGEModel.Z,2);
               DoLoop = 0;
            end;
         end;
         CondSampleStrMat = CondSampleStrMat(1:size(DSGEModel.Z,2),:);
         DateVector = DateVector(1:size(DSGEModel.Z,2));
         %
         FirstPeriod = CondSampleStrMat(1,:);
         LastPeriod = CondSampleStrMat(length(DateVector),:);
         %
         annual = DSGEModel.annual*DSGEModel.K1;
         annualscale = ones(size(annual));
         for i=1:length(annualscale);
            CheckData = DSGEModel.annualscale.*DSGEModel.K1(:,i)';
            annualscale(i) = max(abs(CheckData));
         end;
         %
         DTStatus = VerifyDataTransformation(DSGEModel.ZVariableNames,DSGEModel.ZTransformation,0);
         %
         % we can now view the data
         %
         GraphEditDataDLG('init','Conditioning Variables',DSGEModel.ZVariableNames,DSGEModel.Z',[],DSGEModel.ZTransformation,DTStatus,DateVector,CondSampleStrMat,annual,annualscale,DSGEModel.DataFrequency,CurrINI);
         %
         set(controls.about,'UserData',0);
      end;
   case 'viewdata'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Open the Graph data dialog
         %
         GraphDataDLG('init',CurrINI,DSGEModel,'Original');
         set(controls.about,'UserData',0);
      end;
   case 'viewannualdata'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Open the Graph data dialog
         %
         GraphDataDLG('init',CurrINI,DSGEModel,'Annualized');
         set(controls.about,'UserData',0);
      end;
   case 'viewtransdata'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % try to transform the data
         %
         DTStatus = VerifyDataTransformation(DSGEModel.VariableNames,DSGEModel.YTransformation,0);
         if DTStatus==1;
            [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
         else;
            ErrorStr = 'You haven''t specified all the necessary fields for computing transformations of the observed variables.';
            HeaderStr = 'Missing Transformation Information';
         end;
         %
         % Open the Graph data dialog
         %
         if isempty(ErrorStr)==1;
            GraphDataDLG('init',CurrINI,DSGEModel,'Transformed');
         else;
            About(ErrorStr,'information',HeaderStr,120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'saveannualdata'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % create the annualized data
         %
         DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency);
         %
         % determine the sub-sample from the full sample
         %
         [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
         %
         % annualize the data
         %
         Y = Annualize(DSGEModel.Y(:,FirstPeriod:LastPeriod),DSGEModel.annual,DSGEModel.annualscale);
         YNames = DSGEModel.VariableNames;
         DateVector = DateVector(1,length(DateVector)-size(Y,2)+1:length(DateVector));
         %
         % setup a suitable file
         %
         OutputFile = [DSGEModel.OutputDirectory '\AnnualizedData-' DSGEModel.NameOfModel '.mat'];
         save(OutputFile,'YNames','Y','DateVector');
         %
         % create an m-file to acces the data
         %
         MFile = [DSGEModel.OutputDirectory '\AD' strrep(DSGEModel.NameOfModel,'-','') '.m'];
         fid = fopen(MFile,'wt');
         fprintf(fid,'%%\n%% load the data from "%s"\n%%\n',GetFilename(OutputFile));
         fprintf(fid,'AnnualData = load(''%s'');\n',GetFilename(OutputFile));
         fprintf(fid,'%%\n%% the annualized data\n%%\n');
         fprintf(fid,'Y = AnnualData.Y;\n');
         fprintf(fid,'%%\n%% names of the observed variables\n%%\n');
         fprintf(fid,'YNames = AnnualData.YNames;\n');
         fprintf(fid,'%%\n%% and a vector with numerical dates for the data\n%%\n');
         fprintf(fid,'DateVector = AnnualData.DateVector;\n');
         fprintf(fid,'%%\n%% add your own code here\n%%\n\n\n');
         %
         fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
         fclose(fid);
         txt = ['YADA has stored the annualized observed variables in the file "' GetFilename(OutputFile) '". It is located in the directory "' DSGEModel.OutputDirectory '". You may access this data by running the script file "' GetFilename(MFile) '" that is located in the same directory.'];
         About(txt,'information','Annualized Observed Variables',200,500,CurrINI);
         set(controls.about,'UserData',0);
      end;
   case 'viewgraphics'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Open a Graphics file dialog and the load the graphics file.
         %
         GraphDirectory = [DSGEModel.OutputDirectory '\graphs'];
         if DirExist(GraphDirectory)==0;
            GraphDirectory = pwd;
         end;
         OpenGraphics(GraphDirectory,CurrINI);
         set(controls.about,'UserData',0);
      end;
   case 'viewprior'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            ErrorStr = '';
            try;
               ModeData = load(ModeFile);
            catch;
               ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
            end;
            if strcmp(ErrorStr,'')==1;
               if FileExist(DSGEModel.PriorFile)==1;
                  txt = ['Would you like to use the prior information stored in the posterior mode results file "' GetFilename(ModeFile) '"? If you answer ''No'', YADA will reread the prior file "' GetFilename(DSGEModel.PriorFile) '".'];
                  answer = Query(txt,'question',200,'Prior Density Data',500,'no',CurrINI);
               else;
                  answer = 'Yes';
               end;
               if strcmp(lower(answer),'yes')==1;
                  InitStatus = 1;
                  theta = ModeData.theta;
                  thetaDist = ModeData.thetaDist;
                  PriorDist = ModeData.PriorDist;
                  ParameterNames = ModeData.ParameterNames;
                  LowerBound = ModeData.LowerBound;
               else;
                  [InitStatus,theta,thetaPositions,ModelParameters,thetaDist,PriorDist,ParameterNames,thetaIndex,UniformBounds,LowerBound] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
               end;
            else;
               InitStatus = 0;
               About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
            end;
         else;
            [InitStatus,theta,thetaPositions,ModelParameters,thetaDist,PriorDist,ParameterNames,thetaIndex,UniformBounds,LowerBound] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
         end;
         if InitStatus==1;
            %
            % we can now construct the plots
            %
            GraphPriorDensity(theta,thetaDist,LowerBound,PriorDist,ParameterNames,controls,DSGEModel,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'bvar_psi_prior_density'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % contruct the plots
         %
         drawnow;
         GraphBVARPriorDensity('Psi',DSGEModel,CurrINI)
         set(controls.about,'UserData',0);
      end;
   case 'bvar_pi_prior_density'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % contruct the plots
         %
         drawnow;
         GraphBVARPriorDensity('Pi',DSGEModel,CurrINI)
         set(controls.about,'UserData',0);
      end;
   case 'bvar_omega_prior_density'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % contruct the plots
         %
         drawnow;
         GraphBVARPriorDensity('Omega',DSGEModel,CurrINI)
         set(controls.about,'UserData',0);
      end;
   case 'irs_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view graphs of the impulse responses before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Impulse Responses at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
               %
               % Try to calculate impulse responses. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [IRStructure,mcode] = CalculateDSGEImpulseResponse(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
               %
               % If status~=1, the model doesn't have a unique convergent solutions
               %
               if mcode==1;
                  ShockType = 'individual';
                  if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                     txt = 'Would you like to view plots of impulse responses for shock groups instead of for the individual shocks?';
                     answer = Query(txt,'question',140,'Original Impulse Responses - Initial Values',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                        Ksi = zeros(size(IRStructure.Ksi,1),size(IMatrix,2),size(IRStructure.Ksi,3));
                        Y = zeros(size(IRStructure.Y,1),size(IMatrix,2),size(IRStructure.Y,3));
                        for i=1:size(IRStructure.Y,3);
                           Ksi(:,:,i) = IRStructure.Ksi(:,:,i)*IMatrix;
                           Y(:,:,i) = IRStructure.Y(:,:,i)*IMatrix;
                        end;
                        ShockType = 'group';
                        IRStructure.Ksi = Ksi;
                        IRStructure.Y = Y;
                     end;
                  end;
                  %
                  % Display the impulse responses
                  %
                  IRGraphDLG('init',CurrINI,DSGEModel,IRStructure,'Initial Values','Original',ShockType);
               else;
                  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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'irs_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            %
            % we can now compute the impulse response functions up to a given horizon
            %
            IRStructure = CalculateDSGEImpulseResponse(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
            %
            % Display the impulse responses
            %
            if isempty(IRStructure)==0;
               %
               % check if the user would like to plot shocks or shock groups
               %
               ShockType = 'individual';
               if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                  txt = 'Would you like to view plots of impulse responses for shock groups instead of for the individual shocks?';
                  answer = Query(txt,'question',140,'Original Impulse Responses - Posterior Mode',500,'no',CurrINI);
                  if strcmp(lower(answer),'yes')==1;
                     IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                     Ksi = zeros(size(IRStructure.Ksi,1),size(IMatrix,2),size(IRStructure.Ksi,3));
                     Y = zeros(size(IRStructure.Y,1),size(IMatrix,2),size(IRStructure.Y,3));
                     for i=1:size(IRStructure.Y,3);
                        Ksi(:,:,i) = IRStructure.Ksi(:,:,i)*IMatrix;
                        Y(:,:,i) = IRStructure.Y(:,:,i)*IMatrix;
                     end;
                     ShockType = 'group';
                     IRStructure.Ksi = Ksi;
                     IRStructure.Y = Y;
                  end;
               end;
               IRGraphDLG('init',CurrINI,DSGEModel,IRStructure,'Posterior Mode','Original',ShockType);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'irs_annual_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view graphs of the impulse responses before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Impulse Responses at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
               %
               % Try to calculate impulse responses. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [IRStructure,mcode] = CalculateDSGEImpulseResponse(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,2);
               %
               % If status~=1, the model doesn't have a unique convergent solutions
               %
               if mcode==1;
                  ShockType = 'individual';
                  if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                     txt = 'Would you like to view plots of impulse responses for shock groups instead of for the individual shocks?';
                     answer = Query(txt,'question',140,'Annualized Impulse Responses - Initial Values',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                        Ksi = zeros(size(IRStructure.Ksi,1),size(IMatrix,2),size(IRStructure.Ksi,3));
                        Y = zeros(size(IRStructure.Y,1),size(IMatrix,2),size(IRStructure.Y,3));
                        for i=1:size(IRStructure.Y,3);
                           Ksi(:,:,i) = IRStructure.Ksi(:,:,i)*IMatrix;
                           Y(:,:,i) = IRStructure.Y(:,:,i)*IMatrix;
                        end;
                        ShockType = 'group';
                        IRStructure.Ksi = Ksi;
                        IRStructure.Y = Y;
                     end;
                  end;
                  %
                  % Display the impulse responses
                  %
                  IRGraphDLG('init',CurrINI,DSGEModel,IRStructure,'Initial Values','Annualized',ShockType);
               else;
                  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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'irs_annual_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            %
            % we can now compute the impulse response functions up to a given horizon
            %
            IRStructure = CalculateDSGEImpulseResponse(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,2);
            %
            % Display the impulse responses
            %
            if isempty(IRStructure)==0;
               ShockType = 'individual';
               if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                  txt = 'Would you like to view plots of impulse responses for shock groups instead of for the individual shocks?';
                  answer = Query(txt,'question',140,'Annualized Impulse Responses - Posterior Mode',500,'no',CurrINI);
                  if strcmp(lower(answer),'yes')==1;
                     IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                     Ksi = zeros(size(IRStructure.Ksi,1),size(IMatrix,2),size(IRStructure.Ksi,3));
                     Y = zeros(size(IRStructure.Y,1),size(IMatrix,2),size(IRStructure.Y,3));
                     for i=1:size(IRStructure.Y,3);
                        Ksi(:,:,i) = IRStructure.Ksi(:,:,i)*IMatrix;
                        Y(:,:,i) = IRStructure.Y(:,:,i)*IMatrix;
                     end;
                     ShockType = 'group';
                     IRStructure.Ksi = Ksi;
                     IRStructure.Y = Y;
                  end;
               end;
               IRGraphDLG('init',CurrINI,DSGEModel,IRStructure,'Posterior Mode','Annualized',ShockType);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'irs_levels_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view graphs of the impulse responses of the levels data before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Impulse Responses at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
               %
               % Try to calculate impulse responses. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [IRStructure,mcode] = CalculateDSGEImpulseResponse(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,1);
               %
               % If status~=1, the model doesn't have a unique convergent solutions
               %
               if mcode==1;
                  %
                  % Display the impulse responses
                  %
                  ShockType = 'individual';
                  if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                     txt = 'Would you like to view plots of impulse responses for shock groups instead of for the individual shocks?';
                     answer = Query(txt,'question',140,'Levels Impulse Responses - Initial Values',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                        Ksi = zeros(size(IRStructure.Ksi,1),size(IMatrix,2),size(IRStructure.Ksi,3));
                        Y = zeros(size(IRStructure.Y,1),size(IMatrix,2),size(IRStructure.Y,3));
                        for i=1:size(IRStructure.Y,3);
                           Ksi(:,:,i) = IRStructure.Ksi(:,:,i)*IMatrix;
                           Y(:,:,i) = IRStructure.Y(:,:,i)*IMatrix;
                        end;
                        ShockType = 'group';
                        IRStructure.Ksi = Ksi;
                        IRStructure.Y = Y;
                     end;
                  end;
                  IRGraphDLG('init',CurrINI,DSGEModel,IRStructure,'Initial Values','Levels',ShockType);
               else;
                  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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'irs_levels_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            %
            % we can now compute the impulse response functions up to a given horizon
            %
            IRStructure = CalculateDSGEImpulseResponse(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,1);
            %
            % Display the impulse responses
            %
            if isempty(IRStructure)==0;
               ShockType = 'individual';
               if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                  txt = 'Would you like to view plots of impulse responses for shock groups instead of for the individual shocks?';
                  answer = Query(txt,'question',140,'Levels Impulse Responses - Posterior Mode',500,'no',CurrINI);
                  if strcmp(lower(answer),'yes')==1;
                     IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                     Ksi = zeros(size(IRStructure.Ksi,1),size(IMatrix,2),size(IRStructure.Ksi,3));
                     Y = zeros(size(IRStructure.Y,1),size(IMatrix,2),size(IRStructure.Y,3));
                     for i=1:size(IRStructure.Y,3);
                        Ksi(:,:,i) = IRStructure.Ksi(:,:,i)*IMatrix;
                        Y(:,:,i) = IRStructure.Y(:,:,i)*IMatrix;
                     end;
                     ShockType = 'group';
                     IRStructure.Ksi = Ksi;
                     IRStructure.Y = Y;
                  end;
               end;
               IRGraphDLG('init',CurrINI,DSGEModel,IRStructure,'Posterior Mode','Levels',ShockType);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'fevd_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view the forecast error variance decompositions before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Variance Decompositions at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
               %
               % Try to calculate impulse responses. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [FEVDs,LRVD,UniquenessCheck,mcode] = DSGEVarianceDecompostion(theta,thetaPositions,ModelParameters,0,DSGEModel,CurrINI);
               %
               % If status~=1, the model doesn't have a unique convergent solutions
               %
               if mcode==1;
                  %
                  % Display the results - if any
                  %
                  if (isempty(FEVDs)==0)&(length(size(FEVDs))==3);
                     %
                     % ask if we should save to disk
                     %
                     txt = 'Would you like to save the variance decompositions at initial values to file?';
                     answer = Query(txt,'question',140,'Save - Variance Decompositions',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        file = [DSGEModel.OutputDirectory '\VarianceDecompositions-InitialValues.mat'];
                        YNames = DSGEModel.VariableNames;
                        ShockNames = DSGEModel.StateShockNames;
                        save(file,'FEVDs','LRVD','YNames','ShockNames');
                        %
                        % create a matlab file to read the data
                        %
                        mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'VarianceDecompositions','VD');
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                        fprintf(fid,'YNames = DataStructure.YNames;\n');
                        fprintf(fid,'%%\n%% string matrix with the names of the economic shocks\n%%\n');
                        fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                        fprintf(fid,'%%\n%% a 3D matrix of dimension nx(n+q+1)xh with the variance decompositions\n%% for the n observed variables into the n potential measurement errors,\n%% the q economic shocks, the signal extraction error, and the h\n%% forecast horizons\n%%\n');
                        fprintf(fid,'FEVDs = DataStructure.FEVDs;\n');
                        fprintf(fid,'%%\n%% a nx(n+q) matrix with the long-run variance decompositions for the\n%% n observed variables into the n potential measurement errors,\n%% and the q economic shocks.\n%%\n');
                        fprintf(fid,'LRVD = DataStructure.LRVD;');
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        txt = ['The variance decompositions have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 4 entries: YNames (string matrix with the names of the observed variables), ShockNames (string matrix with the names of the economic shocks), FEVDs (a 3D matrix of dimension nx(n+q+1)xh with the variance decompositions for the n observed variables), and LRVD (a nx(n+q) matrix with the long-run variance decompositions for the n observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','Variance Decompositions',200,500,CurrINI);
                     end;
                     %
                     % ask if we should look at shock groups
                     %
                     PrintGroups = 0;
                     if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                        txt = 'Would you like to view results of the variance decompositions for shock groups instead of for the individual shocks?';
                        answer = Query(txt,'question',140,'Variance Decompositions',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           FEVD = zeros(size(FEVDs,1),max(DSGEModel.ShockGroups)+2,size(FEVDs,3));
                           IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                           IMatrixSR = [ones(size(FEVDs,1),1) zeros(size(FEVDs,1),size(IMatrix,2)+1);zeros(size(IMatrix,1),1) IMatrix zeros(size(IMatrix,1),1);zeros(1,size(IMatrix,2)+1) 1];
                           IMatrixLR = [ones(size(LRVD,1),1) zeros(size(LRVD,1),size(IMatrix,2));zeros(size(IMatrix,1),1) IMatrix];
                           for i=1:size(FEVDs,3);
                              FEVD(:,:,i) = FEVDs(:,:,i)*IMatrixSR;
                           end;
                           LRVD = LRVD*IMatrixLR;
                           FEVDs = FEVD;
                           PrintGroups = 1;
                        end;
                     end;
                     %
                     % print the results to file
                     %
                     PrintVarianceDecompositions(DSGEModel,FEVDs,LRVD,UniquenessCheck,PrintGroups,0,CurrINI,'initial');
                     if PrintGroups==0;
                        ResFile = [DSGEModel.OutputDirectory '\InitialValueFEVDs-' DSGEModel.NameOfModel '.txt'];
                     else;
                        ResFile = [DSGEModel.OutputDirectory '\InitialValueFEVDs-ShockGroups-' DSGEModel.NameOfModel '.txt'];
                     end;
                     if FileExist(ResFile)==1;
                        TextGUI(ResFile,['Variance Decompositions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Initial Parameter Values',50,CurrINI,1,1);
                     end;
                  end;
               else;
                  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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'fevd_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            %
            % we can now compute the forecast error variance decompositions up to a given horizon
            %
            [FEVDs,LRVD,UniquenessCheck] = DSGEVarianceDecompostion(theta,thetaPositions,ModelParameters,0,DSGEModel,CurrINI);
            if (isempty(FEVDs)==0)&(length(size(FEVDs))==3);
               %
               % ask if we should save to disk
               %
               txt = 'Would you like to save the variance decompositions at posterior mode to file?';
               answer = Query(txt,'question',140,'Save - Variance Decompositions',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  file = [DSGEModel.OutputDirectory '\VarianceDecompositions-PosteriorMode.mat'];
                  YNames = DSGEModel.VariableNames;
                  ShockNames = DSGEModel.StateShockNames;
                  save(file,'FEVDs','LRVD','YNames','ShockNames');
                  %
                  % create a matlab file to read the data
                  %
                  mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'VarianceDecompositions','VD');
                  fid = fopen(mfile,'wt');
                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                  fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                  fprintf(fid,'YNames = DataStructure.YNames;\n');
                  fprintf(fid,'%%\n%% string matrix with the names of the economic shocks\n%%\n');
                  fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                  fprintf(fid,'%%\n%% a 3D matrix of dimension nx(n+q+1)xh with the variance decompositions\n%% for the n observed variables into the n potential measurement errors,\n%% the q economic shocks, the signal extraction error, and the h\n%% forecast horizons\n%%\n');
                  fprintf(fid,'FEVDs = DataStructure.FEVDs;\n');
                  fprintf(fid,'%%\n%% a nx(n+q) matrix with the long-run variance decompositions for the\n%% n observed variables into the n potential measurement errors,\n%% and the q economic shocks.\n%%\n');
                  fprintf(fid,'LRVD = DataStructure.LRVD;');
                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                  %
                  % end the script file
                  %
                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                  fclose(fid);
                  txt = ['The variance decompositions have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 4 entries: YNames (string matrix with the names of the observed variables), ShockNames (string matrix with the names of the economic shocks), FEVDs (a 3D matrix of dimension nx(n+q+1)xh with the variance decompositions for the n observed variables), and LRVD (a nx(n+q) matrix with the long-run variance decompositions for the n observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                  About(txt,'information','Variance Decompositions',200,500,CurrINI);
               end;
               %
               % ask if we should look at shock groups
               %
               PrintGroups = 0;
               if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                  txt = 'Would you like to view results of the variance decompositions for shock groups instead of for the individual shocks?';
                  answer = Query(txt,'question',140,'Variance Decompositions',500,'no',CurrINI);
                  if strcmp(lower(answer),'yes')==1;
                     FEVD = zeros(size(FEVDs,1),max(DSGEModel.ShockGroups)+2,size(FEVDs,3));
                     IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                     IMatrixSR = [ones(size(FEVDs,1),1) zeros(size(FEVDs,1),size(IMatrix,2)+1);zeros(size(IMatrix,1),1) IMatrix zeros(size(IMatrix,1),1);zeros(1,size(IMatrix,2)+1) 1];
                     IMatrixLR = [ones(size(LRVD,1),1) zeros(size(LRVD,1),size(IMatrix,2));zeros(size(IMatrix,1),1) IMatrix];
                     for i=1:size(FEVDs,3);
                        FEVD(:,:,i) = FEVDs(:,:,i)*IMatrixSR;
                     end;
                     LRVD = LRVD*IMatrixLR;
                     FEVDs = FEVD;
                     PrintGroups = 1;
                  end;
               end;
               %
               % print the results to file
               %
               PrintVarianceDecompositions(DSGEModel,FEVDs,LRVD,UniquenessCheck,PrintGroups,0,CurrINI,'posterior mode');
               if PrintGroups==0;
                  ResFile = [DSGEModel.OutputDirectory '\PosteriorModeFEVDs-' DSGEModel.NameOfModel '.txt'];
               else;
                  ResFile = [DSGEModel.OutputDirectory '\PosteriorModeFEVDs-ShockGroups-' DSGEModel.NameOfModel '.txt'];
               end;
               if FileExist(ResFile)==1;
                  TextGUI(ResFile,['Variance Decompositions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,1);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'fevd_levels_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view the forecast error variance decompositions for the levels before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Variance Decompositions at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
               %
               % Try to calculate impulse responses. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [FEVDs,LRVD,UniquenessCheck,mcode] = DSGEVarianceDecompostion(theta,thetaPositions,ModelParameters,1,DSGEModel,CurrINI);
               %
               % If status~=1, the model doesn't have a unique convergent solutions
               %
               if mcode==1;
                  %
                  % Display the results - if any
                  %
                  if (isempty(FEVDs)==0)&(length(size(FEVDs))==3);
                     %
                     % ask if we should save to disk
                     %
                     txt = 'Would you like to save the variance decompositions for the levels at initial values to file?';
                     answer = Query(txt,'question',140,'Save - Variance Decompositions',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        file = [DSGEModel.OutputDirectory '\VarianceDecompositions-Levels-InitialValues.mat'];
                        YNames = DSGEModel.VariableNames;
                        ShockNames = DSGEModel.StateShockNames;
                        save(file,'FEVDs','LRVD','YNames','ShockNames');
                        %
                        % create a matlab file to read the data
                        %
                        mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'VarianceDecompositionsLevels','VDL');
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                        fprintf(fid,'YNames = DataStructure.YNames;\n');
                        fprintf(fid,'%%\n%% string matrix with the names of the economic shocks\n%%\n');
                        fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                        fprintf(fid,'%%\n%% a 3D matrix of dimension nx(n+q+1)xh with the variance decompositions\n%% for the levels of the n observed variables into the n potential measurement errors,\n%% the q economic shocks, the signal extraction error, and the h\n%% forecast horizons\n%%\n');
                        fprintf(fid,'FEVDs = DataStructure.FEVDs;\n');
                        fprintf(fid,'%%\n%% a nx(n+q) matrix with the long-run variance decompositions for the\n%% n observed variables into the n potential measurement errors,\n%% and the q economic shocks.\n%%\n');
                        fprintf(fid,'LRVD = DataStructure.LRVD;');
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        txt = ['The variance decompositions for the levels have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 4 entries: YNames (string matrix with the names of the observed variables), ShockNames (string matrix with the names of the economic shocks), FEVDs (a 3D matrix of dimension nx(n+q+1)xh with the variance decompositions for the n observed variables), and LRVD (a nx(n+q) matrix with the long-run variance decompositions for the n observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','Variance Decompositions',200,500,CurrINI);
                     end;
                     %
                     % ask if we should look at shock groups
                     %
                     PrintGroups = 0;
                     if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                        txt = 'Would you like to view results of the variance decompositions of the levels for shock groups instead of for the individual shocks?';
                        answer = Query(txt,'question',140,'Variance Decompositions',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           FEVD = zeros(size(FEVDs,1),max(DSGEModel.ShockGroups)+2,size(FEVDs,3));
                           IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                           IMatrixSR = [ones(size(FEVDs,1),1) zeros(size(FEVDs,1),size(IMatrix,2)+1);zeros(size(IMatrix,1),1) IMatrix zeros(size(IMatrix,1),1);zeros(1,size(IMatrix,2)+1) 1];
                           IMatrixLR = [ones(size(LRVD,1),1) zeros(size(LRVD,1),size(IMatrix,2));zeros(size(IMatrix,1),1) IMatrix];
                           for i=1:size(FEVDs,3);
                              FEVD(:,:,i) = FEVDs(:,:,i)*IMatrixSR;
                           end;
                           LRVD = LRVD*IMatrixLR;
                           FEVDs = FEVD;
                           PrintGroups = 1;
                        end;
                     end;
                     %
                     % print the results to file
                     %
                     PrintVarianceDecompositions(DSGEModel,FEVDs,LRVD,UniquenessCheck,PrintGroups,1,CurrINI,'initial');
                     if PrintGroups==0;
                        ResFile = [DSGEModel.OutputDirectory '\InitialValueFEVDs-Levels-' DSGEModel.NameOfModel '.txt'];
                     else;
                        ResFile = [DSGEModel.OutputDirectory '\InitialValueFEVDs-ShockGroups-Levels-' DSGEModel.NameOfModel '.txt'];
                     end;
                     if FileExist(ResFile)==1;
                        TextGUI(ResFile,['Levels Variance Decompositions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Initial Parameter Values',50,CurrINI,1,1);
                     end;
                  end;
               else;
                  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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'fevd_levels_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            %
            % we can now compute the forecast error variance decompositions up to a given horizon
            %
            [FEVDs,LRVD,UniquenessCheck] = DSGEVarianceDecompostion(theta,thetaPositions,ModelParameters,1,DSGEModel,CurrINI);
            if (isempty(FEVDs)==0)&(length(size(FEVDs))==3);
               %
               % ask if we should save to disk
               %
               txt = 'Would you like to save the variance decompositions for the levels at posterior mode to file?';
               answer = Query(txt,'question',140,'Save - Variance Decompositions',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  file = [DSGEModel.OutputDirectory '\VarianceDecompositions-Levels-PosteriorMode.mat'];
                  YNames = DSGEModel.VariableNames;
                  ShockNames = DSGEModel.StateShockNames;
                  save(file,'FEVDs','LRVD','YNames','ShockNames');
                  %
                  % create a matlab file to read the data
                  %
                  mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'VarianceDecompositionsLevels','VDL');
                  fid = fopen(mfile,'wt');
                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                  fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                  fprintf(fid,'YNames = DataStructure.YNames;\n');
                  fprintf(fid,'%%\n%% string matrix with the names of the economic shocks\n%%\n');
                  fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                  fprintf(fid,'%%\n%% a 3D matrix of dimension nx(n+q+1)xh with the variance decompositions\n%% for the levels of the n observed variables into the n potential measurement errors,\n%% the q economic shocks, the signal extraction error, and the h\n%% forecast horizons\n%%\n');
                  fprintf(fid,'FEVDs = DataStructure.FEVDs;\n');
                  fprintf(fid,'%%\n%% a nx(n+q) matrix with the long-run variance decompositions for the\n%% n observed variables into the n potential measurement errors,\n%% and the q economic shocks.\n%%\n');
                  fprintf(fid,'LRVD = DataStructure.LRVD;');
                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                  %
                  % end the script file
                  %
                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                  fclose(fid);
                  txt = ['The variance decompositions for the levels have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 4 entries: YNames (string matrix with the names of the observed variables), ShockNames (string matrix with the names of the economic shocks), FEVDs (a 3D matrix of dimension nx(n+q+1)xh with the variance decompositions for the n observed variables), and LRVD (a nx(n+q) matrix with the long-run variance decompositions for the n observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                  About(txt,'information','Variance Decompositions',200,500,CurrINI);
               end;
               %
               % ask if we should look at shock groups
               %
               PrintGroups = 0;
               if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                  txt = 'Would you like to view results of the variance decompositions of the levels for shock groups instead of for the individual shocks?';
                  answer = Query(txt,'question',140,'Variance Decompositions',500,'no',CurrINI);
                  if strcmp(lower(answer),'yes')==1;
                     FEVD = zeros(size(FEVDs,1),max(DSGEModel.ShockGroups)+2,size(FEVDs,3));
                     IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                     IMatrixSR = [ones(size(FEVDs,1),1) zeros(size(FEVDs,1),size(IMatrix,2)+1);zeros(size(IMatrix,1),1) IMatrix zeros(size(IMatrix,1),1);zeros(1,size(IMatrix,2)+1) 1];
                     IMatrixLR = [ones(size(LRVD,1),1) zeros(size(LRVD,1),size(IMatrix,2));zeros(size(IMatrix,1),1) IMatrix];
                     for i=1:size(FEVDs,3);
                        FEVD(:,:,i) = FEVDs(:,:,i)*IMatrixSR;
                     end;
                     LRVD = LRVD*IMatrixLR;
                     FEVDs = FEVD;
                     PrintGroups = 1;
                  end;
               end;
               %
               % print the results to file
               %
               PrintVarianceDecompositions(DSGEModel,FEVDs,LRVD,UniquenessCheck,PrintGroups,1,CurrINI,'posterior mode');
               if PrintGroups==0;
                  ResFile = [DSGEModel.OutputDirectory '\PosteriorModeFEVDs-Levels-' DSGEModel.NameOfModel '.txt'];
               else;
                  ResFile = [DSGEModel.OutputDirectory '\PosteriorModeFEVDs-ShockGroups-Levels-' DSGEModel.NameOfModel '.txt'];
               end;
               if FileExist(ResFile)==1;
                  TextGUI(ResFile,['Levels Variance Decompositions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,1);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'cvd_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view the forecast error variance decompositions before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Variance Decompositions at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
               %
               % Try to calculate impulse responses. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [FEVDs,ConvValue,mcode] = DSGECondVarianceDecompostion(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
               %
               % If status~=1, the model doesn't have a unique convergent solutions
               %
               if mcode==1;
                  %
                  % Display the results - if any
                  %
                  if (isempty(FEVDs)==0)&(length(size(FEVDs))==3);
                     %
                     % ask if we should save to disk
                     %
                     txt = 'Would you like to save the conditional variance decompositions for the original data at initial values to file?';
                     answer = Query(txt,'question',140,'Save - Conditional Variance Decompositions',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        file = [DSGEModel.OutputDirectory '\CondVarianceDecompositions-InitialValues-Original.mat'];
                        YNames = DSGEModel.VariableNames;
                        ShockNames = DSGEModel.StateShockNames;
                        save(file,'FEVDs','YNames','ShockNames');
                        %
                        % create a matlab file to read the data
                        %
                        mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'CondVarianceDecompositions','CVD');
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                        fprintf(fid,'YNames = DataStructure.YNames;\n');
                        fprintf(fid,'%%\n%% string matrix with the names of the economic shocks\n%%\n');
                        fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                        fprintf(fid,'%%\n%% a 3D matrix of dimension nxqxh with the conditional variance decompositions\n%% for the n observed variables, the q economic shocks, and the h forecast horizons\n%%\n');
                        fprintf(fid,'FEVDs = DataStructure.FEVDs;\n');
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        txt = ['The conditional variance decompositions for the original data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 3 entries: YNames (string matrix with the names of the observed variables), ShockNames (string matrix with the names of the economic shocks), and FEVDs (a 3D matrix of dimension nxqxh with the variance decompositions for the n observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','Conditional Variance Decompositions',200,500,CurrINI);
                     end;
                     %
                     % ask if we should look at shock groups
                     %
                     PrintGroups = 0;
                     if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                        txt = 'Would you like to view results of the conditional variance decompositions for shock groups instead of for the individual shocks?';
                        answer = Query(txt,'question',140,'Conditional Variance Decompositions',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           FEVD = zeros(size(FEVDs,1),max(DSGEModel.ShockGroups),size(FEVDs,3));
                           IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                           for i=1:size(FEVDs,3);
                              FEVD(:,:,i) = FEVDs(:,:,i)*IMatrix;
                           end;
                           FEVDs = FEVD;
                           PrintGroups = 1;
                        end;
                     end;
                     %
                     % we can now present the results
                     %
                     PrintCondVarianceDecompositions(DSGEModel,FEVDs,ConvValue,PrintGroups,CurrINI,'initial','');
                     if PrintGroups==0;
                        ResFile = [DSGEModel.OutputDirectory '\InitialValueCFEVDs-' DSGEModel.NameOfModel '.txt'];
                     else;
                        ResFile = [DSGEModel.OutputDirectory '\InitialValueCFEVDs-ShockGroups-' DSGEModel.NameOfModel '.txt'];
                     end;
                     if FileExist(ResFile)==1;
                        TextGUI(ResFile,['Conditional Variance Decompositions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Initial Parameter Values',50,CurrINI,1,1);
                     end;
                  end;
               else;
                  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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'cvd_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            %
            % we can now compute the conditional forecast error variance decompositions up to a given horizon
            %
            [FEVDs,ConvValue] = DSGECondVarianceDecompostion(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
            if (isempty(FEVDs)==0)&(length(size(FEVDs))==3);
               %
               % ask if we should save to disk
               %
               txt = 'Would you like to save the conditional variance decompositions for the original data at posterior mode to file?';
               answer = Query(txt,'question',140,'Save - Conditional Variance Decompositions',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  file = [DSGEModel.OutputDirectory '\CondVarianceDecompositions-PosteriorMode-Original.mat'];
                  YNames = DSGEModel.VariableNames;
                  ShockNames = DSGEModel.StateShockNames;
                  save(file,'FEVDs','YNames','ShockNames');
                  %
                  % create a matlab file to read the data
                  %
                  mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'CondVarianceDecompositions','CVD');
                  fid = fopen(mfile,'wt');
                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                  fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                  fprintf(fid,'YNames = DataStructure.YNames;\n');
                  fprintf(fid,'%%\n%% string matrix with the names of the economic shocks\n%%\n');
                  fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                  fprintf(fid,'%%\n%% a 3D matrix of dimension nxqxh with the conditional variance decompositions\n%% for the n observed variables, the q economic shocks, and the h forecast horizons\n%%\n');
                  fprintf(fid,'FEVDs = DataStructure.FEVDs;\n');
                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                  %
                  % end the script file
                  %
                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                  fclose(fid);
                  txt = ['The conditional variance decompositions for the original data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 3 entries: YNames (string matrix with the names of the observed variables), ShockNames (string matrix with the names of the economic shocks), and FEVDs (a 3D matrix of dimension nxqxh with the variance decompositions for the n observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                  About(txt,'information','Conditional Variance Decompositions',200,500,CurrINI);
               end;
               %
               % ask if we should look at shock groups
               %
               PrintGroups = 0;
               if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                  txt = 'Would you like to view results of the conditional variance decompositions for shock groups instead of for the individual shocks?';
                  answer = Query(txt,'question',140,'Conditional Variance Decompositions',500,'no',CurrINI);
                  if strcmp(lower(answer),'yes')==1;
                     FEVD = zeros(size(FEVDs,1),max(DSGEModel.ShockGroups),size(FEVDs,3));
                     IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                     for i=1:size(FEVDs,3);
                        FEVD(:,:,i) = FEVDs(:,:,i)*IMatrix;
                     end;
                     FEVDs = FEVD;
                     PrintGroups = 1;
                  end;
               end;
               %
               % we can now print the results to file
               %
               PrintCondVarianceDecompositions(DSGEModel,FEVDs,ConvValue,PrintGroups,CurrINI,'posterior mode','');
               if PrintGroups==0;
                  ResFile = [DSGEModel.OutputDirectory '\PosteriorModeCFEVDs-' DSGEModel.NameOfModel '.txt'];
               else;
                  ResFile = [DSGEModel.OutputDirectory '\PosteriorModeCFEVDs-ShockGroups-' DSGEModel.NameOfModel '.txt'];
               end;
               if FileExist(ResFile)==1;
                  TextGUI(ResFile,['Conditional Variance Decompositions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,1);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'cvd_annual_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view the annualized forecast error variance decompositions before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Variance Decompositions at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
               %
               % Try to calculate impulse responses. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [FEVDs,ConvValue,mcode] = DSGECondVarianceDecompostion(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,2);
               %
               % If status~=1, the model doesn't have a unique convergent solutions
               %
               if mcode==1;
                  %
                  % Display the results - if any
                  %
                  if (isempty(FEVDs)==0)&(length(size(FEVDs))==3);
                     %
                     % ask if we should save to disk
                     %
                     txt = 'Would you like to save the conditional variance decompositions for the annualized data at initial values to file?';
                     answer = Query(txt,'question',140,'Save - Conditional Variance Decompositions',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        file = [DSGEModel.OutputDirectory '\CondVarianceDecompositions-InitialValues-Annual.mat'];
                        YNames = DSGEModel.VariableNames;
                        ShockNames = DSGEModel.StateShockNames;
                        save(file,'FEVDs','YNames','ShockNames');
                        %
                        % create a matlab file to read the data
                        %
                        mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'CondVarianceDecompositions','CVD');
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                        fprintf(fid,'YNames = DataStructure.YNames;\n');
                        fprintf(fid,'%%\n%% string matrix with the names of the economic shocks\n%%\n');
                        fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                        fprintf(fid,'%%\n%% a 3D matrix of dimension nxqxh with the conditional variance decompositions\n%% for the n observed variables, the q economic shocks, and the h forecast horizons\n%%\n');
                        fprintf(fid,'FEVDs = DataStructure.FEVDs;\n');
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        txt = ['The conditional variance decompositions for the annualized data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 3 entries: YNames (string matrix with the names of the observed variables), ShockNames (string matrix with the names of the economic shocks), and FEVDs (a 3D matrix of dimension nxqxh with the variance decompositions for the n observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','Conditional Variance Decompositions',200,500,CurrINI);
                     end;
                     %
                     % ask if we should look at shock groups
                     %
                     PrintGroups = 0;
                     if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                        txt = 'Would you like to view results of the conditional variance decompositions for shock groups instead of for the individual shocks?';
                        answer = Query(txt,'question',140,'Conditional Variance Decompositions',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           FEVD = zeros(size(FEVDs,1),max(DSGEModel.ShockGroups),size(FEVDs,3));
                           IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                           for i=1:size(FEVDs,3);
                              FEVD(:,:,i) = FEVDs(:,:,i)*IMatrix;
                           end;
                           FEVDs = FEVD;
                           PrintGroups = 1;
                        end;
                     end;
                     %
                     % print the results to file
                     %
                     PrintCondVarianceDecompositions(DSGEModel,FEVDs,ConvValue,PrintGroups,CurrINI,'initial','Annualized');
                     if PrintGroups==0;
                        ResFile = [DSGEModel.OutputDirectory '\InitialValueCFEVDs-Annualized-' DSGEModel.NameOfModel '.txt'];
                     else;
                        ResFile = [DSGEModel.OutputDirectory '\InitialValueCFEVDs-ShockGroups-Annualized-' DSGEModel.NameOfModel '.txt'];
                     end;
                     if FileExist(ResFile)==1;
                        TextGUI(ResFile,['Conditional Annualized Variance Decompositions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Initial Parameter Values',50,CurrINI,1,1);
                     end;
                  end;
               else;
                  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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'cvd_annual_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            %
            % we can now compute the conditional forecast error variance decompositions up to a given horizon
            %
            [FEVDs,ConvValue] = DSGECondVarianceDecompostion(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,2);
            if (isempty(FEVDs)==0)&(length(size(FEVDs))==3);
               %
               % ask if we should save to disk
               %
               txt = 'Would you like to save the conditional variance decompositions for the annualized data at posterior mode to file?';
               answer = Query(txt,'question',140,'Save - Conditional Variance Decompositions',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  file = [DSGEModel.OutputDirectory '\CondVarianceDecompositions-PosteriorMode-Annual.mat'];
                  YNames = DSGEModel.VariableNames;
                  ShockNames = DSGEModel.StateShockNames;
                  save(file,'FEVDs','YNames','ShockNames');
                  %
                  % create a matlab file to read the data
                  %
                  mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'CondVarianceDecompositions','CVD');
                  fid = fopen(mfile,'wt');
                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                  fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                  fprintf(fid,'YNames = DataStructure.YNames;\n');
                  fprintf(fid,'%%\n%% string matrix with the names of the economic shocks\n%%\n');
                  fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                  fprintf(fid,'%%\n%% a 3D matrix of dimension nxqxh with the conditional variance decompositions\n%% for the n observed variables, the q economic shocks, and the h forecast horizons\n%%\n');
                  fprintf(fid,'FEVDs = DataStructure.FEVDs;\n');
                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                  %
                  % end the script file
                  %
                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                  fclose(fid);
                  txt = ['The conditional variance decompositions for the annualized data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 3 entries: YNames (string matrix with the names of the observed variables), ShockNames (string matrix with the names of the economic shocks), and FEVDs (a 3D matrix of dimension nxqxh with the variance decompositions for the n observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                  About(txt,'information','Conditional Variance Decompositions',200,500,CurrINI);
               end;
               %
               % ask if we should look at shock groups
               %
               PrintGroups = 0;
               if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                  txt = 'Would you like to view results of the conditional variance decompositions for shock groups instead of for the individual shocks?';
                  answer = Query(txt,'question',140,'Conditional Variance Decompositions',500,'no',CurrINI);
                  if strcmp(lower(answer),'yes')==1;
                     FEVD = zeros(size(FEVDs,1),max(DSGEModel.ShockGroups),size(FEVDs,3));
                     IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                     for i=1:size(FEVDs,3);
                        FEVD(:,:,i) = FEVDs(:,:,i)*IMatrix;
                     end;
                     FEVDs = FEVD;
                     PrintGroups = 1;
                  end;
               end;
               %
               % print the results to file
               %
               PrintCondVarianceDecompositions(DSGEModel,FEVDs,ConvValue,PrintGroups,CurrINI,'posterior mode','Annualized');
               if PrintGroups==0;
                  ResFile = [DSGEModel.OutputDirectory '\PosteriorModeCFEVDs-Annualized-' DSGEModel.NameOfModel '.txt'];
               else;
                  ResFile = [DSGEModel.OutputDirectory '\PosteriorModeCFEVDs-ShockGroups-Annualized-' DSGEModel.NameOfModel '.txt'];
               end;
               if FileExist(ResFile)==1;
                  TextGUI(ResFile,['Conditional Annualized Variance Decompositions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,1);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'cvd_levels_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view the levels forecast error variance decompositions before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Variance Decompositions at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
               %
               % Try to calculate impulse responses. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [FEVDs,ConvValue,mcode] = DSGECondVarianceDecompostion(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,1);
               %
               % If status~=1, the model doesn't have a unique convergent solutions
               %
               if mcode==1;
                  %
                  % Display the results - if any
                  %
                  if (isempty(FEVDs)==0)&(length(size(FEVDs))==3);
                     %
                     % ask if we should save to disk
                     %
                     txt = 'Would you like to save the conditional variance decompositions for the levels data at initial values to file?';
                     answer = Query(txt,'question',140,'Save - Conditional Variance Decompositions',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        file = [DSGEModel.OutputDirectory '\CondVarianceDecompositions-InitialValues-Levels.mat'];
                        YNames = DSGEModel.VariableNames;
                        ShockNames = DSGEModel.StateShockNames;
                        save(file,'FEVDs','YNames','ShockNames');
                        %
                        % create a matlab file to read the data
                        %
                        mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'CondVarianceDecompositions','CVD');
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                        fprintf(fid,'YNames = DataStructure.YNames;\n');
                        fprintf(fid,'%%\n%% string matrix with the names of the economic shocks\n%%\n');
                        fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                        fprintf(fid,'%%\n%% a 3D matrix of dimension nxqxh with the conditional variance decompositions\n%% for the n observed variables, the q economic shocks, and the h forecast horizons\n%%\n');
                        fprintf(fid,'FEVDs = DataStructure.FEVDs;\n');
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        txt = ['The conditional variance decompositions for the levels data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 3 entries: YNames (string matrix with the names of the observed variables), ShockNames (string matrix with the names of the economic shocks), and FEVDs (a 3D matrix of dimension nxqxh with the variance decompositions for the n observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','Conditional Variance Decompositions',200,500,CurrINI);
                     end;
                     %
                     % ask if we should look at shock groups
                     %
                     PrintGroups = 0;
                     if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                        txt = 'Would you like to view results of the conditional variance decompositions for shock groups instead of for the individual shocks?';
                        answer = Query(txt,'question',140,'Conditional Variance Decompositions',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           FEVD = zeros(size(FEVDs,1),max(DSGEModel.ShockGroups),size(FEVDs,3));
                           IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                           for i=1:size(FEVDs,3);
                              FEVD(:,:,i) = FEVDs(:,:,i)*IMatrix;
                           end;
                           FEVDs = FEVD;
                           PrintGroups = 1;
                        end;
                     end;
                     %
                     % print the results to file
                     %
                     PrintCondVarianceDecompositions(DSGEModel,FEVDs,ConvValue,PrintGroups,CurrINI,'initial','Levels');
                     if PrintGroups==0;
                        ResFile = [DSGEModel.OutputDirectory '\InitialValueCFEVDs-Levels-' DSGEModel.NameOfModel '.txt'];
                     else;
                        ResFile = [DSGEModel.OutputDirectory '\InitialValueCFEVDs-ShockGroups-Levels-' DSGEModel.NameOfModel '.txt'];
                     end;
                     if FileExist(ResFile)==1;
                        TextGUI(ResFile,['Conditional Levels Variance Decompositions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Initial Parameter Values',50,CurrINI,1,1);
                     end;
                  end;
               else;
                  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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'cvd_levels_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            %
            % we can now compute the conditional forecast error variance decompositions up to a given horizon
            %
            [FEVDs,ConvValue] = DSGECondVarianceDecompostion(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,1);
            if (isempty(FEVDs)==0)&(length(size(FEVDs))==3);
               %
               % ask if we should save to disk
               %
               txt = 'Would you like to save the conditional variance decompositions for the levels data at posterior mode to file?';
               answer = Query(txt,'question',140,'Save - Conditional Variance Decompositions',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  file = [DSGEModel.OutputDirectory '\CondVarianceDecompositions-PosteriorMode-Levels.mat'];
                  YNames = DSGEModel.VariableNames;
                  ShockNames = DSGEModel.StateShockNames;
                  save(file,'FEVDs','YNames','ShockNames');
                  %
                  % create a matlab file to read the data
                  %
                  mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'CondVarianceDecompositions','CVD');
                  fid = fopen(mfile,'wt');
                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                  fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                  fprintf(fid,'YNames = DataStructure.YNames;\n');
                  fprintf(fid,'%%\n%% string matrix with the names of the economic shocks\n%%\n');
                  fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                  fprintf(fid,'%%\n%% a 3D matrix of dimension nxqxh with the conditional variance decompositions\n%% for the n observed variables, the q economic shocks, and the h forecast horizons\n%%\n');
                  fprintf(fid,'FEVDs = DataStructure.FEVDs;\n');
                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                  %
                  % end the script file
                  %
                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                  fclose(fid);
                  txt = ['The conditional variance decompositions for the levels data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 3 entries: YNames (string matrix with the names of the observed variables), ShockNames (string matrix with the names of the economic shocks), and FEVDs (a 3D matrix of dimension nxqxh with the variance decompositions for the n observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                  About(txt,'information','Conditional Variance Decompositions',200,500,CurrINI);
               end;
               %
               % ask if we should look at shock groups
               %
               PrintGroups = 0;
               if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                  txt = 'Would you like to view results of the conditional variance decompositions for shock groups instead of for the individual shocks?';
                  answer = Query(txt,'question',140,'Conditional Variance Decompositions',500,'no',CurrINI);
                  if strcmp(lower(answer),'yes')==1;
                     FEVD = zeros(size(FEVDs,1),max(DSGEModel.ShockGroups),size(FEVDs,3));
                     IMatrix = SubIdentityMatrix(DSGEModel.ShockGroups);
                     for i=1:size(FEVDs,3);
                        FEVD(:,:,i) = FEVDs(:,:,i)*IMatrix;
                     end;
                     FEVDs = FEVD;
                     PrintGroups = 1;
                  end;
               end;
               %
               % print the results to file
               %
               PrintCondVarianceDecompositions(DSGEModel,FEVDs,ConvValue,PrintGroups,CurrINI,'posterior mode','Levels');
               if PrintGroups==0;
                  ResFile = [DSGEModel.OutputDirectory '\PosteriorModeCFEVDs-Levels-' DSGEModel.NameOfModel '.txt'];
               else;
                  ResFile = [DSGEModel.OutputDirectory '\PosteriorModeCFEVDs-ShockGroups-Levels-' DSGEModel.NameOfModel '.txt'];
               end;
               if FileExist(ResFile)==1;
                  TextGUI(ResFile,['Conditional Levels Variance Decompositions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,1);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'uncon_pred_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view graphs of the predictive distributions of the observed variables before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Predictive Distributions at Initial Values',450,'no',CurrINI);
         end;
         %
         % check if we should check transformations functions
         %
         if gcbo==controls.predict.unconditional_transformed_initialvalues;
            ErrorStr = '';
            DTStatus = VerifyDataTransformation(DSGEModel.VariableNames,DSGEModel.YTransformation,0);
            if DTStatus==1;
               [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
            else;
               ErrorStr = 'You haven''t specified all the necessary fields for computing transformations of the observed variables.';
               HeaderStr = 'Missing Transformation Information';
            end;
            if isempty(ErrorStr)==0;
               About(ErrorStr,'information',HeaderStr,200,500,CurrINI);
               answer = 'no';
            end;
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
               %
               % check how many time periods to use for predictive distributions
               %
               [MaxPH,NumPredX] = CalcMaxPredictionHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,size(DSGEModel.PredictedX,2));
               %
               % matrix with exogenous variables
               %
               X = [];
               if DSGEModel.k>0;
                  if NumPredX<MaxPH;
                     X = DSGEModel.X(:,LastPeriod+1:LastPeriod+(MaxPH-NumPredX));
                  end;
                  if NumPredX>0;
                     X = [X DSGEModel.PredictedX(:,1:NumPredX)];
                  end;
               end;
               %
               % check if we should annualize or not
               %
               if gcbo==controls.predict.unconditional_original_initialvalues;
                  TransData = 0;
               AnnualizeData = 0;
               AnnualStr = 'original';
               elseif gcbo==controls.predict.unconditional_annual_initialvalues;
                  TransData = 0;
                  AnnualizeData = 1;
                  AnnualStr = 'annual';
               else;
                  TransData = 1;
                  AnnualizeData = 0;
                  AnnualStr = 'transformed';
               end;
               %
               % determine how many prediction paths to use
               %
               NumPredPathsStr = get(controls.forecast.predpaths,'String');
               NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
               %
               % ask if we should conduct prediction event calculations
               %
               if (isfield(DSGEModel,'PredictionEvent')==0)|(isempty(DSGEModel.PredictionEvent)==1)|(size(DSGEModel.PredictionEvent,1)~=DSGEModel.n)|(size(DSGEModel.PredictionEvent,2)~=3);
                  DSGEModel.PredictionEvent = [Inf*ones(DSGEModel.n,1) zeros(DSGEModel.n,1) ones(DSGEModel.n,1)];
               end;
               txt = 'Would you like YADA to calculate prediction event probabilities?';
               answer = Query(txt,'question',140,'Prediction Events',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  %
                  % make sure that the prediction event length does not exceed the maximum prediction horizon
                  %
                  for i=1:DSGEModel.n;
                     if DSGEModel.PredictionEvent(i,3)>MaxPH;
                        DSGEModel.PredictionEvent(i,3) = MaxPH;
                     end;
                  end;
                  %
                  % display a dialog for setting up an prediction event
                  %
                  [action,PredictionEvent] = PredictionEventDLG('init',DSGEModel.VariableNames,DSGEModel.PredictionEvent,MaxPH,CurrINI);
                  if strcmp(lower(action),'ok')==1;
                     DSGEModel.PredictionEvent = PredictionEvent;
                     DSGEModel.RunPredictionEvent = 1;
                  else;
                     DSGEModel.RunPredictionEvent = 0;
                  end;
               else;
                  DSGEModel.RunPredictionEvent = 0;
               end;
               %
               % we can now compute the predictive distribution for the endogenous variables
               % up to period MaxPh
               %
               if DSGEModel.RandomNumberValue==1;
                  randn('state',0);
               else;
                  randn('state',sum(100*clock));
               end;
               [PredPaths,PredData,PredEventData,YObsEventData,mcode,kalmanstatus] = DSGEPredictionPathsTheta(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,X,MaxPH,NumPredPaths,AnnualizeData,TransData,' At Initial Values');
               %
               if (mcode==1)&(kalmanstatus==0);
                  %
                  % we're hopefully OK
                  %
                  if isempty(PredPaths)==0;
                     %
                     % the computations went OK. Compute point estimates from predictive distribution and
                     % quantiles
                     %
                     [MeanPrediction,Quantiles] = PredictionPathDistribution(PredPaths,DSGEModel.Percentiles);
                     %
                     % compute the mean error bias in percent
                     %
                     MeanErrorBias = max(max(abs((PredData.PredMean-MeanPrediction)./PredData.PredMean)));
                     if DSGEModel.AdjustPredictionPaths==0;
                        %
                        % ask if the prediction distribution should be corrected
                        %
                        txt = ['The absolute mean error bias from using the simulated draws is ' num2str(MeanErrorBias,'%0.4f') ' percent relative to the theoretical mean. Would you like to adjust that predictive distribution such that it matches the theoretical mean?'];
                        answer = Query(txt,'question',140,'Mean Error Bias - Predictive Distributions',500,'yes',CurrINI);
                     else;
                        answer = 'Yes';
                     end;
                     if strcmp(lower(answer),'yes')==1;
                        %
                        % adjust the quantiles to match
                        %
                        for i=1:length(Quantiles);
                           OlVal = Quantiles(i).Quantile;
                           Quantiles(i).Quantile = Quantiles(i).Quantile+(PredData.PredMean-MeanPrediction);
                        end;
                        MeanPrediction = PredData.PredMean;
                     end;
                     %
                     % compute the forecast errors based on the mean predictions
                     %
                     PredictionErrors = CalculatePredictionErrors(MeanPrediction,AnnualizeData,TransData,'DSGE',DSGEModel);
                     %
                     % check if the user wants to save the data
                     %
                     txt = ['Would you like to save the predictive distributions for the ' AnnualStr ' data at initial values to file?'];
                     answer = Query(txt,'question',140,'Save - Predictive Distributions',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod,PredDateVector] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,size(MeanPrediction,2));
                        file = [DSGEModel.OutputDirectory '\PredictiveDist-' AnnualStr '-' num2str(MaxPH,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod 'InitialValues.mat'];
                        YNames = DSGEModel.VariableNames;
                        DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,PredEndYear,PredEndPeriod,DSGEModel.DataFrequency);
                        Y = DSGEModel.Y(:,FirstPeriod:min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                        if (length(DateVector)>size(Y,2))&(TransData==0);
                           DateVector = DateVector(1,1:size(Y,2));
                        end;
                        EstimationStartPeriod = DSGEModel.KalmanFirstObservation;
                        EstimationStartPeriodOrig = EstimationStartPeriod;
                        YOrig = Y;
                        DateVectorOrig = DateVector;
                        if AnnualizeData==1;
                           Y = Annualize(Y,DSGEModel.annual,DSGEModel.annualscale);
                           EstimationStartPeriod = max(1,EstimationStartPeriod-(length(DateVector)-size(Y,2)));
                           DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                        end;
                        if TransData==1;
                           [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
                           Y = YData';
                           if size(Y,2)==DSGEModel.T;
                              Y = Y(:,FirstPeriod:min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                           else;
                              T2 = size(Y,2);
                              if (FirstPeriod-(DSGEModel.T-T2))>=1;
                                 Y = Y(:,FirstPeriod-(DSGEModel.T-T2):min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                              else;
                                 Y = Y(:,1:min((LastPeriod+MaxPH),size(DSGEModel.Y,2))-(DSGEModel.T-T2));
                                 DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                              end;
                           end;
                        end;
                        PredMeanKsiStates = PredData.xiStates;
                        PredMean = PredData.PredMean;
                        StateVariableNames = DSGEModel.StateVariableNames;
                        KernelX = PredData.KernelX;
                        KernelY = PredData.KernelY;
                        if isempty(PredEventData)==1;
                           save(file,'MeanPrediction','PredMean','PredMeanKsiStates','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','StateVariableNames','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig');
                        else;
                           save(file,'MeanPrediction','PredMean','PredMeanKsiStates','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','StateVariableNames','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig','PredEventData','YObsEventData');
                        end;
                        %
                        % create a matlab m-file to read the output.
                        %
                        mfile = [DSGEModel.OutputDirectory '\PD' AnnualStr num2str(MaxPH,'%0.0f') DSGEModel.SubEndYear DSGEModel.SubEndPeriod 'InitVal.m'];
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                        fprintf(fid,'YNames = DataStructure.YNames;\n');
                        fprintf(fid,'%%\n%% matrix with the mean predictions of the observed variables\n%%\n');
                        fprintf(fid,'MeanPrediction = DataStructure.MeanPrediction;\n');
                        fprintf(fid,'%%\n%% matrix with the population mean predictions of the observed variables\n%%\n');
                        fprintf(fid,'PredMean = DataStructure.PredMean;\n');
                        fprintf(fid,'%%\n%% matrix with the population mean predictions of the state variables\n%%\n');
                        fprintf(fid,'PredMeanKsiStates = DataStructure.PredMeanKsiStates;\n');
                        fprintf(fid,'%%\n%% string matrix with the names of the state variables\n%%\n');
                        fprintf(fid,'StateVariableNames = DataStructure.StateVariableNames;\n');
                        fprintf(fid,'%%\n%% matrix with the errors from the mean predictions of the observed variables\n%%\n');
                        fprintf(fid,'PredictionErrors = DataStructure.PredictionErrors;\n');
                        fprintf(fid,'%%\n%% vector structure with quantiles from the predictive distribution\n%% the structure has %0.0f entries with fields "Quantile" and "percent"\n%% the first field is a matrix and the second a positive number between 0 and 100\n%%\n',length(Quantiles));
                        fprintf(fid,'Quantiles = DataStructure.Quantiles;\n');
                        if isempty(KernelX)==0;
                           fprintf(fid,'%%\n%% matrix with x-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                           fprintf(fid,'KernelX = DataStructure.KernelX;\n');
                           fprintf(fid,'%%\n%% matrix with y-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                           fprintf(fid,'KernelY = DataStructure.KernelX;\n');
                           KStr = 'KernelX (matrix with x-axis for kernel density estimates of marginal predictive distribution), KernelY (matrix with y-axis values for kernel density estimates of marginal predictive distribution), ';
                           KVal = 2;
                        else;
                           KStr = '';
                           KVal = 0;
                        end;
                        fprintf(fid,'%%\n%% vector with dates for the predictions\n%%\n');
                        fprintf(fid,'PredDateVector = DataStructure.PredDateVector;\n');
                        fprintf(fid,'%%\n%% observed variables\n%%\n');
                        fprintf(fid,'Y = DataStructure.Y;\n');
                        fprintf(fid,'%%\n%% vector with dates for the observed variables\n%%\n');
                        fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                        if isempty(PredEventData)==0;
                           fprintf(fid,'%%\n%% matrix with prediction event data. First column holds the\n%% number of true events, the second the number of times below the events, and the third the number of events\n%%\n');
                           fprintf(fid,'PredEventData = DataStructure.PredEventData;\n');
                           fprintf(fid,'%%\n%% matrix with observed event data. First column holds the\n%% number of true events, the second the number of times below the events, and the third the number of events\n%%\n');
                           fprintf(fid,'YObsEventData = DataStructure.YObsEventData;\n');
                           NumEntries = int2str(12+KVal);
                           ExtraEntry = 'PredEventData (matrix with the number of true prediction events, the number of events below the lower bound for the event, and the number of events tested in the columns), YObsEventData (matrix with the number of true events for prediction paths whose mean is the observed data, the number of events below the lower bound for the event, and the number of events tested in the columns), ';
                        else;
                           NumEntries = int2str(10+KVal);
                           ExtraEntry = '';
                        end;
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        %
                        txt = ['The predictive distributions have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains ' NumEntries ' entries: YNames (string matrix with the names of the observed variables), StateVariableNames (string matrix with the names of the state variables), MeanPrediction (matrix with the mean predictions), PredMean (matrix with the population mean of the predictions), PredMeanKsiStates (matrix with the population mean of the predictions of the state variables), PredictionErrors (matrix with errors for the mean predictions), Quantiles (vector structure with 2 fields: Quantile and percent), ' KStr 'PredDateVector (vector with dates for the predictions), Y (matrix) with the observed variables, ' ExtraEntry 'and DateVector (vector with dates for the observed variables). To access these data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','Predictive Distributions',400,550,CurrINI);
                     end;
                     if isempty(PredEventData)==0;
                        %
                        % write prediction event results to file
                        %
                        file = [DSGEModel.OutputDirectory '\PredictiveDist-' AnnualStr '-' num2str(MaxPH,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '-InitialValues.txt'];
                        [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,MaxPH);
                        PrintPredictionEvent(file,DSGEModel.VariableNames,PredEventData,YObsEventData,DSGEModel.PredictionEvent,[PredStartYear ':' PredStartPeriod '-' PredEndYear ':' PredEndPeriod],MaxPH,NumPredPaths,1,CurrINI);
                        %
                        % displays the file if it exists
                        %
                        if FileExist(file)==1;
                           TextGUI(file,['Prediction Events - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Initial Parameter Values',50,CurrINI,1,0);
                        end;
                     end;
                     %
                     % Open a dialog for displaying predictive distributions
                     %
                     PredictiveDistributionDLG('init',DSGEModel,CurrINI,MeanPrediction,Quantiles,PredData.KernelX,PredData.KernelY,'Initial Values','DSGE',AnnualStr);
                  end;
               elseif (mcode==1)&(kalmanstatus~=0);
                  txt = 'The state variables are not stationary at the initial values.';
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               elseif 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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'uncon_pred_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the predictive distr
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         HeaderStr = 'YADA - Bad MAT File';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         %
         % check if we should check transformations functions
         %
         if (isempty(ErrorStr)==1)&(gcbo==controls.predict.unconditional_transformed_postmode);
            DTStatus = VerifyDataTransformation(DSGEModel.VariableNames,DSGEModel.YTransformation,0);
            if DTStatus==1;
               [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
            else;
               ErrorStr = 'You haven''t specified all the necessary fields for computing transformations of the observed variables.';
               HeaderStr = 'Missing Transformation Information';
            end;
         end;
         %
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % check how many time periods to use for predictive distributions
            %
            [MaxPH,NumPredX] = CalcMaxPredictionHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,size(DSGEModel.PredictedX,2));
            %
            % matrix with exogenous variables
            %
            X = [];
            if DSGEModel.k>0;
               if NumPredX<MaxPH;
                  X = DSGEModel.X(:,LastPeriod+1:LastPeriod+(MaxPH-NumPredX));
               end;
               if NumPredX>0;
                  X = [X DSGEModel.PredictedX(:,1:NumPredX)];
               end;
            end;
            %
            % check if we should annualize or not
            %
            if gcbo==controls.predict.unconditional_original_postmode;
               TransData = 0;
               AnnualizeData = 0;
               AnnualStr = 'original';
            elseif gcbo==controls.predict.unconditional_annual_postmode;
               TransData = 0;
               AnnualizeData = 1;
               AnnualStr = 'annual';
            else;
               TransData = 1;
               AnnualizeData = 0;
               AnnualStr = 'transformed';
            end;
            %
            % determine how many prediction paths to use
            %
            NumPredPathsStr = get(controls.forecast.predpaths,'String');
            NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
            %
            % ask if we should conduct prediction event calculations
            %
            if (isfield(DSGEModel,'PredictionEvent')==0)|(isempty(DSGEModel.PredictionEvent)==1)|(size(DSGEModel.PredictionEvent,1)~=DSGEModel.n)|(size(DSGEModel.PredictionEvent,2)~=3);
               DSGEModel.PredictionEvent = [Inf*ones(DSGEModel.n,1) zeros(DSGEModel.n,1) ones(DSGEModel.n,1)];
            end;
            txt = 'Would you like YADA to calculate prediction event probabilities?';
            answer = Query(txt,'question',140,'Prediction Events',500,'no',CurrINI);
            if strcmp(lower(answer),'yes')==1;
               %
               % make sure that the prediction event length does not exceed the maximum prediction horizon
               %
               for i=1:DSGEModel.n;
                  if DSGEModel.PredictionEvent(i,3)>MaxPH;
                     DSGEModel.PredictionEvent(i,3) = MaxPH;
                  end;
               end;
               %
               % display a dialog for setting up an prediction event
               %
               [action,PredictionEvent] = PredictionEventDLG('init',DSGEModel.VariableNames,DSGEModel.PredictionEvent,MaxPH,CurrINI);
               if strcmp(lower(action),'ok')==1;
                  DSGEModel.PredictionEvent = PredictionEvent;
                  DSGEModel.RunPredictionEvent = 1;
               else;
                  DSGEModel.RunPredictionEvent = 0;
               end;
            else;
               DSGEModel.RunPredictionEvent = 0;
            end;
            %
            % we can now compute the predictive distribution for the endogenous variables
            % up to period MaxPh
            %
            if DSGEModel.RandomNumberValue==1;
               randn('state',0);
            else;
               randn('state',sum(100*clock));
            end;
            [PredPaths,PredData,PredEventData,YObsEventData] = DSGEPredictionPathsTheta(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,X,MaxPH,NumPredPaths,AnnualizeData,TransData,' At Posterior Mode');
            if isempty(PredPaths)==0;
               %
               % the computations went OK. Compute point estimates from predictive distribution and
               % quantiles
               %
               [MeanPrediction,Quantiles] = PredictionPathDistribution(PredPaths,DSGEModel.Percentiles);
               %
               % compute the mean error bias in percent
               %
               MeanErrorBias = max(max(abs((PredData.PredMean-MeanPrediction)./PredData.PredMean)));
               if DSGEModel.AdjustPredictionPaths==0;
                  %
                  % ask if the prediction distribution should be corrected
                  %
                  txt = ['The absolute mean error bias from using the simulated draws is ' num2str(MeanErrorBias,'%0.4f') ' percent relative to the theoretical mean. Would you like to adjust that predictive distribution such that it matches the theoretical mean?'];
                  answer = Query(txt,'question',140,'Mean Error Bias - Predictive Distributions',500,'yes',CurrINI);
               else;
                  answer = 'Yes';
               end;
               if strcmp(lower(answer),'yes')==1;
                  %
                  % adjust the quantiles to match
                  %
                  for i=1:length(Quantiles);
                     OlVal = Quantiles(i).Quantile;
                     Quantiles(i).Quantile = Quantiles(i).Quantile+(PredData.PredMean-MeanPrediction);
                  end;
                  MeanPrediction = PredData.PredMean;
               end;
               %
               % compute the forecast errors based on the mean predictions
               %
               PredictionErrors = CalculatePredictionErrors(MeanPrediction,AnnualizeData,TransData,'DSGE',DSGEModel);
               %
               % check if the user wants to save the data
               %
               txt = ['Would you like to save the predictive distributions for the ' AnnualStr ' data at posterior mode to file?'];
               answer = Query(txt,'question',140,'Save - Predictive Distributions',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod,PredDateVector] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,size(MeanPrediction,2));
                  file = [DSGEModel.OutputDirectory '\PredictiveDist-' AnnualStr '-' num2str(MaxPH,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '-PosteriorMode.mat'];
                  YNames = DSGEModel.VariableNames;
                  DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,PredEndYear,PredEndPeriod,DSGEModel.DataFrequency);
                  Y = DSGEModel.Y(:,FirstPeriod:min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                  if (length(DateVector)>size(Y,2))&(TransData==0);
                     DateVector = DateVector(1,1:size(Y,2));
                  end;
                  EstimationStartPeriod = DSGEModel.KalmanFirstObservation;
                  EstimationStartPeriodOrig = EstimationStartPeriod;
                  YOrig = Y;
                  DateVectorOrig = DateVector;
                  if AnnualizeData==1;
                     Y = Annualize(Y,DSGEModel.annual,DSGEModel.annualscale);
                     EstimationStartPeriod = max(1,EstimationStartPeriod-(length(DateVector)-size(Y,2)));
                     DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                  end;
                  if TransData==1;
                     [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
                     Y = YData';
                     if size(Y,2)==DSGEModel.T;
                        Y = Y(:,FirstPeriod:min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                     else;
                        T2 = size(Y,2);
                        if (FirstPeriod-(DSGEModel.T-T2))>=1;
                           Y = Y(:,FirstPeriod-(DSGEModel.T-T2):min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                        else;
                           Y = Y(:,1:min((LastPeriod+MaxPH),size(DSGEModel.Y,2))-(DSGEModel.T-T2));
                           DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                        end;
                     end;
                  end;
                  PredMeanKsiStates = PredData.xiStates;
                  PredMean = PredData.PredMean;
                  StateVariableNames = DSGEModel.StateVariableNames;
                  %
                  ShockPaths = PredData.Shocks;
                  HistState = PredData.HistState;
                  MeasureErrorPaths = PredData.MeasError;
                  ShockNames = PredData.ShockNames;
                  KernelX = PredData.KernelX;
                  KernelY = PredData.KernelY;
                  if isempty(PredEventData)==1;
                     save(file,'PredPaths','ShockPaths','MeasureErrorPaths','HistState','MeanPrediction','PredMean','PredMeanKsiStates','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','StateVariableNames','ShockNames','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig');
                  else;
                     save(file,'PredPaths','ShockPaths','MeasureErrorPaths','HistState','MeanPrediction','PredMean','PredMeanKsiStates','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','StateVariableNames','ShockNames','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig','PredEventData','YObsEventData');
                  end;
                  %
                  % create a matlab m-file to read the output.
                  %
                  mfile = [DSGEModel.OutputDirectory '\PD' AnnualStr num2str(MaxPH,'%0.0f') DSGEModel.SubEndYear DSGEModel.SubEndPeriod 'PostMode.m'];
                  fid = fopen(mfile,'wt');
                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                  fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                  fprintf(fid,'YNames = DataStructure.YNames;\n');
                  fprintf(fid,'%%\n%% string matrix with the names of the state variables variables\n%%\n');
                  fprintf(fid,'StateVariableNames = DataStructure.StateVariableNames;\n');
                  fprintf(fid,'%%\n%% string matrix with the names of the economic shocks\n%%\n');
                  fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                  fprintf(fid,'%%\n%%  3D matrix with all the prediction paths for the observed variables\n%%\n');
                  fprintf(fid,'PredPaths = DataStructure.PredPaths;\n');
                  fprintf(fid,'%%\n%% Underlying draws of the economic shocks for all paths\n%%\n');
                  fprintf(fid,'ShockPaths = DataStructure.ShockPaths;\n');
                  fprintf(fid,'%%\n%% Underlying draws of the neasurement errors for all paths\n%%\n');
                  fprintf(fid,'MeasureErrorPaths = DataStructure.MeasureErrorPaths;\n');
                  fprintf(fid,'%%\n%% Underlying draws of the state variables before the predictions\n%%\n');
                  fprintf(fid,'HistState = DataStructure.HistState;\n');
                  fprintf(fid,'%%\n%% matrix with the sample mean predictions of the observed variables\n%%\n');
                  fprintf(fid,'MeanPrediction = DataStructure.MeanPrediction;\n');
                  fprintf(fid,'%%\n%% matrix with the population mean of the predictions of the observed variables\n%%\n');
                  fprintf(fid,'PredMean = DataStructure.PredMean;\n');
                  fprintf(fid,'%%\n%% matrix with the population mean of the predictions of the state variables\n%%\n');
                  fprintf(fid,'PredMeanKsiStates = DataStructure.PredMeanKsiStates;\n');
                  fprintf(fid,'%%\n%% matrix with the errors from the mean predictions of the observed variables\n%%\n');
                  fprintf(fid,'PredictionErrors = DataStructure.PredictionErrors;\n');
                  fprintf(fid,'%%\n%% vector structure with quantiles from the predictive distribution\n%% the structure has %0.0f entries with fields "Quantile" and "percent"\n%% the first field is a matrix and the second a positive number between 0 and 100\n%%\n',length(Quantiles));
                  fprintf(fid,'Quantiles = DataStructure.Quantiles;\n');
                  if isempty(KernelX)==0;
                     fprintf(fid,'%%\n%% matrix with x-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                     fprintf(fid,'KernelX = DataStructure.KernelX;\n');
                     fprintf(fid,'%%\n%% matrix with y-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                     fprintf(fid,'KernelY = DataStructure.KernelY;\n');
                     KStr = 'KernelX (matrix with x-axis for kernel density estimates of marginal predictive distribution), KernelY (matrix with y-axis values for kernel density estimates of marginal predictive distribution), ';
                     KVal = 2;
                  else;
                     KStr = '';
                     KVal = 0;
                  end;
                  fprintf(fid,'%%\n%% vector with dates for the predictions\n%%\n');
                  fprintf(fid,'PredDateVector = DataStructure.PredDateVector;\n');
                  fprintf(fid,'%%\n%% observed variables\n%%\n');
                  fprintf(fid,'Y = DataStructure.Y;\n');
                  fprintf(fid,'%%\n%% vector with dates for the observed variables\n%%\n');
                  fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                  if isempty(PredEventData)==0;
                     fprintf(fid,'%%\n%% matrix with prediction event data. First column holds the\n%% number of true events, the second the number of times below the events, and the third the number of events\n%%\n');
                     fprintf(fid,'PredEventData = DataStructure.PredEventData;\n');
                     fprintf(fid,'%%\n%% matrix with observed event data. First column holds the\n%% number of true events, the second the number of times below the events, and the third the number of events\n%%\n');
                     fprintf(fid,'YObsEventData = DataStructure.YObsEventData;\n');
                     NumEntries = int2str(17+KVal);
                     ExtraEntry = 'PredEventData (matrix with the number of true prediction events, the number of events below the lower bound for the event, and the number of events tested in the columns), YObsEventData (matrix with the number of true events for prediction paths whose mean is the observed data, the number of events below the lower bound for the event, and the number of events tested in the columns), ';
                  else;
                     NumEntries = int2str(15+KVal);
                     ExtraEntry = '';
                  end;
                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                  %
                  % end the script file
                  %
                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                  fclose(fid);
                  %
                  txt = ['The predictive distributions have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains ' NumEntries ' entries: YNames (string matrix with the names of the observed variables), StateVariableNames (string matrix with the names of the state variables), ShockNames (string matrix with the names of the economic shocks), PredPaths (3D matrix with the prediction paths for the observed variables), ShockPaths (3D matrix with the underlying economic shocks for the prediction paths), MeasureErrorPaths (3D matrix with the underlying draws of the measurement errors for the prediction paths), HistState (matrix with the underlying draws of the state variables from the period prior to the predictions), MeanPrediction (matrix with the sample mean predictions), PredMean (matrix with the population mean predictions), PredMeanKsiStates (matrix with the population mean state predictions), PredictionErrors (matrix with errors for the mean predictions), Quantiles (vector structure with 2 fields: Quantile and percent), ' KStr 'PredDateVector (vector with dates for the predictions), Y (matrix) with the observed variables, ' ExtraEntry ', and DateVector (vector with dates for the observed variables). To access these data you may run the matlab script file "' GetFilename(mfile) '".'];
                  About(txt,'information','Predictive Distributions',700,550,CurrINI);
               end;
               if isempty(PredEventData)==0;
                  %
                  % write prediction event results to file
                  %
                  file = [DSGEModel.OutputDirectory '\PredictiveDist-' AnnualStr '-' num2str(MaxPH,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '-PosteriorMode.txt'];
                  [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,MaxPH);
                  PrintPredictionEvent(file,DSGEModel.VariableNames,PredEventData,YObsEventData,DSGEModel.PredictionEvent,[PredStartYear ':' PredStartPeriod '-' PredEndYear ':' PredEndPeriod],MaxPH,NumPredPaths,1,CurrINI);
                  %
                  % displays the file if it exists
                  %
                  if FileExist(file)==1;
                     TextGUI(file,['Prediction Events - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,0);
                  end;
               end;
               %
               % Open a dialog for displaying predictive distributions
               %
               PredictiveDistributionDLG('init',DSGEModel,CurrINI,MeanPrediction,Quantiles,PredData.KernelX,PredData.KernelY,'Posterior Mode','DSGE',AnnualStr);
            end;
         else;
            About(ErrorStr,'information',HeaderStr,120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'con_pred_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view graphs of the conditional predictive distributions of the observed variables before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Conditional Predictive Distributions at Initial Values',450,'no',CurrINI);
         end;
         %
         % check if we should check transformations functions
         %
         if gcbo==controls.predict.conditional_transformed_initialvalues;
            ErrorStr = '';
            DTStatus = VerifyDataTransformation(DSGEModel.VariableNames,DSGEModel.YTransformation,0);
            if DTStatus==1;
               [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
            else;
               ErrorStr = 'You haven''t specified all the necessary fields for computing transformations of the observed variables.';
               HeaderStr = 'Missing Transformation Information';
            end;
            if isempty(ErrorStr)==0;
               About(ErrorStr,'information',HeaderStr,200,500,CurrINI);
               answer = 'no';
            end;
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
               %
               % check how many time periods to use for predictive distributions
               %
               [MaxPH,NumPredX] = CalcMaxPredictionHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,size(DSGEModel.PredictedX,2));
               %
               % matrix with exogenous variables
               %
               X = [];
               if DSGEModel.k>0;
                  if NumPredX<MaxPH;
                     X = DSGEModel.X(:,LastPeriod+1:LastPeriod+(MaxPH-NumPredX));
                  end;
                  if NumPredX>0;
                     X = [X DSGEModel.PredictedX(:,1:NumPredX)];
                  end;
               end;
               %
               % check the length of the conditioning sample
               %
               [status,NumPeriods] = CheckConditioningData(DSGEModel);
               %
               % check if we should adjust the X matrix
               %
               if MaxPH<NumPeriods;
                  NumPeriods = MaxPH;
               end;
               %
               % collect the conditional variables and the selected conditioning sample
               %
               Z = DSGEModel.Z(DSGEModel.ConditionalVariables,LastPeriod+1:LastPeriod+NumPeriods);
               U = DSGEModel.U(DSGEModel.ConditionalVariables,LastPeriod-NumPeriods+1:LastPeriod);
               %
               % check if we should annualize or not
               %
               if gcbo==controls.predict.conditional_original_initialvalues;
                  TransData = 0;
                  AnnualizeData = 0;
                  AnnualStr = 'original';
               elseif gcbo==controls.predict.conditional_annual_initialvalues;
                  TransData = 0;
                  AnnualizeData = 1;
                  AnnualStr = 'annual';
               else;
                  TransData = 1;
                  AnnualizeData = 0;
                  AnnualStr = 'transformed';
               end;
               %
               % determine how many prediction paths to use
               %
               NumPredPathsStr = get(controls.forecast.predpaths,'String');
               NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
               %
               % ask if we should conduct prediction event calculations
               %
               if (isfield(DSGEModel,'PredictionEvent')==0)|(isempty(DSGEModel.PredictionEvent)==1)|(size(DSGEModel.PredictionEvent,1)~=DSGEModel.n)|(size(DSGEModel.PredictionEvent,2)~=3);
                  DSGEModel.PredictionEvent = [Inf*ones(DSGEModel.n,1) zeros(DSGEModel.n,1) ones(DSGEModel.n,1)];
               end;
               txt = 'Would you like YADA to calculate prediction event probabilities?';
               answer = Query(txt,'question',140,'Prediction Events',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  %
                  % make sure that the prediction event length does not exceed the maximum prediction horizon
                  %
                  for i=1:DSGEModel.n;
                     if DSGEModel.PredictionEvent(i,3)>MaxPH;
                        DSGEModel.PredictionEvent(i,3) = MaxPH;
                     end;
                  end;
                  %
                  % display a dialog for setting up an prediction event
                  %
                  [action,PredictionEvent] = PredictionEventDLG('init',DSGEModel.VariableNames,DSGEModel.PredictionEvent,MaxPH,CurrINI);
                  if strcmp(lower(action),'ok')==1;
                     DSGEModel.PredictionEvent = PredictionEvent;
                     DSGEModel.RunPredictionEvent = 1;
                  else;
                     DSGEModel.RunPredictionEvent = 0;
                  end;
               else;
                  DSGEModel.RunPredictionEvent = 0;
               end;
               %
               % we can now compute the predictive distribution for the endogenous variables
               % up to period MaxPh
               %
               if DSGEModel.RandomNumberValue==1;
                  randn('state',0);
               else;
                  randn('state',sum(100*clock));
               end;
               if DSGEModel.ShockControlMethod==1;
                  [PredPaths,PredData,PredEventData,YObsEventData,MultiModestyStat,UniModestyStat,MeanUniModestyLZ,mcode,kalmanstatus] = DSGECondPredictionPathsTheta(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,X,Z,U,MaxPH,NumPredPaths,AnnualizeData,TransData,' At Initial Values');
               else;
                  [PredPaths,PredData,PredEventData,YObsEventData,MultiModestyStat,UniModestyStat,MeanUniModestyLZ,mcode,kalmanstatus] = DSGECondPredictionPathsThetaWZ(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,X,Z,U,MaxPH,NumPredPaths,AnnualizeData,TransData,' At Initial Values');
               end;
               %
               if (mcode==1)&(kalmanstatus==0);
                  %
                  % we're hopefully OK
                  %
                  if isempty(PredPaths)==0;
                     %
                     % the computations went OK. Compute point estimates from predictive distribution and
                     % quantiles
                     %
                     [MeanPrediction,Quantiles] = PredictionPathDistribution(PredPaths,DSGEModel.Percentiles);
                     %
                     % compute the mean error bias in percent
                     %
                     MeanErrorBias = max(max(abs((PredData.PredMean-MeanPrediction)./PredData.PredMean)));
                     if DSGEModel.AdjustPredictionPaths==0;
                        %
                        % ask if the prediction distribution should be corrected
                        %
                        txt = ['The absolute mean error bias from using the simulated draws is ' num2str(MeanErrorBias,'%0.4f') ' percent relative to the theoretical mean. Would you like to adjust that predictive distribution such that it matches the theoretical mean?'];
                        answer = Query(txt,'question',140,'Mean Error Bias - Conditional Predictive Distributions',500,'yes',CurrINI);
                     else;
                        answer = 'Yes';
                     end;
                     AdjustMean = 0;
                     if strcmp(lower(answer),'yes')==1;
                        %
                        % adjust the quantiles to match
                        %
                        for i=1:length(Quantiles);
                           OlVal = Quantiles(i).Quantile;
                           Quantiles(i).Quantile = Quantiles(i).Quantile+(PredData.PredMean-MeanPrediction);
                        end;
                        MeanPrediction = PredData.PredMean;
                        PredData.MeanPredPath = PredData.OrigPredMean;
                        AdjustMean = 1;
                     end;
                     %
                     % compute the forecast errors based on the mean predictions
                     %
                     PredictionErrors = CalculatePredictionErrors(MeanPrediction,AnnualizeData,TransData,'DSGE',DSGEModel);
                     %
                     % check if we have modesty statistics to deal with
                     %
                     if AnnualizeData==0;
                        %
                        % check how often we have a greater value of column 1 than column 2 in MultiModestyStat
                        %
                        MultiPValue = sum(MultiModestyStat(:,1)<=MultiModestyStat(:,2))/NumPredPaths;
                        MeanMultiModesty = (1/NumPredPaths)*[sum(MultiModestyStat(:,1)) sum(MultiModestyStat(:,2))];
                        MeanUniModesty = zeros(1,DSGEModel.n);
                        for i=1:DSGEModel.n;
                           MeanUniModesty(1,i) = (1/NumPredPaths)*sum(UniModestyStat(:,i));
                        end;
                        if exist('YADAchi2cdf')==2;
                           ChiSqPValue = 1-YADAchi2cdf(MeanMultiModesty(1),DSGEModel.n);
                        else;
                           if exist('chi2cdf')==2;
                              ChiSqPValue = 1-chi2cdf(MeanMultiModesty(1),DSGEModel.n);
                           else;
                              ChiSqPValue = 1-YADACheapchi2cdf(MeanMultiModesty(1),DSGEModel.n);
                           end;
                        end;
                        PrintDSGEModestyStatistics(DSGEModel,CurrINI,'Initial Values',MaxPH,NumPeriods,1,NumPredPaths,MultiPValue,MeanMultiModesty,MeanUniModesty,MeanUniModestyLZ,PredData.etaShocks,PredData.ShockNames);
                     else;
                        MultiPValue = [];
                        MeanMultiModesty = [];
                        MeanUniModesty = [];
                        ChiSqPValue = [];
                     end;
                     %
                     % check if the user wants to save the data
                     %
                     txt = ['Would you like to save the conditional predictive distributions for the ' AnnualStr ' data at initial values to file?'];
                     answer = Query(txt,'question',140,'Save - Conditional Predictive Distributions',500,'no',CurrINI);
                     drawnow;
                     if strcmp(lower(answer),'yes')==1;
                        [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod,PredDateVector] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,size(MeanPrediction,2));
                        file = [DSGEModel.OutputDirectory '\CondPredictiveDist-' int2str(DSGEModel.ShockControlMethod) '-' AnnualStr '-' num2str(MaxPH,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod 'InitialValues.mat'];
                        YNames = DSGEModel.VariableNames;
                        PredMean = PredData.PredMean;
                        DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,PredEndYear,PredEndPeriod,DSGEModel.DataFrequency);
                        Y = DSGEModel.Y(:,FirstPeriod:min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                        if (length(DateVector)>size(Y,2))&(TransData==1);
                           DateVector = DateVector(1,1:size(Y,2));
                        end;
                        %
                        % check if we should compute the shock scenarios for the predictions
                        %
                        if FileExist([pwd '\addons\sss\DSGEPredictionShockScenarios.m'])==1;
                           if AdjustMean==1;
                              ShockScenarioResults = PredData.ShockScenarioResults;
                              [B0_h,KeepShocks] = RemoveRedundantColumns(PredData.B0);
                              ShockNames = DSGEModel.StateShockNames(KeepShocks,:);
                              wtT = zeros(DSGEModel.n,MaxPH);
                           else;
                              if isempty(DSGEModel.X)==0;
                                 [ShockScenarioResults,ShockNames,wtT,SmoothShocks] = DSGEPredictionShockScenarios(PredData.A,PredData.H,PredData.R,PredData.F,PredData.B0,DSGEModel,DSGEModel.Y(:,FirstPeriod:LastPeriod),PredData.MeanPredPath,DSGEModel.X(:,FirstPeriod:LastPeriod),X,AnnualizeData);
                              else;
                                 [ShockScenarioResults,ShockNames,wtT,SmoothShocks] = DSGEPredictionShockScenarios(PredData.A,PredData.H,PredData.R,PredData.F,PredData.B0,DSGEModel,DSGEModel.Y(:,FirstPeriod:LastPeriod),PredData.MeanPredPath,[],X,AnnualizeData);
                              end;
                           end;
                        else;
                           ShockScenarioResults = [];
                           ShockNames = '';
                           wtT = [];
                           SmoothShocks = [];
                        end;
                        %
                        if (FileExist([pwd '\addons\sss\DSGEPredictionShockScenarios.m'])==1)&(NumPredX<MaxPH);
                           %
                           % matrices with observed data and exogenous variables over the prediction period.
                           %
                           if isempty(DSGEModel.X)==0;
                              DataX = DSGEModel.X(:,LastPeriod+1:LastPeriod+(MaxPH-NumPredX));
                           else;
                              DataX = [];
                           end;
                           DataY = DSGEModel.Y(:,LastPeriod+1:LastPeriod+(MaxPH-NumPredX));
                           %
                           % check if we should compute shock scenarios for the observed data over the prediction sample
                           %
                           if isempty(DSGEModel.X)==0;
                              [DataShockScenarioResults,DataShockNames,DatawtT,SmoothShocks,Yinit] = DSGEPredictionShockScenarios(PredData.A,PredData.H,PredData.R,PredData.F,PredData.B0,DSGEModel,DSGEModel.Y(:,FirstPeriod:LastPeriod),DataY,DSGEModel.X(:,FirstPeriod:LastPeriod),DataX,AnnualizeData);
                           else;
                              [DataShockScenarioResults,DataShockNames,DatawtT,SmoothShocks,Yinit] = DSGEPredictionShockScenarios(PredData.A,PredData.H,PredData.R,PredData.F,PredData.B0,DSGEModel,DSGEModel.Y(:,FirstPeriod:LastPeriod),DataY,[],DataX,AnnualizeData);
                           end;
                           if AnnualizeData==1;
                              DataY = Annualize([Yinit DataY],DSGEModel.annual,DSGEModel.annualscale);
                           end;
                        else;
                           DataY = [];
                           DataShockScenarioResults = [];
                           SmoothShocks = [];
                           DatawtT = [];
                        end;
                        %
                        ConditionalShockNames = DSGEModel.StateShockNames(DSGEModel.ConditionalShocks,:);
                        EstimationStartPeriod = DSGEModel.KalmanFirstObservation;
                        EstimationStartPeriodOrig = EstimationStartPeriod;
                        YOrig = Y;
                        DateVectorOrig = DateVector;
                        PredMeanKsiStates = PredData.xiStates;
                        PredMeanEtaShocks = PredData.etaShocks;
                        KsiStates = PredData.KsitT;
                        StateVariableNames = DSGEModel.StateVariableNames;
                        KernelX = PredData.KernelX;
                        KernelY = PredData.KernelY;
                        if AnnualizeData==1;
                           Y = Annualize(Y,DSGEModel.annual,DSGEModel.annualscale);
                           EstimationStartPeriod = max(1,EstimationStartPeriod-(length(DateVector)-size(Y,2)));
                           DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                        end;
                        %
                        if TransData==1;
                           [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
                           Y = YData';
                           if size(Y,2)==DSGEModel.T;
                              Y = Y(:,FirstPeriod:min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                           else;
                              T2 = size(Y,2);
                              if (FirstPeriod-(DSGEModel.T-T2))>=1;
                                 Y = Y(:,FirstPeriod-(DSGEModel.T-T2):min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                              else;
                                 Y = Y(:,1:min((LastPeriod+MaxPH),size(DSGEModel.Y,2))-(DSGEModel.T-T2));
                                 DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                              end;
                           end;
                        end;
                        %
                        if FileExist([pwd '\addons\sss\DSGEPredictionShockScenarios.m'])==1;
                           if isempty(PredEventData)==1;
                              save(file,'MeanPrediction','PredMean','PredMeanKsiStates','PredMeanEtaShocks','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','KsiStates','StateVariableNames','ShockScenarioResults','ShockNames','wtT','DataY','DataShockScenarioResults','DatawtT','ConditionalShockNames','MeanMultiModesty','MultiPValue','ChiSqPValue','MeanUniModesty','MeanUniModestyLZ','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig');
                           else;
                              save(file,'MeanPrediction','PredMean','PredMeanKsiStates','PredMeanEtaShocks','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','KsiStates','StateVariableNames','ShockScenarioResults','ShockNames','wtT','DataY','DataShockScenarioResults','DatawtT','ConditionalShockNames','MeanMultiModesty','MultiPValue','ChiSqPValue','MeanUniModesty','MeanUniModestyLZ','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig','PredEventData','YObsEventData');
                           end;
                        else;
                           if isempty(PredEventData)==1;
                              save(file,'MeanPrediction','PredMean','PredMeanKsiStates','PredMeanEtaShocks','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','KsiStates','StateVariableNames','MeanMultiModesty','MultiPValue','ChiSqPValue','MeanUniModesty','MeanUniModestyLZ','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig');
                           else;
                              save(file,'MeanPrediction','PredMean','PredMeanKsiStates','PredMeanEtaShocks','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','KsiStates','StateVariableNames','MeanMultiModesty','MultiPValue','ChiSqPValue','MeanUniModesty','MeanUniModestyLZ','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig','PredEventData','YObsEventData');
                           end;
                        end;
                        %
                        % create a matlab m-file to read the output.
                        %
                        mfile = [DSGEModel.OutputDirectory '\CondPD' int2str(DSGEModel.ShockControlMethod) AnnualStr num2str(MaxPH,'%0.0f') DSGEModel.SubEndYear DSGEModel.SubEndPeriod 'InitVal.m'];
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                        fprintf(fid,'YNames = DataStructure.YNames;\n');
                        fprintf(fid,'%%\n%% string matrix with the names of the state variables\n%%\n');
                        fprintf(fid,'StateVariableNames = DataStructure.StateVariableNames;\n');
                        if AdjustMean==0;
                           fprintf(fid,'%%\n%% matrix with the mean of the simulated predictions of the observed variables\n%%\n');
                        else;
                           fprintf(fid,'%%\n%% matrix with the corrected mean of the simulated predictions of the observed variables\n%%\n');
                        end;
                        fprintf(fid,'MeanPrediction = DataStructure.MeanPrediction;\n');
                        fprintf(fid,'%%\n%% matrix with the population mean of the predictions of the observed variables\n%%\n');
                        fprintf(fid,'PredMean = DataStructure.PredMean;\n');
                        fprintf(fid,'%%\n%% matrix with the population mean of the predictions of the state variables\n%%\n');
                        fprintf(fid,'PredMeanKsiStates = DataStructure.PredMeanKsiStates;\n');
                        fprintf(fid,'%%\n%% matrix with the population mean of the predictions of the economic shocks\n%%\n');
                        fprintf(fid,'PredMeanEtaShocks = DataStructure.PredMeanEtaShocks;\n');
                        fprintf(fid,'%%\n%% matrix with the errors from the mean predictions of the observed variables\n%%\n');
                        fprintf(fid,'PredictionErrors = DataStructure.PredictionErrors;\n');
                        fprintf(fid,'%%\n%% vector structure with quantiles from the predictive distribution\n%% the structure has %0.0f entries with fields "Quantile" and "percent"\n%% the first field is a matrix and the second a positive number between 0 and 100\n%%\n',length(Quantiles));
                        fprintf(fid,'Quantiles = DataStructure.Quantiles;\n');
                        if isempty(KernelX)==0;
                           fprintf(fid,'%%\n%% matrix with x-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                           fprintf(fid,'KernelX = DataStructure.KernelX;\n');
                           fprintf(fid,'%%\n%% matrix with y-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                           fprintf(fid,'KernelY = DataStructure.KernelY;\n');
                           KStr = 'KernelX (matrix with x-axis for kernel density estimates of marginal predictive distribution), KernelY (matrix with y-axis values for kernel density estimates of marginal predictive distribution), ';
                           KVal = 2;
                        else;
                           KStr = '';
                           KVal = 0;
                        end;
                        fprintf(fid,'%%\n%% vector with dates for the predictions\n%%\n');
                        fprintf(fid,'PredDateVector = DataStructure.PredDateVector;\n');
                        fprintf(fid,'%%\n%% observed variables\n%%\n');
                        fprintf(fid,'Y = DataStructure.Y;\n');
                        fprintf(fid,'%%\n%% matrix with smooth estimates of the state variables\n%%\n');
                        fprintf(fid,'KsiStates = DataStructure.KsiStates;\n');
                        fprintf(fid,'%%\n%% vector with dates for the observed variables\n%%\n');
                        fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                        if FileExist([pwd '\addons\sss\DSGEPredictionShockScenarios.m'])==1;
                           fprintf(fid,'%%\n%% Names for the economic shocks\n%%\n');
                           fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                           fprintf(fid,'%%\n%% 3D matrix with shock scenarios over the prediction sample\n%%\n');
                           fprintf(fid,'ShockScenarioResults = DataStructure.ShockScenarioResults;\n');
                           fprintf(fid,'%%\n%% estimates of the measurement errors over the prediction sample\n%%\n');
                           fprintf(fid,'wtT = DataStructure.wtT;\n');
                           fprintf(fid,'%%\n%% string matrix with names of the economic shocks that are manipulated\n%% to achieve the conditioning assumptions\n%%\n');
                           fprintf(fid,'ConditionalShockNames = DataStructure.ConditionalShockNames;\n');
                           fprintf(fid,'%%\n%% The observed variables for the prediction sample\n%%\n');
                           fprintf(fid,'DataY = DataStructure.DataY;\n');
                           fprintf(fid,'%%\n%% 3D matrix with shock scenarios over the prediction sample for the observed data\n%%\n');
                           fprintf(fid,'DataShockScenarioResults = DataStructure.DataShockScenarioResults;\n');
                           fprintf(fid,'%%\n%% estimates of the measurement errors over the prediction sample using the observed data\n%%\n');
                           fprintf(fid,'DatawtT = DataStructure.DatawtT;\n');
                           ShockStr = 'ShockNames (string matrix with the names for the economic shocks), ShockScenarioResults (3D matrix of dimension nxhxq with the shocks scenarios for the mean predictions of the observed variables), wtT (matrix with estimated measurement errors over the prediction sample for the mean predictions of the observed variables), ConditionalShockNames (string matrix with names for the shocks used to achieve the conditioning assumptions), DataY (matrix with the observed data for the prediction sample), DataShockScenarioResults (3D matrix with shock scenarios for the observed variables over the prediction sample), DatawtT (estimates of the measurement errors over the prediction sample for the observed variables), ';
                        else;
                           ShockStr = '';
                        end;
                        if isempty(PredEventData)==0;
                           fprintf(fid,'%%\n%% matrix with prediction event data. First column holds the\n%% number of true events, the second the number of times below the events, and the third the number of events\n%%\n');
                           fprintf(fid,'PredEventData = DataStructure.PredEventData;\n');
                           fprintf(fid,'%%\n%% matrix with observed event data. First column holds the\n%% number of true events, the second the number of times below the events, and the third the number of events\n%%\n');
                           fprintf(fid,'YObsEventData = DataStructure.YObsEventData;\n');
                           NumEntries = int2str(21+KVal);
                           ExtraEntry = 'PredEventData (matrix with the number of true events, the number of events below the lower bound for the event, and the number of events tested in the columns), YObsEventData (matrix with the number of true events for prediction paths whose mean is the observed data, the number of events below the lower bound for the event, and the number of events tested in the columns), ';
                        else;
                           NumEntries = int2str(19+KVal);
                           ExtraEntry = '';
                        end;
                        if FileExist([pwd '\addons\sss\DSGEPredictionShockScenarios.m'])==0;
                           NumEntries = num2str(str2num(NumEntries)-7,'%0.0f');
                        end;
                        if AnnualizeData==0;
                           fprintf(fid,'%%\n%% vector with the mean of the multivariate modesty statistic and its reference statistic\n%%\n');
                           fprintf(fid,'MeanMultiModesty = DataStructure.MeanMultiModesty;\n');
                           fprintf(fid,'%%\n%% tail probability based on the reference statistic\n%%\n');
                           fprintf(fid,'MultiPValue = DataStructure.MultiPValue;\n');
                           fprintf(fid,'%%\n%% tail probability based on the chi-square distribution\n%%\n');
                           fprintf(fid,'ChiSqPValue = DataStructure.ChiSqPValue;\n');
                           fprintf(fid,'%%\n%% Adolfson, Laséen, Lindé and Villani univariate modesty statistic\n%%\n');
                           fprintf(fid,'MeanUniModesty = DataStructure.MeanUniModesty;\n');
                           fprintf(fid,'%%\n%% Leeper and Zha univariate modesty statistic\n%%\n');
                           fprintf(fid,'MeanUniModestyLZ = DataStructure.MeanUniModestyLZ;\n');
                           NumEntries = num2str(str2num(NumEntries)+5,'%0.0f');
                           ExtraEntry = [ExtraEntry 'MeanMultiModesty (1x2 vector with the mean of the multivariate modesty statistic and the mean of the multivariate reference modesty statistic), MultiPValue (scalar with the tail probability of the modesty statistic), ChiSqPValue (scalar with the tail probability of the modesty statistic using the chi-square distribution), MeanUniModesty (vector with the univariate modesty statistic from ALLV), MeanUniModestyLZ (vector with the univariate Leeper-Zha modesty statistic), '];
                        end;
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        %
                        txt = ['The conditional predictive distributions have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains ' NumEntries ' entries: YNames (string matrix with the names of the observed variables), MeanPrediction (matrix with the selected mean predictions), PredMean (matrix with the population mean predictions), PredMeanKsiStates (matrix with the population mean of the predictions of the state variables), PredMeanEtaShocks (matrix with the population mean of the predictions of the economic shocks), PredictionErrors (matrix with errors for the mean predictions), Quantiles (vector structure with 2 fields: Quantile and percent), ' KStr 'PredDateVector (vector with dates for the predictions), Y (matrix with the observed variables), KsiStates (matrix with smooth estimates of the state variables), StateVariableNames (string matrix with the names of the state variables), ' ShockStr ExtraEntry 'and DateVector (vector with dates for the observed variables). To access these data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','Conditional Predictive Distributions',400,550,CurrINI);
                     end;
                     if isempty(PredEventData)==0;
                        %
                        % write prediction event results to file
                        %
                        file = [DSGEModel.OutputDirectory '\CondPredictiveDist-' int2str(DSGEModel.ShockControlMethod) '-' AnnualStr '-' num2str(MaxPH,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '-InitialValues.txt'];
                        [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,MaxPH);
                        PrintPredictionEvent(file,DSGEModel.VariableNames,PredEventData,YObsEventData,DSGEModel.PredictionEvent,[PredStartYear ':' PredStartPeriod '-' PredEndYear ':' PredEndPeriod],MaxPH,NumPredPaths,1,CurrINI);
                        %
                        % displays the file if it exists
                        %
                        if FileExist(file)==1;
                           TextGUI(file,['Prediction Events - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Initial Parameter Values',50,CurrINI,1,0);
                        end;
                     end;
                     %
                     % Open a dialog for displaying predictive distributions
                     %
                     CondPredictiveDistributionDLG('init',DSGEModel,CurrINI,MeanPrediction,Quantiles,PredData.KernelX,PredData.KernelY,'Initial Values','DSGE',AnnualStr);
                  end;
               elseif (mcode==1)&(kalmanstatus~=0);
                  txt = 'The state variables are not stationary at the initial values.';
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               elseif 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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'con_pred_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the predictive distr
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         HeaderStr = 'YADA - Bad MAT File';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         %
         % check if we should check transformations functions
         %
         if (isempty(ErrorStr)==1)&(gcbo==controls.predict.conditional_transformed_postmode);
            DTStatus = VerifyDataTransformation(DSGEModel.VariableNames,DSGEModel.YTransformation,0);
            if DTStatus==1;
               [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
            else;
               ErrorStr = 'You haven''t specified all the necessary fields for computing transformations of the observed variables.';
               HeaderStr = 'Missing Transformation Information';
            end;
         end;
         %
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % check how many time periods to use for predictive distributions
            %
            [MaxPH,NumPredX] = CalcMaxPredictionHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,size(DSGEModel.PredictedX,2));
            %
            % matrix with exogenous variables
            %
            X = [];
            if DSGEModel.k>0;
               if NumPredX<MaxPH;
                  X = DSGEModel.X(:,LastPeriod+1:LastPeriod+(MaxPH-NumPredX));
               end;
               if NumPredX>0;
                  X = [X DSGEModel.PredictedX(:,1:NumPredX)];
               end;
            end;
            %
            % check the length of the conditioning sample
            %
            [status,NumPeriods] = CheckConditioningData(DSGEModel);
            %
            % check if we should adjust the X matrix
            %
            if MaxPH<NumPeriods;
               NumPeriods = MaxPH;
            end;
            %
            % collect the conditional variables and the selected conditioning sample
            %
            Z = DSGEModel.Z(DSGEModel.ConditionalVariables,LastPeriod+1:LastPeriod+NumPeriods);
            U = DSGEModel.U(DSGEModel.ConditionalVariables,LastPeriod-NumPeriods+1:LastPeriod);
            %
            % check if we should annualize or not
            %
            if gcbo==controls.predict.conditional_original_postmode;
               TransData = 0;
               AnnualizeData = 0;
               AnnualStr = 'original';
            elseif gcbo==controls.predict.conditional_annual_postmode;
               TransData = 0;
               AnnualizeData = 1;
               AnnualStr = 'annual';
            else;
               TransData = 1;
               AnnualizeData = 0;
               AnnualStr = 'transformed';
            end;
            %
            % determine how many prediction paths to use
            %
            NumPredPathsStr = get(controls.forecast.predpaths,'String');
            NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
            %
            % ask if we should conduct prediction event calculations
            %
            if (isfield(DSGEModel,'PredictionEvent')==0)|(isempty(DSGEModel.PredictionEvent)==1)|(size(DSGEModel.PredictionEvent,1)~=DSGEModel.n)|(size(DSGEModel.PredictionEvent,2)~=3);
               DSGEModel.PredictionEvent = [Inf*ones(DSGEModel.n,1) zeros(DSGEModel.n,1) ones(DSGEModel.n,1)];
            end;
            txt = 'Would you like YADA to calculate prediction event probabilities?';
            answer = Query(txt,'question',140,'Prediction Events',500,'no',CurrINI);
            if strcmp(lower(answer),'yes')==1;
               %
               % make sure that the prediction event length does not exceed the maximum prediction horizon
               %
               for i=1:DSGEModel.n;
                  if DSGEModel.PredictionEvent(i,3)>MaxPH;
                     DSGEModel.PredictionEvent(i,3) = MaxPH;
                  end;
               end;
               %
               % display a dialog for setting up an prediction event
               %
               [action,PredictionEvent] = PredictionEventDLG('init',DSGEModel.VariableNames,DSGEModel.PredictionEvent,MaxPH,CurrINI);
               if strcmp(lower(action),'ok')==1;
                  DSGEModel.PredictionEvent = PredictionEvent;
                  DSGEModel.RunPredictionEvent = 1;
               else;
                  DSGEModel.RunPredictionEvent = 0;
               end;
            else;
               DSGEModel.RunPredictionEvent = 0;
            end;
            %
            % we can now compute the predictive distribution for the endogenous variables
            % up to period MaxPh
            %
            if DSGEModel.RandomNumberValue==1;
               randn('state',0);
            else;
               randn('state',sum(100*clock));
            end;
            %
            if DSGEModel.ShockControlMethod==1;
               [PredPaths,PredData,PredEventData,YObsEventData,MultiModestyStat,UniModestyStat,MeanUniModestyLZ] = DSGECondPredictionPathsTheta(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,X,Z,U,MaxPH,NumPredPaths,AnnualizeData,TransData,' At Posterior Mode');
            else;
               [PredPaths,PredData,PredEventData,YObsEventData,MultiModestyStat,UniModestyStat,MeanUniModestyLZ] = DSGECondPredictionPathsThetaWZ(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,X,Z,U,MaxPH,NumPredPaths,AnnualizeData,TransData,' At Posterior Mode');
            end;
            if isempty(PredPaths)==0;
               %
               % the computations went OK. Compute point estimates from predictive distribution and
               % quantiles
               %
               [MeanPrediction,Quantiles] = PredictionPathDistribution(PredPaths,DSGEModel.Percentiles);
               %
               % compute the mean error bias in percent
               %
               MeanErrorBias = max(max(abs((PredData.PredMean-MeanPrediction)./PredData.PredMean)));
               if DSGEModel.AdjustPredictionPaths==0;
                  %
                  % ask if the prediction distribution should be corrected
                  %
                  txt = ['The absolute mean error bias from using the simulated draws is ' num2str(MeanErrorBias,'%0.4f') ' percent relative to the theoretical mean. Would you like to adjust that predictive distribution such that it matches the theoretical mean?'];
                  answer = Query(txt,'question',140,'Mean Error Bias - Conditional Predictive Distributions',500,'yes',CurrINI);
               else;
                  answer = 'Yes';
               end;
               AdjustMean = 0;
               if strcmp(lower(answer),'yes')==1;
                  %
                  % adjust the quantiles to match
                  %
                  for i=1:length(Quantiles);
                     OlVal = Quantiles(i).Quantile;
                     Quantiles(i).Quantile = Quantiles(i).Quantile+(PredData.PredMean-MeanPrediction);
                  end;
                  MeanPrediction = PredData.PredMean;
                  PredData.MeanPredPath = PredData.OrigPredMean;
                  AdjustMean = 1;
               end;
               %
               % compute the forecast errors based on the mean predictions
               %
               PredictionErrors = CalculatePredictionErrors(MeanPrediction,AnnualizeData,TransData,'DSGE',DSGEModel);
               %
               % check if we have modesty statistics to deal with
               %
               if AnnualizeData==0;
                  %
                  % check how often we have a greater value of column 1 than column 2 in MultiModestyStat
                  %
                  MultiPValue = sum(MultiModestyStat(:,1)<=MultiModestyStat(:,2))/NumPredPaths;
                  MeanMultiModesty = (1/NumPredPaths)*[sum(MultiModestyStat(:,1)) sum(MultiModestyStat(:,2))];
                  MeanUniModesty = zeros(1,DSGEModel.n);
                  for i=1:DSGEModel.n;
                     MeanUniModesty(1,i) = (1/NumPredPaths)*sum(UniModestyStat(:,i));
                  end;
                  if exist('YADAchi2cdf')==2;
                     ChiSqPValue = 1-YADAchi2cdf(MeanMultiModesty(1),DSGEModel.n);
                  else;
                     if exist('chi2cdf')==2;
                        ChiSqPValue = 1-chi2cdf(MeanMultiModesty(1),DSGEModel.n);
                     else;
                        ChiSqPValue = 1-YADACheapchi2cdf(MeanMultiModesty(1),DSGEModel.n);
                     end;
                  end;
                  PrintDSGEModestyStatistics(DSGEModel,CurrINI,'Posterior Mode',MaxPH,NumPeriods,1,NumPredPaths,MultiPValue,MeanMultiModesty,MeanUniModesty,MeanUniModestyLZ,PredData.etaShocks,PredData.ShockNames);
               else;
                  MultiPValue = [];
                  MeanMultiModesty = [];
                  MeanUniModesty = [];
                  ChiSqPValue = [];
               end;
               %
               % check if the user wants to save the data
               %
               txt = ['Would you like to save the conditional predictive distributions for the ' AnnualStr ' data at posterior mode to file?'];
               answer = Query(txt,'question',140,'Save - Conditional Predictive Distributions',500,'no',CurrINI);
               drawnow;
               if strcmp(lower(answer),'yes')==1;
                  [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod,PredDateVector] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,size(MeanPrediction,2));
                  file = [DSGEModel.OutputDirectory '\CondPredictiveDist-' int2str(DSGEModel.ShockControlMethod) '-' AnnualStr '-' num2str(MaxPH,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '-PosteriorMode.mat'];
                  YNames = DSGEModel.VariableNames;
                  PredMean = PredData.PredMean;
                  DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,PredEndYear,PredEndPeriod,DSGEModel.DataFrequency);
                  Y = DSGEModel.Y(:,FirstPeriod:min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                  if (length(DateVector)>size(Y,2))&(TransData==0);
                     DateVector = DateVector(1,1:size(Y,2));
                  end;
                  ShockDateVector = DateVector(1,DSGEModel.KalmanFirstObservation:length(DateVector));
                  if FirstPeriod>=2;
                     YInitial = DSGEModel.Y(:,1:FirstPeriod-1);
                  else;
                     YInitial = [];
                  end;
                  %
                  % check if we should compute the shock scenarios for the predictions
                  %
                  if FileExist([pwd '\addons\sss\DSGEPredictionShockScenarios.m'])==1;
                     if AdjustMean==1;
                        ShockScenarioResults = PredData.ShockScenarioResults;
                        [B0_h,KeepShocks] = RemoveRedundantColumns(PredData.B0);
                        ShockNames = DSGEModel.StateShockNames(KeepShocks,:);
                        wtT = zeros(DSGEModel.n,MaxPH);
                     else;
                        if isempty(DSGEModel.X)==0;
                           [ShockScenarioResults,ShockNames,wtT,SmoothShocks] = DSGEPredictionShockScenarios(PredData.A,PredData.H,PredData.R,PredData.F,PredData.B0,DSGEModel,DSGEModel.Y(:,FirstPeriod:LastPeriod),PredData.MeanPredPath,DSGEModel.X(:,FirstPeriod:LastPeriod),X,AnnualizeData);
                        else;
                           [ShockScenarioResults,ShockNames,wtT,SmoothShocks] = DSGEPredictionShockScenarios(PredData.A,PredData.H,PredData.R,PredData.F,PredData.B0,DSGEModel,DSGEModel.Y(:,FirstPeriod:LastPeriod),PredData.MeanPredPath,[],X,AnnualizeData);
                        end;
                     end;
                  else;
                     ShockScenarioResults = [];
                     [B0_h,KeepShocks] = RemoveRedundantColumns(PredData.B0);
                     ShockNames = DSGEModel.StateShockNames(KeepShocks,:);
                     wtT = [];
                     SmoothShocks = [];
                  end;
                  %
                  % check if we should compute the observed variable scenario for the predictions
                  %
                  if (FileExist([pwd '\addons\ovs\DSGEPredictionOVDecTheta.m'])==1)&(size(DSGEModel.Y>=LastPeriod+MaxPH));
                     txt = ['Would you also like to compute and save observed variable decompositions for the ' AnnualStr ' data at posterior mode to file?'];
                     answer = Query(txt,'question',140,'Conditional Predictive Distributions',500,'yes',CurrINI);
                     drawnow;
                     if strcmp(lower(answer),'yes')==1;
                        if isempty(DSGEModel.X)==0;
                           XSample = DSGEModel.X(:,1:LastPeriod);
                        else;
                           XSample = [];
                        end;
                        [DecData,DecSteadyState,DecHist,DecMeasureError,DecShocks,DecStatus] = DSGEPredictionOVDecTheta(PredData.A,PredData.H,PredData.R,PredData.F,PredData.B0,[XSample X],LastPeriod+1,LastPeriod,MaxPH,0,DSGEModel,CurrINI);
                        if DecStatus==1;
                           [DecFullData,DecFullSteadyState,DecFullHist,DecFullMeasureError,DecFullShocks,DecStatus] = DSGEPredictionOVDecTheta(PredData.A,PredData.H,PredData.R,PredData.F,PredData.B0,[XSample X],1,LastPeriod,MaxPH,1,DSGEModel,CurrINI);
                        end;
                     else;
                        DecData = [];
                        DecSteadyState = [];
                        DecMeasureError = [];
                        DecHist = [];
                        DecShocks = [];
                        DecFullHist = [];
                        DecFullMeasureError = [];
                        DecFullShocks = [];
                        DecStatus = 0;
                     end;
                  else;
                     DecData = [];
                     DecSteadyState = [];
                     DecMeasureError = [];
                     DecHist = [];
                     DecShocks = [];
                     DecFullHist = [];
                     DecFullMeasureError = [];
                     DecFullShocks = [];
                     DecStatus = 0;
                  end;
                  %
                  if (FileExist([pwd '\addons\sss\DSGEPredictionShockScenarios.m'])==1)&(NumPredX<MaxPH);
                     %
                     % matrices with observed data and exogenous variables over the prediction period.
                     %
                     if isempty(DSGEModel.X)==0;
                        DataX = DSGEModel.X(:,LastPeriod+1:LastPeriod+(MaxPH-NumPredX));
                     else;
                        DataX = [];
                     end;
                     DataY = DSGEModel.Y(:,LastPeriod+1:LastPeriod+(MaxPH-NumPredX));
                     %
                     % check if we should compute shock scenarios for the observed data over the prediction sample
                     %
                     if isempty(DSGEModel.X)==0;
                        [DataShockScenarioResults,DataShockNames,DatawtT,SmoothShocks,Yinit] = DSGEPredictionShockScenarios(PredData.A,PredData.H,PredData.R,PredData.F,PredData.B0,DSGEModel,DSGEModel.Y(:,FirstPeriod:LastPeriod),DataY,DSGEModel.X(:,FirstPeriod:LastPeriod),DataX,AnnualizeData);
                     else;
                        [DataShockScenarioResults,DataShockNames,DatawtT,SmoothShocks,Yinit] = DSGEPredictionShockScenarios(PredData.A,PredData.H,PredData.R,PredData.F,PredData.B0,DSGEModel,DSGEModel.Y(:,FirstPeriod:LastPeriod),DataY,[],DataX,AnnualizeData);
                     end;
                     if AnnualizeData==1;
                        DataY = Annualize([Yinit DataY],DSGEModel.annual,DSGEModel.annualscale);
                     end;
                  else;
                     DataY = [];
                     DataShockScenarioResults = [];
                     DatawtT = [];
                     SmoothShocks = [];
                  end;
                  %
                  ConditionalShockNames = DSGEModel.StateShockNames(DSGEModel.ConditionalShocks,:);
                  EstimationStartPeriod = DSGEModel.KalmanFirstObservation;
                  EstimationStartPeriodOrig = EstimationStartPeriod;
                  YOrig = Y;
                  DateVectorOrig = DateVector;
                  if AnnualizeData==1;
                     Y = Annualize(Y,DSGEModel.annual,DSGEModel.annualscale);
                     EstimationStartPeriod = max(1,EstimationStartPeriod-(length(DateVector)-size(Y,2)));
                     DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                  end;
                  %
                  if TransData==1;
                     [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
                     Y = YData';
                     if size(Y,2)==DSGEModel.T;
                        Y = Y(:,FirstPeriod:min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                     else;
                        T2 = size(Y,2);
                        if (FirstPeriod-(DSGEModel.T-T2))>=1;
                           Y = Y(:,FirstPeriod-(DSGEModel.T-T2):min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                        else;
                           Y = Y(:,1:min((LastPeriod+MaxPH),size(DSGEModel.Y,2))-(DSGEModel.T-T2));
                           DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                        end;
                     end;
                  end;
                  %
                  % store conditing data to file
                  %
                  CondData = DSGEModel.Z;
                  CondInitialData = DSGEModel.U;
                  CondNames = DSGEModel.ZVariableNames;
                  HistData = DSGEModel.Y(:,1:LastPeriod);
                  HistNames = DSGEModel.VariableNames;
                  YTransformation = DSGEModel.YTransformation;
                  PredMeanKsiStates = PredData.xiStates;
                  PredMeanEtaShocks = PredData.etaShocks;
                  KsiStates = PredData.KsitT;
                  StateVariableNames = DSGEModel.StateVariableNames;
                  KernelX = PredData.KernelX;
                  KernelY = PredData.KernelY;
                  %
                  ShockPaths = PredData.Shocks;
                  HistState = PredData.HistState;
                  MeasureErrorPaths = PredData.MeasError;
                  %
                  % we need a DateVector for all the data
                  %
                  HistDateVector = MakeDateVector(DSGEModel.BeginYear,DSGEModel.BeginPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency);
                  %
                  if (FileExist([pwd '\addons\sss\DSGEPredictionShockScenarios.m'])==1)&(DecStatus==1);
                     if isempty(PredEventData)==1;
                        save(file,'PredPaths','ShockPaths','MeasureErrorPaths','HistState','MeanPrediction','PredMean','PredMeanKsiStates','PredMeanEtaShocks','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','YInitial','Y','KsiStates','DateVector','YNames','StateVariableNames','ShockScenarioResults','ShockNames','ShockDateVector','SmoothShocks','wtT','DataY','DataShockScenarioResults','DatawtT','ConditionalShockNames','MeanMultiModesty','MultiPValue','ChiSqPValue','MeanUniModesty','MeanUniModestyLZ','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig','CondData','CondInitialData','CondNames','HistData','HistNames','HistDateVector','YTransformation','DecData','DecSteadyState','DecHist','DecMeasureError','DecShocks','DecFullHist','DecFullMeasureError','DecFullShocks','FirstPeriod');
                     else;
                        save(file,'PredPaths','ShockPaths','MeasureErrorPaths','HistState','MeanPrediction','PredMean','PredMeanKsiStates','PredMeanEtaShocks','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','YInitial','Y','KsiStates','DateVector','YNames','StateVariableNames','ShockScenarioResults','ShockNames','ShockDateVector','SmoothShocks','wtT','DataY','DataShockScenarioResults','DatawtT','ConditionalShockNames','MeanMultiModesty','MultiPValue','ChiSqPValue','MeanUniModesty','MeanUniModestyLZ','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig','CondData','CondInitialData','CondNames','HistData','HistNames','HistDateVector','YTransformation','DecData','DecSteadyState','DecHist','DecMeasureError','DecShocks','DecFullHist','DecFullMeasureError','DecFullShocks','FirstPeriod','PredEventData','YObsEventData');
                     end;
                  else;
                     if isempty(PredEventData)==1;
                        save(file,'PredPaths','ShockPaths','MeasureErrorPaths','HistState','MeanPrediction','PredMean','PredMeanKsiStates','PredMeanEtaShocks','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','YInitial','Y','KsiStates','DateVector','YNames','StateVariableNames','ShockNames','MeanMultiModesty','MultiPValue','ChiSqPValue','MeanUniModesty','MeanUniModestyLZ','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig','CondData','CondInitialData','CondNames','HistData','HistNames','HistDateVector','YTransformation');
                     else;
                        save(file,'PredPaths','ShockPaths','MeasureErrorPaths','HistState','MeanPrediction','PredMean','PredMeanKsiStates','PredMeanEtaShocks','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','YInitial','Y','KsiStates','DateVector','YNames','StateVariableNames','ShockNames','MeanMultiModesty','MultiPValue','ChiSqPValue','MeanUniModesty','MeanUniModestyLZ','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig','CondData','CondInitialData','CondNames','HistData','HistNames','HistDateVector','YTransformation','PredEventData','YObsEventData');
                     end;
                  end;
                  %
                  % create a matlab m-file to read the output.
                  %
                  mfile = [DSGEModel.OutputDirectory '\CondPD' int2str(DSGEModel.ShockControlMethod) AnnualStr num2str(MaxPH,'%0.0f') DSGEModel.SubEndYear DSGEModel.SubEndPeriod 'PostMode.m'];
                  fid = fopen(mfile,'wt');
                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                  fprintf(fid,'%%\n%% 3D matrix with all the prediction paths for the observed variables\n%%\n');
                  fprintf(fid,'PredPaths = DataStructure.PredPaths;\n');
                  fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                  fprintf(fid,'YNames = DataStructure.YNames;\n');
                  fprintf(fid,'%%\n%% string matrix with the names of the state variable variables\n%%\n');
                  fprintf(fid,'StateVariableNames = DataStructure.StateVariableNames;\n');
                  if AdjustMean==0;
                     fprintf(fid,'%%\n%% matrix with the mean of the simulated predictions of the observed variables\n%%\n');
                  else;
                     fprintf(fid,'%%\n%% matrix with the corrected mean of the simulated predictions of the observed variables\n%%\n');
                  end;
                  fprintf(fid,'MeanPrediction = DataStructure.MeanPrediction;\n');
                  fprintf(fid,'%%\n%% matrix with the population mean of the predictions of the observed variables\n%%\n');
                  fprintf(fid,'PredMean = DataStructure.PredMean;\n');
                  fprintf(fid,'%%\n%% matrix with the population mean of the predictions of the state variables\n%%\n');
                  fprintf(fid,'PredMeanKsiStates = DataStructure.PredMeanKsiStates;\n');
                  fprintf(fid,'%%\n%% matrix with the population mean of the predictions of the economic shocks\n%%\n');
                  fprintf(fid,'PredMeanEtaShocks = DataStructure.PredMeanEtaShocks;\n');
                  fprintf(fid,'%%\n%% matrix with the errors from the mean predictions of the observed variables\n%%\n');
                  fprintf(fid,'PredictionErrors = DataStructure.PredictionErrors;\n');
                  fprintf(fid,'%%\n%% vector structure with quantiles from the conditional predictive distribution\n%% the structure has %0.0f entries with fields "Quantile" and "percent"\n%% the first field is a matrix and the second a positive number between 0 and 100\n%%\n',length(Quantiles));
                  fprintf(fid,'Quantiles = DataStructure.Quantiles;\n');
                  if isempty(KernelX)==0;
                     fprintf(fid,'%%\n%% matrix with x-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                     fprintf(fid,'KernelX = DataStructure.KernelX;\n');
                     fprintf(fid,'%%\n%% matrix with y-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                     fprintf(fid,'KernelY = DataStructure.KernelY;\n');
                     KStr = 'KernelX (matrix with x-axis for kernel density estimates of marginal predictive distribution), KernelY (matrix with y-axis values for kernel density estimates of marginal predictive distribution), ';
                     KVal = 2;
                  else;
                     KStr = '';
                     KVal = 0;
                  end;
                  fprintf(fid,'%%\n%% vector with dates for the predictions\n%%\n');
                  fprintf(fid,'PredDateVector = DataStructure.PredDateVector;\n');
                  fprintf(fid,'%%\n%% observed variables\n%%\n');
                  fprintf(fid,'Y = DataStructure.Y;\n');
                  fprintf(fid,'%%\n%% smooth estimates of the state variables\n%%\n');
                  fprintf(fid,'KsiStates = DataStructure.KsiStates;\n');
                  fprintf(fid,'%%\n%% vector with dates for the observed variables\n%%\n');
                  fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                  fprintf(fid,'%%\n%% Names for the economic shocks\n%%\n');
                  fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                  fprintf(fid,'%%\n%% Underlying draws of the economic shocks for all paths\n%%\n');
                  fprintf(fid,'ShockPaths = DataStructure.ShockPaths;\n');
                  fprintf(fid,'%%\n%% Underlying draws of the neasurement errors for all paths\n%%\n');
                  fprintf(fid,'MeasureErrorPaths = DataStructure.MeasureErrorPaths;\n');
                  fprintf(fid,'%%\n%% Underlying draws of the state variables before the predictions\n%%\n');
                  fprintf(fid,'HistState = DataStructure.HistState;\n');
                  if (FileExist([pwd '\addons\sss\DSGEPredictionShockScenarios.m'])==1)&(DecStatus==1);
                     fprintf(fid,'%%\n%% 3D matrix with shock scenarios over the prediction sample for the mean predictions\n%%\n');
                     fprintf(fid,'ShockScenarioResults = DataStructure.ShockScenarioResults;\n');
                     fprintf(fid,'%%\n%% estimates of the measurement errors over the prediction sample using the mean predictions\n%%\n');
                     fprintf(fid,'wtT = DataStructure.wtT;\n');
                     fprintf(fid,'%%\n%% string matrix with names of the economic shocks that are manipulated\n%% to achieve the conditioning assumptions\n%%\n');
                     fprintf(fid,'ConditionalShockNames = DataStructure.ConditionalShockNames;\n');
                     fprintf(fid,'%%\n%% The observed variables for the prediction sample\n%%\n');
                     fprintf(fid,'DataY = DataStructure.DataY;\n');
                     fprintf(fid,'%%\n%% 3D matrix with shock scenarios over the prediction sample for the observed data\n%%\n');
                     fprintf(fid,'DataShockScenarioResults = DataStructure.DataShockScenarioResults;\n');
                     fprintf(fid,'%%\n%% estimates of the measurement errors over the prediction sample using the observed data\n%%\n');
                     fprintf(fid,'DatawtT = DataStructure.DatawtT;\n');
                     fprintf(fid,'%%\n%% matrix with the observed variables for the estimation sample and the decomposition sample\n%%\n');
                     fprintf(fid,'DecData = DataStructure.DecData;\n');
                     fprintf(fid,'%%\n%% matrix with the share due to the steady state\n%%\n');
                     fprintf(fid,'DecSteadyState = DataStructure.DecSteadyState;\n');
                     fprintf(fid,'%%\n%% matrix with the share due to the history\n%%\n');
                     fprintf(fid,'DecHist = DataStructure.DecHist;\n');
                     fprintf(fid,'%%\n%% matrix with the share due to the measurement errors over the forecast horizon\n%%\n');
                     fprintf(fid,'DecMeasureError = DataStructure.DecMeasureError;\n');
                     fprintf(fid,'%%\n%% 3D matrix with the shares due to the economic shocks over the forecast horizon\n%%\n');
                     fprintf(fid,'DecShocks = DataStructure.DecShocks;\n');
                     fprintf(fid,'%%\n%% matrix with the share due to the initial state\n%%\n');
                     fprintf(fid,'DecFullHist = DataStructure.DecFullHist;\n');
                     fprintf(fid,'%%\n%% matrix with the share due to the measurement errors over the full sample\n%%\n');
                     fprintf(fid,'DecFullMeasureError = DataStructure.DecFullMeasureError;\n');
                     fprintf(fid,'%%\n%% 3D matrix with the shares due to the economic shocks over the full sample\n%%\n');
                     fprintf(fid,'DecFullShocks = DataStructure.DecFullShocks;\n');
                     fprintf(fid,'%%\n%% The first period in the sample to use with DecData\n%%\n');
                     fprintf(fid,'FirstPeriod = DataStructure.FirstPeriod;\n');
                     ShockStr = 'ShockScenarioResults (3D matrix of dimension nxhxq with the shocks scenarios for the mean predictions of the observed variables), wtT (matrix with estimated measurement errors over the prediction sample for the mean predictions of the observed variables), ConditionalShockNames (string matrix with names for the shocks used to achieve the conditioning assumptions), DataY (matrix with the observed data for the prediction sample), DataShockScenarioResults (3D matrix with shock scenarios for the observed variables over the prediction sample), DatawtT (estimates of the measurement errors over the prediction sample for the observed variables), DecData (matrix with the observed variables), DecSteadyState (matrix with the share of the data due to the steady state), DecHist (matrix with the share of the data due to history), DecMeasureError (matrix with the share of the data due to measurement errors over the prediction horizon), DecShocks (3D matrix with the shares of the data due to the economic shocks over the prediction horizon), DecFullHist (matrix with the share of the data due to the initial state), DecFullMeasureError (matrix with share of the data due to measurement errors over the full sample), DecFullShocks (3D matrix with share of data due to the economic shocks over the full sample), FirstPeriod (integer with the first period of the sample to use with DecData), ';
                     SSEntries = 15;
                  else;
                     ShockStr = '';
                     SSEntries = 0;
                  end;
                  if isempty(PredEventData)==0;
                     fprintf(fid,'%%\n%% matrix with prediction event data. First column holds the\n%% number of true events, the second the number of times below the events, and the third the number of events\n%%\n');
                     fprintf(fid,'PredEventData = DataStructure.PredEventData;\n');
                     fprintf(fid,'%%\n%% matrix with observed event data. First column holds the\n%% number of true events, the second the number of times below the events, and the third the number of events\n%%\n');
                     fprintf(fid,'YObsEventData = DataStructure.YObsEventData;\n');
                     NumEntries = int2str(19+KVal+SSEntries);
                     ExtraEntry = 'PredEventData (matrix with the number of true events, the number of events below the lower bound for the event, and the number of events tested in the columns), YObsEventData (matrix with the number of true events for prediction paths whose mean is the observed data, the number of events below the lower bound for the event, and the number of events tested in the columns), ';
                  else;
                     NumEntries = int2str(17+KVal+SSEntries);
                     ExtraEntry = '';
                  end;
                  if FileExist([pwd '\addons\sss\DSGEPredictionShockScenarios.m'])==0;
                     NumEntries = num2str(str2num(NumEntries)-7,'%0.0f');
                  end;
                  if AnnualizeData==0;
                     fprintf(fid,'%%\n%% vector with the mean of the multivariate modesty statistic and its reference statistic\n%%\n');
                     fprintf(fid,'MeanMultiModesty = DataStructure.MeanMultiModesty;\n');
                     fprintf(fid,'%%\n%% tail probability based on the reference statistic\n%%\n');
                     fprintf(fid,'MultiPValue = DataStructure.MultiPValue;\n');
                     fprintf(fid,'%%\n%% tail probability based on the chi-square distribution\n%%\n');
                     fprintf(fid,'ChiSqPValue = DataStructure.ChiSqPValue;\n');
                     fprintf(fid,'%%\n%% Adolfson, Laséen, Lindé and Villani univariate modesty statistic\n%%\n');
                     fprintf(fid,'MeanUniModesty = DataStructure.MeanUniModesty;\n');
                     fprintf(fid,'%%\n%% Leeper and Zha univariate modesty statistic\n%%\n');
                     fprintf(fid,'MeanUniModestyLZ = DataStructure.MeanUniModestyLZ;\n');
                     NumEntries = num2str(str2num(NumEntries)+5,'%0.0f');
                     ExtraEntry = [ExtraEntry 'MeanMultiModesty (1x2 vector with the mean of the multivariate modesty statistic and the mean of the multivariate reference modesty statistic), MultiPValue (scalar with the tail probability of the modesty statistic), ChiSqPValue (scalar with the tail probability of the modesty statistic using the chi-square distribution), MeanUniModesty (vector with the univariate modesty statistic from ALLV), MeanUniModestyLZ (vector with the univariate Leeper-Zha modesty statistic), '];
                  end;
                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                  %
                  % end the script file
                  %
                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                  fclose(fid);
                  %
                  txt = ['The conditional predictive distributions have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains ' NumEntries ' entries: PredPaths (3D matrix with the prediction paths for the observed variables), YNames (string matrix with the names of the observed variables), StateVariableNames (string matrix with the names of the state variables), MeanPrediction (matrix with the selected mean predictions), PredMean (matrix with the population mean predictions), PredMeanKsiStates (matrix with the population mean state predictions), PredMeanEtaShocks (matrix with the population mean economic shock predictions), PredictionErrors (matrix with errors for the mean prediction), Quantiles (vector structure with 2 fields: Quantile and percent), ' KStr 'PredDateVector (vector with dates for the predictions), Y (matrix with the observed variables), KsiStates (matrix with the smooth estimates of the state variables), ShockNames (string matrix with the names for the economic shocks), ShockPaths (3D matrix with the underlying economic shocks for the prediction paths), MeasureErrorPaths (3D matrix with the underlying draws of the measurement errors for the prediction paths), HistState (matrix with the underlying draws of the state variables from the period prior to the predictions), ' ShockStr ExtraEntry 'and DateVector (vector with dates for the observed variables). To access these data you may run the matlab script file "' GetFilename(mfile) '".'];
                  About(txt,'information','Conditional Predictive Distributions',700,550,CurrINI);
               end;
               if isempty(PredEventData)==0;
                  %
                  % write prediction event results to file
                  %
                  file = [DSGEModel.OutputDirectory '\CondPredictiveDist-' int2str(DSGEModel.ShockControlMethod) '-' AnnualStr '-' num2str(MaxPH,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '-PosteriorMode.txt'];
                  [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,MaxPH);
                  PrintPredictionEvent(file,DSGEModel.VariableNames,PredEventData,YObsEventData,DSGEModel.PredictionEvent,[PredStartYear ':' PredStartPeriod '-' PredEndYear ':' PredEndPeriod],MaxPH,NumPredPaths,1,CurrINI);
                  %
                  % displays the file if it exists
                  %
                  if FileExist(file)==1;
                     TextGUI(file,['Prediction Events - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,0);
                  end;
               end;
               %
               % Open a dialog for displaying predictive distributions
               %
               CondPredictiveDistributionDLG('init',DSGEModel,CurrINI,MeanPrediction,Quantiles,PredData.KernelX,PredData.KernelY,'Posterior Mode','DSGE',AnnualStr);
            end;
         else;
            About(ErrorStr,'information',HeaderStr,120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'condcorr_dist'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            ParameterNames = ModeData.ParameterNames.estimated;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Conditional Correlation Distribution','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check which draws we should use
                  %
                  UseDraws = KeepPosteriorDraws(DSGEModel,controls.posterior.usepostdraws,NumDraws);
                  if length(UseDraws)<NumDraws;
                     thetaPostSample = thetaPostSample(UseDraws,:);
                     UsedDraws = length(UseDraws);
                  else;
                     UsedDraws = NumDraws;
                  end;
                  %
                  % check which parameters should be changed
                  %
                  if (isempty(DSGEModel.ScenarioParameters)==1)|(length(DSGEModel.ScenarioParameters)~=length(theta));
                     ScenarioParameters = ones(1,length(theta));
                  else;
                     ScenarioParameters = DSGEModel.ScenarioParameters;
                  end;
                  positions = ScenarioParameters .* (1:length(theta));
                  %
                  % remove all zeros from positions
                  %
                  positions = positions(positions>0);
                  %
                  [PosAction,positions] = SelectCondVarShockDLG('init','Conditional Correlation Distribution','Parameters For',ParameterNames,positions,CurrINI);
                  if (strcmp(lower(PosAction),'ok')==1)&(isempty(positions)==0);
                     %
                     % rewrite positions into DSGEModel.ScenarioParameters
                     %
                     ScenarioParameters = zeros(1,length(theta));
                     ScenarioParameters(positions) = ones(1,length(positions));
                     %
                     % ask if the user wants to simulate data
                     %
                     txt = 'Would you like to examine model based sample conditional correlations rather than model based population conditional correlations? Note: the model based sample conditional correlations require simulation of data, while the population conditional correlations only use draws from the posterior distribution of the structural parameters.';
                     answer = Query(txt,'information',150,'Conditional Correlations Distribution',450,'no',CurrINI);
                     if strcmp(lower(answer),'no')==1;
                        SimulateData = 0;
                        NumPredPaths = 0;
                     else;
                        SimulateData = 1;
                        NumPredPathsStr = get(controls.forecast.predpaths,'String');
                        NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
                     end;
                     %
                     % First we check if the calculations have already been performed
                     %
                     if CondCorrExist(DSGEModel,ScenarioParameters,UsedDraws,NumDraws,CurrChain,NumPredPaths)==1;
                        txt = 'YADA has located results for the conditional correlations on disk. Would you like to use these results?';
                        answer = Query(txt,'information',150,'Conditional Correlations Distribution',450,'no',CurrINI);
                     else;
                        answer = 'No';
                     end;
                     if strcmp(lower(answer),'yes')==1;
                        DoneCalc = 1;
                     else;
                        %
                        % start estimation
                        %
                        if SimulateData==0;
                           DoneCalc = DSGECondCorrEstimation(theta,thetaPostSample,thetaPositions,ModelParameters,ScenarioParameters,NumDraws,CurrChain,DSGEModel,CurrINI);
                        else;
                           DoneCalc = DSGECondCorrSimulation(theta,thetaPostSample,thetaPositions,ModelParameters,ScenarioParameters,NumDraws,CurrChain,NumPredPaths,DSGEModel,CurrINI);
                        end;
                     end;
                     if DoneCalc==1;
                        %
                        % determine the distribution for the correlations
                        %
                        CorrData = DSGECondCorrDistribution(DSGEModel,CurrINI,ScenarioParameters,UsedDraws,NumDraws,CurrChain,NumPredPaths);
                        %
                        % ask if we should save the results to disk
                        %
                        if NumPredPaths==0;
                           SampleTypeStr = 'Population';
                           AddFileName = '';
                        else;
                           SampleTypeStr = 'Sample';
                           AddFileName = ['-' int2str(NumPredPaths)];
                        end;
                        %
                        txt = ['Would you like to save the mean and quantiles of the ' lower(SampleTypeStr) '-based conditional correlation distribution to file?'];
                        answer = Query(txt,'question',140,'Save - Conditional Correlation Distribution',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           file = [DSGEModel.OutputDirectory '\CondCorrelation' SampleTypeStr 'Dist' AddFileName '-' int2str(UsedDraws) '.mat'];
                           VariableNames = DSGEModel.VariableNames;
                           ShockNames = CorrData(1).ShockNames;
                           for i=1:length(CorrData);
                              ConditionalCorrs(i).Mean = CorrData(i).Mean;
                              ConditionalCorrs(i).Quantiles = CorrData(i).Quantiles;
                           end;
                           %
                           save(file,'VariableNames','ShockNames','ConditionalCorrs');
                           %
                           % write an m-file
                           %
                           mfile = [DSGEModel.OutputDirectory '\CC' SampleTypeStr 'Dist' strrep(AddFileName,'-','') int2str(UsedDraws) '.m'];
                           fid = fopen(mfile,'wt');
                           fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                           fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                           fprintf(fid,'%%\n%% vector structure with fields Mean and Quantiles.\n%% The length of the vector structure is equal to the number of state shocks\n%%\n');
                           fprintf(fid,'ConditionalCorrs = DataStructure.ConditionalCorrs;\n');
                           fprintf(fid,'%%\n%% string matrix with the names of the non-zero state shocks\n%%\n');
                           fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                           fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                           fprintf(fid,'VariableNames = DataStructure.VariableNames;\n');
                           fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                           %
                           %
                           % end the script file
                           %
                           fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                           fclose(fid);
                           txt = ['The model based ' lower(SampleTypeStr) ' conditional correlations data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 3 entries: ConditionalCorrs (a vector structure with the model based mean and quantiles of the ' lower(SampleTypeStr) ' conditional correlations), ShockNames (string matrix with the names of the nonzero state shocks), and VariableNames (string matrix with the names of the observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                           About(txt,'information','Conditional Correlation Distribution - ',200,500,CurrINI);
                        end;
                        %
                        % print the output to file
                        %
                        PrintCondCorrelations(DSGEModel,CorrData,CurrINI,'distribution',NumPredPaths,UsedDraws);
                        %
                        ResFile = [DSGEModel.OutputDirectory '\PosteriorDistCondCorr-' DSGEModel.NameOfModel AddFileName '.' int2str(UsedDraws) '.txt'];
                        if FileExist(ResFile)==1;
                           TextGUI(ResFile,['Conditional Correlations - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Distribution',50,CurrINI,1,1);
                        end;
                     end;
                  elseif isempty(positions)==1;
                     txt = 'You didn''t select any parameters that should be varied for the estimation of the conditional correlation distribution.';
                     About(txt,'information','Conditional Correlation Distribution',150,500,CurrINI);
                  end;
                  %
                  % clear everything
                  %
                  clear('thetaPostSample');
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'obsvar_dist'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            ParameterNames = ModeData.ParameterNames.estimated;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Autocorrelation Distribution','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check which draws we should use
                  %
                  UseDraws = KeepPosteriorDraws(DSGEModel,controls.posterior.usepostdraws,NumDraws);
                  if length(UseDraws)<NumDraws;
                     thetaPostSample = thetaPostSample(UseDraws,:);
                     UsedDraws = length(UseDraws);
                  else;
                     UsedDraws = NumDraws;
                  end;
                  %
                  % check which parameters should be changed
                  %
                  if (isempty(DSGEModel.ScenarioParameters)==1)|(length(DSGEModel.ScenarioParameters)~=length(theta));
                     ScenarioParameters = ones(1,length(theta));
                  else;
                     ScenarioParameters = DSGEModel.ScenarioParameters;
                  end;
                  positions = ScenarioParameters .* (1:length(theta));
                  %
                  % remove all zeros from positions
                  %
                  positions = positions(positions>0);
                  %
                  [PosAction,positions] = SelectCondVarShockDLG('init','Autocorrelation Distribution','Parameters For',ParameterNames,positions,CurrINI);
                  if (strcmp(lower(PosAction),'ok')==1)&(isempty(positions)==0);
                     %
                     % rewrite positions into DSGEModel.ScenarioParameters
                     %
                     ScenarioParameters = zeros(1,length(theta));
                     ScenarioParameters(positions) = ones(1,length(positions));
                     %
                     % ask if the user wants to simulate data
                     %
                     txt = 'Would you like to examine model based sample moments rather than model based population moments? Note: the model based sample moments require simulation of data, while the population moments only use draws from the posterior distribution of the structural parameters.';
                     answer = Query(txt,'information',150,'Autocorrelation Distribution',450,'no',CurrINI);
                     if strcmp(lower(answer),'no')==1;
                        SimulateData = 0;
                        NumPredPaths = 0;
                     else;
                        SimulateData = 1;
                        NumPredPathsStr = get(controls.forecast.predpaths,'String');
                        NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
                     end;
                     %
                     % First we check if the calculations have already been performed
                     %
                     if SVEExist(DSGEModel,ScenarioParameters,UsedDraws,NumDraws,CurrChain,NumPredPaths,1)==1;
                        txt = 'YADA has located results for the autocorrelations on disk. Would you like to use these results?';
                        answer = Query(txt,'information',150,'Autocorrelation Distribution',450,'no',CurrINI);
                     else;
                        answer = 'No';
                     end;
                     if strcmp(lower(answer),'yes')==1;
                        DoneCalc = 1;
                     else;
                        %
                        % start estimation
                        %
                        if SimulateData==0;
                           DoneCalc = DSGEStateVariableEstimation(theta,thetaPostSample,thetaPositions,ModelParameters,ScenarioParameters,'Autocorrelation',NumDraws,CurrChain,DSGEModel,CurrINI);
                        else;
                           DoneCalc = DSGEStateVariableSimulation(theta,thetaPostSample,thetaPositions,ModelParameters,ScenarioParameters,'Autocorrelation',NumDraws,CurrChain,NumPredPaths,DSGEModel,CurrINI);
                        end;
                     end;
                     %
                     % check if we should show any results
                     %
                     if DoneCalc==1;
                        %
                        % compute the distribution for the 1-step ahead forecasts
                        %
                        if SimulateData==0;
                           SVEs = DSGESVEDistribution(DSGEModel,CurrINI,5,ScenarioParameters,UsedDraws,NumDraws,CurrChain);
                           AutoCorrType = 'Population-based';
                        else;
                           SVEs = DSGESVESimulatedDistribution(DSGEModel,CurrINI,5,ScenarioParameters,UsedDraws,NumDraws,CurrChain,NumPredPaths);
                           AutoCorrType = 'Sample-based';
                        end;
                        %
                        % check if results should be written to file
                        %
                        txt = 'Would you like to save the mean, standard deviation, correlations, and quantiles of the autocorrelation distributions to file?';
                        answer = Query(txt,'question',140,'Save - Autocorrelation Distribution',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           SelParamStr = strrep(num2str(ScenarioParameters),' ','');
                           file = [DSGEModel.OutputDirectory '\AutoCorrelationDist-' SelParamStr '-' int2str(UsedDraws) '-' int2str(NumDraws) '-' int2str(CurrChain) '.mat'];
                           VariableNames = DSGEModel.VariableNames;
                           save(file,'SVEs','VariableNames');
                           %
                           % create a matlab file to read the data
                           %
                           mfile = strrep(strrep(strrep(strrep(file,'.mat','.m'),'-',''),SelParamStr,[int2str(sum(ScenarioParameters)) 'x' int2str(length(ScenarioParameters)-sum(ScenarioParameters))]),'AutoCorrelationDist','ACDist');
                           fid = fopen(mfile,'wt');
                           fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                           fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                           fprintf(fid,'%%\n%% structure with fields Data.Mean, Data.Std, Data.Corr (data moments), Mean, Std, Corr (model means), Quantiles, and AutoCovHorizon.\n%%\n');
                           fprintf(fid,'SVEs = DataStructure.SVEs;\n');
                           fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                           fprintf(fid,'VariableNames = DataStructure.VariableNames;\n');
                           fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                           %
                           % end the script file
                           %
                           fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                           fclose(fid);
                           txt = ['The autocorrelation data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 2 entries: SVEs (a structure with the data and model based mean, standard deviation, correlation, quantile data, and correlation points), and VariableNames (string matrix with the names of the observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                           About(txt,'information','Autocorrelation Distribution',300,500,CurrINI);
                        end;
                        %
                        % display the autocorrelations
                        %
                        AutoCorrelationDistributionDLG('init',SVEs,AutoCorrType,'Autcorrelation Distribution','Graphics - Autcorrelation Distribution',DSGEModel,CurrINI);
                        %
                        % check if the user wants to view the mean and the standard deviations
                        %
                        txt = 'Would you like to view the data and model based mean and standard deviations of the observed variables?';
                        answer = Query(txt,'question',200,'Autocorrelation Distribution',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           if NumPredPaths==0;
                              file = [DSGEModel.OutputDirectory '\AutoCorrelationDist-' SelParamStr '-' int2str(UsedDraws) '-' int2str(NumDraws) '-' int2str(CurrChain) '.txt'];
                           else;
                              file = [DSGEModel.OutputDirectory '\AutoCorrelationDist-' SelParamStr '-' int2str(UsedDraws) '-' int2str(NumDraws) '-' int2str(CurrChain) '-' int2str(NumPredPaths) '.txt'];
                           end;
                           %
                           PrintStateVarDistribution(file,SVEs,DSGEModel,CurrINI,4,UsedDraws,NumDraws,CurrChain,NumPredPaths);
                           %
                           % display the results
                           %
                           if FileExist(file)==1;
                              TextGUI(file,['Observed Variable Correlation Distributions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Correlation Distributions',50,CurrINI,1,1);
                           end;
                        end;
                     end;
                  elseif isempty(positions)==1;
                     txt = 'You didn''t select any parameters that should be varied for the estimation of the autocorrelation distribution.';
                     About(txt,'information','Autocorrelation Distribution',150,500,CurrINI);
                  end;
                  %
                  % clear everything
                  %
                  clear('thetaPostSample');
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'ob_dist'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            ParameterNames = ModeData.ParameterNames.estimated;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','1-Step Ahead Forecast Distribution','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check which draws we should use
                  %
                  UseDraws = KeepPosteriorDraws(DSGEModel,controls.posterior.usepostdraws,NumDraws);
                  if length(UseDraws)<NumDraws;
                     thetaPostSample = thetaPostSample(UseDraws,:);
                     UsedDraws = length(UseDraws);
                  else;
                     UsedDraws = NumDraws;
                  end;
                  %
                  % check which parameters should be changed
                  %
                  if (isempty(DSGEModel.ScenarioParameters)==1)|(length(DSGEModel.ScenarioParameters)~=length(theta));
                     ScenarioParameters = ones(1,length(theta));
                  else;
                     ScenarioParameters = DSGEModel.ScenarioParameters;
                  end;
                  positions = ScenarioParameters .* (1:length(theta));
                  %
                  % remove all zeros from positions
                  %
                  positions = positions(positions>0);
                  %
                  [PosAction,positions] = SelectCondVarShockDLG('init','1-Step Ahead Forecast Distribution','Parameters For',ParameterNames,positions,CurrINI);
                  if (strcmp(lower(PosAction),'ok')==1)&(isempty(positions)==0);
                     %
                     % rewrite positions into DSGEModel.ScenarioParameters
                     %
                     ScenarioParameters = zeros(1,length(theta));
                     ScenarioParameters(positions) = ones(1,length(positions));
                     %
                     % First we check if the calculations have already been performed
                     %
                     if SVEExist(DSGEModel,ScenarioParameters,UsedDraws,NumDraws,CurrChain,0)==1;
                        txt = 'YADA has located results for the 1-step ahead forecasts on disk. Would you like to use these results?';
                        answer = Query(txt,'information',150,'1-Step Ahead Forecast Distribution',450,'no',CurrINI);
                     else;
                        answer = 'No';
                     end;
                     if strcmp(lower(answer),'yes')==1;
                        DoneCalc = 1;
                     else;
                        %
                        % start estimation
                        %
                        DoneCalc = DSGEStateVariableEstimation(theta,thetaPostSample,thetaPositions,ModelParameters,ScenarioParameters,'1-Step Ahead Forecast',NumDraws,CurrChain,DSGEModel,CurrINI);
                     end;
                     %
                     % check if we should show any results
                     %
                     if DoneCalc==1;
                        %
                        % compute the distribution for the 1-step ahead forecasts
                        %
                        SVEs = DSGESVEDistribution(DSGEModel,CurrINI,1,ScenarioParameters,UsedDraws,NumDraws,CurrChain);
                        %
                        % ask if we should save results to disk
                        %
                        txt = 'Would you like to save the mean and quantiles of the 1-step ahead forecast distributions to file?';
                        answer = Query(txt,'question',140,'Save - 1-Step Ahead Forecast Distribution',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           SelParamStr = strrep(num2str(ScenarioParameters),' ','');
                           file = [DSGEModel.OutputDirectory '\OneStepForecastDist-' SelParamStr '-' int2str(UsedDraws) '-' int2str(NumDraws) '-' int2str(CurrChain) '.mat'];
                           VariableNames = DSGEModel.VariableNames;
                           save(file,'SVEs','VariableNames');
                           %
                           % create a matlab file to read the data
                           %
                           mfile = strrep(strrep(strrep(strrep(file,'.mat','.m'),'-',''),SelParamStr,[int2str(sum(ScenarioParameters)) 'x' int2str(length(ScenarioParameters)-sum(ScenarioParameters))]),'OneStepForecastDist','OSFDist');
                           fid = fopen(mfile,'wt');
                           fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                           fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                           fprintf(fid,'%%\n%% structure with fields Y (observed variables), Yhat (1-step ahead forecasts), Quantiles, and DateVector.\n%%\n');
                           fprintf(fid,'SVEs = DataStructure.SVEs;\n');
                           fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                           fprintf(fid,'VariableNames = DataStructure.VariableNames;\n');
                           fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                           %
                           % end the script file
                           %
                           fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                           fclose(fid);
                           txt = ['The 1-step ahead forecast data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 2 entries: SVEs (a structure with the mean for the 1-step ahead forecast and the observed values for the variables, quantile data, and numeric dates), and VariableNames (string matrix with the names of the observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                           About(txt,'information','1-Step Ahead Forecast Distribution',200,500,CurrINI);
                        end;
                        %
                        % display the results
                        %
                        StateVarDistributionDLG('init',SVEs,1,DSGEModel,CurrINI);
                     end;
                  elseif isempty(positions)==1;
                     txt = 'You didn''t select any parameters that should be varied for the estimation of the 1-step ahead forecast distribution.';
                     About(txt,'information','1-Step Ahead Forecast Distribution',150,500,CurrINI);
                  end;
                  %
                  % clear everything
                  %
                  clear('thetaPostSample');
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'statevar_dist'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            ParameterNames = ModeData.ParameterNames.estimated;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','State Variable Correlation Distribution','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check which draws we should use
                  %
                  UseDraws = KeepPosteriorDraws(DSGEModel,controls.posterior.usepostdraws,NumDraws);
                  if length(UseDraws)<NumDraws;
                     thetaPostSample = thetaPostSample(UseDraws,:);
                     UsedDraws = length(UseDraws);
                  else;
                     UsedDraws = NumDraws;
                  end;
                  %
                  % check which parameters should be changed
                  %
                  if (isempty(DSGEModel.ScenarioParameters)==1)|(length(DSGEModel.ScenarioParameters)~=length(theta));
                     ScenarioParameters = ones(1,length(theta));
                  else;
                     ScenarioParameters = DSGEModel.ScenarioParameters;
                  end;
                  positions = ScenarioParameters .* (1:length(theta));
                  %
                  % remove all zeros from positions
                  %
                  positions = positions(positions>0);
                  %
                  [PosAction,positions] = SelectCondVarShockDLG('init','State Variable Correlation Distribution','Parameters For',ParameterNames,positions,CurrINI);
                  if (strcmp(lower(PosAction),'ok')==1)&(isempty(positions)==0);
                     %
                     % rewrite positions into DSGEModel.ScenarioParameters
                     %
                     ScenarioParameters = zeros(1,length(theta));
                     ScenarioParameters(positions) = ones(1,length(positions));
                     %
                     % ask if the user wants to simulate data
                     %
                     txt = 'Would you like to examine model based sample moments rather than model based population moments? Note: the model based sample moments require simulation of data, while the population moments only use draws from the posterior distribution of the structural parameters.';
                     answer = Query(txt,'information',150,'State Variable Correlation Distribution',450,'no',CurrINI);
                     if strcmp(lower(answer),'no')==1;
                        SimulateData = 0;
                        NumPredPaths = 0;
                     else;
                        SimulateData = 1;
                        NumPredPathsStr = get(controls.forecast.predpaths,'String');
                        NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
                     end;
                     %
                     % First we check if the calculations have already been performed
                     %
                     if SVEExist(DSGEModel,ScenarioParameters,UsedDraws,NumDraws,CurrChain,NumPredPaths,0)==1;
                        txt = 'YADA has located results for the state variables correlations on disk. Would you like to use these results?';
                        answer = Query(txt,'information',150,'State Variable Correlation Distribution',450,'no',CurrINI);
                     else;
                        answer = 'No';
                     end;
                     if strcmp(lower(answer),'yes')==1;
                        DoneCalc = 1;
                     else;
                        %
                        % start estimation
                        %
                        if SimulateData==0;
                           DoneCalc = DSGEStateVariableEstimation(theta,thetaPostSample,thetaPositions,ModelParameters,ScenarioParameters,'State Variable Correlation',NumDraws,CurrChain,DSGEModel,CurrINI);
                        else;
                           DoneCalc = DSGEStateVariableSimulation(theta,thetaPostSample,thetaPositions,ModelParameters,ScenarioParameters,'State Variable Correlation',NumDraws,CurrChain,NumPredPaths,DSGEModel,CurrINI);
                        end;
                     end;
                     %
                     % check if we should show any results
                     %
                     if DoneCalc==1;
                        %
                        % compute the distribution for the state variables
                        %
                        if SimulateData==0;
                           SVEs = DSGESVEDistribution(DSGEModel,CurrINI,6,ScenarioParameters,UsedDraws,NumDraws,CurrChain);
                           MeanStr = '';
                        else;
                           SVEs = DSGESVESimulatedDistribution(DSGEModel,CurrINI,6,ScenarioParameters,UsedDraws,NumDraws,CurrChain,NumPredPaths);
                           MeanStr = ' sample mean,';
                        end;
                        %
                        % ask if we should save results to disk
                        %
                        txt = 'Would you like to save the mean and quantiles of the state variable correlations distributions to file?';
                        answer = Query(txt,'question',140,'Save - State Variable Correlation Distribution',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           SelParamStr = strrep(num2str(ScenarioParameters),' ','');
                           file = [DSGEModel.OutputDirectory '\StateVariableCorrDist-' SelParamStr '-' int2str(UsedDraws) '-' int2str(NumDraws) '-' int2str(CurrChain) '.mat'];
                           StateVariableNames = DSGEModel.StateVariableNames;
                           save(file,'SVEs','StateVariableNames');
                           %
                           % create a matlab file to read the data
                           %
                           mfile = strrep(strrep(strrep(strrep(file,'.mat','.m'),'-',''),SelParamStr,[int2str(sum(ScenarioParameters)) 'x' int2str(length(ScenarioParameters)-sum(ScenarioParameters))]),'StateVariableCorrDist','SVCDist');
                           fid = fopen(mfile,'wt');
                           fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                           fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                           fprintf(fid,'%%\n%% structure with fields StdKsi (mean standard deviation), CorrKsi (mean correlations), and Quantiles.\n%%\n');
                           fprintf(fid,'SVEs = DataStructure.SVEs;\n');
                           fprintf(fid,'%%\n%% string matrix with the names of the state variables\n%%\n');
                           fprintf(fid,'StateVariableNames = DataStructure.StateVariableNames;\n');
                           fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                           %
                           % end the script file
                           %
                           fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                           fclose(fid);
                           txt = ['The state variable correlation data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 2 entries: SVEs (a structure with the mean of the' MeanStr ' standard deviation, the correlations, and quantile data), and StateVariableNames (string matrix with the names of the state variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                           About(txt,'information','State Variable Correlation Distribution',200,500,CurrINI);
                        end;
                        %
                        % print the results to text file
                        %
                        if NumPredPaths==0;
                           file = [DSGEModel.OutputDirectory '\StateVariableCorrDist-' strrep(num2str(ScenarioParameters),' ','') '-' int2str(UsedDraws) '-' int2str(NumDraws) '-' int2str(CurrChain) '.txt'];
                        else;
                           file = [DSGEModel.OutputDirectory '\StateVariableCorrDist-' strrep(num2str(ScenarioParameters),' ','') '-' int2str(UsedDraws) '-' int2str(NumDraws) '-' int2str(CurrChain) '-' int2str(NumPredPaths) '.txt'];
                        end;
                        %
                        PrintStateVarDistribution(file,SVEs,DSGEModel,CurrINI,1,UsedDraws,NumDraws,CurrChain,NumPredPaths);
                        %
                        % display the results
                        %
                        if FileExist(file)==1;
                           TextGUI(file,['State Variable Correlation Distributions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Correlation Distributions',50,CurrINI,1,1);
                        end;
                     end;
                  elseif isempty(positions)==1;
                     txt = 'You didn''t select any parameters that should be varied for the estimation of the state variable correlation distribution.';
                     About(txt,'information','State Variable Correlation Distribution',150,500,CurrINI);
                  end;
                  %
                  % clear everything
                  %
                  clear('thetaPostSample');
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'sv_dist'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            ParameterNames = ModeData.ParameterNames.estimated;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','State Variable Distribution','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check which draws we should use
                  %
                  UseDraws = KeepPosteriorDraws(DSGEModel,controls.posterior.usepostdraws,NumDraws);
                  if length(UseDraws)<NumDraws;
                     thetaPostSample = thetaPostSample(UseDraws,:);
                     UsedDraws = length(UseDraws);
                  else;
                     UsedDraws = NumDraws;
                  end;
                  %
                  % check which parameters should be changed
                  %
                  if (isempty(DSGEModel.ScenarioParameters)==1)|(length(DSGEModel.ScenarioParameters)~=length(theta));
                     ScenarioParameters = ones(1,length(theta));
                  else;
                     ScenarioParameters = DSGEModel.ScenarioParameters;
                  end;
                  positions = ScenarioParameters .* (1:length(theta));
                  %
                  % remove all zeros from positions
                  %
                  positions = positions(positions>0);
                  %
                  [PosAction,positions] = SelectCondVarShockDLG('init','State Variable Distribution','Parameters For',ParameterNames,positions,CurrINI);
                  if (strcmp(lower(PosAction),'ok')==1)&(isempty(positions)==0);
                     %
                     % rewrite positions into DSGEModel.ScenarioParameters
                     %
                     ScenarioParameters = zeros(1,length(theta));
                     ScenarioParameters(positions) = ones(1,length(positions));
                     %
                     % First we check if the calculations have already been performed
                     %
                     if SVEExist(DSGEModel,ScenarioParameters,UsedDraws,NumDraws,CurrChain,0)==1;
                        txt = 'YADA has located results for the state variables on disk. Would you like to use these results?';
                        answer = Query(txt,'information',150,'State Variable Distribution',450,'no',CurrINI);
                     else;
                        answer = 'No';
                     end;
                     if strcmp(lower(answer),'yes')==1;
                        DoneCalc = 1;
                     else;
                        %
                        % start estimation
                        %
                        DoneCalc = DSGEStateVariableEstimation(theta,thetaPostSample,thetaPositions,ModelParameters,ScenarioParameters,'State Variable',NumDraws,CurrChain,DSGEModel,CurrINI);
                     end;
                     %
                     % check if we should show any results
                     %
                     if DoneCalc==1;
                        %
                        % compute the distribution for the state variables
                        %
                        SVEs = DSGESVEDistribution(DSGEModel,CurrINI,2,ScenarioParameters,UsedDraws,NumDraws,CurrChain);
                        %
                        % ask if we should save results to disk
                        %
                        txt = 'Would you like to save the mean and quantiles of the state variable distributions to file?';
                        answer = Query(txt,'question',140,'Save - State Variable Distribution',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           SelParamStr = strrep(num2str(ScenarioParameters),' ','');
                           file = [DSGEModel.OutputDirectory '\StateVariableDist-' SelParamStr '-' int2str(UsedDraws) '-' int2str(NumDraws) '-' int2str(CurrChain) '.mat'];
                           StateVariableNames = DSGEModel.StateVariableNames;
                           save(file,'SVEs','StateVariableNames');
                           %
                           % create a matlab file to read the data
                           %
                           mfile = strrep(strrep(strrep(strrep(file,'.mat','.m'),'-',''),SelParamStr,[int2str(sum(ScenarioParameters)) 'x' int2str(length(ScenarioParameters)-sum(ScenarioParameters))]),'StateVariableDist','SVDist');
                           fid = fopen(mfile,'wt');
                           fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                           fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                           fprintf(fid,'%%\n%% structure with fields KsitT (smooth mean), Ksitt (update mean), Ksitt1 (forecast mean), Quantiles, and DateVector.\n%%\n');
                           fprintf(fid,'SVEs = DataStructure.SVEs;\n');
                           fprintf(fid,'%%\n%% string matrix with the names of the state variables\n%%\n');
                           fprintf(fid,'StateVariableNames = DataStructure.StateVariableNames;\n');
                           fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                           %
                           % end the script file
                           %
                           fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                           fclose(fid);
                           txt = ['The state variables data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 2 entries: SVEs (a structure with the mean for the forecast, the update and the smooth estimators, quantile data, and numeric dates), and StateVariableNames (string matrix with the names of the state variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                           About(txt,'information','State Variable Distribution',200,500,CurrINI);
                        end;
                        %
                        % display the results
                        %
                        StateVarDistributionDLG('init',SVEs,2,DSGEModel,CurrINI);
                     end;
                  elseif isempty(positions)==1;
                     txt = 'You didn''t select any parameters that should be varied for the estimation of the state variable distribution.';
                     About(txt,'information','State Variable Distribution',150,500,CurrINI);
                  end;
                  %
                  % clear everything
                  %
                  clear('thetaPostSample');
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'sscorr_dist'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            ParameterNames = ModeData.ParameterNames.estimated;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','State Shock Correlation Distribution','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check which draws we should use
                  %
                  UseDraws = KeepPosteriorDraws(DSGEModel,controls.posterior.usepostdraws,NumDraws);
                  if length(UseDraws)<NumDraws;
                     thetaPostSample = thetaPostSample(UseDraws,:);
                     UsedDraws = length(UseDraws);
                  else;
                     UsedDraws = NumDraws;
                  end;
                  %
                  % check which parameters should be changed
                  %
                  if (isempty(DSGEModel.ScenarioParameters)==1)|(length(DSGEModel.ScenarioParameters)~=length(theta));
                     ScenarioParameters = ones(1,length(theta));
                  else;
                     ScenarioParameters = DSGEModel.ScenarioParameters;
                  end;
                  positions = ScenarioParameters .* (1:length(theta));
                  %
                  % remove all zeros from positions
                  %
                  positions = positions(positions>0);
                  %
                  [PosAction,positions] = SelectCondVarShockDLG('init','State Shock Correlation Distribution','Parameters For',ParameterNames,positions,CurrINI);
                  if (strcmp(lower(PosAction),'ok')==1)&(isempty(positions)==0);
                     %
                     % rewrite positions into DSGEModel.ScenarioParameters
                     %
                     ScenarioParameters = zeros(1,length(theta));
                     ScenarioParameters(positions) = ones(1,length(positions));
                     %
                     % First we check if the calculations have already been performed
                     %
                     if SVEExist(DSGEModel,ScenarioParameters,UsedDraws,NumDraws,CurrChain,0)==1;
                        txt = 'YADA has located results for the state shock correlations on disk. Would you like to use these results?';
                        answer = Query(txt,'information',150,'State Shock Correlation Distribution',450,'no',CurrINI);
                     else;
                        answer = 'No';
                     end;
                     if strcmp(lower(answer),'yes')==1;
                        DoneCalc = 1;
                     else;
                        %
                        % start estimation
                        %
                        DoneCalc = DSGEStateVariableEstimation(theta,thetaPostSample,thetaPositions,ModelParameters,ScenarioParameters,'State Shock Correlation',NumDraws,CurrChain,DSGEModel,CurrINI);
                     end;
                     %
                     % check if we should show any results
                     %
                     if DoneCalc==1;
                        %
                        % compute the distribution for the state shock correlations
                        %
                        SVEs = DSGESVEDistribution(DSGEModel,CurrINI,7,ScenarioParameters,UsedDraws,NumDraws,CurrChain);
                        %
                        % ask if we should save results to disk
                        %
                        txt = 'Would you like to save the mean and quantiles of the state shock correlation distributions to file?';
                        answer = Query(txt,'question',140,'Save - State Shock Correlation Distribution',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           SelParamStr = strrep(num2str(ScenarioParameters),' ','');
                           file = [DSGEModel.OutputDirectory '\StateShockCorrDist-' SelParamStr '-' int2str(UsedDraws) '-' int2str(NumDraws) '-' int2str(CurrChain) '.mat'];
                           save(file,'SVEs');
                           %
                           % create a matlab file to read the data
                           %
                           mfile = strrep(strrep(strrep(strrep(file,'.mat','.m'),'-',''),SelParamStr,[int2str(sum(ScenarioParameters)) 'x' int2str(length(ScenarioParameters)-sum(ScenarioParameters))]),'StateShockCorrDist','SSCDist');
                           fid = fopen(mfile,'wt');
                           fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                           fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                           fprintf(fid,'%%\n%% structure with fields Meaneta (mean), Stdeta (standard deviation), Correta (matrix with correlations), Quantiles, and ShockNames.\n%%\n');
                           fprintf(fid,'SVEs = DataStructure.SVEs;\n');
                           fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                           %
                           % end the script file
                           %
                           fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                           fclose(fid);
                           txt = ['The state shock data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 1 entry: SVEs (a structure with the average shocks, standard deviation, correlations, quantile data, and names of shocks). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                           About(txt,'information','State Shock Correlation Distribution',200,500,CurrINI);
                        end;
                        %
                        % print the results to text file
                        %
                        file = [DSGEModel.OutputDirectory '\StateShockCorrDist-' strrep(num2str(ScenarioParameters),' ','') '-' int2str(UsedDraws) '-' int2str(NumDraws) '-' int2str(CurrChain) '.txt'];
                        %
                        PrintStateVarDistribution(file,SVEs,DSGEModel,CurrINI,2,UsedDraws,NumDraws,CurrChain,0);
                        %
                        % display the results
                        %
                        if FileExist(file)==1;
                           TextGUI(file,['State Shock Correlation Distributions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Correlation Distributions',50,CurrINI,1,1);
                        end;
                     end;
                  elseif isempty(positions)==1;
                     txt = 'You didn''t select any parameters that should be varied for the estimation of the state shock distribution.';
                     About(txt,'information','State Shock Correlation Distribution',150,500,CurrINI);
                  end;
                  %
                  % clear everything
                  %
                  clear('thetaPostSample');
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'ss_dist'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            ParameterNames = ModeData.ParameterNames.estimated;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','State Shock Distribution','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check which draws we should use
                  %
                  UseDraws = KeepPosteriorDraws(DSGEModel,controls.posterior.usepostdraws,NumDraws);
                  if length(UseDraws)<NumDraws;
                     thetaPostSample = thetaPostSample(UseDraws,:);
                     UsedDraws = length(UseDraws);
                  else;
                     UsedDraws = NumDraws;
                  end;
                  %
                  % check which parameters should be changed
                  %
                  if (isempty(DSGEModel.ScenarioParameters)==1)|(length(DSGEModel.ScenarioParameters)~=length(theta));
                     ScenarioParameters = ones(1,length(theta));
                  else;
                     ScenarioParameters = DSGEModel.ScenarioParameters;
                  end;
                  positions = ScenarioParameters .* (1:length(theta));
                  %
                  % remove all zeros from positions
                  %
                  positions = positions(positions>0);
                  %
                  [PosAction,positions] = SelectCondVarShockDLG('init','State Shock Distribution','Parameters For',ParameterNames,positions,CurrINI);
                  if (strcmp(lower(PosAction),'ok')==1)&(isempty(positions)==0);
                     %
                     % rewrite positions into DSGEModel.ScenarioParameters
                     %
                     ScenarioParameters = zeros(1,length(theta));
                     ScenarioParameters(positions) = ones(1,length(positions));
                     %
                     % First we check if the calculations have already been performed
                     %
                     if SVEExist(DSGEModel,ScenarioParameters,UsedDraws,NumDraws,CurrChain,0)==1;
                        txt = 'YADA has located results for the state shocks on disk. Would you like to use these results?';
                        answer = Query(txt,'information',150,'State Shock Distribution',450,'no',CurrINI);
                     else;
                        answer = 'No';
                     end;
                     if strcmp(lower(answer),'yes')==1;
                        DoneCalc = 1;
                     else;
                        %
                        % start estimation
                        %
                        DoneCalc = DSGEStateVariableEstimation(theta,thetaPostSample,thetaPositions,ModelParameters,ScenarioParameters,'State Shock',NumDraws,CurrChain,DSGEModel,CurrINI);
                     end;
                     %
                     % check if we should show any results
                     %
                     if DoneCalc==1;
                        %
                        % compute the distribution for the state shocks
                        %
                        SVEs = DSGESVEDistribution(DSGEModel,CurrINI,3,ScenarioParameters,UsedDraws,NumDraws,CurrChain);
                        %
                        % ask if we should save results to disk
                        %
                        txt = 'Would you like to save the mean and quantiles of the state shock distributions to file?';
                        answer = Query(txt,'question',140,'Save - State Shock Distribution',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           SelParamStr = strrep(num2str(ScenarioParameters),' ','');
                           file = [DSGEModel.OutputDirectory '\StateShockDist-' SelParamStr '-' int2str(UsedDraws) '-' int2str(NumDraws) '-' int2str(CurrChain) '.mat'];
                           save(file,'SVEs');
                           %
                           % create a matlab file to read the data
                           %
                           mfile = strrep(strrep(strrep(strrep(file,'.mat','.m'),'-',''),SelParamStr,[int2str(sum(ScenarioParameters)) 'x' int2str(length(ScenarioParameters)-sum(ScenarioParameters))]),'StateShockDist','SSDist');
                           fid = fopen(mfile,'wt');
                           fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                           fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                           fprintf(fid,'%%\n%% structure with fields etatT (smooth mean), etatt (update mean), Quantiles, DateVector and ShockNames.\n%%\n');
                           fprintf(fid,'SVEs = DataStructure.SVEs;\n');
                           fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                           %
                           % end the script file
                           %
                           fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                           fclose(fid);
                           txt = ['The state shock data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 1 entry: SVEs (a structure with the mean for the smooth and the update estimators, quantile data, names of shocks, and numeric dates). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                           About(txt,'information','State Shock Distribution',200,500,CurrINI);
                        end;
                        %
                        % display the results
                        %
                        StateVarDistributionDLG('init',SVEs,3,DSGEModel,CurrINI);
                     end;
                  elseif isempty(positions)==1;
                     txt = 'You didn''t select any parameters that should be varied for the estimation of the state shock distribution.';
                     About(txt,'information','State Shock Distribution',150,500,CurrINI);
                  end;
                  %
                  % clear everything
                  %
                  clear('thetaPostSample');
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'mecorr_dist'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            ParameterNames = ModeData.ParameterNames.estimated;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Measurement Error Correlation Distribution','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check which draws we should use
                  %
                  UseDraws = KeepPosteriorDraws(DSGEModel,controls.posterior.usepostdraws,NumDraws);
                  if length(UseDraws)<NumDraws;
                     thetaPostSample = thetaPostSample(UseDraws,:);
                     UsedDraws = length(UseDraws);
                  else;
                     UsedDraws = NumDraws;
                  end;
                  %
                  % check which parameters should be changed
                  %
                  if (isempty(DSGEModel.ScenarioParameters)==1)|(length(DSGEModel.ScenarioParameters)~=length(theta));
                     ScenarioParameters = ones(1,length(theta));
                  else;
                     ScenarioParameters = DSGEModel.ScenarioParameters;
                  end;
                  positions = ScenarioParameters .* (1:length(theta));
                  %
                  % remove all zeros from positions
                  %
                  positions = positions(positions>0);
                  %
                  [PosAction,positions] = SelectCondVarShockDLG('init','Measurement Error Distribution','Parameters For',ParameterNames,positions,CurrINI);
                  if (strcmp(lower(PosAction),'ok')==1)&(isempty(positions)==0);
                     %
                     % rewrite positions into DSGEModel.ScenarioParameters
                     %
                     ScenarioParameters = zeros(1,length(theta));
                     ScenarioParameters(positions) = ones(1,length(positions));
                     %
                     % First we check if the calculations have already been performed
                     %
                     [Stat,MeasurementErrorStatus] = SVEExist(DSGEModel,ScenarioParameters,UsedDraws,NumDraws,CurrChain,0);
                     if (Stat==1)&(MeasurementErrorStatus==1);
                        txt = 'YADA has located results for the measurement errors on disk. Would you like to use these results?';
                        answer = Query(txt,'information',150,'Measurement Error Correlation Distribution',450,'no',CurrINI);
                        DoCalc = 1;
                     elseif (Stat==1)&(MeasurementErrorStatus==0);
                        txt = ['The DSGE model "' DSGEModel.NameOfModel '" doesn''t have any measurement errors.'];
                        About(txt,'information','Measurement Error Correlation Distribution',180,500,CurrINI);
                        DoCalc = 0;
                     else;
                        answer = 'No';
                        DoCalc = 1;
                     end;
                     %
                     %
                     if DoCalc==1;
                        if strcmp(lower(answer),'yes')==1;
                           DoneCalc = 1;
                        else;
                           %
                           % start estimation
                           %
                           DoneCalc = DSGEStateVariableEstimation(theta,thetaPostSample,thetaPositions,ModelParameters,ScenarioParameters,'Measurement Error Correlation',NumDraws,CurrChain,DSGEModel,CurrINI);
                        end;
                        %
                        % check if we should show any results
                        %
                        if DoneCalc==1;
                           %
                           % compute the distribution for measurement error correlations
                           %
                           SVEs = DSGESVEDistribution(DSGEModel,CurrINI,8,ScenarioParameters,UsedDraws,NumDraws,CurrChain);
                           %
                           % ask if we should save results to disk
                           %
                           txt = 'Would you like to save the mean and quantiles of the measurement error correlation distributions to file?';
                           answer = Query(txt,'question',140,'Save - Measurement Error Correlation Distribution',500,'no',CurrINI);
                           if strcmp(lower(answer),'yes')==1;
                              SelParamStr = strrep(num2str(ScenarioParameters),' ','');
                              file = [DSGEModel.OutputDirectory '\MeasurementErrorCorrDist-' SelParamStr '-' int2str(UsedDraws) '-' int2str(NumDraws) '-' int2str(CurrChain) '.mat'];
                              VariableNames = DSGEModel.VariableNames;
                              save(file,'SVEs','VariableNames');
                              %
                              % create a matlab file to read the data
                              %
                              mfile = strrep(strrep(strrep(strrep(file,'.mat','.m'),'-',''),SelParamStr,[int2str(sum(ScenarioParameters)) 'x' int2str(length(ScenarioParameters)-sum(ScenarioParameters))]),'MeasurementErrorCorrDist','MECDist');
                              fid = fopen(mfile,'wt');
                              fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                              fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                              fprintf(fid,'%%\n%% structure with fields Meanw (mean), Stdw (standard deviation), Corrw (matrix with correlations), and ErrorIndicator.\n%%\n');
                              fprintf(fid,'SVEs = DataStructure.SVEs;\n');
                              fprintf(fid,'%%\n%% string matrix with the names of the variables\n%%\n');
                              fprintf(fid,'VariableNames = DataStructure.VariableNames;\n');
                              fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                              %
                              % end the script file
                              %
                              fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                              fclose(fid);
                              txt = ['The measurement error correlation data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 2 entries: SVEs (a structure with the average measurement error, standard deviation, correlations, quantile data, and an indicator which functions have non-zero measurement errors), and VariableNames (string matrix with the names of the observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                              About(txt,'information','Measurement Error Correlation Distribution',200,500,CurrINI);
                           end;
                           %
                           % print the results to text file
                           %
                           file = [DSGEModel.OutputDirectory '\MeasurementErrorCorrDist-' strrep(num2str(ScenarioParameters),' ','') '-' int2str(UsedDraws) '-' int2str(NumDraws) '-' int2str(CurrChain) '.txt'];
                           %
                           PrintStateVarDistribution(file,SVEs,DSGEModel,CurrINI,3,UsedDraws,NumDraws,CurrChain,0);
                           %
                           % display the results
                           %
                           if FileExist(file)==1;
                              TextGUI(file,['Measurement Error Correlation Distributions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Correlation Distributions',50,CurrINI,1,1);
                           end;
                        end;
                     end;
                  elseif isempty(positions)==1;
                     txt = 'You didn''t select any parameters that should be varied for the estimation of the measurement error correlation distribution.';
                     About(txt,'information','Measurement Error Correlation Distribution',150,500,CurrINI);
                  end;
                  %
                  % clear everything
                  %
                  clear('thetaPostSample');
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'me_dist'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            ParameterNames = ModeData.ParameterNames.estimated;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Measurement Error Distribution','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check which draws we should use
                  %
                  UseDraws = KeepPosteriorDraws(DSGEModel,controls.posterior.usepostdraws,NumDraws);
                  if length(UseDraws)<NumDraws;
                     thetaPostSample = thetaPostSample(UseDraws,:);
                     UsedDraws = length(UseDraws);
                  else;
                     UsedDraws = NumDraws;
                  end;
                  %
                  % check which parameters should be changed
                  %
                  if (isempty(DSGEModel.ScenarioParameters)==1)|(length(DSGEModel.ScenarioParameters)~=length(theta));
                     ScenarioParameters = ones(1,length(theta));
                  else;
                     ScenarioParameters = DSGEModel.ScenarioParameters;
                  end;
                  positions = ScenarioParameters .* (1:length(theta));
                  %
                  % remove all zeros from positions
                  %
                  positions = positions(positions>0);
                  %
                  [PosAction,positions] = SelectCondVarShockDLG('init','Measurement Error Distribution','Parameters For',ParameterNames,positions,CurrINI);
                  if (strcmp(lower(PosAction),'ok')==1)&(isempty(positions)==0);
                     %
                     % rewrite positions into DSGEModel.ScenarioParameters
                     %
                     ScenarioParameters = zeros(1,length(theta));
                     ScenarioParameters(positions) = ones(1,length(positions));
                     %
                     % First we check if the calculations have already been performed
                     %
                     [Stat,MeasurementErrorStatus] = SVEExist(DSGEModel,ScenarioParameters,UsedDraws,NumDraws,CurrChain,0);
                     if (Stat==1)&(MeasurementErrorStatus==1);
                        txt = 'YADA has located results for the measurement errors on disk. Would you like to use these results?';
                        answer = Query(txt,'information',150,'Measurement Error Distribution',450,'no',CurrINI);
                        DoCalc = 1;
                     elseif (Stat==1)&(MeasurementErrorStatus==0);
                        txt = ['The DSGE model "' DSGEModel.NameOfModel '" doesn''t have any measurement errors.'];
                        About(txt,'information','Measurement Error Distribution',180,500,CurrINI);
                        DoCalc = 0;
                     else;
                        answer = 'No';
                        DoCalc = 1;
                     end;
                     %
                     if DoCalc==1;
                        if strcmp(lower(answer),'yes')==1;
                           DoneCalc = 1;
                        else;
                           %
                           % start estimation
                           %
                           DoneCalc = DSGEStateVariableEstimation(theta,thetaPostSample,thetaPositions,ModelParameters,ScenarioParameters,'Measurement Error',NumDraws,CurrChain,DSGEModel,CurrINI);
                        end;
                        %
                        % check if we should show any results
                        %
                        if DoneCalc==1;
                           %
                           % compute the distribution for measurement errors
                           %
                           SVEs = DSGESVEDistribution(DSGEModel,CurrINI,4,ScenarioParameters,UsedDraws,NumDraws,CurrChain);
                           %
                           % ask if we should save results to disk
                           %
                           txt = 'Would you like to save the mean and quantiles of the measurement error distributions to file?';
                           answer = Query(txt,'question',140,'Save - Measurement Error Distribution',500,'no',CurrINI);
                           if strcmp(lower(answer),'yes')==1;
                              SelParamStr = strrep(num2str(ScenarioParameters),' ','');
                              file = [DSGEModel.OutputDirectory '\MeasurementErrorDist-' SelParamStr '-' int2str(UsedDraws) '-' int2str(NumDraws) '-' int2str(CurrChain) '.mat'];
                              VariableNames = DSGEModel.VariableNames;
                              save(file,'SVEs','VariableNames');
                              %
                              % create a matlab file to read the data
                              %
                              mfile = strrep(strrep(strrep(strrep(file,'.mat','.m'),'-',''),SelParamStr,[int2str(sum(ScenarioParameters)) 'x' int2str(length(ScenarioParameters)-sum(ScenarioParameters))]),'MeasurementErrorDist','MEDist');
                              fid = fopen(mfile,'wt');
                              fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                              fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                              fprintf(fid,'%%\n%% structure with fields wtT (smooth mean), wtt (update mean), Quantiles, DateVector and ErrorIndicator.\n%%\n');
                              fprintf(fid,'SVEs = DataStructure.SVEs;\n');
                              fprintf(fid,'%%\n%% string matrix with the names of the variables\n%%\n');
                              fprintf(fid,'VariableNames = DataStructure.VariableNames;\n');
                              fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                              %
                              % end the script file
                              %
                              fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                              fclose(fid);
                              txt = ['The measurement error data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 2 entries: SVEs (a structure with the mean for the smooth and the update estimators, quantile data, indicator which functions have non-zero measurement errors, and numeric dates), and VariableNames (string matrix with the names of the observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                              About(txt,'information','Measurement Error Distribution',200,500,CurrINI);
                           end;
                           %
                           % display the results
                           %
                           StateVarDistributionDLG('init',SVEs,4,DSGEModel,CurrINI);
                        end;
                     end;
                  elseif isempty(positions)==1;
                     txt = 'You didn''t select any parameters that should be varied for the estimation of the measurement error distribution.';
                     About(txt,'information','Measurement Error Distribution',150,500,CurrINI);
                  end;
                  %
                  % clear everything
                  %
                  clear('thetaPostSample');
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'parameterscenarios_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view graphs of the parameter scenario before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Parameter Scenarios at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters,thetaDist,PriorDist,ParameterNames,thetaIndex,UniformBounds,LowerBound] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     thetaDist = ModeData.thetaDist;
                     PriorDist = ModeData.PriorDist;
                     ParameterNames = ModeData.ParameterNames;
                     thetaIndex = ModeData.thetaIndex;
                     UniformBounds = ModeData.UniformBounds;
                     LowerBound = ModeData.LowerBound;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%            else;
               [FirstPeriod,LastPeriod,SubSampleStrMat] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
               %
               % selection dialog for the parameters to change under the secnario
               %
               if isempty(DSGEModel.ParameterScenario)==1;
                  ParameterScenario = zeros(1,length(theta));
               else;
                  ParameterScenario = DSGEModel.ParameterScenario;
               end;
               ScenarioParams = ParameterScenario.*(1:length(theta));
               ScenarioParams = ScenarioParams(ScenarioParams>0);
               ParameterNames = ParameterNames.estimated;
               OldScenarioParams = ScenarioParams;
               [PosAction,ScenarioParams] = SelectCondVarShockDLG('init','Parameters','Scenario',ParameterNames,ScenarioParams,CurrINI);
               if strcmp(PosAction,'OK')==1;
                  if length(ScenarioParams)>0;
                     ParameterScenario = zeros(1,length(theta));
                     ParameterScenario(ScenarioParams) = 1;
                     %
                     % we have now selected at least one parameter. now we need to choose new values for these parameters
                     %
                     phi = ThetaToPhi(theta,thetaIndex,UniformBounds,LowerBound);
                     phiTest = (phi==0);
                     BaseParameterValue = PhiToTheta(1.05*(phi+((0.05/1.05)*phiTest)),thetaIndex,UniformBounds,LowerBound);
                     %
                     ParameterFile = [DSGEModel.OutputDirectory '\parameterscenario\ParameterScenarioValues-' DSGEModel.NameOfModel '-InitialValues.mat'];
                     if isequal(ScenarioParams,OldScenarioParams)==1;
                        if FileExist(ParameterFile)==1;
                           ParameterData = load(ParameterFile);
                           if isfield(ParameterData,'ParameterScenarioValues')==1;
                              ParameterScenarioValues = ParameterData.ParameterScenarioValues;
                              if size(ParameterScenarioValues)~=size(theta);
                                 ParameterScenarioValues = BaseParameterValue;
                              end;
                           else;
                              ParameterScenarioValues = BaseParameterValue;
                           end;
                        else;
                           ParameterScenarioValues = BaseParameterValue;
                        end;
                     else;
                        ParameterScenarioValues = BaseParameterValue;
                     end;
                     ParameterBounds = CreateBounds(thetaDist,LowerBound,UniformBounds);
                     %
                     % make sure that all parameter values satisfy the bounds
                     %
                     ParameterScenarioValues = CheckBounds(ParameterScenarioValues,ParameterBounds);
                     %
                     % we now have the last selected alternative values for the parameters
                     %
                     [action,NewValues] = ParameterScenarioDLG('init',theta(ScenarioParams),ParameterScenarioValues(ScenarioParams),ParameterBounds(ScenarioParams,:),ParameterNames(ScenarioParams,:),'Initial Values',CurrINI);
                     if strcmp(action,'OK')==1;
                        %
                        % we have an alternative vector of values
                        %
                        ParameterScenarioValues = theta;
                        ParameterScenarioValues(ScenarioParams) = NewValues;
                        if max(abs(theta-ParameterScenarioValues))>1.0e-012;
                           %
                           % select the period when the parameters change
                           %
                           if FileExist([pwd '\addons\ovs\OVSTheta.m'])==1;
                              ParameterScenarioValue = DSGEModel.ParameterScenarioValue;
                              SubSampleStrMat = SubSampleStrMat(DSGEModel.KalmanFirstObservation:size(SubSampleStrMat,1),:);
                              %
                              % check if ParameterScenarioValue is valid
                              %
                              if size(SubSampleStrMat,1)<ParameterScenarioValue;
                                 ParameterScenarioValue = 1;
                              end;
                              [action,BreakPeriod] = SelectionDlg(SubSampleStrMat,ParameterScenarioValue,'Select scenario start period:','Parameter Scenarios','Initial Parameter Values','','',CurrINI);
                              if BreakPeriod~=ParameterScenarioValue;
                                 DSGEModel.ParameterScenarioValue = BreakPeriod;
                              end;
                           else;
                              action = 'OK';
                              BreakPeriod = 1;
                           end;
                           if strcmp(lower(action),'ok')==1;
                              %
                              % we can now try to solve the model for these two parameters values and check
                              % the impact th new values has on the data (assuming the shocks are unaffected).
                              %
                              [Status,Y,YScenario,OriginalShocks,ScenarioShocks,OriginalStates,ScenarioStates,KeepShocks] = DSGEParameterScenariosTheta(DSGEModel,theta,ParameterScenarioValues,thetaPositions,ModelParameters,FirstPeriod,LastPeriod,BreakPeriod,0,CurrINI);
                              if Status==1;
                                 %
                                 % we first save the changes to both the DSGEModel structure and the parameter scenario data
                                 %
                                 DSGEModel.ParameterScenario = ParameterScenario;
                                 if DirExist([DSGEModel.OutputDirectory '\parameterscenario'])==0;
                                    stat = MakeDir(DSGEModel.OutputDirectory,'parameterscenario');
                                 end;
                                 save(ParameterFile,'ParameterScenarioValues');
                                 %
                                 % check
                                 %
                                 if (FileExist([pwd '\addons\ovs\OVSTheta.m'])==1)&(BreakPeriod>=2)&(CheckScenarioData(DSGEModel)==1);
                                    [Status,YScenario,ScenarioShocks,ScenarioStates] = OVSTheta(YScenario,ScenarioShocks,ScenarioStates,ParameterScenarioValues,thetaPositions,ModelParameters,1,FirstPeriod,LastPeriod,BreakPeriod,'Initial Values',DSGEModel,CurrINI);
                                 else;
                                    Status = 1;
                                 end;
                                 %
                                 if Status==1;
                                    %
                                    % create additional inputs for displaying results
                                    %
                                    DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency);
                                    DateVector = DateVector(DSGEModel.KalmanFirstObservation:length(DateVector));
                                    ShockNames = DSGEModel.StateShockNames(KeepShocks,:);
                                    %
                                    if gcbo==controls.ps.initialvalues;
                                       AnnualizeData = 0;
                                       AnnualStr = 'Original';
                                    else;
                                       AnnualizeData = 1;
                                       AnnualStr = 'Annualized';
                                       Y = Annualize(Y,DSGEModel.annual,DSGEModel.annualscale);
                                       YScenario = Annualize(YScenario,DSGEModel.annual,DSGEModel.annualscale);
                                    end;
                                    %
                                    % check if the user wants to save the results to disk
                                    %
                                    txt = 'Would you like to save the parameter scenario results at initial values to disk?';
                                    answer = Query(txt,'question',140,'Save - Parameter Scenarios',500,'no',CurrINI);
                                    OrigDateVector = DateVector;
                                    if strcmp(lower(answer),'yes')==1;
                                       ShockDateVector = DateVector;
                                       YNames = DSGEModel.VariableNames;
                                       StateVariableNames = DSGEModel.StateVariableNames;
                                       OriginalTheta = theta;
                                       ParameterScenarioTheta = ParameterScenarioValues;
                                       if AnnualizeData==0;
                                          file = [DSGEModel.OutputDirectory '\ParameterScenario-Original-' int2str(length(ScenarioParams)) '-InitialValues.mat'];
                                          mfile = [DSGEModel.OutputDirectory '\ParaScenOrig' int2str(length(ScenarioParams)) 'InitVal.m'];
                                       else;
                                          DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                                          file = [DSGEModel.OutputDirectory '\ParameterScenario-Annual-' int2str(length(ScenarioParams)) '-InitialValues.mat'];
                                          mfile = [DSGEModel.OutputDirectory '\ParaScenAnn' int2str(length(ScenarioParams)) 'InitVal.m'];
                                       end;
                                       %
                                       if FileExist([pwd '\addons\ovs\OVSTheta.m'])==1;
                                          save(file,'ParameterNames','OriginalTheta','ParameterScenarioTheta','YNames','Y','YScenario','DateVector','ShockNames','OriginalShocks','ScenarioShocks','StateVariableNames','OriginalStates','ScenarioStates','ShockDateVector','BreakPeriod');
                                       else;
                                          save(file,'ParameterNames','OriginalTheta','ParameterScenarioTheta','YNames','Y','YScenario','DateVector','ShockNames','OriginalShocks','ScenarioShocks','StateVariableNames','OriginalStates','ScenarioStates','ShockDateVector');
                                       end;
                                       %
                                       % create the m-file to access the data from
                                       %
                                       fid = fopen(mfile,'wt');
                                       fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                                       fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                                       fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                                       fprintf(fid,'YNames = DataStructure.YNames;\n');
                                       fprintf(fid,'%%\n%% matrix with data for the observed variables\n%%\n');
                                       fprintf(fid,'Y = DataStructure.Y;\n');
                                       fprintf(fid,'%%\n%% The observed variables for unchanged economic shocks but with scenario parameters\n%%\n');
                                       fprintf(fid,'YScenario = DataStructure.YScenario;\n');
                                       fprintf(fid,'%%\n%% vector of dates for the observed variables\n%%\n');
                                       fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                                       if FileExist([pwd '\addons\ovs\OVSTheta.m'])==1;
                                          fprintf(fid,'%%\n%% The position in the data when parameters change\n%%\n');
                                          fprintf(fid,'BreakPeriod = DataStructure.BreakPeriod;\n');
                                          NumEntries = '15';
                                          BreakEntry = ' BreakPeriod (position in the sample when the parameters change),';
                                       else;
                                          NumEntries = '14';
                                          BreakEntry = '';
                                       end;
                                       fprintf(fid,'%%\n%% string matrix with names of the state variables\n%%\n');
                                       fprintf(fid,'StateVariableNames = DataStructure.StateVariableNames;\n');
                                       fprintf(fid,'%%\n%% matrix with smooth estimates of the state variables using the original parameters\n%%\n');
                                       fprintf(fid,'OriginalStates = DataStructure.OriginalStates;\n');
                                       fprintf(fid,'%%\n%% matrix with state variables for the scenario parameters\n%%\n');
                                       fprintf(fid,'ScenarioStates = DataStructure.ScenarioStates;\n');
                                       fprintf(fid,'%%\n%% string matrix with names of the economic shocks\n%%\n');
                                       fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                                       fprintf(fid,'%%\n%% matrix with smooth estimates of the economic shocks using the original parameters\n%%\n');
                                       fprintf(fid,'OriginalShocks = DataStructure.OriginalShocks;\n');
                                       fprintf(fid,'%%\n%% matrix with smooth estimates of the economic shocks using the scenario parameters\n%%\n');
                                       fprintf(fid,'ScenarioShocks = DataStructure.ScenarioShocks;\n');
                                       fprintf(fid,'%%\n%% vector of dates for the estimated economic shocks\n%%\n');
                                       fprintf(fid,'ShockDateVector = DataStructure.ShockDateVector;\n');
                                       fprintf(fid,'%%\n%% string matrix with names of the estimated parameters\n%%\n');
                                       fprintf(fid,'ParameterNames = DataStructure.ParameterNames;\n');
                                       fprintf(fid,'%%\n%% vector with the original values of the parameters\n%%\n');
                                       fprintf(fid,'OriginalTheta = DataStructure.OriginalTheta;\n');
                                       fprintf(fid,'%%\n%% vector with the scenario values of the parameters\n%%\n');
                                       fprintf(fid,'ParameterScenarioTheta = DataStructure.ParameterScenarioTheta;\n');
                                       fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                                       %
                                       % end the script file
                                       %
                                       fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                                       fclose(fid);
                                       %
                                       txt = ['The parameter scenario data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 12 entries: YNames (string matrix with the names of the observed variables), Y (matrix with the observed variables), YScenario (matrix with the observed variables under the parameter scenario with unchanged shocks), DateVector (vector with dates fvor the observed variables),' BreakEntry ' StateVariableNames (string matrix with the names of the state variables), OriginalStates (matrix with smooth estimates of the states for the original parameters), ScenarioStates (matrix with state variables under the parameter scenario), ShockNames (string matrix with the names of the economic shocks), OriginalShocks (matrix with the smooth estimates of the economic shocks using the original parameters), ScenarioShocks (matrix with smooth estimates of the economic shocks using the scenario parameters), ShockDateVector (vector with dates for the shocks), ParameterNames (string matrix with the names of the parameters), OriginalTheta (vector with the original values of the parameters), and ParameterScenarioTheta (vector with the scenario values of the parameters). To access these data you may run the matlab script file "' GetFilename(mfile) '".'];
                                       About(txt,'information','Parameter Scenarios',400,500,CurrINI);
                                    end;
                                    %
                                    % time to show the results
                                    %
                                    GraphParameterScenarioDLG('init',Y,YScenario,OriginalShocks,ScenarioShocks,ShockNames,OrigDateVector,BreakPeriod,AnnualizeData,AnnualStr,'Initial Values',DSGEModel,CurrINI);
                                 end;
                              end;
                           end;
                        else;
                           txt = 'The values for all parameters under the scenario are equal to the initial parameter values. This makes the scenario pointless and YADA has therefore aborted.';
                           About(txt,'information','Parameter Scenarios - Initial Value',200,500,CurrINI);
                        end;
                     end;
                  else;
                     txt = 'You didn''t select any parameters to change for the "Parameter Scenario". This tool requires that you select at least one parameter to change.';
                     About(txt,'information','Parameter Scenarios - Initial Values',200,500,CurrINI);
                  end;
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'parameterscenarios_postmode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            phi = ModeData.phiMode;
            InverseHessian = ModeData.InverseHessian;
            UniformBounds = ModeData.UniformBounds;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            ParameterNames = ModeData.ParameterNames.estimated;
            thetaIndex = ModeData.thetaIndex;
            LowerBound = ModeData.LowerBound;
            phiFittedStd = ModeData.phiFittedStd;
            thetaDist = ModeData.thetaDist;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%            else;
               [FirstPeriod,LastPeriod,SubSampleStrMat] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % selection dialog for the parameters to change under the secnario
            %
            if isempty(DSGEModel.ParameterScenario)==1;
               ParameterScenario = zeros(1,length(theta));
            else;
               ParameterScenario = DSGEModel.ParameterScenario;
            end;
            ScenarioParams = ParameterScenario.*(1:length(theta));
            ScenarioParams = ScenarioParams(ScenarioParams>0);
            OldScenarioParams = ScenarioParams;
            [PosAction,ScenarioParams] = SelectCondVarShockDLG('init','Parameters','Scenario',ParameterNames,ScenarioParams,CurrINI);
            if strcmp(PosAction,'OK')==1;
               if length(ScenarioParams)>0;
                  ParameterScenario = zeros(1,length(theta));
                  ParameterScenario(ScenarioParams) = 1;
                  %
                  % we have now selected at least one parameter. now we need to choose new values for these parameters
                  %
                  if (DSGEModel.InverseHessianEstimator==2)&(isempty(phiFittedStd)==0);
                     BaseParameterValue = PhiToTheta(phi+phiFittedStd,thetaIndex,UniformBounds,LowerBound);
                  else;
                     BaseParameterValue = PhiToTheta(phi+sqrt(diag(InverseHessian)),thetaIndex,UniformBounds,LowerBound);
                  end;
                  %
                  % check if we have the same selected scenario params as before
                  %
                  ParameterFile = [DSGEModel.OutputDirectory '\parameterscenario\ParameterScenarioValues-' DSGEModel.NameOfModel '-PostMode.mat'];
                  if isequal(ScenarioParams,OldScenarioParams)==1;
                     if FileExist(ParameterFile)==1;
                        ParameterData = load(ParameterFile);
                        if isfield(ParameterData,'ParameterScenarioValues')==1;
                           ParameterScenarioValues = ParameterData.ParameterScenarioValues;
                           if size(ParameterScenarioValues)~=size(theta);
                              ParameterScenarioValues = BaseParameterValue;
                           end;
                        else;
                           ParameterScenarioValues = BaseParameterValue;
                        end;
                     else;
                        ParameterScenarioValues = BaseParameterValue;
                     end;
                  else;
                     ParameterScenarioValues = BaseParameterValue;
                  end;
                  ParameterBounds = CreateBounds(thetaDist,LowerBound,UniformBounds);
                  %
                  % make sure that all parameter values satisfy the bounds
                  %
                  ParameterScenarioValues = CheckBounds(ParameterScenarioValues,ParameterBounds);
                  %
                  % we now have the last selected alternative values for the parameters
                  %
                  [action,NewValues] = ParameterScenarioDLG('init',theta(ScenarioParams),ParameterScenarioValues(ScenarioParams),ParameterBounds(ScenarioParams,:),ParameterNames(ScenarioParams,:),'Posterior Mode',CurrINI);
                  if strcmp(action,'OK')==1;
                     %
                     % we have an alternative vector of values
                     %
                     ParameterScenarioValues = theta;
                     ParameterScenarioValues(ScenarioParams) = NewValues;
                     if max(abs(theta-ParameterScenarioValues))>1.0e-012;
                        %
                        % select the period when the parameters change
                        %
                        if FileExist([pwd '\addons\ovs\OVSTheta.m'])==1;
                           ParameterScenarioValue = DSGEModel.ParameterScenarioValue;
                           SubSampleStrMat = SubSampleStrMat(DSGEModel.KalmanFirstObservation:size(SubSampleStrMat,1),:);
                           %
                           % check if ParameterScenarioValue is valid
                           %
                           if size(SubSampleStrMat,1)<ParameterScenarioValue;
                              ParameterScenarioValue = 1;
                           end;
                           [action,BreakPeriod] = SelectionDlg(SubSampleStrMat,ParameterScenarioValue,'Select scenario start period:','Parameter Scenarios','Posterior Mode Parameter Values','','',CurrINI);
                           if BreakPeriod~=ParameterScenarioValue;
                              DSGEModel.ParameterScenarioValue = BreakPeriod;
                           end;
                        else;
                           action = 'OK';
                           BreakPeriod = 1;
                        end;
                        if strcmp(lower(action),'ok')==1;
                           %
                           % we can now try to solve the model for these two parameters values and check
                           % the impact th new values has on the data (assuming the shocks are unaffected).
                           %
                           [Status,Y,YScenario,OriginalShocks,ScenarioShocks,OriginalStates,ScenarioStates,KeepShocks] = DSGEParameterScenariosTheta(DSGEModel,theta,ParameterScenarioValues,thetaPositions,ModelParameters,FirstPeriod,LastPeriod,BreakPeriod,1,CurrINI);
                           if Status==1;
                              %
                              % we first save the changes to both the DSGEModel structure and the parameter scenario data
                              %
                              DSGEModel.ParameterScenario = ParameterScenario;
                              if DirExist([DSGEModel.OutputDirectory '\parameterscenario'])==0;
                                 stat = MakeDir(DSGEModel.OutputDirectory,'parameterscenario');
                              end;
                              save(ParameterFile,'ParameterScenarioValues');
                              %
                              % check
                              %
                              if (FileExist([pwd '\addons\ovs\OVSTheta.m'])==1)&(BreakPeriod>=2)&(CheckScenarioData(DSGEModel)==1);
                                 [Status,YScenario,ScenarioShocks,ScenarioStates] = OVSTheta(YScenario,ScenarioShocks,ScenarioStates,ParameterScenarioValues,thetaPositions,ModelParameters,0,FirstPeriod,LastPeriod,BreakPeriod,'Posterior Mode',DSGEModel,CurrINI);
                              else;
                                 Status = 1;
                              end;
                              %
                              if Status==1;
                                 %
                                 % create additional inputs for displaying results
                                 %
                                 DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency);
                                 DateVector = DateVector(DSGEModel.KalmanFirstObservation:length(DateVector));
                                 ShockNames = DSGEModel.StateShockNames(KeepShocks,:);
                                 %
                                 if gcbo==controls.ps.postmode;
                                    AnnualizeData = 0;
                                    AnnualStr = 'Original';
                                 else;
                                    AnnualizeData = 1;
                                    AnnualStr = 'Annualized';
                                    Y = Annualize(Y,DSGEModel.annual,DSGEModel.annualscale);
                                    YScenario = Annualize(YScenario,DSGEModel.annual,DSGEModel.annualscale);
                                 end;
                                 %
                                 % check if the user wants to save the results to disk
                                 %
                                 txt = 'Would you like to save the parameter scenario results at posterior mode to disk?';
                                 answer = Query(txt,'question',140,'Save - Parameter Scenarios',500,'no',CurrINI);
                                 OrigDateVector = DateVector;
                                 if strcmp(lower(answer),'yes')==1;
                                    ShockDateVector = DateVector;
                                    YNames = DSGEModel.VariableNames;
                                    StateVariableNames = DSGEModel.StateVariableNames;
                                    OriginalTheta = theta;
                                    ParameterScenarioTheta = ParameterScenarioValues;
                                    if AnnualizeData==0;
                                       file = [DSGEModel.OutputDirectory '\ParameterScenario-Original-' int2str(length(ScenarioParams)) '-PosteriorMode.mat'];
                                       mfile = [DSGEModel.OutputDirectory '\ParaScenOrig' int2str(length(ScenarioParams)) 'PostMode.m'];
                                    else;
                                       DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                                       file = [DSGEModel.OutputDirectory '\ParameterScenario-Annual-' int2str(length(ScenarioParams)) '-PosteriorMode.mat'];
                                       mfile = [DSGEModel.OutputDirectory '\ParaScenAnn' int2str(length(ScenarioParams)) 'PostMode.m'];
                                    end;
                                    %
                                    if FileExist([pwd '\addons\ovs\OVSTheta.m'])==1;
                                       save(file,'ParameterNames','OriginalTheta','ParameterScenarioTheta','YNames','Y','YScenario','DateVector','ShockNames','OriginalShocks','ScenarioShocks','StateVariableNames','OriginalStates','ScenarioStates','ShockDateVector','BreakPeriod');
                                    else;
                                       save(file,'ParameterNames','OriginalTheta','ParameterScenarioTheta','YNames','Y','YScenario','DateVector','ShockNames','OriginalShocks','ScenarioShocks','StateVariableNames','OriginalStates','ScenarioStates','ShockDateVector');
                                    end;
                                    %
                                    % create the m-file to access the data from
                                    %
                                    fid = fopen(mfile,'wt');
                                    fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                                    fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                                    fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                                    fprintf(fid,'YNames = DataStructure.YNames;\n');
                                    fprintf(fid,'%%\n%% matrix with data for the observed variables\n%%\n');
                                    fprintf(fid,'Y = DataStructure.Y;\n');
                                    fprintf(fid,'%%\n%% The observed variables for unchanged economic shocks but with scenario parameters\n%%\n');
                                    fprintf(fid,'YScenario = DataStructure.YScenario;\n');
                                    fprintf(fid,'%%\n%% vector of dates for the observed variables\n%%\n');
                                    fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                                    if FileExist([pwd '\addons\ovs\OVSTheta.m'])==1;
                                       fprintf(fid,'%%\n%% The position in the data when parameters change\n%%\n');
                                       fprintf(fid,'BreakPeriod = DataStructure.BreakPeriod;\n');
                                       NumEntries = '15';
                                       BreakEntry = ' BreakPeriod (position in the sample when the parameters change),';
                                    else;
                                       NumEntries = '14';
                                       BreakEntry = '';
                                    end;
                                    fprintf(fid,'%%\n%% string matrix with names of the state variables\n%%\n');
                                    fprintf(fid,'StateVariableNames = DataStructure.StateVariableNames;\n');
                                    fprintf(fid,'%%\n%% matrix with smooth estimates of the state variables using the original parameters\n%%\n');
                                    fprintf(fid,'OriginalStates = DataStructure.OriginalStates;\n');
                                    fprintf(fid,'%%\n%% matrix with state variables for the scenario parameters\n%%\n');
                                    fprintf(fid,'ScenarioStates = DataStructure.ScenarioStates;\n');
                                    fprintf(fid,'%%\n%% string matrix with names of the economic shocks\n%%\n');
                                    fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                                    fprintf(fid,'%%\n%% matrix with smooth estimates of the economic shocks using the original parameters\n%%\n');
                                    fprintf(fid,'OriginalShocks = DataStructure.OriginalShocks;\n');
                                    fprintf(fid,'%%\n%% matrix with smooth estimates of the economic shocks using the scenario parameters\n%%\n');
                                    fprintf(fid,'ScenarioShocks = DataStructure.ScenarioShocks;\n');
                                    fprintf(fid,'%%\n%% vector of dates for the estimated economic shocks\n%%\n');
                                    fprintf(fid,'ShockDateVector = DataStructure.ShockDateVector;\n');
                                    fprintf(fid,'%%\n%% string matrix with names of the estimated parameters\n%%\n');
                                    fprintf(fid,'ParameterNames = DataStructure.ParameterNames;\n');
                                    fprintf(fid,'%%\n%% vector with the original values of the parameters\n%%\n');
                                    fprintf(fid,'OriginalTheta = DataStructure.OriginalTheta;\n');
                                    fprintf(fid,'%%\n%% vector with the scenario values of the parameters\n%%\n');
                                    fprintf(fid,'ParameterScenarioTheta = DataStructure.ParameterScenarioTheta;\n');
                                    fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                                    %
                                    % end the script file
                                    %
                                    fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                                    fclose(fid);
                                    %
                                    txt = ['The parameter scenario data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains ' NumEntries ' entries: YNames (string matrix with the names of the observed variables), Y (matrix with the observed variables), YScenario (matrix with the observed variables under the parameter scenario with unchanged shocks), DateVector (vector with dates fvor the observed variables),' BreakEntry ' StateVariableNames (string matrix with the names of the state variables), OriginalStates (matrix with smooth estimates of the states for the original parameters), ScenarioStates (matrix with state variables under the parameter scenario), ShockNames (string matrix with the names of the economic shocks), OriginalShocks (matrix with the smooth estimates of the economic shocks using the original parameters), ScenarioShocks (matrix with smooth estimates of the economic shocks using the scenario parameters), ShockDateVector (vector with dates for the shocks), ParameterNames (string matrix with the names of the parameters), OriginalTheta (vector with the original values of the parameters), and ParameterScenarioTheta (vector with the scenario values of the parameters). To access these data you may run the matlab script file "' GetFilename(mfile) '".'];
                                    About(txt,'information','Parameter Scenarios',400,500,CurrINI);
                                 end;
                                 %
                                 % time to show the results
                                 %
                                 GraphParameterScenarioDLG('init',Y,YScenario,OriginalShocks,ScenarioShocks,ShockNames,OrigDateVector,BreakPeriod,AnnualizeData,AnnualStr,'Posterior Mode',DSGEModel,CurrINI);
                              end;
                           end;
                        end;
                     else;
                        txt = 'The values for all parameters under the scenario are equal to the posterior mode values. This makes the scenario pointless and YADA has therefore aborted.';
                        About(txt,'information','Parameter Scenarios - Posterior Mode',200,500,CurrINI);
                     end;
                  end;
               else;
                  txt = 'You didn''t select any parameters to change for the "Parameter Scenario". This tool requires that you select at least one parameter to change.';
                  About(txt,'information','Parameter Scenarios - Posterior Mode',200,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
%   case 'bvar_forecast_postmode'
%      if get(controls.about,'UserData')==0;
%         set(controls.about,'UserData',1);
%         %
%         % File with the data needed to calculate the impulse responses
%         %
%         drawnow;
%         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-BVAR-' DSGEModel.NameOfModel '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '.mat'];
%         ErrorStr = '';
%         try;
%            ModeData = load(ModeFile);
%         catch;
%            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
%         end;
%         if strcmp(ErrorStr,'')==1;
%            %
%            % Collect the data we need from ModeData
%            %
%            Psi = ModeData.Psi;
%            Pi = ModeData.Pi;
%            Omega = ModeData.Omega;
%%            VariableNamesBVAR = ModeData.VariableNamesBVAR;
%%            XVariableNamesBVAR = ModeData.XVariableNamesBVAR;
%            %
%            % compute multistep forecasts based on the BVAR model
%            %
%            ForecastResults = BVARMultistepForecast(Psi,Pi,Omega,DSGEModel);
%            %
%            if length(ForecastResults)>0;
%               %
%               % ask if we should save to disk
%               %
%               txt = 'Would you like to save the multistep forecasts from the Bayesian VAR at posterior mode to file?';
%               answer = Query(txt,'question',140,'Save - Multistep Forecasts',500,'no',CurrINI);
%               if strcmp(lower(answer),'yes')==1;
%                  MaxFH = CalcMaxForecastHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod);
%                  file = [DSGEModel.OutputDirectory '\MultistepForecast-BVAR-' num2str(DSGEModel.FreqParameterReest,'%0.0f') '.' num2str(MaxFH,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '-PosteriorMode.mat'];
%                  YNames = DSGEModel.VariableNames(DSGEModel.BVARY,:);
%                  save(file,'ForecastResults','YNames');
%                  %
%                  % create a matlab m-file to read the output.
%                  %
%                  mfile = [DSGEModel.OutputDirectory '\MSFBVAR' num2str(DSGEModel.FreqParameterReest,'%0.0f') num2str(MaxFH,'%0.0f') DSGEModel.SubEndYear DSGEModel.SubEndPeriod 'PostMode.m'];
%                  fid = fopen(mfile,'wt');
%                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
%                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
%                  fprintf(fid,'%%\n%% string matrix with the names of the observed variables in the BVAR\n%%\n');
%                  fprintf(fid,'YNames = DataStructure.YNames;\n');
%                  fprintf(fid,'%%\n%% Set up the vector forecast structure\n%%\n');
%                  fprintf(fid,'ForecastResults = DataStructure.ForecastResults;\n');
%                  fprintf(fid,'%%\n%% Each element of this vector structure has 12 fields:\n%%     * Yhat - forecasts\n%%     * Y - observed variables\n%%     * Error - forecast errors\n%%     * AnnY - annualized observed variables\n%%     * AnnYhat - annualized forecasts\n%%     * AnnError errors from annualized forecasts\n%%     * RMSE - Theoretical root mean square errors\n%%     * rwY - forecasts based on a random walk hypothesis\n%%     * rwError - forecast errors based on a random walk hypothesis\n%%     * AnnrwY - annualized forecasts based on a random walk hypothesis\n     * AnnrwError - errors from annualized forecasts based on a random walk hypothesisn%%     * DateVector - vector with numerical dates\n%%\ndisp(ForecastResults);\n');
%                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
%                  %
%                  % end the script file
%                  %
%                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
%                  fclose(fid);
%                  %
%                  txt = ['The multistep forecast data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 2 entries: YNames (string matrix with the names of the observed variables in the BVAR), ForecastResults (vector structure with 12 fields: YHat, Y, Error, AnnY, AnnYhat, AnnError, RMSE, rwY, rwError, AnnrwY, AnnrwError, and DateVector). To access these data you may run the matlab script file "' GetFilename(mfile) '".'];
%                  About(txt,'information','Multistep Forecasts',200,500,CurrINI);
%               end;
%               if gcbo==controls.bvarforecast.postmode;
%                  AnnualStr = 'original';
%               else;
%                  AnnualStr = 'annual';
%               end;
%               %
%               % display the results
%               %
%               MultistepForecastDLG('init',DSGEModel,CurrINI,ForecastResults,'Posterior Mode','BVAR',AnnualStr);
%            end;
%         else;
%            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
%         end;
%         set(controls.about,'UserData',0);
%      end;
   case 'bvar_predict_postmode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-BVAR-' DSGEModel.NameOfModel '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            %
            % Collect the data we need from ModeData
            %
            Psi = ModeData.Psi;
            Pi = ModeData.Pi;
            Omega = ModeData.Omega;
            [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%            DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
            %
            % check how many time periods to use for predictive distributions
            %
            [MaxPH,NumPredX] = CalcMaxPredictionHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,max(size(DSGEModel.PredictedX,2)*(isempty(DSGEModel.BVARX)==0),240*(isempty(DSGEModel.BVARX)==1)));
            %
            % matrix with exogenous variables
            %
            X = [];
            if isempty(DSGEModel.BVARX)==0;
               if NumPredX<MaxPH;
                  X = DSGEModel.X(DSGEModel.BVARX,LastPeriod+1:LastPeriod+(MaxPH-NumPredX));
               end;
               if NumPredX>0;
                  X = [X DSGEModel.PredictedX(DSGEModel.BVARX,1:NumPredX)];
               end;
            end;
            %
            % check if we should annualize or not
            %
            if gcbo==controls.bvarpredict.original_postmode;
               AnnualizeData = 0;
               AnnualStr = 'original';
            else;
               AnnualizeData = 1;
               AnnualStr = 'annual';
            end;
            %
            % determine how many prediction paths to use
            %
            NumPredPathsStr = get(controls.forecast.predpaths,'String');
            NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
            %
            % ask if we should conduct prediction event calculations
            %
            if (isfield(DSGEModel,'PredictionEvent')==0)|(isempty(DSGEModel.PredictionEvent)==1)|(size(DSGEModel.PredictionEvent,1)~=DSGEModel.n)|(size(DSGEModel.PredictionEvent,2)~=3);
               DSGEModel.PredictionEvent = [Inf*ones(DSGEModel.n,1) zeros(DSGEModel.n,1) ones(DSGEModel.n,1)];
            end;
            txt = 'Would you like YADA to calculate prediction event probabilities?';
            answer = Query(txt,'question',140,'Prediction Events',500,'no',CurrINI);
            if strcmp(lower(answer),'yes')==1;
               %
               % make sure that the prediction event length does not exceed the maximum prediction horizon
               %
               for i=1:DSGEModel.n;
                  if DSGEModel.PredictionEvent(i,3)>MaxPH;
                     DSGEModel.PredictionEvent(i,3) = MaxPH;
                  end;
               end;
               %
               % display a dialog for setting up an prediction event, but using only the selected BVAR endogenous variables
               %
               [action,PredictionEvent] = PredictionEventDLG('init',DSGEModel.VariableNames(DSGEModel.BVARY,:),DSGEModel.PredictionEvent(DSGEModel.BVARY,:),MaxPH,CurrINI);
               if strcmp(lower(action),'ok')==1;
                  DSGEModel.PredictionEvent(DSGEModel.BVARY,:) = PredictionEvent;
                  DSGEModel.RunPredictionEvent = 1;
               else;
                  DSGEModel.RunPredictionEvent = 0;
               end;
            else;
               DSGEModel.RunPredictionEvent = 0;
            end;
            %
            % we can now compute the predictive distribution for the endogenous variables
            % up to period MaxPh
            %
            if DSGEModel.RandomNumberValue==1;
               randn('state',0);
            else;
               randn('state',sum(100*clock));
            end;
            %
            % run the prediction path calculation function
            %
            [PredPaths,PredMean,PredEventData,KernelX,KernelY] = BVARPredictionPathsPostMode(Psi,Pi,Omega,DSGEModel,CurrINI,X,MaxPH,NumPredPaths,AnnualizeData);
            if isempty(PredPaths)==0;
               %
               % the computations went OK. Compute point estimates from predictive distribution and
               % quantiles
               %
               [MeanPrediction,Quantiles] = PredictionPathDistribution(PredPaths,DSGEModel.Percentiles);
               %
               % compute the mean error bias in percent
               %
               MeanErrorBias = max(max(abs((PredMean-MeanPrediction)./PredMean)));
               if DSGEModel.AdjustPredictionPaths==0;
                  %
                  % ask if the prediction distribution should be corrected
                  %
                  txt = ['The absolute mean error bias from using the simulated draws is ' num2str(MeanErrorBias,'%0.4f') ' percent relative to the theoretical mean. Would you like to adjust that predictive distribution such that it matches the theoretical mean?'];
                  answer = Query(txt,'question',140,'Mean Error Bias - Predictive Distributions',500,'yes',CurrINI);
               else;
                  answer = 'Yes';
               end;
               if strcmp(lower(answer),'yes')==1;
                  %
                  % adjust the quantiles to match
                  %
                  for i=1:length(Quantiles);
                     OlVal = Quantiles(i).Quantile;
                     Quantiles(i).Quantile = Quantiles(i).Quantile+(PredMean-MeanPrediction);
                  end;
                  MeanPrediction = PredMean;
               end;
               %
               % compute the forecast errors based on the mean predictions
               %
               PredictionErrors = CalculatePredictionErrors(MeanPrediction,AnnualizeData,0,'BVAR',DSGEModel);
               %
               % check if the user wants to save the data
               %
               txt = ['Would you like to save the predictive distributions from the Bayesian VAR for the ' AnnualStr ' data at posterior mode to file?'];
               answer = Query(txt,'question',140,'Save - Predictive Distributions',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod,PredDateVector] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,size(MeanPrediction,2));
                  file = [DSGEModel.OutputDirectory '\PredictiveDist-BVAR-' AnnualStr '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '-' num2str(MaxPH,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '-PosteriorMode.mat'];
                  YNames = DSGEModel.VariableNames(DSGEModel.BVARY,:);
                  DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,PredEndYear,PredEndPeriod,DSGEModel.DataFrequency);
                  Y = DSGEModel.Y(DSGEModel.BVARY,FirstPeriod:min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                  if length(DateVector)>size(Y,2);
                     DateVector = DateVector(1,1:size(Y,2));
                  end;
                  EstimationStartPeriod = DSGEModel.KalmanFirstObservation;
                  EstimationStartPeriodOrig = EstimationStartPeriod;
                  YOrig = Y;
                  DateVectorOrig = DateVector;
                  if AnnualizeData==1;
                     Y = Annualize(Y,DSGEModel.annual(DSGEModel.BVARY),DSGEModel.annualscale(DSGEModel.BVARY));
                     EstimationStartPeriod = max(1,EstimationStartPeriod-(length(DateVector)-size(Y,2)));
                     DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                  end;
                  if isempty(PredEventData)==1;
                     save(file,'MeanPrediction','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig');
                  else;
                     save(file,'MeanPrediction','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig','PredEventData');
                  end;
                  %
                  % create a matlab m-file to read the output.
                  %
                  mfile = [DSGEModel.OutputDirectory '\PDBVAR' AnnualStr num2str(DSGEModel.PriorType,'%0.0f') num2str(DSGEModel.OmegaPriorType,'%0.0f') num2str(MaxPH,'%0.0f') DSGEModel.SubEndYear DSGEModel.SubEndPeriod 'PostMode.m'];
                  fid = fopen(mfile,'wt');
                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                  fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                  fprintf(fid,'YNames = DataStructure.YNames;\n');
                  fprintf(fid,'%%\n%% matrix with the mean predictions of the observed variables in the BVAR\n%%\n');
                  fprintf(fid,'MeanPrediction = DataStructure.MeanPrediction;\n');
                  fprintf(fid,'%%\n%% matrix with the errors from the mean predictions of the observed variables\n%%\n');
                  fprintf(fid,'PredictionErrors = DataStructure.PredictionErrors;\n');
                  fprintf(fid,'%%\n%% vector structure with quantiles from the predictive distribution\n%% the structure has %0.0f entries with fields "Quantile" and "percent"\n%% the first field is a matrix and the second a positive number between 0 and 100\n%%\n',length(Quantiles));
                  fprintf(fid,'Quantiles = DataStructure.Quantiles;\n');
                  if isempty(KernelX)==0;
                     fprintf(fid,'%%\n%% matrix with x-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                     fprintf(fid,'KernelX = DataStructure.KernelX;\n');
                     fprintf(fid,'%%\n%% matrix with y-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                     fprintf(fid,'KernelY = DataStructure.KernelY;\n');
                     KStr = 'KernelX (matrix with x-axis for kernel density estimates of marginal predictive distribution), KernelY (matrix with y-axis values for kernel density estimates of marginal predictive distribution), ';
                     KVal = 2;
                  else;
                     KStr = '';
                     KVal = 0;
                  end;
                  fprintf(fid,'%%\n%% vector with dates for the predictions\n%%\n');
                  fprintf(fid,'PredDateVector = DataStructure.PredDateVector;\n');
                  fprintf(fid,'%%\n%% observed variables\n%%\n');
                  fprintf(fid,'Y = DataStructure.Y;\n');
                  fprintf(fid,'%%\n%% vector with dates for the observed variables\n%%\n');
                  fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                  if isempty(PredEventData)==0;
                     fprintf(fid,'%%\n%% matrix with prediction event data. First column holds the\n%% number of true events, the second the number of times below the events, and the third the number of events\n%%\n');
                     fprintf(fid,'PredEventData = DataStructure.PredEventData;\n');
                     NumEntries = int2str(8+KVal);
                     ExtraEntry = 'PredEventData (matrix with the number of true events, the number of events below the lower bound for the event, and the number of events tested in the columns), ';
                  else;
                     NumEntries = int2str(7+KVal);
                     ExtraEntry = '';
                  end;
                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                  %
                  % end the script file
                  %
                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                  fclose(fid);
                  %
                  txt = ['The predictive distributions from the Bayesian VAR have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains ' NumEntries ' entries: YNames (string matrix with the names of the observed variables), MeanPrediction (matrix with the mean predictions), PredictionErrors (matrix with errors for the mean predictions), Quantiles (vector structure with 2 fields: Quantile and percent), ' KStr 'PredDateVector (vector with dates for the predictions), Y (matrix) with the observed variables, ' ExtraEntry 'and DateVector (vector with dates for the observed variables). To access these data you may run the matlab script file "' GetFilename(mfile) '".'];
                  About(txt,'information','Predictive Distributions',400,550,CurrINI);
               end;
               if isempty(PredEventData)==0;
                  %
                  % write prediction event results to file
                  %
                  file = [DSGEModel.OutputDirectory '\PredictiveDist-BVAR-' AnnualStr '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '-' num2str(MaxPH,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '-PosteriorMode.txt'];
                  [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,MaxPH);
                  PrintPredictionEvent(file,DSGEModel.VariableNames(DSGEModel.BVARY,:),PredEventData,[],DSGEModel.PredictionEvent(DSGEModel.BVARY,:),[PredStartYear ':' PredStartPeriod '-' PredEndYear ':' PredEndPeriod],MaxPH,NumPredPaths,1,CurrINI);
                  %
                  % displays the file if it exists
                  %
                  if FileExist(file)==1;
                     TextGUI(file,['Prediction Events - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,0);
                  end;
               end;
               %
               % Open a dialog for displaying predictive distributions
               %
               PredictiveDistributionDLG('init',DSGEModel,CurrINI,MeanPrediction,Quantiles,KernelX,KernelY,'Posterior Mode','BVAR',AnnualStr);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'bvar_predict_posterior'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Check if the data actually exists
         %
         if VerifyBVARPosteriorDraws(DSGEModel,controls)==1;
            %
            % load the data
            %
            [PsiPostSample,PiPostSample,OmegaPostSample,LogPsiDensity,LogPiDensity,NumBurnin] = LoadBVARPosteriorDraws(DSGEModel,CurrINI);
            NumDraws = length(LogPsiDensity);
            %
            % clear what is not needed
            %
            clear('LogPsiDensity','LogPiDensity');
            %
            % set up out-of-sample data for the exogenous variable
            %
            [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%            DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
            %
            % check how many time periods to use for predictive distributions
            %
            [MaxPH,NumPredX] = CalcMaxPredictionHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,max(size(DSGEModel.PredictedX,2)*(isempty(DSGEModel.BVARX)==0),240*(isempty(DSGEModel.BVARX)==1)));
            %
            % matrix with exogenous variables
            %
            X = [];
            if isempty(DSGEModel.BVARX)==0;
               if NumPredX<MaxPH;
                  X = DSGEModel.X(DSGEModel.BVARX,LastPeriod+1:LastPeriod+(MaxPH-NumPredX));
               end;
               if NumPredX>0;
                  X = [X DSGEModel.PredictedX(DSGEModel.BVARX,1:NumPredX)];
               end;
            end;
            %
            % 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;
            %
            % select which posterior draws to use
            %
            PsiPostSample = PsiPostSample(NumBurnin+1:NumDraws,:);
            PiPostSample = PiPostSample(NumBurnin+1:NumDraws,:);
            OmegaPostSample = OmegaPostSample(NumBurnin+1:NumDraws,:);
            NumDraws = NumDraws-NumBurnin;
            %
            % check how many draws we should pick among these
            %
            PostDrawsUsageStr = get(controls.posterior.postdrawsusage,'String');
            NumPostDrawsUsage = min(str2num(strrep(StringTrim(PostDrawsUsageStr(DSGEModel.PostDrawsUsageValue,:)),',','')),NumDraws);
            %
            % get the draws to use
            %
            if DSGEModel.RandomizeDraws==0;
               DrawFreq = round(NumDraws/NumPostDrawsUsage);
               SelectDraws = (1:DrawFreq:NumDraws);
               if length(SelectDraws)+1==NumPostDrawsUsage;
                  SelectDraws = [SelectDraws NumDraws];
               elseif length(SelectDraws)>NumPostDrawsUsage;
                  SelectDraws = SelectDraws(1:NumPostDrawsUsage);
               end;
               PsiPostSample = PsiPostSample(SelectDraws,:);
               PiPostSample = PiPostSample(SelectDraws,:);
               OmegaPostSample = OmegaPostSample(SelectDraws,:);
            else;
               PsiPostSample = PsiPostSample(ceil(rand(NumPostDrawsUsage,1)*NumDraws),:);
               PiPostSample = PiPostSample(ceil(rand(NumPostDrawsUsage,1)*NumDraws),:);
               OmegaPostSample = OmegaPostSample(ceil(rand(NumPostDrawsUsage,1)*NumDraws),:);
            end;
            %
            % are we using annualized data or the original
            %
            if gcbo==controls.bvarpredict.original_posterior;
               AnnualizeData = 0;
               AnnualStr = 'original';
               QueryHead = 'Predictive Distributions For Bayesian VAR - Original Data';
            else;
               AnnualizeData = 1;
               AnnualStr = 'annual';
               QueryHead = 'Predictive Distributions For Bayesian VAR - Annualized Data';
            end;
            %
            % determine how many prediction paths to use
            %
            NumPredPathsStr = get(controls.forecast.predpaths,'String');
            NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
            %
            % check if results have already been stored to disk
            %
            if BVARPredictionsExist(DSGEModel.OutputDirectory,DSGEModel.NameOfModel,DSGEModel.PriorType,DSGEModel.OmegaPriorType,MaxPH,NumPostDrawsUsage,NumPredPaths,AnnualizeData)==1;
               txt = 'YADA has located results for the predictive distribution on disk. Would you like to use these results?';
               answer = Query(txt,'information',150,QueryHead,450,'no',CurrINI);
            else;
               answer = 'No';
            end;
            if strcmp(lower(answer),'yes')==1;
               %
               % load the data from disk
               %
               [PredEventData,PredictionEvent,ShockCov,ParameterCov] = LoadBVARPredictionUncertainty(DSGEModel.OutputDirectory,DSGEModel.NameOfModel,DSGEModel.PriorType,DSGEModel.OmegaPriorType,MaxPH,NumPostDrawsUsage,NumPredPaths,AnnualizeData);
               DoneCalc = 1;
            else;
               %
               % ask if we should conduct prediction event calculations
               %
               if (isfield(DSGEModel,'PredictionEvent')==0)|(isempty(DSGEModel.PredictionEvent)==1)|(size(DSGEModel.PredictionEvent,1)~=DSGEModel.n)|(size(DSGEModel.PredictionEvent,2)~=3);
                  DSGEModel.PredictionEvent = [Inf*ones(DSGEModel.n,1) zeros(DSGEModel.n,1) ones(DSGEModel.n,1)];
               end;
               txt = 'Would you like YADA to calculate prediction event probabilities?';
               answer = Query(txt,'question',140,'Prediction Events',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  %
                  % make sure that the prediction event length does not exceed the maximum prediction horizon
                  %
                  for i=1:DSGEModel.n;
                     if DSGEModel.PredictionEvent(i,3)>MaxPH;
                        DSGEModel.PredictionEvent(i,3) = MaxPH;
                     end;
                  end;
                  %
                  % display a dialog for setting up an prediction event, but using only the selected BVAR endogenous variables
                  %
                  [action,PredictionEvent] = PredictionEventDLG('init',DSGEModel.VariableNames(DSGEModel.BVARY,:),DSGEModel.PredictionEvent(DSGEModel.BVARY,:),MaxPH,CurrINI);
                  if strcmp(lower(action),'ok')==1;
                     DSGEModel.PredictionEvent(DSGEModel.BVARY,:) = PredictionEvent;
                     DSGEModel.RunPredictionEvent = 1;
                  else;
                     DSGEModel.RunPredictionEvent = 0;
                  end;
               else;
                  DSGEModel.RunPredictionEvent = 0;
               end;
               %
               % run the prediction path calculation function
               %
               [DoneCalc,PredEventData,ShockCov,ParameterCov] = BVARPredictionPaths(PsiPostSample,PiPostSample,OmegaPostSample,DSGEModel,CurrINI,X,MaxPH,NumPredPaths,AnnualizeData);
            end;
            if DoneCalc==1;
               %
               % the computations went OK. Compute point estimates from predictive distribution and
               % quantiles
               %
               [MeanPrediction,Quantiles,KernelX,KernelY] = BVARPredictionDistribution(DSGEModel.OutputDirectory,DSGEModel.NameOfModel,DSGEModel.PriorType,DSGEModel.OmegaPriorType,MaxPH,NumPostDrawsUsage,NumPredPaths,AnnualizeData,DSGEModel.Percentiles,DSGEModel.VariableNames(DSGEModel.BVARY,:),CurrINI);
               %
               % compute the forecast errors based on the mean predictions
               %
               PredictionErrors = CalculatePredictionErrors(MeanPrediction,AnnualizeData,0,'BVAR',DSGEModel);
               %
               % check if the user wants to save the data
               %
               txt = ['Would you like to save the predictive distributions from the Bayesian VAR for the ' AnnualStr ' data to file?'];
               answer = Query(txt,'question',140,'Save - Predictive Distributions',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod,PredDateVector] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,size(MeanPrediction,2));
                  file = [DSGEModel.OutputDirectory '\PredictiveDist-BVAR-' AnnualStr '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '-' num2str(MaxPH,'%0.0f') '-' num2str(NumPostDrawsUsage,'%0.0f') '.' num2str(NumDraws,'%0.0f') '.' num2str(NumPredPaths,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '.mat'];
                  YNames = DSGEModel.VariableNames(DSGEModel.BVARY,:);
                  DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,PredEndYear,PredEndPeriod,DSGEModel.DataFrequency);
                  Y = DSGEModel.Y(DSGEModel.BVARY,FirstPeriod:min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                  if length(DateVector)>size(Y,2);
                     DateVector = DateVector(1,1:size(Y,2));
                  end;
                  EstimationStartPeriod = DSGEModel.KalmanFirstObservation;
                  EstimationStartPeriodOrig = EstimationStartPeriod;
                  YOrig = Y;
                  DateVectorOrig = DateVector;
                  if AnnualizeData==1;
                     Y = Annualize(Y,DSGEModel.annual(DSGEModel.BVARY),DSGEModel.annualscale(DSGEModel.BVARY));
                     EstimationStartPeriod = max(1,EstimationStartPeriod-(length(DateVector)-size(Y,2)));
                     DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                  end;
                  if isempty(PredEventData)==1;
                     save(file,'MeanPrediction','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig');
                  else;
                     save(file,'MeanPrediction','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig','PredictionEvent','PredEventData');
                  end;
                  %
                  % create a matlab m-file to read the output.
                  %
                  mfile = [DSGEModel.OutputDirectory '\PDBVAR' AnnualStr num2str(DSGEModel.PriorType,'%0.0f') num2str(DSGEModel.OmegaPriorType,'%0.0f') num2str(MaxPH,'%0.0f') num2str(NumPostDrawsUsage,'%0.0f') num2str(NumDraws,'%0.0f') num2str(NumPredPaths,'%0.0f') DSGEModel.SubEndYear DSGEModel.SubEndPeriod '.m'];
                  fid = fopen(mfile,'wt');
                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                  fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                  fprintf(fid,'YNames = DataStructure.YNames;\n');
                  fprintf(fid,'%%\n%% matrix with the mean predictions of the observed variables in the BVAR\n%%\n');
                  fprintf(fid,'MeanPrediction = DataStructure.MeanPrediction;\n');
                  fprintf(fid,'%%\n%% matrix with the errors from the mean predictions of the observed variables\n%%\n');
                  fprintf(fid,'PredictionErrors = DataStructure.PredictionErrors;\n');
                  fprintf(fid,'%%\n%% vector structure with quantiles from the predictive distribution\n%% the structure has %0.0f entries with fields "Quantile" and "percent"\n%% the first field is a matrix and the second a positive number between 0 and 100\n%%\n',length(Quantiles));
                  fprintf(fid,'Quantiles = DataStructure.Quantiles;\n');
                  fprintf(fid,'%%\n%% matrix with x-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                  fprintf(fid,'KernelX = DataStructure.KernelX;\n');
                  fprintf(fid,'%%\n%% matrix with y-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                  fprintf(fid,'KernelY = DataStructure.KernelY;\n');
                  fprintf(fid,'%%\n%% vector with dates for the predictions\n%%\n');
                  fprintf(fid,'PredDateVector = DataStructure.PredDateVector;\n');
                  fprintf(fid,'%%\n%% observed variables\n%%\n');
                  fprintf(fid,'Y = DataStructure.Y;\n');
                  fprintf(fid,'%%\n%% vector with dates for the observed variables\n%%\n');
                  fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                  if isempty(PredEventData)==0;
                     fprintf(fid,'%%\n%% matrix with the prediction event definitions. The first column\n%% holds the upper bound, the second column\n%% the lower bound, and third the length of the event.\n%%\n');
                     fprintf(fid,'PredictionEvent = DataStructure.PredictionEvent;\n');
                     fprintf(fid,'%%\n%% matrix with prediction event data. First column holds the\n%% number of true events, the second the number of times below the events, and the third the number of events\n%%\n');
                     fprintf(fid,'PredEventData = DataStructure.PredEventData;\n');
                     NumEntries = '11';
                     ExtraEntry = 'PredictionEvent (matrix with the upper and lower bound of the event and the length of the event), PredEventData (matrix with the number of true events, the number of events below the lower bound for the event, and the number of events tested in the columns), ';
                  else;
                     NumEntries = '9';
                     ExtraEntry = '';
                  end;
                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                  %
                  % end the script file
                  %
                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                  fclose(fid);
                  %
                  txt = ['The predictive distributions from the Bayesian VAR have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains ' NumEntries ' entries: YNames (string matrix with the names of the observed variables), MeanPrediction (matrix with the mean predictions), PredictionErrors (matrix with errors for the mean predictions), Quantiles (vector structure with 2 fields: Quantile and percent), KernelX (matrix with x-axis for kernel density estimates of marginal predictive distribution), KernelY (matrix with y-axis values for kernel density estimates of marginal predictive distribution), PredDateVector (vector with dates for the predictions), Y (matrix) with the observed variables, ' ExtraEntry 'and DateVector (vector with dates for the observed variables). To access these data you may run the matlab script file "' GetFilename(mfile) '".'];
                  About(txt,'information','Predictive Distributions',500,550,CurrINI);
               end;
               if isempty(PredEventData)==0;
                  %
                  % write prediction event results to file
                  %
                  file = [DSGEModel.OutputDirectory '\PredictiveDist-BVAR-' AnnualStr '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '-' num2str(MaxPH,'%0.0f') '-' num2str(NumPostDrawsUsage,'%0.0f') '.' num2str(NumDraws,'%0.0f') '.' num2str(NumPredPaths,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '.txt'];
                  [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,MaxPH);
                  PrintPredictionEvent(file,DSGEModel.VariableNames(DSGEModel.BVARY,:),PredEventData,[],DSGEModel.PredictionEvent(DSGEModel.BVARY,:),[PredStartYear ':' PredStartPeriod '-' PredEndYear ':' PredEndPeriod],MaxPH,NumPredPaths,1,CurrINI);
                  %
                  % displays the file if it exists
                  %
                  if FileExist(file)==1;
                     TextGUI(file,['Prediction Events - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Distribution - Unconditional Predictions',50,CurrINI,1,0);
                  end;
               end;
               %
               % summarize the information in the uncertainty variables more conveniently
               %
               if isempty(ShockCov)==0;
                  [StateVar,ShockVar,MeasureVar,ParameterVar] = SummarizeDSGEPredictions(zeros(length(DSGEModel.BVARY),length(DSGEModel.BVARY),MaxPH),ShockCov,zeros(length(DSGEModel.BVARY),length(DSGEModel.BVARY)),ParameterCov);
                  %
                  % Open a dialog for displaying predictive distributions
                  %
                  UData.ShockVar = ShockVar;
                  UData.ParameterVar = ParameterVar;
               else;
                  UData = [];
               end;
               PredictiveDistributionDLG('init',DSGEModel,CurrINI,MeanPrediction,Quantiles,KernelX,KernelY,'','BVAR',AnnualStr,UData);
            end;
            %
            % clear everything that remains of the posterior draws
            %
            clear('PsiPostSample','PiPostSample','OmegaPostSample');
         else;
            txt = 'Some of the files for loading the posterior data for the Bayesian VAR are not available.';
            About(txt,'error','Bayesian VAR - Missing Posterior Draws',150,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'bvar_pred_event'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Check if the data actually exists
         %
         if VerifyBVARPosteriorDraws(DSGEModel,controls)==1;
            %
            % load the data
            %
            [PsiPostSample,PiPostSample,OmegaPostSample,LogPsiDensity,LogPiDensity,NumBurnin] = LoadBVARPosteriorDraws(DSGEModel,CurrINI);
            NumDraws = length(LogPsiDensity);
            %
            % clear what is not needed
            %
            clear('LogPsiDensity','LogPiDensity');
            %
            % set up out-of-sample data for the exogenous variable
            %
            [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%            DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
            %
            % check how many time periods to use for predictive distributions
            %
            [MaxPH,NumPredX] = CalcMaxPredictionHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,max(size(DSGEModel.PredictedX,2)*(isempty(DSGEModel.BVARX)==0),240*(isempty(DSGEModel.BVARX)==1)));
            %
            % matrix with exogenous variables
            %
            X = [];
            if isempty(DSGEModel.BVARX)==0;
               if NumPredX<MaxPH;
                  X = DSGEModel.X(DSGEModel.BVARX,LastPeriod+1:LastPeriod+(MaxPH-NumPredX));
               end;
               if NumPredX>0;
                  X = [X DSGEModel.PredictedX(DSGEModel.BVARX,1:NumPredX)];
               end;
            end;
            %
            % 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;
            %
            % select which posterior draws to use
            %
            PsiPostSample = PsiPostSample(NumBurnin+1:NumDraws,:);
            PiPostSample = PiPostSample(NumBurnin+1:NumDraws,:);
            OmegaPostSample = OmegaPostSample(NumBurnin+1:NumDraws,:);
            NumDraws = NumDraws-NumBurnin;
            %
            % check how many draws we should pick among these
            %
            PostDrawsUsageStr = get(controls.posterior.postdrawsusage,'String');
            NumPostDrawsUsage = min(str2num(strrep(StringTrim(PostDrawsUsageStr(DSGEModel.PostDrawsUsageValue,:)),',','')),NumDraws);
            %
            % get the draws to use
            %
            if DSGEModel.RandomizeDraws==0;
               DrawFreq = round(NumDraws/NumPostDrawsUsage);
               SelectDraws = (1:DrawFreq:NumDraws);
               if length(SelectDraws)+1==NumPostDrawsUsage;
                  SelectDraws = [SelectDraws NumDraws];
               elseif length(SelectDraws)>NumPostDrawsUsage;
                  SelectDraws = SelectDraws(1:NumPostDrawsUsage);
               end;
               PsiPostSample = PsiPostSample(SelectDraws,:);
               PiPostSample = PiPostSample(SelectDraws,:);
               OmegaPostSample = OmegaPostSample(SelectDraws,:);
            else;
               PsiPostSample = PsiPostSample(ceil(rand(NumPostDrawsUsage,1)*NumDraws),:);
               PiPostSample = PiPostSample(ceil(rand(NumPostDrawsUsage,1)*NumDraws),:);
               OmegaPostSample = OmegaPostSample(ceil(rand(NumPostDrawsUsage,1)*NumDraws),:);
            end;
            %
            % are we using annualized data or the original
            %
            if gcbo==controls.bvarpredict.original_predevent;
               AnnualizeData = 0;
               AnnualStr = 'original';
               QueryHead = 'Predictive Distributions For Bayesian VAR - Original Data';
            else;
               AnnualizeData = 1;
               AnnualStr = 'annual';
               QueryHead = 'Predictive Distributions For Bayesian VAR - Annualized Data';
            end;
            %
            % ask if we should conduct prediction event calculations
            %
            if (isfield(DSGEModel,'PredictionEvent')==0)|(isempty(DSGEModel.PredictionEvent)==1)|(size(DSGEModel.PredictionEvent,1)~=DSGEModel.n)|(size(DSGEModel.PredictionEvent,2)~=3);
               DSGEModel.PredictionEvent = [Inf*ones(DSGEModel.n,1) zeros(DSGEModel.n,1) ones(DSGEModel.n,1)];
            end;
            %
            % make sure that the prediction event length does not exceed the maximum prediction horizon
            %
            for i=1:DSGEModel.n;
               if DSGEModel.PredictionEvent(i,3)>MaxPH;
                  DSGEModel.PredictionEvent(i,3) = MaxPH;
               end;
            end;
            %
            % display a dialog for setting up an prediction event, but using only the selected BVAR endogenous variables
            %
            [action,PredictionEvent] = PredictionEventDLG('init',DSGEModel.VariableNames(DSGEModel.BVARY,:),DSGEModel.PredictionEvent(DSGEModel.BVARY,:),MaxPH,CurrINI);
            %
            % check if the cancel button was pressed or not
            %
            if strcmp(lower(action),'ok')==1;
               DSGEModel.PredictionEvent(DSGEModel.BVARY,:) = PredictionEvent;
               DSGEModel.RunPredictionEvent = 1;
               %
               % determine how many prediction paths to use
               %
               NumPredPathsStr = get(controls.forecast.predpaths,'String');
               NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
               %
               % check if results have already been stored to disk
               %
               if BVARPredictionsExist(DSGEModel.OutputDirectory,DSGEModel.NameOfModel,DSGEModel.PriorType,DSGEModel.OmegaPriorType,MaxPH,NumPostDrawsUsage,NumPredPaths,AnnualizeData)==1;
                  txt = 'YADA has located results for the predictive distribution on disk. Would you like to use these results?';
                  answer = Query(txt,'information',150,QueryHead,450,'no',CurrINI);
               else;
                  answer = 'No';
               end;
               if strcmp(lower(answer),'yes')==1;
                  %
                  % load the data from disk
                  %
                  PredEventData = LoadBVARPredictionPaths(DSGEModel.PredictionEvent(DSGEModel.BVARY,:),DSGEModel.OutputDirectory,DSGEModel.NameOfModel,DSGEModel.PriorType,DSGEModel.OmegaPriorType,MaxPH,NumPostDrawsUsage,NumPredPaths,AnnualizeData,CurrINI);
                  DoneCalc = 1;
               else;
                  %
                  % run the prediction path calculation function
                  %
                  [DoneCalc,PredEventData,ShockCov,ParameterCov] = BVARPredictionPaths(PsiPostSample,PiPostSample,OmegaPostSample,DSGEModel,CurrINI,X,MaxPH,NumPredPaths,AnnualizeData);
               end;
               if DoneCalc==1;
                  %
                  % check if summary results have previously been saved to disk
                  %
                  [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod,PredDateVector] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,MaxPH);
                  file = [DSGEModel.OutputDirectory '\PredictiveDist-BVAR-' AnnualStr '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '-' num2str(MaxPH,'%0.0f') '-' num2str(NumPostDrawsUsage,'%0.0f') '.' num2str(NumDraws,'%0.0f') '.' num2str(NumPredPaths,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '.mat'];
                  if FileExist(file)==1;
                     save(file,'PredictionEvent','PredEventData','-APPEND');
                     %
                     % create a matlab m-file to read the output.
                     %
                     mfile = [DSGEModel.OutputDirectory '\PDBVAR' AnnualStr num2str(DSGEModel.PriorType,'%0.0f') num2str(DSGEModel.OmegaPriorType,'%0.0f') num2str(MaxPH,'%0.0f') num2str(NumPostDrawsUsage,'%0.0f') num2str(NumDraws,'%0.0f') num2str(NumPredPaths,'%0.0f') DSGEModel.SubEndYear DSGEModel.SubEndPeriod '.m'];
                     fid = fopen(mfile,'wt');
                     fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                     fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                     fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                     fprintf(fid,'YNames = DataStructure.YNames;\n');
                     fprintf(fid,'%%\n%% matrix with the mean predictions of the observed variables in the BVAR\n%%\n');
                     fprintf(fid,'MeanPrediction = DataStructure.MeanPrediction;\n');
                     fprintf(fid,'%%\n%% matrix with the errors from the mean predictions of the observed variables\n%%\n');
                     fprintf(fid,'PredictionErrors = DataStructure.PredictionErrors;\n');
                     fprintf(fid,'%%\n%% vector structure with quantiles from the predictive distribution\n%% the structure has %0.0f entries with fields "Quantile" and "percent"\n%% the first field is a matrix and the second a positive number between 0 and 100\n%%\n',length(DSGEModel.Percentiles));
                     fprintf(fid,'Quantiles = DataStructure.Quantiles;\n');
                     fprintf(fid,'%%\n%% vector with dates for the predictions\n%%\n');
                     fprintf(fid,'PredDateVector = DataStructure.PredDateVector;\n');
                     fprintf(fid,'%%\n%% observed variables\n%%\n');
                     fprintf(fid,'Y = DataStructure.Y;\n');
                     fprintf(fid,'%%\n%% vector with dates for the observed variables\n%%\n');
                     fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                     fprintf(fid,'%%\n%% matrix with the prediction event definitions. The first column\n%% holds the upper bound, the second column\n%% the lower bound, and third the length of the event.\n%%\n');
                     fprintf(fid,'PredictionEvent = DataStructure.PredictionEvent;\n');
                     fprintf(fid,'%%\n%% matrix with prediction event data. First column holds the\n%% number of true events, the second the number of times below the events, and the third the number of events\n%%\n');
                     fprintf(fid,'PredEventData = DataStructure.PredEventData;\n');
                     fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                     %
                     % end the script file
                     %
                     fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                     fclose(fid);
                  end;
                  %
                  % write prediction event results to file
                  %
                  file = [DSGEModel.OutputDirectory '\PredictiveDist-BVAR-' AnnualStr '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '-' num2str(MaxPH,'%0.0f') '-' num2str(NumPostDrawsUsage,'%0.0f') '.' num2str(NumDraws,'%0.0f') '.' num2str(NumPredPaths,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '.txt'];
                  [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,MaxPH);
                  PrintPredictionEvent(file,DSGEModel.VariableNames(DSGEModel.BVARY,:),PredEventData,[],DSGEModel.PredictionEvent(DSGEModel.BVARY,:),[PredStartYear ':' PredStartPeriod '-' PredEndYear ':' PredEndPeriod],MaxPH,NumPredPaths,1,CurrINI);
                  %
                  % displays the file if it exists
                  %
                  if FileExist(file)==1;
                     TextGUI(file,['Prediction Events - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Distribution - Unconditional Predictions',50,CurrINI,1,0);
                  end;
               end;
            end;
            %
            % clear everything that remains of the posterior draws
            %
            clear('PsiPostSample','PiPostSample','OmegaPostSample');
         else;
            txt = 'Some of the files for loading the posterior data for the Bayesian VAR are not available.';
            About(txt,'error','Bayesian VAR - Missing Posterior Draws',150,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'sv_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view graphs of projections of the state variables before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Project State Variables at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
               %
               % Try to calculate state variables. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [StateVarStructure,mcode,kalmanstatus] = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
               if (mcode==1)&(kalmanstatus==0);
                  %
                  % we're OK
                  %
                  if isempty(StateVarStructure)==0;
                     %
                     % ask if we should save to disk
                     %
                     txt = 'Would you like to save estimates of the state variables at initial parameter values to file?';
                     answer = Query(txt,'question',140,'Save - State Variables',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        StateVariableForecast = StateVarStructure.Ksitt1;
                        StateVariableUpdate = StateVarStructure.Ksitt;
                        StateVariableSmooth = StateVarStructure.KsitT;
                        StateVariableNames = DSGEModel.StateVariableNames;
                        DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency);
                        if length(DateVector)>size(StateVariableForecast,2);
                           DateVector = DateVector(1,length(DateVector)-size(StateVariableForecast,2)+1:length(DateVector));
                        end;
                        file = [DSGEModel.OutputDirectory '\StateVariables-InitialValues.mat'];
                        save(file,'StateVariableForecast','StateVariableUpdate','StateVariableSmooth','StateVariableNames','DateVector');
                        %
                        % create a matlab file to read the data
                        %
                        mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'StateVariables','SV');
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% matrix with estimates of the forecasted state variables\n%%\n');
                        fprintf(fid,'StateVariableForecast = DataStructure.StateVariableForecast;\n');
                        fprintf(fid,'%%\n%% matrix with estimates of the updated state variable projections\n%%\n');
                        fprintf(fid,'StateVariableUpdate = DataStructure.StateVariableUpdate;\n');
                        fprintf(fid,'%%\n%% matrix with estimates of the smoothed state variable projections\n%%\n');
                        fprintf(fid,'StateVariableSmooth = DataStructure.StateVariableSmooth;\n');
                        fprintf(fid,'%%\n%% string matrix with the names of the state variables\n%%\n');
                        fprintf(fid,'StateVariableNames = DataStructure.StateVariableNames;\n');
                        fprintf(fid,'%%\n%% vector with the dates\n%%\n');
                        fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        txt = ['Estimates of the state variables at initial parameter values have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 5 entries: StateVariableForecast (' num2str(size(StateVariableForecast,1),'%0.0f') 'x' num2str(size(StateVariableForecast,2),'%0.0f') ' matrix with estimates of the forecasted state variables), StateVariableUpdate (' num2str(size(StateVariableForecast,1),'%0.0f') 'x' num2str(size(StateVariableForecast,2),'%0.0f') ' matrix with estimates of the updated state variable projections), StateVariableSmooth (' num2str(size(StateVariableForecast,1),'%0.0f') 'x' num2str(size(StateVariableForecast,2),'%0.0f') ' matrix with estimates of the smoothed state variable projections), StateVariableNames (string matrix with the names of the state variables), and DateVector (1x' num2str(length(DateVector),'%0.0f') ' vector with the dates). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','State Variables',200,500,CurrINI);
                     end;
                     %
                     % display the graphs
                     %
                     StateGraphDLG('init',CurrINI,DSGEModel,StateVarStructure,'Initial Values','State');
                  end;
               elseif (mcode==1)&(kalmanstatus~=0);
                  txt = 'The state variables are not stationary at the initial values.';
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               elseif 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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'sv_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % we can now compute the state variables
            %
            StateVarStructure = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
            if isempty(StateVarStructure)==0;
               %
               % ask if we should save to disk
               %
               txt = 'Would you like to save estimates of the state variables at posterior mode to file?';
               answer = Query(txt,'question',140,'Save - State Variables',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  StateVariableForecast = StateVarStructure.Ksitt1;
                  StateVariableUpdate = StateVarStructure.Ksitt;
                  StateVariableSmooth = StateVarStructure.KsitT;
                  StateVariableNames = DSGEModel.StateVariableNames;
                  DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency);
                  if length(DateVector)>size(StateVariableForecast,2);
                     DateVector = DateVector(1,length(DateVector)-size(StateVariableForecast,2)+1:length(DateVector));
                  end;
                  file = [DSGEModel.OutputDirectory '\StateVariables-PosteriorMode.mat'];
                  save(file,'StateVariableForecast','StateVariableUpdate','StateVariableSmooth','StateVariableNames','DateVector');
                  %
                  % create a matlab file to read the data
                  %
                  mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'StateVariables','SV');
                  fid = fopen(mfile,'wt');
                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                  fprintf(fid,'%%\n%% matrix with estimates of the forecasted state variables\n%%\n');
                  fprintf(fid,'StateVariableForecast = DataStructure.StateVariableForecast;\n');
                  fprintf(fid,'%%\n%% matrix with estimates of the updated state variable projections\n%%\n');
                  fprintf(fid,'StateVariableUpdate = DataStructure.StateVariableUpdate;\n');
                  fprintf(fid,'%%\n%% matrix with estimates of the smoothed state variable projections\n%%\n');
                  fprintf(fid,'StateVariableSmooth = DataStructure.StateVariableSmooth;\n');
                  fprintf(fid,'%%\n%% string matrix with the names of the state variables\n%%\n');
                  fprintf(fid,'StateVariableNames = DataStructure.StateVariableNames;\n');
                  fprintf(fid,'%%\n%% vector with the dates\n%%\n');
                  fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                  %
                  % end the script file
                  %
                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                  fclose(fid);
                  txt = ['Estimates of the state variables at posterior mode have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 5 entries: StateVariableForecast (' num2str(size(StateVariableForecast,1),'%0.0f') 'x' num2str(size(StateVariableForecast,2),'%0.0f') ' matrix with estimates of the forecasted state variables), StateVariableUpdate (' num2str(size(StateVariableForecast,1),'%0.0f') 'x' num2str(size(StateVariableForecast,2),'%0.0f') ' matrix with estimates of the updated state variable projections), StateVariableSmooth (' num2str(size(StateVariableForecast,1),'%0.0f') 'x' num2str(size(StateVariableForecast,2),'%0.0f') ' matrix with estimates of the smoothed state variable projections), StateVariableNames (string matrix with the names of the state variables), and DateVector (1x' num2str(length(DateVector),'%0.0f') ' vector with the dates). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                  About(txt,'information','State Variables',200,500,CurrINI);
               end;
               %
               % Display the graphs
               %
               StateGraphDLG('init',CurrINI,DSGEModel,StateVarStructure,'Posterior Mode','State');
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'ob_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view graphs of the forecasted observed variables before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Observed Variables Forecast at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
               %
               % Try to calculate state variables. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [StateVarStructure,mcode,kalmanstatus] = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
               if (mcode==1)&(kalmanstatus==0);
                  %
                  % we're OK
                  %
                  if isempty(StateVarStructure)==0;
                     %
                     % ask if we should save to disk
                     %
                     txt = 'Would you like to save the observed variables and 1-step ahead forecasts at initial parameter values to file?';
                     answer = Query(txt,'question',140,'Save - 1-Step Ahead Forecasts',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        Y = StateVarStructure.Y;
                        Yhat = StateVarStructure.Yhat;
                        YNames = DSGEModel.VariableNames;
                        DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency);
                        if length(DateVector)>size(Y,2);
                           DateVector = DateVector(1,length(DateVector)-length(Y)+1:length(DateVector));
                        end;
                        file = [DSGEModel.OutputDirectory '\ObsVarForecast-InitialValues.mat'];
                        save(file,'Y','Yhat','YNames','DateVector');
                        %
                        % create a matlab file to read the data
                        %
                        mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'ObsVarForecast','OVF');
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% matrix with the observed variables over the estimation sample\n%%\n');
                        fprintf(fid,'Y = DataStructure.Y;\n');
                        fprintf(fid,'%%\n%% matrix with the 1-step ahead forecasts of the observed variables\n%%\n');
                        fprintf(fid,'Yhat = DataStructure.Yhat;\n');
                        fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                        fprintf(fid,'YNames = DataStructure.YNames;\n');
                        fprintf(fid,'%%\n%% vector with the dates\n%%\n');
                        fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        txt = ['The observed variables and the 1-step ahead forecasts at initial parameter values have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 4 entries: Y (' num2str(size(Y,1),'%0.0f') 'x' num2str(size(Y,2),'%0.0f') ' matrix with the observed variables over the estimation sample), Yhat (' num2str(size(Y,1),'%0.0f') 'x' num2str(size(Y,2),'%0.0f') ' matrix with the 1-step ahead forecasts of the observed variables), YNames (string matrix with the names of the oberved variables), and DateVector (1x' num2str(length(DateVector),'%0.0f') ' vector with the dates). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','1-Step Ahead Forecasts',200,500,CurrINI);
                     end;
                     %
                     % display the graphs
                     %
                     StateGraphDLG('init',CurrINI,DSGEModel,StateVarStructure,'Initial Values','Observed');
                  end;
               elseif (mcode==1)&(kalmanstatus~=0);
                  txt = 'The state variables are not stationary at the initial values.';
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               elseif 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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'ob_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate forecasts
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % we can now compute the state variables
            %
            StateVarStructure = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
            %
            if isempty(StateVarStructure)==0;
               %
               % ask if we should save to disk
               %
               txt = 'Would you like to save the observed variables and 1-step ahead forecasts at posterior mode to file?';
               answer = Query(txt,'question',140,'Save - 1-Step Ahead Forecasts',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  Y = StateVarStructure.Y;
                  Yhat = StateVarStructure.Yhat;
                  YNames = DSGEModel.VariableNames;
                  DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency);
                  if length(DateVector)>size(Y,2);
                     DateVector = DateVector(1,length(DateVector)-size(Y,2)+1:length(DateVector));
                  end;
                  file = [DSGEModel.OutputDirectory '\ObsVarForecast-PosteriorMode.mat'];
                  save(file,'Y','Yhat','YNames','DateVector');
                  %
                  % create a matlab file to read the data
                  %
                  mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'ObsVarForecast','OVF');
                  fid = fopen(mfile,'wt');
                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                  fprintf(fid,'%%\n%% matrix with the observed variables over the estimation sample\n%%\n');
                  fprintf(fid,'Y = DataStructure.Y;\n');
                  fprintf(fid,'%%\n%% matrix with the 1-step ahead forecasts of the observed variables\n%%\n');
                  fprintf(fid,'Yhat = DataStructure.Yhat;\n');
                  fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                  fprintf(fid,'YNames = DataStructure.YNames;\n');
                  fprintf(fid,'%%\n%% vector with the dates\n%%\n');
                  fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                  %
                  % end the script file
                  %
                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                  fclose(fid);
                  txt = ['The observed variables and the 1-step ahead forecasts at posterior mode have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 4 entries: Y (' num2str(size(Y,1),'%0.0f') 'x' num2str(size(Y,2),'%0.0f') ' matrix with the observed variables over the estimation sample), Yhat (' num2str(size(Y,1),'%0.0f') 'x' num2str(size(Y,2),'%0.0f') ' matrix with the 1-step ahead forecasts of the observed variables), YNames (string matrix with the names of the observed variables), and DateVector (1x' num2str(length(DateVector),'%0.0f') ' vector with the dates). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                  About(txt,'information','1-Step Ahead Forecasts',200,500,CurrINI);
               end;
               %
               % Display the graphs
               %
               StateGraphDLG('init',CurrINI,DSGEModel,StateVarStructure,'Posterior Mode','Observed');
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'ss_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view graphs of the state shocks before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Project State Shocks at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
               %
               % Try to calculate state variables. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [StateVarStructure,mcode,kalmanstatus] = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
               if (mcode==1)&(kalmanstatus==0);
                  %
                  % we're OK
                  %
                  if (isempty(StateVarStructure)==0)&(isempty(StateVarStructure.etatT)==0);
                     %
                     % ask if we should save to disk
                     %
                     txt = 'Would you like to save the smooth and update estimates of the state shocks at initial parameter values to file?';
                     answer = Query(txt,'question',140,'Save - State Shocks',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        SmoothStateShocks = StateVarStructure.etatT;
                        UpdateStateShocks = StateVarStructure.etatt;
                        StateShockNames = DSGEModel.StateShockNames(StateVarStructure.KeepVar,:);
                        DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency);
                        if length(DateVector)>size(SmoothStateShocks,2);
                           DateVector = DateVector(1,length(DateVector)-size(SmoothStateShocks,2)+1:length(DateVector));
                        end;
                        file = [DSGEModel.OutputDirectory '\StateShocks-InitialValues.mat'];
                        save(file,'SmoothStateShocks','UpdateStateShocks','StateShockNames','DateVector');
                        %
                        % create a matlab file to read the data
                        %
                        mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'StateShocks','SS');
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% matrix with the smooth estimates of the non-zero economic shocks\n%%\n');
                        fprintf(fid,'SmoothStateShocks = DataStructure.SmoothStateShocks;\n');
                        fprintf(fid,'%%\n%% matrix with the update estimates of the non-zero economic shocks\n%%\n');
                        fprintf(fid,'UpdateStateShocks = DataStructure.UpdateStateShocks;\n');
                        fprintf(fid,'%%\n%% string matrix with the names of the non-zero economic shocks\n%%\n');
                        fprintf(fid,'StateShockNames = DataStructure.StateShockNames;\n');
                        fprintf(fid,'%%\n%% vector with the dates\n%%\n');
                        fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        txt = ['The smooth and update estimates of the state shocks at initial parameter values have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 4 entries: SmoothStateShocks and UpdateStateShocks (' num2str(size(SmoothStateShocks,1),'%0.0f') 'x' num2str(size(SmoothStateShocks,2),'%0.0f') ' matrix with the smooth and update estimates of the non-zero economic shocks), StateShockNames (string matrix with the names of the non-zero economic shocks), and DateVector (1x' num2str(length(DateVector),'%0.0f') ' vector with the dates). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','State Shocks',200,500,CurrINI);
                     end;
                     %
                     % display the graphs
                     %
                     ShockGraphDLG('init',CurrINI,DSGEModel,StateVarStructure,'Initial Values','State Shock');
                  elseif (isempty(StateVarStructure)==0)&(isempty(StateVarStructure.etatT)==1);
                     txt = 'YADA couldn''t estimate the state shocks. Please make sure that your model has state shocks!';
                     About(txt,'information','YADA - State Shocks',120,500,CurrINI);
                  end;
               elseif (mcode==1)&(kalmanstatus~=0);
                  txt = 'The state variables are not stationary at the initial values.';
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               elseif 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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'ss_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % we can now calculate the state shocks
            %
            StateVarStructure = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
            if (isempty(StateVarStructure)==0)&(isempty(StateVarStructure.etatT)==0);
               %
               % ask if we should save to disk
               %
               txt = 'Would you like to save the smooth and update estimates of the state shocks at posterior mode to file?';
               answer = Query(txt,'question',140,'Save - State Shocks',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  SmoothStateShocks = StateVarStructure.etatT;
                  UpdateStateShocks = StateVarStructure.etatt;
                  StateShockNames = DSGEModel.StateShockNames(StateVarStructure.KeepVar,:);
                  DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency);
                  if length(DateVector)>size(SmoothStateShocks,2);
                     DateVector = DateVector(1,length(DateVector)-size(SmoothStateShocks,2)+1:length(DateVector));
                  end;
                  file = [DSGEModel.OutputDirectory '\StateShocks-PosteriorMode.mat'];
                  save(file,'SmoothStateShocks','UpdateStateShocks','StateShockNames','DateVector');
                  %
                  % create a matlab file to read the data
                  %
                  mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'StateShocks','SS');
                  fid = fopen(mfile,'wt');
                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                  fprintf(fid,'%%\n%% matrix with the smooth estimates of the non-zero economic shocks\n%%\n');
                  fprintf(fid,'SmoothStateShocks = DataStructure.SmoothStateShocks;\n');
                  fprintf(fid,'%%\n%% matrix with the update estimates of the non-zero economic shocks\n%%\n');
                  fprintf(fid,'UpdateStateShocks = DataStructure.UpdateStateShocks;\n');
                  fprintf(fid,'%%\n%% string matrix with the names of the non-zero economic shocks\n%%\n');
                  fprintf(fid,'StateShockNames = DataStructure.StateShockNames;\n');
                  fprintf(fid,'%%\n%% vector with the dates\n%%\n');
                  fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                  %
                  % end the script file
                  %
                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                  fclose(fid);
                  txt = ['The smooth and update estimates of the state shocks at posterior mode have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 4 entries: SmoothStateShocks and UpdateStateShocks (' num2str(size(SmoothStateShocks,1),'%0.0f') 'x' num2str(size(SmoothStateShocks,2),'%0.0f') ' matrix with the smooth and update estimates of the non-zero economic shocks), StateShockNames (string matrix with the names of the non-zero economic shocks), and DateVector (1x' num2str(length(DateVector),'%0.0f') ' vector with the dates). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                  About(txt,'information','State Shocks',200,500,CurrINI);
               end;
               %
               % Display the graphs
               %
               ShockGraphDLG('init',CurrINI,DSGEModel,StateVarStructure,'Posterior Mode','State Shock');
            elseif (isempty(StateVarStructure)==0)&(isempty(StateVarStructure.etatT)==1);
               txt = 'YADA couldn''t estimate the state shocks. Please make sure that your model has state shocks!';
               About(txt,'information','YADA - State Shocks',120,500,CurrINI);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'sscorr_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the impulse responses
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view correlations of the state shocks before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Project State Shocks at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
               %
               % Try to calculate state variables. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [StateVarStructure,mcode,kalmanstatus] = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
               if (mcode==1)&(kalmanstatus==0)&(isempty(StateVarStructure.etatT)==0);
                  %
                  % compute the correlations
                  %
                  if StateVarStructure.TrainSample==0;
                     etatT = StateVarStructure.etatT(:,2:length(StateVarStructure.etatT));
                  else;
                     etatT = StateVarStructure.etatT;
                  end;
                  T = size(etatT,2);
                  %
                  SampleMean = (1/T)*sum(etatT,2);
                  etatT = etatT-SampleMean*ones(1,T);
                  %
                  CovarianceMatrix = (1/T)*etatT*etatT';
                  Correlations = zeros(size(CovarianceMatrix));
                  StDev = sqrt(diag(diag(CovarianceMatrix)));
                  %
                  StateShockNames = DSGEModel.StateShockNames(StateVarStructure.KeepVar,:);
                  %
                  % prepare output for display
                  %
                  prt_val = ['%' num2str(6+CurrINI.decimals,'%0.0f') '.' num2str(CurrINI.decimals,'%0.0f') 'f'];
                  prt_str = '%s';
                  for i=1:length(StateVarStructure.KeepVar);
                     prt_str = [prt_str '     ' prt_val];
                     for j=1:length(StateVarStructure.KeepVar);
                        Correlations(i,j) = CovarianceMatrix(i,j)/(StDev(i,i)*StDev(j,j));
                     end;
                  end;
                  %
                  txt = 'Would you like to save to file the sample estimates of the first and second moments of the state shocks based on the smooth estimates at initial values?';
                  answer = Query(txt,'question',140,'Save - State Shock Correlations',500,'no',CurrINI);
                  if strcmp(lower(answer),'yes')==1;
                     StDev = diag(StDev);
                     StateShockNames = DSGEModel.StateShockNames(StateVarStructure.KeepVar,:);
                     file = [DSGEModel.OutputDirectory '\StateShockCorrelations-InitialValues.mat'];
                     save(file,'StateShockNames','SampleMean','StDev','Correlations');
                     %
                     % create a matlab file to read the data
                     %
                     mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'StateShockCorrelations','SSC');
                     fid = fopen(mfile,'wt');
                     fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                     fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                     fprintf(fid,'%%\n%% string matrix with the names of the non-zero economic shocks\n%%\n');
                     fprintf(fid,'StateShockNames = DataStructure.StateShockNames;\n');
                     fprintf(fid,'%%\n%% vector with the sample mean for the smooth estimates\n%%\n');
                     fprintf(fid,'SampleMean = DataStructure.SampleMean;\n');
                     fprintf(fid,'%%\n%% vector with the sample standard deviation\n%%\n');
                     fprintf(fid,'StDev = DataStructure.StDev;\n');
                     fprintf(fid,'%%\n%% matrix with the sample correlations\n%%\n');
                     fprintf(fid,'Correlations = DataStructure.Correlations;\n');
                     fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                     %
                     % end the script file
                     %
                     fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                     fclose(fid);
                     txt = ['The sample estimates of the first and second moments of the state shocks for the smooth estimator at initial values have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 4 entries: StateShockNames (string matrix with the names of the non-zero economic shocks), SampleMean (vector with the sample mean), StDev (vector with the sample standard deviation), and Correlations (matrix with the sample correlations). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                     About(txt,'information','State Shock Correlations',200,500,CurrINI);
                  end;
                  %
                  txt = strvcat(' ','STATE SHOCKS AT INITIAL VALUES','==============================',' ');
                  %
                  txt = strvcat(txt,'Mean matrix:','------------',' ');
                  for i=1:length(StateVarStructure.KeepVar);
                     txt = strvcat(txt,sprintf(['%s     ' prt_val],StateShockNames(i,:),SampleMean(i)));
                  end;
                  %
                  txt = strvcat(txt,' ','Covariance matrix:','------------------',' ');
                  for i=1:length(StateVarStructure.KeepVar);
                     txt = strvcat(txt,sprintf(prt_str,StateShockNames(i,:),CovarianceMatrix(:,i)));
                  end;
                  txt = strvcat(txt,' ','Correlation matrix:','-------------------',' ');
                  for i=1:length(StateVarStructure.KeepVar);
                     txt = strvcat(txt,sprintf(prt_str,StateShockNames(i,:),Correlations(:,i)));
                  end;
                  %
                  TextGUI(txt,['State Shocks - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Initial Parameter Values',50,CurrINI,1,1);
                  %
               elseif (mcode==1)&(kalmanstatus~=0);
                  txt = 'The state variables are not stationary at the initial values.';
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               elseif 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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               elseif (isempty(StateVarStructure)==0)&(isempty(StateVarStructure.etatT)==1);
                  txt = 'YADA couldn''t estimate the state shocks. Please make sure that your model has state shocks!';
                  About(txt,'information','YADA - State Shocks',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'statevar_postmode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the autocorrelations
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               if isfield(ModeData,'LastPeriod')==1;
%                  FirstPeriod = ModeData.FirstPeriod;
%                  LastPeriod = ModeData.LastPeriod;
%               else;
%                  [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               end;
%            else;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % compute the correlations
            %
            CorrData = CalculateDSGECorrelations(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,FirstPeriod,LastPeriod);
            if isempty(CorrData)==0;
               %
               % ask if we should save to disk
               %
               txt = 'Would you like to save the population standard deviations and correlations of the state variables at posterior mode to file?';
               answer = Query(txt,'question',140,'Save - State Variable Correlations',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  StateVariableNames = DSGEModel.StateVariableNames;
                  StDev = CorrData.StateVars.StDev;
                  Correlations = CorrData.StateVars.Correlations;
                  file = [DSGEModel.OutputDirectory '\StateVariableCorrelations-PosteriorMode.mat'];
                  save(file,'StateVariableNames','StDev','Correlations');
                  %
                  % create a matlab file to read the data
                  %
                  mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'StateVariableCorrelations','SVC');
                  fid = fopen(mfile,'wt');
                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                  fprintf(fid,'%%\n%% string matrix with the names of the state variables\n%%\n');
                  fprintf(fid,'StateVariableNames = DataStructure.StateVariableNames;\n');
                  fprintf(fid,'%%\n%% vector with the population standard deviations of the state variables\n%%\n');
                  fprintf(fid,'StDev = DataStructure.StDev;\n');
                  fprintf(fid,'%%\n%% matrix with the population correlations of the state variables\n%%\n');
                  fprintf(fid,'Correlations = DataStructure.Correlations;\n');
                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                  %
                  % end the script file
                  %
                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                  fclose(fid);
                  txt = ['The population standard deviations and correlations of the state variables at posterior mode have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 3 entries: StateVariableNames (string matrix with the names of the state variables), StDev (vector with the population standard deviations), and Correlations (matrix with the population correlations). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                  About(txt,'information','State Variable Correlations',300,500,CurrINI);
               end;
               %
               % we can now present the results
               %
               PrintStateCorrelations(DSGEModel,CorrData,CurrINI,'posterior mode');
               ResFile = [DSGEModel.OutputDirectory '\PosteriorModeStateCorr-' DSGEModel.NameOfModel '.txt'];
               if FileExist(ResFile)==1;
                  TextGUI(ResFile,['State Variable Correlations - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,1);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'statevar_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the impulse responses
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view correlations of the state variables before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Observed Variable Correlations',450,'no',CurrINI);
         end;
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
               %
               % Try to calculate autocorrelations. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [CorrData,mcode] = CalculateDSGECorrelations(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,FirstPeriod,LastPeriod);
               if mcode==1;
                  %
                  % check to make sure that CorrData is not empty
                  %
                  if isempty(CorrData)==0;
                     %
                     % ask if we should save to disk
                     %
                     txt = 'Would you like to save the population standard deviations and correlations of the state variables at initial values to file?';
                     answer = Query(txt,'question',140,'Save - State Variable Correlations',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        StateVariableNames = DSGEModel.StateVariableNames;
                        StDev = CorrData.StateVars.StDev;
                        Correlations = CorrData.StateVars.Correlations;
                        file = [DSGEModel.OutputDirectory '\StateVariableCorrelations-InitialValues.mat'];
                        save(file,'StateVariableNames','StDev','Correlations');
                        %
                        % create a matlab file to read the data
                        %
                        mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'StateVariableCorrelations','SVC');
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% string matrix with the names of the state variables\n%%\n');
                        fprintf(fid,'StateVariableNames = DataStructure.StateVariableNames;\n');
                        fprintf(fid,'%%\n%% vector with the population standard deviations of the state variables\n%%\n');
                        fprintf(fid,'StDev = DataStructure.StDev;\n');
                        fprintf(fid,'%%\n%% matrix with the population correlations of the state variables\n%%\n');
                        fprintf(fid,'Correlations = DataStructure.Correlations;\n');
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        txt = ['The population standard deviations and correlations of the state variables at initial values have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 3 entries: StateVariableNames (string matrix with the names of the state variables), StDev (vector with the population standard deviations), and Correlations (matrix with the population correlations). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','State Variable Correlations',300,500,CurrINI);
                     end;
                     %
                     % we can now present the results
                     %
                     PrintStateCorrelations(DSGEModel,CorrData,CurrINI,'initial');
                     ResFile = [DSGEModel.OutputDirectory '\InitialValueStateCorr-' DSGEModel.NameOfModel '.txt'];
                     if FileExist(ResFile)==1;
                        TextGUI(ResFile,['State Variable Correlations - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Initial Parameter Values',50,CurrINI,1,1);
                     end;
                  end;
               elseif 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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'informationmatrix_postmode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the autocorrelations
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            ParameterNames = ModeData.ParameterNames.estimated;
            %
            % calculate Fisher's information matrix for the DSGE model
            %
            InformationMatrix = DSGEInformationMatrix(theta,thetaPositions,ModelParameters,ParameterNames,DSGEModel,CurrINI);
            if isempty(InformationMatrix)==0;
               %
               % compute the inverse of Fisher's information
               %
               if rank(InformationMatrix,1.02-010)==length(theta);
                  invIMatrix = eye(length(theta))/InformationMatrix;
                  stdvec = sqrt(diag(invIMatrix));
                  CorrMatrix = invIMatrix./(stdvec*stdvec');
                  %
                  % check which parameters have an absolute correlation greater than or equal 0.7
                  %
                  ExtremeCorrBound = 0.7;
                  CorrMatrix = tril(CorrMatrix,-1);
                  [RowIndex,ColIndex] = find(abs(CorrMatrix)>=ExtremeCorrBound);
                  if isempty(RowIndex)==0;
                     ExtremeCorrParameters = cell(length(RowIndex),3);
                     for i=1:length(RowIndex)
                        ExtremeCorrParameters{i,1} = ParameterNames(RowIndex(i),:);
                        ExtremeCorrParameters{i,2} = ParameterNames(ColIndex(i),:);
                        ExtremeCorrParameters{i,3} = CorrMatrix(RowIndex(i),ColIndex(i));
                     end;
                  else;
                     ExtremeCorrParameters = [];
                  end;
                  if isempty(ExtremeCorrParameters)==0;
                     TextFile = [DSGEModel.OutputDirectory '\InformationMatrixCorrelations-PosteriorMode-' DSGEModel.NameOfModel '.txt'];
                     %
                     % write the ExtremeCorrParameters to file
                     %
                     HeaderStr = strvcat('*       P A R A M E T E R   C O R R E L A T I O N S   U S I N G   T H E        *','* I N V E R S E   O F   F I S H E R '' S   I N F O R M A T I O N   M A T R I X  *');
                     PrintExtremeCorrelations(TextFile,HeaderStr,ExtremeCorrParameters,num2str(ExtremeCorrBound,'%0.2f'),rank(InformationMatrix),length(theta),CurrINI);
                     if FileExist(TextFile)==1;
                        TextGUI(TextFile,['Fisher''s Information Matrix - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,1);
                     end;
                  else;
                     txt = 'YADA has not been able to locate any potential identification issue on the basis of Fisher''s information matrix. The matrix is estimated to have full rank and all suggested parameter correlations are lower in absolute terms than 0.7.';
                     About(txt,'information','Information Matrix - Posterior Mode',200,500,CurrINI);
                  end;
               else;
                  txt = ['The posterior mode estimate of Fisher''s information matrix can''t be properly inverted. Its rank is ' int2str(rank(InformationMatrix,1.0e-010)) ' while the number of parameters is equal to ' int2str(length(theta)) '. This suggests that ' int2str(length(theta)-rank(InformationMatrix,1.0e-010)) ' parameters are not well identified through the log-likelihood function part of the log posterior at the selected parameter values.'];
                  About(txt,'information','YADA - Identification Issue',200,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'informationmatrix_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the impulse responses
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to check the information matrix before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Information Matrix',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters,thetaDist,PriorDist,ParameterNames] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     thetaDist = ModeData.thetaDist;
                     PriorDist = ModeData.PriorDist;
                     ParameterNames = ModeData.ParameterNames;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
               ParameterNames = ParameterNames.estimated;
               %
               % calculate Fisher's information matrix for the DSGE model
               %
               InformationMatrix = DSGEInformationMatrix(theta,thetaPositions,ModelParameters,ParameterNames,DSGEModel,CurrINI);
               %
               % compute the inverse of Fisher's information
               %
               if rank(InformationMatrix,1.02-010)==length(theta);
                  invIMatrix = eye(length(theta))/InformationMatrix;
                  stdvec = sqrt(diag(invIMatrix));
                  CorrMatrix = invIMatrix./(stdvec*stdvec');
                  %
                  % check which parameters have an absolute correlation greater than or equal 0.7
                  %
                  ExtremeCorrBound = 0.7;
                  CorrMatrix = tril(CorrMatrix,-1);
                  [RowIndex,ColIndex] = find(abs(CorrMatrix)>=ExtremeCorrBound);
                  if isempty(RowIndex)==0;
                     ExtremeCorrParameters = cell(length(RowIndex),3);
                     for i=1:length(RowIndex)
                        ExtremeCorrParameters{i,1} = ParameterNames(RowIndex(i),:);
                        ExtremeCorrParameters{i,2} = ParameterNames(ColIndex(i),:);
                        ExtremeCorrParameters{i,3} = CorrMatrix(RowIndex(i),ColIndex(i));
                     end;
                  else;
                     ExtremeCorrParameters = [];
                  end;
                  if isempty(ExtremeCorrParameters)==0;
                     TextFile = [DSGEModel.OutputDirectory '\InformationMatrixCorrelations-InitialValues-' DSGEModel.NameOfModel '.txt'];
                     %
                     % write the ExtremeCorrParameters to file
                     %
                     HeaderStr = strvcat('*       P A R A M E T E R   C O R R E L A T I O N S   U S I N G   T H E        *','* I N V E R S E   O F   F I S H E R '' S   I N F O R M A T I O N   M A T R I X  *');
                     PrintExtremeCorrelations(TextFile,HeaderStr,ExtremeCorrParameters,num2str(ExtremeCorrBound,'%0.2f'),rank(InformationMatrix),length(theta),CurrINI);
                     if FileExist(TextFile)==1;
                        TextGUI(TextFile,['Fisher''s Information Matrix - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Initial Parameter Values',50,CurrINI,1,1);
                     end;
                  else;
                     txt = 'YADA has not been able to locate any potential identification issue on the basis of Fisher''s information matrix. The matrix is estimated to have full rank and all suggested parameter correlations are lower in absolute terms than 0.7.';
                     About(txt,'information','Information Matrix - Initial Values',200,500,CurrINI);
                  end;
               else;
                  txt = ['The initial parameter values estimate of Fisher''s information matrix can''t be properly inverted. Its rank is ' int2str(rank(InformationMatrix,1.0e-010)) ' while the number of parameters is equal to ' int2str(length(theta)) '. This suggests that ' int2str(length(theta)-rank(InformationMatrix,1.0e-010)) ' parameters are not well identified through the log-likelihood function part of the log posterior at the selected parameter values.'];
                  About(txt,'information','YADA - Identification Issue',200,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'condcorr_postmode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the autocorrelations
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               if isfield(ModeData,'LastPeriod')==1;
%                  FirstPeriod = ModeData.FirstPeriod;
%                  LastPeriod = ModeData.LastPeriod;
%               else;
%                  [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               end;
%            else;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % ask if the user wants to simulate data
            %
            txt = 'Would you like to examine model based sample correlations rather than model based population correlations? Note: the model based sample correlations require simulation of data.';
            answer = Query(txt,'information',150,'Conditional Correlations - Posterior Mode',450,'no',CurrINI);
            if strcmp(lower(answer),'no')==1;
               SimulateData = 0;
               NumPredPaths = 0;
            else;
               SimulateData = 1;
               NumPredPathsStr = get(controls.forecast.predpaths,'String');
               NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
            end;
            CondCorr = DSGEConditionalCorrsTheta(theta,thetaPositions,ModelParameters,NumPredPaths,'Posterior Mode',DSGEModel,CurrINI,SimulateData,FirstPeriod,LastPeriod);
            if isempty(CondCorr)==0;
               if SimulateData==1;
                  %
                  % ask if we should save the results to disk
                  %
                  txt = 'Would you like to save the mean and quantiles of the conditional correlation distribution at the posterior mode parameter estimate to file?';
                  answer = Query(txt,'question',140,'Save - Conditional Correlation Distribution',500,'no',CurrINI);
                  if strcmp(lower(answer),'yes')==1;
                     file = [DSGEModel.OutputDirectory '\CondCorrelationDist-' int2str(NumPredPaths) '-PosteriorMode.mat'];
                     VariableNames = DSGEModel.VariableNames;
                     ShockNames = CondCorr(1).ShockNames;
                     for i=1:length(CondCorr);
                        ConditionalCorrs(i).Mean = CondCorr(i).Mean;
                        ConditionalCorrs(i).Quantiles = CondCorr(i).Quantiles;
                     end;
                     %
                     save(file,'VariableNames','ShockNames','ConditionalCorrs');
                     %
                     % write an m-file
                     %
                     mfile = [DSGEModel.OutputDirectory '\CCDist' int2str(NumPredPaths) 'PostMode.m'];
                     fid = fopen(mfile,'wt');
                     fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                     fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                     fprintf(fid,'%%\n%% vector structure with fields Mean and Quantiles.\n%% The length of the vector structure is equal to the number of state shocks\n%%\n');
                     fprintf(fid,'ConditionalCorrs = DataStructure.ConditionalCorrs;\n');
                     fprintf(fid,'%%\n%% string matrix with the names of the non-zero state shocks\n%%\n');
                     fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                     fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                     fprintf(fid,'VariableNames = DataStructure.VariableNames;\n');
                     fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                     %
                     %
                     % end the script file
                     %
                     fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                     fclose(fid);
                     txt = ['The model based sample conditional correlations data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 3 entries: ConditionalCorrs (a vector structure with the model based mean and quantiles of the sample conditional correlations), ShockNames (string matrix with the names of the nonzero state shocks), and VariableNames (string matrix with the names of the observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                     About(txt,'information','Conditional Correlation Distribution - Posterior Mode',200,500,CurrINI);
                  end;
               end;
               %
               % we can now present the results
               %
               PrintCondCorrelations(DSGEModel,CondCorr,CurrINI,'posterior mode',NumPredPaths,1);
               if NumPredPaths==0;
                  ResFile = [DSGEModel.OutputDirectory '\PosteriorModeCondCorr-' DSGEModel.NameOfModel '.txt'];
               else;
                  ResFile = [DSGEModel.OutputDirectory '\PosteriorModeCondCorr-' DSGEModel.NameOfModel '-' int2str(NumPredPaths) '.txt'];
               end;
               if FileExist(ResFile)==1;
                  TextGUI(ResFile,['Conditional Correlations - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,1);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'condcorr_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the impulse responses
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view correlations of the observed variables before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Observed Variable Correlations',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
               %
               % ask if the user wants to simulate data
               %
               txt = 'Would you like to examine model based sample correlations rather than model based population correlations? Note: the model based sample correlations require simulation of data.';
               answer = Query(txt,'information',150,'Conditional Correlations - Initial Values',450,'no',CurrINI);
               if strcmp(lower(answer),'no')==1;
                  SimulateData = 0;
                  NumPredPaths = 0;
               else;
                  SimulateData = 1;
                  NumPredPathsStr = get(controls.forecast.predpaths,'String');
                  NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
               end;
               [CondCorr,mcode] = DSGEConditionalCorrsTheta(theta,thetaPositions,ModelParameters,NumPredPaths,'Initial Values',DSGEModel,CurrINI,SimulateData,FirstPeriod,LastPeriod);
               if mcode==1;
                  %
                  % check to make sure that CondCorr is not empty
                  %
                  if isempty(CondCorr)==0;
                     if SimulateData==1;
                        %
                        % ask if we should save the results to disk
                        %
                        txt = 'Would you like to save the mean and quantiles of the conditional correlation distribution at the initial parameter values to file?';
                        answer = Query(txt,'question',140,'Save - Conditional Correlation Distribution',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           file = [DSGEModel.OutputDirectory '\CondCorrelationDist-' int2str(NumPredPaths) '-InitialValues.mat'];
                           VariableNames = DSGEModel.VariableNames;
                           ShockNames = CondCorr(1).ShockNames;
                           for i=1:length(CondCorr);
                              ConditionalCorrs(i).Mean = CondCorr(i).Mean;
                              ConditionalCorrs(i).Quantiles = CondCorr(i).Quantiles;
                           end;
                           %
                           save(file,'VariableNames','ShockNames','ConditionalCorrs');
                           %
                           % write an m-file
                           %
                           mfile = [DSGEModel.OutputDirectory '\CCDist' int2str(NumPredPaths) 'InitVal.m'];
                           fid = fopen(mfile,'wt');
                           fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                           fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                           fprintf(fid,'%%\n%% vector structure with fields Mean and Quantiles.\n%% The length of the vector structure is equal to the number of state shocks\n%%\n');
                           fprintf(fid,'ConditionalCorrs = DataStructure.ConditionalCorrs;\n');
                           fprintf(fid,'%%\n%% string matrix with the names of the non-zero state shocks\n%%\n');
                           fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                           fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                           fprintf(fid,'VariableNames = DataStructure.VariableNames;\n');
                           fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                           %
                           %
                           % end the script file
                           %
                           fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                           fclose(fid);
                           txt = ['The model based sample conditional correlations data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 3 entries: ConditionalCorrs (a vector structure with the model based mean and quantiles of the sample conditional correlations), ShockNames (string matrix with the names of the nonzero state shocks), and VariableNames (string matrix with the names of the observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                           About(txt,'information','Conditional Correlation Distribution - Initial Values',200,500,CurrINI);
                        end;
                     end;
                     %
                     % we can now present the results
                     %
                     PrintCondCorrelations(DSGEModel,CondCorr,CurrINI,'initial',NumPredPaths,1);
                     if NumPredPaths==0;
                        ResFile = [DSGEModel.OutputDirectory '\InitialValueCondCorr-' DSGEModel.NameOfModel '.txt'];
                     else;
                        ResFile = [DSGEModel.OutputDirectory '\InitialValueCondCorr-' DSGEModel.NameOfModel '-' int2str(NumPredPaths) '.txt'];
                     end;
                     if FileExist(ResFile)==1;
                        TextGUI(ResFile,['Conditional Correlations - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Initial Parameter Values',50,CurrINI,1,1);
                     end;
                  end;
               elseif 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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'obsvar_postmode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the autocorrelations
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               if isfield(ModeData,'LastPeriod')==1;
%                  FirstPeriod = ModeData.FirstPeriod;
%                  LastPeriod = ModeData.LastPeriod;
%               else;
%                  [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               end;
%            else;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % ask if the user wants to simulate data
            %
            txt = 'Would you like to examine model based sample moments rather than model based population moments? Note: the model based sample moments require simulation of data.';
            answer = Query(txt,'information',150,'Observed Variable Correlations - Posterior Mode',450,'no',CurrINI);
            if strcmp(lower(answer),'no')==1;
               SimulateData = 0;
               NumPredPaths = 0;
            else;
               SimulateData = 1;
               NumPredPathsStr = get(controls.forecast.predpaths,'String');
               NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
            end;
            if SimulateData==0;
               SVEs = CalculateDSGECorrelations(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,FirstPeriod,LastPeriod);
            else;
               SVEs = DSGECorrelationSimulationTheta(theta,thetaPositions,ModelParameters,NumPredPaths,'Posterior Mode',DSGEModel,CurrINI);
            end;
            if isempty(SVEs)==0;
               if SimulateData==0;
                  SVEs.Corr = SVEs.StateSpace.Corr;
                  AutoCorrType = 'Population-based';
                  DLGNameStr = 'Autcorrelation Functions - Posterior Mode';
                  BoxStr = 'Graphics - Population Autocorrelations';
               else;
                  %
                  % ask if we should save the results to disk
                  %
                  txt = 'Would you like to save the mean, standard deviation, correlations, and quantiles of the autocorrelation distributions for the posterior mode parameter estimate to file?';
                  answer = Query(txt,'question',140,'Save - Autocorrelation Distribution',500,'no',CurrINI);
                  if strcmp(lower(answer),'yes')==1;
                     file = [DSGEModel.OutputDirectory '\AutoCorrelationDist-' int2str(NumPredPaths) '-PosteriorMode.mat'];
                     VariableNames = DSGEModel.VariableNames;
                     save(file,'SVEs','VariableNames');
                     %
                     % create a matlab file to read the data
                     %
                     mfile = [DSGEModel.OutputDirectory '\ACDist' int2str(NumPredPaths) 'PostMode.m'];
                     fid = fopen(mfile,'wt');
                     fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                     fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                     fprintf(fid,'%%\n%% structure with fields Data.Mean, Data.Std, Data.Corr (data moments), Mean, Std, Corr (model means), Quantiles, and AutoCovHorizon.\n%%\n');
                     fprintf(fid,'SVEs = DataStructure.SVEs;\n');
                     fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                     fprintf(fid,'VariableNames = DataStructure.VariableNames;\n');
                     fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                     %
                     % end the script file
                     %
                     fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                     fclose(fid);
                     txt = ['The autocorrelation data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 2 entries: SVEs (a structure with the data and model based mean, standard deviation, correlation, quantile data, and correlation points), and VariableNames (string matrix with the names of the observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                     About(txt,'information','Autocorrelation Distribution - Posterior Mode',200,500,CurrINI);
                  end;
                  %
                  AutoCorrType = 'Sample-based';
                  DLGNameStr = 'Autcorrelation Distributions - Posterior Mode';
                  BoxStr = 'Graphics - Sample Autocorrelations';
               end;
               %
               % display the autocorrelations
               %
               AutoCorrelationDistributionDLG('init',SVEs,AutoCorrType,DLGNameStr,BoxStr,DSGEModel,CurrINI);
               %
               % we can now present the results
               %
               PrintAutoCorrelations(DSGEModel,SVEs,CurrINI,'posterior mode',NumPredPaths);
               if NumPredPaths==0;
                  ResFile = [DSGEModel.OutputDirectory '\PosteriorModeAutoCorr-' DSGEModel.NameOfModel '.txt'];
               else;
                  ResFile = [DSGEModel.OutputDirectory '\PosteriorModeAutoCorr-' DSGEModel.NameOfModel '-' int2str(NumPredPaths) '.txt'];
               end;
               if FileExist(ResFile)==1;
                  txt = 'Would you like to view the data and model based mean and standard deviations of the observed variables?';
                  answer = Query(txt,'question',200,'Autocorrelation Distribution - Posterior Mode',500,'no',CurrINI);
                  if strcmp(lower(answer),'yes')==1;
                     TextGUI(ResFile,['Mean & Standard Deviation - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,1);
                  end;
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'obsvar_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the impulse responses
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view correlations of the observed variables before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Observed Variable Correlations',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
               %
               % ask if the user wants to simulate data
               %
               txt = 'Would you like to examine model based sample moments rather than model based population moments? Note: the model based sample moments require simulation of data.';
               answer = Query(txt,'information',150,'Observed Variable Correlations - Initial Values',450,'no',CurrINI);
               if strcmp(lower(answer),'no')==1;
                  SimulateData = 0;
                  NumPredPaths = 0;
               else;
                  SimulateData = 1;
                  NumPredPathsStr = get(controls.forecast.predpaths,'String');
                  NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
               end;
               if SimulateData==0;
                  [SVEs,mcode] = CalculateDSGECorrelations(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,FirstPeriod,LastPeriod);
               else;
                  [SVEs,mcode] = DSGECorrelationSimulationTheta(theta,thetaPositions,ModelParameters,NumPredPaths,'Initial Values',DSGEModel,CurrINI);
               end;
               %
               if mcode==1;
                  %
                  % check to make sure that CorrData is not empty
                  %
                  if isempty(SVEs)==0;
                     if SimulateData==0;
                        SVEs.Corr = SVEs.StateSpace.Corr;
                        AutoCorrType = 'Population-based';
                        DLGNameStr = 'Autcorrelation Functions - Initial Values';
                        BoxStr = 'Graphics - Population Autocorrelations';
                     else;
                        %
                        % ask if we should save the results to disk
                        %
                        txt = 'Would you like to save the mean, standard deviation, correlations, and quantiles of the autocorrelation distributions for the initial parameter values to file?';
                        answer = Query(txt,'question',140,'Save - Autocorrelation Distribution',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           file = [DSGEModel.OutputDirectory '\AutoCorrelationDist-' int2str(NumPredPaths) '-InitialValues.mat'];
                           VariableNames = DSGEModel.VariableNames;
                           save(file,'SVEs','VariableNames');
                           %
                           % create a matlab file to read the data
                           %
                           mfile = [DSGEModel.OutputDirectory '\ACDist' int2str(NumPredPaths) 'InitVal.m'];
                           fid = fopen(mfile,'wt');
                           fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                           fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                           fprintf(fid,'%%\n%% structure with fields Data.Mean, Data.Std, Data.Corr (data moments), Mean, Std, Corr (model means), Quantiles, and AutoCovHorizon.\n%%\n');
                           fprintf(fid,'SVEs = DataStructure.SVEs;\n');
                           fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                           fprintf(fid,'VariableNames = DataStructure.VariableNames;\n');
                           fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                           %
                           % end the script file
                           %
                           fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                           fclose(fid);
                           txt = ['The autocorrelation data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 2 entries: SVEs (a structure with the data and model based mean, standard deviation, correlation, quantile data, and correlation points), and VariableNames (string matrix with the names of the observed variables). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                           About(txt,'information','Autocorrelation Distribution - Initial Values',200,500,CurrINI);
                        end;
                        %
                        AutoCorrType = 'Sample-based';
                        DLGNameStr = 'Autcorrelation Distributions - Initial Values';
                        BoxStr = 'Graphics - Sample Autocorrelations';
                     end;
                     %
                     % display the autocorrelations
                     %
                     AutoCorrelationDistributionDLG('init',SVEs,AutoCorrType,DLGNameStr,BoxStr,DSGEModel,CurrINI);
                     %
                     % we can now present the results
                     %
                     PrintAutoCorrelations(DSGEModel,SVEs,CurrINI,'initial',NumPredPaths);
                     if NumPredPaths==0;
                        ResFile = [DSGEModel.OutputDirectory '\InitialValueAutoCorr-' DSGEModel.NameOfModel '.txt'];
                     else;
                        ResFile = [DSGEModel.OutputDirectory '\InitialValueAutoCorr-' DSGEModel.NameOfModel '-' int2str(NumPredPaths) '.txt'];
                     end;
                     if FileExist(ResFile)==1;
                        txt = 'Would you like to view the data and model based mean and standard deviations of the observed variables?';
                        answer = Query(txt,'question',200,'Autocorrelation Distribution - Initial Values',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           TextGUI(ResFile,['Mean & Standard Deviation - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Initial Parameter Values',50,CurrINI,1,1);
                        end;
                     end;
                  end;
               elseif 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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'sscorr_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the impulse responses
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % we can now calculate the state shocks
            %
            StateVarStructure = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
            if (isempty(StateVarStructure)==0)&(isempty(StateVarStructure.etatT)==0);
               %
               % compute the correlations
               %
               if StateVarStructure.TrainSample==0;
                  etatT = StateVarStructure.etatT(:,2:length(StateVarStructure.etatT));
               else;
                  etatT = StateVarStructure.etatT;
               end;
               T = size(etatT,2);
               SampleMean = (1/T)*sum(etatT,2);
               etatT = etatT-SampleMean*ones(1,T);
               CovarianceMatrix = (1/T)*etatT*etatT';
               Correlations = zeros(size(CovarianceMatrix));
               StDev = sqrt(diag(diag(CovarianceMatrix)));
               %
               StateShockNames = DSGEModel.StateShockNames(StateVarStructure.KeepVar,:);
               %
               % prepare output for display
               %
               prt_val = ['%' num2str(6+CurrINI.decimals,'%0.0f') '.' num2str(CurrINI.decimals,'%0.0f') 'f'];
               prt_str = '%s';
               for i=1:length(StateVarStructure.KeepVar);
                  prt_str = [prt_str '     ' prt_val];
                  for j=1:length(StateVarStructure.KeepVar);
                     Correlations(i,j) = CovarianceMatrix(i,j)/(StDev(i,i)*StDev(j,j));
                  end;
               end;
               %
               txt = 'Would you like to save to file the sample estimates of the first and second moments of the state shocks based on the smooth estimates at posterior mode?';
               answer = Query(txt,'question',140,'Save - State Shock Correlations',500,'no',CurrINI);
               if strcmp(lower(answer),'yes')==1;
                  StDev = diag(StDev);
                  StateShockNames = DSGEModel.StateShockNames(StateVarStructure.KeepVar,:);
                  file = [DSGEModel.OutputDirectory '\StateShockCorrelations-PosteriorMode.mat'];
                  save(file,'StateShockNames','SampleMean','StDev','Correlations');
                  %
                  % create a matlab file to read the data
                  %
                  mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'StateShockCorrelations','SSC');
                  fid = fopen(mfile,'wt');
                  fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                  fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                  fprintf(fid,'%%\n%% string matrix with the names of the non-zero economic shocks\n%%\n');
                  fprintf(fid,'StateShockNames = DataStructure.StateShockNames;\n');
                  fprintf(fid,'%%\n%% vector with the sample mean for the smooth estimates\n%%\n');
                  fprintf(fid,'SampleMean = DataStructure.SampleMean;\n');
                  fprintf(fid,'%%\n%% vector with the sample standard deviation\n%%\n');
                  fprintf(fid,'StDev = DataStructure.StDev;\n');
                  fprintf(fid,'%%\n%% matrix with the sample correlations\n%%\n');
                  fprintf(fid,'Correlations = DataStructure.Correlations;\n');
                  fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                  %
                  % end the script file
                  %
                  fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                  fclose(fid);
                  txt = ['The sample estimates of the first and second moments of the state shocks for the smooth estimator at posterior mode have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 4 entries: StateShockNames (string matrix with the names of the non-zero economic shocks), SampleMean (vector with the sample mean), StDev (vector with the sample standard deviation), and Correlations (matrix with the sample correlations). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                  About(txt,'information','State Shock Correlations',200,500,CurrINI);
               end;
               %
               txt = strvcat(' ','STATE SHOCKS AT POSTERIOR MODE','==============================',' ');
               %
               txt = strvcat(txt,'Mean matrix:','------------',' ');
               for i=1:length(StateVarStructure.KeepVar);
                  txt = strvcat(txt,sprintf(['%s     ' prt_val],StateShockNames(i,:),SampleMean(i)));
               end;
               %
               txt = strvcat(txt,' ','Covariance matrix:','------------------',' ');
               for i=1:length(StateVarStructure.KeepVar);
                  txt = strvcat(txt,sprintf(prt_str,StateShockNames(i,:),CovarianceMatrix(:,i)));
               end;
               txt = strvcat(txt,' ','Correlation matrix:','-------------------',' ');
               for i=1:length(StateVarStructure.KeepVar);
                  txt = strvcat(txt,sprintf(prt_str,StateShockNames(i,:),Correlations(:,i)));
               end;
               %
               TextGUI(txt,['State Shocks - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,1);
            elseif (isempty(StateVarStructure)==0)&(isempty(StateVarStructure.etatT)==1);
               txt = 'YADA couldn''t estimate the state shocks. Please make sure that your model has state shocks!';
               About(txt,'information','YADA - State Shocks',120,500,CurrINI);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'mecorr_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the impulse responses
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view correlations of the measurement errors before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Project State Shocks at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
               %
               % Try to calculate state variables. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [StateVarStructure,mcode,kalmanstatus] = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
               if (mcode==1)&(kalmanstatus==0);
                  %
                  % we're OK
                  %
                  if isempty(StateVarStructure.wtT)==0;
                     %
                     % compute the correlations
                     %
                     T = size(StateVarStructure.wtT,2);
                     SampleMean = (1/T)*sum(StateVarStructure.wtT,2);
                     %
                     StateVarStructure.wtT = StateVarStructure.wtT-SampleMean*ones(1,T);
                     CovarianceMatrix = (1/T)*StateVarStructure.wtT*StateVarStructure.wtT';
                     Correlations = zeros(size(CovarianceMatrix));
                     StDev = sqrt(diag(diag(CovarianceMatrix)));
                     %
                     % prepare output for display
                     %
                     prt_val = ['%' num2str(6+CurrINI.decimals,'%0.0f') '.' num2str(CurrINI.decimals,'%0.0f') 'f'];
                     prt_str = '%s';
                     for i=1:size(StateVarStructure.wtNames,1);
                        prt_str = [prt_str '     ' prt_val];
                        for j=1:size(StateVarStructure.wtNames,1);
                           Correlations(i,j) = CovarianceMatrix(i,j)/(StDev(i,i)*StDev(j,j));
                        end;
                     end;
                     %
                     txt = 'Would you like to save to file the sample estimates of the first and second moments of the non-zero measurement errors based on the smooth estimates at initial values?';
                     answer = Query(txt,'question',140,'Save - Measurement Error Correlations',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        StDev = diag(StDev);
                        MeasurementErrorNames = StateVarStructure.wtNames;
                        VariableNames = DSGEModel.VariableNames;
                        file = [DSGEModel.OutputDirectory '\MeasurementErrorCorrelations-InitialValues.mat'];
                        save(file,'MeasurementErrorNames','SampleMean','StDev','Correlations');
                        %
                        % create a matlab file to read the data
                        %
                        mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'MeasurementErrorCorrelations','MEC');
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% string matrix with the names of the non-zero measurement errors\n%%\n');
                        fprintf(fid,'MeasurementErrorNames = DataStructure.MeasurementErrorNames;\n');
                        fprintf(fid,'%%\n%% vector with the sample mean for the smooth estimates\n%%\n');
                        fprintf(fid,'SampleMean = DataStructure.SampleMean;\n');
                        fprintf(fid,'%%\n%% vector with the sample standard deviation\n%%\n');
                        fprintf(fid,'StDev = DataStructure.StDev;\n');
                        fprintf(fid,'%%\n%% matrix with the sample correlations\n%%\n');
                        fprintf(fid,'Correlations = DataStructure.Correlations;\n');
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        txt = ['The sample estimates of the first and second moments of the non-zero measurement errors for the smooth estimator at initial values have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 4 entries: MeasurementErrorNames (string matrix with the names of the non-zero measurement errors), SampleMean (vector with the sample mean), StDev (vector with the sample standard deviation), and Correlations (matrix with the sample correlations). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','Measurement Error Correlations',200,500,CurrINI);
                     end;
                     %
                     txt = strvcat(' ','MEASUREMENT ERRORS AT INITIAL VALUES','====================================',' ');
                     %
                     txt = strvcat(txt,'Mean matrix:','------------',' ');
                     for i=1:size(StateVarStructure.wtNames,1);
                        txt = strvcat(txt,sprintf(['%s     ' prt_val],StateVarStructure.wtNames(i,:),SampleMean(i)));
                     end;
                     %
                     txt = strvcat(txt,' ','Covariance matrix:','------------------',' ');
                     for i=1:size(StateVarStructure.wtNames,1);
                        txt = strvcat(txt,sprintf(prt_str,StateVarStructure.wtNames(i,:),CovarianceMatrix(:,i)));
                     end;
                     txt = strvcat(txt,' ','Correlation matrix:','-------------------',' ');
                     for i=1:size(StateVarStructure.wtNames,1);
                        txt = strvcat(txt,sprintf(prt_str,StateVarStructure.wtNames(i,:),Correlations(:,i)));
                     end;
                     %
                     TextGUI(txt,['Measurement Errors - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Initial Parameter Values',50,CurrINI,1,1);
                  else;
                     txt = ['The DSGE model "' DSGEModel.NameOfModel '" doesn''t have any measurement errors.'];
                     About(txt,'information','Measurement Errors',120,500,CurrINI);
                  end;
               elseif (mcode==1)&(kalmanstatus~=0);
                  txt = 'The state variables are not stationary at the initial values.';
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               elseif 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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'mecorr_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % File with the data needed to calculate the impulse responses
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % we can now calculate the state shocks
            %
            StateVarStructure = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
            if isempty(StateVarStructure)==0;
               if isempty(StateVarStructure.wtT)==0;
                  %
                  % compute the correlations
                  %
                  T = size(StateVarStructure.wtT,2);
                  SampleMean = (1/T)*sum(StateVarStructure.wtT,2);
                  %
                  StateVarStructure.wtT = StateVarStructure.wtT-SampleMean*ones(1,T);
                  CovarianceMatrix = (1/T)*StateVarStructure.wtT*StateVarStructure.wtT';
                  Correlations = zeros(size(CovarianceMatrix));
                  StDev = sqrt(diag(diag(CovarianceMatrix)));
                  %
                  % prepare output for display
                  %
                  prt_val = ['%' num2str(6+CurrINI.decimals,'%0.0f') '.' num2str(CurrINI.decimals,'%0.0f') 'f'];
                  prt_str = '%s';
                  for i=1:size(StateVarStructure.wtNames,1);
                     prt_str = [prt_str '     ' prt_val];
                     for j=1:size(StateVarStructure.wtNames,1);
                        Correlations(i,j) = CovarianceMatrix(i,j)/(StDev(i,i)*StDev(j,j));
                     end;
                  end;
                  %
                  txt = 'Would you like to save to file the sample estimates of the first and second moments of the non-zero measurement errors based on the smooth estimates at posterior mode?';
                  answer = Query(txt,'question',140,'Save - Measurement Error Correlations',500,'no',CurrINI);
                  if strcmp(lower(answer),'yes')==1;
                     StDev = diag(StDev);
                     MeasurementErrorNames = StateVarStructure.wtNames;
                     VariableNames = DSGEModel.VariableNames;
                     file = [DSGEModel.OutputDirectory '\MeasurementErrorCorrelations-PosteriorMode.mat'];
                     save(file,'MeasurementErrorNames','SampleMean','StDev','Correlations');
                     %
                     % create a matlab file to read the data
                     %
                     mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'MeasurementErrorCorrelations','MEC');
                     fid = fopen(mfile,'wt');
                     fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                     fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                     fprintf(fid,'%%\n%% string matrix with the names of the non-zero measurement errors\n%%\n');
                     fprintf(fid,'MeasurementErrorNames = DataStructure.MeasurementErrorNames;\n');
                     fprintf(fid,'%%\n%% vector with the sample mean for the smooth estimates\n%%\n');
                     fprintf(fid,'SampleMean = DataStructure.SampleMean;\n');
                     fprintf(fid,'%%\n%% vector with the sample standard deviation\n%%\n');
                     fprintf(fid,'StDev = DataStructure.StDev;\n');
                     fprintf(fid,'%%\n%% matrix with the sample correlations\n%%\n');
                     fprintf(fid,'Correlations = DataStructure.Correlations;\n');
                     fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                     %
                     % end the script file
                     %
                     fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                     fclose(fid);
                     txt = ['The sample estimates of the first and second moments of the non-zero measurement errors for the smooth estimator at posterior mode have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 4 entries: MeasurementErrorNames (string matrix with the names of the non-zero measurement errors), SampleMean (vector with the sample mean), StDev (vector with the sample standard deviation), and Correlations (matrix with the sample correlations). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                     About(txt,'information','Measurement Error Correlations',200,500,CurrINI);
                  end;
                  %
                  txt = strvcat(' ','MEASUREMENT ERRORS AT POSTERIOR MODE','====================================',' ');
                  %
                  txt = strvcat(txt,'Mean matrix:','------------',' ');
                  for i=1:size(StateVarStructure.wtNames,1);
                     txt = strvcat(txt,sprintf(['%s     ' prt_val],StateVarStructure.wtNames(i,:),SampleMean(i)));
                  end;
                  %
                  txt = strvcat(txt,' ','Covariance matrix:','------------------',' ');
                  for i=1:size(StateVarStructure.wtNames,1);
                     txt = strvcat(txt,sprintf(prt_str,StateVarStructure.wtNames(i,:),CovarianceMatrix(:,i)));
                  end;
                  txt = strvcat(txt,' ','Correlation matrix:','-------------------',' ');
                  for i=1:size(StateVarStructure.wtNames,1);
                     txt = strvcat(txt,sprintf(prt_str,StateVarStructure.wtNames(i,:),Correlations(:,i)));
                  end;
                  %
                  TextGUI(txt,['Measurement Errors - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Mode Parameter Values',50,CurrINI,1,1);
               else;
                  txt = ['The DSGE model "' DSGEModel.NameOfModel '" doesn''t have any measurement errors.'];
                  About(txt,'information','Measurement Errors',120,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'me_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view graphs of the measurement errors before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Project Measurement Errors at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
               %
               % Try to calculate state variables. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [StateVarStructure,mcode,kalmanstatus] = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
               if (mcode==1)&(kalmanstatus==0);
                  %
                  % we're OK
                  %
                  if isempty(StateVarStructure.wtT)==0;
                     %
                     % ask if we should save to disk
                     %
                     txt = 'Would you like to save smooth and update estimates of the measurement errors at initial parameter values to file?';
                     answer = Query(txt,'question',140,'Save - Measurement Errors',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        SmoothMeasurementError = StateVarStructure.wtT;
                        UpdateMeasurementError = StateVarStructure.wtt;
                        MeasurementErrorNames = StateVarStructure.wtNames;
                        DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency);
                        if length(DateVector)>size(SmoothMeasurementError,2);
                           DateVector = DateVector(1,length(DateVector)-size(SmoothMeasurementError,2)+1:length(DateVector));
                        end;
                        file = [DSGEModel.OutputDirectory '\MeasurementErrors-InitialValues.mat'];
                        save(file,'SmoothMeasurementError','UpdateMeasurementError','MeasurementErrorNames','DateVector');
                        %
                        % create a matlab file to read the data
                        %
                        mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'MeasurementErrors','ME');
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% smoothed estimates of the non-zero measurement errors\n%%\n');
                        fprintf(fid,'SmoothMeasurementError = DataStructure.SmoothMeasurementError;\n');
                        fprintf(fid,'%%\n%% update estimates of the non-zero measurement errors\n%%\n');
                        fprintf(fid,'UpdateMeasurementError = DataStructure.UpdateMeasurementError;\n');
                        fprintf(fid,'%%\n%% string matrix with the names of the non-zero measurement errors\n%%\n');
                        fprintf(fid,'MeasurementErrorNames = DataStructure.MeasurementErrorNames;\n');
                        fprintf(fid,'%%\n%% vector with the dates\n%%\n');
                        fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        txt = ['Smooth and update estimates of the measurement errors at initial parameter values have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 4 entries: SmoothMeasurementError and UpdateMeasurementError (' num2str(size(SmoothMeasurementError,1),'%0.0f') 'x' num2str(size(SmoothMeasurementError,2),'%0.0f') ' matrix with smoothed and update estimates of the non-zero measurement errors), MeasurementErrorNames (string matrix with the names of the non-zero measurement errors), and DateVector (1x' num2str(length(DateVector),'%0.0f') ' vector with the dates). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','Measurement Errors',200,500,CurrINI);
                     end;
                     %
                     % Display the graphs
                     %
                     ShockGraphDLG('init',CurrINI,DSGEModel,StateVarStructure,'Initial Values','Measurement Error');
                  else;
                     txt = ['The DSGE model "' DSGEModel.NameOfModel '" doesn''t have any measurement errors.'];
                     About(txt,'information','Measurement Errors',120,500,CurrINI);
                  end;
               elseif (mcode==1)&(kalmanstatus~=0);
                  txt = 'The state variables are not stationary at the initial values.';
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               elseif 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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'me_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % we can now calculate the state shocks
            %
            StateVarStructure = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
            if isempty(StateVarStructure)==0;
               if isempty(StateVarStructure.wtT)==0;
                  %
                  % ask if we should save to disk
                  %
                  txt = 'Would you like to save smooth and update estimates of the measurement errors at posterior mode to file?';
                  answer = Query(txt,'question',140,'Save - Measurement Errors',500,'no',CurrINI);
                  if strcmp(lower(answer),'yes')==1;
                     SmoothMeasurementError = StateVarStructure.wtT;
                     UpdateMeasurementError = StateVarStructure.wtt;
                     MeasurementErrorNames = StateVarStructure.wtNames;
                     DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency);
                     if length(DateVector)>size(SmoothMeasurementError,2);
                        DateVector = DateVector(1,length(DateVector)-size(SmoothMeasurementError,2)+1:length(DateVector));
                     end;
                     file = [DSGEModel.OutputDirectory '\MeasurementErrors-PosteriorMode.mat'];
                     save(file,'SmoothMeasurementError','UpdateMeasurementError','MeasurementErrorNames','DateVector');
                     %
                     % create a matlab file to read the data
                     %
                     mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'MeasurementErrors','ME');
                     fid = fopen(mfile,'wt');
                     fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                     fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                     fprintf(fid,'%%\n%% smoothed estimates of the non-zero measurement errors\n%%\n');
                     fprintf(fid,'SmoothMeasurementError = DataStructure.SmoothMeasurementError;\n');
                     fprintf(fid,'%%\n%% update estimates of the non-zero measurement errors\n%%\n');
                     fprintf(fid,'UpdateMeasurementError = DataStructure.UpdateMeasurementError;\n');
                     fprintf(fid,'%%\n%% string matrix with the names of the non-zero measurement errors\n%%\n');
                     fprintf(fid,'MeasurementErrorNames = DataStructure.MeasurementErrorNames;\n');
                     fprintf(fid,'%%\n%% vector with the dates\n%%\n');
                     fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                     fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                     %
                     % end the script file
                     %
                     fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                     fclose(fid);
                     txt = ['Smooth and update estimates of the measurement errors at posterior mode have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 4 entries: SmoothMeasurementError and UpdateMeasurementError (' num2str(size(SmoothMeasurementError,1),'%0.0f') 'x' num2str(size(SmoothMeasurementError,2),'%0.0f') ' matrix with smoothed and update estimates of the non-zero measurement errors), MeasurementErrorNames (string matrix with the names of the non-zero measurement errors), and DateVector (1x' num2str(length(DateVector),'%0.0f') ' vector with the dates). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                     About(txt,'information','Measurement Errors',200,500,CurrINI);
                  end;
                  %
                  % Display the graphs
                  %
                  ShockGraphDLG('init',CurrINI,DSGEModel,StateVarStructure,'Posterior Mode','Measurement Error');
               else;
                  txt = ['The DSGE model "' DSGEModel.NameOfModel '" doesn''t have any measurement errors.'];
                  About(txt,'information','Measurement Errors',120,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'loglike_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view a graph of the log-likelihood function before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Log-Likelihood Function at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
               %
               % Try to calculate state variables. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [StateVarStructure,mcode,kalmanstatus] = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
               if (mcode==1)&(kalmanstatus==0);
                  %
                  % we're OK
                  %
                  if isempty(StateVarStructure)==0;
                     GraphLogLikelihood(StateVarStructure.lnLt,DSGEModel,CurrINI,'Initial Values');
                  end;
               elseif (mcode==1)&(kalmanstatus~=0);
                  txt = 'The state variables are not stationary at the initial values.';
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               elseif 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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'loglike_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % we can now calculate the state shocks
            %
            StateVarStructure = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
            if isempty(StateVarStructure)==0;
               GraphLogLikelihood(StateVarStructure.lnLt,DSGEModel,CurrINI,'Posterior Mode');
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'hd_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view graphs of the forecast error decompositions before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Forecast Error Decompositions at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
               %
               % Try to calculate state variables. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [StateVarStructure,mcode,kalmanstatus] = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
               if (mcode==1)&(kalmanstatus==0);
                  %
                  % we're OK
                  %
                  if strcmp(lower(DSGEModel.DataFrequency(1,1)),'q')==1;
                     FreqStr = 'quarter';
                     DefaultOption = 4;
                  elseif strcmp(lower(DSGEModel.DataFrequency(1,1)),'m')==1;
                     FreqStr = 'month';
                     DefaultOption = 12;
                  else;
                     FreqStr = 'year';
                     DefaultOption = 1;
                  end;
                  %
                  % select horizon for historical decomposition
                  %
                  SelectionOptions = ['1 ' FreqStr];
                  for i=2:max(20,floor(DSGEModel.T/4));
                     SelectionOptions = strvcat(SelectionOptions,[num2str(i) ' ' FreqStr 's']);
                  end;
                  %
                  [action,SelectedOption] = SelectionDlg(SelectionOptions,DefaultOption,'Select forecast horizon','Forecast Horizon Selection','Forecast Error Decompositions - Initial Values','','',CurrINI);
                  if strcmp(lower(action),'ok')==1;
                     %
                     % Now determine the horizon
                     %
                     ForecastHorizon = strrep(SelectionOptions(SelectedOption,:),FreqStr,'');
                     ForecastHorizon = str2num(StringTrim(strrep(ForecastHorizon,'s','')));
                     %
                     % compute the historical decomposition.
                     %
                     HistDecompStructure = DSGEHistDecompFcn(StateVarStructure.Y,StateVarStructure.X,StateVarStructure.A,StateVarStructure.H,StateVarStructure.F,StateVarStructure.B0,StateVarStructure.Ksitt,StateVarStructure.KsitT,StateVarStructure.etatT,StateVarStructure.wthT,ForecastHorizon);
                     if isempty(HistDecompStructure)==0;
                        HistDecompStructure.R = StateVarStructure.R;
                        HistDecompStructure.ForecastHorizon = ForecastHorizon;
                        HistDecompStructure.FreqStr = strcat(upper(FreqStr(1,1)),FreqStr(1,2:length(FreqStr)));
                        HistDecompDLG('init',CurrINI,DSGEModel,HistDecompStructure,'Initial Values');
                     end;
                  end;
               elseif (mcode==1)&(kalmanstatus~=0);
                  txt = 'The state variables are not stationary at the initial values.';
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               elseif 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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'hd_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            if strcmp(lower(DSGEModel.DataFrequency(1,1)),'q')==1;
               FreqStr = 'quarter';
               DefaultOption = 4;
            elseif strcmp(lower(DSGEModel.DataFrequency(1,1)),'m')==1;
               FreqStr = 'month';
               DefaultOption = 12;
            else;
               FreqStr = 'year';
               DefaultOption = 1;
            end;
            %
            % select horizon for historical decomposition
            %
            SelectionOptions = ['1 ' FreqStr];
            for i=2:max(20,floor(DSGEModel.T/4));
               SelectionOptions = strvcat(SelectionOptions,[num2str(i) ' ' FreqStr 's']);
            end;
            %
            [action,SelectedOption] = SelectionDlg(SelectionOptions,DefaultOption,'Select forecast horizon','Forecast Horizon Selection','Forecast Error Decompositions - Posterior Mode','','',CurrINI);
            if strcmp(lower(action),'ok')==1;
               %
               % Now determine the horizon
               %
               ForecastHorizon = strrep(SelectionOptions(SelectedOption,:),FreqStr,'');
               ForecastHorizon = str2num(StringTrim(strrep(ForecastHorizon,'s','')));
               %
               % calculate all the state variables, shocks, etc
               %
               StateVarStructure = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,0);
               %
               % compute the historical decomposition.
               %
               HistDecompStructure = DSGEHistDecompFcn(StateVarStructure.Y,StateVarStructure.X,StateVarStructure.A,StateVarStructure.H,StateVarStructure.F,StateVarStructure.B0,StateVarStructure.Ksitt,StateVarStructure.KsitT,StateVarStructure.etatT,StateVarStructure.wthT,ForecastHorizon);
               if isempty(HistDecompStructure)==0;
                  HistDecompStructure.R = StateVarStructure.R;
                  HistDecompStructure.ForecastHorizon = ForecastHorizon;
                  HistDecompStructure.FreqStr = strcat(upper(FreqStr(1,1)),FreqStr(1,2:length(FreqStr)));
                  HistDecompDLG('init',CurrINI,DSGEModel,HistDecompStructure,'Posterior Mode');
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'ovd_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view graphs of the observed variables decompositions before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'Observed Variables Decomposition at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
               %
               % Try to calculate state variables. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [StateVarStructure,mcode,kalmanstatus] = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,1);
               if (mcode==1)&(kalmanstatus==0);
                  %
                  % we're OK
                  %
                  if isempty(StateVarStructure)==0;
                     if gcbo==controls.ovd.initialvalues;
                        AnnualStr = 'Original';
                     else;
                        AnnualStr = 'Annualized';
                     end;
                     ObsVarDecompDLG('init',StateVarStructure,'Initial Values',AnnualStr,CurrINI,DSGEModel);
                  end;
               elseif (mcode==1)&(kalmanstatus~=0);
                  txt = 'The state variables are not stationary at the initial values.';
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               elseif 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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Observed Variables Decomposition',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'ovd_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % we can now calculate the state shocks
            %
            StateVarStructure = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,1);
            if isempty(StateVarStructure)==0;
               if gcbo==controls.ovd.postmode;
                  AnnualStr = 'Original';
               else;
                  AnnualStr = 'Annualized';
               end;
               %
               % we can now send the data for graphing
               %
               ObsVarDecompDLG('init',StateVarStructure,'Posterior Mode',AnnualStr,CurrINI,DSGEModel);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'svd_init_values'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check first if posterior mode results exists. If they do we load initial values from this file.
         % Otherwise we have to do a bunch of checking
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         if FileExist(ModeFile)==1;
            answer = 'Yes';
         else;
            %
            % Ask if the user really wants to look at these before estimating the posterior mode
            %
            txt = 'Are you sure you want to view graphs of the state variables decompositions before running the posterior mode estimation routine?';
            answer = Query(txt,'information',150,'State Variable Decomposition at Initial Values',450,'no',CurrINI);
         end;
         %
         if strcmp(lower(answer),'yes')==1;
            %
            % posterior mode estimation has not been completed yet. We therefore need to check all the imput files
            %
            [InitStatus,theta,thetaPositions,ModelParameters] = InitializeDSGEModelSimulation(DSGEModel,CurrINI);
            if (InitStatus==0)&(FileExist(DSGEModel.PriorFile)==0);
               if FileExist(ModeFile)==1;
                  ErrorStr = '';
                  try;
                     ModeData = load(ModeFile);
                  catch;
                     ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     theta = ModeData.theta;
                     thetaPositions = ModeData.thetaPositions;
                     ModelParameters = ModeData.ModelParameters;
                     ModelParameters = ThetaToModelParameters(ModelParameters,theta,thetaPositions);
                     InitStatus = 1;
                  end;
               end;
            end;
            %
            if InitStatus==1;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
               %
               % Try to calculate state variables. First, however, the code needs to check if a unique convergent
               % solution exists.
               %
               [StateVarStructure,mcode,kalmanstatus] = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,1);
               if (mcode==1)&(kalmanstatus==0);
                  %
                  % we're OK
                  %
                  if isempty(StateVarStructure)==0;
                     StateVarDecompDLG('init',StateVarStructure,'Initial Values',CurrINI,DSGEModel);
                  end;
               elseif (mcode==1)&(kalmanstatus~=0);
                  txt = 'The state variables are not stationary at the initial values.';
                  About(txt,'information','Calibrated DSGE Model',120,500,CurrINI);
               elseif 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;
                  SetLogText(strvcat(['   STATUS: ' mcodeStr],' '));
                  txt = ['The AiM solver provided the return code: ' num2str(mcode) ', i.e., "' mcodeStr '" You have to change your initial parameter values.'];
                  About(txt,'information','Observed Variables Decomposition',120,500,CurrINI);
               end;
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'svd_post_mode'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         %
         % File with the data needed to calculate the impulse responses
         %
         drawnow;
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%            else;
%               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % we can now calculate the state shocks
            %
            StateVarStructure = CalculateDSGEStateVariables(theta,thetaPositions,ModelParameters,DSGEModel,CurrINI,1);
            if isempty(StateVarStructure)==0;
               %
               % we can now send the data for graphing
               %
               StateVarDecompDLG('init',StateVarStructure,'Posterior Mode',CurrINI,DSGEModel);
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'browseaim'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Open a file open dialog
         %
         OldAIMFile = DSGEModel.AIMFile;
         status = FileBrowse(DSGEModel.AIMFile,'Open AiM Model File',controls.dsge.aimfile,'aim',CurrINI);
         if status==1;
            DSGEModel.AIMFile = get(controls.dsge.aimfile,'String');
            DSGEModel.NameOfModel = RemoveIllegalChars(GetName(DSGEModel.AIMFile));
            %
            % Setup a new base output directory. Create it if necessary
            %
            if strcmp(lower(OldAIMFile),lower(DSGEModel.AIMFile))==0;
               DirStatus = MakeDir(GetPath(DSGEModel.AIMFile),DSGEModel.NameOfModel);
               if DirStatus==1;
                  DSGEModel.OutputDirectory = [GetPath(DSGEModel.AIMFile) DSGEModel.NameOfModel];
               end;
            end;
            %
            AIMDataFile = [DSGEModel.OutputDirectory '\' DSGEModel.NameOfModel '.mat'];
            if FileExist(AIMDataFile)==1;
               DSGEModel.AIMDataFile = AIMDataFile;
            else;
               DSGEModel.AIMDataFile = pwd;
            end;
            if FileExist(CurrINI.CurrentModelFile)==1;
               set(maingui,'Name',['YADA - ' DSGEModel.NameOfModel ' - [' GetFilename(CurrINI.CurrentModelFile) ']']);
            else;
               set(maingui,'Name',['YADA - ' DSGEModel.NameOfModel]);
            end;
            set(controls.dsge.modelname,'String',DSGEModel.NameOfModel);
            set(controls.runaim,'Enable','on');
            set(controls.runaimmenu,'Enable','on');
            set(controls.aimmodelinfo,'Enable','on');
            set(controls.outputdirtext,'Enable','on');
            set(controls.outputdir,'Enable','on','String',DSGEModel.OutputDirectory);
            set(controls.outputbutton,'Enable','on','CData',CurrINI.images.browse);
            if FileExist(DSGEModel.AIMDataFile)==1;
               set(controls.statevar,'Enable','on');
               set(controls.statevarmenu,'Enable','on');
               set(controls.stateshock,'Enable','on');
               set(controls.stateshockmenu,'Enable','on');
            else;
               set(controls.statevar,'Enable','off');
               set(controls.statevarmenu,'Enable','off');
               set(controls.stateshock,'Enable','off');
               set(controls.stateshockmenu,'Enable','off');
            end;
         end;
         set(controls.about,'UserData',0);
      end;
   case 'checkaimfile'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         OldAIMFile = DSGEModel.AIMFile;
         new_aim_file = StringTrim(get(controls.dsge.aimfile,'String'));
         if strcmp(new_aim_file,'')==0;
            if (FileExist(new_aim_file)==1)&((strcmp(lower(GetExt(new_aim_file)),'.txt')==1)|(strcmp(lower(GetExt),'.aim')==1));
               DSGEModel.AIMFile = new_aim_file;
               DSGEModel.NameOfModel = RemoveIllegalChars(GetName(DSGEModel.AIMFile));
               %
               % Setup a new base output directory. Create it if necessary
               %
               if strcmp(lower(OldAIMFile),lower(DSGEModel.AIMFile))==0;
                  DirStatus = MakeDir(GetPath(DSGEModel.AIMFile),DSGEModel.NameOfModel);
                  if DirStatus==1;
                     DSGEModel.OutputDirectory = [GetPath(DSGEModel.AIMFile) DSGEModel.NameOfModel];
                  end;
               end;
               %
               AIMDataFile = [DSGEModel.OutputDirectory '\' DSGEModel.NameOfModel '.mat'];
               if FileExist(AIMDataFile)==1;
                  DSGEModel.AIMDataFile = AIMDataFile;
                  set(controls.statevar,'Enable','on');
                  set(controls.statevarmenu,'Enable','on');
                  set(controls.stateshock,'Enable','on');
                  set(controls.stateshockmenu,'Enable','on');
               else;
                  DSGEModel.AIMDataFile = pwd;
                  set(controls.statevar,'Enable','off');
                  set(controls.statevarmenu,'Enable','off');
                  set(controls.stateshock,'Enable','off');
                  set(controls.stateshockmenu,'Enable','off');
               end;
               %
               if FileExist(CurrINI.CurrentModelFile)==1;
                  set(maingui,'Name',['YADA - ' DSGEModel.NameOfModel ' - [' GetFilename(CurrINI.CurrentModelFile) ']']);
               else;
                  set(maingui,'Name',['YADA - ' DSGEModel.NameOfModel]);
               end;
               set(controls.dsge.modelname,'String',DSGEModel.NameOfModel);
               set(controls.runaim,'Enable','on');
               set(controls.runaimmenu,'Enable','on');
               set(controls.aimmodelinfo,'Enable','on');
               set(controls.outputdirtext,'Enable','on');
               set(controls.outputdir,'Enable','on','String',DSGEModel.OutputDirectory);
               set(controls.outputbutton,'Enable','on','CData',CurrINI.images.browse);
            else;
               if (strcmp(new_aim_file,'')==1)|(isempty(new_aim_file)==1);
                  DSGEModel.AIMFile = pwd;
                  DSGEModel.AIMDataFile = pwd;
                  DSGEModel.NameOfModel = '';
                  DSGEModel.OutputDirectory = pwd;
               end;
               set(controls.dsge.aimfile,'String',DSGEModel.AIMFile);
               if strcmp(DSGEModel.NameOfModel,'')==0;
                  if FileExist(CurrINI.CurrentModelFile)==1;
                     set(maingui,'Name',['YADA - ' DSGEModel.NameOfModel ' - [' GetFilename(CurrINI.CurrentModelFile) ']']);
                  else;
                     set(maingui,'Name',['YADA - ' DSGEModel.NameOfModel]);
                  end;
               else;
                  set(maingui,'Name','YADA');
               end;
               set(controls.dsge.modelname,'String',DSGEModel.NameOfModel);
               if FileExist(DSGEModel.AIMFile)==1;
                  set(controls.runaim,'Enable','on');
                  set(controls.runaimmenu,'Enable','on');
                  set(controls.aimmodelinfo,'Enable','on');
                  set(controls.outputdirtext,'Enable','on');
                  set(controls.outputdir,'Enable','on','String',DSGEModel.OutputDirectory);
                  set(controls.outputbutton,'Enable','on','CData',CurrINI.images.browse);
               else;
                  DSGEModel.OutputDirectory = pwd;
                  set(controls.runaim,'Enable','off');
                  set(controls.runaimmenu,'Enable','off');
                  set(controls.aimmodelinfo,'Enable','off');
                  set(controls.outputdirtext,'Enable','off');
                  set(controls.outputdir,'Enable','off','String',DSGEModel.OutputDirectory);
                  set(controls.outputbutton,'Enable','off','CData',CurrINI.images.browsedisable);
               end;
            end;
         else;
            if (strcmp(new_aim_file,'')==1)|(isempty(new_aim_file)==1);
               DSGEModel.AIMFile = pwd;
               DSGEModel.AIMDataFile = pwd;
               DSGEModel.NameOfModel = '';
               DSGEModel.OutputDirectory = pwd;
            end;
            set(controls.dsge.aimfile,'String',DSGEModel.AIMFile);
            if strcmp(DSGEModel.NameOfModel,'')==0;
               if FileExist(CurrINI.CurrentModelFile)==1;
                  set(maingui,'Name',['YADA - ' DSGEModel.NameOfModel ' - [' GetFilename(CurrINI.CurrentModelFile) ']']);
               else;
                  set(maingui,'Name',['YADA - ' DSGEModel.NameOfModel]);
               end;
            else;
               set(maingui,'Name','YADA');
            end;
            set(controls.dsge.modelname,'String',DSGEModel.NameOfModel);
            if FileExist(DSGEModel.AIMFile)==1;
               set(controls.runaim,'Enable','on');
               set(controls.runaimmenu,'Enable','on');
               set(controls.aimmodelinfo,'Enable','on');
               set(controls.outputdirtext,'Enable','on');
               set(controls.outputdir,'Enable','on','String',DSGEModel.OutputDirectory);
               set(controls.outputbutton,'Enable','on','CData',CurrINI.images.browse);
            else;
               DSGEModel.OutputDirectory = pwd;
               set(controls.runaim,'Enable','off');
               set(controls.runaimmenu,'Enable','off');
               set(controls.aimmodelinfo,'Enable','off');
               set(controls.outputdirtext,'Enable','off');
               set(controls.outputdir,'Enable','off','String',DSGEModel.OutputDirectory);
               set(controls.outputbutton,'Enable','off','CData',CurrINI.images.browsedisable);
            end;
         end;
         set(controls.about,'UserData',0);
      end;
   case 'browsesteadystatefile'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Open a file open dialog
         %
         status = FileBrowse(DSGEModel.SteadyStatePriorFile,'Open Steady State Prior File',controls.bvar.steadystatefile,'m',CurrINI);
         if status==1;
            DSGEModel.SteadyStatePriorFile = get(controls.bvar.steadystatefile,'String');
         end;
         set(controls.about,'UserData',0);
      end;
   case 'checksteadystatefile'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         new_me_file = StringTrim(get(controls.bvar.steadystatefile,'String'));
         if FileExist(new_me_file)==1;
            %
            % make sure that the file is an m-file
            %
            [FilePath,FileName,FileExt] = fileparts(new_me_file);
            if (strcmp(lower(FileExt),'.m')==1)|(strcmp(lower(FileExt),'.p')==1);
               DSGEModel.SteadyStatePriorFile = new_me_file;
               %
               % Enable any controls that may be affected by this
               %
            else;
               set(controls.bvar.steadystatefile,'String',DSGEModel.SteadyStatePriorFile);
            end;
         else;
            if (strcmp(new_me_file,'')==1)|(isempty(new_me_file)==1);
               DSGEModel.SteadyStatePriorFile = pwd;
            end;
            set(controls.bvar.steadystatefile,'String',DSGEModel.SteadyStatePriorFile);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'browsemeasurefile'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Open a file open dialog
         %
         status = FileBrowse(DSGEModel.MeasurementEquationFile,'Open Measurement Equation File',controls.dsge.measurefile,'m',CurrINI);
         if status==1;
            DSGEModel.MeasurementEquationFile = get(controls.dsge.measurefile,'String');
         end;
         set(controls.about,'UserData',0);
      end;
   case 'checkmeasurefile'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         new_me_file = StringTrim(get(controls.dsge.measurefile,'String'));
         if FileExist(new_me_file)==1;
            %
            % make sure that the file is an m-file
            %
            [FilePath,FileName,FileExt] = fileparts(new_me_file);
            if (strcmp(lower(FileExt),'.m')==1)|(strcmp(lower(FileExt),'.p')==1);
               DSGEModel.MeasurementEquationFile = new_me_file;
            else;
               set(controls.dsge.measurefile,'String',DSGEModel.MeasurementEquationFile);
            end;
         else;
            if (strcmp(new_me_file,'')==1)|(isempty(new_me_file)==1);
               DSGEModel.MeasurementEquationFile = pwd;
            end;
            set(controls.dsge.measurefile,'String',DSGEModel.MeasurementEquationFile);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'browsedatafile'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Open a file open dialog
         %
         status = FileBrowse(DSGEModel.DataConstructionFile,'Open Data Construction File',controls.dsge.datafile,'m',CurrINI);
         if status==1;
            file = StringTrim(get(controls.dsge.datafile,'String'));
            %
            % check if the path for file is equal to pwd, else copy to pwd and overwrite if necessary
            %
            [FilePath,FileName,FileExt] = fileparts(file);
            if strcmp(lower(FilePath),lower([pwd '\tmp']))==0;
               [stat,msg] = dos(['copy /Y "' file '" "' pwd '\tmp"']);
               file = [pwd '\tmp\' FileName FileExt];
            end;
            %
            % check the file to see if we can retrieve the necessary information
            %
            if FileExist(file)==1;
               ErrorStr = '';
               try;
                  eval(['DataStructure = ' FileName ';']);
               catch;
                  ErrorStr = ['Error found in data construction file "' FileName '". The error message caught is: ' lasterr];
               end;
               if isempty(ErrorStr)==1;
                  %
                  % now we check if DataStructure is valid
                  %
                  stat = CheckObservedDataFile(DataStructure,controls.dsge.datafile,DSGEModel.DataConstructionFile,[FileName FileExt],CurrINI);
                  if stat>=1;
                     %
                     % error messages have already been reported by CheckObservedDataFile with stat = 0
                     %
                     % make the necessary changes to the DSGEModel structure
                     %
                     DSGEModel.DataConstructionFile = get(controls.dsge.datafile,'String');
                     DSGEModel.T = length(DataStructure.Y.data);
                     DSGEModel.n = length(DataStructure.Y.names);
                     DSGEModel.k = length(DataStructure.X.names);
                     DSGEModel.Y = DataStructure.Y.data;
                     if isfield(DataStructure.Y,'comparisondata')==1;
                        DSGEModel.CompY = DataStructure.Y.comparisondata;
                     else;
                        DSGEModel.CompY = [];
                     end;
                     DSGEModel.DataFrequency = lower(DataStructure.frequency(1,1));
                     ForecastStr = get(controls.forecast.maxhorizon,'UserData');
                     if strcmp(lower(DSGEModel.DataFrequency),'q')==1;
                        set(controls.forecast.maxhorizon,'String',ForecastStr.quarter);
                     elseif strcmp(lower(DSGEModel.DataFrequency),'m')==1;
                        set(controls.forecast.maxhorizon,'String',ForecastStr.month);
                     else;
                        set(controls.forecast.maxhorizon,'String',ForecastStr.annual);
                     end;
                     if (isfield(DataStructure.Y,'BVAR')==1)&(length(DataStructure.Y.BVAR)<=DSGEModel.n);
                        DSGEModel.BVARY = VerifyVector(DataStructure.Y.BVAR,DSGEModel.n);
                     else;
                        DSGEModel.BVARY = (1:DSGEModel.n);
                     end;
                     if (isfield(DataStructure.X,'BVAR')==1)&(length(DataStructure.X.BVAR)<=DSGEModel.k);
                        DSGEModel.BVARX = VerifyVector(DataStructure.X.BVAR,DSGEModel.k);
                     else;
                        DSGEModel.BVARX = (1:DSGEModel.k);
                     end;
                     if isfield(DataStructure.X,'extradata')==1;
                        %
                        % we need to test if this data is valid
                        %
                        if size(DataStructure.X.extradata,1)==DSGEModel.k;
                           DSGEModel.PredictedX = DataStructure.X.extradata;
                        else;
                           DSGEModel.PredictedX = [];
                        end;
                     else;
                        DSGEModel.PredictedX = [];
                     end;
                     if isfield(DataStructure,'percentiles')==1;
                        Ptiles = unique(DataStructure.percentiles);
                        %
                        % make sure that all entries are greater than 0, less than a 100, and integers
                        %
                        Ptiles = Ptiles(Ptiles>0);
                        Ptiles = Ptiles(Ptiles<100);
                        if length(Ptiles)>1;
                           if IsOdd(length(Ptiles))==1;
                              Pmiddle = Ptiles(ceil(length(Ptiles)/2));
                              Ptiles = Ptiles(Ptiles~=Pmiddle);
                           end;
                           DSGEModel.Percentiles = Ptiles;
                        else;
                           DSGEModel.Percentiles = [5 15 85 95];
                        end;
                     else;
                        DSGEModel.Percentiles = [5 15 85 95];
                     end;
                     if stat==1;
                        DSGEModel.levels = DataStructure.Y.levels;
                        if (isfield(DataStructure.Y,'annual')==1)&(length(DataStructure.Y.annual)==DSGEModel.n);
                           if strcmp(DSGEModel.DataFrequency,'q')==1;
                              SampleFreq = 4;
                           elseif strcmp(DSGEModel.DataFrequency,'m')==1;
                              SampleFreq = 12;
                           else;
                              SampleFreq = 1;
                           end;
                           DSGEModel.annual = ((DataStructure.Y.annual)*(SampleFreq-1))+ones(1,DSGEModel.n);
                        else;
                           DSGEModel.annual = ones(1,DSGEModel.n);
                        end;
                        if (isfield(DataStructure.Y,'annualscale')==1)&(length(DataStructure.Y.annualscale)==DSGEModel.n);
                           DSGEModel.annualscale = ReplaceData(DataStructure.Y.annualscale,0,1);
                        else;
                           DSGEModel.annualscale = ones(1,DSGEModel.n);
                        end;
                     elseif stat==2;
                        DSGEModel.levels = ones(1,DSGEModel.n);
                        DSGEModel.annual = ones(1,DSGEModel.n);
                        DSGEModel.annualscale = ones(1,DSGEModel.n);
                     end;
                     if size(DSGEModel.Y,1)>size(DSGEModel.Y,2);
                        DSGEModel.Y = DSGEModel.Y';
                     end;
                     if size(DSGEModel.CompY,1)>size(DSGEModel.CompY,2);
                        DSGEModel.CompY = DSGEModel.CompY';
                     end;
                     if size(DSGEModel.Y)~=size(DSGEModel.CompY);
                        DSGEModel.CompY = [];
                     end;
                     DSGEModel.X = DataStructure.X.data;
                     if size(DSGEModel.X,1)>size(DSGEModel.X,2);
                        DSGEModel.X = DSGEModel.X';
                     end;
                     DSGEModel.YData = DSGEModel.Y;
                     DSGEModel.YDataOriginal = DSGEModel.Y;
                     DSGEModel.BeginYear = num2str(floor(DataStructure.sample(1)));
                     DSGEModel.BeginPeriod = num2str(floor(DataStructure.sample(2)));
                     DSGEModel.EndYear = num2str(floor(DataStructure.sample(3)));
                     DSGEModel.EndPeriod = num2str(floor(DataStructure.sample(4)));
                     DSGEModel.SubBeginYear = num2str(floor(DataStructure.sample(1)));
                     DSGEModel.SubBeginPeriod = num2str(floor(DataStructure.sample(2)));
                     DSGEModel.SubEndYear = num2str(floor(DataStructure.sample(3)));
                     DSGEModel.SubEndPeriod = num2str(floor(DataStructure.sample(4)));
                     DSGEModel.VariableNames = '';
                     for i=1:DSGEModel.n;
                        DSGEModel.VariableNames = strvcat(DSGEModel.VariableNames,DataStructure.Y.names{i});
                     end;
                     DSGEModel.XVariableNames = '';
                     for i=1:DSGEModel.k;
                        DSGEModel.XVariableNames = strvcat(DSGEModel.XVariableNames,DataStructure.X.names{i});
                     end;
                     if isfield(DataStructure.Y,'transformation')==1;
                        DSGEModel.YTransformation = DataStructure.Y.transformation;
                     else;
                        DSGEModel.YTransformation = [];
                     end;
                     %
                     % now we need to set the controls with the correct entries
                     %
                     [DSGEModel.SubBeginYearValue,DSGEModel.SubBeginPeriodValue,DSGEModel.SubEndYearValue,DSGEModel.SubEndPeriodValue,DSGEModel.YearStrMatrix,DSGEModel.PeriodStrMatrix] = CreateEstimationSampleValues(DSGEModel);
                     %
                     set(controls.dsge.subbeginyear,'String',DSGEModel.YearStrMatrix,'Value',DSGEModel.SubBeginYearValue);
                     set(controls.dsge.subbeginperiod,'String',DSGEModel.PeriodStrMatrix,'Value',DSGEModel.SubBeginPeriodValue);
                     set(controls.dsge.subendyear,'String',DSGEModel.YearStrMatrix,'Value',DSGEModel.SubEndYearValue);
                     set(controls.dsge.subendperiod,'String',DSGEModel.PeriodStrMatrix,'Value',DSGEModel.SubEndPeriodValue);
                     %
                     [FirstPeriod,LastPeriod,EstSample] = CreateSubSample(DSGEModel);
                     DSGEModel.KalmanFirstObservation = 1;
                     set(controls.dsge.initializekalman,'String',EstSample,'Value',DSGEModel.KalmanFirstObservation);
                     %
                     % check if there is conditioning information
                     %
                     DSGEModel = VerifyConditioningInformation(DSGEModel,DataStructure);
                     %
                     % check if there is observed variable scenario information
                     %
                     DSGEModel = VerifyScenarioInformation(DSGEModel,DataStructure);
                     %
                     % Enable any controls that may be affected by this
                     %
                     set(controls.datainfo,'Enable','on');
                  else;
                     set(controls.dsge.datafile,'String',DSGEModel.DataConstructionFile);
                  end;
               else;
                  set(controls.dsge.datafile,'String',DSGEModel.DataConstructionFile);
                  About(ErrorStr,'error',['Error - ' FileName],300,500,CurrINI);
               end;
            end;
         else;
            %
            % Check if we need to disable any controls
            %
            if FileExist(DSGEModel.DataConstructionFile)==0;
               ForecastStr = get(controls.forecast.maxhorizon,'UserData');
               DSGEModel.MaxForecastHorizon = 1;
               set(controls.forecast.maxhorizon,'String',ForecastStr.annual,'Value',DSGEModel.MaxForecastHorizon);
               DSGEModel.T = 0;
               DSGEModel.n = 0;
               DSGEModel.k = 0;
               DSGEModel.Y = [];
               DSGEModel.YData = [];
               DSGEModel.YDataOriginal = [];
               DSGEModel.CompY = [];
               DSGEModel.BVARY = [];
               DSGEModel.BVARX = [];
               DSGEModel.levels = [];
               DSGEModel.annualscale = [];
               DSGEModel.annual = [];
               DSGEModel.X = [];
               DSGEModel.PredictedX = [];
               DSGEModel.Percentiles = [5 15 85 95];
               DSGEModel.ConfidenceBandBaseColor = [1 1 1];
               DSGEModel.DataFrequency = '';
               DSGEModel.BeginYear = '';
               DSGEModel.BeginPeriod = '';
               DSGEModel.EndYear = '';
               DSGEModel.EndPeriod = '';
               DSGEModel.SubBeginYear = '';
               DSGEModel.SubBeginPeriod = '';
               DSGEModel.SubEndYear = '';
               DSGEModel.SubEndPeriod = '';
               DSGEModel.VariableNames = '';
               DSGEModel.XVariableNames = '';
               DSGEModel.Z = [];
               DSGEModel.ZVariableNames = '';
               DSGEModel.K1 = [];
               DSGEModel.K2 = [];
               DSGEModel.U = [];
               DSGEModel.C = [];
               DSGEModel.CData = [];
               DSGEModel.CDataComment = '';
               DSGEModel.CVariableNames = '';
               DSGEModel.ObsVariableScenarioFile = '';
               DSGEModel.C1 = [];
               DSGEModel.C2 = [];
               DSGEModel.CBar = [];
               DSGEModel.CDataOriginal = [];
               DSGEModel.CompData = [];
               DSGEModel.CompCBar = [];
               DSGEModel.CDataCommentOriginal = '';
               DSGEModel.CVariableNamesOriginal = '';
               DSGEModel.C1Original = [];
               DSGEModel.C2Original = [];
               DSGEModel.CBarOriginal = [];
               DSGEModel.YTransformation = [];
               DSGEModel.CTransformation = [];
               DSGEModel.CTransformationOriginal = [];
               DSGEModel.ZTransformation = [];
               DSGEModel.ZTransformationOriginal = [];
               DSGEModel.CExport = [];
               DSGEModel.CExportVariables = [];
               DSGEModel.CCreateData = [];
               DSGEModel.COrder = [];
               set(controls.datainfo,'Enable','off');
               [DSGEModel.SubBeginYearValue,DSGEModel.SubBeginPeriodValue,DSGEModel.SubEndYearValue,DSGEModel.SubEndPeriodValue,DSGEModel.YearStrMatrix,DSGEModel.PeriodStrMatrix] = CreateEstimationSampleValues(DSGEModel);
               %
               DSGEModel.KalmanFirstObservation = 1;
               set(controls.dsge.initializekalman,'String',' ','Value',DSGEModel.KalmanFirstObservation);
               %
               set(controls.dsge.subbeginyear,'String',DSGEModel.YearStrMatrix,'Value',DSGEModel.SubBeginYearValue);
               set(controls.dsge.subbeginperiod,'String',DSGEModel.PeriodStrMatrix,'Value',DSGEModel.SubBeginPeriodValue);
               set(controls.dsge.subendyear,'String',DSGEModel.YearStrMatrix,'Value',DSGEModel.SubEndYearValue);
               set(controls.dsge.subendperiod,'String',DSGEModel.PeriodStrMatrix,'Value',DSGEModel.SubEndPeriodValue);
            end;
         end;
         set(controls.about,'UserData',0);
      end;
   case 'checkdatafile'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         NewDataFile = StringTrim(get(controls.dsge.datafile,'String'));
         if FileExist(NewDataFile)==1;
            %
            % make sure that the file is an m-file
            %
            [FilePath,FileName,FileExt] = fileparts(NewDataFile);
            if (strcmp(lower(FileExt),'.m')==1)|(strcmp(lower(FileExt),'.p')==1);
               %
               % we can now check the file
               %
               if strcmp(lower(FilePath),lower([pwd '\tmp']))==0;
                  [stat,msg] = dos(['copy /Y "' NewDataFile '" "' pwd '\tmp"']);
                  file = [pwd '\tmp\' FileName FileExt];
               else;
                  file = NewDataFile;
               end;
               if FileExist(file)==1;
                  ErrorStr = '';
                  try;
                     eval(['DataStructure = ' FileName ';']);
                  catch;
                     ErrorStr = ['Error found in data construction file "' FileName '". The error message caught is: ' lasterr];
                  end;
                  if isempty(ErrorStr)==1;
                     %
                     % now we check if DataStructure is valid
                     %
                     stat = CheckObservedDataFile(DataStructure,controls.dsge.datafile,DSGEModel.DataConstructionFile,[FileName FileExt],CurrINI);
                     if stat>=1;
                        %
                        % error messages have already been reported by CheckObservedDataFile with stat = 0
                        %
                        % make the necessary changes to the DSGEModel structure
                        %
                        DSGEModel.DataConstructionFile = NewDataFile;
                        DSGEModel.T = length(DataStructure.Y.data);
                        DSGEModel.n = length(DataStructure.Y.names);
                        DSGEModel.k = length(DataStructure.X.names);
                        DSGEModel.Y = DataStructure.Y.data;
                        if isfield(DataStructure.Y,'comparisondata')==1;
                           DSGEModel.CompY = DataStructure.Y.comparisondata;
                        else;
                           DSGEModel.CompY = [];
                        end;
                        DSGEModel.DataFrequency = lower(DataStructure.frequency(1,1));
                        ForecastStr = get(controls.forecast.maxhorizon,'UserData');
                        if strcmp(lower(DSGEModel.DataFrequency),'q')==1;
                           set(controls.forecast.maxhorizon,'String',ForecastStr.quarter);
                        elseif strcmp(lower(DSGEModel.DataFrequency),'m')==1;
                           set(controls.forecast.maxhorizon,'String',ForecastStr.month);
                        else;
                           set(controls.forecast.maxhorizon,'String',ForecastStr.annual);
                        end;
                        if (isfield(DataStructure.Y,'BVAR')==1)&(length(DataStructure.Y.BVAR)<=DSGEModel.n);
                           DSGEModel.BVARY = VerifyVector(DataStructure.Y.BVAR,DSGEModel.n);
                        else;
                           DSGEModel.BVARY = (1:DSGEModel.n);
                        end;
                        if (isfield(DataStructure.X,'BVAR')==1)&(length(DataStructure.X.BVAR)<=DSGEModel.k);
                           DSGEModel.BVARX = VerifyVector(DataStructure.X.BVAR,DSGEModel.k);
                        else;
                           DSGEModel.BVARX = (1:DSGEModel.k);
                        end;
                        if isfield(DataStructure.X,'extradata')==1;
                           %
                           % we need to test if this data is valid
                           %
                           if size(DataStructure.X.extradata,1)==DSGEModel.k;
                              DSGEModel.PredictedX = DataStructure.X.extradata;
                           else;
                              DSGEModel.PredictedX = [];
                           end;
                        else;
                           DSGEModel.PredictedX = [];
                        end;
                        if isfield(DataStructure,'percentiles')==1;
                           Ptiles = unique(DataStructure.percentiles);
                           %
                           % make sure that all entries are greater than 0, less than a 100, and integers
                           %
                           Ptiles = Ptiles(Ptiles>0);
                           Ptiles = Ptiles(Ptiles<100);
                           if length(Ptiles)>1;
                              if IsOdd(length(Ptiles))==1;
                                 Pmiddle = Ptiles(ceil(length(Ptiles)/2));
                                 Ptiles = Ptiles(Ptiles~=Pmiddle);
                              end;
                              DSGEModel.Percentiles = Ptiles;
                           else;
                              DSGEModel.Percentiles = [5 15 85 95];
                           end;
                        else;
                           DSGEModel.Percentiles = [5 15 85 95];
                        end;
                        if stat==1;
                           DSGEModel.levels = DataStructure.Y.levels;
                           if (isfield(DataStructure.Y,'annual')==1)&(length(DataStructure.Y.annual)==DSGEModel.n);
                              if strcmp(DSGEModel.DataFrequency,'q')==1;
                                 SampleFreq = 4;
                              elseif strcmp(DSGEModel.DataFrequency,'m')==1;
                                 SampleFreq = 12;
                              else;
                                 SampleFreq = 1;
                              end;
                              DSGEModel.annual = ((DataStructure.Y.annual)*(SampleFreq-1))+ones(1,DSGEModel.n);
                           else;
                              DSGEModel.annual = ones(1,DSGEModel.n);
                           end;
                           if (isfield(DataStructure.Y,'annualscale')==1)&(length(DataStructure.Y.annualscale)==DSGEModel.n);
                              DSGEModel.annualscale = ReplaceData(DataStructure.Y.annualscale,0,1);
                           else;
                              DSGEModel.annualscale = ones(1,DSGEModel.n);
                           end;
                        elseif stat==2;
                           DSGEModel.levels = ones(1,DSGEModel.n);
                           DSGEModel.annual = ones(1,DSGEModel.n);
                           DSGEModel.annualscale = ones(1,DSGEModel.n);
                        end;
                        if size(DSGEModel.Y,1)>size(DSGEModel.Y,2);
                           DSGEModel.Y = DSGEModel.Y';
                        end;
                        if size(DSGEModel.CompY,1)>size(DSGEModel.CompY,2);
                           DSGEModel.CompY = DSGEModel.CompY';
                        end;
                        if size(DSGEModel.Y)~=size(DSGEModel.CompY);
                           DSGEModel.CompY = [];
                        end;
                        DSGEModel.X = DataStructure.X.data;
                        if size(DSGEModel.X,1)>size(DSGEModel.X,2);
                           DSGEModel.X = DSGEModel.X';
                        end;
                        DSGEModel.YData = DSGEModel.Y;
                        DSGEModel.YDataOriginal = DSGEModel.Y;
                        DSGEModel.BeginYear = num2str(floor(DataStructure.sample(1)));
                        DSGEModel.BeginPeriod = num2str(floor(DataStructure.sample(2)));
                        DSGEModel.EndYear = num2str(floor(DataStructure.sample(3)));
                        DSGEModel.EndPeriod = num2str(floor(DataStructure.sample(4)));
                        DSGEModel.SubBeginYear = num2str(floor(DataStructure.sample(1)));
                        DSGEModel.SubBeginPeriod = num2str(floor(DataStructure.sample(2)));
                        DSGEModel.SubEndYear = num2str(floor(DataStructure.sample(3)));
                        DSGEModel.SubEndPeriod = num2str(floor(DataStructure.sample(4)));
                        DSGEModel.VariableNames = '';
                        for i=1:DSGEModel.n;
                           DSGEModel.VariableNames = strvcat(DSGEModel.VariableNames,DataStructure.Y.names{i});
                        end;
                        DSGEModel.XVariableNames = '';
                        for i=1:DSGEModel.k;
                           DSGEModel.XVariableNames = strvcat(DSGEModel.XVariableNames,DataStructure.X.names{i});
                        end;
                        if isfield(DataStructure.Y,'transformation')==1;
                           DSGEModel.YTransformation = DataStructure.Y.transformation;
                        else;
                           DSGEModel.YTransformation = [];
                        end;
                        %
                        % create the subsample strings and values
                        %
                        [DSGEModel.SubBeginYearValue,DSGEModel.SubBeginPeriodValue,DSGEModel.SubEndYearValue,DSGEModel.SubEndPeriodValue,DSGEModel.YearStrMatrix,DSGEModel.PeriodStrMatrix] = CreateEstimationSampleValues(DSGEModel);
                        %
                        set(controls.dsge.subbeginyear,'String',DSGEModel.YearStrMatrix,'Value',DSGEModel.SubBeginYearValue);
                        set(controls.dsge.subbeginperiod,'String',DSGEModel.PeriodStrMatrix,'Value',DSGEModel.SubBeginPeriodValue);
                        set(controls.dsge.subendyear,'String',DSGEModel.YearStrMatrix,'Value',DSGEModel.SubEndYearValue);
                        set(controls.dsge.subendperiod,'String',DSGEModel.PeriodStrMatrix,'Value',DSGEModel.SubEndPeriodValue);
                        %
                        [FirstPeriod,LastPeriod,EstSample] = CreateSubSample(DSGEModel);
                        DSGEModel.KalmanFirstObservation = 1;
                        set(controls.dsge.initializekalman,'String',EstSample,'Value',DSGEModel.KalmanFirstObservation);
                        %
                        % check if there is conditioning information
                        %
                        DSGEModel = VerifyConditioningInformation(DSGEModel,DataStructure);
                        %
                        % check if there is observed variable scenario information
                        %
                        DSGEModel = VerifyScenarioInformation(DSGEModel,DataStructure);
                        %
                        % Enable any controls that may be affected by this
                        %
                        set(controls.datainfo,'Enable','on');
                     else;
                        set(controls.dsge.datafile,'String',DSGEModel.DataConstructionFile);
                     end;
                  else;
                     set(controls.dsge.datafile,'String',DSGEModel.DataConstructionFile);
                     About(ErrorStr,'error',['Error - ' FileName],300,500,CurrINI);
                  end;
               end;
            else;
               set(controls.dsge.datafile,'String',DSGEModel.DataConstructionFile);
            end;
         else;
            if (strcmp(NewDataFile,'')==1)|isempty(NewDataFile)==1;
               ForecastStr = get(controls.forecast.maxhorizon,'UserData');
               DSGEModel.MaxForecastHorizon = 1;
               set(controls.forecast.maxhorizon,'String',ForecastStr.annual,'Value',DSGEModel.MaxForecastHorizon);
               DSGEModel.DataConstructionFile = pwd;
               DSGEModel.T = 0;
               DSGEModel.n = 0;
               DSGEModel.k = 0;
               DSGEModel.Y = [];
               DSGEModel.YData = [];
               DSGEModel.YDataOriginal = [];
               DSGEModel.CompY = [];
               DSGEModel.BVARY = [];
               DSGEModel.BVARX = [];
               DSGEModel.levels = [];
               DSGEModel.annual = [];
               DSGEModel.annualscale = [];
               DSGEModel.X = [];
               DSGEModel.PredictedX = [];
               DSGEModel.Percentiles = [5 15 85 95];
               DSGEModel.ConfidenceBandBaseColor = [1 1 1];
               DSGEModel.DataFrequency = '';
               DSGEModel.BeginYear = '';
               DSGEModel.BeginPeriod = '';
               DSGEModel.EndYear = '';
               DSGEModel.EndPeriod = '';
               DSGEModel.SubBeginYear = '';
               DSGEModel.SubBeginPeriod = '';
               DSGEModel.SubEndYear = '';
               DSGEModel.SubEndPeriod = '';
               DSGEModel.VariableNames = '';
               DSGEModel.XVariableNames = '';
               DSGEModel.Z = [];
               DSGEModel.ZVariableNames = '';
               DSGEModel.K1 = [];
               DSGEModel.K2 = [];
               DSGEModel.U = [];
               DSGEModel.C = [];
               DSGEModel.CData = [];
               DSGEModel.CDataComment = '';
               DSGEModel.CVariableNames = '';
               DSGEModel.ObsVariableScenarioFile = '';
               DSGEModel.C1 = [];
               DSGEModel.C2 = [];
               DSGEModel.CBar = [];
               DSGEModel.CDataOriginal = [];
               DSGEModel.CompData = [];
               DSGEModel.CompCBar = [];
               DSGEModel.CDataCommentOriginal = '';
               DSGEModel.CVariableNamesOriginal = '';
               DSGEModel.C1Original = [];
               DSGEModel.C2Original = [];
               DSGEModel.CBarOriginal = [];
               DSGEModel.YTransformation = [];
               DSGEModel.CTransformation = [];
               DSGEModel.CTransformationOriginal = [];
               DSGEModel.ZTransformation = [];
               DSGEModel.ZTransformationOriginal = [];
               DSGEModel.CExport = [];
               DSGEModel.CExportVariables = [];
               DSGEModel.CCreateData = [];
               DSGEModel.COrder = [];
            end;
            set(controls.dsge.datafile,'String',DSGEModel.DataConstructionFile);
            %
            % check if we need to disable any controls
            %
            if FileExist(DSGEModel.DataConstructionFile)==0;
               set(controls.datainfo,'Enable','off');
               %
               % create the subsample strings and value
               %
               [DSGEModel.SubBeginYearValue,DSGEModel.SubBeginPeriodValue,DSGEModel.SubEndYearValue,DSGEModel.SubEndPeriodValue,DSGEModel.YearStrMatrix,DSGEModel.PeriodStrMatrix] = CreateEstimationSampleValues(DSGEModel);
               %
               set(controls.dsge.subbeginyear,'String',DSGEModel.YearStrMatrix,'Value',DSGEModel.SubBeginYearValue);
               set(controls.dsge.subbeginperiod,'String',DSGEModel.PeriodStrMatrix,'Value',DSGEModel.SubBeginPeriodValue);
               set(controls.dsge.subendyear,'String',DSGEModel.YearStrMatrix,'Value',DSGEModel.SubEndYearValue);
               set(controls.dsge.subendperiod,'String',DSGEModel.PeriodStrMatrix,'Value',DSGEModel.SubEndPeriodValue);
               %
               DSGEModel.KalmanFirstObservation = 1;
               set(controls.dsge.initializekalman,'String',' ','Value',DSGEModel.KalmanFirstObservation);
            end;
         end;
         set(controls.about,'UserData',0);
      end;
   case 'browsepriorfile'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Open a file open dialog
         %
         status = FileBrowse(DSGEModel.PriorFile,'Open Prior Dist Specification File',controls.dsge.priorfile,'wk1',CurrINI);
         if status==1;
            [FilePath,FileName,FileExt] = fileparts(get(controls.dsge.priorfile,'String'));
            %
            % check if the file is an excel spreadsheet. if so we need to check which sheets there are
            %
            if strcmp(lower(FileExt),'.xls')==1;
               %
               % we must matlab version 6 or later. Check the spreadsheet for sheets
               %
               file = [FilePath '\' FileName FileExt];
               [fok,sheets] = xlsfinfo(file);
               if isempty(fok)==0;
                  if length(sheets)>1;
                     mysheets = sheets{1};
                     for i=2:length(sheets);
                        mysheets = [mysheets '|' sheets{i}];
                     end;
                     [action,selsheet] = SheetDlg(mysheets,file,CurrINI);
                     if strcmp(action,'Cancel')==1;
                        new_sheet = '';
                     else;
                        new_sheet = sheets{selsheet};
                     end;
                  else;
                     new_sheet = sheets;
                  end;
                  if strcmp(new_sheet,'')==0;
                     DSGEModel.PriorFile = file;
                     DSGEModel.PriorFileSheet = new_sheet;
                     set(controls.dsge.priorfilesheet,'String',['Sheet: ' new_sheet]);
                  else;
                     %
                     % cancelled
                     %
                     set(controls.dsge.priorfile,'String',DSGEModel.PriorFile);
                  end;
               else;
                  %
                  % The excel spreadsheet was not readable
                  %
                  set(controls.dsge.priorfile,'String',DSGEModel.PriorFile);
                  txt = ['The excel spreadsheet you selected "' FileName FileExt '" cannot be read by YADA. Please select another file.'];
                  About(txt,'information','Bad Excel Spreadsheet',120,500,CurrINI);
               end;
            else;
               %
               % Check to make sure the file is a Lotus 1-2-3 spreadsheet
               %
               if strcmp(lower(FileExt),'.wk1')==0;
                  set(controls.dsge.priorfile,'String',DSGEModel.PriorFile);
                  txt = ['The file you selected "' FileName FileExt '" is not a valid file for prior distribution  specifications. Please select a valid file for this purpose.'];
                  About(txt,'information','Invalid File Format',120,500,CurrINI);
               else;
                  [fok,chk] = wk1finfo([FilePath '\' FileName FileExt]);
                  if isempty(fok)==0;
                     DSGEModel.PriorFile = [FilePath '\' FileName FileExt];
                     DSGEModel.PriorFileSheet = 'None';
                     set(controls.dsge.priorfilesheet,'String','Sheet: None');
                  else;
                     %
                     % The Lotus spreadsheet was not readable
                     %
                     set(controls.dsge.priorfile,'String',DSGEModel.PriorFile);
                     txt = ['The Lotus 1-2-3 spreadsheet you selected "' FileName FileExt '" cannot be read by YADA. Please select another file.'];
                     About(txt,'information','Bad Lotus Spreadsheet',120,500,CurrINI);
                  end;
               end;
            end;
         end;
         set(controls.about,'UserData',0);
      end;
   case 'checkpriorfile'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Check if the prior file exists, and if it's either a proper Excel or Lotus 1-2-3 spreadsheet
         %
         new_prior_file = StringTrim(get(controls.dsge.priorfile,'String'));
         if FileExist(new_prior_file)==1;
            %
            % Now we try to verify that the file is valid
            %
            [FilePath,FileName,FileExt] = fileparts(new_prior_file);
            if strcmp(lower(FileExt),'.xls')==1;
               %
               % is the file a valid Excel spreadsheet
               %
               if MatlabNumber>=6;
                  %
                  % is the file a valid Excel spreadsheet
                  %
                  [fok,sheets] = xlsfinfo(new_prior_file);
                  if isempty(fok)==0;
                     %
                     % File is OK. If sheets has more than 1 element, open the SheetDlg dialog
                     %
                     if length(sheets)>1;
                        mysheets = sheets{1};
                        for i=2:length(sheets);
                           mysheets = [mysheets '|' sheets{i}];
                        end;
                        [action,selsheet] = SheetDlg(mysheets,new_prior_file,CurrINI);
                        if strcmp(action,'Cancel')==1;
                           new_sheet = '';
                        else;
                           new_sheet = sheets{selsheet};
                        end;
                     else;
                        new_sheet = sheets;
                     end;
                     if strcmp(new_sheet,'')==0;
                        DSGEModel.PriorFile = new_prior_file;
                        DSGEModel.PriorFileSheet = new_sheet;
                        set(controls.dsge.priorfilesheet,'String',['Sheet: ' new_sheet]);
                     else;
                        %
                        % cancelled
                        %
                        set(controls.dsge.priorfile,'String',DSGEModel.PriorFile);
                     end;
                  else;
                     %
                     % The file can't be read by YADA
                     %
                     set(controls.dsge.priorfile,'String',DSGEModel.PriorFile);
                     txt = ['The excel spreadsheet you selected "' FileName FileExt '" cannot be read by YADA. Please select another file.'];
                     About(txt,'information','Bad Excel Spreadsheet',120,500,CurrINI);
                  end;
               else;
                  %
                  % Excel spreadsheet are not supported
                  %
                  set(controls.dsge.priorfile,'String',DSGEModel.PriorFile);
                  txt = 'Your version of Matlab does not support Excel spreadsheets. Please use a different file format.';
                  About(txt,'information','Invalid File Format',100,400,CurrINI);
               end;
            elseif strcmp(lower(FileExt),'.wk1')==1;
               %
               % is the file a valid Lotus 1-2-3 spreadsheet
               %
               [fok,chk] = wk1finfo(new_prior_file);
               if isempty(fok)==0;
                  %
                  % yes, the file can be read by YADA
                  %
                  DSGEModel.PriorFile = [FilePath '\' FileName FileExt];
                  DSGEModel.PriorFileSheet = 'None';
                  set(controls.dsge.priorfilesheet,'String','Sheet: None');
               else;
                  %
                  % No, the Lotus spreadsheet was not readable
                  %
                  set(controls.dsge.priorfile,'String',DSGEModel.PriorFile);
                  txt = ['The Lotus 1-2-3 spreadsheet you selected "' FileName FileExt '" cannot be read by YADA. Please select another file.'];
                  About(txt,'information','Bad Lotus Spreadsheet',120,500,CurrINI);
               end;
            else;
               %
               % we don't have a valid spreadsheet
               %
               set(controls.dsge.priorfile,'String',DSGEModel.PriorFile);
               txt = ['The file you selected "' FileName FileExt '" is not a valid file for prior distribution  specifications. Please select a valid file for this purpose.'];
               About(txt,'information','Invalid File Format',120,500,CurrINI);
            end;
         else;
            if (strcmp(new_prior_file,'')==1)|(isempty(new_prior_file)==1);
               DSGEModel.PriorFile = pwd;
               DSGEModel.PriorFileSheet = 'None';
               set(controls.dsge.priorfilesheet,'String','Sheet: None');
            end;
            set(controls.dsge.priorfile,'String',DSGEModel.PriorFile);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'browseparameterfile'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         CurrField = strrep(get(gco,'Tag'),'Button','');
         if strcmp(CurrField,'UpdateParameterFile')==1;
            CurrControl = controls.dsge.updateparameterfile;
            OtherControl = controls.dsge.initialparameterfile;
            CurrStr = 'Open Update Parameters File';
         else;
            CurrControl = controls.dsge.initialparameterfile;
            OtherControl = controls.dsge.updateparameterfile;
            CurrStr = 'Open Initialize Parameters File';
         end;
         %
         % Open a file open dialog
         %
         status = FileBrowse(getfield(DSGEModel,CurrField),CurrStr,CurrControl,'m',CurrINI);
         if (status==1)&(strcmp(lower(GetName(StringTrim(get(CurrControl,'String')))),lower(GetName(StringTrim(get(OtherControl,'String')))))==0);
            DSGEModel = setfield(DSGEModel,CurrField,get(CurrControl,'String'));
         end;
         %
         if FileExist(DSGEModel.InitializeParameterFile)==1;
            set(controls.dsge.runinitialfirst,'Enable','on');
         else;
            DSGEModel.RunInitializeFirst = 0;
            set(controls.dsge.runinitialfirst,'Enable','off','Value',0);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'checkparameterfile'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         CurrField = strrep(get(gco,'Tag'),'EditBox','');
         if strcmp(CurrField,'UpdateParameterFile')==1;
            CurrControl = controls.dsge.updateparameterfile;
            OtherControl = controls.dsge.initialparameterfile;
            CurrStr = 'Open Update Parameters File';
         else;
            CurrControl = controls.dsge.initialparameterfile;
            OtherControl = controls.dsge.updateparameterfile;
            CurrStr = 'Open Initialize Parameters File';
         end;
         %
         new_me_file = StringTrim(get(CurrControl,'String'));
         if FileExist(new_me_file)==1;
            %
            % make sure that the file is an m-file
            %
            [FilePath,FileName,FileExt] = fileparts(new_me_file);
            if ((strcmp(lower(FileExt),'.m')==1)|(strcmp(lower(FileExt),'.p')==1))&(strcmp(lower(FileName),lower(GetName(StringTrim(get(OtherControl,'String')))))==0);
               DSGEModel = setfield(DSGEModel,CurrField,new_me_file);
            else;
               set(CurrControl,'String',getfield(DSGEModel,CurrField));
            end;
         else;
            if (strcmp(new_me_file,'')==1)|(isempty(new_me_file)==1)|(strcmp(lower(new_me_file),lower(pwd))==1)|(strcmp(lower(new_me_file),lower([pwd '\']))==1);
               DSGEModel = setfield(DSGEModel,CurrField,pwd);
            end;
            set(CurrControl,'String',getfield(DSGEModel,CurrField));
         end;
         if FileExist(DSGEModel.InitializeParameterFile)==1;
            set(controls.dsge.runinitialfirst,'Enable','on');
         else;
            DSGEModel.RunInitializeFirst = 0;
            set(controls.dsge.runinitialfirst,'Enable','off','Value',0);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'initializefirst'
      if get(controls.about,'UserData')==0;
         DSGEModel.RunInitializeFirst = get(controls.dsge.runinitialfirst,'Value');
      else;
         set(controls.dsge.runinitialfirst,'Value',DSGEModel.RunInitializeFirst);
      end;
   case 'usedoublingalgorithm'
      if get(controls.about,'UserData')==0;
         DSGEModel.UseDoublingAlgorithm = get(controls.dsge.usedoublingalgorithm,'Value');
      else;
         set(controls.dsge.usedoublingalgorithm,'Value',DSGEModel.UseDoublingAlgorithm);
      end;
      if DSGEModel.UseDoublingAlgorithm==2;
         set(controls.dsge.doublingalgorithmtext,'Enable','on');
         set(controls.dsge.doublingalgorithm,'Enable','on');
         set(controls.dsge.doublingtolerancetext,'Enable','on');
         set(controls.dsge.doublingtolerance,'Enable','on');
         set(controls.dsge.statecovariancetext,'Enable','off');
         set(controls.dsge.statecovariance,'Enable','off');
      elseif DSGEModel.UseDoublingAlgorithm==3;
         set(controls.dsge.doublingalgorithmtext,'Enable','off');
         set(controls.dsge.doublingalgorithm,'Enable','off');
         set(controls.dsge.doublingtolerancetext,'Enable','off');
         set(controls.dsge.doublingtolerance,'Enable','off');
         set(controls.dsge.statecovariancetext,'Enable','on');
         set(controls.dsge.statecovariance,'Enable','on');
      else;
         set(controls.dsge.doublingalgorithmtext,'Enable','off');
         set(controls.dsge.doublingalgorithm,'Enable','off');
         set(controls.dsge.doublingtolerancetext,'Enable','off');
         set(controls.dsge.doublingtolerance,'Enable','off');
         set(controls.dsge.statecovariancetext,'Enable','off');
         set(controls.dsge.statecovariance,'Enable','off');
      end;
   case 'showprogressclock'
      if get(controls.about,'UserData')==0;
         DSGEModel.ShowProgressClock = get(controls.dsge.progressclock,'Value');
      else;
         set(controls.dsge.progressclock,'Value',DSGEModel.ShowProgressClock);
      end;
   case 'sequentialsteplength'
      if get(controls.about,'UserData')==0;
         DSGEModel.SequentialStepLength = get(controls.dsge.sequentialstep,'Value');
      else;
         set(controls.dsge.sequentialstep,'Value',DSGEModel.SequentialStepLength);
      end;
   case 'sequentialstartiteration'
      if get(controls.about,'UserData')==0;
         DSGEModel.SequentialStartIteration = get(controls.dsge.sequentialstart,'Value');
      else;
         set(controls.dsge.sequentialstart,'Value',DSGEModel.SequentialStartIteration);
      end;
   case 'marginallikelihood'
      if get(controls.about,'UserData')==0;
         DSGEModel.MarginalLikelihoodValue = get(controls.dsge.marginallikelihood,'Value');
      else;
         set(controls.dsge.marginallikelihood,'Value',DSGEModel.MarginalLikelihoodValue);
      end;
   case 'coverageprobability'
      if get(controls.about,'UserData')==0;
         DSGEModel.CoverageStart = get(controls.dsge.coveragestart,'Value');
         DSGEModel.CoverageIncrement = get(controls.dsge.coverageincrement,'Value');
         DSGEModel.CoverageEnd = get(controls.dsge.coverageend,'Value');
      else;
         set(controls.dsge.coveragestart,'Value',DSGEModel.CoverageStart);
         set(controls.dsge.coverageincrement,'Value',DSGEModel.CoverageIncrement);
         set(controls.dsge.coverageend,'Value',DSGEModel.CoverageEnd);
      end;
   case 'sequentialml'
      if get(controls.about,'UserData')==0;
         DSGEModel.SequentialML = get(controls.dsge.sequentialml,'Value');
      else;
         set(controls.dsge.sequentialml,'Value',DSGEModel.SequentialML);
      end;
   case 'overwritedraws'
      if get(controls.about,'UserData')==0;
         DSGEModel.OverwriteDraws = get(controls.dsge.overwritedraws,'Value');
      else;
         set(controls.dsge.overwritedraws,'Value',DSGEModel.OverwriteDraws);
      end;
   case 'showprogress'
      if get(controls.about,'UserData')==0;
         DSGEModel.ShowProgress = get(controls.dsge.progress,'Value');
      else;
         set(controls.dsge.progress,'Value',DSGEModel.ShowProgress);
      end;
      if DSGEModel.ShowProgress==1;
         set(controls.dsge.progressclock,'Enable','on');
      else;
         set(controls.dsge.progressclock,'Enable','off');
      end;
   case 'useowninitialstate'
      if get(controls.about,'UserData')==0;
         DSGEModel.UseOwnInitialState = get(controls.dsge.useowninitialstate,'Value');
      else;
         set(controls.dsge.useowninitialstate,'Value',DSGEModel.UseOwnInitialState);
      end;
   case 'allowunitroot'
      if get(controls.about,'UserData')==0;
         DSGEModel.AllowUnitRoot = get(controls.dsge.allowunitroot,'Value');
      else;
         set(controls.dsge.allowunitroot,'Value',DSGEModel.AllowUnitRoot);
      end;
   case 'initializekalman'
      if get(controls.about,'UserData')==0;
         DSGEModel.KalmanFirstObservation = get(controls.dsge.initializekalman,'Value');
      else;
         set(controls.dsge.initializekalman,'Value',DSGEModel.KalmanFirstObservation);
      end;
   case 'aimtolerance'
      if get(controls.about,'UserData')==0;
         DSGEModel.AIMTolerance = get(controls.dsge.aimtolerance,'Value')+1;
      else;
         set(controls.dsge.aimtolerance,'Value',DSGEModel.AIMTolerance-1);
      end;
   case 'doublingalgorithm'
      if get(controls.about,'UserData')==0;
         DSGEModel.DAMaximumIterationsValue = get(controls.dsge.doublingalgorithm,'Value');
      else;
         set(controls.dsge.doublingalgorithm,'Value',DSGEModel.DAMaximumIterationsValue);
      end;
   case 'predpaths'
      if get(controls.about,'UserData')==0;
         DSGEModel.NumPredPathsValue = get(controls.forecast.predpaths,'Value');
      else;
         set(controls.forecast.predpaths,'Value',DSGEModel.NumPredPathsValue);
      end;
   case 'shockcontrol'
      if get(controls.about,'UserData')==0;
         DSGEModel.ShockControlMethod = get(controls.forecast.shockcontrol,'Value');
      else;
         set(controls.forecast.shockcontrol,'Value',DSGEModel.ShockControlMethod);
      end;
%   case 'freqreest'
%      if get(controls.about,'UserData')==0;
%         DSGEModel.FreqParameterReest = get(controls.forecast.freqreest,'Value');
%      else;
%         set(controls.forecast.freqreest,'Value',DSGEModel.FreqParameterReest);
%      end;
   case 'maxforecasthorizon'
      if get(controls.about,'UserData')==0;
         DSGEModel.MaxForecastHorizon = get(controls.forecast.maxhorizon,'Value');
      else;
         set(controls.forecast.maxhorizon,'Value',DSGEModel.MaxForecastHorizon);
      end;
   case 'riccati_maximumiterations'
      if get(controls.about,'UserData')==0;
         DSGEModel.RiccatiMaxIterations = get(controls.tools.riccatiiteration,'Value');
      else;
         set(controls.tools.riccatiiteration,'Value',DSGEModel.RiccatiMaxIterations);
      end;
   case 'maximumiterations'
      if get(controls.about,'UserData')==0;
         DSGEModel.OptMaxIterationsValue = get(controls.optimize.maximumiterations,'Value');
      else;
         set(controls.optimize.maximumiterations,'Value',DSGEModel.OptMaxIterationsValue);
      end;
   case 'tolerance'
      if get(controls.about,'UserData')==0;
         DSGEModel.OptToleranceValue = get(controls.optimize.tolerance,'Value');
      else;
         set(controls.optimize.tolerance,'Value',DSGEModel.OptToleranceValue);
      end;
   case 'statecov'
      if get(controls.about,'UserData')==0;
         DSGEModel.StateCovConst = get(controls.dsge.statecovariance,'Value');
         StateCStr = get(controls.dsge.statecovariance,'String');
         DSGEModel.StateCovConstValue = str2num(strrep(StringTrim(StateCStr(DSGEModel.StateCovConst,:)),',',''));
      else;
         set(controls.dsge.statecovariance,'Value',DSGEModel.StateCovConst);
      end;
   case 'da_tolerance'
      if get(controls.about,'UserData')==0;
         DSGEModel.DAToleranceValue = get(controls.dsge.doublingtolerance,'Value');
      else;
         set(controls.dsge.doublingtolerance,'Value',DSGEModel.DAToleranceValue);
      end;
   case 'riccati_tolerance'
      if get(controls.about,'UserData')==0;
         DSGEModel.RiccatiToleranceValue = get(controls.tools.riccatitolerance,'Value');
      else;
         set(controls.tools.riccatitolerance,'Value',DSGEModel.RiccatiToleranceValue);
      end;
   case 'randomweight'
      if get(controls.about,'UserData')==0;
         DSGEModel.RandomWeightValue = get(controls.posterior.randomweight,'Value');
      else;
         set(controls.posterior.randomweight,'Value',DSGEModel.RandomWeightValue);
      end;
   case 'scalefactor'
      if get(controls.about,'UserData')==0;
         DSGEModel.MHScaleFactor = get(controls.posterior.scalefactor,'Value');
      else;
         set(controls.posterior.scalefactor,'Value',DSGEModel.MHScaleFactor);
      end;
   case 'initialscalefactor'
      if get(controls.about,'UserData')==0;
         DSGEModel.MHInitialScaleFactor = get(controls.posterior.initialscale,'Value');
      else;
         set(controls.posterior.initialscale,'Value',DSGEModel.MHInitialScaleFactor);
      end;
   case 'invhessian'
      if get(controls.about,'UserData')==0;
         CurrValue = get(controls.posterior.invhessian,'Value');
         if CurrValue<=3;
            DSGEModel.InverseHessianEstimator = CurrValue;
         else;
            %
            % user wants to use own covariance matrix estimator
            %
            if FileExist(DSGEModel.ParameterCovMatrix)==1;
               ParameterCovMatrix = DSGEModel.ParameterCovMatrix;
            else;
               %
               % suggest a mat-file and check if it exists
               %
               BurninStr = get(controls.posterior.burnin,'String');
               NumBurnin = str2num(strrep(StringTrim(BurninStr(DSGEModel.BurnInValue,:)),',',''));
               %
               DrawsStr = get(controls.posterior.draws,'String');
               NumDraws = str2num(StringTrim(strrep(DrawsStr(DSGEModel.PosteriorDrawsValue,:),',','')));
               %
               ParameterCovMatrix = [DSGEModel.OutputDirectory '\' DSGEModel.NameOfModel '-EstParamCovarianceMatrix-' int2str(NumBurnin) '.' int2str(NumDraws) '.1.mat'];
               if FileExist(ParameterCovMatrix)==0;
                  ParameterCovMatrix = [pwd '\.mat'];
               end;
            end;
            %
            % select the file
            %
            [FileName,FilePath] = uigetfile(ParameterCovMatrix,'Parameter Covariance Matrix - Select File');
            drawnow;
            pause(0.02);
            %
            SelectedFile = [FilePath FileName];
            if (isnumeric(FileName)==0)&(FileExist(SelectedFile)==1);
               if strcmp(lower(GetExt(SelectedFile)),'.mat')==1;
                  %
                  % check if the file has the required field.
                  %
                  DataTest = load(SelectedFile);
                  if isfield(DataTest,'ParameterCovarianceMatrix')==1;
                     DSGEModel.ParameterCovMatrix = SelectedFile;
                     DSGEModel.InverseHessianEstimator = CurrValue;
                     set(controls.posterior.invhessian,'String',['Output from optimization routine|Fit quadratic to evaluated log posterior|Finite difference|My estimate ("' GetName(DSGEModel.ParameterCovMatrix) '")']);
                  else;
                     set(controls.posterior.invhessian,'Value',DSGEModel.InverseHessianEstimator);
                     txt = ['The file you selected "' GetFilename(SelectedFile) '" doesn''t have a variable called "ParameterCovarianceMatrix". YADA is therefore unable to accept the data.'];
                     About(txt,'information','Parameter Covariance Matrix - Bad Data',200,500,CurrINI);
                  end;
               else;
                  %
                  % bad file format
                  %
                  set(controls.posterior.invhessian,'Value',DSGEModel.InverseHessianEstimator);
                  txt = ['YADA requires that the file with the parameter covariance matrix is a mat-file. The one you selected "' GetFilename(SelectedFile) '" is not.'];
                  About(txt,'information','Parameter Covariance Matrix - Bad Format',200,500,CurrINI);
               end;
            else;
               set(controls.posterior.invhessian,'Value',DSGEModel.InverseHessianEstimator);
            end;
         end;
      else;
         set(controls.posterior.invhessian,'Value',DSGEModel.InverseHessianEstimator);
      end;
   case 'maxhesscorrelation'
      if get(controls.about,'UserData')==0;
         DSGEModel.MaxCorrelationValue = get(controls.posterior.maxcorrelation,'Value');
      else;
         set(controls.posterior.maxcorrelation,'Value',DSGEModel.MaxCorrelationValue);
      end;
   case 'burnin'
      if get(controls.about,'UserData')==0;
         DSGEModel.BurnInValue = get(controls.posterior.burnin,'Value');
      else;
         set(controls.posterior.burnin,'Value',DSGEModel.BurnInValue);
      end;
   case 'parallelchains'
      if get(controls.about,'UserData')==0;
         DSGEModel.ParallelChainsValue = get(controls.posterior.chains,'Value');
      else;
         set(controls.posterior.chains,'Value',DSGEModel.ParallelChainsValue);
      end;
   case 'samplebatches'
      if get(controls.about,'UserData')==0;
         DSGEModel.SampleBatchValue = get(controls.posterior.batch,'Value');
      else;
         set(controls.posterior.batch,'Value',DSGEModel.SampleBatchValue);
      end;
   case 'usepostdraws'
      if get(controls.about,'UserData')==0;
         DSGEModel.PostDrawsPercentValue = get(controls.posterior.usepostdraws,'Value');
      else;
         set(controls.posterior.usepostdraws,'Value',DSGEModel.PostDrawsPercentValue);
      end;
   case 'postdrawsusage'
      if get(controls.about,'UserData')==0;
         DSGEModel.PostDrawsUsageValue = get(controls.posterior.postdrawsusage,'Value');
      else;
         set(controls.posterior.postdrawsusage,'Value',DSGEModel.PostDrawsUsageValue);
      end;
   case 'posteriordraws'
      if get(controls.about,'UserData')==0;
         DSGEModel.PosteriorDrawsValue = get(controls.posterior.draws,'Value');
      else;
         set(controls.posterior.draws,'Value',DSGEModel.PosteriorDrawsValue);
      end;
   case 'irhorizon'
      if get(controls.about,'UserData')==0;
         DSGEModel.IRHorizon = get(controls.tools.irhorizon,'Value');
      else;
         set(controls.tools.irhorizon,'Value',DSGEModel.IRHorizon);
      end;
   case 'randomnumbervalue'
      if get(controls.about,'UserData')==0;
         DSGEModel.RandomNumberValue = get(controls.tools.randomnumber,'Value');
      else;
         set(controls.tools.randomnumber,'Value',DSGEModel.RandomNumberValue);
      end;
   case 'randomizedraws'
      if get(controls.about,'UserData')==0;
         DSGEModel.RandomizeDraws = get(controls.tools.randomizedraws,'Value');
      else;
         set(controls.tools.randomizedraws,'Value',DSGEModel.RandomizeDraws);
      end;
   case 'maxroutine'
      if get(controls.about,'UserData')==0;
         DSGEModel.MaximizeAlgorithmValue = get(controls.optimize.maxroutine,'Value');
      else;
         set(controls.optimize.maxroutine,'Value',DSGEModel.MaximizeAlgorithmValue);
      end;
   case 'hessiansteplength'
      if get(controls.about,'UserData')==0;
         DSGEModel.StepLengthHessian = get(controls.optimize.steplength,'Value');
      else;
         set(controls.optimize.steplength,'Value',DSGEModel.StepLengthHessian);
      end;
   case 'initcsminwel'
      if get(controls.about,'UserData')==0;
         DSGEModel.InitializeHessian = get(controls.optimize.initcsminwel,'Value');
      else;
         set(controls.optimize.initcsminwel,'Value',DSGEModel.InitializeHessian);
      end;
   case 'gridwidth'
      if get(controls.about,'UserData')==0;
         DSGEModel.GridWidth = get(controls.optimize.gridwidth,'Value');
      else;
         set(controls.optimize.gridwidth,'Value',DSGEModel.GridWidth);
      end;
   case 'numbergridpoints'
      if get(controls.about,'UserData')==0;
         DSGEModel.NumberOfGridPoints = get(controls.optimize.numbergridpoints,'Value');
      else;
         set(controls.optimize.numbergridpoints,'Value',DSGEModel.NumberOfGridPoints);
      end;
   case 'finitediffhessian'
      if get(controls.about,'UserData')==0;
         DSGEModel.FiniteDifferenceHessian = get(controls.optimize.finitediffhessian,'Value');
      else;
         set(controls.optimize.finitediffhessian,'Value',DSGEModel.FiniteDifferenceHessian);
      end;
   case 'checkadjustpredictionpaths'
      if get(controls.about,'UserData')==0;
         DSGEModel.AdjustPredictionPaths = get(controls.forecast.adjustpredictionpaths,'Value');
      else;
         set(controls.forecast.adjustpredictionpaths,'Value',DSGEModel.AdjustPredictionPaths);
      end;
   case 'checkksiuseconddata'
      if get(controls.about,'UserData')==0;
         DSGEModel.KsiUseCondData = get(controls.forecast.ksiuseconddata,'Value');
      else;
         set(controls.forecast.ksiuseconddata,'Value',DSGEModel.KsiUseCondData);
      end;
   case 'checkoptimum'
      if get(controls.about,'UserData')==0;
         DSGEModel.CheckOptimum = get(controls.optimize.checkoptimum,'Value');
      else;
         set(controls.optimize.checkoptimum,'Value',DSGEModel.CheckOptimum);
      end;
      if DSGEModel.CheckOptimum==1;
         set(controls.optimize.gridwidthtext,'Enable','on');
         set(controls.optimize.gridwidth,'Enable','on');
         set(controls.optimize.numbergridpoints,'Enable','on');
         set(controls.optimize.numbergridpointstext,'Enable','on');
         set(controls.optimize.checktransformed,'Enable','on');
         set(controls.optimize.modifiedhessian,'Enable','on');
      else;
         set(controls.optimize.gridwidthtext,'Enable','off');
         set(controls.optimize.gridwidth,'Enable','off');
         set(controls.optimize.numbergridpoints,'Enable','off');
         set(controls.optimize.numbergridpointstext,'Enable','off');
         set(controls.optimize.checktransformed,'Enable','off');
         set(controls.optimize.modifiedhessian,'Enable','off');
      end;
   case 'checktransformedoptimum'
      if get(controls.about,'UserData')==0;
         DSGEModel.CheckTransformedOptimum = get(controls.optimize.checktransformed,'Value');
      else;
         set(controls.optimize.checktransformed,'Value',DSGEModel.CheckTransformedOptimum);
      end;
   case 'checkmodifiedhessian'
      if get(controls.about,'UserData')==0;
         if DSGEModel.ModifiedHessian==1;
            txt = 'Are you sure you don''t want to scale the estimated conditional standard deviations of the modified inverse Hessian with the correlations from the inverse Hessian at the posterior mode when running the random-walk Metropolis algorithm?';
         else;
            txt = 'Are you sure you want to scale the estimated conditional standard deviations of the modified inverse Hessian with the correlations from the inverse Hessian at the posterior mode when running the random-walk Metropolis algorithm?';
         end;
         answer = Query(txt,'information',200,'Posterior Sampling - Modified Inverse Hessian',500,'no',CurrINI);
         if strcmp(lower(answer),'yes')==1;
            DSGEModel.ModifiedHessian = get(controls.optimize.modifiedhessian,'Value');
         else;
            set(controls.optimize.modifiedhessian,'Value',DSGEModel.ModifiedHessian);
         end;
      else;
         set(controls.optimize.modifiedhessian,'Value',DSGEModel.ModifiedHessian);
      end;
   case 'priorlevelmean'
      if get(controls.about,'UserData')==0;
         DSGEModel.PriorLevelMeanValue = get(controls.bvar.priorlevelmean,'Value');
      else;
         set(controls.bvar.priorlevelmean,'Value',DSGEModel.PriorLevelMeanValue);
      end;
   case 'priordiffmean'
      if get(controls.about,'UserData')==0;
         DSGEModel.PriorDiffMeanValue = get(controls.bvar.priordiffmean,'Value');
      else;
         set(controls.bvar.priordiffmean,'Value',DSGEModel.PriorDiffMeanValue);
      end;
   case 'priortype'
      if get(controls.about,'UserData')==0;
         DSGEModel.PriorType = get(controls.bvar.priortype,'Value');
      else;
         set(controls.bvar.priortype,'Value',DSGEModel.PriorType);
      end;
      if DSGEModel.PriorType~=3;
         set(controls.bvar.priorlevelmeantext,'Enable','on');
         set(controls.bvar.priorlevelmean,'Enable','on');
         set(controls.bvar.priordiffmeantext,'Enable','on');
         set(controls.bvar.priordiffmean,'Enable','on');
         set(controls.bvar.overalltightnesstext,'Enable','on');
         set(controls.bvar.overalltightness,'Enable','on');
         set(controls.bvar.crosseqtightnesstext,'Enable','on');
         set(controls.bvar.crosseqtightness,'Enable','on');
         set(controls.bvar.harmoniclagdecaytext,'Enable','on');
         set(controls.bvar.harmoniclagdecay,'Enable','on');
      else;
         set(controls.bvar.priorlevelmeantext,'Enable','off');
         set(controls.bvar.priorlevelmean,'Enable','off');
         set(controls.bvar.priordiffmeantext,'Enable','off');
         set(controls.bvar.priordiffmean,'Enable','off');
         set(controls.bvar.overalltightnesstext,'Enable','off');
         set(controls.bvar.overalltightness,'Enable','off');
         set(controls.bvar.crosseqtightnesstext,'Enable','off');
         set(controls.bvar.crosseqtightness,'Enable','off');
         set(controls.bvar.harmoniclagdecaytext,'Enable','off');
         set(controls.bvar.harmoniclagdecay,'Enable','off');
      end;
   case 'overalltightness'
      if get(controls.about,'UserData')==0;
         DSGEModel.OverallTightnessValue = get(controls.bvar.overalltightness,'Value');
      else;
         set(controls.bvar.overalltightness,'Value',DSGEModel.OverallTightnessValue);
      end;
   case 'crossequationtightness'
      if get(controls.about,'UserData')==0;
         DSGEModel.CrossEqTightnessValue = get(controls.bvar.crosseqtightness,'Value');
      else;
         set(controls.bvar.crosseqtightness,'Value',DSGEModel.CrossEqTightnessValue);
      end;
   case 'harmoniclagdecay'
      if get(controls.about,'UserData')==0;
         DSGEModel.HarmonicLagDecayValue = get(controls.bvar.harmoniclagdecay,'Value');
      else;
         set(controls.bvar.harmoniclagdecay,'Value',DSGEModel.HarmonicLagDecayValue);
      end;
   case 'bvarlags'
      if get(controls.about,'UserData')==0;
         DSGEModel.BVARLags = get(controls.bvar.lag,'Value');
      else;
         set(controls.bvar.lag,'Value',DSGEModel.BVARLags);
      end;
   case 'wishartdf'
      if get(controls.about,'UserData')==0;
         DSGEModel.WishartDFValue = get(controls.bvar.wishartdf,'Value');
      else;
         set(controls.bvar.wishartdf,'Value',DSGEModel.WishartDFValue);
      end;
   case 'variancetightness'
      if get(controls.about,'UserData')==0;
         DSGEModel.VarianceTightnessValue = get(controls.bvar.variancetightness,'Value');
      else;
         set(controls.bvar.variancetightness,'Value',DSGEModel.VarianceTightnessValue);
      end;
   case 'wisharttype'
      if get(controls.about,'UserData')==0;
         DSGEModel.WishartType = get(controls.bvar.wisharttype,'Value');
      else;
         set(controls.bvar.wisharttype,'Value',DSGEModel.WishartType);
      end;
      if DSGEModel.WishartType==1;
         %
         % controls to disable
         %
         set(controls.bvar.variancetightnesstext,'Enable','off');
         set(controls.bvar.variancetightness,'Enable','off');
      else;
         %
         % controls to enable
         %
         set(controls.bvar.variancetightnesstext,'Enable','on');
         set(controls.bvar.variancetightness,'Enable','on');
      end;
   case 'omegapriortype'
      if get(controls.about,'UserData')==0;
         DSGEModel.OmegaPriorType = get(controls.bvar.omegapriortype,'Value');
      else;
         set(controls.bvar.omegapriortype,'Value',DSGEModel.OmegaPriorType);
      end;
      if DSGEModel.OmegaPriorType==1;
         %
         % controls to disable
         %
         set(controls.bvar.wisharttypetext,'Enable','off');
         set(controls.bvar.wisharttype,'Enable','off');
         set(controls.bvar.variancetightnesstext,'Enable','off');
         set(controls.bvar.variancetightness,'Enable','off');
         set(controls.bvar.wishartdftext,'Enable','off');
         set(controls.bvar.wishartdf,'Enable','off');
      else;
         %
         % controls to enable
         %
         set(controls.bvar.wisharttypetext,'Enable','on');
         set(controls.bvar.wisharttype,'Enable','on');
         set(controls.bvar.wishartdftext,'Enable','on');
         set(controls.bvar.wishartdf,'Enable','on');
         if DSGEModel.WishartType==1;
            set(controls.bvar.variancetightnesstext,'Enable','off');
            set(controls.bvar.variancetightness,'Enable','off');
         else;
            set(controls.bvar.variancetightnesstext,'Enable','on');
            set(controls.bvar.variancetightness,'Enable','on');
         end;
      end;
   case 'kerneldensity'
      if get(controls.about,'UserData')==0;
         DSGEModel.KernelDensityValue = get(controls.graphics.kerneldensity,'Value');
         DensityEstimators = strvcat('knorm','kepan','krect','ktria','kbiwe','ktriw','klapl','klogi');
         DSGEModel.KernelDensityEstimator = StringTrim(DensityEstimators(DSGEModel.KernelDensityValue,:));
      else;
         set(controls.graphics.kerneldensity,'Value',DSGEModel.KernelDensityValue);
      end;
   case 'posteriorkerneldensity'
      if get(controls.about,'UserData')==0;
         DSGEModel.PosteriorDensityValue = get(controls.graphics.posteriorkernel,'Value');
      else;
         set(controls.graphics.posteriorkernel,'Value',DSGEModel.PosteriorDensityValue);
      end;
   case 'priorkernel'
      if get(controls.about,'UserData')==0;
         DSGEModel.PriorKernel = get(controls.graphics.priorkernel,'Value');
      else;
         set(controls.graphics.priorkernel,'Value',DSGEModel.PriorKernel);
      end;
      if DSGEModel.PriorKernel==1;
         set(controls.graphics.kerneldensitytext,'Enable','on');
         set(controls.graphics.kerneldensity,'Enable','on');
      else;
         set(controls.graphics.kerneldensitytext,'Enable','off');
         set(controls.graphics.kerneldensity,'Enable','off');
      end;
   case 'browseoutput'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         if MatlabNumber>=6.5;
            %
            % Use the matlab function
            %
            NewDirectory = uigetdir(DSGEModel.OutputDirectory,'Select Base Output Directory');
         else;
            NewDirectory = UIGetDirectory(DSGEModel.OutputDirectory,'Select Base Output Directory',CurrINI);
         end;
         if ischar(NewDirectory)==1;
            %
            % check if the last character is \
            %
            if strcmp(NewDirectory(1,length(NewDirectory)),'\')==1;
               NewDirectory = NewDirectory(1,1:length(NewDirectory)-1);
            end;
            DSGEModel.OutputDirectory = NewDirectory;
            set(controls.outputdir,'String',DSGEModel.OutputDirectory);
            %
            % check if aim file exists
            %
            if FileExist(DSGEModel.AIMFile)==1;
               AIMDataFile = [DSGEModel.OutputDirectory '\' DSGEModel.NameOfModel '.mat'];
               if FileExist(AIMDataFile)==1;
                  DSGEModel.AIMDataFile = AIMDataFile;
                  StateEnable = 'on';
               else;
                  DSGEModel.AIMDataFile = pwd;
                  StateEnable = 'off';
               end;
               set(controls.statevar,'Enable',StateEnable);
               set(controls.statevarmenu,'Enable',StateEnable);
               set(controls.stateshock,'Enable',StateEnable);
               set(controls.stateshockmenu,'Enable',StateEnable);
            else;
               DSGEModel.AIMDataFile = pwd;
               set(controls.statevar,'Enable','off');
               set(controls.statevarmenu,'Enable','off');
               set(controls.stateshock,'Enable','off');
               set(controls.stateshockmenu,'Enable','off');
            end;
         end;
         set(controls.about,'UserData',0);
      end;
   case 'checkoutput'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         new_dir = StringTrim(get(controls.outputdir,'String'));
         %
         % check if we have a valid directory
         %
         if (strcmp(new_dir,'')==0)|(isempty(new_dir)==1);
            if length(new_dir)>3;
               if strcmp(new_dir(1,2:3),':\')==1;
                  if DirExist(new_dir(1,1:3))==1;
                     %
                     % we have a valid drive
                     %
                     if DirExist(new_dir)==0;
                        stat = dos(['mkdir ' new_dir]);
                     end;
                     if strcmp(new_dir(1,length(new_dir)),'\')==1;
                        new_dir = new_dir(1,1:length(new_dir)-1);
                     end;
                     DSGEModel.OutputDirectory = new_dir;
                     set(controls.outputdir,'String',DSGEModel.OutputDirectory);
                     %
                     % check if aim file exists
                     %
                     if FileExist(DSGEModel.AIMFile)==1;
                        AIMDataFile = [DSGEModel.OutputDirectory '\' DSGEModel.NameOfModel '.mat'];
                        if FileExist(AIMDataFile)==1;
                           DSGEModel.AIMDataFile = AIMDataFile;
                           StateEnable = 'on';
                        else;
                           DSGEModel.AIMDataFile = pwd;
                           StateEnable = 'off';
                        end;
                        set(controls.statevar,'Enable',StateEnable);
                        set(controls.statevarmenu,'Enable',StateEnable);
                        set(controls.stateshock,'Enable',StateEnable);
                        set(controls.stateshockmenu,'Enable',StateEnable);
                     else;
                        DSGEModel.AIMDataFile = pwd;
                        set(controls.statevar,'Enable','off');
                        set(controls.statevarmenu,'Enable','off');
                        set(controls.stateshock,'Enable','off');
                        set(controls.stateshockmenu,'Enable','off');
                     end;
                  else;
                     set(controls.outputdir,'String',DSGEModel.OutputDirectory);
                  end;
               else;
                  set(controls.outputdir,'String',DSGEModel.OutputDirectory);
               end;
            else;
               set(controls.outputdir,'String',DSGEModel.OutputDirectory);
            end;
         else;
            set(controls.outputdir,'String',DSGEModel.OutputDirectory);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'checksample'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         if DSGEModel.T>0;
            %
            % get the information from the sample selection controls
            %
            subbeginyearstr = get(controls.dsge.subbeginyear,'String');
            subbeginyearvalue = get(controls.dsge.subbeginyear,'Value');
            subbeginperiodvalue = get(controls.dsge.subbeginperiod,'Value');
            subendyearstr = get(controls.dsge.subendyear,'String');
            subendyearvalue = get(controls.dsge.subendyear,'Value');
            subendperiodvalue = get(controls.dsge.subendperiod,'Value');
            %
            % compute the selected sample values
            %
            subbeginyear = floor(str2num(StringTrim(subbeginyearstr(subbeginyearvalue,:))));
            subbeginperiod = subbeginperiodvalue;
            subendyear = floor(str2num(StringTrim(subendyearstr(subendyearvalue,:))));
            subendperiod = subendperiodvalue;
            SubSample = [subbeginyear subbeginperiod subendyear subendperiod];
            %
            % check the sub sample
            %
            if (length(SubSample)==4)&(SubSample(1)<=SubSample(3));
               if strcmp(DSGEModel.DataFrequency,'q')==1;
                  TestSample = (SubSample(1)+(SubSample(2)/4):(1/4):SubSample(3)+(SubSample(4)/4));
                  SubFirstPeriod = SubSample(1)+(SubSample(2)/4);
                  SubLastPeriod = SubSample(3)+(SubSample(4)/4);
                  FirstPeriod = str2num(DSGEModel.BeginYear)+(str2num(DSGEModel.BeginPeriod)/4);
                  LastPeriod = str2num(DSGEModel.EndYear)+(str2num(DSGEModel.EndPeriod)/4);
               elseif strcmp(DSGEModel.DataFrequency,'m')==1;
                  TestSample = (SubSample(1)+(SubSample(2)/12):(1/12):SubSample(3)+(SubSample(4)/12));
                  SubFirstPeriod = SubSample(1)+(SubSample(2)/12);
                  SubLastPeriod = SubSample(3)+(SubSample(4)/12);
                  FirstPeriod = str2num(DSGEModel.BeginYear)+(str2num(DSGEModel.BeginPeriod)/12);
                  LastPeriod = str2num(DSGEModel.EndYear)+(str2num(DSGEModel.EndPeriod)/12);
               else;
                  TestSample = (SubSample(1):1:SubSample(3));
                  SubFirstPeriod = SubSample(1);
                  SubLastPeriod = SubSample(3);
                  FirstPeriod = str2num(DSGEModel.BeginYear);
                  LastPeriod = str2num(DSGEModel.EndYear);
               end;
               %
               % Test if we have a valid sample
               %
               MatchSample = (length(TestSample)>0)&(FirstPeriod<=SubFirstPeriod)&(LastPeriod>=SubLastPeriod);
               if MatchSample==1;
                  %
                  % we can now change the DSGEModel structure information
                  %
                  DSGEModel.SubBeginYear = num2str(subbeginyear);
                  DSGEModel.SubBeginPeriod = num2str(subbeginperiod);
                  DSGEModel.SubEndYear = num2str(subendyear);
                  DSGEModel.SubEndPeriod = num2str(subendperiod);
                  %
                  DSGEModel.SubBeginYearValue = subbeginyearvalue;
                  DSGEModel.SubBeginPeriodValue = subbeginperiodvalue;
                  DSGEModel.SubEndYearValue = subendyearvalue;
                  DSGEModel.SubEndPeriodValue = subendperiodvalue;
                  %
                  % make sure things are set up correctly
                  %
                  set(controls.dsge.subbeginyear,'Value',DSGEModel.SubBeginYearValue);
                  set(controls.dsge.subbeginperiod,'Value',DSGEModel.SubBeginPeriodValue);
                  set(controls.dsge.subendyear,'Value',DSGEModel.SubEndYearValue);
                  set(controls.dsge.subendperiod,'Value',DSGEModel.SubEndPeriodValue);
                  %
                  % make sure that we can reset the KalmanFirstObservation
                  %
                  KalmanStrMat = get(controls.dsge.initializekalman,'String');
                  KalmanFOStr = StringTrim(KalmanStrMat(DSGEModel.KalmanFirstObservation,:));
                  [FirstPeriod,LastPeriod,EstSample] = CreateSubSample(DSGEModel);
                  pos = LocateStr(EstSample,KalmanFOStr);
                  if pos>0;
                     DSGEModel.KalmanFirstObservation = pos;
                  else;
                     DSGEModel.KalmanFirstObservation = 1;
                  end;
                  set(controls.dsge.initializekalman,'String',EstSample,'Value',DSGEModel.KalmanFirstObservation);
               else;
                  %
                  % bad sub-sample
                  %
                  set(controls.dsge.subbeginyear,'Value',DSGEModel.SubBeginYearValue);
                  set(controls.dsge.subbeginperiod,'Value',DSGEModel.SubBeginPeriodValue);
                  set(controls.dsge.subendyear,'Value',DSGEModel.SubEndYearValue);
                  set(controls.dsge.subendperiod,'Value',DSGEModel.SubEndPeriodValue);
                  txt = 'The sample and frequency information regarding sample length doesn''t match the number of observations for the observed variables.';
                  About(txt,'information','Invalid Sub-Sample',120,500,CurrINI);
               end;
            else;
               %
               % bad sub-sample
               %
               set(controls.dsge.subbeginyear,'Value',DSGEModel.SubBeginYearValue);
               set(controls.dsge.subbeginperiod,'Value',DSGEModel.SubBeginPeriodValue);
               set(controls.dsge.subendyear,'Value',DSGEModel.SubEndYearValue);
               set(controls.dsge.subendperiod,'Value',DSGEModel.SubEndPeriodValue);
               txt = 'The sample and frequency information regarding sample length doesn''t match the number of observations for the observed variables.';
               About(txt,'information','Invalid Sub-Sample',120,500,CurrINI);
            end;
         else;
            %
            % Fix all controls regarding sample and report a message regarding having to select a data constructions file first
            %
            set(controls.dsge.subbeginyear,'Value',DSGEModel.SubBeginYearValue);
            set(controls.dsge.subbeginperiod,'Value',DSGEModel.SubBeginPeriodValue);
            set(controls.dsge.subendyear,'Value',DSGEModel.SubEndYearValue);
            set(controls.dsge.subendperiod,'Value',DSGEModel.SubEndPeriodValue);
            txt = 'You have to select a data construction file before you can edit the sample.';
            About(txt,'information','Sample Information',120,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'editundo'
      editmenufcn(maingui,'EditUndo');
   case 'editcut'
      editmenufcn(maingui,'EditCut');
   case 'editcopy'
      editmenufcn(maingui,'EditCopy');
   case 'editpaste'
      editmenufcn(maingui,'EditPaste');
   case 'editselectall'
      editmenufcn(maingui,'EditSelectAll');
   case 'modeinfo'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         ModeTextFile = get(controls.modeinfo,'UserData');
         TextGUI(ModeTextFile,['Posterior Mode Estimation - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Results',50,CurrINI,1,1);
         set(controls.about,'UserData',0);
      end;
   case 'viewposterior'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % if there are multiple chains, ask which one to load
         %
         ChainsStr = get(controls.posterior.chains,'String');
         NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
         %
         if NumChains>1;
            %
            % ask which chain to load
            %
            ChainsStr = '';
            for i=1:NumChains;
               ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
            end;
            [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Posterior Densities','','',CurrINI);
         else;
            CurrChain = 1;
            action = 'ok';
         end;
         %
         if strcmp(lower(action),'cancel')==0;
            %
            % check if the data actually exists
            %
            if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
               %
               % load the data
               %
               [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
               clear('PostSample','LogPost','AcceptedDraws');
               %
               % check if we have parameters that are functions of estimated parameters
               %
               if FileExist(DSGEModel.UpdateParameterFile)==1;
                  %
                  % ask if the user wants to load additional parameters
                  %
                  txt = ['The model "' DSGEModel.NameOfModel '" has parameters that are a function of the estimated parameters. Would you also like to plot posterior densities for these additional parameters?'];
                  answer = Query(txt,'question',200,'Posterior Densities - Additional Parameters',500,'no',CurrINI);
                  if strcmp(lower(answer),'yes')==1;
                     [UpdatePostSample,UpdateMode,UpdateNames] = GetUpdatePosteriorDraws(thetaPostSample,NumBurnin,CurrChain,NumChains,1,DSGEModel,CurrINI);
                     %
                     % check if the user has the necessary tools for computing prior densitites
                     % for the additional parameters through random draws from the prior of the
                     % relevant estimated parameters
                     %
                     if (isempty(UpdateMode)==0)&((exist('YADAbetarnd')==2)|(exist('betardn')==2));
                        [UpdatePriorX,UpdatePriorY,UpdatePriorBounds] = GetUpdatePriorDensity(DSGEModel,CurrINI,controls,CurrChain,NumChains,NumBurnin,size(thetaPostSample,1));
                     else;
                        UpdatePriorX = [];
                        UpdatePriorY = [];
                        UpdatePriorBounds = [];
                     end;
                  else;
                     UpdatePostSample = [];
                     UpdateMode = [];
                     UpdateNames = '';
                     UpdatePriorX = [];
                     UpdatePriorY = [];
                     UpdatePriorBounds = [];
                  end;
               else;
                  UpdatePostSample = [];
                  UpdateMode = [];
                  UpdateNames = '';
                  UpdatePriorX = [];
                  UpdatePriorY = [];
                  UpdatePriorBounds = [];
               end;
               %
               % send the data to the posterior densities plotting function
               %
               drawnow;
               GraphPosteriorDensity(thetaPostSample,NumBurnin,CurrChain,UpdatePostSample,UpdateMode,UpdateNames,UpdatePriorX,UpdatePriorY,UpdatePriorBounds,DSGEModel,CurrINI,controls);
               %
               % clear everything
               %
               clear('thetaPostSample');
            else;
               txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
               About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'cusum_parameters'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % if there are multiple chains, ask which one to load
         %
         ChainsStr = get(controls.posterior.chains,'String');
         NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
         %
         if gcbo==controls.postsample.cusumplots.original;
            ParamStr = 'Original';
         else;
            ParamStr = 'Transformed';
         end;
         %
         if NumChains>1;
            %
            % ask which chain to load
            %
            ChainsStr = '';
            for i=1:NumChains;
               ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
            end;
            [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection',['CUSUM Plots - ' ParamStr ' Parameters'],'','',CurrINI);
         else;
            CurrChain = 1;
            action = 'ok';
         end;
         %
         if strcmp(lower(action),'cancel')==0;
            %
            % check if the data actually exists
            %
            if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
               %
               % load the data
               %
               [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
               if strcmp(lower(ParamStr),'original')==1;
                  ParamDraws = thetaPostSample;
               else;
                  ParamDraws = PostSample;
               end;
               clear('PostSample','AcceptedDraws','LogPost','thetaPostSample');
               %
               % send the data to the cusum computation function
               %
               drawnow;
               [CUSUMPost,CUSUMAverage] = CUSUM(ParamDraws,NumBurnin,strrep(strrep(get(gcbo,'Label'),'&',''),'...',''),CurrINI);
               %
               if isempty(CUSUMPost)==0;
                  %
                  % display the results
                  %
                  CUSUMPlots(CUSUMPost,CUSUMAverage,NumBurnin,CurrChain,ParamStr,DSGEModel,CurrINI);
               end;
               %
               % clear everything
               %
               clear('ParamDraws');
            else;
               txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
               About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'cusum_logpost'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % if there are multiple chains, ask which one to load
         %
         ChainsStr = get(controls.posterior.chains,'String');
         NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
         %
         if NumChains>1;
            %
            % ask which chain to load
            %
            ChainsStr = '';
            for i=1:NumChains;
               ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
            end;
            [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','CUSUM Plots - Log Posterior','','',CurrINI);
         else;
            CurrChain = 1;
            action = 'ok';
         end;
         %
         if strcmp(lower(action),'cancel')==0;
            %
            % check if the data actually exists
            %
            if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
               %
               % load the data
               %
               [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
               clear('PostSample','AcceptedDraws','thetaPostSample');
               %
               % send the data to the cusum computation function
               %
               drawnow;
               [CUSUMPost,CUSUMAverage] = CUSUM(LogPost,NumBurnin,'Log Posterior',CurrINI);
               %
               if isempty(CUSUMPost)==0;
                  %
                  % display the results
                  %
                  CUSUMPlots(CUSUMPost,CUSUMAverage,NumBurnin,CurrChain,'logpost',DSGEModel,CurrINI);
               end;
               %
               % clear everything
               %
               clear('LogPost');
            else;
               txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
               About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'spmt_parameters'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % if there are multiple chains, ask which one to load
         %
         ChainsStr = get(controls.posterior.chains,'String');
         NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
         %
         if gcbo==controls.postsample.spmt.original;
            ParamStr = 'Original';
         else;
            ParamStr = 'Transformed';
         end;
         %
         % Try to load the posterior mode estimates
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         %
         % check if we could successfully load the data
         %
         if isempty(ErrorStr)==1;
            ParameterNames = ModeData.ParameterNames;
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection',['Separated Partial Means - ' ParamStr ' Parameters'],'','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumIter = size(LogPost,1);
                  clear('AcceptedDraws','LogPost');
                  drawnow;
                  %
                  if strcmp(lower(ParamStr),'original')==1;
                     ParamDraws = thetaPostSample;
                  else;
                     ParamDraws = PostSample;
                  end;
                  clear('thetaPostSample','PostSample');
                  %
                  % check how many separated partial means to compute
                  %
                  NumMeansStr = '';
                  for i=2:20;
                     if IsInteger((NumIter-NumBurnin)/(2*i))==1;
                        NumMeansStr = strvcat(NumMeansStr,num2str(i,'%0.0f'));
                     end;
                  end;
                  %
                  if isempty(NumMeansStr)==0;
                     [action,NumPM] = SelectionDlg(NumMeansStr,1,'Select the number of partial means to allow for','Partial Means Selection',['Separated Partial Means - ' ParamStr ' Parameters'],'','',CurrINI);
                     %
                     % check if the action was cancelled
                     %
                     if strcmp(lower(action),'cancel')==0;
                        NumPM = str2num(StringTrim(NumMeansStr(NumPM,:)));
                        %
                        % check if we have already calculated the separated partial means test for the selected chain and number of partial means
                        %
                        ResFile = [DSGEModel.OutputDirectory '\SeparatedPartialMeans-' ParamStr 'Parameters-' DSGEModel.NameOfModel '-' num2str(NumPM,'%0.0f') '-' num2str(CurrChain,'%0.0f') '.' num2str(NumChains,'%0.0f') '-' num2str(NumBurnin,'%0.0f') '.' num2str(NumIter,'%0.0f') '.txt'];
                        %
                        if FileExist(ResFile)==1;
                           txt = ['YADA has already computed the separated partial means test for ' num2str(NumPM,'%0.0f') ' separated partial means. Would you like to view this file? If you push the "No" button then YADA will recompute the tests.'];
                           GewekeStat = 1;
                           answer = Query(txt,'question',200,['Separated Partial Means Test - ' ParamStr ' Parameters'],500,'no',CurrINI);
                           if strcmp(lower(answer),'no')==1;
                              RunTest = 1;
                           end;
                        else;
                           RunTest = 1;
                        end;
                        if RunTest==1;
                           GewekeStat = SeparatedPartialMeansTest(ParamDraws(NumBurnin+1:NumIter,:),NumPM,[ParamStr ' Parameters'],CurrINI);
                           %
                           % write the results to file
                           %
                           if isempty(GewekeStat)==0;
                              PrintSeparatedPartialMeans(GewekeStat,NumPM,CurrChain,NumChains,NumIter,NumBurnin,[ParamStr ' Parameters'],ParameterNames.estimated,DSGEModel,CurrINI);
                           end;
                        end;
                        if (isempty(GewekeStat)==0)&(FileExist(ResFile)==1);
                           TextGUI(ResFile,['Separated Partial Means Test - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],[ParamStr ' Parameters'],50,CurrINI,1,1);
                        end;
                     end;
                  else;
                     txt = ['YADA was unable to find any interger p between 2 and 20 such that ' num2str(NumIter-NumBurnin,'%0.0f') '/2p is an integer. YADA is therefore unable to calculate Geweke''s separated partial means test.'];
                     About(txt,'information',['Separated Partial Means - ' ParamStr ' Parameters'],200,500,CurrINI);
                  end;
                  %
                  % clear everything
                  %
                  clear('ParamDraws');
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'spmt_logpost'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % if there are multiple chains, ask which one to load
         %
         ChainsStr = get(controls.posterior.chains,'String');
         NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
         %
         if NumChains>1;
            %
            % ask which chain to load
            %
            ChainsStr = '';
            for i=1:NumChains;
               ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
            end;
            [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Separated Partial Means - Log Posterior','','',CurrINI);
         else;
            CurrChain = 1;
            action = 'ok';
         end;
         %
         if strcmp(lower(action),'cancel')==0;
            %
            % check if the data actually exists
            %
            if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
               %
               % load the data
               %
               [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
               clear('PostSample','AcceptedDraws','thetaPostSample');
               drawnow;
               NumIter = size(LogPost,1);
               %
               % check how many separated partial means to compute
               %
               NumMeansStr = '';
               for i=2:20;
                  if IsInteger((NumIter-NumBurnin)/(2*i))==1;
                     NumMeansStr = strvcat(NumMeansStr,num2str(i,'%0.0f'));
                  end;
               end;
               %
               if isempty(NumMeansStr)==0;
                  [action,NumPM] = SelectionDlg(NumMeansStr,1,'Select the number of partial means to allow for','Partial Means Selection','Separated Partial Means - Log Posterior','','',CurrINI);
                  %
                  % check if the action was cancelled
                  %
                  if strcmp(lower(action),'cancel')==0;
                     NumPM = str2num(StringTrim(NumMeansStr(NumPM,:)));
                     %
                     % check if we have already calculated the separated partial means test for the selected chain and number of partial means
                     %
                     ResFile = [DSGEModel.OutputDirectory '\SeparatedPartialMeans-LogPosterior-' DSGEModel.NameOfModel '-' num2str(NumPM,'%0.0f') '-' num2str(CurrChain,'%0.0f') '.' num2str(NumChains,'%0.0f') '-' num2str(NumBurnin,'%0.0f') '.' num2str(NumIter,'%0.0f') '.txt'];
                     %
                     if FileExist(ResFile)==1;
                        txt = ['YADA has already computed the separated partial means test for ' num2str(NumPM,'%0.0f') ' separated partial means. Would you like to view this file? If you push the "No" button then YADA will recompute the tests.'];
                        GewekeStat = 1;
                        answer = Query(txt,'question',200,'Separated Partial Means Test - Log Posterior',500,'no',CurrINI);
                        if strcmp(lower(answer),'no')==1;
                           RunTest = 1;
                        end;
                     else;
                        RunTest = 1;
                     end;
                     if RunTest==1;
                        GewekeStat = SeparatedPartialMeansTest(LogPost(NumBurnin+1:NumIter,:),NumPM,'Log Posterior',CurrINI);
                        %
                        % write the results to file
                        %
                        if isempty(GewekeStat)==0;
                           PrintSeparatedPartialMeans(GewekeStat,NumPM,CurrChain,NumChains,NumIter,NumBurnin,'Log Posterior','log posterior',DSGEModel,CurrINI);
                        end;
                     end;
                     if (isempty(GewekeStat)==0)&(FileExist(ResFile)==1);
                        TextGUI(ResFile,['Separated Partial Means Test - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Log Posterior',50,CurrINI,1,1);
                     end;
                  end;
               else;
                  txt = ['YADA was unable to find any interger p between 2 and 20 such that ' num2str(NumIter-NumBurnin,'%0.0f') '/2p is an integer. YADA is therefore unable to calculate Geweke''s separated partial means test.'];
                  About(txt,'information','Separated Partial Means - Log Posterior',200,500,CurrINI);
               end;
               %
               % clear everything
               %
               clear('LogPost');
            else;
               txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
               About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'converge_manova'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % determine the current number of MCMC chains
         %
         ChainsStr = get(controls.posterior.chains,'String');
         NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
         %
         % determine the number of posterior draws
         %
         DrawsStr = get(controls.posterior.draws,'String');
         NumPostDraws = str2num(StringTrim(strrep(DrawsStr(DSGEModel.PosteriorDrawsValue,:),',','')));
         %
         % determine the number of burn-in draws
         %
         BurninStr = get(controls.posterior.burnin,'String');
         NumBurnin = str2num(strrep(StringTrim(BurninStr(DSGEModel.BurnInValue,:)),',',''));
         %
         % check the results file
         %
         ResFile = [DSGEModel.OutputDirectory '\manova\MANOVA-' DSGEModel.NameOfModel '-' num2str(NumChains,'%0.0f') '.' num2str(NumBurnin,'%0.0f') '.' num2str(NumPostDraws,'%0.0f') '.mat'];
         if FileExist(ResFile)==1;
            txt = ['You have already computed the multivariate potential scale reduction factors for ' num2str(NumChains,'%0.0f') ' MCMC chains with ' num2str(NumPostDraws,'%0.0f') ' posterior draws and ' num2str(NumBurnin,'%0.0f') ' burn-in draws. Would you like to use the old results?'];
            answer = Query(txt,'question',200,'Multivariate ANOVA',500,'no',CurrINI);
            if strcmp(lower(answer),'yes')==1;
               RunANOVA = 0;
               ANOVAData = load(ResFile);
               MPSRF = ANOVAData.MPSRF;
               DoneCalc = 1;
            else;
               RunANOVA = 1;
            end;
         else;
            RunANOVA = 1;
         end;
         if RunANOVA==1;
            %
            % run the multivariate ANOVA functions
            %
            [DoneCalc,MPSRF] = MultiANOVA(NumChains,1,DSGEModel,CurrINI,controls);
         end;
         if DoneCalc==1;
            PlotMultiANOVA(MPSRF,NumBurnin,NumChains,DSGEModel,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'converge_acceptance'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % if there are multiple chains, ask which one to load
         %
         ChainsStr = get(controls.posterior.chains,'String');
         NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
         %
         if NumChains>1;
            %
            % ask which chain to load
            %
            ChainsStr = '';
            for i=1:NumChains;
               ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
            end;
            [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Acceptance Ratio','','',CurrINI);
         else;
            CurrChain = 1;
            action = 'ok';
         end;
         %
         if strcmp(lower(action),'cancel')==0;
            %
            % check if the data actually exists
            %
            if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
               %
               % load the data
               %
               [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
               clear('PostSample','LogPost','thetaPostSample');
               %
               % send the data to the acceptance ratio plotting function
               %
               drawnow;
               AcceptanceRatioPlot(AcceptedDraws,NumBurnin,CurrChain,DSGEModel,CurrINI);
               %
               % clear everything
               %
               clear('AcceptedDraws');
            else;
               txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
               About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'converge_mean'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % if there are multiple chains, ask which one to load
         %
         ChainsStr = get(controls.posterior.chains,'String');
         NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
         %
         if NumChains>1;
            %
            % ask which chain to load
            %
            ChainsStr = '';
            for i=1:NumChains;
               ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
            end;
            [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Posterior Mean','','',CurrINI);
         else;
            CurrChain = 1;
            action = 'ok';
         end;
         %
         if strcmp(lower(action),'cancel')==0;
            %
            % check if the data actually exists
            %
            if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
               %
               % load the data
               %
               [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
               clear('PostSample','LogPost','AcceptedDraws');
               %
               % send the data to the posterior mean and median plotting function
               %
               drawnow;
               PosteriorMeanMedianPlots(thetaPostSample,NumBurnin,CurrChain,'Mean',DSGEModel,CurrINI);
               %
               % clear everything
               %
               clear('thetaPostSample');
            else;
               txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
               About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'converge_median'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % if there are multiple chains, ask which one to load
         %
         ChainsStr = get(controls.posterior.chains,'String');
         NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
         %
         if NumChains>1;
            %
            % ask which chain to load
            %
            ChainsStr = '';
            for i=1:NumChains;
               ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
            end;
            [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Posterior Median','','',CurrINI);
         else;
            CurrChain = 1;
            action = 'ok';
         end;
         %
         if strcmp(lower(action),'cancel')==0;
            %
            % check if the data actually exists
            %
            if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
               %
               % load the data
               %
               [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
               clear('PostSample','LogPost','AcceptedDraws');
               %
               % send the data to the posterior mean and median plotting function
               %
               drawnow;
               PosteriorMeanMedianPlots(thetaPostSample,NumBurnin,CurrChain,'Median',DSGEModel,CurrINI);
               %
               % clear everything
               %
               clear('thetaPostSample');
            else;
               txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
               About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'bvar_mean_median_convergence'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Check if the data actually exists
         %
         if VerifyBVARPosteriorDraws(DSGEModel,controls)==1;
            %
            % load the data
            %
            [PsiPostSample,PiPostSample,OmegaPostSample,LogPsiDensity,LogPiDensity,NumBurnin] = LoadBVARPosteriorDraws(DSGEModel,CurrINI);
            %
            % determine which data to use
            %
            if gcbo==controls.bvarpsimeanconvergence;
               PostSample = PsiPostSample;
               ParamStr = 'Psi';
               MomentType = 'Mean';
            elseif gcbo==controls.bvarpimeanconvergence;
               PostSample = PiPostSample;
               ParamStr = 'Pi';
               MomentType = 'Mean';
            elseif gcbo==controls.bvaromegameanconvergence;
               PostSample = OmegaPostSample;
               ParamStr = 'Omega';
               MomentType = 'Mean';
            elseif gcbo==controls.bvarpsimedianconvergence;
               PostSample = PsiPostSample;
               ParamStr = 'Psi';
               MomentType = 'Median';
            elseif gcbo==controls.bvarpimedianconvergence;
               PostSample = PiPostSample;
               ParamStr = 'Pi';
               MomentType = 'Median';
            elseif gcbo==controls.bvaromegamedianconvergence;
               PostSample = OmegaPostSample;
               ParamStr = 'Omega';
               MomentType = 'Median';
            end;
            %
            % send the data to the posterior densities plotting function
            %
            drawnow;
            PosteriorBVARMeanMedianPlots(PostSample,ParamStr,MomentType,NumBurnin,DSGEModel,CurrINI);
            %
            % clear everything
            %
            clear('PsiPostSample','PiPostSample','OmegaPostSample','LogPsiDensity','LogPiDensity');
         else;
            txt = 'Some of the files for loading the posterior data for the Bayesian VAR are not available.';
            About(txt,'error','Bayesian VAR - Missing Posterior Draws',150,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'rawplots'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % if there are multiple chains, ask which one to load
         %
         ChainsStr = get(controls.posterior.chains,'String');
         NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
         %
         if NumChains>1;
            %
            % ask which chain to load
            %
            ChainsStr = '';
            for i=1:NumChains;
               ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
            end;
            [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Raw Posterior Plots','','',CurrINI);
         else;
            CurrChain = 1;
            action = 'ok';
         end;
         %
         if strcmp(lower(action),'cancel')==0;
            %
            % check if the data actually exists
            %
            if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
               %
               % load the data
               %
               [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
               %
               % check which parameters to use
               %
               if gcbo==controls.postsample.rawplots_original;
                  ParamSample = thetaPostSample;
                  TypeStr = 'Original';
               else;
                  ParamSample = PostSample;
                  TypeStr = 'Transformed';
               end;
               %
               % clear posterior sample data
               %
               clear('PostSample','thetaPostSample','LogPost','AcceptedDraws');
               %
               % send the data to the raw plotting function
               %
               drawnow;
               RawPosteriorPlots(ParamSample,NumBurnin,CurrChain,TypeStr,DSGEModel,CurrINI);
               %
               % clear the used parameter draws
               %
               clear('ParamSample');
            else;
               txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
               About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'scatterplots'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % if there are multiple chains, ask which one to load
         %
         ChainsStr = get(controls.posterior.chains,'String');
         NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
         %
         if NumChains>1;
            %
            % ask which chain to load
            %
            ChainsStr = '';
            for i=1:NumChains;
               ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
            end;
            [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Scatter-plot Posterior Plots','','',CurrINI);
         else;
            CurrChain = 1;
            action = 'ok';
         end;
         %
         if strcmp(lower(action),'cancel')==0;
            ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
            ErrorStr = '';
            try;
               ModeData = load(ModeFile);
            catch;
               ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
            end;
            %
            % check if the data actually exists
            %
            if isempty(ErrorStr)==1;
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  PostSample = PostSample(NumBurnin+1:NumDraws,:);
                  LogPost = LogPost(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check which parameters to use
                  %
                  if gcbo==controls.postsample.scatterplots_original;
                     ParamSample = thetaPostSample;
                     TypeStr = 'Original';
                     ParamMode = ModeData.thetaMode;
                  else;
                     ParamSample = PostSample;
                     TypeStr = 'Transformed';
                     ParamMode = ModeData.phiMode;
                  end;
                  %
                  % clear posterior sample data
                  %
                  clear('PostSample','thetaPostSample','AcceptedDraws');
                  %
                  % check which draws we should use
                  %
                  UseDraws = KeepPosteriorDraws(DSGEModel,controls.posterior.usepostdraws,NumDraws);
                  if length(UseDraws)<NumDraws;
                     ParamSample = ParamSample(UseDraws,:);
                     LogPost = LogPost(UseDraws);
                     UsedDraws = length(UseDraws);
                  else;
                     UsedDraws = NumDraws;
                  end;
                  %
                  % send the data to the raw plotting function
                  %
                  drawnow;
                  ScatterPlotPosteriorDraws('init',ParamSample,LogPost,ModeData.ParameterNames.estimated,ParamMode,CurrChain,TypeStr,DSGEModel,CurrINI);
                  %
                  % clear the used parameter draws
                  %
                  clear('ParamSample','LogPost');
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            else;
               About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'bvar_psi_raw_draws'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Check if the data actually exists
         %
         if VerifyBVARPosteriorDraws(DSGEModel,controls)==1;
            %
            % load the data
            %
            [PsiPostSample,PiPostSample,OmegaPostSample,LogPsiDensity,LogPiDensity,NumBurnin] = LoadBVARPosteriorDraws(DSGEModel,CurrINI);
            %
            % send the data to the raw plotting function
            %
            drawnow;
            RawBVARPosteriorPlots('Psi',PsiPostSample,NumBurnin,DSGEModel,CurrINI);
            %
            % clear everything
            %
            clear('PsiPostSample','PiPostSample','OmegaPostSample','LogPsiDensity','LogPiDensity');
         else;
            txt = 'Some of the files for loading the posterior data for the Bayesian VAR are not available.';
            About(txt,'error','Bayesian VAR - Missing Posterior Draws',150,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'bvar_pi_raw_draws'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Check if the data actually exists
         %
         if VerifyBVARPosteriorDraws(DSGEModel,controls)==1;
            %
            % load the data
            %
            [PsiPostSample,PiPostSample,OmegaPostSample,LogPsiDensity,LogPiDensity,NumBurnin] = LoadBVARPosteriorDraws(DSGEModel,CurrINI);
            %
            % send the data to the raw plotting function
            %
            drawnow;
            RawBVARPosteriorPlots('Pi',PiPostSample,NumBurnin,DSGEModel,CurrINI);
            %
            % clear everything
            %
            clear('PsiPostSample','PiPostSample','OmegaPostSample','LogPsiDensity','LogPiDensity');
         else;
            txt = 'Some of the files for loading the posterior data for the Bayesian VAR are not available.';
            About(txt,'error','Bayesian VAR - Missing Posterior Draws',150,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'bvar_omega_raw_draws'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Check if the data actually exists
         %
         if VerifyBVARPosteriorDraws(DSGEModel,controls)==1;
            %
            % load the data
            %
            [PsiPostSample,PiPostSample,OmegaPostSample,LogPsiDensity,LogPiDensity,NumBurnin] = LoadBVARPosteriorDraws(DSGEModel,CurrINI);
            %
            % send the data to the raw plotting function
            %
            drawnow;
            RawBVARPosteriorPlots('Omega',OmegaPostSample,NumBurnin,DSGEModel,CurrINI);
            %
            % clear everything
            %
            clear('PsiPostSample','PiPostSample','OmegaPostSample','LogPsiDensity','LogPiDensity');
         else;
            txt = 'Some of the files for loading the posterior data for the Bayesian VAR are not available.';
            About(txt,'error','Bayesian VAR - Missing Posterior Draws',150,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'bvar_psi_post_density'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Check if the data actually exists
         %
         if VerifyBVARPosteriorDraws(DSGEModel,controls)==1;
            %
            % load the data
            %
            [PsiPostSample,PiPostSample,OmegaPostSample,LogPsiDensity,LogPiDensity,NumBurnin] = LoadBVARPosteriorDraws(DSGEModel,CurrINI);
            %
            % send the data to the posterior densities plotting function
            %
            drawnow;
            GraphBVARPosteriorDensity('Psi',PsiPostSample,NumBurnin,DSGEModel,CurrINI);
            %
            % clear everything
            %
            clear('PsiPostSample','PiPostSample','OmegaPostSample','LogPsiDensity','LogPiDensity');
         else;
            txt = 'Some of the files for loading the posterior data for the Bayesian VAR are not available.';
            About(txt,'error','Bayesian VAR - Missing Posterior Draws',150,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'bvar_pi_post_density'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Check if the data actually exists
         %
         if VerifyBVARPosteriorDraws(DSGEModel,controls)==1;
            %
            % load the data
            %
            [PsiPostSample,PiPostSample,OmegaPostSample,LogPsiDensity,LogPiDensity,NumBurnin] = LoadBVARPosteriorDraws(DSGEModel,CurrINI);
            %
            % send the data to the posterior densities plotting function
            %
            drawnow;
            GraphBVARPosteriorDensity('Pi',PiPostSample,NumBurnin,DSGEModel,CurrINI);
            %
            % clear everything
            %
            clear('PsiPostSample','PiPostSample','OmegaPostSample','LogPsiDensity','LogPiDensity');
         else;
            txt = 'Some of the files for loading the posterior data for the Bayesian VAR are not available.';
            About(txt,'error','Bayesian VAR - Missing Posterior Draws',150,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'bvar_omega_post_density'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Check if the data actually exists
         %
         if VerifyBVARPosteriorDraws(DSGEModel,controls)==1;
            %
            % load the data
            %
            [PsiPostSample,PiPostSample,OmegaPostSample,LogPsiDensity,LogPiDensity,NumBurnin] = LoadBVARPosteriorDraws(DSGEModel,CurrINI);
            %
            % send the data to the posterior densities plotting function
            %
            drawnow;
            GraphBVARPosteriorDensity('Omega',OmegaPostSample,NumBurnin,DSGEModel,CurrINI);
            %
            % clear everything
            %
            clear('PsiPostSample','PiPostSample','OmegaPostSample','LogPsiDensity','LogPiDensity');
         else;
            txt = 'Some of the files for loading the posterior data for the Bayesian VAR are not available.';
            About(txt,'error','Bayesian VAR - Missing Posterior Draws',150,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'postsample_chib'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % Check if the data actually exists
         %
         if VerifyBVARPosteriorDraws(DSGEModel,controls)==1;
            %
            % load the data
            %
            [PsiPostSample,PiPostSample,OmegaPostSample,LogPsiDensity,LogPiDensity,NumBurnin] = LoadBVARPosteriorDraws(DSGEModel,CurrINI);
            %
            % run the sequential estimation routine
            %
            drawnow;
            PlotMargLikeChib(LogPsiDensity,LogPiDensity,NumBurnin,DSGEModel,CurrINI);
            %
            % clear everything
            %
            clear('PsiPostSample','PiPostSample','OmegaPostSample','LogPsiDensity','LogPiDensity');
         else;
            txt = 'Some of the files for loading the posterior data for the Bayesian VAR are not available.';
            About(txt,'error','Bayesian VAR - Missing Posterior Draws',150,500,CurrINI);
         end;
         set(controls.about,'UserData',0);
      end;
   case 'postsample_mhm'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % if there are multiple chains, ask which one to load
         %
         ChainsStr = get(controls.posterior.chains,'String');
         NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
         %
         if NumChains>1;
            %
            % ask which chain to load
            %
            ChainsStr = '';
            for i=1:NumChains;
               ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
            end;
            [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Sequential Marginal Likelihood - Modified Harmonic Mean','','',CurrINI);
         else;
            CurrChain = 1;
            action = 'ok';
         end;
         %
         if strcmp(lower(action),'cancel')==0;
            %
            % check if the data actually exists
            %
            if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
               %
               % load the data
               %
               [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
               clear('thetaPostSample','AcceptedDraws');
               %
               % run the sequential estimation routine
               %
               drawnow;
               PlotMargLikeModifiedHarmonic(PostSample,LogPost,NumBurnin,CurrChain,DSGEModel,CurrINI);
               %
               % clear everything
               %
               clear('PostSample','LogPost');
            else;
               txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
               About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'postsample_cj'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % if there are multiple chains, ask which one to load
         %
         ChainsStr = get(controls.posterior.chains,'String');
         NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
         %
         if NumChains>1;
            %
            % ask which chain to load
            %
            ChainsStr = '';
            for i=1:NumChains;
               ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
            end;
            [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Sequential Marginal Likelihood - Chib and Jeliazkov','','',CurrINI);
         else;
            CurrChain = 1;
            action = 'ok';
         end;
         %
         %
         if strcmp(lower(action),'cancel')==0;
            %
            % check if the data actually exists
            %
            if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
               %
               % load the data
               %
               [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
               clear('thetaPostSample','AcceptedDraws');
               %
               % run the sequential estimation routine
               %
               drawnow;
               PlotMargLikeChibJeliazkov(PostSample,LogPost,NumBurnin,CurrChain,DSGEModel,CurrINI);
               %
               % clear everything
               %
               clear('PostSample','LogPost');
            else;
               txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
               About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
            end;
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'fevd_post_dist'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Variance Decompositions','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check which draws we should use
                  %
                  UseDraws = KeepPosteriorDraws(DSGEModel,controls.posterior.usepostdraws,NumDraws);
                  if length(UseDraws)<NumDraws;
                     thetaPostSample = thetaPostSample(UseDraws,:);
                     UsedDraws = length(UseDraws);
                  else;
                     UsedDraws = NumDraws;
                  end;
                  %
                  % check which function to run
                  %
                  if gcbo==controls.fevd.posterior;
                     LevelsData = 0;
                     QueryHead = 'Variance Decompositions - Original Data';
                     VarType = 'Original';
                  else;
                     LevelsData = 1;
                     QueryHead = 'Variance Decompositions - Levels Data';
                     VarType = 'Levels';
                  end;
                  %
                  % First we check if the calculations have already been performed
                  %
                  if VarDecExist(DSGEModel,LevelsData,UsedDraws,NumDraws,CurrChain)==1;
                     txt = ['YADA has located results for the forecast error variance decompositions for the ' lower(VarType) ' data on disk. Would you like to use these results?'];
                     answer = Query(txt,'information',150,QueryHead,450,'no',CurrINI);
                  else;
                     answer = 'No';
                  end;
                  RunTimeStr = '';
                  if strcmp(lower(answer),'yes')==1;
                     DoneCalc = 1;
                  else;
                     %
                     % compute the variance decompositions for all the posterior draws
                     %
                     StartTime = clock;
                     DoneCalc = DSGEFEVD(thetaPostSample,thetaPositions,ModelParameters,DSGEModel,CurrINI,LevelsData,NumDraws,CurrChain);
                     EndTime = clock;
                     VarDecRunTime = etime(EndTime,StartTime);
                     RunTimeStr = ['The variance decomposition calculations using ' int2str(UsedDraws) ' posterior draws have finished after ' SecondsToHoursStr(VarDecRunTime) ' (hrs:min:sec). '];
                  end;
                  if DoneCalc==1;
                     %
                     % ask if we should look at shock groups
                     %
                     PrintGroups = 0;
                     if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                        txt = [RunTimeStr 'Would you like to view results of the forecast error variance decompositions for shock groups instead of for the individual shocks?'];
                        answer = Query(txt,'question',150,QueryHead,500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           PrintGroups = 1;
                        end;
                     end;
                     %
                     % compute the distribution for the conditional variance decompositions
                     %
                     VDs = DSGEVarDecDistribution(DSGEModel,CurrINI,LevelsData,PrintGroups,UsedDraws,NumDraws,CurrChain);
                     %
                     % ask if we should save results to disk
                     %
                     txt = 'Would you like to save the forecast error variance decompositions to file?';
                     answer = Query(txt,'question',140,'Save - Variance Decompositions',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        YNames = DSGEModel.VariableNames;
                        if PrintGroups==0;
                           ShockNames = DSGEModel.StateShockNames;
                        else;
                           ShockNames = char(zeros(size(DSGEModel.ShockGroupNames)));
                           for i=1:size(DSGEModel.ShockGroupNames,1);
                              ShockNames(i,:) = strrep(DSGEModel.ShockGroupNames(i,:),'_',' ');
                           end;
                        end;
                        if PrintGroups==0;
                           file = [DSGEModel.OutputDirectory '\VarianceDecompositionDist-' VarType '.mat'];
                        else;
                           file = [DSGEModel.OutputDirectory '\VarianceDecompositionDist-ShockGroup-' VarType '.mat'];
                        end;
                        save(file,'YNames','ShockNames','VDs');
                        %
                        % create a matlab file to read the data
                        %
                        mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'VarianceDecompositionDist','VDDist');
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                        fprintf(fid,'YNames = DataStructure.YNames;\n');
                        if PrintGroups==0;
                           fprintf(fid,'%%\n%% string matrix with the names of the economic shocks\n%%\n');
                        else;
                           fprintf(fid,'%%\n%% string matrix with the names of the economic shock groups\n%%\n');
                        end;
                        fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                        fprintf(fid,'%%\n%% structure with fields FEVD containing the posterior mean\n%% variance decomposition, LRVD the long-run variance\n%% decomposition, Econ containing the joint impact of all\n%% economic shocks, EconLR with the joint impact of all\n%% economic shocks in the long run, and the vector field\n%% Quantiles with subfields FEVD, LRVD, Econ, EconLR, and\n%% percent holding quantile data and quantile percent.\n%%\n');
                        fprintf(fid,'VDs = DataStructure.VDs;\n');
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        txt = ['The forecast error variance decomposition data has been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 3 entries: YNames (string matrix with the names of the observed variables), ShockNames (string matrix with the names of the economic shocks), and VDs (a structure with posterior mean and quantile data for the variance decompositions). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','Variance Decompositions',200,500,CurrINI);
                     end;
                     %
                     % display the results
                     %
                     PrintFEVD(DSGEModel,CurrINI,VDs,PrintGroups,VarType,UsedDraws,NumDraws,CurrChain);
                     if PrintGroups==0;
                        ResFile = [DSGEModel.OutputDirectory '\PosteriorDist-VD-' VarType '-' num2str(CurrChain,'%0.0f') '-' DSGEModel.NameOfModel '-' num2str(UsedDraws,'%0.0f') '.' num2str(NumDraws,'%0.0f') '.txt'];
                     else;
                        ResFile = [DSGEModel.OutputDirectory '\PosteriorDist-VD-ShockGroups-' VarType '-' num2str(CurrChain,'%0.0f') '-' DSGEModel.NameOfModel '-' num2str(UsedDraws,'%0.0f') '.' num2str(NumDraws,'%0.0f') '.txt'];
                     end;
                     if FileExist(ResFile)==1;
                        TextGUI(ResFile,['Variance Decompositions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],['Posterior Distribution - ' VarType ' Data'],50,CurrINI,1,1);
                     end;
                  end;
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'cvd_post_dist'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Conditional Variance Decompositions','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check which draws we should use
                  %
                  UseDraws = KeepPosteriorDraws(DSGEModel,controls.posterior.usepostdraws,NumDraws);
                  if length(UseDraws)<NumDraws;
                     thetaPostSample = thetaPostSample(UseDraws,:);
                     UsedDraws = length(UseDraws);
                  else;
                     UsedDraws = NumDraws;
                  end;
                  %
                  % are we using annualized data, levels, or the original
                  %
                  if gcbo==controls.cvd.posterior;
                     AnnualizeData = 0;
                     LevelsData = 0;
                     QueryHead = 'Conditional Variance Decompositions - Original Data';
                     VarType = 'Original';
                  elseif gcbo==controls.cvd.lev_posterior;
                     AnnualizeData = 0;
                     LevelsData = 1;
                     QueryHead = 'Conditional Variance Decompositions - Levels Data';
                     VarType = 'Levels';
                  else;
                     AnnualizeData = 1;
                     LevelsData = 0;
                     QueryHead = 'Conditional Variance Decompositions - Annualized Data';
                     VarType = 'Annualized';
                  end;
                  %
                  % First we check if the calculations have already been performed
                  %
                  if CVDExist(DSGEModel,AnnualizeData,LevelsData,UsedDraws,NumDraws,CurrChain)==1;
                     txt = 'YADA has located results for the conditional variance decompositions on disk. Would you like to use these results?';
                     answer = Query(txt,'information',150,QueryHead,450,'no',CurrINI);
                  else;
                     answer = 'No';
                  end;
                  if strcmp(lower(answer),'yes')==1;
                     DoneCalc = 1;
                  else;
                     %
                     % compute the conditional variance decompositions for all the posterior draws
                     %
                     DoneCalc = DSGEConditionalFEVD(thetaPostSample,thetaPositions,ModelParameters,DSGEModel,CurrINI,AnnualizeData,LevelsData,NumDraws,CurrChain);
                  end;
                  %
                  % check if we should show any results
                  %
                  if DoneCalc==1;
                     %
                     % ask if we should look at shock groups
                     %
                     PrintGroups = 0;
                     if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                        txt = 'Would you like to view results of the conditional variance decompositions for shock groups instead of for the individual shocks?';
                        answer = Query(txt,'question',140,'Conditional Variance Decompositions',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           PrintGroups = 1;
                        end;
                     end;
                     %
                     % compute the distribution for the conditional variance decompositions
                     %
                     CVDs = DSGECVDDistribution(DSGEModel,CurrINI,AnnualizeData,LevelsData,PrintGroups,UsedDraws,NumDraws,CurrChain);
                     %
                     % ask if we should save results to disk
                     %
                     txt = 'Would you like to save the conditional forecast error variance decompositions to file?';
                     answer = Query(txt,'question',140,'Save - Conditional Variance Decompositions',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        YNames = DSGEModel.VariableNames;
                        if PrintGroups==0;
                           ShockNames = DSGEModel.StateShockNames;
                        else;
                           ShockNames = char(zeros(size(DSGEModel.ShockGroupNames)));
                           for i=1:size(DSGEModel.ShockGroupNames,1);
                              ShockNames(i,:) = strrep(DSGEModel.ShockGroupNames(i,:),'_',' ');
                           end;
                        end;
                        if PrintGroups==0;
                           file = [DSGEModel.OutputDirectory '\ConditionalVarianceDecompositionDist-' VarType '.mat'];
                        else;
                           file = [DSGEModel.OutputDirectory '\ConditionalVarianceDecompositionDist-ShockGroup-' VarType '.mat'];
                        end;
                        save(file,'YNames','ShockNames','CVDs');
                        %
                        % create a matlab file to read the data
                        %
                        mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'ConditionalVarianceDecompositionDist','CVDDist');
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                        fprintf(fid,'YNames = DataStructure.YNames;\n');
                        if PrintGroups==0;
                           fprintf(fid,'%%\n%% string matrix with the names of the economic shocks\n%%\n');
                        else;
                           fprintf(fid,'%%\n%% string matrix with the names of the economic shock groups\n%%\n');
                        end;
                        fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                        fprintf(fid,'%%\n%% structure with fields FEVD containing the posterior mean\n%% conditional variance decomposition and the vector field\n%% Quantiles with subfields FEVD and percent holding quantile\n%% data and quantile percent.\n%%\n');
                        fprintf(fid,'CVDs = DataStructure.CVDs;\n');
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        txt = ['The forecast error variance decomposition data has been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 3 entries: YNames (string matrix with the names of the observed variables), ShockNames (string matrix with the names of the economic shocks), and CVDs (a structure with posterior mean and quantile data for the conditional variance decompositions). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','Conditional Variance Decompositions',200,500,CurrINI);
                     end;
                     %
                     % display the results
                     %
                     PrintConditionalCVD(DSGEModel,CurrINI,CVDs,PrintGroups,VarType,UsedDraws,NumDraws,CurrChain);
                     if PrintGroups==0;
                        ResFile = [DSGEModel.OutputDirectory '\PosteriorDist-CVD-' VarType '-' num2str(CurrChain,'%0.0f') '-' DSGEModel.NameOfModel '-' num2str(UsedDraws,'%0.0f') '.' num2str(NumDraws,'%0.0f') '.txt'];
                     else;
                        ResFile = [DSGEModel.OutputDirectory '\PosteriorDist-CVD-ShockGroups-' VarType '-' num2str(CurrChain,'%0.0f') '-' DSGEModel.NameOfModel '-' num2str(UsedDraws,'%0.0f') '.' num2str(NumDraws,'%0.0f') '.txt'];
                     end;
                     if FileExist(ResFile)==1;
                        TextGUI(ResFile,['Conditional Variance Decompositions - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],['Posterior Distribution - ' VarType ' Data'],50,CurrINI,1,1);
                     end;
                  end;
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'estimateparamcovmat'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            %
            % get the parameter names
            %
            ParameterNames = ModeData.ParameterNames.estimated;
            InverseHessian = ModeData.InverseHessian;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Estimate Parameter Covariance Matrix','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            if strcmp(lower(action),'cancel')==0;
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('thetaPostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % skip the burnin draws
                  %
                  PostSample = PostSample(NumBurnin+1:NumDraws,:)';
                  %
                  % compute the mean
                  %
                  ParamMean = (1/(NumDraws-NumBurnin))*sum(PostSample,2);
                  %
                  % and now the covariance matrix
                  %
                  PostSample = PostSample-(ParamMean*ones(1,NumDraws-NumBurnin));
                  ParameterCovarianceMatrix = (1/(NumDraws-NumBurnin))*PostSample*PostSample';
                  clear('PostSample');
                  %
                  % now we save the matrix
                  %
                  MatFile = [DSGEModel.OutputDirectory '\' DSGEModel.NameOfModel '-EstParamCovarianceMatrix-' int2str(NumBurnin) '.' int2str(NumDraws) '.' int2str(CurrChain) '.mat'];
                  save(MatFile,'ParameterCovarianceMatrix');
                  drawnow;
                  %
                  % provide a message box
                  %
                  txt = ['YADA has estimated a parameter covariance matrix based on ' int2str(NumDraws-NumBurnin) ' post-burnin-period draws from the posterior distribution. The variable containing the matrix, "ParameterCovarianceMatrix", has been saved to disk in the file "' GetFilename(MatFile) '", located in the directory "' GetPath(MatFile) '". To use this matrix in the proposal density for the random-walk Metropolis algorithm you need to select "My estimate" for the option "Method for estimating the inverse Hessian" on the "Options" tab.'];
                  About(txt,'information','Estimate Parameter Covariance Matrix',400,500,CurrINI);
                  %
                  % now print the results to file and compare with the inverse Hessian
                  %
                  TxtFile = [DSGEModel.OutputDirectory '\' DSGEModel.NameOfModel '-EstParamCovarianceMatrix-' int2str(NumBurnin) '.' int2str(NumDraws) '.' int2str(CurrChain) '.txt'];
                  %
                  PrintParameterCovarianceMatrix(TxtFile,ParameterNames,ParameterCovarianceMatrix,InverseHessian,NumBurnin,NumDraws,CurrINI);
                  %
                  % display the results
                  %
                  if FileExist(TxtFile);
                     TextGUI(TxtFile,['Estimated Parameter Covariance Matrix - ' GetFilename(MatFile)],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Parameter Covariance Matrix - Transformed Parameters',50,CurrINI,1,1);
                  end;
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'hd_posterior'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            theta = ModeData.thetaMode;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Forecast Error Decomposition','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check which draws we should use
                  %
                  UseDraws = KeepPosteriorDraws(DSGEModel,controls.posterior.usepostdraws,NumDraws);
                  if length(UseDraws)<NumDraws;
                     thetaPostSample = thetaPostSample(UseDraws,:);
                     UsedDraws = length(UseDraws);
                  else;
                     UsedDraws = NumDraws;
                  end;
                  %
                  % select the forecast horizon
                  %
                  if strcmp(lower(DSGEModel.DataFrequency(1,1)),'q')==1;
                     FreqStr = 'quarter';
                     DefaultOption = 4;
                  elseif strcmp(lower(DSGEModel.DataFrequency(1,1)),'m')==1;
                     FreqStr = 'month';
                     DefaultOption = 12;
                  else;
                     FreqStr = 'year';
                     DefaultOption = 1;
                  end;
                  %
                  % select horizon for historical decomposition
                  %
                  SelectionOptions = ['1 ' FreqStr];
                  for i=2:max(20,floor(DSGEModel.T/4));
                     SelectionOptions = strvcat(SelectionOptions,[num2str(i) ' ' FreqStr 's']);
                  end;
                  %
                  [action,SelectedOption] = SelectionDlg(SelectionOptions,DefaultOption,'Select forecast horizon','Forecast Horizon Selection','Forecast Error Decompositions - Distribution','','',CurrINI);
                  if strcmp(lower(action),'ok')==1;
                     %
                     % Now determine the horizon
                     %
                     ForecastHorizon = strrep(SelectionOptions(SelectedOption,:),FreqStr,'');
                     ForecastHorizon = str2num(StringTrim(strrep(ForecastHorizon,'s','')));
                     %
                     % First we check if the calculations have already been performed
                     %
                     if HFEDExist(DSGEModel,ForecastHorizon,UsedDraws,NumDraws,CurrChain)==1;
                        txt = 'YADA has located results for the historical forecast error decompositions on disk. Would you like to use these results?';
                        answer = Query(txt,'information',150,'Forecast Error Decompositions - Distribution',450,'no',CurrINI);
                     else;
                        answer = 'No';
                     end;
                     if strcmp(lower(answer),'yes')==1;
                        DoneCalc = 1;
                     else;
                        %
                        % compute the historical forecast error decoimpositions for the posterior draws
                        %
                        DoneCalc = DSGEForecastErrorDecomposition(theta,thetaPostSample,thetaPositions,ModelParameters,DSGEModel,CurrINI,ForecastHorizon,NumDraws,CurrChain);
                     end;
                     %
                     % clear the posterior draws
                     %
                     clear('thetaPostSample');
                     %
                     % check if we should show any results
                     %
                     if DoneCalc==1;
                        %
                        % compute the distribution
                        %
                        HistDecompStructure = HFEDDistribution(DSGEModel,CurrINI,ForecastHorizon,UsedDraws,NumDraws,CurrChain);
                        %
                        % ask if the user wants to save the results to disk
                        %
                        txt = 'Would you like to save the historical forecast error decompositions to file?';
                        answer = Query(txt,'question',140,'Save - Forecast Error Decompositions',500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           OldHistDecompStructure = HistDecompStructure;
                           HistDecompStructure = rmfield(HistDecompStructure,{'R' 'KeepVar'});
                           YNames = DSGEModel.VariableNames;
                           ShockNames = DSGEModel.StateShockNames(OldHistDecompStructure.KeepVar,:);
                           file = [DSGEModel.OutputDirectory '\HistForecastErrorDecompDist-' int2str(ForecastHorizon) '-' num2str(CurrChain,'%0.0f') '-' num2str(UsedDraws,'%0.0f') '-' num2str(NumDraws,'%0.0f')   '.mat'];
                           save(file,'YNames','ShockNames','HistDecompStructure');
                           %
                           % create a matlab file to read the data
                           %
                           mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'HistForecastErrorDecompDist','HFEDDist');
                           fid = fopen(mfile,'wt');
                           fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                           fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                           fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                           fprintf(fid,'YNames = DataStructure.YNames;\n');
                           fprintf(fid,'%%\n%% string matrix with the names of the economic shocks\n%%\n');
                           fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                           fprintf(fid,'%%\n%% structure with fields epstth holding the forecast errors,\n%% with share wthT due to the measurement error, KsiErr due\n%% to the state error, and etathT due to the economic shocks.\n%% In addition, the structure has fields ForecastHorizon, and\n%% Quantiles with the percentile data.\n%%\n');
                           fprintf(fid,'HistDecompStructure = DataStructure.HistDecompStructure;\n');
                           fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                           %
                           % end the script file
                           %
                           fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                           fclose(fid);
                           txt = ['The historical forecast error decomposition data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 3 entries: YNames (string matrix with the names of the observed variables), ShockNames (string matrix with the names of the economic shocks), and HistDecompStructure (a structure with posterior mean and quantile data for the decomposition). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                           About(txt,'information','Forecast Error Decompositions - Distribution',200,500,CurrINI);
                           HistDecompStructure = OldHistDecompStructure;
                        end;
                        HistDecompStructure.FreqStr = strcat(upper(FreqStr(1,1)),FreqStr(1,2:length(FreqStr)));
                        %
                        % display the results
                        %
                        HistDecompDLG('init',CurrINI,DSGEModel,HistDecompStructure,'Distribution');
                     end;
                  end;
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'irs_post_dist'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         if strcmp(ErrorStr,'')==1;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Impulse Responses','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check which draws we should use
                  %
                  UseDraws = KeepPosteriorDraws(DSGEModel,controls.posterior.usepostdraws,NumDraws);
                  if length(UseDraws)<NumDraws;
                     thetaPostSample = thetaPostSample(UseDraws,:);
                     UsedDraws = length(UseDraws);
                  else;
                     UsedDraws = NumDraws;
                  end;
                  %
                  % are we using annualized data, levels, or the original
                  %
                  if gcbo==controls.irfunctions.posterior;
                     AnnualizeData = 0;
                     LevelsData = 0;
                     QueryHead = 'Impulse Responses - Original Data';
                     VarType = 'Original';
                  elseif gcbo==controls.irfunctions.lev_posterior;
                     AnnualizeData = 0;
                     LevelsData = 1;
                     QueryHead = 'Impulse Responses - Levels Data';
                     VarType = 'Levels';
                  else;
                     AnnualizeData = 1;
                     LevelsData = 0;
                     QueryHead = 'Impulse Responses - Annualized Data';
                     VarType = 'Annualized';
                  end;
                  %
                  % First we check if the calculations have already been performed
                  %
                  if IRFsExist(DSGEModel,AnnualizeData,LevelsData,UsedDraws,NumDraws,CurrChain)==1;
                     txt = 'YADA has located results for the impulse responses on disk. Would you like to use these results?';
                     answer = Query(txt,'information',150,QueryHead,450,'no',CurrINI);
                  else;
                     answer = 'No';
                  end;
                  if strcmp(lower(answer),'yes')==1;
                     DoneCalc = 1;
                  else;
                     %
                     % compute the impulse responses for all the posterior draws
                     %
                     DoneCalc = DSGEImpulseResponses(thetaPostSample,thetaPositions,ModelParameters,DSGEModel,CurrINI,AnnualizeData,LevelsData,NumDraws,CurrChain);
                  end;
                  %
                  % clear everything
                  %
                  clear('thetaPostSample');
                  %
                  % check if we should show any results
                  %
                  if DoneCalc==1;
                     ShockType = 'Individual';
                     if length(DSGEModel.ShockGroups)>max(DSGEModel.ShockGroups);
                        txt = 'Would you like to view plots of impulse responses for shock groups instead of for the individual shocks?';
                        answer = Query(txt,'question',200,QueryHead,500,'no',CurrINI);
                        if strcmp(lower(answer),'yes')==1;
                           ShockType = 'group';
                        end;
                     end;
                     %
                     % compute the distribution for the impulse responses
                     %
                     IRFs = DSGEIRFsDistribution(DSGEModel,CurrINI,AnnualizeData,LevelsData,lower(ShockType),UsedDraws,NumDraws,CurrChain);
                     %
                     % ask if we should save results to disk
                     %
                     txt = 'Would you like to save the impulse response functions to file?';
                     answer = Query(txt,'question',140,'Save - Impulse Responses',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        YNames = DSGEModel.VariableNames;
                        file = [DSGEModel.OutputDirectory '\ImpulseResponseDist-' VarType '-' ShockType '.mat'];
                        if strcmp(lower(ShockType),'individual')==1;
                           ShockNames = DSGEModel.StateShockNames;
                           save(file,'YNames','ShockNames','IRFs');
                        else;
                           ShockGroupNames = DSGEModel.ShockGroupNames;
                           save(file,'YNames','ShockGroupNames','IRFs');
                        end;
                        %
                        % create a matlab file to read the data
                        %
                        mfile = strrep(strrep(strrep(file,'.mat','.m'),'-',''),'ImpulseResponseDist','IRDist');
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                        fprintf(fid,'YNames = DataStructure.YNames;\n');
                        if strcmp(lower(ShockType),'individual')==1;
                           fprintf(fid,'%%\n%% string matrix with the names of the economic shocks\n%%\n');
                           fprintf(fid,'ShockNames = DataStructure.ShockNames;\n');
                        else;
                           fprintf(fid,'%%\n%% string matrix with the names of the shock groups\n%%\n');
                           fprintf(fid,'ShockGroupNames = DataStructure.ShockGroupNames;\n');
                        end;
                        fprintf(fid,'%%\n%% structure with fields Y containing the posterior mean\n%% impulse responses, and vector field Quantiles\n%% with subfields Y and percent holding quantile data and quantile percent.\n%%\n');
                        fprintf(fid,'IRFs = DataStructure.IRFs;\n');
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        txt = ['The impulse response data have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains 3 entries: YNames (string matrix with the names of the observed variables), ShockNames (string matrix with the names of the economic shocks), and IRFs (a structure with posterior mean and quantile data for the impulse responses). To access this data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','Impulse Responses',200,500,CurrINI);
                     end;
                     %
                     % display the results
                     %
                     IRDistributionGraphDLG('init',DSGEModel,CurrINI,IRFs,VarType,lower(ShockType));
                  end;
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'con_pred_posterior'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         HeaderStr = 'YADA - Bad MAT File';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         %
         % check if we should check transformations functions
         %
         if (isempty(ErrorStr)==1)&(gcbo==controls.predict.unconditional_transformed_postmode);
            DTStatus = VerifyDataTransformation(DSGEModel.VariableNames,DSGEModel.YTransformation,0);
            if DTStatus==1;
               [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
            else;
               ErrorStr = 'You haven''t specified all the necessary fields for computing transformations of the observed variables.';
               HeaderStr = 'Missing Transformation Information';
            end;
         end;
         %
         if strcmp(ErrorStr,'')==1;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % check how many time periods to use for predictive distributions
            %
            [MaxPH,NumPredX] = CalcMaxPredictionHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,size(DSGEModel.PredictedX,2));
            %
            % matrix with exogenous variables
            %
            X = [];
            if DSGEModel.k>0;
               if NumPredX<MaxPH;
                  X = DSGEModel.X(:,LastPeriod+1:LastPeriod+(MaxPH-NumPredX));
               end;
               if NumPredX>0;
                  X = [X DSGEModel.PredictedX(:,1:NumPredX)];
               end;
            end;
            %
            % check the length of the conditioning sample
            %
            [status,NumPeriods] = CheckConditioningData(DSGEModel);
            %
            % check if we should adjust the X matrix
            %
            if MaxPH<NumPeriods;
               NumPeriods = MaxPH;
            end;
            %
            % collect the conditional variables and the selected conditioning sample
            %
            Z = DSGEModel.Z(DSGEModel.ConditionalVariables,LastPeriod+1:LastPeriod+NumPeriods);
            U = DSGEModel.U(DSGEModel.ConditionalVariables,LastPeriod-NumPeriods+1:LastPeriod);
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Conditional Predictive Distributions','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % 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;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check how many draws we should pick among these
                  %
                  PostDrawsUsageStr = get(controls.posterior.postdrawsusage,'String');
                  NumPostDrawsUsage = min(str2num(strrep(StringTrim(PostDrawsUsageStr(DSGEModel.PostDrawsUsageValue,:)),',','')),NumDraws);
                  %
                  % get the draws to use
                  %
                  if DSGEModel.RandomizeDraws==0;
                     DrawFreq = round(NumDraws/NumPostDrawsUsage);
                     SelectDraws = (1:DrawFreq:NumDraws);
                     if length(SelectDraws)+1==NumPostDrawsUsage;
                        SelectDraws = [SelectDraws NumDraws];
                     elseif length(SelectDraws)>NumPostDrawsUsage;
                        SelectDraws = SelectDraws(1:NumPostDrawsUsage);
                     end;
                     thetaPostSample = thetaPostSample(SelectDraws,:);
                  else;
                     thetaPostSample = thetaPostSample(ceil(rand(NumPostDrawsUsage,1)*NumDraws),:);
                  end;
                  %
                  % are we using annualized data or the original
                  %
                  if gcbo==controls.predict.conditional_original_posterior;
                     TransData = 0;
                     AnnualizeData = 0;
                     AnnualStr = 'original';
                     QueryHead = 'Conditional Predictive Distributions - Original Data';
                  elseif gcbo==controls.predict.conditional_annual_posterior;
                     TransData = 0;
                     AnnualizeData = 1;
                     AnnualStr = 'annual';
                     QueryHead = 'Conditional Predictive Distributions - Annualized Data';
                  else;
                     TransData = 1;
                     AnnualizeData = 0;
                     AnnualStr = 'transformed';
                     QueryHead = 'Conditional Predictive Distributions - Transformed Data';
                  end;
                  %
                  % check which method is used for dealing with the conditioning assumptions
                  %
                  if DSGEModel.ShockControlMethod==1;
                     ShockMethod = 'Direct-';
                  else;
                     ShockMethod = 'WaggonerZha-';
                  end;
                  %
                  % determine how many prediction paths to use
                  %
                  NumPredPathsStr = get(controls.forecast.predpaths,'String');
                  NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
                  %
                  % check if we have already stored results to disk
                  %
                  if PredictionsExist(DSGEModel.OutputDirectory,'DSGE','Cond',ShockMethod,DSGEModel.NameOfModel,MaxPH,NumPostDrawsUsage,NumPredPaths,AnnualizeData,TransData,CurrChain)==1;
                     txt = 'YADA has located results for the conditional predictive distribution on disk. Would you like to use these results?';
                     answer = Query(txt,'information',150,QueryHead,450,'no',CurrINI);
                  else;
                     answer = 'No';
                  end;
                  if strcmp(lower(answer),'yes')==1;
                     [PredEventData,PredictionEvent,ShockMean,ShockNames,StateCov,ShockCov,MeasureCov,ParameterCov] = LoadDSGEPredictionUncertainty(DSGEModel.OutputDirectory,'Cond',ShockMethod,DSGEModel.NameOfModel,MaxPH,NumPostDrawsUsage,NumPredPaths,AnnualizeData,TransData,CurrChain);
                     DoneCalc = 1;
                  else;
                     %
                     % ask if we should conduct prediction event calculations
                     %
                     if (isfield(DSGEModel,'PredictionEvent')==0)|(isempty(DSGEModel.PredictionEvent)==1)|(size(DSGEModel.PredictionEvent,1)~=DSGEModel.n)|(size(DSGEModel.PredictionEvent,2)~=3);
                        DSGEModel.PredictionEvent = [Inf*ones(DSGEModel.n,1) zeros(DSGEModel.n,1) ones(DSGEModel.n,1)];
                     end;
                     txt = 'Would you like YADA to calculate prediction event probabilities?';
                     answer = Query(txt,'question',140,'Prediction Events',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        %
                        % make sure that the prediction event length does not exceed the maximum prediction horizon
                        %
                        for i=1:DSGEModel.n;
                           if DSGEModel.PredictionEvent(i,3)>MaxPH;
                              DSGEModel.PredictionEvent(i,3) = MaxPH;
                           end;
                        end;
                        %
                        % display a dialog for setting up an prediction event
                        %
                        [action,PredictionEvent] = PredictionEventDLG('init',DSGEModel.VariableNames,DSGEModel.PredictionEvent,MaxPH,CurrINI);
                        if strcmp(lower(action),'ok')==1;
                           DSGEModel.PredictionEvent = PredictionEvent;
                           DSGEModel.RunPredictionEvent = 1;
                        else;
                           DSGEModel.RunPredictionEvent = 0;
                        end;
                     else;
                        DSGEModel.RunPredictionEvent = 0;
                     end;
                     %
                     % we can now compute the predictive distribution for the endogenous variables
                     % up to period MaxPH
                     %
                     if DSGEModel.ShockControlMethod==1;
                        [DoneCalc,PredEventData,ShockMean,ShockNames,StateCov,ShockCov,MeasureCov,ParameterCov] = DSGECondPredictionPaths(thetaPostSample,ModeData.thetaMode,thetaPositions,ModelParameters,DSGEModel,CurrINI,X,Z,U,MaxPH,NumPredPaths,AnnualizeData,TransData,CurrChain);
                     else;
                        [DoneCalc,PredEventData,ShockMean,ShockNames,StateCov,ShockCov,MeasureCov,ParameterCov] = DSGECondPredictionPathsWZ(thetaPostSample,ModeData.thetaMode,thetaPositions,ModelParameters,DSGEModel,CurrINI,X,Z,U,MaxPH,NumPredPaths,AnnualizeData,TransData,CurrChain);
                     end;
                  end;
                  %
                  % clear everything
                  %
                  clear('thetaPostSample');
                  %
                  % check if we should show any results
                  %
                  if DoneCalc==1;
                     %
                     % yes, now we need to calculate some distribution properties
                     %
                     [MeanPrediction,Quantiles,KernelX,KernelY] = DSGEPredictionDistribution(DSGEModel.n,DSGEModel.OutputDirectory,'Cond',ShockMethod,DSGEModel.NameOfModel,MaxPH,NumPostDrawsUsage,NumPredPaths,AnnualizeData,TransData,CurrChain,DSGEModel.Percentiles,DSGEModel.VariableNames,CurrINI);
                     %
                     % compute the forecast errors based on the mean predictions
                     %
                     PredictionErrors = CalculatePredictionErrors(MeanPrediction,AnnualizeData,TransData,'DSGE',DSGEModel);
                     %
                     % check if we should evaluate modesty test data
                     %
                     if AnnualizeData==0;
                        [MultiPValue,MeanMultiModesty,MeanUniModesty,MeanUniModestyLZ] = DSGEModestyStatistics(DSGEModel.OutputDirectory,ShockMethod,DSGEModel.NameOfModel,MaxPH,NumPostDrawsUsage,NumPredPaths,CurrChain,DSGEModel.n);
                        if exist('YADAchi2cdf')==2;
                           ChiSqPValue = 1-YADAchi2cdf(MeanMultiModesty(1),DSGEModel.n);
                        else;
                           if exist('chi2cdf')==2;
                              ChiSqPValue = 1-chi2cdf(MeanMultiModesty(1),DSGEModel.n);
                           else;
                              ChiSqPValue = 1-YADACheapchi2cdf(MeanMultiModesty(1),DSGEModel.n);
                           end;
                        end;
                        %
                        % print results to file
                        %
                        PrintDSGEModestyStatistics(DSGEModel,CurrINI,CurrChain,MaxPH,NumPeriods,NumPostDrawsUsage,NumPredPaths,MultiPValue,MeanMultiModesty,MeanUniModesty,MeanUniModestyLZ,ShockMean,ShockNames);
                     else;
                        ChiSqPValue = [];
                        MultiPValue = [];
                        MeanMultiModesty = [];
                        MeanUniModesty = [];
                        MeanUniModestyLZ = [];
                     end;
                     %
                     % check if the user wants to save the data
                     %
                     txt = ['Would you like to save the conditional predictive distributions for the ' AnnualStr ' data to file?'];
                     answer = Query(txt,'question',140,'Save - Conditional Predictive Distributions',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod,PredDateVector] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,size(MeanPrediction,2));
                        file = [DSGEModel.OutputDirectory '\CondPredictiveDist-' int2str(DSGEModel.ShockControlMethod) '-' AnnualStr '-' num2str(CurrChain,'%0.0f') '-' num2str(MaxPH,'%0.0f') '-' num2str(NumPostDrawsUsage,'%0.0f') '.' num2str(NumPredPaths,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '.mat'];
                        YNames = DSGEModel.VariableNames;
                        DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,PredEndYear,PredEndPeriod,DSGEModel.DataFrequency);
                        Y = DSGEModel.Y(:,FirstPeriod:min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                        if (length(DateVector)>size(Y,2))&(TransData==0);
                           DateVector = DateVector(1,1:size(Y,2));
                        end;
                        EstimationStartPeriod = DSGEModel.KalmanFirstObservation;
                        EstimationStartPeriodOrig = EstimationStartPeriod;
                        YOrig = Y;
                        DateVectorOrig = DateVector;
                        if AnnualizeData==1;
                           Y = Annualize(Y,DSGEModel.annual,DSGEModel.annualscale);
                           EstimationStartPeriod = max(1,EstimationStartPeriod-(length(DateVector)-size(Y,2)));
                           DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                        end;
                        %
                        if TransData==1;
                           [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
                           Y = YData';
                           if size(Y,2)==DSGEModel.T;
                              Y = Y(:,FirstPeriod:min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                           else;
                              T2 = size(Y,2);
                              if (FirstPeriod-(DSGEModel.T-T2))>=1;
                                 Y = Y(:,FirstPeriod-(DSGEModel.T-T2):min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                              else;
                                 Y = Y(:,1:min((LastPeriod+MaxPH),size(DSGEModel.Y,2))-(DSGEModel.T-T2));
                                 DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                              end;
                           end;
                        end;
                        %
                        if isempty(PredEventData)==1;
                           save(file,'MeanPrediction','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','StateCov','ShockCov','MeasureCov','ParameterCov','MeanMultiModesty','MultiPValue','ChiSqPValue','MeanUniModesty','MeanUniModestyLZ','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig');
                        else;
                           save(file,'MeanPrediction','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','StateCov','ShockCov','MeasureCov','ParameterCov','MeanMultiModesty','MultiPValue','ChiSqPValue','MeanUniModesty','MeanUniModestyLZ','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig','PredictionEvent','PredEventData');
                        end;
                        %
                        % create a matlab m-file to read the output.
                        %
                        mfile = [DSGEModel.OutputDirectory '\CondPD' int2str(DSGEModel.ShockControlMethod) AnnualStr num2str(CurrChain,'%0.0f') num2str(MaxPH,'%0.0f') num2str(NumPostDrawsUsage,'%0.0f') num2str(NumPredPaths,'%0.0f') DSGEModel.SubEndYear DSGEModel.SubEndPeriod '.m'];
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                        fprintf(fid,'YNames = DataStructure.YNames;\n');
                        fprintf(fid,'%%\n%% matrix with the mean predictions of the observed variables\n%%\n');
                        fprintf(fid,'MeanPrediction = DataStructure.MeanPrediction;\n');
                        fprintf(fid,'%%\n%% matrix with the errors from the mean predictions of the observed variables\n%%\n');
                        fprintf(fid,'PredictionErrors = DataStructure.PredictionErrors;\n');
                        fprintf(fid,'%%\n%% vector structure with quantiles from the predictive distribution\n%% the structure has %0.0f entries with fields "Quantile" and "percent"\n%% the first field is a matrix and the second a positive number between 0 and 100\n%%\n',length(Quantiles));
                        fprintf(fid,'Quantiles = DataStructure.Quantiles;\n');
                        fprintf(fid,'%%\n%% matrix with x-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                        fprintf(fid,'KernelX = DataStructure.KernelX;\n');
                        fprintf(fid,'%%\n%% matrix with y-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                        fprintf(fid,'KernelY = DataStructure.KernelY;\n');
                        fprintf(fid,'%%\n%% vector with dates for the predictions\n%%\n');
                        fprintf(fid,'PredDateVector = DataStructure.PredDateVector;\n');
                        fprintf(fid,'%%\n%% observed variables\n%%\n');
                        fprintf(fid,'Y = DataStructure.Y;\n');
                        fprintf(fid,'%%\n%% vector with dates for the observed variables\n%%\n');
                        fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                        if (AnnualizeData==0)&(TransData==0);
                           fprintf(fid,'%%\n%% 3D Error covariance matrix (nxnxh) part due to state uncertainty\n%%\n');
                           fprintf(fid,'StateCov = DataStructure.StateCov;\n');
                           fprintf(fid,'%%\n%% 3D Error covariance matrix (nxnxh) part due to shock uncertainty\n%%\n');
                           fprintf(fid,'ShockCov = DataStructure.ShockCov;\n');
                           fprintf(fid,'%%\n%% 2D Error covariance matrix (nxn) part due to measurement error uncertainty\n%%\n');
                           fprintf(fid,'MeasureCov = DataStructure.MeasureCov;\n');
                           fprintf(fid,'%%\n%% 3D Error covariance matrix (nxnxh) part due to parameter uncertainty\n%%\n');
                           fprintf(fid,'ParameterCov = DataStructure.ParameterCov;\n');
                           CovDecompStr = 'StateCov (3D error covariance matrix with part due to state uncertainty), ShockCov (3D error covariance matrix with part due to shock uncertainty), MeasureCov (2D error covariance matrix with part due to measurement error uncertainty), ParameterCov (3D covariance matrix with part due to parameter uncertainty), ';
                        else;
                           CovDecompStr = '';
                        end;
                        if isempty(PredEventData)==0;
                           fprintf(fid,'%%\n%% matrix with the prediction event definitions. The first column\n%% holds the upper bound, the second column\n%% the lower bound, and third the length of the event.\n%%\n');
                           fprintf(fid,'PredictionEvent = DataStructure.PredictionEvent;\n');
                           fprintf(fid,'%%\n%% matrix with prediction event data. First column holds the\n%% number of true events, the second the number of times below the events, and the third the number of events\n%%\n');
                           fprintf(fid,'PredEventData = DataStructure.PredEventData;\n');
                           if (AnnualizeData==0)&(TransData==0);
                              NumEntries = '15';
                           else;
                              NumEntries = '11';
                           end;
                           ExtraEntry = 'PredictionEvent (matrix with the upper and lower bound of the event and the length of the event), PredEventData (matrix with the number of true events, the number of events below the lower bound for the event, and the number of events tested in the columns), ';
                        else;
                           if (AnnualizeData==0)&(TransData==0);
                              NumEntries = '13';
                           else;
                              NumEntries = '9';
                           end;
                           ExtraEntry = '';
                        end;
                        if AnnualizeData==0;
                           fprintf(fid,'%%\n%% vector with the mean of the multivariate modesty statistic and its reference statistic\n%%\n');
                           fprintf(fid,'MeanMultiModesty = DataStructure.MeanMultiModesty;\n');
                           fprintf(fid,'%%\n%% tail probability based on the reference statistic\n%%\n');
                           fprintf(fid,'MultiPValue = DataStructure.MultiPValue;\n');
                           fprintf(fid,'%%\n%% tail probability based on the chi-square distribution\n%%\n');
                           fprintf(fid,'ChiSqPValue = DataStructure.ChiSqPValue;\n');
                           fprintf(fid,'%%\n%% Adolfson, Laséen, Lindé and Villani univariate modesty statistic\n%%\n');
                           fprintf(fid,'MeanUniModesty = DataStructure.MeanUniModesty;\n');
                           fprintf(fid,'%%\n%% Leeper and Zha univariate modesty statistic\n%%\n');
                           fprintf(fid,'MeanUniModestyLZ = DataStructure.MeanUniModestyLZ;\n');
                           NumEntries = num2str(str2num(NumEntries)+5,'%0.0f');
                           ExtraEntry = [ExtraEntry 'MeanMultiModesty (1x2 vector with the mean of the multivariate modesty statistic and the mean of the multivariate reference modesty statistic), MultiPValue (scalar with the tail probability of the modesty statistic), ChiSqPValue (scalar with the tail probability of the modesty statistic using the chi-square distribution), MeanUniModesty (vector with the univariate modesty statistic from ALLV), MeanUniModestyLZ (vector with the univariate Leeper-Zha modesty statistic), '];
                        end;
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        %
                        txt = ['The conditional predictive distributions have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains ' NumEntries ' entries: YNames (string matrix with the names of the observed variables), MeanPrediction (matrix with the mean predictions), PredictionErrors (matrix with errors for the mean predictions), Quantiles (vector structure with 2 fields: Quantile and percent), KernelX (matrix with x-axis for kernel density estimates of marginal predictive distribution), KernelY (matrix with y-axis values for kernel density estimates of marginal predictive distribution), PredDateVector (vector with dates for the predictions), Y (matrix) with the observed variables, ' CovDecompStr ExtraEntry 'and DateVector (vector with dates for the observed variables). To access these data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','Conditional Predictive Distributions',500,550,CurrINI);
                     end;
                     if isempty(PredEventData)==0;
                        %
                        % write prediction event results to file
                        %
                        file = [DSGEModel.OutputDirectory '\CondPredictiveDist-' int2str(DSGEModel.ShockControlMethod) '-' AnnualStr '-' num2str(CurrChain,'%0.0f') '-' num2str(MaxPH,'%0.0f') '-' num2str(NumPostDrawsUsage,'%0.0f') '.' num2str(NumPredPaths,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '.txt'];
                        [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,MaxPH);
                        PrintPredictionEvent(file,DSGEModel.VariableNames,PredEventData,[],PredictionEvent,[PredStartYear ':' PredStartPeriod '-' PredEndYear ':' PredEndPeriod],MaxPH,NumPredPaths,NumPostDrawsUsage,CurrINI);
                        %
                        % displays the file if it exists
                        %
                        if FileExist(file)==1;
                           TextGUI(file,['Prediction Events - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Distribution - Conditional Predictions',50,CurrINI,1,0);
                        end;
                     end;
                     %
                     % summarize the information in the uncertainty variables more conveniently
                     %
                     if isempty(StateCov)==0;
                        [StateVar,ShockVar,MeasureVar,ParameterVar] = SummarizeDSGEPredictions(StateCov,ShockCov,MeasureCov,ParameterCov);
                        %
                        % Open a dialog for displaying predictive distributions
                        %
                        UData.StateVar = StateVar;
                        UData.ShockVar = ShockVar;
                        UData.MeasureVar = MeasureVar;
                        UData.ParameterVar = ParameterVar;
                     else;
                        UData = [];
                     end;
                     %
                     % make sure that UData is empty until the forecast error variance decompositions have been solved
                     % under conditional forecasting
                     %
                     UData = [];
                     CondPredictiveDistributionDLG('init',DSGEModel,CurrINI,MeanPrediction,Quantiles,KernelX,KernelY,'','DSGE',AnnualStr,UData);
                  end;
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information',HeaderStr,120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'con_pred_event'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         HeaderStr = 'YADA - Bad MAT File';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         %
         % check if we should check transformations functions
         %
         if (isempty(ErrorStr)==1)&(gcbo==controls.predict.conditional_transformed_predevent);
            DTStatus = VerifyDataTransformation(DSGEModel.VariableNames,DSGEModel.YTransformation,0);
            if DTStatus==1;
               [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
            else;
               ErrorStr = 'You haven''t specified all the necessary fields for computing transformations of the observed variables.';
               HeaderStr = 'Missing Transformation Information';
            end;
         end;
         %
         if strcmp(ErrorStr,'')==1;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % check how many time periods to use for predictive distributions
            %
            [MaxPH,NumPredX] = CalcMaxPredictionHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,size(DSGEModel.PredictedX,2));
            %
            % matrix with exogenous variables
            %
            X = [];
            if DSGEModel.k>0;
               if NumPredX<MaxPH;
                  X = DSGEModel.X(:,LastPeriod+1:LastPeriod+(MaxPH-NumPredX));
               end;
               if NumPredX>0;
                  X = [X DSGEModel.PredictedX(:,1:NumPredX)];
               end;
            end;
            %
            % check the length of the conditioning sample
            %
            [status,NumPeriods] = CheckConditioningData(DSGEModel);
            %
            % check if we should adjust the X matrix
            %
            if MaxPH<NumPeriods;
               NumPeriods = MaxPH;
            end;
            %
            % collect the conditional variables and the selected conditioning sample
            %
            Z = DSGEModel.Z(DSGEModel.ConditionalVariables,LastPeriod+1:LastPeriod+NumPeriods);
            U = DSGEModel.U(DSGEModel.ConditionalVariables,LastPeriod-NumPeriods+1:LastPeriod);
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Prediction Event','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % 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;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check how many draws we should pick among these
                  %
                  PostDrawsUsageStr = get(controls.posterior.postdrawsusage,'String');
                  NumPostDrawsUsage = min(str2num(strrep(StringTrim(PostDrawsUsageStr(DSGEModel.PostDrawsUsageValue,:)),',','')),NumDraws);
                  %
                  % get the draws to use
                  %
                  if DSGEModel.RandomizeDraws==0;
                     DrawFreq = round(NumDraws/NumPostDrawsUsage);
                     SelectDraws = (1:DrawFreq:NumDraws);
                     if length(SelectDraws)+1==NumPostDrawsUsage;
                        SelectDraws = [SelectDraws NumDraws];
                     elseif length(SelectDraws)>NumPostDrawsUsage;
                        SelectDraws = SelectDraws(1:NumPostDrawsUsage);
                     end;
                     thetaPostSample = thetaPostSample(SelectDraws,:);
                  else;
                     thetaPostSample = thetaPostSample(ceil(rand(NumPostDrawsUsage,1)*NumDraws),:);
                  end;
                  %
                  % are we using annualized data or the original
                  %
                  if gcbo==controls.predict.conditional_original_predevent;
                     TransData = 0;
                     AnnualizeData = 0;
                     AnnualStr = 'original';
                     QueryHead = 'Conditional Predictive Distributions - Original Data';
                  elseif gcbo==controls.predict.conditional_annual_predevent;
                     TransData = 0;
                     AnnualizeData = 1;
                     AnnualStr = 'annual';
                     QueryHead = 'Conditional Predictive Distributions - Annualized Data';
                  else;
                     TransData = 1;
                     AnnualizeData = 0;
                     AnnualStr = 'transformed';
                     QueryHead = 'Conditional Predictive Distributions - Transformed Data';
                  end;
                  %
                  % prediction event calculations
                  %
                  if (isfield(DSGEModel,'PredictionEvent')==0)|(isempty(DSGEModel.PredictionEvent)==1)|(size(DSGEModel.PredictionEvent,1)~=DSGEModel.n)|(size(DSGEModel.PredictionEvent,2)~=3);
                     DSGEModel.PredictionEvent = [Inf*ones(DSGEModel.n,1) zeros(DSGEModel.n,1) ones(DSGEModel.n,1)];
                  end;
                  %
                  % make sure that the prediction event length does not exceed the maximum prediction horizon
                  %
                  for i=1:DSGEModel.n;
                     if DSGEModel.PredictionEvent(i,3)>MaxPH;
                        DSGEModel.PredictionEvent(i,3) = MaxPH;
                     end;
                  end;
                  %
                  % display a dialog for setting up an prediction event
                  %
                  [action,PredictionEvent] = PredictionEventDLG('init',DSGEModel.VariableNames,DSGEModel.PredictionEvent,MaxPH,CurrINI);
                  %
                  % check if user cancelled or not
                  %
                  if strcmp(lower(action),'ok')==1;
                     DSGEModel.PredictionEvent = PredictionEvent;
                     DSGEModel.RunPredictionEvent = 1;
                     %
                     % check which method is used for dealing with the conditioning assumptions
                     %
                     if DSGEModel.ShockControlMethod==1;
                        ShockMethod = 'Direct-';
                     else;
                        ShockMethod = 'WaggonerZha-';
                     end;
                     %
                     % determine how many prediction paths to use
                     %
                     NumPredPathsStr = get(controls.forecast.predpaths,'String');
                     NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
                     %
                     % check if we have already stored results to disk
                     %
                     if PredictionsExist(DSGEModel.OutputDirectory,'DSGE','Cond',ShockMethod,DSGEModel.NameOfModel,MaxPH,NumPostDrawsUsage,NumPredPaths,AnnualizeData,TransData,CurrChain)==1;
                        txt = 'YADA has located results for the conditional predictive distribution on disk. Would you like to use these results?';
                        answer = Query(txt,'information',150,QueryHead,450,'no',CurrINI);
                     else;
                        answer = 'No';
                     end;
                     if strcmp(lower(answer),'yes')==1;
                        %
                        % compute the prediction event results
                        %
                        PredEventData = LoadDSGEPredictionPaths(DSGEModel.PredictionEvent,DSGEModel.OutputDirectory,'Cond',ShockMethod,DSGEModel.NameOfModel,MaxPH,NumPostDrawsUsage,NumPredPaths,AnnualizeData,TransData,CurrChain,CurrINI);
                        DoneCalc = 1;
                     else;
                        %
                        % we can now compute the predictive distribution for the endogenous variables
                        % up to period MaxPH
                        %
                        if DSGEModel.ShockControlMethod==1;
                           [DoneCalc,PredEventData,StateCov,ShockCov,MeasureCov,ParameterCov] = DSGECondPredictionPaths(thetaPostSample,ModeData.thetaMode,thetaPositions,ModelParameters,DSGEModel,CurrINI,X,Z,U,MaxPH,NumPredPaths,AnnualizeData,TransData,CurrChain);
                        else;
                           [DoneCalc,PredEventData,ShockMean,ShockNames,StateCov,ShockCov,MeasureCov,ParameterCov] = DSGECondPredictionPathsWZ(thetaPostSample,ModeData.thetaMode,thetaPositions,ModelParameters,DSGEModel,CurrINI,X,Z,U,MaxPH,NumPredPaths,AnnualizeData,TransData,CurrChain);
                        end;
                     end;
                     %
                     % clear everything
                     %
                     clear('thetaPostSample');
                     %
                     % check if we should show any results
                     %
                     if DoneCalc==1;
                        %
                        % check if summary results already exist on disk
                        %
                        [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod,PredDateVector] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,MaxPH);
                        file = [DSGEModel.OutputDirectory '\CondPredictiveDist-' int2str(DSGEModel.ShockControlMethod) '-' AnnualStr '-' num2str(CurrChain,'%0.0f') '-' num2str(MaxPH,'%0.0f') '-' num2str(NumPostDrawsUsage,'%0.0f') '.' num2str(NumPredPaths,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '.mat'];
                        if FileExist(file)==1;
                           save(file,'PredictionEvent','PredEventData','-APPEND');
                           %
                           % create a matlab m-file to read the output.
                           %
                           mfile = [DSGEModel.OutputDirectory '\CondPD' int2str(DSGEModel.ShockControlMethod) AnnualStr num2str(CurrChain,'%0.0f') num2str(MaxPH,'%0.0f') num2str(NumPostDrawsUsage,'%0.0f') num2str(NumPredPaths,'%0.0f') DSGEModel.SubEndYear DSGEModel.SubEndPeriod '.m'];
                           fid = fopen(mfile,'wt');
                           fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                           fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                           fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                           fprintf(fid,'YNames = DataStructure.YNames;\n');
                           fprintf(fid,'%%\n%% matrix with the mean predictions of the observed variables\n%%\n');
                           fprintf(fid,'MeanPrediction = DataStructure.MeanPrediction;\n');
                           fprintf(fid,'%%\n%% matrix with the errors from the mean predictions of the observed variables\n%%\n');
                           fprintf(fid,'PredictionErrors = DataStructure.PredictionErrors;\n');
                           fprintf(fid,'%%\n%% vector structure with quantiles from the predictive distribution\n%% the structure has %0.0f entries with fields "Quantile" and "percent"\n%% the first field is a matrix and the second a positive number between 0 and 100\n%%\n',length(DSGEModel.Percentiles));
                           fprintf(fid,'Quantiles = DataStructure.Quantiles;\n');
                           fprintf(fid,'%%\n%% vector with dates for the predictions\n%%\n');
                           fprintf(fid,'PredDateVector = DataStructure.PredDateVector;\n');
                           fprintf(fid,'%%\n%% observed variables\n%%\n');
                           fprintf(fid,'Y = DataStructure.Y;\n');
                           fprintf(fid,'%%\n%% vector with dates for the observed variables\n%%\n');
                           fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                           if (AnnualizeData==0)&(TransData==0);
                              fprintf(fid,'%%\n%% 3D Error covariance matrix (nxnxh) part due to state uncertainty\n%%\n');
                              fprintf(fid,'StateCov = DataStructure.StateCov;\n');
                              fprintf(fid,'%%\n%% 3D Error covariance matrix (nxnxh) part due to shock uncertainty\n%%\n');
                              fprintf(fid,'ShockCov = DataStructure.ShockCov;\n');
                              fprintf(fid,'%%\n%% 2D Error covariance matrix (nxn) part due to measurement error uncertainty\n%%\n');
                              fprintf(fid,'MeasureCov = DataStructure.MeasureCov;\n');
                              fprintf(fid,'%%\n%% 3D Error covariance matrix (nxnxh) part due to parameter uncertainty\n%%\n');
                              fprintf(fid,'ParameterCov = DataStructure.ParameterCov;\n');
                           end;
                           fprintf(fid,'%%\n%% matrix with the prediction event definitions. The first column\n%% holds the upper bound, the second column\n%% the lower bound, and third the length of the event.\n%%\n');
                           fprintf(fid,'PredictionEvent = DataStructure.PredictionEvent;\n');
                           fprintf(fid,'%%\n%% matrix with prediction event data. First column holds the\n%% number of true events, the second the number of times below the events, and the third the number of events\n%%\n');
                           fprintf(fid,'PredEventData = DataStructure.PredEventData;\n');
                           if AnnualizeData==0;
                              fprintf(fid,'%%\n%% vector with the mean of the multivariate modesty statistic and its reference statistic\n%%\n');
                              fprintf(fid,'MeanMultiModesty = DataStructure.MeanMultiModesty;\n');
                              fprintf(fid,'%%\n%% tail probability based on the reference statistic\n%%\n');
                              fprintf(fid,'MultiPValue = DataStructure.MultiPValue;\n');
                              fprintf(fid,'%%\n%% tail probability based on the chi-square distribution\n%%\n');
                              fprintf(fid,'ChiSqPValue = DataStructure.ChiSqPValue;\n');
                              fprintf(fid,'%%\n%% Adolfson, Laséen, Lindé and Villani univariate modesty statistic\n%%\n');
                              fprintf(fid,'MeanUniModesty = DataStructure.MeanUniModesty;\n');
                              fprintf(fid,'%%\n%% Leeper and Zha univariate modesty statistic\n%%\n');
                              fprintf(fid,'MeanUniModestyLZ = DataStructure.MeanUniModestyLZ;\n');
                           end;
                           fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                           %
                           % end the script file
                           %
                           fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                           fclose(fid);
                        end;
                        %
                        % write prediction event results to file
                        %
                        file = [DSGEModel.OutputDirectory '\CondPredictiveDist-' int2str(DSGEModel.ShockControlMethod) '-' AnnualStr '-' num2str(CurrChain,'%0.0f') '-' num2str(MaxPH,'%0.0f') '-' num2str(NumPostDrawsUsage,'%0.0f') '.' num2str(NumPredPaths,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '.txt'];
                        [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,MaxPH);
                        PrintPredictionEvent(file,DSGEModel.VariableNames,PredEventData,[],PredictionEvent,[PredStartYear ':' PredStartPeriod '-' PredEndYear ':' PredEndPeriod],MaxPH,NumPredPaths,NumPostDrawsUsage,CurrINI);
                        %
                        % displays the file if it exists
                        %
                        if FileExist(file)==1;
                           TextGUI(file,['Prediction Events - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Distribution - Conditional Predictions',50,CurrINI,1,0);
                        end;
                     end;
                  else;
                     %
                     % make sure that the posterior draws are released from memory
                     %
                     clear('thetaPostSample');
                  end;
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information',HeaderStr,120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'uncon_pred_posterior'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         HeaderStr = 'YADA - Bad MAT File';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         %
         % check if we should check transformations functions
         %
         if (isempty(ErrorStr)==1)&(gcbo==controls.predict.unconditional_transformed_postmode);
            DTStatus = VerifyDataTransformation(DSGEModel.VariableNames,DSGEModel.YTransformation,0);
            if DTStatus==1;
               [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
            else;
               ErrorStr = 'You haven''t specified all the necessary fields for computing transformations of the observed variables.';
               HeaderStr = 'Missing Transformation Information';
            end;
         end;
         %
         if strcmp(ErrorStr,'')==1;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            thetaMode = ModeData.theta;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % check how many time periods to use for predictive distributions
            %
            [MaxPH,NumPredX] = CalcMaxPredictionHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,size(DSGEModel.PredictedX,2));
            %
            % matrix with exogenous variables
            %
            X = [];
            if DSGEModel.k>0;
               if NumPredX<MaxPH;
                  X = DSGEModel.X(:,LastPeriod+1:LastPeriod+(MaxPH-NumPredX));
               end;
               if NumPredX>0;
                  X = [X DSGEModel.PredictedX(:,1:NumPredX)];
               end;
            end;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Predictive Distributions','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % 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;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check how many draws we should pick among these
                  %
                  PostDrawsUsageStr = get(controls.posterior.postdrawsusage,'String');
                  NumPostDrawsUsage = min(str2num(strrep(StringTrim(PostDrawsUsageStr(DSGEModel.PostDrawsUsageValue,:)),',','')),NumDraws);
                  %
                  % get the draws to use
                  %
                  if DSGEModel.RandomizeDraws==0;
                     DrawFreq = round(NumDraws/NumPostDrawsUsage);
                     SelectDraws = (1:DrawFreq:NumDraws);
                     if length(SelectDraws)+1==NumPostDrawsUsage;
                        SelectDraws = [SelectDraws NumDraws];
                     elseif length(SelectDraws)>NumPostDrawsUsage;
                        SelectDraws = SelectDraws(1:NumPostDrawsUsage);
                     end;
                     thetaPostSample = thetaPostSample(SelectDraws,:);
                  else;
                     thetaPostSample = thetaPostSample(ceil(rand(NumPostDrawsUsage,1)*NumDraws),:);
                  end;
                  %
                  % are we using annualized data or the original
                  %
                  if gcbo==controls.predict.unconditional_original_posterior;
                     TransData = 0;
                     AnnualizeData = 0;
                     AnnualStr = 'original';
                     QueryHead = 'Predictive Distributions - Original Data';
                  elseif gcbo==controls.predict.unconditional_annual_posterior;
                     TransData = 0;
                     AnnualizeData = 1;
                     AnnualStr = 'annual';
                     QueryHead = 'Predictive Distributions - Annualized Data';
                  else;
                     TransData = 1;
                     AnnualizeData = 0;
                     AnnualStr = 'transformed';
                     QueryHead = 'Predictive Distributions - Transformed Data';
                  end;
                  %
                  % determine how many prediction paths to use
                  %
                  NumPredPathsStr = get(controls.forecast.predpaths,'String');
                  NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
                  %
                  % check if we have already stored results to disk
                  %
                  if PredictionsExist(DSGEModel.OutputDirectory,'DSGE','','',DSGEModel.NameOfModel,MaxPH,NumPostDrawsUsage,NumPredPaths,AnnualizeData,TransData,CurrChain)==1;
                     txt = 'YADA has located results for the predictive distribution on disk. Would you like to use these results?';
                     answer = Query(txt,'information',150,QueryHead,450,'no',CurrINI);
                  else;
                     answer = 'No';
                  end;
                  if strcmp(lower(answer),'yes')==1;
                     [PredEventData,PredictionEvent,StateCov,ShockCov,MeasureCov,ParameterCov] = LoadDSGEPredictionUncertainty(DSGEModel.OutputDirectory,'','',DSGEModel.NameOfModel,MaxPH,NumPostDrawsUsage,NumPredPaths,AnnualizeData,TransData,CurrChain);
                     DoneCalc = 1;
                  else;
                     %
                     % ask if we should conduct prediction event calculations
                     %
                     if (isfield(DSGEModel,'PredictionEvent')==0)|(isempty(DSGEModel.PredictionEvent)==1)|(size(DSGEModel.PredictionEvent,1)~=DSGEModel.n)|(size(DSGEModel.PredictionEvent,2)~=3);
                        DSGEModel.PredictionEvent = [Inf*ones(DSGEModel.n,1) zeros(DSGEModel.n,1) ones(DSGEModel.n,1)];
                     end;
                     txt = 'Would you like YADA to calculate prediction event probabilities?';
                     answer = Query(txt,'question',140,'Prediction Events',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        %
                        % make sure that the prediction event length does not exceed the maximum prediction horizon
                        %
                        for i=1:DSGEModel.n;
                           if DSGEModel.PredictionEvent(i,3)>MaxPH;
                              DSGEModel.PredictionEvent(i,3) = MaxPH;
                           end;
                        end;
                        %
                        % display a dialog for setting up an prediction event
                        %
                        [action,PredictionEvent] = PredictionEventDLG('init',DSGEModel.VariableNames,DSGEModel.PredictionEvent,MaxPH,CurrINI);
                        if strcmp(lower(action),'ok')==1;
                           DSGEModel.PredictionEvent = PredictionEvent;
                           DSGEModel.RunPredictionEvent = 1;
                        else;
                           DSGEModel.RunPredictionEvent = 0;
                        end;
                     else;
                        DSGEModel.RunPredictionEvent = 0;
                     end;
                     %
                     % we can now compute the predictive distribution for the endogenous variables
                     % up to period MaxPH
                     %
                     [DoneCalc,PredEventData,StateCov,ShockCov,MeasureCov,ParameterCov] = DSGEPredictionPaths(thetaPostSample,thetaMode,thetaPositions,ModelParameters,DSGEModel,CurrINI,X,MaxPH,NumPredPaths,AnnualizeData,TransData,CurrChain);
                  end;
                  %
                  % clear everything
                  %
                  clear('thetaPostSample');
                  %
                  % check if we should show any results
                  %
                  if DoneCalc==1;
                     %
                     % yes, now we need to calculate some distribution properties
                     %
                     [MeanPrediction,Quantiles,KernelX,KernelY] = DSGEPredictionDistribution(DSGEModel.n,DSGEModel.OutputDirectory,'','',DSGEModel.NameOfModel,MaxPH,NumPostDrawsUsage,NumPredPaths,AnnualizeData,TransData,CurrChain,DSGEModel.Percentiles,DSGEModel.VariableNames,CurrINI);
                     %
                     % compute the forecast errors based on the mean predictions
                     %
                     PredictionErrors = CalculatePredictionErrors(MeanPrediction,AnnualizeData,TransData,'DSGE',DSGEModel);
                     %
                     % check if the user wants to save the data
                     %
                     txt = ['Would you like to save the predictive distributions for the ' AnnualStr ' data to file?'];
                     answer = Query(txt,'question',140,'Save - Predictive Distributions',500,'no',CurrINI);
                     if strcmp(lower(answer),'yes')==1;
                        [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod,PredDateVector] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,size(MeanPrediction,2));
                        file = [DSGEModel.OutputDirectory '\PredictiveDist-' AnnualStr '-' num2str(CurrChain,'%0.0f') '-' num2str(MaxPH,'%0.0f') '-' num2str(NumPostDrawsUsage,'%0.0f') '.' num2str(NumPredPaths,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '.mat'];
                        YNames = DSGEModel.VariableNames;
                        DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,PredEndYear,PredEndPeriod,DSGEModel.DataFrequency);
                        Y = DSGEModel.Y(:,FirstPeriod:min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                        if (length(DateVector)>size(Y,2))&(TransData==0);
                           DateVector = DateVector(1,1:size(Y,2));
                        end;
                        EstimationStartPeriod = DSGEModel.KalmanFirstObservation;
                        EstimationStartPeriodOrig = EstimationStartPeriod;
                        YOrig = Y;
                        DateVectorOrig = DateVector;
                        if AnnualizeData==1;
                           Y = Annualize(Y,DSGEModel.annual,DSGEModel.annualscale);
                           EstimationStartPeriod = max(1,EstimationStartPeriod-(length(DateVector)-size(Y,2)));
                           DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                        end;
                        if TransData==1;
                           [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
                           Y = YData';
                           if size(Y,2)==DSGEModel.T;
                              Y = Y(:,FirstPeriod:min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                           else;
                              T2 = size(Y,2);
                              if (FirstPeriod-(DSGEModel.T-T2))>=1;
                                 Y = Y(:,FirstPeriod-(DSGEModel.T-T2):min((LastPeriod+MaxPH),size(DSGEModel.Y,2)));
                              else;
                                 Y = Y(:,1:min((LastPeriod+MaxPH),size(DSGEModel.Y,2))-(DSGEModel.T-T2));
                                 DateVector = DateVector(length(DateVector)-size(Y,2)+1:length(DateVector));
                              end;
                           end;
                        end;
                        if isempty(PredEventData)==1;
                           save(file,'MeanPrediction','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','StateCov','ShockCov','MeasureCov','ParameterCov','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig');
                        else;
                           save(file,'MeanPrediction','PredictionErrors','Quantiles','KernelX','KernelY','PredDateVector','Y','DateVector','YNames','StateCov','ShockCov','MeasureCov','ParameterCov','EstimationStartPeriod','EstimationStartPeriodOrig','YOrig','DateVectorOrig','PredictionEvent','PredEventData');
                        end;
                        %
                        % create a matlab m-file to read the output.
                        %
                        mfile = [DSGEModel.OutputDirectory '\PD' num2str(CurrChain,'%0.0f') AnnualStr num2str(MaxPH,'%0.0f') num2str(NumPostDrawsUsage,'%0.0f') num2str(NumPredPaths,'%0.0f') DSGEModel.SubEndYear DSGEModel.SubEndPeriod '.m'];
                        fid = fopen(mfile,'wt');
                        fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                        fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                        fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                        fprintf(fid,'YNames = DataStructure.YNames;\n');
                        fprintf(fid,'%%\n%% matrix with the mean predictions of the observed variables\n%%\n');
                        fprintf(fid,'MeanPrediction = DataStructure.MeanPrediction;\n');
                        fprintf(fid,'%%\n%% matrix with the errors from the mean predictions of the observed variables\n%%\n');
                        fprintf(fid,'PredictionErrors = DataStructure.PredictionErrors;\n');
                        fprintf(fid,'%%\n%% vector structure with quantiles from the predictive distribution\n%% the structure has %0.0f entries with fields "Quantile" and "percent"\n%% the first field is a matrix and the second a positive number between 0 and 100\n%%\n',length(Quantiles));
                        fprintf(fid,'Quantiles = DataStructure.Quantiles;\n');
                        fprintf(fid,'%%\n%% matrix with x-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                        fprintf(fid,'KernelX = DataStructure.KernelX;\n');
                        fprintf(fid,'%%\n%% matrix with y-axis values for kernel density estimates of marginal predictive distribution\n%%\n');
                        fprintf(fid,'KernelY = DataStructure.KernelY;\n');
                        fprintf(fid,'%%\n%% vector with dates for the predictions\n%%\n');
                        fprintf(fid,'PredDateVector = DataStructure.PredDateVector;\n');
                        fprintf(fid,'%%\n%% observed variables\n%%\n');
                        fprintf(fid,'Y = DataStructure.Y;\n');
                        fprintf(fid,'%%\n%% vector with dates for the observed variables\n%%\n');
                        fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                        if (AnnualizeData==0)&(TransData==0);
                           fprintf(fid,'%%\n%% 3D Error covariance matrix (nxnxh) part due to state uncertainty\n%%\n');
                           fprintf(fid,'StateCov = DataStructure.StateCov;\n');
                           fprintf(fid,'%%\n%% 3D Error covariance matrix (nxnxh) part due to shock uncertainty\n%%\n');
                           fprintf(fid,'ShockCov = DataStructure.ShockCov;\n');
                           fprintf(fid,'%%\n%% 2D Error covariance matrix (nxn) part due to measurement error uncertainty\n%%\n');
                           fprintf(fid,'MeasureCov = DataStructure.MeasureCov;\n');
                           fprintf(fid,'%%\n%% 3D Error covariance matrix (nxnxh) part due to parameter uncertainty\n%%\n');
                           fprintf(fid,'ParameterCov = DataStructure.ParameterCov;\n');
                           CovDecompStr = 'StateCov (3D error covariance matrix with part due to state uncertainty), ShockCov (3D error covariance matrix with part due to shock uncertainty), MeasureCov (2D error covariance matrix with part due to measurement error uncertainty), ParameterCov (3D covariance matrix with part due to parameter uncertainty), ';
                        else;
                           CovDecompStr = '';
                        end;
                        if isempty(PredEventData)==0;
                           fprintf(fid,'%%\n%% matrix with the prediction event definitions. The first column\n%% holds the upper bound, the second column\n%% the lower bound, and third the length of the event.\n%%\n');
                           fprintf(fid,'PredictionEvent = DataStructure.PredictionEvent;\n');
                           fprintf(fid,'%%\n%% matrix with prediction event data. First column holds the\n%% number of true events, the second the number of times below the events, and the third the number of events\n%%\n');
                           fprintf(fid,'PredEventData = DataStructure.PredEventData;\n');
                           if (AnnualizeData==0)&(TransData==0);
                              NumEntries = '15';
                           else;
                              NumEntries = '11';
                           end;
                           ExtraEntry = 'PredictionEvent (matrix with the upper and lower bound of the event and the length of the event), PredEventData (matrix with the number of true events, the number of events below the lower bound for the event, and the number of events tested in the columns), ';
                        else;
                           if (AnnualizeData==0)&(TransData==0);
                              NumEntries = '13';
                           else;
                              NumEntries = '9';
                           end;
                           ExtraEntry = '';
                        end;
                        fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                        %
                        % end the script file
                        %
                        fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                        fclose(fid);
                        %
                        txt = ['The predictive distributions have been saved to the file "' GetFilename(file) '" in the directory "' GetPath(file) '". The file contains ' NumEntries ' entries: YNames (string matrix with the names of the observed variables), MeanPrediction (matrix with the mean predictions), PredictionErrors (matrix with errors for the mean prediction), Quantiles (vector structure with 2 fields: Quantile and percent), KernelX (matrix with x-axis for kernel density estimates of marginal predictive distribution), KernelY (matrix with y-axis values for kernel density estimates of marginal predictive distribution), PredDateVector (vector with dates for the predictions), Y (matrix with the observed variables), ' CovDecompStr ExtraEntry 'and DateVector (vector with dates for the observed variables). To access these data you may run the matlab script file "' GetFilename(mfile) '".'];
                        About(txt,'information','Predictive Distributions',500,550,CurrINI);
                     end;
                     if isempty(PredEventData)==0;
                        %
                        % write prediction event results to file
                        %
                        file = [DSGEModel.OutputDirectory '\PredictiveDist-' AnnualStr '-' num2str(CurrChain,'%0.0f') '-' num2str(MaxPH,'%0.0f') '-' num2str(NumPostDrawsUsage,'%0.0f') '.' num2str(NumPredPaths,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '.txt'];
                        [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,MaxPH);
                        PrintPredictionEvent(file,DSGEModel.VariableNames,PredEventData,[],PredictionEvent,[PredStartYear ':' PredStartPeriod '-' PredEndYear ':' PredEndPeriod],MaxPH,NumPredPaths,NumPostDrawsUsage,CurrINI);
                        %
                        % displays the file if it exists
                        %
                        if FileExist(file)==1;
                           TextGUI(file,['Prediction Events - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Distribution - Unconditional Predictions',50,CurrINI,1,0);
                        end;
                     end;
                     %
                     % summarize the information in the uncertainty variables more conveniently
                     %
                     if isempty(StateCov)==0;
                        [StateVar,ShockVar,MeasureVar,ParameterVar] = SummarizeDSGEPredictions(StateCov,ShockCov,MeasureCov,ParameterCov);
                        %
                        % Open a dialog for displaying predictive distributions
                        %
                        UData.StateVar = StateVar;
                        UData.ShockVar = ShockVar;
                        UData.MeasureVar = MeasureVar;
                        UData.ParameterVar = ParameterVar;
                     else;
                        UData = [];
                     end;
                     PredictiveDistributionDLG('init',DSGEModel,CurrINI,MeanPrediction,Quantiles,KernelX,KernelY,'','DSGE',AnnualStr,UData);
                  end;
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information',HeaderStr,120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'uncon_pred_event'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % first attempt to load some posterior mode data
         %
         ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
         ErrorStr = '';
         HeaderStr = 'YADA - Bad MAT File';
         try;
            ModeData = load(ModeFile);
         catch;
            ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
         end;
         %
         % check if we should check transformations functions
         %
         if (isempty(ErrorStr)==1)&(gcbo==controls.predict.unconditional_transformed_predevent);
            DTStatus = VerifyDataTransformation(DSGEModel.VariableNames,DSGEModel.YTransformation,0);
            if DTStatus==1;
               [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
            else;
               ErrorStr = 'You haven''t specified all the necessary fields for computing transformations of the observed variables.';
               HeaderStr = 'Missing Transformation Information';
            end;
         end;
         %
         if strcmp(ErrorStr,'')==1;
            thetaPositions = ModeData.thetaPositions;
            ModelParameters = ModeData.ModelParameters;
            thetaMode = ModeData.theta;
%            if isfield(ModeData,'KalmanFirstObservation')==1;
%               DSGEModel.KalmanFirstObservation = ModeData.KalmanFirstObservation;
%               FirstPeriod = ModeData.DSGEModel.FirstPeriod;
%               LastPeriod = ModeData.DSGEModel.LastPeriod;
%            else;
               [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
%               DSGEModel.KalmanFirstObservation = round(((DSGEModel.InitializeKalman-1)/100)*(LastPeriod-FirstPeriod+1))+1;
%            end;
            %
            % check how many time periods to use for predictive distributions
            %
            [MaxPH,NumPredX] = CalcMaxPredictionHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,size(DSGEModel.PredictedX,2));
            %
            % matrix with exogenous variables
            %
            X = [];
            if DSGEModel.k>0;
               if NumPredX<MaxPH;
                  X = DSGEModel.X(:,LastPeriod+1:LastPeriod+(MaxPH-NumPredX));
               end;
               if NumPredX>0;
                  X = [X DSGEModel.PredictedX(:,1:NumPredX)];
               end;
            end;
            %
            % if there are multiple chains, ask which one to load
            %
            ChainsStr = get(controls.posterior.chains,'String');
            NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
            %
            if NumChains>1;
               %
               % ask which chain to load
               %
               ChainsStr = '';
               for i=1:NumChains;
                  ChainsStr = strvcat(ChainsStr,['Posterior chain number ' num2str(i,'%0.0f')]);
               end;
               [action,CurrChain] = SelectionDlg(ChainsStr,1,'Select the posterior draws chain to load','MCMC Chain Selection','Prediction Event','','',CurrINI);
            else;
               CurrChain = 1;
               action = 'ok';
            end;
            %
            %
            if strcmp(lower(action),'cancel')==0;
               %
               % check if the data actually exists
               %
               if VerifyDSGEPosteriorDraws(DSGEModel,CurrChain,controls)==1;
                  %
                  % load the data
                  %
                  [PostSample,thetaPostSample,LogPost,AcceptedDraws,NumBurnin] = LoadDSGEPosteriorDraws(DSGEModel,CurrINI,CurrChain);
                  NumDraws = length(LogPost);
                  clear('PostSample','LogPost','AcceptedDraws');
                  drawnow;
                  %
                  % 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;
                  %
                  % select which posterior draws to use
                  %
                  thetaPostSample = thetaPostSample(NumBurnin+1:NumDraws,:);
                  NumDraws = NumDraws-NumBurnin;
                  %
                  % check how many draws we should pick among these
                  %
                  PostDrawsUsageStr = get(controls.posterior.postdrawsusage,'String');
                  NumPostDrawsUsage = min(str2num(strrep(StringTrim(PostDrawsUsageStr(DSGEModel.PostDrawsUsageValue,:)),',','')),NumDraws);
                  %
                  % get the draws to use
                  %
                  if DSGEModel.RandomizeDraws==0;
                     DrawFreq = round(NumDraws/NumPostDrawsUsage);
                     SelectDraws = (1:DrawFreq:NumDraws);
                     if length(SelectDraws)+1==NumPostDrawsUsage;
                        SelectDraws = [SelectDraws NumDraws];
                     elseif length(SelectDraws)>NumPostDrawsUsage;
                        SelectDraws = SelectDraws(1:NumPostDrawsUsage);
                     end;
                     thetaPostSample = thetaPostSample(SelectDraws,:);
                  else;
                     thetaPostSample = thetaPostSample(ceil(rand(NumPostDrawsUsage,1)*NumDraws),:);
                  end;
                  %
                  % are we using annualized data or the original
                  %
                  if gcbo==controls.predict.unconditional_original_predevent;
                     TransData = 0;
                     AnnualizeData = 0;
                     AnnualStr = 'original';
                     QueryHead = 'Predictive Distributions - Original Data';
                  elseif gcbo==controls.predict.unconditional_annual_predevent;
                     TransData = 0;
                     AnnualizeData = 1;
                     AnnualStr = 'annual';
                     QueryHead = 'Predictive Distributions - Annualized Data';
                  else;
                     TransData = 1;
                     AnnualizeData = 0;
                     AnnualStr = 'transformed';
                     QueryHead = 'Predictive Distributions - Transformed Data';
                  end;
                  %
                  % prediction event calculations
                  %
                  if (isfield(DSGEModel,'PredictionEvent')==0)|(isempty(DSGEModel.PredictionEvent)==1)|(size(DSGEModel.PredictionEvent,1)~=DSGEModel.n)|(size(DSGEModel.PredictionEvent,2)~=3);
                     DSGEModel.PredictionEvent = [Inf*ones(DSGEModel.n,1) zeros(DSGEModel.n,1) ones(DSGEModel.n,1)];
                  end;
                  %
                  % make sure that the prediction event length does not exceed the maximum prediction horizon
                  %
                  for i=1:DSGEModel.n;
                     if DSGEModel.PredictionEvent(i,3)>MaxPH;
                        DSGEModel.PredictionEvent(i,3) = MaxPH;
                     end;
                  end;
                  %
                  % display a dialog for setting up an prediction event
                  %
                  [action,PredictionEvent] = PredictionEventDLG('init',DSGEModel.VariableNames,DSGEModel.PredictionEvent,MaxPH,CurrINI);
                  %
                  % check if user cancelled or not
                  %
                  if strcmp(lower(action),'ok')==1;
                     DSGEModel.PredictionEvent = PredictionEvent;
                     DSGEModel.RunPredictionEvent = 1;
                     %
                     % determine how many prediction paths to use
                     %
                     NumPredPathsStr = get(controls.forecast.predpaths,'String');
                     NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
                     %
                     % check if we have already stored results to disk
                     %
                     if PredictionsExist(DSGEModel.OutputDirectory,'DSGE','','',DSGEModel.NameOfModel,MaxPH,NumPostDrawsUsage,NumPredPaths,AnnualizeData,TransData,CurrChain)==1;
                        txt = 'YADA has located results for the predictive distribution on disk. Would you like to use these results?';
                        answer = Query(txt,'information',150,QueryHead,450,'no',CurrINI);
                     else;
                        answer = 'No';
                     end;
                     if strcmp(lower(answer),'yes')==1;
                        %
                        % compute the prediction event results
                        %
                        PredEventData = LoadDSGEPredictionPaths(DSGEModel.PredictionEvent,DSGEModel.OutputDirectory,'','',DSGEModel.NameOfModel,MaxPH,NumPostDrawsUsage,NumPredPaths,AnnualizeData,TransData,CurrChain,CurrINI);
                        DoneCalc = 1;
                     else;
                        %
                        % we can now compute the predictive distribution for the endogenous variables
                        % up to period MaxPH
                        %
                        [DoneCalc,PredEventData,StateCov,ShockCov,MeasureCov,ParameterCov] = DSGEPredictionPaths(thetaPostSample,thetaMode,thetaPositions,ModelParameters,DSGEModel,CurrINI,X,MaxPH,NumPredPaths,AnnualizeData,TransData,CurrChain);
                     end;
                     %
                     % clear everything
                     %
                     clear('thetaPostSample');
                     %
                     % check if we should show any results
                     %
                     if DoneCalc==1;
                        %
                        % check if summary results from the predictive distribution have been saved to mat-file
                        %
                        [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod,PredDateVector] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,MaxPH);
                        file = [DSGEModel.OutputDirectory '\PredictiveDist-' AnnualStr '-' num2str(CurrChain,'%0.0f') '-' num2str(MaxPH,'%0.0f') '-' num2str(NumPostDrawsUsage,'%0.0f') '.' num2str(NumPredPaths,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '.mat'];
                        if FileExist(file)==1;
                           save(file,'PredictionEvent','PredEventData','-APPEND');
                           %
                           % create a matlab m-file to read the output.
                           %
                           mfile = [DSGEModel.OutputDirectory '\PD' num2str(CurrChain,'%0.0f') AnnualStr num2str(MaxPH,'%0.0f') num2str(NumPostDrawsUsage,'%0.0f') num2str(NumPredPaths,'%0.0f') DSGEModel.SubEndYear DSGEModel.SubEndPeriod '.m'];
                           fid = fopen(mfile,'wt');
                           fprintf(fid,['%%\n%% load the data in ' GetFilename(file) '\n%%\n']);
                           fprintf(fid,'DataStructure = load(''%s'');\n',GetFilename(file));
                           fprintf(fid,'%%\n%% string matrix with the names of the observed variables\n%%\n');
                           fprintf(fid,'YNames = DataStructure.YNames;\n');
                           fprintf(fid,'%%\n%% matrix with the mean predictions of the observed variables\n%%\n');
                           fprintf(fid,'MeanPrediction = DataStructure.MeanPrediction;\n');
                           fprintf(fid,'%%\n%% matrix with the errors from the mean predictions of the observed variables\n%%\n');
                           fprintf(fid,'PredictionErrors = DataStructure.PredictionErrors;\n');
                           fprintf(fid,'%%\n%% vector structure with quantiles from the predictive distribution\n%% the structure has %0.0f entries with fields "Quantile" and "percent"\n%% the first field is a matrix and the second a positive number between 0 and 100\n%%\n',length(DSGEModel.Percentiles));
                           fprintf(fid,'Quantiles = DataStructure.Quantiles;\n');
                           fprintf(fid,'%%\n%% vector with dates for the predictions\n%%\n');
                           fprintf(fid,'PredDateVector = DataStructure.PredDateVector;\n');
                           fprintf(fid,'%%\n%% observed variables\n%%\n');
                           fprintf(fid,'Y = DataStructure.Y;\n');
                           fprintf(fid,'%%\n%% vector with dates for the observed variables\n%%\n');
                           fprintf(fid,'DateVector = DataStructure.DateVector;\n');
                           if AnnualizeData==0;
                              fprintf(fid,'%%\n%% 3D Error covariance matrix (nxnxh) part due to state uncertainty\n%%\n');
                              fprintf(fid,'StateCov = DataStructure.StateCov;\n');
                              fprintf(fid,'%%\n%% 3D Error covariance matrix (nxnxh) part due to shock uncertainty\n%%\n');
                              fprintf(fid,'ShockCov = DataStructure.ShockCov;\n');
                              fprintf(fid,'%%\n%% 2D Error covariance matrix (nxn) part due to measurement error uncertainty\n%%\n');
                              fprintf(fid,'MeasureCov = DataStructure.MeasureCov;\n');
                              fprintf(fid,'%%\n%% 3D Error covariance matrix (nxnxh) part due to parameter uncertainty\n%%\n');
                              fprintf(fid,'ParameterCov = DataStructure.ParameterCov;\n');
                           end;
                           fprintf(fid,'%%\n%% matrix with the prediction event definitions. The first column\n%% holds the upper bound, the second column\n%% the lower bound, and third the length of the event.\n%%\n');
                           fprintf(fid,'PredictionEvent = DataStructure.PredictionEvent;\n');
                           fprintf(fid,'%%\n%% matrix with prediction event data. First column holds the\n%% number of true events, the second the number of times below the events, and the third the number of events\n%%\n');
                           fprintf(fid,'PredEventData = DataStructure.PredEventData;\n');
                           fprintf(fid,'%%\n%% Add your own commands below\n%%\n\n\n');
                           %
                           % end the script file
                           %
                           fprintf(fid,'%%\n%% Created by YADA on %s\n%%\n',datestr(now,0));
                           fclose(fid);
                        end;
                        %
                        % write prediction event results to file
                        %
                        file = [DSGEModel.OutputDirectory '\PredictiveDist-' AnnualStr '-' num2str(CurrChain,'%0.0f') '-' num2str(MaxPH,'%0.0f') '-' num2str(NumPostDrawsUsage,'%0.0f') '.' num2str(NumPredPaths,'%0.0f') '-' DSGEModel.SubEndYear '.' DSGEModel.SubEndPeriod '.txt'];
                        [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,MaxPH);
                        PrintPredictionEvent(file,DSGEModel.VariableNames,PredEventData,[],PredictionEvent,[PredStartYear ':' PredStartPeriod '-' PredEndYear ':' PredEndPeriod],MaxPH,NumPredPaths,NumPostDrawsUsage,CurrINI);
                        %
                        % displays the file if it exists
                        %
                        if FileExist(file)==1;
                           TextGUI(file,['Prediction Events - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Posterior Distribution - Unconditional Predictions',50,CurrINI,1,0);
                        end;
                     end;
                  else;
                     %
                     % make sure that the draws are cleared from memory
                     %
                     clear('thetaPostSample');
                  end;
               else;
                  txt = ['Some of the files for loading the posterior data for chain number ' num2str(CurrChain,'%0.0f') ' are not available.'];
                  About(txt,'error','Missing Posterior Draws',150,500,CurrINI);
               end;
            end;
         else;
            About(ErrorStr,'information',HeaderStr,120,500,CurrINI);
         end;
         %
         set(controls.about,'UserData',0);
      end;
   case 'postsamplesummary'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         PostSampleTextFile = get(gcbo,'UserData');
         TextGUI(PostSampleTextFile,['Posterior Sampling - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Results',50,CurrINI,1,1);
         set(controls.about,'UserData',0);
      end;
   case 'modesummaryinfo'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         ModeTextFile = get(controls.modesummary,'UserData');
         TextGUI(ModeTextFile,['Posterior Mode Estimation - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Results',50,CurrINI,1,1);
         set(controls.about,'UserData',0);
      end;
   case 'opterrorsummaryinfo'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         ErrorTextFile = get(controls.opterrorsummary,'UserData');
         TextGUI(ErrorTextFile,['Optimization Error Summary - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Results',50,CurrINI,1,1);
         set(controls.about,'UserData',0);
      end;
   case 'bvarpostmode_results'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         ModeTextFile = [DSGEModel.OutputDirectory '\PosteriorModeBVAR-' DSGEModel.NameOfModel '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '.txt'];
         TextGUI(ModeTextFile,['Bayesian VAR Posterior Mode Estimation - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Results',50,CurrINI,1,1);
         set(controls.about,'UserData',0);
      end;
   case 'bvargibbs_results'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         DrawsStr = get(controls.posterior.draws,'String');
         NumPostDraws = str2num(StringTrim(strrep(DrawsStr(DSGEModel.PosteriorDrawsValue,:),',','')));
         GibbsTextFile = [DSGEModel.OutputDirectory '\BVAR-GibbsSummary-' DSGEModel.NameOfModel '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '-' num2str(NumPostDraws,'%0.0f') '.txt'];
         TextGUI(GibbsTextFile,['Bayesian VAR Posterior Sampling - ' DSGEModel.NameOfModel],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Results',50,CurrINI,1,1);
         set(controls.about,'UserData',0);
      end;
   case 'viewmodestystat'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         file = get(gcbo,'UserData');
         ChainStr = strrep(strrep(get(gcbo,'Label'),'&',''),'...','');
         %
         % display the text file
         %
         TextGUI(file,['Modesty Statistics - ' ChainStr],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Results',40,CurrINI,1,1);
         set(controls.about,'UserData',0);
      end;
   case 'priorinfo'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % collect the information
         %
         [InitStatus,theta,thetaIndex,thetaDist,LowerBound,ModelParameters,thetaPositions,PriorDist,ParameterNames,UniformBounds] = VerifyPriorData(DSGEModel,CurrINI);
         if InitStatus==1;
            %
            % print to file
            %
            TextFile = PrintPriorInformation(ParameterNames,theta,thetaDist,PriorDist,DSGEModel,CurrINI);
            %
            % check if file exists and display the file in dialog.
            %
            if FileExist(TextFile)==1;
               TextGUI(TextFile,['Prior Distribution - ' GetFilename(DSGEModel.PriorFile)],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'Information',40,CurrINI,1,1);
            end;
         end;
         set(controls.about,'UserData',0);
      end;
   case 'datainfo'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % setup the txt string matrix with all information taken from the data constructions file
         %
         txt = strvcat(' ','DATA CONSTRUCTION INFORMATION','=============================',' ');
         txt = strvcat(txt,['FILE:                          ' GetFilename(DSGEModel.DataConstructionFile)],' ');
         txt = strvcat(txt,['FULL SAMPLE:                   ' DSGEModel.BeginYear ':' DSGEModel.BeginPeriod ' - ' DSGEModel.EndYear ':' DSGEModel.EndPeriod]);
         txt = strvcat(txt,['DATA FREQUENCY:                ' DSGEModel.DataFrequency]);
         txt = strvcat(txt,['NUMBER OF OBSERVATIONS:        ' num2str(DSGEModel.T)]);
         txt = strvcat(txt,['NUMBER OF OBSERVED VARIABLES:  ' num2str(DSGEModel.n)]);
         txt = strvcat(txt,['NUMBER OF EXOGENOUS VARIABLES: ' num2str(DSGEModel.k)],' ');
         txt = strvcat(txt,['OBSERVED VARIABLES:            ' vecstr(DSGEModel.VariableNames,' ')]);
         if isempty(DSGEModel.YTransformation)==0;
            txt = strvcat(txt,' ','TRANSFORMATIONS OF OBSERVED VARIABLES','-------------------------------------',' ');
            AddTxt = '';
            for i=1:size(DSGEModel.VariableNames,1);
               CurrField = getfield(DSGEModel.YTransformation,StringTrim(DSGEModel.VariableNames(i,:)));
               if (isfield(CurrField,'fcn')==1)&(isfield(CurrField,'partial')==1)&(isfield(CurrField,'annualizefcn')==1)&(isfield(CurrField,'annualizepartial')==1)&(isfield(CurrField,'initial')==1)&(isfield(CurrField,'x')==1);
                  AddTxt = strvcat(AddTxt,[' - ' DSGEModel.VariableNames(i,:) ' general function:   ' CurrField.fcn],['   ' SpaceStr(size(DSGEModel.VariableNames,2)) ' - partial function: ' CurrField.partial],['   ' SpaceStr(size(DSGEModel.VariableNames,2)) ' annualize function: ' CurrField.annualizefcn],['   ' SpaceStr(size(DSGEModel.VariableNames,2)) ' - partial function: ' CurrField.annualizepartial]);
               end;
               if (isfield(CurrField,'invertfcn')==1)&(isfield(CurrField,'invertinitial')==1)&(isfield(CurrField,'invertx')==1);
                  AddTxt = strvcat(AddTxt,['   ' SpaceStr(size(DSGEModel.VariableNames,2)) ' inversion function: ' CurrField.invertfcn]);
               end;
               if (isfield(CurrField,'exportfcn')==1)&(isfield(CurrField,'exportinitial')==1)&(isfield(CurrField,'exportx')==1);
                  AddTxt = strvcat(AddTxt,['   ' SpaceStr(size(DSGEModel.VariableNames,2)) ' export function:    ' CurrField.exportfcn]);
               end;
            end;
            if isempty(AddTxt)==0;
               txt = strvcat(txt,AddTxt,' ');
            else;
               txt = strvcat(txt,'                               No information is available.',' ');
            end;
         end;
         txt = strvcat(txt,['LEVELS VARIABLES:              ' num2str(DSGEModel.levels)],'                               0 means first difference','                               1 means levels',' ');
         txt = strvcat(txt,['ANNUALIZATION:                 ' num2str(DSGEModel.annual)],'                               1 means that variable is in annual changes or levels','                               4 means that variable is in quarterly changes','                               12 means that variable is in monthly changes',['SCALE FACTORS:                 ' num2str(DSGEModel.annualscale)],' ');
         if DSGEModel.k>0;
            xvars = vecstr(DSGEModel.XVariableNames,' ');
         else;
            xvars = 'None';
         end;
         txt = strvcat(txt,['EXOGENOUS VARIABLES:           ' xvars]);
         %
         % check if there are conditional variables
         %
         if isempty(DSGEModel.ZVariableNames)==0;
            zvars = vecstr(DSGEModel.ZVariableNames,' ');
         else;
            zvars = 'None';
         end;
         txt = strvcat(txt,' ',['CONDITIONAL VARIABLES:         ' zvars]);
         if isempty(DSGEModel.ZTransformation)==0;
            txt = strvcat(txt,' ','TRANSFORMATIONS OF CONDITIONAL VARIABLES','----------------------------------------',' ');
            AddTxt = '';
            for i=1:size(DSGEModel.ZVariableNames,1);
               CurrField = getfield(DSGEModel.ZTransformation,StringTrim(DSGEModel.ZVariableNames(i,:)));
               if (isfield(CurrField,'fcn')==1)&(isfield(CurrField,'partial')==1)&(isfield(CurrField,'annualizefcn')==1)&(isfield(CurrField,'annualizepartial')==1)&(isfield(CurrField,'initial')==1)&(isfield(CurrField,'x')==1);
                  AddTxt = strvcat(AddTxt,[' - ' DSGEModel.ZVariableNames(i,:) ' general function:   ' CurrField.fcn],['   ' SpaceStr(size(DSGEModel.ZVariableNames,2)) ' - partial function: ' CurrField.partial],['   ' SpaceStr(size(DSGEModel.ZVariableNames,2)) ' annualize function: ' CurrField.annualizefcn],['   ' SpaceStr(size(DSGEModel.ZVariableNames,2)) ' - partial function: ' CurrField.annualizepartial]);
               end;
               if (isfield(CurrField,'invertfcn')==1)&(isfield(CurrField,'invertinitial')==1)&(isfield(CurrField,'invertx')==1);
                  AddTxt = strvcat(AddTxt,['   ' SpaceStr(size(DSGEModel.ZVariableNames,2)) ' inversion function: ' CurrField.invertfcn]);
               end;
               if (isfield(CurrField,'exportfcn')==1)&(isfield(CurrField,'exportinitial')==1)&(isfield(CurrField,'exportx')==1);
                  AddTxt = strvcat(AddTxt,['   ' SpaceStr(size(DSGEModel.ZVariableNames,2)) ' export function:    ' CurrField.exportfcn]);
               end;
            end;
            if isempty(AddTxt)==0;
               txt = strvcat(txt,AddTxt,' ');
            else;
               txt = strvcat(txt,'                               No information is available.',' ');
            end;
         end;
         %
         % check if there are observed variable scenario variables
         %
         if isempty(DSGEModel.CVariableNames)==0;
            cvars = vecstr(DSGEModel.CVariableNames,' ');
         else;
            cvars = 'None';
         end;
         txt = strvcat(txt,' ',['SCENARIO VARIABLES:            ' cvars]);
         if isempty(DSGEModel.CTransformation)==0;
            txt = strvcat(txt,' ','TRANSFORMATIONS OF OBSERVED SCENARIO VARIABLES','----------------------------------------------',' ');
            AddTxt = '';
            for i=1:size(DSGEModel.CVariableNames,1);
               CurrField = getfield(DSGEModel.CTransformation,StringTrim(DSGEModel.CVariableNames(i,:)));
               if (isfield(CurrField,'fcn')==1)&(isfield(CurrField,'partial')==1)&(isfield(CurrField,'annualizefcn')==1)&(isfield(CurrField,'annualizepartial')==1)&(isfield(CurrField,'initial')==1)&(isfield(CurrField,'x')==1);
                  AddTxt = strvcat(AddTxt,[' - ' DSGEModel.CVariableNames(i,:) ' general function:   ' CurrField.fcn],['   ' SpaceStr(size(DSGEModel.CVariableNames,2)) ' - partial function: ' CurrField.partial],['   ' SpaceStr(size(DSGEModel.CVariableNames,2)) ' annualize function: ' CurrField.annualizefcn],['   ' SpaceStr(size(DSGEModel.CVariableNames,2)) ' - partial function: ' CurrField.annualizepartial]);
               end;
               if (isfield(CurrField,'invertfcn')==1)&(isfield(CurrField,'invertinitial')==1)&(isfield(CurrField,'invertx')==1);
                  AddTxt = strvcat(AddTxt,['   ' SpaceStr(size(DSGEModel.CVariableNames,2)) ' inversion function: ' CurrField.invertfcn]);
               end;
               if (isfield(CurrField,'exportfcn')==1)&(isfield(CurrField,'exportinitial')==1)&(isfield(CurrField,'exportx')==1);
                  AddTxt = strvcat(AddTxt,['   ' SpaceStr(size(DSGEModel.CVariableNames,2)) ' export function:    ' CurrField.exportfcn]);
               end;
            end;
            if isempty(AddTxt)==0;
               txt = strvcat(txt,AddTxt,' ');
            else;
               txt = strvcat(txt,'                               No information is available.',' ');
            end;
         end;
         %
         pStr = num2str(DSGEModel.Percentiles(1),'%0.2f');
         for i=2:length(DSGEModel.Percentiles);
            pStr = [pStr '  ' num2str(DSGEModel.Percentiles(i),'%0.2f')];
         end;
         txt = strvcat(txt,' ',['PERCENTILES:                   ' pStr]);
         %
         % Collect information about a Bayesian VAR
         %
         if isempty(DSGEModel.BVARY)==0;
            txt = strvcat(txt,' ','BAYESIAN VAR VARIABLES','----------------------',' ',['ENDOGENOUS:                    ' vecstr(DSGEModel.VariableNames(DSGEModel.BVARY,:),' ')]);
            if isempty(DSGEModel.BVARX)==0;
               txt = strvcat(txt,['EXOGENOUS:                     ' vecstr(DSGEModel.XVariableNames(DSGEModel.BVARX,:),' ')],' ');
            else;
               txt = strvcat(txt,'EXOGENOUS:                     None',' ');
            end;
         end;
         %
         % display the information in a text dialog
         %
         TextGUI(txt,['Data Construction Information - ' GetName(DSGEModel.DataConstructionFile)],[(CurrINI.scrsz(3)-750)/2 (CurrINI.scrsz(4)-500)/2 750 500],'Information',40,CurrINI,1,1);
         set(controls.about,'UserData',0);
      end;
   case 'aimmodelinfo'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         TextGUI(DSGEModel.AIMFile,['AiM Model File - ' GetFilename(DSGEModel.AIMFile)],[(CurrINI.scrsz(3)-1000)/2 32 1000 CurrINI.scrsz(4)-100],'DSGE Model Specification',50,CurrINI,1,1);
         set(controls.about,'UserData',0);
      end;
   case 'helpfile'
      drawnow;
      %
      prog = 'hh.exe help\yada.chm &';
      stat = dos(prog);
   case 'mathmanual'
      drawnow;
      %
      if FileExist([pwd '\bin\shellcmd.exe'])==1;
         cmd = ['"' pwd '\bin\shellcmd.exe" "' pwd '\doc\yada.pdf" &'];
      else;
         cmd = ['"' pwd '\doc\yada.pdf" &'];
      end;
      stat = dos(cmd);
   case 'license'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         TextGUI([pwd '\gpl.txt'],'GNU General Public License',[(CurrINI.scrsz(3)-700)/2 (CurrINI.scrsz(4)-400)/2 700 500],'License',40,CurrINI,1);
         set(controls.about,'UserData',0);
      end;
   case 'about'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         [VersionOfYADA,VersionDateStr] = YADAVersion;
         txt = strvcat(['YADA - Version ' num2str(VersionOfYADA,'%0.2f') ': ' VersionDateStr],'Anders Warne - New Area-Wide Model Project','DG-Research/Econometric Modelling Division, European Central Bank (ECB)',' ','APPROPRIATE LEGAL NOTICES','This program is free software: you can redistribute it and/or modify it in accordance with the terms of the GNU General Public License (http://www.gnu.org/licenses/) as published by the Free Software Foundation, either Version 3 of the license, or (at your option) any later version.',' ','DISCLAIMER OF WARRANTY','By accepting the disclaimer you assume the entire risk related to your use of this program. The European Central Bank (ECB) provides this program ''as is'' and the ECB disclaims any warranties, whether express or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The entire risk as to the quality and performance of the program is with you.',' ','LIMITATION OF LIABILITY','In no event shall the ECB be liable to you or to any third party for any direct, indirect, incidental, consequential, general, special or exemplary damages or lost profit resulting from any use of or inability to use the program (including but not limited to loss of data or data being rendered inaccurate or losses sustained by you or third parties or a failure of the program to operate with any other programs). Should the program prove defective, you assume the cost of all necessary servicing, repair and/or corrections.',' ','COPYRIGHT NOTICE',['This program is released under the GNU General Public License, Version 3, 29 June 2007 (http://www.gnu.org/licenses/) and it was last modified by the ECB on ' VersionDateStr '.'],' ',['Copyright © 2006-' datestr(now,10) ' European Central Bank.'],'Email: anders.warne@ecb.europa.eu');
         About(txt,'logo','About',500,600,CurrINI);
         drawnow;
         pause(0.02);
         set(controls.about,'UserData',0);
      end;
   case 'quit'
      if get(controls.about,'UserData')==0;
         set(controls.about,'UserData',1);
         drawnow;
         %
         % check if DSGEModel and OrigDSGEModel structures are equal. If not suggest that DSGE model should be saved
         %
         status = CompareDSGEModel(DSGEModel,OrigDSGEModel);
         %
         if status==1;
            txt = 'Are you sure you want to quit?';
         else;
            txt = 'Your DSGE model settings have changed. Are you sure you want to quit anyway?';
         end;
         answer = Query(txt,'exit',120,'Exit YADA',400,'yes',CurrINI);
         if strcmp(lower(answer),'yes')==1;
            set(controls.leave,'UserData','done');
         end;
         set(controls.about,'UserData',0);
      end;
   case 'done'
      drawnow;
      %
      % store relevant entries of the CurrINI structure to file
      %
      SaveINIFile(CurrINI);
      set(controls.leave,'UserData','done');
end;
%
% test if we have specified any unit-roots
%
if (isempty(DSGEModel.UnitRootStates)==1)&(DSGEModel.AllowUnitRoot==0);
   set(controls.obsvarcorrs.parent,'Enable','on');
   set(controls.statevarcorrs.parent,'Enable','on');
   if (exist('YADAdare')==2)|(exist('dare')==2);
      set(controls.fevd.parent,'Enable','on');
   else;
      set(controls.fevd.parent,'Enable','off');
   end;
else;
   set(controls.obsvarcorrs.parent,'Enable','off');
   set(controls.statevarcorrs.parent,'Enable','off');
   set(controls.fevd.parent,'Enable','off');
end;
%
% test if we should enable the posterior mode functions
%
if VerifyPosteriorModeEstimation(DSGEModel)==1;
   MaxFH = CalcMaxForecastHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod);
   %
   if FileExist(DSGEModel.PriorFile)==1;
      set(controls.postmode,'Enable','on');
      set(controls.postmodemenu,'Enable','on');
   else;
      set(controls.postmode,'Enable','off');
      set(controls.postmodemenu,'Enable','off');
   end;
   set(controls.shockgroupmenu,'Enable','on');
   set(controls.shockgroup,'Enable','on');
   set(controls.initialstatevaluesmenu,'Enable','on');
   set(controls.unitrootstatemenu,'Enable','on');
   if CheckConditioningData(DSGEModel)==1;
      if MaxFH>0;
         set(controls.viewconditionalvars,'Enable','on');
      else;
         set(controls.viewconditionalvars,'Enable','off');
      end;
      set(controls.setconditionalshocks,'Enable','on');
      set(controls.setconditionalvars,'Enable','on');
%      if length(DSGEModel.ConditionalShocks)>1;
%         set(controls.reorderconditionalshocks,'Enable','on');
%      else;
%         set(controls.reorderconditionalshocks,'Enable','off');
%      end;
   else;
      set(controls.setconditionalshocks,'Enable','off');
      set(controls.setconditionalvars,'Enable','off');
      set(controls.viewconditionalvars,'Enable','off');
%      set(controls.reorderconditionalshocks,'Enable','off');
   end;
   if isfield(controls,'ovs')==1;
      if CheckScenarioData(DSGEModel)==1;
         set(controls.ovs.setscenariovars,'Enable','on');
         set(controls.ovs.setscenarioshocks,'Enable','on');
         set(controls.ovs.savescenariodata,'Enable','on');
         set(controls.ovs.editscenariodata,'Enable','on');
         set(controls.ovs.viewscenariodata,'Enable','on');
         set(controls.ovs.exportscenariodata,'Enable','on');
         if (isempty(GetFiles([DSGEModel.OutputDirectory '\ovsdata'],'mat'))==0)|(isempty(DSGEModel.CompData)==0);
            set(controls.ovs.openscenariodata,'Enable','on');
         else;
            set(controls.ovs.openscenariodata,'Enable','off');
         end;
         if length(DSGEModel.ScenarioShocks)>1;
            set(controls.ovs.reorderscenarioshocks,'Enable','on');
         else;
            set(controls.ovs.reorderscenarioshocks,'Enable','of');
         end;
      else;
         set(controls.ovs.setscenariovars,'Enable','off');
         set(controls.ovs.setscenarioshocks,'Enable','off');
         set(controls.ovs.reorderscenarioshocks,'Enable','off');
         set(controls.ovs.savescenariodata,'Enable','off');
         set(controls.ovs.editscenariodata,'Enable','off');
         set(controls.ovs.viewscenariodata,'Enable','off');
         set(controls.ovs.exportscenariodata,'Enable','off');
         set(controls.ovs.openscenariodata,'Enable','off');
      end;
   end;
   ModeTextFile = [DSGEModel.OutputDirectory '\PosteriorModeResults-' DSGEModel.NameOfModel '.txt'];
   if FileExist(ModeTextFile)==1;
      set(controls.modeinfo,'Enable','on','UserData',ModeTextFile);
   else;
      set(controls.modeinfo,'Enable','off','UserData','');
   end;
   ModeSummaryTextFile = [DSGEModel.OutputDirectory '\PosteriorModeSummary-' DSGEModel.NameOfModel '.txt'];
   if FileExist(ModeSummaryTextFile)==1;
      set(controls.modesummary,'Enable','on','UserData',ModeSummaryTextFile);
   else;
      set(controls.modesummary,'Enable','off','UserData','');
   end;
   TxtFileName = [DSGEModel.OutputDirectory '\OptErrorReport-' DSGEModel.NameOfModel '.txt'];
   if FileExist(TxtFileName)==1;
      set(controls.opterrorsummary,'Enable','on','UserData',TxtFileName);
   else;
      set(controls.opterrorsummary,'Enable','off','UserData','');
   end;
   set(controls.dsgeeigenvalues.initialvalues,'Enable','on');
   set(controls.viewpriorvalue.initialvalues,'Enable','on');
   set(controls.dsgetovareigenvalues.initialvalues,'Enable','on');
   set(controls.informationmatrix.initialvalues,'Enable','on');
   set(controls.statespaceinitialvalues,'Enable','on');
   set(controls.statespacesaveinitialvalues,'Enable','on');
   set(controls.obsvarcorrs.initialvalues,'Enable','on');
   set(controls.condcorrs.initialvalues,'Enable','on');
   set(controls.simulatedata.initialvalues,'Enable','on');
   set(controls.statevarcorrs.initialvalues,'Enable','on');
   set(controls.irfunctions.initialvalues,'Enable','on');
   if max(DSGEModel.annual)>1;
      set(controls.irfunctions.ann_initialvalues,'Enable','on');
      set(controls.cvd.ann_initialvalues,'Enable','on');
      set(controls.ovd.anninitialvalues,'Enable','on');
   else;
      set(controls.irfunctions.ann_initialvalues,'Enable','off');
      set(controls.cvd.ann_initialvalues,'Enable','off');
      set(controls.ovd.anninitialvalues,'Enable','off');
   end;
   set(controls.hd.initialvalues,'Enable','on');
   set(controls.ovd.initialvalues,'Enable','on');
   set(controls.svd.initialvalues,'Enable','on');
   set(controls.fevd.initialvalues,'Enable','on');
   set(controls.fevd.lev_initialvalues,'Enable','on');
   set(controls.cvd.initialvalues,'Enable','on');
   if sum(DSGEModel.levels)<DSGEModel.n;
      set(controls.cvd.lev_initialvalues,'Enable','on');
      set(controls.irfunctions.lev_initialvalues,'Enable','on');
   else;
      set(controls.cvd.lev_initialvalues,'Enable','off');
      set(controls.irfunctions.lev_initialvalues,'Enable','off');
   end;
   set(controls.ps.initialvalues,'Enable','on');
   if max(DSGEModel.annual)>1;
      set(controls.ps.anninitialvalues,'Enable','on');
   else;
      set(controls.ps.anninitialvalues,'Enable','off');
   end;
   set(controls.statevariables.initialvalues,'Enable','on');
   set(controls.obsvar.initialvalues,'Enable','on');
   set(controls.stateshocks.initialvalues,'Enable','on');
   set(controls.measurementerror.initialvalues,'Enable','on');
   set(controls.loglikelihood.initialvalues,'Enable','on');
   if isfield(controls,'ovs')==1;
      if CheckScenarioData(DSGEModel)==1;
         set(controls.ovs.initialvalues,'Enable','on');
         if max(DSGEModel.annual)>1;
            set(controls.ovs.anninitialvalues,'Enable','on');
         else;
            set(controls.ovs.anninitialvalues,'Enable','off');
         end;
      else;
         set(controls.ovs.initialvalues,'Enable','off');
         set(controls.ovs.anninitialvalues,'Enable','off');
      end;
   end;
   if isfield(controls,'shockscenarios')==1;
      if MaxFH>0;
         set(controls.shockscenarios.initialvalues,'Enable','on');
         if max(DSGEModel.annual)>1;
            set(controls.shockscenarios.anninitialvalues,'Enable','on');
         else;
            set(controls.shockscenarios.anninitialvalues,'Enable','off');
         end;
      else;
         set(controls.shockscenarios.initialvalues,'Enable','off');
         set(controls.shockscenarios.anninitialvalues,'Enable','off');
      end;
   end;
   if (isempty(DSGEModel.PredictedX)==1)&(strcmp(DSGEModel.SubEndYear,DSGEModel.EndYear)==1)&(strcmp(DSGEModel.SubEndPeriod,DSGEModel.EndPeriod)==1);
      set(controls.predict.unconditional_original_initialvalues,'Enable','off');
      set(controls.predict.unconditional_annual_initialvalues,'Enable','off');
      set(controls.predict.unconditional_transformed_initialvalues,'Enable','off');
      set(controls.predict.conditional_original_initialvalues,'Enable','off');
      set(controls.predict.conditional_annual_initialvalues,'Enable','off');
      set(controls.predict.conditional_transformed_initialvalues,'Enable','off');
      set(controls.modesty.initialvalues,'Enable','off','UserData','');
   else;
      set(controls.predict.unconditional_original_initialvalues,'Enable','on');
      if isempty(DSGEModel.YTransformation)==0;
         set(controls.predict.unconditional_transformed_initialvalues,'Enable','on');
      else;
         set(controls.predict.unconditional_transformed_initialvalues,'Enable','off');
      end;
      if max(DSGEModel.annual)>1;
         set(controls.predict.unconditional_annual_initialvalues,'Enable','on');
      else;
         set(controls.predict.unconditional_annual_initialvalues,'Enable','off');
      end;
      if CheckConditioningData(DSGEModel)==1;
         set(controls.predict.conditional_original_initialvalues,'Enable','on');
         if isempty(DSGEModel.YTransformation)==0;
            set(controls.predict.conditional_transformed_initialvalues,'Enable','on');
         else;
            set(controls.predict.conditional_transformed_initialvalues,'Enable','off');
         end;
         %
         % check if we have a file for the modesty statistic at the posterior mode
         %
         [MaxPH,NumPredX] = CalcMaxPredictionHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,size(DSGEModel.PredictedX,2));
         NumPredPathsStr = get(controls.forecast.predpaths,'String');
         NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
         if DSGEModel.ShockControlMethod==1;
            ShockMethod = 'Direct-';
         else;
            ShockMethod = 'WaggonerZha-';
         end;
         ModestyFile = [DSGEModel.OutputDirectory '\DSGE-ModestyStatistics-' ShockMethod DSGEModel.NameOfModel '-' num2str(MaxPH,'%0.0f') '.' num2str(NumPredPaths,'%0.0f') '-InitialValues.txt'];;
         if FileExist(ModestyFile)==1;
            set(controls.modesty.initialvalues,'Enable','on','UserData',ModestyFile);
         else;
            set(controls.modesty.initialvalues,'Enable','off','UserData','');
         end;
         if max(DSGEModel.annual)>1;
            set(controls.predict.conditional_annual_initialvalues,'Enable','on');
         else;
            set(controls.predict.conditional_annual_initialvalues,'Enable','off');
         end;
      else;
         set(controls.predict.conditional_original_initialvalues,'Enable','off');
         set(controls.predict.conditional_annual_initialvalues,'Enable','off');
         set(controls.predict.conditional_transformed_initialvalues,'Enable','off');
         set(controls.modesty.initialvalues,'Enable','off','UserData','');
      end;
   end;
   set(controls.stateshockcorrs.initialvalues,'Enable','on');
   set(controls.measurementerrorcorrs.initialvalues,'Enable','on');
   set(controls.viewprior,'Enable','on');
   ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
   if FileExist(ModeFile)==1;
      if (isempty(DSGEModel.PredictedX)==1)&(strcmp(DSGEModel.SubEndYear,DSGEModel.EndYear)==1)&(strcmp(DSGEModel.SubEndPeriod,DSGEModel.EndPeriod)==1);
         set(controls.predict.unconditional_original_postmode,'Enable','off');
         set(controls.predict.unconditional_annual_postmode,'Enable','off');
         set(controls.predict.conditional_original_postmode,'Enable','off');
         set(controls.predict.conditional_annual_postmode,'Enable','off');
         set(controls.predict.unconditional_transformed_postmode,'Enable','off');
         set(controls.predict.conditional_transformed_postmode,'Enable','off');
         set(controls.modesty.postmode,'Enable','off','UserData','');
      else;
         set(controls.predict.unconditional_original_postmode,'Enable','on');
         if isempty(DSGEModel.YTransformation)==0;
            set(controls.predict.unconditional_transformed_postmode,'Enable','on');
         else;
            set(controls.predict.unconditional_transformed_postmode,'Enable','off');
         end;
         if max(DSGEModel.annual)>1;
            set(controls.predict.unconditional_annual_postmode,'Enable','on');
         else;
            set(controls.predict.unconditional_annual_postmode,'Enable','off');
         end;
         if CheckConditioningData(DSGEModel)==1;
            set(controls.predict.conditional_original_postmode,'Enable','on');
            if isempty(DSGEModel.YTransformation)==0;
               set(controls.predict.conditional_transformed_postmode,'Enable','on');
            else;
               set(controls.predict.conditional_transformed_postmode,'Enable','off');
            end;
            if max(DSGEModel.annual)>1;
               set(controls.predict.conditional_annual_postmode,'Enable','on');
            else;
               set(controls.predict.conditional_annual_postmode,'Enable','off');
            end;
            %
            % check if we have a file for the modesty statistic at the posterior mode
            %
            [MaxPH,NumPredX] = CalcMaxPredictionHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,size(DSGEModel.PredictedX,2));
            NumPredPathsStr = get(controls.forecast.predpaths,'String');
            NumPredPaths = str2num(strrep(strrep(StringTrim(NumPredPathsStr(DSGEModel.NumPredPathsValue,:)),'paths',''),',',''));
            if DSGEModel.ShockControlMethod==1;
               ShockMethod = 'Direct-';
            else;
               ShockMethod = 'WaggonerZha-';
            end;
            ModestyFile = [DSGEModel.OutputDirectory '\DSGE-ModestyStatistics-' ShockMethod DSGEModel.NameOfModel '-' num2str(MaxPH,'%0.0f') '.' num2str(NumPredPaths,'%0.0f') '-PosteriorMode.txt'];;
            if FileExist(ModestyFile)==1;
               set(controls.modesty.postmode,'Enable','on','UserData',ModestyFile);
            else;
               set(controls.modesty.postmode,'Enable','off','UserData','');
            end;
         else;
            set(controls.predict.conditional_original_postmode,'Enable','off');
            set(controls.predict.conditional_annual_postmode,'Enable','off');
            set(controls.predict.conditional_transformed_postmode,'Enable','off');
            set(controls.modesty.postmode,'Enable','off','UserData','');
         end;
      end;
      if isfield(controls,'shockscenarios')==1;
         if MaxFH>0;
            set(controls.shockscenarios.postmode,'Enable','on');
            if max(DSGEModel.annual)>1
               set(controls.shockscenarios.annpostmode,'Enable','on');
            else;
               set(controls.shockscenarios.annpostmode,'Enable','off');
            end;
         else;
            set(controls.shockscenarios.postmode,'Enable','off');
            set(controls.shockscenarios.annpostmode,'Enable','off');
         end;
      end;
      if isfield(controls,'ovs')==1;
         if CheckScenarioData(DSGEModel)==1;
            set(controls.ovs.postmode,'Enable','on');
            if max(DSGEModel.annual)>1;
               set(controls.ovs.annpostmode,'Enable','on');
            else;
               set(controls.ovs.annpostmode,'Enable','off');
            end;
         else;
            set(controls.ovs.postmode,'Enable','off');
            set(controls.ovs.annpostmode,'Enable','off');
         end;
      end;
      set(controls.irfunctions.postmode,'Enable','on');
      if max(DSGEModel.annual)>1;
         set(controls.irfunctions.ann_postmode,'Enable','on');
         set(controls.cvd.ann_postmode,'Enable','on');
         set(controls.ovd.annpostmode,'Enable','on');
      else;
         set(controls.irfunctions.ann_postmode,'Enable','off');
         set(controls.cvd.ann_postmode,'Enable','off');
         set(controls.ovd.annpostmode,'Enable','off');
      end;
      set(controls.fevd.postmode,'Enable','on');
      set(controls.fevd.lev_postmode,'Enable','on');
      set(controls.cvd.postmode,'Enable','on');
      if sum(DSGEModel.levels)<DSGEModel.n;
         set(controls.cvd.lev_postmode,'Enable','on');
         set(controls.irfunctions.lev_postmode,'Enable','on');
      else;
         set(controls.cvd.lev_postmode,'Enable','off');
         set(controls.irfunctions.lev_postmode,'Enable','off');
      end;
      set(controls.hd.postmode,'Enable','on');
      set(controls.ovd.postmode,'Enable','on');
      set(controls.svd.postmode,'Enable','on');
      set(controls.postsampling,'Enable','on');
      set(controls.postsamplingmenu,'Enable','on');
      set(controls.checkpostmode,'Enable','on');
      set(controls.ps.postmode,'Enable','on');
      if max(DSGEModel.annual)>1;
         set(controls.ps.annpostmode,'Enable','on');
      else;
         set(controls.ps.annpostmode,'Enable','off');
      end;
      %
      % check to make sure that theta has at least 2 parameters
      %
      pm = load(ModeFile);
      if length(pm.phiMode)>1;
         set(controls.threedeepostmode.transformed,'Enable','on');
         set(controls.threedeepostmode.original,'Enable','on');
      else;
         set(controls.threedeepostmode.transformed,'Enable','off');
         set(controls.threedeepostmode.original,'Enable','off');
      end;
      set(controls.iteratedparameters,'Enable','on');
      set(controls.statevariables.postmode,'Enable','on');
      set(controls.obsvar.postmode,'Enable','on');
      set(controls.stateshocks.postmode,'Enable','on');
      set(controls.measurementerror.postmode,'Enable','on');
      set(controls.loglikelihood.postmode,'Enable','on');
      set(controls.stateshockcorrs.postmode,'Enable','on');
      set(controls.measurementerrorcorrs.postmode,'Enable','on');
      set(controls.dsgeeigenvalues.postmode,'Enable','on');
      set(controls.viewpriorvalue.postmode,'Enable','on');
      set(controls.dsgetovareigenvalues.postmode,'Enable','on');
      set(controls.informationmatrix.postmode,'Enable','on');
      set(controls.simulatedata.postmode,'Enable','on');
      set(controls.statespacemode,'Enable','on');
      set(controls.statespacesavemode,'Enable','on');
      set(controls.obsvarcorrs.postmode,'Enable','on');
      set(controls.condcorrs.postmode,'Enable','on');
      set(controls.statevarcorrs.postmode,'Enable','on');
      %
      % check if the post sample summary file exist
      %
      DrawsStr = get(controls.posterior.draws,'String');
      NumPostDraws = str2num(StringTrim(strrep(DrawsStr(DSGEModel.PosteriorDrawsValue,:),',','')));
      %
      ChainsStr = get(controls.posterior.chains,'String');
      NumChains = str2num(StringTrim(ChainsStr(DSGEModel.ParallelChainsValue,:)));
      for CurrChain=1:10;
         PostSampleTextFile = [DSGEModel.OutputDirectory '\PosteriorSamplingSummary-' DSGEModel.NameOfModel '-' num2str(DSGEModel.InverseHessianEstimator,'%0.0f') '-' num2str(CurrChain,'%0.0f') '.' num2str(NumChains,'%0.0f') '-' num2str(NumPostDraws,'%0.0f') '.txt'];
         if FileExist(PostSampleTextFile)==1;
            set(getfield(controls.postsamplesummary,['chain' num2str(CurrChain,'%0.0f')]),'Enable','on','UserData',PostSampleTextFile);
         else;
            set(getfield(controls.postsamplesummary,['chain' num2str(CurrChain,'%0.0f')]),'Enable','off','UserData','');
         end;
      end;
      if VerifyDSGEPosteriorDraws(DSGEModel,1,controls)==1;
         %
         % enable controls that require that we read the posterior draws data
         %
         set(controls.postsample.mhm,'Enable','on');
         set(controls.postsample.chibjeliazkov,'Enable','on');
         set(controls.postsample.rawplots_original,'Enable','on');
         set(controls.postsample.rawplots_transformed,'Enable','on');
         if length(pm.phiMode)>1;
            set(controls.postsample.scatterplots_original,'Enable','on');
            set(controls.postsample.scatterplots_transformed,'Enable','on');
         else;
            set(controls.postsample.scatterplots_original,'Enable','off');
            set(controls.postsample.scatterplots_transformed,'Enable','off');
         end;
         set(controls.postsample.cusumplots.logposterior,'Enable','on');
         set(controls.postsample.cusumplots.original,'Enable','on');
         set(controls.postsample.cusumplots.transformed,'Enable','on');
         set(controls.postsample.spmt.logposterior,'Enable','on');
         set(controls.postsample.spmt.original,'Enable','on');
         set(controls.postsample.spmt.transformed,'Enable','on');
         set(controls.postsample.acceptancerate,'Enable','on');
         if (strcmp(get(controls.postsamplesummary.chain2,'Enable'),'on')==1)&(DSGEModel.ParallelChainsValue>1);
            set(controls.postsample.manova,'Enable','on');
         else;
            set(controls.postsample.manova,'Enable','off');
         end;
         set(controls.postsample.mean,'Enable','on');
         set(controls.postsample.median,'Enable','on');
         set(controls.viewposterior,'Enable','on');
         set(controls.hd.posterior,'Enable','on');
         set(controls.irfunctions.posterior,'Enable','on');
         set(controls.obsvar.posterior,'Enable','on');
         set(controls.obsvarcorrs.posterior,'Enable','on');
         set(controls.condcorrs.posterior,'Enable','on');
         set(controls.statevariables.posterior,'Enable','on');
         set(controls.statevarcorrs.posterior,'Enable','on');
         set(controls.stateshocks.posterior,'Enable','on');
         set(controls.stateshockcorrs.posterior,'Enable','on');
         set(controls.measurementerror.posterior,'Enable','on');
         set(controls.measurementerrorcorrs.posterior,'Enable','on');
         set(controls.cvd.posterior,'Enable','on');
         set(controls.estimateparamcovmat,'Enable','on');
         set(controls.fevd.posterior,'Enable','on');
         set(controls.fevd.lev_posterior,'Enable','on');
         if isfield(controls,'shockscenarios')==1;
            if MaxFH>0;
               set(controls.shockscenarios.posterior,'Enable','on');
               if max(DSGEModel.annual)>1;
                  set(controls.shockscenarios.annposterior,'Enable','on');
               else;
                  set(controls.shockscenarios.annposterior,'Enable','off');
               end;
            else;
               set(controls.shockscenarios.posterior,'Enable','off');
               set(controls.shockscenarios.annposterior,'Enable','off');
            end;
         end;
         if sum(DSGEModel.levels)<DSGEModel.n;
            set(controls.irfunctions.lev_posterior,'Enable','on');
            set(controls.cvd.lev_posterior,'Enable','on');
         else;
            set(controls.irfunctions.lev_posterior,'Enable','off');
            set(controls.cvd.lev_posterior,'Enable','off');
         end;
         if max(DSGEModel.annual)>1;
            set(controls.irfunctions.ann_posterior,'Enable','on');
            set(controls.cvd.ann_posterior,'Enable','on');
         else;
            set(controls.irfunctions.ann_posterior,'Enable','off');
            set(controls.cvd.ann_posterior,'Enable','off');
         end;
         if isfield(controls,'ovs')==1;
            if CheckScenarioData(DSGEModel)==1;
               set(controls.ovs.posterior,'Enable','on');
               if max(DSGEModel.annual)>1;
                  set(controls.ovs.ann_posterior,'Enable','on');
               else;
                  set(controls.ovs.ann_posterior,'Enable','off');
               end;
            else;
               set(controls.ovs.posterior,'Enable','off');
               set(controls.ovs.ann_posterior,'Enable','off');
            end;
         end;
         if (isempty(DSGEModel.PredictedX)==1)&(strcmp(DSGEModel.SubEndYear,DSGEModel.EndYear)==1)&(strcmp(DSGEModel.SubEndPeriod,DSGEModel.EndPeriod)==1);
            set(controls.predict.unconditional_original_posterior,'Enable','off');
            set(controls.predict.unconditional_annual_posterior,'Enable','off');
            set(controls.predict.unconditional_transformed_posterior,'Enable','off');
            set(controls.predict.unconditional_original_predevent,'Enable','off');
            set(controls.predict.unconditional_annual_predevent,'Enable','off');
            set(controls.predict.unconditional_transformed_predevent,'Enable','off');
            set(controls.predict.conditional_original_posterior,'Enable','off');
            set(controls.predict.conditional_annual_posterior,'Enable','off');
            set(controls.predict.conditional_transformed_posterior,'Enable','off');
            set(controls.predict.conditional_original_predevent,'Enable','off');
            set(controls.predict.conditional_annual_predevent,'Enable','off');
            set(controls.predict.conditional_transformed_predevent,'Enable','off');
            for i=1:10;
               set(getfield(controls.modesty,['chain' num2str(i,'%0.0f')]),'Enable','off','UserData','');
            end;
         else;
            set(controls.predict.unconditional_original_posterior,'Enable','on');
            set(controls.predict.unconditional_original_predevent,'Enable','on');
            if isempty(DSGEModel.YTransformation)==0;
               set(controls.predict.unconditional_transformed_posterior,'Enable','on');
               set(controls.predict.unconditional_transformed_predevent,'Enable','on');
            else;
               set(controls.predict.unconditional_transformed_posterior,'Enable','off');
               set(controls.predict.unconditional_transformed_predevent,'Enable','off');
            end;
            if max(DSGEModel.annual)>1;
               set(controls.predict.unconditional_annual_posterior,'Enable','on');
               set(controls.predict.unconditional_annual_predevent,'Enable','on');
            else;
               set(controls.predict.unconditional_annual_posterior,'Enable','off');
               set(controls.predict.unconditional_annual_predevent,'Enable','off');
            end;
            if CheckConditioningData(DSGEModel)==1;
               set(controls.predict.conditional_original_posterior,'Enable','on');
               set(controls.predict.conditional_original_predevent,'Enable','on');
               if isempty(DSGEModel.YTransformation)==0;
                  set(controls.predict.conditional_transformed_posterior,'Enable','on');
                  set(controls.predict.conditional_transformed_predevent,'Enable','on');
               else;
                  set(controls.predict.conditional_transformed_posterior,'Enable','off');
                  set(controls.predict.conditional_transformed_predevent,'Enable','off');
               end;
               %
               % check if modesty results exists
               %
               [stat,files] = ModestyExist(DSGEModel,controls,'DSGE');
               for i=1:10;
                  if stat(i)==1;
                     set(getfield(controls.modesty,['chain' num2str(i,'%0.0f')]),'Enable','on','UserData',StringTrim(files(i,:)));
                  else;
                     set(getfield(controls.modesty,['chain' num2str(i,'%0.0f')]),'Enable','off','UserData','');
                  end;
               end;
               if max(DSGEModel.annual)>1;
                  set(controls.predict.conditional_annual_posterior,'Enable','on');
                  set(controls.predict.conditional_annual_predevent,'Enable','on');
               else;
                  set(controls.predict.conditional_annual_posterior,'Enable','off');
                  set(controls.predict.conditional_annual_predevent,'Enable','off');
               end;
            else;
               set(controls.predict.conditional_original_posterior,'Enable','off');
               set(controls.predict.conditional_original_predevent,'Enable','off');
               set(controls.predict.conditional_annual_posterior,'Enable','off');
               set(controls.predict.conditional_annual_predevent,'Enable','off');
               set(controls.predict.conditional_transformed_posterior,'Enable','off');
               set(controls.predict.conditional_transformed_predevent,'Enable','off');
               for i=1:10;
                  set(getfield(controls.modesty,['chain' num2str(i,'%0.0f')]),'Enable','off','UserData','');
               end;
            end;
         end;
      else;
         %
         % disable controls that require that all posterior draws data exists
         %
         set(controls.postsample.mhm,'Enable','off');
         set(controls.postsample.chibjeliazkov,'Enable','off');
         set(controls.postsample.rawplots_original,'Enable','off');
         set(controls.postsample.scatterplots_original,'Enable','off');
         set(controls.postsample.rawplots_transformed,'Enable','off');
         set(controls.postsample.scatterplots_transformed,'Enable','off');
         set(controls.hd.posterior,'Enable','off');
         set(controls.irfunctions.posterior,'Enable','off');
         set(controls.obsvar.posterior,'Enable','off');
         set(controls.obsvarcorrs.posterior,'Enable','off');
         set(controls.condcorrs.posterior,'Enable','off');
         set(controls.statevariables.posterior,'Enable','off');
         set(controls.statevarcorrs.posterior,'Enable','off');
         set(controls.stateshocks.posterior,'Enable','off');
         set(controls.stateshockcorrs.posterior,'Enable','off');
         set(controls.measurementerror.posterior,'Enable','off');
         set(controls.measurementerrorcorrs.posterior,'Enable','off');
         if isfield(controls,'ovs')==1;
            set(controls.ovs.posterior,'Enable','off');
            set(controls.ovs.ann_posterior,'Enable','off');
         end;
         if isfield(controls,'shockscenarios')==1;
            set(controls.shockscenarios.posterior,'Enable','off');
            set(controls.shockscenarios.annposterior,'Enable','off');
         end;
         set(controls.cvd.posterior,'Enable','off');
         set(controls.fevd.posterior,'Enable','off');
         set(controls.fevd.lev_posterior,'Enable','off');
         set(controls.estimateparamcovmat,'Enable','off');
         set(controls.irfunctions.ann_posterior,'Enable','off');
         set(controls.cvd.ann_posterior,'Enable','off');
         set(controls.irfunctions.lev_posterior,'Enable','off');
         set(controls.cvd.lev_posterior,'Enable','off');
         set(controls.postsample.cusumplots.logposterior,'Enable','off');
         set(controls.postsample.cusumplots.original,'Enable','off');
         set(controls.postsample.cusumplots.transformed,'Enable','off');
         set(controls.postsample.spmt.logposterior,'Enable','off');
         set(controls.postsample.spmt.original,'Enable','off');
         set(controls.postsample.spmt.transformed,'Enable','off');
         set(controls.postsample.acceptancerate,'Enable','off');
         set(controls.postsample.manova,'Enable','off');
         set(controls.postsample.mean,'Enable','off');
         set(controls.postsample.median,'Enable','off');
         set(controls.viewposterior,'Enable','off');
         set(controls.predict.unconditional_original_posterior,'Enable','off');
         set(controls.predict.unconditional_original_predevent,'Enable','off');
         set(controls.predict.unconditional_transformed_posterior,'Enable','off');
         set(controls.predict.unconditional_transformed_predevent,'Enable','off');
         set(controls.predict.conditional_original_posterior,'Enable','off');
         set(controls.predict.conditional_original_predevent,'Enable','off');
         set(controls.predict.conditional_transformed_posterior,'Enable','off');
         set(controls.predict.conditional_transformed_predevent,'Enable','off');
         for i=1:10;
            set(getfield(controls.modesty,['chain' num2str(i,'%0.0f')]),'Enable','off','UserData','');
         end;
         set(controls.predict.unconditional_annual_posterior,'Enable','off');
         set(controls.predict.unconditional_annual_predevent,'Enable','off');
         set(controls.predict.conditional_annual_posterior,'Enable','off');
         set(controls.predict.conditional_annual_predevent,'Enable','off');
      end;
      clear('pm');
   else;
      if isfield(controls,'ovs')==1;
         set(controls.ovs.postmode,'Enable','off');
         set(controls.ovs.annpostmode,'Enable','off');
         set(controls.ovs.posterior,'Enable','off');
         set(controls.ovs.ann_posterior,'Enable','off');
      end;
      if isfield(controls,'shockscenarios')==1;
         set(controls.shockscenarios.annpostmode,'Enable','off');
         set(controls.shockscenarios.postmode,'Enable','off');
         set(controls.shockscenarios.posterior,'Enable','off');
         set(controls.shockscenarios.annposterior,'Enable','off');
      end;
      set(controls.irfunctions.postmode,'Enable','off');
      set(controls.predict.unconditional_original_postmode,'Enable','off');
      set(controls.predict.conditional_original_postmode,'Enable','off');
      set(controls.predict.unconditional_transformed_postmode,'Enable','off');
      set(controls.predict.conditional_transformed_postmode,'Enable','off');
      set(controls.modesty.postmode,'Enable','off','UserData','');
      set(controls.predict.unconditional_annual_postmode,'Enable','off');
      set(controls.predict.conditional_annual_postmode,'Enable','off');
      set(controls.irfunctions.ann_postmode,'Enable','off');
      set(controls.fevd.postmode,'Enable','off');
      set(controls.fevd.lev_postmode,'Enable','off');
      set(controls.cvd.postmode,'Enable','off');
      set(controls.cvd.ann_postmode,'Enable','off');
      set(controls.cvd.lev_postmode,'Enable','off');
      set(controls.irfunctions.lev_postmode,'Enable','off');
      set(controls.hd.postmode,'Enable','off');
      set(controls.ovd.postmode,'Enable','off');
      set(controls.ovd.annpostmode,'Enable','off');
      set(controls.svd.postmode,'Enable','off');
      set(controls.postsampling,'Enable','off');
      set(controls.postsamplingmenu,'Enable','off');
      set(controls.checkpostmode,'Enable','off');
      set(controls.ps.postmode,'Enable','off');
      set(controls.ps.annpostmode,'Enable','off');
      set(controls.threedeepostmode.transformed,'Enable','off');
      set(controls.threedeepostmode.original,'Enable','off');
      set(controls.iteratedparameters,'Enable','off');
      set(controls.statevariables.postmode,'Enable','off');
      set(controls.obsvar.postmode,'Enable','off');
      set(controls.stateshocks.postmode,'Enable','off');
      set(controls.measurementerror.postmode,'Enable','off');
      set(controls.loglikelihood.postmode,'Enable','off');
      set(controls.stateshockcorrs.postmode,'Enable','off');
      set(controls.measurementerrorcorrs.postmode,'Enable','off');
      set(controls.dsgeeigenvalues.postmode,'Enable','off');
      set(controls.viewpriorvalue.postmode,'Enable','off');
      set(controls.dsgetovareigenvalues.postmode,'Enable','off');
      set(controls.informationmatrix.postmode,'Enable','off');
      set(controls.simulatedata.postmode,'Enable','off');
      set(controls.statespacemode,'Enable','off');
      set(controls.statespacesavemode,'Enable','off');
      set(controls.obsvarcorrs.postmode,'Enable','off');
      set(controls.condcorrs.postmode,'Enable','off');
      set(controls.statevarcorrs.postmode,'Enable','off');
      for CurrChain=1:10;
         set(getfield(controls.postsamplesummary,['chain' num2str(CurrChain,'%0.0f')]),'Enable','off','UserData','');
      end;
      set(controls.postsample.mhm,'Enable','off');
      set(controls.postsample.chibjeliazkov,'Enable','off');
      set(controls.predict.unconditional_original_posterior,'Enable','off');
      set(controls.predict.unconditional_original_predevent,'Enable','off');
      set(controls.predict.unconditional_transformed_posterior,'Enable','off');
      set(controls.predict.unconditional_transformed_predevent,'Enable','off');
      set(controls.predict.conditional_original_posterior,'Enable','off');
      set(controls.predict.conditional_original_predevent,'Enable','off');
      set(controls.predict.conditional_transformed_posterior,'Enable','off');
      set(controls.predict.conditional_transformed_predevent,'Enable','off');
      for i=1:10;
         set(getfield(controls.modesty,['chain' num2str(i,'%0.0f')]),'Enable','off','UserData','');
      end;
      set(controls.predict.unconditional_annual_posterior,'Enable','off');
      set(controls.predict.unconditional_annual_predevent,'Enable','off');
      set(controls.predict.conditional_annual_posterior,'Enable','off');
      set(controls.predict.conditional_annual_predevent,'Enable','off');
      set(controls.postsample.rawplots_original,'Enable','off');
      set(controls.postsample.scatterplots_original,'Enable','off');
      set(controls.postsample.rawplots_transformed,'Enable','off');
      set(controls.postsample.scatterplots_transformed,'Enable','off');
      set(controls.hd.posterior,'Enable','off');
      set(controls.irfunctions.posterior,'Enable','off');
      set(controls.obsvar.posterior,'Enable','off');
      set(controls.obsvarcorrs.posterior,'Enable','off');
      set(controls.condcorrs.posterior,'Enable','off');
      set(controls.statevariables.posterior,'Enable','off');
      set(controls.statevarcorrs.posterior,'Enable','off');
      set(controls.stateshocks.posterior,'Enable','off');
      set(controls.stateshockcorrs.posterior,'Enable','off');
      set(controls.measurementerror.posterior,'Enable','off');
      set(controls.measurementerrorcorrs.posterior,'Enable','off');
      set(controls.cvd.posterior,'Enable','off');
      set(controls.fevd.posterior,'Enable','off');
      set(controls.fevd.lev_posterior,'Enable','off');
      set(controls.estimateparamcovmat,'Enable','off');
      set(controls.irfunctions.ann_posterior,'Enable','off');
      set(controls.cvd.ann_posterior,'Enable','off');
      set(controls.irfunctions.lev_posterior,'Enable','off');
      set(controls.cvd.lev_posterior,'Enable','off');
      set(controls.postsample.cusumplots.logposterior,'Enable','off');
      set(controls.postsample.cusumplots.original,'Enable','off');
      set(controls.postsample.cusumplots.transformed,'Enable','off');
      set(controls.postsample.spmt.logposterior,'Enable','off');
      set(controls.postsample.spmt.original,'Enable','off');
      set(controls.postsample.spmt.transformed,'Enable','off');
      set(controls.postsample.acceptancerate,'Enable','off');
      set(controls.postsample.manova,'Enable','off');
      set(controls.postsample.mean,'Enable','off');
      set(controls.postsample.median,'Enable','off');
      set(controls.viewposterior,'Enable','off');
   end;
else;
   if isfield(controls,'ovs')==1;
      set(controls.ovs.postmode,'Enable','off');
      set(controls.ovs.annpostmode,'Enable','off');
      set(controls.ovs.initialvalues,'Enable','off');
      set(controls.ovs.anninitialvalues,'Enable','off');
      set(controls.ovs.posterior,'Enable','off');
      set(controls.ovs.ann_posterior,'Enable','off');
      set(controls.ovs.setscenariovars,'Enable','off');
      set(controls.ovs.savescenariodata,'Enable','off');
      set(controls.ovs.editscenariodata,'Enable','off');
      set(controls.ovs.viewscenariodata,'Enable','off');
      set(controls.ovs.exportscenariodata,'Enable','off');
      set(controls.ovs.openscenariodata,'Enable','off');
      set(controls.ovs.setscenarioshocks,'Enable','off');
      set(controls.ovs.reorderscenarioshocks,'Enable','off');
   end;
   if isfield(controls,'shockscenarios')==1;
      set(controls.shockscenarios.postmode,'Enable','off');
      set(controls.shockscenarios.annpostmode,'Enable','off');
      set(controls.shockscenarios.initialvalues,'Enable','off');
      set(controls.shockscenarios.anninitialvalues,'Enable','off');
      set(controls.shockscenarios.posterior,'Enable','off');
      set(controls.shockscenarios.annposterior,'Enable','off');
   end;
   set(controls.postmode,'Enable','off');
   set(controls.postmodemenu,'Enable','off');
   set(controls.setconditionalvars,'Enable','off');
   set(controls.setconditionalshocks,'Enable','off');
   set(controls.viewconditionalvars,'Enable','off');
   set(controls.shockgroupmenu,'Enable','off');
   set(controls.shockgroup,'Enable','off');
   set(controls.initialstatevaluesmenu,'Enable','off');
   set(controls.unitrootstatemenu,'Enable','off');
   set(controls.modeinfo,'Enable','off','UserData','');
   set(controls.modesummary,'Enable','off','UserData','');
   set(controls.opterrorsummary,'Enable','off','UserData','');
   set(controls.dsgeeigenvalues.initialvalues,'Enable','off');
   set(controls.viewpriorvalue.initialvalues,'Enable','off');
   set(controls.dsgetovareigenvalues.initialvalues,'Enable','off');
   set(controls.informationmatrix.initialvalues,'Enable','off');
   set(controls.statespaceinitialvalues,'Enable','off');
   set(controls.statespacesaveinitialvalues,'Enable','off');
   set(controls.obsvarcorrs.initialvalues,'Enable','off');
   set(controls.condcorrs.initialvalues,'Enable','off');
   set(controls.simulatedata.initialvalues,'Enable','off');
   set(controls.statevarcorrs.initialvalues,'Enable','off');
   set(controls.irfunctions.initialvalues,'Enable','off');
   set(controls.irfunctions.ann_initialvalues,'Enable','off');
   set(controls.hd.initialvalues,'Enable','off');
   set(controls.ovd.initialvalues,'Enable','off');
   set(controls.ovd.anninitialvalues,'Enable','off');
   set(controls.svd.initialvalues,'Enable','off');
   set(controls.fevd.initialvalues,'Enable','off');
   set(controls.fevd.lev_initialvalues,'Enable','off');
   set(controls.cvd.initialvalues,'Enable','off');
   set(controls.cvd.ann_initialvalues,'Enable','off');
   set(controls.cvd.lev_initialvalues,'Enable','off');
   set(controls.irfunctions.lev_initialvalues,'Enable','off');
   set(controls.statevariables.initialvalues,'Enable','off');
   set(controls.ps.initialvalues,'Enable','off');
   set(controls.ps.anninitialvalues,'Enable','off');
   set(controls.obsvar.initialvalues,'Enable','off');
   set(controls.stateshocks.initialvalues,'Enable','off');
   set(controls.measurementerror.initialvalues,'Enable','off');
   set(controls.loglikelihood.initialvalues,'Enable','off');
   set(controls.predict.unconditional_original_initialvalues,'Enable','off');
   set(controls.predict.conditional_original_initialvalues,'Enable','off');
   set(controls.predict.unconditional_transformed_initialvalues,'Enable','off');
   set(controls.predict.conditional_transformed_initialvalues,'Enable','off');
   set(controls.modesty.initialvalues,'Enable','off','UserData','');
   set(controls.predict.conditional_annual_initialvalues,'Enable','off');
   set(controls.predict.unconditional_annual_initialvalues,'Enable','off');
   set(controls.stateshockcorrs.initialvalues,'Enable','off');
   set(controls.measurementerrorcorrs.initialvalues,'Enable','off');
   set(controls.viewprior,'Enable','off');
   set(controls.irfunctions.postmode,'Enable','off');
   set(controls.predict.unconditional_original_postmode,'Enable','off');
   set(controls.predict.conditional_original_postmode,'Enable','off');
   set(controls.predict.unconditional_transformed_postmode,'Enable','off');
   set(controls.predict.conditional_transformed_postmode,'Enable','off');
   set(controls.modesty.postmode,'Enable','off','UserData','');
   set(controls.predict.unconditional_annual_postmode,'Enable','off');
   set(controls.predict.conditional_annual_postmode,'Enable','off');
   set(controls.irfunctions.ann_postmode,'Enable','off');
   set(controls.fevd.postmode,'Enable','off');
   set(controls.fevd.lev_postmode,'Enable','off');
   set(controls.cvd.postmode,'Enable','off');
   set(controls.cvd.ann_postmode,'Enable','off');
   set(controls.cvd.lev_postmode,'Enable','off');
   set(controls.irfunctions.lev_postmode,'Enable','off');
   set(controls.hd.postmode,'Enable','off');
   set(controls.ovd.postmode,'Enable','off');
   set(controls.ovd.annpostmode,'Enable','off');
   set(controls.svd.postmode,'Enable','off');
   set(controls.postsampling,'Enable','off');
   set(controls.postsamplingmenu,'Enable','off');
   set(controls.checkpostmode,'Enable','off');
   set(controls.ps.postmode,'Enable','off');
   set(controls.ps.annpostmode,'Enable','off');
   set(controls.threedeepostmode.transformed,'Enable','off');
   set(controls.threedeepostmode.original,'Enable','off');
   set(controls.iteratedparameters,'Enable','off');
   set(controls.statevariables.postmode,'Enable','off');
   set(controls.obsvar.postmode,'Enable','off');
   set(controls.stateshocks.postmode,'Enable','off');
   set(controls.measurementerror.postmode,'Enable','off');
   set(controls.loglikelihood.postmode,'Enable','off');
   set(controls.stateshockcorrs.postmode,'Enable','off');
   set(controls.measurementerrorcorrs.postmode,'Enable','off');
   set(controls.dsgeeigenvalues.postmode,'Enable','off');
   set(controls.viewpriorvalue.postmode,'Enable','off');
   set(controls.dsgetovareigenvalues.postmode,'Enable','off');
   set(controls.informationmatrix.postmode,'Enable','off');
   set(controls.simulatedata.postmode,'Enable','off');
   set(controls.statespacemode,'Enable','off');
   set(controls.statespacesavemode,'Enable','off');
   set(controls.obsvarcorrs.postmode,'Enable','off');
   set(controls.condcorrs.postmode,'Enable','off');
   set(controls.statevarcorrs.postmode,'Enable','off');
   for CurrChain=1:10;
      set(getfield(controls.postsamplesummary,['chain' num2str(CurrChain,'%0.0f')]),'Enable','off','UserData','');
   end;
   set(controls.postsample.mhm,'Enable','off');
   set(controls.postsample.chibjeliazkov,'Enable','off');
   set(controls.predict.unconditional_original_posterior,'Enable','off');
   set(controls.predict.unconditional_original_predevent,'Enable','off');
   set(controls.predict.unconditional_transformed_posterior,'Enable','off');
   set(controls.predict.unconditional_transformed_predevent,'Enable','off');
   set(controls.predict.conditional_original_posterior,'Enable','off');
   set(controls.predict.conditional_original_predevent,'Enable','off');
   set(controls.predict.conditional_transformed_posterior,'Enable','off');
   set(controls.predict.conditional_transformed_predevent,'Enable','off');
   for i=1:10;
      set(getfield(controls.modesty,['chain' num2str(i,'%0.0f')]),'Enable','off','UserData','');
   end;
   set(controls.predict.unconditional_annual_posterior,'Enable','off');
   set(controls.predict.unconditional_annual_predevent,'Enable','off');
   set(controls.predict.conditional_annual_posterior,'Enable','off');
   set(controls.predict.conditional_annual_predevent,'Enable','off');
   set(controls.postsample.rawplots_original,'Enable','off');
   set(controls.postsample.scatterplots_original,'Enable','off');
   set(controls.postsample.rawplots_transformed,'Enable','off');
   set(controls.postsample.scatterplots_transformed,'Enable','off');
   set(controls.hd.posterior,'Enable','off');
   set(controls.irfunctions.posterior,'Enable','off');
   set(controls.obsvar.posterior,'Enable','off');
   set(controls.obsvarcorrs.posterior,'Enable','off');
   set(controls.condcorrs.posterior,'Enable','off');
   set(controls.statevariables.posterior,'Enable','off');
   set(controls.statevarcorrs.posterior,'Enable','off');
   set(controls.stateshocks.posterior,'Enable','off');
   set(controls.stateshockcorrs.posterior,'Enable','off');
   set(controls.measurementerror.posterior,'Enable','off');
   set(controls.measurementerrorcorrs.posterior,'Enable','off');
   set(controls.cvd.posterior,'Enable','off');
   set(controls.fevd.posterior,'Enable','off');
   set(controls.fevd.lev_posterior,'Enable','off');
   set(controls.estimateparamcovmat,'Enable','off');
   set(controls.irfunctions.ann_posterior,'Enable','off');
   set(controls.cvd.ann_posterior,'Enable','off');
   set(controls.irfunctions.lev_posterior,'Enable','off');
   set(controls.cvd.lev_posterior,'Enable','off');
   set(controls.postsample.cusumplots.logposterior,'Enable','off');
   set(controls.postsample.cusumplots.original,'Enable','off');
   set(controls.postsample.cusumplots.transformed,'Enable','off');
   set(controls.postsample.spmt.logposterior,'Enable','off');
   set(controls.postsample.spmt.original,'Enable','off');
   set(controls.postsample.spmt.transformed,'Enable','off');
   set(controls.postsample.acceptancerate,'Enable','off');
   set(controls.postsample.manova,'Enable','off');
   set(controls.postsample.mean,'Enable','off');
   set(controls.postsample.median,'Enable','off');
   set(controls.viewposterior,'Enable','off');
end;
if FileExist(DSGEModel.DataConstructionFile)==1;
   set(controls.viewdata,'Enable','on');
   if max(DSGEModel.annual)>1;
      set(controls.viewannualdata,'Enable','on');
      set(controls.saveannualdata,'Enable','on');
   else;
      set(controls.viewannualdata,'Enable','off');
      set(controls.saveannualdata,'Enable','off');
   end;
   if isempty(DSGEModel.YTransformation)==0;
      set(controls.viewtransdata,'Enable','on');
   else;
      set(controls.viewtransdata,'Enable','off');
   end;
   %
   % check if file with steady state prior parameters exists
   %
   if VerifySteadyStatePrior(DSGEModel.SteadyStatePriorFile,DSGEModel.BVARY,DSGEModel.BVARX)==1;
      if exist('MaxFH')==0;
         MaxFH = CalcMaxForecastHorizon(DSGEModel.MaxForecastHorizon,DSGEModel.DataFrequency,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod);
      end;
      set(controls.bvarmodemenu,'Enable','on');
      set(controls.bvarpriordensitypsi,'Enable','on');
      if (DSGEModel.PriorType==1)|((DSGEModel.PriorType==2)&(DSGEModel.OmegaPriorType==2));
         set(controls.bvarpriordensitypi,'Enable','on');
      else;
         set(controls.bvarpriordensitypi,'Enable','off');
      end;
      if DSGEModel.OmegaPriorType==2;
         set(controls.bvarpriordensityomega,'Enable','on');
      else;
         set(controls.bvarpriordensityomega,'Enable','off');
      end;
      DrawsStr = get(controls.posterior.draws,'String');
      NumPostDraws = str2num(StringTrim(strrep(DrawsStr(DSGEModel.PosteriorDrawsValue,:),',','')));
      ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-BVAR-' DSGEModel.NameOfModel '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '.mat'];
      if (FileExist(ModeFile)==1)&(MaxFH>0);
         %
         % Enable a few menu's of interest
         %
         if (isempty(DSGEModel.PredictedX)==1)&(isempty(DSGEModel.BVARX)==0)&(strcmp(DSGEModel.SubEndYear,DSGEModel.EndYear)==1)&(strcmp(DSGEModel.SubEndPeriod,DSGEModel.EndPeriod)==1);
            set(controls.bvarpredict.original_postmode,'Enable','off');
            set(controls.bvarpredict.annual_postmode,'Enable','off');
         else;
            set(controls.bvarpredict.original_postmode,'Enable','on');
            if max(DSGEModel.annual(DSGEModel.BVARY))>1;
               set(controls.bvarpredict.annual_postmode,'Enable','on');
            else;
               set(controls.bvarpredict.annual_postmode,'Enable','off');
            end;
         end;
%         set(controls.bvarforecast.postmode,'Enable','on');
%         if max(DSGEModel.annual(DSGEModel.BVARY))>1;
%            set(controls.bvarforecast.annpostmode,'Enable','on');
%         else;
%            set(controls.bvarforecast.annpostmode,'Enable','off');
%         end;
         ModeTextFile = [DSGEModel.OutputDirectory '\PosteriorModeBVAR-' DSGEModel.NameOfModel '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '.txt'];
         if FileExist(ModeTextFile)==1;
            set(controls.bvarmoderesultsmenu,'Enable','on');
         else;
            set(controls.bvarmoderesultsmenu,'Enable','off');
         end;
         set(controls.gibbssamplingmenu,'Enable','on');
         GibbsTextFile = [DSGEModel.OutputDirectory '\BVAR-GibbsSummary-' DSGEModel.NameOfModel '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '-' num2str(NumPostDraws,'%0.0f') '.txt'];
         if FileExist(GibbsTextFile)==1;
            set(controls.bvargibbsresultsmenu,'Enable','on');
            if length(DSGEModel.BVARX)>0;
               set(controls.bvarrawdrawspsi,'Enable','on');
               set(controls.bvarpostdensitypsi,'Enable','on');
               set(controls.bvarpsimeanconvergence,'Enable','on');
               set(controls.bvarpsimedianconvergence,'Enable','on');
               if (isempty(DSGEModel.PredictedX)==1)&(isempty(DSGEModel.BVARX)==0)&(strcmp(DSGEModel.SubEndYear,DSGEModel.EndYear)==1)&(strcmp(DSGEModel.SubEndPeriod,DSGEModel.EndPeriod)==1);
                  set(controls.bvarpredict.original_posterior,'Enable','off');
                  set(controls.bvarpredict.annual_posterior,'Enable','off');
                  set(controls.bvarpredict.original_predevent,'Enable','off');
                  set(controls.bvarpredict.annual_predevent,'Enable','off');
               else;
                  set(controls.bvarpredict.original_posterior,'Enable','on');
                  set(controls.bvarpredict.original_predevent,'Enable','on');
                  if max(DSGEModel.annual(DSGEModel.BVARY))>1;
                     set(controls.bvarpredict.annual_posterior,'Enable','on');
                     set(controls.bvarpredict.annual_predevent,'Enable','on');
                  else;
                     set(controls.bvarpredict.annual_posterior,'Enable','off');
                     set(controls.bvarpredict.annual_predevent,'Enable','off');
                  end;
               end;
            else;
               set(controls.bvarrawdrawspsi,'Enable','off');
               set(controls.bvarpostdensitypsi,'Enable','off');
               set(controls.bvarpsimeanconvergence,'Enable','off');
               set(controls.bvarpsimedianconvergence,'Enable','off');
               set(controls.bvarpredict.original_posterior,'Enable','off');
               set(controls.bvarpredict.annual_posterior,'Enable','off');
               set(controls.bvarpredict.original_predevent,'Enable','off');
               set(controls.bvarpredict.annual_predevent,'Enable','off');
            end;
            set(controls.bvarrawdrawsomega,'Enable','on');
            set(controls.bvaromegameanconvergence,'Enable','on');
            set(controls.bvaromegamedianconvergence,'Enable','on');
            set(controls.bvarpostdensityomega,'Enable','on');
            set(controls.bvarrawdrawspi,'Enable','on');
            set(controls.bvarpimeanconvergence,'Enable','on');
            set(controls.bvarpimedianconvergence,'Enable','on');
            set(controls.bvarpostdensitypi,'Enable','on');
            set(controls.bvarmarglike,'Enable','on');
         else;
            set(controls.bvargibbsresultsmenu,'Enable','off');
            set(controls.bvarrawdrawspsi,'Enable','off');
            set(controls.bvarpredict.original_posterior,'Enable','off');
            set(controls.bvarpredict.annual_posterior,'Enable','off');
            set(controls.bvarpredict.original_predevent,'Enable','off');
            set(controls.bvarpredict.annual_predevent,'Enable','off');
            set(controls.bvarpostdensitypsi,'Enable','off');
            set(controls.bvarpsimeanconvergence,'Enable','off');
            set(controls.bvarpsimedianconvergence,'Enable','off');
            set(controls.bvarrawdrawsomega,'Enable','off');
            set(controls.bvaromegameanconvergence,'Enable','off');
            set(controls.bvaromegamedianconvergence,'Enable','off');
            set(controls.bvarpostdensityomega,'Enable','off');
            set(controls.bvarrawdrawspi,'Enable','off');
            set(controls.bvarpimeanconvergence,'Enable','off');
            set(controls.bvarpimedianconvergence,'Enable','off');
            set(controls.bvarpostdensitypi,'Enable','off');
            set(controls.bvarmarglike,'Enable','off');
         end;
      else;
         if FileExist(ModeFile)==1;
            if (isempty(DSGEModel.PredictedX)==1)&(isempty(DSGEModel.BVARX)==0)&(strcmp(DSGEModel.SubEndYear,DSGEModel.EndYear)==1)&(strcmp(DSGEModel.SubEndPeriod,DSGEModel.EndPeriod)==1);
               set(controls.bvarpredict.original_postmode,'Enable','off');
               set(controls.bvarpredict.annual_postmode,'Enable','off');
            else;
               set(controls.bvarpredict.original_postmode,'Enable','on');
               if max(DSGEModel.annual(DSGEModel.BVARY))>1;
                  set(controls.bvarpredict.annual_postmode,'Enable','on');
               else;
                  set(controls.bvarpredict.annual_postmode,'Enable','off');
               end;
            end;
            set(controls.gibbssamplingmenu,'Enable','on');
            GibbsTextFile = [DSGEModel.OutputDirectory '\BVAR-GibbsSummary-' DSGEModel.NameOfModel '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '-' num2str(NumPostDraws,'%0.0f') '.txt'];
            if FileExist(GibbsTextFile)==1;
               set(controls.bvargibbsresultsmenu,'Enable','on');
               if length(DSGEModel.BVARX)>0;
                  set(controls.bvarrawdrawspsi,'Enable','on');
                  set(controls.bvarpostdensitypsi,'Enable','on');
                  set(controls.bvarpsimeanconvergence,'Enable','on');
                  set(controls.bvarpsimedianconvergence,'Enable','on');
                  if (isempty(DSGEModel.PredictedX)==1)&(isempty(DSGEModel.BVARX)==0)&(strcmp(DSGEModel.SubEndYear,DSGEModel.EndYear)==1)&(strcmp(DSGEModel.SubEndPeriod,DSGEModel.EndPeriod)==1);
                     set(controls.bvarpredict.original_posterior,'Enable','off');
                     set(controls.bvarpredict.annual_posterior,'Enable','off');
                     set(controls.bvarpredict.original_predevent,'Enable','off');
                     set(controls.bvarpredict.annual_predevent,'Enable','off');
                  else;
                     set(controls.bvarpredict.original_posterior,'Enable','on');
                     set(controls.bvarpredict.original_predevent,'Enable','on');
                     if max(DSGEModel.annual(DSGEModel.BVARY))>1;
                        set(controls.bvarpredict.annual_posterior,'Enable','on');
                        set(controls.bvarpredict.annual_predevent,'Enable','on');
                     else;
                        set(controls.bvarpredict.annual_posterior,'Enable','off');
                        set(controls.bvarpredict.annual_predevent,'Enable','off');
                     end;
                  end;
               else;
                  set(controls.bvarrawdrawspsi,'Enable','off');
                  set(controls.bvarpredict.original_posterior,'Enable','off');
                  set(controls.bvarpredict.annual_posterior,'Enable','off');
                  set(controls.bvarpredict.original_predevent,'Enable','off');
                  set(controls.bvarpredict.annual_predevent,'Enable','off');
                  set(controls.bvarpostdensitypsi,'Enable','off');
                  set(controls.bvarpsimeanconvergence,'Enable','off');
                  set(controls.bvarpsimedianconvergence,'Enable','off');
               end;
               set(controls.bvarrawdrawsomega,'Enable','on');
               set(controls.bvaromegameanconvergence,'Enable','on');
               set(controls.bvaromegamedianconvergence,'Enable','on');
               set(controls.bvarpostdensityomega,'Enable','on');
               set(controls.bvarrawdrawspi,'Enable','on');
               set(controls.bvarpimeanconvergence,'Enable','on');
               set(controls.bvarpimedianconvergence,'Enable','on');
               set(controls.bvarpostdensitypi,'Enable','on');
               set(controls.bvarmarglike,'Enable','on');
            else;
               set(controls.bvargibbsresultsmenu,'Enable','off');
               set(controls.bvarrawdrawspsi,'Enable','off');
               set(controls.bvarpredict.original_posterior,'Enable','off');
               set(controls.bvarpredict.annual_posterior,'Enable','off');
               set(controls.bvarpredict.original_predevent,'Enable','off');
               set(controls.bvarpredict.annual_predevent,'Enable','off');
               set(controls.bvarpostdensitypsi,'Enable','off');
               set(controls.bvarpsimeanconvergence,'Enable','off');
               set(controls.bvarpsimedianconvergence,'Enable','off');
               set(controls.bvarrawdrawsomega,'Enable','off');
               set(controls.bvaromegameanconvergence,'Enable','off');
               set(controls.bvaromegamedianconvergence,'Enable','off');
               set(controls.bvarpostdensityomega,'Enable','off');
               set(controls.bvarrawdrawspi,'Enable','off');
               set(controls.bvarpimeanconvergence,'Enable','off');
               set(controls.bvarpimedianconvergence,'Enable','off');
               set(controls.bvarpostdensitypi,'Enable','off');
               set(controls.bvarmarglike,'Enable','off');
            end;
         else;
            set(controls.gibbssamplingmenu,'Enable','off');
            set(controls.bvargibbsresultsmenu,'Enable','off');
            set(controls.bvarrawdrawspsi,'Enable','off');
            set(controls.bvarpredict.original_posterior,'Enable','off');
            set(controls.bvarpredict.annual_posterior,'Enable','off');
            set(controls.bvarpredict.original_predevent,'Enable','off');
            set(controls.bvarpredict.annual_predevent,'Enable','off');
            set(controls.bvarpostdensitypsi,'Enable','off');
            set(controls.bvarpsimeanconvergence,'Enable','off');
            set(controls.bvarpsimedianconvergence,'Enable','off');
            set(controls.bvarrawdrawsomega,'Enable','off');
            set(controls.bvaromegameanconvergence,'Enable','off');
            set(controls.bvaromegamedianconvergence,'Enable','off');
            set(controls.bvarpostdensityomega,'Enable','off');
            set(controls.bvarrawdrawspi,'Enable','off');
            set(controls.bvarpimeanconvergence,'Enable','off');
            set(controls.bvarpimedianconvergence,'Enable','off');
            set(controls.bvarpostdensitypi,'Enable','off');
            set(controls.bvarmarglike,'Enable','off');
            set(controls.bvarpredict.original_postmode,'Enable','off');
            set(controls.bvarpredict.annual_postmode,'Enable','off');
         end;
%         set(controls.bvarforecast.postmode,'Enable','off');
%         set(controls.bvarforecast.annpostmode,'Enable','off');
         ModeTextFile = [DSGEModel.OutputDirectory '\PosteriorModeBVAR-' DSGEModel.NameOfModel '-' num2str(DSGEModel.PriorType,'%0.0f') '.' num2str(DSGEModel.OmegaPriorType,'%0.0f') '.txt'];
         if FileExist(ModeTextFile)==1;
            set(controls.bvarmoderesultsmenu,'Enable','on');
         else;
            set(controls.bvarmoderesultsmenu,'Enable','off');
         end;
      end;
   else;
      set(controls.gibbssamplingmenu,'Enable','off');
      set(controls.bvargibbsresultsmenu,'Enable','off');
      set(controls.bvarrawdrawspsi,'Enable','off');
      set(controls.bvarpredict.original_posterior,'Enable','off');
      set(controls.bvarpredict.annual_posterior,'Enable','off');
      set(controls.bvarpredict.original_predevent,'Enable','off');
      set(controls.bvarpredict.annual_predevent,'Enable','off');
      set(controls.bvarpostdensitypsi,'Enable','off');
      set(controls.bvarpsimeanconvergence,'Enable','off');
      set(controls.bvarpsimedianconvergence,'Enable','off');
      set(controls.bvarrawdrawsomega,'Enable','off');
      set(controls.bvaromegameanconvergence,'Enable','off');
      set(controls.bvaromegamedianconvergence,'Enable','off');
      set(controls.bvarpostdensityomega,'Enable','off');
      set(controls.bvarrawdrawspi,'Enable','off');
      set(controls.bvarpimeanconvergence,'Enable','off');
      set(controls.bvarpimedianconvergence,'Enable','off');
      set(controls.bvarpostdensitypi,'Enable','off');
      set(controls.bvarmarglike,'Enable','off');
      set(controls.bvarmodemenu,'Enable','off');
      set(controls.bvarpriordensitypsi,'Enable','off');
      set(controls.bvarpriordensitypi,'Enable','off');
      set(controls.bvarpriordensityomega,'Enable','off');
%      set(controls.bvarforecast.postmode,'Enable','off');
%      set(controls.bvarforecast.annpostmode,'Enable','off');
      set(controls.bvarpredict.original_postmode,'Enable','off');
      set(controls.bvarpredict.annual_postmode,'Enable','off');
      set(controls.bvarmoderesultsmenu,'Enable','off');
   end;
else;
   set(controls.viewdata,'Enable','off');
   set(controls.viewannualdata,'Enable','off');
   set(controls.viewtransdata,'Enable','off');
   set(controls.saveannualdata,'Enable','off');
   set(controls.gibbssamplingmenu,'Enable','off');
   set(controls.bvargibbsresultsmenu,'Enable','off');
   set(controls.bvarrawdrawspsi,'Enable','off');
   set(controls.bvarpredict.original_posterior,'Enable','off');
   set(controls.bvarpredict.annual_posterior,'Enable','off');
   set(controls.bvarpredict.original_predevent,'Enable','off');
   set(controls.bvarpredict.annual_predevent,'Enable','off');
   set(controls.bvarpostdensitypsi,'Enable','off');
   set(controls.bvarpsimeanconvergence,'Enable','off');
   set(controls.bvarpsimedianconvergence,'Enable','off');
   set(controls.bvarrawdrawsomega,'Enable','off');
   set(controls.bvaromegameanconvergence,'Enable','off');
   set(controls.bvaromegamedianconvergence,'Enable','off');
   set(controls.bvarpostdensityomega,'Enable','off');
   set(controls.bvarrawdrawspi,'Enable','off');
   set(controls.bvarpimeanconvergence,'Enable','off');
   set(controls.bvarpimedianconvergence,'Enable','off');
   set(controls.bvarpostdensitypi,'Enable','off');
   set(controls.bvarmarglike,'Enable','off');
   set(controls.bvarmodemenu,'Enable','off');
   set(controls.bvarpriordensitypsi,'Enable','off');
   set(controls.bvarpriordensitypi,'Enable','off');
   set(controls.bvarpriordensityomega,'Enable','off');
%   set(controls.bvarforecast.postmode,'Enable','off');
%   set(controls.bvarforecast.annpostmode,'Enable','off');
   set(controls.bvarpredict.original_postmode,'Enable','off');
   set(controls.bvarpredict.annual_postmode,'Enable','off');
   set(controls.bvarmoderesultsmenu,'Enable','off');
end;
if FileExist([pwd '\tmp\AiMErrorData.mat'])==1;
   dos(['del /Q "' pwd '\tmp\AiMErrorData.mat"']);
end;
if FileExist(DSGEModel.PriorFile)==1;
   set(controls.priorinfo,'Enable','on');
else;
   set(controls.priorinfo,'Enable','off');
end;
%
% check if we should display the dialog
%
if strcmp(selector,'init')==1;
   set(maingui,'Visible','on');
   drawnow;
   drawnow;
   drawnow;
%   refresh(maingui);
else;
   set(controls.open,'UserData',DSGEModel);
   set(controls.filemenu,'UserData',CurrINI);
end;
if nargout==1;
   YADAHandle = maingui;
end;
%
if strcmp(selector,'init')==1;
   waitfor(controls.leave,'UserData','done');
end;

%
% end of YADAGUI.m
%
