Implemented exporting to CSV

Also fixed bug causing crash if exporting twice in a row.