fixed foreach bug, a bit of refactoring, fixed one optimization