function [C, P] = CRRa(T, S0, K, r, v, N) 
% Octave/MATLAB function to price American Call
% and Put options using the Cox-Ross-Rubinstein
% (CRR) binomial pricing model.
% INPUTS:                             (Example)
%   T =  expiration time               (1 year)
%   S0 = spot stock price                  (90)
%   K =  strike price                      (95)
%   r =  risk-free yield                 (0.02)
%   v =  volatility; must be >0          (0.15)
%   N =  height of the binomial tree       (10)
% OUTPUT:
%   C =  price of the Call option at all (n,j).
%   P  =  price of the Put option at all (n,j).
% EXAMPLE:
%   [C,P] = CRRa(1, 90, 95, 0.02, 0.15, 10);
%   C(1,1),P(1,1)  % to get just C(0) and P(0)
%
  [pu,up,R] = CRRparams(T,r,v,N); % Use CRR values 
  C=zeros(N+1,N+1); P=zeros(N+1,N+1); % Initial C,P
  for j = 0:N  % Set terminal values at time step N
    V = S0*up^(2*j-N)-K;   % S(N,j) - K
    C(N+1,j+1)=max(V,0); P(N+1,j+1) = max(-V,0);
  end
  for n = (N-1):(-1):0 % Price earlier grid values
    for j = 0:n  % states j={0,1,...,n} at time n
      % Binomial pricing model value
      bC=(pu*C(n+2,j+2) + (1-pu)*C(n+2,j+1))/R;   
      bP=(pu*P(n+2,j+2) + (1-pu)*P(n+2,j+1))/R;   
      % Exercise value: X for Call, -X for Put
      X = S0*up^(2*j-n)-K;  % S(n,j) - K
      % Price at this node is the larger:
      C(n+1,j+1)=max(bC,X); P(n+1,j+1)=max(bP,-X);
    end
  end
  return; % Prices are in matrices C and P.
end
