--[[
   **********************************************
   * Define functions for sorting LaTeX lists.  *
   * Author: Scott Pakin <scott-clsl@pakin.org> *
   **********************************************
--]]

-- Sort a list of "\@elt {package_name}" terms alphabetically by package
-- name.
function sortlist(lst)
   local ordered = {}
   for elt in string.gmatch(lst, "\\@elt%s*(%b{})") do
      table.insert(ordered, elt)
   end
   table.sort(ordered, function (a, b)
      return string.lower(a) < string.lower(b)
   end)
   for i, elt in ipairs(ordered) do
      tex.sprint(string.format("\\@elt %s", elt))
   end
end


-- Sort a list of "\@elt {package_name}" terms so that they appear
-- alphabetically by package name when typeset in a tabular with a given
-- number of columns
function sort_list_columns(lst, nc)
   -- Parse the list of package names and sort it.
   local sorted_order = {}
   for elt in string.gmatch(lst, "\\@elt%s*(%b{})") do
      table.insert(sorted_order, elt)
   end
   table.sort(sorted_order, function (a, b)
      return string.lower(a) < string.lower(b)
   end)

   -- Re-sort the table so that package names will be ordered when typeset
   -- in nc columns.
   local tabular_order = {}
   local nelts = #sorted_order
   local nr = math.ceil(nelts/nc)
   for r = 1, nr do
      table.insert(tabular_order, sorted_order[r])
      if r + nr <= nelts then
         table.insert(tabular_order, sorted_order[r + nr])
         if r + 2*nr <= nelts then
            table.insert(tabular_order, sorted_order[r + 2*nr])
	 else
            table.insert(tabular_order, "{TABLE-PADDING}")
         end
      else
	 table.insert(tabular_order, "{TABLE-PADDING}")
      end
   end

   -- Output tabular_order as a LaTeX list.
   for i, elt in ipairs(tabular_order) do
      tex.sprint(string.format("\\@elt %s", elt))
   end
end
