This is a refactoring. I suggest we start writing unit tests for this. It doesn't seem too hard. Let's start with this function only and a regression test for this bug.