function IRDistributionGraphDLG(selector,DSGEModel,CurrINI,IRFs,VarType,ShockType)
% IRDistributionGraphDLG: Displays impulse response functions
%
% USAGE:
%
%       IRDistributionGraphDLG(selector,DSGEModel,CurrINI,IRFs,VarType,ShockType)
%
% REQUIRED INPUT: selector (string vector) taking on the values "init", "showgraph", and "done".
%
% OPTIONAL INPUT: DSGEModel (structure) whose fields contain all required information
%                           about the model, such as input files, variable and sample
%                           data. Actual observations are not stored in this file.
%
%                 CurrINI (structure), with initialization information.
%
%                 IRFs (structure) with fields "Y" and "Quantiles". The "Y" field holds a 3D matrix of dimension
%                           n x q x h+1, where n is the number of observed variables, q the number of shocks,
%                           and h the impulse response horizon. The values are the posterior mean impulse
%                           responses. The field "Quantiles" is a vector structure with fields "Y" and
%                           "percent", where "Y" holds a 3D matrix of dimension n x q x h+1 with values from
%                           the percent quantile of the marginal distribution of the impulse responses and
%                           "percent" holds the percentile value in percent.
%
%                 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: February 27, 2007.
%                        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:
%
% * 28-2-2007:  The DSGEModel field "ConfidenceBandBaseColor" is now used for the base color for the
%               confidence bands.
%
% * 9-11-2007:  Updated the documentation.
%
% * 10-1-2008:  Changed the last drawnow call to pause(0.02).
%
% * 23-5-2008:  Updated the documentation.
%
% * 11-7-2008:  Changed the ordering of colors for confidence bands.
%
% * 19-12-2008: Updated the documentation.
%
% * 24-02-2009: Added the input variable "ShockType" thereby allowing for impulse responses for
%               shock groups.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

if strcmp(selector,'init')==1;
   DSGEModel.IRFs = IRFs;
   DSGEModel.VarType = VarType;
else
   IRDistGraphGUI = findobj('Type','figure','Tag','IRDistGraphDlg');
   IRcontrol = get(IRDistGraphGUI,'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';
      IRDistGraphGUI = figure('Color',get(0,'defaultuicontrolbackgroundcolor'), ...
         'FileName','IRDistributionGraphDLG.m', ...
         'MenuBar','none', ...
         'PaperUnits','points', ...
         'Units','pixels', ...
         'Position',[(CurrINI.scrsz(3)-500)/2 (CurrINI.scrsz(4)-120)/2 500 120], ...
         'Tag','IRDistGraphDlg', ...
         'Visible','off', ...
         'Resize','off', ...
         'Name',['Impulse Response Distributions - ' VarType ' Data'], ...
         'NumberTitle','off', ...
         'CloseRequestFcn','IRDistributionGraphDLG done', ...
         'ToolBar','none');

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

      %
      % Outer axis
      %

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

      IRcontrol.sample = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 50 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(IRFs.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 16 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 20 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','ShcoksPopup',...
         'Value',1);
      %
      if strcmp(lower(ShockType),'group')==1;
         set(IRcontrol.variables,'String','Select shock group:');
         set(IRcontrol.shocks,'String',DSGEModel.ShockGroupNames);
      end;
      %
      % 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','IRDistributionGraphDLG 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','IRDistributionGraphDLG done', ...
         'Enable','on', ...
         'UserData','waiting', ...
         'Tag','Done');

      set(IRDistGraphGUI,'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.IRFs.Y,3);
      NumY = size(DSGEModel.Y,1);
      YResponses = zeros(NumY,NumResp);
      for i=1:NumResp;
         YResponses(:,i) = DSGEModel.IRFs.Y(:,ShockValue,i);
      end;
      NumFigsY = ceil(NumY/16);
      %
      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
      %
      NumPlotsY = 0;
      pos = [(CurrINI.scrsz(3)-800)/2 (CurrINI.scrsz(4)-600)/2 800 600];
      %
      % 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 - ' CurrShock]);
         else;
            set(FigHandles{i},'Name',['Observed Variable Impulse Responses  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);
                  %
                  % deal with confidence bands
                  %
                  NumBounds = floor(length(DSGEModel.IRFs.Quantiles)/2);
                  Handles = [];
                  LegendStr = '';
                  for nb=1:NumBounds;
                     Lower = zeros(1,NumResp);
                     Upper = Lower;
                     for nr=1:NumResp;
                        Lower(1,nr) = DSGEModel.IRFs.Quantiles(nb).Y(NumPlotsY,ShockValue,nr);
                        Upper(1,nr) = DSGEModel.IRFs.Quantiles(length(DSGEModel.Percentiles)-nb+1).Y(NumPlotsY,ShockValue,nr);
                     end;
                     PatchColor = ((1+(2*(nb-1)))/length(DSGEModel.Percentiles))*DSGEModel.ConfidenceBandBaseColor;
                     ConfBound = DSGEModel.IRFs.Quantiles(length(DSGEModel.Percentiles)-nb+1).percent-DSGEModel.IRFs.Quantiles(nb).percent;
                     ConfPatch = patch([Xvector fliplr(Xvector)],[Upper fliplr(Lower)],PatchColor);
                     set(ConfPatch,'FaceColor',PatchColor,'EdgeColor',PatchColor);
                     hold('on');
                     Handles = [Handles ConfPatch];
                     LegendStr = strvcat(LegendStr,[num2str(ConfBound,'%0.0f') ' confidence']);
                  end;
                  set(gca,'Layer','Top');
                  %
                  %
                  postmean = 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');
                     if size(kids,1)>size(kids,2);
                        kids = kids';
                     end;
                     kids = [kids(2) kids(1) kids(3:length(kids))]';
                     set(gca,'Children',kids);
                  end;
                  hold('off');
               end;
            end;
         end;
         legHandle = legend([postmean Handles],strvcat('Posterior Mean',LegendStr));
         %
         SetAxesFonts(CurrINI,legHandle);
         %
         % transform units temporarily into pixels
         %
         OldAxesUnits = get(gca,'Units');
         OldLegUnits = get(legHandle,'Units');
         set(gca,'Units','pixels');
         set(legHandle,'Units','pixels');
         %
         % check if we can move legend
         %
         LegPos = get(legHandle,'Position');
         AxPos = get(gca,'Position');
         if LegPos(1)<AxPos(1)+AxPos(3);
            if AxPos(1)+AxPos(3)+10+LegPos(3)<1000;
               LegPos(1) = AxPos(1)+AxPos(3)+10;
               set(legHandle,'Position',LegPos);
            end;
         end;
         set(gca,'Units',OldAxesUnits);
         set(legHandle,'Units',OldLegUnits);
         %
         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(IRDistGraphGUI);
      drawnow;
      pause(0.02);
end;
%
if strcmp(selector,'init')==1;
   set(IRDistGraphGUI,'Visible','on');
   drawnow;
   if MatlabNumber>=7;
      uicontrol(IRcontrol.done);
   end;
   waitfor(IRcontrol.done,'UserData','done');
end;

%
% end of IRDistributionGraphDLG.m
%
