function CheckPosteriorMode(DSGEModel,CurrINI,controls)
% CheckPosteriorMode: Opens graphs of the posterior mode. If the graphs already exists on disk,
%                     these are shown. Otherwise, new ones are created based on the information
%                     stored to disk about the posterior mode.
%
% USAGE:
%
%       CheckPosteriorMode(DSGEModel,CurrINI,controls)
%
% REQUIRED 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.
%
%                 controls (structure), whose fields provide handles to all the UI
%                           controls in YADA's main dialog.
%
%
%                       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 21, 2006.
%                        This version: March 9, 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:
%
% * 22-08-2006: Added UserData setting of the controls.about UI control to ensure that other YADAGUI functions
%               can't run while this function is running.
%
% * 25-08-2006: Added the changes required by allowing for a uniform prior distribution.
%
% * 29-08-2006: Added the call to the SetToolbarImages function.
%
% * 17-10-2006: Added a try, catch call when attempting to load mat and fig-files. This is needed if matlab can't
%               read the mat or fig-file, e.g., because it was created with a later version of matlab.
%
% * 20-10-2006: Added the impact of the initialization option "CheckTransformedOptimum".
%
% * 24-11-2006: Took the name changes "logPosteriorPhiDSGEOptimize" to "logPosteriorPhiDSGE", and "logPosteriorThetaDSGEOptimize"
%               to "logPosteriorThetaDSGE" into account.
%
% * 07-12-2006: Took the change from CurrINI.NumberOfGridPoints into DSGEModel.NumberOfGridPoints; and
%               CurrINI.CheckTransformedOptimum into DSGEModel.CheckTransformedOptimum; and CurrINI.GridWidth
%               into DSGEModel.GridWidth into account.
%
% * 10-01-2007: The Output tab is now displayed properly when the figures do not exist on disk.
%
% * 12-11-2007: Updated the documentation.
%
% * 18-02-2008: The field "InitialStateVector" wasn't defined before running the check optimum function.
%
% * 25-02-2008: The function now asks the user if an existing file should be opened.
%
% * 26-02-2008: Updated the documentation.
%
% * 23-05-2008: Updated the documentation.
%
% * 21-01-2009: Updated the documentation.
%
% * 09-03-2009: Added quotation marks around paths for the dos copy commands.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

%
% display graphs of the region around the posterior mode
%
drawnow;
pause(0.02);
GraphDirectory = [DSGEModel.OutputDirectory '\graphs'];
if FileExist([GraphDirectory '\PosterorModeOptimum-phi.fig'])==1;
   txt = 'YADA has located old plots of the posterior mode in the file "PosterorModeOptimum-phi.fig". Would you like to open this file?';
   answer = Query(txt,'information',200,'Check Posterior Mode',500,'yes',CurrINI);
elseif FileExist([GraphDirectory '\PosterorModeOptimum-phi-1.fig'])==1;
   txt = 'YADA has located old plots of the posterior mode in the files "PosterorModeOptimum-phi-x.fig", where x=1,2,... Would you like to open these files?';
   answer = Query(txt,'information',200,'Check Posterior Mode',500,'yes',CurrINI);
else;
   answer = 'No';
end;
%
if (FileExist([GraphDirectory '\PosterorModeOptimum-phi.fig'])==1)&(strcmp(lower(answer),'yes')==1);
   %
   % Files of the optimum already exists. Open them
   %
   ErrorStr = '';
   try;
      open([GraphDirectory '\PosterorModeOptimum-phi.fig']);
   catch;
      ErrorStr = ['Unable to load the file "PosterorModeOptimum-phi.fig". Message caught is: ' lasterr];
   end;
   if isempty(ErrorStr)==1;
      set(gcf,'Visible','off');
      SetToolbarImages(gcf,CurrINI.images);
      set(gcf,'Visible','on');
      drawnow;
      drawnow;
      if DSGEModel.CheckTransformedOptimum==0;
         if FileExist([GraphDirectory '\PosterorModeOptimum-theta.fig'])==1;
            open([GraphDirectory '\PosterorModeOptimum-theta.fig']);
            set(gcf,'Visible','off');
            SetToolbarImages(gcf,CurrINI.images);
            set(gcf,'Visible','on');
            drawnow;
            drawnow;
         end;
      end;
   else;
      About(ErrorStr,'information','YADA - Bad FIG File',160,500,CurrINI);
   end;
elseif (FileExist([GraphDirectory '\PosterorModeOptimum-phi-1.fig'])==1)&(strcmp(lower(answer),'yes')==1);;
   %
   % There are multiple files to open
   %
   done = 0;
   num = 1;
   ErrorStr = '';
   while done==0;
      %
      % we close the loop once a figure doesn't exist
      %
      file = [GraphDirectory '\PosterorModeOptimum-phi-' num2str(num,'%0.0f') '.fig'];
      if FileExist(file)==1;
         try;
            open(file);
         catch;
            ErrorStr = ['Unable to load the file "PosterorModeOptimum-phi-' num2str(num,'%0.0f') '.fig". Message caught is: ' lasterr];
            done = 1;
         end;
         if isempty(ErrorStr)==1;
            set(gcf,'Visible','off');
            SetToolbarImages(gcf,CurrINI.images);
            set(gcf,'Visible','on');
            drawnow;
            drawnow;
            if DSGEModel.CheckTransformedOptimum==0;
               file = strrep(file,'phi','theta');
               if FileExist(file)==1;
                  open(file);
                  set(gcf,'Visible','off');
                  SetToolbarImages(gcf,CurrINI.images);
                  set(gcf,'Visible','on');
                  drawnow;
                  drawnow;
                  num = num+1;
               else;
                  done = 1;
               end;
            else;
               num = num+1;
            end;
         end;
      else;
         done = 1;
      end;
   end;
   if isempty(ErrorStr)==0;
      About(ErrorStr,'information','YADA - Bad FIG File',160,500,CurrINI);
   end;
else;
   oldtab = get(controls.tab1,'UserData');
   maingui = get(controls.tab1,'Parent');
   set(controls.about,'UserData',0);
   set(maingui,'CurrentObject',controls.tab6);
   YADAGUI('tab');
   set(controls.about,'UserData',1);
   %
   % check if estimation log is empty
   %
   LogText = get(controls.estimation_log,'String');
   if isempty(LogText)==0;
      SetLogText(strvcat(' ','******************************************************************','*    Y    A    D    A    Y    A    D    A    Y    A    D    A    *','******************************************************************'));
   end;
   %
   % we need to load data from mat-file, and run the check optimum functions
   %
   ModeFile = [DSGEModel.OutputDirectory '\mode\PosteriorMode-' DSGEModel.NameOfModel '.mat'];
   %
   % Retrieving data from ModeFile
   %
   ErrorStr = '';
   try;
      ModeData = load(ModeFile);
   catch;
      ErrorStr = ['Unable to load the file "' ModeFile '". Message caught is: ' lasterr];
   end;
   if isempty(ErrorStr)==1;
      %
      % copy files that we need to have on the path
      %
      [stat,msg] = dos(['copy /Y "' GetPath(DSGEModel.AIMDataFile) 'compute_aim_matrices.m" "' pwd '\tmp"']);
      [stat,msg] = dos(['copy /Y "' DSGEModel.MeasurementEquationFile '" "' pwd '\tmp"']);
      if FileExist(DSGEModel.UpdateParameterFile)==1;
         [stat,msg] = dos(['copy /Y "' DSGEModel.UpdateParameterFile '" "' pwd '\tmp"']);
      end;
      if FileExist(DSGEModel.InitializeParameterFile)==1;
         [stat,msg] = dos(['copy /Y "' DSGEModel.InitializeParameterFile '" "' pwd '\tmp"']);
      end;
      %
      % and the AIMData file
      %
      try;
         AIMData = load(DSGEModel.AIMDataFile);
      catch;
         ErrorStr = ['Unable to load the file "' DSGEModel.AIMDataFile '". Message caught is: ' lasterr];
      end;
      if isempty(ErrorStr)==1;
         if DSGEModel.UseOwnInitialState==1;
            if length(DSGEModel.InitialStateValues)==size(AIMData.endog,1);
               DSGEModel.InitialStateVector = DSGEModel.InitialStateValues(DSGEModel.StateVariablePositions);
            else;
               DSGEModel.InitialStateVector = zeros(length(DSGEModel.StateVariablePositions),1);
            end;
         else;
            DSGEModel.InitialStateVector = zeros(length(DSGEModel.StateVariablePositions),1);
         end;
         %
         % Set up the sub-sample
         %
         [DSGEModel.FirstPeriod,DSGEModel.LastPeriod] = CreateSubSample(DSGEModel);
         %
         SetLogText(strvcat(' ','Checking the optimum...',' * Transformed parameters'));
         %
         NumGridPointsStr = get(controls.optimize.numbergridpoints,'String');
         NumGridPoints = str2num(StringTrim(NumGridPointsStr(DSGEModel.NumberOfGridPoints,:)));
         %
         % Check if GraphDirectory exists
         %
         GraphDirectory = [DSGEModel.OutputDirectory '\graphs'];
         MinMaxGrid = zeros(length(ModeData.phiMode),2);
         stat = MakeDir(DSGEModel.OutputDirectory,'graphs');
         %
         % create lower and upper bounds from InverseHessian and phiMode
         %
         MinMaxGrid(:,1) = ModeData.phiMode-(DSGEModel.GridWidth*sqrt(diag(ModeData.InverseHessian)));
         MinMaxGrid(:,2) = ModeData.phiMode+(DSGEModel.GridWidth*sqrt(diag(ModeData.InverseHessian)));
         phiFittedStd = VillaniCheckOptimum('logPosteriorPhiDSGE',ModeData.phiMode,MinMaxGrid,ModeData.InverseHessian,NumGridPoints,0,[],ModeData.ParameterNames.estimated,'Checking Curvature at Posterior Mode - Transformed Parameters',CurrINI,GraphDirectory,'phi', ...
                  ModeData.thetaIndex,ModeData.UniformBounds,ModeData.LowerBound,ModeData.thetaPositions,ModeData.thetaDist,ModeData.PriorDist,ModeData.ModelParameters,DSGEModel,AIMData);
         if DSGEModel.CheckTransformedOptimum==0;
            SetLogText(' * Original parameters');
            MinMaxGrid(:,1) = PhiToTheta(MinMaxGrid(:,1),ModeData.thetaIndex,ModeData.UniformBounds,ModeData.LowerBound);
            MinMaxGrid(:,2) = PhiToTheta(MinMaxGrid(:,2),ModeData.thetaIndex,ModeData.UniformBounds,ModeData.LowerBound);
            ThetaPhiPartial = PartialThetaPartialPhi(ModeData.phiMode,ModeData.thetaIndex,ModeData.UniformBounds);
            thetaFittedStd = VillaniCheckOptimum('logPosteriorThetaDSGE',ModeData.thetaMode,MinMaxGrid,ThetaPhiPartial*ModeData.InverseHessian*ThetaPhiPartial,NumGridPoints,0,[],ModeData.ParameterNames.estimated,'Checking Curvature at Posterior Mode - Original Parameters',CurrINI,GraphDirectory,'theta', ...
                     ModeData.thetaIndex,ModeData.LowerBound,ModeData.thetaPositions,ModeData.thetaDist,ModeData.PriorDist,ModeData.ModelParameters,DSGEModel,AIMData);
         else;
            thetaFittedStd = NaN;
         end;
         %
         % save the results
         %
         save(ModeFile,'phiFittedStd','thetaFittedStd','-APPEND');
         SetLogText('All done!');
      else;
         About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
      end;
   else;
      About(ErrorStr,'information','YADA - Bad MAT File',120,500,CurrINI);
   end;
   set(controls.about,'UserData',0);
%         set(maingui,'CurrentObject',getfield(controls,['tab' num2str(oldtab)]));
%         YADAGUI('tab');
end;

%
% end of CheckPosteriorMode.m
%
