Refactored some code into a shared function