Refactored to put the logic into one place