more efficient huffman tree encoding, and fixed memory leak