%% calcUDiff
% 
% Calculates the difference in utility between maximized utility uStar and
% utility at arbitrary earnings z, for ability n, elasticity e, net of
% adjustment cost phi, and given tax structure tax.

function [uD, gradUD] = calcUDiff(uStar, z,n,e, phi, tax)
    
    % Calculate consumption under nonlinear tax rate
    c = z - (tax.t0.*z + (tax.t1-tax.t0).*(z-tax.zStar).*(z>tax.zStar));
    
    % Calculate utility
    uZ = c - (z./n).^(1+1/e) .* n ./ (1+1/e);
    uD = uStar - uZ - phi;
    
    % calculate gradient wrt z (note: does not exist at zStar)
    gradCZ = 1 - (tax.t0 + (tax.t1-tax.t0).*(z>tax.zStar));
    gradUD = -diag(gradCZ - (z./n).^(1/e));
    
end