/**
   * Write the TDS packet to the network.
   *
   * @param last Set to 1 if this is the last packet else 0.
   * @throws IOException
   */
  private void putPacket(int last) throws IOException {
    if (isClosed) {
      throw new IOException("RequestStream is closed");
    }

    buffer[0] = pktType;
    buffer[1] = (byte) last; // last segment indicator
    buffer[2] = (byte) (bufferPtr >> 8);
    buffer[3] = (byte) bufferPtr;
    buffer[4] = 0;
    buffer[5] = 0;
    buffer[6] = (byte) ((socket.getTdsVersion() >= Driver.TDS70) ? 1 : 0);
    buffer[7] = 0;

    if (Logger.isActive()) {
      Logger.logPacket(streamId, false, buffer);
    }

    buffer = socket.sendNetPacket(streamId, buffer);
    bufferPtr = TdsCore.PKT_HDR_LEN;
  }
  /**
   * Write a String to the output stream as translated bytes.
   *
   * @param s The String to write.
   * @throws IOException
   */
  void writeAscii(String s) throws IOException {
    String charsetName = socket.getCharset();

    if (charsetName != null) {
      try {
        write(s.getBytes(charsetName));
      } catch (UnsupportedEncodingException e) {
        write(s.getBytes());
      }
    } else {
      write(s.getBytes());
    }
  }
  /**
   * Copy the contents of a Reader stream to the server as bytes.
   *
   * <p>NB. Only reliable where the charset is single byte.
   *
   * @param in The Reader object with the data.
   * @param length The length of the data in bytes.
   * @throws IOException
   */
  void writeReaderBytes(Reader in, int length) throws IOException {
    char buffer[] = new char[1024];

    for (int i = 0; i < length; ) {
      int result = in.read(buffer);

      if (result == -1) {
        throw new java.io.IOException("Data in stream less than specified by length");
      } else if (i + result > length) {
        throw new java.io.IOException("More data in stream than specified by length");
      }

      write(Support.encodeString(socket.getCharset(), new String(buffer, 0, result)));
      i += result;
    }
  }
  /**
   * Write a String object to the output stream. If the TDS version is >= 7.0 write a UNICODE string
   * otherwise wrote a translated byte stream.
   *
   * @param s The String to write.
   * @throws IOException
   */
  void write(String s) throws IOException {
    if (socket.getTdsVersion() >= Driver.TDS70) {
      int len = s.length();

      for (int i = 0; i < len; ++i) {
        int c = s.charAt(i);

        if (bufferPtr == buffer.length) {
          putPacket(0);
        }

        buffer[bufferPtr++] = (byte) c;

        if (bufferPtr == buffer.length) {
          putPacket(0);
        }

        buffer[bufferPtr++] = (byte) (c >> 8);
      }
    } else {
      writeAscii(s);
    }
  }
 /**
  * Retrieve the TDS version number.
  *
  * @return The TDS version as an <code>int</code>.
  */
 int getTdsVersion() {
   return socket.getTdsVersion();
 }