function [ prc,opt ] = crr( S,X,rf,T,dt,sig,type )
% The output will be the bionomial tree of the underlying asset's
% price(prc) and the bionomial tree of the option price(opt)
% Both the bionomial trees will be in the form of
% S is the underlying asset price;
% X is the option exercise;
% rf is the risk free interest rate;
% T is the option's time until maturity in years;
% dt is the time incremental within T;
% sig is the volaility of the underlying asset's annualized return
% if type=1 then the option is a call option and if type =0 the option is a put option.
% Calculate the number of periods and rebalance the length of each interval
n=round(T/dt);
dt=T/n;
N=n+1;
% Calculate the magnitude of an upward price movement as well as the risk
% neutral probability
u=exp(sig*sqrt(dt));
d=1/u;
p=(exp(rf*dt)-d)/(u-d);
%Construct the asset price binomial matrix
jspan=-fix(n*.5);
ispan=rem(round(T/dt),2);
i=ispan:(n+ispan);
j=(jspan:(n+jspan))';
jex=j(:,ones(size(i')));
iex=i(ones(size(j)),:);
prc=triu(rot90(S*u.^(2*jex-iex),2));
%Construct the option price binomial matrix
opt=zeros(size(prc));
if type==1
opt(:,N)=max(prc(:,N)-X,0);
for a=n:-1:1
for b=1:a
opt(b,a)=(p*opt(b,a+1)+(1-p)*opt(b+1,a+1))*exp(-rf*dt);
end
end
elseif type==0
opt(:,N)=max(X-prc(:,N),0);
for a=n:-1:1
for b=1:a
opt(b,a)=(p*opt(b,a+1)+(1-p)*opt(b+1,a+1))*exp(-rf*dt);
end
end
end