# File lib/columnize.rb, line 35
  def columnize(list, displaywidth=80, colsep = '  ')
    if not list.is_a?(Array)
      return ''
    end
    if list.size == 0
      return  "<empty>\n"
    end
    l = list.map{|l| l.to_s}
    if 1 == l.size
      return "#{l[0]}\n"
    end
    # Consider arranging list in 1 rows total, then 2 rows...
    # Stop when at the smallest number of rows which
    # can be arranged less than the display width.
    nrows = ncols = 0
    colwidths = []
    1.upto(l.size) do 
      colwidths = []
      nrows += 1
      
      ncols = (l.size + nrows-1) / nrows
      totwidth = -colsep.length
      0.upto(ncols-1) do |col|
        # get max column width for this column
        colwidth = 0
        0.upto(nrows-1) do |row|
          i = row + nrows*col  # [rows, cols]
          if i >= l.size
            break
          end
          colwidth = [colwidth, l[i].size].max
        end
        colwidths << colwidth
        totwidth += colwidth + colsep.length
        if totwidth > displaywidth
          break
        end
      end
      if totwidth <= displaywidth
        break
      end
    end
    # The smallest number of rows computed and the
    # max widths for each column has been obtained.
    # Now we just have to format each of the
    # rows.
    s = ''
    0.upto(nrows-1) do |row| 
      texts = []
      0.upto(ncols-1) do |col|
        i = row + nrows*col
        if i >= l.size
          x = ""
        else
          x = l[i]
      end
      texts << x
      end
      while texts and texts[-1] == ''
      texts = texts[0..-2]
      end
      0.upto(texts.size-1) do |col|
        texts[col] = texts[col].ljust(colwidths[col])
      end
      s += "%s\n" % texts.join(colsep)
    end
    return s
  end