private byte[] DoLZWDecode(Bytes.Buffer input, int earlyChange) { List <byte[]> codeTable = new List <byte[]>(); int chunk = 9; var decoded = new Bytes.Buffer(); long nextCommand; long prevCommand = -1; try { while ((nextCommand = input.ReadBits(chunk)) != EOD) { if (nextCommand == CLEAR_TABLE) { chunk = 9; codeTable = CreateCodeTable(); prevCommand = -1; } else { if (nextCommand < codeTable.Count) { byte[] data = codeTable[(int)nextCommand]; byte firstByte = data[0]; decoded.Write(data); if (prevCommand != -1) { CheckIndexBounds(codeTable, prevCommand, input); data = codeTable[(int)prevCommand]; byte[] newData = data.CopyOf(data.Length + 1); newData[data.Length] = firstByte; codeTable.Add(newData); } } else { CheckIndexBounds(codeTable, prevCommand, input); byte[] data = codeTable[(int)prevCommand]; byte[] newData = data.CopyOf(data.Length + 1); newData[data.Length] = data[0]; decoded.Write(newData); codeTable.Add(newData); } chunk = CalculateChunk(codeTable.Count, earlyChange); prevCommand = nextCommand; } } } catch (Exception ex) { Debug.WriteLine("warn: Premature EOF input LZW stream, EOD code missing " + ex); } return(decoded.GetBuffer()); }