/*
 * The RISC OS Latin-1 alphabet against Unicode, both ways.
 *   Copyright RISC OS Developments 2019+, credited to the RISC OS One Project.
 */

#include "alphabet.h"

/*
    &80 to &9F.  Below that the alphabet is ASCII and above it it is
    Latin-1, both of which are already the code point; only this block
    differs, and it is the block Latin-1 spends on control codes.

    U+FFFD marks the six RISC OS leaves undefined.  It is deliberately not
    reversible: a server sending U+FFFD means a character it could not
    represent either, not one of these.
*/
static const unsigned short top[32] =
{
    0x20AC, 0x0174, 0x0175, 0xFFFD, 0xFFFD, 0x0176, 0x0177, 0xFFFD,
    0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x2026, 0x2122, 0x2030, 0x2022,
    0x2018, 0x2019, 0x2039, 0x203A, 0x201C, 0x201D, 0x201E, 0x2013,
    0x2014, 0x2212, 0x0152, 0x0153, 0x2020, 0x2021, 0xFB01, 0xFB02
};

unsigned int AlphabetToUnicode(unsigned int ch)
{
    ch &= 0xFF;
    if((ch >= 0x80) && (ch <= 0x9F))
        return top[ch - 0x80];
    return ch;
}

unsigned int AlphabetFromUnicode(unsigned int u)
{
    int i;

    if(u < 0x80)
        return u;
    /*
        U+0080-U+009F are the C1 controls.  They are NOT the RISC OS
        characters that share those byte values, and mapping them back
        would turn a control code into a Euro sign.
    */
    if(u <= 0x9F)
        return 0;
    if(u <= 0xFF)
        return u;
    for(i = 0; i < 32; i++)
        if((top[i] == u) && (top[i] != 0xFFFD))
            return (unsigned int) (0x80 + i);
    return 0;
}
