function IRGraphDLG(selector,CurrINI,DSGEModel,IRStructure,NameStr,VarType,ShockType)
% IRGraphDLG: Displays impulse response functions
%
% USAGE:
%
%       IRGraphDLG(selector,CurrINI,DSGEModel,IRStructure,NameStr,VarType,ShockType)
%
% 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.
%
%                 IRStructure (structure) with fields Ksi (rxqxh+1) and Y (nxqxh+1). The responses in the
%                           invidual variables are located in the rows, while the columns give the shocks.
%                           The third dimension is the response horizon.
%
%                 NameStr (string vector) taking on the values "Posterior Mode" or "Initial Values".
%
%                 VarType (string vector) taking on the values "Levels", "Original", or "Annualized".
%
%                 ShockType (string vector) taking the values "individual" or "group".
%
% 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: August 15, 2006.
%                        This version: February 24, 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:
%
% * 16-8-2006:  Updated the documentation.
%
% * 18-8-2006:  Changed the StrTrim function to StringStrim.
%
% * 23-8-2006:  Minor fixes.
%
% * 29-8-2006:  Added the call to SetToolbarImages.
%
% * 11-12-2006: Added the VarType string and increased the width of the GUI.
%
% * 23-1-2007:  The VarType string can now take on the value "Annualized".
%
% * 26-2-2007:  The input "IRStructure" is now a structure with fields "Ksi" and "Y", both being 3D matrices.
%
% * 27-2-2007:  Fixed a minor issue regarding the use of "NumfigsState" instead of "NumFigsY" for the observed
%               variables impulse responses.
%
% * 9-11-2007:  Updated the documentation.
%
% * 10-1-2008:  Changed the last drawnow call to pause(0.02).
%
% * 16-4-2008:  Added the check box for displaying the state v ariable responses.
%
% * 23-5-2008:  Updated the documentation.
%
% * 19-12-2008: Updated the documentation.
%
% * 24-02-2009: Adapted the code so that impulse responses for shock group can be shown.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

if strcmp(selector,'init')==1;
   DSGEModel.IRStructure = IRStructure;
   DSGEModel.NameStr = NameStr;
   DSGEModel.VarType = VarType;
   DSGEModel.ShockType = ShockType;
else
   IRGraphGUI = findobj('Type','figure','Tag','GIRGraphDlg');
   IRcontrol = get(IRGraphGUI,'UserData');
   CurrINI = get(IRcontrol.shocks,'UserData');
   DSGEModel = get(IRcontrol.variables,'UserData');
end;

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

switch selector;
   case 'init';
      IRGraphGUI = figure('Color',get(0,'defaultuicontrolbackgroundcolor'), ...
         'FileName','IRGraphDLG.m', ...
         'MenuBar','none', ...
         'PaperUnits','points', ...
         'Units','pixels', ...
         'Position',[(CurrINI.scrsz(3)-500)/2 (CurrINI.scrsz(4)-120)/2 500 140], ...
         'Tag','GIRGraphDlg', ...
         'Visible','off', ...
         'Resize','off', ...
         'Name',[VarType ' Impulse Responses - ' NameStr], ...
         'NumberTitle','off', ...
         'CloseRequestFcn','IRGraphDLG done', ...
         'ToolBar','none');

      if MatlabNumber>=7.0;
         set(IRGraphGUI,'DockControl','off');
      end;

      %
      % Outer axis
      %

      AxesBox([2 2 498 130],'Graphics',45,[0.5 1],'on',CurrINI);

      IRcontrol.sample = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 80 260 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'String',['Impulse responses from year 0 to ' num2str(size(IRStructure.Y,3)-1,'%0.0f')], ...
         'HorizontalAlignment','left', ...
         'Tag','SampleText');

      if strcmp(DSGEModel.DataFrequency,'q')==1;
         set(IRcontrol.sample,'String',strrep(get(IRcontrol.sample,'String'),'year','quarter'));
      elseif strcmp(DSGEModel.DataFrequency,'m')==1;
         set(IRcontrol.sample,'String',strrep(get(IRcontrol.sample,'String'),'year','month'));
      end;
      %
      % Select shock
      %
      IRcontrol.variables = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 50 176 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'UserData',DSGEModel, ...
         'String','Select shock:', ...
         'HorizontalAlignment','left', ...
         'Tag','ShockText');
      %
      IRcontrol.shocks = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[200 55 165 20], ...
         'Style','popupmenu', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'UserData',CurrINI, ...
         'String',DSGEModel.StateShockNames, ...
         'HorizontalAlignment','center', ...
         'Tag','ShocksPopup',...
         'Value',1);
      %
      if strcmp(lower(ShockType),'group')==1;
         set(IRcontrol.variables,'String','Select shock group:');
         set(IRcontrol.shocks,'String',DSGEModel.ShockGroupNames);
      end;
      %
      IRcontrol.showstate = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 20 300 20], ...
         'Style','checkbox', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'UserData',CurrINI, ...
         'String','Show impulse responses for state variables too', ...
         'HorizontalAlignment','center', ...
         'Tag','StatevariableDisplayCheckbox',...
         'Value',0);
      %
      % Create graph button
      %
      IRcontrol.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','IRGraphDLG showgraph', ...
         'Enable','on', ...
         'Tag','Done');
      %
      %  Done button
      %
      IRcontrol.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','IRGraphDLG done', ...
         'Enable','on', ...
         'UserData','waiting', ...
         'Tag','Done');

      set(IRGraphGUI,'UserData',IRcontrol,...
         'HandleVisibility','callback');
   case 'showgraph'
      ShockValue = get(IRcontrol.shocks,'Value');
      ShockNames = get(IRcontrol.shocks,'String');
      CurrShock = StringTrim(ShockNames(ShockValue,:));
      if ShockValue<size(ShockNames,1);
         set(IRcontrol.shocks,'Value',ShockValue+1);
      else;
         set(IRcontrol.shocks,'Value',1);
      end;
      %
      % set up the impulse responses for shock number ShockValue
      %
      NumResp = size(DSGEModel.IRStructure.Y,3);
      NumSV = size(DSGEModel.StateVariableNames,1);
      NumY = size(DSGEModel.Y,1);
      StateResponses = zeros(NumSV,NumResp);
      YResponses = zeros(NumY,NumResp);
      for i=1:NumResp;
         StateResponses(:,i) = DSGEModel.IRStructure.Ksi(:,ShockValue,i);
         YResponses(:,i) = DSGEModel.IRStructure.Y(:,ShockValue,i);
      end;
      %
      % Compute the number of figures (max 16 plots per graph)
      %
      NumFigsState = ceil(NumSV/16);
      NumFigsY = ceil(NumY/16);
      %
      if NumFigsState==1;
         [NRowsState,NColsState] = VillaniConstructOptimalSubplot(NumSV);
      else;
         NRowsState = 4;
         NColsState = 4;
      end;
      if NumFigsY==1;
         [NRowsY,NColsY] = VillaniConstructOptimalSubplot(NumY);
      else;
         NRowsY = 4;
         NColsY = 4;
      end;
      Xvector = (1:1:NumResp)-1;
      %
      % Initialize counters for how many plots have been added
      %
      NumPlotsState = 0;
      NumPlotsY = 0;
      pos = [(CurrINI.scrsz(3)-800)/2 (CurrINI.scrsz(4)-600)/2 800 600];
      if get(IRcontrol.showstate,'Value')==1;
         for i=1:NumFigsState;
            if i>1;
               pos(1) = pos(1)+22;
               pos(2) = pos(2)-22;
               if pos(1)+pos(3)>CurrINI.scrsz(3);
                  pos(1) = 0;
               end;
               if pos(2)+pos(4)>CurrINI.scrsz(4)-80;
                  pos(2) = CurrINI.scrsz(4)-80-pos(4);
               end;
            end;
            FigHandles{i} = figure('Visible','off','Position',pos);
            if NumFigsState==1;
               set(FigHandles{i},'Name',['State Variable Impulse Responses ' StringTrim(DSGEModel.NameStr) ' - ' CurrShock]);
            else;
               set(FigHandles{i},'Name',['State Variable Impulse Responses ' StringTrim(DSGEModel.NameStr) ' for ' CurrShock ' - Figure ' num2str(i)]);
            end;
            SetFigureProperties(FigHandles{i},CurrINI);
            k = 0;
            for r=1:NRowsState;
               for c=1:NColsState;
                  NumPlotsState = NumPlotsState+1;
                  if NumPlotsState<=NumSV;
                     k = k+1;
                     subplot(NRowsState,NColsState,k);
                     plot(Xvector,StateResponses(NumPlotsState,:),'-','Color',[0.75 0 0],'LineWidth',2);
                     if strcmp(lower(DSGEModel.VarType),'levels')==1;
                        SetAxesFonts(CurrINI,'Title',['Levels Resp(' StringTrim(DSGEModel.StateVariableNames(NumPlotsState,:)) ') from ' CurrShock]);
                     else;
                        SetAxesFonts(CurrINI,'Title',['Original Resp(' StringTrim(DSGEModel.StateVariableNames(NumPlotsState,:)) ') from ' CurrShock]);
                     end;
                     axis('tight');
                     %
                     % fix the yaxis
                     %
                     ylim = get(gca,'YLim');
                     addY = 0.1*(ylim(2)-ylim(1));
                     ylim = ylim+[-addY addY];
                     set(gca,'YLim',ylim);
                     %
                     % add a zero line if necessary
                     %
                     if (ylim(2)>0)&(ylim(1)<0);
                        hold('on');
                        plot([Xvector(1) Xvector(NumResp)],[0 0],'-','Color',[0 0 0]);
                        kids = get(gca,'Children');
                        kids = [kids(2) kids(1)]';
                        set(gca,'Children',kids);
                     end;
                     hold('off');
                  end;
               end;
            end;
            SetToolbarImages(FigHandles{i},CurrINI.images);
            set(FigHandles{i},'Visible','on','CloseRequestFcn','delete(gcf); drawnow; pause(0.02);');
            drawnow;
            pause(0.02);
         end;
      end;
      %
      % Now we graph the observed variable responses
      %
      FigHandles = [];
      for i=1:NumFigsY;
         pos(1) = pos(1)+22;
         pos(2) = pos(2)-22;
         if pos(1)+pos(3)>CurrINI.scrsz(3);
            pos(1) = 0;
         end;
         if pos(2)+pos(4)>CurrINI.scrsz(4)-80;
            pos(2) = CurrINI.scrsz(4)-80-pos(4);
         end;
         FigHandles{i} = figure('Visible','off','Position',pos);
         if NumFigsY==1;
            set(FigHandles{i},'Name',['Observed Variable Impulse Responses ' StringTrim(DSGEModel.NameStr) ' - ' CurrShock]);
         else;
            set(FigHandles{i},'Name',['Observed Variable Impulse Responses ' StringTrim(DSGEModel.NameStr) ' for ' CurrShock ' - Figure ' num2str(i)]);
         end;
         SetFigureProperties(FigHandles{i},CurrINI);
         %
         k = 0;
         for r=1:NRowsY;
            for c=1:NColsY;
               NumPlotsY = NumPlotsY+1;
               if NumPlotsY<=NumY;
                  k = k+1;
                  subplot(NRowsY,NColsY,k);
                  plot(Xvector,YResponses(NumPlotsY,:),'-','Color',[0.75 0 0],'LineWidth',2);
                  if strcmp(lower(DSGEModel.VarType),'original')==1;
                     SetAxesFonts(CurrINI,'Title',['Original Resp(' StringTrim(DSGEModel.VariableNames(NumPlotsY,:)) ') from ' CurrShock]);
                  elseif strcmp(lower(DSGEModel.VarType),'levels')==1;
                     SetAxesFonts(CurrINI,'Title',['Levels Resp(' StringTrim(DSGEModel.VariableNames(NumPlotsY,:)) ') from ' CurrShock]);
                  else;
                     SetAxesFonts(CurrINI,'Title',['Annualized Resp(' StringTrim(DSGEModel.VariableNames(NumPlotsY,:)) ') from ' CurrShock]);
                  end;
                  axis('tight');
                  %
                  % fix the yaxis
                  %
                  ylim = get(gca,'YLim');
                  addY = 0.1*(ylim(2)-ylim(1));
                  ylim = ylim+[-addY addY];
                  set(gca,'YLim',ylim);
                  %
                  % add a zero line if necessary
                  %
                  if (ylim(2)>0)&(ylim(1)<0);
                     hold('on');
                     plot([Xvector(1) Xvector(NumResp)],[0 0],'-','Color',[0 0 0]);
                     kids = get(gca,'Children');
                     kids = [kids(2) kids(1)]';
                     set(gca,'Children',kids);
                  end;
                  hold('off');
               end;
            end;
         end;
         %
         SetToolbarImages(FigHandles{i},CurrINI.images);
         set(FigHandles{i},'Visible','on','CloseRequestFcn','delete(gcf); drawnow; pause(0.02);');
         drawnow;
         pause(0.02);
      end;
   case 'done'
      set(IRcontrol.done,'UserData','done');
      delete(IRGraphGUI);
      drawnow;
      pause(0.02);
end;
%
if strcmp(selector,'init')==1;
   set(IRGraphGUI,'Visible','on');
   drawnow;
   if MatlabNumber>=7;
      uicontrol(IRcontrol.done);
   end;
   waitfor(IRcontrol.done,'UserData','done');
end;

%
% end of IRGraphDLG.m
%
