function C = CRRruoC(T,S0,K,B,refund,r,v,N) 
% Octave/MATLAB function to price up-and-out barrier
% Call options with a refund at knock-out 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)
%   refund =  rebate paid if the            (17)
%             option knocks out at
%             the barrier price
%   r =  risk-free annual yield          (0.05)
%   v =  volatility; must be >0          (0.20)
%   N =  height of the binomial tree        (4)
% OUTPUT:
%    C =  price of the option at all (n,j).
% EXAMPLE:
%   uorCa = CRRruoC(1,100,80,120,17,0.05,0.20,4);
%
  [pu,up,R] = CRRparams(T,r,v,N); % Use CRR values 
  C=zeros(N+1,N+1); % allocate the 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) = refund; % ...with a rebate
    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 % states j={0,1,...,n} at time n
      % Test the barrier
      Snj = S0*up^(2*j-n); % asset price S(n,j)
      if(Snj < B) % then barrier is 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 % barrier exceeded, so option vanishes
        C(n+1,j+1) = refund; % ...with a rebate
      end
    end
  end
  return  %  Prices in C are now fully defined.
end
