int total = bufferLength;
int length = Math.min(Math.min(remoteWindow.waitForSpace(), total), remoteWindow.getPacketSize());
int pos = buf.wpos();
buf.wpos(cmd == SshConstants.SSH_MSG_CHANNEL_EXTENDED_DATA ? 14 : 10);
buf.putInt(length);
buf.wpos(buf.wpos() + length);
if (total == length) {
newBuffer(length);
} else {
int leftover = total - length;
newBuffer(Math.max(leftover, length));