local stdnse = require "stdnse"
local strbuf = require "strbuf"
local string = require "string"
local table = require "table"
_ENV = stdnse.module("tab", stdnse.seeall)
function new()
  local t = {}
  t.current_row = 1
  setmetatable(t, {__tostring=dump})
  return t
end
function add(t, c, v)
  assert(t)
  assert(type(v) == "string")
  t[t.current_row] = t[t.current_row] or {}
  t[t.current_row][c] = v
  return true
end
function addrow(t, ...)
  for i = 1, select("#", ...) do
    add(t, i, tostring((select(i, ...))))
  end
  nextrow(t)
end
function nextrow(t)
  assert(t)
  assert(t.current_row)
  t[t.current_row] = t[t.current_row] or {}
  t.current_row = t.current_row + 1
end
function dump(t)
  assert(t)
  local column_width = {}
  local num_columns = {}
  local buf = strbuf.new()
  for i, row in ipairs(t) do
    num_columns[i] = 0
    for x, elem in pairs(row) do
      local elem_width = #elem
      if not column_width[x] or elem_width > column_width[x] then
        column_width[x] = elem_width
      end
      if x > num_columns[i] then
        num_columns[i] = x
      end
    end
  end
  for i, row in ipairs(t) do
    local text_row = {}
    for x = 1, num_columns[i] do
      local elem = row[x] or ""
      if x < num_columns[i] then
        text_row[#text_row + 1] = elem .. string.rep(" ", column_width[x] - #elem)
      else
        text_row[#text_row + 1] = elem
      end
    end
    buf = buf .. table.concat(text_row, "  ") .. "\n"
  end
  return strbuf.dump(buf)
end
return _ENV;
