refactored connection code