/* Copyright (C) 2007  Mikko Sysikaski <mikko.sysikaski@gmail.com>
 * This program is free software distributed under GNU General Public License
 * version 3 or (at your option) any later version.
 * No warranty of any kind is provided. See the accompanying file COPYING for details.
 */

#include "options.h"
#include <cstdio>
#include <boost/spirit.hpp>
#include <boost/spirit/iterator/file_iterator.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <fstream>

Options::Options(const char* file)
{
	read(file);
}

bool Options::read(const char* file)
{
	using namespace boost::spirit;

	iter_t f(file);
	if (!f) {
		fprintf(stderr, "Warning: couldn't open options file %s\n", file);
		return 0;
	}
#define RULE(name, rule) typeof(rule) name = rule
#define BIND(func) boost::bind(&Options:: func, boost::ref(*this), _1, _2)
	RULE(var, (*(anychar_p-'='))[BIND(setVar)]);
	RULE(value, (*(anychar_p-eol_p))[BIND(setValue)]);
	RULE(cfg, *(var >> '=' >> value >> *eol_p));
#undef RULE
#undef BIND
	if (!parse(f, f.make_end(), cfg, space_p-eol_p).full) {
		fprintf(stderr, "Warning: couldn't correctly parse file %s\n", file);
		return 0;
	}
	
	return 1;
}
void Options::write(const char* file)
{
	std::ofstream out(file);
	for(StrMap::iterator i=m_data.begin(); i!=m_data.end(); ++i) {
		if (!i->second.empty())
			out << i->first << " = " << i->second << '\n';
	}
}
