//Only called when creating new rgba value. Traverses the Huffman tree to return the correct value
        private static int RetrieveHuffmanTreeValue(byte[] data, TKMK00HuffmanTreeNode currentNode, TKMK00CommandReader commandReader)
        {
            while (!currentNode.IsEndNode)/*currentNode.Value >= 0x20*/
            {
                int command = commandReader.ReadBits(1); // 0 - left, 1 - right
                if (command == 0)
                    currentNode = currentNode.Left;
                else
                    currentNode = currentNode.Right;
            }

            return currentNode.Value;
        }
        /// <summary>
        /// Creates a Huffman-style binary tree that holds the 5-bit color data referenced in the 
        /// TKMK00 decoding process.
        /// </summary>
        private static TKMK00HuffmanTreeNode SetUpHuffmanTree(uint val, byte[] data, TKMK00CommandReader commandReader)
        {
            TKMK00HuffmanTreeNode newTree = new TKMK00HuffmanTreeNode();

            int command = commandReader.ReadBits(1);//1 - Make new branches, 0 - End current branch

            if (command != 0)
            {
                newTree.Value = (int)val; //Not used, but can't hurt to number it
                val++;
                newTree.Left = SetUpHuffmanTree(val, data,  commandReader);
                newTree.Right = SetUpHuffmanTree(val, data,  commandReader);
                return newTree;
            }

            //Else, return a node with a value
            int value = 0;
            int bitCount = 5;
            do
            {
                command = commandReader.ReadBits(1);
                value = value * 2 + command; //basically bitshifts s0 to the left and adds v0, aka it's loading 5 bytes straight from the comandReader
                bitCount -= 1;
            } while (bitCount > 0);

            newTree.Value = value;
            return newTree;
        }
        /// <summary>
        /// Decodes the TKMK00 format into RGBA5551 formatted data. Uses a Huffman tree to store
        ///  color values that are added/subtracted/sometimes overwrite a predicted color for the
        ///  current pixel. Look up DPCM for a conceptual idea of what it's doing (the Huffman tree
        ///  stands in place for entropy coding.
        /// </summary>
        public static byte[] Decode(byte[] data, int tkmk00Offset, ushort alphaColor)
        {
            //Initialize the header & readers
            byte[] headerBytes = new byte[TKMK00Header.DataSize];
            Array.Copy(data, tkmk00Offset, headerBytes, 0, TKMK00Header.DataSize);
            TKMK00Header header = new TKMK00Header(headerBytes);
            TKMK00CommandReader masterReader = new TKMK00CommandReader(data, tkmk00Offset + TKMK00Header.DataSize, false);
            TKMK00CommandReader[] channelReaders = new TKMK00CommandReader[8];
            for(int i = 0; i < 8; i++)
                channelReaders[i] = new TKMK00CommandReader(data, tkmk00Offset + header.ChannelPointers[i], header.RepeatEnabledFor(i));

            //Set up the image data/buffers
            ushort[] rgbaBuffer = new ushort[0x40];
            for (int i = 0; i < 0x40; i++)
                rgbaBuffer[i] = 0xFF;
            byte[] colorChangeMap = new byte[header.Width * header.Height];
            byte[] imageData = new byte[header.Width * header.Height * 2];
            int pixelIndex = 0;

            //Set up the Huffman binary tree
            TKMK00HuffmanTreeNode headTreeNode = SetUpHuffmanTree(0x20, data, channelReaders[0]);

            ushort lastPixelColor = 0;

            //Iterate through each pixel in order left to right, top to bottom
            for (int row = 0; row < header.Height; row++)
            {
                for (int col = 0; col < header.Width; col++)
                {
                    //Look at the current pixel's color. If it's not empty, then it's already been
                    // set to its correct value, and we can skip to the next pixel
                    ushort currentPixelColor = ByteHelper.ReadUShort(imageData, pixelIndex * 2);

                    if (currentPixelColor != 0) //Color already exists
                    {
                        lastPixelColor = currentPixelColor;

                        //Test to make sure that the curent color is not the alpha value with the incorrect alpha channel value
                        ushort currentPixelWithoutAlpha = (ushort)(currentPixelColor & 0xFFFE);
                        if (currentPixelWithoutAlpha == alphaColor)
                        {
                            ByteHelper.WriteUShort(alphaColor, imageData, pixelIndex * 2);
                            lastPixelColor = alphaColor;
                        }

                        //Done, go to end of the loop
                    }
                    else
                    {
                        //Load up the channel reader that is associated with the given color change value in the
                        // colorChangeMap (low values = not much change around that pixel, high values = lots of change)
                        byte channelIndex = (byte)(colorChangeMap[pixelIndex] + 1);

                        int command = channelReaders[channelIndex].ReadBits(1); // 0 - Use the previous color, 1 - Use new color

                        if (command == 0)
                        {
                            ByteHelper.WriteUShort(lastPixelColor, imageData, pixelIndex * 2);
                            //End of this line
                        }
                        else
                        {
                            command = masterReader.ReadBits(1); // 1 - Create new RGBA, 0 - Use existing RGBA
                            if (command != 0)
                            {
                                //Load in the huffman values for the new green, red and blue. These are combined
                                // with a predicted pixel value for them later on.
                                int newGreen = RetrieveHuffmanTreeValue(data, headTreeNode, channelReaders[0]);
                                int newRed = RetrieveHuffmanTreeValue(data, headTreeNode, channelReaders[0]);
                                int newBlue = RetrieveHuffmanTreeValue(data, headTreeNode, channelReaders[0]);

                                //Retreive the pixel colors from the pixel above and the pixel to the left
                                ushort rgbaTop, rgbaLeft;

                                if (row != 0)
                                {
                                    rgbaTop = ByteHelper.ReadUShort(imageData, (pixelIndex - header.Width) * 2);
                                    rgbaLeft = ByteHelper.ReadUShort(imageData, (pixelIndex - 1) * 2);
                                }
                                else
                                {
                                    rgbaTop = 0;
                                    if (col != 0)
                                        rgbaLeft = ByteHelper.ReadUShort(imageData, (pixelIndex - 1) * 2);
                                    else
                                        rgbaLeft = 0;
                                }

                                //Combine green values of the pixels to make our predicted pixel color
                                ushort greenTop = (byte)((rgbaTop & 0x7C0) >> 6);
                                ushort greenLeft = (byte)((rgbaLeft & 0x7C0) >> 6);
                                int greenPrediction = (greenTop + greenLeft) / 2;

                                //Combine the prediction & huffman value to make the output color
                                ColorCombine(greenPrediction, ref newGreen);

                                //Use the change between the old & new green values to project expected
                                // values for the red & blue colors
                                int greenChange = newGreen - greenPrediction;

                                //Combine red values of the pixels to make our predicted pixel color
                                ushort redTop = (byte)((rgbaTop & 0xF800) >> 11);
                                ushort redLeft = (byte)((rgbaLeft & 0xF800) >> 11);
                                int redPrediction = greenChange + (redTop + redLeft) / 2;
                                redPrediction = Math.Max(0, Math.Min(0x1F, redPrediction)); //Keep between 0 and 0x1F

                                //Combine the prediction & huffman value to make the output color
                                ColorCombine(redPrediction, ref newRed);

                                //Combine blue values of the pixels to make our predicted pixel color
                                ushort blueTop = (byte)((rgbaTop & 0x3E) >> 1);
                                ushort blueLeft = (byte)((rgbaLeft & 0x3E) >> 1);
                                int bluePrediction = greenChange + (blueTop + blueLeft) / 2;
                                bluePrediction = Math.Max(0, Math.Min(0x1F, bluePrediction)); //Keep between 0 and 0x1F

                                //Combine the prediction & huffman value to make the output color
                                ColorCombine(bluePrediction, ref newBlue);

                                //Make the newpixel color
                                currentPixelColor = (ushort)((newRed << 11) | (newGreen << 6) | (newBlue << 1));
                                if (currentPixelColor != alphaColor) //Only transparent if it matches the transparency pixel
                                    currentPixelColor |= 0x1;

                                //Add to the front of the color buffer
                                for (int i = rgbaBuffer.Length - 1; i > 0; i--)
                                    rgbaBuffer[i] = rgbaBuffer[i - 1];
                                rgbaBuffer[0] = currentPixelColor;
                            }
                            else //Use existing RGBA
                            {
                                command = masterReader.ReadBits(6); // Returns index of color in color buffer to use

                                currentPixelColor = rgbaBuffer[command];
                                if (command != 0)
                                {
                                    //Bump the selected color to the front of the buffer
                                    for (int i = command; i > 0; i--)
                                        rgbaBuffer[i] = rgbaBuffer[i - 1];
                                    rgbaBuffer[0] = currentPixelColor;
                                }
                            }

                            //Write the RGBA to the imageData
                            ByteHelper.WriteUShort(currentPixelColor, imageData, pixelIndex * 2);
                            lastPixelColor = currentPixelColor;

                            //Add nearby pixels to the colorChangeMap
                            bool hasLeftCol = (col != 0);
                            bool hasRightCol = (col < (header.Width - 1));
                            bool has2RightCols = (col < (header.Width - 2));
                            bool hasDownRow = (row < (header.Height - 1));
                            bool has2DownRows = (row < (header.Height - 2));

                            //Right 1
                            if (hasRightCol)
                                colorChangeMap[pixelIndex + 1]++;
                            //Right 2
                            if (has2RightCols)
                                colorChangeMap[pixelIndex + 2]++;
                            //Down 1 Left 1
                            if (hasDownRow && hasLeftCol)
                                colorChangeMap[pixelIndex + header.Width - 1]++;
                            //Down 1
                            if (hasDownRow)
                                colorChangeMap[pixelIndex + header.Width]++;
                            //Down 1 Right 1
                            if (hasDownRow && hasRightCol)
                                colorChangeMap[pixelIndex + header.Width + 1]++;
                            //Down 2
                            if (has2DownRows)
                                colorChangeMap[pixelIndex + header.Width * 2]++;

                            //Now test to see if we need to continue writing this color down the column
                            command = masterReader.ReadBits(1);//1 - repeat color, 0 - continue

                            if (command == 1) //Repeat color
                            {
                                //Basically move down one row each repeat, possibly moving to the side, and write the color again
                                int pixelOffset = 0;
                                ushort currentPixelColorOpaque = (ushort)(currentPixelColor | 0x1); //Not sure why this is the case, is it to catch it in the first if statement?

                                while(true) //I hate while(true)
                                {
                                    command = masterReader.ReadBits(2);//0 - advanced move, 1 - back one, 2 - no lateral move, 3 - forward one
                                    if (command == 0)
                                    {
                                        //Advanced move
                                        command = masterReader.ReadBits(1);//0 - stop, 1 - advanced move

                                        if (command == 0)
                                        {
                                            break;
                                        }

                                        command = masterReader.ReadBits(1); //0 - move back 2, 1 - move forward 2
                                        if (command == 0)
                                        {
                                            pixelOffset -= 2;
                                        }
                                        else
                                        {
                                            pixelOffset += 2;
                                        }
                                    }
                                    else if (command == 1)
                                    {
                                        pixelOffset--;
                                    }
                                    else if (command == 3)
                                    {
                                        pixelOffset++;
                                    }

                                    pixelOffset += header.Width; //move down a row
                                    ByteHelper.WriteUShort(currentPixelColorOpaque, imageData, (pixelIndex + pixelOffset) * 2);
                                }

                            }
                        }
                    }

                    //Next pixel
                    pixelIndex++;
                }
            }

            return imageData;
        }