refactoring, cleaning, added loop-check