function Call = CRRuoC(T,S0,K,B,r,v,N) 
% Octave/MATLAB function to price up-and-out 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 annual yield           (0.05)
%    v =  volatility; must be >0           (0.20)
%    N =  height of the binomial tree        (40)
% OUTPUT:
%    Call =  price of the option at all (n,j).
% EXAMPLE:
%    uoCa = CRRuoC(1,100,80,120,0.05,0.20,40);
%
  [pu,up,R] = CRRparams(T,r,v,N); % Use CRR values 
  Call=zeros(N+1,N+1);  % allocate output matrix
  for j=0:N  % set the values at expiry step N
    SNj=S0*up^(2*j-N);    % asset price S(N,j)
    if(SNj < B) % then the barrier is not exceeded
      Call(N+1,j+1) = max( SNj - K, 0 );
    else     % barrier exceeded, so option vanishes
      Call(N+1,j+1) = 0;
    end
  end % use backward induction to price the rest
  for n=(N-1):(-1):0 % grid times n={N-1,..., 0}
    for j=0:n % test the barrier in all states j
      Snj = S0*up^(2*j-n); % asset price S(n,j)
      if(Snj < B) % then barrier is not exceeded
        Call(n+1,j+1)=( pu*Call(n+2,j+2)...
         +(1-pu)*Call(n+2,j+1) )/R; % bin. price
      else % barrier exceeded, so option vanishes
        Call(n+1,j+1) = 0;
      end
    end
  end
  return   %  Prices in Call matrix are now defined.
end
