First working version of the algorithm.