Rewrote these loops a bit