refactor algorithm