added a failsafe to the foreach part