refactored connection handling