#ifndef _CSV_H
#define _CSV_H

#include <map>
#include <vector>
#include <string>
#include <cstring>
#include <fstream>

//
// Copyright (c) 2006 Matthew William Coan.
//
// CSV file reader in C++ (Comma Seperated Values)
//
// Example: "1","2","3""hello","4"
//
// Author : Matthew William Coan
// Date   : Fri Dec 15 09:17:56 EST 2006
//
namespace csv_reader {

using namespace std;

// row type
typedef vector< string > csv_row_type;

// row name map
typedef map< string, int > csv_row_map_type;

// row input
istream & 
operator>>(istream & in, 
	   csv_row_type & row) {
	string str;
	char ch;
	bool in_col = false;

	row.clear();

	while(in) {
		ch = in.get();

		if(!in_col && ch == ',')
			continue;
		else if(!in_col && ch == '\n')
			break;

                if(ch == '\"') {
			if(in.peek() == '\"' && in_col) {
				in.get();

				str += "\"";
			}
			else if(in_col) {
				in_col = false;

				row.insert(row.end(), str);

				str = "";
			}
			else {
				in_col = true;
			}
		}
		else {
			str += ch;
		}
	}

	return in;
}

// map row types
void
map_row(const csv_row_type & row, 
	csv_row_map_type & row_map) {
	csv_row_map_type ret;

	for(size_t i = 0; i < row.size(); i++) {
		row_map[row[i]] = i;
	}
}

}

#endif /* _CSV_H */
