changed for to for_each, added memory cleanup