There are several comments in the code, ask if anything isn't clear.
There are so many things I don't understand. Fortunately I understood some little things so that I was able to integrate it in the whole score. e.g. I realized that it helps to split the staff definition completely for layout and midi. The default output of Frescobaldi is convenient in the first stage, but merging \with blocks may make it more difficult.
Finally I completed this song and I can give it away as a christmas surprise. You saved my day.