Tweaked algorithm.