Updated algorithm after the the found errors.