removed dead code ($success), changed the connection state detection.