// Implementation of the LexTextAffixList class methods.
//
// Copyright 2001, KUN
//
// 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: lextextaffixlist.cc,v 1.8 2003/11/26 22:15:14 pspiertz Exp $

using namespace std;
#include <string>
#include <iostream>
#include "lexfileio.h"
#include "id.h"
#include "lextextaffixlist.h"

void
LexTextAffixList::dump(void) const
{
    cout << "---- LexTextAffixList::dump" << endl;

    for (size_t i = 0; i < affixes.size(); ++i) {
        cout << "\t" << i;
        cout << " -> " << search_by_index(i) << endl;
    }

    cout << "----" << endl;
}

static string
unquote(string s)
{
    size_t from, length;

    if (s[0] == '"') {
        from = 1;
    } else {
        from = 0;
    }

    if (s[s.length() - 1] == '"') {
        length = s.length() - 1;
    } else {
        length = s.length();
    }

    length -= from;

    return s.substr(from, length);
}

void
LexTextAffixList::write_output(ostream& os) const
{
    write_lex_size_and_log(os, size(), " text affixes to file");

    for (size_t i = 0; i < size(); ++i) {
        string txt = unquote(search_by_index(i));
        write_lex_string(os, txt);
    }
}

unsigned
LexTextAffixList::get_index(string aff)
{
    return add_affix(aff);
}

unsigned
LexTextAffixList::add_affix(string aff)
{
    // First check if the affix is already stored:
    text_aff_t::iterator i = affixes.find(aff);

    if (i != affixes.end()) {
        return i->second;
    } else {
        // If this point is reached, the affix is not in the vector, so add it:
        unsigned res = affixes.size();
        affixes_index.push_back(affixes.insert(affixes.begin(),
                                               make_pair(aff, res)));
        return res;
    }
}

string
LexTextAffixList::search_by_index(unsigned idx) const
{
    return affixes_index[idx]->first;
}
