Move CSV output generation into a function.