All this code belongs in it's own function with an intent revealing name and tests.