Added code to do a more graceful shutdown.