% \iffalse
% !TEX encoding = UTF-8 Unicode
% !TEX TS-program = pdflatex
%<*internal>
\begingroup
\input docstrip.tex
\keepsilent
\preamble

  Copyright (C)  2020 Claudio Beccari  all rights reserved.
  License information appended
  
\endpreamble

\postamble

Distributable under the LaTeX Project Public License,
version 1.3c or higher (your choice). The latest version of
this license is at: http://www.latex-project.org/lppl.txt

This work is "maintained"

This work consists of files swfigure.dtx and READEME.txt, and the derived
files swfigure.sty and swfigure.pdf

\endpostamble
\askforoverwritefalse

\generate{\file{swfigure.sty}{\from{swfigure.dtx}{package}}}
%\generate{\file{README.txt}{\from{swfigure.dtx}{readme}}}

\def\tmpa{plain}
\ifx\tmpa\fmtname\endgroup\expandafter\bye\fi
\endgroup
%</internal>
% \fi
%
% \iffalse
%<*package>
%<package>\NeedsTeXFormat{LaTeX2e}[2020/01/01]
%</package>
%<*driver>
\ProvidesFile{swfigure.dtx}%
%</driver>
%<+package>\ProvidesPackage{swfigure}%
%<+readme>File README.txt for package swfigure
%<*package|readme>
        [2020-10-11 v.0.9.07 Managing large and spread wide figures]
%</package|readme>
%<*driver>
\documentclass[a4paper]{ltxdoc}\errorcontextlines=9
\hfuzz 10pt
\usepackage[utf8]{inputenc}
\usepackage{lmodern,textcomp,multicol,enumitem,mflogo,xcolor}
\usepackage{swfigure}

\providecommand*\diff{\mathop{}\!\mathrm{d}}
\renewcommand\meta[1]{{\normalfont\textlangle\textit{#1}\textrangle}}
\renewcommand\marg[1]{\texttt{\{\meta{#1}\}}}
\providecommand\Marg{}
\renewcommand\Marg[1]{\texttt{\{#1\}}}
\providecommand\oarg{}
\renewcommand\oarg[1]{\texttt{[\meta{#1}]}}
\providecommand\Oarg{}
\renewcommand\Oarg[1]{\texttt{[#1]}}
\providecommand\aarg{}
\renewcommand*\aarg[1]{\texttt{<\meta{#1}>}}
\providecommand\Aarg{}
\renewcommand\Aarg[1]{\texttt{<#1>}}
\providecommand\parg{}
\renewcommand\parg[1]{\texttt{(\meta{#1})}}
\providecommand\Parg{}
\renewcommand\Parg[1]{\texttt{(#1)}}
\providecommand\eTeX{}
\newbox\SWsynt
\renewcommand\eTeX{\lower0.5ex\hbox{$\varepsilon\!$}\TeX}

\newenvironment{medaglione}%
{\par\medskip\fboxrule=0.8pt\fboxsep6pt\relax
\begin{lrbox}{\SWsynt}\minipage{\dimexpr\linewidth-2\fboxsep-2\fboxrule}}%
{\endminipage\end{lrbox}\noindent\fbox{\box\SWsynt}\par\medskip}

\newenvironment{ttsyntax}{\medaglione\raggedright\ttfamily\obeylines}{\endmedaglione}

\providecommand\setfontsize{}
\DeclareRobustCommand\setfontsize[2][1.2]{%
\linespread{#1}\fontsize{#2}{#2}\selectfont}

\GetFileInfo{swfigure.dtx}
\title{The \texttt{swfigure} package\\
Managing large and spread wide figures}
\author{Claudio Beccari\thanks{E-mail: \texttt{claudio dot beccari at gmail dot com}}}
\date{Version \fileversion~---~ Last revised \filedate}

\begin{document}\errorcontextlines=100
\maketitle
\columnseprule=0.4pt
\begin{multicols}{2}
 \tableofcontents
 \end{multicols}
 \DocInput{swfigure.dtx}
\end{document}
%</driver>
% \fi
%^^A \CheckSum{10}^^A Doesn't this work any more?
%
% \begin{abstract}
% This package defines a single command that with different options can
% insert large images into the document; those that occupy an entire
% spread s get split into two halves that are inserted on
% two facing pages in such a way that they merge when the document is read
% on the screen (set to double page view) or is printed in a well sewn
% book so that facing pages join correctly at the spine. 
% This documentation is accompanied by another file
% |swfigure-examples.pdf| containing examples of this package several
% uses.
% \end{abstract}
%
%^^A \DFimage[SW]{SWfakeimage}{A large fake image}[fig:SWfake]
%^^A It does not work with the page design of this document.
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\section{Introduction}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Sometimes it is necessary to insert in a given document very large
% images; either they are larger than a spread, or they do not exceed
% the width of a spread. In the first case it is necessary to use
% to large sheets of paper folded in the proper way and inserted in the
% printed document as special inserts; or for documents to be read on
% the screen such large sheets have to be attached to the document as
% separate files to be viewed in windows different from that where the
% document is being read.
%
% In the other case it is possible to manage such large figures in
% different ways; we define a single command that, according to
% different settings, can insert such figures in five different display
% modes.
%\begin{enumerate}[noitemsep]
% \item
% The normal \LaTeX\ kernel full page display mode, but using
% the |figure| environment with the |[p]| placing option. Apparently
% there is no need to define a new command for this display mode, except
% the advantage of using the same command as the other modes and a few
% small further functionalities that the new command has available.
%\item
% The landscape display mode available with the |lscape| package
% and other similar ones. Again this display mode appears superfluous,
% but the advantage is to use the same command as with the other
% display modes
%\item
% The screen-wide display mode, where two facing pages display a large
% figure divided in two halves, each one set in its page shifted to the
% spine so as to occupy on each page the text width plus the internal
% margin width; with suitable aspect ratio, both facing pages are
% practically full. No other text appears in this display mode, except
% the caption in the right page external margin.
%\item
% The slim screen-wide image is similar to the previous mode, but since
% the figure is slim, it is set at the top of two facing pages, with text
% underneath; the caption is under the right figure half in the right
% page, and the left text block height is set so that that the first
% lines of both text blocks are aligned.
%\item
% The slim tall image is set to the side of the text block that wraps
% it. Recurse is made to the |wrapfig| package, therefore the software
% might sometimes hick-up a little bit, because of the idiosyncrasies of
% |wrapfig| that performs very well in most but not all circumstances;
% see that package documentation for such |wrapfig| limitations. With
% this |wsfigure| package we limit the use of this display mode to
% images that have a “height over width” ratio not lower than~2; we
% provide also some option arguments so as to correct small imperfections
% in the sizing of the text indention 
%\end{enumerate}
%
% In any case, depending on the page geometry and the image aspect
% ratio, it is very handy to have available a single command that
% changes the display mode by just changing a single input optional
% argument. In facts the user might start with one of the five
% described display modes; after examining the document daft the
% user might chose another display mode, and it suffices to change
% the optional argument, without changing the whole code.
%
% \bigskip
%
% \noindent\fbox{\textcolor{red}{WARNING}}\quad This package performs
% well with documents typeset in \texttt{twoside} mode, and with a page
% design where the internal margins of both the odd and even  pages
% are equal (symmetrical page design). For example, it does not work
% with this document designed to work in \texttt{oneside} mode and
% where the the left page margin is always larger than the right one
% of each page; this page design is functional to the documentation
% of the \TeX\ system software.
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\section{Installation}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% This package is already installed with any complete and up to date
% \TeX\ system distribution, \TeX\ Live or MiK\TeX.
%
% Should the user have available a basic or a partial \TeX\ system
% installation, the simplest way to install this package is to download
% the |swfigure.zip| file from the Comprehensive \TeX\ Archive Network
% (CTAN), and decompress it either in the very folder where there is
% the document main or single document file or, for a general use, in
% the user personal |texmf| tree; it is possible that the user should
% directly create this personal tree; how to do it is described in the
% documentation of the user \TeX\ system distribution.
%
% The same holds true if the user employs a vintage \TeX\ system
% distribution; this package requires the \LaTeX3 modern language
% functionalities, therefore a \LaTeX\ kernel with a date after
% 2019-01-01. Lacking this modern kernel, the package is strongly
% limited, because packages |xparse| and |xfp| are used for its
% internal workings.
%
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\section{Usage}\label{sec:Usage}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This package defines a single user command, |DFimage| to be used
% with the following syntax:
%\begin{ttsyntax}
%\cs{DFimage}\oarg{display mode}\marg{image file name}\oarg{lof entry}\marg{caption}\oarg{label}\%
%\qquad\parg{heigth correction}\aarg{line correction}
%\end{ttsyntax} 
% where:
%\begin{description}[noitemsep]
%\item[\meta{display mode}]
% is one of the following uppercase acronyms:
% \texttt{NF} (Normal Figure),  \texttt{RF} (Rotated Figure),
% \texttt{SW} (Spread Wide image), \texttt{HS} (Horizontal Spread-wide
% image), and \texttt{VS} (Vertical Slim image).
%\item[\meta{image fie name}]
% Is the name of the image graphic file; remember that the \LaTeX based
% \TeX\ system typesetting programs accept graphic files in the formats
% with extensions \texttt{.pdf}, \texttt{.eps}, \texttt{.jpg},
% \texttt{.png}, and few other less common ones. It is not necessary to
% specify the extension, but it is not forbidden.
%\item[\meta{lof entry}]
% is the optional entry to the List Of Figures; it defaults to the
% \meta{caption} text, but if the latter is sort of lengthy, it is
% better to enter a shorter text in that list.
%\item[\meta{caption}]
%  is the caption text.
%\item[\meta{label}]
% this optional argument is the string that forms the argument of the
% \cs{label} command; of course, if this argument is not specified,
% the figure number and its page cannot be referenced with \cs{ref},
% \cs{pageref} and other similar commands.
%\item[\meta{height correction}]
% This normal parenthesis delimited optional argument is a fractional
% number lower than~1 (default 0.8) with which to further scale the
% scaled image height to be included; it is used by some display modes,
% and it is ignored by others.
%\item[\meta{line correction}] is an angle bracket delimited optional
% argument preset to zero. It is relevant only with the slim
% vertical image display mode. Sometimes the |wrapfig| package
% indents the wrapping text in such a way as to leave to much or too
% little vertical space around the image and its caption; by examining
% the document drafts it is possible to increase or decrease the
% vertical space by any (integer) number of lines.
%\end{description}
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \section{Display mode peculiarities}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Each of the listed display modes has its own pros and cons.
% In the following the phrase “aspect ratio” refers to the “height
% over width” ratio either of the image or of the available space
% where to put the image and possibly its caption.
%\begin{description}[noitemsep]
%
%\item[\texttt{NF}]
% This display mode is convenient when the image
% aspect ratio is close to the text block one. Of course the user
% does not know in advance the vertical space occupied by the caption,
% therefore the optional \meta{height correction} comes handy for
% small adjustments; this display mode is fully and freely floating,
% although its positioning is fixed to~|[p]|.
%
%\item[\texttt{RF}]
% This display mode is convenient when the image
% aspect ratio is close to the reciprocal of the text block one. This
% mode accepts the \meta{height correction} in order to leave space
% to the caption. It is a fully and freely floating object with the
% same pros and cons as the \texttt{NF} display mode.
%
%\item[\texttt{SW}]
% This display mode is convenient when a really large
% image requires two pages to display all its details; its aspect ratio
% should be close to the two page aspect ratio of the total space
% available for the two page spread; depending on the page design this
% total space approximate value probably is close  to~0.5.
% The object to be included in the document should start on an even
% page, therefore it moves to the first even page available; this
% implies that the last document page before the spread wide image
% may be blank or may be shorter than the other text pages; the user
% then should help the automatic positioning by choosing very carefully
% where to insert the \cs{DFfigure} command in the source text; it can
% even set it within a paragraph and the command provides a new page
% just after the line that contains the \cs{DFfigure} command;
% therefore if the paragraph is close to the end of an odd page and
% the position of \cs{DFfigure} command is properly positioned within this
% paragraph, the spread wide insertion would not disturb the quality
% of the typeset document.
%
%\item[\texttt{HS}]
% This display mode is convenient when the initial image aspect
% ratio is very small; if it is smaller than~0.3 its insertion
% leaves enough space beneath the two image halves (plus caption)
% so that normal text can fill the space under such spread wide
% slim figure. The constrains described for display mode \texttt{SW}
% apply also to this mode.
%
%\item[\texttt{VS}]
% This mode is convenient for tall and slim figures with aspect ratio
% not lower than~2; but for obvious reasons, it should not be too
% large, let's say not higher than about~3. As always this depends on
% the page design and the caption size. The limitations of the
% underlying of the |wrapfig| package forbids its usage too close to
% section headings, explicit lists and texts typeset in special modes
% with different measure than normal text. Again it is up to the user
% to chose where to insert the \cs{DFfigure} command. If the aspect
% ratio of the image to include is lower than~2, this message is printed
% in the document where the image should appear (of course with |#2| replaced by the actual image file name):
%\begin{verbatim}
%      ===========================================
%      Figure #2 is not tall enough.
%      Consider using a display mode different
%      from VS; may be NF or RF are better suited.
%      ===========================================
%      Nothing done!
%      ===========================================
%\end{verbatim}
%^^A
%\end{description}
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \section{Acknowlegements}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% This package would not exist if Heinrich Flech did not need
% to insert several types of large images in his documents; he asked
% me to create suitable commands and/or environments and he tested
% all the series of progressive developments of this package; believing
% that this package might be useful to other \TeX\ users, he invited
% me to submit the result to the \TeX\ community, and here it is.
% Heinrich did not want his name as an author, because he insists
% that he was “just” a tester. He was precious and I warmly thank him.
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\begin{thebibliography}{9}
%\bibitem{bib:xparse} The \LaTeX3 Project, \emph{The \texttt{xparse} package} --- Document command parser. Release date 2020-05-15. PDF document readable with \texttt{texdoc xparse}.
%\bibitem{bib:xfp} The \LaTeX3 Project, \emph{The \texttt{xfp} package} --- Floating Point Unit. Release date 2020-05-15. PDF document readable with \texttt{texdoc xfp}.
%\bibitem{bib:Int3} The \LaTeX3 Project, \emph{The \LaTeX3 interfaces}. Release date 2020-09-24. PDF Document readable with \texttt{texdoc interface3}.
%\bibitem{bib:graphics} D.P.~Carlisle and The \LaTeX3 Project, \emph{Packages in the `graphics' bundle}. Release date 2020-08-21. PDF document readable with \texttt{texdoc grfguide}.
%\bibitem{bib:etoolbox} P. Lehman and J Wright, \emph{the \texttt{etoolbox} Package} --- An e-TeX Toolbox for Class and Package Authors. version 2.5j, released on 2020-08-24. PDF document readable with \texttt{texdoc etoolbox}.
%\bibitem{bib:lscape} D.P. Carlisle, \emph{The \texttt{lscape} package}. Version 3.02 released on 2020-05-28. PDF document readable with \texttt{texdoc lscape}.
%\bibitem{bib:afterpage} D.P. Carlisle, \emph{The \texttt{afterpage} package}. Version 1.08 released on 2014-10-28. PDF document readable with \texttt{texdoc afterpage}.
%\bibitem{bib:wrapfig} D. Arseneau, \emph{The \texttt{wrapfig} package}. Version 3.6 released on 2003-01-31.
%\bibitem{bib:memman} P. Wilson, \emph{The Memoir Class for Configurable Typesetting} ---User guide. Version 3.7m released 2020-09-10. PDF document readable with \texttt{texdoc memman}.
%\end{thebibliography}
%
% \StopEventually{}
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \section{The code}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The required \TeX\ format and is date, and the identification of this
% package have already ben inserted by the initial commands  of this
% documented file.
%
% Here we call the initial required packages and, since the necessary
% software to define some \LaTeX3 (L3) language “functions” are already
% part of the \LaTeX\ kernel, we just use them in order to define a
% robust \LaTeXe/L3 interface to create a testing macro that accepts
% many logical operators that act on items that, besides being boolean
% variables, are also numerical expressions connected with relation
% operators; for further details it suffices to examine the
% |interface3.pdf| file, that is integral part of any recent \TeX\ 
% system distribution.
%
% The syntax of the new testing macro is the following:
%\begin{ttsyntax}
%\cs{fptest}\marg{test}\marg{true}\marg{false}
%\end{ttsyntax}
% The logical operators that are usable in the \meta{text} phrase
% are \verb+||+ (\texttt{OR}), \verb+&&+ (\texttt{and}), and \verb+!+
% (\texttt{NOT}), plus other less common ones; the \verb+!+ negates the
% status of boolean variables, but also the numerical relation operators;
% these, on turn, may be paired so that, for example |>=| is the same
% as~|!<|.
%
% The |trace| package is still present in this beta version of the
% package; it will not be present in the next stable versions.
% Packages |graphicx|, |afterpage|, and  |wrapfig| are functional
% for this package. In order to avoid “Option Clash” messages, such
% packages are loaded without any option; should the user load some
% or all  of them with options, this operation must be done
% \emph{before} loading this package.
%\iffalse
%<*package>
%\fi
%    \begin{macrocode}
\RequirePackage{etoolbox}
\RequirePackage{xparse}
\RequirePackage{xfp}

\ExplSyntaxOn
\AtBeginDocument{%
\ProvideExpandableDocumentCommand\fptest{m m m}{%
   \fp_compare:nTF{#1}{#2}{#3}}
}
\ExplSyntaxOff

\RequirePackage{trace}

\RequirePackage{graphicx}
\RequirePackage{afterpage}
\RequirePackage{wrapfig}

%    \end{macrocode}
% We define some dimension and some counter registers; to some dimensions
% we assign parameters relating to the page design. We also compute
% the dimensions of the available spread space so as to have available
% the elements to compare the aspect ratios of the images and of the
% available spaces.
%    \begin{macrocode}
\newdimen\internalmargin 
\internalmargin=\dimexpr\oddsidemargin+1in+1bp\relax
\newdimen\spreadwidth
\spreadwidth=\dimexpr 2\textwidth+2\internalmargin\relax
%
\newdimen\DFwidth 
\newdimen\DFheight 
\newdimen\DFhalfwidth 
\newdimen\DFheight
\newdimen\FigSpace
\newsavebox\DFtotalimage 
\newsavebox\DFimageI 
\newsavebox\DFimageII 
\newsavebox\RFbox
\newdimen\VS@textwidth
\newcount\VS@lines

%    \end{macrocode}
% The following caption-like command recompiles the captions within
% a zero height vertical box and deals with the mandatory and optional
% arguments according to the following syntax: 
%\begin{ttsyntax}
%\cs{DFcaption}\oarg{lof entry}\marg{caption}\oarg{label}
%\end{ttsyntax}
% Notice that the ]lof entry defaults to the full caption text if
% a different text  is not explicitly entered.
% This command is specific  those those display modes that compose
% the caption in vertical mode, therefore the measure is the
% |\textheight|.
%    \begin{macrocode}
\NewDocumentCommand\DFcaption{O{#2} m o}{\refstepcounter{figure}%
  \vtop to 0pt{\hsize=\textheight\parindent=0pt\leavevmode
  Figure \thefigure\quad #2\vss}%
  \addcontentsline{lof}{figure}{\protect\numberline{\thefigure}#1}
  \IfValueT{#3}{\label{#3}}\relax%
}

%    \end{macrocode}
% The |\cleartoevenpage| command may already exist in the document class.
% We prefer to make an absolute redefinition so as to be sure that it
% performs as we need in this package. We tested with the |memoir|
% class that already has such a command, and no problems were found
%
%    \begin{macrocode}
\DeclareRobustCommand\cleartoevenpage{%
  \clearpage\ifodd\value{page}\null\clearpage\fi}
%    \end{macrocode}
%
% Now we define the “real” user macro necessary to chose the
% \meta{display mode} and the various parameters necessary for the
% desired one. See section~\ref{sec:Usage} on page\pageref{sec:Usage}
% for its syntax and the other necessary arguments.  Notice that only
% two arguments are mandatory: the \meta{image file name} and the
% \meta{caption} text. All the other five optional parameters are
% delimited by various delimiters; the first one, \meta{display mode}
% has as default setting the acronym \texttt{SW} for a “Spread-Wide”
% display mode; this mode was the one this package was initially
% conceived for, and its initials recall this priority. All other
% modes came afterwards. the other optional parameters may have a
% default value, but they are ignored by certain modes that don use
% those parameters. As for the previous macro |\DFimage|, here the \meta{lof entry} defaults to the full \meta{caption} text. 
%
% Actually \cs{DFimage} just examines the \meta{display mode}, and
% accordingly passes the necessary parameters to the actual macros
% that implement the various mode displays. It outputs an error
% message if the \meta{display mode} acronym was misspelt. 
%    \begin{macrocode}
\NewDocumentEnvironment{DFimage}{O{SW} m O{#4} m o D(){0.8} D<>{0}}{%
\ifstrequal{#1}{SW}%
  {%
    \SWfigure{#2}[#3]{#4}[#5]%
  }%
  {\ifstrequal{#1}{NF}%
    {%
      \NFfigure{#2}[#3]{#4}[#5](#6)%
    }%
    {\ifstrequal{#1}{RF}% OK
      {%
        \RFfigure{#2}[#3]{#4}[#5]%
      }%
      {\ifstrequal{#1}{VS}%
        {%
          \VSfigure{#2}[#3]{#4}[#5](#6)<#7>%
        }%
        {\ifstrequal{#1}{HS}
          {%
          \HSfigure{#2}[#3]{#4}[#5](#6)%
         }%
          {\PackageWarning{swfigure}%
          {%
            **************************************\MessageBreak
            Option #1\space is not valid           \MessageBreak
            Nothing done                           \MessageBreak
            Image #2\space was not processed       \MessageBreak
            **************************************\MessageBreak}%
          }%
        }%
      }%
    }%
  }%
}%

%    \end{macrocode}
% In the following subsection the five specific display mode macros
% are examined and commented.
%^^A=====================================
% \subsection{The specific \cs{SWfigure} macro for Spread Wide images}
%^^A=====================================
%The specific macro for spread-wide images has the following syntax:
%\begin{ttsyntax}
%\cs{SWfigure}\marg{image file name}\oarg{lof entry}\marg{caption}\oarg{label}
%\end{ttsyntax}
% The various arguments have already been described; as you see the
% \meta{display mode} argument is not there anymore, as well as the
% last two optional arguments of |\DFfigure|.
%
% The working strategy is the following: first the typesetting mode is
% tested and, in case, a filling of the current line is
% performed and, by means of a |\vadjust| \TeX\ native macro, a
% |\newpage| command is executed; in any case a |\cleartoevenpapge|
% is executed so as to be sure to start any action while an even page
% is being processed. Then the initial image to be divided in two
% halves is stored in a box; this box is examined in order
% to find its total width and heigh, so as to be able to compute the
% aspect ratio. All other dimensions are examined to have available
% all the necessary data to display the image halves in the requested
% way.
%
% Notice that the |trim| option to |\includegraphics|, used to
% divide the initial image in two exact halves, (apparently) must
% be used without specifying other options; but, most important,
% it requires real numbers, not macros; therefore we have to make
% use of the usual dirty trick of defining an expanded macro
% |\x| within a group that the macro itself closes upon its
% expansion; in this way the principal part of the |\includegraphics|
% macro contains only keywords and numbers and may be executed
% without errors.
%
% Let $W$ be the total spread width and $w$ be the initial image
% width; let $H$ be the text height and $h$ the initial image height;
% compute the $A_\mathrm{W}$ to be the aspect ratio of the spread
% available space $H/W$. Similarly let $A_\mathrm{fig}$ aspect
% ratio of the initial image; we have to scale the image with a
% scaling factor such that the image keeps its aspect ratio, but
% its scaled height does not exceed the text block height, and
% its scaled width does not exceed the spread width; of course the
% aim is to maintain the scaled image as large as possible therefore 
% we have to chose the most suited of the two scaling factors that
% can be computed from the given data and the inequalities 
% described above.
% In mathematical terms we have to chose the initial image scaling
% factor $S$ such that:
%\begin{equation}
%S= \left\{
%  \begin{array}{lll}
%    w/W &\mathrm{if}& A_\mathrm{fig} \leq A_\mathrm{W}\\
%    h/H &\mathrm{if}& A_\mathrm{fig}   >  A_\mathrm{W}
%  \end{array}
%\right.
%\label{equ:ScalingFactor}
%\end{equation}
% This choice is made by testing the various ratios by means of
% the L3 |\fptest| macro, that computes such ratios and compares them.
% The commented line below shows exactly which lengths are used to
% compute the ratios, and which comparison is executed. Once the
% scaling factors are found the boxes containing the half figures
% are scaled and further on are inserted in floating figure
% environments; we use another dirty trick of matrioska dolls; this
% metaphor describes nested |\makeboxe|s used to mask their actual
% widths, but capable to push the images towards the spread
% spine.
% Eventually the caption is set in the right margin of the right
% spread page, rotated $90^\circ$ counterclockwise.
%    \begin{macrocode}
\NewDocumentCommand\SWfigure{m O{#3} m o}{%
\unless\ifvmode
  \csuse{@bsphack}%
  \vadjust{\vspace{0pt plus1fill}\csuse{@esphack}\newpage}%
\fi
\cleartoevenpage
\setbox\DFtotalimage=\hbox{\includegraphics{#1}}%
\DFwidth=\wd\DFtotalimage \DFhalfwidth=0.5\DFwidth
\DFheight=\ht\DFtotalimage
\FigSpace=\dimexpr\textwidth+\internalmargin\relax
%
\setbox\DFimageI\hbox{\bgroup
\edef\x{\egroup\noexpand\includegraphics*[%
trim = 0 0 \the\DFhalfwidth\space 0]}\x{#1}}%
%
\setbox\DFimageII\hbox{\bgroup
\edef\x{\egroup\noexpand\includegraphics*[%
trim = \the\DFhalfwidth\space 0 0 0]}\x{#1}}%
%
%               h/w            >           H/W
\fptest{\DFheight/\DFhalfwidth > \textheight/\FigSpace}%
  {\edef\DFscalefactor{\fpeval{\textheight/\DFheight}}}%
  {\edef\DFscalefactor{\fpeval{\FigSpace/\DFhalfwidth}}}%
%
\setbox\DFimageI=\hbox{\scalebox{\DFscalefactor}{\usebox{\DFimageI}}}%
\setbox\DFimageII=\hbox{\scalebox{\DFscalefactor}{\usebox{\DFimageII}}}%
%
\begin{figure}[p]%
\vbox to\textheight{\vss\hsize=\textwidth%\
\makebox[\hsize][l]{\makebox[\FigSpace][r]{\box\DFimageI}}\vss}%
\end{figure}\clearpage
%
\begin{figure}[p]%
\vbox to\textheight{\vss\hsize=\textwidth
\makebox[\hsize][r]{\makebox[\FigSpace][l]{\box\DFimageII}%
% Rotated caption in the right page
\makebox(0,0)[lb]{\hspace*{1em}\raisebox{0.5\textheight}{%
\rotatebox[origin=tc]{90}{\DFcaption[#2]{#3}[#4]%
%
}}}}\vss}%
\end{figure}\clearpage}

%    \end{macrocode}
%^^A========================================
%\subsection{The specific \cs{NFfigure} macro for normal full
% page figures}
%^^A========================================
% This code is without surprises, except that it receives from the
% |DFimage| steering macro five arguments, the last (optional) one
% being delimited by round parentheses; by default, it contains the
% value 0.8, but the user can pass to the steering macro a different
% value in order to reduce the actual image size so as to leave
% enough space beneath it for the caption; the user, in facts, does
% not know in advance how many lines would occupy a structured
% complex caption.
%    \begin{macrocode}
\NewDocumentCommand\NFfigure{m O{#3} m o d()}{%
  \begin{figure}[p]
    \includegraphics[width=\linewidth,height=#5\textheight,
                     keepaspectratio]{#1}%
    \caption[#2]{#3}%
    \IfValueT{#4}{\label{#4}}\relax
  \end{figure}
}

%    \end{macrocode}
%^^A========================================
% \subsection{The specific \cs{RFfigure} macro for rotated figures}
%^^A========================================
% There are no new comments to make about this almost standard
% way of displaying a large figure, except, perhaps, the fact
% the instead of invoking the |lscape| package, the whole figure
% is rotated by means of rotating the very box that was used
% to contain the scaled image; the steering macro does not pass
% any \meta{height correction} argument to this macro, because
% it automatically scales the box containing the image and 
% the caption so as to fill up the height or the width of the
% text block.
%    \begin{macrocode}
%\NewDocumentCommand\RFfigure{m o m o}{%
\NewDocumentCommand\RFfigure{m O{#3} m o}{%
      \dimen8=\textwidth\dimen10=\textheight
      \figure[p]\setbox\RFbox=\hbox{%
      \rotatebox[origin=cc]{90}{\parbox[b][\dimen8][c]{\dimen10}%
        {\centering\includegraphics[width=\dimen10, height=\dimen8, 
                        keepaspectratio]{#1}%
          \caption[#2]{#3}%
          \IfValueT{#4}{\label{#4}}\relax%
        }}}%
        \edef\RFx{\fpeval{\ht\RFbox/\textheight}}%
        \edef\RFy{\fpeval{\wd\RFbox/\textwidth}}%
        \fptest{\RFx > \RFy}%
          {\scalebox{\RFx}{\box\RFbox}}%
          {\scalebox{\RFy}{\box\RFbox}}%
        \endfigure}
        
%    \end{macrocode}
%^^A========================================
% \subsection{The specific \cs{VSfigure} macro for tall and slim figures}
%^^A========================================
% This is the most troublesome macro, because it needs to depend
% on the |wrapfig| package, in order to set the image with its
% caption on the external side of the text block, with the text flowing
% around it. Package |wrapfig| has several limitations concerning
% the text that flows around the image. Nevertheless with a “normal”
% textual contents of the text block the result may be very good.
%
% The user should help a little bit the correct performance of
% this macro; for this reason, besides the \meta{height correction}
% factor, the steering macro may pass to it also the \meta{line
% correction} in order to correct the amount of lines the surrounding
% text should be indented; by playing with both corrections
% good results may be obtained.
%
% Notice that only with this macro a test on the initial image
% aspect ratio is performed; should this image have an aspect ratio
% smaller than~2, the process is aborted and a message is printed
% in the output document that informs the user and recommends to
% use another \meta{display mode} acronym.
%
%    \begin{macrocode}
\NewDocumentCommand\VSfigure{m O{#3} m o d() D<>{0}}{%
   \setbox\DFtotalimage=\hbox{\includegraphics{#1}}
   \DFwidth=\wd\DFtotalimage \DFheight=\ht\DFtotalimage
   \edef\VS@aspectratio{\fpeval{\DFheight/\DFwidth}}
   \fptest{ \VS@aspectratio < 2 }%
     {\begin{center}\ttfamily
      ===========================================\\
      Figure #2 is not tall enough.\\
      Consider using a display mode different\\
      from VS; may be NF or RF are better suited.\\
      ===========================================\\
      Nothing done!\\
      ===========================================
      \end{center}
     }%
     {\edef\VS@factor{\fpeval{#5\textheight/\DFheight}}%
   \setbox\DFtotalimage=
     \hbox{\scalebox{\VS@factor}{\box\DFtotalimage}}%
   \edef\VS@width{\fpeval{\VS@factor*\DFwidth}\p@}%
   \setbox\DFtotalimage=\vbox{\hsize=\VS@width%
   \def\@captype{figure}\box\DFtotalimage
   \caption[#2]{#3}%
   \IfValueT{#4}{\label{#4}}\relax}
   \VS@lines=
   \fpeval{round(\ht\DFtotalimage/\baselineskip,0)+#6}%
   \begin{wrapfigure}[\VS@lines]{O}[0pt]{\VS@width}%
   \box\DFtotalimage
   \end{wrapfigure}}%
}

%    \end{macrocode}
%
%^^A=====================================
% \subsection{The specific \cs{HSfigure} macro for spread wide slim
% figures}
%^^A=====================================
%
% The beginning of the macro is not so different from that used
% for the |SWfigure| macro. But this time there is no alternative
% to scale the image taking into account only its width and the
% spread width. The new little problem, now, is to match the total
% height of the two halves of the original wide and slim image,
% so that the texts of the two facing pages have their respective
% first lines perfectly aligned.
%
% Since the right half of the figure contains also the caption
% it is necessary to box again the left page box so as to have
% the same hight and depth as the right page one.
%    \begin{macrocode}
\NewDocumentCommand\HSfigure{m o m o d()}{%
  \unless\ifvmode
    \csuse{@bsphack}%
    \vadjust{\vspace{0pt plus1fill}\csuse{@esphack}\newpage}%
  \fi
  \cleartoevenpage
  \setbox\DFtotalimage=\hbox{\includegraphics{#1}}
  \DFwidth=\wd\DFtotalimage \DFhalfwidth=0.5\DFwidth
  \FigSpace=0.5\spreadwidth% W
%
  \setbox\DFimageI\hbox{\bgroup
  \edef\x{\egroup\noexpand\includegraphics*[%
          trim = 0 0 \the\DFhalfwidth\space 0]}\x{#1}}%
%
  \setbox\DFimageII\hbox{\bgroup
  \edef\x{\egroup\noexpand\includegraphics*[%
         trim = \the\DFhalfwidth\space 0 0 0]}\x{#1}}%
%
  \edef\DFscalefactor{\fpeval{\FigSpace/\DFhalfwidth}}%
%
  \setbox\DFimageI=\hbox{%
    \scalebox{\DFscalefactor}{\usebox{\DFimageI}}}%
  \setbox\DFimageII=\hbox{%
    \scalebox{\DFscalefactor}{\usebox{\DFimageII}}}%
  \setbox\DFimageII=
    \hbox{\dimen10=\linewidth\dimen8\internalmargin
           \vbox{\hsize\DFhalfwidth\parindent\z@
             \box\DFimageII\par
             \leavevmode\hspace*{\dimen8}%
             \vtop{\hsize\dimen10\parindent\z@
               \textwidth=\hsize
               \DFcaption[#2]{#3}[#4]%
              }%
            }%
          }%
  \setbox\DFimageI=\vbox to\ht\DFimageII{\box\DFimageI\vss}%
%
  \begin{figure}[t]
  \makebox[\textwidth][l]{%
    \makebox[\DFhalfwidth][l]{\box\DFimageI}}%
  \end{figure}
  \afterpage{%
    \begin{figure}[t]
    \makebox[\textwidth][r]{%
       \makebox[\DFhalfwidth][r]{\box\DFimageII}}%
    \end{figure}%
  }
}
%    \end{macrocode}
%\begin{center}\setfontsize{15mm}
%\color{red} HAPPY \LaTeX-ING
%\end{center}
%\endinput
%\iffalse
%</package>
%\fi
%\iffalse
%<*readme>
%\fi
%    \begin{macrocode}
This bundle contains file the swfigure.dtx and README.txt files.
This file README.txt contains the licence, the status, and some 
general information. Save both in a .../source/latex/swfigure 
folder either in the main TeX system tree or in your personal 
tree.

This swfigure.dtx file is a self extracting documented one.
Run pdfLaTeX at least twice on this file in order to get all 
references correct, and you obtain the swfigure.pdf and the 
swfigure.sty files. After extraction move the .sty file to 
the .../tex/latex/swfigure folder, and move the .pdf file to 
the .../doc/latex/swfigure folder. From the original folder
.../source/latex/swfigure move all files, except the .dtx and 
the .txt files, to the bin.

The author disclaims any liability from every possible inconvenience 
deriving from the use of this software; you use it at your own risk.

%    \end{macrocode}
%\iffalse
%</readme>
%\fi