Fix segmentation fault and cleanup