fixing #foreach and cleanup