% \iffalse meta-comment
%
% Copyright (C) 2008 by Richard Zach <rzach@ucalgary.ca>
% -------------------------------------------------------
% 
% This file may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either version 1.2
% of this license or (at your option) any later version.
% The latest version of this license is in:
%
%    http://www.latex-project.org/lppl.txt
%
% and version 1.2 or later is part of all distributions of LaTeX 
% version 1999/12/01 or later.
%
% \fi
%
% \iffalse
%<*driver>
\ProvidesFile{facingpages.sty}
%</driver>
%<package>\NeedsTeXFormat{LaTeX2e}
%<package>\ProvidesPackage{facingpages}
%<*package>
    [2008/06/06 0.93 Facing recto and verso pages]
%</package>
%
%<*driver>
\documentclass{ltxdoc}
\usepackage{facingpages}
\EnableCrossrefs         
\CodelineIndex
\RecordChanges
\begin{document}
  \DocInput{facingpages.dtx}
  \PrintChanges
  \PrintIndex
\end{document}
%</driver>
% \fi
%
% \CheckSum{0}
%
% \CharacterTable
%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%   Digits        \0\1\2\3\4\5\6\7\8\9
%   Exclamation   \!     Double quote  \"     Hash (number) \#
%   Dollar        \$     Percent       \%     Ampersand     \&
%   Acute accent  \'     Left paren    \(     Right paren   \)
%   Asterisk      \*     Plus          \+     Comma         \,
%   Minus         \-     Point         \.     Solidus       \/
%   Colon         \:     Semicolon     \;     Less than     \<
%   Equals        \=     Greater than  \>     Question mark \?
%   Commercial at \@     Left bracket  \[     Backslash     \\
%   Right bracket \]     Circumflex    \^     Underscore    \_
%   Grave accent  \`     Left brace    \{     Vertical bar  \|
%   Right brace   \}     Tilde         \~}
%
%
% \changes{v0.9}{2008/02/06}{Initial beta version}
% \changes{v0.91}{2008/02/11}{Added code for sync points}
% \changes{v0.92}{2008/06/07}{Added code for making counters work
%   accross facing pages segments}
%
% \GetFileInfo{facingpages.sty}
%
% \DoNotIndex{\newcommand,\newenvironment}
% 
%
% \title{The \textsf{facingpages} package\thanks{This document
%   corresponds to \textsf{facingpages}~\fileversion, dated \filedate.}}
% \author{Richard Zach \\ \texttt{rzach@ucalgary.ca}}
%
% \maketitle
%
% \section{Introduction}
%
% The |facingpages| packe provides functionality for setting text on
% facing pages, i.e., set some body of text on the verso pages, and a
% differnt segment of text on the recto pages.  The typical use for this
% is to set text in two different languages on facing pages, e.g., when
% typesetting a bilingual edition of a text.  This task is accomplished
% by first typesetting all the even (verso) pages, and then typesetting
% all the odd (recto) pages. This results in an output file which first
% contains all the even pages, with page numbers incremented by two, and
% then all the odd pages.  Parts of the file containing text on facing
% pages may alternate with text typeset in the standard way.
%
% The resulting file must then be interleaved, i.e., the sheets
% rearranged so that the even and odd pages again alternate.  This can
% be done by hand, or with the |psselect| command provided by the
% |PSUtils| package. The provided |bash| shell script
% |makefacingpages| does this automatically, using information written
% during the \LaTeX{} run to the file \meta{jobname}|.pps|.
%
% Functionality for setting text on facing pages is also provided by
% the |ledpar| and |parallel| packages.  (|ledpar| is part of Peter
% Wilson's |ledmac| package; |parallel| was written by Matthias
% Eckermann). Using these packages, however, has some drawbacks which
% may make them unsuitable.  Both |ledpar| and |parallel| require the
% text to be reproduced on facing pages to already be interleaved in
% the source file, i.e., you need to have a paragraph of the verso
% text, followed by a paragraph of the recto text, etc.  Hence, this
% is only really useful if the verso and recto texts are already in
% their final form, and the two texts can then no longer be used
% separately.  |ledpar| provides a lot of additional functionality
% that may not be needed or conflicts with other packages that may
% need to be used, e.g., the |ednote| package.  |parallel| (and, I
% think, |ledmac|) also cannot handle text on facing pages that
% contains floats or displayed formulas, nor can they deal with things
% like |marginnote|s.
%
% The drawback of |facingpages| is that it does not automatically
% align the verso and recto text, this must be done by hand.  Also, it
% can't do some thing |ledpar| can do, e.g., set footnotes across
% facing pages.  So for instance, you can't have footnotes to the
% texts on their respective pages, but editorial footnotes spill from
% a verso to a recto page.  However, |\MakeFPCounter| will turn any
% counter into one that is numbered consecutively across facing pages.
%
% |facingpages| also provides some functionality for aligning the left
% and right sides of text set on facing pages. This is done by the
% ability to set sync points in the text. A sync point is a place that
% you want to line up on the left and right page.  To set a sync
% point, put an |\SP| in the appropriate place in both the left and
% the right part of a segment (usually the beginning of a paragraph).
% After a few runs of \LaTeX, a marginal note will inform you of the
% difference in vertical position of the sync points, in |pt|.  If the
% boolean |SPadjust| is set to |true|, |\SP| will automatically add
% this amount of vertical space to make the points line up visually on
% the page.  An optional argument allows you to do add (or subtract)
% space by hand.  Once you're happy with the way the pages look, you
% can replace all the |\SP|\oarg{vspace} with |\vspace|\oarg{vspace},
% and text on facing pages should line up.
%
% One problem that arises with facing pages as they're done with
% |facingpages| is with counters, such as footnote counters. Since the
% left part of a segment is typeset first, and then the right side,
% footnotes in the left part and right part are numbered
% indepenedently, i.e., footnotes in the right are numbered after all
% the footnotes in the left part (or, if footnotes are reset at the
% beginning of segments, e.g., by a |\chapter| command, they are
% numbered independently.  If you want footnotes to be numbered
% continuously across facing pages (i.e., footnotes on p.~2 numbered
% after those on p.~1 but before those on p.~3), say
% |\MakeFPCounter{footnotes}|.
%
% \section{Interactions}
%
% Facingpages needs the |sheetsequence| counter provided by
% |memoir.cls|, so it probably only works with |memoir.cls|.
%
% If you switch to facingpages mode right before a new chapter,
% be careful to define |\clearforchapter| so that it does not
% move to a recto.  The default in |memoir| is |openright|,
% so use the option |openany|.
%  
%
% \section{Usage}
%
% \DescribeMacro{\BeginFacingPagesLeft} |\BeginFacingPagesLeft| starts
% the left (verso) part of a segment of text on facing pages. If it is
% called on a verso page, a blank page is inserted to make sure the
% facing pagest start on a verso page.
%
% \DescribeMacro{\BeginFacingPagesRight} |\BeginFacingPagesRight| starts
% the right (recto) part of a segment of text on facing pages. It pads the
% currently concluded left part with pages if the following right
% segment contains more pages.
%
% \DescribeMacro{\EndFacingPages} |\EndFacingPages| ends the
% the right (recto) part of a segment of text on facing pages. It pads the
% currently concluded right part with pages if the preceding left
% segment contains more pages.
%
% Running a file using |facingpages.sty| through latex produces a file
% \meta{jobname}|.pps|, which is used by the |makepagesface| script.
% Calling |makepagesface| \meta{jobname} takes \meta{jobname}|.dvi| and
% rearranges the sheets in it according to the data in
% \meta{jobname}|.pps|, using the |psselect| command from the
% |PSUtils| package, and then converts it to PDF format (using
% |ps2pdf|, resulting in \meta{jobname}|.pdf|.
%
% \DescribeMacro{\SP} |\SP|\oarg{vspace} sets a syncpoint.  Sync points are
% numbered consecutively from the beginning of a facing pages segment.
% |\SP| saves the vertical position of the point on the page and the
% sheet offset from the beginning of the segment.  These saved
% positions are read from the auxfile at every run.  If a sync point
% ends up on the same page in both the left and the right segment, a
% marginal note indicates the difference (in |pt|) of the vertical
% position of the sync point on the left and the right.  If
% |SP@adjust| is set to |true|, |\SP| adds the appropriate amount of
% vertical space.  This makes the text line up on the left and right
% sides.  If the sync points lie on different pages (counted from the
% beginning of the segment, i.e., they aren't on facing pages at all), only
% the page difference is shown in the marginal note, and no space is
% added.  The optional argument \oarg{vspace} lets you manually add
% space before the syncpoint is set. The idea is to set syncpoints at
% the beginning of two paragraphs you want to line up on facing pages.
% The output will tell you how far apart they are. Then add this amount
% of vertical space as the optional argument to the sync point where
% the difference is positive.  After the next \LaTeX{} run, the
% difference should be close to~0.
%
% \DescribeMacro{\cutpagehere}\DescribeMacro{\cutpageline} Starting a
% new page without ending a paragraph can be done using |\cutpagehere|
% and |\cutpageline|, which clear the page without ending the
% line---the former by filling the line with space, the latter by
% continuing the line to where it would end normally.
%
% \DescribeMacro{\MakeFPCounter} To set up a counter to be incremented
% continuously across facing pages, say
% |\MakeFPCounter|\marg{counter}.  For instance, you might want
% footnotes numbered continuously and not independently on the left
% and right pages, so a footnote on page 3 should be numbered after a
% footnote on page 2 but before one on page 4.  It requires a few runs
% to get the numbering right, for a couple of reasons.  One is that
% when processing facing pages segments, we typeset the even pages
% first, so when we output a footnote on page 4, any footnotes on page
% 3 have not been processed yet.  And when we process footnotes on the
% odd pages, all the footnotes on the even pages have been processed.
% So if there are 5 footnotes on the even pages, the footnote counter
% on p.~3 will be 5, but it should only be 1 (if there's one footnote
% on p.~2).  We deal with this by remembering what the last footnote
% is on any page, and saving this information to the |aux| file.  On
% the next run, we can then reset the counter on any page by searching
% for the last page on which footnotes appeared, and using the saved
% reset value.  The second reason this might require a few passes is
% that at the time a footnote counter is incremented, the number of
% the page it end ends up on is not set---for instance, if a footnote
% appears toward the end of a page, \LaTeX{} might decide to push it
% to the next page, but at the time it is typeset, the |page| counter
% still has the value of the preceding page.  To get around this, we
% employ the mechanisms of David Kastrup's |perpage| package (part of the
% |bigfoot| bundle).  
% \StopEventually{}
%
% \section{Implementation}
%
% \subsection{Setup}
%    \begin{macrocode}
\RequirePackage{ifthen}
\@ifundefined{thesheetsequence}{\PackageError{facingpages}{%
    \protect\thesheetsequence\space is undefined. Probably you're not
    using memoir.cls?}{}}
\@ifundefined{pdfsavepos}{\PackageWarning{facingpages}{%
    \protect\pdfsavepos\space is undefined. Sync points won't work.}}
%    \end{macrocode}
% Macros for saving and restoring data
%    \begin{macrocode}
\newboolean{RegEmpty}
\def\SaveReg#1#2#3{%
\expandafter\xdef\csname REG@#1@#2\endcsname{#3}}
\def\cSaveReg#1#2#3{\SaveReg{#1}{\number\value{#2}}{#3}}
\def\IfRegEmpty#1#2#3#4{%
  \@ifundefined{REG@#1@#2}{#3}{#4}}
\def\RegValue#1#2{\expandafter\csname REG@#1@#2\endcsname}
\def\cRegValue#1#2{\RegValue{#1}{\number\value{#2}}}
\def\RestoreReg#1#2{%
\@ifundefined{REG@#1@#2}{%
  \setboolean{RegEmpty}{true}}{%
  \setboolean{RegEmpty}{false}}
\xdef\RegContent{\csname REG@#1@#2\endcsname}}
\def\cRestoreReg#1#2{\RestoreReg{#1}{\number\value{#2}}}
%    \end{macrocode}
% \subsection{Line Up Facing Pages}
% 
% Flags to keep track of whether we're doing facing right now or not,
% whether we're in the left or right part, and if the pages have
% changed from the last run (so we output a warning).
%    \begin{macrocode}
\newboolean{FP@On}
\setboolean{FP@On}{false}
\newboolean{FP@Left}
\setboolean{FP@Left}{false}
\newboolean{FP@ChangedWarn}
%    \end{macrocode}
% Counters for start, end, and length of the current segment
% in sheet numbers and page numbers
%    \begin{macrocode}
\newcounter{FP@Seg}
\newcounter{FP@current@LStart}
\newcounter{FP@current@RStart}
\newcounter{FP@current@LEnd}
\newcounter{FP@current@REnd}
\newcounter{FP@current@REndSaved}
\newcounter{FP@current@LLength}
\newcounter{FP@current@RLength}
\newcounter{FP@current@LPageCount}
\newcounter{FP@current@LPageStart}
\setcounter{FP@Seg}{1}
\setcounter{FP@current@LStart}{1}
\newcommand{\FP@Comma}{=}
%    \end{macrocode}
% Change page numbering to double counting, copied from Dirk Schlimm's
% |fullcircle.sty| with slight change. First, we
% save the \@outputpage macro
%    \begin{macrocode}
\let\mytempoutputpage\@outputpage
% RZ - first set to incrementpage by one, so we don't have to worry about
% what happens when incrementpagebytwo is called more than once in succession
\def\incrementpagebytwo{\incrementpagebyone\g@addto@macro\@outputpage{\stepcounter{page}}}
% Reset page numbering 
\def\incrementpagebyone{\let\@outputpage\mytempoutputpage}
% Restore the saved lengths of right parts of segments from aux file
%\def\FP@RestoreLength#1#2{\FP@RLengthSaved(#1)={#2}}
\def\FP@RestoreLength#1#2{\SaveReg{FP@RLengthSaved}{#1}{#2}}
% FP@ProcessSeg -- we're done with a segment and are going to write
% the page ranges to the pss file
\newcommand{\FP@ProcessSeg}{%
  \ifthenelse{\boolean{FP@On}}{%
% we're finishing an facingpages segment
  \whiledo{\not \value{FP@current@LEnd} < \value{FP@current@LStart}}{%
    \immediate\write\@psselect{\arabic{FP@current@LStart},\arabic{FP@current@RStart}\FP@Comma}
    \stepcounter{FP@current@LStart}
    \stepcounter{FP@current@RStart}}}{%
% we're finishing a non-facingpages segment
  \ifthenelse{\value{FP@current@LStart} = \value{FP@current@REnd}}{%
    \immediate\write\@psselect{\arabic{FP@current@LStart}\FP@Comma}}{%
    \immediate\write\@psselect{\arabic{FP@current@LStart}-\arabic{FP@current@REnd}\FP@Comma}}}}
%    \end{macrocode}
% \begin{macro}{\FP@FinishUpRight}
% End a right segment.    
%  
%    \begin{macrocode}
\def\FP@FinishUpRight{%
% calculate actual length of right part of segment
\setcounter{FP@current@RLength}{\value{sheetsequence}}
\addtocounter{FP@current@RLength}{-\value{FP@current@RStart}}
% Write the length to the aux file
% test if the counter is defined
\cRestoreReg{FP@RLengthSaved}{FP@Seg}
\ifthenelse{\boolean{RegEmpty}}{%
% case 1: the counter is undefined
  \setboolean{FP@ChangedWarn}{true}
  \typeout{Length of segment \arabic{FP@Seg} not yet saved.}
}{%
% case 2: the counter is defined
\typeout{Segment \arabic{FP@Seg} length was: \RegContent\space
  current: \arabic{FP@current@RLength}.}
% test if the length has changed
  \ifthenelse{\equal{\RegContent}{\theFP@current@RLength}}{}{%
% it has! -- warn later
    \setboolean{FP@ChangedWarn}{true}
    \typeout{Length of segment \arabic{FP@Seg} has changed!}}}
% write to auxfile
\immediate\write\@auxout{%
\string\FP@RestoreLength{\theFP@Seg}{\theFP@current@RLength}
}
% if we're finishing a right facingpages segment, pad with empty pages
% if necessary
\whiledo{\value{FP@current@RLength} < \value{FP@current@LLength}}{%
  \message{Padding right segment with one page.}
  \newpage
  \phantom{*}
  \stepcounter{FP@current@RLength}}}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\BeginFacingPagesLeft}
% Start a new left segment. 
%  
%    \begin{macrocode}
\newcommand{\BeginFacingPagesLeft}{%
  \message{\string\BeginFacingPagesLeft\space called on sheet \thesheetsequence, page \thepage.}
  \ifthenelse{\boolean{FP@On}}{%
% If we're in facingpages mode, we got things to do
    \ifthenelse{\boolean{FP@Left}}{%
% If we're already in verso mode, output error
      \PackageError{facingpages}{Called \protect \BeginFacingPagesLeft, but
        already in verso mode}{}}{%
% We're in recto mode, so finish the last facingpages segment
      \FP@FinishUpRight}}{%
% We're entering facingpages mode from non-facingpages mode, make sure
% we start on a verso page
\ifthenelse{\isodd{\thepage}}{}{%
  \newpage \phantom{*}%
  \message{Moved one page, now on sheet \thesheetsequence, page \thepage}}}
% Ok, process the last segment
  \setcounter{FP@current@REnd}{\value{sheetsequence}}
  \FP@ProcessSeg
% Move to next verso page
  \incrementpagebyone
  \newpage
% Set up for left part of segment
  \incrementpagebytwo
  \stepcounter{FP@Seg}
  \setcounter{FP@current@LStart}{\value{sheetsequence}}
  \setcounter{FP@current@LPageStart}{\value{page}}
  \setcounter{SP@count}{\theFP@Seg}
  \multiply\c@SP@count by \c@SP@perseg
  \setboolean{FP@On}{true}
  \setboolean{FP@Left}{true}}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\BeginFacingPagesRight}
% Start a new right segment. 
%    \begin{macrocode}
\newcommand{\BeginFacingPagesRight}{%
  \message{\string\BeginFacingPagesRight\space called on sheet \thesheetsequence, page \thepage.}
% Complain if we're not switching from verso mode
\ifthenelse{\boolean{FP@Left}}{}{%
  \PackageError{facingpages}{Called \protect \BeginFacingPagesRight,
    but not in verso mode}{}}
% calculate actual length of left part of segment
  \setcounter{FP@current@LLength}{\value{sheetsequence}}
  \addtocounter{FP@current@LLength}{-\value{FP@current@LStart}}
% pad left part of segment with empty pages
  \cRestoreReg{FP@RLengthSaved}{FP@Seg}
  \ifthenelse{\boolean{RegEmpty}}{}{%
    \whiledo{\value{FP@current@LLength} < \RegContent}{%
    \message{Padding left segment with one page.}
    \newpage
    \phantom{*}
    \stepcounter{FP@current@LLength}}}
  \setcounter{FP@current@LEnd}{\value{sheetsequence}}
% Go to next recto page
  \newpage
% Set up for right part of current segment
  \setcounter{FP@current@RStart}{\value{sheetsequence}}
  \setcounter{page}{\value{FP@current@LPageStart}}
  \addtocounter{page}{\@ne}
  \setcounter{SP@count}{\value{FP@Seg}}
  \multiply\c@SP@count by \c@SP@perseg
  \setboolean{FP@On}{true}
  \setboolean{FP@Left}{false}}

%    \end{macrocode}
% \end{macro}
% \begin{macro}{\EndFacingPages}
% End facing pages mode. 
%    \begin{macrocode}
\newcommand{\EndFacingPages}{%
  \ifthenelse{\boolean{FP@On}}{%
% Complain if we're not switching from recto mode or we're not in
% facing pages mode at all
    \ifthenelse{\boolean{FP@Left}}{%
      \PackageError{facingpages}{Called \protect\EndFacingPages, but not
        in recto mode}{}}{}}{%
    \PackageError{facingpages}{Called \protect\EndFacingPages, but not in
      facing pages mode}{}}
  \setcounter{FP@current@REnd}{\value{sheetsequence}} 
  \FP@FinishUpRight
  \FP@ProcessSeg 
  \setboolean{FP@On}{false} 
  \setboolean{FP@Left}{false}
  \incrementpagebyone 
  \newpage 
  \addtocounter{FP@Seg}{\@ne}
  \setcounter{FP@current@LStart}{\value{sheetsequence}}}
%    \end{macrocode}
% Open the |.pss| file for writing at the beginning of the run.
%    \begin{macrocode}
\AtBeginDocument{%
  \newwrite\@psselect
  \immediate\openout\@psselect\jobname.pss}
%    \end{macrocode}
% At the end of the run, write end data for last segment if we're
% still in facingpages mode.  Then warn if pages have changed.
% Finally, close the |.pss| output file.
%    \begin{macrocode}
\AtEndDocument{%
  \ifthenelse{\boolean{FP@On}}{%
    \ifthenelse{\boolean{FP@Left}}{%
      \PackageError{facingpages}{Document ended in verso mode}{}}{}
    \FP@FinishUpRight}{}
  \setcounter{FP@current@REnd}{\value{sheetsequence}}
  \renewcommand{\FP@Comma}{} \FP@ProcessSeg
  \ifthenelse{\boolean{FP@ChangedWarn}}{%
    \PackageWarning{facingpages}{Facing pages segments have changed.
      Rerun to get facing pages right}}{}
  \immediate\closeout\@psselect}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Sync points}
%
% We need some counters:
%    \begin{macrocode}
\newcounter{SP@count}
\newcounter{SP@perseg}
\setcounter{SP@perseg}{100}
\setcounter{SP@count}{\c@SP@perseg}
\newcounter{SP@Pos}
\newcounter{SP@i}
%    \end{macrocode}
% \begin{macro}{\SPadjust}
%   If |\SPadjust| is true, add vertical space to line up sync points
%   on facing pages.
%    \begin{macrocode}
\newboolean{SPadjust}
\setboolean{SPadjust}{true}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\FP@RestoreSyncPointL}
% \begin{macro}{\FP@RestoreSyncPointR}
%   Restore array of sync point data from aux file. The aux file
%   contains the offsets in scaled points, divide by 65\,536 to get
%   points.
%    \begin{macrocode}
\def\FP@RestoreSyncPointL#1#2{%
  \setcounter{SP@Pos}{#2}
  \divide\c@SP@Pos by 65536
  \SaveReg{SP@PositionL}{#1}{\theSP@Pos}}
\def\FP@RestoreSyncPointR#1#2{%
  \setcounter{SP@Pos}{#2}
  \divide\c@SP@Pos by 65536
  \SaveReg{SP@PositionR}{#1}{\theSP@Pos}}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \begin{macro}{\SP\oarg{offset}}
%   Set a sync point. The {} at the end is there cause something is
%   probably wrong with the exandafters in FP@SyncPointLeft
%    \begin{macrocode}
\newcommand{\SP}[1][]{%
  \stepcounter{SP@count} 
  \ifthenelse{\boolean{FP@Left}}{%
    \FP@SyncPointLeft{#1}}{%
    \FP@SyncPointRight{#1}}{} 
  \ignorespaces}
%    \end{macrocode}
% \end{macro}
% set a syncpoint in the left part of a segment
%    \begin{macrocode}
\def\FP@SyncPointLeft#1{%
%    \end{macrocode}
% If we have an optional argument, add the vertical space
%    \begin{macrocode}
 \ifthenelse{\equal{#1}{}}{}{\vspace*{#1 pt}}
%    \end{macrocode}
% Save the positions
%    \begin{macrocode}
  \pdfsavepos
%    \end{macrocode}
% compute sheet offset from start of current left segment
%    \begin{macrocode}
  \setcounter{SP@i}{\value{sheetsequence}}
  \addtocounter{SP@i}{-\theFP@current@LStart}
%    \end{macrocode}
% At shipout, we write sync point data to aux file. We want the |SP@count|
% to be frozen at the invocation of the command, but |\pdflastpos| to
% expand only when the |\write| is active, i.e., during shipout
%    \begin{macrocode}
 \expandafter\write\@auxout\expandafter{\expandafter\noexpand\expandafter\FP@RestoreSyncPointL\expandafter{\number\c@SP@count}{\number\pdflastypos}}
  \immediate\write\@auxout{\noexpand\SaveReg{SP@SheetL}{\number\c@SP@count}{\number\c@SP@i}}
%    \end{macrocode}
% Recall saved position
%    \begin{macrocode}
  \cRestoreReg{SP@PositionL}{SP@count}
  \ifthenelse{\boolean{RegEmpty}}{}{%
    \setcounter{SP@Pos}{\RegContent}
%    \end{macrocode}
% Recall saved position of corresponding right syncpoint 
%    \begin{macrocode}
  \cRestoreReg{SP@PositionR}{SP@count}
  \ifthenelse{\boolean{RegEmpty}}{}{%
    \addtocounter{SP@Pos}{-\RegContent}
%    \end{macrocode}
% Recall saved sheet offset
%    \begin{macrocode}
  \cRestoreReg{SP@SheetL}{SP@count}
  \ifthenelse{\boolean{RegEmpty}}{}{%
     \setcounter{SP@i}{\RegContent}
%    \end{macrocode}
% Recall saved position of corresponding right syncpoint 
%    \begin{macrocode}
  \cRestoreReg{SP@SheetR}{SP@count}
  \ifthenelse{\boolean{RegEmpty}}{}{%
    \addtocounter{SP@i}{-\RegContent}
  \SP@Adjust{#1}}}}}}
%    \end{macrocode}
% set a syncpoint in the right part of a segment
%    \begin{macrocode}
\def\FP@SyncPointRight#1{%
%    \end{macrocode}
% If we have an optional argument, add the vertical space
%    \begin{macrocode}
 \ifthenelse{\equal{#1}{}}{}{\vspace*{#1 pt}}
%    \end{macrocode}
% Save the positions
%    \begin{macrocode}
  \pdfsavepos
%    \end{macrocode}
% compute sheet offset from start of current left segment
%    \begin{macrocode}
  \setcounter{SP@i}{\value{sheetsequence}}
  \addtocounter{SP@i}{-\theFP@current@RStart}
%    \end{macrocode}
% At shipout, write sync point data to aux file
%    \begin{macrocode}
\expandafter\write\@auxout\expandafter{\expandafter\noexpand\expandafter\FP@RestoreSyncPointR\expandafter{\number\c@SP@count}{\number\pdflastypos}}
\immediate\write\@auxout{\noexpand\SaveReg{SP@SheetR}{\number\c@SP@count}{\number\c@SP@i}}
%    \end{macrocode}
% Recall saved position
%    \begin{macrocode}
  \cRestoreReg{SP@PositionR}{SP@count}
\ifthenelse{\boolean{RegEmpty}}{}{%
  \setcounter{SP@Pos}{\RegContent}
%    \end{macrocode}
% Recall saved position of corresponding left syncpoint 
%    \begin{macrocode}
  \cRestoreReg{SP@PositionL}{SP@count}
  \ifthenelse{\boolean{RegEmpty}}{}{%
    \addtocounter{SP@Pos}{-\RegContent}
%    \end{macrocode}
% Recall saved sheet offset
%    \begin{macrocode}
  \cRestoreReg{SP@SheetR}{SP@count}
  \ifthenelse{\boolean{RegEmpty}}{}{%
    \setcounter{SP@i}{\RegContent}
%    \end{macrocode}
% Recall saved position of corresponding left syncpoint 
%    \begin{macrocode}
  \cRestoreReg{SP@SheetL}{SP@count}
\ifthenelse{\boolean{RegEmpty}}{}{%
  \addtocounter{SP@i}{-\RegContent}
  \SP@Adjust{#1}
}}}}}
%    \end{macrocode}
% \begin{macro}{\SP@show}
% Hook for printing a sync point.
%    \begin{macrocode}
\def\SP@Show#1{\marginpar[\hfil\scriptsize #1]{\scriptsize #1}}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\SP@Adjust}
%   If the sync points are on matching sheets, show position
%   difference and adjust if |SP@adjust| is true, else just show sheet
%   offset.
%    \begin{macrocode}
\def\SP@Adjust#1{%
  \ifthenelse{\equal{\theSP@i}{0}}{%
    \SP@Show{\fbox{\theSP@count} \theSP@Pos}%
    \ifthenelse{\boolean{SPadjust} \AND \equal{#1}{} \AND \theSP@Pos > 0}{%
      \vspace{\number\c@SP@Pos pt}}{}}{%
    \SP@Show{\fbox{\theSP@count} \theSP@i p}}}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\cutpageline}
% This command continues the current line and then breaks the page.
% Use this to adjust the pages of the facing English translation.
%    \begin{macrocode}
\def\cutpageline{\vadjust{\newpage}}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\cutpagehere}
% This command ends a page directly where the command occurs.  Should
% be used only rarely, since it can introduce excessive spacing
% between words.
%    \begin{macrocode}
\def\cutpagehere{{\parfillskip0pt\relax\par}\newpage\noindent}
%    \end{macrocode}
% \end{macro}
%
% \subsection{Counters}
% 
% The |max@reset| counter will contain the last page for which we have
% to save a counter.
\newcounter{max@reset}
\setcounter{max@reset}{0}
% \begin{macro}{\MakeFPCounter}
%   This is the user command to make a counter work across facing
%   pages.  First we make sure the |perpage| package is loaded, then
%   set it up so that at the end of the run, the reset values for the
%   counter are written to the |aux| file. Finally, invoke the
%   |\pp@makeperpage| command from |perpage|---whenever the counter
%   \meta{counter} is stepped, we call |\c@FPchk@|\marg{counter}.
%    \begin{macrocode}
\newcommand*\MakeFPCounter[1]{%
  \RequirePackage{perpage}%
  \AtEndDocument{\SaveResets{#1}}%
  \pp@makeperpage{#1}\c@FPchk@{\@ne}}
%    \end{macrocode}
% |\MakeFPCounter| should only be used in the preamble.
%    \begin{macrocode}
\@onlypreamble\MakeFPCounter
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\c@FPchk@}
%   |c@FPchk@|\marg{counter} checks if we have to reset \meta{counter}
%   and if so, does its magic.  After |\pp@fetchctr|, |\theperpage|
%   has the number of the page the last counter increment happened on,
%   saved in the |aux| file. If that is different than the page the
%   current counter increment happend on, we reset the counter using
%   |\ResetValue|.  If |\theperpage| is already defined (i.e., saved
%   in a previous run), we save the counter reset value for
%   |\theperpage|, set a flag that we've saved it (only those should
%   be saved at the end of the run---this prevents stale counter
%   resets left over from the |aux| file from being saved). Finally,
%   save the page this increment happens on using the |perpage|
%   command |\pp@writectr|.
%    \begin{macrocode}
\def\c@FPchk@#1{\z@=\z@
  \begingroup \pp@fetchctr{#1}\let\next\theperpage
  \addtocounter{pp@a@#1}\@ne \pp@fetchctr{#1}%
  \ifthenelse{\boolean{FP@On} \AND \NOT \equal{\next}{\theperpage}}{%
    \ResetValue{#1}{\theperpage}%
    \addtocounter{#1}\@ne}{}%
  \ifthenelse{\equal{\theperpage}{\@empty}}{}{%
    \SaveReg{FP@cReset@#1}{\theperpage}{\number\value{#1}}%
    \ifthenelse{\theperpage > \value{max@reset}}{%
      \setcounter{max@reset}{\theperpage}}{}%
    \SaveReg{FP@cResetFresh@#1}{\theperpage}{true}}%
  \pp@writectr\pp@pagectr{#1}{\number\value{#1}}}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\FPsetcounter}
% Resetting a counter is tricky. Setting it after it has been stepped
% once already on a page should work fine. If you want to set it at
% the beginning of the page (e.g., at the beginning of a chapter, etc)
% you have to use |\FPsetcounter|, which sets the reset point of the
% previous page, so the first time it is stepped, it should have the
% intended value.
%    \begin{macrocode}
\def\FPsetcounter#1#2{%
  \setcounter{SP@i}{\thepage}%
  \addtocounter{SP@i}\m@ne
  \ifthenelse{\value{SP@i} > \value{max@reset}}{%
    \setcounter{max@reset}{\thepage}{}}%
  \cSaveReg{FP@cReset@#1}{SP@i}{#2}%
  \cSaveReg{FP@cResetFresh@#1}{SP@i}{true}}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\ResetValue}
%   Calculate the reset value of counter |#1| on page |#2| by finding
%   the last page prior to |#2| for which |FP@cReset@#1| was saved
%    \begin{macrocode}
\def\ResetValue#1#2{%
  \setcounter{SP@i}{#2}%
  \setcounter{#1}{0}%
  \whiledo{\value{SP@i}>0}{%
    \addtocounter{SP@i}\m@ne%
    \IfRegEmpty{FP@cReset@#1}{\number\value{SP@i}}{}{%
      \setcounter{#1}{\cRegValue{FP@cReset@#1}{SP@i}}%
      \setcounter{SP@i}{0}}}}
%    \end{macrocode}
% \end{macro}
% At the end of the run, the reset counts for counter |#1| are written
% to the |aux| file, to be read in at the beginning so that reset counts
% for odd pages are available when processing the even pages in a
% facingpages segment.
%    \begin{macrocode}
\def\SaveResets#1{%
  \setcounter{SP@i}{0}
  \whiledo{\value{SP@i} < \value{max@reset}}{%
    \addtocounter{SP@i}\@ne
      \IfRegEmpty{FP@cResetFresh@#1}{\number\value{SP@i}}{}{%
        \immediate\write\@auxout{\noexpand\SaveReg{FP@cReset@#1}{\number\value{SP@i}}{\cRegValue{FP@cReset@#1}{SP@i}}}}{}}}
%    \end{macrocode}
% \Finale
% \PrintChanges
\endinput
