replaced 'foreach' loops with 'where in' clauses