% Apply a fixed consumption-saving policy on sample scenarios
% Used both to optimize (in sample) and test (out of sample)
function [objVal, utilVals, consPaths, wealthPaths] = ...
    RunFixedPolicy(X, W0, empl0, utilFun, gamma, incomeValues, ...
        riskFree, retSampleScenarios, emplSampleScenarios)
% Unpack decision variables
fractCons = X(1); alpha = X(2);
[numScenarios, timeHorizon] = size(retSampleScenarios);
consPaths = zeros(numScenarios, timeHorizon+1); % from 0 to T
wealthPaths = zeros(numScenarios, timeHorizon+1);
utilVals = zeros(numScenarios,1);
% start simulation scenarios
for k = 1:numScenarios
    % set available wealth at time 0
    finWealth = W0;
    emplNow = empl0;
    wealthNow = finWealth + incomeValues(emplNow);
    % Now carry out forward simulation, for t from 0 to T-1
    for t = 0:(timeHorizon-1)
        wealthPaths(k,t+1) = wealthNow;
        C = fractCons * wealthNow;
        consPaths(k,t+1) = C;
        utilVals(k) = utilVals(k) + gamma^(t)*feval(utilFun,C);
        % generate next wealth according to return and employment scenario
        wealthNow = incomeValues(emplSampleScenarios(k, t+1))+...
            (wealthNow-C)*(1+riskFree+ ...
                            alpha*(retSampleScenarios(k,t+1)-riskFree)); 
    end % for time 
    % include last income and consume all available wealth at time horizon 
    wealthPaths(k,timeHorizon+1) = wealthNow; 
    consPaths(k,timeHorizon+1) = wealthNow;
    utilVals(k) = utilVals(k)+gamma^(timeHorizon)*feval(utilFun, wealthNow);
end % for k in simulated scenarios
objVal = mean(utilVals);





