Refactor some logic