// Affix table routines.
//
// 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: affixtab.cc,v 1.6 2003/11/26 22:15:13 pspiertz Exp $

using namespace std;
#include <string>
#include <list>
// #include <algo.h> // for sort()
#include <algorithm> // for sort()
#include "affixtab.h"

pAffixSet
AffixTable::enter(AffixID* ids, unsigned size)
{
    sort(ids, ids + size);
    return AffixTableBase::enter(ids, ids + size);
}

unsigned
AffixTable::requested(void) const
{
    return AffixTableBase::requested();
}

unsigned
AffixTable::allocated(void) const
{
    return AffixTableBase::allocated();
}

string
convert_to_string(pAffixSet s)
{
    string res = "";
    pAffixSet set_p = s;

    while (set_p) {
        res += idtable.to_string(set_p->elem);

        set_p = set_p->next;

        if (set_p) {
            res += "|";
        }
    }

    return res;
}

pAffixSet
AffixTable::merge(pAffixSet set1, pAffixSet set2)
{
    list<AffixID> l1 = to_list(set1);
    list<AffixID> l2 = to_list(set2);

    l1.sort();
    l2.sort();
    l2.merge(l1);

    AffixID set_ids[MaxSetSz];
    unsigned set_sz = 0;
    for (list<AffixID>::iterator i = l2.begin(); i != l2.end(); ++i) {
        set_ids[set_sz] = *i;
        set_sz++;
    }

    return enter(set_ids, set_sz);
}

pAffixSet
AffixTable::merge(pAffixSet set1, AffixID id2)
{
    pAffixSet set2 = to_set(id2);
    return merge(set1, set2);
}

pAffixSet
AffixTable::merge(AffixID id1, pAffixSet set2)
{
    pAffixSet set1 = to_set(id1);
    return merge(set1, set2);
}

pAffixSet
AffixTable::merge(AffixID id1, AffixID id2)
{
    pAffixSet set1 = to_set(id1);
    pAffixSet set2 = to_set(id2);
    return merge(set1, set2);
}

pAffixSet
AffixTable::to_set(AffixID id)
{
    AffixID idl[1];
    idl[0] = id;
    return enter(idl, 1);
}

list<AffixID>
AffixTable::to_list(pAffixSet set)
{
    list<AffixID> res;

    while (set) {
        res.push_back(set->elem);
        set = set->next;
    }

    return res;
}
