package ipipan.spejd.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.TreeMap;

/**
 * Dictionary containing a set of variables with values.
 */
abstract class AbstractDict<T> {

    protected TreeMap<String, T> dict;

    /**
     * Loads configuration from a specified file.
     *
     * @param filename name of the configuration file
     */
    public void load(String filename) {
        int i, line = 1;

        try {
            BufferedReader d;
            d = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "utf-8"));
            String inputLine;

            while ((inputLine = d.readLine()) != null) {
                line++;
                inputLine = inputLine.trim();

                // empty line
                if (inputLine.length() == 0) {
                    continue;
                }

                // comment
		if (inputLine.charAt(0) == '#' || inputLine.charAt(0) == ';') {
                    continue;
                }

                // find =
                for (i = 1; i < inputLine.length(); i++) {
                    if (inputLine.charAt(i) == '=') {
                        break;
                    }
                }

                if (i == inputLine.length()) {
                    System.err.println("Line " + line + " in " 
				       + filename + " is not assignment:");
		    System.err.println(inputLine);
                    continue;
                }

                put(inputLine.substring(0, i).trim(),
                    inputLine.substring(i + 1).trim());

            }
            d.close();
	    
        } catch (IOException e) {
	    //System.err.println("SimpleDict.load(" + filename + "): " + e.getMessage());
        }
    }

    /**
     * Sets value of a configuration variable.
     *
     * @param var name of the variable to set
     * @param value value of the variable as String
     */
    abstract public void put(String var, String value); 

    public TreeMap<String, T> getDict() {
        return dict;
    }
}
