Refactored ManyToMany code to bring it into a single loop.