Refactor step_5a().

This commit refactors step_5a() and tidies up a few other places in the code.