function StateVarDecompDLG(selector,StateVarStructure,NameStr,CurrINI,DSGEModel)
% StateVarDecompDLG: Displays graphs of state variable decomposition.
%
% USAGE:
%
%       StateVarDecompDLG(selector,StateVarStructure,NameStr,CurrINI,DSGEModel)
%
% REQUIRED INPUT: selector (string vector) taking on the values "init", "samplebegin", "sampleend" "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".
%
%                 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: January 4, 2007.
%                        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:
%
% * 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.
%
% * 27-02-2007: Added the call "SetAxesFonts(CurrINI,legHandle)" after the legend call.
%
% * 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).
%
% * 04-03-2008: Added the sample select code.
%
% * 19-03-2008: Added the option to save the data to file.
%
% * 23-05-2008: Updated the documentation.
%
% * 19-12-2008: Updated the documentation.
%
% * 25-02-2009: Added the option to have black edges when drawing the bars.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

if strcmp(selector,'init')==1;
   DSGEModel.NameStr = NameStr;
   DSGEModel.StateVarStructure = StateVarStructure;
else;
   GraphGUI = findobj('Type','figure','Tag','StateVarDecompDLG');
   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','StateVarDecompDLG.m', ...
         'MenuBar','none', ...
         'PaperUnits','points', ...
         'Units','pixels', ...
         'Position',[(CurrINI.scrsz(3)-500)/2 (CurrINI.scrsz(4)-160)/2 500 160], ...
         'Tag','StateVarDecompDLG', ...
         'Visible','off', ...
         'Resize','off', ...
         'Name',['State Variable Decompositions - ' NameStr], ...
         'NumberTitle','off', ...
         'CloseRequestFcn','StateVarDecompDLG done', ...
         'ToolBar','none');

      if MatlabNumber>=7.0;
         set(GraphGUI,'DockControl','off');
      end;
      %
      % Outer axis
      %
      AxesBox([2 2 498 150],'Graphics',45,[0.5 1],'on',CurrINI);
      %
      % Check where the sample of data actually begins
      %
      [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
      [NewStartYear,NewStartPeriod] = AdjustSampleStart(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.DataFrequency,DSGEModel.KalmanFirstObservation-1);
      %
      % 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 95 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',[185 100 87 20], ...
         'Style','popupmenu', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'String',SubSampleStrMat, ...
         'HorizontalAlignment','center', ...
         'Callback','StateVarDecompDLG samplebegin', ...
         'Tag','SampleBeginPopup',...
         'Value',1);
      %
      controls.sampleend = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[278 100 87 20], ...
         'Style','popupmenu', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'String',SubSampleStrMat, ...
         'HorizontalAlignment','center', ...
         'Callback','StateVarDecompDLG sampleend', ...
         'Tag','SampleEndPopup',...
         'Value',size(SubSampleStrMat,1));
      %
      % Select shock
      %
      controls.variablestext = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 65 180 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'UserData',DSGEModel, ...
         'String','Select state variable:', ...
         'HorizontalAlignment','left', ...
         'Tag','ObsVarText');
      %
      controls.variables = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[185 70 180 20], ...
         'Style','popupmenu', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'UserData',CurrINI, ...
         'String',DSGEModel.StateVariableNames, ...
         'HorizontalAlignment','center', ...
         'Tag','ObsVarPopup',...
         'Value',1);
      %
      controls.blackedgebars = 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','Draw bars with black edges', ...
            'Value',1, ...
            'Enable','on', ...
            'Tag','BlackEdgeBarsCheckBox');
      %
      % save data to file
      %
      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',[395 45 90 20], ...
         'String','Display', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'CallBack','StateVarDecompDLG showgraph', ...
         'Enable','on', ...
         'Tag','Done');
      %
      %  Done button
      %
      controls.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','StateVarDecompDLG 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 'showgraph'
      VariableValue = get(controls.variables,'Value');
      CurrVariable = StringTrim(DSGEModel.StateVariableNames(VariableValue,:));
      if VariableValue<size(DSGEModel.StateVariableNames,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.XietaInit(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.XietaDecomp(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.
      %
      OldYmat = Ymat([1 1+unique(ShockGroups)],:);
      Ymat = Ymat([1 1+unique(ShockGroups)],samplebeg:sampleend);
      %
      % 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;
      ShockGroupColors = [0.4 0.4 0.4;ShockGroupColors];
      %
      % Create the bars and collect the handles
      %
      if MatlabNumber>=7.0;
         %
         % make sure the bars are written as patches
         %
         BarHandles = bar('v6',DateVector(samplebeg:sampleend)',Ymat','stacked');
      else;
         BarHandles = bar(DateVector(samplebeg:sampleend)',Ymat','stacked');
      end;
      %
      % remake the bar patches such that all bars are displayed properly.
      %
      BarHandles = RemakeBars(BarHandles,ShockGroupColors,BlackEdgeBars);
      %
      % the smoothed state variables data
      %
      LineHandle = plot(DateVector(samplebeg:sampleend),DSGEModel.StateVarStructure.KsitT(VariableValue,samplebeg:sampleend),'.-','Color',[0 0 0],'LineWidth',2);
      SetAxesFonts(CurrINI,'Title',['Smooth estimate of ' CurrVariable]);
      axis('tight');
      %
      % see if we should add a zero line
      %
      ylim = get(gca,'YLim');
      add_on = 0.1*(ylim(2)-ylim(1));
      ylim = [ylim(1)-add_on ylim(2)+add_on];
      set(gca,'YLim',ylim);
      if (ylim(1)<0)&(ylim(2)>0);
         hold('on');
         plot([DateVector(samplebeg) DateVector(sampleend)],[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;
      %
      % 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('Initial State',ShockGroupNames,[CurrVariable '(t|T)']));
      SetAxesFonts(CurrINI,legHandle);
      hold('off');
      %
      % 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 '\State-' CurrVariable '-ShockDecomp-PosteriorMode.mat'];
            mfile = [DSGEModel.OutputDirectory '\State' CurrVariable 'ShockDecompPostMode.m'];
         else;
            matfile = [DSGEModel.OutputDirectory '\State-' CurrVariable '-ShockDecomp-InitialValues.mat'];
            mfile = [DSGEModel.OutputDirectory '\State' CurrVariable 'ShockDecompInitVal.m'];
         end;
         Variable = strrep(CurrVariable,'-','');
         NamesShockGroup = strvcat('Initial State',ShockGroupNames);
         Ymat = OldYmat;
         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');
         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;
      %
      SetXTickIntegers(gca);
      %
      % display the graph
      %
      SetToolbarImages(FigHandle,CurrINI.images);
      set(FigHandle,'Visible','on','CloseRequestFcn','delete(gcf); drawnow; pause(0.02);');
      drawnow;
      pause(0.02);
   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 StateVarDecompDLG.m
%
