function price = GenericLS(S0,X,r,T,sigma,NSteps,NRepl,fhandles)
dt = T/NSteps;
discount = exp(-r*dt);
discountVet = exp(-r*dt*(1:NSteps)');
NBasis = length(fhandles); % number of basis functions
a = zeros(NBasis,1); % regression parameters
RegrMat = zeros(NRepl,NBasis);
% generate sample paths
SPaths=GenPathsA(S0,r,sigma,T,NSteps,NRepl);
SPaths(:,1) = []; % get rid of starting prices
%
CashFlows = max(0, X - SPaths(:,NSteps));
ExerciseTime = NSteps*ones(NRepl,1);
for step = NSteps-1:-1:1
    InMoney = find(SPaths(:,step) < X);
    XData = SPaths(InMoney,step);
    for i=1:NBasis
        RegrMat(1:length(XData), i) = feval(fhandles(i), XData);
    end
    YData = CashFlows(InMoney) .* discountVet(ExerciseTime(InMoney) - step);
    a = RegrMat(1:length(XData),:) \ YData;
    IntrinsicValue = X - XData;
    ContinuationValue = RegrMat(1:length(XData),:) * a;
    Exercise = find(IntrinsicValue > ContinuationValue);
    k = InMoney(Exercise);
    CashFlows(k) = IntrinsicValue(Exercise);
    ExerciseTime(k) = step;
end % for
price = mean(CashFlows.*discountVet(ExerciseTime));