function [C, P] = CRRbin(T, S0, K, B, r, v, N) 
% Octave/MATLAB function to price binary Call and Put
% options using the Cox-Ross-Rubinstein (CRR) model.
%  INPUTS:                                  (Example)
%    T =  expiration time in years          (1)
%    S0 = spot stock price                  (90)
%    K =  strike price                      (95)
%    B =  payoff at expiry                  (20)
%    r =  risk-free yield per year          (0.02)
%    v =  volatility; must be >0            (0.15)
%    N =  height of the binomial tree       (10)
%  OUTPUTS:
%    C = Call option price at all gridpoints (n,j).
%    P = Put option price at all gridpoints (n,j).
%  EXAMPLE:
%   [C, P] = CRRbin(1, 90, 95, 20, 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
    SNj = S0 * up^(2*j-N);   % Asset price S(N,j)
    if( SNj > K )
      C(N+1,j+1) = B; % ...trigger the Call payoff
    end
    if( SNj < K )
      P(N+1,j+1) = B; % ...trigger the Put payoff
    end
  end  % ...otherwise the payoff is zero.
  for n = N-1:-1:0   %  Price earlier grid values
    for j = 0:n  % ...by backward pricing formula
      C(n+1,j+1)=(pu*C(n+2,j+2)+(1-pu)*C(n+2,j+1))/R;   
      P(n+1,j+1)=(pu*P(n+2,j+2)+(1-pu)*P(n+2,j+1))/R;   
    end
  end
  return; % Prices in matrices C and P are all defined.
end
