function LadP = CRRladP(T,S0,K,L,r,v,N)
% Octave/MATLAB function to price a ladder Put
% option using a Cox-Ross-Rubinstein (CRR) model.
% INPUTS:                           (Example)
%   T  = expiration time in years   (1)
%   S0 = spot price                 (50)
%   K  = strike price               (55)
%   L  = decreasing prices < S0,K   ([45,40,35])
%   r  = riskless yield per year    (0.05)
%   v  = volatility; must be >0     (0.20)
%   N  = height of the tree         (4)
% OUTPUTS:
%   LadP = Ladder Put option price array.
% EXAMPLE:
%   LadP=CRRladP(1,50,55,[45,40,35],0.05,0.20,4)
%
  [pu,up,R] = CRRparams(T,r,v,N);
  Sbar=NRTCRR(S0,up,1/up,N); % S as an NRT
  MinS=NRTmin(Sbar,N); % non-recombining min tree
  LadP=zeros(size(Sbar)); % Put prices NRT
  % Initialize with the payoffs at expiry:
  k=length(L);        % number of ladder levels, >1
  for m=2^N:2*2^N -1  % state indexes at expiry
    if(MinS(m)>L(1)) % above level L(1) is special
      LadP(m)=max(K-Sbar(m),0);
    else % MinS =< L(1)
      if(MinS(m)>L(k)) % ...use levels L(2)>...>L(k)
        for l=2:k      % loop to find the level
          if(MinS(m)>L(l))
            LadP(m)=max(max(K-Sbar(m),K-L(l-1)),0);
            break; % found l: L(l)<MinS=<L(l-1),
          end
        end       % ... so exit the "l" loop
      else % MinS=<L(k), another special case
        LadP(m)=max(max(K-Sbar(m),K-L(k)),0);
      end
    end
  end
  for m=(2^N-1):-1:1 % backward recursion
    LadP(m)=(pu*LadP(2*m+1)+(1-pu)*LadP(2*m))/R;
  end
  return % LadP(1) is the option premium
end
