Finished to_csv function
Minor refactoring