First version of the algorithm