\ProvidesPackage{mqlua}

\RequirePackage{luacode}
\LuaCodeDebugOn

\newcommand\luavar[1]{\directlua{tex.sprint(#1)}}

\begin{luacode*}
function warning(fname, message)
  -- Get the current file name and line number
  -- local info = debug.getinfo(2, "Sl")
  -- local file_name = info.source
  -- local line_number = info.currentline
  -- tex.error(string.format("Warning  %s at %s:%d", message, file_name, line_number))
  if message == nil then 
      texio.write("\nWARNING: " .. fname .. "\n")
  else
      texio.write("\nWARNING: in " .. fname .. ":" .. message .. "\n")
  end
end

OUTDIR = os.getenv("TEXMF_OUTPUT_DIRECTORY") or "."

function fileExists(file)
    local f = io.open(file, "rb")
    if f then f:close() end
    return f ~= nil
end
warning("TEST")
\end{luacode*}

% units: siunitx units arguments, possibly chained by '='
% returns: 1\si{unit1} = 1\si{unit2} = ...
\begin{luacode*}
function split_and_print_units(units)
    if units == nil then
        tex.sprint("1")
        return
    end
        
    local parts = {}
    for part in string.gmatch(units, "[^=]+") do
        table.insert(parts, part)
    end
    local result = ""
    for i, unit in ipairs(parts) do
        if i > 1 then result = result .. " = " end
        result = result .. "\\SI{1}{" .. unit .. "}"
    end
    tex.print(result)
end
\end{luacode*}

% STRING UTILITY
\begin{luacode*}
  function string.startswith(s, start)
      return string.sub(s,1,string.len(start)) == start
  end

  function string.sanitize(s) 
       -- Use gsub to replace the specified characters with an empty string
      local result = s:gsub("[_^&]", " ")
      return result
  end
\end{luacode*}
% Write directlua command to aux and run it as well
% This one expands the argument in the aux file:
\newcommand\directLuaAuxExpand[1]{
    \immediate\write\luaAuxFile{\noexpand\directlua{#1}}
    \directlua{#1}
}
% This one does not:
\newcommand\directLuaAux[1]{
    \immediate\write\luaAuxFile{\noexpand\directlua{\detokenize{#1}}}
    \directlua{#1}
}

% read
\IfFileExists{\jobname.lua.aux}{%
  \input{\jobname.lua.aux}%
}{%
    % \@latex@warning@no@line{"Lua aux not loaded!"}
}
\def\luaAuxLoaded{False}

% write
\newwrite\luaAuxFile
\immediate\openout\luaAuxFile=\jobname.lua.aux
\immediate\write\luaAuxFile{\noexpand\def\noexpand\luaAuxLoaded{True}}%
\AtEndDocument{\immediate\closeout\luaAuxFile}
