refactor connect/disconnect code