function ObsVarDecompDLG(selector,StateVarStructure,NameStr,AnnualStr,CurrINI,DSGEModel)
% ObsVarDecompDLG: Displays graphs of observed variables decomposition.
%
% USAGE:
%
%       ObsVarDecompDLG(selector,StateVarStructure,NameStr,CurrINI,DSGEModel)
%
% REQUIRED INPUT: selector (string vector) taking on the values "init", "samplebegin", "sampleend", "fixcontrols",
%                                   "fixsmall", "showgraph", and "done".
%
% OPTIONAL INPUT: StateVarStructure (structure)  with fields "Y", "Yhat" containing the observed variables and
%                                   the 1-step ahead forecasts of these, "Ksitt1", "Ksitt", and "KsitT" with
%                                   the forecasted, updated, and smoothed values for the state variables. Furthermore,
%                                   the field "MaxEigenvalue" contains the largest eigenvalue of the state transition
%                                   matrix F, "etatT" the smooth projections of the unique state shocks, "wtT" the
%                                   smooth projections of the measurement errors, and "wtNames" the names of the
%                                   measurement errors (determined directly from the observed variable's names. The
%                                   field "wthT" contains all the measurement errors. Furthermore, "TrainSample" is
%                                   a boolean variable that indicates if a training sample was employed for the
%                                   Kalman filter. The field "X" holds the exogneous variables, while the field
%                                   "XiInit" contains the matrix with typical element H'*(F^t)*Ksi0T that is used
%                                   for observed variable decompositions. Similarly, the field "etaDecomp" contains
%                                   a 3D matrix with the parts of the observed variable decomposition that are explained
%                                   by the q economic shocks. The field "KeepVar" contains the column number of B0
%                                   that are non-zero. The parameter matrices of the measurement equation are given by
%                                   the fields "A", "H", and "R", while the fields "F" a "B0" contain the parameter
%                                   matrices of the state equation.
%
%                 NameStr (string vector) taking on the values "Posterior Mode" or "Initial Values".
%
%                 AnnualStr (string vector) taking on the values "Original" or "Annualized".
%
%                 CurrINI (structure), with initialization information.
%
%                 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.
%
% NOTE: When selector = "init", then all optional input arguments are required!
%
%
%                       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: December 5, 2006.
%                        This version: February 25, 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:
%
% * 06-12-2006: Made sure that removed B0 columns and estimated shocks is taken into account.
%
% * 03-01-2007: Fixed the text string for selecting variable.
%
% * 04-01-2007: Updated the documentation.
%
% * 05-01-2007: Fixed a bug that made Ymat contain rows of zeros for shock groups that are zero because
%               all individual shocks are zero by assumption.
%
% * 23-01-2007: Added the input variable "AnnualStr".
%
% * 25-01-2007: Fixed a bug related to annualization. Made sure that the "Annualize" function receives
%               the relevant terms of the DSGEModel.annualscale vector.
%
% * 20-02-2007: Added the options for selecting a sub-sample in the graph.
%
% * 27-02-2007: Added the call "SetAxesFonts(CurrINI,legHandle)" after the legend call.
%
% * 01-03-2007: Added the possibility of decomposing the shock groups into the individual shocks.
%
% * 07-03-2007: Added the possibility to plot multiple decompositions of the shock groups into individual
%               shocks on the same figure and to automatically save the figures into "eps".
%
% * 16-03-2007: The legend is now placed in the upper left corner.
%
% * 03-09-2007: It is now also possible to save the decomposition to file.
%
% * 04-09-2007: Fixed a bug when initializing "ShockMatrix". The setfield calls were changed to eval
%               calls.
%
% * 29-10-2007: Added the option to skip showing initial state and measurement error values.
%
% * 07-11-2007: Made sure that the length of the input variables for the bar function are always equal.
%               This is taken care of by letting the limits for the X axis take the selected sample limits
%               into account, rather than the objects that are plotted.
%
% * 09-11-2007: Added the call to "SetXTickIntegers".
%
% * 02-01-2008: Removed code using "DSGEModel.InitializeKalman".
%
% * 10-01-2008: Changed the last drawnow call to pause(0.02).
%
% * 01-02-2008: Took the DSGEModel fields "ShockColorStart" and "ShockColorEnd" into account.
%
% * 11-03-2008: The limits on the Y-axis are now calculated directory from the data that is displayed.
%
% * 21-05-2008: Made sure that the Y-axis limits are now set to zero.
%
% * 23-05-2008: Updated the documentation.
%
% * 01-08-2008: Changed the color for initial state from 0.6 to 0.7, and for measurement errors from
%               0.4 to 0.3.
%
% * 19-12-2008: Updated the documentation.
%
% * 25-02-2009: Added the option to have draw the bars with black edges.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

if strcmp(selector,'init')==1;
   DSGEModel.NameStr = NameStr;
   DSGEModel.AnnualStr = AnnualStr;
   DSGEModel.StateVarStructure = StateVarStructure;
else;
   GraphGUI = findobj('Type','figure','Tag','ObsVarDecompDLG');
   controls = get(GraphGUI,'UserData');
   CurrINI = get(controls.variables,'UserData');
   DSGEModel = get(controls.variablestext,'UserData');
end;

%
% Set screen size directly instead of using
% get(0,'ScreenSize')!
%

switch selector;
   case 'init';
      GraphGUI = figure('Color',get(0,'defaultuicontrolbackgroundcolor'), ...
         'FileName','ObsVarDecompDLG.m', ...
         'MenuBar','none', ...
         'PaperUnits','points', ...
         'Units','pixels', ...
         'Position',[(CurrINI.scrsz(3)-525)/2 (CurrINI.scrsz(4)-260)/2 525 260], ...
         'Tag','ObsVarDecompDLG', ...
         'Visible','off', ...
         'Resize','off', ...
         'Name',['Observed Variable Decompositions - ' NameStr], ...
         'NumberTitle','off', ...
         'CloseRequestFcn','ObsVarDecompDLG done', ...
         'ToolBar','none');

      if MatlabNumber>=7.0;
         set(GraphGUI,'DockControl','off');
      end;
      %
      % Check where the sample of data actually begins
      %
      [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
      if strcmp(lower(DSGEModel.AnnualStr),'original')==1;
         [NewStartYear,NewStartPeriod] = AdjustSampleStart(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.DataFrequency,DSGEModel.KalmanFirstObservation-1);
      else;
         [NewStartYear,NewStartPeriod] = AdjustSampleStart(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.DataFrequency,DSGEModel.KalmanFirstObservation-1+(max(DSGEModel.annual)-1));
      end;
      %
      % Outer axis
      %
      AxesBox([2 2 523 250],'Graphics',45,[0.5 1],'on',CurrINI);
      %
      % Select the sample
      %
      OldDSGEModel = DSGEModel;
      DSGEModel.SubBeginYear = NewStartYear;
      DSGEModel.SubBeginPeriod = NewStartPeriod;
      %
      [FirstPeriod,LastPeriod,SubSampleStrMat] = CreateSubSample(DSGEModel);
      %
      DSGEModel = OldDSGEModel;
      controls.sampletxt = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 200 360 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'String','Selected Sample:', ...
         'HorizontalAlignment','left', ...
         'Tag','SampleText');
      %
      % sample start and sample end
      %
      controls.samplebeg = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[210 205 87 20], ...
         'Style','popupmenu', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'UserData',CurrINI, ...
         'String',SubSampleStrMat, ...
         'HorizontalAlignment','center', ...
         'Callback','ObsVarDecompDLG samplebegin', ...
         'Tag','SampleBeginPopup',...
         'Value',1);
      %
      controls.sampleend = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[303 205 87 20], ...
         'Style','popupmenu', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'UserData',CurrINI, ...
         'String',SubSampleStrMat, ...
         'HorizontalAlignment','center', ...
         'Callback','ObsVarDecompDLG sampleend', ...
         'Tag','SampleEndPopup',...
         'Value',size(SubSampleStrMat,1));
      %
      % Select variable
      %
      controls.variablestext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 165 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','ObsVarText');
      %
      controls.variables = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[210 170 180 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','ObsVarPopup',...
         'Value',1);
      %
      % chekc box for decomposing the shock groups into individual shocks
      %
      controls.decomposegroups = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[24 140 366 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','on', ...
            'HorizontalAlignment','left', ...
            'String','Decompose shock groups into individual shocks', ...
            'Callback','ObsVarDecompDLG fixcontrols', ...
            'Value',0, ...
            'Enable','on', ...
            'Tag','DecomposeShockGroupCheckBox');
      %
      if length(unique(DSGEModel.ShockGroups(DSGEModel.StateVarStructure.KeepVar)))==length(DSGEModel.StateVarStructure.KeepVar);
         set(controls.decomposegroups,'Enable','off');
      end;
      %
      controls.decomposesubplots = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[40 120 350 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','on', ...
            'HorizontalAlignment','left', ...
            'String','Plot two groups per figure when decomposing shock group', ...
            'Callback','ObsVarDecompDLG fixdecomp', ...
            'Value',0, ...
            'Enable','off', ...
            'Tag','SubPlotDecomposeShockGroupCheckBox');
      %
      controls.showsmallplots = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[40 100 350 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','on', ...
            'HorizontalAlignment','left', ...
            'String','One small plot per figure when decomposing shock group', ...
            'Callback','ObsVarDecompDLG fixsmall', ...
            'Value',0, ...
            'Enable','off', ...
            'Tag','ShowSmallPlotsCheckBox');
      %
      controls.skipstateerrors = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[24 80 366 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','on', ...
            'HorizontalAlignment','left', ...
            'String','Skip initial state share', ...
            'Value',0, ...
            'Enable','on', ...
            'Tag','SavePlotsToFileCheckBox');
      %
      if isempty(DSGEModel.StateVarStructure.wthT)==0;
         set(controls.skipstateerrors,'String','Skip initial state and measurement errors shares');
      end;
      %
      controls.blackedgebars = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[24 60 366 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','on', ...
            'HorizontalAlignment','left', ...
            'String','Draw bars with black edges', ...
            'Value',1, ...
            'Enable','on', ...
            'Tag','BlackEdgeBarsCheckBox');
      %
      controls.saveplotstofile = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[24 40 366 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','on', ...
            'HorizontalAlignment','left', ...
            'String','Save figures to file', ...
            'Value',0, ...
            'Enable','on', ...
            'Tag','SavePlotsToFileCheckBox');
      %
      controls.savedatatofile = uicontrol('Units','pixels', ...
            'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
            'Position',[24 20 366 20], ...
            'FontSize',CurrINI.gui_fontsize, ...
            'FontName',CurrINI.gui_fontname, ...
            'FontWeight',CurrINI.gui_fontweight, ...
            'FontAngle',CurrINI.gui_fontangle, ...
            'Style','checkbox', ...
            'Visible','on', ...
            'HorizontalAlignment','left', ...
            'String','Save data to file', ...
            'Value',0, ...
            'Enable','on', ...
            'Tag','SaveDataToFileCheckBox');
      %
      % Create graph button
      %
      controls.show = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[420 55 90 20], ...
         'String','Display', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'CallBack','ObsVarDecompDLG showgraph', ...
         'Enable','on', ...
         'Tag','Done');
      %
      %  Done button
      %
      controls.done = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[420 20 90 20], ...
         'String','Done', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'CallBack','ObsVarDecompDLG done', ...
         'Enable','on', ...
         'UserData','waiting', ...
         'Tag','Done');

      set(GraphGUI,'UserData',controls,...
         'HandleVisibility','callback');
   case 'samplebegin'
      %
      % check to make sure that the sample begins before it ends!
      %
      samplebeg = get(controls.samplebeg,'Value');
      sampleend = get(controls.sampleend,'Value');
      if sampleend<samplebeg;
         set(controls.sampleend,'Value',samplebeg);
      end;
   case 'sampleend'
      %
      % check to make sure that the sample begins before it ends
      %
      samplebeg = get(controls.samplebeg,'Value');
      sampleend = get(controls.sampleend,'Value');
      if sampleend<samplebeg;
         set(controls.samplebeg,'Value',sampleend);
      end;
   case 'fixsmall'
      if get(controls.showsmallplots,'Value')==1;
         set(controls.decomposesubplots,'Value',0);
      end;
   case 'fixdecomp'
      if get(controls.decomposesubplots,'Value')==1;
         set(controls.showsmallplots,'Value',0);
      end;
   case 'fixcontrols'
      ShockGroups = unique(DSGEModel.ShockGroups(DSGEModel.StateVarStructure.KeepVar));
      if (get(controls.decomposegroups,'Value')==1)&(length(ShockGroups)>1);
         set(controls.decomposesubplots,'Enable','on');
         set(controls.showsmallplots,'Enable','on');
      else;
         set(controls.decomposesubplots,'Enable','off','Value',0);
         set(controls.showsmallplots,'Enable','off','Value',0);
      end;
   case 'showgraph'
      VariableValue = get(controls.variables,'Value');
      CurrVariable = StringTrim(DSGEModel.VariableNames(VariableValue,:));
      if VariableValue<size(DSGEModel.VariableNames,1);
         set(controls.variables,'Value',VariableValue+1);
      else;
         set(controls.variables,'Value',1);
      end;
      %
      % check if the bars should have black edges or not
      %
      BlackEdgeBars = get(controls.blackedgebars,'Value');
      %
      % create a vector with dates
      %
      DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency);
      %
      % Make sure that DateVector is not longer than the number of periods for the shocks
      %
      if length(DateVector)>length(DSGEModel.StateVarStructure.Y);
         DateVector = DateVector(1,length(DateVector)-length(DSGEModel.StateVarStructure.Y)+1:length(DateVector));
      end;
      samplebeg = get(controls.samplebeg,'Value');
      sampleend = get(controls.sampleend,'Value');
      %
      % create the figure
      %
      FigHandle =figure('Visible','off', ...
                'Position',[(CurrINI.scrsz(3)-750)/2 (CurrINI.scrsz(4)-500)/2 750 500], ...
                'Tag',CurrVariable, ...
                'Name',['Graph of ' CurrVariable]);
      %
      SetFigureProperties(FigHandle,CurrINI);
      %
      % Create the Y-data matrix for the shock groups
      %
      Ymat = [DSGEModel.StateVarStructure.XiInit(VariableValue,:);zeros(size(DSGEModel.ShockGroupNames,1),size(DSGEModel.StateVarStructure.Y,2))];
      ShockGroups = DSGEModel.ShockGroups(DSGEModel.StateVarStructure.KeepVar);
      for i=1:length(DSGEModel.StateVarStructure.KeepVar);
         Ymat(1+ShockGroups(i),:) = Ymat(1+ShockGroups(i),:)+DSGEModel.StateVarStructure.etaDecomp(VariableValue,:,i);
      end;
      %
      % remove rows from Ymat where the shock groups are zero because all individual shocks
      % in that group are zero for all t.
      %
      Ymat = Ymat([1 1+unique(ShockGroups)],:);
      if (strcmp(lower(DSGEModel.AnnualStr),'annualized')==1)&(DSGEModel.annual(VariableValue)==max(DSGEModel.annual));
         %
         % we should annualize all entries in Ymat
         %
         Ymat = Annualize(Ymat,DSGEModel.annual(VariableValue)*ones(1,size(Ymat,1)),DSGEModel.annualscale(VariableValue)*ones(1,size(Ymat,1)));
         DateVector = DateVector(1,DSGEModel.annual(VariableValue):length(DateVector));
      elseif (strcmp(lower(DSGEModel.AnnualStr),'annualized')==1)&(DSGEModel.annual(VariableValue)<max(DSGEModel.annual));
         Ymat = Ymat(:,max(DSGEModel.annual):size(Ymat,2));
         DateVector = DateVector(1,max(DSGEModel.annual):length(DateVector));
      end;
      %
      % set up the color scheme for the bars
      %
      if isempty(DSGEModel.ShockGroupColors)==0;
         ShockGroupColors = DSGEModel.ShockGroupColors(unique(ShockGroups),:);
      else;
         ShockGroupColors = CreateDefaultColors(size(Ymat,1)-1);
      end;
      BaseGroupsColors = ShockGroupColors;
      %
      % Add the measurement error
      %
      if get(controls.skipstateerrors,'Value')==0;
         ShockGroupColors = [0.3 0.3 0.3;ShockGroupColors];
         InitStateStr = 'Initial State';
         if isempty(DSGEModel.StateVarStructure.wthT)==0;
            if (strcmp(lower(DSGEModel.AnnualStr),'annualized')==1)&(DSGEModel.annual(VariableValue)==max(DSGEModel.annual));
               Ymat = [Ymat;Annualize(DSGEModel.StateVarStructure.wthT(VariableValue,:),DSGEModel.annual(VariableValue),DSGEModel.annualscale(VariableValue))];
            elseif (strcmp(lower(DSGEModel.AnnualStr),'annualized')==1)&(DSGEModel.annual(VariableValue)<max(DSGEModel.annual));
               Ymat = [Ymat;DSGEModel.StateVarStructure.wthT(VariableValue,max(DSGEModel.annual):size(DSGEModel.StateVarStructure.wthT,2))];
            else;
               Ymat = [Ymat;DSGEModel.StateVarStructure.wthT(VariableValue,:)];
            end;
            MeasureStr = 'Measurement Error';
            ShockGroupColors = [ShockGroupColors;0.7 0.7 0.7];
         else;
            MeasureStr = '';
         end;
      else;
         %
         % make sure that the initial state and any measurement error are disregarded
         %
         Ymat = Ymat(2:size(Ymat,1),:);
         InitStateStr = '';
         MeasureStr = '';
      end;
      %
      % Create the bars and collect the handles
      %
      if MatlabNumber>=7.0;
         %
         % make sure the bars are written as patches
         %
         BarHandles = bar('v6',DateVector',Ymat','stacked');
      else;
         BarHandles = bar(DateVector',Ymat','stacked');
      end;
      %
      % remake the bar patches such that all bars are displayed properly.
      %
      BarHandles = RemakeBars(BarHandles,ShockGroupColors,BlackEdgeBars);
      %
      % the observed data
      %
      y = DSGEModel.StateVarStructure.Y-(DSGEModel.StateVarStructure.A'*DSGEModel.StateVarStructure.X);
      if (strcmp(lower(DSGEModel.AnnualStr),'annualized')==1)&(DSGEModel.annual(VariableValue)==max(DSGEModel.annual));
         y = Annualize(y,DSGEModel.annual,DSGEModel.annualscale);
      elseif (strcmp(lower(DSGEModel.AnnualStr),'annualized')==1)&(DSGEModel.annual(VariableValue)<max(DSGEModel.annual));
         y = y(:,max(DSGEModel.annual):size(y,2));
      end;
      LineHandle = plot(DateVector,y(VariableValue,:),'.-','Color',[0 0 0],'LineWidth',2);
      if strcmp(lower(DSGEModel.AnnualStr),'original')==1;
         SetAxesFonts(CurrINI,'Title',[CurrVariable ' (original data) in deviation from mean at ' lower(DSGEModel.NameStr)]);
      else;
         SetAxesFonts(CurrINI,'Title',[CurrVariable ' (annual data) in deviation from mean at ' lower(DSGEModel.NameStr)]);
      end;
      axis('tight');
      ylim = get(gca,'YLim');
      for h=1:length(BarHandles);
         if h==1;
            YData = get(BarHandles(h),'YData');
            if size(YData,1)~=4;
               YData = YData';
            end;
            ylim(1) = min(min(YData(:,samplebeg:sampleend)));
            ylim(2) = max(max(YData(:,samplebeg:sampleend)));
         else;
            YData = get(BarHandles(h),'YData');
            if size(YData,1)~=4;
               YData = YData';
            end;
            ylim(1) = min([min(YData(:,samplebeg:sampleend)) ylim(1)]);
            ylim(2) = max([max(YData(:,samplebeg:sampleend)) ylim(2)]);
         end;
      end;
      %
      % see if we should add a zero line
      %
      add_on = 0.1*(ylim(2)-ylim(1));
      if add_on==0;
         Ylim = get(gca,'YLim');
         add_on = 0.1*(Ylim(2)-Ylim(1));
      end;
      ylim = [ylim(1)-add_on ylim(2)+add_on];
      set(gca,'YLim',ylim);
      if (ylim(1)<0)&(ylim(2)>0);
         hold('on');
         plot([DateVector(1) DateVector(length(DateVector))],[0 0],'-','Color',[0 0 0]);
         %
         % make sure the zero line is displayed below the observed variable
         %
         kids = get(gca,'Children');
         if size(kids,1)>size(kids,2);
            kids = kids';
         end;
         kids = [kids(2:length(kids)) kids(1)]';
         set(gca,'Children',kids);
      end;
      ShockGroupNames = '';
      for i=1:size(DSGEModel.ShockGroupNames,1);
         ShockGroupNames = strvcat(ShockGroupNames,StringTrim(strrep(DSGEModel.ShockGroupNames(i,:),'_',' ')));
      end;
      %
      % make sure that only the selected sample is displayed
      %
      XData = get(BarHandles(1),'XData');
      if size(XData,1)>size(XData,2);
         XData = XData';
      end;
      set(gca,'XLim',[min(XData(:,samplebeg)) max(XData(:,sampleend))]);
      %
      % check is we should adjust ShockGroupNames
      %
      if (size(ShockGroupNames,1)>length(DSGEModel.StateVarStructure.KeepVar))&(size(ShockGroupNames,1)>=max(DSGEModel.StateVarStructure.KeepVar));
         ShockGroupNames = ShockGroupNames(DSGEModel.StateVarStructure.KeepVar,:);
      elseif (size(ShockGroupNames,1)>length(DSGEModel.StateVarStructure.KeepVar))&(size(ShockGroupNames,1)<max(DSGEModel.StateVarStructure.KeepVar));
         ShockGroupNames = ShockGroupNames(1:length(DSGEModel.StateVarStructure.KeepVar),:);
      end;
      legHandle = legend([BarHandles LineHandle],strvcat(InitStateStr,ShockGroupNames,MeasureStr,CurrVariable),2);
      SetAxesFonts(CurrINI,legHandle);
      hold('off');
      %
      % check if we should fix the X label
      %
      SetXTickIntegers(gca);
      %
      % check if we should save data to file
      %
      if get(controls.savedatatofile,'Value')==1;
         if isempty(findstr(lower(DSGEModel.NameStr),'mode'))==0;
            matfile = [DSGEModel.OutputDirectory '\' CurrVariable '-ShockDecomp-PosteriorMode-' DSGEModel.AnnualStr '.mat'];
            mfile = [DSGEModel.OutputDirectory '\' CurrVariable 'ShockDecompPostMode' lower(DSGEModel.AnnualStr) '.m'];
         else;
            matfile = [DSGEModel.OutputDirectory '\' CurrVariable '-ShockDecomp-InitialValues-' DSGEModel.AnnualStr '.mat'];
            mfile = [DSGEModel.OutputDirectory '\' CurrVariable 'ShockDecompInitVal' lower(DSGEModel.AnnualStr) '.m'];
         end;
         Variable = strrep(CurrVariable,'-','');
         NamesShockGroup = strvcat(InitStateStr,ShockGroupNames,MeasureStr);
         save(matfile,'Ymat','DateVector','NamesShockGroup','ShockGroupColors');
         %
         % write to m-file
         %
         fid = fopen(mfile,'wt');
         fprintf(fid,'%%\n%% load the data in %s\n%%\n',GetFilename(matfile));
         fprintf(fid,'DataOVD = load(''%s'');\n',GetFilename(matfile));
         fprintf(fid,'%%\n%% matrix with decomposed values for variable determined by field name\n%%\n');
         fprintf(fid,'Ymat.%s = DataOVD.Ymat;\n',Variable);
         fprintf(fid,'%%\n%% vector with dates\n%%\n');
         fprintf(fid,'DateVector = DataOVD.DateVector;\n');
         fprintf(fid,'%%\n%% names for the different shockgroups\n%%\n');
         fprintf(fid,'ShockGroupNames = DataOVD.NamesShockGroup;\n');
         fprintf(fid,'%%\n%% colors for the shock groups\n%%\n');
         fprintf(fid,'ShockGroupColors = DataOVD.ShockGroupColors;\n');
      end;
      %
      % check if we should save the figure to disk
      %
      if get(controls.saveplotstofile,'Value')==1;
         GraphDirectory = [DSGEModel.OutputDirectory '\graphs'];
         if DirExist(GraphDirectory)==0;
            stat = MakeDir(DSGEModel.OutputDirectory,'graphs');
         end;
         file = [GraphDirectory '\' CurrVariable '-Shockdecomp-' DSGEModel.AnnualStr '.' CurrINI.graphicsfmt];
         if strcmp(CurrINI.graphicsfmt,'eps')==1;
            saveas(FigHandle,file,'epsc');
         elseif strcmp(CurrINI.graphicsfmt,'ps')==1;
            saveas(FigHandle,file,'psc');
         else;
            saveas(FigHandle,file);
         end;
      end;
      %
      % display the graph
      %
      SetToolbarImages(FigHandle,CurrINI.images);
      set(FigHandle,'Visible','on','CloseRequestFcn','delete(gcf); drawnow; pause(0.02);');
      drawnow;
      pause(0.02);
      %
      % check if we should decompose the shock groups into the individual shocks
      %
      if get(controls.decomposegroups,'Value')==1;
         AllShockNames = DSGEModel.StateShockNames(DSGEModel.StateVarStructure.KeepVar,:);
         pos = [(CurrINI.scrsz(3)-750)/2 (CurrINI.scrsz(4)-500)/2];
         ShockMatrix = [];
         %
         % check if we should use subplot or not
         %
         if get(controls.decomposesubplots,'Value')==0;
            for i=1:size(ShockGroupNames,1);
               %
               % fix the figure position
               %
               pos = pos+[22 -22];
               if pos(1)+750>CurrINI.scrsz(3);
                  pos(1) = 0;
               end;
               if pos(2)<=32;
                  pos(2) = CurrINI.scrsz(4)-550;
               end;
               %
               % the shock group contribution is located in Ymat(1+i,:)
               %
               if get(controls.skipstateerrors,'Value')==0;
                  GroupValues = Ymat(1+i,:);
               else;
                  GroupValues = Ymat(i,:);
               end;
               %
               % find out which shocks appear in group i
               %
               GroupShocks = (ShockGroups==i) .* (1:length(ShockGroups));
               GroupShocks = GroupShocks(GroupShocks>0);
               %
               ShockMat = zeros(length(GroupShocks),size(DSGEModel.StateVarStructure.etaDecomp,2));
               for j=1:length(GroupShocks);
                  ShockMat(j,:) = DSGEModel.StateVarStructure.etaDecomp(VariableValue,:,GroupShocks(j));
               end;
               %
               % check is we should annualize the data in ShockMat
               %
               if (strcmp(lower(DSGEModel.AnnualStr),'annualized')==1)&(DSGEModel.annual(VariableValue)==max(DSGEModel.annual));
                  ShockMat = Annualize(ShockMat,DSGEModel.annual(VariableValue)*ones(1,size(ShockMat,1)),DSGEModel.annualscale(VariableValue)*ones(1,size(ShockMat,1)));
               elseif (strcmp(lower(DSGEModel.AnnualStr),'annualized')==1)&(DSGEModel.annual(VariableValue)<max(DSGEModel.annual));
                  ShockMat = ShockMat(:,max(DSGEModel.annual):size(ShockMat,2));
               end;
%               ShockMat = ShockMat(:,samplebeg:sampleend);
               %
               % collect the base color for the shock group
               %
               if isequal(DSGEModel.ShockColorStart(i,:),DSGEModel.ShockColorEnd(i,:))==1;
                  BaseGroupColor = BaseGroupsColors(i,:);
                  %
                  % create shades of the BaseGroupColor
                  %
                  ShockColors = ones(length(GroupShocks),1)*BaseGroupColor;
                  if length(GroupShocks)>1;
                     for j=1:length(GroupShocks);
                        ShockColors(j,:) = ((1+(2*(j-1)))/(2*length(GroupShocks)))*ShockColors(j,:);
                     end;
                  end;
               else;
                  NumColors = length(GroupShocks);
                  ShockColors = ones(NumColors,1)*DSGEModel.ShockColorStart(i,:);
                  if NumColors>1;
                     for j=2:NumColors;
                        ShockColors(j,:) = (((NumColors-j)/(NumColors-1))*DSGEModel.ShockColorStart(i,:))+(((j-1)/(NumColors-1))*DSGEModel.ShockColorEnd(i,:));
                     end;
                  end;
               end;
               %
               % get the names of the shocks
               %
               ShockNames = AllShockNames(GroupShocks,:);
               %
               % create the figure
               %
               FigHandle =figure('Visible','off', ...
                         'Position',[pos 750 500], ...
                         'Tag',CurrVariable, ...
                         'Name',['Graph of ' StringTrim(ShockGroupNames(i,:)) ' shock group for ' CurrVariable]);
               %
               SetFigureProperties(FigHandle,CurrINI);
               %
               if get(controls.showsmallplots,'Value')==1;
                  subplot(2,1,1);
               end;
               %
               % Create the bars and collect the handles
               %
               if MatlabNumber>=7.0;
                  %
                  % make sure the bars are written as patches
                  %
                  BarHandles = bar('v6',DateVector',ShockMat','stacked');
               else;
                  BarHandles = bar(DateVector',ShockMat','stacked');
               end;
               %
               % remake the bar patches such that all bars are displayed properly.
               %
               BarHandles = RemakeBars(BarHandles,ShockColors,BlackEdgeBars);
               %
               % display the line with the combined shock groups values
               %
               %
               % try to find an optimal color for the line...
               %
               [LineColor,Ind] = max(ShockColors,[],1);
               LineColor = ones(1,3)-LineColor;
               %
               LineHandle = plot(DateVector,GroupValues,'.-','Color',LineColor,'LineWidth',2);
               %
               % set the title
               %
               if strcmp(lower(DSGEModel.AnnualStr),'original')==1;
                  SetAxesFonts(CurrINI,'Title',['Decomposition of ' StringTrim(ShockGroupNames(i,:)) ' shock group for ' CurrVariable ' (original data) at ' lower(DSGEModel.NameStr)]);
               else;
                  SetAxesFonts(CurrINI,'Title',['Decomposition of ' StringTrim(ShockGroupNames(i,:)) ' shock group for ' CurrVariable ' (annual data) at ' lower(DSGEModel.NameStr)]);
               end;
               axis('tight');
               ylim = get(gca,'YLim');
               for h=1:length(BarHandles);
                  if h==1;
                     YData = get(BarHandles(h),'YData');
                     if size(YData,1)~=4;
                        YData = YData';
                     end;
                     ylim(1) = min(min(YData(:,samplebeg:sampleend)));
                     ylim(2) = max(max(YData(:,samplebeg:sampleend)));
                  else;
                     YData = get(BarHandles(h),'YData');
                     if size(YData,1)~=4;
                        YData = YData';
                     end;
                     ylim(1) = min([min(YData(:,samplebeg:sampleend)) ylim(1)]);
                     ylim(2) = max([max(YData(:,samplebeg:sampleend)) ylim(2)]);
                  end;
               end;
               %
               % see if we should add a zero line
               %
               add_on = 0.1*(ylim(2)-ylim(1));
               if add_on==0;
                  Ylim = get(gca,'YLim');
                  add_on = 0.1*(Ylim(2)-Ylim(1));
               end;
               ylim = [ylim(1)-add_on ylim(2)+add_on];
               set(gca,'YLim',ylim);
               if (ylim(1)<0)&(ylim(2)>0);
                  hold('on');
                  plot([DateVector(1) DateVector(length(DateVector))],[0 0],'-','Color',[0 0 0]);
                  %
                  % make sure the zero line is displayed below the observed variable
                  %
                  kids = get(gca,'Children');
                  if size(kids,1)>size(kids,2);
                     kids = kids';
                  end;
                  kids = [kids(2:length(kids)) kids(1)]';
                  set(gca,'Children',kids);
               end;
               %
               % make sure the X axis limits follow the sample selection
               %
               set(gca,'XLim',[min(XData(:,samplebeg)) max(XData(:,sampleend))]);
               legHandle = legend([BarHandles LineHandle],strvcat(ShockNames,[StringTrim(ShockGroupNames(i,:)) ' shock group']),2);
               SetAxesFonts(CurrINI,legHandle);
               hold('off');
               %
               SetXTickIntegers(gca);
               %
               if get(controls.showsmallplots,'Value')==1;
                  subplot(2,1,2);
                  delete(gca);
                  pause(0.02);
               end;
               %
               % check if we should save data to file
               %
               if get(controls.savedatatofile,'Value')==1;
                  GroupName = strrep(ShockGroupNames(i,:),' ','');
                  GroupName = strrep(GroupName,'-','');
                  eval(['ShockMatrix.' Variable '.' GroupName '.Values = ShockMat;']);
                  eval(['ShockMatrix.' Variable '.' GroupName '.Colors = ShockColors;']);
                  eval(['ShockMatrix.' Variable '.' GroupName '.Names = ShockNames;']);
                  %
                  % write to m-file
                  %
                  fprintf(fid,'%%\n%% Values for individual shocks for variable %s in group "%s"\n%%\n',Variable,StringTrim(ShockGroupNames(i,:)));
                  fprintf(fid,'ShockMatrix.%s.%s.Values = DataOVD.ShockMatrix.%s.%s.Values;\n',Variable,GroupName,Variable,GroupName);
                  fprintf(fid,'%%\n%% Colors for individual shocks for variable %s in group "%s"\n%%\n',Variable,StringTrim(ShockGroupNames(i,:)));
                  fprintf(fid,'ShockMatrix.%s.%s.Colors = DataOVD.ShockMatrix.%s.%s.Colors;\n',Variable,GroupName,Variable,GroupName);
                  fprintf(fid,'%%\n%% Names for individual shocks for variable %s in group "%s"\n%%\n',Variable,StringTrim(ShockGroupNames(i,:)));
                  fprintf(fid,'ShockMatrix.%s.%s.Names = DataOVD.ShockMatrix.%s.%s.Names;\n',Variable,GroupName,Variable,GroupName);
               end;
               %
               % check if we should save the figure to disk
               %
               if get(controls.saveplotstofile,'Value')==1;
                  GraphDirectory = [DSGEModel.OutputDirectory '\graphs'];
                  file = [GraphDirectory '\' CurrVariable '-SingleShockGroup-' num2str(i) '-' DSGEModel.AnnualStr '.' CurrINI.graphicsfmt];
                  if strcmp(CurrINI.graphicsfmt,'eps')==1;
                     saveas(FigHandle,file,'epsc');
                  elseif strcmp(CurrINI.graphicsfmt,'ps')==1;
                     saveas(FigHandle,file,'psc');
                  else;
                     saveas(FigHandle,file);
                  end;
               end;
               %
               % display the graph
               %
               SetToolbarImages(FigHandle,CurrINI.images);
               set(FigHandle,'Visible','on','CloseRequestFcn','delete(gcf); drawnow; pause(0.02);');
               drawnow;
               pause(0.02);
            end;
         else;
            %
            % check how many figures we shall make
            %
            NumFigs = ceil(size(ShockGroupNames,1)/2);
            NumGroup = 0;
            for i=1:NumFigs;
               %
               % fix the figure position
               %
               pos = pos+[22 -22];
               if pos(1)+750>CurrINI.scrsz(3);
                  pos(1) = 0;
               end;
               if pos(2)<=32;
                  pos(2) = CurrINI.scrsz(4)-550;
               end;
               %
               % the shock group contribution is located in Ymat(1+NumGroup,:)
               %
               NumGroup = NumGroup+1;
               %
               if get(controls.skipstateerrors,'Value')==0;
                  GroupValues = Ymat(1+NumGroup,:);
               else;
                  GroupValues = Ymat(NumGroup,:);
               end;
               %
               % find out which shocks appear in group NumGroup
               %
               GroupShocks = (ShockGroups==NumGroup) .* (1:length(ShockGroups));
               GroupShocks = GroupShocks(GroupShocks>0);
               %
               ShockMat = zeros(length(GroupShocks),size(DSGEModel.StateVarStructure.etaDecomp,2));
               for j=1:length(GroupShocks);
                  ShockMat(j,:) = DSGEModel.StateVarStructure.etaDecomp(VariableValue,:,GroupShocks(j));
               end;
               %
               % check is we should annualize the data in ShockMat
               %
               if (strcmp(lower(DSGEModel.AnnualStr),'annualized')==1)&(DSGEModel.annual(VariableValue)==max(DSGEModel.annual));
                  ShockMat = Annualize(ShockMat,DSGEModel.annual(VariableValue)*ones(1,size(ShockMat,1)),DSGEModel.annualscale(VariableValue)*ones(1,size(ShockMat,1)));
               elseif (strcmp(lower(DSGEModel.AnnualStr),'annualized')==1)&(DSGEModel.annual(VariableValue)<max(DSGEModel.annual));
                  ShockMat = ShockMat(:,max(DSGEModel.annual):size(ShockMat,2));
               end;
%               ShockMat = ShockMat(:,samplebeg:sampleend);
               %
               % collect the base color for the shock group
               %
               if isequal(DSGEModel.ShockColorStart(NumGroup,:),DSGEModel.ShockColorEnd(NumGroup,:))==1;
                  BaseGroupColor = BaseGroupsColors(NumGroup,:);
                  %
                  % create shades of the BaseGroupColor
                  %
                  ShockColors = ones(length(GroupShocks),1)*BaseGroupColor;
                  if length(GroupShocks)>1;
                     for j=1:length(GroupShocks);
                        ShockColors(j,:) = ((1+(2*(j-1)))/(2*length(GroupShocks)))*ShockColors(j,:);
                     end;
                  end;
               else;
                  NumColors = length(GroupShocks);
                  ShockColors = ones(NumColors,1)*DSGEModel.ShockColorStart(NumGroup,:);
                  if NumColors>1;
                     for j=2:NumColors;
                        ShockColors(j,:) = (((NumColors-j)/(NumColors-1))*DSGEModel.ShockColorStart(NumGroup,:))+(((j-1)/(NumColors-1))*DSGEModel.ShockColorEnd(NumGroup,:));
                     end;
                  end;
               end;
               %
               % get the names of the shocks
               %
               ShockNames = AllShockNames(GroupShocks,:);
               %
               % create the figure
               %
               FigHandle =figure('Visible','off', ...
                         'Position',[pos 750 500], ...
                         'Tag',CurrVariable, ...
                         'Name',['Graph of ' StringTrim(ShockGroupNames(NumGroup,:)) ' shock group for ' CurrVariable]);
               %
               SetFigureProperties(FigHandle,CurrINI);
               %
               if NumGroup<size(ShockGroupNames,1);
                  %
                  % there is at least one more group to plot on this figure
                  %
                  set(FigHandle,'Name',['Graph of ' StringTrim(ShockGroupNames(NumGroup,:)) ' and ' StringTrim(ShockGroupNames(NumGroup+1,:)) ' shock groups for ' CurrVariable]);
               end;
               subplot(2,1,1);
               %
               % Create the bars and collect the handles
               %
               if MatlabNumber>=7.0;
                  %
                  % make sure the bars are written as patches
                  %
                  BarHandles = bar('v6',DateVector',ShockMat','stacked');
               else;
                  BarHandles = bar(DateVector',ShockMat','stacked');
               end;
               %
               % remake the bar patches such that all bars are displayed properly.
               %
               BarHandles = RemakeBars(BarHandles,ShockColors,BlackEdgeBars);
               %
               % display the line with the combined shock groups values
               %
               %
               % try to find an optimal color for the line...
               %
               [LineColor,Ind] = max(ShockColors,[],1);
               LineColor = ones(1,3)-LineColor;
               %
               LineHandle = plot(DateVector,GroupValues,'.-','Color',LineColor,'LineWidth',2);
               %
               % set the title
               %
               if strcmp(lower(DSGEModel.AnnualStr),'original')==1;
                  SetAxesFonts(CurrINI,'Title',['Decomposition of ' StringTrim(ShockGroupNames(NumGroup,:)) ' shock group for ' CurrVariable ' (original data) at ' lower(DSGEModel.NameStr)]);
               else;
                  SetAxesFonts(CurrINI,'Title',['Decomposition of ' StringTrim(ShockGroupNames(NumGroup,:)) ' shock group for ' CurrVariable ' (annual data) at ' lower(DSGEModel.NameStr)]);
               end;
               axis('tight');
               ylim = get(gca,'YLim');
               for h=1:length(BarHandles);
                  if h==1;
                     YData = get(BarHandles(h),'YData');
                     if size(YData,1)~=4;
                        YData = YData';
                     end;
                     ylim(1) = min(min(YData(:,samplebeg:sampleend)));
                     ylim(2) = max(max(YData(:,samplebeg:sampleend)));
                  else;
                     YData = get(BarHandles(h),'YData');
                     if size(YData,1)~=4;
                        YData = YData';
                     end;
                     ylim(1) = min([min(YData(:,samplebeg:sampleend)) ylim(1)]);
                     ylim(2) = max([max(YData(:,samplebeg:sampleend)) ylim(2)]);
                  end;
               end;
               %
               % see if we should add a zero line
               %
               add_on = 0.1*(ylim(2)-ylim(1));
               if add_on==0;
                  Ylim = get(gca,'YLim');
                  add_on = 0.1*(Ylim(2)-Ylim(1));
               end;
               ylim = [ylim(1)-add_on ylim(2)+add_on];
               set(gca,'YLim',ylim);
               if (ylim(1)<0)&(ylim(2)>0);
                  hold('on');
                  plot([DateVector(1) DateVector(length(DateVector))],[0 0],'-','Color',[0 0 0]);
                  %
                  % make sure the zero line is displayed below the observed variable
                  %
                  kids = get(gca,'Children');
                  if size(kids,1)>size(kids,2);
                     kids = kids';
                  end;
                  kids = [kids(2:length(kids)) kids(1)]';
                  set(gca,'Children',kids);
               end;
               set(gca,'XLim',[min(XData(:,samplebeg)) max(XData(:,sampleend))]);
               legHandle = legend([BarHandles LineHandle],strvcat(ShockNames,[StringTrim(ShockGroupNames(NumGroup,:)) ' shock group']),2);
               SetAxesFonts(CurrINI,legHandle);
               hold('off');
               %
               SetXTickIntegers(gca);
               %
               % check if we should save data to file
               %
               if get(controls.savedatatofile,'Value')==1;
                  GroupName = strrep(ShockGroupNames(NumGroup,:),' ','');
                  GroupName = strrep(GroupName,'-','');
                  eval(['ShockMatrix.' Variable '.' GroupName '.Values = ShockMat;']);
                  eval(['ShockMatrix.' Variable '.' GroupName '.Colors = ShockColors;']);
                  eval(['ShockMatrix.' Variable '.' GroupName '.Names = ShockNames;']);
                  %
                  % write to m-file
                  %
                  fprintf(fid,'%%\n%% Values for individual shocks for variable %s in group "%s"\n%%\n',Variable,StringTrim(ShockGroupNames(NumGroup,:)));
                  fprintf(fid,'ShockMatrix.%s.%s.Values = DataOVD.ShockMatrix.%s.%s.Values;\n',Variable,GroupName,Variable,GroupName);
                  fprintf(fid,'%%\n%% Colors for individual shocks for variable %s in group "%s"\n%%\n',Variable,StringTrim(ShockGroupNames(NumGroup,:)));
                  fprintf(fid,'ShockMatrix.%s.%s.Colors = DataOVD.ShockMatrix.%s.%s.Colors;\n',Variable,GroupName,Variable,GroupName);
                  fprintf(fid,'%%\n%% Names for individual shocks for variable %s in group "%s"\n%%\n',Variable,StringTrim(ShockGroupNames(NumGroup,:)));
                  fprintf(fid,'ShockMatrix.%s.%s.Names = DataOVD.ShockMatrix.%s.%s.Names;\n',Variable,GroupName,Variable,GroupName);
               end;
               %
               % check if we should add one more group
               %
               if NumGroup<size(ShockGroupNames,1);
                  %
                  % the shock group contribution is located in Ymat(1+NumGroup,:)
                  %
                  NumGroup = NumGroup+1;
                  %
                  if get(controls.skipstateerrors,'Value')==0;
                     GroupValues = Ymat(1+NumGroup,:);
                  else;
                     GroupValues = Ymat(NumGroup,:);
                  end;
                  %
                  % find out which shocks appear in group NumGroup
                  %
                  GroupShocks = (ShockGroups==NumGroup) .* (1:length(ShockGroups));
                  GroupShocks = GroupShocks(GroupShocks>0);
                  %
                  ShockMat = zeros(length(GroupShocks),size(DSGEModel.StateVarStructure.etaDecomp,2));
                  for j=1:length(GroupShocks);
                     ShockMat(j,:) = DSGEModel.StateVarStructure.etaDecomp(VariableValue,:,GroupShocks(j));
                  end;
                  %
                  % check is we should annualize the data in ShockMat
                  %
                  if (strcmp(lower(DSGEModel.AnnualStr),'annualized')==1)&(DSGEModel.annual(VariableValue)==max(DSGEModel.annual));
                     ShockMat = Annualize(ShockMat,DSGEModel.annual(VariableValue)*ones(1,size(ShockMat,1)),DSGEModel.annualscale(VariableValue)*ones(1,size(ShockMat,1)));
                  elseif (strcmp(lower(DSGEModel.AnnualStr),'annualized')==1)&(DSGEModel.annual(VariableValue)<max(DSGEModel.annual));
                     ShockMat = ShockMat(:,max(DSGEModel.annual):size(ShockMat,2));
                  end;
%                  ShockMat = ShockMat(:,samplebeg:sampleend);
                  %
                  % collect the base color for the shock group
                  %
                  if isequal(DSGEModel.ShockColorStart(NumGroup,:),DSGEModel.ShockColorEnd(NumGroup,:))==1;
                     BaseGroupColor = BaseGroupsColors(NumGroup,:);
                     %
                     % create shades of the BaseGroupColor
                     %
                     ShockColors = ones(length(GroupShocks),1)*BaseGroupColor;
                     if length(GroupShocks)>1;
                        for j=1:length(GroupShocks);
                           ShockColors(j,:) = ((1+(2*(j-1)))/(2*length(GroupShocks)))*ShockColors(j,:);
                        end;
                     end;
                  else;
                     NumColors = length(GroupShocks);
                     ShockColors = ones(NumColors,1)*DSGEModel.ShockColorStart(NumGroup,:);
                     if NumColors>1;
                        for j=2:NumColors;
                           ShockColors(j,:) = (((NumColors-j)/(NumColors-1))*DSGEModel.ShockColorStart(NumGroup,:))+(((j-1)/(NumColors-1))*DSGEModel.ShockColorEnd(NumGroup,:));
                        end;
                     end;
                  end;
                  %
                  % get the names of the shocks
                  %
                  ShockNames = AllShockNames(GroupShocks,:);
                  %
                  % fix the plotting place
                  %
                  subplot(2,1,2);
                  %
                  % Create the bars and collect the handles
                  %
                  if MatlabNumber>=7.0;
                     %
                     % make sure the bars are written as patches
                     %
                     BarHandles = bar('v6',DateVector',ShockMat','stacked');
                  else;
                     BarHandles = bar(DateVector',ShockMat','stacked');
                  end;
                  %
                  % remake the bar patches such that all bars are displayed properly.
                  %
                  BarHandles = RemakeBars(BarHandles,ShockColors,BlackEdgeBars);
                  %
                  % display the line with the combined shock groups values
                  %
                  %
                  % try to find an optimal color for the line...
                  %
                  [LineColor,Ind] = max(ShockColors,[],1);
                  LineColor = ones(1,3)-LineColor;
                  %
                  LineHandle = plot(DateVector,GroupValues,'.-','Color',LineColor,'LineWidth',2);
                  %
                  % set the title
                  %
                  if strcmp(lower(DSGEModel.AnnualStr),'original')==1;
                     SetAxesFonts(CurrINI,'Title',['Decomposition of ' StringTrim(ShockGroupNames(NumGroup,:)) ' shock group for ' CurrVariable ' (original data) at ' lower(DSGEModel.NameStr)]);
                  else;
                     SetAxesFonts(CurrINI,'Title',['Decomposition of ' StringTrim(ShockGroupNames(NumGroup,:)) ' shock group for ' CurrVariable ' (annual data) at ' lower(DSGEModel.NameStr)]);
                  end;
                  axis('tight');
                  ylim = get(gca,'YLim');
                  for h=1:length(BarHandles);
                     if h==1;
                        YData = get(BarHandles(h),'YData');
                        if size(YData,1)~=4;
                           YData = YData';
                        end;
                        ylim(1) = min(min(YData(:,samplebeg:sampleend)));
                        ylim(2) = max(max(YData(:,samplebeg:sampleend)));
                     else;
                        YData = get(BarHandles(h),'YData');
                        if size(YData,1)~=4;
                           YData = YData';
                        end;
                        ylim(1) = min([min(YData(:,samplebeg:sampleend)) ylim(1)]);
                        ylim(2) = max([max(YData(:,samplebeg:sampleend)) ylim(2)]);
                     end;
                  end;
                  %
                  % see if we should add a zero line
                  %
                  add_on = 0.1*(ylim(2)-ylim(1));
                  if add_on==0;
                     Ylim = get(gca,'YLim');
                     add_on = 0.1*(Ylim(2)-Ylim(1));
                  end;
                  ylim = [ylim(1)-add_on ylim(2)+add_on];
                  set(gca,'YLim',ylim);
                  if (ylim(1)<0)&(ylim(2)>0);
                     hold('on');
                     plot([DateVector(1) DateVector(length(DateVector))],[0 0],'-','Color',[0 0 0]);
                     %
                     % make sure the zero line is displayed below the observed variable
                     %
                     kids = get(gca,'Children');
                     if size(kids,1)>size(kids,2);
                        kids = kids';
                     end;
                     kids = [kids(2:length(kids)) kids(1)]';
                     set(gca,'Children',kids);
                  end;
                  set(gca,'XLim',[min(XData(:,samplebeg)) max(XData(:,sampleend))]);
                  legHandle = legend([BarHandles LineHandle],strvcat(ShockNames,[StringTrim(ShockGroupNames(NumGroup,:)) ' shock group']),2);
                  SetAxesFonts(CurrINI,legHandle);
                  hold('off');
                  %
                  SetXTickIntegers(gca);
                  %
                  % check if we should save data to file
                  %
                  if get(controls.savedatatofile,'Value')==1;
                     GroupName = strrep(ShockGroupNames(NumGroup,:),' ','');
                     GroupName = strrep(GroupName,'-','');
                     eval(['ShockMatrix.' Variable '.' GroupName '.Values = ShockMat;']);
                     eval(['ShockMatrix.' Variable '.' GroupName '.Colors = ShockColors;']);
                     eval(['ShockMatrix.' Variable '.' GroupName '.Names = ShockNames;']);
                     %
                     % write to m-file
                     %
                     fprintf(fid,'%%\n%% Values for individual shocks for variable %s in group "%s"\n%%\n',Variable,StringTrim(ShockGroupNames(NumGroup,:)));
                     fprintf(fid,'ShockMatrix.%s.%s.Values = DataOVD.ShockMatrix.%s.%s.Values;\n',Variable,GroupName,Variable,GroupName);
                     fprintf(fid,'%%\n%% Colors for individual shocks for variable %s in group "%s"\n%%\n',Variable,StringTrim(ShockGroupNames(NumGroup,:)));
                     fprintf(fid,'ShockMatrix.%s.%s.Colors = DataOVD.ShockMatrix.%s.%s.Colors;\n',Variable,GroupName,Variable,GroupName);
                     fprintf(fid,'%%\n%% Names for individual shocks for variable %s in group "%s"\n%%\n',Variable,StringTrim(ShockGroupNames(NumGroup,:)));
                     fprintf(fid,'ShockMatrix.%s.%s.Names = DataOVD.ShockMatrix.%s.%s.Names;\n',Variable,GroupName,Variable,GroupName);
                  end;
               else;
                  subplot(2,1,2);
                  delete(gca);
                  pause(0.02);
               end;
               %
               % check if we should save the figure to disk
               %
               if get(controls.saveplotstofile,'Value')==1;
                  GraphDirectory = [DSGEModel.OutputDirectory '\graphs'];
                  file = [GraphDirectory '\' CurrVariable '-MultiShockGroup-' num2str(i) '-' DSGEModel.AnnualStr '.' CurrINI.graphicsfmt];
                  if strcmp(CurrINI.graphicsfmt,'eps')==1;
                     saveas(FigHandle,file,'epsc');
                  elseif strcmp(CurrINI.graphicsfmt,'ps')==1;
                     saveas(FigHandle,file,'psc');
                  else;
                     saveas(FigHandle,file);
                  end;
               end;
               %
               % display the graph
               %
               SetToolbarImages(FigHandle,CurrINI.images);
               set(FigHandle,'Visible','on','CloseRequestFcn','delete(gcf); drawnow; pause(0.02);');
               drawnow;
               pause(0.02);
            end;
         end;
      end;
      if get(controls.savedatatofile,'Value')==1;
         if get(controls.decomposegroups,'Value')==1;
            save(matfile,'ShockMatrix','-append');
         end;
         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);
      end;
   case 'done'
      set(controls.done,'UserData','done');
      delete(GraphGUI);
      drawnow;
      pause(0.02);
end;
%
if strcmp(selector,'init')==1;
   set(GraphGUI,'Visible','on');
   drawnow;
   if MatlabNumber>=7;
      uicontrol(controls.done);
   end;
   waitfor(controls.done,'UserData','done');
end;

%
% end of ObsVarDecompDLG.m
%
