some refactoring; use C++11 foreach