refactoring: move a few obvious things out of the loop; all tests pass