Move functions out of loop

This is for issue #7.