Module:Convert

From TEPwiki, Urth's Encyclopedia
Revision as of 04:54, 16 September 2012 by w>Johnuniq (major refactor to use a table with all values for cleaner code and less runtime calculation)
Jump to navigation Jump to search

Documentation for this module may be created at Module:Convert/doc

--[[
TODO Too many items to list, but following are some points:
- Output needs   rather than space in several places.
- Some conversions require two outputs: {{convert|55|nmi|km mi}}.
- Some units have two values: {{convert|3.21|m|ftin}}.
- Remove commas from input numbers; add to output (always?).
- Use U+2212 MINUS SIGN for input + output number, not '-'.
]]

local function clonetable(t)
    -- Return a shallow copy of t.
    result = {}
    for k, v in pairs(t) do
        result[k] = v
    end
    return result
end

--[[-----BEGIN DATA TABLES-----
Three data tables follow:
    SIprefixes      prefixes like 'M' (mega, 10^6)
    units           all properties for a unit, including default output
    defaultunits    default output exceptions ('Mg' and 'g' have different defaults)
SIprefixes and defaultunits are maintained by editing this file.
However, the units table is generated by a script which reads the wikitext
for a wiki page that documents properties of units.
Could consider putting some or all tables in another module.
Check values at http://en.wikipedia.org/wiki/Conversion_of_units
and http://en.wikipedia.org/wiki/Template:Convert/list_of_units
]]

local SIprefixes = {
    ['Y'] = { exponent = 24, name = 'yotta' },
    ['Z'] = { exponent = 21, name = 'zetta' },
    ['E'] = { exponent = 18, name = 'exa'   },
    ['P'] = { exponent = 15, name = 'peta'  },
    ['T'] = { exponent = 12, name = 'tera'  },
    ['G'] = { exponent =  9, name = 'giga'  },
    ['M'] = { exponent =  6, name = 'mega'  },
    ['k'] = { exponent =  3, name = 'kilo'  },
    ['H'] = { exponent =  2, name = 'hecto' },  -- not an SI prefix, but allow for people typing this
    ['h'] = { exponent =  2, name = 'hecto' },
    ['da']= { exponent =  1, name = 'deca'  },
    ['D'] = { exponent =  1, name = 'deca'  },  -- not an SI prefix, but allow for people typing this
    ['d'] = { exponent = -1, name = 'deci'  },
    ['c'] = { exponent = -2, name = 'centi' },
    ['m'] = { exponent = -3, name = 'milli' },
    ['µ'] = { exponent = -6, name = 'micro' },
    ['u'] = { exponent = -6, name = 'micro' },  -- not an SI prefix, but allow for people typing this
    ['n'] = { exponent = -9, name = 'nano'  },
    ['p'] = { exponent =-12, name = 'pico'  },
    ['f'] = { exponent =-15, name = 'femto' },
    ['a'] = { exponent =-18, name = 'atto'  },
    ['z'] = { exponent =-21, name = 'zepto' },
    ['y'] = { exponent =-24, name = 'yocto' },
}

local units = {
    lookup = function (self, unit)
        -- Return true, t where t is the unit's converter table (or false, message).
        -- Given 'unit' is a symbol (like 'g'), with an optional SI prefix (as in 'kg').
        -- If, for example, 'kg' is in this table, that entry is used; otherwise prefix is applied.
        local t = self[unit]
        if t ~= nil then
            local result = clonetable(t)
            result.baseunit = unit
            result.prefix = ""
            return true, result
        end
        for plen = 2, 1, -1 do
            -- Check for longer prefix first ('dam' is decametre).
            local prefix = string.sub(unit, 1, plen)
            local si = SIprefixes[prefix]
            if si ~= nil then
                local baseunit = unit:sub(plen+1)
                local t = self[baseunit]
                if t ~= nil and t.prefixes == true then
                    local result = clonetable(t)
                    local pname = si.name  -- LATER: is there no better way?
                    result.name1    = pname .. result.name1
                    result.name1_us = pname .. result.name1_us
                    result.name2    = pname .. result.name2
                    result.name2_us = pname .. result.name2_us
                    result.baseunit = baseunit
                    result.prefix = prefix
                    result.scale = t.scale * 10^si.exponent
                    return true, result
                end
            end
        end
        local msg = 'Unit %s is not known.[[Category:Convert unknown unit]]'
        return false, msg:format(unit)
    end,
    ["m2"] = {
	name1    = "square metre",
	name1_us = "square meter",
	name2    = "square metres",
	name2_us = "square meters",
	symbol   = "m<sup>2</sup>",
	sym_us   = "m<sup>2</sup>",
	utype    = "area",
	scale    = 1,
	offset   = 0,
	default  = "sqyd",
    },
    ["a"] = {
	name1    = "are",
	name1_us = "are",
	name2    = "ares",
	name2_us = "ares",
	symbol   = "a",
	sym_us   = "a",
	utype    = "area",
	scale    = 100,
	offset   = 0,
	prefixes = true,
	default  = "acre",
    },
    ["sqft"] = {
	name1    = "square foot",
	name1_us = "square foot",
	name2    = "square feet",
	name2_us = "square feet",
	symbol   = "sq ft",
	sym_us   = "sq ft",
	utype    = "area",
	scale    = 0.09290304,
	offset   = 0,
	default  = "m2",
    },
    ["sqyd"] = {
	name1    = "square yard",
	name1_us = "square yard",
	name2    = "square yards",
	name2_us = "square yards",
	symbol   = "sq yd",
	sym_us   = "sq yd",
	utype    = "area",
	scale    = 0.83612736,
	offset   = 0,
	default  = "m2",
    },
    ["acre"] = {
	name1    = "acre",
	name1_us = "acre",
	name2    = "acres",
	name2_us = "acres",
	symbol   = "acre",
	sym_us   = "acre",
	utype    = "area",
	scale    = 4046.8564224,
	offset   = 0,
	default  = "ha",
    },
    ["m"] = {
	name1    = "metre",
	name1_us = "meter",
	name2    = "metres",
	name2_us = "meters",
	symbol   = "m",
	sym_us   = "m",
	utype    = "length",
	scale    = 1,
	offset   = 0,
	prefixes = true,
	default  = "ft",
    },
    ["mi"] = {
	name1    = "mile",
	name1_us = "mile",
	name2    = "miles",
	name2_us = "miles",
	symbol   = "mi",
	sym_us   = "mi",
	utype    = "length",
	scale    = 1609.344,
	offset   = 0,
	default  = "km",
    },
    ["ft"] = {
	name1    = "foot",
	name1_us = "foot",
	name2    = "feet",
	name2_us = "feet",
	symbol   = "ft",
	sym_us   = "ft",
	utype    = "length",
	scale    = 0.3048,
	offset   = 0,
	default  = "m",
    },
    ["foot"] = {
	name1    = "foot",
	name1_us = "foot",
	name2    = "feet",
	name2_us = "feet",
	symbol   = "ft",
	sym_us   = "ft",
	utype    = "length",
	scale    = 0.3048,
	offset   = 0,
	default  = "m",
    },
    ["yd"] = {
	name1    = "yard",
	name1_us = "yard",
	name2    = "yards",
	name2_us = "yards",
	symbol   = "yd",
	sym_us   = "yd",
	utype    = "length",
	scale    = 0.3048 * 3,
	offset   = 0,
	default  = "m",
    },
    ["in"] = {
	name1    = "inch",
	name1_us = "inch",
	name2    = "inches",
	name2_us = "inches",
	symbol   = "in",
	sym_us   = "in",
	utype    = "length",
	scale    = 0.0254,
	offset   = 0,
	default  = "cm",
    },
    ["g"] = {
	name1    = "gram",
	name1_us = "gram",
	name2    = "grams",
	name2_us = "grams",
	symbol   = "g",
	sym_us   = "g",
	utype    = "mass",
	scale    = 0.001,
	offset   = 0,
	prefixes = true,
	default  = "oz",
    },
    ["lb"] = {
	name1    = "pound",
	name1_us = "pound",
	name2    = "pounds",
	name2_us = "pounds",
	symbol   = "lb",
	sym_us   = "lb",
	utype    = "mass",
	scale    = 0.45359237,
	offset   = 0,
	default  = "kg",
    },
    ["oz"] = {
	name1    = "ounce",
	name1_us = "ounce",
	name2    = "ounces",
	name2_us = "ounces",
	symbol   = "oz",
	sym_us   = "oz",
	utype    = "mass",
	scale    = 0.45359237/16,
	offset   = 0,
	default  = "g",
    },
    ["ozt"] = {
	name1    = "troy ounce",
	name1_us = "troy ounce",
	name2    = "troy ounces",
	name2_us = "troy ounces",
	symbol   = "ozt",
	sym_us   = "ozt",
	utype    = "mass",
	scale    = 0.0311034768,
	offset   = 0,
	default  = "g",
    },
    ["K"] = {
	name1    = "kelvin",
	name1_us = "kelvin",
	name2    = "kelvins",
	name2_us = "kelvins",
	symbol   = "K",
	sym_us   = "K",
	utype    = "temperature",
	scale    = 1,
	offset   = 0,
	default  = "C",
    },
    ["C"] = {
	name1    = "degree Celsius",
	name1_us = "degree Celsius",
	name2    = "degrees Celsius",
	name2_us = "degrees Celsius",
	symbol   = "°C",
	sym_us   = "°C",
	utype    = "temperature",
	scale    = 1,
	offset   = -273.15,
	default  = "F",
    },
    ["°C"] = {
	name1    = "degree Celsius",
	name1_us = "degree Celsius",
	name2    = "degrees Celsius",
	name2_us = "degrees Celsius",
	symbol   = "°C",
	sym_us   = "°C",
	utype    = "temperature",
	scale    = 1,
	offset   = -273.15,
	default  = "F",
    },
    ["F"] = {
	name1    = "degree Fahrenheit",
	name1_us = "degree Fahrenheit",
	name2    = "degrees Fahrenheit",
	name2_us = "degrees Fahrenheit",
	symbol   = "°F",
	sym_us   = "°F",
	utype    = "temperature",
	scale    = 5/9,
	offset   = 32-273.15*(9/5),
	default  = "C",
    },
    ["°F"] = {
	name1    = "degree Fahrenheit",
	name1_us = "degree Fahrenheit",
	name2    = "degrees Fahrenheit",
	name2_us = "degrees Fahrenheit",
	symbol   = "°F",
	sym_us   = "°F",
	utype    = "temperature",
	scale    = 5/9,
	offset   = 32-273.15*(9/5),
	default  = "C",
    },
    ["m3"] = {
	name1    = "cubic metre",
	name1_us = "cubic meter",
	name2    = "cubic metres",
	name2_us = "cubic meters",
	symbol   = "m<sup>3</sup>",
	sym_us   = "m<sup>3</sup>",
	utype    = "volume",
	scale    = 1,
	offset   = 0,
	default  = "cuyd",
    },
    ["l"] = {
	name1    = "litre",
	name1_us = "liter",
	name2    = "litres",
	name2_us = "liters",
	symbol   = "l",
	sym_us   = "l",
	utype    = "volume",
	scale    = 0.001,
	offset   = 0,
	prefixes = true,
	default  = "imppt",
    },
    ["L"] = {
	name1    = "litre",
	name1_us = "liter",
	name2    = "litres",
	name2_us = "liters",
	symbol   = "L",
	sym_us   = "L",
	utype    = "volume",
	scale    = 0.001,
	offset   = 0,
	prefixes = true,
	default  = "imppt",
    },
    ["cuyd"] = {
	name1    = "cubic yard",
	name1_us = "cubic yard",
	name2    = "cubic yards",
	name2_us = "cubic yards",
	symbol   = "cu yd",
	sym_us   = "cu yd",
	utype    = "volume",
	scale    = 0.764554857984,
	offset   = 0,
	default  = "m3",
    },
    ["USgal"] = {
	name1    = "US gallon",
	name1_us = "U.S. gallon",
	name2    = "US gallons",
	name2_us = "U.S. gallons",
	symbol   = "US gal",
	sym_us   = "U.S. gal",
	utype    = "volume",
	scale    = 0.003785411784,
	offset   = 0,
	default  = "L",
    },
    ["USoz"] = {
	name1    = "US fluid ounce",
	name1_us = "U.S. fluid ounce",
	name2    = "US fluid ounces",
	name2_us = "U.S. fluid ounces",
	symbol   = "US fl oz",
	sym_us   = "U.S. fl oz",
	utype    = "volume",
	scale    = 0.003785411784/128,
	offset   = 0,
	default  = "cL",
    },
    ["USpt"] = {
	name1    = "U.S. pint",
	name1_us = "U.S. pint",
	name2    = "U.S. pints",
	name2_us = "U.S. pints",
	symbol   = "US pt",
	sym_us   = "US pt",
	utype    = "volume",
	scale    = 0.003785411784/8,
	offset   = 0,
	default  = "dL",
    },
    ["impgal"] = {
	name1    = "imperial gallon",
	name1_us = "imperial gallon",
	name2    = "imperial gallons",
	name2_us = "imperial gallons",
	symbol   = "imp gal",
	sym_us   = "imp gal",
	utype    = "volume",
	scale    = 0.00454609,
	offset   = 0,
	default  = "L",
    },
    ["impoz"] = {
	name1    = "imperial fluid ounce",
	name1_us = "imperial fluid ounce",
	name2    = "imperial fluid ounces",
	name2_us = "imperial fluid ounces",
	symbol   = "imp fl oz",
	sym_us   = "imp fl oz",
	utype    = "volume",
	scale    = 0.00454609/160,
	offset   = 0,
	default  = "cL",
    },
    ["imppt"] = {
	name1    = "imperial pint",
	name1_us = "imperial pint",
	name2    = "imperial pints",
	name2_us = "imperial pints",
	symbol   = "imp pt",
	sym_us   = "imp pt",
	utype    = "volume",
	scale    = 0.00454609/8,
	offset   = 0,
	default  = "dL",
    },
}

local defaultunits = {
    lookup = function (self, unit_table)
        -- Return true, s where s = name of unit's default output unit (or false, message).
        local baseunit = unit_table.baseunit
        local prefix = unit_table.prefix
        local unit = prefix .. baseunit
        local default = self[unit]
        if default ~= nil then return true, default end
        t = units[baseunit]
        if t ~= nil then
            local default = t.default
            if default ~= nil then return true, default end
        end
        local msg = 'Unit %s has no default target conversion.[[Category:Convert unknown unit]]'
        return false, msg:format(unit)
    end,
    -- Prefixed units with a default different from that of the base unit.
    ['kg']  = 'lb',
    ['Mg']  = 'lb',
    ['Gg']  = 'lb',
    ['pm']  = 'in',
    ['nm']  = 'in',
    ['um']  = 'in',
    ['mm']  = 'in',
    ['cm']  = 'in',
    ['dm']  = 'in',
    ['dam'] = 'yd',
    ['Hm']  = 'yd',
    ['km']  = 'mi',
    ['Mm']  = 'mi',
    ['mL']  = 'impoz',
    ['cL']  = 'impoz',
    ['dL']  = 'impoz',
    ['daL'] = 'impgal',
    ['HL']  = 'impgal',
}

-------END DATA TABLES-----

-- Configuration options to keep magic values in one location.
local config = {}

local function get_config(frame)
    -- Return table of configuration options.
    -- Unclear if this is currently needed, but it may help if adapting
    -- code for a different wiki.
    local cfg = {}
    -- Following settings are defaults that can be overridden by template.
    cfg.numdot = '.'        -- decimal mark before fractional digits
    cfg.numsep = ','        -- thousands separator for numbers (',', '.', or nil)
    for k, v in frame:argumentPairs() do
        cfg[k] = v          -- arguments from template's {{#invoke:}}
    end
    -- Following settings are mandatory (to limit abuse).
    cfg.maxsigfig = 20      -- maximum number of significant figures
    return cfg
end

local function withseparator(text)
    -- Return string for a number with thousand separators inserted.
    -- Parameter text is a string like "-12345" or "12345.6789".
    -- Separator is inserted only in the integer part (not in fraction).
    -- Four-digit integer parts have a separator (like "1,234").
    local numsep = config.numsep
    if #numsep == 0 then
        return text
    end
    local function insert(text, first, last)
        local result = ''
        while last >= first do
            if last >= first + 3 then
                result = numsep .. text:sub(last-2, last) .. result
                last = last - 3
            else
                return text:sub(first, last) .. result
            end
        end
        return result
    end
    local first = 1
    local sign = text:sub(first, 1)
    if sign == '+' or sign == '-' then
        -- To handle Unicode minus (multibyte), perhaps use following:
        -- first = text:find('%d')
        first = 2
    else
        sign = ''
    end
    local last = text:find(config.numdot, first, true)
    if last == nil then
        last = #text
    else
        last = last - 1
    end
    return sign .. insert(text, first, last) .. text:sub(last+1)
end

local function formatnumber(value, sigfig)
    -- Return result of converting number 'value' to a string,
    -- rounded to 'sigfig' significant figures.
    local format = string.format
    local rep = string.rep
    local sign = ''
    local numdot = config.numdot
    local function zeropad(text, dot)
        count = sigfig - #text
        if count <= 0 then
            return text
        end
        return text .. dot .. rep('0', count)
    end
    if sigfig <= 0 then
        sigfig = 1
    elseif sigfig > config.maxsigfig then
        sigfig = config.maxsigfig
    end
    if value == 0 then
        return zeropad('0', numdot)
    end
    if value < 0 then
        sign = '-'  -- need proper Unicode minus
        value = -value
    end
    local digits
    local exp, frac = math.modf(math.log10(value))
    if frac == 0 then
        -- Value 1 gives frac = 0, and 0.1 gives frac = -0 (negative zero).
        -- Both results give true in 'if frac == 0'.
        digits = zeropad('1', '')
        exp = exp + 1  -- adjust so dot is before digits
    else
        local prec = sigfig
        if value > 1 then
            prec = prec - 1  -- will be one sig fig before dot
        end
        digits = format(format('%%.%df', prec), 10^frac)
        if value < 1 then
            -- Is MediaWiki run in a locale where following might be '0,'?
            assert(digits:sub(1, 2) == '0.', 'Bug: rounded number not 0.xxx')
            digits = digits:sub(3)
        else
            if prec == 0 then
                assert(digits:find(numdot, 1, true) == nil, 'Bug: unexpected dot')
            else
                assert(digits:sub(2, 2) == numdot, 'Bug: rounded number not x.xxx')
                digits = digits:sub(1, 1) .. digits:sub(3)
            end
            exp = exp + 1  -- adjust so dot is before digits
        end
    end
    if exp >= #digits then
        digits = digits .. rep('0', exp - #digits)  -- result has no dot
    elseif exp <= 0 then
        digits = '0' .. numdot .. rep('0', -exp) .. digits
    else
        digits = digits:sub(1, exp) .. numdot .. digits:sub(exp+1)
    end
    return sign .. digits
end

local function require_number(value, missing, invalid)
    -- Return true, n where n = number equivalent to given value (or false, message).
    -- Thousand separators (valid or not) are first removed.
    if value == nil then return false, missing end
    if type(value) == 'number' then return true, value end
    local numsep = config.numsep
    if #numsep > 0 then value = string.gsub(value, numsep, '') end
    local number = tonumber(value)
    if number == nil then return false, invalid:format(value) end
    return true, number
end

local function require_integer(value, missing, invalid)
    -- Return true, n where n = integer equivalent to given value (or false, message).
    local success, number = require_number(value, missing, invalid)
    if not success then return success, number end
    if number ~= math.floor(number) then return false, invalid:format(value) end
    return true, number
end

local function get_parms(pframe)
    -- Return true, t where t is a table with all arguments passed to the template
    -- converted to named arguments. The numeric args are used to add named args:
    --   in_text, in_text2 (strings given for value, value2)
    --   value, in_unit, out_unit, value2, range, round_to
    -- (except for range, which is nil or a table, the named args that are
    -- added here could be provided by the user of the template).
    local range_types = {  -- text to separate input, output ranges
        ['and'] = {' and ', ' and '},
        ['by'] = {' by ', ' by '},
        ['to'] = {' to ', ' to '},
        ['-'] = {'–', '–'},
        ['to(-)'] = {' to ', '–'},
        ['x'] = {' by ', ' × '},
        ['+/-'] = {' ± ', ' ± '},
    }
    local success, t
    local args = {}                         -- arguments passed to template
    for k, v in pframe:argumentPairs() do
        args[k] = v
    end
    args.in_text = args[1]
    success, t = require_number(args.in_text, 'Need value', 'Value "%s" must be a number')
    if not success then return success, t else args.value = t end
    local in_unit = args[2]
    local i = 3
    local range = range_types[in_unit]
    if range ~= nil then
        args.in_text2 = args[3]
        success, t = require_number(args.in_text2, 'Need second value', 'Second value "%s" must be a number')
        if not success then return success, t else args.value2 = t end
        in_unit = args[4]
        i = 5
    end
    local out_unit = args[i]
    local round_to = args[i+1]
    if in_unit == nil then return false, 'Need input unit' end
    args.in_unit = in_unit
    args.out_unit = out_unit
    args.range = range
    args.round_to = args.round_to or round_to  -- allow named parameter
    return true, args
end

local function default_roundto(intext, factor)
    -- Return a default value for round_to (an integer like 2, 0, -2).
    -- prec = (precision implied in intext)
    --      = (#digits after dot, or negative of #zeroes before dot)
    -- If conversion is multiplication by a factor, and
    -- if factor >= 0.02, compensate prec by adding N where:
    --     N    factor is in range
    --     1     .02  :   .2   =    .1/5 :   .1*2
    --     0     .2   :   2    =    1/5  :   1*2
    --    -1     2    :  20    =   10/5  :  10*2
    --    -2    20    : 200    =  100/5  : 100*2  etc.
    -- TODO Exception required for temperature.
    prec = 0
    dot = intext:find('.', 1, true)
    if dot ~= nil then
        prec = intext:sub(dot+1):len()
        if prec == 0 then
            intext = intext:sub(1, -2)
        end
    end
    if prec == 0 then
        prec = -intext:match('0*$'):len()
    end
    if factor ~= nil and factor >= 0.02 then
        prec = prec - math.floor(math.log10(factor*5))
    end
    return prec
end

local function scaled(value, in_unit, out_unit)
    -- Return scaled value for a simple convert.
    return (value - in_unit.offset)
        * (in_unit.scale / out_unit.scale)
        + out_unit.offset
end

local function cvtround(invalue, intext, parms)
    -- Return true, s where s = rounded, formatted string from converting invalue,
    -- using the rounding specified in parms (s = '' if invalue == nil).
    -- This code combines convert/round because some rounding requires
    -- knowledge of what we are converting.
    -- TODO Lots of checking required. Will need tweaks for special cases
    -- handled by old Template:Convert.
    -- TODO Limit values to avoid abuse (for example, can currently set
    -- round_to to very large values like 999).
    local text = ''
    if invalue == nil then return true, text end
    local outvalue = scaled(invalue, parms.in_unit_table, parms.out_unit_table)
    local round_to = parms.round_to
    local sigfig = parms.sigfig
    local disp = parms.disp
    local auto = false
    if round_to then
        -- Ignore sigfig, disp.
        success, round_to = require_integer(round_to, 'Need value', 'round_to "%s" must be an integer')
        if not success then return success, round_to end
    elseif sigfig then
        -- Ignore disp.
        success, sigfig = require_integer(sigfig, 'Need value', 'sigfig "%s" must be an integer')
        if not success then return success, sigfig end
        if sigfig <= 0 then
            msg = 'sigfig "%s" must be positive'
            return false, msg:format(parms.sigfig)
        end
        text = formatnumber(outvalue, sigfig)
    elseif disp == '5' then
        local negative = false
        if outvalue < 0 then
            negative = true
            outvalue = -outvalue
        end
        outvalue = math.floor((outvalue / 5) + 0.5) * 5
        if negative then
            outvalue = -outvalue
        end
        text = string.format('%.0f', outvalue)
    else
        auto = true  -- using default rounding
        -- TODO If conversion is not multiplication by a number, need factor = nil.
        local factor = outvalue / invalue
        round_to = default_roundto(intext, factor)
    end
    if round_to then
        if round_to >= 0 then
            if auto then
                -- TODO No less than two significant figures.
            end
            -- It seems format('%d', x) uses modf to extract integer from x
            -- with result '0' if x is 0 or -0 (negative zero).
            -- Using format('%.0f', x) gives '-0' if x is negative zero.
            local fmt = '%.' .. string.format('%d', round_to) .. 'f'
            text = string.format(fmt, outvalue)
        else
            -- This always keeps two sig figs. Should that be done if not auto?
            round_to = -round_to  -- #digits that want to zero
            local maxzeroes = 0  -- maximum #digits that should be zeroed
            if outvalue > 100 then
                maxzeroes = math.modf(math.log10(outvalue)) - 1
            end
            if round_to > maxzeroes then
                round_to = maxzeroes
            end
            if round_to > 0 then
                local scaled = string.format('%.0f', outvalue/(10^round_to))
                text = scaled .. string.rep('0', round_to)
            else
                text = formatnumber(outvalue, 2)  -- can't zero digits; keep 2 sig figs
            end
        end
    end
    return true, withseparator(text)
end

local disp_single = {
    ['or'] = '%s %s or %s %s',
    ['sqbr'] = '%s %s [%s %s]',
    ['comma'] = '%s %s, %s %s',
    ['slash'] = '%s %s / %s %s',
    ['s'] = '%s %s / %s %s',
    ['b'] = '%s %s (%s %s)',
}

local disp_double = {
    ['or'] = '%s%s%s %s or %s%s%s %s',
    ['sqbr'] = '%s%s%s %s [%s%s%s %s]',
    ['comma'] = '%s%s%s %s, %s%s%s %s',
    ['slash'] = '%s%s%s %s / %s%s%s %s',
    ['s'] = '%s%s%s %s / %s%s%s %s',
    ['b'] = '%s%s%s %s (%s%s%s %s)',
}

local function process(parms)
    -- Return true, s where s = final wikitext result (or false, message).
    local success, t
    success, t = units:lookup(parms.in_unit)
    if not success then return success, t else parms.in_unit_table = t end
    if parms.out_unit == nil then           -- need to catch empty string also?
        success, t = defaultunits:lookup(parms.in_unit_table)
        if not success then return success, t else parms.out_unit = t end
    end
    success, t = units:lookup(parms.out_unit)
    if not success then return success, t else parms.out_unit_table = t end
    if parms.in_unit_table.utype ~= parms.out_unit_table.utype then
        local msg = 'Cannot convert %s to %s.[[Category:Convert dimension mismatch]]'
        return false, msg:format(parms.in_unit_table.utype, parms.out_unit_table.utype)
    end
    local intext1, outtext1 = parms.in_text, nil
    local intext2, outtext2 = parms.in_text2, nil
    success, outtext1 = cvtround(parms.value, intext1, parms)
    if not success then return success, outtext1 end
    success, outtext2 = cvtround(parms.value2, intext2, parms)
    if not success then return success, outtext2 end
    local range = parms.range
    local disp = parms.disp
    local wikitext
    intext1 = withseparator(intext1)  -- TODO what if intext1 already has commas?
    -----------------------------------------------------------------------------
    -- TODO Clean up following (a first try at using proper names/symbols).
    local inkey, outkey, symkey = 'name2', 'name2', 'symbol'
    if parms.value == 1 then
        inkey = 'name1'
    end
    local outvalue = 2     -- dummy value
    if outvalue == 1 then  -- TODO need to know if value from cvtround needs singular or plural name
        outkey = 'name1'
    end
    if parms.sp == 'us' then
        inkey = inkey .. '_us'
        outkey = outkey .. '_us'
        symkey = 'sym_us'
    end
    local in_name = parms.in_unit_table[inkey]       -- will not need to calculate all of these
    local in_symbol = parms.in_unit_table[symkey]
    local out_name = parms.out_unit_table[outkey]
    local out_symbol = parms.out_unit_table[symkey]
    local abbr = parms.abbr
    local in_id, out_id
    if abbr == 'on' then            -- all symbols
        in_id = in_symbol
        out_id = out_symbol
    elseif abbr == 'off' then       -- all names
        in_id = in_name
        out_id = out_name
    elseif abbr == 'in' then        -- input symbols
        in_id = in_symbol
        out_id = out_symbol
    elseif abbr == 'out' then       -- output symbols [is this just the default?]
        in_id = in_name
        out_id = out_symbol
    elseif abbr == 'values' then    -- show only values
        -- LATER
    elseif abbr == 'mos' then       -- for ranges, abbreviate with input unit repeated
        -- LATER
    else                            -- default
        in_id = in_name
        out_id = out_symbol
    end
    if range == nil then
        if disp == 'output only' then
            wikitext = '%s %s'
            wikitext = wikitext:format(outtext1, out_id)
        elseif disp == 'output number only' or disp == 'number' then
            wikitext = outtext1
        elseif disp == 'unit' then
            wikitext = in_id
        elseif disp == 'unit2' then
            wikitext = out_id
        elseif disp == 'flip' then
            wikitext = disp_single['b']
            wikitext = wikitext:format(outtext1, out_id, intext1, in_id)
        else
            wikitext = disp_single[disp] or disp_single['b']
            wikitext = wikitext:format(intext1, in_id, outtext1, out_id)
        end
    else
        -- TODO Need in_id, out_id (and more) here.
        wikitext = disp_double[disp] or disp_double['b']
        wikitext = wikitext:format(intext1, range[1], intext2, in_id, outtext1, range[2], outtext2, out_id)
    end
    -----------------------------------------------------------------------------
    return true, wikitext
end

-- Used by template {{convert2}}.
-- We will have to keep old {{convert}} for a long time, and run
-- {{convert2}} in parallel with {{convert}} while testing/developing.
local p = {}
local bodge = require "Module:mw" -- This fixes up mw.text.tag for us.

function p.convert(frame)
    config = get_config(frame)
    local pframe = frame:getParent()
    local parms, text
    success, parms = get_parms(pframe)
    if success then
        success, text = process(parms)
    end
    if not success then
        local params = {style="color:black; background-color:orange;"}
        text=mw.text.tag({name="span", contents="[[Module talk:Convert|Conversion error]]: " .. text, params=params})
    end
    return text
end

return p