using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.Dvb;
using skyscraper5.Skyscraper.IO;

namespace skyscraper5.Teletext
{
    internal static class HammingCode
    {
        public static byte ReadHamming84(this Stream s)
        {
            byte a = s.ReadUInt8();
            byte b = s.ReadUInt8();
            return Unham(a, b);
        }

        public static byte Unham(byte a, byte b)
        {
            byte c1 = unhamtab[a];
            byte c2 = unhamtab[b];

            int tResult = (c2 << 4) | (0x0f & c1);
            byte result = (byte)(tResult & 0x000000ff);
            return result;
        }

        private static readonly byte[] unhamtab = new byte[] {
            0x01, 0xff, 0x81, 0x01, 0xff, 0x00, 0x01, 0xff,
            0xff, 0x02, 0x01, 0xff, 0x0a, 0xff, 0xff, 0x07,
            0xff, 0x00, 0x01, 0xff, 0x00, 0x80, 0xff, 0x00,
            0x06, 0xff, 0xff, 0x0b, 0xff, 0x00, 0x03, 0xff,
            0xff, 0x0c, 0x01, 0xff, 0x04, 0xff, 0xff, 0x07,
            0x06, 0xff, 0xff, 0x07, 0xff, 0x07, 0x07, 0x87,
            0x06, 0xff, 0xff, 0x05, 0xff, 0x00, 0x0d, 0xff,
            0x86, 0x06, 0x06, 0xff, 0x06, 0xff, 0xff, 0x07,
            0xff, 0x02, 0x01, 0xff, 0x04, 0xff, 0xff, 0x09,
            0x02, 0x82, 0xff, 0x02, 0xff, 0x02, 0x03, 0xff,
            0x08, 0xff, 0xff, 0x05, 0xff, 0x00, 0x03, 0xff,
            0xff, 0x02, 0x03, 0xff, 0x03, 0xff, 0x83, 0x03,
            0x04, 0xff, 0xff, 0x05, 0x84, 0x04, 0x04, 0xff,
            0xff, 0x02, 0x0f, 0xff, 0x04, 0xff, 0xff, 0x07,
            0xff, 0x05, 0x05, 0x85, 0x04, 0xff, 0xff, 0x05,
            0x06, 0xff, 0xff, 0x05, 0xff, 0x0e, 0x03, 0xff,
            0xff, 0x0c, 0x01, 0xff, 0x0a, 0xff, 0xff, 0x09,
            0x0a, 0xff, 0xff, 0x0b, 0x8a, 0x0a, 0x0a, 0xff,
            0x08, 0xff, 0xff, 0x0b, 0xff, 0x00, 0x0d, 0xff,
            0xff, 0x0b, 0x0b, 0x8b, 0x0a, 0xff, 0xff, 0x0b,
            0x0c, 0x8c, 0xff, 0x0c, 0xff, 0x0c, 0x0d, 0xff,
            0xff, 0x0c, 0x0f, 0xff, 0x0a, 0xff, 0xff, 0x07,
            0xff, 0x0c, 0x0d, 0xff, 0x0d, 0xff, 0x8d, 0x0d,
            0x06, 0xff, 0xff, 0x0b, 0xff, 0x0e, 0x0d, 0xff,
            0x08, 0xff, 0xff, 0x09, 0xff, 0x09, 0x09, 0x89,
            0xff, 0x02, 0x0f, 0xff, 0x0a, 0xff, 0xff, 0x09,
            0x88, 0x08, 0x08, 0xff, 0x08, 0xff, 0xff, 0x09,
            0x08, 0xff, 0xff, 0x0b, 0xff, 0x0e, 0x03, 0xff,
            0xff, 0x0c, 0x0f, 0xff, 0x04, 0xff, 0xff, 0x09,
            0x0f, 0xff, 0x8f, 0x0f, 0xff, 0x0e, 0x0f, 0xff,
            0x08, 0xff, 0xff, 0x05, 0xff, 0x0e, 0x0d, 0xff,
            0xff, 0x0e, 0x0f, 0xff, 0x0e, 0x8e, 0xff, 0x0e,
        };

    }
}
