function [P,C]=BinomialAmerican(Q,S,r,g)
h=Q(2)-Q(1);
%syms x;
%f = sym(g);
N=length(Q)-1;
expu=S(1,2)/S(1,1);
expd=S(2,2)/S(1,1);
qu=(exp(r*h)-expd)/(expu-expd);
qd=(expu-exp(r*h))/(expu-expd);
if (qu<0 || qd<0)
display('Error: the market is not arbitrage free.');
P=0;
return
end
P=zeros(N+1);
P(:,N+1)=g(S(:,N+1));
C(:,N+1)=0;
Y=g(S);
for j=N:-1:1
for i=1:j
P(i,j)=max(Y(i,j),exp(-r*h)*(qu*P(i,j+1)+qd*P(i+1,j+1)));
C(i,j)=P(i,j)-exp(-r*h)*(qu*P(i,j+1)+qd*P(i+1,j+1));
end
end

