%:strip
% This optional plugin (see ptx-plugins) provides ptx2pdf users with 
% access to decorative ornaments distributed as part of latex package pgfornaments,
% It does not include those ornaments, which are available at https://www.ctan.org/pkg/pgfornament
%
% This code thus includes a  XeTeX-specific, partial reimplementation of some portions
% of the pgfornament package to use the pgf-vectorian (and other) ornaments,
% but without loading (any of) pgf. 
% It also adds auto-filling and scaling functionality not found in that original package.
%
% Copyright (c) 2021 by SIL International written by David Gardner
%
% Some portions of this code derive from the pgfornament.sty file  (v0.2)
%  (C) 2016 Alain Matthes,  which was released under LaTeX Project Public
%  License. 
% Other portions de-abstract the abstraction layers from the pdf drivers from
% the pgf package, released under the same licence.
% 
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  
% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  
% MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND  
% NONINFRINGEMENT. IN NO EVENT SHALL SIL INTERNATIONAL BE LIABLE FOR  
% ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  
% CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  
% WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
%
% Except as contained in this notice, the name of SIL International  
% shall not be used in advertising or otherwise to promote the sale,  
% use or other dealings in this Software without prior written  
% authorization from SIL International.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\makeatletter
\newif\ifpgfsys@eorule\pgfsys@eoruletrue % Using evenodd rule?
\newif\ifClipOrnaments\ClipOrnamentsfalse
\newif\ifboxorn\boxornfalse % Set to true to surroud all ornaments with boxes.
\newif\ifCacheOrnaments\CacheOrnamentsfalse % Cache ornaments in boxes
\newif\ifXformOrnaments\XformOrnamentsfalse % Use XForm objects 
\newif\ifpdf@ornament@stretch
\newif\ifpdf@ornament@repeat
\newif\ifstringornament
\newif\ifornscale % Should the ornament be scaled to the relevant dimension(s)
\newif\ifornamentfill
\def\x@bjpadding{5pt} %How much extra space around xobjects to avoid clipping?
\newdimen\OrnamentUnit\OrnamentUnit=0pt % 0pt triggers a version-dependent value
\plugin@startif{ornaments}
%\plugins@needed{} % Just in case it becomes separate.

% 
\def\MSG#1{\immediate\write -1{#1}}
\newdimen\pdf@xunit
\newdimen\pdf@yunit
\let\orn@label\relax
\let\orn@labelstyle\empty

\def\strip@pt#1{\x@\x@\x@\@strip@pt\x@\the\x@ #1\@pt\E}
{\catcode`P=12 \catcode`T=12 \lowercase{\gdef\@strip@pt#1PT#2\E{#1} \xdef\@pt{PT}}} 
\def\ornYalign{0}%
\def\ornXalign{0}%
\let\x@\expandafter
\x@\let\csname orn@skip176\endcsname\relax
\let\ornamentmaxwidth\empty
\gdef\OrnamentsFamily{vectorian}
\gdef\pgfOrnamentsObject{pgflibrary\OrnamentsFamily.code.tex} 
\newtoks\tmptoks
\def\setorn@scale{%
  \tmptoks{}%
  \pdf@yunit=1bp
  \ifx\undefined\@pgfornamentY
    \trace{orn}{setorn@scale: Setting a scale for undefined object!}%
    \pdf@yunit=1bp
  \else
    \ifx\ornamentwidth\empty
      \tmptoks{\pdf@xunit=\pdf@yunit\relax
      \ifx\ornamentmaxwidth\empty\else
        \trace{orn}{Applying x-limit \ornamentmaxwidth}%
        \ifdim \@pgfornamentX\pdf@xunit > \ornamentmaxwidth
          \pdf@xunit=\dimexpr \ornamentmaxwidth / \@pgfornamentX\relax
          \pdf@yunit=\pdf@xunit
        \fi
      \fi
      }%
    \else
      \pdf@xunit=\dimexpr \ornamentwidth / \@pgfornamentX\relax
    \fi
    \ifx\ornamentheight\empty
      \x@\tmptoks\x@{\the\tmptoks\pdf@yunit=\pdf@xunit}%
    \else
        \pdf@yunit=\dimexpr \ornamentheight / \@pgfornamentY\relax
    \fi
    \the\tmptoks
    \trace{orn}{setorn@scale: xunit \the\pdf@xunit\space yunit \the\pdf@yunit. Object will be \the\dimexpr \@pgfornamentX\pdf@xunit \relax\space by \the\dimexpr \@pgfornamentY\pdf@yunit\relax }%
  \fi
}


\def\check@orn@dot#1.#2.#3\E{%If the caller has given us X.Y, obey that 
  \edef\d@t@tmp{#2}\ifx\d@t@tmp\empty
    \pdf@xunit=\csname orn@scale@#1@x\endcsname
    \pdf@yunit=\csname orn@scale@#1@y\endcsname
  \else
    \setorn@scale
    \pdf@xunit= #1.#2\pdf@xunit
    \pdf@yunit= #1.#2\pdf@yunit
  \fi
}

% Manual setting of ornament scale based on a single ornament and 1 or 2 dimensions
\def\setornscale#1#2#3#4{\bgroup
  \get@ornamentDim{#2}%
  \ifx\dimen1=0pt
    \@notpgfornamentdim{#2}%
  \fi
  \edef\ornamentwidth{#3}%
  \edef\ornamentheight{#4}%
  \setorn@scale
  \x@\xdef\csname orn@scale@#1@x\endcsname{\the\pdf@xunit}%
  \x@\xdef\csname orn@scale@#1@y\endcsname{\the\pdf@yunit}%
\egroup}

\def\p@rsescaleref #1,#2\E{% set ornament scale(s) based on 1 or 2 ornaments and current border width.
  \trace{eb}{p@rsescaleref #1,#2}%
  \def\tmp{#1}\ifx\tmp\empty
    \let\psn@xt\cstackrelax
  \else
    \@p@rsescaleref #1::\E
    \let\psn@xt\p@rsescaleref
  \fi
  \psn@xt #2,\E
}

\def\sc@letype@XY{%
  \ift@mp\else\trace{orn}{Warning: Using xy or XY as part of a 2 part \escapechar OrnamentScaleRef makes no sense (given: \sc@ledbg)}%
  \fi
  \x@\edef\csname \sc@lename x\endcsname{\the\dimexpr \b@drwidth\OrnamentUnit/ \@pgfornamentX\relax}%
  \x@\edef\csname \sc@lename y\endcsname{\the\dimexpr \b@drwidth\OrnamentUnit/ \@pgfornamentY\relax}%
}
\def\sc@letype@X{%
  \x@\edef\csname \sc@lename x\endcsname{\the\dimexpr \b@drwidth\OrnamentUnit/ \@pgfornamentX\relax}%
  \ift@mp
    \x@\let\csname \sc@lename y\x@\endcsname\csname \sc@lename x\endcsname
  \fi
}
\def\sc@letype@Y{%
  \x@\edef\csname \sc@lename y\endcsname{\the\dimexpr \b@drwidth\OrnamentUnit/ \@pgfornamentY\relax}%
  \ift@mp
    \x@\let\csname \sc@lename x\x@\endcsname\csname \sc@lename y\endcsname
  \fi
}
  
\def\sc@letype #1|#2|#3\E{%
  \trace{eb}{sc@letype  #1|#2|#3}%
  \ifdim\OrnamentUnit=0pt \ifversion{2}{\global\OrnamentUnit=1pt}{\global\OrnamentUnit=1\FontSizeUnit}\fi
  \edef\tmp{#2}%
  \edef\t@mptyp{#1}%
  \uppercase{\edef\t@mptypU{#1}}%
  \ifx\tmp\empty \errmessage{Invalid syntax parsing \string\OrnamentScaleRef (given: \sc@ledbg)}%
  \else
    \get@ornamentDim{#2}% Swap X and Y dimens of the ornament
    \ifx\t@mptyp\t@mptypU
      \let\tmp\@pgfornamentX
      \let\@pgfornamentX\@pgfornamentY
      \let\@pgfornamentY\tmp
    \fi
    \ifcsname sc@letype@\t@mptypU\endcsname 
      \csname sc@letype@\t@mptypU\endcsname
    \else
      \errmessage{Invalid key found when parsing \escapechar OrnamentScaleRef : '\t@mptyp' (given: \sc@ledbg)}%
    \fi
  \fi
} 

\def\@p@rsescaleref #1:#2:#3:#4\E{%
  \trace{eb}{@p@rsescaleref #1:#2:#3}%
  \traceifset{p@rsescaleref}%
  \def\tmp{#3}%
  \edef\sc@ledbg{#1:#2:#3}%
  \edef\sc@lename{orn@scale@#1@}%
  \ifx\empty\tmp
    \t@mptrue
    \sc@letype #2||\E
  \else
    \t@mpfalse
    \sc@letype #3||\E
    \sc@letype #2||\E
  \fi
  \traceifcheck{p@rsescaleref}%
}
  

\def\setornamenttransform#1{%
  \setgeomtransform{#1}%
} 


\def\s@tornamenttransform#1#2#3#4{%
  \def\pdf@aa{#1}\def\pdf@ab{#2}\def\pdf@ba{#3}\def\pdf@bb{#4}%
  \ifXformOrnaments
    \edef\pdf@xo{\strip@pt{\dimexpr -\x@bjpadding\relax}}\edef\pdf@yo{\strip@pt{\dimexpr -\x@bjpadding\relax}}%
  \else
    \edef\pdf@xo{0}\edef\pdf@yo{0}%
  \fi
  \calc@ornamentdim
  \ifdim\dimen0<0pt
    \dimen0=-\dimen0
    \edef\pdf@xo{\strip@pt{\dimexpr 0.99626401\dimen0 \ifXformOrnaments +\x@bjpadding\fi\relax}}%
  \fi
  \trace{orn}{xshift \pdf@xo}%
  \ifdim\dimen1<0pt
    \dimen1=-\dimen1
    \edef\pdf@yo{\strip@pt{\dimexpr 0.99626401\dimen1 \ifXformOrnaments +\x@bjpadding\fi\relax}}%
  \fi
  \trace{orn}{yshift \pdf@yo}%
  \edef\pdf@matrix{}%
  \def\pdf@apply@transform{}%
  \ifXformOrnaments
  %\iftrue
    %\def\pdf@apply@transform{\pdf@transformcm{\pdf@aa}{\pdf@ab}{\pdf@ba}{\pdf@bb}{\pdf@xo}{\pdf@yo}}%
    %\edef\pdf@matrix{matrix \pdf@aa\space \pdf@ab\space\pdf@ba\space\pdf@bb\space\strip@pt{\dimen0}\space \strip@pt{\dimen1}}%
    \edef\orn@@x{\the\dimexpr \pdf@xunit*\@pgfornamentX + \x@bjpadding *2\relax}%
    \edef\orn@@y{\the\dimexpr \pdf@yunit*\@pgfornamentY + \x@bjpadding *2\relax}%
    \edef\pdf@matrix{matrix \pdf@aa\space \pdf@ab\space\pdf@ba\space\pdf@bb\space\pdf@xo\space\pdf@yo}%
    \trace{orn}{\pdf@matrix}%
  \else
    \def\pdf@apply@transform{\pdf@transformcm{\pdf@aa}{\pdf@ab}{\pdf@ba}{\pdf@bb}{\pdf@xo}{\pdf@yo}}%
    \edef\orn@@x{\the\dimexpr \pdf@xunit*\@pgfornamentX\relax}%
    \edef\orn@@y{\the\dimexpr \pdf@yunit*\@pgfornamentY\relax}%
    \relax
  \fi
}
\def\orn@qpoint#1#2{%Apply x and y scaling to dimensinons
  {\strip@pt{\dimexpr #1\pdf@xunit\relax}} {\strip@pt{\dimexpr #2\pdf@yunit}} }


% Path construction:
\def\pdf@lineto#1#2{\addto@macro\pdfpath{#1 #2 }\sysprotocol@literal{l}}
\def\pdf@moveto#1#2{\addto@macro\pdfpath{#1 #2 }\sysprotocol@literal{m}}
\def\pdf@curveto#1#2#3#4#5#6{%
  \addto@macro\pdfpath{#1 #2 #3 #4 #5 #6 }\sysprotocol@literal{c}}
\def\pdf@rect#1#2#3#4{\addto@macro\pdfpath{#1 #2 #3 #4 }\sysprotocol@literal{re}}
\def\pdf@closepath{\sysprotocol@literal{h}}


% Path usage:
\def\pdf@stroke{\sysprotocol@literal{S}}\def\pdf@closestroke{\sysprotocol@literal{s}} \def\pdf@fill{\ifpgfsys@eorule\sysprotocol@literal{f*}\else\sysprotocol@literal{f}\fi}
\def\pdf@fillstroke{\ifpgfsys@eorule\sysprotocol@literal{B*}\else\sysprotocol@literal{B}\fi}
\def\pdf@clipnext{\ifClipOrnaments\ifpgfsys@eorule\sysprotocol@literal{W*}\else\sysprotocol@literal{W}\fi\fi \pdf@discardpath\ifx\orn@clip@rect\empty\global\let\orn@clip@rect\orn@last@rect\fi}
%\def\pdf@clipnext{\pdf@stroke\pdf@discardpath}%
\def\pdf@discardpath{\sysprotocol@literal{n}}
\def\pdf@parse@clip@rect#1 #2 #3 #4{\trace{orn}{ParseClip: #1 #2 #3 #4}\dimen2=#1 pt \dimen3=#2 pt \dimen4=#3 pt \dimen 5=#4 pt}
%Pen
\def\pdf@setlinewidth#1{\addto@macro\pdfpath{#1 }\sysprotocol@literal{w}}
\def\pdf@color@rgb@stroke#1 #2 #3\E{\sysprotocol@literal{#1 #2 #3 RG}}
\def\pdf@color@rgb@fill#1 #2 #3\E{\sysprotocol@literal{#1 #2 #3 rg}}
\def\pdf@beginpic{\special{pdf:bcontent}}
\def\pdf@endpic{\special{pdf:econtent}}

% Transformation:
\def\pdf@transformcm#1#2#3#4#5#6{%
  \addto@macro\pdfpath{#1 #2 #3 #4 #5 #6 }\sysprotocol@literal{cm}}
\def\pdf@transformText{%
  \pdf@transformcm{\strip@pt{\pdf@xunit}}{0}{0}{\strip@pt{\pdf@yunit}}{0}{0}}

% Scopes
\def\pdf@beginscope{\sysprotocol@literal{q}}
\def\pdf@endscope{\sysprotocol@literal{Q}}

\def\pdf@special#1{\unskip\special{pdf:code #1}}
\def\pdfcommands{}
\def\pdfpath{}
\def\sysprotocol@literal#1{\let\tmp\pdfpath\xdef\pdfpath{}\x@\pdf@special{\tmp#1}\xdef\pdfcommands{}}
\edef\orn@clip{clip}
\edef\orn@stroke{stroke}
\edef\orn@bb{boundingbox}

\def\orn@usepath#1{%
  \edef\tmp{#1}%
  \ifx\tmp\orn@clip
    \pdf@clipnext
  \else
    \ifx\tmp\orn@stroke
      \pdf@stroke
    \else
      \ifx\tmp\orn@bb
        \pdf@clipnext
      \else
        \errmessage{orn@usepath: #1 unrecognised}%
      \fi
    \fi
  \fi
}

\def\orn@setup{%
  \def\i{\orn@usepath{\orn@clip}}%
  \def\k{\orn@usepath{\orn@stroke}}%
  \def\ubb{\orn@usepath{\orn@bb}}%
  \let\o\pdf@closepath
  \def\p ##1##2{\orn@qpoint{##1}{##2}}%
  \def\m ##1 ##2 {\edef\tmp{\p{##1}{##2}}\x@\pdf@moveto\tmp}%
  \def\l ##1 ##2 {\edef\tmp{\p{##1}{##2}}\x@\pdf@lineto\tmp}%
  \def\r ##1 ##2 ##3 ##4 {\edef\tmp{\p{##1}{##2}\p{##3}{##4}}\xdef\orn@last@rect{\tmp}\x@\pdf@rect\tmp}%
  \def\c ##1 ##2 ##3 ##4 ##5 ##6 {%
    \edef\tmp{\p{##1}{##2}\p{##3}{##4}\p{##5}{##6}}\x@\pdf@curveto\tmp}%
}

\def\LocalOrnament#1#2#3#4{% Define a local ornament #1, natural size #2 x #3, having code #4%
	\x@\gdef\csname localornament@#1@X\endcsname{#2}%
	\x@\gdef\csname localornament@#1@Y\endcsname{#3}%
	\x@\gdef\csname localornament@#1@code\endcsname{#4}%
}
\def\StringOrnament#1#2#3{\x@\global\x@\font\csname localornament@#1@font\endcsname "#2" at 32pt \setbox0\hbox{\csname localornament@#1@font\endcsname #3}%
    \trace{orn}{Defining ornament #1 as box (\the\ht0+\the\dp0) x \the\wd0}%
    \bgroup
      %\tracingassigns=1
      \dimen0=\wd0\dimen1=\dimexpr \dimexpr \ht0+\dp0\relax\relax
      \ifnum 1=\ifdim \the\dimen0=0pt 1 \else\ifdim \the\dimen1=0pt 1 \else 0\fi\fi
	\x@\edef\csname localornament@#1@code\endcsname{\hbox{\csname localornament@#1@font\endcsname #3}}%
	\x@\xdef\csname localornament@#1@X\endcsname{1}%
	\x@\xdef\csname localornament@#1@Y\endcsname{1}%
        \message{Cannot define zero-size ornament #1 properly}%
      \else
        \count255=\dimen0\advance\count255 by 32768 \divide\count255 by 65536
	\x@\xdef\csname localornament@#1@X\endcsname{\the\count255}%
        \count255=\dimen1\advance\count255 by 32768 \divide\count255 by 65536
	\x@\xdef\csname localornament@#1@Y\endcsname{\the\count255}%
        %\tracingassigns=0
	\x@\xdef\csname localornament@#1@code\endcsname{\noexpand\pdf@transformText\raise \the\dp0\hbox{\csname localornament@#1@font\endcsname #3}}%
      \fi
    \egroup
  }

\def\localornament@dims#1{\x@\let\x@\@pgfornamentX\csname localornament@#1@X\endcsname
  \x@\let\x@\@pgfornamentY\csname localornament@#1@Y\endcsname}%
\LocalOrnament{0}{10}{10}{ }% A space
\LocalOrnament{-1}{10}{10}{\m 0.0 5 \l 10 5 \k } % A centred line of equal lenght to a space
\LocalOrnament{-2}{20}{10}{\m 0.0 5 \l 20 5 \k } % A centred line twice as long as a space
\LocalOrnament{-3}{50}{10}{\m 0.0 5 \l 50 5 \k } % A centred line five times longer than as a space
	
\def\get@ornamentDim#1{%
  \ifcsname localornament@#1@X\endcsname
    \localornament@dims{#1}%
  \else
    \ifcsname @pgfornamentDim\endcsname
      \@pgfornamentDim{#1}%
    \else
      \errmessage{@pgfornamentDim not defined. Probably the path from the TEXINPUTS environment variable does not include \pgfOrnamentsObject}%
    \fi
  \fi
}
\def\get@ornament@Code{%
  \ifcsname localornament@\pdf@ornamentNum @code\endcsname
    \csname localornament@\pdf@ornamentNum @code\endcsname
  \else
    {\m@kedigitsother
      \catcode`\%=5
      \catcode`\{=1 
      \catcode`\}=2
      \input "\OrnamentsFamily\pdf@ornamentNum.pgf"%
    \m@kedigitsletters}%
  \fi
}

\def\OrnamentTweakY#1#2#3{%
  \x@\xdef\csname orn@adj@#2@#1@Y\endcsname{#3}%
}
\def\OrnamentTweakX#1#2#3{%
  \x@\xdef\csname orn@adj@#2@#1@X\endcsname{#3}%
}

\OrnamentTweakY{vectorian}{84}{2.5}
\OrnamentTweakX{pgfhan}{76}{-15.5}
\OrnamentTweakX{pgfhan}{77}{-15.5}
\OrnamentTweakX{pgfhan}{74}{-8}
\OrnamentTweakY{pgfhan}{74}{-8}
\OrnamentTweakX{pgfhan}{75}{-8}
\OrnamentTweakY{pgfhan}{75}{-8}
\OrnamentTweakY{pgfhan}{67}{-8}
\OrnamentTweakX{pgfhan}{67}{-8}
\OrnamentTweakY{pgfhan}{65}{-64}
\OrnamentTweakY{pgfhan}{64}{-24}
\OrnamentTweakX{pgfhan}{64}{-8}

\def\calc@ornamentdim{%
    \dimen0=\dimexpr \pdf@xunit*\numexpr \pdf@aa*\@pgfornamentX\relax + \pdf@yunit*\numexpr\pdf@ba*\@pgfornamentY\relax\relax
    \dimen1=\dimexpr \pdf@xunit*\numexpr \pdf@ab*\@pgfornamentX\relax + \pdf@yunit * \numexpr\pdf@bb*\@pgfornamentY\relax\relax
}
\def\ornamentstretch{1}

\def\boxornRGB{0.5 1.0 1.0}
\def\c@cheornbox{% This macro may not contain any logic, so that TeX's logic skipper can skip the macro 
  \x@\newb@x\csname \ornUUID\endcsname
}
\newbox\theornament
\def\orn@do@ornament{\bgroup%
    \traceifset{orn@do@ornament}%
    \ifpdf@ornament@stretch
      \pdf@xunit=\ornamentstretch\pdf@xunit
    \fi
    \calc@ornamentdim
    \ifdim \dimen0<0pt
      \dimen0=-\dimen0
    \fi
    \ifdim\dimen1<0pt
      \dimen1=-\dimen1
    \fi
    \global\let\orn@clip@rect\empty
    \global\let\orn@last@rect\empty
    \ifXformOrnaments
      \@pprox{\the\pdf@xunit}{3}{\tpdf@xunit}%
      \@pprox{\the\pdf@yunit}{3}{\tpdf@yunit}%
      \edef\ornUUID{orn-\ornamentlinewidth-\ornamentlinecol-\ifornamentfill \ornamentfillcol\else nofil\fi-\tpdf@xunit-\tpdf@yunit-\OrnamentsFamily\pdf@ornamentNum}%
      \edef\ornUUID{\x@\x@\x@\zap@space \x@\ornUUID\space \empty}%
    \else
      \edef\ornUUID{orn-\ornamentlinewidth-\geom@xform-\ornamentlinecol-\ifornamentfill \ornamentfillcol\else nofil\fi-\the\pdf@xunit-\the\pdf@yunit-\OrnamentsFamily\pdf@ornamentNum}%
    \fi
    %\message{\ornUUID}%
    \trace{orn}{orn@do@ornament(\ifpdf@ornament@stretch *\ornamentstretch\fi) \the\dimen0 x \the\dimen1}%
    %\tracingifs=1
    %\tracingassigns=1
    \tempfalse
    \ifCacheOrnaments
      \temptrue
    \fi
    \ifXformOrnaments
      \temptrue
    \fi
    \let\ornXFid\relax
    \iftemp
      \ifcsname \ornUUID \endcsname
        \x@\let\x@\ornXFid\csname \ornUUID\endcsname
        \trace{orn}{using \ornXFid\space again}%
      \else
        \tempfalse
      \fi
    \fi
    \traceifset{orn@do@ornamentA}%
    \x@\s@tornamenttransform\geom@xform
    \iftemp
      \trace{orn}{ornUUID is \ornUUID}%
      \dimen2=\x@\csname \ornUUID-dim2\endcsname
      \dimen3=\x@\csname \ornUUID-dim3\endcsname
      \dimen4=\x@\csname \ornUUID-dim4\endcsname
      \dimen5=\x@\csname \ornUUID-dim5\endcsname
      \x@\let\x@\orn@@x\csname \ornUUID-@@x\endcsname
      \x@\let\x@\orn@@y\csname \ornUUID-@@y\endcsname
      \trace{orn}{dimens: \the\dimen0 \x@\space x \the\dimen1, 2:\the\dimen2, 3:\the\dimen3, 4:\the\dimen4, 5:\the\dimen5}%
      \ifXformOrnaments
        \edef\tmp{pdf:uxobj @\ornXFid \space width \orn@@x \space \pdf@matrix}%
        \trace{orn}{special: \tmp}%
        \setbox0\hbox to \dimen0{\x@\special\x@{\tmp }}%
      \else
        \setbox0=\x@\box\csname \ornUUID\endcsname
      \fi
    \else
      %\x@\s@tornamenttransform\geom@xform
      \ifXformOrnaments
        \edef\ornXFid{orn\pdf@ornamentNum-\ifx\orn@label\relax\else\orn@label\fi-\orn@labelstyle-\the\ornXFids}%
        \global\advance\ornXFids by 1
        \x@\global\x@\let\csname \ornUUID\endcsname\ornXFid
        \trace{orn}{Defining \ornXFid}%
      \else
        \ifCacheOrnaments
          \c@cheornbox
        \fi
      \fi
      \x@\setbox0\hbox to \dimen0{%
        \pdf@beginscope
        \pdf@beginpic
        \pdf@apply@transform
        \pdf@setlinewidth{\ornamentlinewidth}%
        \ifx\ornamentlinecol\empty\else
          \x@\pdf@color@rgb@stroke\ornamentlinecol\E
        \fi
        \ifx\ornamentfillcol\empty\else
          \ifx\ornamentfillcol\fill@none
            \ornamentfillfalse
          \else
            \ornamentfilltrue
            \x@\pdf@color@rgb@fill\ornamentfillcol\E%
          \fi
        \fi
        \ifornamentfill
          \let\s\pdf@fillstroke
        \else
          \let\s\k
        \fi
        \get@ornament@Code
        \pdf@endpic
        \pdf@endscope
        \hss
      }%
      \ifXformOrnaments
        \global\xdef\ornXFid@list{\ornXFid@list \ornXFid,}%
        \global\setbox\ornXobjects\hbox{\unhbox\ornXobjects %
          \edef\tmp{pdf:bxobj @\ornXFid\space width \orn@@x \space height \orn@@y \space }%
          \trace{orn}{Definition special: \tmp}%
          \x@\special\x@{\tmp}%
          %\raise \x@bjpadding \hbox to 0pt{\kern \x@bjpadding \unhbox0\hss}%
          \vbox to 0pt{\vss\hbox to 0pt{\kern\x@bjpadding\unhbox0\hss}\kern\x@bjpadding}%
          \special{pdf:exobj}%
        }%
        \edef\tmp{pdf:uxobj @\ornXFid \space width \orn@@x  \space \pdf@matrix \space}%
        \trace{orn}{Usage special: \tmp}%
        \setbox0\hbox to \dimen0{\x@\special\x@{\tmp }}%
        \ifpdf@ornament@repeat\else
          \ifholdXobjects\else\ifvoid\ornXobjects\else
            \trace{orn}{Emmitting Xobj definitions: \ornXFid@list (gt:\the\currentgrouptype, gd:\the\currentgrouplevel)}%
            \global\let\ornXFid@list\empty
            \box\ornXobjects
          \fi\fi
        \fi
      \else
        \ifCacheOrnaments
          \x@\global\x@\setbox\csname \ornUUID\endcsname\copy0
        \fi
      \fi
      \tempfalse
    \fi
    \iftemp\else 
      \ifx\orn@clip@rect\empty
        \dimen2=0pt\dimen3=0pt\dimen4=0pt\dimen5=0pt
        \trace{orn}{No clip rect}%
      \else
        \x@\pdf@parse@clip@rect\orn@clip@rect
      \fi
      \ifdim\dimen2=0pt \else
        \setbox0=\hbox to \dimen0{\kern-\dimen2\unhbox0\kern\dimen2}%
      \fi
      %\x@\global\x@\setbox\csname \ornUUID\endcsname\copy0
      \ifnum 0<  \ifCacheOrnaments 1\fi\ifXformOrnaments 1\fi 0 
        \x@\xdef\csname \ornUUID-dim2\endcsname{\the\dimen2}% Initial Hoffset
        \x@\xdef\csname \ornUUID-dim3\endcsname{\the\dimen3}% 
        \x@\xdef\csname \ornUUID-dim4\endcsname{\the\dimen4}%
        \x@\xdef\csname \ornUUID-dim5\endcsname{\the\dimen5}%
        \x@\xdef\csname \ornUUID-@@x\endcsname{\orn@@x}%
        \x@\xdef\csname \ornUUID-@@y\endcsname{\orn@@y}%
      \trace{orn}{dimens: \the\dimen0 \x@\space x \the\dimen1, 2:\the\dimen2, 3:\the\dimen3, 4:\the\dimen4, 5:\the\dimen5}%
      \fi
    \fi
    \traceifcheck{orn@do@ornamentA}%
    \traceifset{orn@do@ornamentB}%
    \ht0=\dimen1%\@pgfornamentY\pdf@yunit
    \dimen7=\dimen3 % dimen7=vadjust. Start by adjusting to crop-box
    %Manual adjustments?
    \dimen8=0pt  % dimen8 = hadjust.
    \dimen6=0pt % Temp variable
    \ifcsname orn@adj@\pdf@ornamentNum @\OrnamentsFamily @Y\endcsname
      \x@\let\x@\tmp\csname orn@adj@\pdf@ornamentNum @\OrnamentsFamily @Y\endcsname
      \dimen6=\dimexpr \tmp\pdf@xunit* \pdf@ab+ \tmp\pdf@yunit * \pdf@bb\relax
      \advance\dimen7 by -\dimen6
    \fi
    \dimen6=0pt % Temp variable
    \ifcsname orn@adj@\pdf@ornamentNum @\OrnamentsFamily @X\endcsname
      \x@\let\x@\tmp\csname orn@adj@\pdf@ornamentNum @\OrnamentsFamily @X\endcsname
      \trace{orn}{Adjusting by \tmp}%
      \dimen6=\dimexpr \tmp\pdf@xunit* \pdf@aa+ \tmp\pdf@yunit * \pdf@ba\relax
      \advance\dimen8 by -\dimen6
    \fi
    %Is cut box < reported size? Center cutbox. UNHELPFUL AND BUGGY 
    %\dimen6=\dimexpr \dimen5 - \dimen3\relax % Height of cut-box
    %\ifdim\dimen6<0pt \dimen6=-\dimen6\fi
    %\ifdim\dimen6>0pt
      %\ifdim\dimen1>\dimen6
        %\advance \dimen7 by 0.5\dimexpr \dimen6 -\dimen1\relax
      %\fi
    %\fi
    \ifboxorn
      \setbox0=\hbox{%
        \special{color push rgb \boxornRGB}%
        \raise\dimen1\hbox{\vrule height 0.02pt width\dimen0}%
        \kern-\dimen0
        \kern -0.02pt \vrule height \dimen1 width 0.02pt depth 0pt
        \vrule height 0.02pt width\dimen0  depth 0pt
        \vrule height \dimen1 width 0.02pt depth 0pt \kern -0.02pt 
        \kern-\dimen0
        \ifdim\dimen8=0pt \else\kern -\dimen8\trace{orn}{kerning by \the\dimen8}\fi%
        \ifdim\dimen7=0pt
          \box0
        \else
          \ifdim\dimen7<0pt
            \raise -\dimen7
          \else 
            \lower \dimen7
          \fi\box0
        \fi%
        \ifdim\dimen8=0pt \else\kern \dimen8\fi
        \special{color pop}%
      }%
      \ht0=\dimen1
      \dimen7=0pt
      \dimen8=0pt
      %\showbox0
    \fi
    \ifx\orn@label\relax\else
      \toks0{\p@sheof\everyeof{}\makeatletter\r@storbkslsh\x@\scantokens\x@{\orn@label}\p@peof}%
      \ifx\orn@labelstyle\empty
        \setbox1\hbox to \wd0{\hss\hbox{\the\toks0}\hss}%
      \else
        \trace{orn}{Requested label '\orn@label' to use style '\orn@labelstyle'}%
        \mcpush{c}{\orn@labelstyle}%
        \ch@ckb@xedstyle{\styst@kfirst}{\styst@k}%
        \setbox1\hbox{\s@tfont{\orn@labelstyle}{\styst@k}\the\toks0}%
        \ifb@xedstyle
          \set@endb@xedstyle{\styst@kfirst}{\styst@k}%
          \apply@endb@xedstyle{1}%
        \fi
        \setbox1\hbox to \wd0{\hss\box1\hss}%
        %\showbox1
        \mcpop
      \fi
      \setbox0\hbox to \wd0{\dimen0=\ht0\box0\kern-\wd1\raise\dimexpr 0.5\dimen0 - 0.5\ht1\relax\box1}%
    \fi
    \advance\dimen8 by \dimexpr\ornXalign\dimen0\relax
    \advance\dimen7 by \dimexpr\ornYalign\dimen1\relax
    \trace{eb}{\pdf@aa, \ornYalign *\the\dimen0 -> (\the\dimen8,\the\dimen7) }%
    \ifx\@djYalign\empty \else
      \ifnum \pdf@aa=0  
        \advance\dimen8  by \dimexpr \@djYalign\dimen0\relax
      \else
        \advance\dimen7  by \dimexpr \@djYalign\dimen1\relax
      \fi
    \fi
    %\dimen7=-\ornYalign\dimen1
    \global\setbox\theornament\hbox{%
    \ifdim\dimen8=0pt \else\hbox\bgroup\leavevmode \kern -\dimen8 \trace{orn}{kerning by \the\dimen8}\fi
    \ifdim\dimen7=0pt
      \box0
    \else
      \ifhmode 
        \lower \dimen7\box0
      \else
        \box0
      \fi
    \fi%
    \ifdim\dimen8=0pt \else\kern \dimen8\egroup\dimen8=0pt\fi
    }%
    %\tracingmacros=1
    \ifpdf@ornament@repeat\else
      \trace{orn}{Not holding ornament \ornUUID \ifXformOrnaments (\ornXFid)\fi}%
      \box\theornament
    \fi
    \traceifcheck{orn@do@ornamentB}%
    \traceifcheck{orn@do@ornament}%
\egroup}
\def\doOrnament#1{%
  \ifdim\OrnamentUnit=0pt \ifversion{2}{\global\OrnamentUnit=1pt}{\global\OrnamentUnit=1\FontSizeUnit}\fi
  \begingroup
    \orn@setup
    \x@\ornament@parse#1|||||\E
    \setorn@scale
    \orn@do@ornament
  \endgroup
}% 

  
\def\endstack\E{}
\def\E{}

\setgeomtransform{u}

\def\ptn@minus{-}
\def\ptn@ast{*}
\def\ptn@plus{+}
\def\ptn@quest{?}
\def\ptn@range{(}
\def\ptn@eq{=}
\def\ptn@sim{"} % Ditto mars
\def\ptn@ex{x}

\def\parse@repeat@class#1-#2)#3\E{\ifnum 0#2=0\set@repeat@class{#3}{#1}{}\else\set@repeat@class{#3}{#1}{#2}\fi}
\def\StringOrnamentFont{AGA Arabesque Desktop}
\newcount\orn@strings
\orn@strings=20000

\def\chk@cplx#1#2\E{\edef\tmpa{#1}\edef\tmpb{#2}\uppercase{\edef\tmpu{#2}}}

\def\@orn@label@set #1|#2|#3\E{\edef\tmp{#2}\ifx\tmp\empty
  \else
    \def\orn@label{#1}\def\orn@labelstyle{#2}%
  \fi
}
\def\orn@label@set #1^#2^#3\E{\edef\tmp{#2}\ifx\tmp\relaxval
    \message{!Malformed ornament label. Closing mark (^) missing in ornament string "^#1"}%
    \@ornament@parse #1\E
  \else
    \def\orn@label{#1}%
    \@orn@label@set #1||\E
    \@ornament@parse #2\E
  \fi
}

\def\string@check #1"#2"#3\E{%
  \edef\tmp{#1}\ifx\tmp\empty
    \edef\tmp{#2}\ifx\tmp\empty\else
      \stringornamenttrue
      \edef\string@rnament{#2}%
      \ifcsname orn@string\string@rnament\endcsname\else
        \global\advance\orn@strings by 1 
        \x@\xdef\csname orn@string\string@rnament\endcsname{\the\orn@strings}%
        \StringOrnament{\the\orn@strings}{\StringOrnamentFont}{\string@rnament}%
      \fi
      \x@\let\x@\pdf@ornamentNum\csname orn@string\string@rnament\endcsname
    \fi
  \fi
}
%#1 ornament  Ornament number or string. May be prefixed with ^label^style^ which will be centred and set in an hbox.
%#2 orientation
%#3 Stretch/mult
%#4 Size {=|[a-z]|N.NN}  If a number (1.0 is valid, 2. is not) then the item's size will be this much times the normal calulated size.
% if =, the previous scaling will be applied, if it's set, but not '=' or a
% number in formal N.N, then a pre-set scale [which must have been set by setornscale] will be applied 
% #5 offset (-)0.NN  Ajdusts ornYalign. ornYalign takes values: 0.5=align to centre, 1=align to top, 0=align to bottom. Units are size of object.
\def\@@ornsetnum #1#2\E{%
 \trace{eb}{Ornament number is "#1#2"}%
 \edef\pdf@ornamentNum{#1#2}%
}
\def\ornament@parse#1#2\E{%
  \edef\tmp{#1}%
  \trace{orn}{Prefix is \meaning#1 (=\meaning^)?}%
  \let\orn@label\relax
  \let\orn@labelstyle\empty
  \ifx#1^\trace{orn}{Found prefix}%
    \orn@label@set #2^\relax^\E
    \trace{orn}{Label:\orn@label, style: \orn@labelstyle}%
  \else
    \@ornament@parse #1#2\E
  \fi
}
\def\@ornament@parse#1|#2|#3|#4|#5|#6\E{%#6 is scrap
  \trace{orn}{ornament@parse:#1:#2:#3:#4}%
  \stringornamentfalse
  \string@check#1""\E
  \def\@djYalign{#5}%
  \ifstringornament
    \get@ornamentDim{\pdf@ornamentNum}%
  \else
    \x@\@@ornsetnum #1\empty\E
    \get@ornamentDim{\pdf@ornamentNum}%
  \fi
  \trace{orn}{Dimensions for \pdf@ornamentNum:  \@pgfornamentX, \@pgfornamentY}%
  \setgeomtransform{#2}%
  \pdf@ornament@stretchfalse
  \pdf@ornament@repeatfalse
  \let\orn@repeat@class\empty
  \edef\tmp{#4}%
  \ifx\tmp\empty\ornscaletrue
  \else
    \ornscalefalse
    %\tracingassigns=1
    \ifx\tmp\ptn@eq\else %a scale of = means keep the same scaling.
      \x@\check@orn@dot\tmp..\E
    \fi
    \trace{orn}{orn@scale@#4: xunit \the\pdf@xunit\space yunit \the\pdf@yunit}%
    %\tracingassigns=0
  \fi
  \edef\tmp{#3}%
  \ifx\tmp\empty\else
    \ifx\tmp\ptn@minus
      \pdf@ornament@stretchtrue
      \trace{orn}{Stretchd #1}%
    \else
      \ifx\tmp\ptn@ex% No variable, xleader-fill
	\pdf@ornament@repeattrue
      \else
	\x@\chk@cplx#3\E %Split off first code
        %\uppercase{\edef\tmpu{\tmpb}}%
        \ifx\tmpb\tmpu\else % variable needs to be  upper case 
          \trace{orn}{\tmpb\space is lowercase! Treat as \tmpu}%
          \let\tmpb\tmpu %make it upper
          \pdf@ornament@stretchtrue
        \fi
        \ifx\tmpa\ptn@sim
	  \pdf@ornament@repeattrue
	  \edef\orn@repeat@class{\tmpb}% Varable, range set elsewhere
	\else 
	  \ifx\tmpa\ptn@ast % Any number
	    \pdf@ornament@repeattrue
	    \set@repeat@class{\tmpb}{0}{}%
	  \else
	    \ifx\tmpa\ptn@plus % 1 or more
	      \pdf@ornament@repeattrue
	      \set@repeat@class{\tmpb}{1}{}%
	    \else
	      \ifx\tmpa\ptn@quest % 0 or 1
		\pdf@ornament@repeattrue
		\set@repeat@class{\tmpb}{0}{1}%
	      \else
		\ifx\tmpa\ptn@range % Range
		  \pdf@ornament@repeattrue
		  \x@\parse@repeat@class\tmpb\E
		\else
		  \ifx\tmpa\ptn@eq % Preserve variable
		    \pdf@ornament@repeattrue
		    \ifcsname best@mult@class@num@\tmpb\endcsname
		      \x@\let\x@\tmp\csname best@mult@class@num@\tmpb\endcsname
		      \set@repeat@class{\tmpb}{\tmp}{\tmp}%
		    \else
		      \errmessage{Cannot re-use undefined variable \tmpb}%
		      \set@repeat@class{\tmpb}{1}{}%
		    \fi
		  \else
		    \message{Ornamental border: unrecognised control char '#3'}%
		  \fi
		\fi
	      \fi
	    \fi
	  \fi
	\fi
      \fi
    \fi
  \fi
}
\def\orn@rpt@c@missing{0}

\def\set@repeat@class#1#2#3{\edef\orn@repeat@class{#1}%
  \ifx\orn@repeat@class\empty
    \edef\orn@rpt@c@missing{\the\numexpr 1+\orn@rpt@c@missing\relax}%
    \trace{orn}{Missing repeat class}%
    \edef\orn@repeat@class{Z\orn@rpt@c@missing}%
  \fi
  \x@\edef\csname mult@repeat@min@\orn@repeat@class\endcsname{#2}%
  \x@\edef\csname mult@repeat@max@\orn@repeat@class\endcsname{#3}%
}

\def\orn@an@ornament#1,#2\E{%Possibly without changing the scale, output several ornaments
  \advance\orn@seq@num by 1
  \x@\ornament@parse#1|||||\E%
  \ifornscale
    \setorn@scale
  \fi
  %\x@\let\csname orn@label@\the\orn@seq@num\endcsname\orn@label
  \ifpdf@ornament@repeat
    \orn@do@ornament
    \ifXformOrnaments
      \ifholdXobjects\else\ifvoid\ornXobjects\else
        \trace{orn}{Emmitting Xobj definitions: \ornXFid@list (gt:\the\currentgrouptype, gd:\the\currentgrouplevel)}%
        \global\let\ornXFid@list\empty
        \box\ornXobjects
      \fi\fi
    \fi
    \ifx\orn@repeat@class\empty
      \trace{orn}{Repeating ornament using xleaders for \orn@repeat@class}%
      \xleaders\box\theornament\hskip 0pt plus 1 fil\relax
    \else
      \x@\let\x@\tmp \csname best@mult@class@num@\orn@repeat@class\endcsname
      \ifx\tmp\relax
	\trace{orn}{Repeating ornament using xleaders for \orn@repeat@class}%
	\xleaders\box\theornament\hskip 0pt plus 1 fil\relax
      \else
	\trace{orn}{Repeating ornament #1 (\tmp times)}%
	\bgroup\setbox1=\box\theornament\count255=\tmp\loop\ifnum\count255>0\copy1\advance\count255 by -1\repeat\egroup%
      \fi
    \fi
  \else
    \trace{orn}{Simple ornament #1}%
    \orn@do@ornament
  \fi
  \def\tmp{#2}%
  \ifx\tmp\empty
    \let\nxt=\endstack
  \else
    \let\nxt\orn@an@ornament
  \fi
  \x@\nxt\tmp\E
}

\def\Ornaments#1{%
  \begingroup
    \def\orn@rpt@c@missing{0}%
    \orn@seq@num=0
    \orn@setup
    \x@\orn@an@ornament#1,\E%
  \endgroup
}% 
\newdimen\fill@target % Target dimension
\newcount\orn@seq@num
\newcount\mult@count
\newdimen\fill@fixed % length of rigid elements
\newdimen\fill@stretch % length of flexible elements
\newdimen\fill@mult % length of (non-stretchy) optional elements
\newdimen\fill@mult@min % Smallest optional element (0pt if none)
\newdimen\fill@mult@min@used % Smallest optional element currently in use. (0pt if none)

\newtoks\mult@classes
\mult@classes{}
\def\clear@mult@class#1{\x@\let\csname mult@class@dim@#1\endcsname\relax\x@\xdef\csname best@mult@class@num@#1\endcsname{0}}
\def\m@lti@inc#1{\x@\edef\csname mult@class@num@#1\endcsname{\the\numexpr \csname mult@class@num@#1\endcsname +1\relax}}
\def\m@lti@dec#1{\x@\edef\csname mult@class@num@#1\endcsname{\the\numexpr \csname mult@class@num@#1\endcsname -1\relax}}
\def\O@tp@t{}
\def\m@lti@print#1{\edef\O@tp@t{\O@tp@t #1: \csname mult@class@num@#1\endcsname\space}}
\def\best@m@lti@print#1{\edef\O@tp@t{\O@tp@t #1: \csname best@mult@class@num@#1\endcsname\space}}
\def\print@multi{\trace{orn}{\O@tp@t}\let\O@tp@t\empty}
\def\foundb@st#1{\x@\global\x@\let\csname best@mult@class@num@#1\x@\endcsname\csname mult@class@num@#1\endcsname}
\newcount\best@score
\newdimen\best@adjust
\newdimen\best@stretch

\def\apply@checks#1{%
  \ifnum\csname mult@class@num@#1\endcsname < \csname mult@repeat@min@#1\endcsname \advance\count255 by \numexpr 1500 * (\csname mult@repeat@min@#1\endcsname - \csname mult@class@num@#1\endcsname) \relax\fi
  \x@\ifx\csname mult@repeat@max@#1\endcsname\empty\else
    \ifnum\csname mult@class@num@#1\endcsname > \csname mult@repeat@max@#1\endcsname \advance\count255 by \numexpr  1500 *(\csname mult@class@num@#1\endcsname - \csname mult@repeat@max@#1\endcsname)\relax \fi
  \fi
}


\def\prep@dims#1#2{%Prepare dimensions for calcsc@re. \t@mp is the natural length of the object \t@mpstr=\t@mp if the object is stretchy
  \ifnum #2 > 0 
    \ifdim\fill@mult@min@used=0pt
      \fill@mult@min@used=\t@mp
    \else\ifdim\fill@mult@min@used > \t@mp
        \fill@mult@min@used=\t@mp
    \fi\fi
    \dimen0=-\fill@mult@min@used % Sane limit for overfull under-fill
    \ifdim \t@mpstr>0pt
      \advance\fill@mult by #2\dimexpr \t@mp -\t@mpstr\relax  % mult-value also includes stretchy portion
      \advance\fill@stretch by #2\dimexpr \t@mpstr\relax %
    \else
      \advance\fill@mult by #2\dimexpr \t@mp \relax 
    \fi
  \fi
  \ifdim\fill@stretch=0pt
    \dimen0=-100sp% Have *some* overrun, in case of rounding errors
    \dimen2=1pt%
  \else
    \dimen2=\fill@mult@min % underrun of > smallest optional chunk is silly
    \dimen0=-0.5\fill@stretch % Shrink up to 50% is OK.
  \fi
  \dimen1=\dimexpr \fill@target - \fill@mult - \fill@stretch - \fill@fixed\relax
  \x@\edef\csname mult@class@num@#1\endcsname{\the\count255}%
  \ifdim \dimen0 =0pt % Sanity...
    \dimen0=-100sp
  \fi
  \trace{orn}{Try: remaining:\the\dimen1 (\the\fill@target - \the\fill@mult - \the\fill@stretch - \the\fill@fixed), flex:\the\dimen0, \the\dimen2}% 
}
  
\def\calcsc@re{\bgroup \dimen4=\ifdim\dimen1<0pt 0.1\dimen0\else 0.1\dimen2 \fi\count255=\dimen4 
  \trace{orn}{\the\dimen1 / \the\count255 }% 
  \dimen4=\dimexpr 10\dimen1 / \count255\relax \count255=\dimen4
  \trace{orn}{precheck score: \the\dimen4 (\the\count255)}%
  \let\D@\apply@checks\the\mult@classes
  \let\D@\m@lti@print\the\mult@classes
  \trace{orn}{postcheckdscore: \the\dimen4 (\the\count255) \the\fill@stretch}%
  \print@multi
  \ifnum\count255<\best@score 
    \global\best@score=\count255
    \global\best@adjust=\dimen1
    \global\best@stretch=\fill@stretch
    \let\D@\foundb@st\the\mult@classes
    \trace{orn}{New best score:\the\best@score, \the\dimen1, \the\best@stretch}%
 \else
    \trace{orn}{rejecting score:\the\count255, \the\dimen1}%
 \fi\egroup}

\def\setup@meas@ornament{%
  \fill@mult@min=0pt\fill@stretch=0pt\fill@fixed=0pt\best@score=\maxdimen
  \best@stretch=\fill@stretch
  \mult@count=0
}

\edef\mult@class@list{}
\def\clear@vars{%
  \let\D@\clear@mult@class
  \the\mult@classes
  \edef\mult@class@list{}%
  \mult@classes{}%
}

\def\orn@SetStretch#1#2#3#4{%
  \trace{orn}{SetStretch #1 #2 #3 #4}%
  \fill@target=#1
  \ifornscale
    \setorn@scale
  \fi
  \begingroup
    \edef\orn@dir{#2}%
    \ifx\orn@dir\ptn@ex
      \def\@@orndim{0}\else\def\@@orndim{1}\fi
    \setup@meas@ornament
    \edef\tmp{#3}%
    \ifx\tmp\ptn@eq\else
      \clear@vars%
    \fi
    \orn@seq@num=0
    \x@\orn@meas@ornament#4,\E%Measure the (horizontal) dimensions
    \dimen1=\dimexpr \fill@target - \fill@fixed - \fill@stretch \relax
    \trace{orn}{Remaining:\the\dimen1 (\the\fill@target - \the\fill@mult - \the\fill@stretch - \the\fill@fixed)}% 
    \dimen0=0.5\fill@stretch %
    %Set limits for stretch (dimen2) / shrink (dimen0)
    \ifdim\dimen2=0pt
      \dimen2=1em
    \fi
    \relax
    %\tracingifs=1
    \global\best@adjust=\dimen1
    \global\best@stretch=\fill@stretch
    %
    \ifdim\dimen1 < 0pt
      \trace{orn}{No space for optional parts}%
      \ifdim\dimen1 < -0.7\fill@stretch
	 \trace{orn}{Oversquashed fill}%
      \fi
      \clear@vars
    \else
      \trace{orn}{Calculating \the\mult@count\space optional parts (\mult@class@list)}%
      \ifnum\mult@count>0
	\x@\multi@try\mult@class@list,\E{-1}%
	\relax
	\let\D@\best@m@lti@print\the\mult@classes
        \trace{orn}{Final result: stretch:\the\best@stretch, score:\the\best@score}\print@multi
      \fi
    \fi
    \dimen4=\dimexpr \best@stretch+\best@adjust\relax
    \ifdim\best@stretch=0pt 
    \else
      \trace{orn}{Stretch = (a:\the\best@adjust,  s:\the\best@stretch) (a+s:\the\dimen4)/s)}%
      \dimen5=\dimexpr \best@stretch*4\relax%
      \multiply\dimen4 by 4\relax
      \dimen6=\dimen4
      %\tracingassigns=1
      \ifdim\dimen6<0pt \multiply \dimen6 by -1\relax\fi
      \ifdim \dimen5 > \dimen6 \dimen6=\dimen5 \fi
      \loop \ifdim\dimen6<0.4\maxdimen
	\multiply\dimen5 by 2\relax
	\multiply\dimen4 by 2\relax
	\multiply\dimen6 by 2\relax
	\repeat
      %\tracingassigns=0
      \count255=\dimen5 \divide\count255 by 65535 % Integer part only
      \trace{orn}{\the\dimen4 / \the\count255}%
      \dimen4=\dimexpr \dimen4 / \count255\relax%Scale by 32
      \xdef\ornamentstretch{\strip@pt{\dimen4}}%
    \fi
    \trace{orn}{Ornament stretch set to \ornamentstretch}%
  \endgroup
}

\def\E{}
\def\add@mult@class#1{\x@\mult@classes\x@{\the\mult@classes\D@{#1}}}
\newif\iftemp
\def\orn@meas@ornament#1,#2\E{%
  \advance\orn@seq@num by 1
  \x@\ornament@parse#1|||||\E %Set relevant transform matrix and various bools
  \ifornscale
    \setorn@scale
  \fi
  \tmptoks{}%
  \calc@ornamentdim %dimen0=x, dimen1=y
  \ifdim\dimen\@@orndim<0pt
    \dimen\@@orndim=-\dimen\@@orndim
  \fi
  \trace{orn}{Ornament #1 (\the\orn@seq@num) is \the\dimen0 by \the\dimen1 \ifpdf@ornament@stretch Stretchy\fi\ifpdf@ornament@repeat Repeat\fi}%
  \ifpdf@ornament@repeat
    \advance\mult@count by 1
    \ifdim\fill@mult@min=0pt
      \fill@mult@min=\dimen\@@orndim
    \else 
      \ifdim\fill@mult@min>\dimen\@@orndim
        \fill@mult@min=\dimen\@@orndim
      \fi
    \fi
    \x@\let\x@\tmp\csname mult@class@dim@\orn@repeat@class\endcsname
    \ifx\relax\tmp
      \trace{orn}{New class \orn@repeat@class}%
      \ifx\orn@repeat@class\empty\else\x@\add@mult@class\x@{\orn@repeat@class}\fi
      \x@\edef\csname mult@class@dim@\orn@repeat@class\endcsname{\the\dimen\@@orndim}%
      \ifpdf@ornament@stretch
        \x@\edef\csname mult@class@stretch@dim@\orn@repeat@class\endcsname{\the\dimen\@@orndim}%
        \x@\edef\csname mult@class@dim@\orn@repeat@class\endcsname{\the\dimen\@@orndim}%
      \else
        \x@\edef\csname mult@class@dim@\orn@repeat@class\endcsname{\the\dimen\@@orndim}%
        \x@\edef\csname mult@class@stretch@dim@\orn@repeat@class\endcsname{0pt}%
      \fi
      \x@\edef\csname mult@class@num@\orn@repeat@class\endcsname{0}%
      \edef\mult@class@list{\ifx\mult@class@list\empty\else \mult@class@list,\fi \orn@repeat@class}%
    \else
      \x@\edef\csname mult@class@dim@\orn@repeat@class\endcsname{\the\dimexpr\tmp+\the\dimen\@@orndim\relax}%
      \ifpdf@ornament@stretch
        \x@\let\x@\tmpz\csname mult@class@stretch@dim@\orn@repeat@class\endcsname
        \x@\edef\csname mult@class@stretch@dim@\orn@repeat@class\endcsname{\the\dimexpr\tmpz+\the\dimen\@@orndim\relax}%
      \fi
    \fi
    \trace{orn}{\orn@repeat@class: \csname mult@class@dim@\orn@repeat@class\endcsname, \csname mult@class@stretch@dim@\orn@repeat@class\endcsname}%
  \else
    \ifpdf@ornament@stretch
      \advance\fill@stretch by \dimen\@@orndim %stretchy ones subtract roughly their own length
    \else
      \advance\fill@fixed by \dimen\@@orndim
    \fi
  \fi
  \def\tmp{#2}%
  \ifx\tmp\empty
    \let\nxt=\endstack
  \else
    \let\nxt\orn@meas@ornament
  \fi
  \x@\nxt\tmp\E
}

\def\multi@try#1,#2\E#3{\bgroup
    \trace{orn}{multitry '#1' {#3}}%
    \x@\let\x@\t@mp\csname mult@class@dim@#1\endcsname
    \x@\let\x@\t@mpstr\csname mult@class@stretch@dim@#1\endcsname
    \count255=#3
    \ifnum\count255=-1
      \ifdim 3\dimexpr \dimen1-\dimen0\relax > \t@mp
	\dimen3=\dimexpr \dimen1 \ifdim -\dimen0 >\t@mp  + \t@mp \else -\dimen0 \fi\relax
	\dimen4=\t@mp
	\count255=\dimen4
	\count255=\numexpr  \dimen3 / \count255 \relax
	\trace{orn}{ #1 (\t@mp) fits into \the\dimen3 \the\count255\space times}%
	\ifcsname mult@repeat@max@#1\endcsname
          \x@\ifx\csname mult@repeat@max@#1\endcsname\empty\else
            \ifnum \csname mult@repeat@max@#1\endcsname < \count255
              \count255=\csname mult@repeat@max@#1\endcsname
              \trace{orn}{That's above max for #1 (\the\count255); limiting range}%
              \advance \count255 by 1
            \fi
          \fi
        \fi
	\ifcsname mult@repeat@min@#1\endcsname
	  \ifnum \csname mult@repeat@min@#1\endcsname>\count255
	    \count255=\csname mult@repeat@min@#1\endcsname
	    \trace{orn}{ min for #1 (\the\count255) doesn't fit, but try it anyway (it might be shrinkable)}%
	  \fi
	\fi
      \else
	\count255=0
      \fi
    \fi
    \def\tmp{#2}%
    \global\tmptoks{}%
    \ifx\tmp\empty % No more optional items
      \bgroup
        \prep@dims{#1}{\count255}%
	\calcsc@re
      \egroup
      \ifnum\count255>0 %We included some over-run, Try one under...
	\bgroup
	  \advance\count255 by -1
          \prep@dims{#1}{\count255}%
	  \calcsc@re
	\egroup
      \fi
      \ifdim\t@mpstr >0pt % Item can shrink: also try 1 over. 
        \bgroup
          \advance\count255 by 1
          \prep@dims{#1}{\count255}%
          \calcsc@re
        \egroup
      \fi
    \else
      \ifdim\t@mpstr>0pt
          \advance\count255 by 1 % item can shrink; start at 1 over
      \fi
      \loop\unless\ifnum\count255<0
	\bgroup
          \prep@dims{#1}{\count255}%
	  \x@\multi@try#2\E{-1}%
	\egroup
	\advance\count255 by -1
      \repeat
    \fi
  \egroup
}  
% Parameters:
% 1 ornament number
% 2 output x dimension (or empty)
% 3 output y dimension (or empty)
% 4 mirror -> h = horiz, v=vert, c=both
% 5 rotation: up is -> u=up d=down l=left r=right

\def\UseOrnament#1#2#3#4#5{%
    %\orn@setup
    \def\ornamentwidth{#2}%
    \def\ornamentheight{#3}%
    \def\ornamentmirror{#4}%
    \def\ornamentorientation{#5}%
    \ifx\ornamentorientation\empty
      \def\ornamentorientation{u}% Up is up
    \fi
    \x@\ornament@parse#1|||||\E
    \setorn@scale
    \doOrnament{#1}%
}

\x@\def\csname MS:zornament\endcsname{%
  \bgroup
    \orn@setup
    \def\ornXalign{0}%
    \def\ornYalign{0}%
    \get@ttributedef{linewidth}{\ornamentlinewidth}{0.5}%
    \get@ttributedef{linecol}{\ornamentlinecol}{0 0 0}%
    \get@ttributedef{fillcol}{\ornamentfillcol}{NONE}%
    \get@ttribute{size}%
    \ifx\attr@b\relax
      \edef\ornamentheight{\the\dimexpr \c@rrfontsize\dimexpr 0.7\FontSizeUnit\relax\relax}%
    \else
      \m@kenumberns{\attr@b}%
      \edef\ornamentheight{\@@result}%
    \fi
    \get@ttribute{pattern}%
    \ifx\attr@b\relax
      \message{! zornament milestone must have a valid pattern="..." set}%
    \else
      \m@kenumberns{\attr@b}%
      \hbox{\beginL\doOrnament{\@@result}\endL}%prevent reordering of specials in RTL mode!
      \relax
    \fi
    \trace{orn}{end of zornament (\@@result)}%
  \egroup
  %\aftergroup{\showlists}%
} 
\def\n@endsp@ce#1 \E{\def\@@@result{#1}}
\def\chkset#1#2{\edef\tmp{#2}\ifx\tmp\empty\else\x@\global\x@\let\csname #1\endcsname\tmp\fi}

% Parameters:
% 1 stroke width
% 2 stroke colour (or empty for no change)
% 3 fill colour (or 'NONE' for no fill, empty for no change)
\def\SetupOrnament#1#2#3{% Line width / Line colour / Fill colour
  \chkset{ornamentlinewidth}{#1}%
  \chkset{ornamentlinecol}{#2}%
  \chkset{ornamentfillcol}{#3}%
}
\SetupOrnament{0.5}{0 0 0}{NONE}
%\tracingassigns=1
%\tracingmacros=1

%Format for pattern:
% Ornament number | transformation | Fitting Strategy | scale
% Fit is what should happnen to adjust spacing:
% [empty]  - Nothing - Just produce one ornament
% -     - stretch ornament to fill space 
% x	- Fill space using \xleaders 
% *V	- Variable V should be any integer including 0
% +V	- Variable V should be any integer above 0
% ?V	- Variable V should be 0 or 1
% (L-H)V - Variable V should be any integer between L and H (inclusve)
% ~V	- Variable V (no change to rules)
% =V	- Variable V (unchanged from reuslt.)
% Items sharing the same  variable V use the same range limits
% The last range limit is the one that will take effect. 
\newbox\orn@bdr@bot
\newbox\orn@bdr@left
\newbox\orn@bdr@right
\newbox\orn@bdr@top
% Box forming:
% Given X and Y values,
\def\ornamentheight{10pt}
\def\trybox#1#2#3{%
  \trace{orn}{TRYBOX}%
  \def\ornamentheight{#3}%
  \def\ornamentwidth{}%
  \def\ornYalign{1}%
  \def\ornXalign{0}%
  \def\orn@Side{T}\orn@SetStretch{#1}{x}{}{\patternT}\setbox\orn@bdr@top\hbox to #1{\Ornaments{\patternT}}%
  \def\ornYalign{0}%
  \def\orn@Side{B}\orn@SetStretch{#1}{x}{=}{\patternB}\setbox\orn@bdr@bot\hbox to #1{\Ornaments{\patternB}}%
  \trace{orn}{#2 - \the\ht\orn@bdr@top -\the\dp\orn@bdr@top -\the\ht\orn@bdr@bot -\the\dp\orn@bdr@bot}%
  \dimen1=\dimexpr #2 - \ht\orn@bdr@top -\dp\orn@bdr@top -\ht\orn@bdr@bot -\dp\orn@bdr@bot\relax
  %\def\ornamentheight{}
  %\def\ornamentwidth{#3}
  \trace{orn}{Box side is \the\dimen1}%
  \def\orn@Side{L}\orn@SetStretch{\the\dimen1}{y}{=}{\patternL}\setbox\orn@bdr@left\vbox to \dimen1{\lineskip=0pt \baselineskip=0pt \Ornaments{\patternL}}%
  %\showbox\orn@bdr@left
  \def\ornXalign{1}%
  \def\orn@Side{R}\orn@SetStretch{\the\dimen1}{y}{=}{\patternR}\setbox\orn@bdr@right\vbox to \dimen1{\lineskip=0pt \baselineskip=0pt \Ornaments{\patternR}}%
  %\showboxdepth=9
  %\showboxdepth=10
  %\showbox\orn@bdr@right
  \vbox to #2{\baselineskip=0pt \lineskip=0pt \hsize=#1\box\orn@bdr@top\hbox to #1{\box\orn@bdr@left\hfill\box\orn@bdr@right}\box\orn@bdr@bot}%
}
\def\OrnamentBorder#1{%
  \ifdim\OrnamentUnit=0pt \ifversion{2}{\global\OrnamentUnit=1pt}{\global\OrnamentUnit=1\FontSizeUnit}\fi
  \trace{orn}{OrnamentBorder \b@rderbox@width * \b@rderbox@height}%
  \def\ornamentheight{#1}%
  \def\ornamentwidth{}%
  \def\ornXalign{0}%
  \def\ornYalign{1}%
  \ifx\b@drtop\tr@e
    \def\orn@Side{T}\orn@SetStretch{\b@rderbox@width}{x}{}{\patternT}\setbox\orn@bdr@top\hbox to \b@rderbox@width{\Ornaments{\patternT}}%
  \else
    \setbox\orn@bdr@top\hbox{}%
  \fi
  \def\ornYalign{0}%
  \ifx\b@drbottom\tr@e
    \def\orn@Side{B}\orn@SetStretch{\b@rderbox@width}{x}{=}{\patternB}\setbox\orn@bdr@bot\hbox to \b@rderbox@width{\Ornaments{\patternB}}%
  \else
    \setbox\orn@bdr@bot\hbox{}%
  \fi
  \trace{orn}{#1 - \the\ht\orn@bdr@top -\the\dp\orn@bdr@top -\the\ht\orn@bdr@bot -\the\dp\orn@bdr@bot}%
  \dimen1=\dimexpr \b@rderbox@height - \ht\orn@bdr@top -\dp\orn@bdr@top -\ht\orn@bdr@bot -\dp\orn@bdr@bot\relax
  \dimen2=\dimexpr \dimen1 - \ht\b@rderbox\relax
  \divide\dimen2 by \b@drvsides
  %\def\ornamentheight{}
  %\def\ornamentwidth{#3}
  \trace{orn}{Box side portion is \the\dimen1. Orig: \the\ht\b@rderbox +\the\dp\b@rderbox x\the\wd\b@rderbox, final:\b@rderbox@height }%
  \tempfalse
  \def\border@l@pad{0pt}\def\border@r@pad{0pt}%
  \setbox\orn@bdr@right\box\voidb@x
  \ifx\b@drleft\tr@e
    \def\orn@Side{L}\orn@SetStretch{\the\dimen1}{y}{=}{\patternL}\setbox\orn@bdr@left\vbox to \dimen1{\lineskip=0pt \lineskiplimit=0pt \baselineskip=0pt \Ornaments{\patternL}}%
    \def\border@l@pad{\border@lpadding}%
    \ifx\patternL\patternR
      \ifx\b@drright\tr@e
	\setbox\orn@bdr@right\copy\orn@bdr@left
        \def\border@r@pad{\border@rpadding}%
      \fi
    \fi
  \else
    \setbox\orn@bdr@left\vbox{}%
  \fi
  %\showbox\orn@bdr@left
  \ifx\b@drright\tr@e
    \ifvoid\orn@bdr@right
      \def\ornXalign{1}%
      \def\orn@Side{R}\orn@SetStretch{\the\dimen1}{y}{=}{\patternR}\setbox\orn@bdr@right\vbox to \dimen1{\lineskip=0pt \lineskiplimit=0pt \baselineskip=0pt \Ornaments{\patternR}}%
      \def\border@r@pad{\border@rpadding}%
    \fi
  \fi
  %\showboxdepth=3
  %\showboxbreadth=9999
  %\showbox\orn@bdr@right
  \dimen7=\dimexpr\ht\orn@bdr@top+\dp\orn@bdr@top  \ifx\b@drtop\tr@e +\dimen2\fi \relax
  \dimen8=\dimexpr\wd\orn@bdr@left + \border@l@pad\relax
  \dimen9=\dimexpr\wd\orn@bdr@right + \border@r@pad\relax
  \setbox\b@rderbox\vbox to \b@rderbox@height{\baselineskip=0pt \lineskip=0pt \hsize=\b@rderbox@width
    \box\orn@bdr@top\hbox to \b@rderbox@width{\box\orn@bdr@left\hskip\border@l@pad\hss\hbox{\vbox to \dimen1{}}\hskip\border@r@pad\hss\box\orn@bdr@right\kern-\b@drwidth\OrnamentUnit}\baselineskip=\ht\orn@bdr@bot\box\orn@bdr@bot}%
  %\showbox#1%
  %\x@\setbox#1\vbox{\vbox to 0pt{\vskip\dimen7\hbox to \b@rderbox@width{\hskip\dimen8\hss\box#1\hss\hskip\dimen9}\vss}\box\b@rderbox}%
}

\def\OrnamentLine#1#2#3#4{%#1 Line length #2 Ornament height #3 Direction {Capital to keep old variables)  #4 Pattern
  \def\ornamentheight{#2}%
  \def\tmp{#3}\lowercase{\def\tmpb{#3}}%
  \ifx\tmp\tmpb\def\tmp{}\else\def\tmp{=}\fi
  \orn@SetStretch{#1}{\tmpb}{\tmp}{#4}%
  \ifx\tmpb\ptn@ex\hbox \else \vbox\fi to #1{\Ornaments{#4}}%
}

%Stylesheet Options
\def\t@xtbkslsh{\catcode`\\=12}
\def\sb@setcode#1#2\relax{\p@sheof\everyeof={\noexpand}\x@\edef\x@\tmp\x@{\scantokens{#2}}\r@storbkslsh\p@peof\initc@t\setsbp@ram{#1}{\tmp}}

\def\BorderPatternTop{\initc@t\t@xtbkslsh\sb@setcode{borderpatterntop}}
\def\BorderPatternBot{\initc@t\t@xtbkslsh\sb@setcode{borderpatternbot}}
\def\BorderPatternLeft{\initc@t\t@xtbkslsh\sb@setcode{borderpatternleft}}
\def\BorderPatternRight{\initc@t\t@xtbkslsh\sb@setcode{borderpatternright}}
\def\OrnamentScaleRef #1\relax{\initc@t\setsbp@ram{ornamentscaleref}{\detokenize{#1}}}



\def\ornamentheight{20pt}\def\ornamentwidth{}
\def\SwitchOrnamentsFamily#1{%
  %\tracingassigns=1
  \edef\ornDimname{nopgfornamentDim-#1}%
  \ifcsname\ornDimname\endcsname\else 
    \bgroup\let\@pgfornamentDim\relax
      \def\OrnamentsFamily{#1}\includeifpresent{\pgfOrnamentsObject}%
      \ifx\@pgfornamentDim\relax\else\x@\global\x@\let\csname\ornDimname\endcsname\@pgfornamentDim\fi
    \egroup
  \fi
  \ifcsname\ornDimname\endcsname
    \x@\global\x@\let\x@\@pgfornamentDim\csname \ornDimname\endcsname
    \xdef\OrnamentsFamily{#1}%
  \else\trace{orn}{Could not load \pgfOrnamentsObject}%
  \fi
  %\tracingassigns=0
}

\addtoinithooks{\x@\SwitchOrnamentsFamily\x@{\OrnamentsFamily}}%
\catcode`\@=11
\def\m@rker{esb}

\def\DefaultOrnament{-1}
\def\mkb@rder@ornaments{% Plugin for sidebars
  \trace{eb}{mkb@rder@ornaments}%
  \ifdim\OrnamentUnit=0pt \ifversion{2}{\global\OrnamentUnit=1pt}{\global\OrnamentUnit=1\FontSizeUnit}\fi
  \bc@lsetup
  \def\ornamentheight{\b@drwidth}%
  \getsbp@ram{borderfillcolour}\ifx\cp@ram\relax\edef\ornamentfillcol{\fill@none}\else\let\ornamentfillcol\cp@ram\fi
  \trace{eb}{Colour:\meaning\b@drcol, Fill:\meaning\ornamentfillcol}%
  \ifx\b@drcol\relax
    \def\ornamentlinecol{0 0 0}\else
    \let\ornamentlinecol\b@drcol
    \let\thinlinest@ndard\tls@black
  \fi
  \getsbp@ram{borderstyleextra}\ifx\cp@ram\relax\else\x@\SwitchOrnamentsFamily\x@{\cp@ram}\fi
  \getsbp@ram{borderpatterntop}\ifx\cp@ram\relax\edef\patternT{\DefaultOrnament||-}\else\let\patternT\cp@ram\fi
  \getsbp@ram{borderpatternbot}\ifx\cp@ram\relax\edef\patternB{\DefaultOrnament|u|-}\else\let\patternB\cp@ram\fi
  \getsbp@ram{borderpatternleft}\ifx\cp@ram\relax\edef\patternL{\DefaultOrnament|l|-}\else\let\patternL\cp@ram\fi
  \getsbp@ram{borderpatternright}\ifx\cp@ram\relax\edef\patternR{\DefaultOrnament|r|-}\else\let\patternR\cp@ram\fi
  %\tracingassigns=1
  \getsbp@ram{ornamentscaleref}\ifx\cp@ram\relax\else\x@\p@rsescaleref \cp@ram,\E\fi\relax
  %\tracingassigns=0
  \edef\ornamentlinewidth{\strip@pt{\dimexpr\b@drlinewidth\OrnamentUnit\relax}}%
  \let\thinlin@type\tlt@C
  \trace{orn}{Checking line width}%
  \thinlinecheck{\ornamentlinewidth}{pt}{border line width for ornamental border (\c@tprefix\sb@rmarker)}{Stylesheet value \b@drlinewidth, scaled like fonts}%
  \trace{orn}{Checked line width, now \ornamentlinewidth}%
  \OrnamentBorder{\b@drwidth\OrnamentUnit}%
  %\setbox\b@rderbox\vbox{\trybox{\b@rderbox@width}{\b@rderbox@height}{\b@drwidth\OrnamentUnit}}%
  \trace{orn}{ORNAMENTS box \the\ht\b@rderbox+\the\dp\b@rderbox * \the\wd\b@rderbox}%
  %\showbox#1\copy #1 
}
\edef\b@rderparameters{\b@rderparameters,borderstyleextra,borderpatterntop,borderpatternleft,borderpatternright,borderpatternbot,ornamentscaleref}

\x@\def\csname drawzrule-ornaments\endcsname{%
  \ifdim\OrnamentUnit=0pt \ifversion{2}{\global\OrnamentUnit=1pt}{\global\OrnamentUnit=1\FontSizeUnit}\fi
  \getp@ram{borderpatterntop}{zrule}{\styst@k}%
  \ifx\p@ram\relax
    \def\p@ttern{88||-}%
  \else
    \let\p@ttern\p@ram
  \fi
  \let\oldOrnamentsFamily\OrnamentsFamily
  \getp@ram{borderstyleextra}{zrule}{\styst@k}%
  \ifx\p@ram\relax\else 
    \x@\SwitchOrnamentsFamily\x@{\p@ram}%
  \fi
  \getp@ram{borderlinewidth}{zrule}{\styst@k}%
  \ifx\p@ram\relax
    \edef\ornamentlinewidth{0.5}%
    \edef\@thinlinedesc{Default BorderLineWidth}%
  \else
    \edef\ornamentlinewidth{\p@ram}%
    \edef\@thinlinedesc{BorderLineWidth from stylesheet}%
  \fi
  \getp@ram{bordercolour}{zrule}{\styst@k}%
  \ifx\p@ram\relax
    \def\ornamentlinecol{0 0 0}%
    \let\thinlinest@ndard\tls@black
  \else 
    \let\ornamentlinecol\p@ram
    \ifx\ornamentlinecol\fill@none
      \let\thinlinest@ndard\tls@nochk
    \else
      \x@\chk@colortype\ornamentlinecol\E
    \fi
  \fi
  \getp@ram{borderfillcolour}{zrule}{\styst@k}%
  \ifx\p@ram\relax
    \let\ornamentfillcol\fill@none
  \else 
    \let\ornamentfillcol\p@ram
  \fi
  \let\thinlin@type\tlt@C
  \thinlinecheck{\ornamentlinewidth}{pt}{border line width for ornamental zrule (\c@tprefix zrule)}{\@thinlinedesc}%
  \edef\ornamentheight{\dimexpr\rule@thk \relax}%
  \edef\ornamentwidth{}%
  \getp@ram{verticalalign}{zrule}{\styst@k}%
  \ifx\p@ram\@lignTop
    \def\ornYalign{1}%
  \else\ifx\p@ram\@lignBot
      \def\ornYalign{0}%
    \else
      \def\ornYalign{.5}%
    \fi
  \fi
  \def\ornXalign{0}%
  \endgraf
  \edef\rule@adjust{\the\dimexpr \rule@adjust + \ornYalign \dimexpr\rule@thk\relax\relax}%
  \bgroup 
    \trace{m}{Rule will be \rule@wid (hsize=\the\hsize)}%
  \hbox{\raise\rule@adjust\hbox to \hsize{\hskip\leftskip\ifx\rule@pos\@lignLeft\else\hfil\fi
    \hbox to \rule@wid{\orn@SetStretch{\rule@wid}{x}{}{\p@ttern}\Ornaments{\p@ttern}%\hss\vrule height \rule@thk width 0.1pt
    }%
    \ifx\rule@pos\@lignRight\else\hfil\fi\hskip\rightskip}}%
  \egroup
  \ifx\oldOrnamentsFamily\OrnamentsFamily\else
    \trace{m}{Restoring \oldOrnamentsFamily (from \OrnamentsFamily)}%
    \SwitchOrnamentsFamily{\oldOrnamentsFamily}%
  \fi
}

\def\r@und#1.#2\E{\ifdim .#2 pt < .5pt  #1\else\the\numexpr #1+1\relax\fi}
\def\GraphicOrnament#1#2{% Convert an image #2 into local ornament #1
  \bgroup
    \let\picfilecomm@nd=\XeTeXpicfile
    \expandafter\ch@ckpdf#2..\endf@lename
    \setbox0\hbox{\picfilecomm@nd "#2" }%
    \edef\tmp{\strip@pt{\wd0}}%
    \x@\xdef\csname localornament@#1@X\endcsname{\x@\r@und\tmp\E}%
    \edef\tmp{\strip@pt{\ht0}}%
    \x@\xdef\csname localornament@#1@Y\endcsname{\x@\r@und\tmp\E}%
    \ifx\picfilecomm@nd\XeTeXpicfile
      \x@\gdef\csname localornament@#1@code\endcsname{%
        %\def\@@x{\ifdim\dimen0 < 0pt \the\dimexpr-\dimen0\relax \else \the\dimen0\fi}%
        %\def\@@y{\ifdim\dimen1 < 0pt \the\dimexpr-\dimen1\relax \else \the\dimen1\fi}%
	\edef\@@x{\the\dimexpr \@pgfornamentX\pdf@xunit\relax}%
	\edef\@@y{\the\dimexpr \@pgfornamentY\pdf@yunit\relax}%
        \trace{g}{Graphic "#2" width \@@x, height \@@y}%
        \hbox{\XeTeXpicfile "#2" width \@@x height \@@y}}%
    \else
      \x@\gdef\csname localornament@#1@code\endcsname{%
	\edef\@@x{\the\dimexpr \@pgfornamentX\pdf@xunit\relax}%
	\edef\@@y{\the\dimexpr \@pgfornamentY\pdf@yunit\relax}%
        \trace{g}{PDF "#2" width \@@x, height \@@y}%
	\hbox{\XeTeXpdffile "#2" width \@@x height \@@y }}%
    \fi
  \egroup
}

\def\MapBorderHlabels{A,B,C,D,E,F,G,H,I,J,K}
\def\MapBorderVlabels{1,2,3,4,5,6,7,8,9}
\def\m@b@fallbackL{V}
\def\m@b@fallbackR{V}
\def\m@b@fallbackT{H}
\def\m@b@fallbackB{H}
\def\orn@Side{}
\def\zSEQ{%
  \trace{orn}{zSEQ \orn@Side, \the\orn@seq@num}%
  \ifx\orn@Side\undefined\error{!zSEQ called without a defined side}\fi
  \ifx\orn@Side\relax\error{!zSEQ called without a valid side}\fi
  \ifcsname MapBorder\orn@Side labels\endcsname\x@\let\x@\@list\csname MapBorder\orn@Side labels\endcsname \let\tmp\orn@Side\else
    \x@\let\x@\tmp\csname m@b@fallback\orn@Side\endcsname
    \x@\let\x@\@list\csname MapBorder\tmp labels\endcsname
  \fi
  \ifx\@list\relax\message{!zSEQ did not find a valid list (\orn@Side -> \tmp)}\else
    \ifx\@list\empty\else
      \edef\c@llers{\@list,}%
      \count255=\orn@seq@num
      \x@\if\csname m@b@fallback\orn@Side\endcsname H% Horizontal borders have a corner piece.
        \advance\count255 by -1
      \fi
      \loop\ifnum\count255>1
        \advance\count255 by -1
        \expandafter\dropfirstc@ller\c@llers\end
        \ifx\c@llers\empty\edef\c@llers{\@list,}\fi
        \trace{orn}{Autolist: \c@llers}%
        \repeat
      \trace{orn}{zSEQ =>\c@llers}%
      \expandafter\getfirstc@ller\c@llers\end
    \fi
  \fi
}
  
\def\pgfsetmiterlimit#1{}
\edef\borderstylelist{\borderstylelist, ornaments}
\let\pgfsetroundjoin\relax
\let\typeout\message
\let\pgfsetrectcap\relax
\plugin@endif
