private void writeName(String name) throws IOException {
        output.write(NAME);

        // The String value of a name should be output as UTF-8, but the
        // UTF-8 bytes are then escaped such that non-ASCII, ASCII control,
        // and whitespace characters are replaces with # then the 2 digit
        // hex value of the character. The # symbol itself is escaped with
        // its hex value (#23). Escape characters outside the range of
        // EXCLAMATION MARK(21h) (!) to TILDE (7Eh) (~). Decimal 33-126.

        final int pound = 0x23;
        byte[] bytes = name.getBytes("UTF-8");
        for(int b : bytes) {
            b &= 0xFF;
            if (b == pound || b < 0x21 || b > 0x7E) {
                output.write(pound);
                int hexVal = ((b >> 4) & 0x0F);
                int hexDigit = hexVal + ( (hexVal >= 10) ? 'A' : '0' );
                output.write(hexDigit);
                hexVal = (b & 0x0F);
                hexDigit = hexVal + ( (hexVal >= 10) ? 'A' : '0' );
                output.write(hexDigit);
            }
            else {
                output.write(b);
            }
        }
    }