refactor connection code