/**
 * dcagmarkassistant.h - is part of the iwear-framework
 * @file
 * $Id$
 * $Revision$
 * $Author$
 * $Date$
 *
 * This file is part of The iWear Framework.
 * In particular this file is part of the Framework Input Library
 *
 * The iWear Framework is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by the
 * Free Software Foundation as in version 2 of the License.

 * 
 * The iWear Framework is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * The iWear Framework; if not, write to the Free Software Foundation, Inc., 59
 * Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#ifndef __CSVPARSER_H
#define __CSVPARSER_H

#include <iostream>
#include <fstream>
#include <string>
#include <list>

using namespace std;

#define DELIMITER ';'

namespace iwear {
namespace utilities {

class CSVParser
{
public:

    /**  */
    CSVParser();

    /**  */
    ~CSVParser();

    inline list<list<string>*>* parse_file(const char* url){
	std::ifstream filestream (url);
	return this->read_filestream_to_list(&filestream);
    }

    /** Reads a file. 
     * @param filestream the filestream to be read.
     */
    inline list<list<string>*>* read_filestream_to_list(std::ifstream* filestream){
	list<list<string>*>* line_list = new list<list<string>*>();
	std::string line_buffer;
	while (getline(*filestream, line_buffer))
	{
	    line_list->push_back(this->read_csv_line(line_buffer));
	}
	return line_list;
    }

    /** Read a line and add it to list. 
     * @param line The string buffer.
     */ 
    inline list<string>* read_csv_line(string& line){
	int	index_start = 0;
	int	index_end;
	list<string>* token_list = new list<string>();
	/* read all tokens */
	while ((int)line.find_first_of(DELIMITER, index_start) != -1)
	{
	    /* Find delimiter and add the token to list. */
	    index_end = line.find_first_of(DELIMITER, index_start);
	    token_list->push_back(line.substr(index_start, 
					     index_end - index_start));
	    index_start = index_end+1;
	}	
	// fb: there is a bug in the loop. the parser forgets the last column, 
	// so here it has to do the same with the last column
	index_end = line.find_first_of(DELIMITER, index_start);
	token_list->push_back(line.substr(index_start, index_end - index_start));	
	return token_list;
    }

protected:

private:

    list<string>* line_list;

};

} // utility
} // iwear

#endif
