We have several functions inside of the each loop, which feels a bit problematic.  Would it be possible to move all (or at least most) of them outside of the loop?