Added a bunch of consts and references and changed some loops.