better error handling on lost connection
some minor optimization