changed some variable names and logic in connection function