Fixed bug in looping, some refactoring