% detect LaTeX and use the correct method for luatexbase inclusion
\ifx\RequirePackage\undefined
  \input{luatexbase.sty}%
\else
  \RequirePackage{luatexbase}
\fi

\newluatexattribute\preventsinglestatus
% Modify pre_linebreak_filter callback so the spaces can be inserted
\directlua{%         
luavlna = require "luavlna" 
langno  = require "luavlna-langno"
luatexbase.add_to_callback("pre_linebreak_filter", luavlna.preventsingle," ")

local languages = langno.load_languages()
local get_lang_id = function(lang)
  local langid = lang 
  if not tonumber(lang) then
    langid = languages:get_number(lang)
  end
  return langid
end

% Process string and make table of enabled single letters
% By default, spaces for all single letters are inserted
% This can be modified with \singlechars macro
set_singlechars = function(lang,chars)
  local utf_gmatch = unicode.utf8.gmatch
  % local langnumbers = languages.names
  local langid = get_lang_id(lang) 
  if not langid then return nil, "Cannot find language number for: "..lang end
  local chars = chars  or ""
  local singlechars = {}
  local percent = string.char(37)
  local alpha = percent .. "a"
  for char in utf_gmatch(chars,"("..alpha..")") do
    singlechars[char] = true
  end
  luavlna.singlechars(langid,singlechars)
end

% set compound characters for initials handling
% useful for Czech "Ch" etc.
% comma separated list of compounds
set_compounds = function(lang, compounds)
  local langid = get_lang_id(lang)
  if not langid then return nil, "Cannot find language number for: "..lang end
  local c = compounds:explode(",+") % match multiple colons as one
  local  compoundstable = {}
  for _, compound in pairs(c) do
    compoundstable[compound] = true
  end
  luavlna.initials(langid, compoundstable)
end

set_main_language = function(lang)
  local langid = languages:get_number(lang)
  if not langid then return nil, "Cannot find language number for: "..lang end
  luavlna.set_main_language(langid)
end	
}     

% Set letters which are prevented from breaking
\def\singlechars#1#2{%
\directlua{set_singlechars("#1","#2")}
}

% Define compound initials
\def\compoundinitials#1#2{%
\directlua{set_compounds("#1","#2")}
}
% Enable inserting of visual marks for debugging
\def\preventsingledebugon{%
\directlua{luavlna.debug(true)}
}

\def\preventsinglelang#1{%
	\directlua{set_main_language("#1")}
} 

\def\preventsingleon{%
	\preventsinglestatus=2
}

\def\preventsingleoff{
	\preventsinglestatus=1
}
% Disable inserting of visual marks for dewbugging
\def\preventsingledebugoff{%
\directlua{luavlna.debug(false)}
}

% disable processing of units or degrees

\def\nopredegrees{\directlua{luavlna.no_predegrees = true}}
\def\nosufdegrees{\directlua{luavlna.no_sufdegrees = true}}
\def\nounits{\directlua{luavlna.no_unit = true}}

\ifdefined\nosingledefaults\else
  \singlechars{czech}{AIiVvOoUuSsZzKk}
  \singlechars{slovak}{AIiVvOoUuSsZzKk}
  \compoundinitials{czech}{Ch,CH}
\fi

