Add a quit function and improve emergency quiting