Documentation for this module may be created at မဝ်ဂျူ:R:Bailly/doc

local export = {}

local accent_m = require("Module:grc-accent")
local script_m = require("Module:scripts")
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 = math.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="polytonic" 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 = mw.ustring.toNFD(logos), {}
	local len = mw.ustring.len(nfd)
	for i = 1,len do 
      	c = mw.ustring.sub(nfd,i,i)
	 	if diacritics[tostring(mw.ustring.codepoint(c))] == nil then 
	 		rv[#rv+1] = c end end
	return table.concat(rv)
end


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

return export