%% mousik.sty
%% Copyright (C) 2026 Celia Rubio Madrigal <rubiomadrigalcelia@gmail.com>
%%
%% This work may be distributed and/or modified under the conditions of the
%% LaTeX Project Public License, either version 1.3c of this license or (at
%% your option) any later version.
%%
%% The Current Maintainer of this work is Celia Rubio Madrigal.
%% This work has the LPPL maintenance status "maintained".

\NeedsTeXFormat{LaTeX2e}[2018/04/01]
\ProvidesPackage{mousik}[2026/08/24 v0.1 Manual music notation with TikZ]

\RequirePackage{harmony}
\RequirePackage{musixtex}
\RequirePackage{tikz}
\usetikzlibrary{backgrounds}

\DeclareFontFamily{U}{musix}{}%
\DeclareFontShape{U}{musix}{m}{n}{%
  <-12>   s * [1.5] musix11
  <12-15> s * [1.5] musix13
  <15-18> s * [1.5] musix16
  <18-23> s * [1.5] musix20
  <23->   s * [1.5] musix29
}{}%
\DeclareRobustCommand*\M@musix{\usefont{U}{musix}{m}{n}\selectfont}%
\DeclareTextFontCommand{\M@textmusix}{\M@musix}%
\DeclareRobustCommand*\M@musicsymbol[2][0pt]{%
  \raisebox{\dimexpr.45ex+(#1)\relax}{\M@textmusix{#2}}%
}
\DeclareRobustCommand*\M@sharpGlyph{\kern.05em\M@musicsymbol[.2ex]{4}\kern-.05em}%
\DeclareRobustCommand*\M@flatGlyph{\kern-.05em\M@musicsymbol{2}\kern-.06em}%
\DeclareRobustCommand*\M@naturalGlyph{\M@musicsymbol{6}\kern-.06em}%
\DeclareRobustCommand*\M@doubleSharpGlyph{\kern.05em\M@musicsymbol{5}\kern-.05em}%
\DeclareRobustCommand*\M@doubleFlatGlyph{\kern-.05em\M@musicsymbol{3}\kern-.06em}%


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Tools

\newcounter{M@modulo}
\newcommand{\M@odulo}[2]{
	\setcounter{M@modulo}{#1}
	\pgfmathparse{int(#2-#1)}
	\loop
	\ifnum\theM@modulo>\pgfmathresult
		\addtocounter{M@modulo}{-#2}
	\repeat
	\ifnum\theM@modulo<0
		\addtocounter{M@modulo}{#2}
	\repeat
}

\newcounter{M@max}
\newcommand{\M@ax}[2][\theM@max]{
	\setcounter{M@max}{#1}
	\ifnum#2>#1
		\setcounter{M@max}{#2}
	\fi
}

\newcounter{M@min}
\newcommand{\M@in}[2][\theM@min]{
	\setcounter{M@min}{#1}
	\ifnum#2<#1
		\setcounter{M@min}{#2}
	\fi
}

\newcounter{M@count}
\newcommand{\M@Count}[1]{
	\setcounter{M@count}{0}
	\foreach\IND in {#1} {\ifthenelse{\equal{\IND}{!}}{}{\stepcounter{M@count}}}
}

\newcommand{\M@EqStr}[3]{\ifthenelse{\equal{#1}{#2}}{#3}{}}
\newcommand{\M@NotEmpty}[2]{\ifthenelse{\equal{#1}{}}{}{#2}}

\newif\ifM@choiceValid
\newcommand{\M@CheckChoice}[2]{%
    \M@choiceValidfalse
    \edef\M@choiceValue{#1}%
    \@for\M@choice:=#2\do{%
        \edef\M@choiceCandidate{\M@choice}%
        \ifx\M@choiceValue\M@choiceCandidate
            \M@choiceValidtrue
        \fi
    }%
}
\newcommand{\M@CheckKeyValue}[2]{%
    \M@CheckChoice{#1}{-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7}%
    \ifM@choiceValid\else
        \PackageWarning{mousik}{Invalid key signature `#1' in #2. Expected an integer from -7 to 7; command ignored}%
    \fi
}

\newcounter{M@afterBar}
\newcounter{M@canTuckBar}
\newcommand{\M@moveMX}[1]{%
    \setcounter{M@afterBar}{0}%
    \setcounter{M@canTuckBar}{0}%
    \pgfmathparse{int((#1)*\M@hsep)}%
    \addtocounter{M@X}{\pgfmathresult}%
    \pgfmathsetmacro{\M@realX}{\theM@X*0.0625}%
}
\newcommand{\M@addMX}{\M@moveMX{1}}
\newcommand{\M@addhalfMX}{\M@moveMX{0.5}}
\newcommand{\M@addquarterMX}{\M@moveMX{0.25}}
\newcommand{\M@moveFixedMX}[1]{%
    \setcounter{M@afterBar}{0}%
    \setcounter{M@canTuckBar}{0}%
    \pgfmathparse{int(round(16*(#1)))}% 1 MX unit = 0.0625 cm
    \addtocounter{M@X}{\pgfmathresult}%
    \pgfmathsetmacro{\M@realX}{\theM@X*0.0625}%
}
\newcommand{\M@addStructMX}{\M@moveFixedMX{0.5}}% one old/default hsep unit
\newcommand{\M@addStructTwoMX}{\M@moveFixedMX{1.0}}% two old/default hsep units
\newcommand{\M@remStructQuarterMX}{\M@moveFixedMX{-0.125}}% old/default quarter unit
\newcommand{\M@addAccMX}{\M@moveMX{\M@accsep}}
\newcommand{\M@remMX}{\M@moveMX{-1}}
\newcommand{\M@remhalfMX}{\M@moveMX{-0.5}}
\newcommand{\M@remquarterMX}{\M@moveMX{-0.25}}

\newcommand{\M@ApplyIndent}{%
    \pgfmathparse{int(round(16*(\M@indent)))}% 1 MX unit = 0.0625 cm
    \setcounter{M@X}{\pgfmathresult}%
    \pgfmathsetmacro{\M@realX}{\theM@X*0.0625}%
    \setcounter{M@afterBar}{0}%
    \setcounter{M@canTuckBar}{0}%
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The main environment

\newcounter{M@first}
\newcounter{M@X}
\newcounter{M@Y}
\newcounter{M@clef}
\newcounter{M@key}
\newsavebox{\M@scorebox}


\newif\ifM@single
\newif\ifM@piano
\newif\ifM@pianoJoinedBars
\newif\ifM@barTwoMids
\newif\ifM@lengthSet
\newcounter{M@staff}
\newcounter{M@upperMX}
\newcounter{M@lowerMX}
\newcounter{M@upperMY}
\newcounter{M@lowerMY}
\newcounter{M@upperClef}
\newcounter{M@lowerClef}
\newcounter{M@upperKey}
\newcounter{M@lowerKey}
\newcounter{M@upperAfterBar}
\newcounter{M@lowerAfterBar}
\newcounter{M@upperCanTuckBar}
\newcounter{M@lowerCanTuckBar}
\newcounter{M@barAdvance}
\newcounter{M@barTuck}
\newcounter{M@barGapMX}
\newcounter{M@upperBarAdvance}
\newcounter{M@lowerBarAdvance}
\newcounter{M@advAfterBar}
\newcounter{M@advBarAdvance}
\newcounter{M@lastBarMX}
\newcounter{M@lastBarMY}
\newcounter{M@lastBarStaff}

\pgfkeys{
	/mousik/.is family
	, /mousik
	, default/.style = 
	{	indent = 0
		, length = 100
		, color = white
		, hsep = 8
		, accsep = 0.5
		, barsep = 2
		, scale = 1
		, vsep = 2
		, single = false
		, piano = false
		, piano-sep = 1.6
		, piano-bars = joined
		, tikz =
	}
	, indent/.estore in=\M@indent
	, length/.estore in=\M@length
	, color/.estore in=\M@color
	, hsep/.estore in=\M@hsep
	, accsep/.estore in=\M@accsep
	, barsep/.estore in=\M@barsep
	, scale/.estore in=\M@scale
	, vsep/.estore in=\M@vsep
	, single/.is if=M@single
	, piano/.is if=M@piano
	, piano-sep/.estore in=\M@pianoSep
	, piano-bars/.is choice
	, piano-bars/joined/.code={\M@pianoJoinedBarstrue}
	, piano-bars/separate/.code={\M@pianoJoinedBarsfalse}
	, tikz/.estore in=\M@TIKz
}

\newcommand{\M@Initialize}[1][]{%
\pgfkeys{/mousik, default, #1}%
\ifM@piano
	\pgfmathsetmacro{\M@vsep}{\M@vsep+\M@pianoSep}%
\fi
\setcounter{M@X}{0}\setcounter{M@Y}{0}%
\setcounter{M@clef}{-1}\setcounter{M@key}{0}%
\setcounter{M@staff}{1}%
\setcounter{M@upperMX}{0}\setcounter{M@lowerMX}{0}%
\setcounter{M@upperMY}{0}\setcounter{M@lowerMY}{0}%
\setcounter{M@upperClef}{-1}\setcounter{M@lowerClef}{-1}%
\setcounter{M@upperKey}{0}\setcounter{M@lowerKey}{0}%
\setcounter{M@afterBar}{0}\setcounter{M@canTuckBar}{0}%
\setcounter{M@upperAfterBar}{0}\setcounter{M@lowerAfterBar}{0}%
\setcounter{M@upperCanTuckBar}{0}\setcounter{M@lowerCanTuckBar}{0}%
\setcounter{M@barAdvance}{0}\setcounter{M@upperBarAdvance}{0}\setcounter{M@lowerBarAdvance}{0}%
\setcounter{M@advAfterBar}{0}\setcounter{M@advBarAdvance}{0}%
\setcounter{M@lastBarMX}{-100000}\setcounter{M@lastBarMY}{-100000}\setcounter{M@lastBarStaff}{0}%
\M@lengthSetfalse
\ifM@single
	\def\M@staffBottom{0.2}\def\M@staffTop{0.6}\def\M@staffMid{0.4}%
\else
	\def\M@staffBottom{0}\def\M@staffTop{0.8}\def\M@staffMid{0.4}%
\fi
\pgfmathsetmacro{\M@barBottom}{\M@staffBottom-0.007}%

\pgfmathsetmacro{\M@barTop}{\M@staffTop+0.007}%
}

\newcommand{\M@InstallShortCommands}{%
    \let\UpperStaff\mousikUpperStaff
    \let\LowerStaff\mousikLowerStaff
    \let\Clef\mousikClef
    \let\TimeSig\mousikTimeSig
    \let\Dotted\mousikDotted
    \let\Appog\mousikAppog
    \let\Appogs\mousikAppogs
    \let\Note\mousikNote
    \let\Rest\mousikRest
    \let\Artics\mousikArtics
    \let\Artic\mousikArtic
    \let\Symbol\mousikSymbol
    \let\Acc\mousikAcc
    \let\Accs\mousikAccs
    \let\Key\mousikKey
    \let\NoKey\mousikNoKey
    \let\MixedKey\mousikMixedKey
    \let\Text\mousikText
    \let\Dynamics\mousikDynamics
    \let\NoteSpace\mousikNoteSpace
    \let\AccSpace\mousikAccSpace
    \let\Space\mousikSpace
    \let\Barline\mousikBarline
    \let\BreakLine\mousikBreakLine
    \let\Tempo\mousikTempo
    \let\Tie\mousikTie
    \let\Slur\mousikSlur
    \let\Slurred\mousikSlurred
    \let\endSlurred\endmousikSlurred
    \let\Crescendo\mousikCrescendo
    \let\endCrescendo\endmousikCrescendo
    \let\Decrescendo\mousikDecrescendo
    \let\endDecrescendo\endmousikDecrescendo
}

\newcommand{\mousikInit}[1][]{%
    \M@Initialize[#1]%
    \M@InstallShortCommands
}

\newcommand{\M@SaveStaffState}{%
\ifnum\theM@staff=1
	\setcounter{M@upperMX}{\theM@X}\setcounter{M@upperMY}{\theM@Y}%
	\setcounter{M@upperClef}{\theM@clef}\setcounter{M@upperKey}{\theM@key}%
	\setcounter{M@upperAfterBar}{\theM@afterBar}%
	\setcounter{M@upperCanTuckBar}{\theM@canTuckBar}%
	\setcounter{M@upperBarAdvance}{\theM@barAdvance}%
\else
	\setcounter{M@lowerMX}{\theM@X}\setcounter{M@lowerMY}{\theM@Y}%
	\setcounter{M@lowerClef}{\theM@clef}\setcounter{M@lowerKey}{\theM@key}%
	\setcounter{M@lowerAfterBar}{\theM@afterBar}%
	\setcounter{M@lowerCanTuckBar}{\theM@canTuckBar}%
	\setcounter{M@lowerBarAdvance}{\theM@barAdvance}%
\fi}

\newcommand{\M@RestoreStaffState}[1]{%
\ifnum#1=1
	\setcounter{M@X}{\theM@upperMX}\setcounter{M@Y}{\theM@upperMY}%
	\setcounter{M@clef}{\theM@upperClef}\setcounter{M@key}{\theM@upperKey}%
	\setcounter{M@afterBar}{\theM@upperAfterBar}%
	\setcounter{M@canTuckBar}{\theM@upperCanTuckBar}%
	\setcounter{M@barAdvance}{\theM@upperBarAdvance}%
\else
	\setcounter{M@X}{\theM@lowerMX}\setcounter{M@Y}{\theM@lowerMY}%
	\setcounter{M@clef}{\theM@lowerClef}\setcounter{M@key}{\theM@lowerKey}%
	\setcounter{M@afterBar}{\theM@lowerAfterBar}%
	\setcounter{M@canTuckBar}{\theM@lowerCanTuckBar}%
	\setcounter{M@barAdvance}{\theM@lowerBarAdvance}%
\fi
\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}}

\newcommand{\M@SwitchStaff}[1]{%
\ifM@piano
	\ifnum#1=\theM@staff\else
		\M@SaveStaffState
		\ifnum\theM@staff=2 \pgftransformyshift{\M@pianoSep cm}\fi
		\setcounter{M@staff}{#1}%
		\ifnum#1=2 \pgftransformyshift{-\M@pianoSep cm}\fi
		\M@RestoreStaffState{#1}%
	\fi
\else
	\PackageWarning{mousik}{\string\mousikUpperStaff/\string\mousikLowerStaff\space require the piano option}%
\fi}

\newcommand{\mousikUpperStaff}{\M@SwitchStaff{1}}
\newcommand{\mousikLowerStaff}{\M@SwitchStaff{2}}

\newcommand{\M@PreparePianoStaff}{%
\M@SaveStaffState
\ifnum\theM@staff=2 \pgftransformyshift{\M@pianoSep cm}\fi
\pgfmathparse{int(2*\M@hsep)}\setcounter{M@aux}{\pgfmathresult}%
\ifnum\theM@upperAfterBar=1
    \addtocounter{M@upperMX}{-\theM@upperBarAdvance}%
\else
    \addtocounter{M@upperMX}{-\theM@aux}%
\fi
\ifnum\theM@lowerAfterBar=1
    \addtocounter{M@lowerMX}{-\theM@lowerBarAdvance}%
\else
    \addtocounter{M@lowerMX}{-\theM@aux}%
\fi
\ifnum\theM@upperMX<0 \setcounter{M@upperMX}{0}\fi
\ifnum\theM@lowerMX<0 \setcounter{M@lowerMX}{0}\fi
\ifnum\theM@upperMY>\theM@lowerMY
	\setcounter{M@Y}{\theM@upperMY}\setcounter{M@X}{\theM@upperMX}%
\else\ifnum\theM@lowerMY>\theM@upperMY
	\setcounter{M@Y}{\theM@lowerMY}\setcounter{M@X}{\theM@lowerMX}%
\else
	\setcounter{M@Y}{\theM@upperMY}%
	\ifnum\theM@upperMX>\theM@lowerMX
		\setcounter{M@X}{\theM@upperMX}%
	\else
		\setcounter{M@X}{\theM@lowerMX}%
	\fi
\fi\fi
\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}%
}

\newenvironment{mousik}[1][]{%
\M@Initialize[#1]%
\noindent\begin{lrbox}{\M@scorebox}%
\begin{tikzpicture}[
	background rectangle/.style={fill=\M@color},
	show background rectangle,\M@TIKz]
\M@InstallShortCommands
\M@ApplyIndent
\ifM@piano
	\setcounter{M@upperMX}{\theM@X}\setcounter{M@lowerMX}{\theM@X}%
\fi
}{%
\ifM@piano
	\M@PreparePianoStaff
\else
    % End the staff at the printed last symbol.  A final barline has its own
    % spacing (barsep), so do not assume the old fixed two-hsep advance.
    \ifnum\theM@afterBar=1
        \addtocounter{M@X}{-\theM@barAdvance}%
        \pgfmathsetmacro{\M@realX}{\theM@X*0.0625}%
    \else
        \M@remMX\M@remMX
    \fi
\fi
\M@Staff % paint the staff at the end
\setcounter{M@X}{0}\setcounter{M@Y}{0}
\setcounter{M@clef}{-1}\setcounter{M@key}{0}
\end{tikzpicture}%
\end{lrbox}%
\scalebox{\M@scale}{\usebox{\M@scorebox}}}

\newif\ifM@swap\M@swapfalse % the user defined
\newif\ifM@noSwap\M@noSwapfalse % the internal
\newcommand{\M@Swap}{\ifM@noSwap \M@noSwapfalse \else \M@noSwaptrue \fi}

\newcommand{\M@DrawStaffAt}[2]{%
\pgfmathsetmacro{\M@XcoordOne}{%
	\ifnum#1=0 {-0.25+\M@indent} \else {-0.25} \fi}%
\pgfmathsetmacro{\M@XcoordTwo}{%
	\ifnum#1=\theM@Y {\theM@X*0.0625} \else {\M@length*0.12} \fi}%
\ifM@single
	\pgfmathsetmacro{\M@Ycoord}{-#1*\M@vsep+(#2)+0.4}%
	\draw (\M@XcoordOne,\M@Ycoord) -- (\M@XcoordTwo,\M@Ycoord);%
\else
	\foreach\INDj in {0,...,4} {%
		\pgfmathsetmacro{\M@Ycoord}{-#1*\M@vsep+(#2)+\INDj*0.2}%
		\draw (\M@XcoordOne,\M@Ycoord) -- (\M@XcoordTwo,\M@Ycoord);%
	}%
\fi}

\newcommand{\M@DrawPianoInitial}[1]{%
\pgfmathsetmacro{\M@XcoordOne}{%
	\ifnum#1=0 {-0.25+\M@indent} \else {-0.25} \fi}%
\pgfmathsetmacro{\M@PianoTopY}{-#1*\M@vsep+\M@staffTop}%
\pgfmathsetmacro{\M@PianoBottomY}{-#1*\M@vsep-\M@pianoSep+\M@staffBottom}%
\pgfmathsetmacro{\M@PianoMidY}{(\M@PianoTopY+\M@PianoBottomY)/2}%
\pgfmathsetmacro{\M@PianoBraceH}{\M@PianoTopY-\M@PianoBottomY}%
\pgfmathtruncatemacro{\M@PianoBraceChar}{max(128,min(173,round(128+14.2264*\M@PianoBraceH)))}%
\draw (\M@XcoordOne,\M@PianoTopY+0.007) -- (\M@XcoordOne,\M@PianoBottomY-0.007);%
\node[inner sep=0pt] at (\M@XcoordOne-0.10,\M@PianoMidY)
	{\mxsps\char\M@PianoBraceChar\relax};%
}

\newcommand{\M@Staff}{%
\foreach\INDi in {0,...,\theM@Y} {% amount of score systems
	\M@DrawStaffAt{\INDi}{0}%
	\ifM@piano \M@DrawStaffAt{\INDi}{-\M@pianoSep}\M@DrawPianoInitial{\INDi}\fi
}}

\newcommand{\M@Octave}[1]{ % where to place the clefs (hardcoded)
\ifnum#1=8
	\ifnum\theM@clef=1
	\node at (\M@realX+0.15,-\theM@Y*\M@vsep+0.95) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=2
	\node at (\M@realX+0.15,-\theM@Y*\M@vsep+1.1) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=3
	\node at (\M@realX+0.05,-\theM@Y*\M@vsep+0.7) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=4
	\node at (\M@realX+0.05,-\theM@Y*\M@vsep+0.95) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=11
	\node at (\M@realX+0.1,-\theM@Y*\M@vsep+0.6) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=12
	\node at (\M@realX+0.1,-\theM@Y*\M@vsep+0.8) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=13
	\node at (\M@realX+0.1,-\theM@Y*\M@vsep+1) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=14
	\node at (\M@realX+0.1,-\theM@Y*\M@vsep+1.2) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=15
	\node at (\M@realX+0.1,-\theM@Y*\M@vsep+1.4) {\scriptsize\bfseries 8};
	\fi
\fi\ifnum#1=-8
	\ifnum\theM@clef=1
	\node at (\M@realX+0.05,-\theM@Y*\M@vsep-0.6) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=2
	\node at (\M@realX+0.05,-\theM@Y*\M@vsep-0.4) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=3
	\node at (\M@realX+0.05,-\theM@Y*\M@vsep-0.2) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=4
	\node at (\M@realX+0.05,-\theM@Y*\M@vsep) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=11
	\node at (\M@realX+0.1,-\theM@Y*\M@vsep-0.6) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=12
	\node at (\M@realX+0.1,-\theM@Y*\M@vsep-0.4) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=13
	\node at (\M@realX+0.1,-\theM@Y*\M@vsep-0.2) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=14
	\node at (\M@realX+0.1,-\theM@Y*\M@vsep) {\scriptsize\bfseries 8};
	\fi\ifnum\theM@clef=15
	\node at (\M@realX+0.1,-\theM@Y*\M@vsep+0.2) {\scriptsize\bfseries 8};
	\fi
\fi
}

\pgfkeys{
	/mousik/clef/.is family
	, /mousik/clef
	, default/.style = 
	{	t = 2
		, octave = 0
		, xshift = 0
		, yshift = 0
	}
	, t/.estore in=\M@clefT
	, octave/.estore in=\M@clefOct
	, xshift/.estore in=\M@shiftX
	, yshift/.estore in=\M@shiftY
}

\newcommand{\mousikClef}[1][]{
	\pgfkeys{/mousik/clef, default, #1}%
    \M@CheckChoice{\M@clefT}{0,1,2,3,4,11,12,13,14,15}%
    \ifM@choiceValid\else
        \PackageWarning{mousik}{Unknown clef type `\M@clefT'. Using the default t=2}%
        \def\M@clefT{2}%
    \fi
    \M@CheckChoice{\M@clefOct}{-8,0,8}%
    \ifM@choiceValid\else
        \PackageWarning{mousik}{Unknown clef octave `\M@clefOct'. Expected -8, 0, or 8; using 0}%
        \def\M@clefOct{0}%
    \fi
	\setcounter{M@clef}{\M@clefT}
	\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
\begin{scope}[xshift=\M@shiftX cm,yshift=\M@shiftY cm]
	
	\M@Octave{\M@clefOct}
	
	\ifnum\theM@clef=1
		\node at (\M@realX+0.1,-\theM@Y*\M@vsep+0.15)
		{\trebleclef};
	\fi\ifnum\theM@clef=2
		\node at (\M@realX+0.1,-\theM@Y*\M@vsep+0.35)
		{\trebleclef};
	\fi\ifnum\theM@clef=3
		\node at (\M@realX+0.1,-\theM@Y*\M@vsep+0.8)
		{{\resizebox{0.7cm}{0.8cm}{\bassclef}}};
	\fi\ifnum\theM@clef=4
		\node at (\M@realX+0.1,-\theM@Y*\M@vsep+1)
		{{\resizebox{0.7cm}{0.8cm}{\bassclef}}};
	\fi\ifnum\theM@clef=11
		\node at (\M@realX+0.1,-\theM@Y*\M@vsep+0.4)
		{{\resizebox{0.65cm}{0.8cm}{\altoclef}}};
	\fi\ifnum\theM@clef=12
		\node at (\M@realX+0.1,-\theM@Y*\M@vsep+0.6)
		{{\resizebox{0.65cm}{0.8cm}{\altoclef}}};
	\fi\ifnum\theM@clef=13
		\node at (\M@realX+0.1,-\theM@Y*\M@vsep+0.8)
		{{\resizebox{0.65cm}{0.8cm}{\altoclef}}};
	\fi\ifnum\theM@clef=14
		\node at (\M@realX+0.1,-\theM@Y*\M@vsep+1)
		{{\resizebox{0.65cm}{0.8cm}{\altoclef}}};
	\fi\ifnum\theM@clef=15
		\node at (\M@realX+0.1,-\theM@Y*\M@vsep+1.2)
		{{\resizebox{0.65cm}{0.8cm}{\altoclef}}};
	\fi\ifnum\theM@clef=0
		\draw[line width=1.5mm] (\M@realX,-\theM@Y*\M@vsep+0.2) -- (\M@realX,-\theM@Y*\M@vsep+0.6);
		\draw[line width=1.5mm] (\M@realX+0.3,-\theM@Y*\M@vsep+0.2) -- (\M@realX+0.3,-\theM@Y*\M@vsep+0.6);
	\fi
\end{scope}
\M@addStructTwoMX
}

\newlength{\M@Width}
\newlength{\M@Height}
\newcommand{\M@Resize}[1]{
	\settowidth{\M@Width}{#1}
	\settoheight{\M@Height}{#1}
	\resizebox{1.5\M@Width}{1.5\M@Height}{#1}
}

\pgfkeys{
	/mousik/timesig/.is family
	, /mousik/timesig
	, default/.style = 
	{	xshift = 0
		, yshift = 0
	}
	, xshift/.estore in=\M@shiftX
	, yshift/.estore in=\M@shiftY
}

\newcommand{\mousikTimeSig}[3][]{
	\pgfkeys{/mousik/timesig, default, #1}%
	\M@Adv
	\pgfmathsetmacro{\M@TimeSigX}{\M@realX-0.375}%
\begin{scope}[xshift=\M@shiftX cm,yshift=\M@shiftY cm]
	\normalsize
	\ifx&#3&
		\ifthenelse{\equal{#2}{C}}%
			{\node at (\M@TimeSigX,-\theM@Y*\M@vsep+0.5) {\meterC};}%
		{\ifthenelse{\equal{#2}{C|}}%
			{\node at (\M@TimeSigX,-\theM@Y*\M@vsep+0.575) {\allabreve};}%
		{\node at (\M@TimeSigX,-\theM@Y*\M@vsep+0.4) {\bfseries \M@Resize{#2}};}}
	\else
		\node at (\M@TimeSigX,-\theM@Y*\M@vsep+0.6) {\bfseries \M@Resize{#2}};
		\node at (\M@TimeSigX,-\theM@Y*\M@vsep+0.2) {\bfseries \M@Resize{#3}};
	\fi
\end{scope}
\M@addStructTwoMX
}

\newcommand{\M@Dot}[2][1]{
\foreach \IND in {1,...,#1}
	{\M@PlaceNR[+0.15*\IND]{#2}{\resizebox{0.1cm}{0.1cm}{$\bullet$}}}}

\pgfkeys{
	/mousik/dotted/.is family
	, /mousik/dotted
	, default/.style =
	{ t = *
		, xshift = 0
		, yshift = 0
	}
	, t/.estore in=\M@DottedT
	, xshift/.estore in=\M@shiftX
	, yshift/.estore in=\M@shiftY
}

\newcounter{M@aux}
\newcommand{\M@ParallelList}[2]{% #1 symbol/height list, #2 action(symbol,height)
	\setcounter{M@aux}{\theM@X}%
	\foreach\INDp/\INDh in {#1} {%
		\ifthenelse{\equal{\INDp}{!}}{\M@addAccMX}{%
			\M@NotEmpty{\INDp}{#2{\INDp}{\INDh}}%
			\M@addMX
		}%
	}%
	\setcounter{M@X}{\theM@aux}\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}%
}

\newcommand{\M@DrawDotted}[2]{% #1 type, #2 height
	\M@EqStr{#1}{*}{\M@Dot[1]{#2}}%
	\M@EqStr{#1}{.}{\M@Dot[1]{#2}}%
	\M@EqStr{#1}{**}{\M@Dot[2]{#2}}%
	\M@EqStr{#1}{..}{\M@Dot[2]{#2}}%
}
\newcommand{\M@ParallelDotted}[2]{\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}\M@DrawDotted{#1}{#2}}

\newif\ifM@DottedList
\def\M@CheckDottedList#1{%
	\M@DottedListfalse
	\def\M@DottedComma##1,##2\M@DottedEnd{%
		\def\M@DottedTail{##2}%
		\ifx\M@DottedTail\@empty\else\M@DottedListtrue\fi}%
	\expandafter\M@DottedComma#1,\M@DottedEnd
	\ifM@DottedList\else
		\def\M@DottedSlash##1/##2\M@DottedEnd{%
			\def\M@DottedTail{##2}%
			\ifx\M@DottedTail\@empty\else\M@DottedListtrue\fi}%
		\expandafter\M@DottedSlash#1/\M@DottedEnd
	\fi
}

\newcommand{\mousikDotted}[2][]{%
	\pgfkeys{/mousik/dotted, default, #1}%
	\M@CheckDottedList{#2}%
	\ifM@DottedList
		\M@Adv
		\begin{scope}[xshift=\M@shiftX cm,yshift=\M@shiftY cm]
			\M@ParallelList{#2}{\M@ParallelDotted}%
		\end{scope}
	\else
        \M@CheckChoice{\M@DottedT}{*,.,**,..}%
        \ifM@choiceValid\else
            \PackageWarning{mousik}{Unknown dotted type `\M@DottedT'. Expected *, ., **, or ..; no dots drawn}%
        \fi
		\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}%
		\begin{scope}[xshift=\M@shiftX cm,yshift=\M@shiftY cm]
            \ifM@choiceValid \M@DrawDotted{\M@DottedT}{#2}\fi
		\end{scope}
	\fi
}

\newcounter{M@height}
\newif\ifM@tupletBracket
\newcommand{\M@Tuplet}[1][]{
	\pgfmathsetmacro{\M@TupletNoteMid}{
		\theM@aux*0.0625 + int(\theM@X-\theM@aux-\M@hsep*2)*0.0625*0.5}
	\ifnum\theM@count>2
		\ifM@noSwap
			\pgfmathsetmacro{\M@TupletBeamLeft}{\theM@aux*0.0625 + 0.103}
			\pgfmathsetmacro{\M@TupletBeamRight}{(\theM@X-2*\M@hsep)*0.0625 + 0.128}
		\else
			\pgfmathsetmacro{\M@TupletBeamLeft}{\theM@aux*0.0625 - 0.153}
			\pgfmathsetmacro{\M@TupletBeamRight}{(\theM@X-2*\M@hsep)*0.0625 - 0.125}
		\fi
		\pgfmathsetmacro{\M@TupletX}{0.5*(\M@TupletBeamLeft+\M@TupletBeamRight)}
		\pgfmathsetmacro{\M@TupletLeft}{\M@TupletBeamLeft-0.08}
		\pgfmathsetmacro{\M@TupletRight}{\M@TupletBeamRight+0.08}
	\else
		\pgfmathsetmacro{\M@TupletX}{\M@TupletNoteMid}
		\pgfmathsetmacro{\M@TupletLeft}{\theM@aux*0.0625 - 0.08}
		\pgfmathsetmacro{\M@TupletRight}{2*\M@TupletNoteMid-\theM@aux*0.0625 + 0.08}
	\fi

	\pgfmathsetmacro{\M@TupletBeamY}{-\theM@Y*\M@vsep-0.2+\theM@height*0.1}
	\ifM@noSwap
		\pgfmathsetmacro{\M@TupletY}{\M@TupletBeamY+0.35}
	\else
		\pgfmathsetmacro{\M@TupletY}{\M@TupletBeamY-0.35}
	\fi

	\begin{scope}[xshift=\M@tupletXshift cm,yshift=\M@tupletYshift cm]
		\ifM@tupletBracket
			\draw[line width=0.15mm] (\M@TupletLeft,\M@TupletY) -- (\M@TupletRight,\M@TupletY);
			\ifM@noSwap
				\draw[line width=0.15mm] (\M@TupletLeft,\M@TupletY) -- +(0,-0.10);
				\draw[line width=0.15mm] (\M@TupletRight,\M@TupletY) -- +(0,-0.10);
			\else
				\draw[line width=0.15mm] (\M@TupletLeft,\M@TupletY) -- +(0,0.10);
				\draw[line width=0.15mm] (\M@TupletRight,\M@TupletY) -- +(0,0.10);
			\fi
		\fi
		\node[fill=\M@color,inner sep=1pt] at (\M@TupletX,\M@TupletY)
			{\ifthenelse{\equal{#1}{}}{\theM@count}{#1}};
	\end{scope}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Notes : bits

\newcommand{\M@Head}[1]{
	\M@EqStr{.}{\M@head}{\M@RoundHead{#1}}
	\M@EqStr{o}{\M@head}{\M@HollowHead{#1}}
	\M@EqStr{x}{\M@head}{\M@CrossHead{#1}}}

\newcommand{\M@RoundHead}[1]{
	\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
	\ifM@noteBack
		\node [opacity=0.0] (tmp) at (\M@realX-0.265,-\theM@Y*\M@vsep-0.2+#1*0.1) {};
		\fill[black,rotate around={16:(tmp.center)}] (\M@realX-0.01-0.265,-\theM@Y*\M@vsep-0.195+#1*0.1) ellipse (4pt and 2.75pt);
	\else 
		\node [opacity=0.0] (tmp) at (\M@realX,-\theM@Y*\M@vsep-0.2+#1*0.1) {};
		\fill[black,rotate around={16:(tmp.center)}] (\M@realX-0.01,-\theM@Y*\M@vsep-0.195+#1*0.1) ellipse (4pt and 2.75pt);
	\fi
}

\newcommand{\M@HollowHead}[1]{
	\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
	\M@RoundHead{#1}
	\ifM@noteBack
		\fill[\M@color,rotate around={19:(tmp.center)}] (\M@realX-0.01-0.265,-\theM@Y*\M@vsep-0.195+#1*0.1) ellipse (3.2pt and 1.35pt);
	\else 
		\fill[\M@color,rotate around={19:(tmp.center)}] (\M@realX-0.01,-\theM@Y*\M@vsep-0.195+#1*0.1) ellipse (3.2pt and 1.35pt);
	\fi
}

\newcommand{\M@CrossHead}[1]{
	\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
	\ifM@noteBack
		\draw (\M@realX -0.125-0.265,-\theM@Y*\M@vsep+#1*0.1 -0.1) --
		(\M@realX +0.1-0.265,-\theM@Y*\M@vsep+#1*0.1 -0.3);
		\draw (\M@realX +0.1-0.265,-\theM@Y*\M@vsep+#1*0.1 -0.1) --
		(\M@realX -0.125-0.265,-\theM@Y*\M@vsep+#1*0.1 -0.3);
	\else 
		\draw (\M@realX -0.125,-\theM@Y*\M@vsep+#1*0.1 -0.1) --
		(\M@realX +0.1,-\theM@Y*\M@vsep+#1*0.1 -0.3);
		\draw (\M@realX +0.1,-\theM@Y*\M@vsep+#1*0.1 -0.1) --
		(\M@realX -0.125,-\theM@Y*\M@vsep+#1*0.1 -0.3);
	\fi
}

\newcommand{\M@enlarge}[3][\M@stem]{
	\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
	\ifM@noSwap
		\draw[line width=0.25mm]  (\M@realX+0.115,-\theM@Y*\M@vsep+#2*0.1-0.2) --
			(\M@realX+0.115,-\theM@Y*\M@vsep+#3*0.1+#1-0.2);
		
	\else
		\draw[line width=0.25mm]  (\M@realX-0.14,-\theM@Y*\M@vsep+#2*0.1-0.2) --
			(\M@realX-0.14,-\theM@Y*\M@vsep+#3*0.1-0.4-#1+0.2);
	\fi
}

\newcommand{\M@Ledger}[1]{
	\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
	\ifnum1>#1
	\foreach\INDi in {0,...,#1} {
		\ifthenelse{\isodd{\INDi}}{}%
		{\draw (\M@realX-0.25,-\theM@Y*\M@vsep-0.2+\INDi*0.1) --
		(\M@realX+0.25,-\theM@Y*\M@vsep-0.2+\INDi*0.1);}
	}
	\fi\ifnum11<#1
	\foreach\INDi in {12,...,#1} {
		\ifthenelse{\isodd{\INDi}}{}%
		{\draw (\M@realX-0.25,-\theM@Y*\M@vsep-0.2+\INDi*0.1) --
		(\M@realX+0.25,-\theM@Y*\M@vsep-0.2+\INDi*0.1);}
	}
	\fi
}

\newcommand{\M@DrawSlopedBeam}[4]{% left x/y, right x/y; vertical ends
  \pgfmathsetmacro{\M@BeamHalfThickness}{0.05*\M@beam}% beam is in mm; coordinates are cm
  \ifx\tikz@strokecolor\pgfutil@empty
    \fill
  \else
    \fill[\tikz@strokecolor]
  \fi
    (#1,#2+\M@BeamHalfThickness) --
    (#3,#4+\M@BeamHalfThickness) --
    (#3,#4-\M@BeamHalfThickness) --
    (#1,#2-\M@BeamHalfThickness) -- cycle;
}

\newcommand{\M@Beam}[5][\theM@X]{
  \pgfmathsetmacro{\M@BeamLeftX}{(#2)*0.0625}%
  \pgfmathsetmacro{\M@BeamRightX}{((#1)-\M@hsep)*0.0625}%
  \pgfmathsetmacro{\M@BeamLeftY}{-\theM@Y*\M@vsep-0.2+(#3)*0.1}%
  \pgfmathsetmacro{\M@BeamRightY}{-\theM@Y*\M@vsep-0.2+(#4)*0.1}%
  \pgfmathsetmacro{\M@BeamOffset}{#5}%
  \pgfmathtruncatemacro{\M@BeamFlat}{abs((#4)-(#3)) < 0.0001 ? 1 : 0}%
  \ifM@noSwap
    \ifnum\M@BeamFlat=1
      \draw[line width=\M@beam mm]
        (\M@BeamLeftX+0.103,\M@BeamLeftY+\M@BeamOffset) --
        (\M@BeamRightX+0.128,\M@BeamRightY+\M@BeamOffset);%
    \else
      \M@DrawSlopedBeam
        {\M@BeamLeftX+0.103}{\M@BeamLeftY+\M@BeamOffset}
        {\M@BeamRightX+0.128}{\M@BeamRightY+\M@BeamOffset}%
    \fi
  \else
    \ifnum\M@BeamFlat=1
      \draw[line width=\M@beam mm]
        (\M@BeamLeftX-0.153,\M@BeamLeftY-\M@BeamOffset) --
        (\M@BeamRightX-0.125,\M@BeamRightY-\M@BeamOffset);%
    \else
      \M@DrawSlopedBeam
        {\M@BeamLeftX-0.153}{\M@BeamLeftY-\M@BeamOffset}
        {\M@BeamRightX-0.125}{\M@BeamRightY-\M@BeamOffset}%
    \fi
  \fi
}

\newcommand{\M@SetBeamStem}[1]{%
    \ifnum#1<16
        \pgfmathsetmacro\M@Sstem{\M@stem+0.1}%
    \else\ifnum#1=16
        \pgfmathsetmacro\M@Sstem{\M@stem+0.2}%
    \else\ifnum#1=32
        \pgfmathsetmacro\M@Sstem{\M@stem+0.3}%
    \fi\fi\fi
}

\newcommand{\M@DrawBeamLevels}[5][\theM@X]{% #1 right cursor, #2 duration, #3 left cursor, #4/#5 endpoint heights
    \M@SetBeamStem{#2}%
    \M@Beam[#1]{#3}{#4}{#5}{+\M@Sstem}%
    \ifnum#2=16
        \pgfmathsetmacro\M@Sstem{\M@stem+0.05}%
        \M@Beam[#1]{#3}{#4}{#5}{+\M@Sstem}%
    \fi
    \ifnum#2=32
        \pgfmathsetmacro\M@Sstem{\M@stem+0.15}%
        \M@Beam[#1]{#3}{#4}{#5}{+\M@Sstem}%
        \M@Beam[#1]{#3}{#4}{#5}{+\M@stem}%
    \fi
}

\newcommand{\M@Flag}[2][0]{
	\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
	\ifM@noSwap
	\begin{scope}
		\clip (\M@realX+0.13,-\theM@Y*\M@vsep+#2*0.1-0.95+#1) rectangle (\M@realX+0.35,-\theM@Y*\M@vsep+#2*0.1-0.15+#1);
		\node at (\M@realX+0.05,-\theM@Y*\M@vsep-0.5+#2*0.1+#1) {\resizebox{0.55cm}{0.65cm}{\Acht}};
	\end{scope}
	\fill[\M@color] (\M@realX+0.205,-\theM@Y*\M@vsep-0.508+#2*0.1+#1) circle (1.75pt);
	\else
	\begin{scope}
		\node [opacity=0.0] (tmp) at (\M@realX,-\theM@Y*\M@vsep+0.2+#2*0.1) {};
		\clip (\M@realX-0.125,-\theM@Y*\M@vsep+#2*0.1-0.25-#1) rectangle (\M@realX+0.09,-\theM@Y*\M@vsep+#2*0.1+0.35-#1);
		\node[rotate around={180:(tmp.center)}] at (\M@realX+0.175,-\theM@Y*\M@vsep+0.265+#2*0.1+#1) {\reflectbox{\resizebox{0.55cm}{0.65cm}{\Acht}}};
	\end{scope}
	\fill[\M@color] (\M@realX-0.035,-\theM@Y*\M@vsep+0.139+#2*0.1-#1) circle (2pt);
	\fi
}

\newcommand{\M@Semibreve}[1]{
	\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
	\ifM@noteBack
		\node at (\M@realX-0.265,-\theM@Y*\M@vsep-0.2+#1*0.1) {\resizebox{0.3cm}{0.2cm}{\Ganz}};
	\else
		\node at (\M@realX,-\theM@Y*\M@vsep-0.2+#1*0.1) {\resizebox{0.3cm}{0.2cm}{\Ganz}};
	\fi
}

\newcommand{\M@commonStem}[1]{
	\ifnum#1>5 \M@Swap \fi
	\M@enlarge[\M@Sstem]{#1}{#1}	
	\ifM@noSwap \pgfmathparse{1} \else \pgfmathparse{-1} \fi
	\pgfmathsetmacro\M@High{int(#1 + \pgfmathresult * 10*\M@Sstem)}
	\setcounter{M@height}{\M@High}
}

\newcommand{\M@Minim}[1]{
	\M@HollowHead{#1}
	\pgfmathsetmacro\M@Sstem{\M@stem+0.1}
	\M@commonStem{#1}
}

\newcommand{\M@Crotchet}[1]{
	\M@Head{#1}
	\pgfmathsetmacro\M@Sstem{\M@stem+0.1}
	\M@commonStem{#1}
}

\newcommand{\M@SetUnbeamedStem}[1]{%
	\ifnum#1<8
		\pgfmathsetmacro\M@Sstem{\M@stem+0.1}%
	\else\ifnum#1=8
		\pgfmathsetmacro\M@Sstem{\M@stem+0.2}%
	\else\ifnum#1=16
		\pgfmathsetmacro\M@Sstem{\M@stem+0.3}%
	\else\ifnum#1=32
		\pgfmathsetmacro\M@Sstem{\M@stem+0.4}%
	\fi\fi\fi\fi
}

\newcommand{\M@DrawFlags}[2]{% #1 duration, #2 stem base
	\ifnum#1=8
		\M@Flag[\M@Sstem]{#2}%
	\fi
	\ifnum#1=16
		\M@Flag[\M@Sstem]{#2}%
		\pgfmathsetmacro\M@Sstem{\M@stem+0.15}%
		\M@Flag[\M@Sstem]{#2}%
	\fi
	\ifnum#1=32
		\M@Flag[\M@Sstem]{#2}%
		\pgfmathsetmacro\M@Sstem{\M@stem+0.25}%
		\M@Flag[\M@Sstem]{#2}%
		\pgfmathsetmacro\M@Sstem{\M@stem+0.1}%
		\M@Flag[\M@Sstem]{#2}%
	\fi
}

\newcommand{\M@FlaggedNote}[2]{% #1 duration, #2 height
	\M@Head{#2}%
	\M@SetUnbeamedStem{#1}%
	\M@commonStem{#2}%
	\M@DrawFlags{#1}{#2}%
}

\newcommand{\M@Quaver}[1]{\M@FlaggedNote{8}{#1}}
\newcommand{\M@Semiquaver}[1]{\M@FlaggedNote{16}{#1}}
\newcommand{\M@Demisemiquaver}[1]{\M@FlaggedNote{32}{#1}}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Chords

\newif\ifM@ChordLeft
\newcommand{\M@IfChord}[3]{%
    \def\M@ChordYes{#2}%
    \def\M@ChordNo{#3}%
    \expandafter\M@IfChordAux#1/\@nil
}
\def\M@IfChordAux#1/#2\@nil{%
    \def\M@ChordTail{#2}%
    \ifx\M@ChordTail\@empty
        \M@ChordNo
    \else
        \M@ChordYes
    \fi
}

\def\M@ParseChordHead#1{\expandafter\M@ParseChordHeadAux#1\@nil}
\def\M@ParseChordHeadAux#1#2\@nil{%
    \M@ChordLeftfalse
    \def\M@ChordFirst{#1}%
    \def\M@ChordLeftToken{<}%
    \ifx\M@ChordFirst\M@ChordLeftToken
        \def\M@ChordHeight{#2}%
        \M@ChordLefttrue
    \else
        \def\M@ChordHeight{#1#2}%
    \fi
}

\def\M@ChordStop{\relax}
\def\M@ChordLoop#1/{%
    \def\M@ChordPart{#1}%
    \ifx\M@ChordPart\M@ChordStop
        \let\M@ChordNext\relax
    \else
        \M@ChordAction{#1}%
        \let\M@ChordNext\M@ChordLoop
    \fi
    \M@ChordNext
}
\newcommand{\M@ChordForEach}[1]{%
    \expandafter\M@ChordLoop#1/\relax/
}

\newcommand{\M@ChordScanHead}[1]{%
    \M@ParseChordHead{#1}%
    \M@ax{\M@ChordHeight}%
    \M@in{\M@ChordHeight}%
    \ifnum\theM@first=-50 \setcounter{M@first}{\M@ChordHeight}\fi
}

\newcommand{\M@ChordDrawHead}[2]{% #1 duration, #2 head specification
    \M@ParseChordHead{#2}%
    \begingroup
        \ifM@ChordLeft \M@noteBacktrue\fi
        \ifnum#1=1
            \M@Semibreve{\M@ChordHeight}%
        \else\ifnum#1=2
            \M@HollowHead{\M@ChordHeight}%
        \else
            \M@Head{\M@ChordHeight}%
        \fi\fi
    \endgroup
}

\newcommand{\M@ChordLedgerHead}[1]{%
    \M@ParseChordHead{#1}%
    \ifM@ChordLeft
        \begin{scope}[xshift=-0.265cm]\M@Ledger{\M@ChordHeight}\end{scope}%
    \else
        \M@Ledger{\M@ChordHeight}%
    \fi
}

\newcommand{\M@Chord}[2]{% #1 duration, #2 slash-separated chord heads
    \setcounter{M@first}{-50}%
    \setcounter{M@max}{-50}%
    \setcounter{M@min}{50}%
    \let\M@ChordAction\M@ChordScanHead
    \M@ChordForEach{#2}%

    \def\M@ChordAction##1{\M@ChordDrawHead{#1}{##1}}%
    \M@ChordForEach{#2}%

    \ifnum#1=1\relax
    \else
        \ifnum\theM@max<6\else\M@Swap\fi

        \M@SetUnbeamedStem{#1}%

        \ifM@noSwap
            \M@enlarge[\M@Sstem]{\theM@min}{\theM@max}%
            \pgfmathsetmacro\M@ChordStemBase{\theM@max}%
            \pgfmathsetmacro\M@High{int(\theM@max + 10*\M@Sstem)}%
        \else
            \M@enlarge[\M@Sstem]{\theM@max}{\theM@min}%
            \pgfmathsetmacro\M@ChordStemBase{\theM@min}%
            \pgfmathsetmacro\M@High{int(\theM@min - 10*\M@Sstem)}%
        \fi
        \setcounter{M@height}{\M@High}%

        \M@DrawFlags{#1}{\M@ChordStemBase}%
    \fi
}

\newcommand{\M@SimpleColumn}[2]{% #1 duration, #2 one time-position
    \M@IfChord{#2}{%
        \M@Chord{#1}{#2}%
    }{%
        \ifnum#1=1 \M@Semibreve{#2}\else
        \ifnum#1=2 \M@Minim{#2}\else
        \ifnum#1=4 \M@Crotchet{#2}\else
        \ifnum#1=8 \M@Quaver{#2}\else
        \ifnum#1=16 \M@Semiquaver{#2}\else
        \ifnum#1=32 \M@Demisemiquaver{#2}\fi\fi\fi\fi\fi\fi
    }%
}

\newcommand{\M@LedgerColumn}[1]{%
    \M@IfChord{#1}{%
        \let\M@ChordAction\M@ChordLedgerHead
        \M@ChordForEach{#1}%
    }{\M@Ledger{#1}}%
}


\newcounter{M@columnMin}
\newcounter{M@columnMax}
\newcounter{M@beamFound}
\newcounter{M@beamFirstX}
\newcounter{M@beamLastX}
\newcounter{M@beamFirstH}
\newcounter{M@beamLastH}


\newcommand{\M@BeamColumnScanHead}[1]{%
    \M@ParseChordHead{#1}%
    \ifnum\M@ChordHeight<\theM@columnMin
        \setcounter{M@columnMin}{\M@ChordHeight}%
    \fi
    \ifnum\M@ChordHeight>\theM@columnMax
        \setcounter{M@columnMax}{\M@ChordHeight}%
    \fi
}

\newcommand{\M@BeamColumnBounds}[1]{%
    \setcounter{M@columnMin}{50}%
    \setcounter{M@columnMax}{-50}%
    \M@IfChord{#1}{%
        \let\M@ChordAction\M@BeamColumnScanHead
        \M@ChordForEach{#1}%
    }{%
        \setcounter{M@columnMin}{#1}%
        \setcounter{M@columnMax}{#1}%
    }%
}

\newcommand{\M@BeamDrawChordHead}[1]{%
    \M@ParseChordHead{#1}%
    \begingroup
        \ifM@ChordLeft \M@noteBacktrue\fi
        \M@Head{\M@ChordHeight}%
    \endgroup
}
\newcommand{\M@BeamDrawColumnHeads}[1]{%
    \M@IfChord{#1}{%
        \let\M@ChordAction\M@BeamDrawChordHead
        \M@ChordForEach{#1}%
    }{\M@Head{#1}}%
}

\newcommand{\M@BeamColumnAnchor}[1]{%
    \M@BeamColumnBounds{#1}%
    \ifM@noSwap
        \pgfmathsetmacro{\M@columnAnchor}{\theM@columnMax}%
        \pgfmathsetmacro{\M@columnStemStart}{\theM@columnMin}%
    \else
        \pgfmathsetmacro{\M@columnAnchor}{\theM@columnMin}%
        \pgfmathsetmacro{\M@columnStemStart}{\theM@columnMax}%
    \fi
}

\newcommand{\M@BeamHeads}[1]{%
    \setcounter{M@max}{-50}%
    \setcounter{M@min}{50}%
    \setcounter{M@X}{\theM@aux}%
    \foreach\IND in {#1} {%
        \ifthenelse{\equal{\IND}{!}}{\M@addAccMX}{%
            \M@NotEmpty{\IND}{%
                \M@BeamColumnBounds{\IND}%
                \M@ax{\theM@columnMax}%
                \M@in{\theM@columnMin}%
                \M@BeamDrawColumnHeads{\IND}%
            }%
            \M@addMX
        }%
    }%
}

\newcommand{\M@ScanBeamEndpoints}[1]{%
    \setcounter{M@beamFound}{0}%
    \setcounter{M@X}{\theM@aux}%
    \foreach\IND in {#1} {%
        \ifthenelse{\equal{\IND}{!}}{\M@addAccMX}{%
            \M@NotEmpty{\IND}{%
                \M@BeamColumnAnchor{\IND}%
                \ifnum\theM@beamFound=0
                    \setcounter{M@beamFirstX}{\theM@X}%
                    \setcounter{M@beamFirstH}{\M@columnAnchor}%
                    \setcounter{M@beamFound}{1}%
                \fi
                \setcounter{M@beamLastX}{\theM@X}%
                \setcounter{M@beamLastH}{\M@columnAnchor}%
            }%
            \M@addMX
        }%
    }%
}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Appoggiaturas

\newif\ifM@appogSwap
\newif\ifM@appogSlurSwap
\newcounter{M@appogSavedMX}
\newcounter{M@appogSavedAfterBar}
\newcounter{M@appogSavedCanTuckBar}

\pgfkeys{
    /mousik/appog/.is family,
    /mousik/appog,
    default/.style={
        scale=1,
        before=0.5,
        swap=false,
        slur=0,
        to=,
        slur-swap=false,
        slur-width=0.12,
        xshift=0,
        yshift=0,
        slur-xshift=0,
        slur-yshift=0
    },
    scale/.estore in=\M@appogScale,
    before/.estore in=\M@appogBefore,
    space/.estore in=\M@appogBefore,
    swap/.is if=M@appogSwap,
    slur/.estore in=\M@appogSlurAngle,
    to/.estore in=\M@appogSlurTo,
    slur-swap/.is if=M@appogSlurSwap,
    slur-width/.estore in=\M@appogSlurWidth,
    xshift/.estore in=\M@appogXshift,
    yshift/.estore in=\M@appogYshift,
    slur-xshift/.estore in=\M@appogSlurXshift,
    slur-yshift/.estore in=\M@appogSlurYshift
}

\newif\ifM@appogStemUp

\newcommand{\M@SetAppogStemDirection}[1]{% #1 appoggiatura height
    \ifnum#1<6
        \ifM@appogSwap \M@appogStemUpfalse \else \M@appogStemUptrue \fi
    \else
        \ifM@appogSwap \M@appogStemUptrue \else \M@appogStemUpfalse \fi
    \fi
}

\newcommand{\M@NativeAppogSymbol}[1]{% #1 duration
    \ifM@appogStemUp
        \ifnum#1=4
            {\smallnotesize\zqu{0}}%
        \else\ifnum#1=8
            {\advancefalse\grcu{0}}%
        \else\ifnum#1=16
            {\smallnotesize\zccu{0}}%
        \else\ifnum#1=32
            {\smallnotesize\zcccu{0}}%
        \else
            \PackageWarning{mousik}{Unsupported appoggiatura duration #1; using 8}%
            {\advancefalse\grcu{0}}%
        \fi\fi\fi\fi
    \else
        \ifnum#1=4
            {\smallnotesize\zql{0}}%
        \else\ifnum#1=8
            {\advancefalse\grcl{0}}%
        \else\ifnum#1=16
            {\smallnotesize\zccl{0}}%
        \else\ifnum#1=32
            {\smallnotesize\zcccl{0}}%
        \else
            \PackageWarning{mousik}{Unsupported appoggiatura duration #1; using 8}%
            {\advancefalse\grcl{0}}%
        \fi\fi\fi\fi
    \fi
}

\newcommand{\M@DrawAppogNote}[2]{% #1 duration, #2 height
    \begingroup
        \M@SetAppogStemDirection{#2}%
        \pgfmathsetmacro{\M@appogBaseX}{\theM@X*0.0625}%
        \pgfmathsetmacro{\M@appogHeadX}{\M@appogBaseX-(\M@appogBefore)+(\M@appogXshift)}%
        \pgfmathsetmacro{\M@appogHeadY}{-\theM@Y*\M@vsep-0.195+(#2)*0.1+(\M@appogYshift)}%
        \pgfmathsetmacro{\M@appogNativeHeadX}{\M@appogHeadX-0.072*(\M@appogScale)}%
        \node[inner sep=0pt,outer sep=0pt,anchor=base,transform shape,
              scale=\M@appogScale]
            at (\M@appogNativeHeadX,\M@appogHeadY) {\M@NativeAppogSymbol{#1}};%
    \endgroup
}

\newcommand{\M@DrawAppogSlur}[7]{% x1,y1,x2,y2,angle,width,side
    \edef\M@appogThisSide{#7}%
    \def\M@appogDown{down}%
    \pgfmathsetmacro{\M@appogGap}{0.04}% cm
    \pgfmathsetmacro{\M@appogSX}{(#1)+(0.072+\M@appogGap)*(\M@appogScale)}%
    \pgfmathsetmacro{\M@appogEX}{(#3)-(0.115+\M@appogGap)}%
    \pgfmathsetmacro{\M@appogSpan}{max(0.001,abs(\M@appogEX-\M@appogSX))}%
    \pgfmathsetmacro{\M@appogBulge}{0.025+0.55*\M@appogSpan*tan((#5)/2)}%
    \pgfmathsetmacro{\M@appogCOneX}{\M@appogSX+0.33*(\M@appogEX-\M@appogSX)}%
    \pgfmathsetmacro{\M@appogCTwoX}{\M@appogSX+0.67*(\M@appogEX-\M@appogSX)}%
    \ifx\M@appogThisSide\M@appogDown
        \pgfmathsetmacro{\M@appogSY}{(#2)-(0.045+\M@appogGap)*(\M@appogScale)}%
        \pgfmathsetmacro{\M@appogEY}{(#4)-(0.080+\M@appogGap)}%
        \pgfmathsetmacro{\M@appogControlY}{min(\M@appogSY,\M@appogEY)-\M@appogBulge}%
    \else
        \pgfmathsetmacro{\M@appogSY}{(#2)+(0.045+\M@appogGap)*(\M@appogScale)}%
        \pgfmathsetmacro{\M@appogEY}{(#4)+(0.080+\M@appogGap)}%
        \pgfmathsetmacro{\M@appogControlY}{max(\M@appogSY,\M@appogEY)+\M@appogBulge}%
    \fi
    \draw[line width=#6 mm]
        (\M@appogSX,\M@appogSY)
        .. controls (\M@appogCOneX,\M@appogControlY) and (\M@appogCTwoX,\M@appogControlY) ..
        (\M@appogEX,\M@appogEY);%
}

\newcommand{\M@SetAppogSlurSide}[1]{% #1 appoggiatura height
    \M@SetAppogStemDirection{#1}%
    \ifM@appogStemUp
        \def\M@appogSlurSide{down}%
    \else
        \def\M@appogSlurSide{up}%
    \fi
    \ifM@appogSlurSwap
        \def\M@appogUp{up}%
        \ifx\M@appogSlurSide\M@appogUp
            \def\M@appogSlurSide{down}%
        \else
            \def\M@appogSlurSide{up}%
        \fi
    \fi
}

\newcommand{\M@MaybeDrawAppogSlur}[2]{% #1 appoggiatura height, #2 target logical MX
    \pgfmathtruncatemacro{\M@appogSlurOn}{abs(\M@appogSlurAngle)>0.0001 ? 1 : 0}%
    \ifnum\M@appogSlurOn=1
        \ifthenelse{\equal{\M@appogSlurTo}{}}{%
            \PackageWarning{mousik}{Appoggiatura slur requested without target height; use slur=<angle>,to=<height>; slur omitted}%
        }{%
            \M@SetAppogSlurSide{#1}%
            \pgfmathsetmacro{\M@appogTargetBaseX}{(#2)*0.0625}%
            \pgfmathsetmacro{\M@appogTargetBaseY}{-\theM@Y*\M@vsep-0.195+(\M@appogSlurTo)*0.1}%
            \pgfmathsetmacro{\M@appogStartX}{\M@appogTargetBaseX-(\M@appogBefore)+(\M@appogXshift)}%
            \pgfmathsetmacro{\M@appogStartY}{-\theM@Y*\M@vsep-0.195+(#1)*0.1+(\M@appogYshift)}%
            \pgfmathsetmacro{\M@appogTargetX}{\M@appogTargetBaseX-0.01+(\M@appogSlurXshift)}%
            \pgfmathsetmacro{\M@appogTargetY}{\M@appogTargetBaseY+(\M@appogSlurYshift)}%
            \M@DrawAppogSlur
                {\M@appogStartX}{\M@appogStartY}
                {\M@appogTargetX}{\M@appogTargetY}
                {\M@appogSlurAngle}{\M@appogSlurWidth}{\M@appogSlurSide}%
        }%
    \fi
}

\newcommand{\mousikAppog}[3][]{%
    \pgfkeys{/mousik/appog, default, #1}%
    \edef\M@appogTargetMX{\theM@X}%
    \M@DrawAppogNote{#2}{#3}%
    \M@MaybeDrawAppogSlur{#3}{\M@appogTargetMX}%
}

\newcommand{\mousikAppogs}[2][]{%
    \pgfkeys{/mousik/appog, default, #1}%
    \setcounter{M@appogSavedMX}{\theM@X}%
    \setcounter{M@appogSavedAfterBar}{\theM@afterBar}%
    \setcounter{M@appogSavedCanTuckBar}{\theM@canTuckBar}%
    \foreach\M@appogDur/\M@appogHeight in {#2} {%
        \ifthenelse{\equal{\M@appogDur}{!}}{\M@addAccMX}{%
            \M@NotEmpty{\M@appogDur}{%
                \edef\M@appogTargetMX{\theM@X}%
                \M@DrawAppogNote{\M@appogDur}{\M@appogHeight}%
                \M@MaybeDrawAppogSlur{\M@appogHeight}{\M@appogTargetMX}%
            }%
            \M@addMX
        }%
    }%
    \setcounter{M@X}{\theM@appogSavedMX}%
    \setcounter{M@afterBar}{\theM@appogSavedAfterBar}%
    \setcounter{M@canTuckBar}{\theM@appogSavedCanTuckBar}%
    \pgfmathsetmacro{\M@realX}{\theM@X*0.0625}%
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Notes : everything together

\newif\ifM@noteBack
\newif\ifM@sloped
\pgfkeys{
	/mousik/note/.is family
	, /mousik/note
	, default/.style = 
	{	beam = 1
		, sloped = false
		, stem = 5
		, head = .
		, swap = false
		, tuplet = 0
		, tuplet-bracket = false
		, tuplet-xshift = 0
		, tuplet-yshift = 0
		, xshift = 0
		, yshift = 0
	}
	, beam/.estore in=\M@beam
	, sloped/.is if=M@sloped
	, stem/.code={\pgfmathsetmacro{\M@stem}{(#1)/10}}
	, head/.estore in=\M@head
	, tuplet/.estore in=\M@tuplet
	, tuplet-bracket/.is if=M@tupletBracket
	, tuplet-xshift/.estore in=\M@tupletXshift
	, tuplet-yshift/.estore in=\M@tupletYshift
	, swap/.is if=M@swap
	, xshift/.estore in=\M@shiftX
	, yshift/.estore in=\M@shiftY
}
\newcounter{M@duration}
\newcommand{\mousikNote}[3][]{ % #1 = options, #2 = duration, #3 = note(s)
	\M@noteBackfalse % internal: displaced chord heads set this only in a local group
	\pgfkeys{/mousik/note, default, #1}%
    \M@CheckChoice{\M@head}{.,o,x}%
    \ifM@choiceValid\else
        \PackageWarning{mousik}{Unknown note head `\M@head'. Expected ., o, or x; using .}%
        \def\M@head{.}%
    \fi
	\M@Adv \M@noSwaptrue
	\ifM@swap \M@Swap \fi
	\setcounter{M@aux}{\theM@X}	
\begin{scope}[xshift=\M@shiftX cm,yshift=\M@shiftY cm]
	\M@Count{#2}\setcounter{M@duration}{\theM@count}
	\M@Count{#3}
\ifnum\theM@duration=1 % only one duration
    \M@CheckChoice{#2}{1,2,4,8,16,32}%
    \ifM@choiceValid\else
        \PackageWarning{mousik}{Unsupported note duration `#2'. Expected 1, 2, 4, 8, 16, or 32; no note heads drawn}%
    \fi
    \ifM@choiceValid
	\ifnum#2=1 \foreach\IND in {#3} {\M@SimpleColumn{1}{\IND}\M@addMX} \else
	\ifnum#2=2 \foreach\IND in {#3} {\M@SimpleColumn{2}{\IND}\M@addMX} \else
	\ifnum#2=4 \foreach\IND in {#3} {\M@SimpleColumn{4}{\IND}\M@addMX} \else
	\ifnum\theM@count=1 % single note or chord (8 and above)
		\M@SimpleColumn{#2}{#3}
	\else \ifnum\theM@count=2 % two notes together
			\M@TwoNote{#2}{#3}
		\else \ifnum\theM@count>2 % more than two notes together
			\ifM@sloped
				\M@SlopedNote{#2}{#3}
			\else
				\M@FlatNote{#2}{#3}
			\fi
		\fi\fi\fi
	\fi\fi\fi
    \fi
	
\else \M@MixedNote{#2}{#3} \fi % more than one duration

	\setcounter{M@X}{\theM@aux}\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
	\foreach \IND in {#3} {
		\ifthenelse{\equal{\IND}{!}}{\M@addAccMX}{
		\M@NotEmpty{\IND}{\M@LedgerColumn{\IND}}
		\M@addMX}
	}
	\M@addMX
	
	\ifthenelse{\equal{\M@tuplet}{0}}{}{\M@Tuplet[\M@tuplet]}
	\end{scope}
	\setcounter{M@canTuckBar}{1}% a barline may use the trailing half-gap left by this event
}

\newcommand{\M@NormalizeDurationToken}[1]{%
	\def\M@DurationToken{#1}%
	\M@EqStr{#1}{//}{\def\M@DurationToken{=}}%
	\M@EqStr{#1}{//|}{\def\M@DurationToken{=|}}%
	\M@EqStr{#1}{|//}{\def\M@DurationToken{|=}}%
	\M@EqStr{#1}{///}{\def\M@DurationToken{≡}}%
	\M@EqStr{#1}{///|}{\def\M@DurationToken{≡|}}%
	\M@EqStr{#1}{|///}{\def\M@DurationToken{|≡}}%
}

\newcommand{\M@MixedTokenInfo}[1]{%
	\M@NormalizeDurationToken{#1}%
	\def\M@mixDur{0}%
	\def\M@mixStartTwo{0}%
	\def\M@mixEndTwo{0}%
	\def\M@mixStartThree{0}%
	\def\M@mixEndThree{0}%
	\M@EqStr{\M@DurationToken}{-}{\def\M@mixDur{8}}%
	\M@EqStr{\M@DurationToken}{|-}{\def\M@mixDur{8}}%
	\M@EqStr{\M@DurationToken}{-|}{\def\M@mixDur{8}}%
	\M@EqStr{\M@DurationToken}{=}{\def\M@mixDur{16}}%
	\M@EqStr{\M@DurationToken}{|=}{\def\M@mixDur{16}\def\M@mixStartTwo{1}}%
	\M@EqStr{\M@DurationToken}{=|}{\def\M@mixDur{16}\def\M@mixEndTwo{1}}%
	\M@EqStr{\M@DurationToken}{≡}{\def\M@mixDur{32}}%
	\M@EqStr{\M@DurationToken}{|≡}{\def\M@mixDur{32}\def\M@mixStartThree{1}}%
	\M@EqStr{\M@DurationToken}{≡|}{\def\M@mixDur{32}\def\M@mixEndThree{1}}%
}

\newcommand{\M@SetMixedStemOffsets}{%
	\ifM@noSwap
		\pgfmathsetmacro{\M@MixedLeftStemOffset}{0.103}%
		\pgfmathsetmacro{\M@MixedRightStemOffset}{0.128}%
	\else
		\pgfmathsetmacro{\M@MixedLeftStemOffset}{-0.153}%
		\pgfmathsetmacro{\M@MixedRightStemOffset}{-0.125}%
	\fi
}

\newcommand{\M@DrawMixedConnection}[4]{% left cursor, right cursor, beam height, offset
	\pgfmathsetmacro{\M@BeamLeftX}{(#1)*0.0625}%
	\pgfmathsetmacro{\M@BeamRightX}{(#2)*0.0625}%
	\pgfmathsetmacro{\M@BeamY}{-\theM@Y*\M@vsep-0.2+(#3)*0.1}%
	\pgfmathsetmacro{\M@BeamOffset}{#4}%
	\M@SetMixedStemOffsets
	\ifM@noSwap
		\draw[line width=\M@beam mm]
			(\M@BeamLeftX+\M@MixedLeftStemOffset,\M@BeamY+\M@BeamOffset) --
			(\M@BeamRightX+\M@MixedRightStemOffset,\M@BeamY+\M@BeamOffset);%
	\else
		\draw[line width=\M@beam mm]
			(\M@BeamLeftX+\M@MixedLeftStemOffset,\M@BeamY-\M@BeamOffset) --
			(\M@BeamRightX+\M@MixedRightStemOffset,\M@BeamY-\M@BeamOffset);%
	\fi
}

\newcommand{\M@DrawMixedHook}[4]{% left/right, cursor, beam height, offset
	\pgfmathsetmacro{\M@BeamX}{(#2)*0.0625}%
	\pgfmathsetmacro{\M@BeamStep}{\M@hsep*0.0625}%
	\pgfmathsetmacro{\M@BeamY}{-\theM@Y*\M@vsep-0.2+(#3)*0.1}%
	\pgfmathsetmacro{\M@BeamOffset}{#4}%
	\M@SetMixedStemOffsets
	\pgfmathsetmacro{\M@HookRightEnd}{0.5*(\M@MixedLeftStemOffset+\M@BeamStep+\M@MixedRightStemOffset)}%
	\pgfmathsetmacro{\M@HookLeftBegin}{0.5*(-\M@BeamStep+\M@MixedLeftStemOffset+\M@MixedRightStemOffset)}%
	\def\M@HookSide{#1}%
	\def\M@HookRight{right}%
	\ifM@noSwap
		\ifx\M@HookSide\M@HookRight
			\draw[line width=\M@beam mm]
				(\M@BeamX+\M@MixedLeftStemOffset,\M@BeamY+\M@BeamOffset) --
				(\M@BeamX+\M@HookRightEnd,\M@BeamY+\M@BeamOffset);%
		\else
			\draw[line width=\M@beam mm]
				(\M@BeamX+\M@HookLeftBegin,\M@BeamY+\M@BeamOffset) --
				(\M@BeamX+\M@MixedRightStemOffset,\M@BeamY+\M@BeamOffset);%
		\fi
	\else
		\ifx\M@HookSide\M@HookRight
			\draw[line width=\M@beam mm]
				(\M@BeamX+\M@MixedLeftStemOffset,\M@BeamY-\M@BeamOffset) --
				(\M@BeamX+\M@HookRightEnd,\M@BeamY-\M@BeamOffset);%
		\else
			\draw[line width=\M@beam mm]
				(\M@BeamX+\M@HookLeftBegin,\M@BeamY-\M@BeamOffset) --
				(\M@BeamX+\M@MixedRightStemOffset,\M@BeamY-\M@BeamOffset);%
		\fi
	\fi
}

\newcommand{\M@FinalizeMixedEvent}[2]{% right connection at levels 2 and 3
	\ifnum\M@mixPrevDur>15
		\ifnum\M@mixPrevLeftTwo=0 \ifnum#1=0
			\ifnum\M@mixPrevStartTwo=1
				\M@DrawMixedHook{right}{\M@mixPrevX}{\M@heightBeam}{\M@mixSecondOffset}%
			\else\ifnum\M@mixPrevEndTwo=1
				\M@DrawMixedHook{left}{\M@mixPrevX}{\M@heightBeam}{\M@mixSecondOffset}%
			\else\ifnum\M@mixPrevDur=32
				\ifnum\M@mixPrevStartThree=1
					\M@DrawMixedHook{right}{\M@mixPrevX}{\M@heightBeam}{\M@mixSecondOffset}%
				\else\ifnum\M@mixPrevEndThree=1
					\M@DrawMixedHook{left}{\M@mixPrevX}{\M@heightBeam}{\M@mixSecondOffset}%
				\fi\fi
			\fi\fi\fi
		\fi\fi
	\fi
	\ifnum\M@mixPrevDur=32
		\ifnum\M@mixPrevLeftThree=0 \ifnum#2=0
			\ifnum\M@mixPrevStartThree=1
				\M@DrawMixedHook{right}{\M@mixPrevX}{\M@heightBeam}{\M@stem}%
			\else\ifnum\M@mixPrevEndThree=1
				\M@DrawMixedHook{left}{\M@mixPrevX}{\M@heightBeam}{\M@stem}%
			\fi\fi
		\fi\fi
	\fi
}

\newcommand{\M@DrawMixedBeamLevels}[1]{%
	\ifnum\theM@duration=16
		\pgfmathsetmacro{\M@mixSecondOffset}{\M@stem+0.05}%
	\else
		\pgfmathsetmacro{\M@mixSecondOffset}{\M@stem+0.15}%
	\fi
	\def\M@mixHavePrev{0}%
	\setcounter{M@X}{\theM@aux}%
	\foreach\INDd in {#1} {%
		\M@MixedTokenInfo{\INDd}%
		\ifnum\M@mixDur>0
			\def\M@mixConnTwo{0}%
			\def\M@mixConnThree{0}%
			\ifnum\M@mixHavePrev=1
				\ifnum\M@mixPrevDur>15 \ifnum\M@mixDur>15
					\ifnum\M@mixPrevEndTwo=0 \ifnum\M@mixStartTwo=0
						\M@DrawMixedConnection{\M@mixPrevX}{\theM@X}{\M@heightBeam}{\M@mixSecondOffset}%
						\def\M@mixConnTwo{1}%
					\fi\fi
				\fi\fi
				\ifnum\M@mixPrevDur=32 \ifnum\M@mixDur=32
					\ifnum\M@mixPrevEndThree=0 \ifnum\M@mixStartThree=0
						\M@DrawMixedConnection{\M@mixPrevX}{\theM@X}{\M@heightBeam}{\M@stem}%
						\def\M@mixConnThree{1}%
					\fi\fi
				\fi\fi
				\M@FinalizeMixedEvent{\M@mixConnTwo}{\M@mixConnThree}%
			\fi
			\xdef\M@mixPrevDur{\M@mixDur}%
			\xdef\M@mixPrevX{\theM@X}%
			\xdef\M@mixPrevStartTwo{\M@mixStartTwo}%
			\xdef\M@mixPrevEndTwo{\M@mixEndTwo}%
			\xdef\M@mixPrevStartThree{\M@mixStartThree}%
			\xdef\M@mixPrevEndThree{\M@mixEndThree}%
			\xdef\M@mixPrevLeftTwo{\M@mixConnTwo}%
			\xdef\M@mixPrevLeftThree{\M@mixConnThree}%
			\xdef\M@mixHavePrev{1}%
		\fi
		\ifthenelse{\equal{\INDd}{!}}{\M@addAccMX}{\M@addMX}%
	}%
	\ifnum\M@mixHavePrev=1
		\M@FinalizeMixedEvent{0}{0}%
	\fi
}

\newcommand{\M@MixedNote}[2]{
	\setcounter{M@duration}{8}
	\foreach\INDd in {#1} {
		\M@NormalizeDurationToken{\INDd}%
		\ifnum\theM@duration<16
			\M@EqStr{\M@DurationToken}{=}{\setcounter{M@duration}{16}}
			\M@EqStr{\M@DurationToken}{=|}{\setcounter{M@duration}{16}}
			\M@EqStr{\M@DurationToken}{|=}{\setcounter{M@duration}{16}}
		\fi
		\ifnum\theM@duration<32
			\M@EqStr{\M@DurationToken}{≡}{\setcounter{M@duration}{32}}
			\M@EqStr{\M@DurationToken}{≡|}{\setcounter{M@duration}{32}}
			\M@EqStr{\M@DurationToken}{|≡}{\setcounter{M@duration}{32}}
		\fi
	}
	
	\M@BeamHeads{#2}
	\ifnum\theM@max<6
		\ifM@noSwap \pgfmathsetmacro{\M@heightBeam}{\theM@max}
		\else \pgfmathsetmacro{\M@heightBeam}{\theM@min} \fi
	\else 
		\M@Swap
		\ifM@noSwap \pgfmathsetmacro{\M@heightBeam}{\theM@min}
		\else \pgfmathsetmacro{\M@heightBeam}{\theM@max} \fi
	\fi
	
	\setcounter{M@X}{\theM@aux}
	\M@SetBeamStem{\theM@duration}%
	\foreach\IND in {#2} {
		\ifthenelse{\equal{\IND}{!}}{\M@addAccMX}{
		\M@NotEmpty{\IND}{%
			\M@BeamColumnAnchor{\IND}%
			\M@enlarge[\M@Sstem]{\M@columnStemStart}{\M@heightBeam}%
		}
		\M@addMX}
	}

\ifM@noSwap
    \pgfmathsetmacro\M@High{int(\M@heightBeam + 10*\M@Sstem)}%
\else
    \pgfmathsetmacro\M@High{int(\M@heightBeam - 10*\M@Sstem)}%
\fi
\setcounter{M@height}{\M@High}
	\M@SetBeamStem{\theM@duration}%
	\M@Beam{\theM@aux}{\M@heightBeam}{\M@heightBeam}{+\M@Sstem}
	\ifnum\theM@duration>8
		\M@DrawMixedBeamLevels{#1}%
	\fi
}
\newcommand{\M@TwoNote}[2]{
    \M@BeamHeads{#2}%

    \ifnum\theM@max<6
    \else
        \M@Swap
    \fi

    \M@ScanBeamEndpoints{#2}%
    \setcounter{M@X}{\theM@aux}\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
    \M@SetBeamStem{#1}%
    \foreach\IND in {#2} {\ifthenelse{\equal{\IND}{!}}{\M@addAccMX}{%
        \M@NotEmpty{\IND}{%
            \M@BeamColumnAnchor{\IND}%
            \M@enlarge[\M@Sstem]{\M@columnStemStart}{\M@columnAnchor}%
        }%
        \M@addMX}
    }

    \ifM@noSwap
        \pgfmathparse{int(max(\theM@beamFirstH,\theM@beamLastH)+10*\M@Sstem)}%
    \else
        \pgfmathparse{int(min(\theM@beamFirstH,\theM@beamLastH)-10*\M@Sstem)}%
    \fi
    \setcounter{M@height}{\pgfmathresult}%

    \M@DrawBeamLevels[\theM@beamLastX+\M@hsep]{#1}{\theM@beamFirstX}{\theM@beamFirstH}{\theM@beamLastH}%
}

\newcommand{\M@SlopedNote}[2]{%
    \M@BeamHeads{#2}%

    \ifnum\theM@max<6
    \else
        \M@Swap
    \fi

    \M@ScanBeamEndpoints{#2}%
    \setcounter{M@X}{\theM@aux}\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}%

    \M@SetBeamStem{#1}%

    \foreach\IND in {#2} {%
        \ifthenelse{\equal{\IND}{!}}{\M@addAccMX}{%
            \M@NotEmpty{\IND}{%
                \M@BeamColumnAnchor{\IND}%
                \pgfmathsetmacro{\M@SlopeH}{%
                    \theM@beamFirstH +
                        (\theM@X-\theM@beamFirstX)/(\theM@beamLastX-\theM@beamFirstX)*
                        (\theM@beamLastH-\theM@beamFirstH)}%
                \M@enlarge[\M@Sstem]{\M@columnStemStart}{\M@SlopeH}%
            }%
            \M@addMX
        }%
    }%

    \ifM@noSwap
        \pgfmathparse{int(max(\theM@beamFirstH,\theM@beamLastH)+10*\M@Sstem)}%
    \else
        \pgfmathparse{int(min(\theM@beamFirstH,\theM@beamLastH)-10*\M@Sstem)}%
    \fi
    \setcounter{M@height}{\pgfmathresult}%

    \M@DrawBeamLevels[\theM@beamLastX+\M@hsep]{#1}{\theM@beamFirstX}{\theM@beamFirstH}{\theM@beamLastH}%
}

\newcommand{\M@FlatNote}[2]{
    \M@BeamHeads{#2}%

    \ifnum\theM@max<6
    \else
        \M@Swap
    \fi
    \ifM@noSwap
        \pgfmathsetmacro{\M@heightBeam}{\theM@max}%
    \else
        \pgfmathsetmacro{\M@heightBeam}{\theM@min}%
    \fi

    \setcounter{M@X}{\theM@aux}\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
    \M@SetBeamStem{#1}%
    \foreach\IND in {#2} {\ifthenelse{\equal{\IND}{!}}{\M@addAccMX}{%
        \M@NotEmpty{\IND}{%
            \M@BeamColumnAnchor{\IND}%
            \M@enlarge[\M@Sstem]{\M@columnStemStart}{\M@heightBeam}%
        }%
        \M@addMX}
    }

    \ifM@noSwap \pgfmathparse{1} \else \pgfmathparse{-1} \fi
    \pgfmathsetmacro\M@High{int(\M@heightBeam + \pgfmathresult * 10*\M@Sstem)}
    \setcounter{M@height}{\M@High}

    \M@DrawBeamLevels{#1}{\theM@aux}{\M@heightBeam}{\M@heightBeam}%
}

\newif\ifM@restMulti
\pgfkeys{
	/mousik/rest/.is family
	, /mousik/rest
	, default/.style = 
	{	multi = false
		, xshift = 0
		, yshift = 0
	}
	, multi/.is if=M@restMulti
	, xshift/.estore in=\M@shiftX
	, yshift/.estore in=\M@shiftY
}
\newcommand{\mousikRest}[2][]{
	\pgfkeys{/mousik/rest, default, #1}%
	\M@Adv
	\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
\begin{scope}[xshift=\M@shiftX cm,yshift=\M@shiftY cm]
\ifM@restMulti
	\node at (\M@realX+0.3,-\theM@Y*\M@vsep+1.1) {\bfseries \M@Resize{#2}};
	
	\draw[line width=1.5mm] (\M@realX-0.25,-\theM@Y*\M@vsep+0.4) -- (\M@realX+1.25,-\theM@Y*\M@vsep+0.4);
	\draw[line width=0.5mm] (\M@realX-0.25,-\theM@Y*\M@vsep+0.2) -- (\M@realX-0.25,-\theM@Y*\M@vsep+0.6);
	\draw[line width=0.5mm] (\M@realX+1.25,-\theM@Y*\M@vsep+0.2) -- (\M@realX+1.25,-\theM@Y*\M@vsep+0.6);
	\M@addMX\M@addMX
	
\else
    \M@CheckChoice{#2}{1,2,4,8,16,32}%
    \ifM@choiceValid\else
        \PackageWarning{mousik}{Unsupported rest duration `#2'. Expected 1, 2, 4, 8, 16, or 32; no rest drawn}%
    \fi
    \ifM@choiceValid
	\ifnum#2=1
		\node at (\M@realX,-\theM@Y*\M@vsep+0.52) 
		{\resizebox{0.3cm}{0.15cm}{\GaPa}};
	\fi\ifnum#2=2
		\node at (\M@realX,-\theM@Y*\M@vsep+0.42) 
		{\resizebox{0.3cm}{0.15cm}{\HaPa}};
	\fi\ifnum#2=4
		\node at (\M@realX,-\theM@Y*\M@vsep+0.4) 
		{\resizebox{0.3cm}{0.7cm}{\ViPa}};
	\fi\ifnum#2=8
		\node at (\M@realX,-\theM@Y*\M@vsep+0.32) 
		{\resizebox{0.3cm}{0.45cm}{\AcPa}};
	\fi\ifnum#2=16
		\node at (\M@realX,-\theM@Y*\M@vsep+0.3) 
		{\resizebox{0.35cm}{0.525cm}{\SePa}};
	\fi\ifnum#2=32
		\node at (\M@realX,-\theM@Y*\M@vsep+0.375) 
		{\resizebox{0.4cm}{0.6cm}{\ZwPa}};
	\fi
    \fi

\fi
	
	\end{scope}
\M@addMX\M@addMX
\setcounter{M@canTuckBar}{1}% a barline may use the trailing half-gap left by this event
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newcommand{\M@PlaceNR}[3][+0.15]{
	\node at (0.1+\M@realX#1,-\theM@Y*\M@vsep-0.2+0.1*#2) {#3};
}
\newcommand{\M@PlaceNL}[3][-0.25]{
	\node at (\M@realX#1,-\theM@Y*\M@vsep-0.2+0.1*#2) {#3};
}
\newcommand{\M@PlaceNU}[3][+0]{
	\node at (\M@realX#1,-\theM@Y*\M@vsep+0.05+0.1*#2) {#3};
}
\newcommand{\M@PlaceND}[3][+0]{
	\node at (\M@realX#1,-\theM@Y*\M@vsep-0.5+0.1*#2) {#3};
}

\newif\ifM@articsSwap
\newif\ifM@articSwap
\newif\ifM@articBelow
\pgfkeys{
	/mousik/artics/.is family
	, /mousik/artics
	, default/.style = 
	{	xshift = 0
		, yshift = 0
		, swap = false
	}
	, xshift/.estore in=\M@shiftX
	, yshift/.estore in=\M@shiftY
	, swap/.is if=M@articsSwap
}	

\newcommand{\M@ParallelArtic}[2]{%
	\ifM@articsSwap \mousikArtic[swap]{#1}{#2}%
	\else \mousikArtic{#1}{#2}%
	\fi}
\newcommand{\mousikArtics}[2][]{
	\pgfkeys{/mousik/artics, default, #1}%
	\M@Adv
	\begin{scope}[xshift=\M@shiftX cm,yshift=\M@shiftY cm]
	\M@ParallelList{#2}{\M@ParallelArtic}%
	\end{scope}
}

\pgfkeys{
	/mousik/artic/.is family
	, /mousik/artic
	, default/.style = 
	{	xshift = 0
		, yshift = 0
		, swap = false
	}
	, xshift/.estore in=\M@shiftX
	, yshift/.estore in=\M@shiftY
	, swap/.is if=M@articSwap
}	

\newcommand{\mousikArtic}[3][]{
	\pgfkeys{/mousik/artic, default, #1}%
    \M@CheckChoice{#2}{.,',>,-,^,(.),+,~,~|,?,o,v,n}%
    \ifM@choiceValid\else
        \PackageWarning{mousik}{Unknown articulation `#2'; no articulation drawn}%
    \fi
	\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
	\ifnum#3<6 \M@articBelowtrue \else \M@articBelowfalse \fi
	\ifM@articSwap
		\ifM@articBelow \M@articBelowfalse \else \M@articBelowtrue \fi
	\fi
	\begin{scope}[xshift=\M@shiftX cm,yshift=\M@shiftY cm]
    \ifM@choiceValid
	\ifM@articBelow
	\M@EqStr{#2}{.}{\M@PlaceND[-0.125]{#3+0.15}{\lpz{0}}}
	\M@EqStr{#2}{'}{\M@PlaceND[-0.125]{#3+0.1}{\lppz{0}}}
	\M@EqStr{#2}{>}{\M@PlaceND[-0.1]{#3+0.1}{\lsf{0}}}
	\M@EqStr{#2}{-}{\M@PlaceND[-0.125]{#3+0.15}{\lst{0}}}
	\M@EqStr{#2}{^}{\M@PlaceND[-0.125]{#3+0.05}{\lsfz{0}}}
	\M@EqStr{#2}{(.)}{\M@PlaceND[-0.105]{#3}{\fermatadown{0}}}
	\M@EqStr{#2}{+}{\M@PlaceND[-0.025]{#3-0.05}{\bfseries +}}
	\M@EqStr{#2}{~}{\M@PlaceND[-0.125]{#3-0.05}{\shake{0}}}
	\M@EqStr{#2}{~|}{\M@PlaceND[-0.125]{#3-0.05}{\mordent{0}}}
	\M@EqStr{#2}{?}{\M@PlaceND[-0.125]{#3-0.05}{\turn{0}}}
	%%%%%%%%%%%%
	\M@EqStr{#2}{o}{\M@PlaceND[-0.1]{#3-0.05}{\flageolett{0}}}
	\M@EqStr{#2}{v}{\M@PlaceND[-0.1]{#3-0.05}{\upbow}}
	\M@EqStr{#2}{n}{\M@PlaceND[-0.1]{#3-0.05}{\downbow}}
	\else
	\M@EqStr{#2}{.}{\M@PlaceNU[-0.1]{#3-0.15}{\upz{0}}}
	\M@EqStr{#2}{'}{\M@PlaceNU[-0.1]{#3-0.1}{\uppz{0}}}
	\M@EqStr{#2}{>}{\M@PlaceNU[-0.1]{#3-0.1}{\usf{0}}}
	\M@EqStr{#2}{-}{\M@PlaceNU[-0.1]{#3-0.15}{\ust{0}}}
	\M@EqStr{#2}{^}{\M@PlaceNU[-0.1]{#3-0.05}{\usfz{0}}}
	\M@EqStr{#2}{(.)}{\M@PlaceNU[-0.1]{#3}{\fermataup{0}}}
	\M@EqStr{#2}{+}{\M@PlaceNU{#3+0.05}{\bfseries +}}
	\M@EqStr{#2}{~}{\M@PlaceNU[-0.1]{#3+0.05}{\shake{0}}}
	\M@EqStr{#2}{~|}{\M@PlaceNU[-0.1]{#3+0.05}{\mordent{0}}}
	\M@EqStr{#2}{?}{\M@PlaceNU[-0.1]{#3+0.05}{\turn{0}}}
	%%%%%%%%%%%%%
	\M@EqStr{#2}{o}{\M@PlaceNU[-0.1]{#3-0.1}{\flageolett{0}}}
	\M@EqStr{#2}{v}{\M@PlaceNU[-0.1]{#3+0.05}{\upbow}}
	\M@EqStr{#2}{n}{\M@PlaceNU[-0.1]{#3-0.05}{\downbow}}
	\fi
    \fi
	\end{scope}
}

\pgfkeys{
	/mousik/symbol/.is family
	, /mousik/symbol
	, default/.style = 
	{	xshift = 0
		, yshift = 0
	}
	, xshift/.estore in=\M@shiftX
	, yshift/.estore in=\M@shiftY
}

\newcommand{\mousikSymbol}[2][]{
	\pgfkeys{/mousik/symbol, default, #1}%
    \M@CheckChoice{#2}{/,\%,s\%,o+,Ped,*}%
    \ifthenelse{\equal{#2}{,}}{\M@choiceValidtrue}{}%
    \ifM@choiceValid\else
        \PackageWarning{mousik}{Unknown symbol `#2'; no symbol drawn}%
    \fi
	\begin{scope}[xshift=\M@shiftX cm,yshift=\M@shiftY cm]
    \ifM@choiceValid
	\M@EqStr{#2}{,}{\M@PlaceNU[-0.1]{7}{\cbreath}}
	\M@EqStr{#2}{/}{\M@PlaceNU[-0.1]{4}{\caesura}}
	\M@EqStr{#2}{\%}{\M@PlaceNU[-0.1]{3+0.04}{\duevolte}}
	\M@EqStr{#2}{s\%}{\M@PlaceNU[-0.1]{11}{\segno{0}}}
	\M@EqStr{#2}{o+}{\M@PlaceNU[+0.3]{11}{\coda{0}}}
	\M@EqStr{#2}{Ped}{\M@PlaceNU[-0.1]{-5}{\PED}}
	\M@EqStr{#2}{*}{\M@PlaceNU[-0.1]{-5}{\sDEP}}
    \fi
	\end{scope}
}

\newcommand{\M@dflat}{\tikz [baseline] \node [anchor=base, inner sep=0pt] {\reflectbox{$\M@flatGlyph$}};}

\newcommand{\M@sflat}{\tikz [baseline] \node [anchor=base, inner sep=0pt] {\reflectbox{$\M@flatGlyph$}$\M@flatGlyph$};}

\newcommand{\M@dsharp}{\tikz [baseline] {%
		\clip (-0.2em,-1ex) rectangle (-0.01em,2ex);
		\node[anchor=base, inner sep=0pt] {$\M@sharpGlyph$};}
}

\newcommand{\M@ssharp}{\tikz [baseline] {%
		\node[anchor=base,inner sep=0pt,name=leftsharp] at (0,0) {$\M@sharpGlyph$};
		\node  at (leftsharp.east) [xshift=-0.1em, yshift=0.15ex, inner sep=0pt,anchor=west] {\M@dsharp};}
}

\newcommand{\M@Acc}[3][-0.25]{ % place sharps and flats (hardcoded)
    \M@CheckChoice{#2}{-2,-1.5,-1,b,-0.5,0,0.5,1,\#,1.5,2}%
    \ifM@choiceValid\else
        \PackageWarning{mousik}{Unknown accidental `#2'. Expected -2 to 2 in steps of 0.5 (or b/\string\#); no accidental drawn}%
    \fi
	\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
    \ifM@choiceValid
	\M@EqStr{#2}{-2}{\M@PlaceNL[#1-0.07]{#3+0.1}{{\resizebox{0.3cm}{0.35cm}{\M@doubleFlatGlyph}}}}
	\M@EqStr{#2}{-1.5}{\M@PlaceNL[#1-0.07]{#3+0.1}{{\resizebox{0.3cm}{0.35cm}{\M@sflat}}}}
	\M@EqStr{#2}{-1}{\M@PlaceNL[#1]{#3+0.1}{{\resizebox{0.15cm}{0.35cm}{\M@flatGlyph}}}}
	\M@EqStr{#2}{b}{\M@PlaceNL[#1]{#3+0.1}{{\resizebox{0.15cm}{0.35cm}{\M@flatGlyph}}}}
	\M@EqStr{#2}{-0.5}{\M@PlaceNL[#1]{#3+0.1}{{\resizebox{0.15cm}{0.35cm}{\M@dflat}}}}
	\M@EqStr{#2}{0}{\M@PlaceNL[#1]{#3}{{\resizebox{0.15cm}{0.35cm}{\M@naturalGlyph}}}}
	\M@EqStr{#2}{0.5}{\M@PlaceNL[#1+0.07]{#3-0.015}{{\resizebox{0.2cm}{0.35cm}{\M@dsharp}}}}
	\M@EqStr{#2}{1}{\M@PlaceNL[#1]{#3}{{\resizebox{0.15cm}{0.35cm}{\M@sharpGlyph}}}}
	\M@EqStr{#2}{\#}{\M@PlaceNL[#1]{#3}{{\resizebox{0.15cm}{0.35cm}{\M@sharpGlyph}}}}
	\M@EqStr{#2}{1.5}{\M@PlaceNL[#1+0.02]{#3}{{\resizebox{0.3cm}{0.35cm}{\M@ssharp}}}}
	\M@EqStr{#2}{2}{\M@PlaceNL[#1]{#3}{{\resizebox{0.15cm}{0.15cm}{\M@doubleSharpGlyph}}}}
    \fi
}

\pgfkeys{
	/mousik/acc/.is family
	, /mousik/acc
	, default/.style = 
	{	xshift = 0
		, yshift = 0
	}
	, xshift/.estore in=\M@shiftX
	, yshift/.estore in=\M@shiftY
}
\newcommand{\mousikAcc}[3][]{
	\pgfkeys{/mousik/acc, default, #1}%
	\begin{scope}[xshift=\M@shiftX cm,yshift=\M@shiftY cm]
	\M@Acc{#2}{#3}
	\end{scope}
}
\pgfkeys{
/mousik/accs/.is family
, /mousik/accs
, default/.style = 
{	xshift = 0
	, yshift = 0
}
, xshift/.estore in=\M@shiftX
, yshift/.estore in=\M@shiftY
}
\newcommand{\M@ParallelAcc}[2]{\M@Acc{#1}{#2}}
\newcommand{\mousikAccs}[2][]{
	\pgfkeys{/mousik/accs, default, #1}%
	\begin{scope}[xshift=\M@shiftX cm,yshift=\M@shiftY cm]
	\M@Adv
	\M@ParallelList{#2}{\M@ParallelAcc}%
	\end{scope}
}

\newcommand{\M@KB}[2]{
	\setcounter{M@aux}{#1}
	\ifnum#2<0 \setcounter{M@max}{3} \else \setcounter{M@max}{5}\fi
	\addtocounter{M@aux}{-\theM@max}
	\pgfmathparse{int(2.74545*\theM@clef-5.01818)}
	\addtocounter{M@aux}{\pgfmathresult}
	\M@odulo{\theM@aux}{7}
	\setcounter{M@aux}{\theM@modulo}
	\addtocounter{M@aux}{\theM@max}
}

\newcommand{\M@WalkKeyOrder}[3]{% #1 order, #2 absolute key size, #3 kept accidentals
    \foreach\IND [count=\INDi] in {#1} {%
        \ifnum\INDi>#2 \else
            \ifnum\INDi>#3
                \M@KB{\IND}{\M@KeySign}%
                \M@Acc[-0.01*\theM@min]{\M@KeyAccType}{\theM@aux}%
            \fi
            \addtocounter{M@min}{\M@result}%
        \fi
    }%
}

\newcommand{\M@WalkKeySignature}[3]{% #1 signed key, #2 kept accidentals, #3 naturals (0/1)
    \ifnum#1=0 \else
        \pgfmathtruncatemacro{\M@KeyAbs}{abs(#1)}%
        \pgfmathparse{int(10*(abs(#1)-1)^(1/2)+20)}\setcounter{M@min}{\pgfmathresult}%
        \pgfmathsetmacro{\M@result}{int(abs(#1)*2-23)}%
        \ifnum#1>0
            \def\M@KeySign{1}%
            \ifnum#3=1 \def\M@KeyAccType{0}\else \def\M@KeyAccType{1}\fi
            \M@WalkKeyOrder{10,7,11,8,5,9,6}{\M@KeyAbs}{#2}%
        \else
            \def\M@KeySign{-1}%
            \ifnum#3=1 \def\M@KeyAccType{0}\else \def\M@KeyAccType{-1}\fi
            \M@WalkKeyOrder{6,9,5,8,4,7,3}{\M@KeyAbs}{#2}%
        \fi
    \fi
}

\newcommand{\M@DrawKey}[1]{\M@WalkKeySignature{#1}{0}{0}}
\newcommand{\M@DrawNoKey}[1]{\M@WalkKeySignature{#1}{0}{1}}
\newcommand{\M@DrawKeyCancellation}[2]{\M@WalkKeySignature{#1}{#2}{1}}

\newcommand{\M@BarKeyKern}{%
    \ifnum\theM@afterBar=1 \M@remStructQuarterMX \fi}

\newcommand{\mousikKey}[1]{
    \M@CheckKeyValue{#1}{\string\Key}%
    \ifM@choiceValid
        \setcounter{M@key}{#1}%
        \ifnum#1=0 \setcounter{M@afterBar}{0}%
        \else
            \M@BarKeyKern
            \M@DrawKey{#1}%
            \M@addStructMX
        \fi
    \fi
}

\newcommand{\mousikNoKey}[1]{
    \M@CheckKeyValue{#1}{\string\NoKey}%
    \ifM@choiceValid
        \ifnum#1=0 \setcounter{M@afterBar}{0}%
        \else
            \M@BarKeyKern
            \M@DrawNoKey{#1}%
            \M@addStructMX
        \fi
        \setcounter{M@key}{0}% cancellation leaves no active key signature
    \fi
}

\newif\ifM@mixedCancel
\newcommand{\mousikMixedKey}[2]{
    \M@CheckKeyValue{#1}{\string\MixedKey}%
    \ifM@choiceValid
        \M@CheckKeyValue{#2}{\string\MixedKey}%
    \fi
    \ifM@choiceValid
    \ifnum#1=0 \ifnum#2=0 \setcounter{M@afterBar}{0}%
        \else \M@BarKeyKern \fi
    \else \M@BarKeyKern \fi
    \M@mixedCancelfalse
    \pgfmathtruncatemacro{\M@oldkeyabs}{abs(#1)}
    \pgfmathtruncatemacro{\M@newkeyabs}{abs(#2)}
    \def\M@mixedKeep{0}
    \ifnum#1=0 \else
        \ifnum#2=0
            \M@mixedCanceltrue
        \else\ifnum\numexpr#1*#2\relax<0
            \M@mixedCanceltrue
        \else\ifnum\M@newkeyabs<\M@oldkeyabs
            \M@mixedCanceltrue
            \edef\M@mixedKeep{\M@newkeyabs}
        \fi\fi\fi
    \fi
    \ifM@mixedCancel
        \M@DrawKeyCancellation{#1}{\M@mixedKeep}%
        \M@addStructMX
    \fi
    \ifnum#2=0 \else
        \M@DrawKey{#2}%
        \M@addStructMX
    \fi
    \setcounter{M@key}{#2}
    \fi
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\pgfkeys{
	/mousik/text/.is family
	, /mousik/text
	, default/.style = 
	{	xshift = 0
		, yshift = 0
	}
	, xshift/.estore in=\M@shiftX
	, yshift/.estore in=\M@shiftY
}
\newcommand{\mousikText}[2][]{
	\pgfkeys{/mousik/text, default, #1}%
	\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
	\begin{scope}[xshift=\M@shiftX cm,yshift=\M@shiftY cm]
	\node at (\M@realX,-\theM@Y*\M@vsep-0.7) {#2};
	\end{scope}
}

\newcommand{\M@muskern}{\kern-.15ex }
\newcommand\M@dynmark[1]{{\normalfont\bfseries\itshape
		\@tfor\M@next:=#1\do{\M@putMuskern\M@next}\/}}
\newcommand{\M@putMuskern}{\let\M@putMuskern\M@muskern}

\newcommand{\mousikDynamics}[2][]{\mousikText[#1]{\Large\M@dynmark{#2}}}

\newcommand{\mousikNoteSpace}[1][1]{%
	\setcounter{M@afterBar}{0}% manual spacing cancels bar-to-key kerning
	\setcounter{M@canTuckBar}{0}% and prevents a following bar from consuming note tail space
	\pgfmathsetmacro\M@spaceAmount{int((#1) * \M@hsep)}%
	\ifnum\M@spaceAmount<0 \else {\M@Adv} \fi
	\addtocounter{M@X}{\M@spaceAmount}\pgfmathsetmacro\M@realX{\theM@X*0.0625}%
}
\newcommand{\mousikAccSpace}[1][1]{%
	\pgfmathparse{(#1)*(\M@accsep)}%
	\edef\M@AccSpaceAmount{\pgfmathresult}%
	\mousikNoteSpace[\M@AccSpaceAmount]%
}

\newcommand{\mousikSpace}[1][1]{
	\setcounter{M@afterBar}{0}% explicit spacing cancels bar-to-key kerning
	\setcounter{M@canTuckBar}{0}% and prevents a following bar from consuming note tail space
	\pgfmathsetmacro\M@spaceAmount{int((#1) * \M@hsep * 2)}
	\ifnum\M@spaceAmount<0 \else {\M@Adv} \fi
	\addtocounter{M@X}{\M@spaceAmount} \pgfmathsetmacro\M@realX{\theM@X*0.0625}
}

\pgfkeys{
	/mousik/barline/.is family
	, /mousik/barline
	, default/.style = 
	{	t = |%
		, xshift = 0
		, yshift = 0
	}
	, t/.estore in=\M@BarT
	, xshift/.estore in=\M@shiftX
	, yshift/.estore in=\M@shiftY
}
\newcommand{\M@SetBarGeometry}{%
	\M@barTwoMidsfalse
	\pgfmathsetmacro{\M@BarTopY}{-\theM@Y*\M@vsep+\M@staffTop}%
	\pgfmathsetmacro{\M@BarBottomY}{-\theM@Y*\M@vsep+\M@staffBottom}%
	\pgfmathsetmacro{\M@BarMidA}{-\theM@Y*\M@vsep+\M@staffMid}%
	\ifM@piano
		\ifM@pianoJoinedBars
			\M@barTwoMidstrue
			\ifnum\theM@staff=1
				\pgfmathsetmacro{\M@BarBottomY}{-\theM@Y*\M@vsep-\M@pianoSep+\M@staffBottom}%
				\pgfmathsetmacro{\M@BarMidB}{-\theM@Y*\M@vsep-\M@pianoSep+\M@staffMid}%
			\else
				\pgfmathsetmacro{\M@BarTopY}{-\theM@Y*\M@vsep+\M@pianoSep+\M@staffTop}%
				\pgfmathsetmacro{\M@BarMidB}{-\theM@Y*\M@vsep+\M@pianoSep+\M@staffMid}%
			\fi
		\fi
	\fi
	\pgfmathsetmacro{\M@BarThickTopY}{\M@BarTopY+0.007}%
	\pgfmathsetmacro{\M@BarThickBottomY}{\M@BarBottomY-0.007}%
}

\newcommand{\M@BarThin}[1][0]{%
	\draw (\M@realX+#1,\M@BarTopY) -- (\M@realX+#1,\M@BarBottomY);}
\newcommand{\M@BarThick}[1][0]{%
	\draw[line width=1mm] (\M@realX+#1,\M@BarThickTopY) -- (\M@realX+#1,\M@BarThickBottomY);}
\newcommand{\M@BarDots}[1]{%
	\node at (\M@realX+#1,\M@BarMidA) {\resizebox{0.175cm}{0.25cm}{:}};%
	\ifM@barTwoMids
		\node at (\M@realX+#1,\M@BarMidB) {\resizebox{0.175cm}{0.25cm}{:}};%
	\fi}

\newcommand{\mousikBarline}[1][]{
    \setcounter{M@barTuck}{\theM@canTuckBar}%
    \pgfmathparse{int(\M@hsep)}\setcounter{M@aux}{\pgfmathresult}%
    \pgfmathparse{int(round(\M@barsep*\theM@aux))}%
    \setcounter{M@barGapMX}{\pgfmathresult}%
    \setcounter{M@afterBar}{0}\setcounter{M@canTuckBar}{0}%
    \ifnum\theM@barTuck=1
        \addtocounter{M@X}{-\theM@aux}\addtocounter{M@X}{-\theM@aux}%
        \addtocounter{M@X}{\theM@barGapMX}%
    \fi
	\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}
	\pgfkeys{/mousik/barline, default, #1}%
    \M@CheckChoice{\M@BarT}{|,:,||,|.,:|,|:,:|:}%
    \ifM@choiceValid\else
        \PackageWarning{mousik}{Unknown barline type `\M@BarT'. Expected |, :, ||, |., :|, |:, or :|:; no barline drawn}%
    \fi
	\M@SetBarGeometry
	\begin{scope}[xshift=\M@shiftX cm,yshift=\M@shiftY cm]
    \ifM@choiceValid
	\ifthenelse{\equal{\M@BarT}{|}}%
		{\M@BarThin}{}
	\ifthenelse{\equal{\M@BarT}{:}}%
		{\draw[dashed] (\M@realX,\M@BarTopY) -- (\M@realX,\M@BarBottomY);}{}
	\ifthenelse{\equal{\M@BarT}{||}}%
		{\M@BarThin[-0.12]\M@BarThin}{}
	\ifthenelse{\equal{\M@BarT}{|.}}%
		{\M@BarThin[-0.12]\M@BarThick}{}
	\ifthenelse{\equal{\M@BarT}{:|}}%
		{\M@BarDots{-0.24}\M@BarThin[-0.12]\M@BarThick}{}
	\ifthenelse{\equal{\M@BarT}{|:}}%
		{\M@BarThick[-0.3275]\M@BarDots{-0.0875}\M@BarThin[-0.2075]}{}
	\ifthenelse{\equal{\M@BarT}{:|:}}%
		{\M@BarDots{-0.5675}\M@BarThin[-0.4475]\M@BarThick[-0.3275]\M@BarDots{-0.0875}\M@BarThin[-0.2075]}{}
    \fi
	\end{scope}
	\setcounter{M@lastBarMX}{\theM@X}\setcounter{M@lastBarMY}{\theM@Y}\setcounter{M@lastBarStaff}{\theM@staff}%
    \addtocounter{M@X}{\theM@barGapMX}% leave the same clearance after the printed bar
    \pgfmathsetmacro{\M@realX}{\theM@X*0.0625}%
    \setcounter{M@barAdvance}{\theM@barGapMX}%
	\setcounter{M@afterBar}{1}%
    \setcounter{M@canTuckBar}{0}%
}

\newcommand{\M@Adv}{
	\setcounter{M@advAfterBar}{\theM@afterBar}%
	\setcounter{M@advBarAdvance}{\theM@barAdvance}%
	\M@addhalfMX
	\pgfmathsetmacro\M@cmp{int(\M@realX*100-\M@length*12)}
	\ifnum\M@cmp>0
		\M@remhalfMX
		\M@DoBreakLine{\theM@advAfterBar}{\theM@advBarAdvance}
		\ifnum\theM@clef=0 \else {\mousikClef[t=\theM@clef]} \fi
		\mousikKey{\theM@key}
	\else {\M@remhalfMX} \fi
}

\newcommand{\M@DoBreakLine}[2]{
	\ifnum#1=1
		\addtocounter{M@X}{-#2}%
		\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}%
		\setcounter{M@afterBar}{0}%
		\def\M@BreakPad{0}%
	\else
		\mousikSpace[-1]%
		\def\M@BreakPad{1}% keep the old small margin unless the line ends on a barline
		\ifnum\theM@X=\theM@lastBarMX
			\ifnum\theM@Y=\theM@lastBarMY
				\ifnum\theM@staff=\theM@lastBarStaff \def\M@BreakPad{0}\fi
			\fi
		\fi
	\fi
	\ifM@lengthSet\else
		\ifnum\theM@Y=0
			\pgfmathsetmacro{\M@length}{(\theM@X+\M@BreakPad)*6.25/12}%
			\M@lengthSettrue
		\fi
	\fi
	\setcounter{M@X}{0}\pgfmathsetmacro{\M@realX}{0}
    \setcounter{M@canTuckBar}{0}%
	\addtocounter{M@Y}{1}
}

\newcommand{\mousikBreakLine}{\M@DoBreakLine{\theM@afterBar}{\theM@barAdvance}}

\newcommand{\M@TempoNote}[1]{%
	\raisebox{0.02cm}[0.85cm][0.20cm]{%
		\makebox[0.45cm][c]{\tikz[baseline=0pt]{\mousikNote{#1}{2}}}%
	}%
}

\newcommand{\mousikTempo}[3][]{%
	\mousikText[yshift=2.5,#1]{\M@TempoNote{#2}\Large\textbf{ = #3}}%
	\mousikSpace[-1]% undo the cursor movement made by the internal note
}

\newcommand{\mousikTie}[2][]{
	\mousikSlur[#1]{#2}{#2}
}

\newif\ifM@slurSwap
\newif\ifM@slurBelow
\pgfkeys{
	/mousik/slur/.is family
	, /mousik/slur
	, default/.style = 
	{	angle = 20
		, bshift = 0
		, eshift = 1
		, swap = false
		, width = 0.15
		, xshift = 0
		, yshift = 0
	}
	, angle/.estore in=\M@slurAngle
	, bshift/.estore in=\M@slurBshift
	, eshift/.estore in=\M@slurEshift
	, swap/.is if=M@slurSwap
	, width/.estore in=\M@slurWidth
	, xshift/.estore in=\M@shiftX
	, yshift/.estore in=\M@shiftY
}
\newcommand{\mousikSlur}[3][]{%
	\begingroup
	\pgfmathsetmacro{\M@SlurTrail}{2*\M@hsep*0.0625}%
	\pgfkeys{/mousik/slur, default, eshift=\M@SlurTrail, #1}%
	\pgfmathsetmacro{\M@realX}{\theM@X*0.0625}%
	\pgfmathsetmacro{\M@SlurDX}{(\M@slurEshift)-(\M@slurBshift)}%
	\pgfmathsetmacro{\M@SlurDY}{0.1*((#3)-(#2))}%
	\pgfmathsetmacro{\M@SlurSlope}{atan2(\M@SlurDY,\M@SlurDX)}%
	\ifnum#2<6 \M@slurBelowtrue \else \M@slurBelowfalse \fi
	\ifM@slurSwap
		\ifM@slurBelow \M@slurBelowfalse \else \M@slurBelowtrue \fi
	\fi
	\begin{scope}[xshift=\M@shiftX cm,yshift=\M@shiftY cm]
	\ifM@slurBelow
		\pgfmathsetmacro{\M@SlurOut}{\M@SlurSlope-\M@slurAngle}%
		\pgfmathsetmacro{\M@SlurIn}{\M@SlurSlope+180+\M@slurAngle}%
		\draw[line width=\M@slurWidth mm] (-\M@SlurTrail+\M@slurBshift+\M@realX,-\theM@Y*\M@vsep+0.1*#2-0.35) to[out=\M@SlurOut,in=\M@SlurIn] (-\M@SlurTrail+\M@slurEshift+\M@realX,-\theM@Y*\M@vsep+0.1*#3-0.35);
	\else
		\pgfmathsetmacro{\M@SlurOut}{\M@SlurSlope+\M@slurAngle}%
		\pgfmathsetmacro{\M@SlurIn}{\M@SlurSlope+180-\M@slurAngle}%
		\draw[line width=\M@slurWidth mm]
		 (-\M@SlurTrail+\M@slurBshift+\M@realX,-\theM@Y*\M@vsep+0.1*#2-0.05) to[out=\M@SlurOut,in=\M@SlurIn] (-\M@SlurTrail+\M@slurEshift+\M@realX,-\theM@Y*\M@vsep+0.1*#3-0.05);
	\fi
	\end{scope}
	\endgroup
}

\newif\ifM@slurEnvSwap
\pgfkeys{
	/mousik/slurred/.is family
	, /mousik/slurred
	, default/.style = 
	{	angle = 20
		, bshift = 0
		, eshift = 1
		, swap = false
		, width = 0.15
		, xshift = 0
		, yshift = 0
	}
	, angle/.estore in=\M@slurredAngle
	, bshift/.estore in=\M@slurredBshift
	, eshift/.estore in=\M@slurredEshift
	, swap/.is if=M@slurEnvSwap
	, width/.estore in=\M@slurredWidth
	, xshift/.estore in=\M@slurredX
	, yshift/.estore in=\M@slurredY
}
\newcounter{M@slurred}
\newcounter{M@slurredB}
\newcounter{M@slurredE}
\newcommand{\M@DrawSlurred}[1]{%
	\mousikSlur[#1angle=\M@slurredAngle%
		, bshift=\M@slurredBshift%
		, eshift=\theM@slurred*0.0625+\M@slurredEshift-1
		, width=\M@slurredWidth%
		, xshift=\M@slurredX%
		, yshift=\M@slurredY%
		]%
		{\theM@slurredB}{\theM@slurredE}%
}
\newenvironment{mousikSlurred}[3][]{%
\pgfmathsetmacro{\M@slurAux}{int(\theM@X+\M@hsep*2)}
\setcounter{M@slurred}{\M@slurAux}
\pgfkeys{/mousik/slurred, default, #1}%
\setcounter{M@slurredB}{#2}
\setcounter{M@slurredE}{#3}
}{
\setcounter{M@aux}{\theM@X}
\setcounter{M@X}{\theM@slurred}
\setcounter{M@slurred}{\theM@aux}
\addtocounter{M@slurred}{-\theM@X}
\ifM@slurEnvSwap
	\M@DrawSlurred{swap,}%
\else
	\M@DrawSlurred{}%
\fi
\setcounter{M@X}{\theM@aux}
}

\newcounter{M@cres}
\newcounter{M@cresY}
\pgfkeys{
    /mousik/hairpin/.is family
    , /mousik/hairpin
    , common/.style = {
        bshift = 0.1
        , eshift = -0.1
        , width = 0.15
        , xshift = 0
        , yshift = 0
    }
    , crescendo/.style = {common, bopen = 0, eopen = 0.4}
    , decrescendo/.style = {common, bopen = 0.4, eopen = 0}
    , bopen/.estore in=\M@HairpinBeginOpen
    , eopen/.estore in=\M@HairpinEndOpen
    , bshift/.estore in=\M@HairpinBshift
    , eshift/.estore in=\M@HairpinEshift
    , width/.estore in=\M@HairpinW
    , xshift/.estore in=\M@HairpinX
    , yshift/.estore in=\M@HairpinY
}

\newcommand{\M@HairpinStartEnv}[2]{% #1 style, #2 key-value options
    \pgfkeys{/mousik/hairpin,#1}%
    \def\M@HairpinRaw{#2}%
    \ifx\M@HairpinRaw\@empty\else
        \pgfkeys{/mousik/hairpin,#2}%
    \fi
    \setcounter{M@cres}{\theM@X}%
    \setcounter{M@cresY}{\theM@Y}%
}

\newcommand{\M@HairpinFinishEnv}{%
    \ifnum\theM@Y=\theM@cresY\else
        \PackageWarning{mousik}{Hairpin crossed a score line; split it into two environments and match eopen/bopen apertures}%
    \fi
    \pgfmathsetmacro{\M@HairpinStartX}{\theM@cres*0.0625 + \M@HairpinBshift}%
    \pgfmathsetmacro{\M@HairpinLastNoteX}{(\theM@X-2*\M@hsep)*0.0625}%
    \pgfmathsetmacro{\M@HairpinEndX}{\M@HairpinLastNoteX + \M@HairpinEshift}%
    \pgfmathsetmacro{\M@HairpinCenterY}{-\theM@Y*\M@vsep - 0.7}%
    \pgfmathsetmacro{\M@HairpinBeginHalf}{0.5*\M@HairpinBeginOpen}%
    \pgfmathsetmacro{\M@HairpinEndHalf}{0.5*\M@HairpinEndOpen}%
    \begin{scope}[xshift=\M@HairpinX cm,yshift=\M@HairpinY cm]
        \draw[line width=\M@HairpinW mm]
            (\M@HairpinStartX,\M@HairpinCenterY+\M@HairpinBeginHalf) --
            (\M@HairpinEndX,\M@HairpinCenterY+\M@HairpinEndHalf);
        \draw[line width=\M@HairpinW mm]
            (\M@HairpinStartX,\M@HairpinCenterY-\M@HairpinBeginHalf) --
            (\M@HairpinEndX,\M@HairpinCenterY-\M@HairpinEndHalf);
    \end{scope}%
}

\newenvironment{mousikCrescendo}[1][]
    {\M@HairpinStartEnv{crescendo}{#1}}
    {\M@HairpinFinishEnv}

\newenvironment{mousikDecrescendo}[1][]
    {\M@HairpinStartEnv{decrescendo}{#1}}
    {\M@HairpinFinishEnv}


\endinput
