This module serves {{R:Bailly}}.


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

local codepoint = m_str_utils.codepoint
local concat = table.concat
local floor = math.floor
local len = m_str_utils.len
local lower = m_str_utils.lower
local sub = m_str_utils.sub
local toNFD = mw.ustring.toNFD

local export = {}

local accent_m = require("Module:grc-accent")
local lang = require("Module:languages").getByCode("grc")

function b_search_wrapper(ys,x,L,H)
	local i = b_search(ys,x,L,H)
	return ys[i][2] - (ys[i][1] == x and 0 or 1)
end

function b_search(ys, x, L, H)
    if L < 0 then error('L < 0') end
    while L < H do
        M = floor((L+H) / 2)
        if ys[M][1] < x then L = M+1 else H = M end
    end
    return L
 end

function sundesmos(logos, selis)
	local url = "https://archive.org/stream/BaillyDictionnaireGrecFrancais/Bailly_DictionnaireGrecFrancais#page/n"..(selis-1).."/mode/1up"
	local logos_span = '<span class="Polyt" lang="grc">'..logos..'</span>'
	return '['..url..' '..logos_span..'] in '
end

function remove_diacritics(logos) --not used; keeping this function around just in case
	local diacritics = { ["769"]={}, ["787"]={}, ["788"]={}, ["770"]={}}           --acute, smooth, rough, circumflex
	local nfd, rv = toNFD(logos), {}
	local len = len(nfd)
	for i = 1,len do 
      	c = sub(nfd,i,i)
	 	if diacritics[tostring(codepoint(c))] == nil then 
	 		rv[#rv+1] = c end end
	return concat(rv)
end


function export.create(frame)
	local args = frame:getParent().args
	local logos = args['w'] or mw.title.getCurrentTitle().text
	local sccode = lang:findBestScript(logos):getCode()
	if sccode ~= "Polyt" and sccode ~= "polytonic" then
		return ''
	end
	local selis = b_search_wrapper(
		mw.loadData("Module:R:Bailly/headwords"),
		lower(accent_m.strip_accent(logos)),
		1,
		2163
		)
	return sundesmos(logos, selis)
end

return export