function [Pa,Pe,EE] = CRRmDaeP(T,S0,K,Di,ri,v,N) 
% Octave/MATLAB function to price American and
% European Put options on an asset decomposed
% into S=Sx+Ipv by CRRD(), using the modified
% Cox-Ross-Rubinstein (CRR) yield curve model.
% INPUTS:                             (Example)
%   T =  expiration time               (1 year)
%   S0 = stock price                      (100)
%   K =  strike price                     (101)
%   Di = dividend sequence 2:N+2    (see below)
%   ri = risk-free APRs 1:N+1       (see below)
%   v =  volatility; must be >0          (0.15)
%   N =  height of the binomial tree       (12)
% OUTPUT:
%   Pa =  price of American Put at all (n,j).
%   Pe =  price of European Put at all (n,j).
%   EE =  Is early exercise optimal at (n,j)?
% EXAMPLE:
%   Di=[0 1 0 0 1 0 0 2 0 0 2 0 0 2]; % Di(k+1)=D_k
%   ri=[1 1 1 1 1 2 2 2 2 2 3 3 3]/100; % ri(k+1)=r_k
%   [Pa,Pe,EE]=CRRmDaeP(1,100,101,Di,ri,0.15,12);
%
  [pui,up,Ri]=CRRparams(T,ri,v,N); % Modified CRR
  [S,Sx,Ipv]=CRRmD(T,S0,Di,ri,v,N); % decompose
  Pa=zeros(N+1,N+1); Pe=zeros(N+1,N+1); % output
  EE=zeros(N,N); % early exercise optimal? T/F
  for j=0:N  % to set terminal values at (N,j)
    xP=K-S(N+1,j+1); % Put payoff at expiry is the
    Pa(N+1,j+1)=Pe(N+1,j+1)=max(xP,0); % plus part
  end
  for n=(N-1):(-1):0 % textbook time indices
    for j=0:n % states j={0,1,...,n} at time n
      % Backward pricing for A and E:
      bPe=(pui(n+1)*Pe(n+2,j+2) + ...
	   (1-pui(n+1))*Pe(n+2,j+1))/Ri(n+1);   
      bPa=(pui(n+1)*Pa(n+2,j+2) + ...
	   (1-pui(n+1))*Pa(n+2,j+1))/Ri(n+1);   
      xP=K-S(n+1,j+1); % Put exercise value
      % Set prices at node (n,j):
      Pe(n+1,j+1)=bPe; % always binomial price
      Pa(n+1,j+1)=max(bPa,xP); % highest price
      % Is early exercise optimal?
      EE(n+1,j+1)=(xP>bPa); % Yes, if xP>bPa
    end
  end % ...backward induction pricing:
  return; % Pa,Pe, and EE are defined.
end
