Refactor algorithm