fixed critical bug: foreach deleted its iterating element