Questo modulo contiene funzioni di appoggio al template {{Infobox nave}}


local p = {}
local getArgs = require('Module:Arguments').getArgs

---============================================================
-- Round to precision
---============================================================
function round(num, idp)
	local pow = idp or 0
	if idp then
		local mult = 10^idp
		local adder = (num >= 0 and 0.5) or -0.5
		return math.floor(num * mult + adder) / mult
	end
	return math.floor(num + 0.5)
end

---============================================================
-- Autorounding based on the magnitude of value
---============================================================
local function round_auto(num)
	local  base = math.floor(math.log10(math.abs(num))-1)
	return round(num, base)
end

---============================================================
-- format value using   to separate three digit group
--============================================================
local function sep_thousand(value)
	local formatted = value
	while true do
		formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1 %2')
		if (k==0) then
			break
		end
	end
	return formatted
end

function p.speed(frame)
	
	local args = getArgs(frame)
	local spd_kn = args[1] 
	local spd_kmh = args[2] 
	if spd_kmh == nil and spd_kn == nil then
		return ''
	elseif spd_kmh ==nil and spd_kn ~= nil then
		local kn = tonumber(spd_kn:gsub(",", "."))
		if kn then
			spd_kmh = sep_thousand(tostring(round_auto(1.852*kn)))
		end
	else
		local kmh = tonumber(spd_kmh:gsub(",", "."))
			if kmh then
				spd_kn = sep_thousand(tostring(round_auto(kmh/1.852)))
			end
		end
	local out_kn = spd_kn and (spd_kn ..  " [[Nodo (unità di misura)|nodi]]")
	local out_kmh = spd_kmh and (spd_kmh .. " [[Chilometro orario|km/h]]" )
	local out
	if out_kn and out_kmh then
		out = out_kn .. " (" .. out_kmh .. ")"
	elseif out_kn then
		out = out_kn
	else
		out = out_kmh or ''
	end
	return out
end

return p