it looks like only the assignment of start_date and csv_filename need to be in the if/else block (the startkey and endkey can be moved outside making it clearer)