/// <summary>
        ///   Constructs a new <c>ParallelBZip2OutputStream</c> with specified blocksize,
        ///   and explicitly specifies whether to leave the wrapped stream open.
        /// </summary>
        ///
        /// <param name = "output">the destination stream.</param>
        /// <param name = "blockSize">
        ///   The blockSize in units of 100000 bytes.
        ///   The valid range is 1..9.
        /// </param>
        /// <param name = "leaveOpen">
        ///   whether to leave the captive stream open upon closing this stream.
        /// </param>
        public ParallelBZip2OutputStream(Stream output, int blockSize, bool leaveOpen)
        {
            if (blockSize < BZip2.MinBlockSize || blockSize > BZip2.MaxBlockSize)
            {
                var msg = String.Format("blockSize={0} is out of range; must be between {1} and {2}",
                                        blockSize,
                                        BZip2.MinBlockSize, BZip2.MaxBlockSize);
                throw new ArgumentException(msg, "blockSize");
            }

            this.output = output;
            if (!this.output.CanWrite)
            {
                throw new ArgumentException("The stream is not writable.", "output");
            }

            this.bw            = new BitWriter(this.output);
            this.blockSize100k = blockSize;
            this.leaveOpen     = leaveOpen;
            this.combinedCRC   = 0;
            this.MaxWorkers    = 16; // default
            EmitHeader();
        }
        /// <summary>
        ///   Close the stream.
        /// </summary>
        /// <remarks>
        ///   <para>
        ///     This may or may not close the underlying stream.  Check the
        ///     constructors that accept a bool value.
        ///   </para>
        /// </remarks>
        public override void Close()
        {
            if (this.pendingException != null)
            {
                this.handlingException = true;
                var pe = this.pendingException;
                this.pendingException = null;
                throw pe;
            }

            if (this.handlingException)
            {
                return;
            }

            if (output == null)
            {
                return;
            }

            Stream o = this.output;

            try
            {
                FlushOutput(true);
            }
            finally
            {
                this.output = null;
                this.bw     = null;
            }

            if (!leaveOpen)
            {
                o.Close();
            }
        }