Tweaked algorithm