public static String wrap(String str, int width) {
        StringBuffer buf = new StringBuffer(str);
        int index;
        /*
         * normalize any existing IFS characters to spaces
         */
        while ((index = buf.indexOf("\n")) != -1) {
            buf.setCharAt(index, ' ');
        }
        while ((index = buf.indexOf("\t")) != -1) {
            buf.setCharAt(index, ' ');
        }
        /*
         * trim. Yes, I know about String.trim(), but we've already done half
         * the work it does; no need to be inefficient.
         */
        while (buf.charAt(0) == ' ') {
            buf.deleteCharAt(0);
        }
        while (buf.charAt(buf.length() - 1) == ' ') {
            buf.deleteCharAt(buf.length() - 1);
        }

        while ((index = buf.indexOf("  ")) != -1) {
            buf.deleteCharAt(index);
        }

        /*
         * word wrap.
         */
        int next_space = 0;
        int line_start = 0;

        while (next_space != -1) {
            if ((next_space - line_start) > width) {
                buf.setCharAt(next_space, '\n');
                line_start = next_space;
            }
            next_space = buf.indexOf(" ", next_space + 1); // bounds?
        }

        return buf.toString();
    }