\unprotect

\def\dostartmathcases[#1][#2]%
  {\begingroup
   \edef\currentmathcases{#1}%
   \doifassignmentelse{#2}{\setupmathcases[#1][#2]}\donothing
   \mathcasesparameter\c!left
   \vcenter\bgroup
   \pushmacro\docasesNC
   \let\endmath\relax
   \def\NC{\docasesNC}%
   \def\MC{\docasesNC\ifmmode\else$\def\endmath{$}\fi}%
   \global\let\docasesNC\dodocasesNC
   \def\NR{\unskip\endmath&\global\let\docasesNC\dodocasesNC\doxxdoubleempty\docasesNR}%
   \normalbaselines
   \mathsurround\zeropoint
   \everycr\emptytoks
   \tabskip\zeropoint
   \global\eqaligncolumn\plusone
   \halign\bgroup
        $\mathcasesparameter\c!style##$\hfil 
       &\hskip\mathcasesparameter\c!distance\relax
        \popmacro\docasesNC##\hfil
       &\hskip\mathcasesparameter\c!numberdistance\relax
        \let\formuladistance\!!zeropoint
        \span\textineqalign{##}%
     \crcr} % todo: number

\def\preparemathmatrix
  {\!!toksa{\strut 
            \firstineqalign\leftofeqalign \span 
            \textineqalign{\mathmatrixparameter\c!style ##}\rightofeqalign}%
   \!!toksb{&\hskip\mathmatrixparameter\c!distance
            \nextineqalign\leftofeqalign \span 
            \textineqalign{\mathmatrixparameter\c!style ##}\rightofeqalign}%
   \!!toksc{&&\hskip\mathmatrixparameter\c!distance
            \leftofeqalign \span 
            \textineqalign{\mathmatrixparameter\c!style ##}\rightofeqalign}%
   \buildmathmatrix
   \halign \@EA \bgroup\the\scratchtoks \crcr}

\def\dostartmathmatrix[#1][#2]%
  {\begingroup
   \edef\currentmathmatrix{#1}%
   \doifassignmentelse{#2}{\setupmathmatrix[#1][#2]}\donothing
   \null
   \mathmatrixparameter\c!left
   \processaction
      [\mathmatrixparameter\c!location]
      [\s!default=>\let\vchbox\vcenter,
       \s!unknown=>\let\vchbox\vcenter,
       \v!top=>\let\vchbox\vtop,
       \v!bottom=>\let\vchbox\vbox]%
   \vchbox\bgroup
   \pushmacro\domatrixNC
   \let\endmath\relax
   \def\NC{\domatrixNC}%
   \def\MC{\domatrixNC\ifmmode\else$\def\endmath{$}\fi}%
   \global\let\domatrixNC\dodomatrixNC
   \def\NR{\endmath\global\let\domatrixNC\dodomatrixNC\crcr}%
   \normalbaselines
   \mathsurround\zeropoint
   \everycr\emptytoks
   \tabskip\zeropoint
   \eqaligncolumn\zerocount % could be \scratchcounter
   \processcommacommand[\mathmatrixparameter\c!align]{\advance\eqaligncolumn\plusone\dosetmatrixcolumn}%
   \scratchcounter=\ifnum\eqaligncolumn>\scratchcounter \eqaligncolumn \else \plusone \fi
   \global\eqaligncolumn\plusone
   \preparemathmatrix } % uses scratchcounter

\def\dobothaligneqalignno#1%
  {\ifmmode
    \displ@y
    \global\chardef\mathnumberstatus\plusone
    \ifcase\mathraggedstatus 
       \def\finishalignno{\crcr\egroup}%
    \else
       % we're in a mathbox
       \vcenter\bgroup
       \def\finishalignno{\crcr\egroup\egroup}%
    \fi
   \fi
   #1%
   \halign \ifcase\eqalignmode \or to \displaywidth \fi \@EA \bgroup\the\scratchtoks\crcr}

\protect
