function ThreeDeeParamsGraphDLG(selector,DSGEModel,CurrINI,ModeData,UseTransformed)
% ThreeDeeParamsGraphDLG: Displays a dialog for selecting 2 parameters to use for computing a 3D surface
%                         of the log posterior. The function uses the original sample from the posterior
%                         mode estimation.
%
% USAGE:
%
%       ThreeDeeParamsGraphDLG(selector,DSGEModel,CurrINI,ModeData,UseTransformed)
%
% REQUIRED INPUT: selector (string vector) that takes on the values "init", "showgraph",
%                          "checkparams", 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.
%
%                 ModeData (structure) with all required information about the posterior
%                          mode of the DSGE model.
%
%                 UseTransformed (boolean) that is 1 if transformed parameters are used and 0 if
%                          the original parameters are considered.
%
%
%                       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: March 15, 2007.
%                        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:
%
% * 19-03-2007: Finished the function.
%
% * 20-03-2006: Made sure that the colorbar is an axes object for version 7 and later of Matlab. Added
%               the input "UseTransformed" to allow for calculations using both the transformed parameters
%               and the original parameters.
%
% * 28-03-2007: Made sure that the correct mode values are used in for plot and plot3 commands when
%               the original parameters are examined.
%
% * 09-11-2007: Updated the documentation.
%
% * 02-01-2008: Removed code using "DSGEModel.InitializeKalman".
%
% * 10-01-2008: Changed the last drawnow call to pause(0.02).
%
% * 13-02-2008: Added tests if the DSGEModel structure fields involving files are the same as the
%               fields of the DSGEModel structure stored in the ModeData structure.
%
% * 04-04-2008: Made sure that the ZLabel string uses "\phi" when trandsformed parameters are studied
%               and "\theta" when the original parameters are considered. Fixed a bug where "ColorMapValue"
%               was computed through the floor function rather than the ceil function. This meant that
%               it could take on the value 0, i.e., YADA would try to pick row 65 from the colormap.
%               This object has exactly 64 rows!
%
% * 23-05-2008: Updated the documentation.
%
% * 19-12-2008: Updated the documentation.
%
% * 09-03-2009: Added quotation marks around paths for the dos copy commands.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%

if strcmp(selector,'init')==1;
   DSGEModel.ModeData = ModeData;
   DSGEModel.UseTransformed = UseTransformed;
   %
   % make sure that files are copied
   %
   %
   % copy files to the tmp folder
   %
   [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;
else
   ThreeDeeParamsGraphGUI = findobj('Type','figure','Tag','ThreeDeeParamsGraphDLG');
   ThreeDeeControls = get(ThreeDeeParamsGraphGUI,'UserData');
   CurrINI = get(ThreeDeeControls.parameter1popup,'UserData');
   DSGEModel = get(ThreeDeeControls.parameter1,'UserData');
   UseTransformed = DSGEModel.UseTransformed;
end;

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

switch selector;
   case 'init';
      ThreeDeeParamsGraphGUI = figure('Color',get(0,'defaultuicontrolbackgroundcolor'), ...
         'FileName','ThreeDeeParamsGraphDLG.m', ...
         'MenuBar','none', ...
         'PaperUnits','points', ...
         'Units','pixels', ...
         'Position',[(CurrINI.scrsz(3)-500)/2 (CurrINI.scrsz(4)-210)/2 500 210], ...
         'Tag','ThreeDeeParamsGraphDLG', ...
         'Visible','off', ...
         'Resize','off', ...
         'Name','Posterior Mode Surface', ...
         'NumberTitle','off', ...
         'CloseRequestFcn','ThreeDeeParamsGraphDLG done', ...
         'ToolBar','none');

      if MatlabNumber>=7.0;
         set(ThreeDeeParamsGraphGUI,'DockControl','off');
      end;
      if UseTransformed==1;
         set(ThreeDeeParamsGraphGUI,'Name','Posterior Mode Surface - Transformed Parameters');
      else;
         set(ThreeDeeParamsGraphGUI,'Name','Posterior Mode Surface - Original Parameters');
      end;
      %
      % Check where the sample of data actually begins
      %
      [NewStartYear,NewStartPeriod] = AdjustSampleStart(DSGEModel.ModeData.DSGEModel.SubBeginYear,DSGEModel.ModeData.DSGEModel.SubBeginPeriod,DSGEModel.ModeData.DSGEModel.DataFrequency,DSGEModel.ModeData.DSGEModel.KalmanFirstObservation-1);
      %
      % Outer axis
      %

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

      ThreeDeeControls.sample = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 140 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.ModeData.DSGEModel.SubEndYear ':' DSGEModel.ModeData.DSGEModel.SubEndPeriod], ...
         'HorizontalAlignment','left', ...
         'Tag','SampleText');
      %
      % Select first parameter
      %
      ThreeDeeControls.parameter1 = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 105 180 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'UserData',DSGEModel, ...
         'String','Select parameter 1:', ...
         'HorizontalAlignment','left', ...
         'Tag','ParameterOneText');
      %
      ThreeDeeControls.parameter1popup = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[200 110 175 20], ...
         'Style','popupmenu', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'UserData',CurrINI, ...
         'String',ModeData.ParameterNames.estimated, ...
         'HorizontalAlignment','center', ...
         'CallBack','ThreeDeeParamsGraphDLG checkparams', ...
         'Tag','ParameterOnePopup',...
         'Value',1);
      %
      % Select second parameter
      %
      ThreeDeeControls.parameter2 = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 75 180 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'String','Select parameter 2:', ...
         'HorizontalAlignment','left', ...
         'Tag','ParameterTwoText');
      %
      ThreeDeeControls.parameter2popup = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[200 80 175 20], ...
         'Style','popupmenu', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'String',ModeData.ParameterNames.estimated, ...
         'HorizontalAlignment','center', ...
         'CallBack','ThreeDeeParamsGraphDLG checkparams', ...
         'Tag','ParameterTwoPopup',...
         'Value',2);
      %
      % select grid width
      %
      ThreeDeeControls.GridWidthText = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 45 180 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'String','Select grid width:', ...
         'HorizontalAlignment','left', ...
         'Tag','GridWidthText');
      %
      ThreeDeeControls.GridWidth = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[200 50 175 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','on', ...
         'HorizontalAlignment','left', ...
         'String','mode +/-1 standard deviation|mode +/-2 standard deviations|mode +/-3 standard deviations|mode +/-4 standard deviations|mode +/-5 standard deviations|mode +/-6 standard deviations|mode +/-7 standard deviations|mode +/-8 standard deviations|mode +/-9 standard deviations|mode +/-10 standard deviations', ...
         'Value',DSGEModel.GridWidth, ...
         'Tag','GridWidthPopup');
      %
      % number of grid points
      %
      ThreeDeeControls.NumGridPointsText = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[24 16 180 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','text', ...
         'String','Number of grid points per axes:', ...
         'HorizontalAlignment','left', ...
         'Tag','NumGridPointsText');
      %
      ThreeDeeControls.NumGridPoints = uicontrol('Units','pixels', ...
         'BackgroundColor',[1 1 1], ...
         'Position',[200 20 175 20], ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'Style','popup', ...
         'Enable','on', ...
         'Visible','on', ...
         'HorizontalAlignment','left', ...
         'String','10|15|20|25|30|35|40|45|50|55|60|65|70|75|80|85|90|95|100', ...
         'Value',DSGEModel.NumberOfGridPoints, ...
         'Tag','NumberOfGridPointsPopup');
      %
      % Create graph button
      %
      ThreeDeeControls.show = uicontrol('Units','pixels', ...
         'BackgroundColor',get(0,'defaultuicontrolbackgroundcolor'), ...
         'Position',[395 50 90 20], ...
         'String','Display', ...
         'FontSize',CurrINI.gui_fontsize, ...
         'FontName',CurrINI.gui_fontname, ...
         'FontWeight',CurrINI.gui_fontweight, ...
         'FontAngle',CurrINI.gui_fontangle, ...
         'CallBack','ThreeDeeParamsGraphDLG showgraph', ...
         'Enable','on', ...
         'Tag','Done');
      %
      %  Done button
      %
      ThreeDeeControls.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','ThreeDeeParamsGraphDLG done', ...
         'Enable','on', ...
         'UserData','waiting', ...
         'Tag','Done');

      set(ThreeDeeParamsGraphGUI,'UserData',ThreeDeeControls,...
         'HandleVisibility','callback');
   case 'checkparams'
      Param1Val = get(ThreeDeeControls.parameter1popup,'Value');
      Param2Val = get(ThreeDeeControls.parameter2popup,'Value');
      if Param1Val==Param2Val;
         %
         % check which controls should be adjusted
         %
         NumParams = size(get(ThreeDeeControls.parameter1popup,'String'),1);
         if gco==ThreeDeeControls.parameter1popup;
            %
            % parameter 1 has changed
            %
            if Param2Val<NumParams;
               set(ThreeDeeControls.parameter2popup,'Value',Param2Val+1);
            else;
               set(ThreeDeeControls.parameter2popup,'Value',1);
            end;
         else;
            %
            % parameter 2 has changed
            %
            if Param2Val<NumParams;
               set(ThreeDeeControls.parameter1popup,'Value',Param1Val+1);
            else;
               set(ThreeDeeControls.parameter1popup,'Value',1);
            end;
         end;
      end;
   case 'showgraph'
      set(ThreeDeeParamsGraphGUI,'Visible','off');
      drawnow;
      drawnow;
      Param1Value = get(ThreeDeeControls.parameter1popup,'Value');
      Param1String = get(ThreeDeeControls.parameter1popup,'String');
      Param1 = StringTrim(Param1String(Param1Value,:));
      %
      Param2Value = get(ThreeDeeControls.parameter2popup,'Value');
      Param2String = get(ThreeDeeControls.parameter2popup,'String');
      Param2 = StringTrim(Param2String(Param2Value,:));
      %
      % determine the grid of the two parameters
      %
      phiMode = DSGEModel.ModeData.phiMode;
      LogPostDensity = DSGEModel.ModeData.LogPostDensity;
      InverseHessian = DSGEModel.ModeData.InverseHessian;
      thetaIndex = DSGEModel.ModeData.thetaIndex;
      UniformBounds = DSGEModel.ModeData.UniformBounds;
      LowerBound = DSGEModel.ModeData.LowerBound;
      thetaPositions = DSGEModel.ModeData.thetaPositions;
      thetaDist = DSGEModel.ModeData.thetaDist;
      PriorDist = DSGEModel.ModeData.PriorDist;
      ModelParameters = DSGEModel.ModeData.ModelParameters;
      ModeDSGEModel = DSGEModel.ModeData.DSGEModel;
      AIMData = DSGEModel.ModeData.AIMData;
      %
      % check som ModeDSGEModel fields
      %
      if strcmp(lower(DSGEModel.DataConstructionFile),lower(ModeDSGEModel.DataConstructionFile))==0;
         txt = ['The data construction file that was used when estimating the posterior mode has a different name (' GetName(ModeDSGEModel.DataConstructionFile) ') than your currently specified data construction file (' GetName(DSGEModel.DataConstructionFile) '). YADA has therefore aborted the calculation of the surface of the log posterior around the posterior mode.'];
         About(txt,'information','Bad Data - Posterior Mode Surface',200,500,CurrINI);
         %
         set(ThreeDeeParamsGraphGUI,'Visible','on');
         drawnow;
         pause(0.02);
         return;
      end;
      if strcmp(lower(DSGEModel.MeasurementEquationFile),lower(ModeDSGEModel.MeasurementEquationFile))==0;
         txt = ['The measurement equation file that was used when estimating the posterior mode has a different name (' GetName(ModeDSGEModel.MeasurementEquationFile) ') than your currently specified measurement equation file (' GetName(DSGEModel.MeasurementEquationFile) '). YADA has therefore aborted the calculation of the surface of the log posterior around the posterior mode.'];
         About(txt,'information','Bad Data - Posterior Mode Surface',200,500,CurrINI);
         %
         set(ThreeDeeParamsGraphGUI,'Visible','on');
         drawnow;
         pause(0.02);
         return;
      end;
      if strcmp(lower(DSGEModel.PriorFile),lower(ModeDSGEModel.PriorFile))==0;
         txt = ['The prior distribution specification file that was used when estimating the posterior mode has a different name (' GetName(ModeDSGEModel.PriorFile) ') than your currently specified prior distribution specification file (' GetName(DSGEModel.PriorFile) '). YADA has therefore aborted the calculation of the surface of the log posterior around the posterior mode.'];
         About(txt,'information','Bad Data - Posterior Mode Surface',200,500,CurrINI);
         %
         set(ThreeDeeParamsGraphGUI,'Visible','on');
         drawnow;
         pause(0.02);
         return;
      end;
      if strcmp(lower(DSGEModel.UpdateParameterFile),lower(ModeDSGEModel.UpdateParameterFile))==0;
         txt = ['The file with parameters to update that was used when estimating the posterior mode has a different name (' GetName(ModeDSGEModel.UpdateParameterFile) ') than your currently specified file with parameters to update (' GetName(DSGEModel.UpdateParameterFile) '). YADA has therefore aborted the calculation of the surface of the log posterior around the posterior mode.'];
         About(txt,'information','Bad Data - Posterior Mode Surface',200,500,CurrINI);
         %
         set(ThreeDeeParamsGraphGUI,'Visible','on');
         drawnow;
         pause(0.02);
         return;
      end;
      if strcmp(lower(DSGEModel.InitializeParameterFile),lower(ModeDSGEModel.InitializeParameterFile))==0;
         txt = ['The file with parameters to initialize that was used when estimating the posterior mode has a different name (' GetName(ModeDSGEModel.InitializeParameterFile) ') than your currently specified file with parameters to initialize (' GetName(DSGEModel.InitializeParameterFile) '). YADA has therefore aborted the calculation of the surface of the log posterior around the posterior mode.'];
         About(txt,'information','Bad Data - Posterior Mode Surface',200,500,CurrINI);
         %
         set(ThreeDeeParamsGraphGUI,'Visible','on');
         drawnow;
         pause(0.02);
         return;
      end;
      if strcmp(lower(DSGEModel.AIMFile),lower(ModeDSGEModel.AIMFile))==0;
         txt = ['The AiM model file that was used when estimating the posterior mode has a different name (' GetFilename(ModeDSGEModel.AIMFile) ') than your currently specified AiM model file (' GetFilename(DSGEModel.AIMFile) '). YADA has therefore aborted the calculation of the surface of the log posterior around the posterior mode.'];
         About(txt,'information','Bad Data - Posterior Mode Surface',200,500,CurrINI);
         %
         set(ThreeDeeParamsGraphGUI,'Visible','on');
         drawnow;
         pause(0.02);
         return;
      end;
      %
      % determine the grid width
      %
      GridWidth = get(ThreeDeeControls.GridWidth,'Value');
      %
      % determine the number of grid points
      %
      NumGridPointsString = get(ThreeDeeControls.NumGridPoints,'String');
      NumGridPoints = str2num(StringTrim(NumGridPointsString(get(ThreeDeeControls.NumGridPoints,'Value'),:)));
      %
      % Parameter 1
      %
      MinParam1 = phiMode(Param1Value)-(GridWidth*sqrt(InverseHessian(Param1Value,Param1Value)));
      MaxParam1 = phiMode(Param1Value)+(GridWidth*sqrt(InverseHessian(Param1Value,Param1Value)));
      Param1Grid = (MinParam1:((MaxParam1-MinParam1)/NumGridPoints):MaxParam1);
      %
      % Parameter 2
      %
      MinParam2 = phiMode(Param2Value)-(GridWidth*sqrt(InverseHessian(Param2Value,Param2Value)));
      MaxParam2 = phiMode(Param2Value)+(GridWidth*sqrt(InverseHessian(Param2Value,Param2Value)));
      Param2Grid = (MinParam2:((MaxParam2-MinParam2)/NumGridPoints):MaxParam2);
      %
      % Initialize the output
      %
      LogPostMatrix = zeros(length(Param2Grid),length(Param1Grid));
      XDataMatrix = ones(length(Param2Grid),1)*Param1Grid;
      YDataMatrix = Param2Grid'*ones(1,length(Param1Grid));
      NumPairs = length(Param1Grid)*length(Param2Grid);
      CurrPair = 0;
      phi = phiMode;
      %
      % display a progress dialog
      %
      if DSGEModel.ShowProgress==1;
         NumParamPairs = length(Param1Grid)*length(Param2Grid);
         ProgressStructure.title = ['Progress for ' num2str(NumParamPairs,'%0.0f') ' parameter pairs'];
         ProgressStructure.facecolor = CurrINI.progress_facecolor;
         ProgressStructure.startfacecolor = CurrINI.progress_startfacecolor;
         ProgressStructure.edgecolor = CurrINI.progress_edgecolor;
         ProgressStructure.bgcolor = CurrINI.progress_bgcolor;
         ProgressStructure.stop = 0;
         ProgressStructure.clock = DSGEModel.ShowProgressClock;
         ProgressStructure.label = ['(' Param1 ',' Param2 ') ='];
         %
         ProgressStructure.name = 'Posterior Mode Surface';
         ProgressStructure.CurrINI = CurrINI;
         WaitHandle = ProgressDLG(0,ProgressStructure);
         set(WaitHandle,'Color',get(0,'defaultuicontrolbackgroundcolor'));
         drawnow;
      end;
      %
      if UseTransformed==0;
         Theta1Grid = zeros(1,length(Param1Grid));
         Theta2Grid = zeros(1,length(Param2Grid));
      end;
      abort = '';
      StopEstimation = 0;
      Num1 = 1;
      for i=Param1Grid;
         phi(Param1Value) = i;
         Num2 = 1;
         for j=Param2Grid;
            CurrPair = CurrPair+1;
            %
            % compute the log posterior
            %
            phi(Param2Value) = j;
            if UseTransformed==0;
               theta = PhiToTheta(phi,thetaIndex,UniformBounds,LowerBound);
               Theta1Grid(1,Num1) = theta(Param1Value);
               Theta2Grid(1,Num2) = theta(Param2Value);
            end;
            %
            % check if we should update the progress dialog
            %
            if DSGEModel.ShowProgress==1;
               abort = get(WaitHandle,'UserData');
               if (strcmp(abort,'cancel')==1)|(strcmp(abort,'done')==1);
                  StopEstimation = 1;
                  break;
               else;
                  if UseTransformed==1;
                     ProgressDLG([CurrPair/NumParamPairs phi(Param1Value) phi(Param2Value)]);
                  else;
                     ProgressDLG([CurrPair/NumParamPairs theta(Param1Value) theta(Param2Value)]);
                  end;
               end;
            end;
            if StopEstimation==1;
               break;
            end;
            if UseTransformed==1;
               logPost = logPosteriorPhiDSGE(phi,thetaIndex,UniformBounds,LowerBound,thetaPositions,thetaDist,PriorDist,ModelParameters,ModeDSGEModel,AIMData);
            else;
               logPost = logPosteriorThetaDSGE(theta,thetaIndex,LowerBound,thetaPositions,thetaDist,PriorDist,ModelParameters,ModeDSGEModel,AIMData);
            end;
            %
            % check if the value is proper
            %
            if logPost~=1000000;
               LogPostMatrix(Num2,Num1) = -logPost;
               if UseTransformed==0;
                  XDataMatrix(Num2,Num1) = theta(Param1Value);
                  YDataMatrix(Num2,Num1) = theta(Param2Value);
               end;
            else;
               LogPostMatrix(Num2,Num1) = NaN;
               XDataMatrix(Num2,Num1) = NaN;
               YDataMatrix(Num2,Num1) = NaN;
            end;
            Num2 = Num2+1;
         end;
         Num1 = Num1+1;
      end;
      %
      % close the wait handle
      %
      if DSGEModel.ShowProgress==1;
         set(WaitHandle,'UserData','done');
         close(WaitHandle);
         drawnow;
         pause(0.02);
      end;
      %
      set(ThreeDeeParamsGraphGUI,'Visible','on');
      drawnow;
      pause(0.02);
      %
      % check if we should display results
      %
      if StopEstimation==0;
         if UseTransformed==0;
            thetaMode = DSGEModel.ModeData.thetaMode;
            Param1Grid = Theta1Grid;
            Param2Grid = Theta2Grid;
            LogPostDensity = LogPostDensity-DSGEModel.ModeData.LogJacobianValue;
            LogPostStr = 'log p (\theta | Data)';
         else;
            thetaMode = phiMode;
            LogPostStr = 'log p (\phi | Data)';
         end;
         %
         % Setting up the surface
         %
         FigHandle = figure('Units','pixels', ...
            'Position',[(CurrINI.scrsz(3)-650)/2 (CurrINI.scrsz(4)-500)/2 650 500], ...
            'NumberTitle','off', ...
            'Visible','off', ...
            'Tag',[Param1 '-' Param2], ...
            'Name',['Surface Plot of Log-Posterior, ' Param1 ', and ' Param2]);
         %
         SetFigureProperties(FigHandle,CurrINI);
         %
         Surfhandle = surf(XDataMatrix',YDataMatrix',LogPostMatrix','EdgeColor','none','LineWidth',1,'FaceLighting','gouraud','SpecularStrength',0.5);
         hold('on');
         %
         % ensure the presence of a colormap
         %
         colormap(jet);
         CurrColorMap = colormap;
         %
         % shading
         %
         shading('interp');
         %
         ZLim = get(gca,'ZLim');
         %
         % plot lines for the posterior mode of parameter 1
         %
         Mode1Handle = plot3(thetaMode(Param1Value)*ones(1,2),[Param2Grid(1) Param2Grid(length(Param2Grid))],LogPostDensity*ones(1,2),'LineStyle','-','Color',[0 0 0],'LineWidth',2);
         hold('on');
         Mode1HandleLeft = plot3(thetaMode(Param1Value)*ones(1,2),Param2Grid(1)*ones(1,2),[ZLim(1) LogPostDensity],'LineStyle','-','Color',[0 0 0],'LineWidth',2);
         hold('on');
         Mode1HandleRight = plot3(thetaMode(Param1Value)*ones(1,2),Param2Grid(length(Param2Grid))*ones(1,2),[ZLim(1) LogPostDensity],'LineStyle','-','Color',[0 0 0],'LineWidth',2);
         hold('on');
         Mode1HandleBottom = plot3(thetaMode(Param1Value)*ones(1,2),[Param2Grid(1) Param2Grid(length(Param2Grid))],ZLim(1)*ones(1,2),'LineStyle','-','Color',[0 0 0],'LineWidth',2);
         hold('on');
         %
         % plot lines for the posterior mode of parameter 2
         %
         Mode2Handle = plot3([Param1Grid(1) Param1Grid(length(Param1Grid))],thetaMode(Param2Value)*ones(1,2),LogPostDensity*ones(1,2),'LineStyle','-','Color',[0 0 0],'LineWidth',2);
         hold('on');
         Mode2HandleLeft = plot3(Param1Grid(1)*ones(1,2),thetaMode(Param2Value)*ones(1,2),[ZLim(1) LogPostDensity],'LineStyle','-','Color',[0 0 0],'LineWidth',2);
         hold('on');
         Mode2HandleRight = plot3(Param1Grid(length(Param1Grid))*ones(1,2),thetaMode(Param2Value)*ones(1,2),[ZLim(1) LogPostDensity],'LineStyle','-','Color',[0 0 0],'LineWidth',2);
         hold('on');
         Mode2HandleBottom = plot3([Param1Grid(1) Param1Grid(length(Param1Grid))],thetaMode(Param2Value)*ones(1,2),ZLim(1)*ones(1,2),'LineStyle','-','Color',[0 0 0],'LineWidth',2);
         hold('on');
         %
         % set the limits
         %
         set(gca,'XLim',[Param1Grid(1) Param1Grid(length(Param1Grid))],'YLim',[Param2Grid(1) Param2Grid(length(Param2Grid))]);
         %
         % add a light
         %
         LightHandle = light('Position',[Param1Grid(1) Param2Grid(1) max(get(gca,'ZLim'))],'Style','infinite');
         hold('on');
         %
         % add a colorbar
         %
         if MatlabNumber>=7;
            ColorBarHandle = colorbar('v6');
         else;
            ColorBarHandle = colorbar;
         end;
         set(ColorBarHandle,'Tag','colorbar');
         SetAxesFonts(CurrINI,ColorBarHandle);
         %
         % make sure the the bar is not too wide
         %
         ColorBarPosition = get(ColorBarHandle,'Position');
         set(ColorBarHandle,'Position',[ColorBarPosition(1)+(2*ColorBarPosition(3)/3) ColorBarPosition(2) ColorBarPosition(3)/3 ColorBarPosition(4)]);
         hold('off');
         %
         % fix the title, xlabel, ylabel and zlabel
         %
         SetAxesFonts(CurrINI,'Title',['Log-posterior for ' Param1 ' and ' Param2],'XLabel',Param1,'Ylabel',Param2,'ZLabel',LogPostStr);
         %
         if (strcmp(get(gca,'YGrid'),'on')==1)&(strcmp(get(gca,'ZGrid'),'on')==1);
            set(gca,'XGrid','on');
         end;
         %
         % Fix the toolbar
         %
         SetToolbarImages(FigHandle,CurrINI.images);
         set(FigHandle,'Visible','on','CloseRequestFcn','delete(gcf); drawnow; pause(0.02);');
         drawnow;
         pause(0.02);
         %
         % set up the contour plot
         %
         if GridWidth>1;
            %
            % check the colorbar in the previous plot
            %
            CBKids = get(ColorBarHandle,'Children');
            MinMax = get(CBKids(1),'YData');
            %
            FigHandle = figure('Units','pixels', ...
               'Position',[(CurrINI.scrsz(3)-650)/2+22 (CurrINI.scrsz(4)-500)/2-22 650 500], ...
               'NumberTitle','off', ...
               'Visible','off', ...
               'Tag',[Param1 '-' Param2], ...
               'Name',['Contour Plot of Log-Posterior, ' Param1 ', and ' Param2]);
            %
            SetFigureProperties(FigHandle,CurrINI);
            %
            % compute data for contour, i.e. 80, 90, 95, 98 and 99 percent values for lnL
            %
            ContourVec = zeros(1,min(GridWidth-1,3));
            ContourHandles = ContourVec;
            LegendText = '';
            LineStyles = {':' '--' '-'};
            for i=1:length(ContourVec);
               %
               % Find the correct x and y data
               %
               XLow = phiMode(Param1Value)-(i*sqrt(InverseHessian(Param1Value,Param1Value)));
               XHigh = phiMode(Param1Value)+(i*sqrt(InverseHessian(Param1Value,Param1Value)));
               YLow = phiMode(Param2Value)-(i*sqrt(InverseHessian(Param2Value,Param2Value)));
               YHigh = phiMode(Param2Value)+(i*sqrt(InverseHessian(Param2Value,Param2Value)));
               if UseTransformed==0;
                  %
                  % we need to map the Xlow, XHigh, YLow, and YHigh values into the
                  % original parameters
                  %
                  phiTest = phiMode;
                  phiTest(Param1Value) = XLow;
                  thetaTest = PhiToTheta(phiTest,thetaIndex,UniformBounds,LowerBound);
                  XLow = thetaTest(Param1Value);
                  %
                  phiTest(Param1Value) = XHigh;
                  thetaTest = PhiToTheta(phiTest,thetaIndex,UniformBounds,LowerBound);
                  XHigh = thetaTest(Param1Value);
                  %
                  phiTest = phiMode;
                  phiTest(Param2Value) = YLow;
                  thetaTest = PhiToTheta(phiTest,thetaIndex,UniformBounds,LowerBound);
                  YLow = thetaTest(Param2Value);
                  %
                  phiTest(Param2Value) = YHigh;
                  thetaTest = PhiToTheta(phiTest,thetaIndex,UniformBounds,LowerBound);
                  YHigh = thetaTest(Param2Value);
               end;
               %
               % find the columns for the XLow and the XHigh values
               %
               XLowPos1 = (Param1Grid>=XLow) .* (1:length(Param1Grid));
               XLowPos1 = min(XLowPos1(XLowPos1>0));
               XLowPos2 = (Param1Grid<XLow) .* (1:length(Param1Grid));
               XLowPos2 = max(XLowPos2(XLowPos2>0));
               %
               XHighPos1 = (Param1Grid>=XHigh) .* (1:length(Param1Grid));
               XHighPos1 = min(XHighPos1(XHighPos1>0));
               XHighPos2 = (Param1Grid<XHigh) .* (1:length(Param1Grid));
               XHighPos2 = max(XHighPos2(XHighPos2>0));
               %
               % find the columns of the YLow and the YHigh values
               %
               YLowPos1 = (Param2Grid>=YLow) .* (1:length(Param2Grid));
               YLowPos1 = min(YLowPos1(YLowPos1>0));
               YLowPos2 = (Param2Grid<YLow) .* (1:length(Param2Grid));
               YLowPos2 = max(YLowPos2(YLowPos2>0));
               %
               YHighPos1 = (Param2Grid>=YHigh) .* (1:length(Param2Grid));
               YHighPos1 = min(YHighPos1(YHighPos1>0));
               YHighPos2 = (Param2Grid<YHigh) .* (1:length(Param2Grid));
               YHighPos2 = max(YHighPos2(YHighPos2>0));
               %
               % collect the appropriate value
               %
               ContourVec(i) = min(min(LogPostMatrix([YLowPos1 YLowPos2 YHighPos1 YHighPos2],[XLowPos1 XLowPos2 XHighPos1 XHighPos2])));
               LegendText = strvcat(LegendText,['min log-posterior at ' num2str(i,'%0.0f') ' std = ' num2str(ContourVec(i),'%0.4f')]);
               %
               % from the ContourVec(i) value establish it relative position with respect to MinMax
               %
               ColorMapValue = ceil(((MinMax(2)-ContourVec(i))/(MinMax(2)-MinMax(1)))*64);
               if ColorMapValue>64;
                  ColorMapValue = 64;
               elseif ColorMapValue<1;
                  ColorMapValue = 1;
               end;
               CurrColor = CurrColorMap(65-ColorMapValue,:);
               %
               % plot the contour - one level at a time
               %
               [c_mat,ContourHandle] = contour(XDataMatrix',YDataMatrix',LogPostMatrix',ContourVec(i)*ones(1,2),'-');
               hold('on');
               %
               % here we can fix the properties of ContourHandle if we wish
               %
               set(ContourHandle,'Color',CurrColor,'LineWidth',2,'LineStyle',LineStyles{i});
               ContourHandles(i) = ContourHandle(1);
            end;
            %
            % plot the posterior mode of parameter 1
            %
            Mode1Handle = plot(thetaMode(Param1Value)*ones(1,2),[Param2Grid(1) Param2Grid(length(Param2Grid))],'LineStyle','-','Color',[0 0 0],'LineWidth',1);
            hold('on');
            %
            % plot the posterior mode of parameter 2
            %
            Mode2Handle = plot([Param1Grid(1) Param1Grid(length(Param1Grid))],thetaMode(Param2Value)*ones(1,2),'LineStyle','-','Color',[0 0 0],'LineWidth',1);
            hold('on');
            %
            % set the limits
            %
            set(gca,'XLim',[Param1Grid(1) Param1Grid(length(Param1Grid))],'YLim',[Param2Grid(1) Param2Grid(length(Param2Grid))]);
            %
            % fix the title, xlabel, and ylabel
            %
            SetAxesFonts(CurrINI,'Title',['Contour plots of log-posterior for ' Param1 ' and ' Param2],'XLabel',Param1,'Ylabel',Param2);
            %
            % set the legend
            %
            legHandle = legend(ContourHandles,LegendText);
            set(legHandle,'Tag','legend');
            SetAxesFonts(CurrINI,legHandle);
            hold('off');
            %
            % Fix the toolbar
            %
            SetToolbarImages(FigHandle,CurrINI.images);
            set(FigHandle,'Visible','on','CloseRequestFcn','delete(gcf); drawnow; pause(0.02);');
            drawnow;
            pause(0.02);
         end;
      end;
   case 'done'
      set(ThreeDeeControls.done,'UserData','done');
      delete(ThreeDeeParamsGraphGUI);
      drawnow;
      pause(0.02);
end;
%
if strcmp(selector,'init')==1;
   set(ThreeDeeParamsGraphGUI,'Visible','on');
   drawnow;
   if MatlabNumber>=7;
      uicontrol(ThreeDeeControls.done);
   end;
   waitfor(ThreeDeeControls.done,'UserData','done');
end;

%
% end of ThreeDeeParamsGraphDLG.m
%
