% \iffalse
% !TEX TS-program = pdflatex
% !TEX encoding = UTF-8 Unicode
%^^A Ho cercato di renderlo indipendente da m0,emoir (2022-10-24)
% \fi
% \iffalse
%<*internal>
\begingroup
\input docstrip.tex
\keepsilent
\preamble
  ______________________________________________________
  The canoniclayout package for LaTeX
  Copyright (C) 2010 Claudio Beccari 
  All rights reserved

  License information appended

\endpreamble
\postamble
Copyright 2010 Claudio Beccari

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 "author-maintained"

This work consists of this file canoniclayout.dtx, a README file
and the derived files canoniclayout.sty and canoniclayout.pdf.

\endpostamble
\askforoverwritefalse
%
\generate{\file{canoniclayout.sty}{\from{canoniclayout.dtx}{package}}}
%
\def\tmpa{plain}
\ifx\tmpa\fmtname\endgroup\expandafter\bye\fi
\endgroup
%</internal>
% \fi
%
% \iffalse
%<*driver>
\ProvidesFile{canoniclayout.dtx}
%</driver>
%<package>\NeedsTeXFormat{LaTeX2e}[2009/01/01]
%<package>\ProvidesPackage{canoniclayout}%
%<*package>
   [2022/11/01 v.1.0 Text block height equal to paper width]
%</package>
%<*driver>
\documentclass{ltxdoc}
\paperwidth=220mm\paperheight=280mm
\pdfpagewidth=\paperwidth \pdfpageheight=\paperheight
%\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{textcomp}
\usepackage{multicol}
\usepackage{amsmath,array,booktabs}
\usepackage{pict2e}[2009/06/01]%
\usepackage{color}
\hfuzz 10pt

\newcommand*\class[1]{\textsf{#1}}
\newcommand*\pack[1]{\textsf{#1}}
\newcommand*\prog[1]{\textsl{#1}}
\newcommand*\file[1]{\texttt{#1}}
\renewcommand*\meta[1]{{\normalfont\textlangle#1\textrangle}}
\renewcommand*\marg[1]{\texttt{\{\meta{#1}\}}}
\newcommand*\Marg[1]{\texttt{\{#1\}}}
\renewcommand*\oarg[1]{\texttt{[\meta{#1]}}}
\newcommand*\Oarg[1]{\texttt{[#1]}}
\renewcommand*\cs[1]{\texttt{\char92#1}}
\newcommand*\eTeX{$varepsilon$\TeX}

\definecolor{grigio}{gray}{.75}
\allowdisplaybreaks
\begin{document}
\GetFileInfo{canoniclayout.dtx}
\title{Package \pack{canoniclayout}\\[0.5\baselineskip]{\normalsize Version number \fileversion; last
 revision \filedate.}}
\author{Claudio Beccari\thanks{e-mail: \texttt{claudio dot beccari at gmail dot com}}}
 \maketitle
 \DocInput{canoniclayout.dtx}
\end{document}
%</driver>
% \fi
%
% \CheckSum{466}
% \begin{abstract}
% This package  may be used as an extension to the \class{memoir} or as a
% standalone package that might work with any standard class. It tests if
% \class{memoir} was loaded within the preamble, otherwise it does all the
% necessary calculations with the usual facilities of a recent
% \LaTeX\ based engine.
%
% This package computes the page parameters for a canonical layout where
% the text block is placed onto the page in such a way that: $(a)$ its,
% diagonal coincides with the page relevant diagonal, and $(b)$ the circle,
% vertically inscribed within the text block, is also tangent to the page
% sides. The text block width to height ratio is kept equal to the page
% ratio, as well as  the inner to outer and the top to bottom margin
% ratios. See figure~\ref{fig:canoniclayout}
%
% \end{abstract}
%
% \begin{multicols}{2}
% \tableofcontents
% \end{multicols}
%
% \section{Introduction}
% As any user of the \class{memoir} class knows well, this class allows
% to customise the page layout virtually without any limitation; such
% limitations are connected mainly with the user inconsistent data that
% miss to specify necessary information or give unnecessary and
% conflicting information. The same happens when \class{memoir} is not
% being used. In facts, if \class{memoir} is not used, the package computes
% the necessary data that turn out to be correct with the standard document
% classes; they might be correct also with other classes, and users can
% check the correctness by using some commands that are described below,
% within the code documented section.
% 
% Many packages exist in order to specify a specific layout; this package
% \pack{canoniclayout} is another one that computes the page parameters 
% to determine the horizontal and vertical dimensions of the margins and
% the text block. All other details shall be specified by the user, for
% example the dimensions of the stock paper, the trimming widths, and
% therefore the position of the page onto the stock paper, and so on.
% This package deals only with the trimmed page, not with the page and
% stock paper relationship. See the documentation of class \class{memoir}
% in order to deal with stock paper and the details for configuring the
% position of the page to be trimmed on the stock paper. With the standard
% document classes this package works with the standard paper sizes
% that \LaTeX\ can handle. An attempt to use package \pack{geometry} was
% made, but it was abandoned, because this package has limitations due to
% the two digit integer values of element ratios; may be in the future 
% it might be resumed.
%
% \begin{figure}
% \makebox[\textwidth]{\makebox[1.1\textwidth][r]{%
% \unitlength=0.0015\textwidth
% \let\ul\unitlength
%	\begin{picture}(184,320)(0,-20)
%	\put(0,0){\framebox(184,297){}}
%	\put(27,70){\makebox(0,0)[bl]{\color{grigio}\rule{113\ul}{184\ul}}}
%	\put(92,-20){\makebox(0,0)[t]{Golden number canonical layout}}
%	\color{red}
%	\put(92,162){\circle{184}}
%	\linethickness{.2pt}
%	\multiput(0,297)(1.98918918919,-3.21081081082){93}{\line(184,-297){1}}
%	\end{picture}%
% \hfill
%	\unitlength0.0015\textwidth
%	\let\ul\unitlength
%		\begin{picture}(210,330)(0,-20)
%		\put(0,0){\framebox(210,297){}}
%		\put(25,51){\makebox(0,0)[bl]{\color{grigio}\rule{149\ul}{210\ul}}}
%		\put(105,-35){\makebox(0,0)[b]{ISO canonical layout}}
%		\color{red}
%		\put(105,156){\circle{210}}
%		\multiput(0,297)(2.27027027027,-3.21081081082){93}{\line(210,-297){1}}
%		\end{picture}%
% \hfill
%   \unitlength0.001591\textwidth
%   \let\ul=\unitlength
%   \begin{picture}(220,330)(0,-20)
%   		\put(0,0){\framebox(220,280){}}
%   		\put(20.742,33.6){\makebox(0,0)[bl]{\color{grigio}\rule{172.86\ul}{220\ul}}}
%   		\put(110,-35){\makebox(0,0)[b]{Letter paper canonical layout}}
%   		\color{red}
%   		\put(110,143.6){\circle{220}}
%		\multiput(0,280)(2.37837837838,-3.02702702703){93}{\line(220,-280){1}}
%   \end{picture}
% }}%
% \caption{A right page with the relevant diagonal, the text block and the
% canonical circle. In this figure the important pieces of information are
% the page proportions, not the drawing scale; matter of fact the letter
% paper is 17.6~mm shorter than the A4 paper, but the drawings to the same
% height emphasises the relative proportions of the various page parts.}
% \label{fig:canoniclayout}
% \end{figure}
%
% Figure~\ref{fig:canoniclayout} depicts the situation described above;
% the grey rectangle represents the type block; the dotted page diagonal,
% as it can be seen, passes through the diagonal vertices of the type
% block; at the same time the circle is tangent to both the type block
% and the page contour\footnote{Geometrically speaking this sentence is
% meaningless, but the drawings in the picture show what we mean.}.
%.
% It must also be noticed, in the sketch on the left, that the page
% rectangle is a golden one; therefore also the type block is a golden
% rectangle; the inner to the outer margin ratio is the golden section
% value so as this same ratio exists between the top and the bottom margin.
%
% This canonical layout implies that the type block height is equal to the
% page width. Therefore this canonical layout is not suited when the page
% width is small compared to the page height: with the golden
% section\footnote{Here we denote $\phi=1,618\dots$ with the name of
% \emph{golden number}, and its reciprocal $\varphi=0.618\dots$ with the
% name of \emph{golden section}.} this ratio is 0.618.
%
% With the ISO paper shape, in the sketch on the center, this ratio is
% 0.707, and so on.
%
% But it is also evident that this layout is unsuitable with squarish
% pages, such as the sketch on the right where the page proportions are
% those of the USA letter paper size: the type block leaves little space
% for the margins, as it is evident from the properties of the canonical
% circle, which is tangent to the page lateral sides and to the type block
% horizontal sides; to the limit in a square trimmed page the type block
% fills he whole page so that the margins vanish.
%
% \section{The mathematics of the canonical layout}
% With reference to the drawing on figure~\ref{fig:canoniclayout}
% and what has been described in the Introduction, the following formulas 
% may be easily derived:
%\begin{align}
%  &\text{Page shape ratio:}      & x  &=b/h \label{equ:1}   \\
%  &\text{Inner margin:}          & I  &=bx(1-x)/(1+x)       \\
%  &\text{External margin:}       & E  &=b(1-x)/(1+x)        \\
%  &\text{Top margin:}            & T  &=hx(1-x)/(1+x)       \\
%  &\text{Bottom margin:}         & B  &=h(1-x)/(1+x)        \\
%  &\text{Text width:}            & W  &=xb                  \\
%  &\text{Text height:}           & H  &=b                   \\
%  &\text{Circle center abscissa:}& C_x&=b/2                \\
%  &\text{Circle center ordinate:}& C_y&=h(1-x)/(1+x)+b/2    \\
%  &\text{Circle radius:}         & R  &=b/2 \label{equ:10}
%\end{align}
% Notice that the circle center coordinates are referred to the lower
% left corner of the trimmed page.
%
% The results of the above formulas are summarised in
% table~\ref{tab:canoniclayout} for four values of the shape factor 
% including the USA letter paper, that is 8.5~inches wide and 11~inches
% high.
%
%\begin{table}[!b]\centering\let~\enspace
%\hrule
%\caption{Canonical layout ratios referred to the the base (or width, $b$)
% of the trimmed page and its height ($h$).
% The circle coordinates are referred to the lower left corner of the
% trimmed page.}\label{tab:canoniclayout}
%\bigskip
%\begin{tabular}{l@{\qquad}*4{>{$}c<{$}}}
%\toprule
%						&\multicolumn4c{Page ratio $h/b$}			\\
%\multicolumn1c{Quantity}& \phi:1	& 3:2	& \sqrt2:1	& 11:8.5\\
%\midrule
% Base to height ratio 		&0.6180		&0.6666		&0.7071		&0.7727~\\
% Inner margin 						&0.146b		&0.133b		&0.121b		&0.099b \\
% External margin 				&0.236b		&0.200b		&0.172b		&0.128b	\\
% Top margin 							&0.146h		&0.133h		&0.121h		&0.099h \\
% Bottom margin 					&0.236h		&0.200h		&0.172h		&0.128h	\\
% Text width  						&0.618b		&0.666b		&0.707b		&0.773b	\\
% Text height 						& b				& b				& 	b			&b			\\
% Circle center abscissa	& b/2			& b/2			& b/2			&b/2		\\
% Circle center ordinate	& 0.545h	&0.533h		&0.526h		&0.515h	\\
% Circle diameter					& b				& b				& b				& b		  \\
%\bottomrule
%\end{tabular}
%\end{table}
%
% Actually the formulas~\ref{equ:1}--\ref{equ:10}, and their numerical
% values reported in table~\ref{tab:canoniclayout}, are just for general
% information. The actual computations are performed by this package, by
% means of the package built-in facilities. But it can be easily seen that
% as the trimmed page becomes more squarish, the page size ratio tends to
% one, and the margins become smaller and tend to vanish. Therefore it
% seems that this layout is most suited for intermediate page ratios, such
% as the ISO one or the common European book page size of 170\,mm
% by~240\,mm with a ratio $b/h=0.708$.
%
% \section{Usage}
% This package is invoked as usual with:
%\begin{verbatim}
%   \usepackahe{canoniclayout}
%\end{verbatim}
% No options are required; but it is necessary to invoke the package only
% after the page dimensions are known, be they specified by a class option,
% such as, for example, \texttt{a4paper}, or by means of explicit
% \verb|\paperwidth| and \verb|\paperheight| assignments.
% 
% At a convenient moment after calling this package, the trimming margins
% with respect to the trimmed page may be computed and the layout
% rechecked and fixed for consistency. The convenient moment is chosen by
% the package to be at the \cs{begin}\Marg{document} statement execution,
% because only at that moment all required packages are loaded and
% possibly the user's macros are defined and settings are~set.
%
% \section{Font normal size}
% At the same time, if this page layout is chosen, the font normal size
% should be selected on the actual text block width; it is possible that
% the golden ratio type block, on a golden rectangle paper obtained by
% trimming  an ISO A4 stock paper, might be suitable with a 10pt normal
% font size (exactly 66 characters per line with 10pt Latin Modern fonts),
% while a full ISO A4 paper yields a type block that might be more suited
% for a 12pt normal font size (about 86 characters with 10pt Latin Modern
% fonts). The computations might be left, for example, to the used class
% \class{memoir} commands or to the user specifications, but it is
% important that the user is aware of this particular point.
%
% For the user's sake this package provides the command
% |\currentfontletters| (to be used only after |\begin{document}|,
% because this package computations are available only after the
% \cs{begin}\Marg{document} delayed computations are done; in any case the
% command  types out a sentence such as “The number of characters in one
% text line with the current font is $n$'', where the $n$ is the actual
% number printed out. If such number is much outside the ideal Bringhurst
% range of $66\pm5$, it is wiser to chose a larger or smaller normal font
% size. 
%
% In any case the alternative command |\charactersperpage| types out the
% same above information, the number of lines and the estimated number of
% characters per page. These commands are supposed to be useful while
% setting up or revise the complete preliminary parameters for the page
% layout. 
%
% Just to have a comparison, table~\ref{tab:sizes} displays the number of
% characters in one line of text for several fonts and for page sizes A4,
% A5, and~B5.
%
%\begin{table}
%\caption{Text line lengths measured in average number
% of characters in different fonts}\label{tab:sizes}
% \bigskip
% 
% \centering
% \let\b\bfseries \let\i\itshape\tabcolsep=5pt
% \makebox[\textwidth]{\small\begin{tabular}{l*9c}
% \toprule
% Font collection	& \multicolumn3c{A4 paper size}
%                        & \multicolumn3c{A5 paper size}
%                              &\multicolumn3c{B5 paper size}\\
% 				& 10\,pt	& 11\,pt	& 12\,pt	& 10\,pt	& 11\,pt	& 12\,pt	& 10\,pt	& 11\,pt	& 12\,pt	\\
% \midrule
% Times eXtended	&	\i92	&	\i84	&	\i77	&	\b64	&	59	&	\i54	&	\i77	&	\b70	&	\b64	\\
% Latin Modern	&	\i86	&	\i79	&	73	&	60	&	\i55	&	\i51	&	72	&	\b66	&	\b61	\\
% Kepler Project	&	\i83	&	76	&	\b69	&	58	&	\i53	&	\i48	&	\b69	&	\b63	&	58	\\
% Palatino eXtended&	\i82	&	75	&	\b69	&	58	&	\i53	&	\i48	&	\b69	&	\b63	&	57	\\
% \bottomrule
% \end{tabular}}
%\end{table}
%
% It can be seen that the bold typeset numbers satisfy the Bringhurst rule
% with such numbers falling within the range $66\pm5$; the computed numbers
% typeset in normal series and shape are slightly out of the optimal
% Bringhurst range, and may be considered acceptable; those typeset in
% italics are completely out of the interval $66\pm10$ and should not be
% accepted.
% This means that the large A4 paper size may be best used with
% intrinsically large fonts such as the Palatino eXtended (package
% \pack{pxfonts} or \pack{newpxtext}) and the Kepler Project (package
% \pack{kpfonts}).
%
% With the smaller A5 paper size with 10\,pt size fonts, the best ones are
% the Times eXtended (package \pack{txfonts} or \pack{newtxtext}), but
% substantially all the examined fonts are acceptable except those in
% 12\,pt size.
%
% With an intermediate sized paper, such as a B5 ISO size, all the
% considered fonts are acceptable inside or just outside the optimal
% Bringhurst interval.
%
% Many books have trimmed pages sized close the B5 paper size, therefore
% the page layout produced with this package is most useful with medium and
% smaller paper sizes (at least with the ISO ones).

% \section{Conclusion}
% We don't think this package should set also the header and footer
% distances, for example, or should set any specification for the page
% “decorations”, such as underlined headers, or over lined footers, or
% the font size, family, series and shape of the header and footer
% contents. These specifications are of course important, but have nothing
% to do with the relationship between the paper size, the page size and the
% type block size. 
%
%
% \StopEventually{}^^A================================================== 
%
% \section{Documented code}
% The package preliminaries are already in place. We are going to make some
% computations in order to determine the page shape factor $x$; 
% to this end we use the functionalities of the \LaTeX\,3 language, already 
% contained in the \LaTeX\ kernel since 2020; even dimensions and skip
% calculations are being  available since June 2022. But the first thing
% to do is to verify if the package is being used with a sufficiently
% recent version of the \LaTeX\ engine; we test if the kernel has
% a date of at least 2022/06/01
%
% We exploit also the \eTeX\ dimensional computing capabilities, that are
% already embedded in the most recent implementations of the program
% \prog{pdftex}; in fact it must be remarked that these facilities are
% being embedded into the \LaTeX\ based typesetting engine since the
% \TeX~Live distribution of the year 2005. If these facilities are not
% available, either because the \TeX\ distribution is a little too old, or
% because the real \prog{tex} typesetting interpreter, not \prog{pdftex},
% or\prog{luatex}, or \prog{xetex}, is being used, then this entire
% package contents is skipped and nothing is done, except issuing a
% suitable warning.
%\iffalse
%<*package>
%\fi
%    \begin{macrocode}
\IfFormatAtLeastTF{2022/06/01}{}{%
	\PackageWarning{canoniclayout}{%
	The format file is not suited\MessageBreak
	for working with this package.\MessageBreak
	This package is being skipped and \MessageBreak
	its functionalities are not available
	\expandafter\endinput}
\fi}

%    \end{macrocode}
% Then we test if the \class{memoir} class is being used; if that is the
% case, we use its code (identical to the one of the  previous package
% version), otherwise we set up the code for this package internal
% computations..
%
% We delay both codes to the \cs{begin}\Marg{document} statement execution,
% so% we are sure that there are no interferences between the document
% preamble settings and the \pack{canoniclayout}~ones.
%
% The user might start his main document \file{.tex} file according to the
% following model:
%  \begin{flushleft}\obeylines
%  \cs{documentclass}\Oarg{...,a4paper,...}\marg{class}
%  ...
%  \cs{usepackage}\Marg{canoniclayout}
%  ...
%  \cs{begin}\Marg{document}
%  \meta{main document body}
%  \cs{end}\Marg{document}
%  \end{flushleft}
% It is very important that the paper size be established within the
% options of the \cs{documentclass} statement, because this package
% needs the dimensions of the page to deal with.
% \subsection[Using the memoir class]{Using the \class{memoir} class}
%    \begin{macrocode}
\@ifclassloaded{memoir}{%
\AtBeginDocument{%
%    \end{macrocode}
% Now we can determine the page shape factor and we save it into the
% control sequence \cs{CLshape}. The trick of multiplying by \cs{p@}, a
% length of 1\,pt, is a simple trick for reducing the shape ratio to a
% length whose numerical value is exactly the ratio we are interested in.
% By stripping the `pt' part from this dimension value we remain with the
% real number we want to keep in memory. Of course we need also the
% reciprocal value so that we have to perform this calculation two times
% with different factors. This “strange” way of computing real ratios
% derives from the ability of the \eTeX\ engine to scale lengths with a
% higher computational precision than “normal” \TeX\ can do with the
% standard dimension and integer operations. In facts all the computational
% operations are performed within the computer CPU and the intermediate
% first result of the multiplication is kept into a double length register,
% so that no bits are rounded or truncated; the division operation is
% therefore performed with a double length numerator and a single length 
% denominator, so that, again, almost no information is lost at the
% inevitable end of the division algorithm with a non vanishing remainder.
%    \begin{macrocode}
\dimen@=\dimexpr \p@ * \paperwidth / \paperheight\relax
\edef\CLshape{\strip@pt\dimen@}
\dimen@=\dimexpr \p@ * \p@ / \dimen@\relax
\edef\CLinvshape{\strip@pt\dimen@}
%    \end{macrocode}
% We then assign the text height, thanks to the fact that the canonical
% layout has the block height just as long as the page width, thanks to the
% circle property mentioned in the Introduction; in any case 
% formulas~\ref{equ:1}--\ref{equ:10} and  table~\ref{tab:canoniclayout}
% confirm this property for any shape.
%    \begin{macrocode}
\textheight=\paperwidth
%    \end{macrocode}
%
% This done, we can use the internal \class{memoir} commands to determine
% the other layout dimensions.
%    \begin{macrocode}
\settypeblocksize{\textheight}{*}{\CLshape}
\setlrmargins{*}{*}{\CLinvshape}
\setulmargins{*}{*}{\CLinvshape}
\setmarginnotes{7pt}{\dimexpr \foremargin-3\marginparsep}{\onelineskip}

%    \end{macrocode}
%
% We now use the \cs{checkandfixthelayout} so that it prints the page
% parameters to the \file{.log} file.
%    \begin{macrocode}
\checkandfixthelayout
}}%              memoir class end code; start code for standard classes
%    \end{macrocode}
%
% \subsection{Using a standard class}
% Now we define the code in case \class{memoir} is not being used; the
% various computations require a longer code. We need the
% \pack{pict2e} package in order to use the |picture| environment with the
% upgrades foreseen by Leslie Lamport himself and available since 2003.
% We need also package \pack{etoolbox} in order to have an easy access to
% the recent \LaTeX\ kernel hooks. In particular we use the
% \cs{AtEndPreamble} hook command so as to be sure that all settings
% for the paper size and the user preamble settings are already fixed.
%
%    \begin{macrocode}
%
{\RequirePackage{etoolbox,pict2e}%
\AtEndPreamble{%
%
%    \end{macrocode}
% If we use a standard class, we miss the powerful \class{memoir} commands;
% we do not copy them into this package, but we make our own calculations;
% by so doing we have full control also on the necessary parameters for
% drawing the circles and the relevant diagonals. The necessary code is
% going to be longer that that required for the \class{memoir} class,
% also because we have to redefine the four standard page styles.
%
% We compute the relevant values by using equations from~\ref{equ:1}
% to~\ref{equ:10}. Notice that we also create the service macros for
% drawing the circle and the relevant page diagonal in case the user
% wants them to appear in certain pages; see below for more details.
% In any case we must check if the |\color| macro is available; in case
% it is not, we load the \pack{xcolor} package without any options.
%
% Attention: if users want to use colors in their document, they should
% load either package \pack{color} or package \pack{xcolor} with their
% options \textcolor{red}{before} loading this package
% \pack{canoniclayout}. If this is done, users are sure that the package
% loaded within this module will not override their settings; notice that
% \pack{xcolor} redefines some macros that have the same name as those of
% \pack{color}; therefore \pack{color} might be loaded before
% \pack{canoniclayout}, absolutely not \textcolor{red}{after}, otherwise
% some \pack{xcolor} functionalities get corrupted; see the \pack{xcolor}
% documentation. In a different wording: \textcolor{red}{avoid loading
% package \pack{color}, because its functionalities are given
% by \pack{xcolor} and \pack{color} is not required any more!}
%    \begin{macrocode}
\unless\ifcsname color\endcsname \RequirePackage{xcolor}\fi
\newlength\CLinner \newlength\CLouter %             new length registers
\newlength\CLtop \newlength\CLbottom  %              other new registers
\edef\CLx{\fpeval{\paperwidth/\paperheight}}%                 equation 1
\edef\CLxx{\fpeval{(1-\CLx)/(1+\CLx)}}%      for equations 2, 3, 4, 5, 9
\CLinner=\fpeval{\paperwidth*\CLx*\CLxx}\p@%                  equation 2
\CLouter=\fpeval{\paperwidth*\CLxx}\p@%                       equation 3
\CLtop=\fpeval{\paperheight*\CLx*\CLxx}\p@%                   equation 4
\CLbottom=\fpeval{\paperheight*\CLxx}\p@%                     equation 5
\textwidth=\fpeval{\CLx*\paperwidth}\p@%                      equation 6
\textheight=\paperwidth%                                      equation 7
\edef\CLcirclecenterX{\fpeval{\paperwidth/2}}%                equation 8
\edef\CLcirclecenterY{\fpeval{\CLxx*\paperheight+\paperwidth/2}}%  eq. 9
\let\CLcircleradius\CLcirclecenterX%                         equation 10
\edef\CLcirclediameter{\strip@pt\paperwidth}%
\let\CLpageW\CLcirclediameter

%    \end{macrocode}
% Then the text body height is proportional to the text body width trough
% the above determined ratios.
% We now set the other necessary page settings, even if by so doing, it
% becomes impossible to modify them either in the preamble or after the
% \cs{begin}\Marg{document} command. May be in the future this constraint
% may be eliminated.
%    \begin{macrocode}
\normalsize
\headheight=\baselineskip
\headsep=\baselineskip
\footskip=2\baselineskip
\marginparsep=0.1\CLouter\relax
\marginparwidth=0.8\CLouter\relax
\topmargin=\dimexpr\CLtop-\headsep-\headheight-1in\relax
\oddsidemargin=\dimexpr\CLinner-1in \relax
\evensidemargin=\dimexpr\CLouter-1in \relax

%    \end{macrocode}
%
% While \class{memoir} uses its computed results and applies them to all
% pages; with the local calculations it is necessary to redesign the page
% styles; we redefine also the |empty| and |plain| styles so as to have a
% place holder in the otherwise empty headers, such that users can verify
% the correct layout geometry by placing under the text being typeset,
% a red drawing that shows the circle and the diagonal. Since the place
% holder may contain some executable code, it is necessary to have handy
% user macros to set it on or off.
%
%    \begin{macrocode}
\edef\CLdiagX{\strip@pt\paperwidth}%       diagonal horizontal component
\edef\CLdiagY{\strip@pt\paperheight}%        diagonal vertical component
\let\@CLdrawing\relax%                 initially drawings are turned off
%Coordinates of the lower left page corner relative to the header origin
\edef\CLlly{-\expandafter\strip@pt%           both pages corner ordinate
    \dimexpr\paperheight-\CLtop+\headsep}%
\edef\CLllLx{-\strip@pt\CLouter}%   lower left left-page corner abscissa
\edef\CLllRx{-\strip@pt\CLinner}%  lower left right-page corner abscissa
%    \end{macrocode}
% The user commands for turning on and off the canonical layout drawings
% are the following; sometimes it might be necessary to delay them
% to the start of a new page; this may me easily done by using the
% \pack{afterpage} package and its command \cs{afterpage}.
% There are two commands, one for starting to insert drawings
% in consecutive pages, and another to stop this functionality.
%    \begin{macrocode}

\newcommand*\CLstartdrawings{\let\@CLdrawing\CLdrawing}
\newcommand*\CLstopdrawings{\let\@CLdrawing\relax}

\newcommand*\CLdrawing{% 
  \begin{picture}(0,0)\color{red}%
  \unitlength=\p@
  \if@twoside
    \ifodd\value{page}%
      \put(\CLllRx,\CLlly){%     right page: displaces the origin to the
%                                                lower left paper corner
        \put(\CLcirclecenterX,\CLcirclecenterY){\circle{\CLcirclediameter}}
          \put(\CLpageW,0){\line(-\CLdiagX,\CLdiagY){\CLpageW}}
      }
    \else
      \put(\CLllLx,\CLlly){%      left page: displaces the origin to the
%                                                lower left paper corner
        \put(\CLcirclecenterX,\CLcirclecenterY){\circle{\CLcirclediameter}}
        \put(0,0){\line(\CLdiagX,\CLdiagY){\CLpageW}}
      }
    \fi
  \else
    \put(\CLllRx,\CLlly){%         one side: displaces the origin to the
%                                                lower left paper corner
      \put(\CLcirclecenterX,\CLcirclecenterY){\circle{\CLcirclediameter}}
      \put(\CLcirclecenterX,\CLcirclecenterY){%
        \put(0,0){\line(\CLdiagX,\CLdiagY){\CLcircleradius}}
        \put(0,0){\line(-\CLdiagX,-\CLdiagY){\CLcircleradius}}
      }
    }
  \fi
  \end{picture}
}
%    \end{macrocode}
% Now we redefine the four standard page styles so as to set the place
% holder in all the headers; when this place holder is activated by
% \cs{CLstartdrawings}, it gets defined with an environment |picture|
% code extended by the use of package \pack{pict2e}. The environment
% |picture| initial command has zero dimensions, therefore it does not
% occupy any space in the headers. Command \cs{CLstopdrawings} redefines
% the place holder to \cs{relax} and stops all drawings relative
% to the page design.
%    \begin{macrocode}
\def\ps@empty{%
  \let\@mkboth\@gobbletwo
  \def\@oddhead{\makebox[\textwidth][l]{{\@CLdrawing}}}\let\@oddfoot\@empty
  \def\@evenheadhead{\makebox[\textwidth][l]{{\@CLdrawing}}}
  \let\@evenfoot\@empty}
%    \end{macrocode}
% The above settings for an empty page may be useful to get the drawing
% in a completely empty page, without any other object entering the page.
%
% The following redefinition of the |plain| page style is necessary in
% order to get a chapter page overlaid on the red drawing.
%    \begin{macrocode}
\def\ps@plain{\let\@mkboth\@gobbletwo
     \def\@oddhead{\makebox[\textwidth][l]{{\@CLdrawing}}}
     \def\@oddfoot{\reset@font\hfil\thepage\hfil}
     \def\@evenheadhead{\makebox[\textwidth][l]{{\@CLdrawing}}}
     \let\@evenfoot\@oddfoot}
%    \end{macrocode}
% Th redefinition of the |headings| and |myhheadings| page styles are the
% most useful ones because the typeset text is overlaid on the red drawing
% and the user can see the effect of the  canonical layout in the style of
% a typeset page.
%    \begin{macrocode}
\if@twoside
  \def\ps@headings{%
    \let\@oddfoot\@empty\let\@evenfoot\@empty
    \def\@evenhead{\@CLdrawing\thepage\hfil{\slshape\leftmark}}%
    \def\@oddhead{\@CLdrawing{\slshape\rightmark}\hfil\thepage}%
    \let\@mkboth\markboth
    \def\chaptermark##1{%
      \markboth {\MakeUppercase{%
        \ifnum \c@secnumdepth >\m@ne
          \if@mainmatter
            \@chapapp\ \thechapter. \ %
          \fi
        \fi
        ##1}}{}}%
    \def\sectionmark##1{%
      \markright {\MakeUppercase{%
        \ifnum \c@secnumdepth >\z@
          \thesection. \ %
        \fi
        ##1}}}}
\else
  \def\ps@headings{%
    \let\@oddfoot\@empty
    \def\@oddhead{\@CLdrawing{\slshape\rightmark}\hfil\thepage}%
    \let\@mkboth\markboth
    \def\chaptermark##1{%
      \markright {\MakeUppercase{%
        \ifnum \c@secnumdepth >\m@ne
          \if@mainmatter
            \@chapapp\ \thechapter. \ %
          \fi
        \fi
        ##1}}}}
\fi
%    \end{macrocode}
% The |myheadings| page style is much simpler, at least this is the
% definition based on the standard \LaTeX\ class \class{book} code:
%    \begin{macrocode}
\def\ps@myheadings{%
    \let\@oddfoot\@empty\let\@evenfoot\@empty
    \def\@evenhead{\@CLdrawing\thepage\hfil{\slshape\leftmark}}%
    \def\@oddhead{\@CLdrawing{\slshape\rightmark}\hfil\thepage}%
    \let\@mkboth\@gobbletwo
    \let\chaptermark\@gobble
    \let\sectionmark\@gobble
    }

%    \end{macrocode}
%
% At this point we may close the argument of the \cs{AtEndPreamble}
% command and the test on the use of the \class{memoir}~class.
%    \begin{macrocode}
}}% 
%    \end{macrocode}
%\subsection{Service macros}
% Just for testing the number of characters in a line the following macros
% are provided. A couple of scratch dimension registers will be used
% |dimen@| and |\abcwidth|; |\abcwidth| will hold the current lowercase
% alphabet length, and |\dimen@| will hold several values in succession.
% The scratch counters |\count254|, |\count252|, and |count250| will
% receive the final result to be printed out.  \eTeX\ arithmetics will be
% used throughout, and we know this is possible, since we already tested
% it at the very beginning.
%
% Another service macro for the user's sake is |\charactersperpage|; this
% macro typesets the number of characters per line, the numbers of lines
% per page, and eventually their product, a good estimate of the number of
% characters per page. Many text editors have facilities for counting
% a “compuscript” number o words and characters; with this further
% information users may easily estimate the number of pages of their
% document; of course they must make a certain allowance for the front
% and back matter pages, so that they can evaluate the total
% amount of signatures of the whole typeset document; of course, by
% typesetting it with any engine based on \LaTeX\ they know exactly the
% number of pages of the final document, but typographers like
% to know a good estimate before the source \TeX\ files are finished.
%    \begin{macrocode}
\newlength\abc@width
\newcommand*\currentfontletters{%
\settowidth\abc@width{abcdefghijklmnopqrstuvwxyz}\dimen0=26\p@
\dimen0=\dimexpr \textwidth * \dimen0 / \abc@width \relax
\count254=\numexpr \dimen0 / \p@ \relax
\par The number of characters in one text line with the current font is
    \the\count254.\par}
    
\newcommand*\charactersperpage{%
\settowidth\abc@width{abcdefghijklmnopqrstuvwxyz}\dimen0=26\p@
\dimen0=\dimexpr \textwidth * \dimen0 / \abc@width \relax
\count254=\numexpr \dimen0 / \p@ \relax
\count252=\numexpr \textheight / \baselineskip \relax
\count250=\numexpr \count252 * \count254\relax
\quote The number of characters in one text line with the current
    font is \the\count254;\\
    this text block contains \the\count252\ lines;\\
    a rough estimate of the number of characters per page is
    \the\count250.\par
    This might be used to estimate the total number of pages of
    a document.
\endquote}
%    \end{macrocode}
%
%{\centering\color{red} \LARGE Happy \LaTeX{ing} \par}
% \Finale
%\iffalse
%</package>
%\fi
% \endinput
%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

