unroll recursion into loop