refactored common logic into fn