Added code to make shutdowns more graceful, without segmentation faults