function [Exotic, Vanilla] = CRRuiC(T,S0,K,B,r,v,N) 
%  Octave/MATLAB function to price up-and-in barrier
%  Call options using the Cox-Ross-Rubinstein (CRR)
%  binomial pricing model.
%  INPUTS:                             (Example)
%    T =  expiration time               (1 year)
%    S0 = spot stock price                 (100)
%    K =  strike price                      (80)
%    B =  barrier price                    (120)
%    r =  risk-free yield                 (0.05)
%    v =  volatility; must be >0          (0.20)
%    N =  height of the binomial tree       (40)
%  OUTPUT:
%    Exotic =  price of the option at all (n,j).
%    Vanilla =  price of European Call at (n,j).
%  EXAMPLE:
%   [uiCa, eCa] = CRRuiC(1,100,80,120,0.05,0.20,40);
%
  [pu,up,R] = CRRparams(T,r,v,N); % Use CRR values 
  Exotic=zeros(N+1,N+1); Vanilla=zeros(N+1,N+1);
  for j = 0:N  %  set values at expiry step N
    SNj = S0*up^(2*j-N); % asset price S(N,j)
    Vanilla(N+1,j+1)=max(SNj-K, 0); % plain Eur.Call
    if(SNj < B) % barrier not exceeded, so no Exotic 
      Exotic(N+1,j+1) = 0;
    else  % barrier exceeded, so Exotic is created
      Exotic(N+1,j+1) = Vanilla(N+1,j+1);
    end
  end  % Now price earlier values by induction:
  for n = (N-1):(-1):0  % grid times n={N-1,...,0}
    for j = 0:n % states j={0,1,...,n} at time n
      Vanilla(n+1,j+1)=( pu*Vanilla(n+2,j+2)...
        + (1-pu)*Vanilla(n+2,j+1))/R; % all cases
      % Test the barrier
      Snj = S0*up^(2*j-n); % asset price S(n,j)
      if(Snj<B) % barrier not exceeded, so use Exotic
        Exotic(n+1,j+1)=(pu*Exotic(n+2,j+2)...
          +(1-pu)*Exotic(n+2,j+1) )/R; % bin. price
      else   % barrier exceeded, so use Vanilla
        Exotic(n+1,j+1) = Vanilla(n+1,j+1);   
      end
    end
  end
  return % Prices are in matrices Exotic and Vanilla.
end
