first working version of the algorithm