Implement graceful exit (fixes #411, #317)