function [Cash,Rule] = lsm(T)

%Repeating the calculations shown in Paper of Longstaff and Schwartz

r = 1.05;

degree = 2;

K = 30;

% t0 = [1   , 1   , 1   , 1   , 1   , 1   , 1   , 1   ]';
% t1 = [1.09, 1.16, 1.22, 0.93, 1.11, 0.76, 0.92, 0.88]';
% t2 = [1.08, 1.26, 1.07, 0.97, 1.56, 0.77, 0.84, 1.22]';
% t3 = [1.34, 1.54, 1.03, 0.92, 1.52, 0.90, 1.01, 1.34]';
% 
% T = [t0,t1,t2,t3];

X = zeros(size(T,1),size(T,2)-1);
ImEx = zeros(size(T,1),size(T,2)-1);
Con = zeros(size(T,1),size(T,2)-1);
Cash = zeros(size(T,1),size(T,2)-1);
Rule = zeros(size(T,1),size(T,2)-1);

CEF = zeros(size(T,1),3);

starti = (size(T,2)-1);

for i = starti:-1:2

if i == starti
    Cash(:,i) = K - T(:,i+1);
    Cash((Cash(:,i) <= 0),i) = 0;
end

X(T(:,i)<K,i) = T(T(:,i)<K,i);

%If I want to log Y, I should log it in a Cell as Ysmall.

Xsmall = T((T(:,i)<K),i);
Ysmall = Cash((T(:,i)<K),i)/r;

%Entries that go in Y

%Could use N > 2 if want prob.
CEF(i,:) = polyfit(Xsmall,Ysmall,degree);

ImEx((X(:,i)>0),i) = K - X((X(:,i)>0),i);

Con((X(:,i)>0),i) = polyval(CEF(i,:),Xsmall);

Cash((Con(:,i)<ImEx(:,i)),i-1) = ImEx((Con(:,i)<ImEx(:,i)),i);
Cash((Con(:,i)<ImEx(:,i)),i) = 0;
%Now for time 1

end

Rule(Cash ~= 0) = 1;











