function C = CRRpuoC(T,S0,K,B,r,v,N,N0) 
% Octave/MATLAB function to price partial 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 yield                     (0.05)
%   v =  volatility; must be >0              (0.20)
%   N =  height of the binomial tree            (4)
%   N0 =  first barrier test time;              (3)
%          must satisfy 0 < N0 < N
% OUTPUT:
%   C =  price at all gridpoints (n,j).
% EXAMPLE:
%  puoCa = CRRpuoC(1,100,80,120,0.05,0.20,4,3);
%
  [pu,up,R] = CRRparams(T,r,v,N); % Use CRR values 
  C=zeros(N+1,N+1); % allocate output matrix
  for j=0:N  %  set 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
      C(N+1,j+1) = max( SNj - K, 0 );
    else     % barrier exceeded, so option vanishes
      C(N+1,j+1) = 0;
    end
  end
  % Use backward induction to price earlier values:
  for n = (N-1):(-1):0  % grid times n={N-1,..., 0}
    for j = 0:n    % states j={0,1,...,n} at time n
      % Test the barrier
      Snj = S0*up^(2*j-n);   % asset price S(n,j)
      if(n < N0 || Snj < B)  % too early, or else
                             % barrier not exceeded
      % ...so use the binomial pricing model value
        C(n+1,j+1)=(pu*C(n+2,j+2)+(1-pu)*C(n+2,j+1))/R;   
      else % time after N0 and barrier exceeded,
           % so option vanishes
        C(n+1,j+1) = 0;
      end
    end
  end
  return; %  Prices in C are now defined.
end
