function sargentCB(action)
global StopMotion MotionDirection;

switch(action)
   
case 'loadsim' %1
      errormsgH = findobj(gcbf,'Tag','Errormsg');
      set(errormsgH,'Visible','off');
      tipofiles = '.fig';
      [fname,fpath] = uigetfile(['*',tipofiles],'Select the figure file containing your simulation');
      hgload([fpath fname]);
      %give a title to the figure
      oldtitle = get(gcf,'Name');
      i0_simul_str = findstr(oldtitle,'Simulation of'); 
      i1_simul_str = findstr(oldtitle,')'); 
      if isempty(i1_simul_str)
         performdate = oldtitle(i0_simul_str:length(oldtitle));
      else   
         performdate = oldtitle(i0_simul_str:(i1_simul_str - 1));
      end
      set(gcf,'Name',[' 'fpath fname '  (' performdate ')']);
          
   case 'newsim' %2
      errormsgH = findobj(gcbf,'Tag','Errormsg');
      set(errormsgH,'Visible','off');
      Error = 0;
      
      aH = findobj(gcbf,'Tag','a');
      a  = str2num(get(aH,'String'));
      if isempty(a) 
         Error = 1;
      end;
      betaH = findobj(gcbf,'Tag','beta');
      bbeta = str2num(get(betaH,'String'));
      if isempty(bbeta) 
         Error = 1;
      end;
      sigma1H = findobj(gcbf,'Tag','sigma1');
      sigma1  = str2num(get(sigma1H,'String'));
      if isempty(sigma1) 
         Error = 1;
      end;
      sigma2H = findobj(gcbf,'Tag','sigma2');
      sigma2  = str2num(get(sigma2H,'String'));
      if isempty(sigma2) 
         Error = 1;
      end;
      UstarH = findobj(gcbf,'Tag','Ustar');
      Ustar  = str2num(get(UstarH,'String'));
      if isempty(Ustar) 
         Error = 1;
      end;
      thetaH = findobj(gcbf,'Tag','theta'); 
      theta  = str2num(get(thetaH,'String'));
      if isempty(theta) 
         Error = 1;
      end;
      NperiodsH = findobj(gcbf,'Tag','Nperiods');
      N  = str2num(get(NperiodsH,'String'));
      if isempty(N) 
         Error = 1;
      end;
              
    if ~Error
      counterH = findobj(gcbf,'Tag','counter');   
      % simulation starts from the self confirming eq.um
		gamma1 = -theta;
		gamma0 = Ustar*(bbeta + theta^2)/bbeta;
		gamma = [gamma0 gamma1]';
		x = -(gamma0*gamma1)/(bbeta + gamma1^2);
		y = x;
		R = [1 x; x (x^2 + sigma2^2)];
		U = Ustar;

		% initialize some simulation vectors
      gammas = zeros(2,N);
      Us  = zeros(1,N);
		ys  = zeros(1,N);
      xs  = zeros(1,N);      
      v1s = zeros(1,N);      
      v2s = zeros(1,N);      
              
      % do the simulation
      for i = 1:N
		   [gamma,R,x,y,U,v] = sargent(gamma,R,x,y,U,a,bbeta,sigma1,sigma2,Ustar,theta);
         gammas(:,i) = gamma;
         v1s(i) = v(1);
         v2s(i) = v(2);
         ys(i)  = y;
         Us(i)  = U;
         xs(i)  = x;
         if ~rem(i,1000)
            set(counterH,'Str',num2str(i));
            drawnow;
         end%if ~rem(i,1000)   
      end%for i
      set(counterH,'Str','');
     
      %============================================%
      %===  Analysis of the simulation created  ===%
      %============================================%
      
      %load the figure file used to analyse the simulation
      hgload('analysesim_template');
      
      % gives it a name
      dd = datestr(now);
      title = ['  Simulation of ' dd];
      set(gcf,'Name',title); 
      
      % memorize the handles of the saved figure file
      UyplaneH      = findobj(gcf,'Tag','Axes3');
      gammasplaneH  = findobj(gcf,'Tag','Axes4');
      axes1H        = findobj(gcf,'Tag','Axes1');
      axes2H        = findobj(gcf,'Tag','Axes2');
      value_ax1H    = findobj(gcf,'Tag','value_ax1');
      value_ax2H    = findobj(gcf,'Tag','value_ax2');
      paramsH       = findobj(gcf,'Tag','params');
      startperiodH  = findobj(gcf,'Tag','startperiod');
      endperiodH    = findobj(gcf,'Tag','endperiod');
      forwbuttH     = findobj(gcf,'Tag','forward');
      
      % fill the U-y plane
      axes(UyplaneH);
      set(UyplaneH,'NextPlot','add','UserData',{Us,ys,v1s,v2s});
      %plot of U-y points
      UyplotH = plot(Us,ys);
      set(UyplotH,'LineStyle','none','Marker','.','MarkerSize',5,'Tag','Uyplot');
      %plot of marked U-y points
      color_marked_seq = [0.9 0.4 0];
      marked_seqH = plot(Us,ys);
      set(marked_seqH,'LineStyle','none','Marker','.','MarkerSize',5,...
         'Visible','off','Color',color_marked_seq,'Tag','marked_seq');
      %plot of the LAST point U-y
      lastUyH = plot(Us(N),ys(N));
      set(lastUyH,'Marker','hexagram','MarkerSize',5,...
         			'Color',color_marked_seq,'Tag','lastUy');
      	% find the right axis limits (chop the extreme 5% values of U & y)
      	% maybe it's already there: check 'Clipping' in Axes Properties !!!
      
      % label the axis of the U-y plane
      set(UyplaneH,'XLimMode','auto','YLimMode','auto');
      Xlim_Uy = get(UyplaneH,'XLim');
      Ylim_Uy = get(UyplaneH,'YLim');
      rangeX = Xlim_Uy(2) - Xlim_Uy(1);
      rangeY = Ylim_Uy(2) - Ylim_Uy(1);
      dispX = 0.01 * rangeX;
      dispY = 0.02 * rangeY;
      text(Xlim_Uy(1)+dispX,Ylim_Uy(2)-dispY,'\pi',...
         	'FontSize',11,'FontWeight','bold',...
 				'VerticalAlignment','Top',...
				'HorizontalAlignment','Left');
      text(Xlim_Uy(2)-dispX,Ylim_Uy(1)+dispY,'U',...
          	'FontWeight','bold',...
				'VerticalAlignment','Bottom',...
            'HorizontalAlignment','Right');
      set(UyplaneH,'XLimMode','manual','YLimMode','manual');
       
      % Phillips curve perceived by the Govnt (U-y plane)     
      ypointsPC = Ylim_Uy(1):(rangeY/10):Ylim_Uy(2);
      UpointsPC = GovntPC(gammas(1,N),gammas(2,N),ypointsPC);
      PCplotH = plot(UpointsPC,ypointsPC);
      set(PCplotH,'Color',[0.5 0 0],'Tag','PCplot','UserData',ypointsPC,...
         			'Visible','off');
      
      % indifference curve (U-y plane)
      ypointsIC = Ylim_Uy(1):(rangeY/50):Ylim_Uy(2);      
      UpointsIC = IndiffCurve(bbeta,gammas(1,N),gammas(2,N),ypointsIC);
      reals = find(~imag(UpointsIC));
      indCurveH = plot(UpointsIC(reals),ypointsIC(reals));
      set(indCurveH,'Color',[0 0.5 0.2],'Tag','indCurve','UserData',ypointsIC,... 
         			  'Visible','off','LineWidth',1.3);
      
      % DGP (Data Generating Process)
      ypointsDGP = Ylim_Uy(1):(rangeY/10):Ylim_Uy(2);
      UpointsDGP = DGP(Ustar,theta,xs(N),ypointsDGP);
      DGPplotH = plot(UpointsDGP,ypointsDGP);
      set(DGPplotH,'Color',[0 0 0],'Tag','DGPplot','UserData',ypointsDGP,...
      			    'Visible','off','LineStyle','--');
      lines_color = [1 0.7 0];
      v1lineH = line([Us(N),Us(N)],[xs(N),ys(N)]);
      set(v1lineH,'Color',lines_color,'Tag','v1line',...
         	  'Visible','off','LineWidth',1.3);      
      v2lineH = line([Us(N)-v1s(N),Us(N)],[ys(N),ys(N)]);
      set(v2lineH,'Color',lines_color,'Tag','v2line',...
         	  'Visible','off','LineWidth',1.3);      
            
      % x optimal (U-y plane)
      xopt_tH = text(Xlim_Uy(1)+dispX,xs(N)+dispY,'\pi^{*}',...
         		'FontSize',11,'FontWeight','bold',...
 					'VerticalAlignment','Bottom',...
                'HorizontalAlignment','left',...
                'Visible','off','Tag','xopt_t');
      xopt_lH = line(Xlim_Uy,[xs(N),xs(N)]);
      set(xopt_lH,'Color',[0 0 0],'Tag','xopt_l',...  
         		   'Visible','off','LineStyle',':');
                 
      % Ustar (text & line) (U-y plane)
      Ustar_tH = text(Ustar+dispX,Ylim_Uy(1)+dispY,'U*',...
         		'FontWeight','bold',...
 					'VerticalAlignment','Bottom',...
               'HorizontalAlignment','left','Tag','Ustar_t');
      Ustar_lH = line([Ustar,Ustar],Ylim_Uy);
      set(Ustar_tH,'ButtonDownFcn','sargentCB Ustar');
      set(Ustar_lH,'ButtonDownFcn','sargentCB Ustar',...
         		'Color',[0 0 0],'Tag','Ustar_l',...
      			'Visible','off','LineStyle',':');
      
      % Plots in the Axes1 
      % plus start & end period lines and textbox
      axes(axes1H);
      set(axes1H,'NextPlot','add','UserData',{gammas(1,:),gammas(2,:),xs});
      data_ax1 = gammas(2,:);
      Ylim_ax1 = [floor(min(data_ax1)) ceil(max(data_ax1))];
      set(axes1H,'YLim',Ylim_ax1);
      plot_ax1H = plot(data_ax1);
      set(plot_ax1H,'ButtonDownFcn','sargentCB select','Tag','plot_ax1');
      Sline_ax1H = line([1,1],Ylim_ax1);
      Eline_ax1H = line([N,N],Ylim_ax1);
      set(Sline_ax1H,'Color',[0.6 0 0],'Tag','Sline_ax1');
      set(Eline_ax1H,'Color',[0 0 0],'Tag','Eline_ax1');
      set(value_ax1H,'String',sprintf('%2.3g',data_ax1(N)));
      
      % Plots in the Axes2 
      % plus start & end period lines and textbox
      axes(axes2H);
      set(axes2H,'NextPlot','add');   
      data_ax2 = ys;
      Ylim_ax2 = [floor(min(data_ax2)) ceil(max(data_ax2))];
      set(axes2H,'YLim',Ylim_ax2);
      plot_ax2H = plot(data_ax2);
      set(plot_ax2H,'ButtonDownFcn','sargentCB select','Tag','plot_ax2');
      Sline_ax2H = line([1,1],Ylim_ax2);
      Eline_ax2H = line([N,N],Ylim_ax2);
      set(Sline_ax2H,'Color',[0.6 0 0],'Tag','Sline_ax2');
      set(Eline_ax2H,'Color',[0 0 0],'Tag','Eline_ax2');
      set(value_ax2H,'String',sprintf('%2.3g',data_ax2(N)));
               
      % parameter values & other bottons
      par(1) = {['a       = ' sprintf('%2.3g',a)]};
      par(2) = {['beta    = ' sprintf('%2.3g',bbeta)]};
      par(3) = {['sigma1  = ' sprintf('%2.3g',sigma1)]};
      par(4) = {['sigma2  = ' sprintf('%2.3g',sigma2)]};
      par(5) = {['Ustar   = ' sprintf('%2.3g',Ustar)]};
      par(6) = {['theta   = ' sprintf('%2.3g',theta)]};
      set(paramsH,'String',par,'UserData',[a,bbeta,sigma1,sigma2,Ustar,theta]);
      newSperiod = 1;
      set(startperiodH,'String',sprintf('%d',newSperiod));
      newEperiod = N;
      set(endperiodH,'String',sprintf('%d',newEperiod));
      set(forwbuttH,'Enable','off');
      markSperiod = 1;
      
      % write in the UserData area of the figure 
      % the relevant data for this simulation
      set(gcf,'UserData',[newSperiod, newEperiod, markSperiod, N]);
      
    else   %an error in the parameters of the intro window
       set(errormsgH,'Visible','on');
    end%if ~Error
    
case 'mainaxis' %3
      axes3H     = findobj(gcf,'Tag','Axes3');
%      ax3_childH = get(axes3H,'Children');
      axes4H     = findobj(gcf,'Tag','Axes4');
%      ax4_childH = get(axes4H,'Children');
      cashinH    = findobj(gcf,'Tag','cashin');
      
      mainax = get(gcbo,'Value');
      % Legend mainax:
      % 1 = data points
      % 2 = estimated coefficients
      if mainax == 1  % data points
         set(axes3H,'Visible','on');
%         set(ax3_childH,'Visible','on');
         set(axes4H,'Visible','off');
         set(cashinH,'Visible','off');
      else   % estimated coefficients 
         set(axes3H,'Visible','off');
         set(axes4H,'Visible','on');
         set(cashinH,'Visible','on');
      end 
      
case 'redraw' %4
   % load the necessary handles
      axes1H        = findobj(gcf,'Tag','Axes1');
      axes2H        = findobj(gcf,'Tag','Axes2');
      startperiodH  = findobj(gcf,'Tag','startperiod');
      endperiodH    = findobj(gcf,'Tag','endperiod');
      backbuttH     = findobj(gcf,'Tag','backward');
      forwbuttH     = findobj(gcf,'Tag','forward');
      UyplotH       = findobj(gcf,'Tag','Uyplot');
    	marked_seqH   = findobj(gcf,'Tag','marked_seq');
      lastUyH   	  = findobj(gcf,'Tag','lastUy');
      PCplotH       = findobj(gcf,'Tag','PCplot');
      DGPplotH		  = findobj(gcf,'Tag','DGPplot');
      v1lineH		  = findobj(gcf,'Tag','v1line');
      v2lineH		  = findobj(gcf,'Tag','v2line');
      indCurveH     = findobj(gcf,'Tag','indCurve');
      menu_mainaxH  = findobj(gcf,'Tag','Menu_mainax');
      xopt_lH       = findobj(gcf,'Tag','xopt_l');
      xopt_tH       = findobj(gcf,'Tag','xopt_t');
      Sline_ax1H    = findobj(gcf,'Tag','Sline_ax1');
      Eline_ax1H    = findobj(gcf,'Tag','Eline_ax1');
      value_ax1H    = findobj(gcf,'Tag','value_ax1');
      menu_ax1H     = findobj(gcf,'Tag','Menu_ax1');
      plot_ax1H     = findobj(gcf,'Tag','plot_ax1');
      Sline_ax2H    = findobj(gcf,'Tag','Sline_ax2');
      Eline_ax2H    = findobj(gcf,'Tag','Eline_ax2');
      value_ax2H    = findobj(gcf,'Tag','value_ax2');
      menu_ax2H     = findobj(gcf,'Tag','Menu_ax2');
      plot_ax2H     = findobj(gcf,'Tag','plot_ax2');
      
      % load from the current figure the relevant data
      [a,bbeta,sigma1,sigma2,Ustar,theta]      = Userdata('params');
      [newSperiod, newEperiod, markSperiod, N] = Userdata('figure');
      [gamma0,gamma1,xs]                       = Userdata('axes1');
      [Us,ys,v1s,v2s]                          = Userdata('Uyplane');
     
      % check congruence of start & end periods
      if newSperiod <= 0 
         newSperiod = 1;
         set(gcf,'UserData',[newSperiod, newEperiod, markSperiod, N]);
      end
      if newEperiod > N
         newEperiod = N;
         set(gcf,'UserData',[newSperiod, newEperiod, markSperiod, N]);
      end
      
      % text fields for start & end periods 
   	set(startperiodH,'String',sprintf('%d',newSperiod));
   	set(endperiodH,'String',sprintf('%d',newEperiod));
      % deactivate backward & forward buttons (if necessary)
      set(backbuttH,'Enable','on');
   	set(forwbuttH,'Enable','on'); 
      if newEperiod <= 1
         set(backbuttH,'Enable','off');
      end   
      if newEperiod >= N
         set(forwbuttH,'Enable','off');
      end
      % re-draw objects in the U-y plane:
      	%the U-y plot
      set(UyplotH,'YData',ys(newSperiod:newEperiod));
      set(UyplotH,'XData',Us(newSperiod:newEperiod));
      set(marked_seqH,'YData',ys(max([markSperiod,newSperiod]):newEperiod));
      set(marked_seqH,'XData',Us(max([markSperiod,newSperiod]):newEperiod));        
      set(lastUyH,'YData',ys(newEperiod));
      set(lastUyH,'XData',Us(newEperiod)); 
      
      	%the Govnt Phillips curve
      ypointsPC = get(PCplotH,'Userdata');
      newUptsPC = GovntPC(gamma0(newEperiod),gamma1(newEperiod),ypointsPC);
      set(PCplotH,'XData',newUptsPC);
      
      	%the indifference curve
      ypointsIC = get(indCurveH,'Userdata');
      newUptsIC = IndiffCurve(bbeta,gamma0(newEperiod),gamma1(newEperiod),ypointsIC);
      reals = find(~imag(newUptsIC));
      set(indCurveH,'XData',newUptsIC(reals),'YData',ypointsIC(reals));
      
      	%the DGP (Data Generating Process)
      ypointsDGP = get(DGPplotH,'Userdata');
      newUptsDGP = DGP(Ustar,theta,xs(newEperiod),ypointsDGP);
      set(DGPplotH,'XData',newUptsDGP);
      set(v1lineH,'XData',[Us(newEperiod),Us(newEperiod)],...
         			'YData',[xs(newEperiod),ys(newEperiod)]);      
      set(v2lineH,'XData',[Us(newEperiod)-v1s(newEperiod),Us(newEperiod)],...
         			'YData',[ys(newEperiod),ys(newEperiod)]);      
      
      	%x* optimal
      set(xopt_lH,'YData',[xs(newEperiod),xs(newEperiod)]);
      text_pos = get(xopt_tH,'Position');   
      set(xopt_tH,'Position',[text_pos(1),xs(newEperiod)]);
      
      % re-draw the plots in axes 1 & 2
      % and the numeric values in the textboxes
            %axes1
      serie1{1} = gamma0;
      serie1{2} = gamma1;
      serie1{3} = xs;
      value1 = get(menu_ax1H,'Value');
      eval(['data_ax1 = serie1{' num2str(value1) '}(:);']);
      set(plot_ax1H,'YData',data_ax1);
      set(axes1H,'YLim',[floor(min(data_ax1)) ceil(max(data_ax1))]);
      set(value_ax1H,'String',sprintf('%2.3g',data_ax1(newEperiod)));
            %axes2
      serie2{1} = gamma0;
      serie2{2} = ys;
      serie2{3} = xs;
      value2 = get(menu_ax2H,'Value');
      eval(['data_ax2 = serie2{' num2str(value2) '}(:);']);
      set(plot_ax2H,'YData',data_ax2);
      set(axes2H,'YLim',[floor(min(data_ax2)) ceil(max(data_ax2))]);
      set(value_ax2H,'String',sprintf('%2.3g',data_ax2(newEperiod)));
      
      % re-draw period lines in axes 1 & 2
      Ylim_ax1 = get(axes1H,'YLim');
      set(Sline_ax1H,'XData',[newSperiod,newSperiod],'YData',Ylim_ax1);
      set(Eline_ax1H,'XData',[newEperiod,newEperiod],'YData',Ylim_ax1);
      Ylim_ax2 = get(axes2H,'YLim');
      set(Sline_ax2H,'XData',[newSperiod,newSperiod],'YData',Ylim_ax2);
      set(Eline_ax2H,'XData',[newEperiod,newEperiod],'YData',Ylim_ax2);

case 'compute_escapes' %5
      comp_esc_Str = get(gcbo,'String');
      num_esc_valueH = findobj(gcf,'Tag','num_esc_value');
      num_esc_textH  = findobj(gcf,'Tag','num_esc_text');

      if ~(isempty(findstr(comp_esc_Str,'re-compute'))) %re-compute the escapes
         Esclines_ax1H    = findobj(gcf,'Tag','Esclines_ax1');
         Esclines_ax2H    = findobj(gcf,'Tag','Esclines_ax2');      
         delete(Esclines_ax1H);
         delete(Esclines_ax2H);
      else % it is the first time you compute escapes   
         show_esc_buttH   = findobj(gcf,'Tag','show_esc_butt');
         set(show_esc_buttH,'Enable','on');
         set(gcbo,'String','re-compute escapes');
         set([num_esc_valueH num_esc_textH],'Visible','on');
      end    
      axes1H    = findobj(gcf,'Tag','Axes1');
      axes2H    = findobj(gcf,'Tag','Axes2');   
      [a,bbeta,sigma1,sigma2,Ustar,theta] = Userdata('params');
      [gamma0,gamma1,xs]                  = Userdata('axes1');
      esc_points = compute_escapes(gamma0,gamma1,xs,bbeta,theta,Ustar);
      n_escapes  = length(esc_points);
      esc_x      = [esc_points; esc_points];
         %first axis
      axes(axes1H);
      Ylim_ax1 = get(gca,'YLim')';
      esc_y1   = repmat(Ylim_ax1,1,n_escapes);
      Esclines_ax1H = line(esc_x,esc_y1);
      set(Esclines_ax1H,'Color',[0.5 0.5 0.5],'LineStyle','--','Tag','Esclines_ax1');
         %second axis
      axes(axes2H);
      Ylim_ax2 = get(gca,'YLim')';
      esc_y2   = repmat(Ylim_ax2,1,length(esc_points));
      Esclines_ax2H = line(esc_x,esc_y2);
      set(Esclines_ax2H,'Color',[0.5 0.5 0.5],'LineStyle','--','Tag','Esclines_ax2');
         %write the number of escapes
      if (n_escapes == 1) & (esc_points(1) == 0) %there are no escapes in this case
          n_escapes = 0; 
      end   
      set(num_esc_valueH,'String',num2str(n_escapes));
      
case 'show_escapes' %5a
      show_esc_Str = get(gcbo,'String');
      compute_esc_buttH = findobj(gcf,'Tag','compute_esc_butt');
      Esclines_ax1H    = findobj(gcf,'Tag','Esclines_ax1');
      Esclines_ax2H    = findobj(gcf,'Tag','Esclines_ax2');
      num_esc_valueH   = findobj(gcf,'Tag','num_esc_value');
      num_esc_textH    = findobj(gcf,'Tag','num_esc_text');

      if ~(isempty(findstr(show_esc_Str,'hide'))) %hide the escapes
         set(gcbo,'String','show escapes');
         set([Esclines_ax1H Esclines_ax2H],'Visible','off');
         set([compute_esc_buttH num_esc_valueH num_esc_textH],'Visible','off'); 
      else                                        %show the escapes
         set(gcbo,'String','hide escapes');
         set([Esclines_ax1H Esclines_ax2H],'Visible','on');
         set([compute_esc_buttH num_esc_valueH num_esc_textH],'Visible','on'); 
      end%if  
            
case 'select' %6
   	% load the necessary data
      fixedwindowH  = findobj(gcf,'Tag','fixedwindow');     
      [newSperiod, newEperiod, markSperiod, N] = Userdata('figure');
      
      currentPoint = get(gca,'CurrentPoint');
      oldEperiod = newEperiod;
      newEperiod = round(currentPoint(1));
      
      windowIsFixed = get(fixedwindowH,'Value');
      if windowIsFixed
         difference = oldEperiod - newSperiod;
         newSperiod = newEperiod - difference;
      end
      set(gcf,'UserData',[newSperiod, newEperiod, markSperiod, N]);
      sargentCB('redraw')
      
case 'startperiod' %7
   	% load the necessary data
      fixedwindowH  = findobj(gcf,'Tag','fixedwindow');
      [newSperiod, newEperiod, markSperiod, N] = Userdata('figure');
      
      temp = str2num(get(gcbo,'string'));
      if ~isempty(temp)
         newSperiod = temp;
      end   
      oldEperiod = newEperiod;
      if newSperiod >= oldEperiod
         newSperiod = oldEperiod - 1;
      end
      
      windowIsFixed = get(fixedwindowH,'Value');
      if windowIsFixed
         difference = oldEperiod - newSperiod;
         newEperiod = newSperiod + difference;
      end
      set(gcf,'UserData',[newSperiod, newEperiod, markSperiod, N]);
      sargentCB('redraw')

case 'endperiod' %8
   	% load the necessary data
      fixedwindowH  = findobj(gcf,'Tag','fixedwindow');
      [newSperiod, newEperiod, markSperiod, N] = Userdata('figure');
      
      temp = str2num(get(gcbo,'string'));
      if ~isempty(temp)
         newEperiod = temp;
      end   
      oldSperiod = newSperiod;
      if newEperiod <= oldSperiod
         newEperiod = oldSperiod + 1;
      end   
      
      windowIsFixed = get(fixedwindowH,'Value');
      if windowIsFixed
         difference = newEperiod - oldSperiod; 
         newSperiod = newEperiod - difference;
      end     
      
      set(gcf,'UserData',[newSperiod, newEperiod, markSperiod, N]);
      sargentCB('redraw')
      
   case 'motiontype' %9
    	% load the necessary data
      speedsliderH  =findobj(gcf,'Tag','speedslider');
      speedtextH    =findobj(gcf,'Tag','speedtext');
       
      motionvalue = get(gcbo,'Value');
      % Legend for motionvalue:
      %   1 = one step
      %   2 = continuous
      if motionvalue == 1  %motion is one step
         set(speedsliderH,'Visible','off');
         set(speedtextH,'Visible','off');
      else
         set(speedsliderH,'Visible','on');
         set(speedtextH,'Visible','on');        
      end%if
      
   case 'forward' %10
   	% load the necessary data
      fixedwindowH  = findobj(gcf,'Tag','fixedwindow');      
      motiontypeH   = findobj(gcf,'Tag','motiontype');
      backbuttH     = findobj(gcf,'Tag','backward');
      forwbuttH     = gcbo;
      [newSperiod, newEperiod, markSperiod, N] = Userdata('figure');
      
      motionvalue = get(motiontypeH,'Value');
      % Legend for motionvalue:
      %   1 = one step
      %   2 = continuous
      windowIsFixed = get(fixedwindowH,'Value');
      if motionvalue == 1  %motion is one step
         newEperiod = newEperiod + 1;
         if windowIsFixed
		      newSperiod = newSperiod + 1;    
         end
         set(gcf,'UserData',[newSperiod, newEperiod, markSperiod, N]);
         sargentCB('redraw')
      else                 %motion is continuous
         speedsliderH  =findobj(gcf,'Tag','speedslider');
         StopMotion = 0;
         MotionDirection = +1;
         set(gcbf,'WindowButtonDownFcn','sargentCB stopmotion');
         set(backbuttH,'CallBack','sargentCB motiondirisback'); 
         set(forwbuttH,'CallBack','sargentCB motiondirisforw'); 
         while 1,
            newEperiod = newEperiod + MotionDirection;
            if windowIsFixed
		         newSperiod = newSperiod + MotionDirection;    
            end
            set(gcf,'UserData',[newSperiod, newEperiod, markSperiod, N]);
            sargentCB('redraw')
            if (newEperiod >= N) | (StopMotion) 
               break
            end   
            pause(2 - 2*get(speedsliderH,'Value'));
         end%while
         set(backbuttH,'CallBack','sargentCB backward'); 
         set(forwbuttH,'CallBack','sargentCB forward'); 
         set(gcbf,'WindowButtonDownFcn','');
    	end%if motionvalue
      
   case 'backward' %11
   	% load the necessary data
      fixedwindowH  = findobj(gcf,'Tag','fixedwindow');      
      motiontypeH   = findobj(gcf,'Tag','motiontype');
      backbuttH     = gcbo;
      forwbuttH     = findobj(gcf,'Tag','forward');
     [newSperiod, newEperiod, markSperiod, N] = Userdata('figure');
      
      motionvalue = get(motiontypeH,'Value');
      % Legend for motionvalue:
      %   1 = one step
      %   2 = continuous
      windowIsFixed = get(fixedwindowH,'Value');
      if motionvalue == 1  %motion is one step
         newEperiod = newEperiod - 1;
         if windowIsFixed
		      newSperiod = newSperiod - 1;    
         end
         set(gcf,'UserData',[newSperiod, newEperiod, markSperiod, N]);
         sargentCB('redraw')
		else                 %motion is continuous
         speedsliderH  =findobj(gcf,'Tag','speedslider');
         StopMotion = 0;
         MotionDirection = -1;
         set(gcbf,'WindowButtonDownFcn','sargentCB stopmotion');
         set(backbuttH,'CallBack','sargentCB motiondirisback'); 
         set(forwbuttH,'CallBack','sargentCB motiondirisforw'); 
         while 1,
            newEperiod = newEperiod + MotionDirection;
            if windowIsFixed
		         newSperiod = newSperiod + MotionDirection;    
            end
            set(gcf,'UserData',[newSperiod, newEperiod, markSperiod, N]);
            sargentCB('redraw')
             if (newEperiod <= 1) | (StopMotion) 
               break
            end   
            pause(2 - 2*get(speedsliderH,'Value'));
         end%while
         set(backbuttH,'CallBack','sargentCB backward'); 
         set(forwbuttH,'CallBack','sargentCB forward'); 
         set(gcbf,'WindowButtonDownFcn','');
		end%if motionvalue     
    
case 'stopmotion' %12
      StopMotion = 1;
      
case 'motiondirisforw' %13
      MotionDirection = +1;
      
case 'motiondirisback' %14
      MotionDirection = -1;
   
case 'Ustar' %15
   	% load the necessary handles
      Ustar_tH  = findobj(gcf,'Tag','Ustar_t');      
      Ustar_lH  = findobj(gcf,'Tag','Ustar_l');
      
      Ustar_line = get(Ustar_lH,'Visible');
      if isempty(findstr(Ustar_line,'off'))
         set(Ustar_lH,'Visible','off');
    %     set(Ustar_tH,'Visible','on');
      else
         set(Ustar_lH,'Visible','on');
    %     set(Ustar_tH,'Visible','off');
      end
                  
case 'DGP' %16
   	% load the necessary data
      DGPplotH  = findobj(gcf,'Tag','DGPplot');
      v1lineH   = findobj(gcf,'Tag','v1line');
      v2lineH   = findobj(gcf,'Tag','v2line');
      Ustar_lH  = findobj(gcf,'Tag','Ustar_l');
      xopt_lH   = findobj(gcf,'Tag','xopt_l');
      xopt_tH   = findobj(gcf,'Tag','xopt_t');
      xopt_buttH = findobj(gcf,'Tag','xopt_butt');

      DGPStr = get(gcbo,'String');
      if isempty(findstr(DGPStr,'hide'))
         set(gcbo,'String','hide DGP');
         set(DGPplotH,'Visible','on');
         set(v1lineH,'Visible','on');
         set(v2lineH,'Visible','on');
         set(Ustar_lH,'Visible','on');
         set(xopt_lH,'Visible','on');
         set(xopt_tH,'Visible','on');
         set(xopt_buttH,'String','hide target inflation');
      else
         set(gcbo,'String','DGP');
         set(DGPplotH,'Visible','off');    
         set(v1lineH,'Visible','off');
         set(v2lineH,'Visible','off');
   	end
      sargentCB('redraw')
      
   case 'perceived_PC' %17
   	% load the necessary data
      perceived_PCH  = findobj(gcf,'Tag','PCplot');
      
      perceived_PCStr = get(gcbo,'String');
      if isempty(findstr(perceived_PCStr,'hide'))
         set(gcbo,'String','hide perceived PC');
         set(perceived_PCH,'Visible','on');

      else
         set(gcbo,'String','perceived PC');
         set(perceived_PCH,'Visible','off');
   	end      
      sargentCB('redraw')
    
case 'mark_seq' %18
   	% load the necessary data
      marked_seqH  = findobj(gcf,'Tag','marked_seq');
      lastUyH  	 = findobj(gcf,'Tag','lastUy');
      [newSperiod, newEperiod, markSperiod, N] = Userdata('figure');
      
      mark_seqStr = get(gcbo,'String');
      if isempty(findstr(mark_seqStr,'UNmark'))
         set(gcbo,'String','UNmark sequence');
         markSperiod = newEperiod;
         set(marked_seqH,'Visible','on');
         set(gcf,'UserData',[newSperiod, newEperiod, markSperiod, N]);
         sargentCB('redraw')
      else
         set(marked_seqH,'Visible','off');        
         set(gcbo,'String','mark sequence');
   	end      
      
case 'dots' %19
   	% load the necessary handles
      UyplotH      = findobj(gcf,'Tag','Uyplot');
      marked_seqH  = findobj(gcf,'Tag','marked_seq');
      
      marktype = get(gcbo,'String');
      if isempty(findstr(marktype,'thin'))
         set(UyplotH,'MarkerSize',5);
         set(marked_seqH,'MarkerSize',5);
         set(gcbo,'String','thin dots');
      else
         set(UyplotH,'MarkerSize',3);
         set(marked_seqH,'MarkerSize',3);
         set(gcbo,'String','thick dots');         
      end%if
      
case 'xoptimal' %20
   	% load the necessary handles
      xopt_lH     = findobj(gcf,'Tag','xopt_l');
      xopt_tH     = findobj(gcf,'Tag','xopt_t');
            
      xoptStr = get(gcbo,'String');
      if isempty(findstr(xoptStr,'hide'))
         set(gcbo,'String','hide target inflation');
         set(xopt_lH,'Visible','on');        
         set(xopt_tH,'Visible','on');        
      else
         set(gcbo,'String','target inflation');
         set(xopt_lH,'Visible','off');        
         set(xopt_tH,'Visible','off');        
 	end
      sargentCB('redraw')

case 'ind_curves' %21     
   	% load the necessary handles
      indCurveH    = findobj(gcf,'Tag','indCurve');
            
      indCurvetype = get(gcbo,'String');
      if isempty(findstr(indCurvetype,'hide'))
         set(indCurveH,'Visible','on');
         set(gcbo,'String','hide indiff. curve');
      else
         set(indCurveH,'Visible','off');
         set(gcbo,'String','indiff. curve');
      end%if
      sargentCB('redraw')
   
end%switch


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                      Auxiliary subfunctions                         %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
   
function [gamma,R,x,y,U,v] = sargent(gamma,R,x,y,U,a,bbeta,sigma1,sigma2,Ustar,theta)
% Perform one iteration of the system   
gamma = gamma + a*inv(R)*[1 y]'*(U - gamma(1) - gamma(2)*y);
R = R + a*([1 y]'*[1 y]- R);
v = diag([sigma1 sigma2])*randn(2,1);
U = Ustar - theta*v(2) + v(1);
x = h0(gamma,bbeta);
y = x + v(2);

function x = h0(gamma,bbeta)
% Self Conf. Equilibrium level of inflation
x = -(gamma(1)*gamma(2))/(bbeta + gamma(2)^2);

function U = GovntPC(gamma0,gamma1,y)
% Unemployment from the Government PC 
U = gamma0 + gamma1*y;

function U = DGP(Ustar,theta,xopt,y)
% abscissa values for the Data Generating process 
U = Ustar + theta*xopt - theta*y;

function U = IndiffCurve(bbeta,gamma0,gamma1,y)
% abscissa values for the Indifference Curve 
ValuesIC = (bbeta*gamma0^2)/(bbeta+gamma1^2)*0.998;
U = sqrt(ValuesIC - bbeta*(y.^2));

function esc_points = compute_escapes(gamma0,gamma1,xs,bbeta,theta,Ustar)
% vector of periods where an escape begin
threshold_in  = -0.2;
threshold_out = -0.25;
% initializations for the cycle
n_escapes = 0;            % count the escapes
was_Ramsey = 0;           % logical flag: =1 if I was already in a nbhd of R.
esc_points = 0;           % vector containing the results
% count the escapes 
for period = 1:length(xs)
   if (gamma1(period) > threshold_in) & ~(was_Ramsey)
       was_Ramsey = 1;
       n_escapes = n_escapes + 1;
       esc_points(n_escapes) = period;
   end         
   if (gamma1(period) < threshold_out) & (was_Ramsey)
       was_Ramsey = 0;
   end 
end %for period

function h = xSCE(bbeta,theta,Ustar)
% Inflation target for the govn.t in an SCE (Self Conf. Equilibrium)
h = (theta*Ustar)/bbeta;

function [varargout] = Userdata(sourceH)
switch(sourceH)
case 'figure'
   [t,figure] = gcbo; 
   rawdata = get(figure,'UserData'); 
   [t,numdat] = size(rawdata);
   for i=1:numdat, varargout{i} = rawdata(i); end
case 'params'
   paramsH  = findobj(gcf,'Tag','params');
   rawdata = get(paramsH,'UserData');
   [t,numdat] = size(rawdata);
   for i=1:numdat, varargout{i} = rawdata(i); end
case 'axes1'
   axes1H  = findobj(gcf,'Tag','Axes1');
   rawdata = get(axes1H,'UserData'); 
   [t,numdat] = size(rawdata);
   for i=1:numdat, varargout{i} = rawdata{i}(:); end
%case 'axes2'
%   axes2H  = findobj(gcf,'Tag','Axes2');
%   rawdata = get(axes2H,'UserData');
%   [t,numdat] = size(rawdata);
%   for i=1:numdat, varargout(i) = {rawdata(i)}; end
case 'Uyplane'
   UyplaneH  = findobj(gcf,'Tag','Axes3');
   rawdata = get(UyplaneH,'UserData');
   [t,numdat] = size(rawdata);
   for i=1:numdat, varargout{i} = rawdata{i}(:); end
   
end%switch(sourceH)   
   
