Numerous fixes to the shutdown code