refactoring ugly loops