Replaced some loops with functors/lambdas