function PosteriorMeanMedianPlots(thetaPostSample,NumBurnin,CurrChain,PlotType,DSGEModel,CurrINI)
% PosteriorMeanMedianPlots: Provides plots of sequential estimates of the posterior mean or median
%                           of the individual original parameters.
%
% USAGE:
%
%       PosteriorMeanMedianPlots(thetaPostSample,NumBurnin,CurrChain,PlotType,DSGEModel,CurrINI)
%
% REQUIRED INPUT: thetaPostSample (matrix) of dimension NumIterxNumParam with all the posterior
%                                 draws of the original parameters.
%
%                 NumBurnin (integer) with the number of burn-in draws.
%
%                 CurrChain (integer) with the number for the used sampling chain.
%
%                 PlotType (string vector) which is either "Mean" or "Median".
%
%                 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.
%
%
%                       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: December 14, 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:
%
% * 21-12-2006: The function now either plots the posterior mean or the posterior median instead of both.
%
% * 9-1-2007:   The plots are now automatically stored in the graphs directory.
%
% * 8-2-2007:   Updated the documentation. Made sure that the line width is 2 for the mean and median lines.
%               Added a second "drawnow" call at the end of the figure loop.
%
% * 9-11-2007:  Updated the documenation.
%
% * 10-1-2008:  Changed the last drawnow call to pause(0.02).
%
% * 10-3-2008:  Made sure that the "CurrChain" variable affects the filename for the figure.
%
% * 23-5-2008:  Updated the documentation.
%
% * 19-12-2008: Updated the documentation.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

[NumIter,NumParam] = size(thetaPostSample);
%
%
% Try to load the posterior mode estimates
%
ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
ErrorStr = '';
try;
   ModeData = load(ModeFile);
catch;
   ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
end;
if isempty(ErrorStr)==0;
   About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
   return;
end;
%
thetaMode = ModeData.thetaMode;
ParameterNames = ModeData.ParameterNames;
%
% Directory where the plots are stored
%
GraphDirectory = [DSGEModel.OutputDirectory '\graphs'];
%
% locate the controls structure
%
maingui = findobj('Type','figure','Tag','YADA');
controls = get(maingui,'UserData');
%
% sequential estimation start value and step length
%
SeqStartStr = get(controls.dsge.sequentialstart,'String');
Origin = str2num(strrep(StringTrim(SeqStartStr(DSGEModel.SequentialStartIteration,:)),',',''));
SeqStepStr = get(controls.dsge.sequentialstep,'String');
StepLength = str2num(strrep(StringTrim(SeqStepStr(DSGEModel.SequentialStepLength,:)),',',''));
%
%
% Create the sequential grid over which we will compute the marginal likelihood
%
SeqGrid = (Origin+NumBurnin:StepLength:NumIter);
%
if SeqGrid(length(SeqGrid))<NumIter;
   SeqGrid = [SeqGrid NumIter];
end;
%
% vehicle for collecting results
%
DataMeanMatrix = zeros(length(SeqGrid),NumParam);
DataMedianMatrix = DataMeanMatrix;
LimMatrix = zeros(NumParam,2);
%
% set up a wait dialog
%
txt = ['Please wait while YADA computes sequential estimates of the posterior ' lower(PlotType) ' of the original parameters. Estimation started at: ' StringTrim(datestr(now,14)) '.'];
WaitHandle = WaitDLG(txt,'information',['Sequential Posterior ' PlotType],500,150,CurrINI,1);
WaitControls = get(WaitHandle,'UserData');
%
% now we start up the
%
StopEstimation = 0;
for t=1:length(SeqGrid);
   for i=1:NumParam;
      if strcmp(get(WaitControls.cancel,'UserData'),'cancel')==1;
         StopEstimation = 1;
         break;
      end;
      Param = thetaPostSample(1+NumBurnin:SeqGrid(t),i);
      if strcmp(lower(PlotType),'mean')==1;
         DataMeanMatrix(t,i) = mean(Param);
      elseif strcmp(lower(PlotType),'median')==1;
         DataMedianMatrix(t,i) = median(Param);
      end;
      if t==length(SeqGrid);
         LimMatrix(i,:) = [min(Param) max(Param)];
      end;
      drawnow;
   end;
   if StopEstimation==1;
      break;
   end;
end;
%
% shut down the wait dialog
%
set(WaitControls.text,'UserData','done');
delete(WaitHandle);
drawnow;
pause(0.02);
%
% check if we should abort the function
%
if StopEstimation==1;
   return;
end;
%
% Compute the number of figures (max 16 plots per graph)
%
NumFigs = ceil(NumParam/16);
%
if NumFigs==1;
   [NumRows,NumCols] = VillaniConstructOptimalSubplot(NumParam);
else;
   NumRows = 4;
   NumCols = 4;
end;
NumPlots = 0;
pos = [(CurrINI.scrsz(3)-1000)/2 (CurrINI.scrsz(4)-680)/2 1000 650];
%
%
% now we can start the loops
%
for i=1:NumFigs;
   if i>1;
      pos(1) = pos(1)+22;
      pos(2) = pos(2)-22;
      if pos(1)+1000>CurrINI.scrsz(3);
         pos(1) = 0;
      end;
      if pos(2)<=32;
         pos(2) = CurrINI.scrsz(4)-700;
      end;
   end;
   FigHandles{i} = figure('Visible','off','Position',pos);
   if NumFigs==1;
      set(FigHandles{i},'Name',['Sequential Posterior ' PlotType ' - Chain ' num2str(CurrChain,'%0.0f')]);
   else;
      set(FigHandles{i},'Name',['Sequential Posterior ' PlotType ' - Figure ' num2str(i,'%0.0f') ' Chain ' num2str(CurrChain,'%0.0f')]);
   end;
   SetFigureProperties(FigHandles{i},CurrINI);
   %
   k = 0;
   for r=1:NumRows;
      for c=1:NumCols;
         NumPlots = NumPlots+1;
         if NumPlots<=NumParam;
            k = k+1;
            subplot(NumRows,NumCols,k);
            %
            % plot the posterior mode estimate
            %
            pmode = plot([0 NumIter],thetaMode(NumPlots)*ones(1,2),'-','Color',[0 0 0]);
            hold('on');
            if strcmp(lower(PlotType),'mean')==1;
               %
               % plot the sequential posterior mean estimates
               %
               pmean = plot(SeqGrid',DataMeanMatrix(:,NumPlots),'-','Color',[0.75 0 0],'LineWidth',2);
               hold('on');
               ydata = DataMeanMatrix(:,NumPlots);
            elseif strcmp(lower(PlotType),'median')==1;
               %
               % plot the sequential posterior median estimates
               %
               pmedian = plot(SeqGrid',DataMedianMatrix(:,NumPlots),'-','Color',[0 0 0.75],'LineWidth',2);
               hold('on');
               ydata = DataMedianMatrix(:,NumPlots);
            end;
            SetAxesFonts(CurrINI,'Title',StringTrim(ParameterNames.estimated(NumPlots,:)));
            axis('tight');
            ylim = get(gca,'YLim');
            add_on = 0.1*(ylim(2)-ylim(1));
            ylim = [ylim(1)-add_on ylim(2)+add_on];
            %
            % use the information in LimMatrix for the upper and lower bounds on the Y axis
            %
            ylim = [min(ylim(1),LimMatrix(NumPlots,1)) max(ylim(2),LimMatrix(NumPlots,2))];
            set(gca,'YLim',ylim,'XLim',[0 NumIter]);
            %
            % check if we should add a zero line
            %
            if (ylim(1)<0)&(ylim(2)>0);
               hold('on');
               plot([0 NumIter],[0 0],'-','Color',[0 0 0]);
            end;
            %
            % plot the BurnIn value
            %
            plot(NumBurnin*ones(1,2),ylim,'-','Color',[0 0 0]);
            hold('off');
         end;
      end;
   end;
   %
   % save it to disk before
   %
   if DirExist(GraphDirectory)==1;
      if strcmp(lower(PlotType),'mean')==1;
         AddFilename = 'Mean';
      else;
         AddFilename = 'Median';
      end;
      if NumFigs>1;
         file = [GraphDirectory '\Posterior' AddFilename '-' num2str(NumIter,'%0.0f') '-' int2str(CurrChain) '-' num2str(i,'%0.0f') '.fig'];
      else;
         file = [GraphDirectory '\Posterior' AddFilename '-' num2str(NumIter,'%0.0f') '-' int2str(CurrChain) '.fig'];
      end;
      saveas(FigHandles{i},file);
   end;
   %
   % Fix the toolbar cdata
   %
   SetToolbarImages(FigHandles{i},CurrINI.images);
   %
   % Display the current figure
   %
   set(FigHandles{i},'Visible','on','CloseRequestFcn','delete(gcf); drawnow; pause(0.02);');
   drawnow;
   pause(0.02);
end;

%
% end of PosteriorMeanMedianPlots.m
%
