using System;
using System.Collections.Generic;
using System.Text;
using ADGE_3RDPARTY_CANDYLib;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.IO;

namespace ADGEDotNetUt {
    public class ADGEUt {
        public static byte[] LZWUncompress(byte[] chunk) {
            object r = new CandyLzw().Decode(StrFromb(chunk));
            Debug.Assert(r is string);
            return StrTob(r as string);
        }

        static string StrFromb(byte[] b) {
            String s = "";
            for (int x = 0; x < b.Length; x++) {
                s += (char)b[x];
            }
            return s;
        }

        static byte[] StrTob(string s) {
            byte[] b = new byte[s.Length];
            for (int x = 0; x < s.Length; x++) {
                b[x] = (byte)s[x];
            }
            return b;
        }

        public static Bitmap CreatePic(int cx, int cy, Color[] pal256, byte[] pixels) {
            Bitmap pic = new Bitmap(cx, cy, PixelFormat.Format8bppIndexed);
            ColorPalette pal = pic.Palette;
            for (int c = 0; c < 256; c++) pal.Entries[c] = pal256[c];
            pic.Palette = pal;

            BitmapData bd = pic.LockBits(new Rectangle(0, 0, cx, cy), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
            try {
                Marshal.Copy(pixels, 0, bd.Scan0, Math.Min(bd.Stride * cy, pixels.Length));
            }
            finally {
                pic.UnlockBits(bd);
            }

            return pic;
        }

        public static byte[] ConcatBin(byte[] a, byte[] b) {
            MemoryStream os = new MemoryStream(a.Length + a.Length);
            os.Write(a, 0, a.Length);
            os.Write(b, 0, b.Length);
            return os.ToArray();
        }
    }
    public class ArrayUt<T> where T : new() {
        public static T[] NewArray1(int size1) {
            size1++;
            T[] res = new T[size1];
            for (int x = 0; x < size1; x++)
                res[x] = new T();

            return res;
        }
        public static T[,] NewArray2(int size1, int size2) {
            size1++;
            size2++;
            T[,] res = new T[size1, size2];
            for (int x = 0; x < size1; x++)
                for (int y = 0; y < size2; y++)
                    res[x, y] = new T();

            return res;
        }
        public static T[][] NewJagArray2(int size1, int size2) {
            size1++;
            size2++;
            T[][] res = new T[size1][];
            for (int x = 0; x < size1; x++) {
                res[x] = new T[size2];
                for (int y = 0; y < size2; y++) {
                    res[x][y] = new T();
                }
            }
            return res;
        }
    }
}
