Major revamp of the algorithm