Refactor the logic to be clearer