moved some anonymous functions outside the loop. No need to make multiple instances of the same function, while a single reference suffices