function result = euler(c,x,X,cprev,stoch,beta,R,theta,y,sigma)
% The function returns the LHS minus the RHS of the Euler equation.
% c is a scalar with the proposed value for the new policy rule
% x is a scalar for cash-in-hand
% X and cprev are vectors containing the previous policy rule
% stoch = 1 for the stochastic model, 0 for perfect foresight
% The other arguments are model parameters.

LHS = c^(-theta);

if stoch == 0
    X_tplus1 = R*(x-c) + y;
    c_tplus1 = interp1(X,cprev,X_tplus1,'linear','extrap');
    E = c_tplus1^(-theta);
elseif stoch == 1
    X_tplus1_H = R*(x-c) + y + sigma;
    X_tplus1_L = R*(x-c) + y - sigma;
    c_tplus1_H = interp1(X,cprev,X_tplus1_H,'linear','extrap');
    c_tplus1_L = interp1(X,cprev,X_tplus1_L,'linear','extrap');
    E = .5*c_tplus1_H^(-theta) + .5*c_tplus1_L^(-theta);
else
    error('invalid value for stoch');
end
RHS = beta*R*E;
result = LHS - RHS;

if isnan(result) | isinf(result) | c < 0
    result = c^2;
end

