Would you mind splitting this function into two functions depending on the n_elements value?  It seems like the kernel-launching logic and the code generation are both pretty different depending on this value. Weaving everything together makes this function pretty hard to read, what do you think?