public override void Flush()
        {
            if (_read)
            {
                throw new InvalidOperationException();
            }

            if (_bitPosition > 0)
            {
                if (_baseStream.Position != _baseStream.Length)
                {
                    _temp = _temp.SetBitsAtRight(8 - _bitPosition, (byte)_baseStream.ReadByte());
                    _baseStream.BackByte();
                }
                _baseStream.WriteByte(_temp);
            }
        }
        public BitStream(Stream baseStream, bool createNew)
        {
            _baseStream = baseStream;

            if (_baseStream.Position == _baseStream.Length || createNew)
            {
                _temp      = 0;
                _bitLength = 0;
                _baseStream.WriteByte(0);
                _baseStream.WriteInt64(_baseStream.Position + 8);
                _end = _origin = _baseStream.Position;
            }
            else
            {
                _bitLength = (byte)_baseStream.ReadByte();
                _end       = _baseStream.ReadInt64();

                if (_end == _baseStream.Position)
                {
                    _temp = 0;
                }
                else if (_end > _baseStream.Position)
                {
                    _temp = (byte)_baseStream.ReadByte();
                    _baseStream.BackByte();
                }
                else
                {
                    throw new InvalidDataException();
                }

                _origin = _baseStream.Position;
            }
            _bitPosition = 0;
            _changed     = false;
        }
        public override void Flush()
        {
            var npos = _baseStream.Position;

            _baseStream.SeekTo(_origin - 9);
            _baseStream.WriteByte((byte)_bitLength);
            _baseStream.WriteInt64(_end);
            _baseStream.SeekTo(npos);

            if ((_baseStream.Length == _baseStream.Position && _bitLength > 0) || _bitPosition > 0)
            {
                _baseStream.WriteByte(_temp);
                _baseStream.BackByte();
            }

            _baseStream.Flush();
        }