% OPmac
%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Petr Olsak, 2012 -- 2016

%% The history of versions is at the end of this file, after \endpinput

\ifx\OPmacversion\undefined \else \endinput \fi
\def\OPmacversion{Mar. 2018a}  
\immediate\write16{This is OPmac (Olsak's Plain macros), version <\OPmacversion>}

%%%%%%%%%%%%%% Basic macros, sec. 3.1 in opmac-d.pdf

\newcount\tmpnum % auxiliary count
\newdimen\tmpdim % auxiliary dimen

\def\opwarning#1{\immediate\write16{l.\the\inputlineno\space OPmac WARNING: #1.}}

\long\def\addto#1#2{\expandafter\def\expandafter#1\expandafter{#1#2}}

\def\protectlist{}
\def\addprotect#1{\addto\protectlist{\doprotect#1}}
\addprotect~

\ifx\pdfextension\undefined \else 
   \let\pdfoutput=\outputmode \def\pdfcolorstackinit{\pdffeedback colorstackinit}\fi

\newif\ifpdftex  \pdftextrue
\ifx\pdfoutput\undefined \pdftexfalse \else \ifnum\pdfoutput=0 \pdftexfalse \fi \fi
\ifx\XeTeXversion\undefined \else \pdftextrue \fi

\def\sdef#1{\expandafter\def\csname#1\endcsname}
\def\sxdef#1{\expandafter\xdef\csname#1\endcsname}
\def\slet#1#2{\expandafter\let\csname#1\expandafter\endcsname\csname#2\endcsname}

\def\adef#1{\catcode`#1=13 \begingroup \lccode`\~=`#1\lowercase{\endgroup\def~}}

\def\isdefined #1#2{\expandafter\ifx \csname#1\endcsname \relax
     \csname iffalse\expandafter\endcsname
   \else
     \csname iftrue\expandafter\endcsname
   \fi
}
\long\def\isinlist#1#2#3{\begingroup \long\def\tmp##1#2##2\end{\def\tmp{##2}%
   \ifx\tmp\empty \endgroup \csname iffalse\expandafter\endcsname \else
                  \endgroup \csname iftrue\expandafter\endcsname \fi}% end of \def\tmp
   \expandafter\tmp#1\endlistsep#2\end
}
\long\def\isnextchar#1#2#3{\begingroup\toks0={\endgroup#2}\toks1={\endgroup#3}%
   \let\tmp=#1\futurelet\next\isnextcharA
}
\def\isnextcharA{\the\toks\ifx\tmp\next0\else1\fi\space}

\def\eoldef#1{\def#1{\begingroup \catcode`\^^M=12 \eoldefA#1}%
   \expandafter\def\csname\string#1:M\endcsname}
{\catcode`\^^M=12 \gdef\eoldefA#1#2^^M{\endgroup\csname\string#1:M\endcsname{#2}}}

\def\maybebreak{\afterassignment\maybebreakA\tmpdim=}
\def\maybebreakA{\ifvmode \vskip0pt plus\tmpdim \penalty-130 \vskip0pt plus-\tmpdim 
    \else \hskip0pt plus\tmpdim \penalty-130 \hskip0pt plus-\tmpdim \fi \relax
}
\long\def\uv#1{\clqq#1\crqq}
\let\\=\undefined
{\lccode`\?=`\%  \lowercase{\gdef\percent{?}}}
{\lccode`\?=`\\  \lowercase{\gdef\bslash{?}}}
\def\,{\relax\ifmmode \mskip\thinmuskip \else \thinspace \fi}
\addprotect\percent \addprotect\bslash \addprotect\, \addprotect\exfont

\bgroup \catcode`!=3 \catcode`?=3
\gdef\replacestrings#1#2{\long\def\replacestringsA##1#1{\def\tmpb{##1}\replacestringsB}%
   \long\def\replacestringsB##1#1{\ifx!##1\relax \else\addto\tmpb{#2##1}%
      \expandafter\replacestringsB\fi}%     improved version <May 2016> inspired 
   \expandafter\replacestringsA\tmpb?#1!#1% from pysyntax.tex by Petr Krajnik
   \long\def\replacestringsA##1?{\def\tmpb{##1}}\expandafter\replacestringsA\tmpb
}
\egroup

%%%%%%%%%%%%%% Global parameters, sec. 3.2 in opmac-d.pdf

\widowpenalty=10000
\clubpenalty=10000
\showboxdepth=7
\showboxbreadth=30

\newdimen\iindent  \iindent=\parindent
   % indentation of items, TOC, captions, list of bib. references
\newdimen\ttindent \ttindent=\parindent
   % indentation in \begtt...\endtt and \verbinput

\def\ttskip{\medskip}       % space above and below \begtt, \verbinput
\mathchardef\ttpenalty=100  % penalty between lines in \begtt, \verbinput
\def\tthook{}               % hook in \begtt, \verbinput
\def\intthook{}             % hook in in-text verbatim
\def\ptthook{}              % hook in \begtt, \verbinput for post-processing 

\def\iiskip{\medskip}     % space above and below \begitems...\enditems
\def\itemhook{}           % hook in \startitem
\def\bibskip{\smallskip}  % space between bibitems

\def\tabstrut{\strut}     % strut in the \table
\def\tabiteml{\enspace}   % left material before each \table item
\def\tabitemr{\enspace}   % right material after each \table item
\def\vvkern{1pt}          % space between vertical lines
\def\hhkern{1pt}          % space between horizontal lines

\def\multiskip{\medskip}      % space above and below \begmulti...\endmulti
\newdimen\colsep \colsep=2em  % space between columns

\newdimen\mnoteindent \mnoteindent=10pt % ditance between mnote and text
\newdimen\mnotesize   \mnotesize=20mm   % the width of the mnote paragraph

\def\picdir{}      % the directory with picture files
\def\bibtexhook{}  % hook in \usebibtex and \usebbl macros
\def\chaphook{}    % hook in \chap
\def\sechook{}     % hook in \sec
\def\secchook{}    % hook in \secc
\def\cnvhook{}     % hook before conversion of outlines
\def\prepghook{}   % hook before page building in \output routine
\def\pghook{}      % next hook in \output routine
\def\toclinehook{} % hook in \tocline
\def\fnotehook{}   % hook in \fnote
\def\mnotehook{}   % hook in \mnote
\def\captionhook#1{} % hook in \caption (#1 is "t" or "f")

%%%%%%%%%%%%%% OPmac, CSplain and LaTeX logos, sec. 3.3 in opmac-d.pdf

\def\OPmac{\leavevmode
   \lower.2ex\hbox{\thefontscale[1400]O}\kern-.86em P{\em mac}}
\def\CS{$\cal C$\kern-.1667em\lower.5ex\hbox{$\cal S$}}
\def\csplain{\CS plain}

\def\LaTeX{\tmpdim=.42ex L\kern-.36em \kern\slantcorr % slant correction
  \raise\tmpdim\hbox{\thefontscale[710]A}%
  \kern-.15em \kern-\slantcorr \TeX}
\def\slantcorr{\expandafter\ignorept\the\fontdimen1\the\font\tmpdim}

\addprotect\TeX   \addprotect\OPmac   \addprotect\CS  \addprotect\LaTeX


%%%%%%%%%%%%%% Sizes of fonts and \baselineskip, sec. 3.4 in opmac-d.pdf

\ifx\regfont\undefined
   \ifx\uselanguage\undefined % if this is etex.src, the following warning is suppressed
      \opwarning{No multilanguage support (csplain is recommended)}
   \fi
   % macros from csplain, file csfontsm.tex:
   \ifx\tenbi\undefined \font\tenbi=cmbxti10 \def\bi{\tenbi}\fi
   \def\letfont#1#2{\ifx#2=\expandafter\letfont\expandafter#1\else
     \expandafter\font\expandafter#1\expandafter\rfontskipat\fontname#2 \relax\space \fi}
   \def\rfontskipat#1{\ifx#1"\expandafter\rfskipatX\else\expandafter\rfskipatN\expandafter#1\fi}
   \def\rfskipatX #1" #2\relax{"\whichtfm{#1}"}  \def\rfskipatN #1 #2\relax{\whichtfm{#1}}
   \def\sizespec{}   \def\whichtfm#1{#1}
   \def\resizefont#1{\letfont#1#1\sizespec}
   \def\regfont#1{\expandafter\def\expandafter\resizeall\expandafter{\resizeall \resizefont#1}}
   \def\resizeall{}
   \regfont\tenrm \regfont\tenit \regfont\tenbf \regfont\tenbi \regfont\tentt
\fi

\newdimen\ptunit    \ptunit=1pt
\newdimen\fontdim   \fontdim=10pt

\ifx\normalmath\undefined \input ams-math \fi  % ams-math.tex is in csplain package

{\lccode`\?=`\p \lccode`\!=`\t  \lowercase{\gdef\ignorept#1?!{#1}}}

\def\typosize[#1/#2]{\fontsizex[#1]\setbaselineskip[#2]\ignorespaces}
\def\typoscale[#1/#2]{\fontscalex[#1]\scalebaselineskip[#2]\ignorespaces}

\def\fontsizex[#1]{\if$#1$\else
  \textfontsize[#1]%
  \tmpdim=0.7\fontdim \edef\tmpa{\expandafter\ignorept\the\tmpdim}%
  \tmpdim=0.5\fontdim \edef\tmpb{\expandafter\ignorept\the\tmpdim}%
  \edef\tmp{\noexpand\setmathsizes[\expandafter\ignorept\the\fontdim/\tmpa/\tmpb]}%
  \tmp \normalmath
  \fi
}
\def\textfontsize[#1]{\if$#1$\else
  \fontdim=#1\ptunit \ifx\fontdimB\undefined \edef\fontdimB{\the\fontdim}\fi
  \let\dgsize=\fontdim
  \edef\sizespec{at\the\fontdim}%
  \resizeall \rm \let\dgsize=\undefined
  \fi
}
\def\setbaselineskip[#1]{\if$#1$\else
  \tmpdim=#1\ptunit
  \baselineskip=\tmpdim \relax 
  \ifx\baselineskipB\undefined \edef\baselineskipB{\the\baselineskip}\fi
  \bigskipamount=\tmpdim plus.33333\tmpdim minus.33333\tmpdim
  \medskipamount=.5\tmpdim plus.16666\tmpdim minus.16666\tmpdim
  \smallskipamount=.25\tmpdim plus.08333\tmpdim minus.08333\tmpdim
  \normalbaselineskip=\tmpdim
  \jot=.25\tmpdim
  \maxdepth=.33333\tmpdim
  \setbox\strutbox=\hbox{\vrule height.709\tmpdim depth.291\tmpdim width0pt}%
  \fi
}
\def\withoutunit#1#2{\expandafter#1\expandafter[\expandafter\ignorept\the#2]}

\def\fontscalex[#1]{\if$#1$\else \ifnum#1=1000 \else
  \tmpdim=3277sp \tmpdim=#1\tmpdim \divide\tmpdim by50
  \tmpdim=\expandafter\ignorept\the\tmpdim \fontdim
  \withoutunit\fontsizex\tmpdim
  \fi\fi
}
\def\textfontscale[#1]{\if$#1$\else
  \tmpdim=#1pt \divide\tmpdim by1000
  \tmpdim=\expandafter\ignorept\the\tmpdim \fontdim
  \withoutunit\textfontsize\tmpdim
  \fi
}
\def\scalebaselineskip[#1]{\if$#1$\else \ifnum#1=1000 \else
  \tmpdim=3277sp \tmpdim=#1\tmpdim \divide\tmpdim by50
  \tmpdim=\expandafter\ignorept\the\tmpdim \baselineskip
  \withoutunit\setbaselineskip\tmpdim
  \fi\fi
}
\def\thefontsize[#1]{\fontdim=#1\ptunit
  \expandafter\let \expandafter\thefont \the\font
  \edef\sizespec{at#1\ptunit}\def\dgsize{#1\ptunit}\resizefont\thefont
  \thefont \let\dgsize=\undefined \ignorespaces
}
\def\thefontscale[#1]{%
  \tmpdim=#1pt \divide\tmpdim by1000
  \tmpdim=\expandafter\ignorept\the\tmpdim \fontdim
  \withoutunit\thefontsize\tmpdim
}
\def\magstep#1{\ifcase#1 1000\or1200\or1440\or1728\or2074\or2488\fi\space}

\def\typobase{\ifx\baselineskipB\undefined \def\baselineskipB{12pt}\fi
   \ifx\fontdimB\undefined \def\fontdimB{10pt}\fi
   \baselineskip=\baselineskipB\relax \fontdim=\fontdimB\relax
}
\def\em {\expandafter\ifx \the\font \tenit \additcorr \rm  \else
         \expandafter\ifx \the\font \tenbf \bi\aftergroup\afteritcorr\else
         \expandafter\ifx \the\font \tenbi \additcorr \bf  \else
         \it \aftergroup\afteritcorr\fi\fi\fi}
\def\additcorr{\ifdim\lastskip>0pt \skip0=\lastskip \unskip\/\hskip\skip0 \else\/\fi}
\def\afteritcorr{\def\tmp{\ifx\next..\else\ifx\next,,\else\/%
                          \expandafter\expandafter\expandafter\next\expandafter\fi\fi}%
   \afterassignment\tmp \let\next= }

\addprotect\thefontsize   \addprotect\thefontscale
\addprotect\typosize      \addprotect\typoscale
\addprotect\textfontsize  \addprotect\textfontscale
\addprotect\em

\def\fontfam{\par \input fontfam \fontfam}

%%%%%%%%%%%%%% Multilingual support, sec. 3.5 in opmac-d.pdf

\def\mtext#1{\csname mt:#1:\csname lan:\the\language\endcsname\endcsname}

\sdef{mt:chap:en}{Chapter}  \sdef{mt:chap:cs}{Kapitola}  \sdef{mt:chap:sk}{Kapitola}
\sdef{mt:t:en}{Table}       \sdef{mt:t:cs}{Tabulka}      \sdef{mt:t:sk}{Tabu\v lka}
\sdef{mt:f:en}{Figure}      \sdef{mt:f:cs}{Obr\'azek}    \sdef{mt:f:sk}{Obr\'azok}

\ifx\r\undefined \csname csaccents\endcsname \fi

\sdef{lan:0}{en}  \sdef{lan:100}{en} \sdef{lan:101}{en}
\sdef{lan:5}{cs}  \sdef{lan:15}{cs}  \sdef{lan:115}{cs}
\sdef{lan:6}{sk}  \sdef{lan:16}{sk}  \sdef{lan:116}{sk}

\ifx\uselanguage\undefined \def\isolangset#1#2{}\else 
  \message{OPmac: etex.src macros detected}
  \def\isolangset#1#2{{\uselanguage{#1}\sxdef{lan:\the\language}{#2}%
      \global\expandafter\chardef\csname#2Patt\endcsname=\language}}
  \isolangset{USenglish}{en} \isolangset{czech}{cs} \isolangset{slovak}{sk}
\fi

%%%%%%%%%%%%%% REF file, sec 3.6 in opmac-d.pdf

\newwrite\reffile
\newread\testin

\def\wrefrelax#1#2{}
\let\wref=\wrefrelax

\def\inputref{
  \openin\testin=\jobname.ref
  \ifeof\testin \else
    \closein\testin
    \input \jobname.ref
    \fnotenum=0 \mnotenum=0
    \openrefA{\string\inputref}%
  \fi
}
\def\openref{%
  \ifx\wref\wrefrelax \openrefA{\string\openref}\fi
  \gdef\openref{}%
}
\def\openrefA#1{%
   \immediate\openout\reffile=\jobname.ref
   \gdef\wref##1##2{\write\reffile{\string##1##2}}%
   \immediate\write\reffile {\percent\percent\space OPmac - REF file (#1)}%
   \immediate\wref\Xrefversion{{\REFversion}}%
}
\def\REFversion{2}
\def\Xrefversion#1{\ifnum#1=\REFversion\relax \else \endinput \fi}

%%%%%%%%%%%%%% \label, \ref, \pgref, sec. 3.7 in opmac-d.pdf

\def\label[#1]{\isdefined{l0:#1}%
  \iftrue \opwarning{duplicated label [#1], ignored}\else \xdef\lastlabel{#1}\fi
  \ignorespaces}

\def\wlabel#1{%
  \ifx\lastlabel\undefined \else
     \dest[ref:\lastlabel]%
     \edef\tmp{\wref\Xlabel{{\lastlabel}{#1}}}\tmp
     \sxdef{lab:\lastlabel}{#1}\sxdef{l0:\lastlabel}{}%
     \global\let\lastlabel=\undefined
  \fi
}
\def\ref[#1]{\isdefined{lab:#1}%
  \iftrue \reflink[#1]{\csname lab:#1\endcsname}%
  \else ??\opwarning{label [#1] unknown. Try to TeX me again}\openref
  \fi
}
\def\pgref[#1]{\isdefined{pgref:#1}%
  \iftrue \pglink{\csname pgref:#1\endcsname}%
  \else ??\opwarning{pg-label [#1] unknown. Try to TeX me again}\openref
  \fi
}
\def\Xlabel#1#2{\sxdef{lab:#1}{#2}\sxdef{pgref:#1}{\the\lastpage}}

%%%%%%%%%%%%%% Chapters, sections, subsections -- sec. 3.8 in opmac-d.pdf

\def\printchap#1{\vfil\break
  {\chapfont \noindent \mtext{chap} \dotocnum{\thetocnum}\par
   \nobreak\smallskip\noindent #1\nbpar}\mark{}%
  \nobreak \remskip\bigskipamount \firstnoindent
}
\def\printsec#1{\par \norempenalty-400 \bigskip
  {\secfont \noindent \dotocnum{\thetocnum\quad}#1\nbpar}\insertmark{#1}%
  \nobreak \remskip\medskipamount \firstnoindent
}
\def\printsecc#1{\par \norempenalty-200 \medskip
  {\seccfont \noindent \dotocnum{\thetocnum\quad}#1\nbpar}%
  \nobreak \remskip\medskipamount \firstnoindent
}
\eoldef\tit#1{\vglue4em
  {\leftskip=0pt plus1fill \rightskip=\leftskip
   \titfont \noindent #1\par}%
   \nobreak\bigskip
}
\def\titfont{\typobase\typoscale[\magstep4/\magstep4]\bfshape}
\def\chapfont{\typobase\typoscale[\magstep3/\magstep3]\bfshape}
\def\secfont{\typobase\typoscale[\magstep2/\magstep2]\bfshape}
\def\seccfont{\typobase\typoscale[\magstep1/\magstep1]\bfshape}
\def\bfshape{\let\tenit=\tenbi \everymath\expandafter{\the\everymath\boldmath}\bf}

\newcount\chapnum \newcount\secnum \newcount\seccnum \newcount\nonumnum
\newif\ifnotoc \notocfalse  \def\notoc{\global\notoctrue}
\newif\ifnonum \nonumfalse  \def\nonum{\global\nonumtrue}

\eoldef\chap#1{\ifnonum\else \global\advance\chapnum by1 \fi
  \chaphook {\globaldefs=1 \secnum=0 \seccnum=0 \tnum=0 \fnum=0 \dnum=0}\relax
  \edef\thechapnum{\the\chapnum}\let\thetocnum=\thechapnum 
  \def\dotocnumafter{\wtotoc0\bfshape{#1}}%
  \printchap{#1}\resetnonumnotoc
}
\eoldef\sec#1{\ifnonum\else \global\advance\secnum by1 \fi
  \sechook {\globaldefs=1 \seccnum=0 \tnum=0 \fnum=0 \dnum=0}\relax
  \edef\thesecnum{\othe\chapnum.\the\secnum}\let\thetocnum=\thesecnum 
  \def\dotocnumafter{\wtotoc1\rm{#1}}% 
  \printsec{#1}\resetnonumnotoc
}
\eoldef\secc#1{\ifnonum\else \global\advance\seccnum by1 \fi
  \secchook {}\relax
  \edef\theseccnum{\othe\chapnum.\the\secnum.\the\seccnum}\let\thetocnum=\theseccnum
  \def\dotocnumafter{\wtotoc2\rm{#1}}%
  \printsecc{#1}\resetnonumnotoc
}
\def\wtotoc#1#2#3{% #1 = level, #2 = info, #3 = titletext
  \ifnotoc\else
      \def\act{\wref{\Xtoc{#1}{\noexpand#2}}}%
      \expandafter\act\expandafter{\expandafter{\thetocnum}{#3}{\the\pageno}}%
  \fi
}
\def\wcontents#1#2{% #1 = sequence to REF, #2 = titletext
  \ifnotoc\else
      \expandafter\wref\expandafter#1\expandafter
        {\expandafter{\thetocnum}{#2}{\the\pageno}}%
  \fi
}
\def\dotocnum#1{%
  \leavevmode 
     {\ifnonum \global\advance\nonumnum by1 \edef\thetocnum{!\the\nonumnum}\fi
      \wlabel\thetocnum \dest[toc:\tocilabel.\thetocnum]%
      \dotocnumafter}\ifnonum\else#1\fi
  \global\let\dotocnumafter=\relax
}
\def\resetnonumnotoc{\global\notocfalse \global\nonumfalse
  \ifx\dotocnumafter\relax \else
    \opwarning{\noexpand\dotocnum unused in printchap/printsec/printsecc}\fi
}
\def\insertmark#1{\toks0={#1}\mark{{\ifnonum\else\thetocnum\fi} {\the\toks0}}}

\newskip\remskipamount
\def\remskip{\afterassignment\remskipA \global\remskipamount}
\def\remskipA{\vskip\remskipamount \penalty11333 }
\def\norempenalty{\ifnum\lastpenalty=11333 
   \vskip-\remskipamount \tmpnum=\else \removelastskip \penalty \fi}

\def\othe#1.{\ifnum#1>0 \the#1.\fi}
\def\thechapnum{} \def\thesecnum{} \def\theseccnum{}

\def\afternoindent{\global\everypar={\wipeepar\setbox7=\lastbox}}
\def\wipeepar{\global\everypar={}}
\let\firstnoindent=\afternoindent
\def\nbpar{{\interlinepenalty=10000\endgraf}}
\def\nl{\hfil\break}

%%%%%%%%%%%%%% Captions, equations -- sec. 3.9 in opmac-d.pdf

\newcount\tnum  \newcount\fnum   \newcount\dnum

\def\thetnum{\thesecnum.\the\tnum}
\def\thefnum{\thesecnum.\the\fnum}
\def\thednum{(\the\dnum)}

\def\caption/#1 {\isdefined{#1num}%
   \iftrue \global\advance \csname #1num\endcsname by1
   \else   \opwarning{Unknown caption /#1}%
   \fi
   \bgroup
      \leftskip=\iindent plus1fil
      \rightskip=\iindent plus-1fil
      \parfillskip=0pt plus2fil
      \def\par{\nbpar\egroup}%
      \captionhook{#1}\noindent 
      \wlabel{\csname the#1num\endcsname}%
      \printcaption{\mtext{#1}}{\csname the#1num\endcsname}%
}
\def\printcaption#1#2{{\bf#1 #2}\enspace}

\expandafter\def\expandafter\endinsert\expandafter{\expandafter\par\endinsert}

\def\eqmark{\global\advance\dnum by1
  \ifinner\else\eqno \fi 
  \wlabel\thednum \thednum
}

%%%%%%%%%%%%%% Items -- sec. 3.10 in opmac-d.pdf

\newcount\itemnum  \itemnum=0

\def\begitems{\par\iiskip\bgroup
  \itemnum=0 \adef*{\startitem}
  \advance\leftskip by\iindent
  \let\printitem=\normalitem
}
\def\enditems{\par\egroup\iiskip}

\def\startitem{\par \advance\itemnum by1
   \itemhook \noindent\llap{\printitem}\ignorespaces}
\def\normalitem{$\bullet$\enspace}

\def\style#1{\expandafter\let\expandafter\printitem\csname item:#1\endcsname
  \ifx\printitem\relax \let\printitem=\normalitem \fi
}
\sdef{item:o}{\raise.4ex\hbox{$\scriptscriptstyle\bullet$} }
\sdef{item:-}{- }
\sdef{item:n}{\the\itemnum. }
\sdef{item:N}{\the\itemnum) }
\sdef{item:i}{(\romannumeral\itemnum) }
\sdef{item:I}{\uppercase\expandafter{\romannumeral\itemnum}\kern.5em}
\sdef{item:a}{\athe\itemnum) }
\sdef{item:A}{\uppercase\expandafter{\athe\itemnum}) }
\sdef{item:x}{\raise.3ex\fullrectangle{.6ex} }
\sdef{item:X}{\raise.2ex\fullrectangle{1ex}\kern.5em}

\def\fullrectangle#1{\hbox{\vrule height#1 width#1}}

\def\athe#1{\ifcase#1?\or a\or b\or c\or d\or e\or f\or g\or h\or i\or j\or k\or l\or 
   m\or n\or o\or p\or q\or r\or s\or t\or u\or v\or w\or x\or y\or z\else ?\fi
}

%%%%%%%%%%%%%% TOC -- sec. 3.11 in opmac-d.pdf

\def\toclist{} \newif\ifischap \ischapfalse

\def\Xtoc#1#2#3#4#5{\ifnum#1=0 \ischaptrue\fi \addto\toclist{\tocline{#1}{#2}{#3}{#4}{#5}}}
\def\Xchap{\Xtoc0\bfshape} \def\Xsec{\Xtoc1\rm} \def\Xsecc{\Xtoc2\rm}

\def\tocline#1#2#3#4#5{{\leftskip=#1\iindent \rightskip=2\iindent
   \ifischap\advance\leftskip by\iindent\fi
   \ifnum#1>1 \advance\leftskip by\iindent\fi
   \toclinehook \noindent\llap{#2\toclink{#3}\enspace}%
         {#2#4}\nobreak\tocdotfill\pglink{#5}\nobreak\hskip-2\iindent\null\par}}
\def\tocdotfill{\leaders\hbox to.8em{\hss.\hss}\hskip 1em plus1fill\relax}

\def\maketoc{\par \ifx\toclist\empty
      \opwarning{\noexpand\maketoc -- data unavailable, TeX me again}\openref
   \else \toclist \fi}

\def\toclinkA#1{\def\tmp##1!##2\end{\if^##1^\kern.8em \else##1\fi}\tmp#1!\end}

%%%%%%%%%%%%%% Index -- sec. 3.12 on opmac-d.pdf

\def\iindex#1{\openref\wref\Xindex{{#1}{\the\pageno}}}

\def\ii #1 {\leavevmode\def\tmp{#1}\iiA #1,,}

\def\iiA #1,{\if$#1$\else\def\tmpa{#1}%
   \ifx\tmpa\iiatsign \expandafter\iiB\tmp,,\else\iindex{#1}\fi
   \expandafter\iiA\fi}
\def\iiatsign{@}

\def\iiB #1,{\if$#1$\else \iiC#1/\relax \expandafter\iiB\fi}
\def\iiC #1/#2\relax{\if$#2$\else\iindex{#2#1}\fi}

\def\iid #1 {\leavevmode\iindex{#1}#1\futurelet\tmp\iiD}
\def\iiD{\ifx\tmp,\else\ifx\tmp.\else\space\fi\fi}

\def\Xindex{\Xindexg,}
\def\Xindexg#1#2#3{\bgroup \def~{ }% #1=prefix, #2=index-item, #3=pageno
   \isdefined{#1#2}\iftrue
      \ifx^#3^\else
         \expandafter\firstdata \csname#1#2\endcsname \XindexA
         \ifnum#3=\tmpa % \ii on the same page
         \else
            \tmpnum=#3 \advance\tmpnum by\pgfolioB-1
            \expandafter\seconddata \csname#1#2\endcsname \XindexB
            \ifx\tmp\empty
               \sxdef{#1#2}{{#3/+}{\pgfolioA{#3}}} % previous item: empty page 
            \else
               \if\tmpb+% state: the pagelist ends by a pagenumber
                  \ifnum\tmpnum=\tmpa  % the consecutive page
                     \sxdef{#1#2}{{#3/-}{\tmp\iiendash}}
                  \else                % the pages drop
                     \sxdef{#1#2}{{#3/+}{\tmp, \pgfolioA{#3}}}
                  \fi
               \else    % state: the pagelist ends by --
                  \ifnum\tmpnum=\tmpa  % the consecutive page
                     \sxdef{#1#2}{{#3/-}{\tmp}}
                  \else                % the pages drop
                     \sxdef{#1#2}{{#3/+}{\tmp\pgfolioA{\tmpa}, \pgfolioA{#3}}}
      \fi\fi\fi\fi\fi
   \else % first occurrence of the index item #2
      \ifx^#3^\sxdef{#1#2}{{0/+}{}}\else \sxdef{#1#2}{{#3/+}{\pgfolioA{#3}}}\fi
      \ifx,#1
         \global \expandafter\addto \expandafter\iilist \csname#1#2\endcsname
      \else
         \isdefined{iilist:#1}\iftrue
            \global\expandafter\addto \csname iilist:#1\expandafter\endcsname \csname#1#2\endcsname
         \else \sxdef{iilist:#1}{\expandafter\noexpand \csname#1#2\endcsname}
   \fi\fi\fi
   \egroup
}
\def\iilist{} \def\iiendash{--}

\def\firstdata#1#2{\expandafter\expandafter\expandafter #2\expandafter\firstdataA#1}
\def\firstdataA#1#2{#1&}
\def\seconddata#1#2{\expandafter\expandafter\expandafter #2\expandafter\seconddataA#1}
\def\seconddataA#1#2{#2&}

\def\XindexA#1/#2&{\def\tmpa{#1}\let\tmpb=#2}
\def\XindexB#1&{\def\tmp{#1}}

\def\pgfolioA#1{\ifnum#1<0 \romannumeral-\fi#1}
\def\pgfolioB{\ifnum\tmpnum<0-\fi}

\def\makeindex{\par
  \ifx\iilist\empty \opwarning{index data-buffer is empty. TeX me again}
    \else
    \bgroup
       \setprimarysorting
       \def\act##1{\ifx##1\relax \else
          \firstdata##1\XindexA \seconddata##1\XindexB
          \if\tmpb+%
             \preparesorting##1% converted item by sorting data in \tmpb
             \xdef##1{{\tmpb}{\tmp}}
          \else
             \preparesorting##1% converted item by sorting data in \tmpb
             \xdef##1{{\tmpb}{\tmp\pgfolioA{\tmpa}}}
          \fi
          \expandafter\act\fi}
       \expandafter \act \iilist \relax
    \egroup
    \dosorting  % sorting is in progress
    \bgroup
       \rightskip=0pt plus1fil \exhyphenpenalty=10000 \leftskip=\iindent
       \def\act##1{\ifx##1\relax \else \prepii##1%
                \seconddata##1\printiipages \expandafter\act \fi}
       \expandafter \act \iilist \relax
    \egroup
  \fi
}
\def\printiipages#1&{ #1\par}

\def\prepii #1{\isinlist \iispeclist #1\iftrue
   \expandafter\expandafter\expandafter \printii \csname\string#1\endcsname&%
   \else \expandafter\prepiiA\string #1&%
   \fi
}
\def\prepiiA #1#2#3&{\printii#3&}

\def\iis #1 #2{\bgroup \def~{ }%
    \global\expandafter\addto\expandafter\iispeclist\csname,#1\endcsname
    \global\sdef{\expandafter\string\csname,#1\endcsname}{#2}%
  \egroup \ignorespaces
}
\def\iispeclist{}

\def\printii #1&{\gdef\currii{#1}\noindent\everyii
   \hskip-\iindent \ignorespaces\printiiA#1//}
\def\printiiA #1/{\if^#1^\let\previi=\currii \else
   \expandafter\scanprevii\previi/&\def\tmpb{#1}\edef\tmpb{\meaning\tmpb}%
   \ifx\tmpa\tmpb \iiemdash \else#1 \gdef\previi{}\fi
   \expandafter\printiiA\fi
}
\def\iiemdash{\kern.1em---\space}
\def\everyii{}

\def\scanprevii#1/#2&{\def\previi{#2}\def\tmpa{#1}\edef\tmpa{\meaning\tmpa}}
\def\previi{} % previous index item

%%%%%%%%%%%%%% Sorting -- sec. 3.13 in opmac-d.pdf

\def\sortingdata{%
  /,{ },-,&,@,%
  aA\"a\"A\'a\'A,%
  bB,%
  cC,%
  \v c\v C,%
  dD\v d\v D,%
  eE\'e\'E\v e\v E,%
  fF,%
  gG,%
  hH,%
  ^^T^^U^^V,% ch Ch CH
  iI\'i\'I,%
  jJ,%
  kK,%
  lL\'l\'L\v l\v L,%
  mM,%
  nN\v n\v N,%
  oO\"o\"O\'o\'O\^o\^O,%
  pP,%
  qQ,%
  rR\'r\'R,%
  \v r\v R,%
  sS,%
  \v s\v S,%
  tT\v t\v T,%
  uU\"u\"U\'u\'U\r u\r U,%
  vV,%
  wW,%
  xX,%
  yY\'y\'Y,%
  zZ,%
  \v z\v Z,%
  0,1,2,3,4,5,6,7,8,9,'.%
}
\def\setignoredchars{\setlccodes ,.;.?.!.:.'.".|.(.).[.].<.>.=.+.{}{}}
\def\specsortingdatacs {ch:^^T Ch:^^U CH:^^V}
\def\specsortingdatask {ch:^^T Ch:^^U CH:^^V} % DZ etc. are sorted normally

\def\setprimarysorting {%
   \isdefined{sortingdata\csname lan:\the\language\endcsname}\iftrue
      \expandafter \let\expandafter\sortingdata
         \csname sortingdata\csname lan:\the\language\endcsname\endcsname
      \xdef\sortingmessage{using \string\sortingdata\csname lan:\the\language\endcsname}%
   \else
      \xdef\sortingmessage{using internal \string\sortingdata}%
      \ifx\r\undefined
         \opwarning{\noexpand\csaccents is unused, falling back to ASCII sorting}%
         \global\let\asciisorting=t%
   \fi\fi
   \ifx\asciisorting\undefined
      \xdef\sortingdata{\sortingdata}% expand sorting data now
      \isdefined{specsortingdata\csname lan:\the\language\endcsname}\iftrue
         \xdef\specsortingdata{\csname specsortingdata\csname lan:\the\language\endcsname
            \endcsname\space}%
         \expandafter\setprimarysortingA \meaning\specsortingdata\relax
      \else \gdef\specsortingdata{}\fi
   \else 
      \gdef\sortingdata{.}\gdef\specsortingdata{}\gdef\sortingmessage{ASCII}%
   \fi
   \def\act##1{\ifx##1.\else
      \ifx##1,\advance\tmpnum by1
      \else \lccode`##1=\tmpnum \fi
      \expandafter \act \fi}%
   \tmpnum=60 \expandafter \act\sortingdata \setignoredchars
}
\def\setprimarysortingA#1->#2\relax{\gdef\specsortingdata{#2}}
\def\sortingmessage{ASCII default}

\def\setsecondarysorting {\def\act##1{\ifx##1.\else
     \ifx##1,\else \advance\tmpnum by1 \lccode`##1=\tmpnum \fi
     \expandafter \act \fi}%
  \tmpnum=60 \expandafter \act\sortingdata \setignoredchars
}

\def\preparesorting#1{\expandafter\preparesortingA\string#1&}
\gdef\preparesortingA#1#2#3&{\xdef\tmpb{#3}%
   \expandafter\preparesortingB\specsortingdata.:{}
   \lowercase\expandafter{\expandafter\gdef\expandafter\tmpb\expandafter{\tmpb}}%
   \replacestrings{.}{}%
}
\def\preparesortingB#1#2:#3 {\ifx.#1\else \replacestrings{#1#2}{#3}\expandafter\preparesortingB\fi}

\newif \ifAleB

\def\isAleB #1#2{%
  \edef\tmp{\firstdata#1\empty\relax\firstdata#2\empty\relax \noexpand#1\noexpand#2}%
  \expandafter \testAleB \tmp
}
\def\testAleB #1#2\relax #3#4\relax #5#6{%
  \if #1#3\if #1&\testAleBsecondary #5#6%
          \else \testAleB #2\relax #4\relax #5#6%
          \fi
  \else \ifnum `#1<`#3 \AleBtrue \else \AleBfalse \fi
  \fi
}
\def\testAleBsecondary#1#2{%
  \bgroup
     \setsecondarysorting
     \preparesorting#1\let\tmpa=\tmpb \preparesorting#2%
     \edef\tmp{\tmpa0\relax\tmpb1\relax}%
     \expandafter\testAleBsecondaryX \tmp
  \egroup
}
\def\testAleBsecondaryX #1#2\relax #3#4\relax {%
  \if #1#3\testAleBsecondaryX #2\relax #4\relax
  \else \ifnum `#1<`#3 \global\AleBtrue \else \global \AleBfalse \fi
  \fi
}
\def\dosorting{%
   \message{Opmac: Sorting index (\sortingmessage)...}%
   \def\act##1{\ifx##1\relax\else \addto\iilist{##1,}%
             \expandafter\act\fi}%
   \edef\iilist{\expandafter}\expandafter\act \iilist\relax
   \edef\iilist{\expandafter}\expandafter\mergesort \iilist \end,\end
}

\def\mergesort #1#2,#3{% by Miroslav Olsak
   \ifx,#1%                      % prazdna-skupina,neco,  (#2=neco #3=pokracovani)
      \addto\iilist{#2,}%        % dvojice skupin vyresena
      \sortreturn{\fif\mergesort#3}%   % \mergesort pokracovani
   \fi
   \ifx,#3%                      % neco,prazna-skupina,  (#1#2=neco #3=,)
      \addto\iilist{#1#2,}%      % dvojice skupin vyresena
      \sortreturn{\fif\mergesort}%      % \mergesort dalsi
   \fi
   \ifx\end#3%                   % neco,konec (#1#2=neco)
      \ifx\empty\iilist                % neco=kompletni setrideny seznam
         \def\iilist{#1#2}%
         \sortreturn{\fif\fif\gobbletoend}%   % koncim
      \else                      % neco=posledni skupina nebo \end
         \sortreturn{\fif\fif       % spojim \indexbuffer+necoa cele znova
                     \edef\iilist{\expandafter}\expandafter\mergesort\iilist#1#2,#3}%
   \fi\fi                      % zatriduji: p1+neco1,p2+neco2, (#1#2=p1+neco1 #3=p2)
   \isAleB #1#3\ifAleB         % p1<p2
      \addto\iilist{#1}%       % p1 do bufferu
      \sortreturn{\fif\mergesort#2,#3}%         % \mergesort neco1,p2+neco2,
   \else                       % p1>p2
      \addto\iilist{#3}%       % p2 do bufferu
      \sortreturn{\fif\mergesort#1#2,}%         % \mergesort p1+neco1,neco2,
   \fi
   \relax % zarazka, na ktere se zastavi \sortreturn
}
\def\sortreturn#1#2\fi\relax{#1} \def\fif{\fi}
\def\gobbletoend #1\end{}

%%%%%%%%%%%%%% \begmulti ... \endmulti TBN p. 244, 245 -- sec. 3.14 in opmac-d.pdf

\newcount\mullines
\def\corrsize #1{%% #1 := #1 + \splittopskip - \topskip
   \advance #1 by \splittopskip \advance #1 by-\topskip
}
\def\begmulti #1 {\par\bgroup\wipeepar\multiskip\penalty0 \def\Ncols{#1}
   \setbox6=\vbox\bgroup\penalty0
   %% \hsize := Sirka sloupce = (\hsize+\colsep) / n - \colsep
   \advance\hsize by\colsep
   \divide\hsize by\Ncols  \advance\hsize by-\colsep
   \mullines=0
   \def\par{\ifhmode\endgraf\global\advance\mullines by\prevgraf\fi}%
}
\def\endmulti{\vskip-\prevdepth\vfil
   \expandafter\egroup\expandafter\baselineskip\the\baselineskip\relax 
   \dimen0=.8\maxdimen \tmpnum=\dimen0 \divide\tmpnum by\baselineskip 
   \splittopskip=\baselineskip
   \setbox1=\vsplit6 to0pt
   %% \dimen1 := the free space on the page
   \ifdim\pagegoal=\maxdimen \dimen1=\vsize \corrsize{\dimen1}
   \else \dimen1=\pagegoal \advance\dimen1 by-\pagetotal \fi
   \ifdim \dimen1<2\baselineskip
     \vfil\break \dimen1=\vsize \corrsize{\dimen1} \fi
   \ifnum\mullines<\tmpnum \dimen0=\ht6 \else \dimen0=.8\maxdimen \fi
   \divide\dimen0 by\Ncols \relax
   %% split the material to more pages?
   \ifdim \dimen0>\dimen1 \splitpart
   \else \balancecolumns \fi  % only balancing
   \multiskip\egroup
}
\def\makecolumns{\bgroup % full page, destination height: \dimen1
   \vbadness=20000 \setbox1=\hbox{}\tmpnum=0
   \loop \ifnum\Ncols>\tmpnum
      \advance\tmpnum by1
      \setbox1=\hbox{\unhbox1 \vsplit6 to\dimen1 \hss}
   \repeat
   \hbox{}\nobreak\vskip-\splittopskip \nointerlineskip
   \line{\unhbox1\unskip}
   \dimen0=\dimen1 \divide\dimen0 by\baselineskip \multiply\dimen0 by\Ncols
   \global\advance\mullines by-\dimen0
   \egroup
}
\def\splitpart{%
   \makecolumns % full page
   \vskip 0pt plus 1fil minus\baselineskip \break
   \ifnum\mullines<\tmpnum \dimen0=\ht6 \else \dimen0=.8\maxdimen \fi
   \divide\dimen0 by\Ncols \relax
   \ifx\balancecolumns\flushcolumns \advance\dimen0 by-.5\vsize \fi
   \dimen1=\vsize \corrsize{\dimen1}\dimen2=\dimen1
   \advance\dimen2 by-\Ncols\baselineskip
   %% split the material to more pages?
   \ifvoid6 \else
      \ifdim \dimen0>\dimen2 \expandafter\expandafter\expandafter \splitpart
      \else \balancecolumns % last balancing
   \fi \fi
}
\def\balancecolumns{\bgroup \setbox7=\copy6 % destination height: \dimen0
   \ifdim\dimen0>\baselineskip \else \dimen0=\baselineskip \fi
   \vbadness=20000
   \def\tmp{%
      \setbox1=\hbox{}\tmpnum=0
      \loop \ifnum\Ncols>\tmpnum
         \advance\tmpnum by1
         \setbox1=\hbox{\unhbox1
              \ifvoid6 \hbox to\wd6{\hss}\else \vsplit6 to\dimen0 \fi\hss}
      \repeat
   \ifvoid6 \else
      \advance \dimen0 by.2\baselineskip
      \setbox6=\copy7
      \expandafter \tmp \fi}\tmp
   \hbox{}\nobreak\vskip-\splittopskip \nointerlineskip
   \hbox to\hsize{\unhbox1\unskip}%
   \egroup
}

%%%%%%%%%%%%%% Colors -- sec. 3.15 in opmac-d.pdf

\newif\iflocalcolor \localcolorfalse  
\let\localcolor=\localcolortrue  

% for backward compatibility:
\let\longlocalcolor=\localcolor  \let\locpgcolor=\relax
\def\linecolor#1{}

\def\Blue{\setcmykcolor{1 1 0 0}}
\def\Red{\setcmykcolor{0 1 1 0}}
\def\Brown{\setcmykcolor{0 0.67 0.67 0.5}}
\def\Green{\setcmykcolor{1 0 1 0}}
\def\Yellow{\setcmykcolor{0 0 1 0}}
\def\Cyan{\setcmykcolor{1 0 0 0}}
\def\Magenta{\setcmykcolor{0 1 0 0}}
\def\White{\setcmykcolor{0 0 0 0}}
\def\Grey{\setcmykcolor{0 0 0 0.5}}
\def\LightGrey{\setcmykcolor{0 0 0 0.2}}
\def\Black{\setcmykcolor{0 0 0 1}}

\def\setcmykcolor#1{\global\let\ensureblacko=\ensureblackoA
   \iflocalcolor \edef\currentcolor{#1}\colorstackpush\currentcolor \aftergroup\colorstackpop
   \else         \xdef\currentcolor{#1}\colorstackset\currentcolor \fi
}
\def\pdfblackcolor{0 0 0 1}
\xdef\currentcolor{\pdfblackcolor}
\def\ensureblacko#1{#1}
\def\ensureblackoA#1{\colorstackpush\pdfblackcolor #1\colorstackpop}

\ifx\pdfcolorstackinit\undefined
   \def\colorstackpush#1{\pdfliteral{#1 k #1 K}}
   \def\colorstackpop{\colorstackpush\currentcolor}
   \let\colorstackset=\colorstackpush
\else
   \mathchardef\colorstackcnt=\pdfcolorstackinit page {0 g 0 G}
   \def\colorstackpush#1{\pdfcolorstack\colorstackcnt push{#1 k #1 K}}
   \def\colorstackpop{\pdfcolorstack\colorstackcnt pop}
   \def\colorstackset#1{\pdfcolorstack\colorstackcnt set{#1 k #1 K}}
\fi

\addprotect\setcmykcolor  \addprotect\localcolor  \addprotect\longlocalcolor

\ifpdftex\else
   \def\setcmykcolor#1{} \def\pdfliteral#1{}
\fi

\def\draft{\addto\prepghook{\draftbox{\tenbf DRAFT}\nointerlineskip}}
\def\draftbox#1{\vbox to0pt{\setbox0=\hbox{\typosize[10/]#1}%
   \kern.5\vsize \kern4\wd0 \hbox to0pt{\kern.5\hsize \kern-2.5\wd0
   \pdfsave \pdfrotate{55}\pdfscale{10}{10}%
   \hbox to0pt{\localcolor\LightGrey \box0\hss}%
   \pdfrestore
   \hss}\vss}}

\ifpdftex\else
   \def\draft{\opwarning{\string\draft: Grey color is possible in pdfTeX only}}
\fi

%%%%%%%%%%%%%% Hyperrefs -- sec. 3.16 in opmac-d.pdf

\def\destheight{1.4em}
\def\destactive[#1:#2]{\if$#2$\else\ifvmode
      \tmpdim=\prevdepth \prevdepth=-1000pt
      \destbox[#1:#2]\prevdepth=\tmpdim
   \else \destbox[#1:#2]%
   \fi\fi
}
\def\destbox[#1]{\vbox to0pt{\kern-\destheight \pdfdest name{#1} xyz\vss}}
\def\dest[#1]{}

\def\linkactive[#1:#2]#3#4{\leavevmode\pdfstartlink height.9em depth.3em
      \pdfborder{#1} goto name{#1:#2}\relax {#3#4}\pdfendlink
}
\def\link[#1]#2#3{\leavevmode#3}

\def\urllink[#1:#2]#3{{\let~=\relax \let\\=\relax \let\{=\relax \let\}=\relax
   \leavevmode\pdfstartlink height.9em depth.3em
   \pdfborder{#1}user{/Subtype/Link/A <</Type/Action/S/URI/URI(#2)>>}\relax
   {\def~{\nobreak\space}\urlcolor#3}\pdfendlink}%
}
\def\toclink#1{\toclinkA{#1}}
\def\pglink#1{\pgfolioA{#1}\relax}
\def\citelink#1#2{\leavevmode#2}
\def\reflink[#1]#2{\leavevmode#2}
\def\ulink[#1]#2{{\leavevmode#2}}
\def\urlcolor{}

\def\hyperlinks#1#2{%
   \let\dest=\destactive \let\link=\linkactive
   \def\toclink##1{\link[toc:\tocilabel.##1]{\localcolor#1}{\toclinkA{##1}}}%
   \def\pglink##1{\link[pg:\pgilabel.##1]{\localcolor#1}{\pgfolioA{##1}}}%
   \def\citelink##1##2{\link[cite:##1]{\localcolor#1}{##2}}%
   \def\reflink[##1]##2{\link[ref:##1]{\localcolor#1}{##2}}%
   \def\ulink[##1]##2{\urllink[url:##1]{##2}}%
   \def\urlcolor{\localcolor#2}%
}
\def\tocilabel{} \def\pgilabel{}

\def\pdfborder#1{\if^#1^\else \isdefined{#1border}\iftrue
   \if^\csname#1border\endcsname^\else attr{/C[\csname#1border\endcsname] /Border[0 0 .6]}\fi
   \else attr{/Border[0 0 0]}\fi\fi
}

\ifpdftex \else
  \def\link[#1]#2#3{#3}
  \def\urllink[#1]#2{#2}
  \def\hyperlinks#1#2{\opwarning{No pdfTeX detected, \noexpand\hyperlinks ignored}}
\fi

\def\url#1{{\def\tmpb{#1}%
   \replacestrings{//}{{\urlskip\urlslashslash\urlbskip}}%
   \replacestrings{/}{{\urlskip/\urlbskip}}%
   \replacestrings{.}{{\urlskip.\urlbskip}}%
   \replacestrings{?}{{\urlskip?\urlbskip}}%
   \replacestrings{=}{{\urlskip=\urlbskip}}%
   \replacestrings{~}{{\char`\~}}%
   \replacestrings{_}{{\char`\_}}%
   \replacestrings{^}{{\char`\^}}%
   \replacestrings{\\}{\bslash}%
   \replacestrings{\{}{{\char`\{}}%
   \replacestrings{\}}{{\char`\}}}%
   \replacestrings{&}{{\urlbskip\char`\& \urlskip}}%
   \def\|{}\ulink[#1]{\urlfont\tmpb\null}%
}}
\def\urlfont{\tt \let\|=\urlspecchar}
\def\urlspecchar{\penalty10 }
\def\urlskip{\null\nobreak\hskip0pt plus0.05em\relax}
\def\urlbskip{\penalty100 \hskip0pt plus0.05em\relax}
\def\urlslashslash{/\urlskip/}
\addprotect\url

%%%%%%%%%%%%%% Outlines -- sec. 3.17 in opmac-d.pdf

\def\outlines#1{\pdfcatalog{/PageMode/UseOutlines}\openref\ifx\toclist\empty
     \opwarning{\noexpand\outlines -- data unavailable. TeX me again}%
   \else
     \ifx\urlcolor\empty 
        \opwarning{\noexpand\outlines doesn't work when \noexpand\hyperlinks isn't declared}\fi
     {\let\tocline=\outlinesA
      \count0=0 \count1=0 \toclist % calculate numbers o childs
      \def\outlinelevel{#1}\let\tocline=\outlinesB
      \count0=0 \count1=0 \toclist}% create outlines
   \fi
}
\def\outlinesA#1#2#3#4#5{%
   \advance\count#1 by1
   \ifcase#1\or
     \addoneol{ol:\the\count0}\or
     \addoneol{ol:\the\count0:\the\count1}\fi
}
\def\addoneol#1{\isdefined{#1}%
   \iftrue \tmpnum=\csname#1\endcsname\relax
           \advance\tmpnum by1 \sxdef{#1}{\the\tmpnum}%
   \else \sxdef{#1}{1}%
   \fi
}
\def\outlinesB#1#2#3#4#5{%
   \advance\count#1 by1
   \ifcase#1\tmpnum=\isdefined{ol:\the\count0}%
               \iftrue\csname ol:\the\count0\endcsname\else0\fi \or
            \tmpnum=\isdefined{ol:\the\count0:\the\count1}%
               \iftrue\csname ol:\the\count0:\the\count1\endcsname\else0\fi \or
            \tmpnum = 0 \fi
   \protectlist \def~{ }\setcnvcodesA 
   \ifx\toasciidata\empty \let\lowercase=\relax \else \expandafter\setlccodes\toasciidata{}{}\fi
   \cnvhook \lowercase{\gdef\tmp{#4}}%
   \outlinesC{#1}{toc:\tocilabel.#3}{\ifnum#1<\outlinelevel\space\else-\fi}{\tmpnum}{\tmp}%
}
\def\outlinesC#1#2#3#4#5{\pdfoutline goto name{#2} count #3#4{#5}\relax}

\def\setcnvcodesA{\global\let\setcnvcodesA=\relax % I am working only once
   \isdefined{toasciidata\csname lan:\the\language\endcsname}\iftrue
      \xdef\toasciidata{\csname toasciidata\csname lan:\the\language\endcsname\endcsname}%
   \else
      \ifx\r\undefined
         \gdef\toasciidata{}
         \opwarning{\noexpand\csaccents unused, CZ/SK outline-conversion is off}%
      \else
         \xdef\toasciidata{\toasciidata}%
   \fi\fi
}
\def\toasciidata{%  Removes Czech+Slovak accents
       AA\'AA\"AA\'aa\"aaBBCC\v CC\v ccDD\v DD\v ddEE\'EE\v EE\'ee\v ee%
       FFGGHHII\'II\'iiJJKKLL\'LL\v LL\'ll\v llMMNN\v NN\v nnOO\'OO\"OO\^OO%
       \'oo\"oo\^ooPPQQRR\v RR\v rrSS\v SS\v ssTT\v TT\v ttUU\'UU\"UU\r UU%
       \'uu\"uu\r uuVVWWXXYY\'YY\'yyZZ\v ZZ\v zz%
}
\def\setlccodes#1#2{\if\relax#2\relax \else \lccode`#1=`#2 \expandafter \setlccodes \fi}

\newcount\oulnum
\def\insertoutline#1{\global\advance\oulnum by1
   \pdfdest name{oul:\the\oulnum} xyz\relax
   \pdfoutline goto name{oul:\the\oulnum} count0 {#1}\relax
}

\ifpdftex \else
  \def\outlines#1{\opwarning{DVI output has no outlines}\gdef\outlines##1{}}
  \let\insertoutline=\outlines
\fi

%%%%%%%%%%%%%% Verbatim, \begtt, \endtt -- sec. 3.18 in opmac-d.pdf

\newcount\ttline    \ttline=-1
\newcount\viline
\newread\vifile

\def\setverb{\frenchspacing\def\do##1{\catcode`##1=12}\dospecials \catcode`\*=12 }
\def\begtt{\par \vskip\parskip \ttskip \bgroup \wipeepar
   \setverb \adef{ }{\ }%
   \ifx\savedttchar\undefined \else \catcode\savedttchar=12 \fi
   \parindent=\ttindent \parskip=0pt
   \tthook\relax
   \ifnum\ttline<0 \else
     \tenrm \thefontscale[700]\let\sevenrm=\thefont
     \everypar\expandafter{\the\everypar \global\advance\ttline by1 \printttline}\fi
   \def\par##1{\endgraf\ifx##1\egroup\else\penalty\ttpenalty\leavevmode\fi ##1}%
   \obeylines \startverb}
{\catcode`\|=0 \catcode`\\=12
|gdef|startverb#1\endtt{|tt|ptthook#1|egroup|par|ttskip|testparA}}
\def\testparA{\expandafter\testparB\romannumeral-`\.}
\def\testparB{\futurelet\tmpa\testparC}
\def\testparC{\ifx\tmpa\par\else\afternoindent\fi}

\def\printttline{\llap{\sevenrm\the\ttline\kern.9em}}

\def\activettchar#1{%
   \ifx\savedttchar\undefined\else \catcode\savedttchar=\savedttcharc \fi
   \chardef\savedttchar=`#1%
   \chardef\savedttcharc=\catcode`#1%
   \bgroup\lccode`\~=`#1%
   \lowercase {\egroup\def~}{\leavevmode\hbox\bgroup\setverb\adef{ }{\ }%
                      \intthook\tt\readverb}%
   \bgroup\lccode`\~=`#1\lowercase{\egroup\def\readverb ##1~}{##1\egroup}%
   \catcode`#1=13
}

\def\verbinput (#1) #2 {\par \def\tmpa{#2}%
   \ifx\vifilename\tmpa \else
      \openin\vifile=#2
      \global\viline=0 \global\let\vifilename=\tmpa
      \ifeof\vifile
         \opwarning{\noexpand\verbinput - file "#2" is unable to reading}
         \expandafter\expandafter\expandafter\skiptorelax
      \fi
   \fi
   \viscanparameter #1+\relax
}
\def\skiptorelax#1\relax{}

\def \viscanparameter #1+#2\relax{%
   \if$#2$\viscanminus(#1)\else \viscanplus(#1+#2)\fi
}
\def\viscanplus(#1+#2+){%
   \if$#1$\tmpnum=\viline
   \else \ifnum#1<0 \tmpnum=\viline \advance\tmpnum by-#1
       \else \tmpnum=#1
             \advance\tmpnum by-1
             \ifnum\tmpnum<0 \tmpnum=0 \fi % (0+13) = (1+13)
   \fi \fi
   \edef\vinolines{\the\tmpnum}%
   \if$#2$\def\vidolines{0}\else\edef\vidolines{#2}\fi
   \doverbinput
}
\def\viscanminus(#1-#2){%
   \if$#1$\tmpnum=0
      \else \tmpnum=#1 \advance\tmpnum by-1 \fi
   \ifnum\tmpnum<0 \tmpnum=0 \fi  % (0-13) = (1-13)
   \edef\vinolines{\the\tmpnum}%
   \if$#2$\tmpnum=0
      \else \tmpnum=#2 \advance\tmpnum by-\vinolines \fi
   \edef\vidolines{\the\tmpnum}%
   \doverbinput
}
\def\doverbinput{%
   \tmpnum=\vinolines
   \advance\tmpnum by-\viline
   \ifnum\tmpnum<0
      \openin\vifile=\vifilename\space
      \global\viline=0
   \else
      \edef\vinolines{\the\tmpnum}%
   \fi
   \vskip\parskip \ttskip \bgroup \wipeepar
   \setverb \adef{ }{\ }%
   \ifx\savedttchar\undefined \else \catcode\savedttchar=12 \fi
   \parindent=\ttindent \parskip=0pt
   \tthook\relax
   \ifnum\ttline<-1 \else
     \tenrm \thefontscale[700]\let\sevenrm=\thefont
     \everypar\expandafter{\the\everypar \glob\advance\ttline by1 \printttline}\fi
   \def\par##1{\endgraf\ifx##1\egroup\else\penalty\ttpenalty\leavevmode\fi ##1}%
   \obeylines \tmpnum=0 \lccode`\~=`\^^M \lowercase{\def\tmpb{~}}%
   \loop \ifeof\vifile \tmpnum=\vinolines\space \fi
         \ifnum\tmpnum<\vinolines\space
         \vireadline \advance\tmpnum by1 \repeat      %% skip line
   \ifnum\ttline=-1 \ttline=\viline \let\glob=\relax \else\let\glob=\global \fi
   \tmpnum=0 \ifnum\vidolines=0 \tmpnum=-1 \fi
   \ifeof\vifile \tmpnum=\vidolines\space \fi
   \loop \ifnum\tmpnum<\vidolines\space
            \vireadline 
            \ifeof\vifile \tmpnum=\vidolines\space \else \viprintline \fi %% print line
            \ifnum\vidolines=0 \else\advance\tmpnum by1 \fi 
            \repeat
   \tt\expandafter\ptthook\tmpb\egroup\par\ttskip\testparA
}
\def\vireadline{\read\vifile to \tmp \global\advance\viline by1 }
\def\viprintline{\expandafter\addto\expandafter\tmpb\expandafter{\tmp}}

%%%%%%%%%%%%%% \table -- sec. 3.19 in opmac-d.pdf

\newtoks\tabdata
\def\tabstrutA{\tabstrut}
\newcount\colnum
\def\ddlinedata{}
\def\vvleft{}

\def\table{\vbox\bgroup \catcode`\|=12 \tableA}
\def\tableA#1#2{\offinterlineskip \colnum=0 \def\tmpa{}\tabdata={}\scantabdata#1\relax
   \halign\expandafter{\the\tabdata\cr#2\crcr}\egroup}

\def\scantabdata#1{\let\next=\scantabdata
   \ifx\relax#1\let\next=\relax
   \else\ifx|#1\addtabvrule
      \else\isinlist{123456789}#1\iftrue \def\next{\scantabdataC#1}%
          \else \expandafter\ifx\csname tabdeclare#1\endcsname \relax
                \expandafter\ifx\csname paramtabdeclare#1\endcsname \relax
                   \opwarning{tab-declarator "#1" unknown, ignored}%
                \else \def\next{\expandafter \scantabdataB \csname paramtabdeclare#1\endcsname}\fi
             \else \def\next{\expandafter\scantabdataA \csname tabdeclare#1\endcsname}%
   \fi\fi\fi\fi \next
}
\def\scantabdataA#1{\addtabitem \expandafter\addtabdata\expandafter{#1\tabstrutA}\scantabdata}
\def\scantabdataB#1#2{\addtabitem\expandafter\addtabdata\expandafter{#1{#2}\tabstrutA}\scantabdata}
\def\scantabdataC {\def\tmpb{}\afterassignment\scantabdataD \tmpnum=}
\def\scantabdataD#1{\loop \ifnum\tmpnum>0 \advance\tmpnum by-1 \addto\tmpb{#1}\repeat
   \expandafter\scantabdata\tmpb
}
\def\tabdeclarec{\tabiteml\hfil##\unsskip\hfil\tabitemr}
\def\tabdeclarel{\tabiteml##\unsskip\hfil\tabitemr}
\def\tabdeclarer{\tabiteml\hfil##\unsskip\tabitemr}
\def\paramtabdeclarep#1{\tabiteml\vtop{\hsize=#1\relax \baselineskip=\normalbaselineskip 
   \lineskiplimit=0pt \noindent##\unsskip \vbox to0pt{\vss\hbox{\tabstrutA}}}\tabitemr}

\def\unsskip{\ifdim\lastskip>0pt \unskip\fi}
\def\addtabitem{\ifnum\colnum>0 \addtabdata{&}\addto\ddlinedata{&\dditem}\fi
    \advance\colnum by1 \let\tmpa=\relax}
\def\addtabdata#1{\tabdata\expandafter{\the\tabdata#1}}
\def\addtabvrule{%
    \ifx\tmpa\vrule \addtabdata{\kern\vvkern}%
       \ifnum\colnum=0 \addto\vvleft{\vvitem}\else\addto\ddlinedata{\vvitem}\fi
    \else \ifnum\colnum=0 \addto\vvleft{\vvitemA}\else\addto\ddlinedata{\vvitemA}\fi\fi
    \let\tmpa=\vrule \addtabdata{\vrule}}

\def\crl{\crcr\noalign{\hrule}}
\def\crll{\crcr\noalign{\hrule\kern\hhkern\hrule}}

\def\crli{\crcr \omit 
   \gdef\dditem{\omit\tablinefil}\gdef\vvitem{\kern\vvkern\vrule}\gdef\vvitemA{\vrule}%
   \vvleft\tablinefil\ddlinedata\crcr}
\def\crlli{\crli\noalign{\kern\hhkern}\crli}
\def\tablinefil{\leaders\hrule\hfil}

\def\crlp#1{\crcr \noalign{\kern-\drulewidth}%
   \omit \xdef\crlplist{#1}\xdef\crlplist{,\expandafter}\expandafter\crlpA\crlplist,\end,%
   \global\tmpnum=0 \gdef\dditem{\omit\crlpD}%
   \gdef\vvitem{\kern\vvkern\kern\drulewidth}\gdef\vvitemA{\kern\drulewidth}%
   \vvleft\crlpD\ddlinedata \global\tmpnum=0 \crcr}
\def\crlpA#1,{\ifx\end#1\else \crlpB#1-\end,\expandafter\crlpA\fi}
\def\crlpB#1#2-#3,{\ifx\end#3\xdef\crlplist{\crlplist#1#2,}\else\crlpC#1#2-#3,\fi}
\def\crlpC#1-#2-#3,{\tmpnum=#1\relax 
   \loop \xdef\crlplist{\crlplist\the\tmpnum,}\ifnum\tmpnum<#2\advance\tmpnum by1 \repeat}
\def\crlpD{\global\advance\tmpnum by1
   \edef\tmpa{\noexpand\isinlist\noexpand\crlplist{,\the\tmpnum,}}%
   \tmpa\iftrue \kern-\drulewidth \tablinefil \kern-\drulewidth\else\hfil \fi}

\def\tskip{\afterassignment\tskipA \tmpdim}
\def\tskipA{\gdef\dditem{}\gdef\vvitem{}\gdef\vvitemA{}\gdef\tabstrutA{}%
    \vbox to\tmpdim{}\ddlinedata \crcr \noalign{\gdef\tabstrutA{\tabstrut}}}

\def\mspan{\omit \tabdata={\tabstrut}\let\tmpa=\relax \afterassignment\mspanA \mscount=}
\def\mspanA[#1]{\loop \ifnum\mscount>1 \csname span\endcsname \omit \advance\mscount by-1 \repeat 
   \mspanB#1\relax}
\def\mspanB#1{\ifx\relax#1\def\tmpa{\def\tmpa####1}%
   \expandafter\tmpa\expandafter{\the\tabdata\ignorespaces}\expandafter\tmpa\else
   \ifx |#1\ifx\tmpa\vrule\addtabdata{\kern\vvkern}\fi \addtabdata{\vrule}\let\tmpa=\vrule
   \else \let\tmpa=\relax
      \ifx c#1\addtabdata{\tabiteml\hfil\ignorespaces##1\unsskip\hfil\tabitemr}\fi
      \ifx l#1\addtabdata{\tabiteml\ignorespaces##1\unsskip\hfil\tabitemr}\fi
      \ifx r#1\addtabdata{\tabiteml\hfil\ignorespaces##1\unsskip\tabitemr}\fi
   \fi \expandafter\mspanB \fi}

\newdimen\drulewidth  \drulewidth=0.4pt
\let\orihrule=\hrule  \let\orivrule=\vrule
\def\rulewidth{\afterassignment\rulewidthA \drulewidth}
\def\rulewidthA{\edef\hrule{\orihrule height\the\drulewidth}%
                \edef\vrule{\orivrule width\the\drulewidth}}

\long\def\frame#1{%
   \hbox{\vrule\vtop{\vbox{\hrule\kern\vvkern
      \hbox{\kern\hhkern\relax#1\kern\hhkern}%
   }\kern\vvkern\hrule}\vrule}}

%%%%%%%%%%%%%% \inspic -- sec. 3.20 in opmac-d.pdf

\newdimen\picwidth    \picwidth=0pt   \let\picw=\picwidth
\newdimen\picheight   \picheight=0pt

\ifpdftex
  \def\inspic #1 {\hbox{%
      \pdfximage \ifdim\picwidth=0pt \else width\picwidth\fi 
                 \ifdim\picheight=0pt \else height\picheight\fi \inspicpage {\picdir#1}%
      \pdfrefximage\pdflastximage}}
\else
  \def\inspic #1 {\opwarning
     {The \noexpand\inspic is supported for PDF output only}}
\fi
\def\inspicpage{}

%%%%%%%%%%%%%%% transformation matrix -- sec. 3.21 in opmac-d.pdf

\def\pdfscale#1#2{\pdfsetmatrix{#1 0 0 #2}}

\def\pdfrotate#1{\tmpdim=#1pt
   \ifdim\tmpdim=0pt
   \else \ifdim\tmpdim=90pt \pdfsetmatrix{0 1 -1 0}%
         \else \edef\tmp{#1}\expandafter\pdfrotateA\tmp..\relax
   \fi   \fi
}
\def\pdfrotateA #1.#2.#3\relax{%
   \def\tmp##1.##2\relax {##1}%
   \tmpnum=\expandafter \tmp \the\tmpdim \relax % round
   \ifdim\tmpdim>0pt \def\tmpa{}\else\def\tmpa{-}\fi % save -
   \loop \ifnum\tmpnum<0 \advance\tmpnum by360 \repeat
   \loop \ifnum\tmpnum>360 \advance\tmpnum by-360 \repeat
   \loop \ifnum\tmpnum>90 \pdfrotate{90}\advance\tmpnum by-90 \repeat
   \ifnum\tmpnum=90 \pdfrotate{90}\else
      \ifnum\tmpnum>44 \pdfsetmatrix{.7071 .7071 -.7071 .7071}%
                       \advance\tmpnum by-45 \fi
      \ifnum\tmpnum>22 \pdfsetmatrix{.9272 .3746 -.3746 .9272}%
                       \advance\tmpnum by-22 \fi
      \ifnum\tmpnum>0
         \pdfsetmatrix{\smallcos \smallsin -\smallsin \smallcos}%
   \fi\fi
   \if$#2$\else % fraction part
      \tmpdim=.01745329pt % \pi/180
      \tmpdim=.#2\tmpdim  %
      \edef\tmp{\expandafter\ignorept\the\tmpdim\space}%
      \ifx\tmpa\empty \pdfsetmatrix{1 \tmp -\tmp 1}%
      \else           \pdfsetmatrix{1 -\tmp \tmp 1}%
   \fi\fi
}
\def\smallcos{.\ifcase\tmpnum \or9998\or9994\or9986\or9976\or9962\or9945\or
  9925\or9903\or9877\or9848\or9816\or9781\or9744\or9703\or9659\or9613\or
  9563\or9511\or9455\or9397\or9336\or9272\fi\space}
\def\smallsin{.\ifcase\tmpnum 0\or0175\or0359\or0523\or0698\or0872\or1045\or
  1219\or1391\or1564\or1736\or1908\or2079\or2250\or2419\or2588\or2756\or
  2924\or309\or3256\or342\or3584\or3746\fi\space}

\ifpdftex \else
  \def\pdfsetmatrix#1{} \def\pdfsave{} \def\pdfrestore{}
\fi

%%%%%%%%%%%%%% \fnote, \mnote -- sec 3.22 in opmac-d.pdf

\newcount\fnotenum \fnotenum=0
\newcount\fnotenumlocal
\newif\iflocfnum \locfnumtrue

\long\def\fnote#1{\global\advance \fnotenum by1
   \leavevmode\openref\wref\Xfnote{}%
   \iflocfnum \isdefined{fn:\the\fnotenum}\iftrue
      \else\opwarning{unknown \noexpand\fnote mark. TeX me again}\fi\fi
   \fnmarkx{\fnotehook\typobase\typoscale[800/800]\vfootnote\fnmarkx{#1}}%
}
\def\fnotemark#1{{\advance\fnotenum by#1\relax
   \isdefined{fn:\the\fnotenum}\iftrue\thefnote
   \else$^?$\opwarning{unknown \string\fnotemark. TeX me again}\fi}%
}
\long\def\fnotetext#1{\global\advance \fnotenum by1 \openref\wref\Xfnote{}%
   {\everypar={}\fnotehook\typobase\typoscale[800/800]\vfootnote\fnmarkx{#1}}%
}
\def\fnmarkx{\isdefined{fn:\the\fnotenum}\iftrue\thefnote\else$^?$\fi}
\def\thefnote{$^{\locfnum}$}
\def\locfnum{\csname fn:\the\fnotenum\endcsname}

\def\Xfnote{\advance\fnotenumlocal by1 \advance\fnotenum by1
   \sxdef{fn:\the\fnotenum}{\the\fnotenumlocal}}

\def\runningfnotes{\locfnumfalse\def\locfnum{\the\fnotenum}\def\fnmarkx{\thefnote}}

\newcount\mnotenum    \mnotenum=0       % global counter of mnotes
\newdimen\mnoteskip   \mnoteskip=0pt

\long\def\mnote#1{\ifvmode \hbox{\vbox to\ht\strutbox{}\mnoteA{#1}}\nobreak\vskip-\baselineskip
   \else \strut\vadjust{\kern-\dp\strutbox \mnoteA{#1}\kern\dp\strutbox}%
   \fi
}
\long\def\mnoteA#1{\global\advance \mnotenum by1
   \ifx\mnotesfixed\undefined
      \isdefined{mn:\the\mnotenum}\iftrue
      \else\opwarning{unknown \noexpand\mnote side. TeX me again}\fi
      \edef\tmp{\csname mn:\the\mnotenum\endcsname}%
      \openref\wref\Xmnote{}\ifvmode\nobreak\fi
   \else \let\tmp=\mnotesfixed \fi
   \expandafter\ifx\tmp \left
      \hbox to0pt{\kern-\mnotesize \kern-\mnoteindent
         \vbox to0pt{\vss \setbox0=\vtop{\hsize=\mnotesize 
            \leftskip=0pt plus 1fill \rightskip=0pt {\mnotehook\noindent#1\endgraf}}%
         \dp0=0pt \box0 \kern\mnoteskip \global\mnoteskip=0pt}\hss}%
   \else
      \hbox to0pt{\kern\hsize \kern\mnoteindent
         \vbox to0pt{\vss \setbox0=\vtop{\hsize=\mnotesize 
             \rightskip=0pt plus 1fil \leftskip=0pt {\mnotehook\noindent#1\endgraf}}%
          \dp0=0pt \box0 \kern\mnoteskip \global\mnoteskip=0pt}\hss}%
   \fi
}
\def\Xmnote{\advance\mnotenum by1
   \sxdef{mn:\the\mnotenum}{\ifodd\lastpage \right \else \left \fi}}

\def\fixmnotes#1{\def\mnotesfixed{#1}}

%%%%%%%%%%%%%% \cite, \bib, \usebibtex, \usebbl -- sec. 3.23 in opmac-d.pdf

\newwrite\auxfile                      % AUX file for BibTeX
\newcount\bibnum                       % the bibitem counter
\newtoks\bibmark                       % the bibmark used if \nonumcitations
\newcount\lastcitenum  \lastcitenum=0  % for \shortcitations

\def\cite[#1]{{\citeA#1,,,[\printsavedcites]}}
\def\nocite[#1]{{\citeA#1,,,}}
\def\rcite[#1]{{\citeA#1,,,\printsavedcites}}
\def\savedcites{}

\def\citeA #1#2,{\if#1,\else 
   \if *#1\addcitelist{*}\expandafter \skiptorelax \fi
   \isdefined{bib:#1#2}\iftrue \else
      \addcitelist{#1#2}%
      \opwarning{The cite [#1#2] unknown. Try to TeX me again}\openref
      \addto\savedcites{?,}\def\sortcitesA{}\lastcitenum=0
      \expandafter\gdef\csname bib:#1#2\endcsname {}%
      \expandafter \skiptorelax \fi
   \expandafter \ifx \csname bib:#1#2\endcsname \empty
      \addto\savedcites{?,}\def\sortcitesA{}\lastcitenum=0
      \expandafter \skiptorelax \fi
   \def\bibnn##1{}%
   \if &\csname bib:#1#2\endcsname
      \addcitelist{#1#2}%
      \def\bibnn##1##2{##1}%
      \sxdef{bib:#1#2}{\csname bib:#1#2\endcsname}%
   \fi
   \edef\savedcites{\savedcites \csname bib:#1#2\endcsname,}%
   \relax
   \expandafter\citeA\fi
}
\def\printsavedcites{\sortcitesA 
   \chardef\tmpb=0 \expandafter\citeB\savedcites,%
   \ifnum\tmpb>0 \printdashcite{\the\tmpb}\fi
}
\def\sortcitesA{}
\def\sortcitations{%
  \def\sortcitesA{\edef\savedcites{300000,\expandafter}\expandafter\sortcitesB\savedcites,%
                  \def\tmpa####1300000,{\def\savedcites{####1}}\expandafter\tmpa\savedcites}%
}
\def\sortcitesB #1,{\if $#1$%
  \else
     \mathchardef\tmpa=#1
     \edef\savedcites{\expandafter}\expandafter\sortcitesC \savedcites\end
     \expandafter\sortcitesB 
  \fi
}
\def\sortcitesC#1,{\ifnum\tmpa<#1\edef\tmpa{\the\tmpa,#1}\expandafter\sortcitesD 
                   \else\edef\savedcites{\savedcites#1,}\expandafter\sortcitesC\fi}
\def\sortcitesD#1\end{\edef\savedcites{\savedcites\tmpa,#1}}

\def\citeB#1,{\if$#1$\else
   \if?#1\relax??%
      \else
      \ifnum\lastcitenum=0   % only comma separated list
         \printcite{#1}%
      \else
         \ifx\citesep\empty  % first cite item
            \lastcitenum=#1\relax
            \printcite{#1}%
         \else               % next cite item
            \advance\lastcitenum by1
            \ifnum\lastcitenum=#1\relax % cosecutive cite item
               \mathchardef\tmpb=\lastcitenum
            \else  % there is a gap between cite items
               \lastcitenum=#1\relax
               \ifnum\tmpb=0 % previous items were printed
                  \printcite{#1}%
               \else
                  \printdashcite{\the\tmpb}\printcite{#1}\chardef\tmpb=0
   \fi\fi\fi\fi\fi
   \expandafter\citeB\fi
}
\def\shortcitations{\lastcitenum=1 }

\def\printcite#1{\citesep\citelink{#1}{\citelinkA{#1}}\def\citesep{,\hskip.2em\relax}}
\def\printdashcite#1{\ifmmode-\else\hbox{--}\fi\citelink{#1}{\citelinkA{#1}}}
\def\citesep{}

\def\nonumcitations{\lastcitenum=0\def\sortcitesA{}\def\etalchar##1{$^{##1}$}%
   \def\citelinkA##1{\isdefined{bim:##1}\iftrue \csname bim:##1\endcsname
      \else ##1\opwarning{\noexpand\nonumcitations + empty bibmark. Maybe bad BibTeX style}\fi}
}
\def\citelinkA{}

\def\ecite[#1]{\bgroup\citeA#1,,,\expandafter\eciteB\savedcites;}
\def\eciteB#1,#2;#3{\if?#1\relax #3\else \citelink{#1}{#3}\fi\egroup}

\def\bib[#1]{\def\tmp{\isnextchar={\bibA[#1]}{\bibmark={}\bibB[#1]}}%
   \expandafter\tmp\romannumeral-`\.} % ignore optional space
\def\bibA[#1]=#2{\bibmark={#2}\bibB[#1]}
\def\bibB[#1]{\par \ifnum\bibnum>0 \bibskip \fi
   \advance\bibnum by1
   \noindent \def\tmpb{#1}\wbib{#1}{\the\bibnum}{\the\bibmark}%
   \printbib \ignorespaces
}
\def\wbib#1#2#3{\dest[cite:\the\bibnum]%
   \ifx\wref\wrefrelax\else \immediate\wref\Xbib{{#1}{#2}{#3}}\fi}

\def\Xbib#1#2#3{\sdef{bib:#1}{\bibnn{#2}&}\if^#3^\else\sdef{bim:#2}{#3}\fi\def\lastbibnum{#2}}

\def\printbib{\hangindent=\iindent
   \ifx\citelinkA\empty \noindent\hskip\iindent \llap{[\the\bibnum] }%
   \else \noindent \fi
}

\def\addcitelist#1{\global\addto\citelist{\citeI[#1]}}
\def\writeaux#1{\immediate\write\auxfile{\string\citation{#1}}}
\def\writeXcite#1{\openref\immediate\wref\Xcite{{#1}}}
\def\citelist{} \def\citelistB{}

\def\usebibtex#1#2{%
   \openref \openauxfile{#1}{#2}%
   \def\citeI[##1]{\writeaux{##1}}\citelist
   \global\let\addcitelist=\writeaux
   \bgroup \readbblfile{\jobname}\egroup
}
\def\openauxfile#1#2{%
   \immediate\openout\auxfile=\jobname.aux
   \immediate\write\auxfile
      {\percent\percent\space Opmac: AUX file reserved for bibtex only}%
   \immediate\write\auxfile{\string\bibdata{#1}}%
   \immediate\write\auxfile{\string\bibstyle{#2}}%
}
\def\readbblfile #1{%
  \openin\testin=#1.bbl
  \ifeof\testin
    \opwarning{The `#1.bbl' file doesn't exist. Use `bibtex'..}%
  \else
    \closein\testin
    \bibnum=0
    \long\def\begin##1\bibitem{\bibitem}\def\end##1{}% LaTeX environment
    \def\httpAddr##1{\url{http:##1}}\def\\{\hfill\break}%
    \def\newblock{\hskip .11em plus.33em minus.07em}%
    \def\mbox{\leavevmode\hbox}\def\emph##1{{\it##1}}%
    \parindent=\iindent \bibtexhook\relax
    \input #1.bbl
    \par
  \fi
}
\def\bibitem{\isnextchar[{\bibitemB}{\bibmark={}\bibitemC}}
\def\bibitemB[#1]{\bibmark={#1}\bibitemC}
\def\bibitemC#1{\bibitemD{#1}}
\def\bibitemD#1{\par\ifnum\bibnum>0 \bibskip \fi
   \advance\bibnum by1
   \noindent \def\tmpb{#1}\wbib{#1}{\the\bibnum}{\the\bibmark}% 
   \printbib \ignorespaces
}
\def\genbbl#1#2{\openauxfile{#1}{#2}%
   \immediate\write\auxfile{\string\citation{*}}%
   \bgroup
     \iindent=4em
     \def\bibitemC##1{\par\ifnum\bibnum>0 \bibskip \fi
        \advance\bibnum by1
        \noindent \hangindent=\parindent 
        \indent \llap{[##1]\enspace}\ignorespaces
     }%
     \readbblfile{\jobname}%
   \egroup
}
\def\usebbl/#1 #2 {\isdefined{bbl:#1}%
   \iftrue \csname bbl:#1\endcsname {#2}\else
      \opwarning{\string\usebbl/#1 #2 ... the `#1' type undefined}%
   \fi
}
\sdef{bbl:a}#1{\bgroup \readbblfile{#1}\egroup}

\sdef{bbl:b}#1{\bgroup
     \let\citeI=\relax \xdef\citelist{\citelist\citelistB}%
     \def\bibitemC##1 ##2\par{%
        \isinlist\citelist{[##1]}\iftrue \bibitemD{##1}##2\par\fi}%
     \readbblfile{#1}%
     \global\let\addcitelist=\writeXcite
  \egroup
}
\sdef{bbl:c}#1{\bgroup
     \ifx\citelinkA\empty \else 
         \opwarning{\string\nonumcitations: don't use \string\usebbl/c}\fi
     \let\citeI=\relax \xdef\citelist{\citelist\citelistB}%
     \def\bibitemC##1 ##2\par{%
        \isinlist\citelist{[##1]}\iftrue
           \if^\the\bibmark^\sdef{bb:##1}{\bibitemD{##1}##2\par}%
           \else \toks0={##2\par}%
                 \edef\tmpa{\noexpand\sdef{bb:##1}{% \the\bibmark have to expand
                      \noexpand\bibitemB[\the\bibmark]{##1}\the\toks0}}\tmpa
        \fi\fi}%
     \readbblfile{#1}%
     \def\bibitemC##1{\bibitemD{##1}}%
     \def\citeI[##1]{\csname bb:##1\endcsname}\citelist
     \global\let\addcitelist=\writeXcite
  \egroup
}
\def\Xcite#1{\addto\citelistB{\citeI[#1]}}

\def\usebib{\par \input opmac-bib \usebib}

%%%%%%%%%%%%%% output -- sec. 3.24 in opmac-d.pdf

\output={\begoutput \opmacoutput \endoutput}
\def\begoutput{%
   \immediate\wref\Xpage{{\the\pageno}}%
   \def\nl{ }\def\fnote##1{}\def\fnotemark##1{}%
   \prephoffset
}
\def\endoutput{} \def\prephoffset{}

\def\opmacoutput{%
  \setbox0=\vbox{\prepghook\ensureblacko{\makeheadline}\pagebody\ensureblacko{\makefootline}}%
  \pghook \protectlist
  \shipout\box0 \advancepageno
  \ifnum\outputpenalty>-20000 \else\dosupereject\fi
}
\def\doprotect#1{\let#1=\relax}
\def\prepage{\def\destheight{25pt}\dest[pg:\pgilabel.\the\pageno]}
\def\preboxcclv{}  \def\postboxcclv{}

{\catcode`\@=11
\gdef\pagecontents{\prepage % dest of pageno
  \ifvoid\topins\else\ensureblacko{\unvbox\topins}\fi
  \preboxcclv
  \dimen@=\dp\@cclv \unvbox\@cclv % open up \box255
  \postboxcclv
  \ifvoid\footins\else % footnote info is present
    \vskip\skip\footins
    \ensureblacko{\footnoterule \unvbox\footins}\fi
  \ifr@ggedbottom \kern-\dimen@ \vfil \fi
}}

\footline={\hss\tenrm\thefontsize[10]\folio\hss}

\newcount\lastpage  \lastpage=0  % the last page of the document
\def\Xpage#1{\lastpage=#1 \fnotenumlocal=0 }

%%%%%%%%%%%%%% margins -- sec. 3.25 in opmac-d.pdf

\newdimen\pgwidth  \newdimen\pgheight  \pgwidth=0pt
\newdimen\shiftoffset

\def\margins/#1 #2 (#3,#4,#5,#6)#7 {\def\tmp{#7}%
   \ifx\tmp\empty
      \opwarning{\string\margins: missing unit, mm inserted}\def\tmp{mm}\fi
   \addto\tmp{\relax}%
   \setpagedimens #2 % setting \pgwidth, \pgheight
   \ifdim\pgwidth=0pt \else
      \hoffset=-1\trueunit in \voffset=-1\trueunit in
      \if$#3$\if$#4$\tmpdim=\pgwidth \advance\tmpdim -\hsize
                    \divide\tmpdim by2 \advance\hoffset \tmpdim % left=right
             \else  \rbmargin\hoffset\hsize{#4\tmp}% only right margin
             \fi
      \else  \if$#4$\advance\hoffset #3\tmp   % only left margin
             \else  \hsize=\pgwidth           % left+right margin
                    \advance\hsize -#3\tmp \advance\hsize -#4\tmp
                    \advance\hoffset #3\tmp
      \fi\fi
      \if$#5$\if$#6$\tmpdim=\pgheight \advance\tmpdim -\vsize
                    \divide\tmpdim by2 \advance\voffset \tmpdim % top=bottom
             \else  \rbmargin\voffset\vsize{#6\tmp}% only bottom margin
             \fi
      \else  \if$#6$\advance\voffset #5\tmp   % only top margin
             \else  \vsize=\pgheight          % top+bottom margin
                    \advance\vsize -#5\tmp \advance\vsize -#6\tmp
                    \advance\voffset #5\tmp
      \fi\fi
      \if 1#1\shiftoffset=0pt \def\prephoffset{}\else \if 2#1% double-page layout
         \shiftoffset=\pgwidth \advance\shiftoffset -\hsize
         \advance\shiftoffset -2\hoffset \advance\shiftoffset -2in
         \def\prephoffset{\ifodd\pageno \else \advance\hoffset \shiftoffset \fi}%
      \else \opwarning{use \string\margins/1 or \string\margins/2}%
   \fi\fi\fi
}
\def\rbmargin#1#2#3{\advance#1\pgwidth \advance#1-#2 \advance#1-#3}

\def\setpagedimens{\isnextchar({\setpagedimensB}{\setpagedimensA}}
\def\setpagedimensA#1 {\isdefined{pgs:#1}\iftrue
   \expandafter\expandafter\expandafter\setpagedimensB \csname pgs:#1\expandafter\endcsname\space
   \else \opwarning{page specification "#1" is undefined}\fi}
\def\setpagedimensB (#1,#2)#3 {\setpagedimensC\pgwidth=#1:#3 \setpagedimensC\pgheight=#2:#3
    \ifx\pdfpagewidth\undefined \else
        \pdfpagewidth=\pgwidth \pdfpageheight=\pgheight \fi}
\def\setpagedimensC #1=#2:#3 {#1=#2\ifx^#3^\tmp\else#3\fi\relax\truedimen#1}

\sdef{pgs:a3}{(297,420)mm}  \sdef{pgs:a4}{(210,297)mm}  \sdef{pgs:a5}{(148,210)mm}
\sdef{pgs:a3l}{(420,297)mm} \sdef{pgs:a4l}{(297,210)mm} \sdef{pgs:a5l}{(210,148)mm}
\sdef{pgs:b5}{(176,250)mm}  \sdef{pgs:letter}{(8.5,11)in}

\def\trueunit{}
\def\magscale[#1]{\mag=#1\def\trueunit{true}%
   \ifdim\pgwidth=0pt \else \truedimen\pgwidth \truedimen\pgheight \fi
   \ifx\pdfpagewidth\undefined \else 
      \truedimen\pdfpagewidth \truedimen\pdfpageheight 
      \ifx\pdfhorigin\undefined\else       
         \pdfhorigin=1truein \pdfvorigin=1truein % Origin is independent off \mag
   \fi\fi}
\def\truedimen#1{\ifx\trueunit\empty \else#1=\expandafter\ignorept\the#1truept \fi}

%%%%%%%%%%%%%% XeTeX specific + REF file is read now -- sec 3.26 in opmac-d.pdf

\ifx\XeTeXversion\undefined \else \pdftexfalse \input opmac-xetex \fi
\ifx\pdfextension\undefined \else \input opmac-luatex \fi
\inputref
\endinput

%%%%%%%%%%%%%% History of versions:

beta (a) Nov. 2012 ... first released version.
Dec. 2012  first stable version
Jan. 2013  \parfillskip in \caption corrected.
           \athetnum, \captionhook introduced.
           \nobreak in \tocline corrected, \tocdotfill corrected.
           New \url, \urlcolor implicitly defined as \empty.
           \bibitem by \hangindent, \afteritcorr in \em
           \bslash introduced
           \toclinehook \mnotehook, \mnoteskip introduced.
           \global\advance in \caption corrected.
           \thechapnum is without the dot.
Feb. 2013  \urllink: works with \\, \%, \#, \$, \{, \}.
           \localcolor, \longlocalcolor introduced
           \global\advance for chap./sec. nums corrected
           \printcaption introduced
Apr. 2013  \table in \table allowed, \catcode`\|=12 set in \table.
           \printsec(c): \ifnum\lastpenalty added.
           \urlink: ``~ removing'' corrected
           {\em text}\macro error  corrected.
May  2013  \margins (2pages laylout) can be redefined by new \margins
           \outlines use \pdfcatalog{/PageMode/UseOutlines}
Jul. 2013  \fnotetext unwanted space - corrected
           \picw=0pt prints picture in natural size, \picheight introduced
           \isinlist corrected,
           \othe\secnum in \secc removed
           \dotocnum, \remskip, \reminsert introduced
           \nonum, \notoc implemented
           \destheight introduced as macro
           \runningfnotes introduced
           \addto defined as \long
           \iiskip, \ttskip, \bibskip precedes by \par
Aug. 2013  \dgsize corrected
           \ifx\tmpa\tmpb in \printiiA is realized via \meaning
           \ignorespaces included to \iis
           \url hidden in group, in order to handle & in tables
           \destheight rewritten as a dimen register
           \rightskip, \leftskip corrected in \mnote
           space corrected in \prepii
           \input ams-math only if \normalmath is \undefined (released)
Sep. 2013  \label: the ``duplicated label'' test added
           \afternoindent: \box0 -> \box7
           \scantabdata: \if#1| -> \ifx|#1
           \fixmnotes recoded
           \, uses \thinspace and it is \addprotected
           \pdfliteral instead \special{PDF:...} used
           XeTeX specific added
           \draft, \insertoulines recoded
           \endinsert redefined (\par added)
           \addprotect\exfont (for exchars.tex cooperating)
           \ulink improved and added to opmac-u
           \postboxcclv: {\advancepageno} corrected
Oct. 2013  /Border .6
           better \adef
           \typobase introduced
           \typoscale[20000/] ``too large dimension'' ... solved 
           \activettchar reimplemented
Nov. 2013  \Xpage: \ifnum\lastpage=#1 \else inserted
           \frame is defined as \long
           multilanuage: cz -> cs changed (by ISO 639-1)
           \cr -> \crcr in \crl, \crll and \crli
           \doverbinput: \ifeof\vifile added (bug ``empty line at EOF'' corrected)
           eTeX support for multilang added.
Feb. 2014  \sortcitations introduced, internal macros of \cite rewritten
Mar. 2014  \frame: \setbox0=\hbox{{#1}} in order to \aftergroup in #1
           \mnote: \pdfsave,\pdfrestore inserted, \mnote colors rewritten
Apr. 2014  \nonumcitations, \ecite, \printbib, \lastbibnum introduced
           \wbib, \citelink rewritten (more parameters now)
           \destheight rewritten as macro, sorry
           \fnotehook introduced
Apr. 2014b \nocite[*] bug removed, \insertmark corrected
Apr. 2014c nowarn about old csplain if csplain isn't used
May  2014  \hyphenchar\urlfont=-1, \urlspecchar introduced
May  2014b \linkactive introduced (bug fixing)
May  2014c \maybebreak introduced
May  2014d \seccfont bug fixed
           \tabstrut inserted to each column in the \table
Jun  2014  \opwarning about missing .bbl file rewritten.
           more robust \replacestrings
Jun. 2014a \mnoteC: default base mnote color set as current
Jun. 2014b \footline: \the\pageno replaced by \folio
           ? instead \/ in \replacestrings
Jun. 2014c \pgfolioA, \pgfolioB introduced
           \Xindexg introduced
Jul. 2014  \bgroup -> \begingroup in \adef
Aug. 2014  \parskip=0pt in \begtt ...\endtt
           \addtabdata: redundant \expandafter removed
Sep. 2014  \bib [...] = {...} space before = is now optional
           \nbpar in \caption
           \replacestrings: reduced by 3\expandafter
           \isnextchar, \isinlist prefixed as \long
           \testparA uses \romannumeral trick now.
Oct. 2014  \pdfborder corrected: /Border [0 0 0] set for AR users.
Nov. 2014  \sortingdata corrected, \specsortingdata introduced.
           \replacestrings uses \replacestringsA instead \tmp
           \bfshape used in \titfont and \Xchap
           \adef{ }{\ } in verbatim environment (instead \adef{ }{ }).
           \fnotemark+\fnotetext+\runningfnotes bug fixed.
           \flushcolumns, \iiparams removed, \mullines introduced.
Dec. 2014  Color features rewritten using \pdfcolorstack.
           Unwanted spaces in \dosorting removed.
           Better definition of \frame.
           \margins/\setpagedimens improved, \isnextchar: \bgroup\egroup added.
Apr. 2015  \wtotoc, \Xtoc, \tocilabel, \pgilabel introduced.
           \outlinesC introduced
           \setpagedimensC corrected: \truedimen
           \opwarnig about missing \hyperlinks in \outlines added.
           \fnotetext: \fnotehook inserted (bug fixing)
May  2015  \itemhook introduced
           \REFversion introduced
           \prepghook introduced, \draft redefined using \prepghook
           \mnote, \fnote redeclared as \long
Jun  2015  \urlfont: \hyphenchar=-1 removed (bug fixed)
           \mnote: \nobreak after \wref added (bug fixed)
           csbxti10 -> cmbxti10, corrected for non-csplain users
           default \ulink: \leavevmode added (bug fixed)
Jul. 2015  \openref: \def\wref -> \gdef\wref (bug fixed)
           \margins/2: \prephoffset introduced (bug fixed)
           \hyperlinks when non-pdftex prints warning
Sep. 2015  \sortingdata<iso-code> introduced, \isolangset introduced.
           \toasciidata<iso-code> introduced.
           \dosorting: local \iisort changes.
Oct. 2015  \printttline, \ptthook introduced, \viprintline redesigned.
           \everypar\expandafter{\the\everypar...} in \begtt, \doverbinput.
Nov. 2015  \parskip=0 in \doverbinput, \vskip\parskip before first \ttskip
           \addto\prepghook instead \def\prepghook in \draft
           \mnote: ifvmode \hbox{\strut...} added
Jan. 2016  \inspicpage introduced
           \isolangset: \chardef..Patt added
Mar. 2016  \thefnote default changed: ^{num}) -> ^{num} 
Apr. 2016  \frame: redundant group removed
           \isnextchar improved (using \toks)
           \eoldef introduced to \tit, \chap, \sec, \secc, see OPmac trick 0121
           \input opmac-luatex.tex introduced
           \slet introduced
           \fontfam introduced, \usebib as module loaded
May  2016  \replacestrings improved
           \bfshape: \everymath={\boldmath} instead \boldmath directly
           \tskip corrected
Jun  2016  \thefontsize: \fontdim=#1\ptunit added.
           \pdfhvorigin unknown in XeTeX, bug fixed
Jun  2017  \begingroup...\endgroup trick introduced in \isinlist
           \table: repeating and p declarator added, 
           \colnum=0 in table corrected (cor cases table in table) 
           \mspan added
           \fnotetext: \everypar={} added (bug correction)
Mar. 2018  \frame: \relax after \kern\hhkern added (bug correction)
Mar. 2018a \uv defined as \long

%%%%%%%%%%%%%% End of opmac.tex
