Move helper functions outside a loop, for performance. Fixes #4