% \iffalse      THIS IS A META-COMMENT
%<*dtx>
\ProvidesFile
%========================================================================
                       {BALANCE.DTX}
%========================================================================
%</dtx>
%% Copyright 1993-1999 Patrick W Daly
%% Max-Planck-Institut f\"ur Aeronomie
%% Max-Planck-Str. 2
%% D-37191 Katlenburg-Lindau
%% Germany
%% E-mail: daly@linmpi.mpg.de
% 
% This program can be redistributed and/or modified under the terms
% of the LaTeX Project Public License Distributed from CTAN
% archives in directory macros/latex/base/lppl.txt; either
% version 1 of the License, or any later version.
%
% This is a contributed file to the LaTeX2e system.
% -------------------------------------------------
% This is a LaTeX package to balance the last two columns in twocolumn mode.
% Installation:
%    LaTeX this file: creates docstrip installation file balance.ins
%                         AND the (LaTeX2e) documentation
%    (La)TeX balance.ins: creates package files balance.sty, and optionally
%                         documentation driver balance.drv
%    (balance.ins may be edited as needed)
% Docstrip options available:
%        package - to produce a (LaTeX2e) package .sty file
%        driver  - to produce a driver file to print the documentation
%        209     - (with package) for package that runs under LaTeX 2.09
%        subpack - (with package) for coding included in other packages
%--------------------------------------------------------------------------
%<*!subpack>
%<package&209>\def\ProvidesPackage#1#2]
%<package&209>  {\typeout{Style option `#1'#2]}}
%
%  *** Identify the package file:-
%<package&!209>\NeedsTeXFormat{LaTeX2e}[1994/06/01]
%<package>\ProvidesPackage{balance}
%</!subpack>
%
%  *** Provide command to dislay module version
%<package&subpack>\def\ModuleVersion#1[#2]{}
%<package&subpack>    \ModuleVersion{balance}
%
%  *** Identify the driver file:-
%<driver>\NeedsTeXFormat{LaTeX2e}
%<driver>\ProvidesFile{balance.drv}
%
%  *** The DATE, VERSION, and other INFO
%\fi
%\ProvidesFile{balance}
         [1999/02/23 4.3 (PWD)]
% \changes{4.0}{1993 Oct 10}{First release with \texttt{docstrip}}
% \changes{4.0}{1993 Oct 20}{Change so \cs{balance} makes redefinitions
%                              and does not just set flag}
% \changes{4.1}{1994 May 16}{Convert to \LaTeXe}
% \changes{4.1a}{1994 Jun 22}{Update to first official release of \LaTeXe}
% \changes{4.1b}{1995 Jan 2}{Update documentation to PWD standard}
% \changes{4.2}{1995 Nov 7}{Fix up \cmd{\cleardoublepage}}
% \changes{4.2a}{1997 Mar 16}{Fix copyright for subpackage and other minor
%                                    things}
% \changes{4.2b}{1997 Apr 29}{Conform to new \texttt{docstrip}}
% \changes{4.3}{1999 Feb 23}{Update copyright notice}
%
% \CheckSum{168}
% \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         \~}
% \iffalse
%<*install>
%^^A =============================================
%^^A    Here is the docstrip installation file
%^^A    It is written on first LaTeX run if it 
%^^A    does not already exist
%^^A =============================================
\begin{filecontents*}{balance.ins}
% File: balance.ins
% Copyright 1999 Patrick W. Daly
%
% This file can be redistributed and/or modified under the terms
% of the LaTeX Project Public License Distributed from CTAN
% archives in directory macros/latex/base/lppl.txt; either
% version 1 of the License, or any later version.
% 
% It is an installation file for extracting package and driver
% files from the original source file. Simply process it under
% TeX or LaTeX. 

\input docstrip

\preamble
=============================================
IMPORTANT NOTICE:

This program can be redistributed and/or modified under the terms
of the LaTeX Project Public License Distributed from CTAN
archives in directory macros/latex/base/lppl.txt; either
version 1 of the License, or any later version.

This is a generated file.
It may not be distributed without the original source file \inFileName.

Full documentation can be obtained by LaTeXing that original file.
Only a few abbreviated comments remain here to describe the usage.
=============================================
\endpreamble
\postamble

<<<<< End of generated file <<<<<<
\endpostamble

\declarepreamble\driver
============================================
This is the driver file to produce the LaTeX documentation 
from the original source file \inFileName.

Make changes to it as needed. (Never change the file \inFileName!)
============================================
\endpreamble

\declarepostamble\driverq

End of documentation driver file.
\endpostamble

\keepsilent
\askforoverwritefalse

\generate{\file{balance.sty}{\from{balance.dtx}{package}}
          \file{balance.drv}{\usepreamble\driver\usepostamble\driverq
                           \from{balance.dtx}{driver}}
         }

\obeyspaces
\Msg{******************************************}%
\Msg{* For documentation, process balance.dtx *}%
\Msg{*    or the driver file      balance.drv *}%
\Msg{******************************************}

\endbatchfile
\end{filecontents*}
%</install>
%<*driver>
\documentclass{ltxdoc}
%<driver>%\documentclass[twoside]{ltxdoc}
%<driver>%\documentclass[a4paper]{ltxdoc}
%<driver>%\documentclass[twoside,a4paper]{ltxdoc}
\raggedbottom

 %** To include the detailed explanation of the coding, comment out
 %**   the next line
\OnlyDescription

 %** To produce a command index: add the following line for one run,
 %**   then run  makeindex -s gind.ist natbib
 %**   and reprocess, with or without this line (much faster without)
%<driver>% \EnableCrossrefs\CodelineIndex

 %** To produce a change history: add the following line for one run,
 %**   then run  makeindex -s gglo.ist -o natbib.gls natbib.glo
 %**   and reprocess, with or without this line (faster without)
%<driver>% \RecordChanges

\DisableCrossrefs %May stay; zapped by \EnableCrossrefs
\CodelineNumbered %May stay

\begin{document}
   \DocInput{balance.dtx}
\end{document}
%</driver>
% \fi
%
% \DoNotIndex{\begin,\CodelineIndex,\CodelineNumbered,\def,\DisableCrossrefs}
% \DoNotIndex{\DocInput,\documentclass,\EnableCrossrefs,\end,\GetFileInfo}
% \DoNotIndex{\NeedsTeXFormat,\OnlyDescription,\RecordChanges,\usepackage}
% \DoNotIndex{\ProvidesClass,\ProvidesPackage,\ProvidesFile,\RequirePackage}
% \DoNotIndex{\LoadClass,\PassOptionsToClass,\PassOptionsToPackage}
% \DoNotIndex{\DeclareOption,\CurrentOption,\ProcessOptions,\ExecuteOptions}
% \DoNotIndex{\AtEndOfClass,\AtEndOfPackage,\AtBeginDocument,\AtEndDocument}
% \DoNotIndex{\InputIfFileExists,\IfFileExists,\ClassError,\PackageError}
% \DoNotIndex{\ClassWarning,\PackageWarning,\ClassWarningNoLine}
% \DoNotIndex{\PackageWarningNoLine,\ClassInfo,\PackageInfo,\MessageBreak}
% \DoNotIndex{\space,\protect,\DeclareRobustCommand,\CheckCommand}
% \DoNotIndex{\newcommand,\renewcommand,\providecommand\newenvironment}
% \DoNotIndex{\renewenvironment,\newif,\newlength,\newcounter,\setlength}
% \DoNotIndex{\setcounter,\if,\ifx,\ifcase,\ifnum,\ifdim,\else,\fi}
% \DoNotIndex{\texttt,\textbf,\textrm,\textsl,\textsc}
% \DoNotIndex{\textup,\textit,\textmd,\textsf,\emph}
% \DoNotIndex{\ttfamily,\rmfamily,\sffamily,\mdseries,\bfseries,\upshape}
% \DoNotIndex{\slshape,\scshape,\itshape,\em,\LaTeX,\LaTeXe}
% \DoNotIndex{\filename,\fileversion,\filedate,\let}
% \DoNotIndex{\@@warning,\@M,\@colht,\@combinedblfloats,\@dblfloatplacement}
% \DoNotIndex{\@firstcolumnfalse,\@firstcolumntrue,\@leftcolumn,\@outputbox}
% \DoNotIndex{\@outputdblcol,\@outputpage,\@startdblcolumn,\@tempdima}
% \DoNotIndex{\@whilesw,\advance,\baselineskip,\begingroup,\box,\columnseprule}
% \DoNotIndex{\columnwidth,\copy,\dimen,\divide,\dp,\else,\endgroup,\fi}
% \DoNotIndex{\global,\hbox,\hfil,\hss,\ht,\if@fcolmade,\if@firstcolumn}
% \DoNotIndex{\if@twocolumn,\ifdim,\kern,\loop,\multiply,\newdimen}
% \DoNotIndex{\outputpenalty,\penalty,\repeat,\setbox,\splittopskip}
% \DoNotIndex{\string,\textwidth,\topskip,\unvbox,\vbadness,\vbox}
% \DoNotIndex{\vfil,\vrule,\vsplit}
%
% \setcounter{IndexColumns}{2}
% \setlength{\IndexMin}{10cm}
% \setcounter{StandardModuleDepth}{1}
%
% \GetFileInfo{balance}
%
% \title{\bfseries Balancing the Two Columns of Text on the Last Page}
%
% \author{Patrick W. Daly}
%
% \date{This paper describes package \texttt{\filename}\\
%       version \fileversion{} from \filedate\\[1ex]
%     \textsl{It is part of the \texttt{preprint} collection of packages}
%  }
%
% \maketitle
%
% \pagestyle{myheadings}
% \markboth{P. W. Daly}{BALANCING TWO COLUMN TEXT}
%
%^^A In order to keep all marginal notes on the one (left) side:
%^^A (otherwise they switch sides disasterously with twoside option)
% \makeatletter \@mparswitchfalse \makeatother
%
%\begin{small}\begin{center}\textbf{Summary}\end{center}
% The stripped version of this file contains the following brief description:
%\iffalse
%<*package&!subpack>
%\fi
% \begin{verbatim}
 % In order to balance the columns on a page, \balance must be given
 % somewhere within the first column. To turn off the feature, give
 % \nobalance. One has to look at the unbalanced text first to decide
 % where best to place \balance.
% \end{verbatim}
%\iffalse
 %-----------------------------------------------------------
%</package&!subpack>
%\fi
%\end{small}
%
% \section{Introduction}
% When a \LaTeX{} document is to be set in two-column mode, one can
% add |twocolumn| as an option to |\documentstyle| (\LaTeX~2.09)
% or to |\documentclass| (\LaTeXe), or one can use the
% |\twocolumn| command in the text. In either case, the columns on the last
% page, or those before a |\cleardoublepage| command, will be of unequal
% height.  This is because \LaTeX{} views the columns as pages which are
% just output as pairs, and it no longer knows about the left-hand column
% when a short right-hand one is finished.
%
% The macros in this package solve this problem by modifying the output
% routines in two-column mode.
%
% \section{Invoking the Package}
% The macros in this package are included in the main document
% with the |\usepackage| command of \LaTeXe,
% \begin{quote}
% |\documentclass[..,twocolumn,..]{...}|\\
% |\usepackage{|\texttt{\filename}|}|
% \end{quote}
% There are no \LaTeXe{} options for this package.
%
% Alternatively, the name of the package is added as an option to the
% |\documentstyle| command in \LaTeX~2.09 compatibility mode, as
% \begin{quote}
% |\documentstyle[..,twocolumn,|\texttt{\filename}|..]{...}|
% \end{quote}
%
% \section{Usage}
% Including the \texttt{\filename} package as shown above does not activate it
% immediately. There are a number of reasons for this.
% \begin{enumerate}
% \item It could be that a newer (or much older) version of \LaTeX{} is
%       being used for which the modified |\output| routines are
%       incompatible; in this case, the new routines must be left inactive.
%
% \item Sometimes the modified output routine does not work well for normal
%       pages, especially with floats (figures and tables) or footnotes.
%
% \end{enumerate}
% For these reasons, it is thought better to have the modified output
% routines left inactive, and to turn them on only when needed.
% \DescribeMacro{\balance}
% This is done with the command |\balance|, which should be issued
% somewhere in the text of what would be the first column of the last page
% without balanced columns. If it is issued too late, i.e., in the second
% column, then a warning message is printed that balancing may not take
% place.
%
% \DescribeMacro{\nobalance}
% To turn off the balancing routines, call |\nobalance|. This might be
% useful where there are many `last' pages, say at the end of book
% chapters. The |\balance| command should be given for each page that
% needs balancing, and then turned off at the end of the second column.
%
% It might well be that |\balance| can be left on all the time, but one
% should check the output carefully, and turn it off if need be.
%
% \section{An Alternative}
% Making multicolumn text with Mittelbach's {\tt multicol} package is
% perhaps a better method. It balances automatically, and allows more than
% just two columns. Never use \texttt{\filename} together with {\tt multicol}!
%
% \StopEventually{\PrintIndex\PrintChanges}
%
% \section{Options with \texttt{docstrip}}
% The source \texttt{.dtx} file is meant to be processed with
% \texttt{docstrip}, for which a number of options are available:
% \begin{description}
% \item[\tt package] to produce a \texttt{.sty} package file with most
%     comments removed;
% \item[\tt 209] for a package file that will also run under the older
%     \LaTeX~2.09 and not just under the newer (mid-1994) \LaTeXe;
% \item[\tt subpack] (together with \texttt{package}) for coding that is to
%     be included inside a larger package; even more comments are removed,
%     as well as \LaTeXe{} option handling and identification;
% \item[\tt driver] to produce a driver \texttt{.drv} file that will print
%     out the documentation under \LaTeXe; with the \texttt{209} option,
%     a driver \texttt{.209} file is also produced, for printing the
%     documentation under \LaTeX~2.09.
% \end{description}
% The source file \texttt{\filename.dtx} is itself a driver file and can
% be processed directly by \LaTeXe.
%
% \section{The Coding}
% This section presents and explains the actual coding of the macros.
% It is nested between |%<*package>| and |%</package>|, which
% are indicators to \texttt{docstrip} that this coding belongs to the package
% file.
%
% The \texttt{docstrip} option |<subpack>| should only be called if the
% coding is to be included as part of another package, in which case the
% announcement text and \LaTeXe{} options are suppressed.
%
% An inferior version of this coding is provided for running as a
% style file under \LaTeX~2.09. Code lines belonging to this are
% indicated with guard |<209>|; those for LaTeXe{} only with |<!209>|.
%
% \subsection{Altering the Standard {\tt\bslash output} Routines}
% The column balancing procedure here involves making changes to the
% standard output routines in \LaTeX. I normally do not like assuming
% anything from {\tt latex.tex} because it may have been different in
% earlier versions, and may change again. There I try as much as possible
% to save current definitions of internal macros and then simply add
% revisions.
%
% In this case, that is not possible. I have had to take the routine
% |\@outputdblcol| from \LaTeX{} version 2.09, (1992 March~25) as basis.
% However, I notice that they have not changed for many versions, so that
% maybe there is some stability here.
%
% The newer \LaTeXe{} version (1994 Dec.~01) also has the same definition
% of |\@outputdblcol|, so there should be no problems of compatibility
% here.
%
% In earlier versions of \texttt{\filename}, |\@outputdblcol| was changed
% such that
% a flag would activate the new coding if set, otherwise the old coding
% took place. This assumes that the `old' coding is known, because I give
% it explicitly in the new definition. This is where problems could arise
% if |\@outputdblcol| is ever changed.
%
% I now do this differently. The old definition of |\@outputdblcol| is
% stored (without knowing what it is), and the |\balance| command redefines
% it. Without giving |\balance|, one has the default output routines as
% though \texttt{\filename} were never selected. This gives the user the
% chance to turn everything off if any problems should arise.
%
% Since the balancing act does not always work for normal pages (where the
% two columns are full) especially when floats are involved, it is better
% to turn it on with |\balance| only where it is needed. It may then be
% turned off again with |\nobalance|.
%
% \subsection{The Principle Behind Balancing Columns}
% Let me first explain how |\@outputdblcol| normally works. By the time it
% is called, the accumulated text for the `page' (\TeX{} considers each
% column to be a page at this point) is contained in the box |\@outputbox|.
% The routine checks if this is the first column, and if so stuffs
% |\@outputbox| into the box |\@leftcolumn|; it then toggles the
% |\if@firstcolumn| flag. On the next call to |\@outputdblcol|, it combines
% |\@leftcolumn| with |\@outputbox| side by side on a single page, all
% stored in |\@outputbox|.
%
% For column balancing, the procedure is slightly different. If it is the
% first column, then the height of the column (|\@colht| = |\textheight|
% minus double-column floats and footnotes) is doubled and the contents of
% |\@outputbox| are dumped back into the processing. The height must be
% doubled temporarily to allow this, otherwise the |\output| routines will
% be immediately called again. On the second column, the new routine
% |\@BAlancecol| is called to split |\@outputbox| into two equally high
% pieces of text, stored in |\@leftcolumn| and |\@outputbox|, which are
% then placed side by side as usual.
%
% \subsection{Macro Definitions}
% \begin{macro}{\@BAlancecol}
% \changes{4.0}{1993 Nov 1}{Add \cmd{\vfil} after
%      \cmd{\unvbox1} to prevent underfull vbox}
% \changes{4.1}{1994 May 16}{New name for \cmd{\@balancecol}, to conform
%      more with newer conventions for package programming.}
% \changes{4.1a}{1994 Jun 22}{Use \cmd{\newcommand} instead of \cmd{\def}}
% We begin by defining |\@BAlancecol|, the routine that splits
% |\@outputbox| into two nearly equally high boxes, which are then stored
% in boxes |\@leftcolumn| and |\@outputbox|. This routine is almost
% identical with that of Knuth in the \TeX{}Book (macro |\balancecolumns|
% on page~417). The loop keeps going until the first column is less than
% the second in height, making 1~pt changes in the specification each time.
%    \begin{macrocode}
%<*package>
\newcommand{\@BAlancecol}{\if@twocolumn
  \setbox0=\vbox{\unvbox\@outputbox} \@tempdima=\ht0
  \advance\@tempdima by \topskip \advance\@tempdima
     by -\baselineskip \divide\@tempdima by 2
     \splittopskip=\topskip
  {\vbadness=\@M \loop \global\setbox3=\copy0
   \global\setbox1=\vsplit3 to \@tempdima
   \ifdim\ht3>\@tempdima \global\advance\@tempdima by 1pt \repeat}
   \setbox\@leftcolumn=\vbox to \@tempdima{\unvbox1\vfil}
   \setbox\@outputbox=\vbox to \@tempdima
     {\dimen2=\dp3\unvbox3\kern-\dimen2
      \vfil}
  \fi}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@BAdblcol}
% \changes{4.1}{1994 May 16}{New name for \cmd{\@baldblcol}, to conform
%      more with newer conventions for package programming.}
% \changes{4.1a}{1994 Jun 22}{Use \cmd{\newcommand} instead of \cmd{\def}}
% \changes{4.1a}{1994 Jun 22}{Use \cmd{\PackageWarningNoLine} instead of
%              \cmd{\@@warning}}
% Now define the revised routine |\@outputdblcol|, and name it
% |\@BAdblcol|. In the first column, it just puts |\@outputbox| back into
% the processing with a doubled column height (|\@colht|). In the second
% column, it calls |\@BAlancecol| and the places the boxes |\@leftcolumn|
% and |\@outputbox| side by side in almost the same way that the original
% |\@outputdblcol| does. The difference is that the final vbox is made to
% be |\@colht| high and a |\vfil| must be added below to fill up the
% missing space. In the original, the column boxes themselves are |\@colht|
% high, so this is not necessary. If this feature were left off, then the
% final box would not have the correct height, something that is noticeable
% when a footline is added at the bottom.
%    \begin{macrocode}
\newif\if@BAlanceone
\global\@BAlanceonefalse
\newdimen\oldvsize
\newcommand{\@BAdblcol}{\if@firstcolumn
       \unvbox\@outputbox \penalty\outputpenalty
       \global\oldvsize=\@colht \global\multiply \@colht by 2
       \global\@BAlanceonetrue
       \global\@firstcolumnfalse
  \else \global\@firstcolumntrue
       \if@BAlanceone
       \global\@BAlanceonefalse\@BAlancecol
       \global\@colht=\oldvsize \else
%<!209>       \PackageWarningNoLine{balance}
%<209>       \@@warning
          {You have called \protect\balance\space
%<!209>             in second column\MessageBreak
%<209>             in second column^^J
           Columns might not be balanced}\fi
     \setbox\@outputbox\vbox to \@colht{\hbox to\textwidth
     {\hbox to\columnwidth {\box\@leftcolumn \hss}\hfil
      \vrule width\columnseprule\hfil \hbox to\columnwidth
      {\box\@outputbox \hss}}\vfil}\@combinedblfloats
     \@outputpage \begingroup \@dblfloatplacement
     \@startdblcolumn \@whilesw\if@fcolmade \fi
     {\@outputpage\@startdblcolumn}\endgroup
  \fi}
%    \end{macrocode}
% The flag |\if@BAlanceone| seems redundant, since it is always the
% complement of |\if@firstcolumn|. However, its function is to ensure that
% the |\balance| command, that activates |\@BAdblcol|, actually occurs
% before the first column of text is completed. If this is not the case, if
% |\balance| is issued too late, then the procedure cannot function. In
% this case, |\@BAdblcol| is entered with both |\if@firstcolumn| and
% |\if@BAlanceone| set \meta{false}, so that the call to |\@BAlancecol| is
% suppressed and warning message is printed.
% \end{macro}
%
% \begin{macro}{\cleardoublepage}
% \changes{4.2}{1995 Nov 07}{Add revised definition for balanced mode}
% A new version of |\cleardoublepage| is necessary when |\balance| is
% active. The regular command adds two |\newpage| commands on an even page
% in two column mode, since each |\newpage| only starts a new column.
% However, when |\balance| is active, each |\newpage| makes two balanced
% columns, to it actually starts a new page, and not just a new column.
%     \begin{macrocode}
\newcommand{\@BAcleardblpage}{\clearpage\if@twoside \ifodd\c@page\else
  \hbox{}\newpage\fi\fi}
\newcommand{\@@cleardblpage}{}
\let\@@cleardblpage=\cleardoublepage
%    \end{macrocode}
% \end{macro}
%

% \begin{macro}{\balance}
% \changes{4.0}{1993 Oct 20}{Change from setting flag to redefining output
%               routine.}
% \changes{4.1a}{1994 Jun 22}{Use \cmd{\newcommand} instead of \cmd{\def}}
% \changes{4.2}{1995 Nov 07}{Add revised \cmd{\cleardoublepage}}
% The command that activates the balancing replaces |\@outputdblcol|
% with the new |\@BAdblcol|.
%    \begin{macrocode}
\newcommand{\@@utputdblcol}{}
\let\@@utputdblcol=\@outputdblcol
\newcommand{\balance}{\global\let\@outputdblcol=\@BAdblcol
  \global\let\cleardoublepage=\@BAcleardblpage}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\nobalance}
% \changes{4.0}{1993 Oct 20}{Change from setting flag to restoring
%                   original output routine.}
% \changes{4.1a}{1994 Jun 22}{Use \cmd{\newcommand} instead of \cmd{\def}}
% \changes{4.2}{1995 Nov 07}{Add revised \cmd{\cleardoublepage}}
% To turn off the balancing routine, call |\nobalance|.
%    \begin{macrocode}
\newcommand{\nobalance}{\global\let\@outputdblcol=\@@utputdblcol
  \global\let\cleardoublepage=\@@cleardblpage}
%</package>
%    \end{macrocode}
% \end{macro}
%
% \Finale
