Event on on_pre_close rather than on_close

Also some code cleanup