Module:Convert: Difference between revisions

From Random Island Wiki
Jump to navigation Jump to search
>Johnuniq
(major updates for bn:: fix many problems with internationalization; workaround two mw.ustring issues; enhance digit grouping)
m (1 revision imported)
 
(53 intermediate revisions by 6 users not shown)
Line 1: Line 1:
-- Convert a value from one unit of measurement to another.
-- Convert a value from one unit of measurement to another.
-- Example: {{convert|123|lb|kg}} --> 123 pounds (56 kg)
-- Example: {{convert|123|lb|kg}} --> 123 pounds (56 kg)
-- See [[:en:Template:Convert/Transwiki guide]] if copying to another wiki.


local MINUS = '−'  -- Unicode U+2212 MINUS SIGN (UTF-8: e2 88 92)
local MINUS = '−'  -- Unicode U+2212 MINUS SIGN (UTF-8: e2 88 92)
Line 9: Line 10:
local ustring = mw.ustring
local ustring = mw.ustring
local ulen = ustring.len
local ulen = ustring.len
 
local usub = ustring.sub
-- mw.ustring has two bugs: following works around one of them; see "2013-07-05" for second.
-- Bug has been reported, and the fix will be deployed, possibly before August 2013.
-- local usub = ustring.sub
-- When fix is deployed, remove following usub function, and uncomment above usub variable.
local function usub(s, i, j)
    return (j and i > j) and '' or ustring.sub(s, i, j)
end


-- Configuration options to keep magic values in one location.
-- Configuration options to keep magic values in one location.
-- The conversion data and message text are defined in separate modules.
-- Conversion data and message text are defined in separate modules.
-- To allow easy comparison between "require" and "loadData", a config option
local config, maxsigfig
-- can be set to control which is used.
local numdot  -- must be '.' or ',' or a character which works in a regex
local numdot, numsep -- each must be a single byte for simple regex search/replace
local numsep, numsep_remove, numsep_remove2
local maxsigfig, warnings
local data_code, all_units
local default_exceptions, link_exceptions, units
local text_code
local SIprefixes, all_categories, all_messages, customary_units, disp_joins
local varname        -- can be a code to use variable names that depend on value
local en_option_value, eng_scales, local_option_name, range_aliases, range_types
local from_en_table -- to translate an output string of en digits to local language
local to_en_table    -- to translate an input string of digits in local language to en
-- Use translation_table in convert/text to change the following.
local en_default          -- true uses lang=en unless convert has lang=local or local digits
local group_method = 3    -- code for how many digits are in a group
local group_method = 3    -- code for how many digits are in a group
local per_word = 'per'    -- for units like "liters per kilometer"
local plural_suffix = 's'  -- only other useful value is probably '' to disable plural unit names
local plural_suffix = 's'  -- only other useful value is probably '' to disable plural unit names
local from_en_table  -- to translate an output string of en digits to local language
local omitsep              -- true to omit separator before local symbol/name
local to_en_table    -- to translate an input string of digits in local language to en
 
-- All units should be defined in the data module. However, to cater for quick changes
-- and experiments, any unknown unit is looked up in an extra data module, if it exists.
-- That module would be transcluded in only a small number of pages, so there should be
-- little server overhead from making changes, and changes should propagate quickly.
local extra_module  -- name of module with extra units
local extra_units  -- nil or table of extra units from extra_module


local function boolean(text)
-- Some options in the invoking template can set variables used later in the module.
    -- Return true if text represents a "true" option value.
local currency_text  -- for a user-defined currency symbol: {{convert|12|$/ha|$=€}} (euro replaces dollar)
    if text then
        text = text:lower()
        if text == '1' or text == 'y' or text == 'yes' or text == 'true' then
            return true
        end
    end
end


local function from_en(text)
local function from_en(text)
    -- Input is a string representing a number in en digits with '.' decimal mark,
-- Input is a string representing a number in en digits with '.' decimal mark,
    -- without digit grouping (which is done just after calling this).
-- without digit grouping (which is done just after calling this).
    -- Return the translation of the string with numdot and digits in local language.
-- Return the translation of the string with numdot and digits in local language.
    if numdot ~= '.' then
if numdot ~= '.' then
        text = text:gsub('%.', numdot)
text = text:gsub('%.', numdot)
    end
end
    if from_en_table then
if from_en_table then
        text = text:gsub('%d', from_en_table)
text = text:gsub('%d', from_en_table)
    end
end
    return text
return text
end
end


local function to_en(text)
local function to_en(text)
    -- Input is a string representing a number in the local language with
-- Input is a string representing a number in the local language with
    -- an optional numdot decimal mark and numsep digit grouping.
-- an optional numdot decimal mark and numsep digit grouping.
    -- Return the translation of the string with '.' mark and en digits,
-- Return the translation of the string with '.' mark and en digits,
    -- and no separators (they have to be removed here to handle cases like
-- and no separators (they have to be removed here to handle cases like
    -- numsep = '.' and numdot = ',' with input "1.234.567,8").
-- numsep = '.' and numdot = ',' with input "1.234.567,8").
    if numsep ~= '' then
if to_en_table then
        text = text:gsub('[' .. numsep .. ']', '')  -- use '[x]' in case x is '.'
text = ustring.gsub(text, '%d', to_en_table)
    end
end
    if numdot ~= '.' then
if numsep_remove then
        text = text:gsub('[' .. numdot .. ']', '.')
text = text:gsub(numsep_remove, '')
    end
end
    if to_en_table then
if numsep_remove2 then
        text = ustring.gsub(text, '%d', to_en_table)
text = text:gsub(numsep_remove2, '')
    end
end
    return text
if numdot ~= '.' then
text = text:gsub(numdot, '.')
end
return text
end
 
local function decimal_mark(text)
-- Return ',' if text probably is using comma for decimal mark, or has no decimal mark.
-- Return '.' if text probably is using dot for decimal mark.
-- Otherwise return nothing (decimal mark not known).
if not text:find('[.,]') then return ',' end
text = text:gsub('^%-', ''):gsub('%+%d+/%d+$', ''):gsub('[Ee]%-?%d+$', '')
local decimal =
text:match('^0?([.,])%d+$') or
text:match('%d([.,])%d?%d?$') or
text:match('%d([.,])%d%d%d%d+$')
if decimal then return decimal end
if text:match('%.%d+%.') then return ',' end
if text:match('%,%d+,') then return '.' end
end
 
local add_warning, with_separator -- forward declarations
local function to_en_with_check(text, parms)
-- Version of to_en() for a wiki using numdot = ',' and numsep = '.' to check
-- text (an input number as a string) which might have been copied from enwiki.
-- For example, in '1.234' the '.' could be a decimal mark or a group separator.
-- From viwiki.
if to_en_table then
text = ustring.gsub(text, '%d', to_en_table)
end
if decimal_mark(text) == '.' then
local original = text
text = text:gsub(',', '')  -- for example, interpret "1,234.5" as an enwiki value
if parms then
add_warning(parms, 0, 'cvt_enwiki_num', original, with_separator({}, text))
end
else
if numsep_remove then
text = text:gsub(numsep_remove, '')
end
if numsep_remove2 then
text = text:gsub(numsep_remove2, '')
end
if numdot ~= '.' then
text = text:gsub(numdot, '.')
end
end
return text
end
 
local function omit_separator(id)
-- Return true if there should be no separator before id (a unit symbol or name).
-- For zhwiki, there should be no separator if id uses local characters.
-- The following kludge should be a sufficient test.
if omitsep then
if id:sub(1, 2) == '-{' then  -- for "-{...}-" content language variant
return true
end
if id:byte() > 127 then
local first = usub(id, 1, 1)
if first ~= 'Å' and first ~= '°' and first ~= 'µ' then
return true
end
end
end
return id:sub(1, 1) == '/' -- no separator before units like "/ha"
end
 
local spell_module  -- name of module that can spell numbers
local speller      -- function from that module to handle spelling (set if needed)
local wikidata_module, wikidata_data_module  -- names of Wikidata modules
local wikidata_code, wikidata_data  -- exported tables from those modules (set if needed)
 
local function set_config(args)
-- Set configuration options from template #invoke or defaults.
config = args
maxsigfig = config.maxsigfig or 14  -- maximum number of significant figures
local data_module, text_module
local sandbox = config.sandbox and ('/' .. config.sandbox) or ''
data_module = "Module:Convert/data" .. sandbox
text_module = "Module:Convert/text" .. sandbox
extra_module = "Module:Convert/extra" .. sandbox
wikidata_module = "Module:Convert/wikidata" .. sandbox
wikidata_data_module = "Module:Convert/wikidata/data" .. sandbox
spell_module = "Module:ConvertNumeric"
data_code = mw.loadData(data_module)
text_code = mw.loadData(text_module)
all_units = data_code.all_units
local translation = text_code.translation_table
if translation then
numdot = translation.numdot
numsep = translation.numsep
if numdot == ',' and numsep == '.' then
if text_code.all_messages.cvt_enwiki_num then
to_en = to_en_with_check
end
end
if translation.group then
group_method = translation.group
end
if translation.per_word then
per_word = translation.per_word
end
if translation.plural_suffix then
plural_suffix = translation.plural_suffix
end
varname = translation.varname
from_en_table = translation.from_en
local use_workaround = true
if use_workaround then
-- 2013-07-05 workaround bug by making a copy of the required table.
-- mw.ustring.gsub fails with a table (to_en_table) as the replacement,
-- if the table is accessed via mw.loadData.
local source = translation.to_en
if source then
to_en_table = {}
for k, v in pairs(source) do
to_en_table[k] = v
end
end
else
to_en_table = translation.to_en
end
if translation.lang == 'en default' then
en_default = true  -- for hiwiki
end
omitsep = translation.omitsep  -- for zhwiki
end
numdot = config.numdot or numdot or '.'  -- decimal mark before fractional digits
numsep = config.numsep or numsep or ','  -- group separator for numbers
-- numsep should be ',' or '.' or '' or ' ' or a Unicode character.
-- numsep_remove must work in a regex to identify separators to be removed.
if numsep ~= '' then
numsep_remove = (numsep == '.') and '%.' or numsep
end
if numsep ~= ',' and numdot ~= ',' then
numsep_remove2 = ','  -- so numbers copied from enwiki will work
end
end
 
local function collection()
-- Return a table to hold items.
return {
n = 0,
add = function (self, item)
self.n = self.n + 1
self[self.n] = item
end,
}
end
end


local function set_config(frame)
local function divide(numerator, denominator)
    -- Set configuration options from template #invoke or defaults.
-- Return integers quotient, remainder resulting from dividing the two
    local args = frame.args
-- given numbers, which should be unsigned integers.
    numdot = args.numdot or '.'      -- decimal mark before fractional digits
local quotient, remainder = floor(numerator / denominator), numerator % denominator
    numsep = args.numsep or ','      -- group separator for numbers (',', '.', '')
if not (0 <= remainder and remainder < denominator) then
    maxsigfig = args.maxsigfig or 14  -- maximum number of significant figures
-- Floating point limits may need this, as in {{convert|160.02|Ym|ydftin}}.
    warnings = boolean(args.warnings) -- true if want warnings for invalid options
remainder = 0
    -- Scribunto sets the global variable 'mw'.
end
    -- A testing program can set the global variable 'is_test_run'.
return quotient, remainder
    local convertdata, converttext, data_module, text_module
    if is_test_run then
        data_module = "convertdata"
        text_module = "converttext"
    else
        data_module = "Module:Convert/data"
        text_module = "Module:Convert/text"
    end
    if args.use_require then
        convertdata = require(data_module)
        converttext = require(text_module)
    else
        convertdata = mw.loadData(data_module)
        converttext = mw.loadData(text_module)
    end
    default_exceptions = convertdata.default_exceptions
    link_exceptions = convertdata.link_exceptions
    units = convertdata.units
    SIprefixes = converttext.SIprefixes
    all_categories = converttext.all_categories
    all_messages = converttext.all_messages
    customary_units = converttext.customary_units
    disp_joins = converttext.disp_joins
    en_option_value = converttext.en_option_value
    eng_scales = converttext.eng_scales
    local_option_name = converttext.local_option_name
    range_aliases = converttext.range_aliases
    range_types = converttext.range_types
    -- LATER: Simplify following by using a translation table if it is defined,
    -- without needing to check the current wiki's language. Am using this more
    -- generic treatment while testing.
    local lang = mw.language.getContentLanguage()
    local translation = converttext.translation_table[lang.code]
    if translation then
        if translation.group then
            group_method = translation.group
        end
        if translation.plural_suffix then
            plural_suffix = translation.plural_suffix
        end
        from_en_table = translation.from_en
        local use_workaround = true
        if use_workaround then
            -- 2013-07-05 workaround bug by making a copy of the required table.
            -- mw.ustring.gsub fails with a table (to_en_table) as the replacement,
            -- if the table is accessed via mw.loadData.
            local source = translation.to_en
            if source then
                to_en_table = {}
                for k, v in pairs(source) do
                    to_en_table[k] = v
                end
            end
        else
            to_en_table = translation.to_en
        end
    end
end
end


local function split(text, delimiter)
local function split(text, delimiter)
    -- Return a numbered table with fields from splitting text.
-- Return a numbered table with fields from splitting text.
    -- The delimiter is used in a regex without escaping (for example, '.' would fail).
-- The delimiter is used in a regex without escaping (for example, '.' would fail).
    -- Each field has any leading/trailing whitespace removed.
-- Each field has any leading/trailing whitespace removed.
    local t = {}
local t = {}
    text = text .. delimiter  -- to get last item
text = text .. delimiter  -- to get last item
    for item in text:gmatch('%s*(.-)%s*' .. delimiter) do
for item in text:gmatch('%s*(.-)%s*' .. delimiter) do
        table.insert(t, item)
table.insert(t, item)
    end
end
    return t
return t
end
end


local function strip(text)
local function strip(text)
    -- If text is a string, return its content with no leading/trailing
-- If text is a string, return its content with no leading/trailing
    -- whitespace. Otherwise return nil (a nil argument gives a nil result).
-- whitespace. Otherwise return nil (a nil argument gives a nil result).
    if type(text) == 'string' then
if type(text) == 'string' then
        return text:match("^%s*(.-)%s*$")
return text:match("^%s*(.-)%s*$")
    end
end
end
end


local function message(mcode)
local function table_len(t)
    -- Return wikitext for an error message, including category if specified
-- Return length (<100) of a numbered table to replace #t which is
    -- for the message type.
-- documented to not work if t is accessed via mw.loadData().
    -- mcode = numbered table specifying the message:
for i = 1, 100 do
    --    mcode[1] = 'cvt_xxx' (string used as a key to get message info)
if t[i] == nil then
    --    mcode[2] = 'parm1' (string to replace first %s if any in message)
return i - 1
    --    mcode[3] = 'parm2' (string to replace second %s if any in message)
end
    --    mcode[4] = 'parm3' (string to replace third %s if any in message)
end
    local msg = all_messages[mcode[1]]
end
    if msg then
 
        local text = format(msg[1] or 'Missing message',
local function wanted_category(catkey, catsort, want_warning)
            mcode[2] or '?',
-- Return message category if it is wanted in current namespace,
            mcode[3] or '?',
-- otherwise return ''.
            mcode[4] or '?')
local cat
        local cat = all_categories[msg[2]] or ''
local title = mw.title.getCurrentTitle()
        local prefix = all_messages[msg.warning and 'cvt_prefix_warning' or 'cvt_prefix_error'] or ''
if title then
        local suffix = (prefix == '') and '' or '</span>'
local nsdefault = '0'  -- default namespace: '0' = article; '0,10' = article and template
        local regex, replace = msg.regex, msg.replace
local namespace = title.namespace
        if regex and replace then
for _, v in ipairs(split(config.nscat or nsdefault, ',')) do
            text = text:gsub(regex, replace)
if namespace == tonumber(v) then
        end
cat = text_code.all_categories[want_warning and 'warning' or catkey]
        return prefix .. ' ' .. text .. cat .. suffix
if catsort and catsort ~= '' and cat:sub(-2) == ']]' then
    end
cat = cat:sub(1, -3) .. '|' .. mw.text.nowiki(usub(catsort, 1, 20)) .. ']]'
    return 'Convert internal error: unknown message'
end
break
end
end
end
return cat or ''
end
 
local function message(parms, mcode, is_warning)
-- Return wikitext for an error message, including category if specified
-- for the message type.
-- mcode = numbered table specifying the message:
--    mcode[1] = 'cvt_xxx' (string used as a key to get message info)
--    mcode[2] = 'parm1' (string to replace '$1' if any in message)
--    mcode[3] = 'parm2' (string to replace '$2' if any in message)
--    mcode[4] = 'parm3' (string to replace '$3' if any in message)
local msg
if type(mcode) == 'table' then
if mcode[1] == 'cvt_no_output' then
-- Some errors should cause convert to output an empty string,
-- for example, for an optional field in an infobox.
return ''
end
msg = text_code.all_messages[mcode[1]]
end
parms.have_problem = true
local function subparm(fmt, ...)
local rep = {}
for i, v in ipairs({...}) do
rep['$' .. i] = v
end
return (fmt:gsub('$%d+', rep))
end
if msg then
local parts = {}
local regex, replace = msg.regex, msg.replace
for i = 1, 3 do
local limit = 40
local s = mcode[i + 1]
if s then
if regex and replace then
s = s:gsub(regex, replace)
limit = nil  -- allow long "should be" messages
end
-- Escape user input so it does not break the message.
-- To avoid tags (like {{convert|1<math>23</math>|m}}) breaking
-- the mouseover title, any strip marker starting with char(127) is
-- replaced with '...' (text not needing i18n).
local append
local pos = s:find(string.char(127), 1, true)
if pos then
append = '...'
s = s:sub(1, pos - 1)
end
if limit and ulen(s) > limit then
s = usub(s, 1, limit)
append = '...'
end
s = mw.text.nowiki(s) .. (append or '')
else
s = '?'
end
parts['$' .. i] = s
end
local function ispreview()
-- Return true if a prominent message should be shown.
if parms.test == 'preview' or parms.test == 'nopreview' then
-- For testing, can preview a real message or simulate a preview
-- when running automated tests.
return parms.test == 'preview'
end
local success, revid = pcall(function ()
return (parms.frame):preprocess('{{REVISIONID}}') end)
return success and (revid == '')
end
local want_warning = is_warning and
not config.warnings and  -- show unobtrusive warnings if config.warnings not configured
not msg.nowarn          -- but use msg settings, not standard warning, if specified
local title = string.gsub(msg[1] or 'Missing message', '$%d+', parts)
local text = want_warning and '*' or msg[2] or 'Missing message'
local cat = wanted_category(msg[3], mcode[2], want_warning)
local anchor = msg[4] or ''
local fmtkey = ispreview() and 'cvt_format_preview' or
(want_warning and 'cvt_format2' or msg.format or 'cvt_format')
local fmt = text_code.all_messages[fmtkey] or 'convert: bug'
return subparm(fmt, title:gsub('"', '&quot;'), text, cat, anchor)
end
return 'Convert internal error: unknown message'
end
 
function add_warning(parms, level, key, text1, text2)  -- for forward declaration above
-- If enabled, add a warning that will be displayed after the convert result.
-- A higher level is more verbose: more kinds of warnings are displayed.
-- To reduce output noise, only the first warning is displayed.
if level <= (tonumber(config.warnings) or 1) then
if parms.warnings == nil then
parms.warnings = message(parms, { key, text1, text2 }, true)
end
end
end
 
local function spell_number(parms, inout, number, numerator, denominator)
-- Return result of spelling (number, numerator, denominator), or
-- return nil if spelling is not available or not supported for given text.
-- Examples (each value must be a string or nil):
--  number  numerator  denominator  output
--  ------  ---------  -----------  -------------------
--  "1.23"    nil        nil        one point two three
--    "1"      "2"        "3"        one and two thirds
--    nil      "2"        "3"        two thirds
if not speller then
local function get_speller(module)
return require(module).spell_number
end
local success
success, speller = pcall(get_speller, spell_module)
if not success or type(speller) ~= 'function' then
add_warning(parms, 1, 'cvt_no_spell', 'spell')
return nil
end
end
local case
if parms.spell_upper == inout then
case = true
parms.spell_upper = nil  -- only uppercase first word in a multiple unit
end
local sp = not parms.opt_sp_us
local adj = parms.opt_adjectival
return speller(number, numerator, denominator, case, sp, adj)
end
end


Line 191: Line 407:
-- LATER: If need much more code, move to another module to simplify this module.
-- LATER: If need much more code, move to another module to simplify this module.
local function speed_of_sound(altitude)
local function speed_of_sound(altitude)
    -- This is for the Mach built-in unit of speed.
-- This is for the Mach built-in unit of speed.
    -- Return speed of sound in metres per second at given altitude in feet.
-- Return speed of sound in metres per second at given altitude in feet.
    -- If no altitude given, use default (zero altitude = sea level).
-- If no altitude given, use default (zero altitude = sea level).
    -- Table gives speed of sound in miles per hour at various altitudes:
-- Table gives speed of sound in miles per hour at various altitudes:
    --  altitude = -17,499 to 302,499 feet
--  altitude = -17,499 to 302,499 feet
    -- mach_table[a + 4] = s where
-- mach_table[a + 4] = s where
    --  a = (altitude / 5000) rounded to nearest integer (-3 to 60)
--  a = (altitude / 5000) rounded to nearest integer (-3 to 60)
    --  s = speed of sound (mph) at that altitude
--  s = speed of sound (mph) at that altitude
    -- LATER: Should calculate result from an interpolation between the next
-- LATER: Should calculate result from an interpolation between the next
    -- lower and higher altitudes in table, rather than rounding to nearest.
-- lower and higher altitudes in table, rather than rounding to nearest.
    -- From: http://www.aerospaceweb.org/question/atmosphere/q0112.shtml
-- From: http://www.aerospaceweb.org/question/atmosphere/q0112.shtml
    local mach_table = {                                                      -- a =
local mach_table = {                                                      -- a =
        799.5, 787.0, 774.2, 761.207051,                                      -- -3 to  0
799.5, 787.0, 774.2, 761.207051,                                      -- -3 to  0
        748.0, 734.6, 721.0, 707.0, 692.8, 678.3, 663.5, 660.1, 660.1, 660.1,  --  1 to 10
748.0, 734.6, 721.0, 707.0, 692.8, 678.3, 663.5, 660.1, 660.1, 660.1,  --  1 to 10
        660.1, 660.1, 660.1, 662.0, 664.3, 666.5, 668.9, 671.1, 673.4, 675.6,  -- 11 to 20
660.1, 660.1, 660.1, 662.0, 664.3, 666.5, 668.9, 671.1, 673.4, 675.6,  -- 11 to 20
        677.9, 683.7, 689.9, 696.0, 702.1, 708.1, 714.0, 719.9, 725.8, 731.6,  -- 21 to 30
677.9, 683.7, 689.9, 696.0, 702.1, 708.1, 714.0, 719.9, 725.8, 731.6,  -- 21 to 30
        737.3, 737.7, 737.7, 736.2, 730.5, 724.6, 718.8, 712.9, 707.0, 701.1,  -- 31 to 40
737.3, 737.7, 737.7, 736.2, 730.5, 724.6, 718.8, 712.9, 707.0, 701.1,  -- 31 to 40
        695.0, 688.9, 682.8, 676.6, 670.4, 664.1, 657.8, 652.9, 648.3, 643.7,  -- 41 to 50
695.0, 688.9, 682.8, 676.6, 670.4, 664.1, 657.8, 652.9, 648.3, 643.7,  -- 41 to 50
        639.1, 634.4, 629.6, 624.8, 620.0, 615.2, 613.2, 613.2, 613.2, 613.5,  -- 51 to 60
639.1, 634.4, 629.6, 624.8, 620.0, 615.2, 613.2, 613.2, 613.2, 613.5,  -- 51 to 60
    }
}
    altitude = altitude or 0
altitude = altitude or 0
    local a = (altitude < 0) and -altitude or altitude
local a = (altitude < 0) and -altitude or altitude
    a = floor(a / 5000 + 0.5)
a = floor(a / 5000 + 0.5)
    if altitude < 0 then
if altitude < 0 then
        a = -a
a = -a
    end
end
    if a < -3 then
if a < -3 then
        a = -3
a = -3
    elseif a > 60 then
elseif a > 60 then
        a = 60
a = 60
    end
end
    return mach_table[a + 4] * 0.44704  -- mph converted to m/s
return mach_table[a + 4] * 0.44704  -- mph converted to m/s
end
end
-- END: Code required only for built-in units.
-- END: Code required only for built-in units.
------------------------------------------------------------------------
------------------------------------------------------------------------
local function add_style(parms, class)
-- Add selected template style to parms if not already present.
parms.templatestyles = parms.templatestyles or {}
if not parms.templatestyles[class] then
parms.templatestyles[class] = parms.frame:extensionTag({
name = 'templatestyles', args = { src = text_code.titles[class] }
})
end
end
local function get_styles(parms)
-- Return string of required template styles, empty if none.
if parms.templatestyles then
local t = {}
for _, v in pairs(parms.templatestyles) do
table.insert(t, v)
end
return table.concat(t)
end
return ''
end
local function get_range(word)
-- Return a range (string or table) corresponding to word (like "to"),
-- or return nil if not a range word.
local ranges = text_code.ranges
return ranges.types[word] or ranges.types[ranges.aliases[word]]
end
local function check_mismatch(unit1, unit2)
-- If unit1 cannot be converted to unit2, return an error message table.
-- This allows conversion between units of the same type, and between
-- Nm (normally torque) and ftlb (energy), as in gun-related articles.
-- This works because Nm is the base unit (scale = 1) for both the
-- primary type (torque), and the alternate type (energy, where Nm = J).
-- A match occurs if the primary types are the same, or if unit1 matches
-- the alternate type of unit2, and vice versa. That provides a whitelist
-- of which conversions are permitted between normally incompatible types.
if unit1.utype == unit2.utype or
(unit1.utype == unit2.alttype and unit1.alttype == unit2.utype) then
return nil
end
return { 'cvt_mismatch', unit1.utype, unit2.utype }
end


local function override_from(out_table, in_table, fields)
local function override_from(out_table, in_table, fields)
    -- Copy the specified fields from in_table to out_table, but do not
-- Copy the specified fields from in_table to out_table, but do not
    -- copy nil fields (keep any corresponding field in out_table).
-- copy nil fields (keep any corresponding field in out_table).
    for _, field in ipairs(fields) do
for _, field in ipairs(fields) do
        if in_table[field] then
if in_table[field] then
            out_table[field] = in_table[field]
out_table[field] = in_table[field]
        end
end
    end
end
end
end


local function shallow_copy(t)
local function shallow_copy(t)
    -- Return a shallow copy of table t.
-- Return a shallow copy of table t.
    -- Do not need the features and overhead of the Scribunto mw.clone().
-- Do not need the features and overhead of the Scribunto mw.clone().
    local result = {}
local result = {}
    for k, v in pairs(t) do
for k, v in pairs(t) do
        result[k] = v
result[k] = v
    end
end
    return result
return result
end
end


local unit_mt = {
local unit_mt = {
    -- Metatable to get missing values for a unit that does not accept SI prefixes,
-- Metatable to get missing values for a unit that does not accept SI prefixes.
    -- or for a unit that accepts prefixes but where no prefix was used.
-- Warning: The boolean value 'false' is returned for any missing field
    -- In the latter case, and before use, fields symbol, name1, name1_us
-- so __index is not called twice for the same field in a given unit.
    -- must be set from _symbol, _name1, _name1_us respectively.
__index = function (self, key)
    __index = function (self, key)
local value
        local value
if key == 'name1' or key == 'sym_us' then
        if key == 'name1' or key == 'sym_us' then
value = self.symbol
            value = self.symbol
elseif key == 'name2' then
        elseif key == 'name2' then
value = self.name1 .. plural_suffix
            value = self.name1 .. plural_suffix
elseif key == 'name1_us' then
        elseif key == 'name1_us' then
value = self.name1
            value = self.name1
if not rawget(self, 'name2_us') then
            if not rawget(self, 'name2_us') then
-- If name1_us is 'foot', do not make name2_us by appending plural_suffix.
                -- If name1_us is 'foot', do not make name2_us by appending plural_suffix.
self.name2_us = self.name2
                self.name2_us = self.name2
end
            end
elseif key == 'name2_us' then
        elseif key == 'name2_us' then
local raw1_us = rawget(self, 'name1_us')
            local raw1_us = rawget(self, 'name1_us')
if raw1_us then
            if raw1_us then
value = raw1_us .. plural_suffix
                value = raw1_us .. plural_suffix
else
            else
value = self.name2
                value = self.name2
end
            end
elseif key == 'link' then
        elseif key == 'link' then
value = self.name1
            value = self.name1
else
        elseif key == 'builtin' then
value = false
            value = false
end
        else
rawset(self, key, value)
            return nil
return value
        end
end
        rawset(self, key, value)
        return value
    end
}
}
local function prefixed_name(unit, name, index)
-- Return unit name with SI prefix inserted at correct position.
-- index = 1 (name1), 2 (name2), 3 (name1_us), 4 (name2_us).
-- The position is a byte (not character) index, so use Lua's sub().
local pos = rawget(unit, 'prefix_position')
if type(pos) == 'string' then
pos = tonumber(split(pos, ',')[index])
end
if pos then
return name:sub(1, pos - 1) .. unit.si_name .. name:sub(pos)
end
return unit.si_name .. name
end


local unit_prefixed_mt = {
local unit_prefixed_mt = {
    -- Metatable to get missing values for a unit that accepts SI prefixes,
-- Metatable to get missing values for a unit that accepts SI prefixes.
    -- and where a prefix has been used.
-- Before use, fields si_name, si_prefix must be defined.
    -- Before use, fields si_name, si_prefix must be defined.
-- The unit must define _symbol, _name1 and
    __index = function (self, key)
-- may define _sym_us, _name1_us, _name2_us
        local value
-- (_sym_us, _name2_us may be defined for a language using sp=us
        if key == 'symbol' then
-- to refer to a variant unrelated to U.S. units).
            value = self.si_prefix .. self._symbol
__index = function (self, key)
        elseif key == 'sym_us' then
local value
            value = self.symbol -- always the same as sym_us for prefixed units
if key == 'symbol' then
        elseif key == 'name1' then
value = self.si_prefix .. self._symbol
            local pos = rawget(self, 'prefix_position') or 1
elseif key == 'sym_us' then
            value = self._name1
value = rawget(self, '_sym_us')
            value = usub(value, 1, pos - 1) .. self.si_name .. usub(value, pos)
if value then
        elseif key == 'name2' then
value = self.si_prefix .. value
            value = self.name1 .. plural_suffix
else
        elseif key == 'name1_us' then
value = self.symbol
            value = rawget(self, '_name1_us')
end
            if value then
elseif key == 'name1' then
                local pos = rawget(self, 'prefix_position') or 1
value = prefixed_name(self, self._name1, 1)
                value = usub(value, 1, pos - 1) .. self.si_name .. usub(value, pos)
elseif key == 'name2' then
            else
value = rawget(self, '_name2')
                value = self.name1
if value then
            end
value = prefixed_name(self, value, 2)
        elseif key == 'name2_us' then
else
            if rawget(self, '_name1_us') then
value = self.name1 .. plural_suffix
                value = self.name1_us .. plural_suffix
end
            else
elseif key == 'name1_us' then
                value = self.name2
value = rawget(self, '_name1_us')
            end
if value then
        elseif key == 'link' then
value = prefixed_name(self, value, 3)
            value = self.name1
else
        elseif key == 'builtin' then
value = self.name1
            value = false
end
        else
elseif key == 'name2_us' then
            return nil
value = rawget(self, '_name2_us')
        end
if value then
        rawset(self, key, value)
value = prefixed_name(self, value, 4)
        return value
elseif rawget(self, '_name1_us') then
    end
value = self.name1_us .. plural_suffix
else
value = self.name2
end
elseif key == 'link' then
value = self.name1
else
value = false
end
rawset(self, key, value)
return value
end
}
}


local unit_per_mt = {
local unit_per_mt = {
    -- Metatable to get values for a "per" unit of form "x/y".
-- Metatable to get values for a per unit of form "x/y".
    -- This is never called to determine a unit name or link because "per" units
-- This is never called to determine a unit name or link because per units
    -- are handled as a special case.
-- are handled as a special case.
    __index = function (self, key)
-- Similarly, the default output is handled elsewhere, and for a symbol
        local value
-- this is only called from get_default() for default_exceptions.
        if key == 'symbol' then
__index = function (self, key)
            local per = self.per
local value
            local unit1, unit2 = per[1], per[2]
if key == 'symbol' then
            if unit1 then
local per = self.per
                value = unit1[key] .. '/' .. unit2[key]
local unit1, unit2 = per[1], per[2]
            else
if unit1 then
                value = '/' .. unit2[key]
value = unit1[key] .. '/' .. unit2[key]
            end
else
        elseif key == 'sym_us' then
value = '/' .. unit2[key]
            value = self.symbol
end
        elseif key == 'scale' then
elseif key == 'sym_us' then
            local per = self.per
value = self.symbol
            local unit1, unit2 = per[1], per[2]
elseif key == 'scale' then
            value = (unit1 and unit1.scale or 1) / unit2.scale
local per = self.per
        elseif key == 'builtin' then
local unit1, unit2 = per[1], per[2]
            value = false
value = (unit1 and unit1.scale or 1) * self.scalemultiplier / unit2.scale
        else
else
            return nil
value = false
        end
end
        rawset(self, key, value)
rawset(self, key, value)
        return value
return value
    end
end
}
}


local function lookup(unitcode, opt_sp_us, what)
local function make_per(unitcode, unit_table, ulookup)
    -- Return true, t where t is a copy of the unit's converter table,
-- Return true, t where t is a per unit with unit codes expanded to unit tables,
    -- or return false, t where t is an error message table.
-- or return false, t where t is an error message table.
    -- Parameter opt_sp_us is true for US spelling of SI prefixes and
local result = {
    -- the symbol and name of the unit. If true, the result includes field
unitcode = unitcode,
    -- sp_us = true (that field may also have been in the unit definition).
utype = unit_table.utype,
    -- Parameter 'what' determines whether combination units are accepted:
per = {}
    --  'no_combination'  : single unit only
}
    --  'any_combination' : single unit or combination or output multiple
override_from(result, unit_table, { 'invert', 'iscomplex', 'default', 'link', 'symbol', 'symlink' })
    --  'only_multiple'  : single unit or output multiple only
result.symbol_raw = (result.symbol or false)  -- to distinguish between a defined exception and a metatable calculation
    -- Parameter unitcode is a symbol (like 'g'), with an optional SI prefix (like 'kg').
local prefix
    -- If, for example, 'kg' is in this table, that entry is used;
for i, v in ipairs(unit_table.per) do
    -- otherwise the prefix ('k') is applied to the base unit ('g').
if i == 1 and v == '' then
    -- If unitcode is a known combination code (and if allowed by what),
-- First unit symbol can be empty; that gives a nil first unit table.
    -- a table of output multiple unit tables is included in the result.
elseif i == 1 and text_code.currency[v] then
    -- For compatibility with the old template, underscores in unitcode are replaced
prefix = currency_text or v
    -- with spaces so {{convert|350|board_feet}} --> 350 board feet (0.83 m³).
else
    if unitcode == nil or unitcode == '' then
local success, t = ulookup(v)
        return false, { 'cvt_no_unit' }
if not success then return false, t end
    end
result.per[i] = t
    unitcode = unitcode:gsub('_', ' ')
end
    local t = units[unitcode]
end
    if t then
local multiplier = unit_table.multiplier
        if t.shouldbe then
if not result.utype then
            return false, { 'cvt_should_be', t.shouldbe }
-- Creating an automatic per unit.
        end
local unit1 = result.per[1]
        local force_sp_us = opt_sp_us
local utype = (unit1 and unit1.utype or prefix or '') .. '/' .. result.per[2].utype
        if t.sp_us then
local t = data_code.per_unit_fixups[utype]
            force_sp_us = true
if t then
            opt_sp_us = true
if type(t) == 'table' then
        end
utype = t.utype or utype
        local target = t.target  -- nil, or unitcode is an alias for this target
result.link = result.link or t.link
        if target then
multiplier = multiplier or t.multiplier
            local success, result = lookup(target, opt_sp_us, what)
else
            if not success then return false, result end
utype = t
            override_from(result, t, { 'customary', 'default', 'link', 'symbol', 'symlink' })
end
            local multiplier = t.multiplier
end
            if multiplier then
result.utype = utype
                result.multiplier = tostring(multiplier)
end
                result.scale = result.scale * multiplier
result.scalemultiplier = multiplier or 1
            end
result.vprefix = prefix or false -- set to non-nil to avoid calling __index
            return true, result
return true, setmetatable(result, unit_per_mt)
        end
        local per = t.per  -- nil/false, or a numbered table for "x/y" units
        if per then
            local result = { utype = t.utype, per = {} }
            override_from(result, t, { 'default', 'invert', 'iscomplex', 'symbol', 'symlink' })
            result.symbol_raw = (result.symbol or false)  -- to distinguish between a defined exception and a metatable calculation
            local cvt = result.per
            local prefix
            for i, v in ipairs(per) do
                if i == 1 and (v == '$' or v == '£') then
                    prefix = v
                else
                    local success, t = lookup(v, opt_sp_us, 'no_combination')
                    if not success then return false, t end
                    cvt[i] = t
                    if t.sp_us then  -- if the top or bottom unit forces sp=us, set the per unit to use the correct name/symbol
                        force_sp_us = true
                    end
                end
            end
            if prefix then
                result.vprefix = prefix
            else
                result.vprefix = false  -- to avoid calling __index
            end
            result.sp_us = force_sp_us
            return true, setmetatable(result, unit_per_mt)
        end
        local combo = t.combination  -- nil or a table of unitcodes
        if combo then
            local multiple = t.multiple
            if what == 'no_combination' or (what == 'only_multiple' and multiple == nil) then
                return false, { 'cvt_bad_unit', unitcode }
            end
            -- Recursively create a combination table containing the
            -- converter table of each unitcode.
            local result = { utype = t.utype, multiple = multiple, combination = {} }
            local cvt = result.combination
            for i, v in ipairs(combo) do
                local success, t = lookup(v, opt_sp_us, multiple and 'no_combination' or 'only_multiple')
                if not success then return false, t end
                cvt[i] = t
            end
            return true, result
        end
        local result = shallow_copy(t)
        result.sp_us = force_sp_us
        if result.prefixes then
            result.symbol = result._symbol
            result.name1 = result._name1
            result.name1_us = result._name1_us
        end
        return true, setmetatable(result, unit_mt)
    end
    for plen = 2, 1, -1 do
        -- Look for an SI prefix; should never occur with an alias.
        -- Check for longer prefix first ('dam' is decametre).
        local prefix = usub(unitcode, 1, plen)
        local si = SIprefixes[prefix]
        if si then
            local t = units[usub(unitcode, plen+1)]
            if t and t.prefixes then
                local result = shallow_copy(t)
                if opt_sp_us then
                    result.sp_us = true
                end
                if result.sp_us and si.name_us then
                    result.si_name = si.name_us
                else
                    result.si_name = si.name
                end
                result.si_prefix = si.prefix or prefix
                result.scale = t.scale * 10 ^ (si.exponent * t.prefixes)
                return true, setmetatable(result, unit_prefixed_mt)
            end
        end
    end
    -- Accept any unit with an engineering notation prefix like "e6cuft"
    -- (million cubic feet), but not chained prefixes like "e3e6cuft",
    -- and not if the unit is a combination or multiple,
    -- and not if the unit has an offset or is a built-in.
    -- Only en digits are accepted.
    local exponent, baseunit = unitcode:match('^e(%d+)(.*)')
    if exponent then
        local engscale = eng_scales[exponent]
        if engscale then
            local success, result = lookup(baseunit, opt_sp_us, 'no_combination')
            if not success then return false, result end
            if not (result.offset or result.builtin or result.engscale) then
                result.defkey = unitcode -- key to lookup default exception
                result.engscale = engscale
                result.scale = result.scale * 10 ^ tonumber(exponent)
                return true, result
            end
        end
    end
    return false, { 'cvt_unknown', unitcode }
end
end


local function valid_number(num)
local function lookup(parms, unitcode, what, utable, fails, depth)
    -- Return true if num is a valid number.
-- Return true, t where t is a copy of the unit's converter table,
    -- Expressed as a string, overflow or other problems are indicated with
-- or return false, t where t is an error message table.
    -- text like "1.#INF" or ".#IND" which are regarded as invalid here.
-- Parameter 'what' determines whether combination units are accepted:
    if type(num) == 'number' and tostring(num):find('#', 1, true) == nil then
--  'no_combination'  : single unit only
        return true
--  'any_combination' : single unit or combination or output multiple
    end
--  'only_multiple'  : single unit or output multiple only
-- Parameter unitcode is a symbol (like 'g'), with an optional SI prefix (like 'kg').
-- If, for example, 'kg' is in this table, that entry is used;
-- otherwise the prefix ('k') is applied to the base unit ('g').
-- If unitcode is a known combination code (and if allowed by what),
-- a table of output multiple unit tables is included in the result.
-- For compatibility with the old template, an underscore in a unitcode is
-- replaced with a space so usage like {{convert|350|board_feet}} works.
-- Wikignomes may also put two spaces or "&nbsp;" in combinations, so
-- replace underscore, "&nbsp;", and multiple spaces with a single space.
utable = utable or parms.unittable or all_units
fails = fails or {}
depth = depth and depth + 1 or 1
if depth > 9 then
-- There are ways to mistakenly define units which result in infinite
-- recursion when lookup() is called. That gives a long delay and very
-- confusing error messages, so the depth parameter is used as a guard.
return false, { 'cvt_lookup', unitcode }
end
if unitcode == nil or unitcode == '' then
return false, { 'cvt_no_unit' }
end
unitcode = unitcode:gsub('_', ' '):gsub('&nbsp;', ' '):gsub('  +', ' ')
local function call_make_per(t)
return make_per(unitcode, t,
function (ucode) return lookup(parms, ucode, 'no_combination', utable, fails, depth) end
)
end
local t = utable[unitcode]
if t then
if t.shouldbe then
return false, { 'cvt_should_be', t.shouldbe }
end
if t.sp_us then
parms.opt_sp_us = true
end
local target = t.target  -- nil, or unitcode is an alias for this target
if target then
local success, result = lookup(parms, target, what, utable, fails, depth)
if not success then return false, result end
override_from(result, t, { 'customary', 'default', 'link', 'symbol', 'symlink' })
local multiplier = t.multiplier
if multiplier then
result.multiplier = tostring(multiplier)
result.scale = result.scale * multiplier
end
return true, result
end
if t.per then
return call_make_per(t)
end
local combo = t.combination  -- nil or a table of unitcodes
if combo then
local multiple = t.multiple
if what == 'no_combination' or (what == 'only_multiple' and not multiple) then
return false, { 'cvt_bad_unit', unitcode }
end
-- Recursively create a combination table containing the
-- converter table of each unitcode.
local result = { utype = t.utype, multiple = multiple, combination = {} }
local cvt = result.combination
for i, v in ipairs(combo) do
local success, t = lookup(parms, v, multiple and 'no_combination' or 'only_multiple', utable, fails, depth)
if not success then return false, t end
cvt[i] = t
end
return true, result
end
local result = shallow_copy(t)
result.unitcode = unitcode
if result.prefixes then
result.si_name = ''
result.si_prefix = ''
return true, setmetatable(result, unit_prefixed_mt)
end
return true, setmetatable(result, unit_mt)
end
local SIprefixes = text_code.SIprefixes
for plen = SIprefixes[1] or 2, 1, -1 do
-- Look for an SI prefix; should never occur with an alias.
-- Check for longer prefix first ('dam' is decametre).
-- SIprefixes[1] = prefix maximum #characters (as seen by mw.ustring.sub).
local prefix = usub(unitcode, 1, plen)
local si = SIprefixes[prefix]
if si then
local t = utable[usub(unitcode, plen+1)]
if t and t.prefixes then
local result = shallow_copy(t)
result.unitcode = unitcode
result.si_name = parms.opt_sp_us and si.name_us or si.name
result.si_prefix = si.prefix or prefix
result.scale = t.scale * 10 ^ (si.exponent * t.prefixes)
return true, setmetatable(result, unit_prefixed_mt)
end
end
end
-- Accept user-defined combinations like "acre+m2+ha" or "acre m2 ha" for output.
-- If '+' is used, each unit code can include a space, and any error is fatal.
-- If ' ' is used and if each space-separated word is a unit code, it is a combo,
-- but errors are not fatal so the unit code can be looked up as an extra unit.
local err_is_fatal
local combo = collection()
if unitcode:find('+', 1, true) then
err_is_fatal = true
for item in (unitcode .. '+'):gmatch('%s*(.-)%s*%+') do
if item ~= '' then
combo:add(item)
end
end
elseif unitcode:find('%s') then
for item in unitcode:gmatch('%S+') do
combo:add(item)
end
end
if combo.n > 1 then
local function lookup_combo()
if what == 'no_combination' or what == 'only_multiple' then
return false, { 'cvt_bad_unit', unitcode }
end
local result = { combination = {} }
local cvt = result.combination
for i, v in ipairs(combo) do
local success, t = lookup(parms, v, 'only_multiple', utable, fails, depth)
if not success then return false, t end
if i == 1 then
result.utype = t.utype
else
local mismatch = check_mismatch(result, t)
if mismatch then
return false, mismatch
end
end
cvt[i] = t
end
return true, result
end
local success, result = lookup_combo()
if success or err_is_fatal then
return success, result
end
end
-- Accept any unit with an engineering notation prefix like "e6cuft"
-- (million cubic feet), but not chained prefixes like "e3e6cuft",
-- and not if the unit is a combination or multiple,
-- and not if the unit has an offset or is a built-in.
-- Only en digits are accepted.
local exponent, baseunit = unitcode:match('^e(%d+)(.*)')
if exponent then
local engscale = text_code.eng_scales[exponent]
if engscale then
local success, result = lookup(parms, baseunit, 'no_combination', utable, fails, depth)
if success and not (result.offset or result.builtin or result.engscale) then
result.unitcode = unitcode  -- 'e6cuft' not 'cuft'
result.defkey = unitcode  -- key to lookup default exception
result.engscale = engscale
result.scale = result.scale * 10 ^ tonumber(exponent)
return true, result
end
end
end
-- Look for x/y; split on right-most slash to get scale correct (x/y/z is x/y per z).
local top, bottom = unitcode:match('^(.-)/([^/]+)$')
if top and not unitcode:find('e%d') then
-- If valid, create an automatic per unit for an "x/y" unit code.
-- The unitcode must not include extraneous spaces.
-- Engineering notation (apart from at start and which has been stripped before here),
-- is not supported so do not make a per unit if find text like 'e3' in unitcode.
local success, result = call_make_per({ per = {top, bottom} })
if success then
return true, result
end
end
if not parms.opt_ignore_error and not get_range(unitcode) then
-- Want the "what links here" list for the extra_module to show only cases
-- where an extra unit is used, so do not require it if invoked from {{val}}
-- or if looking up a range word which cannot be a unit.
if not extra_units then
local success, extra = pcall(function () return require(extra_module).extra_units end)
if success and type(extra) == 'table' then
extra_units = extra
end
end
if extra_units then
-- A unit in one data table might refer to a unit in the other table, so
-- switch between them, relying on fails or depth to terminate loops.
if not fails[unitcode] then
fails[unitcode] = true
local other = (utable == all_units) and extra_units or all_units
local success, result = lookup(parms, unitcode, what, other, fails, depth)
if success then
return true, result
end
end
end
end
if to_en_table then
-- At fawiki it is common to translate all digits so a unit like "km2" becomes "km۲".
local en_code = ustring.gsub(unitcode, '%d', to_en_table)
if en_code ~= unitcode then
return lookup(parms, en_code, what, utable, fails, depth)
end
end
return false, { 'cvt_unknown', unitcode }
end
end


local function ntsh(num, debug)
local function valid_number(num)
    -- Return html text to be used for a hidden sort key so that
-- Return true if num is a valid number.
    -- the given number will be sorted in numeric order.
-- In Scribunto (different from some standard Lua), when expressed as a string,
    -- If debug == 'yes', output is in a box (not hidden).
-- overflow or other problems are indicated with text like "inf" or "nan"
    -- This implements Template:Ntsh (number table sorting, hidden).
-- which are regarded as invalid here (each contains "n").
    local result, style
if type(num) == 'number' and tostring(num):find('n', 1, true) == nil then
    if not valid_number(num) then
return true
        if num < 0 then
end
            result = '1000000000000000000'
        else
            result = '9000000000000000000'
        end
    elseif num == 0 then
        result = '5000000000000000000'
    else
        local mag = floor(log10(abs(num)) + 1e-14)
        local prefix
        if num > 0 then
            prefix = 7000 + mag
        else
            prefix = 2999 - mag
            num = num + 10^(mag+1)
        end
        result = format('%d', prefix) .. format('%015.0f', floor(num * 10^(14-mag)))
    end
    if debug == 'yes' then
        style = 'border:1px solid'
    else
        style = 'display:none'
    end
    return '<span style="' .. style .. '">' .. result .. '</span>'
end
end


local function hyphenated(name)
local function hyphenated(name, parts)
    -- Return a hyphenated form of given name (for adjectival usage).
-- Return a hyphenated form of given name (for adjectival usage).
    -- This uses a simple and efficient procedure that works for most cases.
-- The name may be linked and the target of the link must not be changed.
    -- Some units (if used) would require more, and can later think about
-- Hypothetical examples:
    -- adding a method to handle exceptions.
--  [[long ton|ton]]        →  [[long ton|ton]]          (no change)
    -- The procedure is to replace each space with a hyphen, but
--  [[tonne|long ton]]      →  [[tonne|long-ton]]
    -- not a space after ')' [for "(pre-1954&nbsp;US) nautical mile"], and
--  [[metric ton|long ton]]  →  [[metric ton|long-ton]]
    -- not spaces immediately before '(' or in '(...)' [for cases like
--  [[long ton]]            →  [[long ton|long-ton]]
    -- "British thermal unit (ISO)" and "Calorie (International Steam Table)"].
-- Input can also have multiple links in a single name like:
    local pos
--  [[United States customary units|U.S.]] [[US gallon|gallon]]
    if name:sub(1, 1) == '(' then
--  [[mile]]s per [[United States customary units|U.S.]] [[quart]]
        pos = name:find(')', 1, true)
--  [[long ton]]s per [[short ton]]
        if pos then
-- Assume that links cannot be nested (never like "[[abc[[def]]ghi]]").
            return name:sub(1, pos+1) .. name:sub(pos+2):gsub(' ', '-')
-- This uses a simple and efficient procedure that works for most cases.
        end
-- Some units (if used) would require more, and can later think about
    elseif name:sub(-1, -1) == ')' then
-- adding a method to handle exceptions.
        pos = name:find('(', 1, true)
-- The procedure is to replace each space with a hyphen, but
        if pos then
-- not a space after ')' [for "(pre-1954&nbsp;US) nautical mile"], and
            return name:sub(1, pos-2):gsub(' ', '-') .. name:sub(pos-1)
-- not spaces immediately before '(' or in '(...)' [for cases like
        end
-- "British thermal unit (ISO)" and "Calorie (International Steam Table)"].
    end
if name:find(' ', 1, true) then
    return name:gsub(' ', '-')
if parts then
local pos
if name:sub(1, 1) == '(' then
pos = name:find(')', 1, true)
if pos then
return name:sub(1, pos+1) .. name:sub(pos+2):gsub(' ', '-')
end
elseif name:sub(-1) == ')' then
pos = name:find('(', 1, true)
if pos then
return name:sub(1, pos-2):gsub(' ', '-') .. name:sub(pos-1)
end
end
return name:gsub(' ', '-')
end
parts = collection()
for before, item, after in name:gmatch('([^[]*)(%[%[[^[]*%]%])([^[]*)') do
if item:find(' ', 1, true) then
local prefix
local plen = item:find('|', 1, true)
if plen then
prefix = item:sub(1, plen)
item = item:sub(plen + 1, -3)
else
prefix = item:sub(1, -3) .. '|'
item = item:sub(3, -3)
end
item = prefix .. hyphenated(item, parts) .. ']]'
end
parts:add(before:gsub(' ', '-') .. item .. after:gsub(' ', '-'))
end
if parts.n == 0 then
-- No link like "[[...]]" was found in the original name.
parts:add(hyphenated(name, parts))
end
return table.concat(parts)
end
return name
end
end


local function hyphenated_maybe(parms, want_name, sep, id, inout)
local function hyphenated_maybe(parms, want_name, sep, id, inout)
    -- Return s, f where
-- Return s, f where
    --  s = id, possibly modified
--  s = id, possibly modified
    --  f = true if hyphenated
--  f = true if hyphenated
    -- Possible modifications: hyphenate; prepend '-'; append mid text.
-- Possible modifications: hyphenate; prepend '-'; append mid text.
    if id == nil or id == '' then
if id == nil or id == '' then
        return ''
return ''
    end
end
    local mid
local mid = (inout == (parms.opt_flip and 'out' or 'in')) and parms.mid or ''
    if parms.opt_adjectival then
if want_name then
        if inout == (parms.opt_flip and 'out' or 'in') then
if parms.opt_adjectival then
            mid = parms.mid
return '-' .. hyphenated(id) .. mid, true
        end
end
        if want_name then
if parms.opt_add_s and id:sub(-1) ~= 's' then
            return '-' .. hyphenated(id) .. (mid or ''), true
id = id .. 's' -- for nowiki
        end
end
    end
end
    return sep .. id .. (mid or '')
return sep .. id .. mid
end
 
local function change_sign(text)
    -- Change sign of text for correct appearance because it is negated.
    if text:sub(1, 1) == '-' then
        return text:sub(2)
    end
    return '-' .. text
end
end


local function use_minus(text)
local function use_minus(text)
    -- Return text with Unicode minus instead of '-', if present.
-- Return text with Unicode minus instead of '-', if present.
    if text:sub(1, 1) == '-' then
if text:sub(1, 1) == '-' then
        return MINUS .. text:sub(2)
return MINUS .. text:sub(2)
    end
end
    return text
return text
end
end


local function digit_grouper(method, gaps)
local function digit_groups(parms, text, method)
    -- Return a table to hold groups of digits which can be joined with
-- Return a numbered table of groups of digits (left-to-right, in local language).
    -- suitable separators (such as commas).
-- Parameter method is a number or nil:
    -- Each group is separately translated to the local language because the
--  3 for 3-digit grouping (default), or
    -- separators may include '.' characters which should not be translated.
--  2 for 3-then-2 grouping (only for digits before decimal mark).
    -- Parameter method is a number or nil:
local len_right
    --  3 for 3-digit grouping, or
local len_left = text:find('.', 1, true)
    --  2 for 3-then-2 grouping.
if len_left then
    -- Parameter gaps is true to use <span> gaps (numsep ignored).
len_right = #text - len_left
    return {
len_left = len_left - 1
        n = 0,
else
        add = function (self, digits)
len_left = #text
            self.n = self.n + 1
end
            self[self.n] = from_en(digits)
local twos = method == 2 and len_left > 5
        end,
local groups = collection()
        join = function (self, rhs)
local run = len_left
            -- Concatenate in reverse order.
local n
            if gaps then
if run < 4 or (run == 4 and parms.opt_comma5) then
                local result = ''
if parms.opt_gaps then
                for i = 1, self.n - 1 do
n = run
                    result = '<span style="margin-left: 0.25em">' .. self[i] .. '</span>' .. result
else
                end
n = #text
                return '<span style="white-space: nowrap">' .. self[self.n] .. result .. from_en(rhs) .. '</span>'
end
            else
elseif twos then
                local result = self[1]
n = run % 2 == 0 and 1 or 2
                for i = 2, self.n do
else
                    result = self[i] .. numsep .. result
n = run % 3 == 0 and 3 or run % 3
                end
end
                return result .. from_en(rhs)
while run > 0 do
            end
groups:add(n)
        end,
run = run - n
        step = 3,
n = (twos and run > 3) and 2 or 3
        next_position = function (self, previous)
end
            -- Return position of digit just before next group.
if len_right then
            -- Digits are grouped from right-to-left (least significant first).
if groups.n == 0 then
            local result = previous - self.step
groups:add(0)
            if method == 2 then
end
                self.step = 2  -- may need more (3, 2, 2, 3, 2, 2, ...) in some languages
if parms.opt_gaps and len_right > 3 then
            end
local want4 = not parms.opt_gaps3  -- true gives no gap before trailing single digit
            return (result < 0) and 0 or result
local isfirst = true
        end,
run = len_right
    }
while run > 0 do
n = (want4 and run == 4) and 4 or (run > 3 and 3 or run)
if isfirst then
isfirst = false
groups[groups.n] = groups[groups.n] + 1 + n
else
groups:add(n)
end
run = run - n
end
else
groups[groups.n] = groups[groups.n] + 1 + len_right
end
end
local pos = 1
for i, length in ipairs(groups) do
groups[i] = from_en(text:sub(pos, pos + length - 1))
pos = pos + length
end
return groups
end
end


local function with_separator(parms, text)
function with_separator(parms, text) -- for forward declaration above
    -- Input text is a number in en digits and with '.' decimal mark.
-- Input text is a number in en digits with optional '.' decimal mark.
    -- Return an equivalent of text, formatted for display:
-- Return an equivalent, formatted for display:
    --  with a custom decimal mark instead of '.', if wanted
--  with a custom decimal mark instead of '.', if wanted
    --  with thousand separators inserted, if wanted
--  with thousand separators inserted, if wanted
    --  digits in local language
--  digits in local language
    -- The given text is like '123' or '12345.6789' or '1.23e45'
-- The given text is like '123' or '123.' or '12345.6789'.
    -- (e notation can only occur when processing an input value).
-- The text has no sign (caller inserts that later, if necessary).
    -- The text has no sign (caller inserts that later, if necessary).
-- When using gaps, they are inserted before and after the decimal mark.
    -- Separator is inserted only in the integer part of the significand
-- Separators are inserted only before the decimal mark.
    -- (not after the decimal mark, and not after 'e' or 'E').
-- A trailing dot (as in '123.') is removed because their use appears to
    if parms.opt_nocomma or numsep == '' then
-- be accidental, and such a number should be shown as '123' or '123.0'.
        return from_en(text)
-- It is useful for convert to suppress the dot so, for example, '4000.'
    end
-- is a simple way of indicating that all the digits are significant.
    local last = text:match('()[.eE]')  -- () returns position
if text:sub(-1) == '.' then
    if last == nil then
text = text:sub(1, -2)
        last = #text
end
    else
if #text < 4 or parms.opt_nocomma or numsep == '' then
        last = last - 1 -- index of last character before dot/e/E
return from_en(text)
    end
end
    if last < 4 or (last == 4 and parms.opt_comma5) then
local groups = digit_groups(parms, text, group_method)
        return from_en(text)
if parms.opt_gaps then
    end
if groups.n <= 1 then
    local groups = digit_grouper(group_method, parms.opt_gaps)
return groups[1] or ''
    local i = last
end
    while i > 0 do
local nowrap = '<span style="white-space: nowrap">'
        local position = groups:next_position(i)
local gap = '<span style="margin-left: 0.25em">'
        groups:add(text:sub(position+1, i))
local close = '</span>'
        i = position
return nowrap .. groups[1] .. gap .. table.concat(groups, close .. gap, 2, groups.n) .. close .. close
    end
end
    return groups:join(text:sub(last+1))
return table.concat(groups, numsep)
end
end


-- Input values can use values like 1.23e12, but are never displayed
-- An input value like 1.23e12 is displayed using scientific notation (1.23×10¹²).
-- using scientific notation like 1.23×10¹².
-- That also makes the output use scientific notation, except for small values.
-- Very small or very large output values use scientific notation.
-- In addition, very small or very large output values use scientific notation.
-- Use format(fmtpower, significand, '10', exponent) where each arg is a string.
-- Use format(fmtpower, significand, '10', exponent) where each argument is a string.
local fmtpower = '%s<span style="margin:0 .15em 0 .25em">×</span>%s<sup>%s</sup>'
local fmtpower = '%s<span style="margin:0 .15em 0 .25em">×</span>%s<sup>%s</sup>'


local function with_exponent(show, exponent)
local function with_exponent(parms, show, exponent)
    -- Return wikitext to display the implied value in scientific notation.
-- Return wikitext to display the implied value in scientific notation.
    -- Input uses en digits; output uses digits in local language.
-- Input uses en digits; output uses digits in local language.
    if #show > 1 then
return format(fmtpower, with_separator(parms, show), from_en('10'), use_minus(from_en(tostring(exponent))))
        show = show:sub(1, 1) .. '.' .. show:sub(2)
    end
    return format(fmtpower, from_en(show), from_en('10'), use_minus(from_en(tostring(exponent))))
end
end


local function make_sigfig(value, sigfig)
local function make_sigfig(value, sigfig)
    -- Return show, exponent that are equivalent to the result of
-- Return show, exponent that are equivalent to the result of
    -- converting the number 'value' (where value >= 0) to a string,
-- converting the number 'value' (where value >= 0) to a string,
    -- rounded to 'sigfig' significant figures.
-- rounded to 'sigfig' significant figures.
    -- The returned items are:
-- The returned items are:
    --  show: a string of digits; no sign and no dot;
--  show: a string of digits; no sign and no dot;
    --        there is an implied dot before show.
--        there is an implied dot before show.
    --  exponent: a number (an integer) to shift the implied dot.
--  exponent: a number (an integer) to shift the implied dot.
    -- Resulting value = tonumber('.' .. show) * 10^exponent.
-- Resulting value = tonumber('.' .. show) * 10^exponent.
    -- Examples:
-- Examples:
    --  make_sigfig(23.456, 3) returns '235', 2 (.235 * 10^2).
--  make_sigfig(23.456, 3) returns '235', 2 (.235 * 10^2).
    --  make_sigfig(0.0023456, 3) returns '235', -2 (.235 * 10^-2).
--  make_sigfig(0.0023456, 3) returns '235', -2 (.235 * 10^-2).
    --  make_sigfig(0, 3) returns '000', 1 (.000 * 10^1).
--  make_sigfig(0, 3) returns '000', 1 (.000 * 10^1).
    if sigfig <= 0 then
if sigfig <= 0 then
        sigfig = 1
sigfig = 1
    elseif sigfig > maxsigfig then
elseif sigfig > maxsigfig then
        sigfig = maxsigfig
sigfig = maxsigfig
    end
end
    if value == 0 then
if value == 0 then
        return string.rep('0', sigfig), 1
return string.rep('0', sigfig), 1
    end
end
    local exp, frac = math.modf(log10(value))
local exp, fracpart = math.modf(log10(value))
    if frac >= 0 then
if fracpart >= 0 then
        frac = frac - 1
fracpart = fracpart - 1
        exp = exp + 1
exp = exp + 1
    end
end
    local digits = format('%.0f', 10^(frac + sigfig))
local digits = format('%.0f', 10^(fracpart + sigfig))
    if #digits > sigfig then
if #digits > sigfig then
        -- Overflow (for sigfig=3: like 0.9999 rounding to "1000"; need "100").
-- Overflow (for sigfig=3: like 0.9999 rounding to "1000"; need "100").
        digits = digits:sub(1, sigfig)
digits = digits:sub(1, sigfig)
        exp = exp + 1
exp = exp + 1
    end
end
    assert(#digits == sigfig, 'Bug: rounded number has wrong length')
assert(#digits == sigfig, 'Bug: rounded number has wrong length')
    return digits, exp
return digits, exp
end
 
-- Fraction output format.
local fracfmt = {
{ -- Like {{frac}} (fraction slash).
'<span class="frac" role="math">{SIGN}<span class="num">{NUM}</span>&frasl;<span class="den">{DEN}</span></span>',  -- 1/2
'<span class="frac" role="math">{SIGN}{WHOLE}<span class="sr-only">+</span><span class="num">{NUM}</span>&frasl;<span class="den">{DEN}</span></span>',  -- 1+2/3
style = 'frac',
},
{ -- Like {{sfrac}} (stacked fraction, that is, horizontal bar).
'<span class="sfrac tion" role="math">{SIGN}<span class="num">{NUM}</span><span class="sr-only">/</span><span class="den">{DEN}</span></span>',  -- 1//2
'<span class="sfrac" role="math">{SIGN}{WHOLE}<span class="sr-only">+</span><span class="tion"><span class="num">{NUM}</span><span class="sr-only">/</span><span class="den">{DEN}</span></span></span>',  -- 1+2//3
style = 'sfrac',
},
}
 
local function format_fraction(parms, inout, negative, wholestr, numstr, denstr, do_spell, style)
-- Return wikitext for a fraction, possibly spelled.
-- Inputs use en digits and have no sign; output uses digits in local language.
local wikitext
if not style then
style = parms.opt_fraction_horizontal and 2 or 1
end
if wholestr == '' then
wholestr = nil
end
local substitute = {
SIGN = negative and MINUS or '',
WHOLE = wholestr and with_separator(parms, wholestr),
NUM = from_en(numstr),
DEN = from_en(denstr),
}
wikitext = fracfmt[style][wholestr and 2 or 1]:gsub('{(%u+)}', substitute)
if do_spell then
if negative then
if wholestr then
wholestr = '-' .. wholestr
else
numstr = '-' .. numstr
end
end
local s = spell_number(parms, inout, wholestr, numstr, denstr)
if s then
return s
end
end
add_style(parms, fracfmt[style].style)
return wikitext
end
end


local function format_number(parms, show, exponent, isnegative)
local function format_number(parms, show, exponent, isnegative)
    -- Input show is a number in en digits and with '.' decimal mark.
-- Parameter show is a string or a table containing strings.
    -- Return t where t is a table with fields:
-- Each string is a formatted number in en digits and optional '.' decimal mark.
    --  show = wikitext formatted to display implied value
-- A table represents a fraction: integer, numerator, denominator;
    --          (digits in local language)
-- if a table is given, exponent must be nil.
    --  is_scientific = true if show uses scientific notation
-- Return t where t is a table with fields:
    --  clean = unformatted show (possibly adjusted and with inserted '.')
--  show = wikitext formatted to display implied value
    --          (en digits)
--          (digits in local language)
    --  sign = '' or MINUS
--  is_scientific = true if show uses scientific notation
    --  exponent = exponent (possibly adjusted)
--  clean = unformatted show (possibly adjusted and with inserted '.')
    -- The clean and exponent fields can be used to calculate the
--          (en digits)
    -- rounded absolute value, if needed.
--  sign = '' or MINUS
    --
--  exponent = exponent (possibly adjusted)
    -- The value implied by the arguments is found from:
-- The clean and exponent fields can be used to calculate the
    --  exponent is nil; and
-- rounded absolute value, if needed.
    --  show is a string of digits (no sign), with an optional dot;
--
    --  show = '123.4' is value 123.4, '1234' is value 1234.0;
-- The value implied by the arguments is found from:
    -- or:
--  exponent is nil; and
    --  exponent is an integer indicating where dot should be;
--  show is a string of digits (no sign), with an optional dot;
    --  show is a string of digits (no sign and no dot);
--  show = '123.4' is value 123.4, '1234' is value 1234.0;
    --  there is an implied dot before show;
-- or:
    --  show does not start with '0';
--  exponent is an integer indicating where dot should be;
    --  show = '1234', exponent = 3 is value 0.1234*10^3 = 123.4.
--  show is a string of digits (no sign and no dot);
    --
--  there is an implied dot before show;
    -- The formatted result:
--  show does not start with '0';
    -- * Includes a Unicode minus if isnegative.
--  show = '1234', exponent = 3 is value 0.1234*10^3 = 123.4.
    -- * Uses a custom decimal mark, if wanted.
--
    -- * Has digits grouped where necessary, if wanted.
-- The formatted result:
    -- * Uses scientific notation for very small or large values.
-- * Is for an output value and is spelled if wanted and possible.
    -- * Has no more than maxsigfig significant digits
-- * Includes a Unicode minus if isnegative and not spelled.
    --  (same as old template and {{#expr}}).
-- * Uses a custom decimal mark, if wanted.
    local sign = isnegative and MINUS or ''
-- * Has digits grouped where necessary, if wanted.
    local maxlen = maxsigfig
-- * Uses scientific notation if requested, or for very small or large values
    if exponent == nil then
--  (which forces result to not be spelled).
        local integer, dot, fraction = show:match('^(%d*)(%.?)(.*)')
-- * Has no more than maxsigfig significant digits
        if #integer >= 10 then
--  (same as old template and {{#expr}}).
            show = integer .. fraction
local xhi, xlo  -- these control when scientific notation (exponent) is used
            exponent = #integer
if parms.opt_scientific then
        elseif integer == '0' or integer == '' then
xhi, xlo = 4, 2  -- default for output if input uses e-notation
            local zeros, figs = fraction:match('^(0*)([^0]?.*)')
elseif parms.opt_scientific_always then
            if #figs == 0 then
xhi, xlo = 0, 0  -- always use scientific notation (experimental)
                if #zeros > maxlen then
else
                    show = '0.' .. zeros:sub(1, maxlen)
xhi, xlo = 10, 4  -- default
                end
end
            elseif #zeros >= 4 then
local sign = isnegative and MINUS or ''
                show = figs
local maxlen = maxsigfig
                exponent = -#zeros
local tfrac
            elseif #figs > maxlen then
if type(show) == 'table' then
                show = '0.' .. zeros .. figs:sub(1, maxlen)
tfrac = show
            end
show = tfrac.wholestr
        else
assert(exponent == nil, 'Bug: exponent given with fraction')
            maxlen = maxlen + #dot
end
            if #show > maxlen then
if not tfrac and not exponent then
                show = show:sub(1, maxlen)
local integer, dot, decimals = show:match('^(%d*)(%.?)(.*)')
            end
if integer == '0' or integer == '' then
        end
local zeros, figs = decimals:match('^(0*)([^0]?.*)')
    end
if #figs == 0 then
    if exponent then
if #zeros > maxlen then
        if #show > maxlen then
show = '0.' .. zeros:sub(1, maxlen)
            show = show:sub(1, maxlen)
end
        end
elseif #zeros >= xlo then
        if exponent > 10 or exponent <= -4 or (exponent == 10 and show ~= '1000000000') then
show = figs
            -- Rounded value satisfies: value >= 1e9 or value < 1e-4 (1e9 = 0.1e10).
exponent = -#zeros
            return {
elseif #figs > maxlen then
                clean = '.' .. show,
show = '0.' .. zeros .. figs:sub(1, maxlen)
                exponent = exponent,
end
                sign = sign,
elseif #integer >= xhi then
                show = sign .. with_exponent(show, exponent-1),
show = integer .. decimals
                is_scientific = true }
exponent = #integer
        end
else
        if exponent >= #show then
maxlen = maxlen + #dot
            show = show .. string.rep('0', exponent - #show)  -- result has no dot
if #show > maxlen then
        elseif exponent <= 0 then
show = show:sub(1, maxlen)
            show = '0.' .. string.rep('0', -exponent) .. show
end
        else
end
            show = show:sub(1, exponent) .. '.' .. show:sub(exponent+1)
end
        end
if exponent then
    end
local function zeros(n)
    if isnegative and show:match('^0.?0*$') then
return string.rep('0', n)
        sign = ''  -- don't show minus if result is negative but rounds to zero
end
    end
if #show > maxlen then
    return {
show = show:sub(1, maxlen)
        clean = show,
end
        sign = sign,
if exponent > xhi or exponent <= -xlo or (exponent == xhi and show ~= '1' .. zeros(xhi - 1)) then
        show = sign .. with_separator(parms, show) }
-- When xhi, xlo = 10, 4 (the default), scientific notation is used if the
-- rounded value satisfies: value >= 1e9 or value < 1e-4 (1e9 = 0.1e10),
-- except if show is '1000000000' (1e9), for example:
-- {{convert|1000000000|m|m|sigfig=10}} → 1,000,000,000 metres (1,000,000,000 m)
local significand
if #show > 1 then
significand = show:sub(1, 1) .. '.' .. show:sub(2)
else
significand = show
end
return {
clean = '.' .. show,
exponent = exponent,
sign = sign,
show = sign .. with_exponent(parms, significand, exponent-1),
is_scientific = true,
}
end
if exponent >= #show then
show = show .. zeros(exponent - #show)  -- result has no dot
elseif exponent <= 0 then
show = '0.' .. zeros(-exponent) .. show
else
show = show:sub(1, exponent) .. '.' .. show:sub(exponent+1)
end
end
local formatted_show
if tfrac then
show = tostring(tfrac.value)  -- to set clean in returned table
formatted_show = format_fraction(parms, 'out', isnegative, tfrac.wholestr, tfrac.numstr, tfrac.denstr, parms.opt_spell_out)
else
if isnegative and show:match('^0.?0*$') then
sign = ''  -- don't show minus if result is negative but rounds to zero
end
formatted_show = sign .. with_separator(parms, show)
if parms.opt_spell_out then
formatted_show = spell_number(parms, 'out', sign .. show) or formatted_show
end
end
return {
clean = show,
sign = sign,
show = formatted_show,
is_scientific = false, -- to avoid calling __index
}
end
end


-- Fraction output format (like old template).
local function extract_fraction(parms, text, negative)
-- frac1: sign, numerator, denominator
-- If text represents a fraction, return
-- frac2: wholenumber, sign, numerator, denominator
--  value, altvalue, show, denominator
local frac1 = '<span style="white-space:nowrap">%s<sup>%s</sup>&frasl;<sub>%s</sub></span>'
-- where
local frac2 = '<span class="frac nowrap">%s<s style="display:none">%s</s><sup>%s</sup>&frasl;<sub>%s</sub></span>'
--  value is a number (value of the fraction in argument text)
--  altvalue is an alternate interpretation of any fraction for the hands
--        unit where "12.1+3/4" means 12 hands 1.75 inches
--  show is a string (formatted text for display of an input value,
--        and is spelled if wanted and possible)
--   denominator is value of the denominator in the fraction
-- Otherwise, return nil.
-- Input uses en digits and '.' decimal mark (input has been translated).
-- Output uses digits in local language and local decimal mark, if any.
------------------------------------------------------------------------
-- Originally this function accepted x+y/z where x, y, z were any valid
-- numbers, possibly with a sign. For example '1.23e+2+1.2/2.4' = 123.5,
-- and '2-3/8' = 1.625. However, such usages were found to be errors or
-- misunderstandings, so since August 2014 the following restrictions apply:
--  x (if present) is an integer or has a single digit after decimal mark
--  y and z are unsigned integers
--  e-notation is not accepted
-- The overall number can start with '+' or '-' (so '12+3/4' and '+12+3/4'
-- and '-12-3/4' are valid).
-- Any leading negative sign is removed by the caller, so only inputs
-- like the following are accepted here (may have whitespace):
--  negative = false      false        true (there was a leading '-')
--  text    = '2/3'      '+2/3'      '2/3'
--  text    = '1+2/3'    '+1+2/3'    '1-2/3'
--  text    = '12.3+1/2'  '+12.3+1/2'  '12.3-1/2'
-- Values like '12.3+1/2' are accepted, but are intended only for use
-- with the hands unit (not worth adding code to enforce that).
------------------------------------------------------------------------
local leading_plus, prefix, numstr, slashes, denstr =
text:match('^%s*(%+?)%s*(.-)%s*(%d+)%s*(/+)%s*(%d+)%s*$')
if not leading_plus then
-- Accept a single U+2044 fraction slash because that may be pasted.
leading_plus, prefix, numstr, denstr =
text:match('^%s*(%+?)%s*(.-)%s*(%d+)%s*⁄%s*(%d+)%s*$')
slashes = '/'
end
local numerator = tonumber(numstr)
local denominator = tonumber(denstr)
if numerator == nil or denominator == nil or (negative and leading_plus ~= '') then
return nil
end
local whole, wholestr
if prefix == '' then
wholestr = ''
whole = 0
else
-- Any prefix must be like '12+' or '12-' (whole number and fraction sign);
-- '12.3+' and '12.3-' are also accepted (single digit after decimal point)
-- because '12.3+1/2 hands' is valid (12 hands 3½ inches).
local num1, num2, frac_sign = prefix:match('^(%d+)(%.?%d?)%s*([+%-])$')
if num1 == nil then return nil end
if num2 == '' then  -- num2 must be '' or like '.1' but not '.' or '.12'
wholestr = num1
else
if #num2 ~= 2 then return nil end
wholestr = num1 .. num2
end
if frac_sign ~= (negative and '-' or '+') then return nil end
whole = tonumber(wholestr)
if whole == nil then return nil end
end
local value = whole + numerator / denominator
if not valid_number(value) then return nil end
local altvalue = whole + numerator / (denominator * 10)
local style = #slashes  -- kludge: 1 or 2 slashes can be used to select style
if style > 2 then style = 2 end
local wikitext = format_fraction(parms, 'in', negative, leading_plus .. wholestr, numstr, denstr, parms.opt_spell_in, style)
return value, altvalue, wikitext, denominator
end


local function extract_fraction(text, negative)
local function extract_number(parms, text, another, no_fraction)
    -- If text represents a fraction, return value, show where
-- Return true, info if can extract a number from text,
    -- value is a number and show is a string.
-- where info is a table with the result,
    -- Otherwise, return nil.
-- or return false, t where t is an error message table.
    -- Input uses en digits and '.' decimal mark (input has been translated).
-- Input can use en digits or digits in local language and can
    -- Output uses digits in local language and custom decimal mark, if any.
-- have references at the end. Accepting references is intended
    --
-- for use in infoboxes with a field for a value passed to convert.
    -- In the following, '(3/8)' represents the wikitext required to
-- Parameter another = true if the expected value is not the first.
    -- display a fraction with numerator 3 and denominator 8.
-- Before processing, the input text is cleaned:
    -- In the wikitext, Unicode minus is used for a negative value.
-- * Any thousand separators (valid or not) are removed.
    --   text         value, show            value, show
-- * Any sign is replaced with '-' (if negative) or '' (otherwise).
    --                 if not negative      if negative
--  That replaces Unicode minus with '-'.
    --   3 / 8        0.375, '(3/8)'       -0.375, '(3/8)'
-- If successful, the returned info table contains named fields:
    --  2 + 3 / 8    2.375, '2(3/8)'       -1.625, '−2(−3/8)'
--  value    = a valid number
    --  2 - 3 / 8    1.625, '2(−3/8)'      -2.375, '−2(3/8)'
--   altvalue = a valid number, usually same as value but different
    --  1 + 20/8      3.5  , '1/(20/8)'     1.5  , '−1/(−20/8)'
--             if fraction used (for hands unit)
    --  1 - 20/8      -1.5., '1(−20/8)'    -3., '−1(20/8)'
--  singular = true if value is 1 or -1 (to use singular form of units)
    -- Wherever an integer appears above, numbers like 1.25 or 12.5e-3
--  clean    = cleaned text with any separators and sign removed
    -- (which may be negative) are also accepted (like old template).
--              (en digits and '.' decimal mark)
    -- Template interprets '1.23e+2+12/24' as '123(12/24)' = 123.5!
--  show    = text formatted for output, possibly with ref strip markers
    local lhs, negfrac, rhs, numstr, numerator, denstr, denominator, wholestr, whole, value
--             (digits in local language and custom decimal mark)
    lhs, denstr = text:match('^%s*([^/]-)%s*/%s*(.-)%s*$')
-- The resulting show:
    denominator = tonumber(denstr)
-- * Is for an input value and is spelled if wanted and possible.
    if denominator == nil then return nil end
-- * Has a rounded value, if wanted.
    wholestr, negfrac, rhs = lhs:match('^%s*(.-[^eE])%s*([+-])%s*(.-)%s*$')
-- * Has digits grouped where necessary, if wanted.
    if wholestr == nil or wholestr == '' then
-- * If negative, a Unicode minus is used; otherwise the sign is
        wholestr = nil
--   '+' (if the input text used '+'), or is '' (if no sign in input).
        whole = 0
text = strip(text or '')
        numstr = lhs
local reference
    else
local pos = text:find('\127', 1, true)
        whole = tonumber(wholestr)
if pos then
        if whole == nil then return nil end
local before = text:sub(1, pos - 1)
        numstr = rhs
local remainder = text:sub(pos)
    end
local refs = {}
    negfrac = (negfrac == '-')
while #remainder > 0 do
    numerator = tonumber(numstr)
local ref, spaces
    if numerator == nil then return nil end
ref, spaces, remainder = remainder:match('^(\127[^\127]*UNIQ[^\127]*%-ref[^\127]*\127)(%s*)(.*)')
    if negative == negfrac or wholestr == nil then
if ref then
        value = whole + numerator / denominator
table.insert(refs, ref)
    else
else
        value = whole - numerator / denominator
refs = {}
        numstr = change_sign(numstr)
break
    end
end
    if not valid_number(value) then
end
        return nil -- overflow or similar
if #refs > 0 then
    end
text = strip(before)
    numstr = use_minus(numstr)
reference = table.concat(refs)
    denstr = use_minus(denstr)
end
    local wikitext
end
    if wholestr then
local clean = to_en(text, parms)
        local sign = negative and MINUS or '+'
if clean == '' then
        if negative then
return false, { another and 'cvt_no_num2' or 'cvt_no_num' }
            wholestr = change_sign(wholestr)
end
        end
local isnegative, propersign = false, ''  -- most common case
        wikitext = format(frac2, use_minus(from_en(wholestr)), sign, from_en(numstr), from_en(denstr))
local singular, show, denominator
    else
local value = tonumber(clean)
        local sign = negative and MINUS or ''
local altvalue
        wikitext = format(frac1, sign, from_en(numstr), from_en(denstr))
if value then
    end
local sign = clean:sub(1, 1)
    return value, wikitext
if sign == '+' or sign == '-' then
propersign = (sign == '+') and '+' or MINUS
clean = clean:sub(2)
end
if value < 0 then
isnegative = true
value = -value
end
else
local valstr
for _, prefix in ipairs({ '-', MINUS, '&minus;' }) do
-- Including '-' sets isnegative in case input is a fraction like '-2-3/4'.
local plen = #prefix
if clean:sub(1, plen) == prefix then
valstr = clean:sub(plen + 1)
if valstr:match('^%s') then -- "- 1" is invalid but "-1 - 1/2" is ok
return false, { 'cvt_bad_num', text }
end
break
end
end
if valstr then
isnegative = true
propersign = MINUS
clean = valstr
value = tonumber(clean)
end
if value == nil then
if not no_fraction then
value, altvalue, show, denominator = extract_fraction(parms, clean, isnegative)
end
if value == nil then
return false, { 'cvt_bad_num', text }
end
if value <= 1 then
singular = true  -- for example, "½ mile" or "one half mile" (singular unit)
end
end
end
if not valid_number(value) then  -- for example, "1e310" may overflow
return false, { 'cvt_invalid_num' }
end
if show == nil then
-- clean is a non-empty string with no spaces, and does not represent a fraction,
-- and value = tonumber(clean) is a number >= 0.
-- If the input uses e-notation, show will be displayed using a power of ten, but
-- we use the number as given so it might not be normalized scientific notation.
-- The input value is spelled if specified so any e-notation is ignored;
-- that allows input like 2e6 to be spelled as "two million" which works
-- because the spell module converts '2e6' to '2000000' before spelling.
local function rounded(value, default, exponent)
local precision = parms.opt_ri
if precision then
local fmt = '%.' .. format('%d', precision) .. 'f'
local result = fmt:format(tonumber(value) + 2e-14)  -- fudge for some common cases of bad rounding
if not exponent then
singular = (tonumber(result) == 1)
end
return result
end
return default
end
singular = (value == 1)
local scientific
local significand, exponent = clean:match('^([%d.]+)[Ee]([+%-]?%d+)')
if significand then
show = with_exponent(parms, rounded(significand, significand, exponent), exponent)
scientific = true
else
show = with_separator(parms, rounded(value, clean))
end
show = propersign .. show
if parms.opt_spell_in then
show = spell_number(parms, 'in', propersign .. rounded(value, clean)) or show
scientific = false
end
if scientific then
parms.opt_scientific = true
end
end
if isnegative and (value ~= 0) then
value = -value
altvalue = -(altvalue or value)
end
return true, {
value = value,
altvalue = altvalue or value,
singular = singular,
clean = clean,
show = show .. (reference or ''),
denominator = denominator,
}
end
end


local missing = { 'cvt_no_num', 'cvt_no_num2' }
local function get_number(text)
local invalid = { 'cvt_bad_num', 'cvt_bad_num2' }
-- Return v, f where:
--  v = nil (text is not a number)
-- or
--  v = value of text (text is a number)
--  f = true if value is an integer
-- Input can use en digits or digits in local language,
-- but no separators, no Unicode minus, and no fraction.
if text then
local number = tonumber(to_en(text))
if number then
local _, fracpart = math.modf(number)
return number, (fracpart == 0)
end
end
end


local function extract_number(parms, text, which, no_fraction)
local function gcd(a, b)
    -- Return true, info if can extract a number from text,
-- Return the greatest common denominator for the given values,
    -- where info is a table with the result,
-- which are known to be positive integers.
    -- or return false, t where t is an error message table.
if a > b then
    -- Input can use en digits or digits in local language.
a, b = b, a
    -- Parameter 'which' (1 or 2) selects which input value is being
end
    -- processed (to select the appropriate error message, if needed).
if a <= 0 then
    -- Before processing, the input text is cleaned:
return b
    -- * Any thousand separators (valid or not) are removed.
end
    -- * Any sign (and optional following whitespace) is replaced with
local r = b % a
    --  '-' (if negative) or '' (otherwise).
if r <= 0 then
    --  That replaces Unicode minus with '-'.
return a
    -- If successful, the returned info table contains named fields:
end
    --  value    = a valid number
if r == 1 then
    --  singular = true if value is 1 (to use singular form of units)
return 1
    --            = false if value is -1 (like old template)
end
    --  clean    = cleaned text with any separators and sign removed
return gcd(r, a)
    --              (en digits and '.' decimal mark)
    --  show    = text formatted for output
    --              (digits in local language and custom decimal mark)
    -- For show:
    -- * Value is rounded, if wanted.
    -- * Thousand separators are inserted, if wanted.
    -- * If negative, a Unicode minus is used; otherwise the sign is
    --  '+' (if the input text used '+'), or is '' (if no sign in input).
    text = strip(text or '')
    local clean = to_en(text)
    if clean == '' then
        return false, { missing[which] }
    end
    local isnegative, propersign = false, ''  -- most common case
    local singular, show
    local value = tonumber(clean)
    if value then
        local sign = clean:sub(1, 1)
        if sign == '+' or sign == '-' then
            propersign = (sign == '+') and '+' or MINUS
            clean = clean:sub(2)
        end
        if value < 0 then
            isnegative = true
            value = -value
        end
    else
        local valstr
        for _, prefix in ipairs({ '-', MINUS, '&minus;' }) do
            -- Including '-' means inputs like '- 2' (with space) are accepted as -2.
            -- It also sets isnegative in case input is a fraction like '-2-3/4'.
            local plen = #prefix
            if clean:sub(1, plen) == prefix then
                valstr = clean:sub(plen + 1)
                break
            end
        end
        if valstr then
            isnegative = true
            propersign = MINUS
            clean = valstr
            value = tonumber(clean)
        end
        if value == nil then
            if not no_fraction then
                value, show = extract_fraction(clean, isnegative)
            end
            if value == nil then
                return false, { invalid[which], text }
            end
            singular = false  -- any fraction (even with value 1) is regarded as plural
        end
    end
    if not valid_number(value) then  -- for example, "1e310" overflows
        return false, { 'cvt_invalid_num' }
    end
    if show == nil then
        singular = (value == 1 and not isnegative)
        local precision = parms.input_precision
        if precision and 0 <= precision and precision <= 8 then
            value = value + 2e-14  -- fudge for some common cases of bad rounding
            local fmt = '%.' .. format('%d', precision) .. 'f'
            show = fmt:format(value)
        else
            show = clean
        end
        show = propersign .. with_separator(parms, show)
    end
    if isnegative and (value ~= 0) then
        value = -value
    end
    return true, {
        value = value,
        singular = singular,
        clean = clean,
        show = show
    }
end
end


local function get_number(text)
local function fraction_table(value, denominator)
    -- Return v, f where:
-- Return value as a string or a table:
    --  v = nil (text is not a number)
-- * If result is a string, there is no fraction, and the result
    -- or
--  is value formatted as a string of en digits.
    --  v = value of text (text is a number)
-- * If result is a table, it represents a fraction with named fields:
    --   f = true if value is an integer
--  wholestr, numstr, denstr (strings of en digits for integer, numerator, denominator).
    -- Input can use en digits or digits in local language,
-- The result is rounded to the nearest multiple of (1/denominator).
    -- but no separators, no Unicode minus, and no fraction.
-- If the multiple is zero, no fraction is included.
    if text then
-- No fraction is included if value is very large as the fraction would
        local number = tonumber(to_en(text))
-- be unhelpful, particularly if scientific notation is required.
        if number then
-- Input value is a non-negative number.
            local integer, fraction = math.modf(number)
-- Input denominator is a positive integer for the desired fraction.
            return number, (fraction == 0)
if value <= 0 then
        end
return '0'
    end
end
if denominator <= 0 or value > 1e8 then
return format('%.2f', value)
end
local integer, decimals = math.modf(value)
local numerator = floor((decimals * denominator) +
0.5 + 2e-14) -- add fudge for some common cases of bad rounding
if numerator >= denominator then
integer = integer + 1
numerator = 0
end
local wholestr = tostring(integer)
if numerator > 0 then
local div = gcd(numerator, denominator)
if div > 1 then
numerator = numerator / div
denominator = denominator / div
end
return {
wholestr = (integer > 0) and wholestr or '',
numstr = tostring(numerator),
denstr = tostring(denominator),
value = value,
}
end
return wholestr
end
end


local function preunits(count, preunit1, preunit2)
local function preunits(count, preunit1, preunit2)
    -- If count is 1:
-- If count is 1:
    --    ignore preunit2
--    ignore preunit2
    --    return p1
--    return p1
    -- else:
-- else:
    --    preunit1 is used for preunit2 if the latter is empty
--    preunit1 is used for preunit2 if the latter is empty
    --    return p1, p2
--    return p1, p2
    -- where:
-- where:
    --    p1 is text to insert before the input unit
--    p1 is text to insert before the input unit
    --    p2 is text to insert before the output unit
--    p2 is text to insert before the output unit
    --    p1 or p2 may be nil to mean "no preunit"
--    p1 or p2 may be nil to mean "no preunit"
    -- Using '+ ' gives output like "5+ feet" (no preceding space).
-- Using '+' gives output like "5+ feet" (no space before, but space after).
    local function withspace(text, i)
local function withspace(text, wantboth)
        -- Insert space at beginning if i == 1, or at end if i == -1.
-- Return text with space before and, if wantboth, after.
        -- However, no space is inserted if there is a space or '&nbsp;'
-- However, no space is added if there is a space or '&nbsp;' or '-'
        -- or '-' at that position ('-' is for adjectival text).
-- at that position ('-' is for adjectival text).
        local current = text:sub(i, i)
-- There is also no space if text starts with '&'
        if current == ' ' or current == '-' then
-- (e.g. '&deg;' would display a degree symbol with no preceding space).
            return text
local char = text:sub(1, 1)
        end
if char == '&' then
        if i == 1 then
return text  -- an html entity can be used to specify the exact display
            current = text:sub(1, 6)
end
        else
if not (char == ' ' or char == '-' or char == '+') then
            current = text:sub(-6, -1)
text = ' ' .. text
        end
end
        if current == '&nbsp;' then
if wantboth then
            return text
char = text:sub(-1, -1)
        end
if not (char == ' ' or char == '-' or text:sub(-6, -1) == '&nbsp;') then
        if i == 1 then
text = text .. ' '
            return ' ' .. text
end
        end
end
        return text .. ' '
return text
    end
end
    preunit1 = preunit1 or ''
local PLUS = '+ '
    local trim1 = strip(preunit1)
preunit1 = preunit1 or ''
    if count == 1 then
local trim1 = strip(preunit1)
        if trim1 == '' then
if count == 1 then
            return nil
if trim1 == '' then
        end
return nil
        return withspace(withspace(preunit1, 1), -1)
end
    end
if trim1 == '+' then
    preunit2 = preunit2 or ''
return PLUS
    local trim2 = strip(preunit2)
end
    if trim1 == '' and trim2 == '' then
return withspace(preunit1, true)
        return nil, nil
end
    end
preunit1 = withspace(preunit1)
    if trim1 ~= '+' then
preunit2 = preunit2 or ''
        preunit1 = withspace(preunit1, 1)
local trim2 = strip(preunit2)
    end
if trim1 == '+' then
    if trim2 == '&#32;' then  -- trick to make preunit2 empty
if trim2 == '' or trim2 == '+' then
        preunit2 = nil
return PLUS, PLUS
    elseif trim2 == '' then
end
        preunit2 = preunit1
preunit1 = PLUS
    elseif trim2 ~= '+' then
end
        preunit2 = withspace(preunit2, 1)
if trim2 == '' then
    end
if trim1 == '' then
    return preunit1, preunit2
return nil, nil
end
preunit2 = preunit1
elseif trim2 == '+' then
preunit2 = PLUS
elseif trim2 == '&#32;' then  -- trick to make preunit2 empty
preunit2 = nil
else
preunit2 = withspace(preunit2)
end
return preunit1, preunit2
end
 
local function range_text(range, want_name, parms, before, after, inout)
-- Return before .. rtext .. after
-- where rtext is the text that separates two values in a range.
local rtext, adj_text, exception
if type(range) == 'table' then
-- Table must specify range text for ('off' and 'on') or ('input' and 'output'),
-- and may specify range text for 'adj=on',
-- and may specify exception = true.
rtext = range[want_name and 'off' or 'on'] or
range[((inout == 'in') == (parms.opt_flip == true)) and 'output' or 'input']
adj_text = range['adj']
exception = range['exception']
else
rtext = range
end
if parms.opt_adjectival then
if want_name or (exception and parms.abbr_org == 'on') then
rtext = adj_text or rtext:gsub(' ', '-'):gsub('&nbsp;', '-')
end
end
if rtext == '–' and after:sub(1, #MINUS) == MINUS then
rtext = '&nbsp;– '
end
return before .. rtext .. after
end
 
local function get_composite(parms, iparm, in_unit_table)
-- Look for a composite input unit. For example, {{convert|1|yd|2|ft|3|in}}
-- would result in a call to this function with
--  iparm = 3 (parms[iparm] = "2", just after the first unit)
--  in_unit_table = (unit table for "yd"; contains value 1 for number of yards)
-- Return true, iparm, unit where
--  iparm = index just after the composite units (7 in above example)
--  unit = composite unit table holding all input units,
-- or return true if no composite unit is present in parms,
-- or return false, t where t is an error message table.
local default, subinfo
local composite_units, count = { in_unit_table }, 1
local fixups = {}
local total = in_unit_table.valinfo[1].value
local subunit = in_unit_table
while subunit.subdivs do  -- subdivs is nil or a table of allowed subdivisions
local subcode = strip(parms[iparm+1])
local subdiv = subunit.subdivs[subcode] or subunit.subdivs[(all_units[subcode] or {}).target]
if not subdiv then
break
end
local success
success, subunit = lookup(parms, subcode, 'no_combination')
if not success then return false, subunit end  -- should never occur
success, subinfo = extract_number(parms, parms[iparm])
if not success then return false, subinfo end
iparm = iparm + 2
subunit.inout = 'in'
subunit.valinfo = { subinfo }
-- Recalculate total as a number of subdivisions.
-- subdiv[1] = number of subdivisions per previous unit (integer > 1).
total = total * subdiv[1] + subinfo.value
if not default then  -- set by the first subdiv with a default defined
default = subdiv.default
end
count = count + 1
composite_units[count] = subunit
if subdiv.unit or subdiv.name then
fixups[count] = { unit = subdiv.unit, name = subdiv.name, valinfo = subunit.valinfo }
end
end
if count == 1 then
return true  -- no error and no composite unit
end
for i, fixup in pairs(fixups) do
local unit = fixup.unit
local name = fixup.name
if not unit or (count > 2 and name) then
composite_units[i].fixed_name = name
else
local success, alternate = lookup(parms, unit, 'no_combination')
if not success then return false, alternate end  -- should never occur
alternate.inout = 'in'
alternate.valinfo = fixup.valinfo
composite_units[i] = alternate
end
end
return true, iparm, {
utype = in_unit_table.utype,
scale = subunit.scale,  -- scale of last (least significant) unit
valinfo = { { value = total, clean = subinfo.clean, denominator = subinfo.denominator } },
composite = composite_units,
default = default or in_unit_table.default
}
end
end


local function range_text(range, want_name, parms, before, after)
local function translate_parms(parms, kv_pairs)
    -- Return before .. rtext .. after
-- Update fields in parms by translating each key:value in kv_pairs to terms
    -- where rtext is the text that separates two values in a range.
-- used by this module (may involve translating from local language to English).
    local rtext, adj_text, exception
-- Also, checks are performed which may display warnings, if enabled.
    if type(range) == 'table' then
-- Return true if successful or return false, t where t is an error message table.
        -- Table must specify range text for abbr=off and for abbr=on,
currency_text = nil  -- local testing can hold module in memory; must clear globals
        -- and may specify range text for 'adj=on',
local accept_any_text = {
        -- and may specify exception = true.
input = true,
        rtext = range[want_name and 'off' or 'on']
qid = true,
        adj_text = range['adj']
qual = true,
        exception = range['exception']
stylein = true,
    else
styleout = true,
        rtext = range
tracking = true,
    end
}
    if parms.opt_adjectival then
if kv_pairs.adj and kv_pairs.sing then
        if want_name or (exception and parms.abbr_org == 'on') then
-- For enwiki (before translation), warn if attempt to use adj and sing
            rtext = adj_text or rtext:gsub(' ', '-'):gsub('&nbsp;', '-')
-- as the latter is a deprecated alias for the former.
        end
if kv_pairs.adj ~= kv_pairs.sing and kv_pairs.sing ~= '' then
    end
add_warning(parms, 1, 'cvt_unknown_option', 'sing=' .. kv_pairs.sing)
    if rtext == '' and after:sub(1, #MINUS) == MINUS then
end
        rtext = '&nbsp;– '
kv_pairs.sing = nil
    end
end
    return before .. rtext .. after
kv_pairs.comma = kv_pairs.comma or config.comma  -- for plwiki who want default comma=5
for loc_name, loc_value in pairs(kv_pairs) do
local en_name = text_code.en_option_name[loc_name]
if en_name then
local en_value
if en_name == '$' or en_name == 'frac' or en_name == 'sigfig' then
if loc_value == '' then
add_warning(parms, 2, 'cvt_empty_option', loc_name)
elseif en_name == '$' then
-- Value should be a single character like "€" for the euro currency symbol, but anything is accepted.
currency_text = (loc_value == 'euro') and '€' or loc_value
else
local minimum
local number, is_integer = get_number(loc_value)
if en_name == 'frac' then
minimum = 2
if number and number < 0 then
parms.opt_fraction_horizontal = true
number = -number
end
else
minimum = 1
end
if number and is_integer and number >= minimum then
en_value = number
else
add_warning(parms, 1, (en_name == 'frac' and 'cvt_bad_frac' or 'cvt_bad_sigfig'), loc_name .. '=' .. loc_value)
end
end
elseif accept_any_text[en_name] then
en_value = loc_value ~= '' and loc_value or nil  -- accept non-empty user text with no validation
if en_name == 'input' then
-- May have something like {{convert|input=}} (empty input) if source is an infobox
-- with optional fields. In that case, want to output nothing rather than an error.
parms.input_text = loc_value  -- keep input because parms.input is nil if loc_value == ''
end
else
en_value = text_code.en_option_value[en_name][loc_value]
if en_value and en_value:sub(-1) == '?' then
en_value = en_value:sub(1, -2)
add_warning(parms, -1, 'cvt_deprecated', loc_name .. '=' .. loc_value)
end
if en_value == nil then
if loc_value == '' then
add_warning(parms, 2, 'cvt_empty_option', loc_name)
else
add_warning(parms, 1, 'cvt_unknown_option', loc_name .. '=' .. loc_value)
end
elseif en_value == '' then
en_value = nil  -- an ignored option like adj=off
elseif type(en_value) == 'string' and en_value:sub(1, 4) == 'opt_' then
for _, v in ipairs(split(en_value, ',')) do
local lhs, rhs = v:match('^(.-)=(.+)$')
if rhs then
parms[lhs] = tonumber(rhs) or rhs
else
parms[v] = true
end
end
en_value = nil
end
end
parms[en_name] = en_value
else
add_warning(parms, 1, 'cvt_unknown_option', loc_name .. '=' .. loc_value)
end
end
local abbr_entered = parms.abbr
local cfg_abbr = config.abbr
if cfg_abbr then
-- Don't warn if invalid because every convert would show that warning.
if cfg_abbr == 'on always' then
parms.abbr = 'on'
elseif cfg_abbr == 'off always' then
parms.abbr = 'off'
elseif parms.abbr == nil then
if cfg_abbr == 'on default' then
parms.abbr = 'on'
elseif cfg_abbr == 'off default' then
parms.abbr = 'off'
end
end
end
if parms.abbr then
if parms.abbr == 'unit' then
parms.abbr = 'on'
parms.number_word = true
end
parms.abbr_org = parms.abbr  -- original abbr, before any flip
elseif parms.opt_hand_hh then
parms.abbr_org = 'on'
parms.abbr = 'on'
else
parms.abbr = 'out'  -- default is to abbreviate output only (use symbol, not name)
end
if parms.opt_order_out then
-- Disable options that do not work in a useful way with order=out.
parms.opt_flip = nil  -- override adj=flip
parms.opt_spell_in = nil
parms.opt_spell_out = nil
parms.opt_spell_upper = nil
end
if parms.opt_spell_out and not abbr_entered then
parms.abbr = 'off' -- should show unit name when spelling the output value
end
if parms.opt_flip then
local function swap_in_out(option)
local value = parms[option]
if value == 'in' then
parms[option] = 'out'
elseif value == 'out' then
parms[option] = 'in'
end
end
swap_in_out('abbr')
swap_in_out('lk')
if parms.opt_spell_in and not parms.opt_spell_out then
-- For simplicity, and because it does not appear to be needed,
-- user cannot set an option to spell the output only.
parms.opt_spell_in = nil
parms.opt_spell_out = true
end
end
if parms.opt_spell_upper then
parms.spell_upper = parms.opt_flip and 'out' or 'in'
end
if parms.opt_table or parms.opt_tablecen then
if abbr_entered == nil and parms.lk == nil then
parms.opt_values = true
end
parms.table_align = parms.opt_table and 'right' or 'center'
end
if parms.table_align or parms.opt_sortable_on then
parms.need_table_or_sort = true
end
local disp_joins = text_code.disp_joins
local default_joins = disp_joins['b']
parms.join_between = default_joins[3] or '; '
local disp = parms.disp
if disp == nil then  -- special case for the most common setting
parms.joins = default_joins
elseif disp == 'x' then
-- Later, parms.joins is set from the input parameters.
else
-- Old template does this.
local abbr = parms.abbr
if disp == 'slash' then
if abbr_entered == nil then
disp = 'slash-nbsp'
elseif abbr == 'in' or abbr == 'out' then
disp = 'slash-sp'
else
disp = 'slash-nosp'
end
elseif disp == 'sqbr' then
if abbr == 'on' then
disp = 'sqbr-nbsp'
else
disp = 'sqbr-sp'
end
end
parms.joins = disp_joins[disp] or default_joins
parms.join_between = parms.joins[3] or parms.join_between
parms.wantname = parms.joins.wantname
end
if (en_default and not parms.opt_lang_local and (parms[1] or ''):find('%d')) or parms.opt_lang_en then
from_en_table = nil
end
if en_default and from_en_table then
-- For hiwiki: localized symbol/name is defined with the US symbol/name field,
-- and is used if output uses localized numbers.
parms.opt_sp_us = true
end
return true
end
end


local function add_warning(parms, mcode, text)
local function get_values(parms)
    -- If enabled, add a warning that will be displayed after the convert result.
-- If successful, update parms and return true, v, i where
    -- Currently, only the first warning is displayed.
--  v = table of input values
    if warnings then
--  i = index to next entry in parms after those processed here
        if parms.warnings == nil then
-- or return false, t where t is an error message table.
            parms.warnings = message({ mcode, text })
local valinfo = collection()  -- numbered table of input values
        end
local range = collection()  -- numbered table of range items (having, for example, 2 range items requires 3 input values)
    end
local had_nocomma  -- true if removed "nocomma" kludge from second parameter (like "tonocomma")
local parm2 = strip(parms[2])
if parm2 and parm2:sub(-7, -1) == 'nocomma' then
parms[2] = strip(parm2:sub(1, -8))
parms.opt_nocomma = true
had_nocomma = true
end
local function extractor(i)
-- If the parameter is not a value, try unpacking it as a range ("1-23" for "1 to 23").
-- However, "-1-2/3" is a negative fraction (-1⅔), so it must be extracted first.
-- Do not unpack a parameter if it is like "3-1/2" which is sometimes incorrectly
-- used instead of "3+1/2" (and which should not be interpreted as "3 to ½").
-- Unpacked items are inserted into the parms table.
-- The tail recursion allows combinations like "1x2 to 3x4".
local valstr = strip(parms[i])  -- trim so any '-' as a negative sign will be at start
local success, result = extract_number(parms, valstr, i > 1)
if not success and valstr and i < 20 then  -- check i to limit abuse
local lhs, sep, rhs = valstr:match('^(%S+)%s+(%S+)%s+(%S.*)')
if lhs and not (sep == '-' and rhs:match('/')) then
if sep:find('%d') then
return success, result  -- to reject {{convert|1 234 567|m}} with a decent message (en only)
end
parms[i] = rhs
table.insert(parms, i, sep)
table.insert(parms, i, lhs)
return extractor(i)
end
if not valstr:match('%-.*/') then
for _, sep in ipairs(text_code.ranges.words) do
local start, stop = valstr:find(sep, 2, true)  -- start at 2 to skip any negative sign for range '-'
if start then
parms[i] = valstr:sub(stop + 1)
table.insert(parms, i, sep)
table.insert(parms, i, valstr:sub(1, start - 1))
return extractor(i)
end
end
end
end
return success, result
end
local i = 1
local is_change
while true do
local success, info = extractor(i)  -- need to set parms.opt_nocomma before calling this
if not success then return false, info end
i = i + 1
if is_change then
info.is_change = true  -- value is after "±" and so is a change (significant for range like {{convert|5|±|5|°C}})
is_change = nil
end
valinfo:add(info)
local range_item = get_range(strip(parms[i]))
if not range_item then
break
end
i = i + 1
range:add(range_item)
if type(range_item) == 'table' then
-- For range "x", if append unit to some values, append it to all.
parms.in_range_x = parms.in_range_x or range_item.in_range_x
parms.out_range_x = parms.out_range_x or range_item.out_range_x
parms.abbr_range_x = parms.abbr_range_x or range_item.abbr_range_x
is_change = range_item.is_range_change
end
end
if range.n > 0 then
if range.n > 30 then  -- limit abuse, although 4 is a more likely upper limit
return false, { 'cvt_invalid_num' }  -- misleading message but it will do
end
parms.range = range
elseif had_nocomma then
return false, { 'cvt_unknown', parm2 }
end
return true, valinfo, i
end
end


local function get_composite(parms, iparm, total, in_unit_table)
local function simple_get_values(parms)
    -- Look for a composite input unit. For example, "{{convert|1|yd|2|ft|3|in}}"
-- If input is like "{{convert|valid_value|valid_unit|...}}",
    -- would result in a call to this function with
-- return true, i, in_unit, in_unit_table
    --  iparm = 3 (parms[iparm] = "2", just after the first unit)
-- i = index in parms of what follows valid_unit, if anything.
    --   total = 1 (number of yards)
-- The valid_value is not negative and does not use a fraction, and
    --  in_unit_table = (unit table for "yd")
-- no options requiring further processing of the input are used.
    -- Return true, iparm, unit where
-- Otherwise, return nothing or return false, parm1 for caller to interpret.
    --   iparm = index just after the composite units (7 in above example)
-- Testing shows this function is successful for 96% of converts in articles,
    --   unit = composite unit table holding all input units,
-- and that on average it speeds up converts by 8%.
    -- or return true if no composite unit is present in parms,
local clean = to_en(strip(parms[1] or ''), parms)
    -- or return false, t where t is an error message table.
if parms.opt_ri or parms.opt_spell_in or #clean > 10 or not clean:match('^[0-9.]+$') then
    local default, subinfo
return false, clean
    local composite_units, count = { in_unit_table }, 1
end
    local fixups = {}
local value = tonumber(clean)
    local subunit = in_unit_table
if not value then return end
    while subunit.subdivs do  -- subdivs is nil or a table of allowed subdivisions
local info = {
        local subcode = strip(parms[iparm+1])
value = value,
        local subdiv = subunit.subdivs[subcode]
altvalue = value,
        if not subdiv then
singular = (value == 1),
            break
clean = clean,
        end
show = with_separator(parms, clean),
        local success
}
        success, subunit = lookup(subcode, parms.opt_sp_us, 'no_combination')
local in_unit = strip(parms[2])
        if not success then return false, subunit end -- should never occur
local success, in_unit_table = lookup(parms, in_unit, 'no_combination')
        success, subinfo = extract_number(parms, parms[iparm], 1)
if not success then return end
        if not success then return false, subinfo end
in_unit_table.valinfo = { info }
        iparm = iparm + 2
return true, 3, in_unit, in_unit_table
        subunit.inout = 'in'
        subunit.valinfo = { subinfo }
        -- Recalculate total as a number of subdivisions.
        -- subdiv[1] = number of subdivisions per previous unit (integer > 1).
        total = total * subdiv[1] + subinfo.value
        if not default then  -- set by the first subdiv with a default defined
            default = subdiv.default
        end
        count = count + 1
        composite_units[count] = subunit
        if subdiv.unit or subdiv.name then
            fixups[count] = { unit = subdiv.unit, name = subdiv.name, valinfo = subunit.valinfo }
        end
    end
    if count == 1 then
        return true  -- no error and no composite unit
    end
    for i, fixup in pairs(fixups) do
        local unit = fixup.unit
        local name = fixup.name
        if not unit or (count > 2 and name) then
            composite_units[i].fixed_name = name
        else
            local success, alternate = lookup(unit, parms.opt_sp_us, 'no_combination')
            if not success then return false, alternate end -- should never occur
            alternate.inout = 'in'
            alternate.valinfo = fixup.valinfo
            composite_units[i] = alternate
        end
    end
    return true, iparm, {
        utype = in_unit_table.utype,
        scale = subunit.scale,  -- scale of last (least significant) unit
        valinfo = { { value = total, clean = subinfo.clean } },
        composite = composite_units,
        default = default or in_unit_table.default
    }
end
end


local function translate_parms(parms)
local function wikidata_call(parms, operation, ...)
    -- Update fields in parms by translating parameters to those used at enwiki.
-- Return true, s where s is the result of a Wikidata operation,
    for en_name, loc_name in pairs(local_option_name) do
-- or return false, t where t is an error message table.
        if en_name ~= 'sing' then  -- 'sing' is an old equivalent of 'adj'; cannot have both
local function worker(...)
            local loc_value = parms[loc_name]
wikidata_code = wikidata_code or require(wikidata_module)
            if loc_value == nil and en_name == 'adj' then
wikidata_data = wikidata_data or mw.loadData(wikidata_data_module)
                loc_name = local_option_name['sing']
return wikidata_code[operation](wikidata_data, ...)
                loc_value = parms[loc_name]
end
            end
local success, status, result = pcall(worker, ...)
            if loc_value then
if success then
                local en_value = en_option_value[en_name][loc_value]
return status, result
                if en_value == nil then
end
                    if loc_value == '' then
if parms.opt_sortable_debug then
                        add_warning(parms, 'cvt_empty_option', loc_name)
-- Use debug=yes to crash if an error while accessing Wikidata.
                    else
error('Error accessing Wikidata: ' .. status, 0)
                        add_warning(parms, 'cvt_unknown_option', loc_name .. '=' .. loc_value)
end
                    end
return false, { 'cvt_wd_fail' }
                elseif en_value == '' then
                    en_value = nil
                elseif en_value:sub(1, 4) == 'opt_' then
                    for _, v in ipairs(split(en_value, ':')) do
                        parms[v] = true
                    end
                    en_value = nil
                end
                parms[en_name] = en_value
            end
        end
    end
    if parms.adj then
        if parms.adj:sub(1, 2) == 'ri' then
            -- It is known that adj is 'ri1' or 'ri2' or 'ri3', so precision is valid.
            -- Only en digits are accepted.
            parms.input_precision = tonumber(parms.adj:sub(-1))
            parms.adj = nil
        end
    end
    if parms.abbr then
        parms.abbr_org = parms.abbr  -- original abbr that was set, before any flip
    else
        parms.abbr = 'out'  -- default is to abbreviate output only (use symbol, not name)
    end
    if parms.opt_flip then
        if parms.abbr == 'in' then
            parms.abbr = 'out'
        elseif parms.abbr == 'out' then
            parms.abbr = 'in'
        end
        if parms.lk == 'in' then
            parms.lk = 'out'
        elseif parms.lk == 'out' then
            parms.lk = 'in'
        end
    end
    if parms.opt_table or parms.opt_tablecen then
        if parms.abbr_org == nil and parms.lk == nil then
            parms.opt_values = true
        end
        local align = format('align="%s"', parms.opt_table and 'right' or 'center')
        parms.table_joins = { align .. '|', '\n|' .. align .. '|' }
    end
    if parms.opt_lang_en then
        from_en_table = nil
    end
end
end


local function get_parms(pframe)
local function get_parms(parms, args)
    -- If successful, return true, parms, unit where
-- If successful, update parms and return true, unit where
    --  parms is a table of all arguments passed to the template
--  parms is a table of all arguments passed to the template
    --        converted to named arguments, and
--        converted to named arguments, and
    --  unit is the input unit table;
--  unit is the input unit table;
    -- or return false, t where t is an error message table.
-- or return false, t where t is an error message table.
    -- MediaWiki removes leading and trailing whitespace from the values of
-- For special processing (not a convert), can also return
    -- named arguments. However, the values of numbered arguments include any
-- true, wikitext where wikitext is the final result.
    -- whitespace entered in the template, and whitespace is used by some
-- The returned input unit table may be for a fake unit using the specified
    -- parameters (example: the numbered parameters associated with "disp=x").
-- unit code as the symbol and name, and with bad_mcode = message code table.
    local success, info1, info2
-- MediaWiki removes leading and trailing whitespace from the values of
    local parms = {}  -- arguments passed to template
-- named arguments. However, the values of numbered arguments include any
    for k, v in pairs(pframe.args) do
-- whitespace entered in the template, and whitespace is used by some
        parms[k] = v
-- parameters (example: the numbered parameters associated with "disp=x").
    end
local kv_pairs = {}  -- table of input key:value pairs where key is a name; needed because cannot iterate parms and add new fields to it
    translate_parms(parms)
for k, v in pairs(args) do
    local range
if type(k) == 'number' or k == 'test' then  -- parameter "test" is reserved for testing and is not translated
    local next = strip(parms[2])
parms[k] = v
    local i = 3
else
    if next then
kv_pairs[k] = v
        range = range_types[next] or range_types[range_aliases[next]]
end
        if range == nil and next:sub(-7, -1) == 'nocomma' then
end
            local base = strip(next:sub(1, -8))
if parms.test == 'wikidata' then
            range = range_types[base] or range_types[range_aliases[base]]
local ulookup = function (ucode)
            if range then
-- Use empty table for parms so it does not accumulate results when used repeatedly.
                parms.opt_nocomma = true
return lookup({}, ucode, 'no_combination')
            end
end
        end
return wikidata_call(parms, '_listunits', ulookup)
    end
end
    success, info1 = extract_number(parms, parms[1], 1) -- need to set parms.opt_nocomma before calling this
local success, msg = translate_parms(parms, kv_pairs)
    if not success then return false, info1 end
if not success then return false, msg end
    local in_unit
if parms.input then
    if range == nil then
success, msg = wikidata_call(parms, '_adjustparameters', parms, 1)
        in_unit = next
if not success then return false, msg end
    else
end
        parms.range = range
local success, i, in_unit, in_unit_table = simple_get_values(parms)
        parms.is_range_x = range.is_range_x
if not success then
        success, info2 = extract_number(parms, parms[3], 2)
if type(i) == 'string' and i:match('^NNN+$') then
        if not success then return false, info2 end
-- Some infoboxes have examples like {{convert|NNN|m}} (3 or more "N").
        in_unit = strip(parms[4])
-- Output an empty string for these.
        i = 5
return false, { 'cvt_no_output' }
    end
end
    local success, in_unit_table = lookup(in_unit, parms.opt_sp_us, 'no_combination')
local valinfo
    if not success then return false, in_unit_table end
success, valinfo, i = get_values(parms)
    if parms.test == 'msg' then
if not success then return false, valinfo end
        -- Am testing the messages produced when no output unit is specified, and
in_unit = strip(parms[i])
        -- the input unit has a missing or invalid default.
i = i + 1
        -- Set two units for testing that.
success, in_unit_table = lookup(parms, in_unit, 'no_combination')
        -- LATER: Remove this code.
if not success then
        if in_unit == 'chain' then
in_unit = in_unit or ''
            in_unit_table.default = nil  -- no default
if parms.opt_ignore_error then  -- display given unit code with no error (for use with {{val}})
        elseif in_unit == 'rd' then
in_unit_table = ''  -- suppress error message and prevent processing of output unit
            in_unit_table.default  = "ft!X!m"  -- an invalid expression
end
        end
in_unit_table = setmetatable({
    end
symbol = in_unit, name2 = in_unit, utype = in_unit,
    in_unit_table.valinfo = { info1, info2 }  -- info2 is nil if no range
scale = 1, default = '', defkey = '', linkey = '',
    in_unit_table.inout = 'in'  -- this is an input unit
bad_mcode = in_unit_table }, unit_mt)
    if not range then
end
        local success, inext, composite_unit = get_composite(parms, i, info1.value, in_unit_table)
in_unit_table.valinfo = valinfo
        if not success then return false, inext end
end
        if composite_unit then
if parms.test == 'msg' then
            in_unit_table = composite_unit
-- Am testing the messages produced when no output unit is specified, and
            i = inext
-- the input unit has a missing or invalid default.
        end
-- Set two units for testing that.
    end
-- LATER: Remove this code.
    if in_unit_table.builtin == 'mach' then
if in_unit == 'chain' then
        -- As with old template, a number following Mach as the input unit is the altitude,
in_unit_table.default = nil  -- no default
        -- and there is no way to specify an altitude for the output unit.
elseif in_unit == 'rd' then
        -- Could put more code in this function to get any output unit and check for
in_unit_table.default  = "ft!X!m"  -- an invalid expression
        -- an altitude following that unit.
end
        local success, info = extract_number(parms, parms[i], 1, true)
end
        if success then
in_unit_table.inout = 'in'  -- this is an input unit
            i = i + 1
if not parms.range then
            in_unit_table.altitude = info.value
local success, inext, composite_unit = get_composite(parms, i, in_unit_table)
        end
if not success then return false, inext end
    end
if composite_unit then
    next = strip(parms[i])
in_unit_table = composite_unit
    i = i + 1
i = inext
    local precision, is_bad_precision
end
    local function set_precision(text)
end
        local number, is_integer = get_number(text)
if in_unit_table.builtin == 'mach' then
        if number then
-- As with old template, a number following Mach as the input unit is the altitude,
            if is_integer then
-- and there is no way to specify an altitude for the output unit.
                precision = number
-- Could put more code in this function to get any output unit and check for
            else
-- an altitude following that unit.
                precision = text
local success, info = extract_number(parms, parms[i], false, true)
                is_bad_precision = true
if success then
            end
i = i + 1
            return true  -- text was used for precision, good or bad
in_unit_table.altitude = info.value
        end
end
    end
end
    if not set_precision(next) then
local word = strip(parms[i])
        parms.out_unit = next
i = i + 1
        if set_precision(strip(parms[i])) then
local precision, is_bad_precision
            i = i + 1
local function set_precision(text)
        end
local number, is_integer = get_number(text)
    end
if number then
    if parms.opt_adj_mid then
if is_integer then
        parms.opt_adjectival = true
precision = number
        next = parms[i]
else
        i = i + 1
precision = text
        if next then  -- mid-text words
is_bad_precision = true
            if next:sub(1, 1) == '-' then
end
                parms.mid = next
return true  -- text was used for precision, good or bad
            else
end
                parms.mid = ' ' .. next
end
            end
if word and not set_precision(word) then
        end
parms.out_unit = parms.out_unit or word
    end
if set_precision(strip(parms[i])) then
    if parms.opt_one_preunit then
i = i + 1
        parms[parms.opt_flip and 'preunit2' or 'preunit1'] = preunits(1, parms[i])
end
        i = i + 1
end
    end
if parms.opt_adj_mid then
    if parms.disp == 'x' then
word = parms[i]
        -- Following is reasonably compatible with the old template.
i = i + 1
        local first = parms[i] or ''
if word then  -- mid-text words
        local second = parms[i+1] or ''
if word:sub(1, 1) == '-' then
        i = i + 2
parms.mid = word
        if strip(first) == '' then  -- user can enter '&#32;' rather than ' ' to avoid the default
else
            first = ' [&nbsp;' .. first
parms.mid = ' ' .. word
            second = '&nbsp;]' .. second
end
        end
end
        parms.joins = { first, second }
end
    elseif parms.opt_two_preunits then
if parms.opt_one_preunit then
        local p1, p2 = preunits(2, parms[i], parms[i+1])
parms[parms.opt_flip and 'preunit2' or 'preunit1'] = preunits(1, parms[i])
        i = i + 2
i = i + 1
        if parms.preunit1 then
end
            -- To simplify documentation, allow unlikely use of adj=pre with disp=preunit
if parms.disp == 'x' then
            -- (however, an output unit must be specified with adj=pre and with disp=preunit).
-- Following is reasonably compatible with the old template.
            parms.preunit1 = parms.preunit1 .. p1
local first = parms[i] or ''
            parms.preunit2 = p2
local second = parms[i+1] or ''
        else
i = i + 2
            parms.preunit1, parms.preunit2 = p1, p2
if strip(first) == '' then  -- user can enter '&#32;' rather than ' ' to avoid the default
        end
first = ' [&nbsp;' .. first
    end
second = '&nbsp;]' .. second
    if precision == nil then
end
        if set_precision(strip(parms[i])) then
parms.joins = { first, second }
            i = i + 1
elseif parms.opt_two_preunits then
        end
local p1, p2 = preunits(2, parms[i], parms[i+1])
    end
i = i + 2
    if is_bad_precision then
if parms.preunit1 then
        return false, { 'cvt_bad_prec', precision }
-- To simplify documentation, allow unlikely use of adj=pre with disp=preunit
    end
-- (however, an output unit must be specified with adj=pre and with disp=preunit).
    parms.precision = precision
parms.preunit1 = parms.preunit1 .. p1
    local sigfig = parms.sigfig
parms.preunit2 = p2
    if sigfig then
else
        local number, is_integer = get_number(sigfig)
parms.preunit1, parms.preunit2 = p1, p2
        if not number or not is_integer or number <= 0 then
end
            return false, { 'cvt_bad_sigfig', sigfig }
end
        end
if precision == nil then
        parms.sigfig = number
if set_precision(strip(parms[i])) then
    end
i = i + 1
    return true, parms, in_unit_table
end
end
if is_bad_precision then
add_warning(parms, 1, 'cvt_bad_prec', precision)
else
parms.precision = precision
end
for j = i, i + 3 do
local parm = parms[j]  -- warn if find a non-empty extraneous parameter
if parm and parm:match('%S') then
add_warning(parms, 1, 'cvt_unknown_option', parm)
break
end
end
return true, in_unit_table
end
end


local function default_precision(invalue, inclean, outvalue, in_current, out_current, extra)
local function record_default_precision(parms, out_current, precision)
    -- Return a default value for precision (an integer like 2, 0, -2).
-- If necessary, adjust parameters and return a possibly adjusted precision.
    -- Code follows procedures used in old template.
-- When converting a range of values where a default precision is required,
    local fudge = 1e-14  -- {{Order of magnitude}} adds this, so we do too
-- that default is calculated for each value because the result sometimes
    local prec, minprec, adjust
-- depends on the precise input and output values. This function may cause
    local utype = out_current.utype
-- the entire convert process to be repeated in order to ensure that the
    local subunit_ignore_trailing_zero
-- same default precision is used for each individual convert.
    local subunit_more_precision  -- kludge for "in" used in input like "|2|ft|6|in"
-- If that were not done, a range like 1000 to 1000.4 may give poor results
    local composite = in_current.composite
-- because the first output could be heavily rounded, while the second is not.
    if composite then
-- For range 1000.4 to 1000, this function can give the second convert the
        subunit_ignore_trailing_zero = true  -- input "|2|st|10|lb" has precision 0, not -1
-- same default precision that was used for the first.
        if composite[#composite].exception == 'subunit_more_precision' then
if not parms.opt_round_each then
            subunit_more_precision = true  -- do not use standard precision with input like "|2|ft|6|in"
local maxdef = out_current.max_default_precision
        end
if maxdef then
    end
if maxdef < precision then
    -- Count digits after decimal mark, handling cases like '12.345e6'.
parms.do_convert_again = true
    local exponent
out_current.max_default_precision = precision
    local integer, dot, fraction, expstr = inclean:match('^(%d*)(%.?)(%d*)(.*)')
else
    local e = expstr:sub(1, 1)
precision = out_current.max_default_precision
    local boost = 0  -- can increase default precision
end
    if e == 'e' or e == 'E' then
else
        exponent = tonumber(expstr:sub(2))
out_current.max_default_precision = precision
    elseif expstr:find('/', 1, true) then
end
        boost = 1  -- any input fraction is regarded as one extra digit of precision
end
    end
return precision
    if dot == '' then
        prec = subunit_ignore_trailing_zero and 0 or -integer:match('0*$'):len()
    else
        prec = #fraction
    end
    if exponent then
        -- So '1230' and '1.23e3' both give prec = -1, and '0.00123' and '1.23e-3' give 5.
        prec = prec - exponent
    end
    local exception = (utype == 'temperature' and not
            (in_current.exception == 'temperature' or out_current.exception == 'temperature'))
    if exception then
        -- Kelvin value can be almost zero, or small but negative due to precision problems.
        -- Also, an input value like -300 C (below absolute zero) gives negative kelvins.
        -- Calculate minimum precision from absolute value.
        adjust = 0
        local kelvin = abs((invalue - in_current.offset) * in_current.scale)
        if kelvin < 1e-8 then -- assume nonzero due to input or calculation precision problem
            minprec = 2
        else
            minprec = 2 - floor(log10(kelvin) + fudge)  -- 3 sigfigs in kelvin
        end
    else
        if invalue == 0 or outvalue <= 0 then
            -- We are never called with a negative outvalue, but it might be zero.
            -- This is special-cased to avoid calculation exceptions.
            return 0
        end
        if out_current.exception == 'integer_more_precision' and floor(invalue) == invalue then
            -- With certain output units that sometimes give poor results
            -- with default rounding, use more precision when the input
            -- value is equal to an integer. An example of a poor result
            -- is when input 50 gives a smaller output than input 49.5.
            -- Experiment shows this helps, but it does not eliminate all
            -- surprises because it is not clear whether "50" should be
            -- interpreted as "from 45 to 55" or "from 49.5 to 50.5".
            adjust = -log10(in_current.scale)
        elseif subunit_more_precision then
            -- Conversion like "{{convert|6|ft|1|in|cm}}" (where subunit is "in")
            -- has a non-standard adjust value, to give more output precision.
            adjust = log10(out_current.scale) + 2
        else
            adjust = log10(abs(invalue / outvalue))
        end
        adjust = adjust + log10(2)
        -- Ensure that the output has at least two significant figures.
        minprec = 1 - floor(log10(outvalue) + fudge)
    end
    if extra then
        adjust = extra.adjust or adjust
        minprec = extra.minprec or minprec
    end
    return math.max(floor(prec + adjust + boost), minprec)
end
end


local function convert(invalue, inclean, in_current, out_current)
local function default_precision(parms, invalue, inclean, denominator, outvalue, in_current, out_current, extra)
    -- Convert given input value from one unit to another.
-- Return a default value for precision (an integer like 2, 0, -2).
    -- Return output_value (a number) if a simple convert, or
-- If denominator is not nil, it is the value of the denominator in inclean.
    -- return f, t where
-- Code follows procedures used in old template.
    --   f = true, t = table of information with results, or
local fudge = 1e-14  -- {{Order of magnitude}} adds this, so we do too
    --   f = false, t = error message table.
local prec, minprec, adjust
    local inscale = in_current.scale
local subunit_ignore_trailing_zero
    local outscale = out_current.scale
local subunit_more_precision  -- kludge for "in" used in input like "|2|ft|6|in"
    if not in_current.iscomplex and not out_current.iscomplex then
local composite = in_current.composite
        return invalue * (inscale / outscale) -- minimize overhead for most common case
if composite then
    end
subunit_ignore_trailing_zero = true  -- input "|2|st|10|lb" has precision 0, not -1
    if in_current.invert then
if composite[#composite].exception == 'subunit_more_precision' then
        -- Fuel efficiency (there are no built-ins for this type of unit).
subunit_more_precision = true -- do not use standard precision with input like "|2|ft|6|in"
        if in_current.invert * out_current.invert < 0 then
end
            return 1 / (invalue * inscale * outscale)
end
        end
if denominator and denominator > 0 then
        return invalue * (inscale / outscale)
prec = math.max(log10(denominator), 1)
    elseif in_current.offset then
else
        -- Temperature (there are no built-ins for this type of unit).
-- Count digits after decimal mark, handling cases like '12.345e6'.
        return (invalue - in_current.offset) * (inscale / outscale) + out_current.offset
local exponent
    else
local integer, dot, decimals, expstr = inclean:match('^(%d*)(%.?)(%d*)(.*)')
        -- Built-in unit.
local e = expstr:sub(1, 1)
        local in_builtin = in_current.builtin
if e == 'e' or e == 'E' then
        local out_builtin = out_current.builtin
exponent = tonumber(expstr:sub(2))
        if in_builtin and out_builtin then
end
            if in_builtin == out_builtin then
if dot == '' then
                return invalue
prec = subunit_ignore_trailing_zero and 0 or -integer:match('0*$'):len()
            end
else
            -- There are no cases (yet) where need to convert from one
prec = #decimals
            -- built-in unit to another, so this should never occur.
end
            return false, { 'cvt_bug_convert' }
if exponent then
        end
-- So '1230' and '1.23e3' both give prec = -1, and '0.00123' and '1.23e-3' give 5.
        if in_builtin == 'mach' or out_builtin == 'mach' then
prec = prec - exponent
            local adjust
end
            if in_builtin == 'mach' then
end
                inscale = speed_of_sound(in_current.altitude)
if in_current.istemperature and out_current.istemperature then
                adjust = outscale / 0.1
-- Converting between common temperatures (°C, °F, °R, K); not keVT.
            else
-- Kelvin value can be almost zero, or small but negative due to precision problems.
                outscale = speed_of_sound(out_current.altitude)
-- Also, an input value like -300 C (below absolute zero) gives negative kelvins.
                adjust = 0.1 / inscale
-- Calculate minimum precision from absolute value.
            end
adjust = 0
            return true, {
local kelvin = abs((invalue - in_current.offset) * in_current.scale)
                outvalue = invalue * (inscale / outscale),
if kelvin < 1e-8 then  -- assume nonzero due to input or calculation precision problem
                adjust = log10(adjust) + log10(2),
minprec = 2
            }
else
        elseif in_builtin == 'hand' then
minprec = 2 - floor(log10(kelvin) + fudge) -- 3 sigfigs in kelvin
            -- 1 hand = 4 inches; 1.2 hands = 6 inches.
end
            -- Fractions of a hand are only defined for the first digit, and
else
            -- the first fractional digit should be a number of inches (1, 2 or 3).
if invalue == 0 or outvalue <= 0 then
            -- However, this code interprets the entire fraction as the number
-- We are never called with a negative outvalue, but it might be zero.
            -- of inches / 10 (so 1.75 inches would be 0.175 hands).
-- This is special-cased to avoid calculation exceptions.
            -- A value like 12.3 hands is exactly 12*4 + 3 inches; base default precision on that.
return record_default_precision(parms, out_current, 0)
            local integer, fraction = math.modf(invalue)
end
            local outvalue = (integer + 2.5 * fraction) * (inscale / outscale)
if out_current.exception == 'integer_more_precision' and floor(invalue) == invalue then
            local inch_value = 4 * integer + 10 * fraction  -- equivalent number of inches
-- With certain output units that sometimes give poor results
            local fracstr = inclean:match('%.(.*)') or ''
-- with default rounding, use more precision when the input
            local fmt
-- value is equal to an integer. An example of a poor result
            if fracstr == '' then
-- is when input 50 gives a smaller output than input 49.5.
                fmt = '%.0f'
-- Experiment shows this helps, but it does not eliminate all
            else
-- surprises because it is not clear whether "50" should be
                fmt = '%.' .. format('%d', #fracstr - 1) .. 'f'
-- interpreted as "from 45 to 55" or "from 49.5 to 50.5".
            end
adjust = -log10(in_current.scale)
            return true, {
elseif subunit_more_precision then
                invalue = inch_value,
-- Conversion like "{{convert|6|ft|1|in|cm}}" (where subunit is "in")
                inclean = format(fmt, inch_value),
-- has a non-standard adjust value, to give more output precision.
                outvalue = outvalue,
adjust = log10(out_current.scale) + 2
                minprec = 0,
else
            }
adjust = log10(abs(invalue / outvalue))
        end
end
    end
adjust = adjust + log10(2)
    return false, { 'cvt_bug_convert' }  -- should never occur
-- Ensure that the output has at least two significant figures.
minprec = 1 - floor(log10(outvalue) + fudge)
end
if extra then
adjust = extra.adjust or adjust
minprec = extra.minprec or minprec
end
return record_default_precision(parms, out_current, math.max(floor(prec + adjust), minprec))
end
end
local function convert(parms, invalue, info, in_current, out_current)
-- Convert given input value from one unit to another.
-- Return output_value (a number) if a simple convert, or
-- return f, t where
--  f = true, t = table of information with results, or
--  f = false, t = error message table.
local inscale = in_current.scale
local outscale = out_current.scale
if not in_current.iscomplex and not out_current.iscomplex then
return invalue * (inscale / outscale)  -- minimize overhead for most common case
end
if in_current.invert or out_current.invert then
-- Inverted units, such as inverse length, inverse time, or
-- fuel efficiency. Built-in units do not have invert set.
if (in_current.invert or 1) * (out_current.invert or 1) < 0 then
return 1 / (invalue * inscale * outscale)
end
return invalue * (inscale / outscale)
elseif in_current.offset then
-- Temperature (there are no built-ins for this type of unit).
if info.is_change then
return invalue * (inscale / outscale)
end
return (invalue - in_current.offset) * (inscale / outscale) + out_current.offset
else
-- Built-in unit.
local in_builtin = in_current.builtin
local out_builtin = out_current.builtin
if in_builtin and out_builtin then
if in_builtin == out_builtin then
return invalue
end
-- There are no cases (yet) where need to convert from one
-- built-in unit to another, so this should never occur.
return false, { 'cvt_bug_convert' }
end
if in_builtin == 'mach' or out_builtin == 'mach' then
local adjust
if in_builtin == 'mach' then
inscale = speed_of_sound(in_current.altitude)
adjust = outscale / 0.1
else
outscale = speed_of_sound(out_current.altitude)
adjust = 0.1 / inscale
end
return true, {
outvalue = invalue * (inscale / outscale),
adjust = log10(adjust) + log10(2),
}
elseif in_builtin == 'hand' then
-- 1 hand = 4 inches; 1.2 hands = 6 inches.
-- Decimals of a hand are only defined for the first digit, and
-- the first fractional digit should be a number of inches (1, 2 or 3).
-- However, this code interprets the entire fractional part as the number
-- of inches / 10 (so 1.75 inches would be 0.175 hands).
-- A value like 12.3 hands is exactly 12*4 + 3 inches; base default precision on that.
local integer, fracpart = math.modf(invalue)
local inch_value = 4 * integer + 10 * fracpart  -- equivalent number of inches
local factor = inscale / outscale
if factor == 4 then
-- Am converting to inches: show exact result, and use "inches" not "in" by default.
if parms.abbr_org == nil then
out_current.usename = true
end
local show = format('%g', abs(inch_value))  -- show and clean are unsigned
if not show:find('e', 1, true) then
return true, {
invalue = inch_value,
outvalue = inch_value,
clean = show,
show = show,
}
end
end
local outvalue = (integer + 2.5 * fracpart) * factor
local fracstr = info.clean:match('%.(.*)') or ''
local fmt
if fracstr == '' then
fmt = '%.0f'
else
fmt = '%.' .. format('%d', #fracstr - 1) .. 'f'
end
return true, {
invalue = inch_value,
clean = format(fmt, inch_value),
outvalue = outvalue,
minprec = 0,
}
end
end
return false, { 'cvt_bug_convert' }  -- should never occur
end
local function user_style(parms, i)
-- Return text for a user-specified style for a table cell, or '' if none,
-- given i = 1 (input style) or 2 (output style).
local style = parms[(i == 1) and 'stylein' or 'styleout']
if style then
style = style:gsub('"', '')
if style ~= '' then
if style:sub(-1) ~= ';' then
style = style .. ';'
end
return style
end
end
return ''
end
local function make_table_or_sort(parms, invalue, info, in_current, scaled_top)
-- Set options to handle output for a table or a sort key, or both.
-- The text sort key is based on the value resulting from converting
-- the input to a fake base unit with scale = 1, and other properties
-- required for a conversion derived from the input unit.
-- For other modules, return the sort key in a hidden span element, and
-- the scaled value used to generate the sort key.
-- If scaled_top is set, it is the scaled value of the numerator of a per unit
-- to be combined with this unit (the denominator) to make the sort key.
-- Scaling only works with units that convert with a factor (not temperature).
local sortkey, scaled_value
if parms.opt_sortable_on then
local base = {  -- a fake unit with enough fields for a valid convert
scale = 1,
invert = in_current.invert and 1,
iscomplex = in_current.iscomplex,
offset = in_current.offset and 0,
}
local outvalue, extra = convert(parms, invalue, info, in_current, base)
if extra then
outvalue = extra.outvalue
end
if in_current.istemperature then
-- Have converted to kelvin; assume numbers close to zero have a
-- rounding error and should be zero.
if abs(outvalue) < 1e-12 then
outvalue = 0
end
end
if scaled_top and outvalue ~= 0 then
outvalue = scaled_top / outvalue
end
scaled_value = outvalue
if not valid_number(outvalue) then
if outvalue < 0 then
sortkey = '1000000000000000000'
else
sortkey = '9000000000000000000'
end
elseif outvalue == 0 then
sortkey = '5000000000000000000'
else
local mag = floor(log10(abs(outvalue)) + 1e-14)
local prefix
if outvalue > 0 then
prefix = 7000 + mag
else
prefix = 2999 - mag
outvalue = outvalue + 10^(mag+1)
end
sortkey = format('%d', prefix) .. format('%015.0f', floor(outvalue * 10^(14-mag)))
end
end
local sortspan
if sortkey and not parms.table_align then
sortspan = parms.opt_sortable_debug and
'<span data-sort-value="' .. sortkey .. '♠"><span style="border:1px solid">' .. sortkey .. '♠</span></span>' or
'<span data-sort-value="' .. sortkey .. '♠"></span>'
parms.join_before = sortspan
end
if parms.table_align then
local sort
if sortkey then
sort = ' data-sort-value="' .. sortkey .. '"'
if parms.opt_sortable_debug then
parms.join_before = '<span style="border:1px solid">' .. sortkey .. '</span>'
end
else
sort = ''
end
local style = 'style="text-align:' .. parms.table_align .. ';'
local joins = {}
for i = 1, 2 do
joins[i] = (i == 1 and '' or '\n|') .. style .. user_style(parms, i) .. '"' .. sort .. '|'
end
parms.table_joins = joins
end
return sortspan, scaled_value
end
local cvt_to_hand


local function cvtround(parms, info, in_current, out_current)
local function cvtround(parms, info, in_current, out_current)
    -- Return true, t where t is a table with the conversion results; fields:
-- Return true, t where t is a table with the conversion results; fields:
    --  show = rounded, formatted string with the result of converting value in info,
--  show = rounded, formatted string with the result of converting value in info,
    --      using the rounding specified in parms.
--      using the rounding specified in parms.
    --  singular = true if result is positive, and (after rounding)
--  singular = true if result (after rounding and ignoring any negative sign)
    --      is "1", or like "1.00";
--      is "1", or like "1.00", or is a fraction with value < 1;
    --  (and more fields shown below, and a calculated 'absvalue' field).
--  (and more fields shown below, and a calculated 'absvalue' field).
    -- or return true, nil if no value specified;
-- or return false, t where t is an error message table.
    -- or return false, t where t is an error message table.
-- Input info.clean uses en digits (it has been translated, if necessary).
    -- Input info.clean uses en digits (it has been translated, if necessary).
-- Output show uses en or non-en digits as appropriate, or can be spelled.
    -- Output show uses en or non-en digits as appropriate.
if out_current.builtin == 'hand' then
    local invalue, inclean, show, exponent, singular
return cvt_to_hand(parms, info, in_current, out_current)
    if info then
end
        invalue, inclean = info.value, info.clean
local invalue = in_current.builtin == 'hand' and info.altvalue or info.value
    end
local outvalue, extra = convert(parms, invalue, info, in_current, out_current)
    if invalue == nil or invalue == '' then
if parms.need_table_or_sort then
        return true, nil
parms.need_table_or_sort = nil  -- process using first input value only
    end
make_table_or_sort(parms, invalue, info, in_current)
    if out_current.builtin == 'hand' then
end
        -- Convert to hands, then convert the fractional part to inches.
if extra then
        local dummy_unit_table = { scale = out_current.scale }
if not outvalue then return false, extra end
        local success, outinfo = cvtround(parms, info, in_current, dummy_unit_table)
invalue = extra.invalue or invalue
        if not success then return false, outinfo end
outvalue = extra.outvalue
        local fmt
end
        local fraction = (outinfo.show):match('[' .. numdot .. '](.*)') or ''  -- outinfo.show is in local language
if not valid_number(outvalue) then
        if fraction == '' then
return false, { 'cvt_invalid_num' }
            if not outinfo.use_default_precision then
end
                return true, outinfo
local isnegative
            end
if outvalue < 0 then
            fmt = '%.0f'
isnegative = true
        else
outvalue = -outvalue
            fmt = '%.' .. format('%d', ulen(fraction) - 1) .. 'f'
end
        end
local precision, show, exponent
        local hands, inches = math.modf(outinfo.raw_absvalue)
local denominator = out_current.frac
        inches = format(fmt, inches * 4)
if denominator then
        if inches:sub(1, 1) == '4' then
show = fraction_table(outvalue, denominator)
            hands = hands + 1
else
            inches = '0' .. inches:sub(2)
precision = parms.precision
            if tonumber(inches) == 0 then
if not precision then
                inches = '0'
if parms.sigfig then
            end
show, exponent = make_sigfig(outvalue, parms.sigfig)
        end
elseif parms.opt_round then
        if inches:sub(2, 2) == '.' then
local n = parms.opt_round
            inches = inches:sub(1, 1) .. inches:sub(3)
if n == 0.5 then
        end
local integer, fracpart = math.modf(floor(2 * outvalue + 0.5) / 2)
        return true, {
if fracpart == 0 then
            sign = outinfo.sign,
show = format('%.0f', integer)
            singular = outinfo.singular,
else
            show = outinfo.sign .. with_separator(parms, format('%d', hands)) .. numdot .. from_en(inches)
show = format('%.1f', integer + fracpart)
        }
end
    end
else
    local outvalue, extra = convert(invalue, inclean, in_current, out_current)
show = format('%.0f', floor((outvalue / n) + 0.5) * n)
    if extra then
end
        if not outvalue then return false, extra end
else
        invalue = extra.invalue or invalue
local inclean = info.clean
        inclean = extra.inclean or inclean
if extra then
        outvalue = extra.outvalue
inclean = extra.clean or inclean
    end
show = extra.show
    if not valid_number(outvalue) then
end
        return false, { 'cvt_invalid_num' }
if not show then
    end
precision = default_precision(parms, invalue, inclean, info.denominator, outvalue, in_current, out_current, extra)
    local isnegative
end
    if outvalue < 0 then
end
        isnegative = true
end
        outvalue = -outvalue
end
    end
if precision then
    local success, use_default_precision
if precision >= 0 then
    local precision = parms.precision
local fudge
    if not precision then
if precision <= 8 then
        local sigfig = parms.sigfig
-- Add a fudge to handle common cases of bad rounding due to inability
        if sigfig then
-- to precisely represent some values. This makes the following work:
            show, exponent = make_sigfig(outvalue, sigfig)
-- {{convert|-100.1|C|K}} and {{convert|5555000|um|m|2}}.
        elseif parms.opt_round5 then
-- Old template uses #expr round, which invokes PHP round().
            show = format('%.0f', floor((outvalue / 5) + 0.5) * 5)
-- LATER: Investigate how PHP round() works.
        else
fudge = 2e-14
            use_default_precision = true
else
            precision = default_precision(invalue, inclean, outvalue, in_current, out_current, extra)
fudge = 0
        end
end
    end
local fmt = '%.' .. format('%d', precision) .. 'f'
    if precision then
local success
        if precision >= 0 then
success, show = pcall(format, fmt, outvalue + fudge)
            if precision <= 8 then
if not success then
                -- Add a fudge to handle common cases of bad rounding due to inability
return false, { 'cvt_big_prec', tostring(precision) }
                -- to precisely represent some values. This makes the following work:
end
                -- {{convert|-100.1|C|K}} and {{convert|5555000|um|m|2}}.
else
                -- Old template uses #expr round, which invokes PHP round().
precision = -precision  -- #digits to zero (in addition to any digits after dot)
                -- LATER: Investigate how PHP round() works.
local shift = 10 ^ precision
                outvalue = outvalue + 2e-14
show = format('%.0f', outvalue/shift)
            end
if show ~= '0' then
            local fmt = '%.' .. format('%d', precision) .. 'f'
exponent = #show + precision
            local success
end
            success, show = pcall(format, fmt, outvalue)
end
            if not success then
end
                return false, { 'cvt_big_prec', tostring(precision) }
local t = format_number(parms, show, exponent, isnegative)
            end
if type(show) == 'string' then
        else
-- Set singular using match because on some systems 0.99999999999999999 is 1.0.
            precision = -precision  -- #digits to zero (in addition to any digits after dot)
if exponent then
            local shift = 10 ^ precision
t.singular = (exponent == 1 and show:match('^10*$'))
            show = format('%.0f', outvalue/shift)
else
            if show ~= '0' then
t.singular = (show == '1' or show:match('^1%.0*$'))
                exponent = #show + precision
end
            end
else
        end
t.fraction_table = show
    end
t.singular = (outvalue <= 1)  -- cannot have 'fraction == 1', but if it were possible it would be singular
    if (show == '1' or show:match('^1%.0*$') ~= nil) and not isnegative then
end
        -- Use match because on some systems 0.99999999999999999 is 1.0.
t.raw_absvalue = outvalue  -- absolute value before rounding
        singular = true
return true, setmetatable(t, {
    end
__index = function (self, key)
    local t = format_number(parms, show, exponent, isnegative)
if key == 'absvalue' then
    t.singular = singular
-- Calculate absolute value after rounding, if needed.
    t.raw_absvalue = outvalue  -- absolute value before rounding
local clean, exponent = rawget(self, 'clean'), rawget(self, 'exponent')
    t.use_default_precision = use_default_precision
local value = tonumber(clean)  -- absolute value (any negative sign has been ignored)
    return true, setmetatable(t, {
if exponent then
        __index = function (self, key)
value = value * 10^exponent
            if key == 'absvalue' then
end
                -- Calculate absolute value after rounding, if needed.
rawset(self, key, value)
                local clean, exponent = rawget(self, 'clean'), rawget(self, 'exponent')
return value
                local value = tonumber(clean)  -- absolute value (any negative sign has been ignored)
end
                if exponent then
end })
                    value = value * 10^exponent
end
                end
 
                rawset(self, key, value)
function cvt_to_hand(parms, info, in_current, out_current)
                return value
-- Convert input to hands, inches.
            end
-- Return true, t where t is a table with the conversion results;
        end })
-- or return false, t where t is an error message table.
if parms.abbr_org == nil then
out_current.usename = true  -- default is to show name not symbol
end
local precision = parms.precision
local frac = out_current.frac
if not frac and precision and precision > 1 then
frac = (precision == 2) and 2 or 4
end
local out_next = out_current.out_next
if out_next then
-- Use magic knowledge to determine whether the next unit is inches without requiring i18n.
-- The following ensures that when the output combination "hand in" is used, the inches
-- value is rounded to match the hands value. Also, displaying say "61½" instead of 61.5
-- is better as 61.5 implies the value is not 61.4.
if out_next.exception == 'subunit_more_precision' then
out_next.frac = frac
end
end
-- Convert to inches; calculate hands from that.
local dummy_unit_table = { scale = out_current.scale / 4, frac = frac }
local success, outinfo = cvtround(parms, info, in_current, dummy_unit_table)
if not success then return false, outinfo end
local tfrac = outinfo.fraction_table
local inches = outinfo.raw_absvalue
if tfrac then
inches = floor(inches)  -- integer part only; fraction added later
else
inches = floor(inches + 0.5)  -- a hands measurement never shows decimals of an inch
end
local hands, inches = divide(inches, 4)
outinfo.absvalue = hands + inches/4  -- supposed to be the absolute rounded value, but this is close enough
local inchstr = tostring(inches)  -- '0', '1', '2' or '3'
if precision and precision <= 0 then  -- using negative or 0 for precision rounds to nearest hand
hands = floor(outinfo.raw_absvalue/4 + 0.5)
inchstr = ''
elseif tfrac then
-- Always show an integer before fraction (like "15.0½") because "15½" means 15-and-a-half hands.
inchstr = numdot .. format_fraction(parms, 'out', false, inchstr, tfrac.numstr, tfrac.denstr)
else
inchstr = numdot .. from_en(inchstr)
end
outinfo.show = outinfo.sign .. with_separator(parms, format('%.0f', hands)) .. inchstr
return true, outinfo
end
end


local function evaluate_condition(value, condition)
local function evaluate_condition(value, condition)
    -- Return true or false from applying a conditional expression to value,
-- Return true or false from applying a conditional expression to value,
    -- or throw an error if invalid.
-- or throw an error if invalid.
    -- A very limited set of expressions is supported:
-- A very limited set of expressions is supported:
    --    v < 9
--    v < 9
    --    v * 9 < 9
--    v * 9 < 9
    -- where
-- where
    --    'v' is replaced with value
--    'v' is replaced with value
    --    9 is any number (as defined by Lua tonumber)
--    9 is any number (as defined by Lua tonumber)
    --      only en digits are accepted
--      only en digits are accepted
    --    '<' can also be '<=' or '>' or '>='
--    '<' can also be '<=' or '>' or '>='
    -- In addition, the following form is supported:
-- In addition, the following form is supported:
    --    LHS and RHS
--    LHS and RHS
    -- where
-- where
    --    LHS, RHS = any of above expressions.
--    LHS, RHS = any of above expressions.
    local function compare(value, text)
local function compare(value, text)
        local arithop, factor, compop, limit = text:match('^%s*v%s*([*]?)(.-)([<>]=?)(.*)$')
local arithop, factor, compop, limit = text:match('^%s*v%s*([*]?)(.-)([<>]=?)(.*)$')
        if arithop == nil then
if arithop == nil then
            error('Invalid default expression', 0)
error('Invalid default expression', 0)
        elseif arithop == '*' then
elseif arithop == '*' then
            factor = tonumber(factor)
factor = tonumber(factor)
            if factor == nil then
if factor == nil then
                error('Invalid default expression', 0)
error('Invalid default expression', 0)
            end
end
            value = value * factor
value = value * factor
        end
end
        limit = tonumber(limit)
limit = tonumber(limit)
        if limit == nil then
if limit == nil then
            error('Invalid default expression', 0)
error('Invalid default expression', 0)
        end
end
        if compop == '<' then
if compop == '<' then
            return value < limit
return value < limit
        elseif compop == '<=' then
elseif compop == '<=' then
            return value <= limit
return value <= limit
        elseif compop == '>' then
elseif compop == '>' then
            return value > limit
return value > limit
        elseif compop == '>=' then
elseif compop == '>=' then
            return value >= limit
return value >= limit
        end
end
        error('Invalid default expression', 0)  -- should not occur
error('Invalid default expression', 0)  -- should not occur
    end
end
    local lhs, rhs = condition:match('^(.-%W)and(%W.*)')
local lhs, rhs = condition:match('^(.-%W)and(%W.*)')
    if lhs == nil then
if lhs == nil then
        return compare(value, condition)
return compare(value, condition)
    end
end
    return compare(value, lhs) and compare(value, rhs)
return compare(value, lhs) and compare(value, rhs)
end
end


local function get_default(value, unit_table)
local function get_default(value, unit_table)
    -- Return true, s where s = name of unit's default output unit,
-- Return true, s where s = name of unit's default output unit,
    -- or return false, t where t is an error message table.
-- or return false, t where t is an error message table.
    -- Some units have a default that depends on the input value
-- Some units have a default that depends on the input value
    -- (the first value if a range of values is used).
-- (the first value if a range of values is used).
    -- If '!' is in the default, the first bang-delimited field is an
-- If '!' is in the default, the first bang-delimited field is an
    -- expression that uses 'v' to represent the input value.
-- expression that uses 'v' to represent the input value.
    -- Example: 'v < 120 ! small ! big ! suffix' (suffix is optional)
-- Example: 'v < 120 ! small ! big ! suffix' (suffix is optional)
    -- evaluates 'v < 120' as a boolean with result
-- evaluates 'v < 120' as a boolean with result
    -- 'smallsuffix' if (value < 120), or 'bigsuffix' otherwise.
-- 'smallsuffix' if (value < 120), or 'bigsuffix' otherwise.
    -- Input must use en digits and '.' decimal mark.
-- Input must use en digits and '.' decimal mark.
    local default = default_exceptions[unit_table.defkey or unit_table.symbol] or unit_table.default
local default = data_code.default_exceptions[unit_table.defkey or unit_table.symbol] or unit_table.default
    if default == nil then
if not default then
        return false, { 'cvt_no_default', unit_table.symbol }
local per = unit_table.per
    end
if per then
    if default:find('!', 1, true) == nil then
local function a_default(v, u)
        return true, default
local success, ucode = get_default(v, u)
    end
if not success then
    local t = split(default, '!')
return '?'  -- an unlikely error has occurred; will cause lookup of default to fail
    if #t == 3 or #t == 4 then
end
        local success, result = pcall(evaluate_condition, value, t[1])
-- Attempt to use only the first unit if a combination or output multiple.
        if success then
-- This is not bulletproof but should work for most cases.
            default = result and t[2] or t[3]
-- Where it does not work, the convert will need to specify the wanted output unit.
            if #t == 4 then
local t = all_units[ucode]
                default = default .. t[4]
if t then
            end
local combo = t.combination
            return true, default
if combo then
        end
-- For a multiple like ftin, the "first" unit (ft) is last in the combination.
    end
local i = t.multiple and table_len(combo) or 1
    return false, { 'cvt_bad_default', unit_table.symbol }
ucode = combo[i]
end
else
-- Try for an automatically generated combination.
local item = ucode:match('^(.-)%+') or ucode:match('^(%S+)%s')
if all_units[item] then
return item
end
end
return ucode
end
local unit1, unit2 = per[1], per[2]
local def1 = (unit1 and a_default(value, unit1) or unit_table.vprefix or '')
local def2 = a_default(1, unit2)  -- 1 because per unit of denominator
return true, def1 .. '/' .. def2
end
return false, { 'cvt_no_default', unit_table.symbol }
end
if default:find('!', 1, true) == nil then
return true, default
end
local t = split(default, '!')
if #t == 3 or #t == 4 then
local success, result = pcall(evaluate_condition, value, t[1])
if success then
default = result and t[2] or t[3]
if #t == 4 then
default = default .. t[4]
end
return true, default
end
end
return false, { 'cvt_bad_default', unit_table.symbol }
end
end


local linked_pages  -- to record linked pages so will not link to the same page more than once
local linked_pages  -- to record linked pages so will not link to the same page more than once


local function make_link(link, id, link_key)
local function unlink(unit_table)
    -- Return wikilink "[[link|id]]", possibly abbreviated as in examples:
-- Forget that the given unit has previously been linked (if it has).
    --  [[Mile|mile]]  --> [[mile]]
-- That is needed when processing a range of inputs or outputs when an id
    --  [[Mile|miles]] --> [[mile]]s
-- for the first range value may have been evaluated, but only an id for
    -- However, just id is returned if:
-- the last value is displayed, and that id may need to be linked.
    -- * no link given (so caller does not need to check if a link was defined); or
linked_pages[unit_table.unitcode or unit_table] = nil
    -- * link has previously been used during the current convert (to avoid overlinking).
end
    -- Linking with a unit uses the unit table as the link key, which fails to detect
 
    -- overlinking for conversions like (each links "mile" twice):
local function make_link(link, id, unit_table)
    --  {{convert|1|impgal/mi|USgal/mi|lk=on}}
-- Return wikilink "[[link|id]]", possibly abbreviated as in examples:
    --  {{convert|1|l/km|impgal/mi USgal/mi|lk=on}}
--  [[Mile|mile]]  --> [[mile]]
    link_key = link_key or link -- use key if given (the key, but not the link, may be known when need to cancel a link record)
--  [[Mile|miles]] --> [[mile]]s
    if link == nil or link == '' or linked_pages[link_key] then
-- However, just id is returned if:
        return id
-- * no link given (so caller does not need to check if a link was defined); or
    end
-- * link has previously been used during the current convert (to avoid overlinking).
    linked_pages[link_key] = true
local link_key
    -- Following only works for language en, but it should be safe on other wikis,
if unit_table then
    -- and overhead of doing it generally does not seem worthwhile.
link_key = unit_table.unitcode or unit_table
    local l = link:sub(1, 1):lower() .. link:sub(2)
else
    if link == id or l == id then
link_key = link
        return '[[' .. id .. ']]'
end
    elseif link .. 's' == id or l .. 's' == id then
if not link or link == '' or linked_pages[link_key] then
        return '[[' .. id:sub(1, -2) .. ']]s'
return id
    else
end
        return '[[' .. link .. '|' .. id .. ']]'
linked_pages[link_key] = true
     end
-- Following only works for language en, but it should be safe on other wikis,
-- and overhead of doing it generally does not seem worthwhile.
local l = link:sub(1, 1):lower() .. link:sub(2)
if link == id or l == id then
return '[[' .. id .. ']]'
elseif link .. 's' == id or l .. 's' == id then
return '[[' .. id:sub(1, -2) .. ']]s'
else
return '[[' .. link .. '|' .. id .. ']]'
end
end
 
local function variable_name(clean, unit_table)
-- For slwiki, a unit name depends on the value.
-- Parameter clean is the unsigned rounded value in en digits, as a string.
-- Value            Source    Example for "m"
-- integer 1:        name1     meter  (also is the name of the unit)
-- integer 2:        var{1}    metra
-- integer 3 and 4:  var{2}    metri
-- integer else:    var{3}    metrov (0 and 5 or more)
-- real/fraction:    var{4}    metra
-- var{i} means the i'th field in unit_table.varname if it exists and has
-- an i'th field, otherwise name2.
-- Fields are separated with "!" and are not empty.
-- A field for a unit using an SI prefix has the prefix name inserted,
-- replacing '#' if found, or before the field otherwise.
local vname
if clean == '1' then
vname = unit_table.name1
elseif unit_table.varname then
local i
if clean == '2' then
i = 1
elseif clean == '3' or clean == '4' then
i = 2
elseif clean:find('.', 1, true) then
i = 4
else
i = 3
end
if i > 1 and varname == 'pl' then
i = i - 1
end
vname = split(unit_table.varname, '!')[i]
end
if vname then
local si_name = rawget(unit_table, 'si_name') or ''
local pos = vname:find('#', 1, true)
if pos then
vname = vname:sub(1, pos - 1) .. si_name .. vname:sub(pos + 1)
else
vname = si_name .. vname
end
return vname
end
return unit_table.name2
end
end


local function linked_id(unit_table, key_id, want_link)
local function linked_id(parms, unit_table, key_id, want_link, clean)
    -- Return final unit id (symbol or name), optionally with a wikilink,
-- Return final unit id (symbol or name), optionally with a wikilink,
    -- and update unit_table.sep if required.
-- and update unit_table.sep if required.
    -- key_id is one of: 'symbol', 'sym_us', 'name1', 'name1_us', 'name2', 'name2_us'.
-- key_id is one of: 'symbol', 'sym_us', 'name1', 'name1_us', 'name2', 'name2_us'.
    local abbr_on = (key_id == 'symbol' or key_id == 'sym_us')
local abbr_on = (key_id == 'symbol' or key_id == 'sym_us')
    if abbr_on and want_link then
if abbr_on and want_link then
        local symlink = rawget(unit_table, 'symlink')
local symlink = rawget(unit_table, 'symlink')
        if symlink then
if symlink then
            return symlink  -- for exceptions that have the linked symbol built-in
return symlink  -- for exceptions that have the linked symbol built-in
        end
end
    end
end
    local multiplier = rawget(unit_table, 'multiplier')
local multiplier = rawget(unit_table, 'multiplier')
    local per = unit_table.per
local per = unit_table.per
    if per then
if per then
        local unit1 = per[1]  -- top unit_table, or nil
local paren1, paren2 = '', ''  -- possible parentheses around bottom unit
        local unit2 = per[2]  -- bottom unit_table
local unit1 = per[1]  -- top unit_table, or nil
        if abbr_on then
local unit2 = per[2]  -- bottom unit_table
            if not unit1 then
if abbr_on then
                unit_table.sep = ''  -- no separator in "$2/acre"
if not unit1 then
            end
unit_table.sep = ''  -- no separator in "$2/acre"
            if not want_link then
end
                local symbol = unit_table.symbol_raw
if not want_link then
                if symbol then
local symbol = unit_table.symbol_raw
                    return symbol  -- for exceptions that have the symbol built-in
if symbol then
                end
return symbol  -- for exceptions that have the symbol built-in
            end
end
        end
end
        local key_id2  -- unit2 is always singular
if (unit2.symbol):find('⋅', 1, true) then
        if key_id == 'name2' then
paren1, paren2 = '(', ')'
            key_id2 = 'name1'
end
        elseif key_id == 'name2_us' then
end
            key_id2 = 'name1_us'
local key_id2  -- unit2 is always singular
        else
if key_id == 'name2' then
            key_id2 = key_id
key_id2 = 'name1'
        end
elseif key_id == 'name2_us' then
        local result
key_id2 = 'name1_us'
        if abbr_on then
else
            result = '/'
key_id2 = key_id
        elseif unit1 then
end
            result = ' per '
local result
        else
if abbr_on then
            result = 'per '
result = '/'
        end
elseif omitsep then
        if unit1 then
result = per_word
            result = linked_id(unit1, key_id, want_link) .. result
elseif unit1 then
        end
result = ' ' .. per_word .. ' '
        return result .. linked_id(unit2, key_id2, want_link)
else
    end
result = per_word .. ' '
    if multiplier then
end
        -- A multiplier (like "100" in "100km") forces the unit to be plural.
if want_link and unit_table.link then
        if abbr_on then
if abbr_on or not varname then
            multiplier = multiplier .. '&nbsp;'
result = (unit1 and linked_id(parms, unit1, key_id, false, clean) or '') .. result .. linked_id(parms, unit2, key_id2, false, '1')
        else
else
            multiplier = multiplier .. ' '
result = (unit1 and variable_name(clean, unit1) or '') .. result .. variable_name('1', unit2)
            if key_id == 'name1' then
end
                key_id = 'name2'
if omit_separator(result) then
            elseif key_id == 'name1_us' then
unit_table.sep = ''
                key_id = 'name2_us'
end
            end
return make_link(unit_table.link, result, unit_table)
        end
end
    else
if unit1 then
        multiplier = ''
result = linked_id(parms, unit1, key_id, want_link, clean) .. result
    end
if unit1.sep then
    local id = unit_table.fixed_name or unit_table[key_id]
unit_table.sep = unit1.sep
    if want_link then
end
        local link = link_exceptions[unit_table.symbol] or unit_table.link
elseif omitsep then
        if link then
unit_table.sep = ''
            local before = ''
end
            local i = unit_table.customary
return result .. paren1 .. linked_id(parms, unit2, key_id2, want_link, '1') .. paren2
            if i == 1 and unit_table.sp_us then
end
                i = 2  -- show "U.S." not "US"
if multiplier then
            end
-- A multiplier (like "100" in "100km") forces the unit to be plural.
            if i == 3 and abbr_on then
multiplier = from_en(multiplier)
                i = 4  -- abbreviate "imperial" to "imp"
if not omitsep then
            end
multiplier = multiplier .. (abbr_on and '&nbsp;' or ' ')
            local customary = customary_units[i]
end
            if customary then
if not abbr_on then
                -- LATER: This works for language en only, but it's esoteric so ignore for now.
if key_id == 'name1' then
                local pertext
key_id = 'name2'
                if id:sub(1, 1) == '/' then
elseif key_id == 'name1_us' then
                    -- Want unit "/USgal" to display as "/U.S. gal", not "U.S. /gal".
key_id = 'name2_us'
                    pertext = '/'
end
                    id = id:sub(2)
end
                elseif id:sub(1, 4) == 'per ' then
else
                    -- Similarly want "per U.S. gallon", not "U.S. per gallon" (but in practice this is unlikely to be used).
multiplier = ''
                    pertext = 'per '
end
                    id = id:sub(5)
local id = unit_table.fixed_name or ((varname and not abbr_on) and variable_name(clean, unit_table) or unit_table[key_id])
                else
if omit_separator(id) then
                    pertext = ''
unit_table.sep = ''
                end
end
                -- Omit any "US"/"U.S."/"imp"/"imperial" from start of id since that will be inserted.
if want_link then
                local removes = (i < 3) and { 'US&nbsp;', 'US ', 'U.S.&nbsp;', 'U.S. ' } or { 'imp&nbsp;', 'imp ', 'imperial ' }
local link = data_code.link_exceptions[unit_table.linkey or unit_table.symbol] or unit_table.link
                for _, prefix in ipairs(removes) do
if link then
                    local plen = #prefix
local before = ''
                    if id:sub(1, plen) == prefix then
local i = unit_table.customary
                        id = id:sub(plen + 1)
if i == 1 and parms.opt_sp_us then
                        break
i = 2  -- show "U.S." not "US"
                    end
end
                end
if i == 3 and abbr_on then
                before = pertext .. make_link(customary.link, customary[1]) .. ' '
i = 4  -- abbreviate "imperial" to "imp"
            end
end
            id = before .. make_link(link, id, unit_table)
local customary = text_code.customary_units[i]
        end
if customary then
    end
-- LATER: This works for language en only, but it's esoteric so ignore for now.
    return multiplier .. id
local pertext
if id:sub(1, 1) == '/' then
-- Want unit "/USgal" to display as "/U.S. gal", not "U.S. /gal".
pertext = '/'
id = id:sub(2)
elseif id:sub(1, 4) == 'per ' then
-- Similarly want "per U.S. gallon", not "U.S. per gallon" (but in practice this is unlikely to be used).
pertext = 'per '
id = id:sub(5)
else
pertext = ''
end
-- Omit any "US"/"U.S."/"imp"/"imperial" from start of id since that will be inserted.
local removes = (i < 3) and { 'US&nbsp;', 'US ', 'U.S.&nbsp;', 'U.S. ' } or { 'imp&nbsp;', 'imp ', 'imperial ' }
for _, prefix in ipairs(removes) do
local plen = #prefix
if id:sub(1, plen) == prefix then
id = id:sub(plen + 1)
break
end
end
before = pertext .. make_link(customary.link, customary[1]) .. ' '
end
id = before .. make_link(link, id, unit_table)
end
end
return multiplier .. id
end
end


local function make_id(parms, which, unit_table)
local function make_id(parms, which, unit_table)
    -- Return id, f where
-- Return id, f where
    --  id = unit name or symbol, possibly modified
--  id = unit name or symbol, possibly modified
    --  f = true if id is a name, or false if id is a symbol
--  f = true if id is a name, or false if id is a symbol
    -- using 1st or 2nd values (which), and for 'in' or 'out' (unit_table.inout).
-- using the value for index 'which', and for 'in' or 'out' (unit_table.inout).
    -- Result is '' if no symbol/name is to be used.
-- Result is '' if no symbol/name is to be used.
    -- In addition, set unit_table.sep = ' ' or '&nbsp;' or ''
-- In addition, set unit_table.sep = ' ' or '&nbsp;' or ''
    -- (the separator that caller will normally insert before the id).
-- (the separator that caller will normally insert before the id).
    if parms.opt_values then
if parms.opt_values then
        unit_table.sep = ''
unit_table.sep = ''
        return ''
return ''
    end
end
    local inout = unit_table.inout
local inout = unit_table.inout
    local valinfo = unit_table.valinfo
local info = unit_table.valinfo[which]
    local abbr_org = parms.abbr_org
local abbr_org = parms.abbr_org
    local adjectival = parms.opt_adjectival
local adjectival = parms.opt_adjectival
    local disp = parms.disp
local lk = parms.lk
    local lk = parms.lk
local want_link = (lk == 'on' or lk == inout)
    local usename = unit_table.usename
local usename = unit_table.usename
    local singular = valinfo[which].singular
local singular = info.singular
    if usename then
local want_name
        -- Old template does something like this.
if usename then
        if lk == 'on' or lk == inout then
want_name = true
            -- A linked unit uses the standard singular.
else
        else
if abbr_org == nil then
            -- Set non-standard singular.
if parms.wantname then
            local flipped = parms.opt_flip
want_name = true
            if inout == 'in' then
end
                if not adjectival and (abbr_org == 'out' or flipped) then
if unit_table.usesymbol then
                    local value = valinfo[which].value
want_name = false
                    singular = (0 < value and value < 1.0001)
end
                end
end
            else
if want_name == nil then
                if (abbr_org == 'on') or
local abbr = parms.abbr
                (not flipped and (abbr_org == nil or abbr_org == 'out')) or
if abbr == 'on' or abbr == inout or (abbr == 'mos' and inout == 'out') then
                (flipped and abbr_org == 'in') then
want_name = false
                    singular = (valinfo[which].absvalue < 1.0001 and
else
                                not valinfo[which].is_scientific)
want_name = true
                end
end
            end
end
        end
end
    end
local key
    local want_name
if want_name then
    if usename then
if lk == nil and unit_table.builtin == 'hand' then
        want_name = true
want_link = true
    else
end
        if abbr_org == nil then
if parms.opt_use_nbsp then
            if disp == 'br' or disp == 'or' or disp == 'slash' then
unit_table.sep = '&nbsp;'
                want_name = true
else
            end
unit_table.sep = ' '
            if unit_table.utype == 'temperature' or unit_table.utype == 'temperature change' then
end
                if not (unit_table.exception == 'temperature') then
if parms.opt_singular then
                    want_name = false
local value
                end
if inout == 'in' then
            end
value = info.value
        end
else
        if want_name == nil then
value = info.absvalue
            local abbr = parms.abbr
end
            if abbr == 'on' or abbr == inout or (abbr == 'mos' and inout == 'out') then
if value then  -- some unusual units do not always set value field
                want_name = false
value = abs(value)
            else
singular = (0 < value and value < 1.0001)
                want_name = true
end
            end
end
        end
if unit_table.engscale then
    end
-- engscale: so "|1|e3kg" gives "1 thousand kilograms" (plural)
    local key
singular = false
    if want_name then
end
        if parms.opt_use_nbsp then
key = (adjectival or singular) and 'name1' or 'name2'
            unit_table.sep = '&nbsp;'
if parms.opt_sp_us then
        else
key = key .. '_us'
            unit_table.sep = ' '
end
        end
else
        if parms.opt_singular then
if unit_table.builtin == 'hand' then
            local value
if parms.opt_hand_hh then
            if inout == 'in' then
unit_table.symbol = 'hh'  -- LATER: might want i18n applied to this
                value = valinfo[which].value
end
            else
end
                value = valinfo[which].absvalue
unit_table.sep = '&nbsp;'
            end
key = parms.opt_sp_us and 'sym_us' or 'symbol'
            if value then  -- some unusual units do not always set value field
end
                value = abs(value)
return linked_id(parms, unit_table, key, want_link, info.clean), want_name
                singular = (0 < value and value < 1.0001)
            end
        end
        if unit_table.engscale or parms.is_range_x then
            -- engscale: so "|1|e3kg" gives "1 thousand kilograms" (plural)
            -- is_range_x: so "|0.5|x|0.9|mi" gives "0.5 by 0.9 miles" (plural)
            singular = false
        end
        key = (adjectival or singular) and 'name1' or 'name2'
        if unit_table.sp_us then
            key = key .. '_us'
        end
    else
        unit_table.sep = '&nbsp;'
        key = unit_table.sp_us and 'sym_us' or 'symbol'
    end
    return linked_id(unit_table, key, lk == 'on' or lk == inout), want_name
end
end


local function decorate_value(parms, unit_table, which)
local function decorate_value(parms, unit_table, which, number_word)
    -- If needed, update unit_table so values will be shown with extra information.
-- If needed, update unit_table so values will be shown with extra information.
    -- For consistency with the old template (but different from fmtpower),
-- For consistency with the old template (but different from fmtpower),
    -- the style to display powers of 10 includes "display:none" to allow some
-- the style to display powers of 10 includes "display:none" to allow some
    -- browsers to copy, for example, "10³" as "10^3", rather than as "103".
-- browsers to copy, for example, "10³" as "10^3", rather than as "103".
    local engscale = unit_table.engscale
local info
    if engscale then
local engscale = unit_table.engscale
        local inout = unit_table.inout
local prefix = unit_table.vprefix
        local info = unit_table.valinfo[which]
if engscale or prefix then
        local abbr = parms.abbr
info = unit_table.valinfo[which]
        if abbr == 'on' or abbr == inout then
if info.decorated then
            info.show = info.show ..
return  -- do not redecorate if repeating convert
                '<span style="margin-left:0.2em">×<span style="margin-left:0.1em">' ..
end
                from_en('10') ..
info.decorated = true
                '</span></span><s style="display:none">^</s><sup>' ..
if engscale then
                from_en(tostring(engscale.exponent)) .. '</sup>'
local inout = unit_table.inout
        else
local abbr = parms.abbr
            local number_id
if (abbr == 'on' or abbr == inout) and not parms.number_word then
            local lk = parms.lk
info.show = info.show ..
            if lk == 'on' or lk == inout then
'<span style="margin-left:0.2em">×<span style="margin-left:0.1em">' ..
                number_id = make_link(engscale.link, engscale[1])
from_en('10') ..
            else
'</span></span><s style="display:none">^</s><sup>' ..
                number_id = engscale[1]
from_en(tostring(engscale.exponent)) .. '</sup>'
            end
elseif number_word then
            -- WP:NUMERAL recommends "&nbsp;" in values like "12 million".
local number_id
            info.show = info.show .. (parms.opt_adjectival and '-' or '&nbsp;') .. number_id
local lk = parms.lk
        end
if lk == 'on' or lk == inout then
    end
number_id = make_link(engscale.link, engscale[1])
    local prefix = unit_table.vprefix
else
    if prefix then
number_id = engscale[1]
        local info = unit_table.valinfo[which]
end
        info.show = prefix .. info.show
-- WP:NUMERAL recommends "&nbsp;" in values like "12 million".
    end
info.show = info.show .. (parms.opt_adjectival and '-' or '&nbsp;') .. number_id
end
end
if prefix then
info.show = prefix .. info.show
end
end
end
end


local function process_input(parms, in_current)
local function process_input(parms, in_current)
    -- Processing required once per conversion.
-- Processing required once per conversion.
    -- Return block of text to represent input (value/unit).
-- Return block of text to represent input (value/unit).
    if parms.opt_output_only or parms.opt_output_number_only or parms.opt_output_unit_only then
if parms.opt_output_only or parms.opt_output_number_only or parms.opt_output_unit_only then
        parms.joins = { '', '' }
parms.joins = { '', '' }
        return ''
return ''
    end
end
    local first_unit
local first_unit
    local composite = in_current.composite  -- nil or table of units
local composite = in_current.composite  -- nil or table of units
    if composite then
if composite then
        first_unit = composite[1]
first_unit = composite[1]
    else
else
        first_unit = in_current
first_unit = in_current
    end
end
    local id1, want_name = make_id(parms, 1, first_unit)
local id1, want_name = make_id(parms, 1, first_unit)
    local sep = first_unit.sep  -- separator between value and unit, set by make_id
local sep = first_unit.sep  -- separator between value and unit, set by make_id
    local preunit = parms.preunit1
local preunit = parms.preunit1
    if preunit then
if preunit then
        sep = ''  -- any separator is included in preunit
sep = ''  -- any separator is included in preunit
    else
else
        preunit = ''
preunit = ''
    end
end
    if parms.opt_input_unit_only then
if parms.opt_input_unit_only then
        parms.joins = { '', '' }
parms.joins = { '', '' }
        if composite then
if composite then
            local parts = { id1 }
local parts = { id1 }
            for i, unit in ipairs(composite) do
for i, unit in ipairs(composite) do
                if i > 1 then
if i > 1 then
                    table.insert(parts, (make_id(parms, 1, unit)))
table.insert(parts, (make_id(parms, 1, unit)))
                end
end
            end
end
            id1 = table.concat(parts, ' ')
id1 = table.concat(parts, ' ')
        end
end
        if want_name and parms.opt_adjectival then
if want_name and parms.opt_adjectival then
            return preunit .. hyphenated(id1)
return preunit .. hyphenated(id1)
        end
end
        return  preunit .. id1
return  preunit .. id1
    end
end
    local abbr = parms.abbr
if parms.opt_also_symbol and not composite and not parms.opt_flip then
    local disp = parms.disp
local join1 = parms.joins[1]
    if disp == nil then  -- special case for the most common setting
if join1 == ' (' or join1 == ' [' then
        parms.joins = disp_joins['b']
parms.joins = { ' [' .. first_unit[parms.opt_sp_us and 'sym_us' or 'symbol'] .. ']' .. join1 , parms.joins[2] }
    elseif disp ~= 'x' then
end
        -- Old template does this.
end
        if disp == 'slash' then
if in_current.builtin == 'mach' and first_unit.sep ~= '' then -- '' means omitsep with non-enwiki name
            if parms.abbr_org == nil then
local prefix = id1 .. '&nbsp;'
                disp = 'slash-nbsp'
local range = parms.range
            elseif abbr == 'in' or abbr == 'out' then
local valinfo = first_unit.valinfo
                disp = 'slash-sp'
local result = prefix .. valinfo[1].show
            else
if range then
                disp = 'slash-nosp'
-- For simplicity and because more not needed, handle one range item only.
            end
local prefix2 = make_id(parms, 2, first_unit) .. '&nbsp;'
        elseif disp == 'sqbr' then
result = range_text(range[1], want_name, parms, result, prefix2 .. valinfo[2].show, 'in')
            if abbr == 'on' then
end
                disp = 'sqbr-nbsp'
return preunit .. result
            else
end
                disp = 'sqbr-sp'
if composite then
            end
-- Simplify: assume there is no range, and no decoration.
        end
local mid = (not parms.opt_flip) and parms.mid or ''
        parms.joins = disp_joins[disp] or disp_joins['b']
local sep1 = '&nbsp;'
    end
local sep2 = ' '
    if parms.opt_also_symbol and not composite then
if parms.opt_adjectival and want_name then
        local join1 = parms.joins[1]
sep1 = '-'
        if join1 == ' (' or join1 == ' [' then
sep2 = '-'
            parms.joins = { join1 .. first_unit[first_unit.sp_us and 'sym_us' or 'symbol'] .. ', ', parms.joins[2] }
end
        end
if omitsep and sep == '' then
    end
-- Testing the id of the most significant unit should be sufficient.
    if in_current.builtin == 'mach' then
sep1 = ''
        local prefix = id1 .. '&nbsp;'
sep2 = ''
        local range = parms.range
end
        local valinfo = first_unit.valinfo
local parts = { first_unit.valinfo[1].show .. sep1 .. id1 }
        local result = prefix .. valinfo[1].show
for i, unit in ipairs(composite) do
        if range then
if i > 1 then
            local prefix2 = make_id(parms, 2, first_unit) .. '&nbsp;'
table.insert(parts, unit.valinfo[1].show .. sep1 .. (make_id(parms, 1, unit)))
            result = range_text(range, want_name, parms, result, prefix2 .. valinfo[2].show)
end
        end
end
        return preunit .. result
return table.concat(parts, sep2) .. mid
    end
end
    if composite then
local add_unit = (parms.abbr == 'mos') or
        -- Simplify: assume there is no range, and no decoration.
parms[parms.opt_flip and 'out_range_x' or 'in_range_x'] or
        local mid = ''
(not want_name and parms.abbr_range_x)
        local sep1 = '&nbsp;'
local range = parms.range
        local sep2 = ' '
if range and not add_unit then
        if parms.opt_adjectival then
unlink(first_unit)
            if not parms.opt_flip then
end
                mid = parms.mid or ''
local id = range and make_id(parms, range.n + 1, first_unit) or id1
            end
local extra, was_hyphenated = hyphenated_maybe(parms, want_name, sep, id, 'in')
            if want_name then
if was_hyphenated then
                sep1 = '-'
add_unit = false
                sep2 = '-'
end
            end
local result
        end
local valinfo = first_unit.valinfo
        local parts = { first_unit.valinfo[1].show .. sep1 .. id1 }
if range then
        for i, unit in ipairs(composite) do
for i = 0, range.n do
            if i > 1 then
local number_word
                table.insert(parts, unit.valinfo[1].show .. sep1 .. (make_id(parms, 1, unit)))
if i == range.n then
            end
add_unit = false
        end
number_word = true
        return table.concat(parts, sep2) .. mid
end
    end
decorate_value(parms, first_unit, i+1, number_word)
    local result, mos
local show = valinfo[i+1].show
    local range = parms.range
if add_unit then
    if range then
show = show .. first_unit.sep .. (i == 0 and id1 or make_id(parms, i+1, first_unit))
        mos = (abbr == 'mos')
end
        if not (mos or (parms.is_range_x and not want_name)) then
if i == 0 then
            linked_pages[first_unit] = nil  -- so the second and only id will be linked, if wanted
result = show
        end
else
    end
result = range_text(range[i], want_name, parms, result, show, 'in')
    local id = (range == nil) and id1 or make_id(parms, 2, first_unit)
end
    local extra, was_hyphenated = hyphenated_maybe(parms, want_name, sep, id, 'in')
end
    if mos and was_hyphenated then
else
        mos = false -- suppress repeat of unit in a range
decorate_value(parms, first_unit, 1, true)
        if linked_pages[first_unit] then
result = valinfo[1].show
            linked_pages[first_unit] = nil
end
            id = make_id(parms, 2, first_unit)
return result .. preunit .. extra
            extra = hyphenated_maybe(parms, want_name, sep, id, 'in')
        end
    end
    local valinfo = first_unit.valinfo
    if range then
        local sep1 = first_unit.sep
        if mos then
            decorate_value(parms, in_current, 1)
            decorate_value(parms, in_current, 2)
            result = valinfo[1].show .. sep1 .. id1
        elseif parms.is_range_x and not want_name then
            if abbr == 'in' or abbr == 'on' then
                decorate_value(parms, in_current, 1)
            end
            decorate_value(parms, in_current, 2)
            result = valinfo[1].show .. sep1 .. id1
        else
            if abbr == 'in' or abbr == 'on' then
                decorate_value(parms, in_current, 1)
            end
            decorate_value(parms, in_current, 2)
            result = valinfo[1].show
        end
        result = range_text(range, want_name, parms, result, valinfo[2].show)
    else
        decorate_value(parms, first_unit, 1)
        result = valinfo[1].show
    end
    return result .. preunit .. extra
end
end


local function process_one_output(parms, out_current)
local function process_one_output(parms, out_current)
    -- Processing required for each output unit.
-- Processing required for each output unit.
    -- Return block of text to represent output (value/unit).
-- Return block of text to represent output (value/unit).
    local id1, want_name = make_id(parms, 1, out_current)
local inout = out_current.inout  -- normally 'out' but can be 'in' for order=out
    local sep = out_current.sep  -- set by make_id
local id1, want_name = make_id(parms, 1, out_current)
    local preunit = parms.preunit2
local sep = out_current.sep  -- set by make_id
    if preunit then
local preunit = parms.preunit2
        sep = ''  -- any separator is included in preunit
if preunit then
    else
sep = ''  -- any separator is included in preunit
        preunit = ''
else
    end
preunit = ''
    if parms.opt_output_unit_only then
end
        if want_name and parms.opt_adjectival then
if parms.opt_output_unit_only then
            return preunit .. hyphenated(id1)
if want_name and parms.opt_adjectival then
        end
return preunit .. hyphenated(id1)
        return preunit .. id1
end
    end
return preunit .. id1
    if out_current.builtin == 'mach' then
end
        local prefix = id1 .. '&nbsp;'
if out_current.builtin == 'mach' and out_current.sep ~= '' then -- '' means omitsep with non-enwiki name
        local range = parms.range
local prefix = id1 .. '&nbsp;'
        local valinfo = out_current.valinfo
local range = parms.range
        local result = prefix .. valinfo[1].show
local valinfo = out_current.valinfo
        if range then
local result = prefix .. valinfo[1].show
            result = range_text(range, want_name, parms, result, prefix .. valinfo[2].show)
if range then
        end
-- For simplicity and because more not needed, handle one range item only.
        return preunit .. result
result = range_text(range[1], want_name, parms, result, prefix .. valinfo[2].show, inout)
    end
end
    local result
return preunit .. result
    local range = parms.range
end
    if range then
local add_unit = (parms[parms.opt_flip and 'in_range_x' or 'out_range_x'] or
        if not (parms.is_range_x and not want_name) then
(not want_name and parms.abbr_range_x)) and
            linked_pages[out_current] = nil  -- so the second and only id will be linked, if wanted
not parms.opt_output_number_only
        end
local range = parms.range
    end
if range and not add_unit then
    local id = (range == nil) and id1 or make_id(parms, 2, out_current)
unlink(out_current)
    local extra = hyphenated_maybe(parms, want_name, sep, id, 'out')
end
    local valinfo = out_current.valinfo
local id = range and make_id(parms, range.n + 1, out_current) or id1
    if range then
local extra, was_hyphenated = hyphenated_maybe(parms, want_name, sep, id, inout)
        local sep1 = out_current.sep
if was_hyphenated then
        local abbr = parms.abbr
add_unit = false
        if parms.is_range_x and not want_name then
end
            if abbr == 'out' or abbr == 'on' then
local result
                decorate_value(parms, out_current, 1)
local valinfo = out_current.valinfo
            end
if range then
            decorate_value(parms, out_current, 2)
for i = 0, range.n do
            result = valinfo[1].show .. sep1 .. id1
local number_word
        else
if i == range.n then
            if abbr == 'out' or abbr == 'on' then
add_unit = false
                decorate_value(parms, out_current, 1)
number_word = true
            end
end
            decorate_value(parms, out_current, 2)
decorate_value(parms, out_current, i+1, number_word)
            result = valinfo[1].show
local show = valinfo[i+1].show
        end
if add_unit then
        result = range_text(range, want_name, parms, result, valinfo[2].show)
show = show .. out_current.sep .. (i == 0 and id1 or make_id(parms, i+1, out_current))
    else
end
        decorate_value(parms, out_current, 1)
if i == 0 then
        result = valinfo[1].show
result = show
    end
else
    if parms.opt_output_number_only then
result = range_text(range[i], want_name, parms, result, show, inout)
        return result
end
    end
end
    return result .. preunit .. extra
else
decorate_value(parms, out_current, 1, true)
result = valinfo[1].show
end
if parms.opt_output_number_only then
return result
end
return result .. preunit .. extra
end
end


local function make_output_single(parms, in_unit_table, out_unit_table)
local function make_output_single(parms, in_unit_table, out_unit_table)
    -- Return true, item where item = wikitext of the conversion result
-- Return true, item where item = wikitext of the conversion result
    -- for a single output (which is not a combination or a multiple);
-- for a single output (which is not a combination or a multiple);
    -- or return false, t where t is an error message table.
-- or return false, t where t is an error message table.
    local success, info1, info2
if parms.opt_order_out and in_unit_table.unitcode == out_unit_table.unitcode then
    local valinfo = in_unit_table.valinfo
out_unit_table.valinfo = in_unit_table.valinfo
    success, info1 = cvtround(parms, valinfo[1], in_unit_table, out_unit_table)
else
    if not success then return false, info1 end
out_unit_table.valinfo = collection()
    success, info2 = cvtround(parms, valinfo[2], in_unit_table, out_unit_table)
for _, v in ipairs(in_unit_table.valinfo) do
    if not success then return false, info2 end
local success, info = cvtround(parms, v, in_unit_table, out_unit_table)
    out_unit_table.valinfo = { info1, info2 }
if not success then return false, info end
    return true, process_one_output(parms, out_unit_table)
out_unit_table.valinfo:add(info)
end
end
return true, process_one_output(parms, out_unit_table)
end
end


local function make_output_multiple(parms, in_unit_table, out_unit_table)
local function make_output_multiple(parms, in_unit_table, out_unit_table)
    -- Return true, item where item = wikitext of the conversion result
-- Return true, item where item = wikitext of the conversion result
    -- for an output which is a multiple (like 'ftin');
-- for an output which is a multiple (like 'ftin');
    -- or return false, t where t is an error message table.
-- or return false, t where t is an error message table.
    local multiple = out_unit_table.multiple  -- table of scaling factors (will not be nil)
local inout = out_unit_table.inout  -- normally 'out' but can be 'in' for order=out
    local combos = out_unit_table.combination  -- table of unit tables (will not be nil)
local multiple = out_unit_table.multiple  -- table of scaling factors (will not be nil)
    local abbr = parms.abbr
local combos = out_unit_table.combination  -- table of unit tables (will not be nil)
    local abbr_org = parms.abbr_org
local abbr = parms.abbr
    local disp = parms.disp
local abbr_org = parms.abbr_org
    local want_name = (abbr_org == nil and (disp == 'or' or disp == 'slash')) or
local disp = parms.disp
                      not (abbr == 'on' or abbr == 'out' or abbr == 'mos')
local want_name = (abbr_org == nil and (disp == 'or' or disp == 'slash')) or
    local want_link = (parms.lk == 'on' or parms.lk == 'out')
not (abbr == 'on' or abbr == inout or abbr == 'mos')
    local mid = ''
local want_link = (parms.lk == 'on' or parms.lk == inout)
    local sep1 = '&nbsp;'
local mid = parms.opt_flip and parms.mid or ''
    local sep2 = ' '
local sep1 = '&nbsp;'
    if parms.opt_adjectival then
local sep2 = ' '
        if parms.opt_flip then
if parms.opt_adjectival and want_name then
            mid = parms.mid or ''
sep1 = '-'
        end
sep2 = '-'
        if want_name then
end
            sep1 = '-'
local do_spell = parms.opt_spell_out
            sep2 = '-'
parms.opt_spell_out = nil  -- so the call to cvtround does not spell the value
        end
local function make_result(info, isfirst)
    end
local fmt, outvalue, sign
    local function make_result(info)
local results = {}
        local outvalue, sign, fmt
for i = 1, #combos do
        local results = {}
local tfrac, thisvalue, strforce
        for i = 1, #combos do
local out_current = combos[i]
            local thisvalue
out_current.inout = inout
            local out_current = combos[i]
local scale = multiple[i]
            out_current.inout = 'out'
if i == 1 then  -- least significant unit ('in' from 'ftin')
            local scale = multiple[i]
local decimals
            if i == 1 then  -- least significant unit ('in' from 'ftin')
out_current.frac = out_unit_table.frac
                local success, outinfo = cvtround(parms, info, in_unit_table, out_current)
local success, outinfo = cvtround(parms, info, in_unit_table, out_current)
                if not success then return false, outinfo end
if not success then return false, outinfo end
                sign = outinfo.sign
if isfirst then
                local fraction = (outinfo.show):match('[' .. numdot .. '](.*)') or ''  -- outinfo.show is in local language
out_unit_table.valinfo = { outinfo }  -- in case output value of first least significant unit is needed
                fmt = '%.' .. ulen(fraction) .. 'f'  -- to reproduce precision
end
                if fraction == '' then
sign = outinfo.sign
                    outvalue = floor(outinfo.raw_absvalue + 0.5)  -- keep all integer digits of least significant unit
tfrac = outinfo.fraction_table
                else
if outinfo.is_scientific then
                    outvalue = outinfo.absvalue
strforce = outinfo.show
                end
decimals = ''
            end
elseif tfrac then
            if scale then
decimals = ''
                outvalue, thisvalue = floor(outvalue / scale), outvalue % scale
else
            else
local show = outinfo.show -- number as a string in local language
                thisvalue = outvalue
local p1, p2 = show:find(numdot, 1, true)
            end
decimals = p1 and show:sub(p2 + 1) or ''  -- text after numdot, if any
            local id
end
            if want_name then
fmt = '%.' .. ulen(decimals) .. 'f'  -- to reproduce precision
                id = out_current[(thisvalue == 1) and 'name1' or 'name2']
if decimals == '' then
            else
if tfrac then
                id = out_current['symbol']
outvalue = floor(outinfo.raw_absvalue)  -- integer part only; fraction added later
            end
else
            if want_link then
outvalue = floor(outinfo.raw_absvalue + 0.5)  -- keep all integer digits of least significant unit
                local link = out_current.link
end
                if link then
else
                    id = make_link(link, id, out_current)
outvalue = outinfo.absvalue
                end
end
            end
end
            local strval = (thisvalue == 0) and from_en('0') or with_separator(parms, format(fmt, thisvalue))
if scale then
            table.insert(results, strval .. sep1 .. id)
outvalue, thisvalue = divide(outvalue, scale)
            if outvalue == 0 then
else
                break
thisvalue = outvalue
            end
end
            fmt = '%.0f'  -- only least significant unit can have a fraction
local id
        end
if want_name then
        local reversed, count = {}, #results
if varname then
        for i = 1, count do
local clean
            reversed[i] = results[count + 1 - i]
if strforce or tfrac then
        end
clean = '.1'  -- dummy value to force name for floating point
        return true, sign .. table.concat(reversed, sep2)
else
    end
clean = format(fmt, thisvalue)
    local valinfo = in_unit_table.valinfo
end
    local success, result = make_result(valinfo[1])
id = variable_name(clean, out_current)
    if not success then return false, result end
else
    local range = parms.range
local key = 'name2'
    if range then
if parms.opt_adjectival then
        local success, result2 = make_result(valinfo[2])
key = 'name1'
        if not success then return false, result2 end
elseif tfrac then
        result = range_text(range, want_name, parms, result, result2)
if thisvalue == 0 then
    end
key = 'name1'
    return true, result .. mid
end
elseif parms.opt_singular then
if 0 < thisvalue and thisvalue < 1.0001 then
key = 'name1'
end
else
if thisvalue == 1 then
key = 'name1'
end
end
id = out_current[key]
end
else
id = out_current['symbol']
end
if i == 1 and omit_separator(id) then
-- Testing the id of the least significant unit should be sufficient.
sep1 = ''
sep2 = ''
end
if want_link then
local link = out_current.link
if link then
id = make_link(link, id, out_current)
end
end
local strval
local spell_inout = (i == #combos or outvalue == 0) and inout or ''  -- trick so the last value processed (first displayed) has uppercase, if requested
if strforce and outvalue == 0 then
sign = ''  -- any sign is in strforce
strval = strforce  -- show small values in scientific notation; will only use least significant unit
elseif tfrac then
local wholestr = (thisvalue > 0) and tostring(thisvalue) or nil
strval = format_fraction(parms, spell_inout, false, wholestr, tfrac.numstr, tfrac.denstr, do_spell)
else
strval = (thisvalue == 0) and from_en('0') or with_separator(parms, format(fmt, thisvalue))
if do_spell then
strval = spell_number(parms, spell_inout, strval) or strval
end
end
table.insert(results, strval .. sep1 .. id)
if outvalue == 0 then
break
end
fmt = '%.0f'  -- only least significant unit can have a non-integral value
end
local reversed, count = {}, #results
for i = 1, count do
reversed[i] = results[count + 1 - i]
end
return true, sign .. table.concat(reversed, sep2)
end
local valinfo = in_unit_table.valinfo
local success, result = make_result(valinfo[1], true)
if not success then return false, result end
local range = parms.range
if range then
for i = 1, range.n do
local success, result2 = make_result(valinfo[i+1])
if not success then return false, result2 end
result = range_text(range[i], want_name, parms, result, result2, inout)
end
end
return true, result .. mid
end
end


local function process(parms, in_unit_table)
local function process(parms, in_unit_table, out_unit_table)
    -- Return true, s where s = final wikitext result,
-- Return true, s, outunit where s = final wikitext result,
    -- or return false, t where t is an error message table.
-- or return false, t where t is an error message table.
    linked_pages = {}
linked_pages = {}
    local success, out_unit_table
local success, bad_output
    local invalue1 = in_unit_table.valinfo[1].value
local bad_input_mcode = in_unit_table.bad_mcode  -- nil if input unit is a valid convert unit
    local out_unit = parms.out_unit
local out_unit = parms.out_unit
    if out_unit == nil or out_unit == '' then
if out_unit == nil or out_unit == '' or type(out_unit) == 'function' then
        success, out_unit = get_default(invalue1, in_unit_table)
if bad_input_mcode or parms.opt_input_unit_only then
        if not success then return false, out_unit end
bad_output = ''
    end
else
    success, out_unit_table = lookup(out_unit, parms.opt_sp_us, 'any_combination')
local getdef = type(out_unit) == 'function' and out_unit or get_default
    if not success then return false, out_unit_table end
success, out_unit = getdef(in_unit_table.valinfo[1].value, in_unit_table)
    if in_unit_table.utype ~= out_unit_table.utype then
parms.out_unit = out_unit
        return false, { 'cvt_mismatch', in_unit_table.utype, out_unit_table.utype }
if not success then
    end
bad_output = out_unit
    local flipped = parms.opt_flip
end
    local parts = {}
end
    for part = 1, 2 do
end
        -- The LHS (parts[1]) is normally the input, but is the output if flipped.
if not bad_output and not out_unit_table then
        -- Process LHS first so it will be linked, if wanted.
success, out_unit_table = lookup(parms, out_unit, 'any_combination')
        -- Linking to the same item is suppressed in the RHS to avoid overlinking.
if success then
        if (part == 1 and not flipped) or (part == 2 and flipped) then
local mismatch = check_mismatch(in_unit_table, out_unit_table)
            parts[part] = process_input(parms, in_unit_table)
if mismatch then
        else
bad_output = mismatch
            local outputs = {}
end
            local combos  -- nil (for 'ft' or 'ftin'), or table of unit tables (for 'm ft')
else
            if out_unit_table.multiple == nil then  -- nil ('ft' or 'm ft'), or table of factors ('ftin')
bad_output = out_unit_table
                combos = out_unit_table.combination
end
            end
end
            local imax = combos and #combos or 1  -- 1 (single unit) or number of unit tables
local lhs, rhs
            for i = 1, imax do
local flipped = parms.opt_flip and not bad_input_mcode
                local success, item
if bad_output then
                local out_current = combos and combos[i] or out_unit_table
rhs = (bad_output == '') and '' or message(parms, bad_output)
                out_current.inout = 'out'
elseif parms.opt_input_unit_only then
                if out_current.multiple == nil then
rhs = ''
                    success, item = make_output_single(parms, in_unit_table, out_current)
else
                else
local combos  -- nil (for 'ft' or 'ftin'), or table of unit tables (for 'm ft')
                    success, item = make_output_multiple(parms, in_unit_table, out_current)
if not out_unit_table.multiple then  -- nil/false ('ft' or 'm ft'), or table of factors ('ftin')
                end
combos = out_unit_table.combination
                if not success then return false, item end
end
                table.insert(outputs, item)
local frac = parms.frac  -- nil or denominator of fraction for output values
            end
if frac then
            parts[part] = parms.opt_input_unit_only and '' or table.concat(outputs, '; ')
-- Apply fraction to the unit (if only one), or to non-SI units (if a combination),
        end
-- except that if a precision is also specified, the fraction only applies to
    end
-- the hand unit; that allows the following result:
    if parms.opt_sortable then
-- {{convert|156|cm|in hand|1|frac=2}} → 156 centimetres (61.4 in; 15.1½ hands)
        parts[1] = ntsh(invalue1, parms.debug) .. parts[1]
-- However, the following is handled elsewhere as a special case:
    end
-- {{convert|156|cm|hand in|1|frac=2}} → 156 centimetres (15.1½ hands; 61½ in)
    local wikitext
if combos then
    if parms.table_joins then
local precision = parms.precision
        wikitext = parms.table_joins[1] .. parts[1] .. parms.table_joins[2] .. parts[2]
for _, unit in ipairs(combos) do
    else
if unit.builtin == 'hand' or (not precision and not unit.prefixes) then
        wikitext = parts[1] .. parms.joins[1] .. parts[2] .. parms.joins[2]
unit.frac = frac
    end
end
    if parms.warnings then
end
        wikitext = wikitext .. parms.warnings
else
    end
out_unit_table.frac = frac
    return true, wikitext
end
end
local outputs = {}
local imax = combos and #combos or 1  -- 1 (single unit) or number of unit tables
if imax == 1 then
parms.opt_order_out = nil  -- only useful with an output combination
end
if not flipped and not parms.opt_order_out then
-- Process left side first so any duplicate links (from lk=on) are suppressed
-- on right. Example: {{convert|28|e9pc|e9ly|abbr=off|lk=on}}
lhs = process_input(parms, in_unit_table)
end
for i = 1, imax do
local success, item
local out_current = combos and combos[i] or out_unit_table
out_current.inout = 'out'
if i == 1 then
if imax > 1 and out_current.builtin == 'hand' then
out_current.out_next = combos[2]  -- built-in hand can influence next unit in a combination
end
if parms.opt_order_out then
out_current.inout = 'in'
end
end
if out_current.multiple then
success, item = make_output_multiple(parms, in_unit_table, out_current)
else
success, item = make_output_single(parms, in_unit_table, out_current)
end
if not success then return false, item end
outputs[i] = item
end
if parms.opt_order_out then
lhs = outputs[1]
table.remove(outputs, 1)
end
local sep = parms.table_joins and parms.table_joins[2] or parms.join_between
rhs = table.concat(outputs, sep)
end
if flipped or not lhs then
local input = process_input(parms, in_unit_table)
if flipped then
lhs = rhs
rhs = input
else
lhs = input
end
end
if parms.join_before then
lhs = parms.join_before .. lhs
end
local wikitext
if bad_input_mcode then
if bad_input_mcode == '' then
wikitext = lhs
else
wikitext = lhs .. message(parms, bad_input_mcode)
end
elseif parms.table_joins then
wikitext = parms.table_joins[1] .. lhs .. parms.table_joins[2] .. rhs
else
wikitext = lhs .. parms.joins[1] .. rhs .. parms.joins[2]
end
if parms.warnings and not bad_input_mcode then
wikitext = wikitext .. parms.warnings
end
return true, get_styles(parms) .. wikitext, out_unit_table
end
end


local function main_convert(frame)
local function main_convert(frame)
    set_config(frame)
-- Do convert, and if needed, do it again with higher default precision.
    local result
local parms = { frame = frame }  -- will hold template arguments, after translation
    local success, parms, in_unit_table = get_parms(frame:getParent())
set_config(frame.args)
    if success then
local success, result = get_parms(parms, frame:getParent().args)
        success, result = process(parms, in_unit_table)
if success then
    else
if type(result) ~= 'table' then
        result = parms
return tostring(result)
    end
end
    if success then
local in_unit_table = result
        return result
local out_unit_table
     end
for _ = 1, 2 do  -- use counter so cannot get stuck repeating convert
    return message(result)
success, result, out_unit_table = process(parms, in_unit_table, out_unit_table)
if success and parms.do_convert_again then
parms.do_convert_again = false
else
break
end
end
end
-- If input=x gives a problem, the result should be just the user input
-- (if x is a property like P123 it has been replaced with '').
-- An unknown input unit would display the input and an error message
-- with success == true at this point.
-- Also, can have success == false with a message that outputs an empty string.
if parms.input_text then
if success and not parms.have_problem then
return result
end
local cat
if parms.tracking then
-- Add a tracking category using the given text as the category sort key.
-- There is currently only one type of tracking, but in principle multiple
-- items could be tracked, using different sort keys for convenience.
cat = wanted_category('tracking', parms.tracking)
end
return parms.input_text .. (cat or '')
end
return success and result or message(parms, result)
end
 
local function _unit(unitcode, options)
-- Helper function for Module:Val to look up a unit.
-- Parameter unitcode must be a string to identify the wanted unit.
-- Parameter options must be nil or a table with optional fields:
--  value = number (for sort key; default value is 1)
--  scaled_top = nil for a normal unit, or a number for a unit which is
--                the denominator of a per unit (for sort key)
--  si = { 'symbol', 'link' }
--                (a table with two strings) to make an SI unit
--                that will be used for the look up
--  link = true if result should be [[linked]]
--  sort = 'on' or 'debug' if result should include a sort key in a
--                span element ('debug' makes the key visible)
--  name = true for the name of the unit instead of the symbol
--  us = true for the US spelling of the unit, if any
-- Return nil if unitcode is not a non-empty string.
-- Otherwise return a table with fields:
--  text = requested symbol or name of unit, optionally linked
--  scaled_value = input value adjusted by unit scale; used for sort key
--  sortspan = span element with sort key like that provided by {{ntsh}},
--    calculated from the result of converting value
--     to a base unit with scale 1.
--  unknown = true if the unitcode was not known
unitcode = strip(unitcode)
if unitcode == nil or unitcode == '' then
return nil
end
set_config({})
linked_pages = {}
options = options or {}
local parms = {
abbr = options.name and 'off' or 'on',
lk = options.link and 'on' or nil,
opt_sp_us = options.us and true or nil,
opt_ignore_error = true,  -- do not add pages using this function to 'what links here' for Module:Convert/extra
opt_sortable_on = options.sort == 'on' or options.sort == 'debug',
opt_sortable_debug = options.sort == 'debug',
}
if options.si then
-- Make a dummy table of units (just one unit) for lookup to use.
-- This makes lookup recognize any SI prefix in the unitcode.
local symbol = options.si[1] or '?'
parms.unittable = { [symbol] = {
_name1 = symbol,
_name2 = symbol,
_symbol = symbol,
utype = symbol,
scale = symbol == 'g' and 0.001 or 1,
prefixes = 1,
default = symbol,
link = options.si[2],
}}
end
local success, unit_table = lookup(parms, unitcode, 'no_combination')
if not success then
unit_table = setmetatable({
symbol = unitcode, name2 = unitcode, utype = unitcode,
scale = 1, default = '', defkey = '', linkey = '' }, unit_mt)
end
local value = tonumber(options.value) or 1
local clean = tostring(abs(value))
local info = {
value = value,
altvalue = value,
singular = (clean == '1'),
clean = clean,
show = clean,
}
unit_table.inout = 'in'
unit_table.valinfo = { info }
local sortspan, scaled_value
if options.sort then
sortspan, scaled_value = make_table_or_sort(parms, value, info, unit_table, options.scaled_top)
end
return {
text = make_id(parms, 1, unit_table),
sortspan = sortspan,
scaled_value = scaled_value,
unknown = not success and true or nil,
}
end
end


return { convert = main_convert }
return { convert = main_convert, _unit = _unit }

Latest revision as of 10:55, 6 September 2021

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

-- Convert a value from one unit of measurement to another.
-- Example: {{convert|123|lb|kg}} --> 123 pounds (56 kg)
-- See [[:en:Template:Convert/Transwiki guide]] if copying to another wiki.

local MINUS = '−'  -- Unicode U+2212 MINUS SIGN (UTF-8: e2 88 92)
local abs = math.abs
local floor = math.floor
local format = string.format
local log10 = math.log10
local ustring = mw.ustring
local ulen = ustring.len
local usub = ustring.sub

-- Configuration options to keep magic values in one location.
-- Conversion data and message text are defined in separate modules.
local config, maxsigfig
local numdot  -- must be '.' or ',' or a character which works in a regex
local numsep, numsep_remove, numsep_remove2
local data_code, all_units
local text_code
local varname        -- can be a code to use variable names that depend on value
local from_en_table  -- to translate an output string of en digits to local language
local to_en_table    -- to translate an input string of digits in local language to en
-- Use translation_table in convert/text to change the following.
local en_default           -- true uses lang=en unless convert has lang=local or local digits
local group_method = 3     -- code for how many digits are in a group
local per_word = 'per'     -- for units like "liters per kilometer"
local plural_suffix = 's'  -- only other useful value is probably '' to disable plural unit names
local omitsep              -- true to omit separator before local symbol/name

-- All units should be defined in the data module. However, to cater for quick changes
-- and experiments, any unknown unit is looked up in an extra data module, if it exists.
-- That module would be transcluded in only a small number of pages, so there should be
-- little server overhead from making changes, and changes should propagate quickly.
local extra_module  -- name of module with extra units
local extra_units   -- nil or table of extra units from extra_module

-- Some options in the invoking template can set variables used later in the module.
local currency_text  -- for a user-defined currency symbol: {{convert|12|$/ha|$=€}} (euro replaces dollar)

local function from_en(text)
	-- Input is a string representing a number in en digits with '.' decimal mark,
	-- without digit grouping (which is done just after calling this).
	-- Return the translation of the string with numdot and digits in local language.
	if numdot ~= '.' then
		text = text:gsub('%.', numdot)
	end
	if from_en_table then
		text = text:gsub('%d', from_en_table)
	end
	return text
end

local function to_en(text)
	-- Input is a string representing a number in the local language with
	-- an optional numdot decimal mark and numsep digit grouping.
	-- Return the translation of the string with '.' mark and en digits,
	-- and no separators (they have to be removed here to handle cases like
	-- numsep = '.' and numdot = ',' with input "1.234.567,8").
	if to_en_table then
		text = ustring.gsub(text, '%d', to_en_table)
	end
	if numsep_remove then
		text = text:gsub(numsep_remove, '')
	end
	if numsep_remove2 then
		text = text:gsub(numsep_remove2, '')
	end
	if numdot ~= '.' then
		text = text:gsub(numdot, '.')
	end
	return text
end

local function decimal_mark(text)
	-- Return ',' if text probably is using comma for decimal mark, or has no decimal mark.
	-- Return '.' if text probably is using dot for decimal mark.
	-- Otherwise return nothing (decimal mark not known).
	if not text:find('[.,]') then return ',' end
	text = text:gsub('^%-', ''):gsub('%+%d+/%d+$', ''):gsub('[Ee]%-?%d+$', '')
	local decimal =
		text:match('^0?([.,])%d+$') or
		text:match('%d([.,])%d?%d?$') or
		text:match('%d([.,])%d%d%d%d+$')
	if decimal then return decimal end
	if text:match('%.%d+%.') then return ',' end
	if text:match('%,%d+,') then return '.' end
end

local add_warning, with_separator  -- forward declarations
local function to_en_with_check(text, parms)
	-- Version of to_en() for a wiki using numdot = ',' and numsep = '.' to check
	-- text (an input number as a string) which might have been copied from enwiki.
	-- For example, in '1.234' the '.' could be a decimal mark or a group separator.
	-- From viwiki.
	if to_en_table then
		text = ustring.gsub(text, '%d', to_en_table)
	end
	if decimal_mark(text) == '.' then
		local original = text
		text = text:gsub(',', '')  -- for example, interpret "1,234.5" as an enwiki value
		if parms then
			add_warning(parms, 0, 'cvt_enwiki_num', original, with_separator({}, text))
		end
	else
		if numsep_remove then
			text = text:gsub(numsep_remove, '')
		end
		if numsep_remove2 then
			text = text:gsub(numsep_remove2, '')
		end
		if numdot ~= '.' then
			text = text:gsub(numdot, '.')
		end
	end
	return text
end

local function omit_separator(id)
	-- Return true if there should be no separator before id (a unit symbol or name).
	-- For zhwiki, there should be no separator if id uses local characters.
	-- The following kludge should be a sufficient test.
	if omitsep then
		if id:sub(1, 2) == '-{' then  -- for "-{...}-" content language variant
			return true
		end
		if id:byte() > 127 then
			local first = usub(id, 1, 1)
			if first ~= 'Å' and first ~= '°' and first ~= 'µ' then
				return true
			end
		end
	end
	return id:sub(1, 1) == '/'  -- no separator before units like "/ha"
end

local spell_module  -- name of module that can spell numbers
local speller       -- function from that module to handle spelling (set if needed)
local wikidata_module, wikidata_data_module  -- names of Wikidata modules
local wikidata_code, wikidata_data  -- exported tables from those modules (set if needed)

local function set_config(args)
	-- Set configuration options from template #invoke or defaults.
	config = args
	maxsigfig = config.maxsigfig or 14  -- maximum number of significant figures
	local data_module, text_module
	local sandbox = config.sandbox and ('/' .. config.sandbox) or ''
	data_module = "Module:Convert/data" .. sandbox
	text_module = "Module:Convert/text" .. sandbox
	extra_module = "Module:Convert/extra" .. sandbox
	wikidata_module = "Module:Convert/wikidata" .. sandbox
	wikidata_data_module = "Module:Convert/wikidata/data" .. sandbox
	spell_module = "Module:ConvertNumeric"
	data_code = mw.loadData(data_module)
	text_code = mw.loadData(text_module)
	all_units = data_code.all_units
	local translation = text_code.translation_table
	if translation then
		numdot = translation.numdot
		numsep = translation.numsep
		if numdot == ',' and numsep == '.' then
			if text_code.all_messages.cvt_enwiki_num then
				to_en = to_en_with_check
			end
		end
		if translation.group then
			group_method = translation.group
		end
		if translation.per_word then
			per_word = translation.per_word
		end
		if translation.plural_suffix then
			plural_suffix = translation.plural_suffix
		end
		varname = translation.varname
		from_en_table = translation.from_en
		local use_workaround = true
		if use_workaround then
			-- 2013-07-05 workaround bug by making a copy of the required table.
			-- mw.ustring.gsub fails with a table (to_en_table) as the replacement,
			-- if the table is accessed via mw.loadData.
			local source = translation.to_en
			if source then
				to_en_table = {}
				for k, v in pairs(source) do
					to_en_table[k] = v
				end
			end
		else
			to_en_table = translation.to_en
		end
		if translation.lang == 'en default' then
			en_default = true  -- for hiwiki
		end
		omitsep = translation.omitsep  -- for zhwiki
	end
	numdot = config.numdot or numdot or '.'  -- decimal mark before fractional digits
	numsep = config.numsep or numsep or ','  -- group separator for numbers
	-- numsep should be ',' or '.' or '' or '&nbsp;' or a Unicode character.
	-- numsep_remove must work in a regex to identify separators to be removed.
	if numsep ~= '' then
		numsep_remove = (numsep == '.') and '%.' or numsep
	end
	if numsep ~= ',' and numdot ~= ',' then
		numsep_remove2 = ','  -- so numbers copied from enwiki will work
	end
end

local function collection()
	-- Return a table to hold items.
	return {
		n = 0,
		add = function (self, item)
			self.n = self.n + 1
			self[self.n] = item
		end,
	}
end

local function divide(numerator, denominator)
	-- Return integers quotient, remainder resulting from dividing the two
	-- given numbers, which should be unsigned integers.
	local quotient, remainder = floor(numerator / denominator), numerator % denominator
	if not (0 <= remainder and remainder < denominator) then
		-- Floating point limits may need this, as in {{convert|160.02|Ym|ydftin}}.
		remainder = 0
	end
	return quotient, remainder
end

local function split(text, delimiter)
	-- Return a numbered table with fields from splitting text.
	-- The delimiter is used in a regex without escaping (for example, '.' would fail).
	-- Each field has any leading/trailing whitespace removed.
	local t = {}
	text = text .. delimiter  -- to get last item
	for item in text:gmatch('%s*(.-)%s*' .. delimiter) do
		table.insert(t, item)
	end
	return t
end

local function strip(text)
	-- If text is a string, return its content with no leading/trailing
	-- whitespace. Otherwise return nil (a nil argument gives a nil result).
	if type(text) == 'string' then
		return text:match("^%s*(.-)%s*$")
	end
end

local function table_len(t)
	-- Return length (<100) of a numbered table to replace #t which is
	-- documented to not work if t is accessed via mw.loadData().
	for i = 1, 100 do
		if t[i] == nil then
			return i - 1
		end
	end
end

local function wanted_category(catkey, catsort, want_warning)
	-- Return message category if it is wanted in current namespace,
	-- otherwise return ''.
	local cat
	local title = mw.title.getCurrentTitle()
	if title then
		local nsdefault = '0'  -- default namespace: '0' = article; '0,10' = article and template
		local namespace = title.namespace
		for _, v in ipairs(split(config.nscat or nsdefault, ',')) do
			if namespace == tonumber(v) then
				cat = text_code.all_categories[want_warning and 'warning' or catkey]
				if catsort and catsort ~= '' and cat:sub(-2) == ']]' then
					cat = cat:sub(1, -3) .. '|' .. mw.text.nowiki(usub(catsort, 1, 20)) .. ']]'
				end
				break
			end
		end
	end
	return cat or ''
end

local function message(parms, mcode, is_warning)
	-- Return wikitext for an error message, including category if specified
	-- for the message type.
	-- mcode = numbered table specifying the message:
	--    mcode[1] = 'cvt_xxx' (string used as a key to get message info)
	--    mcode[2] = 'parm1' (string to replace '$1' if any in message)
	--    mcode[3] = 'parm2' (string to replace '$2' if any in message)
	--    mcode[4] = 'parm3' (string to replace '$3' if any in message)
	local msg
	if type(mcode) == 'table' then
		if mcode[1] == 'cvt_no_output' then
			-- Some errors should cause convert to output an empty string,
			-- for example, for an optional field in an infobox.
			return ''
		end
		msg = text_code.all_messages[mcode[1]]
	end
	parms.have_problem = true
	local function subparm(fmt, ...)
		local rep = {}
		for i, v in ipairs({...}) do
			rep['$' .. i] = v
		end
		return (fmt:gsub('$%d+', rep))
	end
	if msg then
		local parts = {}
		local regex, replace = msg.regex, msg.replace
		for i = 1, 3 do
			local limit = 40
			local s = mcode[i + 1]
			if s then
				if regex and replace then
					s = s:gsub(regex, replace)
					limit = nil  -- allow long "should be" messages
				end
				-- Escape user input so it does not break the message.
				-- To avoid tags (like {{convert|1<math>23</math>|m}}) breaking
				-- the mouseover title, any strip marker starting with char(127) is
				-- replaced with '...' (text not needing i18n).
				local append
				local pos = s:find(string.char(127), 1, true)
				if pos then
					append = '...'
					s = s:sub(1, pos - 1)
				end
				if limit and ulen(s) > limit then
					s = usub(s, 1, limit)
					append = '...'
				end
				s = mw.text.nowiki(s) .. (append or '')
			else
				s = '?'
			end
			parts['$' .. i] = s
		end
		local function ispreview()
			-- Return true if a prominent message should be shown.
			if parms.test == 'preview' or parms.test == 'nopreview' then
				-- For testing, can preview a real message or simulate a preview
				-- when running automated tests.
				return parms.test == 'preview'
			end
			local success, revid = pcall(function ()
				return (parms.frame):preprocess('{{REVISIONID}}') end)
			return success and (revid == '')
		end
		local want_warning = is_warning and
			not config.warnings and  -- show unobtrusive warnings if config.warnings not configured
			not msg.nowarn           -- but use msg settings, not standard warning, if specified
		local title = string.gsub(msg[1] or 'Missing message', '$%d+', parts)
		local text = want_warning and '*' or msg[2] or 'Missing message'
		local cat = wanted_category(msg[3], mcode[2], want_warning)
		local anchor = msg[4] or ''
		local fmtkey = ispreview() and 'cvt_format_preview' or
			(want_warning and 'cvt_format2' or msg.format or 'cvt_format')
		local fmt = text_code.all_messages[fmtkey] or 'convert: bug'
		return subparm(fmt, title:gsub('"', '&quot;'), text, cat, anchor)
	end
	return 'Convert internal error: unknown message'
end

function add_warning(parms, level, key, text1, text2)  -- for forward declaration above
	-- If enabled, add a warning that will be displayed after the convert result.
	-- A higher level is more verbose: more kinds of warnings are displayed.
	-- To reduce output noise, only the first warning is displayed.
	if level <= (tonumber(config.warnings) or 1) then
		if parms.warnings == nil then
			parms.warnings = message(parms, { key, text1, text2 }, true)
		end
	end
end

local function spell_number(parms, inout, number, numerator, denominator)
	-- Return result of spelling (number, numerator, denominator), or
	-- return nil if spelling is not available or not supported for given text.
	-- Examples (each value must be a string or nil):
	--   number  numerator  denominator  output
	--   ------  ---------  -----------  -------------------
	--   "1.23"    nil        nil        one point two three
	--    "1"      "2"        "3"        one and two thirds
	--    nil      "2"        "3"        two thirds
	if not speller then
		local function get_speller(module)
			return require(module).spell_number
		end
		local success
		success, speller = pcall(get_speller, spell_module)
		if not success or type(speller) ~= 'function' then
			add_warning(parms, 1, 'cvt_no_spell', 'spell')
			return nil
		end
	end
	local case
	if parms.spell_upper == inout then
		case = true
		parms.spell_upper = nil  -- only uppercase first word in a multiple unit
	end
	local sp = not parms.opt_sp_us
	local adj = parms.opt_adjectival
	return speller(number, numerator, denominator, case, sp, adj)
end

------------------------------------------------------------------------
-- BEGIN: Code required only for built-in units.
-- LATER: If need much more code, move to another module to simplify this module.
local function speed_of_sound(altitude)
	-- This is for the Mach built-in unit of speed.
	-- Return speed of sound in metres per second at given altitude in feet.
	-- If no altitude given, use default (zero altitude = sea level).
	-- Table gives speed of sound in miles per hour at various altitudes:
	--   altitude = -17,499 to 302,499 feet
	-- mach_table[a + 4] = s where
	--   a = (altitude / 5000) rounded to nearest integer (-3 to 60)
	--   s = speed of sound (mph) at that altitude
	-- LATER: Should calculate result from an interpolation between the next
	-- lower and higher altitudes in table, rather than rounding to nearest.
	-- From: http://www.aerospaceweb.org/question/atmosphere/q0112.shtml
	local mach_table = {                                                       -- a =
		799.5, 787.0, 774.2, 761.207051,                                       -- -3 to  0
		748.0, 734.6, 721.0, 707.0, 692.8, 678.3, 663.5, 660.1, 660.1, 660.1,  --  1 to 10
		660.1, 660.1, 660.1, 662.0, 664.3, 666.5, 668.9, 671.1, 673.4, 675.6,  -- 11 to 20
		677.9, 683.7, 689.9, 696.0, 702.1, 708.1, 714.0, 719.9, 725.8, 731.6,  -- 21 to 30
		737.3, 737.7, 737.7, 736.2, 730.5, 724.6, 718.8, 712.9, 707.0, 701.1,  -- 31 to 40
		695.0, 688.9, 682.8, 676.6, 670.4, 664.1, 657.8, 652.9, 648.3, 643.7,  -- 41 to 50
		639.1, 634.4, 629.6, 624.8, 620.0, 615.2, 613.2, 613.2, 613.2, 613.5,  -- 51 to 60
	}
	altitude = altitude or 0
	local a = (altitude < 0) and -altitude or altitude
	a = floor(a / 5000 + 0.5)
	if altitude < 0 then
		a = -a
	end
	if a < -3 then
		a = -3
	elseif a > 60 then
		a = 60
	end
	return mach_table[a + 4] * 0.44704  -- mph converted to m/s
end
-- END: Code required only for built-in units.
------------------------------------------------------------------------

local function add_style(parms, class)
	-- Add selected template style to parms if not already present.
	parms.templatestyles = parms.templatestyles or {}
	if not parms.templatestyles[class] then
		parms.templatestyles[class] = parms.frame:extensionTag({
			name = 'templatestyles', args = { src = text_code.titles[class] }
		})
	end
end

local function get_styles(parms)
	-- Return string of required template styles, empty if none.
	if parms.templatestyles then
		local t = {}
		for _, v in pairs(parms.templatestyles) do
			table.insert(t, v)
		end
		return table.concat(t)
	end
	return ''
end

local function get_range(word)
	-- Return a range (string or table) corresponding to word (like "to"),
	-- or return nil if not a range word.
	local ranges = text_code.ranges
	return ranges.types[word] or ranges.types[ranges.aliases[word]]
end

local function check_mismatch(unit1, unit2)
	-- If unit1 cannot be converted to unit2, return an error message table.
	-- This allows conversion between units of the same type, and between
	-- Nm (normally torque) and ftlb (energy), as in gun-related articles.
	-- This works because Nm is the base unit (scale = 1) for both the
	-- primary type (torque), and the alternate type (energy, where Nm = J).
	-- A match occurs if the primary types are the same, or if unit1 matches
	-- the alternate type of unit2, and vice versa. That provides a whitelist
	-- of which conversions are permitted between normally incompatible types.
	if unit1.utype == unit2.utype or
		(unit1.utype == unit2.alttype and unit1.alttype == unit2.utype) then
		return nil
	end
	return { 'cvt_mismatch', unit1.utype, unit2.utype }
end

local function override_from(out_table, in_table, fields)
	-- Copy the specified fields from in_table to out_table, but do not
	-- copy nil fields (keep any corresponding field in out_table).
	for _, field in ipairs(fields) do
		if in_table[field] then
			out_table[field] = in_table[field]
		end
	end
end

local function shallow_copy(t)
	-- Return a shallow copy of table t.
	-- Do not need the features and overhead of the Scribunto mw.clone().
	local result = {}
	for k, v in pairs(t) do
		result[k] = v
	end
	return result
end

local unit_mt = {
	-- Metatable to get missing values for a unit that does not accept SI prefixes.
	-- Warning: The boolean value 'false' is returned for any missing field
	-- so __index is not called twice for the same field in a given unit.
	__index = function (self, key)
		local value
		if key == 'name1' or key == 'sym_us' then
			value = self.symbol
		elseif key == 'name2' then
			value = self.name1 .. plural_suffix
		elseif key == 'name1_us' then
			value = self.name1
			if not rawget(self, 'name2_us') then
				-- If name1_us is 'foot', do not make name2_us by appending plural_suffix.
				self.name2_us = self.name2
			end
		elseif key == 'name2_us' then
			local raw1_us = rawget(self, 'name1_us')
			if raw1_us then
				value = raw1_us .. plural_suffix
			else
				value = self.name2
			end
		elseif key == 'link' then
			value = self.name1
		else
			value = false
		end
		rawset(self, key, value)
		return value
	end
}

local function prefixed_name(unit, name, index)
	-- Return unit name with SI prefix inserted at correct position.
	-- index = 1 (name1), 2 (name2), 3 (name1_us), 4 (name2_us).
	-- The position is a byte (not character) index, so use Lua's sub().
	local pos = rawget(unit, 'prefix_position')
	if type(pos) == 'string' then
		pos = tonumber(split(pos, ',')[index])
	end
	if pos then
		return name:sub(1, pos - 1) .. unit.si_name .. name:sub(pos)
	end
	return unit.si_name .. name
end

local unit_prefixed_mt = {
	-- Metatable to get missing values for a unit that accepts SI prefixes.
	-- Before use, fields si_name, si_prefix must be defined.
	-- The unit must define _symbol, _name1 and
	-- may define _sym_us, _name1_us, _name2_us
	-- (_sym_us, _name2_us may be defined for a language using sp=us
	-- to refer to a variant unrelated to U.S. units).
	__index = function (self, key)
		local value
		if key == 'symbol' then
			value = self.si_prefix .. self._symbol
		elseif key == 'sym_us' then
			value = rawget(self, '_sym_us')
			if value then
				value = self.si_prefix .. value
			else
				value = self.symbol
			end
		elseif key == 'name1' then
			value = prefixed_name(self, self._name1, 1)
		elseif key == 'name2' then
			value = rawget(self, '_name2')
			if value then
				value = prefixed_name(self, value, 2)
			else
				value = self.name1 .. plural_suffix
			end
		elseif key == 'name1_us' then
			value = rawget(self, '_name1_us')
			if value then
				value = prefixed_name(self, value, 3)
			else
				value = self.name1
			end
		elseif key == 'name2_us' then
			value = rawget(self, '_name2_us')
			if value then
				value = prefixed_name(self, value, 4)
			elseif rawget(self, '_name1_us') then
				value = self.name1_us .. plural_suffix
			else
				value = self.name2
			end
		elseif key == 'link' then
			value = self.name1
		else
			value = false
		end
		rawset(self, key, value)
		return value
	end
}

local unit_per_mt = {
	-- Metatable to get values for a per unit of form "x/y".
	-- This is never called to determine a unit name or link because per units
	-- are handled as a special case.
	-- Similarly, the default output is handled elsewhere, and for a symbol
	-- this is only called from get_default() for default_exceptions.
	__index = function (self, key)
		local value
		if key == 'symbol' then
			local per = self.per
			local unit1, unit2 = per[1], per[2]
			if unit1 then
				value = unit1[key] .. '/' .. unit2[key]
			else
				value = '/' .. unit2[key]
			end
		elseif key == 'sym_us' then
			value = self.symbol
		elseif key == 'scale' then
			local per = self.per
			local unit1, unit2 = per[1], per[2]
			value = (unit1 and unit1.scale or 1) * self.scalemultiplier / unit2.scale
		else
			value = false
		end
		rawset(self, key, value)
		return value
	end
}

local function make_per(unitcode, unit_table, ulookup)
	-- Return true, t where t is a per unit with unit codes expanded to unit tables,
	-- or return false, t where t is an error message table.
	local result = {
		unitcode = unitcode,
		utype = unit_table.utype,
		per = {}
	}
	override_from(result, unit_table, { 'invert', 'iscomplex', 'default', 'link', 'symbol', 'symlink' })
	result.symbol_raw = (result.symbol or false)  -- to distinguish between a defined exception and a metatable calculation
	local prefix
	for i, v in ipairs(unit_table.per) do
		if i == 1 and v == '' then
			-- First unit symbol can be empty; that gives a nil first unit table.
		elseif i == 1 and text_code.currency[v] then
			prefix = currency_text or v
		else
			local success, t = ulookup(v)
			if not success then return false, t end
			result.per[i] = t
		end
	end
	local multiplier = unit_table.multiplier
	if not result.utype then
		-- Creating an automatic per unit.
		local unit1 = result.per[1]
		local utype = (unit1 and unit1.utype or prefix or '') .. '/' .. result.per[2].utype
		local t = data_code.per_unit_fixups[utype]
		if t then
			if type(t) == 'table' then
				utype = t.utype or utype
				result.link = result.link or t.link
				multiplier = multiplier or t.multiplier
			else
				utype = t
			end
		end
		result.utype = utype
	end
	result.scalemultiplier = multiplier or 1
	result.vprefix = prefix or false  -- set to non-nil to avoid calling __index
	return true, setmetatable(result, unit_per_mt)
end

local function lookup(parms, unitcode, what, utable, fails, depth)
	-- Return true, t where t is a copy of the unit's converter table,
	-- or return false, t where t is an error message table.
	-- Parameter 'what' determines whether combination units are accepted:
	--   'no_combination'  : single unit only
	--   'any_combination' : single unit or combination or output multiple
	--   'only_multiple'   : single unit or output multiple only
	-- Parameter unitcode is a symbol (like 'g'), with an optional SI prefix (like 'kg').
	-- If, for example, 'kg' is in this table, that entry is used;
	-- otherwise the prefix ('k') is applied to the base unit ('g').
	-- If unitcode is a known combination code (and if allowed by what),
	-- a table of output multiple unit tables is included in the result.
	-- For compatibility with the old template, an underscore in a unitcode is
	-- replaced with a space so usage like {{convert|350|board_feet}} works.
	-- Wikignomes may also put two spaces or "&nbsp;" in combinations, so
	-- replace underscore, "&nbsp;", and multiple spaces with a single space.
	utable = utable or parms.unittable or all_units
	fails = fails or {}
	depth = depth and depth + 1 or 1
	if depth > 9 then
		-- There are ways to mistakenly define units which result in infinite
		-- recursion when lookup() is called. That gives a long delay and very
		-- confusing error messages, so the depth parameter is used as a guard.
		return false, { 'cvt_lookup', unitcode }
	end
	if unitcode == nil or unitcode == '' then
		return false, { 'cvt_no_unit' }
	end
	unitcode = unitcode:gsub('_', ' '):gsub('&nbsp;', ' '):gsub('  +', ' ')
	local function call_make_per(t)
		return make_per(unitcode, t,
			function (ucode) return lookup(parms, ucode, 'no_combination', utable, fails, depth) end
		)
	end
	local t = utable[unitcode]
	if t then
		if t.shouldbe then
			return false, { 'cvt_should_be', t.shouldbe }
		end
		if t.sp_us then
			parms.opt_sp_us = true
		end
		local target = t.target  -- nil, or unitcode is an alias for this target
		if target then
			local success, result = lookup(parms, target, what, utable, fails, depth)
			if not success then return false, result end
			override_from(result, t, { 'customary', 'default', 'link', 'symbol', 'symlink' })
			local multiplier = t.multiplier
			if multiplier then
				result.multiplier = tostring(multiplier)
				result.scale = result.scale * multiplier
			end
			return true, result
		end
		if t.per then
			return call_make_per(t)
		end
		local combo = t.combination  -- nil or a table of unitcodes
		if combo then
			local multiple = t.multiple
			if what == 'no_combination' or (what == 'only_multiple' and not multiple) then
				return false, { 'cvt_bad_unit', unitcode }
			end
			-- Recursively create a combination table containing the
			-- converter table of each unitcode.
			local result = { utype = t.utype, multiple = multiple, combination = {} }
			local cvt = result.combination
			for i, v in ipairs(combo) do
				local success, t = lookup(parms, v, multiple and 'no_combination' or 'only_multiple', utable, fails, depth)
				if not success then return false, t end
				cvt[i] = t
			end
			return true, result
		end
		local result = shallow_copy(t)
		result.unitcode = unitcode
		if result.prefixes then
			result.si_name = ''
			result.si_prefix = ''
			return true, setmetatable(result, unit_prefixed_mt)
		end
		return true, setmetatable(result, unit_mt)
	end
	local SIprefixes = text_code.SIprefixes
	for plen = SIprefixes[1] or 2, 1, -1 do
		-- Look for an SI prefix; should never occur with an alias.
		-- Check for longer prefix first ('dam' is decametre).
		-- SIprefixes[1] = prefix maximum #characters (as seen by mw.ustring.sub).
		local prefix = usub(unitcode, 1, plen)
		local si = SIprefixes[prefix]
		if si then
			local t = utable[usub(unitcode, plen+1)]
			if t and t.prefixes then
				local result = shallow_copy(t)
				result.unitcode = unitcode
				result.si_name = parms.opt_sp_us and si.name_us or si.name
				result.si_prefix = si.prefix or prefix
				result.scale = t.scale * 10 ^ (si.exponent * t.prefixes)
				return true, setmetatable(result, unit_prefixed_mt)
			end
		end
	end
	-- Accept user-defined combinations like "acre+m2+ha" or "acre m2 ha" for output.
	-- If '+' is used, each unit code can include a space, and any error is fatal.
	-- If ' ' is used and if each space-separated word is a unit code, it is a combo,
	-- but errors are not fatal so the unit code can be looked up as an extra unit.
	local err_is_fatal
	local combo = collection()
	if unitcode:find('+', 1, true) then
		err_is_fatal = true
		for item in (unitcode .. '+'):gmatch('%s*(.-)%s*%+') do
			if item ~= '' then
				combo:add(item)
			end
		end
	elseif unitcode:find('%s') then
		for item in unitcode:gmatch('%S+') do
			combo:add(item)
		end
	end
	if combo.n > 1 then
		local function lookup_combo()
			if what == 'no_combination' or what == 'only_multiple' then
				return false, { 'cvt_bad_unit', unitcode }
			end
			local result = { combination = {} }
			local cvt = result.combination
			for i, v in ipairs(combo) do
				local success, t = lookup(parms, v, 'only_multiple', utable, fails, depth)
				if not success then return false, t end
				if i == 1 then
					result.utype = t.utype
				else
					local mismatch = check_mismatch(result, t)
					if mismatch then
						return false, mismatch
					end
				end
				cvt[i] = t
			end
			return true, result
		end
		local success, result = lookup_combo()
		if success or err_is_fatal then
			return success, result
		end
	end
	-- Accept any unit with an engineering notation prefix like "e6cuft"
	-- (million cubic feet), but not chained prefixes like "e3e6cuft",
	-- and not if the unit is a combination or multiple,
	-- and not if the unit has an offset or is a built-in.
	-- Only en digits are accepted.
	local exponent, baseunit = unitcode:match('^e(%d+)(.*)')
	if exponent then
		local engscale = text_code.eng_scales[exponent]
		if engscale then
			local success, result = lookup(parms, baseunit, 'no_combination', utable, fails, depth)
			if success and not (result.offset or result.builtin or result.engscale) then
				result.unitcode = unitcode  -- 'e6cuft' not 'cuft'
				result.defkey = unitcode  -- key to lookup default exception
				result.engscale = engscale
				result.scale = result.scale * 10 ^ tonumber(exponent)
				return true, result
			end
		end
	end
	-- Look for x/y; split on right-most slash to get scale correct (x/y/z is x/y per z).
	local top, bottom = unitcode:match('^(.-)/([^/]+)$')
	if top and not unitcode:find('e%d') then
		-- If valid, create an automatic per unit for an "x/y" unit code.
		-- The unitcode must not include extraneous spaces.
		-- Engineering notation (apart from at start and which has been stripped before here),
		-- is not supported so do not make a per unit if find text like 'e3' in unitcode.
		local success, result = call_make_per({ per = {top, bottom} })
		if success then
			return true, result
		end
	end
	if not parms.opt_ignore_error and not get_range(unitcode) then
		-- Want the "what links here" list for the extra_module to show only cases
		-- where an extra unit is used, so do not require it if invoked from {{val}}
		-- or if looking up a range word which cannot be a unit.
		if not extra_units then
			local success, extra = pcall(function () return require(extra_module).extra_units end)
			if success and type(extra) == 'table' then
				extra_units = extra
			end
		end
		if extra_units then
			-- A unit in one data table might refer to a unit in the other table, so
			-- switch between them, relying on fails or depth to terminate loops.
			if not fails[unitcode] then
				fails[unitcode] = true
				local other = (utable == all_units) and extra_units or all_units
				local success, result = lookup(parms, unitcode, what, other, fails, depth)
				if success then
					return true, result
				end
			end
		end
	end
	if to_en_table then
		-- At fawiki it is common to translate all digits so a unit like "km2" becomes "km۲".
		local en_code = ustring.gsub(unitcode, '%d', to_en_table)
		if en_code ~= unitcode then
			return lookup(parms, en_code, what, utable, fails, depth)
		end
	end
	return false, { 'cvt_unknown', unitcode }
end

local function valid_number(num)
	-- Return true if num is a valid number.
	-- In Scribunto (different from some standard Lua), when expressed as a string,
	-- overflow or other problems are indicated with text like "inf" or "nan"
	-- which are regarded as invalid here (each contains "n").
	if type(num) == 'number' and tostring(num):find('n', 1, true) == nil then
		return true
	end
end

local function hyphenated(name, parts)
	-- Return a hyphenated form of given name (for adjectival usage).
	-- The name may be linked and the target of the link must not be changed.
	-- Hypothetical examples:
	--   [[long ton|ton]]         →  [[long ton|ton]]          (no change)
	--   [[tonne|long ton]]       →  [[tonne|long-ton]]
	--   [[metric ton|long ton]]  →  [[metric ton|long-ton]]
	--   [[long ton]]             →  [[long ton|long-ton]]
	-- Input can also have multiple links in a single name like:
	--   [[United States customary units|U.S.]] [[US gallon|gallon]]
	--   [[mile]]s per [[United States customary units|U.S.]] [[quart]]
	--   [[long ton]]s per [[short ton]]
	-- Assume that links cannot be nested (never like "[[abc[[def]]ghi]]").
	-- This uses a simple and efficient procedure that works for most cases.
	-- Some units (if used) would require more, and can later think about
	-- adding a method to handle exceptions.
	-- The procedure is to replace each space with a hyphen, but
	-- not a space after ')' [for "(pre-1954&nbsp;US) nautical mile"], and
	-- not spaces immediately before '(' or in '(...)' [for cases like
	-- "British thermal unit (ISO)" and "Calorie (International Steam Table)"].
	if name:find(' ', 1, true) then
		if parts then
			local pos
			if name:sub(1, 1) == '(' then
				pos = name:find(')', 1, true)
				if pos then
					return name:sub(1, pos+1) .. name:sub(pos+2):gsub(' ', '-')
				end
			elseif name:sub(-1) == ')' then
				pos = name:find('(', 1, true)
				if pos then
					return name:sub(1, pos-2):gsub(' ', '-') .. name:sub(pos-1)
				end
			end
			return name:gsub(' ', '-')
		end
		parts = collection()
		for before, item, after in name:gmatch('([^[]*)(%[%[[^[]*%]%])([^[]*)') do
			if item:find(' ', 1, true) then
				local prefix
				local plen = item:find('|', 1, true)
				if plen then
					prefix = item:sub(1, plen)
					item = item:sub(plen + 1, -3)
				else
					prefix = item:sub(1, -3) .. '|'
					item = item:sub(3, -3)
				end
				item = prefix .. hyphenated(item, parts) .. ']]'
			end
			parts:add(before:gsub(' ', '-') .. item .. after:gsub(' ', '-'))
		end
		if parts.n == 0 then
			-- No link like "[[...]]" was found in the original name.
			parts:add(hyphenated(name, parts))
		end
		return table.concat(parts)
	end
	return name
end

local function hyphenated_maybe(parms, want_name, sep, id, inout)
	-- Return s, f where
	--   s = id, possibly modified
	--   f = true if hyphenated
	-- Possible modifications: hyphenate; prepend '-'; append mid text.
	if id == nil or id == '' then
		return ''
	end
	local mid = (inout == (parms.opt_flip and 'out' or 'in')) and parms.mid or ''
	if want_name then
		if parms.opt_adjectival then
			return '-' .. hyphenated(id) .. mid, true
		end
		if parms.opt_add_s and id:sub(-1) ~= 's' then
			id = id .. 's'  -- for nowiki
		end
	end
	return sep .. id .. mid
end

local function use_minus(text)
	-- Return text with Unicode minus instead of '-', if present.
	if text:sub(1, 1) == '-' then
		return MINUS .. text:sub(2)
	end
	return text
end

local function digit_groups(parms, text, method)
	-- Return a numbered table of groups of digits (left-to-right, in local language).
	-- Parameter method is a number or nil:
	--   3 for 3-digit grouping (default), or
	--   2 for 3-then-2 grouping (only for digits before decimal mark).
	local len_right
	local len_left = text:find('.', 1, true)
	if len_left then
		len_right = #text - len_left
		len_left = len_left - 1
	else
		len_left = #text
	end
	local twos = method == 2 and len_left > 5
	local groups = collection()
	local run = len_left
	local n
	if run < 4 or (run == 4 and parms.opt_comma5) then
		if parms.opt_gaps then
			n = run
		else
			n = #text
		end
	elseif twos then
		n = run % 2 == 0 and 1 or 2
	else
		n = run % 3 == 0 and 3 or run % 3
	end
	while run > 0 do
		groups:add(n)
		run = run - n
		n = (twos and run > 3) and 2 or 3
	end
	if len_right then
		if groups.n == 0 then
			groups:add(0)
		end
		if parms.opt_gaps and len_right > 3 then
			local want4 = not parms.opt_gaps3  -- true gives no gap before trailing single digit
			local isfirst = true
			run = len_right
			while run > 0 do
				n = (want4 and run == 4) and 4 or (run > 3 and 3 or run)
				if isfirst then
					isfirst = false
					groups[groups.n] = groups[groups.n] + 1 + n
				else
					groups:add(n)
				end
				run = run - n
			end
		else
			groups[groups.n] = groups[groups.n] + 1 + len_right
		end
	end
	local pos = 1
	for i, length in ipairs(groups) do
		groups[i] = from_en(text:sub(pos, pos + length - 1))
		pos = pos + length
	end
	return groups
end

function with_separator(parms, text)  -- for forward declaration above
	-- Input text is a number in en digits with optional '.' decimal mark.
	-- Return an equivalent, formatted for display:
	--   with a custom decimal mark instead of '.', if wanted
	--   with thousand separators inserted, if wanted
	--   digits in local language
	-- The given text is like '123' or '123.' or '12345.6789'.
	-- The text has no sign (caller inserts that later, if necessary).
	-- When using gaps, they are inserted before and after the decimal mark.
	-- Separators are inserted only before the decimal mark.
	-- A trailing dot (as in '123.') is removed because their use appears to
	-- be accidental, and such a number should be shown as '123' or '123.0'.
	-- It is useful for convert to suppress the dot so, for example, '4000.'
	-- is a simple way of indicating that all the digits are significant.
	if text:sub(-1) == '.' then
		text = text:sub(1, -2)
	end
	if #text < 4 or parms.opt_nocomma or numsep == '' then
		return from_en(text)
	end
	local groups = digit_groups(parms, text, group_method)
	if parms.opt_gaps then
		if groups.n <= 1 then
			return groups[1] or ''
		end
		local nowrap = '<span style="white-space: nowrap">'
		local gap = '<span style="margin-left: 0.25em">'
		local close = '</span>'
		return nowrap .. groups[1] .. gap .. table.concat(groups, close .. gap, 2, groups.n) .. close .. close
	end
	return table.concat(groups, numsep)
end

-- An input value like 1.23e12 is displayed using scientific notation (1.23×10¹²).
-- That also makes the output use scientific notation, except for small values.
-- In addition, very small or very large output values use scientific notation.
-- Use format(fmtpower, significand, '10', exponent) where each argument is a string.
local fmtpower = '%s<span style="margin:0 .15em 0 .25em">×</span>%s<sup>%s</sup>'

local function with_exponent(parms, show, exponent)
	-- Return wikitext to display the implied value in scientific notation.
	-- Input uses en digits; output uses digits in local language.
	return format(fmtpower, with_separator(parms, show), from_en('10'), use_minus(from_en(tostring(exponent))))
end

local function make_sigfig(value, sigfig)
	-- Return show, exponent that are equivalent to the result of
	-- converting the number 'value' (where value >= 0) to a string,
	-- rounded to 'sigfig' significant figures.
	-- The returned items are:
	--   show: a string of digits; no sign and no dot;
	--         there is an implied dot before show.
	--   exponent: a number (an integer) to shift the implied dot.
	-- Resulting value = tonumber('.' .. show) * 10^exponent.
	-- Examples:
	--   make_sigfig(23.456, 3) returns '235', 2 (.235 * 10^2).
	--   make_sigfig(0.0023456, 3) returns '235', -2 (.235 * 10^-2).
	--   make_sigfig(0, 3) returns '000', 1 (.000 * 10^1).
	if sigfig <= 0 then
		sigfig = 1
	elseif sigfig > maxsigfig then
		sigfig = maxsigfig
	end
	if value == 0 then
		return string.rep('0', sigfig), 1
	end
	local exp, fracpart = math.modf(log10(value))
	if fracpart >= 0 then
		fracpart = fracpart - 1
		exp = exp + 1
	end
	local digits = format('%.0f', 10^(fracpart + sigfig))
	if #digits > sigfig then
		-- Overflow (for sigfig=3: like 0.9999 rounding to "1000"; need "100").
		digits = digits:sub(1, sigfig)
		exp = exp + 1
	end
	assert(#digits == sigfig, 'Bug: rounded number has wrong length')
	return digits, exp
end

-- Fraction output format.
local fracfmt = {
	{ -- Like {{frac}} (fraction slash).
		'<span class="frac" role="math">{SIGN}<span class="num">{NUM}</span>&frasl;<span class="den">{DEN}</span></span>',  -- 1/2
		'<span class="frac" role="math">{SIGN}{WHOLE}<span class="sr-only">+</span><span class="num">{NUM}</span>&frasl;<span class="den">{DEN}</span></span>',  -- 1+2/3
		style = 'frac',
	},
	{ -- Like {{sfrac}} (stacked fraction, that is, horizontal bar).
		'<span class="sfrac tion" role="math">{SIGN}<span class="num">{NUM}</span><span class="sr-only">/</span><span class="den">{DEN}</span></span>',  -- 1//2
		'<span class="sfrac" role="math">{SIGN}{WHOLE}<span class="sr-only">+</span><span class="tion"><span class="num">{NUM}</span><span class="sr-only">/</span><span class="den">{DEN}</span></span></span>',  -- 1+2//3
		style = 'sfrac',
	},
}

local function format_fraction(parms, inout, negative, wholestr, numstr, denstr, do_spell, style)
	-- Return wikitext for a fraction, possibly spelled.
	-- Inputs use en digits and have no sign; output uses digits in local language.
	local wikitext
	if not style then
		style = parms.opt_fraction_horizontal and 2 or 1
	end
	if wholestr == '' then
		wholestr = nil
	end
	local substitute = {
		SIGN = negative and MINUS or '',
		WHOLE = wholestr and with_separator(parms, wholestr),
		NUM = from_en(numstr),
		DEN = from_en(denstr),
	}
	wikitext = fracfmt[style][wholestr and 2 or 1]:gsub('{(%u+)}', substitute)
	if do_spell then
		if negative then
			if wholestr then
				wholestr = '-' .. wholestr
			else
				numstr = '-' .. numstr
			end
		end
		local s = spell_number(parms, inout, wholestr, numstr, denstr)
		if s then
			return s
		end
	end
	add_style(parms, fracfmt[style].style)
	return wikitext
end

local function format_number(parms, show, exponent, isnegative)
	-- Parameter show is a string or a table containing strings.
	-- Each string is a formatted number in en digits and optional '.' decimal mark.
	-- A table represents a fraction: integer, numerator, denominator;
	-- if a table is given, exponent must be nil.
	-- Return t where t is a table with fields:
	--   show = wikitext formatted to display implied value
	--          (digits in local language)
	--   is_scientific = true if show uses scientific notation
	--   clean = unformatted show (possibly adjusted and with inserted '.')
	--          (en digits)
	--   sign = '' or MINUS
	--   exponent = exponent (possibly adjusted)
	-- The clean and exponent fields can be used to calculate the
	-- rounded absolute value, if needed.
	--
	-- The value implied by the arguments is found from:
	--   exponent is nil; and
	--   show is a string of digits (no sign), with an optional dot;
	--   show = '123.4' is value 123.4, '1234' is value 1234.0;
	-- or:
	--   exponent is an integer indicating where dot should be;
	--   show is a string of digits (no sign and no dot);
	--   there is an implied dot before show;
	--   show does not start with '0';
	--   show = '1234', exponent = 3 is value 0.1234*10^3 = 123.4.
	--
	-- The formatted result:
	-- * Is for an output value and is spelled if wanted and possible.
	-- * Includes a Unicode minus if isnegative and not spelled.
	-- * Uses a custom decimal mark, if wanted.
	-- * Has digits grouped where necessary, if wanted.
	-- * Uses scientific notation if requested, or for very small or large values
	--   (which forces result to not be spelled).
	-- * Has no more than maxsigfig significant digits
	--   (same as old template and {{#expr}}).
	local xhi, xlo  -- these control when scientific notation (exponent) is used
	if parms.opt_scientific then
		xhi, xlo = 4, 2  -- default for output if input uses e-notation
	elseif parms.opt_scientific_always then
		xhi, xlo = 0, 0  -- always use scientific notation (experimental)
	else
		xhi, xlo = 10, 4  -- default
	end
	local sign = isnegative and MINUS or ''
	local maxlen = maxsigfig
	local tfrac
	if type(show) == 'table' then
		tfrac = show
		show = tfrac.wholestr
		assert(exponent == nil, 'Bug: exponent given with fraction')
	end
	if not tfrac and not exponent then
		local integer, dot, decimals = show:match('^(%d*)(%.?)(.*)')
		if integer == '0' or integer == '' then
			local zeros, figs = decimals:match('^(0*)([^0]?.*)')
			if #figs == 0 then
				if #zeros > maxlen then
					show = '0.' .. zeros:sub(1, maxlen)
				end
			elseif #zeros >= xlo then
				show = figs
				exponent = -#zeros
			elseif #figs > maxlen then
				show = '0.' .. zeros .. figs:sub(1, maxlen)
			end
		elseif #integer >= xhi then
			show = integer .. decimals
			exponent = #integer
		else
			maxlen = maxlen + #dot
			if #show > maxlen then
				show = show:sub(1, maxlen)
			end
		end
	end
	if exponent then
		local function zeros(n)
			return string.rep('0', n)
		end
		if #show > maxlen then
			show = show:sub(1, maxlen)
		end
		if exponent > xhi or exponent <= -xlo or (exponent == xhi and show ~= '1' .. zeros(xhi - 1)) then
			-- When xhi, xlo = 10, 4 (the default), scientific notation is used if the
			-- rounded value satisfies: value >= 1e9 or value < 1e-4 (1e9 = 0.1e10),
			-- except if show is '1000000000' (1e9), for example:
			-- {{convert|1000000000|m|m|sigfig=10}} → 1,000,000,000 metres (1,000,000,000 m)
			local significand
			if #show > 1 then
				significand = show:sub(1, 1) .. '.' .. show:sub(2)
			else
				significand = show
			end
			return {
				clean = '.' .. show,
				exponent = exponent,
				sign = sign,
				show = sign .. with_exponent(parms, significand, exponent-1),
				is_scientific = true,
			}
		end
		if exponent >= #show then
			show = show .. zeros(exponent - #show)  -- result has no dot
		elseif exponent <= 0 then
			show = '0.' .. zeros(-exponent) .. show
		else
			show = show:sub(1, exponent) .. '.' .. show:sub(exponent+1)
		end
	end
	local formatted_show
	if tfrac then
		show = tostring(tfrac.value)  -- to set clean in returned table
		formatted_show = format_fraction(parms, 'out', isnegative, tfrac.wholestr, tfrac.numstr, tfrac.denstr, parms.opt_spell_out)
	else
		if isnegative and show:match('^0.?0*$') then
			sign = ''  -- don't show minus if result is negative but rounds to zero
		end
		formatted_show = sign .. with_separator(parms, show)
		if parms.opt_spell_out then
			formatted_show = spell_number(parms, 'out', sign .. show) or formatted_show
		end
	end
	return {
		clean = show,
		sign = sign,
		show = formatted_show,
		is_scientific = false,  -- to avoid calling __index
	}
end

local function extract_fraction(parms, text, negative)
	-- If text represents a fraction, return
	--   value, altvalue, show, denominator
	-- where
	--   value is a number (value of the fraction in argument text)
	--   altvalue is an alternate interpretation of any fraction for the hands
	--        unit where "12.1+3/4" means 12 hands 1.75 inches
	--   show is a string (formatted text for display of an input value,
	--        and is spelled if wanted and possible)
	--   denominator is value of the denominator in the fraction
	-- Otherwise, return nil.
	-- Input uses en digits and '.' decimal mark (input has been translated).
	-- Output uses digits in local language and local decimal mark, if any.
	------------------------------------------------------------------------
	-- Originally this function accepted x+y/z where x, y, z were any valid
	-- numbers, possibly with a sign. For example '1.23e+2+1.2/2.4' = 123.5,
	-- and '2-3/8' = 1.625. However, such usages were found to be errors or
	-- misunderstandings, so since August 2014 the following restrictions apply:
	--   x (if present) is an integer or has a single digit after decimal mark
	--   y and z are unsigned integers
	--   e-notation is not accepted
	-- The overall number can start with '+' or '-' (so '12+3/4' and '+12+3/4'
	-- and '-12-3/4' are valid).
	-- Any leading negative sign is removed by the caller, so only inputs
	-- like the following are accepted here (may have whitespace):
	--   negative = false       false        true (there was a leading '-')
	--   text     = '2/3'       '+2/3'       '2/3'
	--   text     = '1+2/3'     '+1+2/3'     '1-2/3'
	--   text     = '12.3+1/2'  '+12.3+1/2'  '12.3-1/2'
	-- Values like '12.3+1/2' are accepted, but are intended only for use
	-- with the hands unit (not worth adding code to enforce that).
	------------------------------------------------------------------------
	local leading_plus, prefix, numstr, slashes, denstr =
		text:match('^%s*(%+?)%s*(.-)%s*(%d+)%s*(/+)%s*(%d+)%s*$')
	if not leading_plus then
		-- Accept a single U+2044 fraction slash because that may be pasted.
		leading_plus, prefix, numstr, denstr =
			text:match('^%s*(%+?)%s*(.-)%s*(%d+)%s*⁄%s*(%d+)%s*$')
		slashes = '/'
	end
	local numerator = tonumber(numstr)
	local denominator = tonumber(denstr)
	if numerator == nil or denominator == nil or (negative and leading_plus ~= '') then
		return nil
	end
	local whole, wholestr
	if prefix == '' then
		wholestr = ''
		whole = 0
	else
		-- Any prefix must be like '12+' or '12-' (whole number and fraction sign);
		-- '12.3+' and '12.3-' are also accepted (single digit after decimal point)
		-- because '12.3+1/2 hands' is valid (12 hands 3½ inches).
		local num1, num2, frac_sign = prefix:match('^(%d+)(%.?%d?)%s*([+%-])$')
		if num1 == nil then return nil end
		if num2 == '' then  -- num2 must be '' or like '.1' but not '.' or '.12'
			wholestr = num1
		else
			if #num2 ~= 2 then return nil end
			wholestr = num1 .. num2
		end
		if frac_sign ~= (negative and '-' or '+') then return nil end
		whole = tonumber(wholestr)
		if whole == nil then return nil end
	end
	local value = whole + numerator / denominator
	if not valid_number(value) then return nil end
	local altvalue = whole + numerator / (denominator * 10)
	local style = #slashes  -- kludge: 1 or 2 slashes can be used to select style
	if style > 2 then style = 2 end
	local wikitext = format_fraction(parms, 'in', negative, leading_plus .. wholestr, numstr, denstr, parms.opt_spell_in, style)
	return value, altvalue, wikitext, denominator
end

local function extract_number(parms, text, another, no_fraction)
	-- Return true, info if can extract a number from text,
	-- where info is a table with the result,
	-- or return false, t where t is an error message table.
	-- Input can use en digits or digits in local language and can
	-- have references at the end. Accepting references is intended
	-- for use in infoboxes with a field for a value passed to convert.
	-- Parameter another = true if the expected value is not the first.
	-- Before processing, the input text is cleaned:
	-- * Any thousand separators (valid or not) are removed.
	-- * Any sign is replaced with '-' (if negative) or '' (otherwise).
	--   That replaces Unicode minus with '-'.
	-- If successful, the returned info table contains named fields:
	--   value    = a valid number
	--   altvalue = a valid number, usually same as value but different
	--              if fraction used (for hands unit)
	--   singular = true if value is 1 or -1 (to use singular form of units)
	--   clean    = cleaned text with any separators and sign removed
	--              (en digits and '.' decimal mark)
	--   show     = text formatted for output, possibly with ref strip markers
	--              (digits in local language and custom decimal mark)
	-- The resulting show:
	-- * Is for an input value and is spelled if wanted and possible.
	-- * Has a rounded value, if wanted.
	-- * Has digits grouped where necessary, if wanted.
	-- * If negative, a Unicode minus is used; otherwise the sign is
	--   '+' (if the input text used '+'), or is '' (if no sign in input).
	text = strip(text or '')
	local reference
	local pos = text:find('\127', 1, true)
	if pos then
		local before = text:sub(1, pos - 1)
		local remainder = text:sub(pos)
		local refs = {}
		while #remainder > 0 do
			local ref, spaces
			ref, spaces, remainder = remainder:match('^(\127[^\127]*UNIQ[^\127]*%-ref[^\127]*\127)(%s*)(.*)')
			if ref then
				table.insert(refs, ref)
			else
				refs = {}
				break
			end
		end
		if #refs > 0 then
			text = strip(before)
			reference = table.concat(refs)
		end
	end
	local clean = to_en(text, parms)
	if clean == '' then
		return false, { another and 'cvt_no_num2' or 'cvt_no_num' }
	end
	local isnegative, propersign = false, ''  -- most common case
	local singular, show, denominator
	local value = tonumber(clean)
	local altvalue
	if value then
		local sign = clean:sub(1, 1)
		if sign == '+' or sign == '-' then
			propersign = (sign == '+') and '+' or MINUS
			clean = clean:sub(2)
		end
		if value < 0 then
			isnegative = true
			value = -value
		end
	else
		local valstr
		for _, prefix in ipairs({ '-', MINUS, '&minus;' }) do
			-- Including '-' sets isnegative in case input is a fraction like '-2-3/4'.
			local plen = #prefix
			if clean:sub(1, plen) == prefix then
				valstr = clean:sub(plen + 1)
				if valstr:match('^%s') then  -- "- 1" is invalid but "-1 - 1/2" is ok
					return false, { 'cvt_bad_num', text }
				end
				break
			end
		end
		if valstr then
			isnegative = true
			propersign = MINUS
			clean = valstr
			value = tonumber(clean)
		end
		if value == nil then
			if not no_fraction then
				value, altvalue, show, denominator = extract_fraction(parms, clean, isnegative)
			end
			if value == nil then
				return false, { 'cvt_bad_num', text }
			end
			if value <= 1 then
				singular = true  -- for example, "½ mile" or "one half mile" (singular unit)
			end
		end
	end
	if not valid_number(value) then  -- for example, "1e310" may overflow
		return false, { 'cvt_invalid_num' }
	end
	if show == nil then
		-- clean is a non-empty string with no spaces, and does not represent a fraction,
		-- and value = tonumber(clean) is a number >= 0.
		-- If the input uses e-notation, show will be displayed using a power of ten, but
		-- we use the number as given so it might not be normalized scientific notation.
		-- The input value is spelled if specified so any e-notation is ignored;
		-- that allows input like 2e6 to be spelled as "two million" which works
		-- because the spell module converts '2e6' to '2000000' before spelling.
		local function rounded(value, default, exponent)
			local precision = parms.opt_ri
			if precision then
				local fmt = '%.' .. format('%d', precision) .. 'f'
				local result = fmt:format(tonumber(value) + 2e-14)  -- fudge for some common cases of bad rounding
				if not exponent then
					singular = (tonumber(result) == 1)
				end
				return result
			end
			return default
		end
		singular = (value == 1)
		local scientific
		local significand, exponent = clean:match('^([%d.]+)[Ee]([+%-]?%d+)')
		if significand then
			show = with_exponent(parms, rounded(significand, significand, exponent), exponent)
			scientific = true
		else
			show = with_separator(parms, rounded(value, clean))
		end
		show = propersign .. show
		if parms.opt_spell_in then
			show = spell_number(parms, 'in', propersign .. rounded(value, clean)) or show
			scientific = false
		end
		if scientific then
			parms.opt_scientific = true
		end
	end
	if isnegative and (value ~= 0) then
		value = -value
		altvalue = -(altvalue or value)
	end
	return true, {
		value = value,
		altvalue = altvalue or value,
		singular = singular,
		clean = clean,
		show = show .. (reference or ''),
		denominator = denominator,
	}
end

local function get_number(text)
	-- Return v, f where:
	--   v = nil (text is not a number)
	-- or
	--   v = value of text (text is a number)
	--   f = true if value is an integer
	-- Input can use en digits or digits in local language,
	-- but no separators, no Unicode minus, and no fraction.
	if text then
		local number = tonumber(to_en(text))
		if number then
			local _, fracpart = math.modf(number)
			return number, (fracpart == 0)
		end
	end
end

local function gcd(a, b)
	-- Return the greatest common denominator for the given values,
	-- which are known to be positive integers.
	if a > b then
		a, b = b, a
	end
	if a <= 0 then
		return b
	end
	local r = b % a
	if r <= 0 then
		return a
	end
	if r == 1 then
		return 1
	end
	return gcd(r, a)
end

local function fraction_table(value, denominator)
	-- Return value as a string or a table:
	-- * If result is a string, there is no fraction, and the result
	--   is value formatted as a string of en digits.
	-- * If result is a table, it represents a fraction with named fields:
	--   wholestr, numstr, denstr (strings of en digits for integer, numerator, denominator).
	-- The result is rounded to the nearest multiple of (1/denominator).
	-- If the multiple is zero, no fraction is included.
	-- No fraction is included if value is very large as the fraction would
	-- be unhelpful, particularly if scientific notation is required.
	-- Input value is a non-negative number.
	-- Input denominator is a positive integer for the desired fraction.
	if value <= 0 then
		return '0'
	end
	if denominator <= 0 or value > 1e8 then
		return format('%.2f', value)
	end
	local integer, decimals = math.modf(value)
	local numerator = floor((decimals * denominator) +
		0.5 + 2e-14)  -- add fudge for some common cases of bad rounding
	if numerator >= denominator then
		integer = integer + 1
		numerator = 0
	end
	local wholestr = tostring(integer)
	if numerator > 0 then
		local div = gcd(numerator, denominator)
		if div > 1 then
			numerator = numerator / div
			denominator = denominator / div
		end
		return {
			wholestr = (integer > 0) and wholestr or '',
			numstr = tostring(numerator),
			denstr = tostring(denominator),
			value = value,
		}
	end
	return wholestr
end

local function preunits(count, preunit1, preunit2)
	-- If count is 1:
	--     ignore preunit2
	--     return p1
	-- else:
	--     preunit1 is used for preunit2 if the latter is empty
	--     return p1, p2
	-- where:
	--     p1 is text to insert before the input unit
	--     p2 is text to insert before the output unit
	--     p1 or p2 may be nil to mean "no preunit"
	-- Using '+' gives output like "5+ feet" (no space before, but space after).
	local function withspace(text, wantboth)
		-- Return text with space before and, if wantboth, after.
		-- However, no space is added if there is a space or '&nbsp;' or '-'
		-- at that position ('-' is for adjectival text).
		-- There is also no space if text starts with '&'
		-- (e.g. '&deg;' would display a degree symbol with no preceding space).
		local char = text:sub(1, 1)
		if char == '&' then
			return text  -- an html entity can be used to specify the exact display
		end
		if not (char == ' ' or char == '-' or char == '+') then
			text = ' ' .. text
		end
		if wantboth then
			char = text:sub(-1, -1)
			if not (char == ' ' or char == '-' or text:sub(-6, -1) == '&nbsp;') then
				text = text .. ' '
			end
		end
		return text
	end
	local PLUS = '+ '
	preunit1 = preunit1 or ''
	local trim1 = strip(preunit1)
	if count == 1 then
		if trim1 == '' then
			return nil
		end
		if trim1 == '+' then
			return PLUS
		end
		return withspace(preunit1, true)
	end
	preunit1 = withspace(preunit1)
	preunit2 = preunit2 or ''
	local trim2 = strip(preunit2)
	if trim1 == '+' then
		if trim2 == '' or trim2 == '+' then
			return PLUS, PLUS
		end
		preunit1 = PLUS
	end
	if trim2 == '' then
		if trim1 == '' then
			return nil, nil
		end
		preunit2 = preunit1
	elseif trim2 == '+' then
		preunit2 = PLUS
	elseif trim2 == '&#32;' then  -- trick to make preunit2 empty
		preunit2 = nil
	else
		preunit2 = withspace(preunit2)
	end
	return preunit1, preunit2
end

local function range_text(range, want_name, parms, before, after, inout)
	-- Return before .. rtext .. after
	-- where rtext is the text that separates two values in a range.
	local rtext, adj_text, exception
	if type(range) == 'table' then
		-- Table must specify range text for ('off' and 'on') or ('input' and 'output'),
		-- and may specify range text for 'adj=on',
		-- and may specify exception = true.
		rtext = range[want_name and 'off' or 'on'] or
				range[((inout == 'in') == (parms.opt_flip == true)) and 'output' or 'input']
		adj_text = range['adj']
		exception = range['exception']
	else
		rtext = range
	end
	if parms.opt_adjectival then
		if want_name or (exception and parms.abbr_org == 'on') then
			rtext = adj_text or rtext:gsub(' ', '-'):gsub('&nbsp;', '-')
		end
	end
	if rtext == '–' and after:sub(1, #MINUS) == MINUS then
		rtext = '&nbsp;– '
	end
	return before .. rtext .. after
end

local function get_composite(parms, iparm, in_unit_table)
	-- Look for a composite input unit. For example, {{convert|1|yd|2|ft|3|in}}
	-- would result in a call to this function with
	--   iparm = 3 (parms[iparm] = "2", just after the first unit)
	--   in_unit_table = (unit table for "yd"; contains value 1 for number of yards)
	-- Return true, iparm, unit where
	--   iparm = index just after the composite units (7 in above example)
	--   unit = composite unit table holding all input units,
	-- or return true if no composite unit is present in parms,
	-- or return false, t where t is an error message table.
	local default, subinfo
	local composite_units, count = { in_unit_table }, 1
	local fixups = {}
	local total = in_unit_table.valinfo[1].value
	local subunit = in_unit_table
	while subunit.subdivs do  -- subdivs is nil or a table of allowed subdivisions
		local subcode = strip(parms[iparm+1])
		local subdiv = subunit.subdivs[subcode] or subunit.subdivs[(all_units[subcode] or {}).target]
		if not subdiv then
			break
		end
		local success
		success, subunit = lookup(parms, subcode, 'no_combination')
		if not success then return false, subunit end  -- should never occur
		success, subinfo = extract_number(parms, parms[iparm])
		if not success then return false, subinfo end
		iparm = iparm + 2
		subunit.inout = 'in'
		subunit.valinfo = { subinfo }
		-- Recalculate total as a number of subdivisions.
		-- subdiv[1] = number of subdivisions per previous unit (integer > 1).
		total = total * subdiv[1] + subinfo.value
		if not default then  -- set by the first subdiv with a default defined
			default = subdiv.default
		end
		count = count + 1
		composite_units[count] = subunit
		if subdiv.unit or subdiv.name then
			fixups[count] = { unit = subdiv.unit, name = subdiv.name, valinfo = subunit.valinfo }
		end
	end
	if count == 1 then
		return true  -- no error and no composite unit
	end
	for i, fixup in pairs(fixups) do
		local unit = fixup.unit
		local name = fixup.name
		if not unit or (count > 2 and name) then
			composite_units[i].fixed_name = name
		else
			local success, alternate = lookup(parms, unit, 'no_combination')
			if not success then return false, alternate end  -- should never occur
			alternate.inout = 'in'
			alternate.valinfo = fixup.valinfo
			composite_units[i] = alternate
		end
	end
	return true, iparm, {
		utype = in_unit_table.utype,
		scale = subunit.scale,  -- scale of last (least significant) unit
		valinfo = { { value = total, clean = subinfo.clean, denominator = subinfo.denominator } },
		composite = composite_units,
		default = default or in_unit_table.default
	}
end

local function translate_parms(parms, kv_pairs)
	-- Update fields in parms by translating each key:value in kv_pairs to terms
	-- used by this module (may involve translating from local language to English).
	-- Also, checks are performed which may display warnings, if enabled.
	-- Return true if successful or return false, t where t is an error message table.
	currency_text = nil  -- local testing can hold module in memory; must clear globals
	local accept_any_text = {
		input = true,
		qid = true,
		qual = true,
		stylein = true,
		styleout = true,
		tracking = true,
	}
	if kv_pairs.adj and kv_pairs.sing then
		-- For enwiki (before translation), warn if attempt to use adj and sing
		-- as the latter is a deprecated alias for the former.
		if kv_pairs.adj ~= kv_pairs.sing and kv_pairs.sing ~= '' then
			add_warning(parms, 1, 'cvt_unknown_option', 'sing=' .. kv_pairs.sing)
		end
		kv_pairs.sing = nil
	end
	kv_pairs.comma = kv_pairs.comma or config.comma  -- for plwiki who want default comma=5
	for loc_name, loc_value in pairs(kv_pairs) do
		local en_name = text_code.en_option_name[loc_name]
		if en_name then
			local en_value
			if en_name == '$' or en_name == 'frac' or en_name == 'sigfig' then
				if loc_value == '' then
					add_warning(parms, 2, 'cvt_empty_option', loc_name)
				elseif en_name == '$' then
					-- Value should be a single character like "€" for the euro currency symbol, but anything is accepted.
					currency_text = (loc_value == 'euro') and '€' or loc_value
				else
					local minimum
					local number, is_integer = get_number(loc_value)
					if en_name == 'frac' then
						minimum = 2
						if number and number < 0 then
							parms.opt_fraction_horizontal = true
							number = -number
						end
					else
						minimum = 1
					end
					if number and is_integer and number >= minimum then
						en_value = number
					else
						add_warning(parms, 1, (en_name == 'frac' and 'cvt_bad_frac' or 'cvt_bad_sigfig'), loc_name .. '=' .. loc_value)
					end
				end
			elseif accept_any_text[en_name] then
				en_value = loc_value ~= '' and loc_value or nil  -- accept non-empty user text with no validation
				if en_name == 'input' then
					-- May have something like {{convert|input=}} (empty input) if source is an infobox
					-- with optional fields. In that case, want to output nothing rather than an error.
					parms.input_text = loc_value  -- keep input because parms.input is nil if loc_value == ''
				end
			else
				en_value = text_code.en_option_value[en_name][loc_value]
				if en_value and en_value:sub(-1) == '?' then
					en_value = en_value:sub(1, -2)
					add_warning(parms, -1, 'cvt_deprecated', loc_name .. '=' .. loc_value)
				end
				if en_value == nil then
					if loc_value == '' then
						add_warning(parms, 2, 'cvt_empty_option', loc_name)
					else
						add_warning(parms, 1, 'cvt_unknown_option', loc_name .. '=' .. loc_value)
					end
				elseif en_value == '' then
					en_value = nil  -- an ignored option like adj=off
				elseif type(en_value) == 'string' and en_value:sub(1, 4) == 'opt_' then
					for _, v in ipairs(split(en_value, ',')) do
						local lhs, rhs = v:match('^(.-)=(.+)$')
						if rhs then
							parms[lhs] = tonumber(rhs) or rhs
						else
							parms[v] = true
						end
					end
					en_value = nil
				end
			end
			parms[en_name] = en_value
		else
			add_warning(parms, 1, 'cvt_unknown_option', loc_name .. '=' .. loc_value)
		end
	end
	local abbr_entered = parms.abbr
	local cfg_abbr = config.abbr
	if cfg_abbr then
		-- Don't warn if invalid because every convert would show that warning.
		if cfg_abbr == 'on always' then
			parms.abbr = 'on'
		elseif cfg_abbr == 'off always' then
			parms.abbr = 'off'
		elseif parms.abbr == nil then
			if cfg_abbr == 'on default' then
				parms.abbr = 'on'
			elseif cfg_abbr == 'off default' then
				parms.abbr = 'off'
			end
		end
	end
	if parms.abbr then
		if parms.abbr == 'unit' then
			parms.abbr = 'on'
			parms.number_word = true
		end
		parms.abbr_org = parms.abbr  -- original abbr, before any flip
	elseif parms.opt_hand_hh then
		parms.abbr_org = 'on'
		parms.abbr = 'on'
	else
		parms.abbr = 'out'  -- default is to abbreviate output only (use symbol, not name)
	end
	if parms.opt_order_out then
		-- Disable options that do not work in a useful way with order=out.
		parms.opt_flip = nil  -- override adj=flip
		parms.opt_spell_in = nil
		parms.opt_spell_out = nil
		parms.opt_spell_upper = nil
	end
	if parms.opt_spell_out and not abbr_entered then
		parms.abbr = 'off'  -- should show unit name when spelling the output value
	end
	if parms.opt_flip then
		local function swap_in_out(option)
			local value = parms[option]
			if value == 'in' then
				parms[option] = 'out'
			elseif value == 'out' then
				parms[option] = 'in'
			end
		end
		swap_in_out('abbr')
		swap_in_out('lk')
		if parms.opt_spell_in and not parms.opt_spell_out then
			-- For simplicity, and because it does not appear to be needed,
			-- user cannot set an option to spell the output only.
			parms.opt_spell_in = nil
			parms.opt_spell_out = true
		end
	end
	if parms.opt_spell_upper then
		parms.spell_upper = parms.opt_flip and 'out' or 'in'
	end
	if parms.opt_table or parms.opt_tablecen then
		if abbr_entered == nil and parms.lk == nil then
			parms.opt_values = true
		end
		parms.table_align = parms.opt_table and 'right' or 'center'
	end
	if parms.table_align or parms.opt_sortable_on then
		parms.need_table_or_sort = true
	end
	local disp_joins = text_code.disp_joins
	local default_joins = disp_joins['b']
	parms.join_between = default_joins[3] or '; '
	local disp = parms.disp
	if disp == nil then  -- special case for the most common setting
		parms.joins = default_joins
	elseif disp == 'x' then
		-- Later, parms.joins is set from the input parameters.
	else
		-- Old template does this.
		local abbr = parms.abbr
		if disp == 'slash' then
			if abbr_entered == nil then
				disp = 'slash-nbsp'
			elseif abbr == 'in' or abbr == 'out' then
				disp = 'slash-sp'
			else
				disp = 'slash-nosp'
			end
		elseif disp == 'sqbr' then
			if abbr == 'on' then
				disp = 'sqbr-nbsp'
			else
				disp = 'sqbr-sp'
			end
		end
		parms.joins = disp_joins[disp] or default_joins
		parms.join_between = parms.joins[3] or parms.join_between
		parms.wantname = parms.joins.wantname
	end
	if (en_default and not parms.opt_lang_local and (parms[1] or ''):find('%d')) or parms.opt_lang_en then
		from_en_table = nil
	end
	if en_default and from_en_table then
		-- For hiwiki: localized symbol/name is defined with the US symbol/name field,
		-- and is used if output uses localized numbers.
		parms.opt_sp_us = true
	end
	return true
end

local function get_values(parms)
	-- If successful, update parms and return true, v, i where
	--   v = table of input values
	--   i = index to next entry in parms after those processed here
	-- or return false, t where t is an error message table.
	local valinfo = collection()  -- numbered table of input values
	local range = collection()  -- numbered table of range items (having, for example, 2 range items requires 3 input values)
	local had_nocomma  -- true if removed "nocomma" kludge from second parameter (like "tonocomma")
	local parm2 = strip(parms[2])
	if parm2 and parm2:sub(-7, -1) == 'nocomma' then
		parms[2] = strip(parm2:sub(1, -8))
		parms.opt_nocomma = true
		had_nocomma = true
	end
	local function extractor(i)
		-- If the parameter is not a value, try unpacking it as a range ("1-23" for "1 to 23").
		-- However, "-1-2/3" is a negative fraction (-1⅔), so it must be extracted first.
		-- Do not unpack a parameter if it is like "3-1/2" which is sometimes incorrectly
		-- used instead of "3+1/2" (and which should not be interpreted as "3 to ½").
		-- Unpacked items are inserted into the parms table.
		-- The tail recursion allows combinations like "1x2 to 3x4".
		local valstr = strip(parms[i])  -- trim so any '-' as a negative sign will be at start
		local success, result = extract_number(parms, valstr, i > 1)
		if not success and valstr and i < 20 then  -- check i to limit abuse
			local lhs, sep, rhs = valstr:match('^(%S+)%s+(%S+)%s+(%S.*)')
			if lhs and not (sep == '-' and rhs:match('/')) then
				if sep:find('%d') then
					return success, result  -- to reject {{convert|1 234 567|m}} with a decent message (en only)
				end
				parms[i] = rhs
				table.insert(parms, i, sep)
				table.insert(parms, i, lhs)
				return extractor(i)
			end
			if not valstr:match('%-.*/') then
				for _, sep in ipairs(text_code.ranges.words) do
					local start, stop = valstr:find(sep, 2, true)  -- start at 2 to skip any negative sign for range '-'
					if start then
						parms[i] = valstr:sub(stop + 1)
						table.insert(parms, i, sep)
						table.insert(parms, i, valstr:sub(1, start - 1))
						return extractor(i)
					end
				end
			end
		end
		return success, result
	end
	local i = 1
	local is_change
	while true do
		local success, info = extractor(i)  -- need to set parms.opt_nocomma before calling this
		if not success then return false, info end
		i = i + 1
		if is_change then
			info.is_change = true  -- value is after "±" and so is a change (significant for range like {{convert|5|±|5|°C}})
			is_change = nil
		end
		valinfo:add(info)
		local range_item = get_range(strip(parms[i]))
		if not range_item then
			break
		end
		i = i + 1
		range:add(range_item)
		if type(range_item) == 'table' then
			-- For range "x", if append unit to some values, append it to all.
			parms.in_range_x = parms.in_range_x or range_item.in_range_x
			parms.out_range_x = parms.out_range_x or range_item.out_range_x
			parms.abbr_range_x = parms.abbr_range_x or range_item.abbr_range_x
			is_change = range_item.is_range_change
		end
	end
	if range.n > 0 then
		if range.n > 30 then  -- limit abuse, although 4 is a more likely upper limit
			return false, { 'cvt_invalid_num' }  -- misleading message but it will do
		end
		parms.range = range
	elseif had_nocomma then
		return false, { 'cvt_unknown', parm2 }
	end
	return true, valinfo, i
end

local function simple_get_values(parms)
	-- If input is like "{{convert|valid_value|valid_unit|...}}",
	-- return true, i, in_unit, in_unit_table
	-- i = index in parms of what follows valid_unit, if anything.
	-- The valid_value is not negative and does not use a fraction, and
	-- no options requiring further processing of the input are used.
	-- Otherwise, return nothing or return false, parm1 for caller to interpret.
	-- Testing shows this function is successful for 96% of converts in articles,
	-- and that on average it speeds up converts by 8%.
	local clean = to_en(strip(parms[1] or ''), parms)
	if parms.opt_ri or parms.opt_spell_in or #clean > 10 or not clean:match('^[0-9.]+$') then
		return false, clean
	end
	local value = tonumber(clean)
	if not value then return end
	local info = {
		value = value,
		altvalue = value,
		singular = (value == 1),
		clean = clean,
		show = with_separator(parms, clean),
	}
	local in_unit = strip(parms[2])
	local success, in_unit_table = lookup(parms, in_unit, 'no_combination')
	if not success then return end
	in_unit_table.valinfo = { info }
	return true, 3, in_unit, in_unit_table
end

local function wikidata_call(parms, operation, ...)
	-- Return true, s where s is the result of a Wikidata operation,
	-- or return false, t where t is an error message table.
	local function worker(...)
		wikidata_code = wikidata_code or require(wikidata_module)
		wikidata_data = wikidata_data or mw.loadData(wikidata_data_module)
		return wikidata_code[operation](wikidata_data, ...)
	end
	local success, status, result = pcall(worker, ...)
	if success then
		return status, result
	end
	if parms.opt_sortable_debug then
		-- Use debug=yes to crash if an error while accessing Wikidata.
		error('Error accessing Wikidata: ' .. status, 0)
	end
	return false, { 'cvt_wd_fail' }
end

local function get_parms(parms, args)
	-- If successful, update parms and return true, unit where
	--   parms is a table of all arguments passed to the template
	--        converted to named arguments, and
	--   unit is the input unit table;
	-- or return false, t where t is an error message table.
	-- For special processing (not a convert), can also return
	-- true, wikitext where wikitext is the final result.
	-- The returned input unit table may be for a fake unit using the specified
	-- unit code as the symbol and name, and with bad_mcode = message code table.
	-- MediaWiki removes leading and trailing whitespace from the values of
	-- named arguments. However, the values of numbered arguments include any
	-- whitespace entered in the template, and whitespace is used by some
	-- parameters (example: the numbered parameters associated with "disp=x").
	local kv_pairs = {}  -- table of input key:value pairs where key is a name; needed because cannot iterate parms and add new fields to it
	for k, v in pairs(args) do
		if type(k) == 'number' or k == 'test' then  -- parameter "test" is reserved for testing and is not translated
			parms[k] = v
		else
			kv_pairs[k] = v
		end
	end
	if parms.test == 'wikidata' then
		local ulookup = function (ucode)
			-- Use empty table for parms so it does not accumulate results when used repeatedly.
			return lookup({}, ucode, 'no_combination')
		end
		return wikidata_call(parms, '_listunits', ulookup)
	end
	local success, msg = translate_parms(parms, kv_pairs)
	if not success then return false, msg end
	if parms.input then
		success, msg = wikidata_call(parms, '_adjustparameters', parms, 1)
		if not success then return false, msg end
	end
	local success, i, in_unit, in_unit_table = simple_get_values(parms)
	if not success then
		if type(i) == 'string' and i:match('^NNN+$') then
			-- Some infoboxes have examples like {{convert|NNN|m}} (3 or more "N").
			-- Output an empty string for these.
			return false, { 'cvt_no_output' }
		end
		local valinfo
		success, valinfo, i = get_values(parms)
		if not success then return false, valinfo end
		in_unit = strip(parms[i])
		i = i + 1
		success, in_unit_table = lookup(parms, in_unit, 'no_combination')
		if not success then
			in_unit = in_unit or ''
			if parms.opt_ignore_error then  -- display given unit code with no error (for use with {{val}})
				in_unit_table = ''  -- suppress error message and prevent processing of output unit
			end
			in_unit_table = setmetatable({
				symbol = in_unit, name2 = in_unit, utype = in_unit,
				scale = 1, default = '', defkey = '', linkey = '',
				bad_mcode = in_unit_table }, unit_mt)
		end
		in_unit_table.valinfo = valinfo
	end
	if parms.test == 'msg' then
		-- Am testing the messages produced when no output unit is specified, and
		-- the input unit has a missing or invalid default.
		-- Set two units for testing that.
		-- LATER: Remove this code.
		if in_unit == 'chain' then
			in_unit_table.default = nil  -- no default
		elseif in_unit == 'rd' then
			in_unit_table.default  = "ft!X!m"  -- an invalid expression
		end
	end
	in_unit_table.inout = 'in'  -- this is an input unit
	if not parms.range then
		local success, inext, composite_unit = get_composite(parms, i, in_unit_table)
		if not success then return false, inext end
		if composite_unit then
			in_unit_table = composite_unit
			i = inext
		end
	end
	if in_unit_table.builtin == 'mach' then
		-- As with old template, a number following Mach as the input unit is the altitude,
		-- and there is no way to specify an altitude for the output unit.
		-- Could put more code in this function to get any output unit and check for
		-- an altitude following that unit.
		local success, info = extract_number(parms, parms[i], false, true)
		if success then
			i = i + 1
			in_unit_table.altitude = info.value
		end
	end
	local word = strip(parms[i])
	i = i + 1
	local precision, is_bad_precision
	local function set_precision(text)
		local number, is_integer = get_number(text)
		if number then
			if is_integer then
				precision = number
			else
				precision = text
				is_bad_precision = true
			end
			return true  -- text was used for precision, good or bad
		end
	end
	if word and not set_precision(word) then
		parms.out_unit = parms.out_unit or word
		if set_precision(strip(parms[i])) then
			i = i + 1
		end
	end
	if parms.opt_adj_mid then
		word = parms[i]
		i = i + 1
		if word then  -- mid-text words
			if word:sub(1, 1) == '-' then
				parms.mid = word
			else
				parms.mid = ' ' .. word
			end
		end
	end
	if parms.opt_one_preunit then
		parms[parms.opt_flip and 'preunit2' or 'preunit1'] = preunits(1, parms[i])
		i = i + 1
	end
	if parms.disp == 'x' then
		-- Following is reasonably compatible with the old template.
		local first = parms[i] or ''
		local second = parms[i+1] or ''
		i = i + 2
		if strip(first) == '' then  -- user can enter '&#32;' rather than ' ' to avoid the default
			first = ' [&nbsp;' .. first
			second = '&nbsp;]' .. second
		end
		parms.joins = { first, second }
	elseif parms.opt_two_preunits then
		local p1, p2 = preunits(2, parms[i], parms[i+1])
		i = i + 2
		if parms.preunit1 then
			-- To simplify documentation, allow unlikely use of adj=pre with disp=preunit
			-- (however, an output unit must be specified with adj=pre and with disp=preunit).
			parms.preunit1 = parms.preunit1 .. p1
			parms.preunit2 = p2
		else
			parms.preunit1, parms.preunit2 = p1, p2
		end
	end
	if precision == nil then
		if set_precision(strip(parms[i])) then
			i = i + 1
		end
	end
	if is_bad_precision then
		add_warning(parms, 1, 'cvt_bad_prec', precision)
	else
		parms.precision = precision
	end
	for j = i, i + 3 do
		local parm = parms[j]  -- warn if find a non-empty extraneous parameter
		if parm and parm:match('%S') then
			add_warning(parms, 1, 'cvt_unknown_option', parm)
			break
		end
	end
	return true, in_unit_table
end

local function record_default_precision(parms, out_current, precision)
	-- If necessary, adjust parameters and return a possibly adjusted precision.
	-- When converting a range of values where a default precision is required,
	-- that default is calculated for each value because the result sometimes
	-- depends on the precise input and output values. This function may cause
	-- the entire convert process to be repeated in order to ensure that the
	-- same default precision is used for each individual convert.
	-- If that were not done, a range like 1000 to 1000.4 may give poor results
	-- because the first output could be heavily rounded, while the second is not.
	-- For range 1000.4 to 1000, this function can give the second convert the
	-- same default precision that was used for the first.
	if not parms.opt_round_each then
		local maxdef = out_current.max_default_precision
		if maxdef then
			if maxdef < precision then
				parms.do_convert_again = true
				out_current.max_default_precision = precision
			else
				precision = out_current.max_default_precision
			end
		else
			out_current.max_default_precision = precision
		end
	end
	return precision
end

local function default_precision(parms, invalue, inclean, denominator, outvalue, in_current, out_current, extra)
	-- Return a default value for precision (an integer like 2, 0, -2).
	-- If denominator is not nil, it is the value of the denominator in inclean.
	-- Code follows procedures used in old template.
	local fudge = 1e-14  -- {{Order of magnitude}} adds this, so we do too
	local prec, minprec, adjust
	local subunit_ignore_trailing_zero
	local subunit_more_precision  -- kludge for "in" used in input like "|2|ft|6|in"
	local composite = in_current.composite
	if composite then
		subunit_ignore_trailing_zero = true  -- input "|2|st|10|lb" has precision 0, not -1
		if composite[#composite].exception == 'subunit_more_precision' then
			subunit_more_precision = true  -- do not use standard precision with input like "|2|ft|6|in"
		end
	end
	if denominator and denominator > 0 then
		prec = math.max(log10(denominator), 1)
	else
		-- Count digits after decimal mark, handling cases like '12.345e6'.
		local exponent
		local integer, dot, decimals, expstr = inclean:match('^(%d*)(%.?)(%d*)(.*)')
		local e = expstr:sub(1, 1)
		if e == 'e' or e == 'E' then
			exponent = tonumber(expstr:sub(2))
		end
		if dot == '' then
			prec = subunit_ignore_trailing_zero and 0 or -integer:match('0*$'):len()
		else
			prec = #decimals
		end
		if exponent then
			-- So '1230' and '1.23e3' both give prec = -1, and '0.00123' and '1.23e-3' give 5.
			prec = prec - exponent
		end
	end
	if in_current.istemperature and out_current.istemperature then
		-- Converting between common temperatures (°C, °F, °R, K); not keVT.
		-- Kelvin value can be almost zero, or small but negative due to precision problems.
		-- Also, an input value like -300 C (below absolute zero) gives negative kelvins.
		-- Calculate minimum precision from absolute value.
		adjust = 0
		local kelvin = abs((invalue - in_current.offset) * in_current.scale)
		if kelvin < 1e-8 then  -- assume nonzero due to input or calculation precision problem
			minprec = 2
		else
			minprec = 2 - floor(log10(kelvin) + fudge)  -- 3 sigfigs in kelvin
		end
	else
		if invalue == 0 or outvalue <= 0 then
			-- We are never called with a negative outvalue, but it might be zero.
			-- This is special-cased to avoid calculation exceptions.
			return record_default_precision(parms, out_current, 0)
		end
		if out_current.exception == 'integer_more_precision' and floor(invalue) == invalue then
			-- With certain output units that sometimes give poor results
			-- with default rounding, use more precision when the input
			-- value is equal to an integer. An example of a poor result
			-- is when input 50 gives a smaller output than input 49.5.
			-- Experiment shows this helps, but it does not eliminate all
			-- surprises because it is not clear whether "50" should be
			-- interpreted as "from 45 to 55" or "from 49.5 to 50.5".
			adjust = -log10(in_current.scale)
		elseif subunit_more_precision then
			-- Conversion like "{{convert|6|ft|1|in|cm}}" (where subunit is "in")
			-- has a non-standard adjust value, to give more output precision.
			adjust = log10(out_current.scale) + 2
		else
			adjust = log10(abs(invalue / outvalue))
		end
		adjust = adjust + log10(2)
		-- Ensure that the output has at least two significant figures.
		minprec = 1 - floor(log10(outvalue) + fudge)
	end
	if extra then
		adjust = extra.adjust or adjust
		minprec = extra.minprec or minprec
	end
	return record_default_precision(parms, out_current, math.max(floor(prec + adjust), minprec))
end

local function convert(parms, invalue, info, in_current, out_current)
	-- Convert given input value from one unit to another.
	-- Return output_value (a number) if a simple convert, or
	-- return f, t where
	--   f = true, t = table of information with results, or
	--   f = false, t = error message table.
	local inscale = in_current.scale
	local outscale = out_current.scale
	if not in_current.iscomplex and not out_current.iscomplex then
		return invalue * (inscale / outscale)  -- minimize overhead for most common case
	end
	if in_current.invert or out_current.invert then
		-- Inverted units, such as inverse length, inverse time, or
		-- fuel efficiency. Built-in units do not have invert set.
		if (in_current.invert or 1) * (out_current.invert or 1) < 0 then
			return 1 / (invalue * inscale * outscale)
		end
		return invalue * (inscale / outscale)
	elseif in_current.offset then
		-- Temperature (there are no built-ins for this type of unit).
		if info.is_change then
			return invalue * (inscale / outscale)
		end
		return (invalue - in_current.offset) * (inscale / outscale) + out_current.offset
	else
		-- Built-in unit.
		local in_builtin = in_current.builtin
		local out_builtin = out_current.builtin
		if in_builtin and out_builtin then
			if in_builtin == out_builtin then
				return invalue
			end
			-- There are no cases (yet) where need to convert from one
			-- built-in unit to another, so this should never occur.
			return false, { 'cvt_bug_convert' }
		end
		if in_builtin == 'mach' or out_builtin == 'mach' then
			local adjust
			if in_builtin == 'mach' then
				inscale = speed_of_sound(in_current.altitude)
				adjust = outscale / 0.1
			else
				outscale = speed_of_sound(out_current.altitude)
				adjust = 0.1 / inscale
			end
			return true, {
				outvalue = invalue * (inscale / outscale),
				adjust = log10(adjust) + log10(2),
			}
		elseif in_builtin == 'hand' then
			-- 1 hand = 4 inches; 1.2 hands = 6 inches.
			-- Decimals of a hand are only defined for the first digit, and
			-- the first fractional digit should be a number of inches (1, 2 or 3).
			-- However, this code interprets the entire fractional part as the number
			-- of inches / 10 (so 1.75 inches would be 0.175 hands).
			-- A value like 12.3 hands is exactly 12*4 + 3 inches; base default precision on that.
			local integer, fracpart = math.modf(invalue)
			local inch_value = 4 * integer + 10 * fracpart  -- equivalent number of inches
			local factor = inscale / outscale
			if factor == 4 then
				-- Am converting to inches: show exact result, and use "inches" not "in" by default.
				if parms.abbr_org == nil then
					out_current.usename = true
				end
				local show = format('%g', abs(inch_value))  -- show and clean are unsigned
				if not show:find('e', 1, true) then
					return true, {
						invalue = inch_value,
						outvalue = inch_value,
						clean = show,
						show = show,
					}
				end
			end
			local outvalue = (integer + 2.5 * fracpart) * factor
			local fracstr = info.clean:match('%.(.*)') or ''
			local fmt
			if fracstr == '' then
				fmt = '%.0f'
			else
				fmt = '%.' .. format('%d', #fracstr - 1) .. 'f'
			end
			return true, {
				invalue = inch_value,
				clean = format(fmt, inch_value),
				outvalue = outvalue,
				minprec = 0,
			}
		end
	end
	return false, { 'cvt_bug_convert' }  -- should never occur
end

local function user_style(parms, i)
	-- Return text for a user-specified style for a table cell, or '' if none,
	-- given i = 1 (input style) or 2 (output style).
	local style = parms[(i == 1) and 'stylein' or 'styleout']
	if style then
		style = style:gsub('"', '')
		if style ~= '' then
			if style:sub(-1) ~= ';' then
				style = style .. ';'
			end
			return style
		end
	end
	return ''
end

local function make_table_or_sort(parms, invalue, info, in_current, scaled_top)
	-- Set options to handle output for a table or a sort key, or both.
	-- The text sort key is based on the value resulting from converting
	-- the input to a fake base unit with scale = 1, and other properties
	-- required for a conversion derived from the input unit.
	-- For other modules, return the sort key in a hidden span element, and
	-- the scaled value used to generate the sort key.
	-- If scaled_top is set, it is the scaled value of the numerator of a per unit
	-- to be combined with this unit (the denominator) to make the sort key.
	-- Scaling only works with units that convert with a factor (not temperature).
	local sortkey, scaled_value
	if parms.opt_sortable_on then
		local base = {  -- a fake unit with enough fields for a valid convert
			scale = 1,
			invert = in_current.invert and 1,
			iscomplex = in_current.iscomplex,
			offset = in_current.offset and 0,
		}
		local outvalue, extra = convert(parms, invalue, info, in_current, base)
		if extra then
			outvalue = extra.outvalue
		end
		if in_current.istemperature then
			-- Have converted to kelvin; assume numbers close to zero have a
			-- rounding error and should be zero.
			if abs(outvalue) < 1e-12 then
				outvalue = 0
			end
		end
		if scaled_top and outvalue ~= 0 then
			outvalue = scaled_top / outvalue
		end
		scaled_value = outvalue
		if not valid_number(outvalue) then
			if outvalue < 0 then
				sortkey = '1000000000000000000'
			else
				sortkey = '9000000000000000000'
			end
		elseif outvalue == 0 then
			sortkey = '5000000000000000000'
		else
			local mag = floor(log10(abs(outvalue)) + 1e-14)
			local prefix
			if outvalue > 0 then
				prefix = 7000 + mag
			else
				prefix = 2999 - mag
				outvalue = outvalue + 10^(mag+1)
			end
			sortkey = format('%d', prefix) .. format('%015.0f', floor(outvalue * 10^(14-mag)))
		end
	end
	local sortspan
	if sortkey and not parms.table_align then
		sortspan = parms.opt_sortable_debug and
			'<span data-sort-value="' .. sortkey .. '♠"><span style="border:1px solid">' .. sortkey .. '♠</span></span>' or
			'<span data-sort-value="' .. sortkey .. '♠"></span>'
		parms.join_before = sortspan
	end
	if parms.table_align then
		local sort
		if sortkey then
			sort = ' data-sort-value="' .. sortkey .. '"'
			if parms.opt_sortable_debug then
				parms.join_before = '<span style="border:1px solid">' .. sortkey .. '</span>'
			end
		else
			sort = ''
		end
		local style = 'style="text-align:' .. parms.table_align .. ';'
		local joins = {}
		for i = 1, 2 do
			joins[i] = (i == 1 and '' or '\n|') .. style .. user_style(parms, i) .. '"' .. sort .. '|'
		end
		parms.table_joins = joins
	end
	return sortspan, scaled_value
end

local cvt_to_hand

local function cvtround(parms, info, in_current, out_current)
	-- Return true, t where t is a table with the conversion results; fields:
	--   show = rounded, formatted string with the result of converting value in info,
	--      using the rounding specified in parms.
	--   singular = true if result (after rounding and ignoring any negative sign)
	--      is "1", or like "1.00", or is a fraction with value < 1;
	--   (and more fields shown below, and a calculated 'absvalue' field).
	-- or return false, t where t is an error message table.
	-- Input info.clean uses en digits (it has been translated, if necessary).
	-- Output show uses en or non-en digits as appropriate, or can be spelled.
	if out_current.builtin == 'hand' then
		return cvt_to_hand(parms, info, in_current, out_current)
	end
	local invalue = in_current.builtin == 'hand' and info.altvalue or info.value
	local outvalue, extra = convert(parms, invalue, info, in_current, out_current)
	if parms.need_table_or_sort then
		parms.need_table_or_sort = nil  -- process using first input value only
		make_table_or_sort(parms, invalue, info, in_current)
	end
	if extra then
		if not outvalue then return false, extra end
		invalue = extra.invalue or invalue
		outvalue = extra.outvalue
	end
	if not valid_number(outvalue) then
		return false, { 'cvt_invalid_num' }
	end
	local isnegative
	if outvalue < 0 then
		isnegative = true
		outvalue = -outvalue
	end
	local precision, show, exponent
	local denominator = out_current.frac
	if denominator then
		show = fraction_table(outvalue, denominator)
	else
		precision = parms.precision
		if not precision then
			if parms.sigfig then
				show, exponent = make_sigfig(outvalue, parms.sigfig)
			elseif parms.opt_round then
				local n = parms.opt_round
				if n == 0.5 then
					local integer, fracpart = math.modf(floor(2 * outvalue + 0.5) / 2)
					if fracpart == 0 then
						show = format('%.0f', integer)
					else
						show = format('%.1f', integer + fracpart)
					end
				else
					show = format('%.0f', floor((outvalue / n) + 0.5) * n)
				end
			else
				local inclean = info.clean
				if extra then
					inclean = extra.clean or inclean
					show = extra.show
				end
				if not show then
					precision = default_precision(parms, invalue, inclean, info.denominator, outvalue, in_current, out_current, extra)
				end
			end
		end
	end
	if precision then
		if precision >= 0 then
			local fudge
			if precision <= 8 then
				-- Add a fudge to handle common cases of bad rounding due to inability
				-- to precisely represent some values. This makes the following work:
				-- {{convert|-100.1|C|K}} and {{convert|5555000|um|m|2}}.
				-- Old template uses #expr round, which invokes PHP round().
				-- LATER: Investigate how PHP round() works.
				fudge = 2e-14
			else
				fudge = 0
			end
			local fmt = '%.' .. format('%d', precision) .. 'f'
			local success
			success, show = pcall(format, fmt, outvalue + fudge)
			if not success then
				return false, { 'cvt_big_prec', tostring(precision) }
			end
		else
			precision = -precision  -- #digits to zero (in addition to any digits after dot)
			local shift = 10 ^ precision
			show = format('%.0f', outvalue/shift)
			if show ~= '0' then
				exponent = #show + precision
			end
		end
	end
	local t = format_number(parms, show, exponent, isnegative)
	if type(show) == 'string' then
		-- Set singular using match because on some systems 0.99999999999999999 is 1.0.
		if exponent then
			t.singular = (exponent == 1 and show:match('^10*$'))
		else
			t.singular = (show == '1' or show:match('^1%.0*$'))
		end
	else
		t.fraction_table = show
		t.singular = (outvalue <= 1)  -- cannot have 'fraction == 1', but if it were possible it would be singular
	end
	t.raw_absvalue = outvalue  -- absolute value before rounding
	return true, setmetatable(t, {
		__index = function (self, key)
			if key == 'absvalue' then
				-- Calculate absolute value after rounding, if needed.
				local clean, exponent = rawget(self, 'clean'), rawget(self, 'exponent')
				local value = tonumber(clean)  -- absolute value (any negative sign has been ignored)
				if exponent then
					value = value * 10^exponent
				end
				rawset(self, key, value)
				return value
			end
		end })
end

function cvt_to_hand(parms, info, in_current, out_current)
	-- Convert input to hands, inches.
	-- Return true, t where t is a table with the conversion results;
	-- or return false, t where t is an error message table.
	if parms.abbr_org == nil then
		out_current.usename = true  -- default is to show name not symbol
	end
	local precision = parms.precision
	local frac = out_current.frac
	if not frac and precision and precision > 1 then
		frac = (precision == 2) and 2 or 4
	end
	local out_next = out_current.out_next
	if out_next then
		-- Use magic knowledge to determine whether the next unit is inches without requiring i18n.
		-- The following ensures that when the output combination "hand in" is used, the inches
		-- value is rounded to match the hands value. Also, displaying say "61½" instead of 61.5
		-- is better as 61.5 implies the value is not 61.4.
		if out_next.exception == 'subunit_more_precision' then
			out_next.frac = frac
		end
	end
	-- Convert to inches; calculate hands from that.
	local dummy_unit_table = { scale = out_current.scale / 4, frac = frac }
	local success, outinfo = cvtround(parms, info, in_current, dummy_unit_table)
	if not success then return false, outinfo end
	local tfrac = outinfo.fraction_table
	local inches = outinfo.raw_absvalue
	if tfrac then
		inches = floor(inches)  -- integer part only; fraction added later
	else
		inches = floor(inches + 0.5)  -- a hands measurement never shows decimals of an inch
	end
	local hands, inches = divide(inches, 4)
	outinfo.absvalue = hands + inches/4  -- supposed to be the absolute rounded value, but this is close enough
	local inchstr = tostring(inches)  -- '0', '1', '2' or '3'
	if precision and precision <= 0 then  -- using negative or 0 for precision rounds to nearest hand
		hands = floor(outinfo.raw_absvalue/4 + 0.5)
		inchstr = ''
	elseif tfrac then
		-- Always show an integer before fraction (like "15.0½") because "15½" means 15-and-a-half hands.
		inchstr = numdot .. format_fraction(parms, 'out', false, inchstr, tfrac.numstr, tfrac.denstr)
	else
		inchstr = numdot .. from_en(inchstr)
	end
	outinfo.show = outinfo.sign .. with_separator(parms, format('%.0f', hands)) .. inchstr
	return true, outinfo
end

local function evaluate_condition(value, condition)
	-- Return true or false from applying a conditional expression to value,
	-- or throw an error if invalid.
	-- A very limited set of expressions is supported:
	--    v < 9
	--    v * 9 < 9
	-- where
	--    'v' is replaced with value
	--    9 is any number (as defined by Lua tonumber)
	--      only en digits are accepted
	--    '<' can also be '<=' or '>' or '>='
	-- In addition, the following form is supported:
	--    LHS and RHS
	-- where
	--    LHS, RHS = any of above expressions.
	local function compare(value, text)
		local arithop, factor, compop, limit = text:match('^%s*v%s*([*]?)(.-)([<>]=?)(.*)$')
		if arithop == nil then
			error('Invalid default expression', 0)
		elseif arithop == '*' then
			factor = tonumber(factor)
			if factor == nil then
				error('Invalid default expression', 0)
			end
			value = value * factor
		end
		limit = tonumber(limit)
		if limit == nil then
			error('Invalid default expression', 0)
		end
		if compop == '<' then
			return value < limit
		elseif compop == '<=' then
			return value <= limit
		elseif compop == '>' then
			return value > limit
		elseif compop == '>=' then
			return value >= limit
		end
		error('Invalid default expression', 0)  -- should not occur
	end
	local lhs, rhs = condition:match('^(.-%W)and(%W.*)')
	if lhs == nil then
		return compare(value, condition)
	end
	return compare(value, lhs) and compare(value, rhs)
end

local function get_default(value, unit_table)
	-- Return true, s where s = name of unit's default output unit,
	-- or return false, t where t is an error message table.
	-- Some units have a default that depends on the input value
	-- (the first value if a range of values is used).
	-- If '!' is in the default, the first bang-delimited field is an
	-- expression that uses 'v' to represent the input value.
	-- Example: 'v < 120 ! small ! big ! suffix' (suffix is optional)
	-- evaluates 'v < 120' as a boolean with result
	-- 'smallsuffix' if (value < 120), or 'bigsuffix' otherwise.
	-- Input must use en digits and '.' decimal mark.
	local default = data_code.default_exceptions[unit_table.defkey or unit_table.symbol] or unit_table.default
	if not default then
		local per = unit_table.per
		if per then
			local function a_default(v, u)
				local success, ucode = get_default(v, u)
				if not success then
					return '?'  -- an unlikely error has occurred; will cause lookup of default to fail
				end
				-- Attempt to use only the first unit if a combination or output multiple.
				-- This is not bulletproof but should work for most cases.
				-- Where it does not work, the convert will need to specify the wanted output unit.
				local t = all_units[ucode]
				if t then
					local combo = t.combination
					if combo then
						-- For a multiple like ftin, the "first" unit (ft) is last in the combination.
						local i = t.multiple and table_len(combo) or 1
						ucode = combo[i]
					end
				else
					-- Try for an automatically generated combination.
					local item = ucode:match('^(.-)%+') or ucode:match('^(%S+)%s')
					if all_units[item] then
						return item
					end
				end
				return ucode
			end
			local unit1, unit2 = per[1], per[2]
			local def1 = (unit1 and a_default(value, unit1) or unit_table.vprefix or '')
			local def2 = a_default(1, unit2)  -- 1 because per unit of denominator
			return true, def1 .. '/' .. def2
		end
		return false, { 'cvt_no_default', unit_table.symbol }
	end
	if default:find('!', 1, true) == nil then
		return true, default
	end
	local t = split(default, '!')
	if #t == 3 or #t == 4 then
		local success, result = pcall(evaluate_condition, value, t[1])
		if success then
			default = result and t[2] or t[3]
			if #t == 4 then
				default = default .. t[4]
			end
			return true, default
		end
	end
	return false, { 'cvt_bad_default', unit_table.symbol }
end

local linked_pages  -- to record linked pages so will not link to the same page more than once

local function unlink(unit_table)
	-- Forget that the given unit has previously been linked (if it has).
	-- That is needed when processing a range of inputs or outputs when an id
	-- for the first range value may have been evaluated, but only an id for
	-- the last value is displayed, and that id may need to be linked.
	linked_pages[unit_table.unitcode or unit_table] = nil
end

local function make_link(link, id, unit_table)
	-- Return wikilink "[[link|id]]", possibly abbreviated as in examples:
	--   [[Mile|mile]]  --> [[mile]]
	--   [[Mile|miles]] --> [[mile]]s
	-- However, just id is returned if:
	-- * no link given (so caller does not need to check if a link was defined); or
	-- * link has previously been used during the current convert (to avoid overlinking).
	local link_key
	if unit_table then
		link_key = unit_table.unitcode or unit_table
	else
		link_key = link
	end
	if not link or link == '' or linked_pages[link_key] then
		return id
	end
	linked_pages[link_key] = true
	-- Following only works for language en, but it should be safe on other wikis,
	-- and overhead of doing it generally does not seem worthwhile.
	local l = link:sub(1, 1):lower() .. link:sub(2)
	if link == id or l == id then
		return '[[' .. id .. ']]'
	elseif link .. 's' == id or l .. 's' == id then
		return '[[' .. id:sub(1, -2) .. ']]s'
	else
		return '[[' .. link .. '|' .. id .. ']]'
	end
end

local function variable_name(clean, unit_table)
	-- For slwiki, a unit name depends on the value.
	-- Parameter clean is the unsigned rounded value in en digits, as a string.
	-- Value             Source    Example for "m"
	-- integer 1:        name1     meter  (also is the name of the unit)
	-- integer 2:        var{1}    metra
	-- integer 3 and 4:  var{2}    metri
	-- integer else:     var{3}    metrov (0 and 5 or more)
	-- real/fraction:    var{4}    metra
	-- var{i} means the i'th field in unit_table.varname if it exists and has
	-- an i'th field, otherwise name2.
	-- Fields are separated with "!" and are not empty.
	-- A field for a unit using an SI prefix has the prefix name inserted,
	-- replacing '#' if found, or before the field otherwise.
	local vname
	if clean == '1' then
		vname = unit_table.name1
	elseif unit_table.varname then
		local i
		if clean == '2' then
			i = 1
		elseif clean == '3' or clean == '4' then
			i = 2
		elseif clean:find('.', 1, true) then
			i = 4
		else
			i = 3
		end
		if i > 1 and varname == 'pl' then
			i = i - 1
		end
		vname = split(unit_table.varname, '!')[i]
	end
	if vname then
		local si_name = rawget(unit_table, 'si_name') or ''
		local pos = vname:find('#', 1, true)
		if pos then
			vname = vname:sub(1, pos - 1) .. si_name .. vname:sub(pos + 1)
		else
			vname = si_name .. vname
		end
		return vname
	end
	return unit_table.name2
end

local function linked_id(parms, unit_table, key_id, want_link, clean)
	-- Return final unit id (symbol or name), optionally with a wikilink,
	-- and update unit_table.sep if required.
	-- key_id is one of: 'symbol', 'sym_us', 'name1', 'name1_us', 'name2', 'name2_us'.
	local abbr_on = (key_id == 'symbol' or key_id == 'sym_us')
	if abbr_on and want_link then
		local symlink = rawget(unit_table, 'symlink')
		if symlink then
			return symlink  -- for exceptions that have the linked symbol built-in
		end
	end
	local multiplier = rawget(unit_table, 'multiplier')
	local per = unit_table.per
	if per then
		local paren1, paren2 = '', ''  -- possible parentheses around bottom unit
		local unit1 = per[1]  -- top unit_table, or nil
		local unit2 = per[2]  -- bottom unit_table
		if abbr_on then
			if not unit1 then
				unit_table.sep = ''  -- no separator in "$2/acre"
			end
			if not want_link then
				local symbol = unit_table.symbol_raw
				if symbol then
					return symbol  -- for exceptions that have the symbol built-in
				end
			end
			if (unit2.symbol):find('⋅', 1, true) then
				paren1, paren2 = '(', ')'
			end
		end
		local key_id2  -- unit2 is always singular
		if key_id == 'name2' then
			key_id2 = 'name1'
		elseif key_id == 'name2_us' then
			key_id2 = 'name1_us'
		else
			key_id2 = key_id
		end
		local result
		if abbr_on then
			result = '/'
		elseif omitsep then
			result = per_word
		elseif unit1 then
			result = ' ' .. per_word .. ' '
		else
			result = per_word .. ' '
		end
		if want_link and unit_table.link then
			if abbr_on or not varname then
				result = (unit1 and linked_id(parms, unit1, key_id, false, clean) or '') .. result .. linked_id(parms, unit2, key_id2, false, '1')
			else
				result = (unit1 and variable_name(clean, unit1) or '') .. result .. variable_name('1', unit2)
			end
			if omit_separator(result) then
				unit_table.sep = ''
			end
			return make_link(unit_table.link, result, unit_table)
		end
		if unit1 then
			result = linked_id(parms, unit1, key_id, want_link, clean) .. result
			if unit1.sep then
				unit_table.sep = unit1.sep
			end
		elseif omitsep then
			unit_table.sep = ''
		end
		return result .. paren1 .. linked_id(parms, unit2, key_id2, want_link, '1') .. paren2
	end
	if multiplier then
		-- A multiplier (like "100" in "100km") forces the unit to be plural.
		multiplier = from_en(multiplier)
		if not omitsep then
			multiplier = multiplier .. (abbr_on and '&nbsp;' or ' ')
		end
		if not abbr_on then
			if key_id == 'name1' then
				key_id = 'name2'
			elseif key_id == 'name1_us' then
				key_id = 'name2_us'
			end
		end
	else
		multiplier = ''
	end
	local id = unit_table.fixed_name or ((varname and not abbr_on) and variable_name(clean, unit_table) or unit_table[key_id])
	if omit_separator(id) then
		unit_table.sep = ''
	end
	if want_link then
		local link = data_code.link_exceptions[unit_table.linkey or unit_table.symbol] or unit_table.link
		if link then
			local before = ''
			local i = unit_table.customary
			if i == 1 and parms.opt_sp_us then
				i = 2  -- show "U.S." not "US"
			end
			if i == 3 and abbr_on then
				i = 4  -- abbreviate "imperial" to "imp"
			end
			local customary = text_code.customary_units[i]
			if customary then
				-- LATER: This works for language en only, but it's esoteric so ignore for now.
				local pertext
				if id:sub(1, 1) == '/' then
					-- Want unit "/USgal" to display as "/U.S. gal", not "U.S. /gal".
					pertext = '/'
					id = id:sub(2)
				elseif id:sub(1, 4) == 'per ' then
					-- Similarly want "per U.S. gallon", not "U.S. per gallon" (but in practice this is unlikely to be used).
					pertext = 'per '
					id = id:sub(5)
				else
					pertext = ''
				end
				-- Omit any "US"/"U.S."/"imp"/"imperial" from start of id since that will be inserted.
				local removes = (i < 3) and { 'US&nbsp;', 'US ', 'U.S.&nbsp;', 'U.S. ' } or { 'imp&nbsp;', 'imp ', 'imperial ' }
				for _, prefix in ipairs(removes) do
					local plen = #prefix
					if id:sub(1, plen) == prefix then
						id = id:sub(plen + 1)
						break
					end
				end
				before = pertext .. make_link(customary.link, customary[1]) .. ' '
			end
			id = before .. make_link(link, id, unit_table)
		end
	end
	return multiplier .. id
end

local function make_id(parms, which, unit_table)
	-- Return id, f where
	--   id = unit name or symbol, possibly modified
	--   f = true if id is a name, or false if id is a symbol
	-- using the value for index 'which', and for 'in' or 'out' (unit_table.inout).
	-- Result is '' if no symbol/name is to be used.
	-- In addition, set unit_table.sep = ' ' or '&nbsp;' or ''
	-- (the separator that caller will normally insert before the id).
	if parms.opt_values then
		unit_table.sep = ''
		return ''
	end
	local inout = unit_table.inout
	local info = unit_table.valinfo[which]
	local abbr_org = parms.abbr_org
	local adjectival = parms.opt_adjectival
	local lk = parms.lk
	local want_link = (lk == 'on' or lk == inout)
	local usename = unit_table.usename
	local singular = info.singular
	local want_name
	if usename then
		want_name = true
	else
		if abbr_org == nil then
			if parms.wantname then
				want_name = true
			end
			if unit_table.usesymbol then
				want_name = false
			end
		end
		if want_name == nil then
			local abbr = parms.abbr
			if abbr == 'on' or abbr == inout or (abbr == 'mos' and inout == 'out') then
				want_name = false
			else
				want_name = true
			end
		end
	end
	local key
	if want_name then
		if lk == nil and unit_table.builtin == 'hand' then
			want_link = true
		end
		if parms.opt_use_nbsp then
			unit_table.sep = '&nbsp;'
		else
			unit_table.sep = ' '
		end
		if parms.opt_singular then
			local value
			if inout == 'in' then
				value = info.value
			else
				value = info.absvalue
			end
			if value then  -- some unusual units do not always set value field
				value = abs(value)
				singular = (0 < value and value < 1.0001)
			end
		end
		if unit_table.engscale then
			-- engscale: so "|1|e3kg" gives "1 thousand kilograms" (plural)
			singular = false
		end
		key = (adjectival or singular) and 'name1' or 'name2'
		if parms.opt_sp_us then
			key = key .. '_us'
		end
	else
		if unit_table.builtin == 'hand' then
			if parms.opt_hand_hh then
				unit_table.symbol = 'hh'  -- LATER: might want i18n applied to this
			end
		end
		unit_table.sep = '&nbsp;'
		key = parms.opt_sp_us and 'sym_us' or 'symbol'
	end
	return linked_id(parms, unit_table, key, want_link, info.clean), want_name
end

local function decorate_value(parms, unit_table, which, number_word)
	-- If needed, update unit_table so values will be shown with extra information.
	-- For consistency with the old template (but different from fmtpower),
	-- the style to display powers of 10 includes "display:none" to allow some
	-- browsers to copy, for example, "10³" as "10^3", rather than as "103".
	local info
	local engscale = unit_table.engscale
	local prefix = unit_table.vprefix
	if engscale or prefix then
		info = unit_table.valinfo[which]
		if info.decorated then
			return  -- do not redecorate if repeating convert
		end
		info.decorated = true
		if engscale then
			local inout = unit_table.inout
			local abbr = parms.abbr
			if (abbr == 'on' or abbr == inout) and not parms.number_word then
				info.show = info.show ..
					'<span style="margin-left:0.2em">×<span style="margin-left:0.1em">' ..
					from_en('10') ..
					'</span></span><s style="display:none">^</s><sup>' ..
					from_en(tostring(engscale.exponent)) .. '</sup>'
			elseif number_word then
				local number_id
				local lk = parms.lk
				if lk == 'on' or lk == inout then
					number_id = make_link(engscale.link, engscale[1])
				else
					number_id = engscale[1]
				end
				-- WP:NUMERAL recommends "&nbsp;" in values like "12 million".
				info.show = info.show .. (parms.opt_adjectival and '-' or '&nbsp;') .. number_id
			end
		end
		if prefix then
			info.show = prefix .. info.show
		end
	end
end

local function process_input(parms, in_current)
	-- Processing required once per conversion.
	-- Return block of text to represent input (value/unit).
	if parms.opt_output_only or parms.opt_output_number_only or parms.opt_output_unit_only then
		parms.joins = { '', '' }
		return ''
	end
	local first_unit
	local composite = in_current.composite  -- nil or table of units
	if composite then
		first_unit = composite[1]
	else
		first_unit = in_current
	end
	local id1, want_name = make_id(parms, 1, first_unit)
	local sep = first_unit.sep  -- separator between value and unit, set by make_id
	local preunit = parms.preunit1
	if preunit then
		sep = ''  -- any separator is included in preunit
	else
		preunit = ''
	end
	if parms.opt_input_unit_only then
		parms.joins = { '', '' }
		if composite then
			local parts = { id1 }
			for i, unit in ipairs(composite) do
				if i > 1 then
					table.insert(parts, (make_id(parms, 1, unit)))
				end
			end
			id1 = table.concat(parts, ' ')
		end
		if want_name and parms.opt_adjectival then
			return preunit .. hyphenated(id1)
		end
		return  preunit .. id1
	end
	if parms.opt_also_symbol and not composite and not parms.opt_flip then
		local join1 = parms.joins[1]
		if join1 == ' (' or join1 == ' [' then
			parms.joins = { ' [' .. first_unit[parms.opt_sp_us and 'sym_us' or 'symbol'] .. ']' .. join1 , parms.joins[2] }
		end
	end
	if in_current.builtin == 'mach' and first_unit.sep ~= '' then  -- '' means omitsep with non-enwiki name
		local prefix = id1 .. '&nbsp;'
		local range = parms.range
		local valinfo = first_unit.valinfo
		local result = prefix .. valinfo[1].show
		if range then
			-- For simplicity and because more not needed, handle one range item only.
			local prefix2 = make_id(parms, 2, first_unit) .. '&nbsp;'
			result = range_text(range[1], want_name, parms, result, prefix2 .. valinfo[2].show, 'in')
		end
		return preunit .. result
	end
	if composite then
		-- Simplify: assume there is no range, and no decoration.
		local mid = (not parms.opt_flip) and parms.mid or ''
		local sep1 = '&nbsp;'
		local sep2 = ' '
		if parms.opt_adjectival and want_name then
			sep1 = '-'
			sep2 = '-'
		end
		if omitsep and sep == '' then
			-- Testing the id of the most significant unit should be sufficient.
			sep1 = ''
			sep2 = ''
		end
		local parts = { first_unit.valinfo[1].show .. sep1 .. id1 }
		for i, unit in ipairs(composite) do
			if i > 1 then
				table.insert(parts, unit.valinfo[1].show .. sep1 .. (make_id(parms, 1, unit)))
			end
		end
		return table.concat(parts, sep2) .. mid
	end
	local add_unit = (parms.abbr == 'mos') or
		parms[parms.opt_flip and 'out_range_x' or 'in_range_x'] or
		(not want_name and parms.abbr_range_x)
	local range = parms.range
	if range and not add_unit then
		unlink(first_unit)
	end
	local id = range and make_id(parms, range.n + 1, first_unit) or id1
	local extra, was_hyphenated = hyphenated_maybe(parms, want_name, sep, id, 'in')
	if was_hyphenated then
		add_unit = false
	end
	local result
	local valinfo = first_unit.valinfo
	if range then
		for i = 0, range.n do
			local number_word
			if i == range.n then
				add_unit = false
				number_word = true
			end
			decorate_value(parms, first_unit, i+1, number_word)
			local show = valinfo[i+1].show
			if add_unit then
				show = show .. first_unit.sep .. (i == 0 and id1 or make_id(parms, i+1, first_unit))
			end
			if i == 0 then
				result = show
			else
				result = range_text(range[i], want_name, parms, result, show, 'in')
			end
		end
	else
		decorate_value(parms, first_unit, 1, true)
		result = valinfo[1].show
	end
	return result .. preunit .. extra
end

local function process_one_output(parms, out_current)
	-- Processing required for each output unit.
	-- Return block of text to represent output (value/unit).
	local inout = out_current.inout  -- normally 'out' but can be 'in' for order=out
	local id1, want_name = make_id(parms, 1, out_current)
	local sep = out_current.sep  -- set by make_id
	local preunit = parms.preunit2
	if preunit then
		sep = ''  -- any separator is included in preunit
	else
		preunit = ''
	end
	if parms.opt_output_unit_only then
		if want_name and parms.opt_adjectival then
			return preunit .. hyphenated(id1)
		end
		return preunit .. id1
	end
	if out_current.builtin == 'mach' and out_current.sep ~= '' then  -- '' means omitsep with non-enwiki name
		local prefix = id1 .. '&nbsp;'
		local range = parms.range
		local valinfo = out_current.valinfo
		local result = prefix .. valinfo[1].show
		if range then
			-- For simplicity and because more not needed, handle one range item only.
			result = range_text(range[1], want_name, parms, result, prefix .. valinfo[2].show, inout)
		end
		return preunit .. result
	end
	local add_unit = (parms[parms.opt_flip and 'in_range_x' or 'out_range_x'] or
		(not want_name and parms.abbr_range_x)) and
		not parms.opt_output_number_only
	local range = parms.range
	if range and not add_unit then
		unlink(out_current)
	end
	local id = range and make_id(parms, range.n + 1, out_current) or id1
	local extra, was_hyphenated = hyphenated_maybe(parms, want_name, sep, id, inout)
	if was_hyphenated then
		add_unit = false
	end
	local result
	local valinfo = out_current.valinfo
	if range then
		for i = 0, range.n do
			local number_word
			if i == range.n then
				add_unit = false
				number_word = true
			end
			decorate_value(parms, out_current, i+1, number_word)
			local show = valinfo[i+1].show
			if add_unit then
				show = show .. out_current.sep .. (i == 0 and id1 or make_id(parms, i+1, out_current))
			end
			if i == 0 then
				result = show
			else
				result = range_text(range[i], want_name, parms, result, show, inout)
			end
		end
	else
		decorate_value(parms, out_current, 1, true)
		result = valinfo[1].show
	end
	if parms.opt_output_number_only then
		return result
	end
	return result .. preunit .. extra
end

local function make_output_single(parms, in_unit_table, out_unit_table)
	-- Return true, item where item = wikitext of the conversion result
	-- for a single output (which is not a combination or a multiple);
	-- or return false, t where t is an error message table.
	if parms.opt_order_out and in_unit_table.unitcode == out_unit_table.unitcode then
		out_unit_table.valinfo = in_unit_table.valinfo
	else
		out_unit_table.valinfo = collection()
		for _, v in ipairs(in_unit_table.valinfo) do
			local success, info = cvtround(parms, v, in_unit_table, out_unit_table)
			if not success then return false, info end
			out_unit_table.valinfo:add(info)
		end
	end
	return true, process_one_output(parms, out_unit_table)
end

local function make_output_multiple(parms, in_unit_table, out_unit_table)
	-- Return true, item where item = wikitext of the conversion result
	-- for an output which is a multiple (like 'ftin');
	-- or return false, t where t is an error message table.
	local inout = out_unit_table.inout  -- normally 'out' but can be 'in' for order=out
	local multiple = out_unit_table.multiple  -- table of scaling factors (will not be nil)
	local combos = out_unit_table.combination  -- table of unit tables (will not be nil)
	local abbr = parms.abbr
	local abbr_org = parms.abbr_org
	local disp = parms.disp
	local want_name = (abbr_org == nil and (disp == 'or' or disp == 'slash')) or
						not (abbr == 'on' or abbr == inout or abbr == 'mos')
	local want_link = (parms.lk == 'on' or parms.lk == inout)
	local mid = parms.opt_flip and parms.mid or ''
	local sep1 = '&nbsp;'
	local sep2 = ' '
	if parms.opt_adjectival and want_name then
		sep1 = '-'
		sep2 = '-'
	end
	local do_spell = parms.opt_spell_out
	parms.opt_spell_out = nil  -- so the call to cvtround does not spell the value
	local function make_result(info, isfirst)
		local fmt, outvalue, sign
		local results = {}
		for i = 1, #combos do
			local tfrac, thisvalue, strforce
			local out_current = combos[i]
			out_current.inout = inout
			local scale = multiple[i]
			if i == 1 then  -- least significant unit ('in' from 'ftin')
				local decimals
				out_current.frac = out_unit_table.frac
				local success, outinfo = cvtround(parms, info, in_unit_table, out_current)
				if not success then return false, outinfo end
				if isfirst then
					out_unit_table.valinfo = { outinfo }  -- in case output value of first least significant unit is needed
				end
				sign = outinfo.sign
				tfrac = outinfo.fraction_table
				if outinfo.is_scientific then
					strforce = outinfo.show
					decimals = ''
				elseif tfrac then
					decimals = ''
				else
					local show = outinfo.show  -- number as a string in local language
					local p1, p2 = show:find(numdot, 1, true)
					decimals = p1 and show:sub(p2 + 1) or ''  -- text after numdot, if any
				end
				fmt = '%.' .. ulen(decimals) .. 'f'  -- to reproduce precision
				if decimals == '' then
					if tfrac then
						outvalue = floor(outinfo.raw_absvalue)  -- integer part only; fraction added later
					else
						outvalue = floor(outinfo.raw_absvalue + 0.5)  -- keep all integer digits of least significant unit
					end
				else
					outvalue = outinfo.absvalue
				end
			end
			if scale then
				outvalue, thisvalue = divide(outvalue, scale)
			else
				thisvalue = outvalue
			end
			local id
			if want_name then
				if varname then
					local clean
					if strforce or tfrac then
						clean = '.1'  -- dummy value to force name for floating point
					else
						clean = format(fmt, thisvalue)
					end
					id = variable_name(clean, out_current)
				else
					local key = 'name2'
					if parms.opt_adjectival then
						key = 'name1'
					elseif tfrac then
						if thisvalue == 0 then
							key = 'name1'
						end
					elseif parms.opt_singular then
						if 0 < thisvalue and thisvalue < 1.0001 then
							key = 'name1'
						end
					else
						if thisvalue == 1 then
							key = 'name1'
						end
					end
					id = out_current[key]
				end
			else
				id = out_current['symbol']
			end
			if i == 1 and omit_separator(id) then
				-- Testing the id of the least significant unit should be sufficient.
				sep1 = ''
				sep2 = ''
			end
			if want_link then
				local link = out_current.link
				if link then
					id = make_link(link, id, out_current)
				end
			end
			local strval
			local spell_inout = (i == #combos or outvalue == 0) and inout or ''  -- trick so the last value processed (first displayed) has uppercase, if requested
			if strforce and outvalue == 0 then
				sign = ''  -- any sign is in strforce
				strval = strforce  -- show small values in scientific notation; will only use least significant unit
			elseif tfrac then
				local wholestr = (thisvalue > 0) and tostring(thisvalue) or nil
				strval = format_fraction(parms, spell_inout, false, wholestr, tfrac.numstr, tfrac.denstr, do_spell)
			else
				strval = (thisvalue == 0) and from_en('0') or with_separator(parms, format(fmt, thisvalue))
				if do_spell then
					strval = spell_number(parms, spell_inout, strval) or strval
				end
			end
			table.insert(results, strval .. sep1 .. id)
			if outvalue == 0 then
				break
			end
			fmt = '%.0f'  -- only least significant unit can have a non-integral value
		end
		local reversed, count = {}, #results
		for i = 1, count do
			reversed[i] = results[count + 1 - i]
		end
		return true, sign .. table.concat(reversed, sep2)
	end
	local valinfo = in_unit_table.valinfo
	local success, result = make_result(valinfo[1], true)
	if not success then return false, result end
	local range = parms.range
	if range then
		for i = 1, range.n do
			local success, result2 = make_result(valinfo[i+1])
			if not success then return false, result2 end
			result = range_text(range[i], want_name, parms, result, result2, inout)
		end
	end
	return true, result .. mid
end

local function process(parms, in_unit_table, out_unit_table)
	-- Return true, s, outunit where s = final wikitext result,
	-- or return false, t where t is an error message table.
	linked_pages = {}
	local success, bad_output
	local bad_input_mcode = in_unit_table.bad_mcode  -- nil if input unit is a valid convert unit
	local out_unit = parms.out_unit
	if out_unit == nil or out_unit == '' or type(out_unit) == 'function' then
		if bad_input_mcode or parms.opt_input_unit_only then
			bad_output = ''
		else
			local getdef = type(out_unit) == 'function' and out_unit or get_default
			success, out_unit = getdef(in_unit_table.valinfo[1].value, in_unit_table)
			parms.out_unit = out_unit
			if not success then
				bad_output = out_unit
			end
		end
	end
	if not bad_output and not out_unit_table then
		success, out_unit_table = lookup(parms, out_unit, 'any_combination')
		if success then
			local mismatch = check_mismatch(in_unit_table, out_unit_table)
			if mismatch then
				bad_output = mismatch
			end
		else
			bad_output = out_unit_table
		end
	end
	local lhs, rhs
	local flipped = parms.opt_flip and not bad_input_mcode
	if bad_output then
		rhs = (bad_output == '') and '' or message(parms, bad_output)
	elseif parms.opt_input_unit_only then
		rhs = ''
	else
		local combos  -- nil (for 'ft' or 'ftin'), or table of unit tables (for 'm ft')
		if not out_unit_table.multiple then  -- nil/false ('ft' or 'm ft'), or table of factors ('ftin')
			combos = out_unit_table.combination
		end
		local frac = parms.frac  -- nil or denominator of fraction for output values
		if frac then
			-- Apply fraction to the unit (if only one), or to non-SI units (if a combination),
			-- except that if a precision is also specified, the fraction only applies to
			-- the hand unit; that allows the following result:
			-- {{convert|156|cm|in hand|1|frac=2}} → 156 centimetres (61.4 in; 15.1½ hands)
			-- However, the following is handled elsewhere as a special case:
			-- {{convert|156|cm|hand in|1|frac=2}} → 156 centimetres (15.1½ hands; 61½ in)
			if combos then
				local precision = parms.precision
				for _, unit in ipairs(combos) do
					if unit.builtin == 'hand' or (not precision and not unit.prefixes) then
						unit.frac = frac
					end
				end
			else
				out_unit_table.frac = frac
			end
		end
		local outputs = {}
		local imax = combos and #combos or 1  -- 1 (single unit) or number of unit tables
		if imax == 1 then
			parms.opt_order_out = nil  -- only useful with an output combination
		end
		if not flipped and not parms.opt_order_out then
			-- Process left side first so any duplicate links (from lk=on) are suppressed
			-- on right. Example: {{convert|28|e9pc|e9ly|abbr=off|lk=on}}
			lhs = process_input(parms, in_unit_table)
		end
		for i = 1, imax do
			local success, item
			local out_current = combos and combos[i] or out_unit_table
			out_current.inout = 'out'
			if i == 1 then
				if imax > 1 and out_current.builtin == 'hand' then
					out_current.out_next = combos[2]  -- built-in hand can influence next unit in a combination
				end
				if parms.opt_order_out then
					out_current.inout = 'in'
				end
			end
			if out_current.multiple then
				success, item = make_output_multiple(parms, in_unit_table, out_current)
			else
				success, item = make_output_single(parms, in_unit_table, out_current)
			end
			if not success then return false, item end
			outputs[i] = item
		end
		if parms.opt_order_out then
			lhs = outputs[1]
			table.remove(outputs, 1)
		end
		local sep = parms.table_joins and parms.table_joins[2] or parms.join_between
		rhs = table.concat(outputs, sep)
	end
	if flipped or not lhs then
		local input = process_input(parms, in_unit_table)
		if flipped then
			lhs = rhs
			rhs = input
		else
			lhs = input
		end
	end
	if parms.join_before then
		lhs = parms.join_before .. lhs
	end
	local wikitext
	if bad_input_mcode then
		if bad_input_mcode == '' then
			wikitext = lhs
		else
			wikitext = lhs .. message(parms, bad_input_mcode)
		end
	elseif parms.table_joins then
		wikitext = parms.table_joins[1] .. lhs .. parms.table_joins[2] .. rhs
	else
		wikitext = lhs .. parms.joins[1] .. rhs .. parms.joins[2]
	end
	if parms.warnings and not bad_input_mcode then
		wikitext = wikitext .. parms.warnings
	end
	return true, get_styles(parms) .. wikitext, out_unit_table
end

local function main_convert(frame)
	-- Do convert, and if needed, do it again with higher default precision.
	local parms = { frame = frame }  -- will hold template arguments, after translation
	set_config(frame.args)
	local success, result = get_parms(parms, frame:getParent().args)
	if success then
		if type(result) ~= 'table' then
			return tostring(result)
		end
		local in_unit_table = result
		local out_unit_table
		for _ = 1, 2 do  -- use counter so cannot get stuck repeating convert
			success, result, out_unit_table = process(parms, in_unit_table, out_unit_table)
			if success and parms.do_convert_again then
				parms.do_convert_again = false
			else
				break
			end
		end
	end
	-- If input=x gives a problem, the result should be just the user input
	-- (if x is a property like P123 it has been replaced with '').
	-- An unknown input unit would display the input and an error message
	-- with success == true at this point.
	-- Also, can have success == false with a message that outputs an empty string.
	if parms.input_text then
		if success and not parms.have_problem then
			return result
		end
		local cat
		if parms.tracking then
			-- Add a tracking category using the given text as the category sort key.
			-- There is currently only one type of tracking, but in principle multiple
			-- items could be tracked, using different sort keys for convenience.
			cat = wanted_category('tracking', parms.tracking)
		end
		return parms.input_text .. (cat or '')
	end
	return success and result or message(parms, result)
end

local function _unit(unitcode, options)
	-- Helper function for Module:Val to look up a unit.
	-- Parameter unitcode must be a string to identify the wanted unit.
	-- Parameter options must be nil or a table with optional fields:
	--   value = number (for sort key; default value is 1)
	--   scaled_top = nil for a normal unit, or a number for a unit which is
	--                the denominator of a per unit (for sort key)
	--   si = { 'symbol', 'link' }
	--                (a table with two strings) to make an SI unit
	--                that will be used for the look up
	--   link = true if result should be [[linked]]
	--   sort = 'on' or 'debug' if result should include a sort key in a
	--                span element ('debug' makes the key visible)
	--   name = true for the name of the unit instead of the symbol
	--   us = true for the US spelling of the unit, if any
	-- Return nil if unitcode is not a non-empty string.
	-- Otherwise return a table with fields:
	--   text = requested symbol or name of unit, optionally linked
	--   scaled_value = input value adjusted by unit scale; used for sort key
	--   sortspan = span element with sort key like that provided by {{ntsh}},
	--     calculated from the result of converting value
	--     to a base unit with scale 1.
	--   unknown = true if the unitcode was not known
	unitcode = strip(unitcode)
	if unitcode == nil or unitcode == '' then
		return nil
	end
	set_config({})
	linked_pages = {}
	options = options or {}
	local parms = {
		abbr = options.name and 'off' or 'on',
		lk = options.link and 'on' or nil,
		opt_sp_us = options.us and true or nil,
		opt_ignore_error = true,  -- do not add pages using this function to 'what links here' for Module:Convert/extra
		opt_sortable_on = options.sort == 'on' or options.sort == 'debug',
		opt_sortable_debug = options.sort == 'debug',
	}
	if options.si then
		-- Make a dummy table of units (just one unit) for lookup to use.
		-- This makes lookup recognize any SI prefix in the unitcode.
		local symbol = options.si[1] or '?'
		parms.unittable = { [symbol] = {
			_name1 = symbol,
			_name2 = symbol,
			_symbol = symbol,
			utype = symbol,
			scale = symbol == 'g' and 0.001 or 1,
			prefixes = 1,
			default = symbol,
			link = options.si[2],
		}}
	end
	local success, unit_table = lookup(parms, unitcode, 'no_combination')
	if not success then
		unit_table = setmetatable({
			symbol = unitcode, name2 = unitcode, utype = unitcode,
			scale = 1, default = '', defkey = '', linkey = '' }, unit_mt)
	end
	local value = tonumber(options.value) or 1
	local clean = tostring(abs(value))
	local info = {
		value = value,
		altvalue = value,
		singular = (clean == '1'),
		clean = clean,
		show = clean,
	}
	unit_table.inout = 'in'
	unit_table.valinfo = { info }
	local sortspan, scaled_value
	if options.sort then
		sortspan, scaled_value = make_table_or_sort(parms, value, info, unit_table, options.scaled_top)
	end
	return {
		text = make_id(parms, 1, unit_table),
		sortspan = sortspan,
		scaled_value = scaled_value,
		unknown = not success and true or nil,
	}
end

return { convert = main_convert, _unit = _unit }