added headers to output and optimized writing rows