private void writeSelectorsAndHuffmanTables() throws IOException {

		final BZip2BitOutputStream bitOutputStream = this.bitOutputStream;
		final byte[] selectors = this.selectors;
		final int totalSelectors = selectors.length;
		final int[][] huffmanCodeLengths = this.huffmanCodeLengths;
		final int mtfAlphabetSize = this.mtfAlphabetSize;

		final int totalTables = huffmanCodeLengths.length;

		bitOutputStream.writeBits (3, totalTables);
		bitOutputStream.writeBits (15, totalSelectors);

		// Write the selectors
		MoveToFront selectorMTF = new MoveToFront();
		for (int i = 0; i < totalSelectors; i++) {
			bitOutputStream.writeUnary (selectorMTF.valueToFront (selectors[i]));
		}

		// Write the Huffman tables
		for (int i = 0; i < totalTables; i++) {
			final int[] tableLengths = huffmanCodeLengths[i];
			int currentLength = tableLengths[0];

			bitOutputStream.writeBits (5, currentLength);

			for (int j = 0; j < mtfAlphabetSize; j++) {
				final int codeLength = tableLengths[j];
				final int value = (currentLength < codeLength) ? 2 : 3;
				int delta = Math.abs (codeLength - currentLength);
				while (delta-- > 0) {
					bitOutputStream.writeBits (2, value);
				}
				bitOutputStream.writeBoolean (false);
				currentLength = codeLength;
			}
		}

	}