make code more DRY

This replaces 15 instances of similar code with just 3 loops (two of which are nearly the same)