Added more graceful shutdown and new debug code