Added L parameter to M function. First version of working algorithm.