Optimisation: changed forIn loops to for loops