function price = LongstaffSchwartz(S0,X,r,T,sigma,NSteps,NRepl)
dt = T/NSteps;
discount = exp(-r*dt);
% discount rates over different time intervals
discountVet = exp(-r*dt*(1:NSteps)');
a = zeros(3,1); % regression parameters
% generate sample paths
SPaths=GenPathsA(S0,r,sigma,T,NSteps,NRepl);
SPaths(:,1) = []; % get rid of starting prices
%
CashFlows = max(0, X - SPaths(:,NSteps));
% first set exercise time at expiration for convenience
ExerciseTime = NSteps*ones(NRepl,1);
for step = NSteps-1:-1:1
    InMoney = find(SPaths(:,step) < X);
    XData = SPaths(InMoney,step);
    RegrMat = [ones(length(XData),1), XData, XData.^2];
    YData = CashFlows(InMoney) .* discountVet(ExerciseTime(InMoney) - step);
    a = RegrMat \ YData;
    IntrinsicValue = X - XData;
    ContinuationValue = RegrMat * a;
    Exercise = find(IntrinsicValue > ContinuationValue);
    k = InMoney(Exercise);
    CashFlows(k) = IntrinsicValue(Exercise);
    ExerciseTime(k) = step;
end % for
price = mean(CashFlows.*discountVet(ExerciseTime));