Rewrote a couple of foreach loops as index-based for loops, as they could cause an odd recursive loop on iOS devices