// Module handling the name<->id translation
// 
// Copyright 2000, Erik J. Verbruggen <ejv@xtdnet.nl>
//
// This program 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; either version 2 of the License, or
// (at your option) any later version.
//
// This program 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 Library General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

// $Id: id.h,v 1.4 2002/11/07 00:44:02 murphy Exp $

#ifndef ID_H
#define ID_H

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string>
#include <vector>
#include <map>
#include <list>

typedef long ID;
ID const unknown_id = -1;

class IDTable
{
    private:
        typedef map<string,ID> StringIdMap;
        StringIdMap string_to_id;
        vector<string> id_to_string;

    public:
        ID add(string s);
        ID to_id(string& s);
        string to_string(ID const id) const;
        bool exists(string& s);
};

inline ID IDTable::to_id(string& s)
{
    StringIdMap::iterator i = string_to_id.find(s);

    if (i == string_to_id.end()) {
        return unknown_id;
    } else {
        return i->second;
    }
}

inline string IDTable::to_string(ID const id) const
{
    if ((id < 0) && (id >= (ID) id_to_string.size())) {
        return "<unknown id>";
    }

    return id_to_string[id];
}

inline bool IDTable::exists(string& s)
{
    StringIdMap::iterator i = string_to_id.find(s);

    return i != string_to_id.end();
}

class IDList: public list<ID>
{
    public:
        iterator find(ID key) {
            iterator i = begin();

            while (i != end()) {
                if (*i == key) {
                    return i;
                }

                ++i;
            }

            return i;
        };
        string to_string(char seperator);
};

inline ID IDTable::add(string s)
{
    StringIdMap::iterator i = string_to_id.find(s);

    if (i == string_to_id.end()) {
        ID res = id_to_string.size();
        id_to_string.push_back(s);
        string_to_id[s] = res;
        return res;
    } else {
        return i->second;
    }
}

extern IDTable idtable;

inline string IDList::to_string(char seperator)
{
    string result = "";
    iterator i = begin();

    while (i != end()) {
        result += idtable.to_string(*i);

        ++i;
        if (i != end()) {
            result += seperator;
        }
    }

    return result;
}

#endif // ID_H
