/***************************************************************************
 *   Copyright (C) 2004-2009 by Pere Constans
 *   constans@molspaces.com
 *   cb2Bib version 1.3.2. Licensed under the GNU GPL version 3.
 *   See the LICENSE file that comes with this distribution.
 ***************************************************************************/
#include "wordPattern.h"
#include "cb2bib_utilities.h"


wordPattern::wordPattern(const QString newPattern, Qt::CaseSensitivity newCs) : compositePattern(newPattern, newCs)
{
    setPattern();
}

wordPattern::~wordPattern()
{}


void wordPattern::setPattern()
{
    const QStringList patternPieces(pattern.split(c2bUtils::nonLetter, QString::SkipEmptyParts));
    if (patternPieces.count() < 2)
    {
        arx.setPattern(escape(pattern, caseSensitivity));
        return;
    }
    QStringList subPatterns;
    QRegExp _asrx;
    _asrx.setPatternSyntax(QRegExp::RegExp2);
    _asrx.setMinimal(false);
    _asrx.setCaseSensitivity(Qt::CaseSensitive);
    QMap<double, QRegExp> sort_asrx;
    for (int i = 0; i < patternPieces.count(); ++i)
    {
        const QString sp(escape(patternPieces.at(i), caseSensitivity));
        subPatterns.append(sp);
        _asrx.setPattern(sp);
        // Sort according expectation (arXiv:0705.0751v1, Eq. 6)
        sort_asrx.insert(-probability(sp), _asrx);
    }
    asrx = sort_asrx.values();
    arx.setPattern(QString("(?:%1)").arg(subPatterns.join("|")));
}
