/**
   * Inserts the bytes written as header and puts the write pointer at the end of the stream.
   *
   * @throws IOException if write fails
   */
  public void append() throws IOException {
    // append the top-level buffer
    super.byteAlign();

    if (currentBuffer + 1 >= bufferList.size()) {
      // there is no buffer to append
      return;
    }

    Buffer append = bufferList.get(currentBuffer + 1);
    if (append.getLength() > 0) {
      if (currentBuffer >= 0) {
        bufferList.get(currentBuffer).add(append);
      } else {
        super.write(append.getBytes(), 0, append.getLength());
      }
    }
    bufferList.remove(currentBuffer + 1);
  }
  // Improve byte array performance.
  @Override
  protected void writeByteArray(byte[] bytes, int offset, int length) throws IOException {
    // original stream
    if (currentBuffer == -1) {
      super.writeByteArray(bytes, offset, length);
      return;
    }

    Buffer buffer = bufferList.get(currentBuffer);
    buffer.add(bytes, offset, length);
  }
  // Renamed and final to detect write(int) changes.
  @Override
  protected final void writeSingleByte(int b) throws IOException {
    // System.out.println(Integer.toHexString(b)+" "+index);
    // original stream
    if (currentBuffer == -1) {
      super.write(b);
      return;
    }

    Buffer buffer = bufferList.get(currentBuffer);
    buffer.add((byte) b);
  }
 /** closes the stream, inserting any non-written header. */
 @Override
 public void close() throws IOException {
   append();
   super.close();
 }