Refactor scan_for_exiting and add unit tests for it. Also, fix some other places where the unit tests were broken.