Restructered shutdown code