Refactored connection logic to its own function