%%% License %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This package is licensed under the terms of the MIT License.

% Copyright (c) 2025 Kosei Kawaguchi

% Permission is hereby granted, free of charge, 
% to any person obtaining a copy of this software and associated documentation files 
% (the "Software"), to deal in the Software without restriction, 
% including without limitation the rights to use, copy, modify, merge, publish, 
% distribute, sublicense, and/or sell copies of the Software, 
% and to permit persons to whom the Software is furnished to do so, 
% subject to the following conditions:

% The above copyright notice and this permission notice 
% shall be included in all copies or substantial portions of the Software.

% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
% IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
% DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 
% ARISING FROM, 
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{modernruler}[2025/12/28, Version 1.0.0]

%%% basical settings
\RequirePackage{kvoptions} 
\RequirePackage{varwidth}
\RequirePackage[most]{tcolorbox}

%%% kv（undernoteの方）
\SetupKeyvalOptions{%
  family=undernote,%
  prefix=undernote@%
}
\DeclareStringOption[\footnotesize]{notesize}
\DeclareStringOption[3mm]{notepos}
\DeclareStringOption[4mm]{noteshift}
\DeclareStringOption[.4pt]{noterulethickness}
\DeclareStringOption[1.5mm]{noterulehshift}
\DeclareStringOption[1.5mm]{noterulehsize}
\DeclareStringOption[2em]{notesep}
\DeclareStringOption[3em]{noteoverhang}
\DeclareStringOption[0]{parstyle}
\ProcessKeyvalOptions*

\def\notesize@internal@undernote{\undernote@notesize}                     
   %%% 注釈部分の文字サイズ
\def\notepos@internal@undernote{\undernote@notepos}                        
   %%% 注釈へと伸ばす縦線の長さの最小値
\def\noteshift@internal@undernote{\undernote@noteshift}                    
   %%% 注釈を下にずらす場合の1段階分の移動量
\def\noterulethickness@internal@undernote{\undernote@noterulethickness}    
   %%% \note で用いる罫線の太さ
\def\noterulehshift@internal@undernote{\undernote@noterulehshift}          
   %%% 注釈へと伸ばす縦線の位置（注釈をつける語句につけた下線の左端から
   %%% \noterulehshift@internal@undernote だけ右にずれた位置に縦線を置く）
\def\noterulehsize@internal@undernote{\undernote@noterulehsize}           
   %%% 注釈へと伸ばす横線の長さ
\def\notesep@internal@undernote{\undernote@notesep}                        
   %%% 前にある注釈が次の注釈の縦線から \notesep@internal@undernote 以内に近づくようなら，
   %%% 前にある注釈を下にずらす（「2em」のように文字サイズに依存する
   %%% 指定をした場合は，\notesize@internal@undernote（の，現在使用中のフォント）における値）
\def\noteoverhang@internal@undernote{\undernote@noteoverhang}                                 
   %%% parbox に入れるタイプ（スターをつけた時）
   %%% どの程度後ろに注釈部分を張り出させるか
\def\noteparstyle@internal@undernote{\undernote@parstyle}                                     
   %%% 注釈部分を
   %%% 1 と 2 以外: 囲みなし 1: 実線で囲う 2:点線で囲う


% command
\NewDocumentCommand{\SetUNoteSize}{O{\footnotesize}}{%
  \def\notesize@internal@undernote{#1}%
}                 
\NewDocumentCommand{\SetUNoteRuleThickness}{O{.4pt}}{%
  \def\noterulethickness@internal@undernote{#1}%
}
\NewDocumentCommand{\SetUNoteRuleHShift}{O{1.5mm}}{%
  \def\noterulehshift@internal@undernote{#1}%
}
\NewDocumentCommand{\SetUNoteRuleHSize}{O{1.5mm}}{%
  \def\noterulehsize@internal@undernote{#1}%
}
\NewDocumentCommand{\SetUNotePos}{O{3mm}}{%
  \def\notepos@internal@undernote{#1}%
}
\NewDocumentCommand{\SetUNoteShift}{O{4mm}}{%
  \def\noteshift@internal@undernote{#1}%
}
\NewDocumentCommand{\SetUNoteSep}{O{2em}}{%
  \def\notesep@internal@undernote{#1}%
}
\NewDocumentCommand{\SetUNoteOverHang}{O{3em}}{%
  \def\noteoverhang@internal@undernote{#1}%
}
\NewDocumentCommand{\SetUNoteParstyle}{O{0}}{%
  \ifnum#1=1%
   \let\wrap@undernote\wrap@undernote@styleA%
   \let\wrap@undernote@par\wrap@undernote@par@styleA%
   \def\hline@undernote@par{\mruleth[height=\noterulethickness@internal@undernote, width=\undernote@textlen@tempo]}%
   \def\vlines@undernote@par{%
      \mruletv[height=\dimen@, width=\noterulethickness@internal@undernote, depth=0pt]%
      \mruleth[height=\noterulethickness@internal@undernote, width=\noterulehsize@internal@undernote, depth=0pt]%
   }%
   \else\ifnum#1=2
      \let\wrap@undernote\wrap@undernote@styleB%
      \let\wrap@undernote@par\wrap@undernote@par@styleB%
      \def\hline@undernote@par{\mruleth[height=\noterulethickness@internal@undernote, width=\undernote@textlen@tempo, dash=true]}%
      \def\vlines@undernote@par{%
         \mruletv[height=\dimen@, width=\noterulethickness@internal@undernote, depth=0pt ,dash=true]%
         \mruleth[height=\noterulethickness@internal@undernote, width=\noterulehsize@internal@undernote, depth=0pt, dash=true]%
      }%
      \else
         \let\wrap@undernote\wrap@undernote@styleC%
         \let\wrap@undernote@par\wrap@undernote@par@styleC%
         \def\hline@undernote@par{\mruleth[height=\noterulethickness@internal@undernote, width=\undernote@textlen@tempo]}%
         \def\vlines@undernote@par{%
            \mruletv[height=\dimen@, width=\noterulethickness@internal@undernote, depth=0pt]%
            \mruleth[height=\noterulethickness@internal@undernote, width=\noterulehsize@internal@undernote, depth=0pt]%
         }%
   \fi\fi
}
%%%

%%% modern rule commands
\ExplSyntaxOn

% 変数の宣言
\dim_new:N  \l_mrule_width_dim
\dim_new:N  \l_mrule_height_dim
\dim_new:N  \l_mrule_depth_dim
\dim_new:N  \l_mrule_dash_len_dim
\dim_new:N  \l_mrule_gap_len_dim
\dim_new:N  \l_mrule_total_width_dim 
\tl_new:N   \l_mrule_color_tl
\bool_new:N \l_mrule_dash_bool
\tl_new:N \l_mrule_leader_cmd_tl
\dim_new:N \l__mrule_tmp_remaining_dim

% キーの定義
\keys_define:nn { modernrule }
  {
    width    .dim_set:N = \l_mrule_width_dim,
    height   .dim_set:N = \l_mrule_height_dim,
    depth    .dim_set:N = \l_mrule_depth_dim,
    color    .tl_set:N  = \l_mrule_color_tl,
    dash     .bool_set:N = \l_mrule_dash_bool,
    dash-len .dim_set:N  = \l_mrule_dash_len_dim,
    gap-len  .dim_set:N  = \l_mrule_gap_len_dim,
    gap-color .tl_set:N = \l_mrule_gap_color_tl,

    % デフォルト値
    width    .initial:n = 0pt,
    height   .initial:n = 0pt,
    depth    .initial:n = 0pt,
    color    .initial:n = black,
    dash     .initial:n = false,
    dash-len .initial:n = 3pt,
    gap-len  .initial:n = 2.5pt,
    gap-color .initial:n = white,
  }

% 水平方向：2色点線
\NewDocumentCommand{\mruleth}{O{}}
  {
    \group_begin:
    \keys_set:nn { modernrule } { #1 }
    \ifvmode \nointerlineskip \fi
    
    \bool_if:NTF \l_mrule_dash_bool
      {
        % dash=true: 2色交互の点線描画
        \hbox_to_wd:nn { \l_mrule_width_dim }
          {
            \dim_set:Nn \l__mrule_tmp_remaining_dim { \l_mrule_width_dim }
            \dim_while_do:nNnn { \l__mrule_tmp_remaining_dim } > { 0pt }
              {
                \dim_compare:nNnTF { \l__mrule_tmp_remaining_dim } > { \l_mrule_dash_len_dim }
                  {
                    % メイン色
                    {\color{\l_mrule_color_tl} \vrule width \l_mrule_dash_len_dim height \l_mrule_height_dim depth \l_mrule_depth_dim}
                    \dim_sub:Nn \l__mrule_tmp_remaining_dim { \l_mrule_dash_len_dim }
                    
                    % ギャップ色
                    \dim_compare:nNnTF { \l__mrule_tmp_remaining_dim } > { \l_mrule_gap_len_dim }
                      {
                        {\color{\l_mrule_gap_color_tl} \vrule width \l_mrule_gap_len_dim height \l_mrule_height_dim depth \l_mrule_depth_dim}
                        \dim_sub:Nn \l__mrule_tmp_remaining_dim { \l_mrule_gap_len_dim }
                      }
                      {
                        {\color{\l_mrule_gap_color_tl} \vrule width \l__mrule_tmp_remaining_dim height \l_mrule_height_dim depth \l_mrule_depth_dim}
                        \dim_set:Nn \l__mrule_tmp_remaining_dim { 0pt }
                      }
                  }
                  {
                    {\color{\l_mrule_color_tl} \vrule width \l__mrule_tmp_remaining_dim height \l_mrule_height_dim depth \l_mrule_depth_dim}
                    \dim_set:Nn \l__mrule_tmp_remaining_dim { 0pt }
                  }
              }
            \hss
          }
      }
      {
        \hbox_to_wd:nn { \l_mrule_width_dim } {{
            \color{\l_mrule_color_tl}
            \vrule width \l_mrule_width_dim height \l_mrule_height_dim depth \l_mrule_depth_dim
         }}
      }
      
    \ifvmode \nointerlineskip \fi
    \group_end:
  }

% 垂直方向：2色点線
\NewDocumentCommand{\mruletv}{O{}}
  {
    \group_begin:
    \keys_set:nn { modernrule } { #1 }
    
    \bool_if:NTF \l_mrule_dash_bool
      {
        % dash=true: 2色交互の垂直点線
        \dim_set:Nn \l__mrule_tmp_remaining_dim { \l_mrule_height_dim }
        \vbox:n
          {
            \dim_while_do:nNnn { \l__mrule_tmp_remaining_dim } > { 0pt }
              {
                \dim_compare:nNnTF { \l__mrule_tmp_remaining_dim } > { \l_mrule_dash_len_dim }
                  {
                    % メイン色
                    {\color{\l_mrule_color_tl} \hrule width \l_mrule_width_dim height \l_mrule_dash_len_dim}
                    \dim_sub:Nn \l__mrule_tmp_remaining_dim { \l_mrule_dash_len_dim }
                    
                    % ギャップ色
                    \dim_compare:nNnTF { \l__mrule_tmp_remaining_dim } > { \l_mrule_gap_len_dim }
                      {
                        {\color{\l_mrule_gap_color_tl} \hrule width \l_mrule_width_dim height \l_mrule_gap_len_dim}
                        \dim_sub:Nn \l__mrule_tmp_remaining_dim { \l_mrule_gap_len_dim }
                      }
                      {
                        {\color{\l_mrule_gap_color_tl} \hrule width \l_mrule_width_dim height \l__mrule_tmp_remaining_dim}
                        \dim_set:Nn \l__mrule_tmp_remaining_dim { 0pt }
                      }
                  }
                  {
                    {\color{\l_mrule_color_tl} \hrule width \l_mrule_width_dim height \l__mrule_tmp_remaining_dim}
                    \dim_set:Nn \l__mrule_tmp_remaining_dim { 0pt }
                  }
              }
          }
      }
      {
        \vbox:n { {\color{\l_mrule_color_tl} \hrule width \l_mrule_width_dim height \l_mrule_height_dim} }
      }
    \group_end:
  }
\ExplSyntaxOff
%%%

\DeclareTotalTCBox{\FramedBox@undernote}{ O{} +m }{%
  on line,arc=0pt,
  sharp corners,boxsep=0mm,
  left=.3mm,right=.3mm,top=0.3mm,bottom=0.3mm,
  colback=white,colframe=white,
  enhanced,before={\hspace*{-.1722\zw}},
  borderline={\noterulethickness@internal@undernote}{0mm}{solid},
  #1
}{#2}
\DeclareTotalTCBox{\DashedBox@undernote}{ O{} +m }{%
  on line,arc=0pt,
  sharp corners,boxsep=0mm,
  left=.3mm,right=.3mm,top=0.3mm,bottom=0.3mm,
  colback=white,colframe=white,
  enhanced,before={\hspace*{-.1722\zw}},
  borderline={\noterulethickness@internal@undernote}{0mm}{dashed},
  #1
}{#2}
\DeclareTotalTCBox{\NoframeBox@undernote}{ O{} +m }{%
  on line,arc=0pt,
  sharp corners,boxsep=0mm,
  left=.3mm,right=.3mm,top=0.3mm,bottom=0.3mm,
  colback=white,colframe=white,
  enhanced,before={\hspace*{-.1722\zw}},
  #1
}{#2}

\newlength{\undernote@textlen@tempo}

\NewDocumentCommand{\wrap@undernote@par@styleA}{ +m }{%
{%
   \FramedBox@undernote{%
      \parbox[t]{\dimexpr\undernote@textlen@tempo - \noterulehsize@internal@undernote - \noterulehshift@internal@undernote + \noteoverhang@internal@undernote\relax}%
      {\setlength{\baselineskip}{.2153\zw}\setlength{\parindent}{1em}#1}}%
}}
\NewDocumentCommand{\wrap@undernote@par@styleB}{ +m }{%
{%
   \DashedBox@undernote{%
      \parbox[t]{\dimexpr\undernote@textlen@tempo - \noterulehsize@internal@undernote - \noterulehshift@internal@undernote + \noteoverhang@internal@undernote\relax}%
      {\setlength{\baselineskip}{.2153\zw}\setlength{\parindent}{1em}#1}}%
}}
\NewDocumentCommand{\wrap@undernote@par@styleC}{ +m }{%
{%
   \NoframeBox@undernote{%
      \parbox[t]{\dimexpr\undernote@textlen@tempo - \noterulehsize@internal@undernote - \noterulehshift@internal@undernote + \noteoverhang@internal@undernote\relax}%
      {\setlength{\baselineskip}{.2153\zw}\setlength{\parindent}{1em}#1}}%
}}
\NewDocumentCommand{\wrap@undernote@styleA}{ +m }{{\FramedBox@undernote{#1}}}
\NewDocumentCommand{\wrap@undernote@styleB}{ +m }{{\DashedBox@undernote{#1}}}
\NewDocumentCommand{\wrap@undernote@styleC}{ +m }{{\NoframeBox@undernote{#1}}}
\NewDocumentCommand{\wrap@undernote}{ +m }{{#1}}
\NewDocumentCommand{\wrap@undernote@par}{ +m }{{\wrap@undernote@styleC{#1}}}
\ifnum\noteparstyle@internal@undernote=1
   \let\wrap@undernote\wrap@undernote@styleA
   \let\wrap@undernote@par\wrap@undernote@par@styleA
   \def\hline@undernote@par{\mruleth[height=\noterulethickness@internal@undernote, width=\undernote@textlen@tempo]}%
   \def\vlines@undernote@par{%
      \mruletv[height=\dimen@, width=\noterulethickness@internal@undernote, depth=0pt]%
      \mruleth[height=\noterulethickness@internal@undernote, width=\noterulehsize@internal@undernote, depth=0pt]%
   }
\else\ifnum\noteparstyle@internal@undernote=2
   \let\wrap@undernote\wrap@undernote@styleB
   \let\wrap@undernote@par\wrap@undernote@par@styleB
   \def\hline@undernote@par{\mruleth[height=\noterulethickness@internal@undernote, width=\undernote@textlen@tempo, dash=true]}%
   \def\vlines@undernote@par{%
      \mruletv[height=\dimen@, width=\noterulethickness@internal@undernote, depth=0pt ,dash=true]%
      \mruleth[height=\noterulethickness@internal@undernote, width=\noterulehsize@internal@undernote, depth=0pt, dash=true]%
   }
   \else
      \let\wrap@undernote\wrap@undernote@styleC
      \let\wrap@undernote@par\wrap@undernote@par@styleC
      \def\hline@undernote@par{\mruleth[height=\noterulethickness@internal@undernote, width=\undernote@textlen@tempo]}%
      \def\vlines@undernote@par{%
         \mruletv[height=\dimen@, width=\noterulethickness@internal@undernote, depth=0pt]%
         \mruleth[height=\noterulethickness@internal@undernote, width=\noterulehsize@internal@undernote, depth=0pt]%
      }
\fi\fi

\newbox\@undernote@maintext
\newbox\@undernote@subtext
\newcounter{undernote@id} \setcounter{undernote@id}{0}
\DeclareDocumentCommand{\undernote}{ s O{} m +m O{} }{%
      %%% #1（star）注釈をparboxに包む
      %%% #2 (optinal): 注釈を下にずらす「行数」（与えない場合自動設定）
      %%% #3: 注釈をつける語句
      %%% #4: 注釈
      %%% #5: どういう線にするか
   \def\key@undernote@ruler{#5}%
   \settowidth{\undernote@textlen@tempo}{#3}%
   \begingroup%
   \stepcounter{undernote@id}%
   \ifmmode%
      \@note@save@conters%
      \savepos%
      \expandafter\@math@undernote%
   \else%
      \leavevmode%
      \savepos%
      \expandafter\@text@undernote%
   \fi%
   {#2}{#3}{%
      \ifnum\ltjgetparameter{direction}=4%
         \begin{varwidth}[t]{\maxdimen}%
            \IfBooleanTF{#1}{\wrap@undernote@par{#4}}{\wrap@undernote{#4}}%
         \end{varwidth}%
     \else%
         \raisebox{.38\zw}{%
            \begin{varwidth}[t]{\maxdimen}%
               \IfBooleanTF{#1}{\wrap@undernote@par{#4}}{\wrap@undernote{#4}}%
            \end{varwidth}%
         }%
     \fi%
     }%
   \endgroup}

% 名称カウンタ
\def\@note@save@conters{%
   \begingroup
   \def\@elt@udnote##1{%
      \expandafter\ifx\csname c@##1\endcsname\c@page\else
         \csname c@##1\endcsname\the\csname c@##1\endcsname\relax
      \fi}%
   \edef\@tempa{\cl@@ckpt}%
   \expandafter\endgroup
   \expandafter\def\expandafter\@note@restore@counters\expandafter{\@tempa}}

% 数式モードの場合への対応
\def\@math@undernote#1#2#3{%
   \mathchoice
      {\@note@restore@counters\@text@undernote{#1}{\m@th$\displaystyle #2$}{#3}}%
      {\@note@restore@counters\@text@undernote{#1}{\m@th$\textstyle #2$}{#3}}%
      {\@note@restore@counters\@text@undernote{#1}{\m@th$\scriptstyle #2$}{#3}}%
      {\@note@restore@counters\@text@undernote{#1}{\m@th$\scriptscriptstyle #2$}{#3}}}

% 注釈の内部実装
\long\def\@text@undernote#1#2#3{%
   \hbox{%
      \def\@UNDATA@vsize{#1}% \undernoteの第２引数
      \ifx\@UNDATA@vsize\@empty% 
            % 指定なしパターン
            % \undernoteの第２引数が空かそうでないか
         \expandafter\ifx\csname @UNDATAS@\the\c@undernote@id\endcsname\relax%
            % １回目のコンパイルではまだ空
            % →\relaxと比較してスルー
            \def\@UNDATA@vsize{1}%
         \else%
            % ２回目のコンパイルでは自動設定されている
            % →\@UNDATAS@12のようなデータを\@UNDATA@vsizeに格納
            \edef\@UNDATA@vsize{\csname @UNDATAS@\the\c@undernote@id\endcsname}%
         \fi%
      \fi%
      \setbox\@undernote@maintext\hbox{#2\vphantom{)}}% \undernoteの第３引数
      \setbox\@undernote@subtext\hbox{\notesize@internal@undernote #3}% \undernoteの第４引数
      \vtop{%
         \box\@undernote@maintext% 
         \begingroup%
            \notesize@internal@undernote% 
            \if@filesw% .auxへの書き出しokかどうか
               \dimen@\wd\@undernote@subtext%
               \advance\dimen@\notesep@internal@undernote\relax%
                     % 注釈の長さと、sepの長さを足す
                     % 水平方向にどれだけスペースをとっているか
               \edef\@tempa{%
                  \write\@auxout{% .auxへの書き出し
                     \string\undernotedata@internal{\the\c@undernote@id}%
                        {\noexpand\the\lastxpos}{\noexpand\the\lastypos}%
                        {\number\dimen@}{\number\ht\@undernote@subtext}{\number\dp\@undernote@subtext}%
                        {\noexpand\the\c@page}% これで.auxに
                                             % \undernotedata@internal{<id>}{<xpos>}{<ypos>}{<width of the note>}%
                                             % {<height of the note>}{<depth of the note>}{<page>}
                                             % が書き込まれる
                  }%
               }%
               \@tempa%
            \else%
               \write16{}% 書き出し不可の場合、何もしない
            \fi%
         \endgroup%
         \hline@undernote@par% アンダーライン
         \hbox{\notesize@internal@undernote% 
               % サイズ指定
            \hskip\noterulehshift@internal@undernote% 
               % 横に少しずらす
            \count@\@UNDATA@vsize\relax \advance\count@\m@ne% 
               % \count@ = 現在の段 - 1 
            \dimen@\noteshift@internal@undernote\relax \multiply\dimen@\count@%
               % \count@*\dimen@ i.e. 
               % ノートの縦幅だけ下へ
            \advance\dimen@\notepos@internal@undernote\relax% 
               % 縦線の長さの分さらに下へ
            \vlines@undernote@par%
               % 縦線を出力
            \hbox to \z@ {\lower.38\zw% 
                  % 注釈テキストを.38\zw下へ
               \box\@undernote@subtext\hss%
                  % 注釈配置
            }%
         }%
         \vskip .3\dimexpr\f@size pt\relax%
      }%
   }%
}

\newcount\@UNDATA@min
\newcount\@UNDATA@max
\global\@UNDATA@max -\@M
\global\let\@UNDATA@idlist\@empty
\let\@UNDATA@elt\relax
\def\undernotedata@internal#1#2#3#4#5#6#7{%%% #1: id, #2: xpos, #3: ypos, #4: width of the note,
                                          %%% #5: height of the note, #6: depth of the note, #7: page
   \@ifundefined{@UNDATA@#1}%
      {\@tempcnta\@UNDATA@max \advance\@tempcnta\@ne%
         % 連番チェック
       \ifnum\@tempcnta=#1\relax%
          \global\@UNDATA@max\@tempcnta%
       \else%
          \ifnum\@UNDATA@max<\z@\else % 
               % 最初はmaxが-10000なので
               % 必ずこの分岐に入り
               % idlistが作られる
             \xdef\@UNDATA@idlist{\@UNDATA@idlist\@UNDATA@elt{\the\@UNDATA@min}{\the\@UNDATA@max}}%
               % １回目では\relaxが入ってるので
               % 残って２回目へ
          \fi%
          \global\@UNDATA@min=#1\relax%
          \global\@UNDATA@max\@UNDATA@min%
       \fi}%
      {\gdef\@multiplelabels{\@latex@warning@no@line{There were multiply-defined labels}}%
       \@latex@warning@no@line{Note ID `#1' multiply appeared}%
      }%
   \global\@namedef{@UNDATA@#1}{{#2}{#3}{#4}{#5}{#6}{#7}}%
      % データを.aux用に格納
}

\def\@undernotedata#1#2#3#4#5#6#7{%
   \def\@tempa{{#2}{#3}{#4}{#5}{#6}{#7}}%
   \expandafter\ifx\csname @UNDATA@#1\endcsname\@tempa\else \@tempswatrue \fi%
}

\def\checkundernotedata{%
   \ifnum\@UNDATA@max<\z@\else%
      \xdef\@UNDATA@idlist{\@UNDATA@idlist\@UNDATA@elt{\the\@UNDATA@min}{\the\@UNDATA@max}}%
      \begingroup%
         \let\@UNDATA@elt\@check@undernotedata%
         \@UNDATA@idlist%
      \endgroup%
   \fi%
}

\def\@check@undernotedata#1#2{%
   \def\@currpage{-10000}%
   \@tempcnta\z@ \@tempcntb\z@%
   \@tempdima-\p@ \@tempdimb-\p@%
   \let\@linelist\@empty%
   \let\@elt@udnote\relax%
   \count@#1\relax %
   \advance\count@\m@ne%
   \@whilenum\count@<#2\do{%
      \advance\count@\@ne%
      \@check@undernotedata@split\count@%
      \def\@tempz{T}%
      \ifnum\@currpage=\@thispage\relax%
         \ifdim\@thisy sp<\@tempdima \def\@tempz{F}\fi%
         \ifdim\@thisy sp>\@tempdimb \def\@tempz{F}\fi%
      \else%
         \def\@tempz{F}%
      \fi%
      \if T\@tempz\relax%
         \@tempcntb\count@%
      \else%
         \ifnum\@tempcnta>\z@%
            \edef\@linelist{\@linelist\@elt@udnote{\the\@tempcnta}{\the\@tempcntb}}%
         \fi%
         \@tempcnta\count@ \@tempcntb\count@%
         \let\@currpage\@thispage%
         \@tempdima\@thisy sp\relax%
         \@tempdimb\@tempdima%
         \advance\@tempdima -\@UNDATA@yfuzz\relax%
         \advance\@tempdimb  \@UNDATA@yfuzz\relax%
      \fi}%
   \edef\@linelist{\@linelist\@elt@udnote{\the\@tempcnta}{\the\@tempcntb}}%
   \let\@elt@udnote\@check@undernotedata@elt%
   \@linelist%
}

\def\@UNDATA@yfuzz{3\p@}

\def\@check@undernotedata@split#1{%
   \expandafter\expandafter\expandafter\@check@undernotedata@split@%
      \csname @UNDATA@\number#1\endcsname 000000\@nnil%
}

\def\@check@undernotedata@split@#1#2#3#4#5#6#7\@nnil{%
   \def\@thisx{#1}%
   \def\@thisy{#2}%
   \def\@thiswd{#3}%
   \def\@thisht{#4}%
   \def\@thisdp{#5}%
   \def\@thispage{#6}%
}

\def\@check@undernotedata@elt#1#2{%
   \count@#2\relax%
   \advance\count@\@ne%
   \@whilenum\count@>#1\do{%
      \advance\count@\m@ne%
      \@check@undernotedata@split\count@%
      \dimen@\@thisx sp\relax%
      \advance\dimen@ \@thiswd sp\relax%
      \advance\dimen@\noterulehsize@internal@undernote\relax%
      \advance\dimen@\p@%
      \let\@currht\@thisht%
      \@tempcntb\@ne%
      \@tempcnta\count@%
      \@whilenum\@tempcnta<#2\do{%
         \advance\@tempcnta\@ne%
         \@check@undernotedata@split\@tempcnta%
         \ifdim\@thisx sp<\dimen@%
            \@tempdima\noteshift@internal@undernote\relax%
            \@tempdimb\@thisdp sp\relax%
            \advance\@tempdimb\@currht sp\relax%
            \advance\@tempdimb\lineskip%
            \divide\@tempdimb\@tempdima%
            \count\tw@\@tempdimb%
            \advance\count\tw@ \@ne%
            \advance\count\tw@\@nameuse{@UNDATAS@\the\@tempcnta}\relax%
            \ifnum\@tempcntb<\count\tw@ \@tempcntb\count\tw@ \fi%
         \fi%
      }%
      \expandafter\xdef\csname @UNDATAS@\the\count@\endcsname{\the\@tempcntb}%
   }%
}

\AtEndDocument{%
   \if@filesw%
      \write\@auxout{\string\checkundernotedata}%
      \let\checkundernotedata\relax%
      \def\undernotedata@internal{\@undernotedata}%
   \fi%
}

\endinput