Refactored shutdown code.