% Applied Computational Economics (Nottingham, 2020)
% Problem Set 2 (RCE with Representative Households)
% AHS, September 2019

% Function for the piecewise linearly interpolated value function

% Inputs are (x, xp, x_grid, y_grid, u, t) where
    % x is the point (current capital stock)
    % xp is the control choice (next period's capital stock)
    % x_grid is the set of gridpoints for the first independent variable
    % y_grid is the set of gridpoints for the dependent variable
    % u is an additional variable (the interest rate for us here)
    % t is an additional variable (the wage for us here)
    
function approx_eval = lin_int_v_PS3_2022(x, xp, x_grid, y_grid, u, t)
    
    global beta sigma delta 
  
    B = zeros(length(x_grid),1);    % vector of coefficients
    
    % Fill the vector of coefficients for each interval
    for i = 1: (length(x_grid)-1) 
    
        B(i,1) = (x_grid(i+1)-xp)/(x_grid(i+1,1)-x_grid(i,1));
        
    end
    
    % Generate the function evaluation based-on which interval x falls into
    for i = 1: (length(x_grid)-1)
 
        if (xp >= x_grid(i,1) && xp < x_grid(i+1,1))
                
            vp = (B(i,1)*y_grid(i,1) + (1-B(i,1))*y_grid(i+1,1));
            
        end
        
    end
    
    c = x*(1-delta+u) - xp + t;
    
    if (c < 0) 
        
        approx_eval = -10000000;
        
    else
        
        approx_eval = c^(1-sigma)/(1-sigma) + beta*vp;
        
    end
   
    % The optimiser we'll use gives back negative objectives
    approx_eval = -approx_eval;
    
end