Simplify some logic, and use more for loops, replacing whiles