
#include "environment.h"

#include <fstream.h>


Environment::Environment() {
}

Environment::Environment(const JLString &filename) {

	ifstream iFile(filename.GetString(), ios::in);

	if (!iFile)
		cerr << "Enviroment: file not found '" << filename << "'" << endl;

	else {
		iFile >> *this;
		iFile.close();
	}
}

Environment::~Environment() {
}

Environment& Environment::CopyFrom(const Environment &E) {

	_options = E._options;
	_values = E._values;

	return *this;
}

ostream& operator<<(ostream &co, const Environment &E) {

	for (int i=0; i<E._options.Size(); i++)
		co << E._options[i] << " " << E._values[i] << endl;

	return co;
}

istream& operator>>(istream &ci, Environment &E) {

	JLString line;
	int i, count, space;
	int lineno = 0;

	while (1) {

		ci >> line;
		lineno++;

		if (ci.eof())
			return ci;

		if ((line.Len() > 0) && (line[0] != '#')) {
			count = 0;
			for (i=0; i<line.Len(); i++)
				if (line[i] == ' ') {
					space = i;
					count++;
				}

			if (count != 1) {
				cerr << "Error paring dot-rc-file, line " << lineno << ':'
					 << endl;
				cerr << line << endl << endl;
			}
			else {
				E.SetOption(line.SubString(0, space),
							line.SubString(space+1, line.Len()));
			}
		}
	}
}


void Environment::SetOption(const JLString &option, const JLString &value) {

	for (int i=0; i<_options.Size(); i++)
		if (option == _options[i]) {
			_values[i] = value;
			return;
		}

	_options.PlaceInList(new JLString(option));
	_values.PlaceInList(new JLString(value));
}

const JLString& Environment::LookupOption(const JLString &option) const {

	for (int i=0; i<_options.Size(); i++)
		if (option == _options[i])
			return _values[i];

	return _null;
}
