Refactor a little, add exit event handling.