% OPmac
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Petr Olsak, 2012

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

\ifx\OPmacversion\undefined \else \endinput \fi
\def\OPmacversion{Dec. 2012}

\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.}}

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

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

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

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

\def\adef#1{\lccode`\~=`#1\catcode`#1=13
   \afterassignment\lccodetiezero
   \lowercase{\def~}%
}
\def\lccodetiezero{\lccode`\~=0 }

\def\isdefined #1#2{\expandafter\ifx \csname#1\endcsname \relax
     \csname iffalse\expandafter\endcsname
   \else
     \csname iftrue\expandafter\endcsname
   \fi
}
\def\isinlist#1#2#3{\def\tmp##1#2##2\end{\def\tmp{##2}%
   \ifx\tmp\empty \csname iffalse\expandafter\endcsname \else
                  \csname iftrue\expandafter\endcsname \fi}%
   \expandafter\tmp#1#2\end
}
\def\isnextchar#1#2#3{\def\tmpa{#2}\def\tmpb{#3}%
   \let\tmp=#1\futurelet\next\isnextcharA
}
\def\isnextcharA{\ifx\tmp\next\expandafter\tmpa\else\expandafter\tmpb\fi}

\def\uv#1{\clqq#1\crqq}
\let\\=\undefined
{\lccode`\?=`\%  \lowercase{\gdef\percent{?}}}
\def\,{\ifmmode \mskip\thinmuskip \else \kern.166em \fi}


%%%%%%%%%%%%%% 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\iiskip{\medskip}     % space above and below \begitems...\enditems
\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\pghook{}     % hook in \output rutine


%%%%%%%%%%%%%% 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
   \opwarning{csplain version <Nov. 2012> or later is recommended}
   % macros from csplain, file csfontsm.tex:
   \font\tenbi=csbxti10 \def\bi{\tenbi}
   \def\sizespec{}
   \def\resizefont #1{\expandafter
     \font\expandafter#1\expandafter\resizefontskipat\fontname#1 \relax}
   \def\regfont#1{\expandafter\def\expandafter\resizeall\expandafter{%
     \resizeall \resizefont#1}}
   \def\resizeall{}
   \regfont\tenrm \regfont\tenit \regfont\tenbf \regfont\tenbi \regfont\tentt
\fi

\input ams-math  % ams-math.tex is in csplain package Nov. 2012 or later

\def\resizefontskipat#1 #2\relax{\whichtfm{#1} \sizespec\relax}

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

{\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
  \let\dgsize=\fontdim
  \edef\sizespec{at\the\fontdim}%
  \resizeall \rm
  \fi
}
\def\setbaselineskip[#1]{\if$#1$\else
  \tmpdim=#1\ptunit
  \baselineskip=\tmpdim \relax
  \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
  \tmpdim=#1pt \divide\tmpdim by1000
  \tmpdim=\expandafter\ignorept\the\tmpdim \fontdim
  \withoutunit\fontsizex\tmpdim
  \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
  \tmpdim=#1pt \divide\tmpdim by1000
  \tmpdim=\expandafter\ignorept\the\tmpdim \baselineskip
  \withoutunit\setbaselineskip\tmpdim
  \fi
}
\def\thefontsize[#1]{%
  \expandafter\let \expandafter\thefont \the\font
  \def\sizespec{at#1\ptunit}\def\dgsize{#1\ptunit}\resizefont\thefont
  \thefont \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\em {\expandafter\ifx \the\font \tenit \additcorr \rm  \else
         \expandafter\ifx \the\font \tenbf \bi\aftergroup\/\else
         \expandafter\ifx \the\font \tenbi \additcorr \bf  \else
         \it \aftergroup\/\fi\fi\fi}
\def\additcorr{\ifdim\lastskip>0pt \skip0=\lastskip \unskip\/\hskip\skip0 \else\/\fi}

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


%%%%%%%%%%%%%% 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:cz}{Kapitola}  \sdef{mt:chap:sk}{Kapitola}
\sdef{mt:t:en}{Table}       \sdef{mt:t:cz}{Tabulka}      \sdef{mt:t:sk}{Tabu\v lka}
\sdef{mt:f:en}{Figure}      \sdef{mt:f:cz}{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}{cz}  \sdef{lan:15}{cz}  \sdef{lan:115}{cz}
\sdef{lan:6}{sk}  \sdef{lan:16}{sk}  \sdef{lan:116}{sk}

%%%%%%%%%%%%%% 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
    \immediate\openout\reffile=\jobname.ref
    \def\wref##1##2{\write\reffile{\string##1##2}}
    \immediate\write\reffile {\percent\percent\space OPmac - REF file}
  \fi
}
\def\openref{%
  \ifx\wref\wrefrelax
     \immediate\openout\reffile=\jobname.ref
     \gdef\wref##1##2{\write\reffile{\string##1##2}}%
     \immediate\write\reffile
       {\percent\percent\space OPmac - REF file (\string\openref)}%
  \fi
  \gdef\openref{}%
}

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

\def\label[#1]{\xdef\lastlabel{#1}\ignorespaces}

\def\wlabel#1{%
  \ifx\lastlabel\undefined \else
     \dest[ref:\lastlabel]{2.1em}%
     \edef\tmp{\wref\Xlabel{{\lastlabel}{#1}}}\tmp
     \isdefined{lab:\lastlabel}\iftrue \else
        \sxdef{lab:\lastlabel}{#1}%
     \fi
     \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\titfont{\typoscale[\magstep4/\magstep4]\bf}
\def\chapfont{\typoscale[\magstep3/\magstep3]\bfshape}
\def\secfont{\typoscale[\magstep2/\magstep2]\bfshape}
\def\seccfont{\typoscale[\magstep1/\magstep2]\bfshape}
\def\bfshape{\let\tenit=\tenbi \boldmath \bf}

\newcount\chapnum \newcount\secnum \newcount\seccnum

\def\tit#1\par{\vglue4em
  {\leftskip=0pt plus1fill \rightskip=\leftskip
   \titfont \noindent #1\unskip\par}%
  \nobreak\bigskip
}
\def\chap#1\par{\advance\chapnum by1
  \chaphook \secnum=0 \seccnum=0 \relax
  \edef\thechapnum{\the\chapnum.}%
  \printchap{#1\unskip}%
  \wlabel\thechapnum \wcontents\Xchap\thechapnum{#1}\nobreak
}
\def\sec#1\par{\par\advance\secnum by1
  \sechook \seccnum=0 \tnum=0 \fnum=0 \dnum=0 \relax
  \edef\thesecnum{\othe\chapnum.\the\secnum}%
  \printsec{#1\unskip}%
  \insertmark\thesecnum{#1\unskip}%
  \wlabel\thesecnum \wcontents\Xsec\thesecnum{#1}\nobreak
}
\def\secc#1\par{\advance\seccnum by1
  \secchook \relax
  \edef\theseccnum{\othe\chapnum.\othe\secnum.\the\seccnum}%
  \printsecc{#1\unskip}%
  \wlabel\theseccnum \wcontents\Xsecc\theseccnum{#1}\nobreak
}
\def\wcontents#1#2#3{%
  \expandafter\wref\expandafter#1\expandafter
     {\expandafter{#2}{#3}{\the\pageno}}%
}
\def\othe#1.{\ifnum#1>0 \the#1.\fi}
\def\thechapnum{} \def\thesecnum{} \def\theseccnum{}

\def\insertmark#1#2{\toks0={#2}\mark{{#1} {\the\toks0}}}

\def\printchap#1{\vfil\break
  {\chapfont \noindent \dest[toc:\thechapnum]{1.3em}%
     \mtext{chap} \thechapnum\par\nobreak\smallskip\noindent #1\nbpar}%
  \nobreak\bigskip
  \firstnoindent
}
\def\printsec#1{\removelastskip \goodbreak \bigskip
  {\secfont \noindent \dest[toc:\thesecnum]{1.3em}\thesecnum\quad #1\nbpar}%
  \nobreak\medskip
  \firstnoindent
}
\def\printsecc#1{\removelastskip \goodbreak \medskip
  {\seccfont \noindent
   \dest[toc:\theseccnum]{1.3em}\theseccnum\quad #1\nbpar}%
  \nobreak\medskip
  \firstnoindent
}
\def\afternoindent{\global\everypar={\wipeepar\setbox0=\lastbox}}
\def\wipeepar{\global\everypar={}}
\let\firstnoindent=\afternoindent
\def\nbpar{{\interlinepenalty=10000\par}}
\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 \advance \csname #1num\endcsname by1
   \else   \opwarning{Unknown caption /#1}%
   \fi
   \bgroup
      \leftskip=\iindent plus1fil
      \rightskip=\iindent plus-1fil
      \parfillskip=\iindent plus2fil
      \def\par{\endgraf\egroup}%
      \noindent \wlabel{\csname the#1num\endcsname}%
      {\bf \mtext{#1} \csname the#1num\endcsname}\enspace
}
\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{\iiskip\bgroup
  \itemnum=0 \adef*{\startitem}
  \advance\leftskip by\iindent
  \let\printitem=\normalitem
}
\def\enditems{\par\egroup\iiskip}

\def\startitem{\par \advance\itemnum by1
   \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\Xchap#1#2#3{\ischaptrue\addto\toclist{\tocline{0}{\bf}{#1}{#2}{#3}}}
\def\Xsec#1#2#3{\addto\toclist{\tocline{1}{\rm}{#1}{#2}{#3}}}
\def\Xsecc#1#2#3{\addto\toclist{\tocline{2}{\rm}{#1}{#2}{#3}}}

\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
   \noindent\llap{#2\toclink{#3}\enspace}%
         {#2#4\unskip}\tocdotfill\pglink{#5}\hskip-2\iindent\null\par}}
\def\tocdotfill{\leaders\hbox to.8em{\hss.\hss}\hfill}

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


%%%%%%%%%%%%%% 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#1#2{\bgroup \def~{ }%
   \isdefined{,#1}\iftrue
     \expandafter\firstdata \csname,#1\endcsname \XindexA
     \ifnum#2=\tmpa % \ii on the same page
     \else
        \tmpnum=#2 \advance\tmpnum by-1
        \expandafter\seconddata \csname,#1\endcsname \XindexB
        \if\tmpb+% state: the pagelist ends by a pagenumber
           \ifnum\tmpnum=\tmpa  % the consecutive page
              \sxdef{,#1}{{#2/-}{\tmp\iiendash}}
           \else                % the pages drop
              \sxdef{,#1}{{#2/+}{\tmp, #2}}
           \fi
        \else    % state: the pagelist ends by --
           \ifnum\tmpnum=\tmpa  % the consecutive page
              \sxdef{,#1}{{#2/-}{\tmp}}
           \else                % the pages drop
              \sxdef{,#1}{{#2/+}{\tmp\tmpa, #2}}
           \fi
        \fi
     \fi
   \else % first occurrence of the index item #1
     \sxdef{,#1}{{#2/+}{#2}}
     \global \expandafter\addto \expandafter\iilist \csname,#1\endcsname
   \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\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\tmpa}}
          \fi
          \expandafter\act\fi}
      \expandafter \act \iilist \relax
    \egroup
    \dosorting  % sorting is in progress
    \iiparparams
    \gdef\act##1{\ifx##1\relax \else \prepii##1%
             \seconddata##1\printiipages \expandafter\act \fi}
      \expandafter \act \iilist \relax
    \orippx \global\let\act=\undefined \global\let\orippx=\undefined
  \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
}
\def\iispeclist{}

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

\def\iiparparams{%
   \xdef\orippx{\global\rightskip=\the\rightskip
               \global\leftskip=\the\leftskip
               \global\exhyphenpenalty=\the\exhyphenpenalty}
   \global\rightskip=0pt plus1fil
   \global\exhyphenpenalty=10000
   \global\leftskip=\iindent
}

\def\scanprevii#1/#2&{\def\previi{#2}\def\tmpa{#1}}
\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,%
  h^^HH,%
  ^^T^^U^^V,%
  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\setprimarysorting {\csname sort:\csname lan:\the\language\endcsname \endcsname
  \def\act##1{\ifx##1.\else
     \ifx##1,\advance\tmpnum by1
     \else \lccode`##1=\tmpnum \fi
     \expandafter \act \fi}%
  \ifx\r\undefined 
     \opwarning{\noexpand\csaccents is unused, falling back to ASCII sorting}%
     \gdef\sortingdata{.}\global\let\chsorting=n%
  \else
     \xdef\sortingdata{\sortingdata}% expand sorting data now
  \fi 
  \tmpnum=133 \expandafter \act\sortingdata \setignoredchars
}
\sdef{sort:en}{\global\let\chsorting=n} % skipping ch processing in English language

\def\setsecondarysorting {\def\act##1{\ifx##1.\else
     \ifx##1,\else \advance\tmpnum by1 \lccode`##1=\tmpnum \fi
     \expandafter \act \fi}%
  \tmpnum=133 \expandafter \act\sortingdata \setignoredchars
}
\bgroup
\lccode`4=`c \lccode`5=`h \lccode`6=`C \lccode`7=`H
\lowercase{
\gdef\iiscanch #145#2\relax{#1\if$#2$\else^^T\iiscanch #2\relax\fi}
\gdef\iiscanCh #165#2\relax{#1\if$#2$\else^^U\iiscanCh #2\relax\fi}
\gdef\iiscanCH #167#2\relax{#1\if$#2$\else^^V\iiscanCH #2\relax\fi}
\gdef\preparesorting#1{\expandafter\preparesortingA\string#1&}
\gdef\preparesortingA#1#2#3&{\xdef\tmpb{#3}%
  \ifx\chsorting\undefined 
    \xdef\tmpb{\expandafter\iiscanch\tmpb 45\relax}%
    \xdef\tmpb{\expandafter\iiscanCh\tmpb 65\relax}%
    \xdef\tmpb{\expandafter\iiscanCH\tmpb 67\relax}\fi
  \lowercase\expandafter{\expandafter\gdef\expandafter\tmpb\expandafter{\tmpb}}%
  \xdef\tmpb{\expandafter\removedot\tmpb.\relax}%
}}
\egroup

\def\removedot #1.#2\relax{#1\if$#2$\else\removedot #2\relax\fi}
\def\setignoredchars{\setlccodes ,.;.?.!.:.'.".|.(.).[.].<.>.=.+.{}{}}

\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...}
   \def\act##1{\ifx##1\relax\else \global\addto\iilist{##1,}%
             \expandafter\act\fi}
   \expandafter\removeiilist \expandafter\act \iilist\relax
   \expandafter\removeiilist \expandafter\mergesort \iilist \end,\end
}
\def\removeiilist{\gdef\iilist{}}

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

\def\corrsize #1{%% #1 := #1 + \splittopskip - \topskip
   \advance #1 by \splittopskip \advance #1 by-\topskip}

\def\begmulti #1 {\par\wipeepar\multiskip\penalty0 \def\Ncols{#1}
   \splittopskip=\baselineskip
   \setbox6=\vbox\bgroup\penalty0
   %% \hsize := Sirka sloupce = (\hsize+\colsep) / n - \colsep
   \advance\hsize by\colsep
   \divide\hsize by\Ncols  \advance\hsize by-\colsep
   \dimen0=0pt
   \def\par{\endgraf\advance\dimen0 by\the\prevgraf\baselineskip
            \ifdim\dimen0>.9\maxdimen \message{flushcolumns:}%
               \global\let\balancecolumns=\flushcolumns \expandafter \endmulti
            \fi}%
}
\def\endmulti{\vskip-\prevdepth\vfil\egroup \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
   \dimen0=\ht6 \divide\dimen0 by\Ncols \relax
   %% split the material to more pages?
   \ifdim \dimen0>\dimen1 \splitpart
   \else \balancecolumns \fi  % only balancing
   \multiskip\relax}
\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}
   \egroup}
\def\splitpart{%
   \makecolumns % full page
   \vskip 0pt plus 1fil minus\baselineskip \break
   \dimen0=\ht6 \divide\dimen0 by\Ncols \relax
   \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
}
\def\flushcolumns#1\relax{\fi\fi\fi
   \setbox6=\vbox\bgroup\penalty0
   \global\let\balancecolumns=\ibalancecolumns
   \dimen0=\ht6 \unvbox6 \unskip\unskip
   \advance\hsize by\colsep
   \divide\hsize by\Ncols  \advance\hsize by-\colsep
   \def\par{\endgraf\advance\dimen0 by\the\prevgraf\baselineskip
            \ifdim\dimen0>.9\maxdimen \message{flush-columns:}%
               \global\let\balancecolumns=\flushcolumns \expandafter \endmulti
            \fi}%
}
\let\ibalancecolumns=\balancecolumns

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

\newif\ifpgcolor \pgcolorfalse
\newcount\lastpage  \lastpage=0  % the last page of the document

\def\Blue{\setcmykcolor{1.0 1.0 0.0 0}}
\def\Red{\setcmykcolor{0.0 1.0 1.0 0}}
\def\Brown{\setcmykcolor{0 0.67 0.67 0.5}}
\def\Green{\setcmykcolor{1.0 0.0 1.0 0.0}}
\def\Yellow{\setcmykcolor{0.0 0.0 1 0}}
\def\Cyan{\setcmykcolor{1.0 0.0 0 0}}
\def\Magenta{\setcmykcolor{0.0 1.0 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}\global\pgcolorfalse}

\ifpdftex
  \def\setcmykcolor#1{\special{PDF:#1 \pdfK}%
    \ifpgcolor\else
       \openref\expandafter\wref\expandafter\Xpdfcolor\expandafter{\pdfK{#1}}%
    \fi
  }
\else
  \def\setcmykcolor#1{}
\fi

\def\linecolor#1{{\def\pdfK{K}#1}}
\def\pdfK{k}
\def\locpgcolor{\global\pgcolortrue}

\def\Xpdfcolork#1{\def\pdflastcolork{#1}}
\def\XpdfcolorK#1{\def\pdflastcolorK{#1}}
\def\pdfblackcolor{0 0 0 1}
\let\pdflastcolork=\pdfblackcolor \let\pdflastcolorK=\pdfblackcolor

\def\Xpage#1{\lastpage=#1 \fnotenumlocal=0
   \ifx\pdflastcolork\pdfblackcolor\else
      \isdefined{pg:#1}\iftrue \else \sxdef{pg:#1}{}\fi
      {\let\setpgcolor=\relax \sxdef{pg:#1}%
            {\csname pg:#1\endcsname\setpgcolor k{\pdflastcolork}}}\fi
   \ifx\pdflastcolorK\pdfblackcolor\else
      \isdefined{pg:#1}\iftrue \else \sxdef{pg:#1}{}\fi
      {\let\setpgcolor=\relax \sxdef{pg:#1}%
            {\csname pg:#1\endcsname\setpgcolor K{\pdflastcolorK}}}\fi
}
\def\setpgcolor#1#2{\special{PDF:#2 #1}}

\def\draft{\edef\tmp{\headline={\noexpand\draftbox{\tenbf DRAFT}\the\headline}}
   \ifpdftex \tmp \else
      \opwarning{\string\draft: Grey color is possible in pdfTeX only}\fi}

\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{\locpgcolor\LightGrey \box0\hss\Black}%
   \pdfrestore
\hss}\vss}\hss}


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

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

\def\link[#1:#2]#3#4{\leavevmode\pdfstartlink height.9em depth.3em
      \pdfborder{#1} goto name{#1:#2}\relax
      \ifx\Black#3#4\else#3#4\Black\fi \pdfendlink
}
\def\urllink[#1:#2]#3{{\leavevmode\pdfstartlink height.9em depth.3em
   \pdfborder{#1}user{/Subtype/Link/A << /Type/Action/S/URI/URI(#2)>>}\relax
   \urlcolor{#3}\Black\pdfendlink}%
}
\def\url{\leavevmode\bgroup \adef{/}{\\}%
   \catcode`\_=12 \catcode`\#=12 \catcode`\~=12 \dourl}
\def\dourl#1{\def\\{/}\ulink[url:#1]{\tt\def\\{\discretionary{/}{}{/}}#1}\egroup}

\def\toclink#1{#1}
\def\pglink#1{#1}
\def\citelink#1{#1}
\def\reflink[#1]#2{#2}
\def\ulink[#1]#2{#2}

\def\hyperlinks#1#2{%
   \let\dest=\destactive
   \def\toclink##1{\locpgcolor\link[toc:##1]{#1}{##1}}%
   \def\pglink##1{\locpgcolor\link[pg:##1]{#1}{##1}}%
   \def\citelink##1{\locpgcolor\link[cite:##1]{#1}{##1}}%
   \def\reflink[##1]##2{\locpgcolor\link[ref:##1]{#1}{##2}}%
   \def\ulink[##1]##2{\urllink[##1]{##2}}%
   \def\urlcolor{#2}%
}

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

\ifpdftex \else
  \def\dest[#1]#2{}
  \def\link[#1]#2#3{#3}
  \def\urllink[#1]#2{#2}
  \def\hyperlinks#1#2{}
\fi


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

\def\outlines#1{\openref\ifx\toclist\empty
     \opwarning{\noexpand\outlines -- data unavailable. TeX me again}%
   \else
     {\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 
  \expandafter \setlccodes \toasciidata{}{}%
  \cnvhook \lowercase{\gdef\tmp{#4}}%
  \pdfoutline goto name{toc:#3} count
     \ifnum#1<\outlinelevel\space\else-\fi\tmpnum {\tmp}\relax
}
\def\setcnvcodesA{\global\let\setcnvcodesA=\relax % I am working only once
  \ifx\r\undefined
     \gdef\toasciidata{}
     \opwarning{\noexpand\csaccents unused, CZ/SK outline-conversion is off}%
  \else
     \xdef\toasciidata{\toasciidata}%
  \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}

\def\insertoutline#1{\pdfdest name{oul:#1} xyz\relax
   \pdfoutline goto name{oul:#1} 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{\def\do##1{\catcode`##1=12}\dospecials \catcode`\*=12 }
\def\begtt{\ttskip\bgroup \wipeepar
   \setverb \adef{ }{ }%
   \ifx\savedttchar\undefined \else \catcode\savedttchar=12 \fi
   \parindent=\ttindent
   \tthook\relax
   \ifnum\ttline<0 \else
     \tenrm \thefontscale[700]\let\sevenrm=\thefont
     \everypar={\global\advance\ttline by1
                \llap{\sevenrm\the\ttline\kern.9em}}\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#1|egroup|ttskip|testparA}}
\def\testparA{\afterassignment\testparB\let\tmpa= }
\def\testparB{\futurelet\tmpa\testparC}
\def\testparC{\ifx\tmpa\par\else\afternoindent\fi}

\def\activettchar#1{%
   \ifx\savedttchar\undefined\else \catcode\savedttchar=\savedttcharc \fi
   \chardef\savedttchar=`#1%
   \chardef\savedttcharc=\catcode`#1%
   \lccode`\~=`#1
   \lowercase {\def~}{\leavevmode\hbox\bgroup\setverb\adef{ }{ }%
                      \intthook\tt\readverb}%
   \lowercase{\def\readverb ##1~}{##1\egroup}%
   \lccode`\~=0 \catcode\savedttchar=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
   \ttskip\bgroup \wipeepar
   \setverb \adef{ }{ }%
   \ifx\savedttchar\undefined \else \catcode\savedttchar=12 \fi
   \parindent=\ttindent
   \tthook\relax
   \ifnum\ttline<-1 \else
      \tenrm \thefontscale[700]\let\sevenrm=\thefont \fi
   \tmpnum=0 \tt
   \loop \ifeof\vifile \tmpnum=\vinolines\space \fi
         \ifnum\tmpnum<\vinolines\space
         \vireadline \advance\tmpnum by1 \repeat      %% skip line
   \tmpnum=0 \ifnum\vidolines=0 \tmpnum=-1 \fi
   \loop \ifeof\vifile \tmpnum=\vidolines\space \fi
         \ifnum\tmpnum<\vidolines\space
         \vireadline \penalty\ttpenalty \viprintline  %% print line
             \ifnum\vidolines=0 \else\advance\tmpnum by1 \fi \repeat
   \egroup\ttskip\testparB
}
\def\vireadline{\read\vifile to \tmp \global\advance\viline by1 }
\def\viprintline{\indent
   \ifnum \ttline<-1 \else
      \llap{\sevenrm\ifnum\ttline<0 \the\viline \else
               \global\advance\ttline by1 \the\ttline \fi \kern.9em}%
   \fi
   \tmp\par % print the line from \tmp
}


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

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

\def\table#1#2{\vbox{\offinterlineskip
   \def\tmpa{}\scantabdata#1\relax
   \halign\expandafter{\the\tabdata\tabstrutA\cr#2\crcr}}}

\def\scantabdata#1{%
   \ifx#1\relax\let\scantabdata=\relax
   \else\if#1|\addtabvrule
   \else\expandafter\ifx\csname tabdeclare#1\endcsname \relax
     \opwarning{tab-declare letter #1 unknown, ignored}%
        \else\expandafter \addtabitem\expandafter{\csname tabdeclare#1\endcsname}%
   \fi\fi\fi \scantabdata
}
\def\tabdeclarec{\tabiteml\hfil##\unsskip\hfil\tabitemr}
\def\tabdeclarel{\tabiteml##\unsskip\hfil\tabitemr}
\def\tabdeclarer{\tabiteml\hfil##\unsskip\tabitemr}

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

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

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

\def\tskip{\afterassignment\tskipA \tmpdim}
\def\tskipA{\gdef\dditem{}\gdef\vvitem{}\gdef\tabstrutA{}%
    \vrule height\tmpdim width0pt \ddlinedata\cr
    \gdef\tabstrutA{\tabstrut}}

\let\orihrule=\hrule  \let\orivrule=\vrule
\def\rulewidth{\afterassignment\rulewidthA \tmpdim}
\def\rulewidthA{\edef\hrule{\orihrule height\the\tmpdim}%
                \edef\vrule{\orivrule width\the\tmpdim}}

\def\frame#1{\setbox0=\hbox{#1}\setbox1=\vbox{\hrule}%
   \tmpdim=\dp0 \advance\tmpdim by\ht1 \advance\tmpdim by\hhkern
   \vbox{\hrule\hbox{\vrule\kern\vvkern
         \vbox{\kern\hhkern\box0\kern\hhkern}\kern\vvkern\vrule}%
         \hrule\kern-\tmpdim\hbox{\vrule depth\tmpdim width0pt}}}


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

\newdimen\picw   \picw=0pt

\ifpdftex
  \def\inspic #1 {\ifdim\picw=0pt
       \opwarning{\noexpand\inspic -- the width \noexpand\picw is not set}%
     \else
       \hbox{\pdfximage width\picw {\picdir#1}\pdfrefximage\pdflastximage}%
     \fi
  }
\else
  \def\inspic #1 {\opwarning
     {The \noexpand\inspic is supported for PDF output only}}
\fi

%%%%%%%%%%%%%%% 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

\def\fnote#1{\global\advance \fnotenum by1
   \leavevmode\openref\wref\Xfnote{}%
   \isdefined{fn:\the\fnotenum}\iftrue
   \else\opwarning{unknown \noexpand\fnote mark. TeX me again}\fi
   \fnmarkx{\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}%
}
\def\fnotetext#1{\global\advance \fnotenum by1 \openref\wref\Xfnote{}%
   {\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}}

\newcount\mnotenum    \mnotenum=0       % global counter of mnotes

\def\mnote#1{\ifvmode \mnoteA{#1}\nobreak\vskip-\baselineskip
   \else \strut\vadjust{\kern-\dp\strutbox \mnoteA{#1}\kern\dp\strutbox}%
   \fi
}
\def\mnoteA#1{\global\advance \mnotenum by1
   \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{}%
   \expandafter\ifx\tmp \left
      \hbox to0pt{\kern-\mnotesize \kern-\mnoteindent
         \vbox to0pt{\vss \setbox0=\vtop{%
             \hsize=\mnotesize \leftskip=0pt plus 1fill\noindent#1}%
               \dp0=0pt \box0}\hss}%
   \else
      \hbox to0pt{\kern\hsize \kern\mnoteindent
         \vbox to0pt{\vss \setbox0=\vtop{%
             \hsize=\mnotesize \rightskip=0pt plus 1fil\noindent#1}%
               \dp0=0pt \box0}\hss}%
   \fi
}
\def\Xmnote{\advance\mnotenum by1
   \sxdef{mn:\the\mnotenum}{\ifodd\lastpage \right \else \left \fi}}

\def\fixmnotes#1{\tmpnum=0
   \loop \advance\tmpnum by1
         \isdefined{mn:\the\tmpnum}\iftrue \sxdef{mn:\the\tmpnum}{#1}\repeat}

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

\newwrite\auxfile                      % AUX file for BibTeX
\newcount\bibnum                       % the bibitem counter
\newcount\lastcitenum  \lastcitenum=0  % for \shortcitations

\def\cite[#1]{{[\chardef\tmpb=0 \citeA #1,,,%
   \ifnum\tmpb>0 \printdashcite{\the\tmpb}\fi]}}
\def\nocite[#1]{{\def\docite##1{}\citeA #1,,,}}
\def\citeA #1#2,{\if#1,\else \rcite{#1#2}\expandafter\citeA\fi}
\def\citesep{}

\def\rcite#1{%
   \if *#1\addcitelist{*}\expandafter \skiptorelax \fi
   \expandafter \ifx \csname bib:#1\endcsname \relax
      \addcitelist{#1}%
      \opwarning{The cite [#1] unknown. Try to TeX me again}%
      \docite{}\openref
      \expandafter\gdef\csname bib:#1\endcsname {}%
      \expandafter \skiptorelax \fi
   \expandafter \ifx \csname bib:#1\endcsname \empty
      \docite{}%
      \expandafter \skiptorelax \fi
   \def\bibnn##1{}%
   \if &\csname bib:#1\endcsname
      \addcitelist{#1}%
      \def\bibnn##1##2{##1}%
      \sxdef{bib:#1}{\csname bib:#1\endcsname}%
   \fi
   \docite{\csname bib:#1\endcsname}%
   \relax
}
\def\printcite#1{\citesep\citelink{#1}\def\citesep{,\hskip.2em\relax}}
\def\printdashcite#1{\hbox{--}\citelink{#1}}

\def\docite#1{\if$#1$??%
   \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
}
\def\shortcitations{\lastcitenum=1 }

\def\bib[#1]{\par \ifnum\bibnum>0 \bibskip \fi
   \advance\bibnum by1
   \wbib{#1}{\the\bibnum}%
   \hangindent=\iindent \hangafter=1
   \noindent \dest[cite:\the\bibnum]{1.2em}%
   \hskip\iindent \llap{[\the\bibnum] }\ignorespaces
}
\def\wbib#1#2{\edef\tmp{\wref\Xbib{{#1}{#2}}}%
  \ifx\tmp\empty\else \immediate\tmp \fi
}
\def\Xbib#1#2{\sdef{bib:#1}{\bibnn{#2}&}}

\def\addcitelist#1{\global\addto\citelist{\lcite[#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\lcite[##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{.bbl file doesn't exist.
                Use the ``bibtex #1'' command}%
  \else
    \closein\testin
    \bibnum=0
    \def\begin##1##2{}\def\end##1{}% LaTeX environment
    \def\newcommand##1 {}%
    \def\httpAddr##1{\url{http:##1}}\def\\{\hfill\break}%
    \def\newblock{\hskip .11em plus.33em minus.07em}%
    \def\mbox{\leavevmode\hbox}\let\em=\it
    \leftskip=\iindent
    \bibtexhook\relax
    \input #1.bbl
    \par
  \fi
}
\def\bibitem{\isnextchar[{\bibitemB}{\def\tmpa{}\bibitemC}}
\def\bibitemB[#1]{\def\tmpa{#1}\bibitemC}
\def\bibitemC#1{\bibitemD{#1}}
\def\bibitemD#1{\ifnum\bibnum>0 \bibskip \fi
   \advance\bibnum by1
   \noindent \dest[cite:\if$\tmpa$\the\bibnum\else\tmpa\fi]{1.2em}%
   \if$\tmpa$\llap{[\the\bibnum] }\wbib{#1}{\the\bibnum}\else
                 \hskip-\iindent [\tmpa]\wbib{#1}{\tmpa}\enskip
   \fi
   \ignorespaces
}
\def\genbbl#1#2{\openauxfile{#1}{#2}%
   \immediate\write\auxfile{\string\citation{*}}%
   \bgroup
     \iindent=4em
     \def\bibitemC##1{\ifnum\bibnum>0 \bibskip \fi
        \advance\bibnum by1
        \noindent \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\lcite=\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
     \let\lcite=\relax \xdef\citelist{\citelist\citelistB}%
     \def\bibitemC##1 ##2\par{%
        \isinlist\citelist{[##1]}\iftrue
           \ifx\tmpa\empty \sdef{bb:##1}{\bibitemD{##1}##2\par}%
           \else \toks0={##2\par}%
                 \edef\tmpa{\noexpand\sdef{bb:##1}{% \tmpa have to expand
                      \noexpand\bibitemB[\tmpa]{##1}\the\toks0}}\tmpa
        \fi\fi}%
     \readbblfile{#1}%
     \def\bibitemC##1{\bibitemD{##1}}%
     \def\lcite[##1]{\csname bb:##1\endcsname}\citelist
     \global\let\addcitelist=\writeXcite
  \egroup
}
\def\Xcite#1{\addto\citelistB{\lcite[#1]}}


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

\output={\opmacoutput}

\def\opmacoutput{\def\nl{ }%
  \setbox0=\vbox{\makeheadline\prepage\pagebody\makefootline}%
  \pghook \protectlist
  \shipout\box0 \advancepageno
  \ifnum\outputpenalty>-20000 \else\dosupereject\fi
}
\def\doprotect#1{\let#1=\relax}

\def\prepage{\wref\Xpage{{\the\pageno}}%
   \dest[pg:\the\pageno]{25pt}%
   \csname pg:\the\pageno\endcsname
}

\footline={\locpgcolor\Black \hss\tenrm\thefontsize[10]\the\pageno\hss}


%%%%%%%%%%%%%% 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\else \if 2#1% double-page layout
         \shiftoffset=\pgwidth \advance\shiftoffset -\hsize
         \advance\shiftoffset -2\hoffset \advance\shiftoffset -2in
         \addto\pghook{\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#1 {\isdefined{pgs:#1}\iftrue
   \expandafter\expandafter\expandafter \setpagedimensA \csname pgs:#1\endcsname&%
   \else \opwarning{page specification "#1" is undefined}\fi}
\def\setpagedimensA (#1,#2)#3&{\pgwidth=#1\trueunit#3 \pgheight=#2\trueunit#3\relax
    \ifx\pdfpagewidth\undefined \else
        \pdfpagewidth=\pgwidth \pdfpageheight=\pgheight \fi}

\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 
       \pdfhorigin=1truein \pdfvorigin=1truein % Origin is independent off \mag 
   \fi}
\def\truedimen#1{#1=\expandafter\ignorept\the#1truept }

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

\inputref
\endinput

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

beta (a) Nov. 2012 ... first released version.
Dec. 2012          ... first stable version

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

