refactor big chunk to a separate function