cleaned up nested foreach code