Improved error handling
Better re-connect handling
Credits to Ryan Bullock