Restructured looping to avoid unnecessary wheres