% !TEX program = LuaLaTeX+se

% Simple template for using Gregorio scores in a LuaLaTeX document.

\documentclass{scrartcl} % set document class: manual at https://ctan.org/pkg/koma-script

% Load packages:
\usepackage[osf,p]{libertine} % set font
\usepackage{gregoriotex} % enable Gregorio score inclusion
\usepackage[latin]{babel} % set language
\usepackage{luacode}

\setkomafont{section}{\normalfont\centering\huge\scshape} % section heading style
\setcounter{secnumdepth}{-\maxdimen} % remove section numbering


% Set the space around the initial:
% See http://gregorio-project.github.io/gregoriotex/details.html for more details and options
\grechangedim{beforeinitialshift}{2.2mm}{scalable}
\grechangedim{afterinitialshift}{2.2mm}{scalable}

% Set the initial font (change 43 for a larger size):
\grechangestyle{initial}{\fontsize{40}{40}\selectfont}%

% Make staff lines red; remove for black:
\gresetlinecolor{gregoriocolor}

% Use the "commentary" field of the score in the top right corner:
\gresetheadercapture{commentary}{grecommentary}{string}

% Format annotation above initial
\grechangestyle{annotation}{\small\bfseries}

\begin{luacode*}
  function editGabc(part)
   fileRef = io.open("temp.gabc","r")
    for line in fileRef:lines() do
      idx = string.find(string.lower(line),"mode:")
      if idx then
        mode = string.sub(line,string.find(line,":")+1,-1)
        break
      end
    end
    io.close(fileRef)
    fileRef = io.open("temp.gabc","r")
    fileContent = {}
    table.insert(fileContent,"annotation: " .. part .. ";")
    table.insert(fileContent,"annotation: " .. mode)
    for line in fileRef:lines() do
      table.insert(fileContent,line)
    end
    io.close(fileRef)
    fileRef = io.open("temp.gabc", "w")
    for index, value in ipairs(fileContent) do
        fileRef:write(value .. "\n")
    end
    io.close(fileRef)
  end
\end{luacode*}

\luaexec{N = 0}
\def\includeGB#1#2{
  \luaexec{N = N + 1}
  \luaexec{print(N)}
  \luaexec{os.execute("curl -o temp.gabc https://gregobase.selapa.net/download.php?id=#1^&format=gabc^&elem=1")}
  \luaexec{editGabc(\luastring{#2})}
  \luaexec{os.execute("gregorio temp.gabc")}
  \input temp.gtex
}
