Refactor shutdown process.