% -------------------------------------------------------------------------
%
% Project: Uneven Growth
%
% Purpose: routine to calibrate rho
%
% -------------------------------------------------------------------------

function rho = calibration_routine_v09(r_target,Parameter)

% - grid for rho ----------------------------------------------------------
N=1000;
rho_grid=linspace(0,r_target-Parameter.sigma*Parameter.g,N);
rk=zeros(1,N);

for n=1:N
   
    Parameter.rho=rho_grid(n);
    
    if (n==1)
    % - Initialize Guess ------------------------------------------------------
    % - Note: equations_v05 accepts log(k), b, log(rb-g) ----------------------
    Solution0    = zeros(3,1);
    Solution0(1) = log((Parameter.alpha/(1-Parameter.alpha)) ...
                   /(Parameter.delta+Parameter.rho+Parameter.sigma*Parameter.g)); 
             % log of normalized capital (k in notes)
    Solution0(2) = Parameter.govbonds;                                          
             % normalized bond holdings of households (b in notes)
    Solution0(3) = log(Parameter.rho+(Parameter.sigma-1)*Parameter.g);            
             % log of return to bonds (rb in notes) - g
             
    else % Use previous result
        Solution0 = Solution;
    end
    
    % - load solver -----------------------------------------------------------
    options=optimset('disp','off','LargeScale','off', ...
                 'TolFun',.00000001,'MaxFunEvals',10^7,'MaxIter',10^7);
    Solution = fsolve(@(Solution)equations_v09(Solution,Parameter),Solution0,options);
    Check=equations_v09(Solution,Parameter);
    assert(max(abs(Check))<0.0001);  
    
    k_norm       = exp(Solution(1));
    rb          = Parameter.g+exp(Solution(3));
    rk(n)       = (Parameter.alpha/(1-Parameter.alpha))*(rb-Parameter.g)/k_norm - Parameter.delta;
  
end

[~,index]=min(abs(rk-r_target));

rho=rho_grid(index);
    
end