added error checking and connection closing