[Tex/LaTex] TikZ matrix decoration

diagramsmathtoolsmatricestikz-pgf

What I'm trying to achieve is a code structure to draw this kind of diagram:

example

I need to decorate a two-rows matrix grouping one or more columns with a square bracket above them, and then again with a square bracket grouping one or more subgroups (there may be more than three levels of nested groups).

At first I tried nesting matrices with above delimiter=\lbrack, but TikZ told me that You cannot nest pgfmatrix environments, yet, so I ended up with something like this

\documentclass{minimal}
\usepackage{tikz}
\usetikzlibrary{matrix,fit,positioning,decorations.pathreplacing,arrows,calc}
\begin{document}
\begin{tikzpicture}[
  group/.style={inner sep=0pt},
  brace/.style={very thick,decorate,decoration={brace,amplitude=10pt}},
  square/.style={-,to path={-- ++(0,.25) -| (\tikztotarget)}}
]
\matrix (A) [matrix of nodes]
{
  1--2 & 3--4 & 5 &
  6--7 & 8--9 & 10 &
  11--12 & 13--14 & 15--16 \\
  %
  I & V--I--V & V--IV &
  V$^6$--IV & V$^7$ & V--IV &
  I--V--I--IV & V$^7$--I & V--VI \\
};
\node (gdg) [group,fit=(A-1-1)(A-2-1)] {};
\node (boh) [group,fit=(A-1-2)(A-2-2)] {};
\node (z) [group,fit=(A-1-3)(A-2-3)] {};
\node (frase-a) [group,fit=(gdg)(boh)(z)] {};
\draw[square] ([yshift=.5cm]gdg.west) to ([yshift=.5cm]gdg.east);
\draw[square] ([yshift=.5cm]boh.west) to ([yshift=.5cm]boh.east);
\draw[square] ([yshift=.5cm]z.west) to ([yshift=.5cm]z.east);

\draw[square] ([yshift=1cm]frase-a.west) to ([yshift=1cm]frase-a.east);

\draw[brace] ([yshift=2cm]A.west) -- ([yshift=2cm]A.east);
\end{tikzpicture}
\end{document}

where I first draw the matrix, then I group each column in an invisible node (with fit) and then draw the square brackets as paths from/to west/east anchor point of groups, shifting coordinates on the y-axis. Which is quite unmaintainable and ugly.
Of course the main target is to build something that could adapt to the variable width of matrix columns. Any suggestion would be very appreciated!

Best Answer

Inspired by David Carlisle answer, I came up with this solution:

\documentclass{minimal}
\usepackage{mathtools}
\newcommand{\mfrac}[2]{\genfrac{}{}{0pt}{}{#1}{#2}}
\begin{document}
\[
\overbrace{
  \overbracket{
    \overbracket{\mfrac{1-2}{I}}^{\text{Gdg}}
    \overbracket{\mfrac{3-4}{V-I-V}}
    \overbracket{\mfrac{5}{V-IV}}^{z}
  }^{\text{frase }a}
  \overbracket{
    \overbracket{\mfrac{6-7}{V^6}}
    \overbracket{\mfrac{8-9}{V^7}}^{y}
    \overbracket{\mfrac{10}{V-IV}}^{z'}
  }^{\text{frase }b/a'}
  \overbracket{
    \overbracket{\mfrac{11-12}{I-V-I-IV}}
    \overbracket{\mfrac{13-14}{V^7-I}}^{y'}
    \overbracket{\mfrac{15-16}{V-VI}}^{z''}
  }^{\text{frase }a'/b}
}^{A}
\]
\end{document}

which results in:

image

Now it's flexible and maintainable, I just need to find out to add labels outside the brace on the left of each line.