using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace everdrive3x.Misc
{
    class DataTool
    {
        public static int read32(byte[] buff, int offset)
        {
            int val = 0;
            val |= (buff[offset++] & 0xFF) << 24;
            val |= (buff[offset++] & 0xFF) << 16;
            val |= (buff[offset++] & 0xFF) << 8;
            val |= (buff[offset++] & 0xFF) << 0;
            return val;
        }

        public static int read16(byte[] buff, int offset)
        {
            int val = 0;
            val |= (buff[offset++] & 0xFF) << 8;
            val |= (buff[offset++] & 0xFF) << 0;
            return val;
        }

        public static void write32(byte[]buff, int offset, int val)
        {
            buff[offset++] = (byte)(val >> 24);
            buff[offset++] = (byte)(val >> 16);
            buff[offset++] = (byte)(val >> 8);
            buff[offset++] = (byte)(val >> 0);
        }

        public static void write16(byte[] buff, int offset, int val)
        {
            buff[offset++] = (byte)(val >> 8);
            buff[offset++] = (byte)(val >> 0);
        }

        public static int readHexByte(FileStream file)
        {
            int H = file.ReadByte();
            int L = file.ReadByte();
            if (H >= '0' && H <= '9')
            {
                H -= '0';
            }
            else if (H >= 'A' && H <= 'F')
            {
                H -= 'A' - 10;
            }
            else { throw new Exception("bad hex string: " + H); }

            if (L >= '0' && L <= '9')
            {
                L -= '0';
            }
            else if (L >= 'A' && L <= 'F')
            {
                L -= 'A' - 10;
            }
            else { throw new Exception("bad hex string: " + L); }

            return H << 4 | L;
        }


        public static String byteToHex(int val)
        {
            val &= 0xff;
            int H = val >> 4;
            int L = val & 0x0f;

            String str = "";

            if (H < 10) str += H; else str += (char)(H - 10 + 'A');
            if (L < 10) str += L; else str += (char)(L - 10 + 'A');


            return str;
        }
    }
}
