Improved for loops, removed magic numbers, tidied