clean code; split loop into small functions