Fixes to ensure clean shutdown and some error handing improvements