Reworked code a litle to improve connection error handling