Improve shutdown code