function StateGraphDLG(selector,CurrINI,DSGEModel,StateVarStructure,NameStr,VarTypeStr)
% StateGraphDLG: Displays graphs of forecasted, updated and smoothed state variables as well as
%                1 step ahead forecasts of the observed variables.
%
% USAGE:
%
%       StateGraphDLG(selector,CurrINI,DSGEModel,StateVarStructure,NameStr,VarTypeStr)
%
% REQUIRED INPUT: selector (string vector) taking on the values "init", "showgraph", and "done".
%
% OPTIONAL INPUT: 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.
%
%                 StateVarStructure (structure) of dimension h+1, with fields Xi and Y having the responses
%                           of the state variables (Xi) and the observed variables (Y), respectively. The
%                           fields have dimension rxq and nxq respectively. The responses in the invidual
%                           variables are located in the rows, while the columns give the shocks.
%
%                 NameStr (string vector) taking on the values "Posterior Mode" or "Initial Values".
%
%                 VarTypeStr (string vector) taking on the values "State" or "Observed"
%
% 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-2008 European Central Bank.
%
%                       First version: August 22, 2006.
%                        This version: December 19, 2008.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% 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:
%
% * 23-8-2006:  Minor fixes.
%
% * 29-8-2006:  Added the call to SetToolbarImages.
%
% * 9-11-2006:  Added the call to the AdjustSampleStart function.
%
% * 17-11-2006: Changed the colors of the state variable lines. Added the input VarTypeStr which allows the function
%               call to imply that either state variables or observed variables will be displayed.
%
% * 6-12-2006:  Fixed a bug that made the DateVector too long if the number of state variables exceeded the number
%               of observations.
%
% * 27-2-2007:  Added the call "SetAxesFonts(CurrINI,legHandle)" after the legend call.
%
% * 9-11-2007:  Added the call to "SetXTickIntegers".
%
% * 2-1-2008:   Removed code using "DSGEModel.InitializeKalman".
%
% * 10-1-2008:  Changed the last drawnow call to pause(0.02).
%
% * 11-1-2008:  Made it possible to select the sample for the displayed state variables.
%
% * 14-1-2008:  Fixed a bug where the DSGEModel wasn't correctly updated when setting up the sub-sample
%               string matrix.
%
% * 23-5-2008:  Updated the documentation.
%
% * 19-12-2008: Updated the documentation.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

if strcmp(selector,'init')==1;
   DSGEModel.StateVarStructure = StateVarStructure;
   DSGEModel.NameStr = NameStr;
   DSGEModel.VarTypeStr = VarTypeStr;
else
   StateGraphGUI = findobj('Type','figure','Tag','StateGraphDlg');
   StateControls = get(StateGraphGUI,'UserData');
   CurrINI = get(StateControls.variablespopup,'UserData');
   DSGEModel = get(StateControls.variables,'UserData');
end;

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

switch selector;
   case 'init';
      StateGraphGUI = figure('Color',get(0,'defaultuicontrolbackgroundcolor'), ...
         'FileName','StateGraphDLG.m', ...
         'MenuBar','none', ...
         'PaperUnits','points', ...
         'Units','pixels', ...
         'Position',[(CurrINI.scrsz(3)-500)/2 (CurrINI.scrsz(4)-120)/2 500 120], ...
         'Tag','StateGraphDlg', ...
         'Visible','off', ...
         'Resize','off', ...
         'Name',['Graph ' VarTypeStr ' Variables - ' NameStr], ...
         'NumberTitle','off', ...
         'CloseRequestFcn','StateGraphDLG done', ...
         'ToolBar','none');

      if MatlabNumber>=7.0;
         set(StateGraphGUI,'DockControl','off');
      end;
      %
      % Check wehere the sample of data actually begins
      %
      [NewStartYear,NewStartPeriod] = AdjustSampleStart(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.DataFrequency,DSGEModel.KalmanFirstObservation-1);
      OldDSGEModel = DSGEModel;
      DSGEModel.SubBeginYear = NewStartYear;
      DSGEModel.SubBeginPeriod = NewStartPeriod;
      [FirstPeriod,LastPeriod,SubSampleStrMat] = CreateSubSample(DSGEModel);
      %
      DSGEModel = OldDSGEModel;
      %
      % Outer axis
      %
      AxesBox([2 2 498 110],'Graphics',45,[0.5 1],'on',CurrINI);
      %
      % Sample selection controls
      %
      StateControls.sampletxt = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 50 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
      %
      StateControls.samplebeg = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[185 55 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','StateGraphDLG samplebegin', ...
         'Tag','SampleBeginPopup',...
         'Value',1);
      %
      StateControls.sampleend = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[278 55 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','StateGraphDLG sampleend', ...
         'Tag','SampleEndPopup',...
         'Value',size(SubSampleStrMat,1));
%
%      StateControls.sample = uicontrol('Units','pixels', ...
%         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
%         'Position',[24 50 360 20], ...
%         'FontSize',CurrINI.gui_fontsize, ...
%         'FontName',CurrINI.gui_fontname, ...
%         'FontWeight',CurrINI.gui_fontweight, ...
%         'FontAngle',CurrINI.gui_fontangle, ...
%         'Style','text', ...
%         'String',['Estimation Sample: ' NewStartYear ':' NewStartPeriod ' - ' DSGEModel.SubEndYear ':' DSGEModel.SubEndPeriod], ...
%         'HorizontalAlignment','left', ...
%         'Tag','SampleText');
      %
      % Select variable
      %
      StateControls.variables = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 16 160 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'UserData',DSGEModel, ...
         'String',['Select ' lower(VarTypeStr) ' variable:'], ...
         'HorizontalAlignment','left', ...
         'Tag','VariablesText');
      %
      StateControls.variablespopup = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[185 20 180 20], ...
         'Style','popupmenu', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'UserData',CurrINI, ...
         'String',' ', ...
         'HorizontalAlignment','center', ...
         'Tag','VariablePopup',...
         'Value',1);
      if strcmp(lower(VarTypeStr),'state')==1;
         set(StateControls.variablespopup,'String',DSGEModel.StateVariableNames);
      else;
         set(StateControls.variablespopup,'String',DSGEModel.VariableNames);
      end;
      %
      % Create graph button
      %
      StateControls.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','StateGraphDLG showgraph', ...
         'Enable','on', ...
         'Tag','Done');
      %
      %  Done button
      %
      StateControls.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','StateGraphDLG done', ...
         'Enable','on', ...
         'UserData','waiting', ...
         'Tag','Done');

      set(StateGraphGUI,'UserData',StateControls,...
         'HandleVisibility','callback');
   case 'samplebegin'
      %
      % check to make sure that the sample begins before it ends!
      %
      samplebeg = get(StateControls.samplebeg,'Value');
      sampleend = get(StateControls.sampleend,'Value');
      if sampleend<samplebeg;
         set(StateControls.sampleend,'Value',samplebeg);
      end;
   case 'sampleend'
      %
      % check to make sure that the sample begins before it ends
      %
      samplebeg = get(StateControls.samplebeg,'Value');
      sampleend = get(StateControls.sampleend,'Value');
      if sampleend<samplebeg;
         set(StateControls.samplebeg,'Value',sampleend);
      end;
   case 'showgraph'
      VarValue = get(StateControls.variablespopup,'Value');
      VarString = get(StateControls.variablespopup,'String');
      CurrVariable = StringTrim(VarString(VarValue,:));
      if VarValue<size(VarString,1);
         set(StateControls.variablespopup,'Value',VarValue+1);
      else;
         set(StateControls.variablespopup,'Value',1);
      end;
      %
      % create a vector with dates
      %
      DateVector = MakeDateVector(DSGEModel.SubBeginYear,DSGEModel.SubBeginPeriod,DSGEModel.SubEndYear,DSGEModel.SubEndPeriod,DSGEModel.DataFrequency);
      %
      % get the selected sample
      %
      StartSample = get(StateControls.samplebeg,'Value');
      EndSample = get(StateControls.sampleend,'Value');
      %
      % create the figure
      %
      FigHandle =figure('Visible','off', ...
                'Position',[(CurrINI.scrsz(3)-650)/2 (CurrINI.scrsz(4)-500)/2 650 500], ...
                'Tag',CurrVariable, ...
                'Name',['Graph of ' CurrVariable]);
      %
      SetFigureProperties(FigHandle,CurrINI);
      %
      % Determine if the selected variable is a state variable or an observed variable
      %
%      if VarValue<=size(DSGEModel.StateVariableNames,1);
      if strcmp(lower(DSGEModel.VarTypeStr),'state')==1;
         %
         % Make sure that DateVector is not longer than the number of forecast periods for the state variables
         %
         if length(DateVector)>length(DSGEModel.StateVarStructure.Y);
            DateVector = DateVector(1,length(DateVector)-length(DSGEModel.StateVarStructure.Y)+1:length(DateVector));
         end;
         %
         % Graph a state variable
         %
         ForeCastHandle = plot(DateVector(StartSample:EndSample),DSGEModel.StateVarStructure.Ksitt1(VarValue,StartSample:EndSample),'--','LineWidth',2,'Color',[0 0 0.75]);
         hold('on');
         %
         if isempty(DSGEModel.StateVarStructure.Ksitt)==0;
            %
            % Plot the updates
            %
            UpdateHandle = plot(DateVector(StartSample:EndSample),DSGEModel.StateVarStructure.Ksitt(VarValue,StartSample:EndSample),'-.','LineWidth',2,'Color',[0.5 0.5 0.5]);
            hold('on');
            SmoothHandle = plot(DateVector(StartSample:EndSample),DSGEModel.StateVarStructure.KsitT(VarValue,StartSample:EndSample),':','LineWidth',2,'Color',[1 0 0]);
            hold('on');
         end;
         set(gca,'XLim',[DateVector(StartSample) DateVector(EndSample)]);
         %
         % check if we should add a zero line
         %
         ylim = get(gca,'YLim');
         if (ylim(1)<0)&(ylim(2)>0);
            kids = get(gca,'Children');
            if size(kids,2)>size(kids,1);
               kids = kids';
            end;
            ZeroHandle = plot([DateVector(StartSample) DateVector(EndSample)],[0 0],'-','Color',[0 0 0]);
            set(gca,'Children',[ZeroHandle;kids]);
         end;
         %
         SetAxesFonts(CurrINI,'Title',[CurrVariable ' projections at ' lower(DSGEModel.NameStr) ' (max eigenvalue of F is ' num2str(DSGEModel.StateVarStructure.MaxEigenvalue) ')']);
         %
         % check what type of legend we should add
         %
         if isempty(DSGEModel.StateVarStructure.Ksitt)==0;
            legHandle = legend([ForeCastHandle UpdateHandle SmoothHandle],strvcat('Forecast (t|t-1)','Update (t|t)','Smoothing (t|T)'));
         else;
            legHandle = legend(ForeCastHandle,'Forecast (t|t-1)');
         end;
         SetAxesFonts(CurrINI,legHandle);
         %
         SetXTickIntegers(gca);
      else;
         %
         % Make sure that DateVector is not longer than the number of forecast periods for the observed variables
         %
         if length(DateVector)>length(DSGEModel.StateVarStructure.Yhat);
            AddToFirstPeriod = length(DateVector)-length(DSGEModel.StateVarStructure.Yhat);
            DateVector = DateVector(1,length(DateVector)-length(DSGEModel.StateVarStructure.Yhat)+1:length(DateVector));
         else;
            AddToFirstPeriod = 0;
         end;
         %
         % determine the sub-sample from the full sample
         %
         [FirstPeriod,LastPeriod] = CreateSubSample(DSGEModel);
         %
         % get the sub-sample values for the selected observed variable
         %
         y = DSGEModel.Y(VarValue,AddToFirstPeriod+FirstPeriod:LastPeriod);
         %
         % plot the observed variable for the selected sample
         %
         YHandle = plot(DateVector(StartSample:EndSample),y(StartSample:EndSample),'.-','Color',[0.75 0 0],'LineWidth',2);
         hold('on');
         YhatHandle = plot(DateVector(StartSample:EndSample),DSGEModel.StateVarStructure.Yhat(VarValue,StartSample:EndSample),'--','LineWidth',2,'Color',[0 0 0.75]);
         hold('on');
         set(gca,'XLim',[DateVector(StartSample) DateVector(EndSample)]);
         %
         ylim = get(gca,'YLim');
         if (ylim(1)<0)&(ylim(2)>0);
            kids = get(gca,'Children');
            if size(kids,2)>size(kids,1);
               kids = kids';
            end;
            ZeroHandle = plot([DateVector(StartSample) DateVector(EndSample)],[0 0],'-','Color',[0 0 0]);
            set(gca,'Children',[ZeroHandle;kids]);
         end;
         %
         SetAxesFonts(CurrINI,'Title',[CurrVariable ' and forecasts at ' lower(DSGEModel.NameStr) ' (max eigenvalue of F is ' num2str(DSGEModel.StateVarStructure.MaxEigenvalue) ')']);
         %
         legHandle = legend([YHandle YhatHandle],strvcat('Observed','Forecast (t|t-1)'));
         SetAxesFonts(CurrINI,legHandle);
         %
         SetXTickIntegers(gca);
      end;
      %
      SetToolbarImages(FigHandle,CurrINI.images);
      set(FigHandle,'Visible','on','CloseRequestFcn','delete(gcf); drawnow; pause(0.02);');
      drawnow;
      pause(0.02);
   case 'done'
      set(StateControls.done,'UserData','done');
      delete(StateGraphGUI);
      drawnow;
      pause(0.02);
end;
%
if strcmp(selector,'init')==1;
   set(StateGraphGUI,'Visible','on');
   drawnow;
   if MatlabNumber>=7;
      uicontrol(StateControls.done);
   end;
   waitfor(StateControls.done,'UserData','done');
end;

%
% end of StateGraphDLG.m
%
