@Override
  public void writeBytes(byte[] b, int offset, int length) throws IOException {
    int bytesLeft = BUFFER_SIZE - bufferPosition;
    // is there enough space in the buffer?
    if (bytesLeft >= length) {
      // we add the data to the end of the buffer
      System.arraycopy(b, offset, buffer, bufferPosition, length);
      bufferPosition += length;
      // if the buffer is full, flush it
      if (BUFFER_SIZE - bufferPosition == 0)
        flush();
    } else {
      // is data larger then buffer?
      if (length > BUFFER_SIZE) {
        // we flush the buffer
        if (bufferPosition > 0)
          flush();
        // and write data at once
        flushBuffer(b, offset, length);
        bufferStart += length;
      } else {
        // we fill/flush the buffer (until the input is written)
        int pos = 0; // position in the input data
        int pieceLength;
        while (pos < length) {
          pieceLength = (length - pos < bytesLeft) ? length - pos : bytesLeft;
          System.arraycopy(b, pos + offset, buffer, bufferPosition, pieceLength);
          pos += pieceLength;
          bufferPosition += pieceLength;
          // if the buffer is full, flush it
          bytesLeft = BUFFER_SIZE - bufferPosition;
          if (bytesLeft == 0) {
            flush();
            bytesLeft = BUFFER_SIZE;
          }
        }
      }
    }
  }