This module implements the reference template {{R:en:DAFN}}.


local m_str_utils = require("Module:string utilities")

local codepoint = m_str_utils.codepoint
local concat = table.concat
local floor = math.floor
local insert = table.insert
local ulen = m_str_utils.len
local usub = m_str_utils.sub

local export = {}

function export.normalize(term)
	term = term:ulower()
	local normalized, i, length = {}, 1, ulen(term)
	while i <= length do
		local x = codepoint(term, i)
		if 0x61 <= x and x <= 0x7A then
			insert(normalized, usub(term, i, i))
		end
		i = i + 1
	end
	return concat(normalized)
end


function export.page_number(frame)
	local value = export.normalize(frame.args[1])

	local first, list = usub(value, 1, 1)
	if first < "g" then
		list = require("Module:R:en:DAFN/data1")
	elseif "g" <= first and first <= "n" then
		list = require("Module:R:en:DAFN/data2")
	else
		return ""
	end

    local low = 1
    local high = #list
    local mid = 0
    while high - low > 1 do
        mid = floor((low+high)/2)
        local midval = export.normalize(list[mid])
        if midval == value then return mid
        elseif midval < value then low = mid
        elseif midval > value then high = mid - 1
        end
    end

    if export.normalize(list[high]) <= value then return high
    else return low
    end
end

return export