%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Part of the ptx2pdf macro package for formatting USFM text
% copyright (c) 2007-2020 by SIL International
% original parts by Johnathan Kew, 
% split off into separate parts and recent additions by David Gardner
%
% Permission is hereby granted, free of charge, to any person obtaining  
% a copy of this software and associated documentation files (the  
% "Software"), to deal in the Software without restriction, including  
% without limitation the rights to use, copy, modify, merge, publish,  
% distribute, sublicense, and/or sell copies of the Software, and to  
% permit persons to whom the Software is furnished to do so, subject to  
% the following conditions:
%
% The above copyright notice and this permission notice shall be  
% included in all copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  
% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF  
% MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND  
% NONINFRINGEMENT. IN NO EVENT SHALL 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.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% \fig handling code, originally from paratext2.tex

% Inserts
%\newinsert\topins is already defined in plainTeX
\count\topins=1000 \dimen\topins=\maxdimen \skip\topins=0pt
\newinsert\bottomins \count\bottomins=1000 \dimen\bottomins=\maxdimen
\newinsert\verybottomins \count\verybottomins=0 \dimen\verybottomins=\maxdimen
\newinsert\topleftins \count\topleftins=0 \dimen\topleftins=\maxdimen
\newinsert\toprightins \count\toprightins=0 \dimen\toprightins=\maxdimen
\newinsert\bottomleftins \count\bottomleftins=0 \dimen\bottomleftins=\maxdimen
\newinsert\bottomrightins\count\bottomrightins=0 \dimen\bottomrightins=\maxdimen
\newcount\tmpcountB
\newbox\c@ptionbox
\def\colinsert@name#1{colinsert@#1}
\let\colinsert@tL\topleftins
\let\colinsert@bL\bottomleftins
\let\colinsert@tR\toprightins
\let\colinsert@bR\bottomrightins

\def\pageins@rts{bottomins,verybottomins,topins,}
\def\columnins@rts{colinsert@tL,colinsert@tR,colinsert@bL,colinsert@bR,}
%toprightins, bottomleftins etc. are now aliases
\edef\ins@rts{\columnins@rts\pageins@rts}

\def\s@veclasses{col,chunk,} % diglot needs to save two distinct states per box.
\def\s@veins@class@name#1#2{save#1#2}
\def\s@veclass@name#1{\s@veins@class@name{#1}{\s@veclass}}
\def\m@kes@veb@x#1\E{\x@\newb@x\csname \s@veins@class@name{\ins@base}{#1}\endcsname}
\def\s@veins#1\E{\x@\setbox\x@3\x@\copy\csname #1\endcsname\x@\global\x@\setbox\csname \s@veclass@name{#1}\endcsname\box3}
\def\r@strins#1\E{\x@\setbox\x@3\x@\copy\csname \s@veclass@name{#1}\endcsname\x@\global\x@\setbox\csname #1\endcsname\box3}
\def\sh@winsertdim#1\E{\x@\let\x@\tmp\csname \v@lpfx#1\v@lsfx\endcsname\immediate\write-1{\v@lpfx#1\v@lsfx: \ifx\tmp\relax\else\the\ht\tmp\space x \the\wd\tmp\fi}}

\def\m@keinsertsaveboxes#1\E{\edef\ins@base{#1}\let\D@=\d@\let\d@=\m@kes@veb@x
  \x@\cstackdown\s@veclasses\E
  \let\d@=\D@
}

\def\s@veinserts#1{%loop through \ins@rts and save them
  \trace{gI}{Saving inserts (#1)}%
  \edef\s@veclass{#1}%
  \let\d@=\s@veins
  \x@\cstackdown\ins@rts\E
}

\def\r@storeinserts#1{%loop through \ins@rts and save them
  \trace{gI}{Restoring inserts (#1)}%
  \edef\s@veclass{#1}%
  \let\d@=\r@strins
  \x@\cstackdown\ins@rts\E
}


% Helper function for figure parameters which might come from the fig line, a stylesheet, or a default.
\def\setf@gval#1#2#3#4{\let#1\empty
  \x@\let\x@\tmpp@ram\csname figparam-x-#2\endcsname
  \trace{F}{figparam-x-#2 (lo:\loc@ption, \picl@c, \l@cspec@a\l@cspec@b) is \meaning\tmpp@ram }%
  \ifx\tmpp@ram\relax\let\tmpp@ram\empty\fi
  \ifx\tmpp@ram\empty
    \getp@ram{#2}{loc:\picl@c|fig}{loc:\picl@c|fig}% +fig ? Dangerous.
    \ifx\p@ram\relax
      \edef#1{#4}%
    \else
      \ifx\p@ram\empty
        \edef#1{#4}%
      \else
        \edef#1{\p@ram #3}%
      \fi
    \fi
  \else
    \let#1\tmpp@ram
  \fi
  \trace{F}{\string#1 is #1}%
}
\def\setf@gNval#1#2#3#4{\edef#1{#4}% As above, but allowing for Normal fig values too
  \x@\let\x@\tmpp@ram\csname figparam-x-#2\endcsname
  \trace{F}{figparam-x-#2 (lo:\loc@ption, \picl@c, \l@cspec@a\l@cspec@b) is \meaning\tmpp@ram }%
  \ifx\tmpp@ram\relax\let\tmpp@ram\empty\fi
  \ifx\tmpp@ram\empty
    \getp@ram{#2}{fig}{fig}%
    \ifx\p@ram\relax\else
      \ifx\p@ram\empty
        \edef#1{#4}%
      \else
        \edef#1{\p@ram #3}%
      \fi
    \fi
  \else
    \let#1\tmpp@ram
  \fi
  \trace{F}{\string#1 is #1}%
}


% Generate the insert save-boxes for each class at start-up
\addtoinithooks{\let\d@=\m@keinsertsaveboxes\x@\cstackdown\ins@rts\E}

%%%%%%%%%%%%%% FIGURES %%%%%%%%%%%%%%
% called from \fig or from figure list

% Place everything up to first | into \param-N.
% Redefine \p@rams to be rest of list
%+cfig_stripspace
\def\stripspace#1 \end/#2\relax#3{\if\relax#2\relax\xdef\p@ram{#3}\else\stripspace#1\end/ \end/\relax{#1}\fi}
%-cfig_stripspace
%+cfig_getonepair
%\def\FigP@ramAlt{alt} \def\FigP@ramSrc{src} \def\FigP@ramSize{size} \def\FigP@ramLoc{loc}
%\def\FigP@ramCopy{copy} \def\FigP@ramRef{ref} \def\FigP@ramXtra{x-xetex} \def\FigP@ramPgpos{pgpos}
%\def\FigP@ramMirror{mirror} \def\FigP@ramScale{scale}  \def\FigP@ramMedia{media}

\def\s@tp@ramid{%This is used both to decode numeric parameters and to reset named parameters.
  \ifnum \p@ramnumber<0
    \edef\p@ramid{NEG\the\p@ramnumber}%
  \else
    \ifnum \p@ramnumber>21 \global\morep@ramsfalse\fi % The number on this line should be 1 below the count of valid parameters.
    %WARNING: There must not be a space after the text(before \or / \else / \fi) or (re)-initialisation will break
    \edef\p@ramid{\ifcase\p@ramnumber UNK-0\or alt\or src\or size\or loc\or copy\or caption\or ref\or x-xetex\or mirror\or  %0-9
         scale\or media\or pgpos\or x-credit\or x-creditpos\or x-creditrot\or x-creditbox\or x-spacebeside\or x-spacebefore\or x-spaceafter\or %10-19
         x-edgeadjust\or cat\or x-spacebetween\else UNK-\the\p@ramnumber\fi}%
  \fi
}
\newif\ifusfmthree \usfmthreefalse
\lowercase{\def\setp@r@mid #1#2\E{\edef\p@ramid{\ifx ~#1\else #1\fi#2}}}% Kill off infuriating leading space issue
\def\getonepairp@ram#1="#2" {\stripspace#1\end/ \end/\relax{#1}\ifx\p@ram\empty\let\p@ramid\empty\else\x@\setp@r@mid\p@ram\E\fi
  \stripspace#2\end/ \end/\relax{#2}\edef\p@ramval{\p@ram}%
  \trace{g}{getonepairparam: [\p@ramid] = [\p@ramval]}%
  \ifx\p@ramid\empty\let\fnext=\relax\else
    %\ifx\p@ramid\FigP@ramSrc\global\p@ramnumber=2\else
    %\ifx\p@ramid\FigP@ramSize\global\p@ramnumber=3 \trace{g}{Got Size}\else
    %\ifx\p@ramid\FigP@ramLoc\global\p@ramnumber=\x@\ifx\csname param-4\endcsname\empty 4\else 5\fi\else
    %\ifx\p@ramid\FigP@ramPgpos\global\p@ramnumber=4\else
    %\ifx\p@ramid\FigP@ramCopy\global\p@ramnumber=5\else
    %\ifx\p@ramid\FigP@ramAlt\global\p@ramnumber=6\else
    %\ifx\p@ramid\FigP@ramRef\global\p@ramnumber=7\else
    %\ifx\p@ramid\FigP@ramXtra\global\p@ramnumber=8\else %experimental extra parameter, post filename e.g. "rotated 90"
    %\ifx\p@ramid\FigP@ramMirror\global\p@ramnumber=9\else %experimental mirror parameter.
    %\ifx\p@ramid\FigP@ramScale\global\p@ramnumber=10\else
    %\ifx\p@ramid\FigP@ramMedia\global\p@ramnumber=11\else
    \ifx\p@ramval\empty
      \ifusfmthree
        \let\fnext=\getonepairp@ram
      \else
        \let\p@ramval=\p@ramid
        \ifnum\p@ramnumber>0
          \s@tp@ramid
        \else
          \edef\p@ramid{error}%
        \fi
        \let\fnext=\relax
        \trace{g}{usfm2 style parameter (\p@ramid=)\p@ramval}%
       \fi
    \else
      \trace{g}{usfm3 parameter \p@ramid=\p@ramval}%
      \ifusfmthree\else %first usfm3 parameter. USFM3 says first param is comment,  not alt-text. Swap them
        \x@\let\x@\t@mp\csname figparam-alt\endcsname
        \x@\global\x@\let\csname figparam-caption\endcsname\t@mp
        \x@\global\x@\let\csname figparam-alt\endcsname\empty
        \usfmthreetrue
      \fi
      \let\fnext=\getonepairp@ram
      %\trace{g}{Unrecognised usfm3 parameter \p@ramid}\p@ramnumber=-1%
    \fi% If there's no value, it's probably usfm2-style
    \x@\global\x@\let\csname figparam-\p@ramid\endcsname\p@ramval
    %\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi
   % \tempfalse
   % \ifx\p@ramval\empty\ifusfmthree\else
   %   \trace{g}{param-\the\p@ramnumber = "\p@ramid" but not "\p@ramval"}%
   %   \x@\global\x@\edef\csname param-\the\p@ramnumber\endcsname{\p@ramid}%
   %   \let\fnext=\relax
   %   \temptrue
   % \fi\fi
   % \iftemp\else
   %   \trace{g}{param-\the\p@ramnumber [\p@ramid]  = "#2" from "\p@ramval"}%
   %   \x@\gdef\csname param-\the\p@ramnumber\endcsname{#2}%
   %   \let\fnext=\getonepairp@ram \usfmthreetrue
   % \fi
  \fi\fnext}
%-cfig_getonepair

%+cfig_parsesize
\def\p@rsesize#1*#2*#3\end{%
  \trace{g}{p@rsesize #1*#2*#3}%
  \global\def\size@ption{#1}%
  \edef\tmp{#2}%
  \ifx\tmp\empty\else\def\sizem@ltiple{#2}\trace{g}{Setting scale to #2}\fi% empty if not provided
}
%-cfig_parsesize

%+cfig_parsextra
\def\getnum#1=#2\end{#1}%

% These three macros split up x-xetex="foo" parameter, stripping out any key=val formated parameters and leaving the rest.
%

\def\p@rs@xtr@#1=#2=#3\end{\edef\t{#2}%
  \ifx\t\empty \edef\t{#1}%
    \ifx\t\empty\else
      \edef\xtraremains{\xtraremains#1\space}\trace{g}{Passing #1 directly to xetex}%
    \fi
  \else
    \trace{g}{Found k=#1,v=#2 (x=#3)}%
    \def\key{#1}\def\val{#2}%
    \ifx\key\keyR@TATE \rotimagetrue
      \ifx\val\val@BIND \ifodd\whichp@ge\def\xtra{rotated 90}\else\def\xtra{rotated -90}\fi
      \else
        \ifx\val\val@EDGE \ifodd\whichp@ge\def\xtra{rotated -90}\else\def\xtra{rotated 90}\fi
        \else \tempfalse \t@mpfalse
          \ifx\val\val@dd \t@mptrue \ifodd\whichp@ge\temptrue\fi\fi
          \ifx\val\val@ven \t@mptrue \ifodd\whichp@ge\else\temptrue\fi\fi
          \iftemp \edef\angle{\getnum#3==\end}%
            \ifx\empty\angle \message{Expected rotate=\val=42 or similar in definition of picture \f@lename}%
            \else \xdef\xtra{rotated \angle}\fi
          \fi
          \ift@mp\else
            \message{Unexpected value rotate=#2. Expected values "edge", "binding", "odd", or "even"}%
          \fi
        \fi
      \fi
    \else
      \ifx\key\keyP@GE
        \ifx\picfilecomm@nd\XeTeXpdffile
          \edef\picp@ge{page \val}%
        \else
          \message{Not a PDF file, page=... only supported on PDFs}%
        \fi
      \else
        \message{Unexpected key #1=#2. Expected key "rotate"}%
      \fi
    \fi
  \fi
}
\def\p@rsextr@#1 #2\relax{%                                                     %(2)
  \trace{g}{processing #1}%
  \edef\t{#2}\ifx\t\empty\let\n@xt=\relax\fi
  \edef\t{#1}\ifx\t\empty\let\n@xt=\relax
  \else \x@\p@rs@xtr@\t==\end \fi
  \x@\n@xt#2 \relax
}
\def\p@rsextra#1{%                                                              %(1)
  \trace{g}{Parsing #1}%
  \edef\@rg{#1 }%Space is needed!
  \def\xtraremains{}\let\n@xt=\p@rsextr@
  \edef\t{#1}\ifx\t\empty\let\n@xt=\relax\fi
  \x@\n@xt\@rg  \relax
}
%-cfig_parsextra

%+cfig_getoneparam
\def\getonep@ram#1|#2\end{\gdef\p@rams{#2}%
  \trace{g}{getoneparam: #1 | #2}%
  \getonepairp@ram#1 ="" \relax%
  \global\advance\p@ramnumber by 1 }
%-cfig_getoneparam

\newif\iffiglocleft \figloclefttrue
\newif\ifpicUsesIns \picUsesInstrue
\newif\ifpicNarrow \picNarrowfalse
\newif\ifpicTall \picTallfalse
\newif\ifrotimage
\newif\ift@mp %because just one temp isn't enough

%+cfig_parsepicuse
\def\p@rsePicXtra#1#2\end{% Parse optional new picture options, and remember them
  \xdef\l@cspec@b{#1}\xdef\l@cspec@c{#2}%
}
\def\p@rseLoc#1#2\end{% Parse the new picture options, and remember them
  \edef\l@cspec@a{#1}\edef\l@cspec@b{#2}%
  \ifx\l@cspec@b\empty\let\l@cspec@c=\l@cspec@b\else\x@\p@rsePicXtra\l@cspec@b\end\fi
  \trace{g}{p@rseLoc: #1 \l@cspec@b|\l@cspec@c}%
  % inner/outer support for everything
  \tempfalse
  %Switch relative (inner/outer) to absolute (left/right) depending on page number for this image.
  \ifx\l@cspec@b\@lignOuter\temptrue\ifodd\whichp@ge\let\l@cspec@b=\@lignRight\else\let\l@cspec@b=\@lignLeft\fi\fi
  \ifx\l@cspec@b\@lignInner\temptrue\ifodd\whichp@ge\let\l@cspec@b=\@lignLeft\else\let\l@cspec@b=\@lignRight\fi\fi
}

%NB THIS IS ONLY for page-based items, not for e.g. captions.
\def\p@rsePicUse#1\end{% Parse the new picture options, and remember them.
  \x@\p@rseLoc#1\end % sets \l@cspec@a, \l@cspec@b, \l@cspec@c to chars 1, 2, 3+
  \iftemp
    % inner/outer support for inserts
    \trace{g}{Page \the\whichp@ge, defined #1 to \l@cspec@a, \l@cspec@b, \l@cspec@c}%
  \fi
  \tempfalse
  \ifx\l@cspec@a\loc@T\temptrue\fi
  \ifx\l@cspec@a\loc@B\temptrue\fi
  \iftemp
    \ifx\l@cspec@b\empty\else
      \ifnum\c@rrentcols>1\else
        \tempfalse %Can't do it.
      \fi
    \fi
    %redefine loc@ption
    \iftemp
      \xdef\loc@ption{\l@cspec@a\l@cspec@b}%
    \else
      \let\l@cspec@b\empty
      \x@\let\x@\tmp\csname \w@tsit @warning\endcsname
      \ifx\tmp\relax
        \picw@rning{#1}{\l@cspec@a\l@cspec@b}%
      \else
        \tmp{#1}{\l@cspec@a\l@cspec@b}%
      \fi
      \xdef\loc@ption{\l@cspec@a}%
    \fi
    \ifx\l@cspec@b\empty
      \global\let\picl@c\loc@ption
    \else
      \xdef\picl@c{\l@cspec@a X}%
    \fi
  \fi
  % new options
  \ifx\l@cspec@a\loc@InlB
    \InlBelowtrue
    \let\l@cspec@a\loc@Inl
  \else
    \InlBelowfalse
  \fi
  \ifx\l@cspec@a\loc@InText
    \trace{g}{Experimental intext \w@tsit in \m@rker, \the\dimexpr 1em\relax, \the\dimexpr \c@rrfontsize\FontSizeUnit\relax}%
    \global\let\picl@c\loc@InText\xdef\pic@lign{\l@cspec@b}\global\picUsesInsfalse\p@cinswid=\hsize
    \picNarrowtrue
  \fi
  \ifx\l@cspec@a\loc@Inl
    \trace{g}{Experimental inline \w@tsit}%
    \global\let\picl@c\loc@Inl\xdef\pic@lign{\l@cspec@b}\global\picUsesInsfalse\p@cinswid=\hsize
    \ifx\l@cspec@b\@lignLeft\picNarrowtrue\fi
    \ifx\l@cspec@b\@lignRight\picNarrowtrue\fi
  \fi
  \ifx\l@cspec@a\loc@Cut
    \global\let\picl@c\loc@Cut\global\picUsesInsfalse\global\picNarrowtrue\p@cinswid=\hsize
    \xdef\l@cspec{\l@cspec@b}%
    \ifx\l@cspec@c\empty\gdef\c@tskip{0}\gdef\c@tskipfrac{0}\else
      \x@\c@tskipparse\l@cspec@c...\E %split c@tskip into whole and fractional parts.
    \fi
    \trace{g}{Experimental \w@tsit in cutout, after \c@tskip lines}%
  \fi
  \ifx\l@cspec@a\loc@Par
    \global\let\picl@c=\loc@Par\p@cinswid=\hsize
    \xdef\pic@lign{\l@cspec@b}\global\picUsesInsfalse
    \ifx\l@cspec@b\@lignLeft\picNarrowtrue\fi
    \ifx\l@cspec@b\@lignRight\picNarrowtrue\fi
    \ifx\l@cspec@c\empty\gdef\c@tskip{0}\else
      \x@\p@rskipparse\l@cspec@c...\E
    \fi%We Borrow cutskip for parskip
    \trace{g}{Experimental after-paragraph \w@tsit, delay: \c@tskip}%
  \fi
  % full-page options
  \tempfalse
  \ifx\l@cspec@a\loc@Page\global\let\picl@c=\loc@Page\global\picUsesInsfalse\temptrue\fi
  \ifx\l@cspec@a\loc@Full\global\let\picl@c=\loc@Full\global\picUsesInsfalse\temptrue \p@cinswid=\PaperWidth\fi
  \iftemp
    \xdef\pic@lign{\l@cspec@b}\xdef\picV@lign{\l@cspec@c}%
    \trace{g}{Experimental page / full-page \w@tsit (\pic@lign|\picV@lign)}%
  \fi
  \ifx\l@cspec@a\loc@M\global\picUsesInsfalse\fi
}
%-cfig_parsepicuse

%+cfig_docaption
\def\DecorateRef#1{(#1)}

\def\d@c@ption#1{% Called with #1= diglot column or {} for normal.
  \edef\cpt@mp{#1}%
  \x@\let\x@\thsr@f\csname figparam-ref#1\endcsname% get reference
  \ifx\thsr@f\relax
    \xdef\@r@f{\r@f}\else
    \xdef\@r@f{\thsr@f}\x@\global\x@\let\csname figparam-ref#1\endcsname\undefined%
  \fi%
  \stripspace\@r@f\end/ \end/\relax\@r@f \edef\@r@f{\p@ram}% strip space
  \x@\let\x@\c@ption\csname figparam-caption#1\endcsname% get caption
  \ifx\c@ption\relax\let\c@ption\empty\else
    \x@\global\x@\let\csname figparam-caption#1\endcsname\undefined%
  \fi
  \trace{g}{Fig caption#1: [\c@ption] \ifx\@r@f\empty\else(\@r@f)\fi}%
  \ifx\c@ption\empty\else
    \bgroup
    \ifx\cpt@mp\empty\else\setLRspecific\fi
    \edef\@@r@f{\ifx\@r@f\empty\else\DecorateRef{\@r@f\unskip}\fi}%
    \t@xtfragment{fig}{%
      \let\styst@k=\empty
      \s@tstyst@k%
      \s@tfont{fig}{fig}%
      \ifCaptionRefFirst\@@r@f\nobreak\ \fi
      %\implicitcl@sefalse
      \p@sheof
      \x@\scantokens\x@{\c@ption}\unskip
      \p@peof
      \ifCaptionRefFirst\else\nobreak\ \@@r@f\fi}%
    \egroup
  \fi
}

\newif\ifDoCaptions
\DoCaptionstrue
\newif\iffigh@scaption\figh@scaptionfalse

\def\d@caption{%
  %\ifhmode\endgraf\fi
  \unvbox\c@ptionbox
  \vskip.5\onel@neunit
}

\def\FigCaptionAdjust{0pt}

\def\setc@ptionbox{%
 \setbox\c@ptionbox\vbox{\everypar={}\let\par\endgraf%
  \ifDoCaptions
    \ifCaptionFirst\else \prevdepth=0pt\fi %Interline glue above a low caption
    \ifpicNarrow
      \hsize=\sizem@ltiple\p@cwidth
    \else
      \hsize=\p@cinswid
    \fi
    \xdef\r@f{\csname figparam-ref\endcsname}% get reference
    \mcpush{\ss@Fig}{fig}%
    \d@c@ption{}%Normal monoglot caption.
    \ifdiglot
      \bgroup %Alternative captions
        \def\col@do##1{\def\c@rrdstat{##1}\d@c@ption{##1}}%
		\ifx\DiglotCaptions\undefined \let\tmp=\diglot@list\else \let\tmp=\DiglotCaptions\fi
        \x@\each@col\tmp\E
      \egroup
    \fi
    \end@llpoppedstyles{\ss@Fig*}%
  \fi
 }%
}

\def\t@xtfragment#1#2{\bgroup\everypar={}\let\par\endgraf
    \trace{F}{t@xtfragment{#1}}%
    \leftskip=0pt plus \hsize \rightskip=\leftskip \parfillskip=0pt
    \getp@ram{justification}{#1}{#1}%
    \ifx\p@ram\r@ght\rightskip=0pt\fi
    \ifx\p@ram\l@ftb@l\leftskip=0pt\fi
    \ifx\p@ram\l@ft\leftskip=0pt\fi
    \getp@ram{leftmargin}{#1}{#1}%
    \ifx\p@ram\relax \else \advance \ifRTL\rightskip\else\leftskip\fi\p@ram \IndentUnit \fi
    \getp@ram{rightmargin}{#1}{#1}%
    \ifx\p@ram\relax \else \advance \ifRTL\leftskip\else\rightskip\fi\p@ram \IndentUnit \fi
    \ifRTL\beginR\fi
    \linepenalty=1000
    \s@tbaseline{#1}{#1}%
    \trace{F}{Checking boxed style for #1 /  \c@tprefix:\m@rker (\tmpstyst@k)}%
    \let\styst@k\tmpstyst@k
    \ch@ckb@xedstyle{\styst@kfirst}{\styst@k}%
    \ifb@xedstyle
      \trace{F}{t@xtfragment applying boxed style}%
      \setbox1\hbox{#2}%
      \set@endb@xedstyle{\styst@kfirst}{\styst@k}%
      \apply@endb@xedstyle{1}%
      \noindent\leavevmode\unhbox1\par
    \else
      \noindent\leavevmode #2\par
    \fi
    \ifRTL\endR\fi
    \egroup
}
%-cfig_docaption
%+cfig_addcredit
\newdimen\FigCreditPadding
\FigCreditPadding=2pt
\newdimen\FigCreditOverEdgeV
\newdimen\FigCreditOverEdgeH
\FigCreditOverEdgeH=0.07pt
\FigCreditOverEdgeV=0.07pt
\def\add@credit{% Box to add credit to is  \newpicb@x
  \ifx\cr@ditpos\empty
    \edef\cr@ditpos{ti}% Center, inner edge
  \fi
  \x@\p@rseLoc\cr@ditpos\end
  \edef\cred@v{\l@cspec@a}\edef\cred@h{\l@cspec@b}%
  \trace{g}{creditrot="\cr@ditrot"}%
  \ifx\cr@ditrot\empty % Set some kind of a defaults
    \ifx\cred@h\@lignLeft
      \edef\cr@ditrot{-90}
    \else
      \ifx\cred@h\@lignRight
        \edef\cr@ditrot{90}
      \else
        \edef\cr@ditrot{0}%
      \fi
    \fi
    \trace{g}{credit rotation blank, \cr@ditrot deg chosen}%
  \fi
  % Positioning of credit box.
  \def\pr@credit{}\def\p@stcredit{}\def\ab@vecredit{}\def\b@lowcredit{}%
  \ifx\@lignLeft\cred@h\def\p@stcredit{\hfill}%
  \else\ifx\@lignRight\cred@h\def\pr@credit{\hfill}%
    \else\def\pr@credit{\hfill}\def\p@stcredit{\hfill}\fi
  \fi
  \ifx\@lignTop\cred@v\def\b@lowcredit{\vfill}%
  \else\ifx\@lignBot\cred@v\def\ab@vecredit{\vfill}%
    \else\def\b@lowcredit{\vfill}\def\ab@vecredit{\vfill}\fi
  \fi
  %
  %\trace{g}{Parse credit box}%
  \let\cr@dit@col\empty
  \edef\cr@ditstyle{x-credit}%
  \edef\cr@ditlist{x-credit|fig,x-credit}%
  \ifx\cr@ditbox\empty\else
    \ifx\cr@ditbox\tru@\else
      \expandafter\p@rseCreditBox \cr@ditbox - - - \end\relax%
    \fi
    \ifx\cr@ditbox\tru@
    \else
      \edef\cr@ditlist{x-credit:box=\cr@ditbox|fig,\cr@ditbox|x-credit,x-credit|fig,\cr@ditstyle}%
    \fi
  \fi
  \trace{g}{cr@ditlist is \cr@ditlist.}%
  % Determine if the credit (as a full line) is wider or taller, and whether it should be treated as a paragraph or a
  % small piece of text.
  \count255=\cr@ditrot % adjust to -180 to 180 range.
  \loop
    \ifnum \count255>180 \advance\count255 by -360 \repeat
  \loop
    \ifnum \count255<-180 \advance\count255 by 360 \repeat
  \edef\@ngle{\the\count255}%
  \ifnum \count255>0
     \def\r@tSet{\kern\ht0}%
  \else
     \def\r@tSet{\kern\dp0}%
     \count255=-\count255
  \fi
  \edef\cr@ditr@tn{\the\count255}%credit rotation as a positive number (0-180)
  %pad credit
  \s@tfont{\cr@ditlist}{\cr@ditlist}% Use the fact that s@tfont checks for #1=#2 
  \setbox0=\hbox{\XeTeXuseglyphmetrics=3 % We subvert s@tfont's mechanism and provide a pre-formed list
    \ifRTL\beginR\fi\cr@dit\ifRTL\endR\fi}%
  \trace{g}{credit natural size is \the\ht0+\the\dp0 x\the\wd0}%
  \dimen1=\ht0\advance\dimen1 by \FigCreditPadding\ht0=\dimen1
  \dimen1=\dp0\advance\dimen1 by \FigCreditPadding\dp0=\dimen1
  % Calculuate maximum credit width.  (note count255 is now
  % positive)
  \ifnum \cr@ditr@tn>45
    \ifnum \cr@ditr@tn<135
       \dimen0=\ht\newpicb@x
    \else
       \dimen0=\wd\newpicb@x
       \def\r@tSet{}%
    \fi
  \else
    \dimen0=\wd\newpicb@x
  \fi
  \advance\dimen0 by -2\FigCreditPadding
  \ifdim\wd0>0.9\dimen0% Credit doesn't comfortably fit on one line. Find out how many it'll take
     \count255=2
     \loop
       \dimen1=\wd0
       \divide\dimen1 by \count255
       \ifdim \dimen1>\dimen0 \advance\count255 by 1 \repeat
     \advance \dimen1 by \ht0 %Add ~1em to each line as line breaking space
     \ifdim \dimen1>\dimen0
       \dimen1=\dimen0
     \fi
     % Now cram the text into a box that ought to be just wide enough
     \setbox0=\vbox{\topskip=0pt\hsize=\dimen1\relax\t@xtfragment{\cr@ditstyle}{\vrule width 0pt height\ht0 \unhbox0\vrule depth\FigCreditPadding width 0pt}}%
    %\ifnum\im@gecount=5 \showbox0\fi
  \else
    \b@ckgroundelsewheretrue
    \ch@ckb@xedstyle{\cr@ditlist}{\cr@ditlist}%
    \ifb@xedstyle
      \trace{g}{before applyingb@xedstyle \space credit boxed size is \the\ht0+\the\dp0 x\the\wd0}%
      \set@endb@xedstyle{\cr@ditlist}{\cr@ditlist}%
      \b@ckgroundelsewheretrue
      \apply@endb@xedstyle{0}%
      %\ifnum\im@gecount=5 \showbox0\fi
    \fi
  \fi
  \setbox0=\hbox{\hskip \FigCreditPadding\box0\hskip \FigCreditPadding}%
  \trace{g}{image\the\im@gecount \space credit boxed size is \the\ht0+\the\dp0 x\the\wd0}%
  \ifx\cr@ditbox\empty\else
    \ifx\cr@dit@col\empty
      \getp@ram{background}{\cr@ditlist}{\cr@ditlist}%
      \ifx\p@ram\relax
        \edef\cr@dit@col{1 1 1}%
      \else
        \ifx\p@ram\h@phen
          \edef\cr@dit@col{\p@ram}%
        \else
          \trace{g}{decoding \p@ram}%
          \x@\checkh@x \p@ram\end
          \let\cr@dit@col\rgb@out
          \trace{g}{ result: \cr@dit@col}%
          %\edef\cr@dit@col{\p@ram}%
        \fi
      \fi
    \fi
    \trace{g}{credit text on \cr@dit@col background}%
    \ifx\cr@dit@col\h@phen\else
      \setbox0=\hbox{\kern-5sp \colourbox{\cr@dit@col}{}{\the\dimexpr \wd0}{\the\dp0}{\the\ht0}{0pt}{\box0}\relax}%
    \fi
  \fi
  \ifnum\cr@ditrot=0 \else
    \ifnum\cr@ditr@tn>135
      \setbox0=\hbox{\rot@tebzoneeighty}%
      %\setbox0=\hbox{\raise\dp0 \box0}%
    \else
      \setbox0=\hbox{\rot@tebz}%
    \fi
  \fi
  \edef\cr@ditHshift{\the\FigCreditOverEdgeH}%
  \edef\cr@ditVshift{\the\FigCreditOverEdgeV}%
  %\trace{g}{cr@ditlist is \cr@ditlist}%
  \getp@ram{spacebefore}{\cr@ditlist}{\cr@ditlist}%
  \ifx\p@ram\relax\else
    \ifnum\cr@ditr@tn=90
      \edef\cr@ditHshift{\dimexpr \cr@ditHshift +\p@ram pt\relax}%
    \else
      \edef\cr@ditVshift{\dimexpr \cr@ditVshift + \p@ram pt\relax}%
    \fi
  \fi
  \getp@ram{spacebeside}{\cr@ditlist}{\cr@ditlist}%
  \ifx\p@ram\relax\else
    \ifnum\cr@ditr@tn=90
      \edef\cr@ditVshift{\dimexpr \cr@ditVshift - \p@ram pt\relax}%
    \else
      \edef\cr@ditHshift{\dimexpr \cr@ditHshift - \p@ram pt\relax}%
    \fi
  \fi
  \trace{g}{credit text is \the\wd0 x (\the\ht0 + \the\dp0) \ab@vecredit,\b@lowcredit // \cr@ditHshift, \cr@ditVshift}%
  \edef\ol@yboxwd{\the\dimexpr \wd\newpicb@x \relax}%
  \setbox0=\vbox to \ht\newpicb@x{\baselineskip=0pt \hsize=\ol@yboxwd\vskip -\cr@ditVshift\relax\ab@vecredit\hbox to \ol@yboxwd{\beginL\hskip -\cr@ditHshift\relax\pr@credit\box0\p@stcredit\hskip -\cr@ditHshift\relax\endL}\b@lowcredit\vskip -\cr@ditVshift}%
  \setbox\newpicb@x=\vbox to \ht\newpicb@x{\box\newpicb@x\vss\box0}%
  %\ifnum\cr@ditrot=180\showbox\newpicb@x\fi
}
\def\strip@minus#1-{#1}
\def\p@rseCreditBox#1 #2 #3 #4\end{%
  \trace{g}{credit box params "#1" "#2" "#3" "#4"}%
  \def\t@mp{- - }\def\tmp{#4}\ifx\tmp\t@mp
     \edef\cr@dit@col{\strip@minus #1 #2 #3}%
  \else
     \def\t@mp{t-}\def\tmp{#1}\ifx\tmp\t@mp
        \let\cr@ditbox\tru@
     \fi
  \fi
}
%-cfig_addcredit
%+cfig_hex
\def\checkh@x #1#2\end{%
  \def\t@mp{#1}%
  \uppercase{\edef\t@@mp{#1#2}}\ifx\t@@mp\fill@none\let\rgb@out\fill@none\else
  \ifx \t@mp\@x@\x@\h@xsixtotripple #1#2\end\else\def\rgb@out{#1#2}\fi\fi}

\def\h@xsixtotripple x#1#2#3#4#5#6\end{%
 \uppercase\x@{\def\rgb@out{%
   \x@\strip@pt\x@{\x@\dimexpr "#1#2 pt / 255}
   \x@\strip@pt\x@{\x@\dimexpr "#3#4 pt / 255}
   \x@\strip@pt\x@{\x@\dimexpr "#5#6 pt / 255}}}}
\setp@ram{fontsize}{x-credit|fig}{7}
%-cfig_hex

\def\PlaceHolderRule{0.5pt}% Thickness of rule around skipped figures
\def\m@kepl@ceholder#1#2#3{%
\vbox to #2{\offinterlineskip
  \trace{g}{makeplaceholder #3}%
  \hrule height \PlaceHolderRule\kern-\PlaceHolderRule
  \hbox to #1{\vrule height #2 width \PlaceHolderRule\vrule width \PlaceHolderRule}%
  \vbox to 0pt{\kern-#2 \vss \hbox to #1{\hss\idf@nt #3\hss}\vss}%
  \kern-\PlaceHolderRule\relax \hrule height \PlaceHolderRule\relax}}

\newif\ifSkipMissingFig \SkipMissingFigfalse
\newif\iffigf@und

\def\ins@rtpic#1#2#3#4#5#6#7{%Figure name #1 already has quotes.
 \edef\tmpfile{\mapinputfile{#1}}%
 \trace{g}{ins@rtpic #1 -> \tmpfile #7 #2 #3 (#4) #5 #6}%
 \openin\t@stread=#1\relax
   \ifeof\t@stread
     \message{MISSING IMAGE: #1 -> \tmpfile}%
     \global\figf@undfalse
     \dimen0=\ifdim #3>#4 #4\else #3\fi
     \m@kepl@ceholder{\dimen0}{0.618 \dimen0}{missing: #1}%  \csname figparam-src\endcsname
   \else \closein\t@stread
     \global\figf@undtrue
     \message{INPUTFILE: #1 -> \tmpfile}%
     \picfilecomm@nd \tmpfile\space #7 #2 #3 #5 #6%
   \fi
}

\oddc@tcodes%NO SPACES until |normalc@tcodes is called.
|def|ch@ckpathfwd#1/#2|E{|edef|t@mp{#2}|ifx|t@mp|empty|else|global|temptrue|fi}
|def|ch@ckpathback#1\#2|E{|edef|t@mp{#2}|ifx|t@mp|empty|else|global|temptrue|fi}%
|def|ch@ckpath#1{|global|tempfalse|ch@ckpathfwd#1/|E|ch@ckpathback#1\|E}%
|normalc@tcodes%
%+cfig_dofigure_intro

\def\@parpicstart#1#2#3#4{}
\def\@parpicstop#1#2#3#4#5#6{}
\def\@parpicsize#1#2#3#4{}
\def\@parpicanchor#1#2#3{}

\def\write@parpicsize{%
  \edef\p@cinfo{\p@climit\string{\the\wd\newpicb@x\string}\string{\the\ht\newpicb@x\string}}%
  \write\x@\p@rlocs\x@{\p@cinfo}%
}

\def\write@picanchor{%
  \pdfsavepos
  \edef\tmp@nchor{\string\@parpicanchor{\ifdiglot\dc@rref\else\c@rref\fi}}%
  \write\x@\p@rlocs\x@{\tmp@nchor{\the\pdflastxpos}{\the\pdflastypos}}%
}

\gdef\pr@penalty{10}\gdef\p@stpenalty{10}%
\def\d@figure#1{%
 \trace{g}{d@figure entered IncludeFigures\ifIncludeFigures true\else false\fi}%
 \ifIncludeFigures
  \ifdim\hsize=0pt
    \hsize=\colwidth
  \fi
  \trace{g}{In d@figure #1 (hsz=\the\hsize)}\usfmthreefalse
  \t@gempty{Anchor}{fig}%
  \rotimagefalse
  \figh@scaptionfalse
  \def\pr@penalty{10}\def\p@stpenalty{10}%
  \edef\hs@ze{\the\hsize}% Current col size
  \gdef\p@rams{#1|}% ensure there is a trailing | separator
  % place parts of text into \param-1, \param-2, ...
  \global\p@ramnumber=1
  % Set all parameters to empty
  \loop
    \morep@ramstrue
    \s@tp@ramid% Sets morep@ramsfalse if off the end.
    \x@\gdef\csname figparam-\p@ramid\endcsname{}%
    \global\advance\p@ramnumber by 1
    \ifmorep@rams \repeat
    %\ifnum\p@ramnumber<12\repeat
  \global\p@ramnumber=1
  \loop
    \x@\getonep@ram\p@rams\end
    \ifx\p@rams\empty \morep@ramsfalse \else \morep@ramstrue \fi
    \ifmorep@rams\repeat
  %\ifusfmthree\x@\edef\csname param-caption\endcsname{\csname param-1\endcsname}\fi
  % get size
  \lowercase{\edef\size@ption{\csname figparam-size\endcsname}}%
  \lowercase{\edef\sizem@ltiple{\csname figparam-scale\endcsname}}%
  \expandafter\p@rsesize\size@ption**\end % extract possible multiplier
  % figparam-loc is ambiguously used, as either pgpos or media or something else.
  \x@\ifx\csname figparam-loc\endcsname\empty\else
    %if there's no -pgpos, assume that the (ambiguous) -loc parameter got used
    \x@\ifx\csname figparam-pgpos\endcsname\empty
      \x@\xdef\csname figparam-pgpos\endcsname{\csname figparam-loc\endcsname}%
      \x@\xdef\csname figparam-loc\endcsname{}%
    \else
      \x@\ifx\csname figparam-media\endcsname\empty
        \x@\xdef\csname figparam-media\endcsname{\csname figparam-loc\endcsname}%
        \x@\xdef\csname figparam-loc\endcsname{}%
      \fi
    \fi
  \fi
  \global\let\origc@t\c@tegory
  \let\orig@sbm\sb@rmarker
  \ifcsname figparam-cat\endcsname
    % Relying on the fact that \fig is always in a box, pretend to be in a sidebar called 'fig', and get the border parameters.
    \x@\S@tCat\x@{\csname figparam-cat\endcsname}%
    \trace{g}{Loading border parameters for \c@tegory}%
    \def\sb@rmarker{fig}%
    \get@border@style@params
    \prepb@rderdims
    \getsbp@ram{hascol}\let\h@scol\cp@ram%
    \ifx\h@scol\tr@e
      \getsbp@ram{alpha}\global\let\pdf@lpha=\cp@ram
      \getsbp@ram{bgcolour}\let\pdfBGc@l=\cp@ram
    \fi
  \else
    \hasb@rderfalse
    \let\h@scol\false
  \fi
  % get location
  \edef\loc@ption{\csname figparam-pgpos\endcsname}%%
%-cfig_dofigure_intro
  %
%+cfig_dofigure_1
  \ifx\loc@ption\empty % if location empty
    \ifx\size@ption\size@SPAN%
        \def\loc@ption{t}% if size is SPAN default to top
        \else\def\loc@ption{tl}\fi % else default to top left FIXME? Standard says inline. Could swap to h if that proves stable.
  \fi
  \ifDoCaptions
    \t@mpfalse
    \x@\ifx\csname figparam-caption\endcsname\empty
      \ifdiglot
        \def\col@do##1{\ifcsname figparam-caption##1\endcsname \x@\ifx\csname figparam-caption##1\endcsname\empty\else\figh@scaptiontrue\fi\fi}%
        \x@\each@col\diglot@list\E
      \fi
    \else
      \figh@scaptiontrue
    \fi
  \fi
  % set width to column width or span width and other default parameters
  \p@cwidth=\textwidth \advance\p@cwidth by -\columnshift
  \p@cheight=\textheight
  \advance\p@cheight by -2\onel@neunit % there should be text on the page too - allow for caption+space+2 lines of text!
  \picUsesInstrue \picNarrowfalse                                               %(1)
  \gdef\pic@lign{c}% How does the picture align within the box?
  \gdef\picV@lign{c}% How does the picture align vertically on the page (Page/Full only)
  \gdef\picl@c{}% location code for in-line (non-insert) pictures
  % By default, set the insert width to full span
  \p@cinswid=\textwidth\advance\p@cinswid by -\columnshift
  \picTallfalse
  \ifx\size@ption\size@COL \p@cwidth=\hsize
  \else\ifx\size@ption\size@SPAN
    \else\ifx\size@ption\size@WIDTH
      \p@cwidth=\PaperWidth
     \else\ifx\size@ption\size@PAGE
        \global\let\picl@c=\loc@Page
        \picUsesInsfalse
        \p@cheight=\textheight % without text
      \else\ifx\size@ption\size@FULL
          \global\let\picl@c=\loc@Full
          \picUsesInsfalse
          \p@cwidth=\PaperWidth\p@cheight=\PaperHeight
          \p@cinswid=\PaperWidth
        \else
          \ifx\size@ption\size@FONT \p@cwidth=\c@rrfontsize\FontSizeUnit
            \p@cinswid=\p@cwidth \picTalltrue
          \else
            \ifx\size@ption\size@LINE \p@cwidth=\baselineskip
              \p@cinswid=\baselineskip \picTalltrue
            \else
             \errmessage{Unknown picture size "\size@ption", expected "col", "span", "width", "page", "full", "font" or "line"}\fi\fi\fi\fi\fi\fi\fi
  \let\p@cins=\relax
%-cfig_dofigure_1
  % --------- Parse the location option -----------
%+cfig_dofigure_2
  \global\advance\im@gecount by 1
  \x@\let\x@\pgn@\csname fig\the\im@gecount p@ge\endcsname                    %(1)
  \ifx\pgn@\relax
    \whichp@ge=\pageno
    \trace{g}{Picture \the\im@gecount may not be mirrored/rotated/aligned properly}%
  \else
    \whichp@ge=\pgn@
    \trace{g}{Picture \the\im@gecount was on page \pgn@ last time. [\the\pageno]}%
  \fi
  \let\w@tsit\gr@phic   % Make sure the debugging info is correct. Also, tested for sometimes
  \x@\p@rsePicUse\loc@ption\end                                               %(2)
  % make \p@cins point to insertion class for this location
  \otherinsht=0pt % subtract this from the insert height.
  \ifx\loc@ption\loc@T \let\p@cins=\topins
  \else
    \ifx\loc@ption\loc@B \let\p@cins=\bottomins
    \else
      \ifdiglot %For diglot, need to know the height of the tallest insert
        \ifx\l@cspec@a\loc@T %(Only affects top)
          \let\col@do=\max@boxht \dimen1=0pt
          \edef\v@lpfx{\colinsert@name{t}}\def\v@lsfx{}%
          \x@\each@col\diglot@list\E
          \uppercase{\def\t@mp{\l@cspec@b}}%
          \ifx\t@mp\m@x@at@col\else %don't adjust height if this box is already highest
            \otherinsht=\dimen1
          \fi
        \fi
      \fi
      \ifnum\c@rrentcols>1
        \ifx\l@cspec@a\loc@T
          \p@cinswid=\hsize
        \else\ifx\l@cspec@a\loc@B
          \p@cinswid=\hsize
        \fi\fi
      \else
        \ifdiglot\ifseriesdiglot\else\MSG{HOW DID THAT HAPPEN? c@rrentcols=\the\c@rrentcols\space is surprising(incorrect) with diglot}\fi\fi
        \ifx\loc@ption\loc@TL \picw@rning{tl}{t}\let\loc@ption\loc@T
        \else\ifx\loc@ption\loc@TR \picw@rning{tr}{t}\let\loc@ption\loc@T
        \else\ifx\loc@ption\loc@BL \picw@rning{bl}{b}\let\loc@ption\loc@B
        \else\ifx\loc@ption\loc@BR \picw@rning{br}{b}\let\loc@ption\loc@B
        \fi\fi\fi\fi
      \fi
  \fi\fi
  \ifpicUsesIns
    \x@\let\x@\p@cins\csname ins-\loc@ption\endcsname
    \ifx\p@cins\relax
      \x@\let\x@\p@cins\csname \colinsert@name{\loc@ption}\endcsname
      \ifx\p@cins\relax
        \message{Unknown picture location "\loc@ption",
          expected one of t,b,tl,tr,bl,br,tL,tR,bL,bR or an inline one}%
        \ifnum\c@rrentcols>1
          \p@cinswid=\hsize
          \iffiglocleft\let\p@cins=\topleftins\figlocleftfalse \otherinsht=\ht\toprightins
          \else\let\p@cins=\toprightins\figloclefttrue \otherinsht=\ht\topleftins\fi
        \else \let\p@cins=\topins\fi
      \else
        \ifdiglot
          \x@\let\x@\tmp\csname column\l@cspec@b width\endcsname
          \ifx\tmp\relax\else
            \p@cinswid=\tmp
          \fi
        \fi
      \fi
    \fi
  \fi
  \ifdiglot\else\otherinsht=0pt \fi %Nothing to subtract if not diglot
  \iffigh@scaption
    \setc@ptionbox
    \advance\p@cheight by -\ht\c@ptionbox
  \fi
  \ifdim\p@cinswid<\p@cwidth
    \message{*** Picture \the\p@cwidth\space wide in  \the\p@cinswid\space space. \ifx\size@ption\size@SPAN Did you mean to use col, instead of span?\fi}%
  \fi
%-cfig_dofigure_2
  % create box to contain picture
%+cfig_dofigure_3
  \setf@gval{\sp@cebeside}{spacebeside}{pt}{\DefaultSpaceBeside}% absolute value
  \setf@gval{\sp@cebefore}{spacebefore}{}{0}%  in \onel@neunit
  \setf@gval{\sp@ceafter}{spaceafter}{}{0}% in \onel@neunit
  \setf@gNval{\sp@cebetween}{spacebetween}{}{0}%  in \onel@neunit
  \setf@gval{\tmp}{edgeadjust}{}{0}% in same units as margins - \IndentUnit
  \p@chshift=\tmp\IndentUnit
  \trace{g}{Figure \the\im@gecount\space size=\size@ption, scale=\sizem@ltiple, loc=\loc@ption \ifpicUsesIns, picins=\the\p@cins\fi, hsz=\the\hsize}%
  \trace{g}{Spacing: \sp@cebefore,  \sp@ceafter (\sp@cebeside)}%
  \setbox0=\vbox{%
    \pdfsavepos
    \edef\t@mp{\string \@parpicstart{\ifdiglot\dc@rref\else\c@rref\fi}{\ifcsname figparam-src\endcsname\csname figparam-src\endcsname\fi}}%
    \x@\write\x@\p@rlocs\x@{\t@mp{\the\pdflastxpos}{\the\pdflastypos}}%
    \ifpicNarrow
      \hsize=\sizem@ltiple\p@cwidth
      \p@cinswid=\hsize
    \else
      \hsize=\p@cinswid
    \fi
    \ifdim\sp@cebefore pt =0pt \else\vskip \sp@cebefore\onel@neunit\fi
    \tempfalse
    %\ifpicUsesIns\temptrue\fi
    \ifx\picl@c\loc@Inl\temptrue\fi
    \ifx\picl@c\loc@Par\temptrue\fi
    \ifx\picl@c\loc@Cut\temptrue\fi
    \ifCaptionFirst
      \setbox0\vbox{\d@caption
      \ifdim\dimexpr \FigCaptionAdjust+ \sp@cebetween\onel@neunit\relax =0pt\else
        \vskip \dimexpr \FigCaptionAdjust+\sp@cebetween\onel@neunit\relax
      \fi}%
      \dimen0=\ht0
      \ifdim\ht0<0pt
    %      \vskip0.3\baselineskip
        \kern -\ht0
      \fi
      \unvbox0
    \else
      \iftemp
        \vskip0.3\baselineskip
      \fi
    \fi
    \ifhasb@rder
      \ifdim \border@tpadding < -\b@drwidth pt  
        \kern\the\dimexpr -\border@tpadding - \b@drwidth pt\relax%
      \fi
    \fi
    % insert picture based on PicPath and file name, scaled to \p@cwidth
    \let\picfilecomm@nd=\XeTeXpicfile
    \edef\f@lename{\csname figparam-src\endcsname}%
    \edef\mirr@r{\csname figparam-mirror\endcsname}%
    \def\xtra{}\def\xtraremains{}%
    \expandafter\ch@ckpdf\f@lename..\endf@lename
    \let\picp@ge\empty
    \x@\p@rsextra{\csname figparam-x-xetex\endcsname}%See if there are any key=val parameters in the x-xetex parameter
    %what are we scaling on the image? Width or height?
    \ifnum \ifrotimage 1\else 0\fi = \ifpicTall 0 \else 1 \fi
      %If there's rotation, fit the image height to width instead of the normal way:
      \def\picdim@n{height}\def\picaltdim@n{width}%
    \else
      \def\picdim@n{width}\def\picaltdim@n{height}%Normal
    \fi
    \edef\r@qdim{\sizem@ltiple\space\the\p@cwidth}%
    \p@cwidth=\sizem@ltiple\p@cwidth%
    \ifhasb@rder
      \dimen1=\p@cwidth
      \@@sb@width@calcs
      \trace{g}{Reducing image size to \the\dimen1 \space  from \the\p@cwidth, due to border}%
      \p@cwidth=\dimen1
    \fi
    % First, try to set it at the requested dimension:
    \tempfalse
    \x@\ch@ckpath\x@{\f@lename}
    \iftemp\else\edef\f@lename{\the\PicPath\f@lename}\fi
    \setbox\newpicb@x=\hbox{%
      \xdef\p@climit{\string\@parpicsize\string{\picdim@n\string}\string{normal\string}}%
      \ins@rtpic{"\f@lename"}%
       {\picdim@n}{\the\p@cwidth}{\the\dimexpr\p@cheight\relax}{\xtra}{\xtraremains}{\picp@ge}}%
    \ifdim\ht\newpicb@x>\p@cheight
      \xdef\p@climit{\string\@parpicsize\string{\picaltdim@n\string}\string{heightlimit\string}}%
      \ins@rtpic{"\f@lename"}%
      %It doesn't fit. Scale to other dimension:
      \trace{g}{Picture too big set with \picdim@n=\r@qdim, switching to \picaltdim@n=\p@cheight}%\sizem@ltiple\space\the\p@cwidth}%
      \setbox\newpicb@x=\hbox{%
        \ins@rtpic{"\f@lename"}%
         {\picaltdim@n}{\p@cheight}{\sizem@ltiple}{\xtra}{\xtraremains}{\picp@ge}}%
    \fi
    \ifFigurePlaceholders % replace graphic with a frame and the file name
      \setbox\newpicb@x=\m@kepl@ceholder{\wd\newpicb@x}{\ht\newpicb@x}{\csname figparam-src\endcsname}%
    \fi
	\write@parpicsize
    \trace{g}{Object going into hbox \the\p@cwidth}%
    \edef\l@gstring{{\the\im@gecount}{\f@lename}{\csname figparam-pgpos\endcsname}{\csname figparam-copy\endcsname}{\picdim@n:\the\wd\newpicb@x x\the\ht\newpicb@x}}% Fully expand figure parameters, but leave page no. to be expanded later.
    \ifpicTall %Tall boxes don't get centred.
      \setbox\newpicb@x=\hbox{\x@\writefigp@gelog\x@{\l@gstring}\box\newpicb@x}%
    \else
      \setbox\newpicb@x=\hbox to \p@cwidth{\hss\x@\writefigp@gelog\x@{\l@gstring}\box\newpicb@x\hss}%
    \fi
%-cfig_dofigure_3
%+cfig_dofigure_4
    \tempfalse
    \def\pr@pic{}\def\p@stpic{}%
    \ifx\mirr@r\empty\else
      \trace{g}{Mirror: \mirr@r, \the\pageno}%
      \global\def\pr@pic{%
         \trace{g}{prepic: Mirror: \mirr@r, \the\pageno}%
         \ifx\mirr@r\val@dd\ifodd\whichp@ge\temptrue\fi\fi %Page number is frequently low by one or 2 when image is read. Needs external toc-style file.
         \ifx\mirr@r\val@ven\ifodd\whichp@ge\else\temptrue\fi\fi
         \ifx\mirr@r\valb@th\temptrue\fi
         \iftemp\trace{g}{Mirrored image requested}%
           \dimen0=\wd\newpicb@x\kern\dimen0\special{pdf:  begintransform}\special{x:scale -1 1}\fi
      }%
      \global\def\p@stpic{\iftemp\special{pdf: endtransform}\kern-\dimen0\fi
      }%
      \setbox\newpicb@x\hbox{\pr@pic\box\newpicb@x\p@stpic}%
    \fi
    %
    \x@\ifx\csname figparam-x-credit\endcsname\empty\else
        \x@\let\x@\cr@dit\x@=\csname figparam-x-credit\endcsname
        \x@\let\x@\cr@ditpos\x@=\csname figparam-x-creditpos\endcsname
        \x@\let\x@\cr@ditrot\x@=\csname figparam-x-creditrot\endcsname
        \x@\let\x@\cr@ditbox\x@=\csname figparam-x-creditbox\endcsname
        \add@credit%
    \fi
    \ifx\h@scol\tr@e
      \ifx\pdf@lpha\relax\def\pdf@lpha{1}\fi
      \setbox\newpicb@x\vbox{\feintbox{\pdf@lpha}{\pdfBGc@l}{\box\newpicb@x}}%
    \else
      \ifhasb@rder \ifdim\dp\newpicb@x < \fb@bpadding \dp\newpicb@x=\fb@bpadding\fi\fi
    \fi
    \ifhasb@rder
      \prepb@rderbox\newpicb@x 
      \headingtopspace=0pt
      \dob@rder % Actually generate the border
      \let\xtra@depth\empty
      \ifx\h@scol\tr@e \ifx\b@drbottom\tr@e \ifdim \border@bpadding < -\b@drwidth pt  
            \def\xtra@depth{-\border@bpadding - \b@drwidth pt }%
      \fi \fi \fi 
      \setbox\newpicb@x\vbox to \dimexpr \ht\b@rderbox+\dp\b@rderbox \xtra@depth\relax{\lineskiplimit=0pt \lineskip=0pt \baselineskip=0pt
          \vbox to 0pt{\vskip\b@dr@top@pad\hbox to \b@rderbox@width{\hskip\b@dr@left@pad\box\newpicb@x\hskip\b@dr@right@pad}\vss}\penalty10000\vskip\headingtopspace\vbox to 0pt{\box\b@rderbox\vss}}%
    \fi
    %Align image left/right or centre
    \ifx\picl@c\loc@InText % InTextBoxes get their natural width + spacebeside 
      \p@cinswid=\wd\newpicb@x
      \advance\p@cinswid\sp@cebeside
    \fi
    \trace{g}{Object aligned into hbox \the\p@cinswid}%
    \t@gstartfull{Figure}{fig}{width="\the\wd\newpicb@x" height="\the\ht\newpicb@x" pgpos="\csname figparam-pgpos\endcsname" size="\size@ption" loc="\loc@ption"}%
    \ifx\pic@lign\@lignRight\hbox to \p@cinswid{\hss\box\newpicb@x}%
    \else
      \ifx\pic@lign\@lignLeft \hbox to \p@cinswid{\box\newpicb@x\hss}%
      \else\hbox to \p@cinswid{\hss\box\newpicb@x\hss}\fi
    \fi
    \ifCaptionFirst\vskip 0.5\onel@neunit\else
      \setbox0\vbox{\ifdim\dimexpr \FigCaptionAdjust+ \sp@cebetween\onel@neunit\relax =0pt\else
          \vskip \dimexpr \FigCaptionAdjust+\sp@cebetween\onel@neunit\relax
        \fi
        \d@caption}\trace{g}{caption box is \the\ht0 high}%
      \dimen0=0pt\ifdim\ht0<0pt \dimen0=-\ht0\fi
      \nointerlineskip\box0%\unvbox0
      \ifdim\dimen0=0pt\else \kern\dimen0 \fi
    \fi
    \ifdim\sp@ceafter pt =0pt \else\vskip \sp@ceafter\onel@neunit\fi
    \trace{g}{Spacing: \sp@cebefore,  \sp@ceafter (\sp@cebeside)}%
    \t@gend{Figure}%
    %\pdfsavepos
  }% END of box0
  \temptrue
  \iffigf@und\else\ifSkipMissingFig
     \tempfalse
     \message{SkipMissingFigtrue: Missing figure \csname figparam-src\endcsname\space ignored.}%
  \fi\fi
  \iftemp
    \pl@cefigure
  \fi
  \let\sb@rmarker\orig@sbm
  \S@tCat{\origc@t}%
 \fi% end \ifIncludeFigures
}

\def\pl@cefigure{%Acutally place the figure
  \trace{g}{Picture height=\the\ht0, vs:\the\vsize, \the\partialLpenalty,  pg:\the\pagegoal, pt:\the\pagetotal, av:\the\availht, aligned:\csname pic@lign\endcsname}%
%-cfig_dofigure_4
%+cfig_dofigure_5
  \trace{b}{BALANCE fig: height=\the\ht0: baselineskip=\the\baselineskip}%
  % insert into proper insertion class for this position
  \ifpicUsesIns
    \trace{g}{Picture (\the\ht0,\the\dp0) goes to insert}%
    \prepwr@teparstop{0}%
    \ifdiglot
      \trace{g}{Other side: \the\otherinsht.}%
      \ifdim\ht0<\otherinsht
        \ht0=0pt
      \else
        \advance\otherinsht by -\ht0 %can't do maths on \ht0, need to calculate backwards
        \ht0=-\otherinsht
      \fi
    \fi
    \trace{g}{Picture now \the\ht0 \space into insert box \the\p@cins}%
    \ifinextended\edef\@wrap{\global\setbox\sid@barnotes=\vbox\bgroup\unvbox\sid@barnotes}\else
      \ifdoingt@ble\edef\@wrap{\global\setbox\t@blenotes=\vbox\bgroup\unvbox\t@blenotes}\else%
        \ifhe@dings\edef\@wrap{\global\setbox\he@dingnotes=\vbox\bgroup\unvbox\he@dingnotes}\else
          \let\@wrap\empty
        \fi
      \fi
    \fi%
    \write@picanchor
    \@wrap\insert\p@cins{\penalty10000 % make sure this picture does not float away to another page
      \splittopskip\z@skip
      \splitmaxdepth\maxdimen \floatingpenalty20000 % was zero
      \headingtopspace=0pt%
      \penalty10000
      \pdfsavepos\penalty10000
      \write\p@rlocs{\noexpand\@nontextstart{\the\pdflastxpos}{\the\pdflastypos}}\penalty10000%
      \gridp@ctrue\gridb@x0\gridp@cfalse% make sure we align to the page grid
      \unpenalty\setbox1=\lastbox\unvbox1\setbox1=\lastbox\vbox{\unvbox1\global\skip1=\lastskip\unskip}%
      \pdfsavepos
      \x@\write\x@\p@rlocs\x@{\t@mp{\the\pdflastxpos}{\the\pdflastypos}}%
      \write\p@rlocs{\noexpand\@nontextstop{\the\pdflastxpos}{\the\pdflastypos}}%
      \kern -\lastdepth
      \vskip\lastdepth
      \vskip\skip1
    }\ifx\@wrap\empty\else\egroup\fi
%-cfig_dofigure_5
%+cfig_dofigure_6
  \else %ifpicUsesIns
    % Calculate lines used for the picture
    \dimen0=\ht0 \advance\dimen0 by \dp0 %
    \count255=\dimen0
    \divide\count255 by \baselineskip
    \advance\count255 by 1
    \dimen2=\count255\baselineskip %space reserved...
    \trace{g}{Inline \w@tsit\space takes \the\dimen0, reserving \the\dimen2}%
    %
    \ifx\picl@c\loc@InText
      \d@figureInText 0%
    \fi
    \ifx\picl@c\loc@Inl
      \headingtopspace=0pt
      \d@figureInl 0%
    \fi
    %
    \ifx\picl@c\loc@Par
      \d@figurePar 0%
    \fi
    %
    \ifx\picl@c\loc@Page
      \d@figurePage 0%
    \fi
    \ifx\picl@c\loc@Full
      \d@figureFull 0%
    \fi
    \ifx\picl@c\loc@Cut
      \d@figureCut 0%
    \fi
    %Sanity check. If we used \box0 then it'll be empty now.
    \ifvoid0\else\message{Placement for image \the\im@gecount (at \c@rref) could not be understood. Image Lost!}\fi
  \fi %ifpicUsesIns
}


\def\@lignpic#1{%Align pic (or whatever) according to pic@lign
  \def\l@ftedge{\hss}\def\r@ghtedge{\hss}%
  \ifx\pic@lign\@lignLeft\def\l@ftedge{\kern\p@chshift}\fi
  \ifx\pic@lign\@lignRight\def\r@ghtedge{\kern\p@chshift}\fi
  \ifRTL\let\t@mp\r@ghtedge\let\r@ghtedge\l@ftedge\let\l@ftedge\t@mp\fi
  \setbox#1\vbox{\hbox to \p@cinswid{\l@ftedge\box#1\r@ghtedge}}%
}
\newif\ifInlBelow \InlBelowfalse
\newif\ifAdjustInlBelow \AdjustInlBelowfalse
\def\prepwr@teparstop#1{%
  \tempfalse
  \ifx\w@tsit\gr@phic \temptrue\def\w@tsitid{\csname figparam-src\endcsname}%
  \else\ifx\w@tsit\sb@rb@x\def\w@tsitid{\w@tsit\the\im@gecount}%
    \else\def\w@tsitid{\w@tsit\the\notim@gecount}\fi
  \fi
  \xdef\t@mp{\string\@parpicstop\string{\ifdiglot\dc@rref\else\c@rref\fi\string}\string{\w@tsitid\string}\string{\the\wd#1\string}\string{\the\ht#1\string}}%
}

\def\d@figureInText#1{%
  %\showbox #1
  %\vrule height 10pt depth 0pt width 10pt
  \leavevmode
  \pdfsavepos
  \prepwr@teparstop{#1}%
  \pdfsavepos\x@\write\x@\p@rlocs\x@{\t@mp{\the\pdflastxpos}{\the\pdflastypos}}%
  \hbox{\box #1}%
  \pdfsavepos\write\p@rlocs{\noexpand\@nontextstart{\the\pdflastxpos}{\the\pdflastypos}}%
  \write\p@rlocs{\noexpand\@nontextstop{\the\pdflastxpos}{\the\pdflastypos}}%
}
\def\d@figureInl#1{%
  \let\curmode\empty
  \ifhmode \edef\curmode{\curmode, in HMODE}\fi %Can't test for these inside a write
  \ifvmode \edef\curmode{\curmode, in VMODE}\fi
  \trace{g}{\w@tsit\space is inline, \the\hsize \curmode \ifpicNarrow, narrow\fi. Penalties: \pr@penalty,\p@stpenalty}%
  \tempfalse
  \ifpicNarrow\temptrue\else
    \iffigh@scaption\else\temptrue\fi\fi
  \iftemp
    \@lignpic{#1}%
  \fi
  %\splittopskip\baselineskip
  \prepwr@teparstop{#1}%
  \ifhmode \temptrue\fi
  \def\picc@ntents{%
    \pdfsavepos\write\p@rlocs{\noexpand\@nontextstart{\the\pdflastxpos}{\the\pdflastypos}}%
    \penalty\ifinn@te 10000\else\pr@penalty\fi\relax% Allow the page to break except in footnotes.
    \gridp@cfalse% Not true! It's not a floating fig.
    \trace{g}{Before gridbox \the\ht#1+\the\dp#1 (inn@te\ifinn@te true\else false\fi)}%
    %\lastdepth=0pt
    %\ifdim\lastdepth>0.2\onel@neunit\vskip\onel@neunit\fi%
    \gridb@x#1%
    \pdfsavepos\x@\write\x@\p@rlocs\x@{\t@mp{\the\pdflastxpos}{\the\pdflastypos}}%
    \iftemp
      \dimen9=\lastdepth \kern\dimen9
      \trace{g}{gridbox dp=\the\dimen9}%Figs have a skip at the bottom of the box, but somehow the depth is kept. Need to kill it. sidebars don't have this issue.
    \fi
    \penalty\ifinn@te 10000\else\p@stpenalty\fi\relax
    \pdfsavepos\write\p@rlocs{\noexpand\@nontextstop{\the\pdflastxpos}{\the\pdflastypos}}%
    \penalty\ifinn@te 10000\else\p@stpenalty\fi\relax
  }%
  \ifvmode \picc@ntents
  \else 
    \ifInlBelow
      \iffalse %ifAdjustInlBelow % FIXME. This needs careful logic. Can only correct for descent if there's enough space to do so!
        \strut
        \vadjust {\kern-\dp\str@tbox\picc@ntents\kern\dp\str@tbox}%
      \else
        \vadjust {\picc@ntents}%
      \fi
    \else
      \vadjust pre{\picc@ntents}%
    \fi
  \fi
}

\newif\ifearlyeotpskip
\def\d@figurePar#1{%
  \trace{g}{\w@tsit is post-paragraph, \the\hsize/\the\p@cinswid \ifpicNarrow , narrow\fi}%
  \x@\let\x@\picb@@x\csname picb@x\g@tdstat\endcsname
    %\ifx\pic@lign\@lignLeft \global\setbox\picb@@x\vbox{\hbox to \colwidth{\box\picb@@x\hss}}\trace{g}{Pic aligned left}%
    %\else \global\setbox\picb@@x\vbox{\hbox to \colwidth{\hss\box\picb@@x}}\trace{g}{Pic aligned right}%
    %\fi
    %\showbox\picb@@x
  \earlyeotpskipfalse
  \prepwr@teparstop{#1}%
  \ifvbox0 \setbox0\vbox{\unvcopy#1 \dimen0=\lastkern\ifdim\dimen0=1sp \global\earlyeotpskiptrue\fi}\fi%
  \global\setbox\picb@@x\vbox{\box\picb@@x\penalty 10
      \pdfsavepos\write\p@rlocs{\noexpand\@nontextstart{\the\pdflastxpos}{\the\pdflastypos}}%
      \gridp@ctrue% TRUE. Out of band like a floating image.
      \prevdepth=0pt
      \headingtopspace=0pt
      \tempfalse
      \ifpicNarrow\temptrue\else
        \iffigh@scaption\else \temptrue\fi\fi
      \iftemp
        \@lignpic{#1}%
      \fi
      \gridb@x#1%
      \lastdepth=0pt
      %\kern 0pt
      \ifearlyeotpskip\kern -1sp\kern 1sp\fi
      \pdfsavepos\x@\write\x@\p@rlocs\x@{\t@mp{\the\pdflastxpos}{\the\pdflastypos}}%
      \pdfsavepos\write\p@rlocs{\noexpand\@nontextstop{\the\pdflastxpos}{\the\pdflastypos}}%
    }%
  \seteotpn@me
  \trace{g}{\eotpn@me\space defined}%
  \addtoeotp{%
    \seteotpn@me
    \trace{s}{eotp: \eotpn@me. st@k:\styst@k, cref:\c@rref}%
    \relax \x@\let\x@\picb@@x\csname picb@x\g@tdstat\endcsname
    \ifhmode\edef\eotpprevdepth{0pt}\else\edef\eotpprevdepth{\the\prevdepth}%
      \prevdepth=0pt
    \fi%
    \lastdepth=0pt  % prevdepth accounted for...
    \earlyeotpskipfalse % An early skip of -prevdepth doesn't look good with figures, but keeps gridding for sidebars.
    \setbox0\vbox{\unvbox\picb@@x \dimen0=\lastkern\ifdim\dimen0=1sp \unkern\aftergroup\earlyeotpskiptrue\fi}%
    \trace{g}{Box flagged for early skip? \ifearlyeotpskip true\else false\fi}%
    \ifearlyeotpskip \vskip-\eotpprevdepth\relax\fi
    \penalty10 % Allow the page to break
    \edef\b@xdepth{\the\dp\picb@@x}%
    \unvbox0
    \dimen0=\lastkern\ifdim\dimen0=1sp \unkern\fi
    \penalty10
    \ifearlyeotpskip\else \vskip-\eotpprevdepth\relax\fi
   }%
   \def\temp{}%
   \ifnum\c@tskip>1 \count255=\c@tskip
     \loop\ifnum\count255>1
       \edef\temp{D|\temp}\advance\count255 by -1
     \repeat
   \fi
   \trace{g}{\eotpn@me Delay  set to '\temp'}%
   \x@\xdef\csname \eotpn@me Delay\endcsname{\temp}%
   \relax\relax
}
%-cfig_dofigure_6
%+cfig_dofigure_7

\def\d@figurePage#1{%
  \d@figurep@ge{#1}{page}{\textheight}{11}{0pt}%
}
\def\d@figureFull#1{%
  \d@figurep@ge{#1}{full-page}{\PaperHeight}{9}{\FullPageFudgeFactor}%
  %\showbox\wholepagepic
}

% #1 box, #2 type, #3 vertical size, #4 magic penalty, #5 fine tuning kern
\def\d@figurep@ge#1#2#3#4#5{%
  \trace{g}{\w@tsit\space is #2, \the\ht#1, \the\wd#1}%
  \dimen0=#3\advance\dimen0 by -\ht#1%
  \advance\dimen0 by -\dp#1%
  \divide\dimen0 by 2
  \ifx\picV@lign\@lignTop \trace{g}{V alignment: top}\setbox#1\vbox{\vbox to #3{\kern#5\box#1\vss}}\else
    \ifx\picV@lign\@lignBot \trace{g}{V alignment: bottom}\setbox#1\vbox{\vbox to #3{\vss\box#1}}\else
      \ifx\picV@lign\@lignCent \trace{g}{V alignment: center}\setbox#1\vbox{\vbox to #3{\vss\box#1\vss}}\else
        \trace{g}{V alignment: none}\setbox#1\vbox{\vskip 0pt plus \the\dimen0 \penalty10000\box#1\penalty10000\vskip 0pt plus \dimen0}%
    \fi\fi\fi
  \prepwr@teparstop{#1}%
  \tempfalse
  \trace{g}{pagetotal=\the\pagetotal}%
  \ifhmode\temptrue\else
    \ifdim\pagetotal=0pt\else\temptrue\fi
  \fi
  \global\setbox\wholepagepic\vbox{\unvbox\wholepagepic
    \write\p@rlocs{\noexpand\@nontextstart{\the\pdflastxpos}{\the\pdflastypos}}%
    \unvbox#1
    \pdfsavepos\x@\write\x@\p@rlocs\x@{\t@mp{\the\pdflastxpos}{\the\pdflastypos}}%
    \pdfsavepos\write\p@rlocs{\noexpand\@nontextstop{\the\pdflastxpos}{\the\pdflastypos}}%
    \kern#4 sp\penalty 1}% magic number
  \iftemp\else
    %\def\pagecontents{\vss\box#1\vss}\plainoutput
    \ifh@ldfig
      \h@ldfigfalse
    \else
      \trace{g}{Can proceess immediately}%
      \dofigp@ge
    \fi
  \fi
}
\newif\ifh@ldfig


\def\DefaultSpaceBeside{10pt}
\def\c@tskipparse#1.#2.#3\E{%
  \def\t@mp{#2}\ifx\t@mp\empty
    \gdef\c@tskipfrac{#1}%
    \xdef\c@tskip{#1}%
  \else
    \xdef\c@tskipfrac{#1.#2}%
    \def\t@mp{#1}\ifx\t@mp\empty\def\t@mp{0}\else\ifx\t@mp\h@phen\def\t@mp{0}\fi\fi
    \ifnum #2 < 5
      \xdef\c@tskip{\t@mp}%
    \else
      \ifnum \t@mp<0
        \xdef\c@tskip{\the\numexpr \t@mp  -1\relax}%
      \else
        \xdef\c@tskip{\the\numexpr \t@mp  +1\relax}%
      \fi
    \fi
  \fi
  \trace{g}{cut skip is \c@tskip (\c@tskipfrac)}%
}
\def\p@rskipparse#1.#2.#3\E{%
  \trace{g}{paragraph skip is #1}%
  \xdef\c@tskip{#1}\edef\t@mp{#2}\ifx\t@mp\empty
  \else
    \MSG{Fractional part (.#2) of paragraph skip meaningless and ignored for \ifx\w@tsit\gr@phic\csname figparam-src\endcsname\fi (\w@tsit\space\the\im@gecount), at \c@rref}%
  \fi
}
\newif\ifimmediatefigure \immediatefigurefalse
\def\d@figureCut#1{% Expects: count255=number of lines gap, \c@tskip=delay
  \mkstr@t
  \dimen0=\ht#1%
  \ifx\w@tsit\gr@phic
   \edef\dr@pthingid{droppic\the\im@gecount}%
  \else
   \global\advance\notim@gecount by 1
   \edef\dr@pthingid{drop\w@tsit\the\notim@gecount}%
   \x@\ifx\csname thisw@tsitslop\endcsname\relax\else
     \@@getCutoutSlop{\dr@pthingid}%
     \ifx\r@iselimit\relax
       \x@\setCutoutSlop\x@{\x@\dr@pthingid\x@}\thisw@tsitslop
     \fi
     \let\thisw@tsitslop\relax
   \fi
  \fi
  \trace{g}{\w@tsit\space\dr@pthingid\space is in a cutout. \the\count255 x \the\baselineskip.}%
  %\setbox#1=\hbox{\vrule height\dimen0\kern 0.5pt\box#1}%TESTING.
  \dimen1=-\baselineskip %where does the picture go? Starting point is the lowest point of the current line(i.e. this includes descenders, but we'll deal with that via the strutb@x)
  \advance\dimen1 by -\dp\str@tbox
  \ifhmode
     \trace{g}{Cutout in horizontal mode. ref:\ifdiglot\dc@rref\else\c@rref\fi}%
     \ifx\prev@rsemode\empty
       \trace{g}{we were in horizontal mode even before the verse number.}%
     %  \dimen1=0pt
     \else
       \trace{g}{Before this verse was started it was in vertical mode (\prev@rsemode).}%
       \setCutoutSlop{\dr@pthingid}{0}{0}%
        %\ifdim\lastdepth>0pt
          %\advance\dimen1 by -\lastdepth
        %\fi
     \fi
     %\csname\m@rker\endcsname
  \else
     \trace{g}{Cutout for \dr@pthingid\space was in vertical mode. Setting slop to 0}%
     \setCutoutSlop{\dr@pthingid}{0}{0}%
     \ifimmediatefigure\else 
        \leavevmode %needed for keyterm-based figures, at least
     \fi
     \tmpcount=0
  \fi
  %\advance\dimen1 by \baselineskip
  \advance\dimen1 by \c@tskipfrac\baselineskip
  \dimen2=\wd#1\advance\dimen2 by \sp@cebeside\relax
  \advance\dimen2 by \p@chshift
  \dimen3=\hs@ze \advance\dimen3 by -\dimen2
  \ifdim\dimen3<5em\message{** \w@tsit specification of \csname size@ption\endcsname \csname sizem@ltiple\endcsname (at \ch@pter:\v@rse) leaves \the\dimen3 \space for text. That's probably not enough.}\fi
  \raise@test{\dr@pthingid}%
  \ifx\t@str@ise\relax\else
    \advance\dimen1 by -\t@str@ise\baselineskip
  \fi
  \ifimmediatefigure
    \advance\dimen1 by \ht#1
  \else
    \advance\dimen1 by \count255\baselineskip
  \fi
  \setbox#1\vbox to 0pt{\kern\dimen1\vbox to 0pt{\vss\box#1}\vss}%
  \advance\tmpcount by \c@tskip\relax
  \ifx\l@cspec\@lignLeft
    \let\c@tcmd\leftcutout
    \edef\thing@side{L}%
    \setbox#1\hbox to \hsize{\ifdim \p@chshift=0pt\else\kern\p@chshift\fi\box#1\hss}%
  \else
    \ifx\l@cspec\@lignRight
      \let\c@tcmd\rightcutout
      \edef\thing@side{R}%
      \setbox#1\hbox to \hsize{\hss\box#1\ifdim \p@chshift=0pt\else\kern\p@chshift\fi}%
    \else
      \message{!! Unknown cutout position \l@cspec, picture misplaced}%
      \let\c@tcmd\rightcutout
      \edef\thing@side{R}%
      \setbox#1\hbox to \hsize{\hss\box#1\hss}%
    \fi
  \fi
  \ifimmediatefigure\pl@cecutoutfigvmode{#1}{0}\prevdepth=-1000pt\leavevmode\fi
  \delay@test{\dr@pthingid}%
  \ifx\t@std@lay\relax \MSG{** Cutout for picture \the\im@gecount, (\ifdiglot\dc@rref\else\c@rref\fi) re-run to generate \string\DelayedItem\space setting}%
  \else\MSG{* Cutout for picture \the\im@gecount\space at \ifdiglot\dc@rref\else\c@rref\fi, delay is \t@std@lay}\fi
  %
  \ifx\t@std@lay\relax
    \tmpcount=0
  \else
    \tmpcount=\t@std@lay
  \fi
  %\ifhmode 2|\fi
  \write@delayedthing{\dr@pthingid}{\the\tmpcount}{\the\dimen2}{\the\count255}{\c@tskip}{\thing@side}%
  \ifx\t@std@lay\relax
    \MSG{** Image in cutout at \ifdiglot\dc@rref\else\c@rref\fi, re-run to generate \string\DelayedItem\space settings}%
  \else\fi
  \add@pending{\dr@pthingid}{\ifdiglot\dc@rref\else\c@rref\fi}{0}{\the\dimen2}{\the\count255}{\the\tmpcount}{\thing@side}%
  \ifx\gr@phic\w@tsit
    \leavevmode\str@t\vadjust {\vbox to 0pt{%
      \pdfsavepos\write\p@rlocs{\noexpand\@nontextstart{\the\pdflastxpos}{\the\pdflastypos}}%
      \box#1\vss
      \pdfsavepos\write\p@rlocs{\noexpand\@nontextstop{\the\pdflastxpos}{\the\pdflastypos}}%
      }}%
  \else
    \ifhmode \vadjust{\vbox to 0pt{\box#1\vss}\penalty10021}%
    \else
      \ifimmediatefigure\else\pl@cecutoutfigvmode{#1}{-1}\fi%
    \fi
  \fi
  \run@pending
    %\setbox#1\hbox to \hsize{\box#1\hss}%
    %\trace{g}{leftcutout \the\dimen2, \c@tskip, \the\count255}%
    %\leftcutout{\the\dimen2}{\the\coun254}{\the\count255}%
  %\else\ifx\l@cspec\@lignRight
      %\leavevmode\str@t\vadjust {\vbox to 0pt{\box#1\vss}}%
     %% \strut\vadjust pre{\box#1}%
      %\trace{g}{rightcutout \the\dimen2, \c@tskip, \the\count255}%\
  %\fi
}
\def\pl@cecutoutfigvmode#1#2{%
       % \vrule height 0pt depth 1pt width 10ex\kern-1pt
        \vbox to 0pt{
          \vskip #2\baselineskip
          \pdfsavepos\write\p@rlocs{\noexpand\@nontextstart{\the\pdflastxpos}{\the\pdflastypos}}%
          \box#1\vss
          \pdfsavepos\write\p@rlocs{\noexpand\@nontextstop{\the\pdflastxpos}{\the\pdflastypos}}%
          }%
}

\def\MarginNoteSide{outer}
\def\d@figureMargin#1{%Stick the figure in the margin
  \dimen0 = \dimexpr \sp@cebeside + \marginnotesgap
  \getsbp@ram{baseline} \dimen1=0pt %\ifx\cp@ram\relax -\baselineskip\else -\cp@ram\fi
  \advance\dimen1 -\dp\pstr@t
  \lastdepth=\prevdepth
  %\kern-\baselineskip
  \setbox#1=\vtop{\unvbox#1}
  \trace{e}{Margin figure x=\the\dimen0, y=\the\dimen1, ht=\the\ht#1+\the\dp#1*\the\wd#1, lastdepth=\the\lastdepth}%
  \d@marginnote{#1}{\c@rref}{\sb@rmarker}{\MarginNoteSide}{inline}{\the\dimen0}{\the\dimen1}%
  \prevdepth=\lastdepth
  \trace{e}{prevdepth=\the\lastdepth}%
}

%-cfig_dofigure_7

\newtoks\PicPath % directory containing picture files
\newif\ifIncludeFigures \IncludeFigurestrue
\newif\ifFigurePlaceholders
\newif\ifCaptionRefFirst % Does the reference come before or after the caption text?
\CaptionRefFirstfalse
\newif\ifCaptionFirst % Does the caption come before the image or after?
\CaptionFirstfalse
\def\FullPageFudgeFactor{0pt} % How much does a full page top-aligned picture miss the top of the page by?
%+cfig_checkpdf
\def\ch@ckpdf#1.#2.#3\endf@lename{\lowercase{\edef\@xt{#2}}%
  \ifx\@xt\@pdf \let\picfilecomm@nd\XeTeXpdffile \fi}
%-cfig_checkpdf

%+cfig_declare
\def\picw@rning#1#2{\msg{converted picture placement "#1" to "#2" in single-column layout}}
\x@\let\csname \gr@phic @warning\endcsname\picw@rning

\def\alias@inserts{%
  \x@\let\csname ins-\loc@TL\endcsname\topleftins
  \x@\let\csname ins-\loc@TR\endcsname\toprightins
  \x@\let\csname ins-\loc@BL\endcsname\bottomleftins
  \x@\let\csname ins-\loc@BR\endcsname\bottomrightins
  \x@\let\csname ins-\loc@T\endcsname\topins
  \x@\let\csname ins-\loc@B\endcsname\bottomins
  \x@\let\csname ins-\loc@VB\endcsname\verybottomins
}
\alias@inserts
\newbox\newpicb@x
\newbox\picb@x % Delayed picture
\newbox\picb@xR % (diglot, right-hand) delayed picture.
\newbox\wholepagepic
\newcount\p@ramnumber
\newcount\notim@gecount \notim@gecount=0 % non-images are counted separately to images.
\newdimen\p@cinswid
\newdimen\p@cwidth
\newdimen\p@cheight
\newdimen\p@chshift % Shift pic relative to an edge.
\newdimen\otherinsht % In a diglot, an insert doesn't affect availht if it's smaller

\newif\ifmorep@rams
\newif\ifpicp@gefile \picp@gefilefalse
\newread\picl@ctest
\newwrite\picp@ges
%-cfig_declare

%+cfig_openpicpages
\def\inputpicp@ges "#1"{%read picpages file.
    \openin\picl@ctest="#1" % test to see if the file exists before reading it.
    \ifeof\picl@ctest \let\n@xt=\relax
    \else \def\n@xt{\input "#1"}%
    \fi
    \closein\picl@ctest
    \n@xt
}

\def\openpicpages "#1"{%set up a .picpages file, and check for changes at the end of the run.
  \ifpicp@gefile\else
    \trace{g}{openpicpages "#1"}%
    \inputpicp@ges "#1"
    \picp@gefiletrue
    \addtoendhooks{\finishpicp@ges "#1"}%
    \immediate\openout\picp@ges="#1" % test to see if the file exists
  \fi
}
\def\l@stfignum{0}
\def\finishpicp@ges "#1"{\immediate\closeout\picp@ges % close the picpages file, then re-read it and check for changes
   \trace{g}{finishpicp@ges}%
   \tempfalse
   \trace{g}{lastfignum was \l@stfignum, count now:\the\im@gecount}%
   \ifnum\im@gecount=\l@stfignum\else
     \temptrue
     \trace{g}{Number of images has changed}%
   \fi
   \let\figonpage=\checkfigpage
   \let\labelonpage=\checklabelpage
   \inputpicp@ges "#1"
   \iftemp\message{}\message{*** Figures have changed. It may be necessary to re-run the job}\fi%
}

\def\writefigp@gelog#1{%
  \write\picp@ges{\string\figonpage{\the\pageno}#1}%
  \x@\ifx\csname tr@cemode-gI\endcsname\y@s\immediate\write-1{Figure: #1}\fi
}

%: `\figonpage` gets written to the picpages auxiliary file at insert use.
% #1 ~ Page number
% #2 ~ Figure number
% #3 ~ File name
% #4 ~ pgpos parameter
% #5 ~ Copyright info from \fig line
% #6 ~ Anything else that might affect page breaking or alignment (e.g. size, rotation)
\def\figonpage#1#2#3#4#5#6{\x@\gdef\csname fig#2p@ge\endcsname{#1}%Page number
\x@\gdef\csname fig#2p@ram\endcsname{#3#4#6}% Any other parameters that might affect page-breaking.
  \ifnum\l@stfignum>#2 \else
    \xdef\l@stfignum{#2}%
  \fi
%\trace{P}{Picture "#3" turned up on page #1}%
}%
\def\checkfigpage#1#2#3#4#5#6{%
  \edef\ch@ck{#3#4#6}%
  \trace{g}{Comparing "\ch@ck" with "\csname fig#2p@ram\endcsname"}%
  \x@\ifx\csname fig#2p@ram\endcsname\ch@ck\else\trace{g}{Figure #2 parameters changed}%
   %\temptrue %Probably don't matter on their own, but could change pagination. Significant pagination changes should be caught by other tests.
  \fi
  \edef\ch@ck{#1}%
  \x@\ifx\csname fig#2p@ge\endcsname\ch@ck\else\trace{g}{Figure #2 page changed from \ch@ck \space to \csname fig#2p@ge\endcsname}\temptrue\fi
  \x@\let\x@\ch@ck\csname fig#2occurrences\endcsname
  \ifx\ch@ck\relax\x@\edef\csname fig#2occurrences\endcsname{#1}\else
    \message{*** Figure #2 on page #1, but previously seen on \ch@ck. Work-around is to move the anchor to a different verse or alter the size/placement.}%
    \x@\edef\csname fig#2occurrences\endcsname{\ch@ck, #1}%
  \fi
}
%-cfig_openpicpages
%
%+cfig_dofigpage
\def\dofigp@ge{%
  \ifvoid\wholepagepic\else
    \trace{g}{wholepagepic is \the\ht\wholepagepic high}%
    %\tracingassigns=1
    \savingvdiscards=1
    %\nonstopmode\showbox\wholepagepic
    \setbox2=\copy\wholepagepic
    \setbox0=\vsplit\wholepagepic to \PaperHeight
    \tmpcountB=\badness
    \tempfalse
    \ifnum\tmpcountB>200 % Overstretch or understretch
      \temptrue
    \fi
    \setbox3=\vbox{\splitdiscards}%
    \setbox1=\vbox{\unvcopy3\unpenalty\unskip\unpenalty\global\tmpcount=\lastkern}%
    \global\setbox\wholepagepic=\vbox{\unvbox\wholepagepic}%
    \trace{g}{After split (\the\tmpcountB)  wholepagepic \the\ht\wholepagepic+\the\dp\wholepagepic}%
    \ifdim\ht\wholepagepic>0pt
      %\showbox3 \showbox\wholepagepic
      \global\setbox\wholepagepic=\vbox{\unvcopy1\unvbox\wholepagepic}%
    \else
      \global\setbox\wholepagepic\box\voidb@x
    \fi
    %\showboxdepth=99
    %\showboxbreadth=99
    %\showbox\wholepagepic
    %\showbox1
    %\showbox0
    \setbox0=\vbox{\unvbox 0\unpenalty\global\tmpcountB=\lastkern}% MUST do this unconditionally
    \trace{g}{lp: box0 is \the\ht0\space high, penalty:\the\tmpcount, \the\tmpcountB, th:\the\textheight, ph:\the\PaperHeight}%
    \ifnum\tmpcountB=0\else\tmpcount=\tmpcountB\fi % Because if processing in a box gets surprising.
    %\showbox0
    \ifdim\ht0>0pt
      \ifnum\tmpcount=11% expected values: 11 (normal-sized page)
        \def\pagecontents{%
          \trace{g}{Topins=\the\ht\topins, Bottomins=\the\ht\bottomins, tlins=\the\ht\topleftins, blins=\the\ht\bottomleftins, trins=\the\ht\toprightins, brins=\the\ht\bottomrightins, hoffset=\the\hoffset, voffset=\the\voffset}%
          \vbox to \textheight{\par\unvbox0}%
          }%
        \plainoutput
      \else% Full page, past margins (9) or 0
        \dimen8=\pdfpagewidth \dimen9=\pdfpageheight
        %\showbox 0
        \trace{g}{Topins=\the\ht\topins, Bottomins=\the\ht\bottomins, tlins=\the\ht\topleftins, blins=\the\ht\bottomleftins, trins=\the\ht\toprightins, brins=\the\ht\bottomrightins, hoffset=\the\hoffset, voffset=\the\voffset, PaperHeight=\the\PaperHeight, pdfpageheight=\the\pdfpageheight}%
        \setbox0\vbox to \PaperHeight{\unvbox0}%
        \trace{g}{Box prepared (\the\ht0+\the\dp0)x\the\wd0}%
        \shipcompletep@gewithcr@pmarks{\box0}
        \pdfpagewidth=\dimen8 \pdfpageheight=\dimen9
        \ifholdpageno\else\advancepageno\fi
      \fi
    \fi
  \fi
  %\tracingassigns=0
  \let\n@xt\relax
  \ifdim\ht\wholepagepic>0pt
    \let\n@xt\dofigp@ge
  \fi
  \n@xt
}
\newtoks\onship@ut
\def\addtonextshipout#1{\x@\global\x@\onship@ut\x@{\the\onship@ut #1}}
\def\nextshipout{\x@\toks0\x@{\the\onship@ut}\global\onship@ut{}\the\toks0\dofigp@ge}
%-cfig_dofigpage

