มอดูล:Convert2

-- มันเหมือนกับ Module:Convert นั่นแหละครับ แต่เพียงแค่ว่าไม่ได้แปลหน่วย การแสดงผมจึงเพี้ยน และผมแก้ไขไม่ได้ จึงจชต้องทำอันใหม่ ทำการแปลให้เสร็จ แล้วเอาอันเก่ามารอ
-- Convert a value from one unit of measurement to another.
-- Example: 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 default_exceptions, link_exceptions, 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 = 'ต่อ'     -- for units like "liters per kilometer"
local plural_suffix =   -- 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
local ignore_extra_units  -- if true, do not require the extra module
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 want_separator(id)
	-- Return true if id (a unit symbole or name) should be proceeded by a separator.
	-- For zhwiki, there should be no separator if id uses local characters.
	-- The following kludge should be a sufficient test.
	if id:sub(1, 2) == '-{' then  -- for "-{...}-" content language variant
		return false
	end
	if id:byte() > 127 then
		local first = usub(id, 1, 1)
		if first ~= 'Å' and first ~= '°' and first ~= 'µ' then
			return false
		end
	end
	return true
end
local spell_module  -- name of module that can spell numbers
local speller       -- function from that module to handle spelling (set if spelling is wanted)
local function set_config(frame)
	-- Set configuration options from template #invoke or defaults.
	config = frame.args
	maxsigfig = config.maxsigfig or 14  -- maximum number of significant figures
	-- Scribunto sets the global variable 'mw'.
	-- A testing program can set the global variable 'is_test_run'.
	local data_module, text_module, data_code
	if is_test_run then
		local langcode = mw.language.getContentLanguage().code
		data_module = "convertdata-" .. langcode
		text_module = "converttext-" .. langcode
		extra_module = "convertextra-" .. langcode
		spell_module = "ConvertNumeric"
	else
		local sandbox = config.sandbox and ('/' .. config.sandbox) or 
		data_module = "Module:Convert/data2" .. sandbox
		text_module = "Module:Convert/text2" .. sandbox
		extra_module = "Module:Convert/extra2" .. sandbox
		spell_module = "Module:ConvertNumeric"
	end
	data_code = mw.loadData(data_module)
	text_code = mw.loadData(text_module)
	default_exceptions = data_code.default_exceptions
	link_exceptions = data_code.link_exceptions
	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_tablek = 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
			selfself.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  limit then
					s = usub(s, 1, limit)
					append = '...'
				end
				s = nowiki(s) .. (append or )
			else
				s = '?'
			end
			partsi = s
		end
		local title = format(msg1 or 'Missing message', parts1, parts2, parts3)
		local text = msg2 or 'Missing message'
		local cat = wanted_category(text_code.all_categoriesmsg3) or 
		local anchor = msg4 or 
		local fmt = text_code.all_messages'cvt_format' or 'convert: bug'
		title = title:gsub('"', '"')
		return format(fmt, anchor, title, text, cat)
	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.
	-- To reduce output noise, only the first warning is displayed.
	if config.warnings then
		if level  60 then
		a = 60
	end
	return mach_tablea + 4 * 0.44704  -- mph converted to m/s
end
-- END: Code required only for built-in units.
------------------------------------------------------------------------
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.typesword or ranges.typesranges.aliasesword
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_tablefield then
			out_tablefield = in_tablefield
		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
		resultk = 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.
	__index = function (self, key)
		local value
		if key == 'symbol' then
			local per = self.per
			local unit1, unit2 = per1, per2
			if unit1 then
				value = unit1key .. '/' .. unit2key
			else
				value = '/' .. unit2key
			end
		elseif key == 'sym_us' then
			value = self.symbol
		elseif key == 'scale' then
			local per = self.per
			local unit1, unit2 = per1, per2
			value = (unit1 and unit1.scale or 1) * self.scalemultiplier / unit2.scale
		else
			value = false
		end
		rawset(self, key, value)
		return value
	end
}
local function lookup(unitcode, opt_sp_us, 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 opt_sp_us is true for US spelling of SI prefixes and
	-- the symbol and name of the unit. If true, the result includes field
	-- sp_us = true (that field may also have been in the unit definition).
	-- 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 board_feet works.
	-- Wikignomes may also put two spaces or " " in combinations, so
	-- replace underscore, " ", and multiple spaces with a single space.
	utable = utable 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(' ', ' '):gsub('  +', ' ')
	local t = utableunitcode
	if t then
		if t.shouldbe then
			return false, { 'cvt_should_be', t.shouldbe }
		end
		local force_sp_us = opt_sp_us
		if t.sp_us then
			force_sp_us = true
			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(target, opt_sp_us, 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
		local per = t.per  -- nil/false, or a numbered table for "x/y" units
		if per then
			local result = { utype = t.utype, per = {} }
			result.scalemultiplier = t.multiplier or 1
			override_from(result, t, { 'invert', 'iscomplex', 'default', 'link', '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 text_code.currencyv then
					prefix = v
				else
					local success, t = lookup(v, opt_sp_us, 'no_combination', utable, fails, depth)
					if not success then return false, t end
					cvti = 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 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(v, opt_sp_us, multiple and 'no_combination' or 'only_multiple', utable, fails, depth)
				if not success then return false, t end
				cvti = t
			end
			return true, result
		end
		local result = shallow_copy(t)
		result.sp_us = force_sp_us
		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 = SIprefixes1 or 2, 1, -1 do
		-- Look for an SI prefix; should never occur with an alias.
		-- Check for longer prefix first ('dam' is decametre).
		-- SIprefixes1 = prefix maximum #characters (as seen by mw.ustring.sub).
		local prefix = usub(unitcode, 1, plen)
		local si = SIprefixesprefix
		if si then
			local t = utableusub(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 has_plus = unitcode:find('+', 1, true)
	if not has_plus then
		local exponent, baseunit = unitcode:match('^e(%d+)(.*)')
		if exponent then
			local engscale = text_code.eng_scalesexponent
			if engscale then
				local success, result = lookup(baseunit, opt_sp_us, 'no_combination', utable, fails, depth)
				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
	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 has_plus 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(v, opt_sp_us, '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
				cvti = t
			end
			return true, result
		end
		local success, result = lookup_combo()
		if success or err_is_fatal then
			return success, result
		end
	end
	if not ignore_extra_units 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 
		-- 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 failsunitcode then
				failsunitcode = true
				local other = (utable == all_units) and extra_units or all_units
				local success, result = lookup(unitcode, opt_sp_us, 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(en_code, opt_sp_us, 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 ntsh(num, debug)
	-- Return html text to be used for a hidden sort key so that
	-- the given number will be sorted in numeric order.
	-- If debug == true, output is in a box (not hidden).
	-- This implements แม่แบบ:Ntsh (number table sorting, hidden).
	local result, style
	if not valid_number(num) then
		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 then
		style = 'border:1px solid'
	else
		style = 'display:none'
	end
	return  .. result .. 
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:
	--   ton         →  ton          (no change)
	--   long ton       →  long-ton
	--   long ton  →  long-ton
	--   long ton             →  long-ton
	-- Input can also have multiple links in a single name like:
	--   U.S. gallon
	--   miles per U.S. quart
	--   long tons per short ton
	-- Assume that links cannot be nested (never like "abcdefghi").
	-- 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 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, -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('(^*)(%%^*%%)('
					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 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
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_grouper(method, gaps)
	-- Return a table to hold groups of digits which can be joined with
	-- suitable separators (such as commas).
	-- Each group is separately translated to the local language because
	-- gap separators include digits which should not be translated.
	-- Parameter method is a number or nil:
	--   3 for 3-digit grouping, or
	--   2 for 3-then-2 grouping.
	-- Parameter gaps is true to use  gaps (numsep ignored).
	return {
		n = 0,
		add = function (self, digits)
			self.n = self.n + 1
			selfself.n = from_en(digits)
		end,
		join = function (self, rhs)
			-- Concatenate in reverse order.
			if gaps then
				local result = 
				for i = 1, self.n - 1 do
					result =  .. selfi ..  .. result
				end
				return  .. selfself.n .. result .. from_en(rhs) .. 
			else
				local result = self1
				for i = 2, self.n do
					result = selfi .. numsep .. result
				end
				return result .. from_en(rhs)
			end
		end,
		step = 3,
		next_position = function (self, previous)
			-- Return position of digit just before next group.
			-- Digits are grouped from right-to-left (least significant first).
			local result = previous - self.step
			if method == 2 then
				self.step = 2
			end
			return (result  0 do
		local position = groups:next_position(i)
		groups:add(text:sub(position+1, i))
		i = position
	end
	return groups:join(text:sub(last+1))
end
-- Input values can use values like 1.23e12, but are never displayed
-- using scientific notation like 1.23×10¹².
-- Very small or very large output values use scientific notation.
-- Use format(fmtpower, significand, '10', exponent) where each arg is a string.
local fmtpower = '%s×%s%s'
local function with_exponent(show, exponent)
	-- Return wikitext to display the implied value in scientific notation.
	-- Input uses en digits; output uses digits in local language.
	if #show > 1 then
		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
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  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  (fraction slash).
		-- 1/2    : sign, numerator, denominator
		-- 1+2/3  : signed_wholenumber, numerator, denominator
		'%s%s⁄%s',
		'%s %s⁄%s',
	},
	{ -- Like  (fraction horizontal bar).
		-- 1//2   : sign, numerator, denominator (sign should probably be before the fraction, but then it can wrap, and html is already too long)
		-- 1+2//3 : signed_wholenumber, numerator, denominator
		'%s%s/%s',
		'%s %s/%s',
	},
}
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
	if wholestr then
		local decorated = with_separator(parms, wholestr)
		if negative then
			decorated = MINUS .. decorated
		end
		local fmt = fracfmtstyle2
		wikitext = format(fmt, decorated, from_en(numstr), from_en(denstr))
	else
		local sign = negative and MINUS or 
		wikitext = format(fracfmtstyle1, sign, from_en(numstr), from_en(denstr))
	end
	if do_spell then
		if negative then
			if wholestr then
				wholestr = '-' .. wholestr
			else
				numstr = '-' .. numstr
			end
		end
		wikitext = spell_number(parms, inout, wholestr, numstr, denstr) or wikitext
	end
	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 for very small or large values
	--   (which forces output to not be spelled).
	-- * Has no more than maxsigfig significant digits
	--   (same as old template and ).
	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 >= 10 then
			show = integer .. decimals
			exponent = #integer
		elseif 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 >= 4 then
				show = figs
				exponent = -#zeros
			elseif #figs > maxlen then
				show = '0.' .. zeros .. figs:sub(1, maxlen)
			end
		else
			maxlen = maxlen + #dot
			if #show > maxlen then
				show = show:sub(1, maxlen)
			end
		end
	end
	if exponent then
		if #show > maxlen then
			show = show:sub(1, maxlen)
		end
		if exponent > 10 or exponent = 1e9 or value = #show then
			show = show .. string.rep('0', exponent - #show)  -- result has no dot
		elseif exponent  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 one reference at the end. Accepting a reference 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 (and optional following whitespace) 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 (to use singular form of units)
	--            = false if value is -1 (like old template)
	--   clean    = cleaned text with any separators and sign removed
	--              (en digits and '.' decimal mark)
	--   show     = text formatted for output, possibly with ref strip marker
	--              (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 t, reference = text:match('^(.*)(\127UNIQ%x+%-ref%-%x+%-QINU\127)$')
	if reference then  -- found a single strip marker at end containing "-ref-"
		text = strip(t)
	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  b then
		a, b = b, a
	end
	if a  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 preceding space).
	local function withspace(text, i)
		-- Insert space at beginning if i == 1, or at end if i == -1.
		-- However, no space is inserted if there is a space or ' '
		-- or '-' at that position ('-' is for adjectival text).
		local current = text:sub(i, i)
		if current == ' ' or current == '-' then
			return text
		end
		if i == 1 then
			current = text:sub(1, 6)
		else
			current = text:sub(-6, -1)
		end
		if current == ' ' then
			return text
		end
		if i == 1 then
			return ' ' .. text
		end
		return text .. ' '
	end
	preunit1 = preunit1 or 
	local trim1 = strip(preunit1)
	if count == 1 then
		if trim1 ==  then
			return nil
		end
		return withspace(withspace(preunit1, 1), -1)
	end
	preunit2 = preunit2 or 
	local trim2 = strip(preunit2)
	if trim1 ==  and trim2 ==  then
		return nil, nil
	end
	if trim1 ~= '+' then
		preunit1 = withspace(preunit1, 1)
	end
	if trim2 == ' ' then  -- trick to make preunit2 empty
		preunit2 = nil
	elseif trim2 ==  then
		preunit2 = preunit1
	elseif trim2 ~= '+' then
		preunit2 = withspace(preunit2, 1)
	end
	return preunit1, preunit2
end
local function range_text(range, want_name, parms, before, after)
	-- 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 abbr=off and for abbr=on,
		-- and may specify range text for 'adj=on',
		-- and may specify exception = true.
		rtext = rangewant_name and 'off' or 'on'
		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(' ', '-')
		end
	end
	if rtext == '–' and after:sub(1, #MINUS) == MINUS then
		rtext = ' – '
	end
	return before .. rtext .. after
end
local function get_composite(parms, iparm, in_unit_table)
	-- Look for a composite input unit. For example, "in"
	-- would result in a call to this function with
	--   iparm = 3 (parmsiparm = "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.valinfo1.value
	local subunit = in_unit_table
	while subunit.subdivs do  -- subdivs is nil or a table of allowed subdivisions
		local subcode = strip(parmsiparm+1)
		local subdiv = subunit.subdivssubcode or subunit.subdivs(all_unitssubcode or {}).target
		if not subdiv then
			break
		end
		local success
		success, subunit = lookup(subcode, parms.opt_sp_us, 'no_combination')
		if not success then return false, subunit end  -- should never occur
		success, subinfo = extract_number(parms, parmsiparm)
		if not success then return false, subinfo end
		iparm = iparm + 2
		subunit.inout = 'in'
		subunit.valinfo = { subinfo }
		-- Recalculate total as a number of subdivisions.
		-- subdiv1 = number of subdivisions per previous unit (integer > 1).
		total = total * subdiv1 + subinfo.value
		if not default then  -- set by the first subdiv with a default defined
			default = subdiv.default
		end
		count = count + 1
		composite_unitscount = subunit
		if subdiv.unit or subdiv.name then
			fixupscount = { 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_unitsi.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_unitsi = 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.
	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
	for loc_name, loc_value in pairs(kv_pairs) do
		local en_name = text_code.en_option_nameloc_name
		if en_name then
			local en_value
			if en_name == 'frac' or en_name == 'sigfig' then
				if loc_value ==  then
					add_warning(parms, 2, 'cvt_empty_option', loc_name)
				else
					local minimum
					local number, is_integer = get_number(loc_value)
					if en_name == 'frac' then
						minimum = 2
						if number and number = minimum then
						en_value = number
					else
						add_warning(parms, 1, (en_name == 'frac' and 'cvt_bad_frac' or 'cvt_bad_sigfig'), loc_value)
					end
				end
			else
				en_value = text_code.en_option_valueen_nameloc_value
				if en_value == nil then
					if loc_value ==  then
						add_warning(parms, 2, 'cvt_empty_option', loc_name)
					else
						-- loc_value can no longer be nil here (at one time, that could occur
						-- with aliases like |sing=off|adj=on), but am retaining safety check.
						local text = loc_value and (loc_name .. '=' .. loc_value) or loc_name
						add_warning(parms, 1, 'cvt_unknown_option', text)
					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
						parmsv = true
					end
					en_value = nil
				end
			end
			parmsen_name = en_value
		else
			add_warning(parms, 1, 'cvt_unknown_option', loc_name .. '=' .. loc_value)
		end
	end
	if parms.adj then
		if parms.adj:sub(1, 2) == 'ri' then
			-- It is known that adj is 'riN' where N is a single digit, so precision is valid.
			-- Only a single en digit is accepted.
			parms.input_precision = tonumber(parms.adj:sub(-1))
			parms.adj = nil
		end
	end
	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
		parms.abbr_org = parms.abbr  -- original abbr that was set, 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_flip then
		local function swap_in_out(option)
			local value = parmsoption
			if value == 'in' then
				parmsoption = 'out'
			elseif value == 'out' then
				parmsoption = '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 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
	local disp_joins = text_code.disp_joins
	local default_joins = disp_joins'b'
	parms.join_between = default_joins3 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 parms.abbr_org == 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_joinsdisp or default_joins
		parms.join_between = parms.joins3 or parms.join_between
	end
	if (en_default and not parms.opt_lang_local and (parms1 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(parms2)
	if parm2 and parm2:sub(-7, -1) == 'nocomma' then
		parms2 = 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.
		local valstr = strip(parmsi)  -- 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 not valstr:match('%-.*/') and i  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 "...",
	-- return true, 3, in_unit, in_unit_table
	-- 3 = index in parms of whatever 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 and caller will reparse the input.
	-- Testing shows this function is successful for 96% of converts in articles,
	-- and that on average it speeds up converts by 8%.
	if parms.input_precision or parms.opt_spell_in then return end
	local clean = to_en(strip(parms1 or ), parms)
	if #clean > 10 or not clean:match('^0-9.+$') then return 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(parms2)
	local success, in_unit_table = lookup(in_unit, parms.opt_sp_us, 'no_combination')
	if not success then return end
	in_unit_table.valinfo = { info }
	return true, 3, in_unit, in_unit_table
end
local function get_parms(pframe)
	-- If successful, return true, parms, 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.
	-- 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 parms = {}  -- arguments passed to template, after translation
	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(pframe.args) do
		if type(k) == 'number' or k == 'test' then  -- parameter "test" is reserved for testing and is not translated
			parmsk = v
		else
			kv_pairsk = v
		end
	end
	local success, msg = translate_parms(parms, kv_pairs)
	if not success then return false, msg end
	ignore_extra_units = parms.opt_ignore_error
	local success, i, in_unit, in_unit_table = simple_get_values(parms)
	if not success then
		local valinfo
		success, valinfo, i = get_values(parms)
		if not success then return false, valinfo end
		in_unit = strip(parmsi)
		i = i + 1
		success, in_unit_table = lookup(in_unit, parms.opt_sp_us, 'no_combination')
		if not success then
			if in_unit == nil then
				in_unit = 
			end
			if parms.opt_ignore_error then  -- display given unit code with no error (for use with )
				in_unit_table =   -- suppress error message and prevent processing of output unit
			end
			in_unit_table = setmetatable({ symbol = in_unit, name2 = in_unit,
				default = "m", defkey = "m", linkey = "m",
				utype = "length", scale = 1, 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, parmsi, false, true)
		if success then
			i = i + 1
			in_unit_table.altitude = info.value
		end
	end
	local next = strip(parmsi)
	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 not set_precision(next) then
		parms.out_unit = next
		if set_precision(strip(parmsi)) then
			i = i + 1
		end
	end
	if parms.opt_adj_mid then
		next = parmsi
		i = i + 1
		if next then  -- mid-text words
			if next:sub(1, 1) == '-' then
				parms.mid = next
			else
				parms.mid = ' ' .. next
			end
		end
	end
	if parms.opt_one_preunit then
		parmsparms.opt_flip and 'preunit2' or 'preunit1' = preunits(1, parmsi)
		i = i + 1
	end
	if parms.disp == 'x' then
		-- Following is reasonably compatible with the old template.
		local first = parmsi or 
		local second = parmsi+1 or 
		i = i + 2
		if strip(first) ==  then  -- user can enter ' ' rather than ' ' to avoid the default
			first = '  ' .. first
			second = ' ' .. second
		end
		parms.joins = { first, second }
	elseif parms.opt_two_preunits then
		local p1, p2 = preunits(2, parmsi, parmsi+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(parmsi)) then
			i = i + 1
		end
	end
	if is_bad_precision then
		add_warning(parms, 1, 'cvt_bad_prec', precision)
	else
		parms.precision = precision
	end
	return true, parms, 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  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, MK.
		-- 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 = 0 then
			local fudge
			if 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 ' 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
		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  mile
	--   miles --> miles
	-- 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).
	-- Linking with a unit uses the unit table as the link key, which fails to detect
	-- overlinking for conversions like the following (each links "mile" twice):
	--   lk=on
	--   lk=on
	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)
	if not link or link ==  or linked_pageslink_key then
		return id
	end
	linked_pageslink_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  .. 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
		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(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 unit1 = per1  -- top unit_table, or nil
		local unit2 = per2  -- 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
		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 unit1key_id or ) .. result .. unit2key_id2
			else
				result = (unit1 and variable_name(clean, unit1) or ) .. result .. variable_name('1', unit2)
			end
			if omitsep and not want_separator(result) then
				unit_table.sep = 
			end
			return make_link(unit_table.link, result, unit_table)
		end
		if unit1 then
			result = linked_id(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 .. linked_id(unit2, key_id2, want_link, '1')
	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 ' ' 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_tablekey_id)
	if omitsep and not want_separator(id) then
		unit_table.sep = 
	end
	if want_link then
		local link = link_exceptionsunit_table.linkey or unit_table.symbol or unit_table.link
		if link then
			local before = 
			local i = unit_table.customary
			if i == 1 and unit_table.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_unitsi
			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 ×' ..
				from_en('10') ..
				'^' ..
				from_en(tostring(engscale.exponent)) .. 
		else
			local number_id
			local lk = parms.lk
			if lk == 'on' or lk == inout then
				number_id = make_link(engscale.link, engscale1)
			else
				number_id = engscale1
			end
			-- WP:NUMERAL recommends " " in values like "12 million".
			info.show = info.show .. (parms.opt_adjectival and '-' or ' ') .. number_id
		end
	end
	if prefix then
		info.show = prefix .. info.show
	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 = composite1
	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 then
		local join1 = parms.joins1
		if join1 == ' (' or join1 == ' ' then
			parms.joins = { join1 .. first_unitfirst_unit.sp_us and 'sym_us' or 'symbol' .. ', ', parms.joins2 }
		end
	end
	if in_current.builtin == 'mach' and first_unit.sep ~=  then  --  means omitsep with non-enwiki name
		local prefix = id1 .. ' '
		local range = parms.range
		local valinfo = first_unit.valinfo
		local result = prefix .. valinfo1.show
		if range then
			-- For simplicity and because more not needed, handle one range item only.
			local prefix2 = make_id(parms, 2, first_unit) .. ' '
			result = range_text(range1, want_name, parms, result, prefix2 .. valinfo2.show)
		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 = ' '
		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.valinfo1.show .. sep1 .. id1 }
		for i, unit in ipairs(composite) do
			if i > 1 then
				table.insert(parts, unit.valinfo1.show .. sep1 .. (make_id(parms, 1, unit)))
			end
		end
		return table.concat(parts, sep2) .. mid
	end
	local result, mos
	local abbr = parms.abbr
	local range = parms.range
	if range then
		mos = (abbr == 'mos')
		if not (mos or (parms.is_range_x and not want_name)) then
			linked_pagesfirst_unit = nil  -- so the second and only id will be linked, if wanted
		end
	end
	local id = (range == nil) and id1 or make_id(parms, 2, first_unit)
	local extra, was_hyphenated = hyphenated_maybe(parms, want_name, sep, id, 'in')
	if mos and was_hyphenated then
		mos = false  -- suppress repeat of unit in a range
		if linked_pagesfirst_unit then
			linked_pagesfirst_unit = nil
			id = make_id(parms, 2, first_unit)
			extra = hyphenated_maybe(parms, want_name, sep, id, 'in')
		end
	end
	local valinfo = first_unit.valinfo
	if range then
		if range.n == 1 then
			-- Like ft (one range item; two values).
			-- Do what old template did.
			local sep1 = first_unit.sep
			if mos then
				decorate_value(parms, in_current, 1)
				decorate_value(parms, in_current, 2)
				result = valinfo1.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 = valinfo1.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 = valinfo1.show
			end
			result = range_text(range1, want_name, parms, result, valinfo2.show)
		else
			-- Like ft (two or more range items): simplify.
			decorate_value(parms, in_current, 1)
			result = valinfo1.show
			for i = 1, range.n do
				decorate_value(parms, in_current, i+1)
				result = range_text(rangei, want_name, parms, result, valinfoi+1.show)
			end
		end
	else
		decorate_value(parms, first_unit, 1)
		result = valinfo1.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 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 .. ' '
		local range = parms.range
		local valinfo = out_current.valinfo
		local result = prefix .. valinfo1.show
		if range then
			-- For simplicity and because more not needed, handle one range item only.
			result = range_text(range1, want_name, parms, result, prefix .. valinfo2.show)
		end
		return preunit .. result
	end
	local result
	local range = parms.range
	if range then
		if not (parms.is_range_x and not want_name) then
			linked_pagesout_current = nil  -- so the second and only id will be linked, if wanted
		end
	end
	local id = (range == nil) and id1 or make_id(parms, 2, out_current)
	local extra = hyphenated_maybe(parms, want_name, sep, id, 'out')
	local valinfo = out_current.valinfo
	if range then
		if range.n == 1 then
			local sep1 = out_current.sep
			local abbr = parms.abbr
			if parms.is_range_x and not want_name then
				if abbr == 'out' or abbr == 'on' then
					decorate_value(parms, out_current, 1)
				end
				decorate_value(parms, out_current, 2)
				result = valinfo1.show .. sep1 .. id1
			else
				if abbr == 'out' or abbr == 'on' then
					decorate_value(parms, out_current, 1)
				end
				decorate_value(parms, out_current, 2)
				result = valinfo1.show
			end
			result = range_text(range1, want_name, parms, result, valinfo2.show)
		else
			-- Like ft (two or more range items): simplify.
			decorate_value(parms, out_current, 1)
			result = valinfo1.show
			for i = 1, range.n do
				decorate_value(parms, out_current, i+1)
				result = range_text(rangei, want_name, parms, result, valinfoi+1.show)
			end
		end
	else
		decorate_value(parms, out_current, 1)
		result = valinfo1.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.
	out_unit_table.valinfo = collection()
	local range = parms.range
	for i = 1, (range and (range.n + 1) or 1) do
		local success, info = cvtround(parms, in_unit_table.valinfoi, in_unit_table, out_unit_table)
		if not success then return false, info end
		out_unit_table.valinfo:add(info)
	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 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 == 'out' or abbr == 'mos')
	local want_link = (parms.lk == 'on' or parms.lk == 'out')
	local mid = parms.opt_flip and parms.mid or 
	local sep1 = ' '
	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 = combosi
			out_current.inout = 'out'
			local scale = multiplei
			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  0) and tostring(thisvalue) or nil
				strval = format_fraction(parms, 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, 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
			reversedi = resultscount + 1 - i
		end
		return true, sign .. table.concat(reversed, sep2)
	end
	local valinfo = in_unit_table.valinfo
	local success, result = make_result(valinfo1, 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(valinfoi+1)
			if not success then return false, result2 end
			result = range_text(rangei, want_name, parms, result, result2)
		end
	end
	return true, result .. mid
end
local function process(parms, in_unit_table, out_unit_table)
	-- Return true, s where s = final wikitext result,
	-- or return false, t where t is an error message table.
	linked_pages = {}
	local success, bad_output, out_first
	local bad_input_mcode = in_unit_table.bad_mcode  -- false if input unit is valid
	local invalue1 = in_unit_table.valinfo1.value
	local out_unit = parms.out_unit
	if out_unit == nil or out_unit ==  then
		if bad_input_mcode then
			bad_output = 
		else
			success, out_unit = get_default(invalue1, 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(out_unit, parms.opt_sp_us, '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 flipped = parms.opt_flip and not bad_input_mcode
	local parts = {}
	for part = 1, 2 do
		-- The LHS (parts1) is normally the input, but is the output if flipped.
		-- Process LHS first so it will be linked, if wanted.
		-- Linking to the same item is suppressed in the RHS to avoid overlinking.
		if (part == 1 and not flipped) or (part == 2 and flipped) then
			partspart = process_input(parms, in_unit_table)
		elseif bad_output then
			if bad_output ~=  then
				partspart = message(bad_output)
			end
		else
			local outputs = {}
			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:
				-- frac=2 → 156 centimetres (61.4 in; 15.1½ hands)
				-- However, the following is handled elsewhere as a special case:
				-- 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 imax = combos and #combos or 1  -- 1 (single unit) or number of unit tables
			for i = 1, imax do
				local success, item
				local out_current = combos and combosi or out_unit_table
				out_current.inout = 'out'
				if i == 1 then
					out_first = out_current
					if imax > 1 and out_current.builtin == 'hand' then
						out_current.out_next = combos2  -- built-in hand can influence next unit in a combination
					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
				table.insert(outputs, item)
			end
			local sep = parms.table_joins and parms.table_joins2 or parms.join_between
			partspart = parms.opt_input_unit_only and  or table.concat(outputs, sep)
		end
	end
	if parms.opt_sortable_in or parms.opt_sortable_out then
		local value
		if parms.opt_sortable_in then
			value = invalue1
		else
			local info = out_first and out_first.valinfo
			if info then
				info = info1
				value = info.raw_absvalue
				if value and info.sign == MINUS then
					value = -value
				end
			end
		end
		parts1 = ntsh((value or 0), parms.opt_sortable_debug) .. parts1
	end
	local wikitext
	if bad_input_mcode then
		if bad_input_mcode ==  then
			wikitext = parts1
		else
			wikitext = parts1 .. message(bad_input_mcode)
		end
	elseif parms.table_joins then
		wikitext = parms.table_joins1 .. parts1 .. parms.table_joins2 .. parts2
	else
		wikitext = parts1 .. parms.joins1 .. parts2 .. parms.joins2
	end
	if parms.warnings and not bad_input_mcode then
		wikitext = wikitext .. parms.warnings
	end
	return true, wikitext, out_unit_table
end
local function main_convert(frame)
	-- Do convert, and if needed, do it again with higher default precision.
	set_config(frame)
	local result, out_unit_table
	local success, parms, in_unit_table = get_parms(frame:getParent())
	if success then
		for i = 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
	else
		result = parms
	end
	if success then
		return result
	end
	return message(result)
end
return { convert = main_convert }