/*
** Hanzi/Pinyin table
** (c) 2007 Zarathoustra
** for www.obopo.com
**
** GetPinyinFromCharacter("個") == "gè"
**
** If the argument is not in the table, is not a hanzi,
** or is not a single character, it is returned unchanged.
*/

function GetPinyinFromCharacter(Hanzi)
{
    // Not a single character
    if (Hanzi.length != 1)
        return (Hanzi);

    var left = 1; // Skip the first character to better the value distribution to make interpolation search more efficient.
    var right = H.length - 1;
    var x;
    
    while ((H[left].charCodeAt(0) < Hanzi.charCodeAt(0)) && (H[right].charCodeAt(0) >= Hanzi.charCodeAt(0)))
    {
        //document.write("Iteration for " + Hanzi + " (" + Hanzi.charCodeAt(0) + ")");
        //document.write("<br/>\n");

        // dichotomic search
        //x = (left + right) / 2;
        // interpolation search
        x = left + ((Hanzi.charCodeAt(0) - H[left].charCodeAt(0)) * (right - left) / (H[right].charCodeAt(0) - H[left].charCodeAt(0)));

        x = x ^ 0; // XXX: make it an integer.
        
        if (Hanzi.charCodeAt(0) < H[x].charCodeAt(0))
            right = x - 1;
        else if (Hanzi.charCodeAt(0) > H[x].charCodeAt(0))
            left = x + 1;
        else
            return (P[x]);
    }

    if (H[left].charCodeAt(0) == Hanzi.charCodeAt(0))
        return (P[left]);

    // Not found in table
    return (Hanzi);
}

function GetPinyinFromString(HanziString, DoAddSpace)
{
    var NewString = "";
    
    if (DoAddSpace == false)
        for (i=0 ; i < HanziString.length ; i++)
            NewString += GetPinyinFromCharacter(HanziString.charAt(i));
    else
        for (i=0 ; i < HanziString.length ; i++)
        {
            var c = GetPinyinFromCharacter(HanziString.charAt(i));
            NewString += c;

            if ((i != HanziString.length - 1) && (c != HanziString.charAt(i)))
                NewString += " ";
        }

    return (NewString);
}