function PredictiveDistributionDLG(selector,DSGEModel,CurrINI,MeanPrediction,Quantiles,KernelX,KernelY,NameStr,ModelStr,AnnualStr,UData)
% PredictiveDistributionDLG: Displays predictive distributions of the observed variables along with the mean
%                            predictions and when possible the observed values.
%
% USAGE:
%
%       PredictiveDistributionDLG(selector,DSGEModel,CurrINI,MeanPrediction,Quantiles,KernelX,KernelY,Y,NameStr,ModelStr,AnnualStr,UData)
%
% REQUIRED INPUT: selector (string vector) taking on the values "init", "showgraph", and "done".
%
% OPTIONAL INPUT: DSGEModel (structure) whose fields contain all required information
%                           about the model, such as input files, variable and sample
%                           data. Actual observations are not stored in this file.
%
%                 CurrINI (structure), with initialization information.
%
%                 MeanPrediction (matrix) of dimension nxh with the mean predictions.
%
%                 Quantiles (structure) of dimension NumQuants where each has a field called "Quantile" which
%                           is an nxh matrix with the quantiles of the prediction paths. The second field
%                           is "percent" that gives the percentile value as a string vector.
%
%                 KernelX (matrix) of dimension (n x NumGridPoints x h) with the x-axis values of the
%                           kernel density estimates of the marginal predictive densities.
%
%                 KernelY (matrix) of dimension (n x NumGridPoints x h) with the y-axis values of the
%                           kernel density estimates of the marginal predictive densities.
%
%                 NameStr (string vector) taking on the values "Posterior Mode", "Initial Values", or "".
%
%                 ModelStr (string vector) taking on the values "DSGE" or "BVAR".
%
%                 AnnualStr (string vector) taking on the values "original", "annual", or "transformed".
%
%                 UData (structure) with data on uncertainty measures for the variables. The field names depend
%                           on which model is defined through the ModelStr input.
%
%
%                       Written by: Anders Warne
%                                   New Area Wide Model Project
%                                   DG-R/EMO
%                                   European Central Bank (ECB)
%                                   Email: anders.warne@ecb.europa.eu
%                                   Copyright © 2006-2009 European Central Bank.
%
%                       First version: February 21, 2007.
%                        This version: March 3, 2009.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LICENSE INFORMATION:
%
%      YADA is free software: you can redistribute it and/or modify
%      it under the terms of the GNU General Public License as published by
%      the Free Software Foundation, either version 3 of the License, or
%      (at your option) any later version.
%
%      This program is distributed in the hope that it will be useful,
%      but WITHOUT ANY WARRANTY; without even the implied warranty of
%      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%      GNU General Public License for more details.
%
%      You should have received a copy of the GNU General Public License
%      along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%      YADA is released under the GNU General Public License, Version 3,
%      29 June 2007 <http://www.gnu.org/licenses/>. The current release of
%      the program was last modified by the ECB on the "This version" date
%      above.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CHANGELOG:
%
% * 22-02-2007: Changed the name of the main dialog.
%
% * 23-02-2007: The dialog can now display decompositions of the prediction uncertainty.
%
% * 26-02-2007: The color ordering for the confidence bands was changed from light->dark to dark->light as the
%               bands become wider.
%
% * 27-02-2007: Added the call "SetAxesFonts(CurrINI,legHandle)" after legend call.
%
% * 28-02-2007: Include the use of the DSGEModel field "ConfidenceBandBaseColor".
%
% * 01-03-2007: Made sure that the zero horizontal line cobvers the full width of the plot.
%
% * 09-03-2007: Fixed a typo in the dialog name.
%
% * 03-05-2007: Fixed a few DateVector related bugs when plotting the observed variables.
%
% * 10-05-2007: Made sure that the function plots the bars from the shock and parameter uncertainty
%               correctly for the Bayesian VAR model.
%
% * 09-11-2007: Added the call to "SetXTickIntegers".
%
% * 10-01-2008: Changed the last drawnow call to pause(0.02).
%
% * 15-01-2008: Added the code needed to select the sample.
%
% * 15-02-2008: Fixed a bug when DateVector doesn't cover the forecast sample.
%
% * 02-05-2008: Allow AnnualStr to be "transformed".
%
% * 23-05-2008: Updated the documentation.
%
% * 11-07-2008: Changed the ordering of colors for confidence bands.
%
% * 19-12-2008: Updated the documentation.
%
% * 21-01-2009: Added code to let the predictive distribution be adjusted so that the mean
%               is equal to the realized values.
%
% * 03-03-2009: Added the input variables "KernelX" and "KernelY" for plotting kernel density
%               estimates of the marginal predictive densities.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

if strcmp(selector,'init')==1;
   DSGEModel.MeanPrediction = MeanPrediction;
   DSGEModel.Quantiles = Quantiles;
   DSGEModel.NameStr = NameStr;
   DSGEModel.ModelStr = ModelStr;
   DSGEModel.AnnualStr = AnnualStr;
   if (nargin==9)&(isempty(UData)==0);
      DSGEModel.UData = UData;
   else;
      DSGEModel.UData = [];
   end;
   %
   % Check where the sample of prediction data actually begins
   %
   [PredStartYear,PredStartPeriod,PredEndYear,PredEndPeriod,DSGEModel.PredDateVector,DSGEModel.PredSampleStrMat] = CreatePredictionSample(DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency,size(MeanPrediction,2));
   %
   % check if we have observations for the whole prediction sample
   %
   [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
   if (LastPeriod+length(DSGEModel.PredDateVector)<=size(DSGEModel.Y,2));
      DSGEModel.ShowAdjustOption = 1;
      AddHeight = 35;
   else;
      DSGEModel.ShowAdjustOption = 0;
      AddHeight = 0;
   end;
   if isempty(KernelX)==0;
      DSGEModel.ShowKernel = 1;
      DSGEModel.KernelX = KernelX;
      DSGEModel.KernelY = KernelY;
      AddKHeight = 25+(10*(1-DSGEModel.ShowAdjustOption));
   else;
      DSGEModel.ShowKernel = 0;
      AddKHeight = 0;
   end;
else
   PredictiveDistributionGUI = findobj('Type','figure','Tag','PredictiveDistributionDLG');
   PredictiveControls = get(PredictiveDistributionGUI,'UserData');
   CurrINI = get(PredictiveControls.varnames,'UserData');
   DSGEModel = get(PredictiveControls.variables,'UserData');
end;
%
% Set screen size directly instead of using
% get(0,'ScreenSize')!
%
switch selector;
   case 'init';
      PredictiveDistributionGUI = figure('Color',get(0,'defaultuicontrolbackgroundcolor'), ...
         'FileName','PredictiveDistributionDLG.m', ...
         'MenuBar','none', ...
         'PaperUnits','points', ...
         'Units','pixels', ...
         'Position',[(CurrINI.scrsz(3)-500)/2 (CurrINI.scrsz(4)-140-AddHeight-AddKHeight)/2 500 140+AddHeight+AddKHeight], ...
         'Tag','PredictiveDistributionDLG', ...
         'Visible','off', ...
         'Resize','off', ...
         'Name',['Predictive Distributions With ' ModelStr ' Model - ' NameStr], ...
         'NumberTitle','off', ...
         'CloseRequestFcn','PredictiveDistributionDLG done', ...
         'ToolBar','none');
      %
      if isempty(NameStr)==1;
         set(PredictiveDistributionGUI,'Name',['Predictive Distribution With ' ModelStr ' Model']);
      end;
      %
      if MatlabNumber>=7.0;
         set(PredictiveDistributionGUI,'DockControl','off');
      end;
      %
      % Outer axis
      %
      AxesBox([2 2 498 130+AddHeight+AddKHeight],'Multistep Unconditional Predictions',45,[0.5 1],'on',CurrINI);
      %
      PredictiveControls.sample = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 85+AddHeight+AddKHeight 360 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'String',['Prediction Sample: ' PredStartYear ':' PredStartPeriod ' - ' PredEndYear ':' PredEndPeriod], ...
         'HorizontalAlignment','left', ...
         'Tag','SampleText');
      %
      if (strcmp(lower(AnnualStr),'original')==1)|(strcmp(lower(AnnualStr),'transformed')==1);
         if DSGEModel.KalmanFirstObservation>1;
            [NewStartYear,NewStartPeriod] = AdjustSampleStart(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.DataFrequency,DSGEModel.KalmanFirstObservation-1);
         else;
            NewStartYear = DSGEModel.SubBeginYear;
            NewStartPeriod = DSGEModel.SubBeginPeriod;
         end;
      else;
         [NewStartYear,NewStartPeriod] = AdjustSampleStart(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.DataFrequency,max(DSGEModel.annual)+DSGEModel.KalmanFirstObservation-2);
      end;
      %
      OldDSGEModel = DSGEModel;
      DSGEModel.SubBeginYear = NewStartYear;
      DSGEModel.SubBeginPeriod = NewStartPeriod;
      [FirstPeriod,LastPeriod,SampleStrMat] = CreateSubSample(DSGEModel);
      DSGEModel = OldDSGEModel;
      %
      % check if we need to change the sample from the top
      %
      if strcmp(lower(AnnualStr),'transformed')==1;
         [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y',DSGEModel.YTransformation);
         T2 = size(YData,1);
         if DSGEModel.T-T2>FirstPeriod+DSGEModel.KalmanFirstObservation-1;
            SampleStrMat = SampleStrMat(DSGEModel.T-T2-(FirstPeriod+DSGEModel.KalmanFirstObservation-1):size(SampleStrMat,1),:);
         end;
      end;
      %
      % data sample
      %
      PredictiveControls.startdatatext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 50+AddHeight+AddKHeight 180 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'String','Start period for variable:', ...
         'HorizontalAlignment','left', ...
         'Tag','StartDataText');
      %
      PredictiveControls.startdata = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[210 55+AddHeight+AddKHeight 155 20], ...
         'Style','popupmenu', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'String',SampleStrMat, ...
         'HorizontalAlignment','center', ...
         'Tag','StartDataPopup',...
         'Value',1);
      %
      % Select variable
      %
      PredictiveControls.variables = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 15+AddHeight+AddKHeight 180 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'UserData',DSGEModel, ...
         'String','Select variable', ...
         'HorizontalAlignment','left', ...
         'Tag','VariableNamesText');
      %
      PredictiveControls.varnames = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[210 20+AddHeight+AddKHeight 155 20], ...
         'Style','popupmenu', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'UserData',CurrINI, ...
         'String',DSGEModel.VariableNames, ...
         'HorizontalAlignment','center', ...
         'Tag','VariableNamesPopup',...
         'Value',1);
      %
      if strcmp(ModelStr,'BVAR')==1;
         set(PredictiveControls.varnames,'String',DSGEModel.VariableNames(DSGEModel.BVARY,:));
      end;
      %
      if DSGEModel.ShowKernel==1;
         PredictiveControls.ShowKernelDensity = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[24 15+min(AddHeight,25) 341 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Value',0, ...
            'String','Show kernel density estimates of marginal predictive densities', ...
            'HorizontalAlignment','left', ...
            'Tag','ShowKernelDensityCheckbox');
      else;
         PredictiveControls.ShowKernelDensity = [];
      end;
      %
      if DSGEModel.ShowAdjustOption==1;
         PredictiveControls.AdjustMean = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[24 15 341 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Value',0, ...
            'String','Set mean of predictive dist. equal to realized values', ...
            'HorizontalAlignment','left', ...
            'Tag','AdjustMeanCheckbox');
      else;
         PredictiveControls.AdjustMean = [];
      end;
      %
      % Create graph button
      %
      PredictiveControls.show = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[395 55 90 20], ...
         'String','Display', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'CallBack','PredictiveDistributionDLG showgraph', ...
         'Enable','on', ...
         'Tag','Done');
      %
      %  Done button
      %
      PredictiveControls.done = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[395 20 90 20], ...
         'String','Done', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'CallBack','PredictiveDistributionDLG done', ...
         'Enable','on', ...
         'UserData','waiting', ...
         'Tag','Done');

      set(PredictiveDistributionGUI,'UserData',PredictiveControls,...
         'HandleVisibility','callback');
   case 'showgraph'
      VariableValue = get(PredictiveControls.varnames,'Value');
      VariableStr = get(PredictiveControls.varnames,'String');
      CurrVariable = StringTrim(VariableStr(VariableValue,:));
      if VariableValue<size(VariableStr,1);
         set(PredictiveControls.varnames,'Value',VariableValue+1);
      else;
         set(PredictiveControls.varnames,'Value',1);
      end;
      %
      % create a vector with dates
      %
      DateVector = MakeDateVector(DSGEModel.BeginYear,DSGEModel.BeginPeriod,DSGEModel.EndYear,DSGEModel.EndPeriod,DSGEModel.DataFrequency);
      [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
      FirstPeriod = FirstPeriod+DSGEModel.KalmanFirstObservation+get(PredictiveControls.startdata,'Value')-2;
      %
      % create the figure
      %
      FigHandle = figure('Visible','off', ...
                     'Position',[(CurrINI.scrsz(3)-750)/2 (CurrINI.scrsz(4)-500)/2 750 500], ...
                     'Tag',[CurrVariable '-' DSGEModel.ModelStr], ...
                     'Name',['Multistep Predictions in ' DSGEModel.ModelStr ' Model - ' CurrVariable]);
      %
      SetFigureProperties(FigHandle,CurrINI);
      %
      % check if we should adjust the mean to be equal to the actual data
      %
      if (isempty(PredictiveControls.AdjustMean)==0)&(get(PredictiveControls.AdjustMean,'Value')==1);
         if strcmp(DSGEModel.AnnualStr,'original')==1;
            if strcmp(DSGEModel.ModelStr,'DSGE')==1;
               y = DSGEModel.Y(VariableValue,LastPeriod+1:LastPeriod+length(DSGEModel.PredDateVector));
            else;
               y = DSGEModel.Y(DSGEModel.BVARY(VariableValue),LastPeriod+1:LastPeriod+length(DSGEModel.PredDateVector));
            end;
         elseif strcmp(DSGEModel.AnnualStr,'annual')==1;
            Y = Annualize(DSGEModel.Y(:,FirstPeriod:min(size(DSGEModel.Y,2),LastPeriod+length(DSGEModel.PredDateVector))),DSGEModel.annual,DSGEModel.annualscale);
            if strcmp(DSGEModel.ModelStr,'DSGE')==1;
               y = Y(VariableValue,size(Y,2)-length(DSGEModel.PredDateVector)+1:size(Y,2));
            else;
               y = Y(DSGEModel.BVARY(VariableValue),size(Y,2)-length(DSGEModel.PredDateVector)+1:size(Y,2));
            end;
         else;
            %
            % we're using the transformed data
            %
            T1 = min(size(DSGEModel.Y,2),LastPeriod+length(DSGEModel.PredDateVector));
            [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y(:,1:T1)',DSGEModel.YTransformation);
            Y = YData';
            T2 = size(Y,2);
            if T2==T1;
               Y = Y(:,FirstPeriod:T1);
            else;
               if FirstPeriod-(T1-T2)>=1;
                  Y = Y(:,FirstPeriod-(T1-T2):T1);
               end;
            end;
            if strcmp(DSGEModel.ModelStr,'DSGE')==1;
               y = Y(VariableValue,size(Y,2)-length(DSGEModel.PredDateVector)+1:size(Y,2));
            else;
               y = Y(DSGEModel.BVARY(VariableValue),size(Y,2)-length(DSGEModel.PredDateVector)+1:size(Y,2));
            end;
         end;
         AddOnVector = y-DSGEModel.MeanPrediction(VariableValue,:);
      else;
         AddOnVector = zeros(1,length(DSGEModel.PredDateVector));
      end;
      %
      % first we plot the predictive bounds
      %
      NumBounds = floor(length(DSGEModel.Quantiles)/2);
      Handles = [];
      LegendStr = '';
      for i=1:NumBounds;
         Lower = DSGEModel.Quantiles(i).Quantile(VariableValue,:)+AddOnVector;
         Upper = DSGEModel.Quantiles(length(DSGEModel.Quantiles)-i+1).Quantile(VariableValue,:)+AddOnVector;
         PatchColor = ((1+(2*(i-1)))/length(DSGEModel.Quantiles))*DSGEModel.ConfidenceBandBaseColor;
         ConfBound = DSGEModel.Quantiles(length(DSGEModel.Quantiles)-i+1).percent-DSGEModel.Quantiles(i).percent;
         ConfPatch = patch([DSGEModel.PredDateVector fliplr(DSGEModel.PredDateVector)],[Upper fliplr(Lower)],PatchColor);
         set(ConfPatch,'FaceColor',PatchColor,'EdgeColor',PatchColor);
         hold('on');
         Handles = [Handles ConfPatch];
         LegendStr = strvcat(LegendStr,[num2str(ConfBound,'%0.0f') ' confidence']);
      end;
      set(gca,'Layer','Top');
      %
      % next we plot the observed variable
      %
      if strcmp(DSGEModel.AnnualStr,'original')==1;
         %
         % we're using the original data
         %
         if strcmp(DSGEModel.ModelStr,'DSGE')==1;
            YHandle = plot(DateVector(FirstPeriod:min(size(DSGEModel.Y,2),LastPeriod+length(DSGEModel.PredDateVector))),DSGEModel.Y(VariableValue,FirstPeriod:min(size(DSGEModel.Y,2),LastPeriod+length(DSGEModel.PredDateVector))),'+-','Color',[0.75 0 0],'LineWidth',2);
         else;
            YHandle = plot(DateVector(FirstPeriod:min(size(DSGEModel.Y,2),LastPeriod+length(DSGEModel.PredDateVector))),DSGEModel.Y(DSGEModel.BVARY(VariableValue),FirstPeriod:min(size(DSGEModel.Y,2),LastPeriod+length(DSGEModel.PredDateVector))),'+-','Color',[0.75 0 0],'LineWidth',2);
         end;
      elseif strcmp(DSGEModel.AnnualStr,'annual')==1;;
         %
         % we're using the annualized data
         %
         Y = Annualize(DSGEModel.Y(:,FirstPeriod:min(size(DSGEModel.Y,2),LastPeriod+length(DSGEModel.PredDateVector))),DSGEModel.annual,DSGEModel.annualscale);
         if strcmp(DSGEModel.ModelStr,'DSGE')==1;
            YHandle = plot(DateVector(1,max(DSGEModel.annual)+FirstPeriod-1:min(size(DSGEModel.Y,2),LastPeriod+length(DSGEModel.PredDateVector))),Y(VariableValue,:),'+-','Color',[0.75 0 0],'LineWidth',2);
         else;
            YHandle = plot(DateVector(1,max(DSGEModel.annual)+FirstPeriod-1:min(size(DSGEModel.Y,2),LastPeriod+length(DSGEModel.PredDateVector))),Y(DSGEModel.BVARY(VariableValue),:),'+-','Color',[0.75 0 0],'LineWidth',2);
         end;
      else;
         %
         % we're using the transformed data
         %
         T1 = min(size(DSGEModel.Y,2),LastPeriod+length(DSGEModel.PredDateVector));
         OldDateVector = DateVector;
         DateVector = DateVector(FirstPeriod:T1);
         [YTStatus,YData,ErrorStr,HeaderStr] = CalcTransformData(DSGEModel.VariableNames,DSGEModel.Y(:,1:T1)',DSGEModel.YTransformation);
         Y = YData';
         T2 = size(Y,2);
         if T2==T1;
            Y = Y(:,FirstPeriod:T1);
         else;
            if FirstPeriod-(T1-T2)>=1;
               Y = Y(:,FirstPeriod-(T1-T2):T1);
            else;
               DateVector = DateVector(T1-T2+1:T1);
            end;
         end;
         if strcmp(DSGEModel.ModelStr,'DSGE')==1;
            YHandle = plot(DateVector,Y(VariableValue,:),'+-','Color',[0.75 0 0],'LineWidth',2);
         else;
            YHandle = plot(DateVector,Y(DSGEModel.BVARY(VariableValue),:),'+-','Color',[0.75 0 0],'LineWidth',2);
         end;
         DateVector = OldDateVector(T1-T2+1:length(OldDateVector));
      end;
      hold('on');
      %
      % plot the mean prediction
      %
      if (isempty(PredictiveControls.AdjustMean)==0)&(get(PredictiveControls.AdjustMean,'Value')==1);
         PredHandle = [];
         PredStr = '';
      else;
         PredHandle = plot(DSGEModel.PredDateVector,DSGEModel.MeanPrediction(VariableValue,:),'--','Color',[0 0 0.75],'LineWidth',2);
         PredStr = 'Mean predictions';
      end;
      hold('on');
      Handles = [YHandle PredHandle Handles];
      LegendStr = strvcat(CurrVariable,PredStr,LegendStr);
      %
      ylim = get(gca,'YLim');
      add_on = 0.1*(ylim(2)-ylim(1));
      ylim = [ylim(1)-add_on ylim(2)+add_on];
      if (strcmp(lower(DSGEModel.AnnualStr),'original')==1)|(strcmp(lower(DSGEModel.AnnualStr),'transformed')==1);
         set(gca,'YLim',ylim,'XLim',[DateVector(FirstPeriod) max(DSGEModel.PredDateVector)]);
      else;
         set(gca,'YLim',ylim,'XLim',[DateVector(max(DSGEModel.annual)+FirstPeriod-1) max(DSGEModel.PredDateVector)]);
      end;
      %
      % add a vertical line from the forecast point
      %
      fp = plot((((3*DateVector(LastPeriod))-DateVector(LastPeriod-1))/2)*[1 1],ylim,':','Color',[0 0 0]);
      hold('on');
      %
      if (ylim(1)<0)&(ylim(2)>0);
         %
         % add a zero line
         %
         zl = plot(get(gca,'XLim'),[0 0],'-','Color',[0 0 0]);
      else;
         zl = [];
      end;
      %
      if isempty(PredHandle)==0;
         set(gca,'Children',[PredHandle;YHandle;zl;fp;fliplr(Handles(3:length(Handles)))']);
      else;
         set(gca,'Children',[YHandle;zl;fp;fliplr(Handles(2:length(Handles)))']);
      end;
      %
      if isempty(DSGEModel.NameStr)==0;
         SetAxesFonts(CurrINI,'Title',[CurrVariable ' (' DSGEModel.AnnualStr ' data) and out-of-sample prediction paths - ' lower(DSGEModel.NameStr) ' of the parameters']);
      else;
         SetAxesFonts(CurrINI,'Title',[CurrVariable ' (' DSGEModel.AnnualStr ' data) and out-of-sample prediction paths']);
      end;
      hold('off');
      %
      % add the legend
      %
      legHandle = legend(Handles,LegendStr,2);
      SetAxesFonts(CurrINI,legHandle);
      %
      SetXTickIntegers(gca);
      %
      SetToolbarImages(FigHandle,CurrINI.images);
      TopFigHandle = FigHandle;
      %
      % check if we should make another figure
      %
      if isempty(DSGEModel.UData)==0;
         %
         % create the figure
         %
         FigHandle = figure('Visible','off', ...
                        'Position',[((CurrINI.scrsz(3)-750)/2)+22 ((CurrINI.scrsz(4)-500)/2)-22 750 500], ...
                        'Tag',[CurrVariable '-' DSGEModel.ModelStr], ...
                        'Name',['Prediction Uncertainty Decompositions in ' DSGEModel.ModelStr ' Model - ' CurrVariable]);
         %
         SetFigureProperties(FigHandle,CurrINI);
         %
         %
         if strcmp(DSGEModel.ModelStr,'DSGE')==1;
            Ydata = [DSGEModel.UData.MeasureVar(VariableValue,:);DSGEModel.UData.StateVar(VariableValue,:);DSGEModel.UData.ShockVar(VariableValue,:);DSGEModel.UData.ParameterVar(VariableValue,:)];
            ColorMat = [0.5 0.5 0.5;0 0 0.75;0.5 0.75 1;0.75 0 0];
         else;
            Ydata = [DSGEModel.UData.ShockVar(VariableValue,:);DSGEModel.UData.ParameterVar(VariableValue,:)];
            ColorMat = [0.5 0.75 1;0.75 0 0];
         end;
         BarVector = (1:size(Ydata,2));
         if MatlabNumber>=7.0;
            %
            % make sure the bars are written as patches
            %
            BarHandles = bar('v6',BarVector',Ydata','stacked');
         else;
            BarHandles = bar(BarVector',Ydata','stacked');
         end;
         %
         for i=1:length(BarHandles);
            set(BarHandles(i),'FaceColor',ColorMat(i,:),'EdgeColor',ColorMat(i,:));
         end;
         %
         set(gca,'YLim',[0 100],'Layer','Top');
         %
         SetAxesFonts(CurrINI,'Title',['Decomposition of Prediction Uncertainty for ' CurrVariable],'XLabel','Prediction Horizon','YLabel','Percent');
         %
         % add the legend
         %
         if strcmp(DSGEModel.ModelStr,'DSGE')==1;
            legHandle = legend(BarHandles,strvcat('Measurement','Current State','Shocks','Parameter'),-1);
         else;
            legHandle = legend(BarHandles,strvcat('Shocks','Parameter'),-1);
         end;
         SetAxesFonts(CurrINI,legHandle);
         %
         SetToolbarImages(FigHandle,CurrINI.images);
         PredFigHandle = FigHandle;
      else;
         PredFigHandle = [];
      end;
      %
      if (ishandle(PredictiveControls.ShowKernelDensity)==1)&(get(PredictiveControls.ShowKernelDensity,'Value')==1);
         %
         % the prediction sample date strings are located in: DSGEModel.PredSampleStrMat
         %
         [n,NumGridPoints,h] = size(DSGEModel.KernelX);
         %
         % get the observed data and check if we can use it
         %
         y = get(YHandle,'YData');
         DateVector = get(YHandle,'XData');
         %
         % find the position in DateVector that corresponds to the first obs in PredDateVector
         %
         PredPos = (DateVector==DSGEModel.PredDateVector(1)).*(1:length(DateVector));
         PredPos = PredPos(PredPos>0);
         if isempty(PredPos)==0;
            y = y(PredPos:length(y));
            if length(y)<h;
               y = [y NaN*ones(1,h-length(y))];
            end;
         else;
            y = [];
         end;
         %
         % check how many plots we should make
         %
         NumPlots = 0;
         for i=1:h;
            if isequal(DSGEModel.KernelX(VariableValue,:,i),zeros(1,NumGridPoints))==0;
               NumPlots = NumPlots+1;
            end;
         end;
         NumFigs = ceil(NumPlots/16);
         if NumFigs==1;
            [NumRows,NumCols] = VillaniConstructOptimalSubplot(NumPlots);
         elseif NumFigs>1;
            NumRows = 4;
            NumCols = 4;
         end;
         CurrPlot = 0;
         MadePlots = 0;
         pos = [(CurrINI.scrsz(3)-1000)/2 (CurrINI.scrsz(4)-680)/2 1000 650];
         %
         for i=1:NumFigs;
            if i>1;
               pos(1) = pos(1)+22;
               pos(2) = pos(2)-22;
               if pos(1)+1000>CurrINI.scrsz(3);
                  pos(1) = 0;
               end;
               if pos(2)<=32;
                  pos(2) = CurrINI.scrsz(4)-700;
               end;
            end;
            FigHandles{i} = figure('Visible','off','Position',pos);
            if NumFigs==1;
               set(FigHandles{i},'Name',['Marginal Predictive Densities For - ' CurrVariable]);
            else;
               set(FigHandles{i},'Name',['Marginal Predictive Densities For - Figure ' num2str(i,'%0.0f') ' - ' CurrVariable]);
            end;
            SetFigureProperties(FigHandles{i},CurrINI);
            %
            k = 0;
            DataHandle = [];
            DataStr = '';
            for r=1:NumRows;
               for c=1:NumCols;
                  if MadePlots<NumPlots;
                     CurrPlot = CurrPlot+1;
                     while isequal(DSGEModel.KernelX(VariableValue,:,CurrPlot),zeros(1,NumGridPoints))==1;
                        CurrPlot = CurrPlot+1;
                     end;
                     k = k+1;
                     MadePlots = MadePlots+1;
                     %
                     subplot(NumRows,NumCols,k);
                     %
                     % graph the predictive density
                     %
                     PredDensityHandle = plot(DSGEModel.KernelX(VariableValue,:,CurrPlot)+AddOnVector(CurrPlot),DSGEModel.KernelY(VariableValue,:,CurrPlot),'-','Color',[0 0.25 0],'LineWidth',2);
                     hold('on');
                     %
                     SetAxesFonts(CurrINI,'Title',[CurrVariable ' - ' DSGEModel.PredSampleStrMat(CurrPlot,:)]);
                     %
                     % deal with axis limits
                     %
                     axis('tight');
                     xlim = [min(DSGEModel.KernelX(VariableValue,:,CurrPlot)) max(DSGEModel.KernelX(VariableValue,:,CurrPlot))];
                     set(gca,'XLim',xlim);
                     %
                     ylim = [0 1.2*max(DSGEModel.KernelY(VariableValue,:,CurrPlot))];
                     %
                     % display the mean prediction
                     %
                     if (isempty(PredictiveControls.AdjustMean)==0)&(get(PredictiveControls.AdjustMean,'Value')==1);
                        MeanPredHandle = plot((DSGEModel.MeanPrediction(VariableValue,CurrPlot)+AddOnVector(CurrPlot))*ones(1,2),ylim,'-.','Color',[0.75 0 0],'LineWidth',2);
                        MeanStr = 'Observation';
                     else;
                        %
                        %
                        if (isempty(y)==0)&(isnan(y(CurrPlot))==0);
                           DataHandle = plot(y(CurrPlot)*ones(1,2),ylim,'-.','Color',[0.75 0 0],'LineWidth',2);
                           hold('on');
                           DataStr = 'Observation';
                        end;
                        MeanPredHandle = plot(DSGEModel.MeanPrediction(VariableValue,CurrPlot)*ones(1,2),ylim,'--','Color',[0 0 0.75],'LineWidth',2);
                        MeanStr = 'Mean';
                     end;
                     hold('on');
                     %
                     x_lim = get(gca,'XLim');
                     add_x = 0.1*(xlim(2)-xlim(1));
                     x_lim = [xlim(1)-add_x xlim(2)+add_x];
                     %
                     set(gca,'XLim',x_lim,'YLim',ylim);
                     hold('off');
                  end;
               end;
            end;
            legHandle = legend([PredDensityHandle MeanPredHandle DataHandle],strvcat('Density',MeanStr,DataStr));
            %
            SetAxesFonts(CurrINI,legHandle);
            %
            % transform units temporarily into pixels
            %
            OldAxesUnits = get(gca,'Units');
            OldLegUnits = get(legHandle,'Units');
            set(gca,'Units','pixels');
            set(legHandle,'Units','pixels');
            %
            % check if we can move legend
            %
            LegPos = get(legHandle,'Position');
            AxPos = get(gca,'Position');
            if LegPos(1)<AxPos(1)+AxPos(3);
               if AxPos(1)+AxPos(3)+10+LegPos(3)<1000;
                  LegPos(1) = AxPos(1)+AxPos(3)+10;
                  set(legHandle,'Position',LegPos);
               end;
            end;
            set(gca,'Units',OldAxesUnits);
            set(legHandle,'Units',OldLegUnits);
            %
            % Fix the toolbar cdata
            %
            SetToolbarImages(FigHandles{i},CurrINI.images);
            %
            % Display the current figure
            %
            set(FigHandles{i},'Visible','on','CloseRequestFcn','delete(gcf); drawnow; pause(0.02);');
            drawnow;
            pause(0.02);
         end;
      end;
      %
      if isempty(PredFigHandle)==0;
         set(PredFigHandle,'Visible','on','CloseRequestFcn','delete(gcf); drawnow; pause(0.02);');
         drawnow;
         pause(0.02);
      end;
      %
      set(TopFigHandle,'Visible','on','CloseRequestFcn','delete(gcf); drawnow; pause(0.02);');
      drawnow;
      pause(0.02);
   case 'done'
      set(PredictiveControls.done,'UserData','done');
      delete(PredictiveDistributionGUI);
      drawnow;
      pause(0.02);
end;
%
if strcmp(selector,'init')==1;
   set(PredictiveDistributionGUI,'Visible','on');
   drawnow;
   if MatlabNumber>=7;
      uicontrol(PredictiveControls.done);
   end;
   waitfor(PredictiveControls.done,'UserData','done');
end;

%
% end of PredictiveDistributionDLG.m
%
