Break down large next_row generation function
Some more code cleanup