completed extract function to generate csv file