/*
 *  psychlops_io_misc.h
 *  Psychlops Standard Library (MacOSX)
 *
 *  Last Modified 2005/10/18 by Kenchi HOSOKAWA
 *  (C) 2005 Kenchi HOSOKAWA, Kazushi MARUYA, Takao SATO
 */


#include "psychlops_d_misc.h"



namespace Psychlops {


	std::map<const char*, double> Data::number;


	Data::DUMMY_ *Data::_tmp;
	Data_DUMMY2_ *Data::dummy2_;
	void operator >>(std::istream &a, Data_DUMMY2_ &b){}
//	const int Data::prohibitedcnt = 11;
	char * Data::prohibited[prohibitedcnt] = {"\\","/",";",",",":","*","?","\"","<",">","|"};
	char * Data::delimiter = "\t";
	std::ofstream Data::output;


	int Data::loadCSVraw(const std::string& filename, std::vector<std::vector<std::string> >& lines)
	{
		//	filename
		std::string filenamechacker = File::decodePath(filename);
		std::ifstream fin(filenamechacker.c_str());

		std::string tmp, source("");
		while( std::getline(fin,tmp) ) {
			source += tmp;
			source += '\n';
		}
		fin.close();

		return parseCSV(source, lines);
	}

	// code from  http://stackoverflow.com/questions/1120140/csv-parser-in-c
	int Data::parseCSV(const std::string& csvSource, std::vector<std::vector<std::string> >& lines)
    {
		int result = 0;

		bool inQuote = false;
		bool lastCharWasAQuote = false;
		bool newLine = false;
		std::string field;
		lines.clear();
		std::vector<std::string> line;

		std::string::const_iterator aChar = csvSource.begin();
		while (aChar != csvSource.end())
		{
			switch (*aChar)
			{
				case '"':
					newLine = false;
					if (lastCharWasAQuote == true)
					{
						lastCharWasAQuote = false;
						field += *aChar;
					}
					else
					{
						inQuote = !inQuote;
					}
					break;

				case ',':
					newLine = false;
					if (inQuote == true)
					{
						field += *aChar;
					}
					else
					{
						line.push_back(field);
						field.clear();
					}
					break;

				case '\n':
				case '\r':
					if (inQuote == true)
					{
						field += *aChar;
					}
					else
					{
						if (newLine == false)
						{
							line.push_back(field);
							lines.push_back(line);
							field.clear();
							line.clear();
							newLine = true;
						}
					}
					break;

				default:
					newLine = false;
					field.push_back(*aChar);
					break;
			}

			aChar++;
		}

		if (line.size())
		{
			if (field.size())
				line.push_back(field);

          lines.push_back(line);
       }

       return result;
    }


}	/*	<- namespace Psycholops 	*/

