Improve exit mechanism and general cleanup

Using at_exit in combination with Signal.trap.