%
% $Id: callmf.w,v 2.12 1998/03/12 19:11:27 root Exp $
%
% N.B.: A `\date' field is defined for the title page of this document;
%       please change that value whenever the file is modified!
% And don't modify the file under any circumstances.
%
% Included in this NUWEB program are the ARexx scripts `MakeBatch.rexx'
% and `MakeTeXFont.rexx' and `MakeTeXPK.rexx' for automatic font creation
% with METAFONT in the AmiWeb2c system.  To extract these ARexx scripts,
% use the command
%
%    > ami_nuweb -t callmf.w
%
% To create the LaTeX documentation of this file, use the suite of commands
%
%    > ami_nuweb -o callmf.w
%    > latex callmf.tex
%    > ami_nuweb -o callmf.w
%    > latex callmf.tex
%    > latex callmf.tex
%
% You can find the Amiga port of the NUWEB system for language independent
% ``literate programming'' in the AmiNet at directory
%
%    AmiNet:/dev/misc/ami_nuweb0.90.lha
%
% and in the Comprehensive TeX Archive Network at directory
%
%    CTAN:/web/nuweb/nuweb_ami/ami_nuweb0.90.lha
%
% $Log: callmf.w,v $
% Revision 2.12  1998/03/12 19:11:27  root
% It has been suggested by those whose opinion I otherwise
% value highly that the style of programming used in callmf.w,
% most prominently the code layout, was kind of "sick".
% Being rather picky with this particular issue of the
% programming trade, I decided to apply the final spit and
% polish to the source code.  What follows is my personal
% style of programming, developed over the last few years and
% used with any kind of programming language to the greatest
% benefit.  Enjoy!
%
% Revision 2.11  1998/03/08 10:41:27  scherer
% The interface of mktex* has changed, so CallMF must follow suite.
%
% Revision 2.10  1998/03/07  22:05:08  scherer
% The "share/" part of the installation has gone.
%
% Revision 2.9  1998/02/27  23:58:00  root
% "0" war der denkbar schlechteste Wert nach Aufruf von
% MakeTeXFont.rexx. Statt dessen muß der aktuelle RC weitergereicht
% werden.
%
% Revision 2.8  1997/10/24 18:20:15  root
% Extended implementation by Christophe to switch between gsftopk
% and ps2pk.
%
% Revision 2.7  1997/09/07 17:58:36  root
% New (and hopefully permanent) private e-mail address.
%
% Revision 2.6  1997/07/27 13:59:38  root
% New sections from Christophe for use with gsftopk.
%
% Revision 2.5  1997/06/20 19:14:01  Andreas
% We don't care about the 'mode' when creating pk fonts from type1 fonts.
%
% Revision 2.4  1997/05/20 19:05:30  root
% "CURPKFILENAME" may be changed in certain lines of processing.
%
% Revision 2.3  1997/05/14  14:22:37  scherer
% "CallMF" may well be invoked from ShowDVI/DVIPrint prior to any
% "AmiWeb2c" program.  We have to make sure that "SELFAUTOPARENT"
% gets initialized somehow.
%
% Revision 2.2  1997/05/09  11:12:50  scherer
% Thanks to major contributions by Christophe Labouisse "CallMF" provides
% new functionality for converting PostScript Type1 fonts to PK bitmaps,
% font lookup prior to METAFONT/GFtoPK invocation, and some other things.
%
% Revision 2.1  1997/05/09  07:37:01  scherer
% This is "CallMF 2.1" as prepared for "AmiWeb2c 2.1".
%
\documentclass{article}

\usepackage[latin1]{inputenc}

\usepackage{latexsym} % for the `\diamond' marker.
\usepackage{mflogo} % for the `METAFONT' logo.

\language=\USenglish % your TeX system should be set up with `hyphen.cfg'.

\title{CallMF 2 \\
  Automatic Font Generation with \MF}

\author{Andreas Scherer \\
  Rochusstraße 22--24 \\
  52062 Aachen, Germany \\
  \texttt{\small andreas.scherer@@pobox.com}
  \and Christophe Labouisse \\
  \texttt{\small labouiss@@club-internet.fr}}

\date{March 12, 1998}

% We define several ``self-expanding acronyms'' following suggestions by
% John V. Langer in the ``TeX and TUG NEWS'' newsletter, together with
% the award-winning approach by Philip Taylor to take care of situations
% when a period follows the abbreviated versions, concurrently preventing
% a following <digit> from becoming elided with the previous <number>.
% Both features are to be found in `TTN', Volume 3, Number 4, 1994:
\newcommand{\TUG}{\TeX\ Users Group (TUG)%
  \renewcommand{\TUG}{TUG\spacefactor=1000 }}
\newcommand{\TDS}{\TeX\ Directory Structure (TDS)%
  \renewcommand{\TDS}{TDS\spacefactor=1000 }}
\newcommand{\TWG}{\TUG\ Working Group (TWG)%
  \renewcommand{\TWG}{TWG\spacefactor=1000 }}
\newcommand{\PostScript}{\textsc{PostScript}}

\begin{document}

\maketitle

\begin{abstract}
\noindent % Indenting the first line of the `abstract' could be
          % considered indecent behavior.
This is version~2 of the `CallMF' package, the ARexx scripts for
automatic font generation with the Pas\TeX\ drivers \texttt{ShowDVI}
and \texttt{DVIprint} and \texttt{DVIPS}\@@.  This package is
intended to be used with \texttt{AmiWeb2c}~2.
\end{abstract}

\vfill
{\small\noindent\baselineskip=11pt
Copyright \copyright\ 1995, 1997 by Andreas Scherer,
  \copyright\ 1997 by Christophe Labouisse.
All rights reserved.

\noindent
Permission is granted to make and distribute verbatim copies of the
electronic form of this documentation provided that the electronic
copyright notice and this permission notice are preserved on all copies.

\noindent
Permission is granted to copy and distribute modified versions of the
electronic form of this documentation under the conditions for verbatim
copying, provided that the entire resulting derived work is distributed
under the terms of a permission notice identical to this one.\par}

\newpage
\tableofcontents

\newpage
\section{Introduction}

This is the completely revised second edition of the CallMF package for
automatic font generation.  It is intended for use with the AmiWeb2c
system on the \MF\ side and the Pas\TeX\ drivers \texttt{ShowDVI} and
\texttt{DVIprint} as well as \texttt{DVIPS} on the driver side.  In the
following, the three ARexx scripts \texttt{MakeBatch.rexx} and
\texttt{MakeTeXFont.rexx} and \texttt{MakeTeXPK.rexx} are described.

Christophe Labouisse provided changes which added functionality for use of
CallMF with the version of Pas\TeX\ on the ``Meeting Pearls CD.''  Here is
a list of his work:

\begin{itemize}

\item Possibility to copy on demand a pk font from various \texttt{PKVols},
  e.g., from the Meeting Pearls CD.
 
\item Automatic generation of pk fonts from type~1 definitions if
  configured in the \texttt{PSMAPFILENAME} file.

\item Selection of different bases for \MF\ according to the font's
  name\footnote{I don't really know if this useful or not, but since
  I had it with Pas\TeX\ I decided to add it here.  Since there is no
  significant performance gain and since AmiWeb2c does not provide
  special \MF\ bases, this feature is not activated.  You'll have to
  uncomment the code below.}: 

  \begin{itemize}
  \item \texttt{CMBASE} when the font name start with \texttt{cm}.
  \item \texttt{EXBASE}\footnote{I did nothing for dc fonts since these
  fonts are now obsolete.} when the font name start with \texttt{ec}.
  \end{itemize}

\end{itemize}

\section{History}

CallMF~2 is, of course, directly descended from CallMF~1, provided with
either Pas\TeX\ or \MF~2.71.  There have been many hands working on CallMF
since 1991.  CallMF~1 was written and developed by Martin Bokämper, Georg
Heßmann, Jörg Höhle, and Ulrich Wisser, who kindly put their code
into the public domain.  For my own distribution of \MF~2.71 in 1993 and
1994, I made several minor changes to improve the scripts.

Although the names \texttt{MakeBatch.rexx} and \texttt{MakeTeXFont.rexx}
are the same in both versions of CallMF, they should absolutely \emph{not}
be mixed in any way.  CallMF~2 works completely differently than version~1.

Ulrich Wisser's \texttt{MakeTeXFontSet.rexx} script is \emph{not} included
in version~2 of CallMF\@@.  As the author warns about its use, I do not
support it either.  Maybe somebody will come up with a better idea for
creating sets of related fonts automatically.

\section{\TeX\ Directory Structure}

CallMF~2 is fully depending on the new \TDS\ developed by the \TUG\ in
1995.  The main idea is the following directory scheme, which should be
present on all systems soon.

\begin{verbatim}
   </texmf>/fonts/<type>/<supplier>/<typeface>/<file>
\end{verbatim}

\begin{itemize}
\item{\texttt{</texmf>}} is a system-dependent part of the global
directory structure.  My personal installation puts this in
`\texttt{TeXMF:AmiWeb2c-2.1/texmf/}', but the device name is of no
significance.  The binaries of the AmiWeb2c distribution start
their search depending on their own absolute location, so no
specific environment variable needs to be set as long as you do
not change the configuration.  However, the `\texttt{/texmf}' part
should not be made the first level below the device name, that is,
it should not be the first path element next to the colon.
\item{\texttt{<type>}} is one of `\texttt{gf}', `\texttt{log}',
`\texttt{pk}', `\texttt{source}', or `\texttt{tfm}'.
\item{\texttt{<supplier>}} is for example `\texttt{ams}', or
`\texttt{public}' for freely available fonts.
\item{\texttt{<typeface>}} is for example `\texttt{cm}', `\texttt{euler}',
or `\texttt{latex}'.
\item{\texttt{<file>}} is any name of a file residing in this scheme.
\end{itemize}

If the \texttt{<type>} is one of `\texttt{gf}', `\texttt{pk}', or
`\texttt{log}', two extra levels of subdirectories are necessary
to uniquely distinguish the files:

\begin{verbatim}
   </texmf>/fonts/pk/<mode>/<supplier>/<typeface>/<dpi>/<file>
\end{verbatim}

\begin{itemize}
\item{\texttt{<mode>}} may be any entry from the canonical modes
collection `\texttt{modes.mf}' (current version~3).
\item{\texttt{<dpi>}} is an ISO-compliant form of the resolution
dependent subdirectory structure.
\end{itemize}

After the installation of \texttt{cmr10} for \texttt{<mode>=amiga} there
will be the following files according to the new scheme:

\begin{verbatim}
   /texmf/fonts/gf/amiga/public/cm/dpi100/cmr10.gf
   /texmf/fonts/log/amiga/public/cm/dpi100/cmr10.log
   /texmf/fonts/pk/amiga/public/cm/dpi100/cmr10.pk
   /texmf/fonts/source/public/cm/cmr10.mf
   /texmf/fonts/tfm/public/cm/cmr10.tfm
\end{verbatim}

\section{Installation}

\subsection{System requirements}

CallMF is a set of ARexx scripts, so you need William Hawes' ARexx
system installed.  It is included in version~2 of the AmigaOS, but
even for OS~1.3 you can purchase ARexx separately.

\subsection{Automatic installation}

The ARexx scripts are automatically installed by `\texttt{execut}ing' the
shell script `\texttt{callmf.ins}' coming with this distribution.  Do
\emph{not} install CallMF~2 simply as an update in your existing system,
if you do not intend to switch to~\TDS.

\subsection{Setup for use with Pas\TeX}

To make use of CallMF in connection with Georg Heßmann's Pas\TeX\ drivers
\texttt{ShowDVI} and \texttt{DVIprint} set the environment variable
\texttt{CALLMF} to~one~of

\begin{verbatim}
   MakeBatch.rexx
   MakeTeXFont.rexx
\end{verbatim}

The first entry is the preferred choice, it collects all references to
missing fonts in a batch file, calling \texttt{MakeTeXFont.rexx} later.
The second generates missing fonts ``on the fly''.  Due to the excessive
time consumption of \MF\ it should only be used on really fast machines.

\section{Description of the files}

\subsection{\texttt{MakeBatch.rexx}}

This is the revised version of the CallMF `batch' script.  To make use
of it in connection with the Pas\TeX\ drivers \texttt{ShowDVI} and
\texttt{DVIprint} set the environment variable \texttt{CALLMF} to

\begin{verbatim}
   MakeBatch.rexx
\end{verbatim}

These two dvi driver programs evaluate the environment variable
\texttt{CALLMF} and call the ARexx command defined there, whenever
a font file is missing.

\texttt{MakeBatch.rexx} has the following arguments provided by the dvi
drivers \texttt{ShowDVI} and \texttt{DVIprint} directly:

\begin{itemize}
\item{\texttt{FONTNAME}} is the name of the font driver,
e.g., `\texttt{cmr10}'.
\item{\texttt{DPI}} is the resolution of the final output,
e.g., `\texttt{120}'.
\item{\texttt{HBASE}} is the horizontal base resolution,
e.g., `\texttt{100}'.
\item{\texttt{VBASE}} is the vertical base resolution,
e.g., `\texttt{100}'.
\item{\texttt{DRIVER}} is either `\texttt{show}' or `\texttt{print}'
depending on the dvi driver in use.
\item{\texttt{PKFILENAME}} is the resolution dependent file name prepended
with the `\texttt{<dpi>}' part of~\TDS, e.g., `\texttt{dpi120/cmr10.pk}'.
\item{\texttt{PKDIR}} is the complete driver dependent directory path as
specified in the font configuration files, e.g.,
`\texttt{/texmf/fonts/source/public/cm/amiga/}'.  (\texttt{ShowDVI} and
\texttt{DVIprint} use only the first entry in the font configuration file,
which should be set up to the `\texttt{<mode>}' only.  See the examples
coming with the AmiWeb2c system.)
\end{itemize}

Here is the overall layout of the \texttt{MakeBatch.rexx} script.
For ARexx it is essential to find a C~like comment in the first
line of~a~script.
@o MakeBatch.rexx
@{/* This ARexx program was automatically created by NUWEB from
   the master source file `callmf.w'.  Do not edit by hand! */
@<Files and scripts for \texttt{MakeBatch.rexx}@>
Address COMMAND
@<Set up the batch file@>
@<Get the calling parameters@>
@<Fix any \texttt{show} entries to a single \texttt{<mode>}@>
@<Create a new line for the batch file@>
@<Enter the new line in the batch file, but not twice@>
Exit 0
@}

\subsection{\texttt{MakeTeXFont.rexx}}

This is the kernel script of CallMF~2.  Here the necessary steps for
generation of \TeX\ fonts with \MF\ are processed automatically.  Also
format conversion and installation are performed.

It has the following arguments provided by \texttt{ShowDVI} and
\texttt{DVIprint} directly, just the same as for \texttt{MakeBatch.rexx}:

\begin{itemize}
\item{\texttt{FONTNAME}} is the name of the font driver loaded by~\MF,
e.g., `\texttt{cmr10}'.
\item{\texttt{DPI}} is the resolution of the final output,
e.g., `\texttt{120}'.  This together with the next parameter
determines the `\texttt{mag}' value.
\item{\texttt{HBASE}} is the horizontal base resolution of the
\texttt{<driver>} used, e.g., `\texttt{100}' for `\texttt{amiga}'.
\item{\texttt{VBASE}} is the vertical base resolution,
e.g., `\texttt{100}'.  This value is not used in the script.
\item{\texttt{DRIVER}} is either `\texttt{show}' or `\texttt{print}'
and is ignored in this script.  (It has a meaning
in \texttt{MakeBatch.rexx}, though.)
\item{\texttt{PKFILEARG}} is the resolution dependent file name including
the lowest level of the directory path , e.g., `\texttt{dpi120/cmr10.pk}'.
Although this is in fact part of the \TDS, this value is currently not used.
\item{\texttt{PKDIRARG}} is the driver dependent directory path in \TDS\
notation, e.g., `\texttt{/texmf/fonts/source/public/cm/amiga/}'.  This value
is only used to determine the \texttt{<mode>}, so it could contain virtually
anything as long there is a valid \texttt{<mode>} name padded with slashes,
e.g., this entry could as well be~`\texttt{/amiga/}'.
\end{itemize}

Here is the overall layout of \texttt{MakeTeXFont.rexx}.  For ARexx it is
essential to find a C~like comment in the first line of~a~script.
@o MakeTeXFont.rexx
@{/* This ARexx program was automatically created by NUWEB from
   the master source file `callmf.w'.  Do not edit by hand! */
@<User definable stuff in \texttt{MakeTeXFont.rexx}@>
@<The main body of \texttt{MakeTeXFont.rexx}@>
@<Local procedures for \texttt{MakeTeXFont.rexx}@>
@}

\subsection{\texttt{MakeTeXPK.rexx}}

Although the Pas\TeX\ drivers conveniently append entries to
\texttt{MakeTeXFont.sh} when fonts at certain resolutions are missing, in
rare cases one might want to create a pk file by hand.  Of course, entering
a similar line as created by \texttt{MakeBatch.rexx} into
\texttt{MakeTeXFont.sh} would be appropriate, but here is an ``expert
interface'' providing simpler and faster access to the
\texttt{MakeTeXFont.rexx} script.  The first three of the following
arguments are required to get it going, the \texttt{MODE} name is optional
and will be guessed in rare cases:

\begin{itemize}
\item{\texttt{FONTNAME}} is the name of the font driver loaded by~\MF,
e.g., `\texttt{cmr10}'.
\item{\texttt{DPI}} is the resolution of the final output,
e.g., `\texttt{120}'.  This together with the next parameter
determines the `\texttt{mag}' value.
\item{\texttt{HBASE}} is the horizontal base resolution of the
\texttt{MODE} used, e.g., `\texttt{100}' for `\texttt{amiga}'.
\item{\texttt{MODE}} determines the \texttt{<mode>} \MF\ will be
called with, e.g., `\texttt{amiga}' or `\texttt{deskjet}'.  This
should match the \texttt{HBASE} value!
\end{itemize}

Here is the overall layout of \texttt{MakeTeXPK.rexx}.  For ARexx it is
essential to find a C~like comment in the first line of~a~script.
@o MakeTeXPK.rexx
@{/* This ARexx program was automatically created by NUWEB from
   the master source file `callmf.w'.  Do not edit by hand! */
Address COMMAND
@<Reference the main script@>
@<Parse the calling parameters@>
@<Strip a \texttt{.tfm} extension@>
@<Set up the additional arguments@>
@<Call the main script \texttt{MakeTeXFont.rexx}@>
Exit RC
@}

\subsection{\texttt{fontvols}}

The file \texttt{fontsvols} will be used by \texttt{MakeTeXFont.rexx} to
detect the locations of some archived pk files. It has to be placed in
\texttt{</texmf>/web2c/} and will consist of several lines, one for each
base resolution, with the following format:
 
\begin{verbatim}
  <FontVol>=<base_res>d.<res1>[.<res2>]*
\end{verbatim}
 
\noindent where

\begin{description}

\item [\texttt{FontVol}] is the name of the logical volume to explore to
  find the fonts from the mode corresponding to \texttt{\emph{base\_res}}.

\item [\texttt{base\_res}] is the base resolution defining the mode.

\item [\texttt{res1,...,resN}] are the horizontal resolutions whose pk
  files can be found.

\end{description}

When we find a line with the matching mode and resolution, we look for
\verb+<FontVol>:<dpi>/<fontname>.<dpi>pk+. Here is a sample
\texttt{fontvols} which is suitable for the ``Meeting Pearls~IV''~CD.
 
@o fontvols
@{PKVol-nec=180d.162.180.197.216.237.259.284.311.373.448.537.645
PKVol-deskjet=300d.270.300.329.360.394.432.473.518.622.746.896.1075
PKVol-nechi=360d.324.360.394.432.473.518.568.622.746.896.1075.1290
PKVol-ljfour=600d.600.657.720.789.864.946.1037.1244.1493.1792.2150
 
PKVol-amiga=100d.40.44.48.53.58.63.69.75.76.82.83.90.91.99.100.108.109.110.120.131.132.143.144.157.158.172.173.189.190.207.226.228.249.272.299.326.358.430
@}

\subsubsection{Differences to the original \texttt{fontvols}}

\begin{itemize}

\item The original file had to be placed in the \texttt{TeX:config}
  directory but this one has to be placed in \texttt{</texmf>/web2c}.

\item The original \texttt{fontvols} file supported volumes for device with
  a different horizontal and vertical resolutions like the fax mode.
  Currently, the script \texttt{MakeTeXFont.rexx} does \emph{not}
  support this.

\end{itemize}

\subsection{\texttt{ps2pk.map}}

The file \texttt{ps2pk.map} will be used to detect the parameters to be
used to build pk files from \PostScript\ Type~1 fonts.  It has to be
placed in the \texttt{<texmf>/dvips} directory.  Its structure is the
same than the other \texttt{.map} files located there.  I deliberately
chose to have a separate file rather than using \texttt{psfonts.map} to
allow the user to configure which fonts he likes to send as bitmap.

Here is a small example made from parts of various \texttt{.map} files.
More information about the format of this file can be found in the
\texttt{dvips} documentation.

@o ps2pk.map
@{padb8r AGaramond-Bold "TeXBase1Encoding ReEncodeFont" <8r.enc <padb8a.pfb
padbo8r AGaramond-Bold " .167 SlantFont TeXBase1Encoding ReEncodeFont " <8r.enc <padb8a.pfb
pcrr8rn Courier ".85 ExtendFont TeXBase1Encoding ReEncodeFont" <8r.enc <pcrr8a.pfb
padra AGaramondAlt-Regular <padra.pfb
@}

\section{Implementation of the scripts}

\subsection{\texttt{MakeBatch.rexx}}

\subsubsection{User definable part}

This is the complete set of files necessary for CallMF~2 to work.
You may change these entries to accommodate your personal system setup.
@d Files and scripts for \texttt{MakeBatch.rexx}
@{BATCHNAME = "S:MakeTeXFont.sh"
@<Reference the main script@>
@}

This name might also need adaption.
@d Reference the main script
@{MAKETEXFONT = "MakeTeXFont.rexx"
@| MAKETEXFONT @}

\subsubsection{Fixed part}

First, \texttt{MakeBatch.rexx} makes sure it is able to write (or more
often append) entries to the batch file.
@d Set up the batch file
@{If ~Exists( BATCHNAME ) Then Do
  If ~Open( BATCHFILE, BATCHNAME, "Write" ) Then Do
    Say "MakeBatch: Could not create" BATCHNAME || "!"
    Exit 10
  End
  Writeln( BATCHFILE, ";# Batchfile for font generation" )
  If ~Close( BATCHFILE ) Then Do
    Say "MakeBatch: Error during creation of" BATCHNAME || "!"
    Exit 10
  End
  Protect BATCHNAME "Add s"
  Say "MakeBatch: Batchfile" BATCHNAME "created."
End
@}

Here is the complete list of parameters to the \texttt{MakeBatch.rexx}
script as described earlier.
@d Get the calling parameters
@{Parse Arg PARAMETERS
Parse Value PARAMETERS With FONTNAME DUMMY
Parse Value DUMMY With DPI HBASE VBASE DUMMY
Parse Value DUMMY With DRIVER PKFILENAME PKDIR .
@}

Only \texttt{ShowDVI} and \texttt{DVIprint} of version ${}\geq1.08$
supply arguments \texttt{<drivertype>} (\texttt{show}/\texttt{print})
and \texttt{<pkfilename>} (for example `\texttt{dpi120/cmr10.pk}',
depending on the font configuration files \texttt{ShowDVI.fnt} and
\texttt{DVIprint.fnt}).

Only \texttt{ShowDVI} and \texttt{DVIPrint} of version ${}\geq1.10$
supply the argument \texttt{<pkdir>} (for example
`\texttt{/texmf/fonts/source/public/cm/amiga/}').  For the purposes
of CallMF~2, only the \texttt{<mode>} part of \texttt{<pkdir>} would
suffice, e.g., `\texttt{/amiga/}'.

To save a considerable amount of disk space, all `\texttt{show}' entries
are redirected to the standard `\texttt{amiga}' mode.  For example, the
Pas\TeX\ mode `\texttt{OneTwoZero}' will use the 120~dpi fonts generated
for `\texttt{mag=1.2}' of mode `\texttt{amiga}'.
@d Fix any \texttt{show} entries to a single \texttt{<mode>}
@{If "show" = DRIVER Then Do
  HBASE = "100"
  VBASE = "100"
  PKDIR = "/amiga/"
  PARAMETERS = FONTNAME DPI HBASE VBASE DRIVER PKFILENAME PKDIR
End
@}

Uncomment the first lines to see what \texttt{MakeBatch.rexx} intends
to~do.  Else it is very simple, just hand over all \texttt{PARAMETERS}
to the kernel script that will do the actual font generation.  I~thought
about modifying some of the unused entries, but it doesn't seem worthwhile
(and it is a good test for \texttt{MakeTeXFont.rexx}).
@d Create a new line for the batch file
@{/*
 * Say "MakeBatch: Font named =" FONTNAME "with dpi =" DPI
 * Say "and base x =" HBASE || ", y =" VBASE
 * If "" ~= DRIVER Then
 *   Say " for driver =" DRIVER || ", pkname =" PKFILENAME
 */
MESSAGE = "rx" MAKETEXFONT PARAMETERS
@}

Would it be better to `\texttt{Search}' for \texttt{FONTNAME},
\texttt{DPI}, \texttt{HBASE}, and \texttt{VBASE} only?
@d Enter the new line in the batch file, but not twice
@{Search ">NIL:" BATCHNAME '"'MESSAGE'"'

If 0 ~= RC Then
  @<The line does not yet exist, append it to the batch file@>
Else
  Say "MakeBatch: Entry already exists!"
@}

@d The line does not yet exist, append it to the batch file
@{Do
  @<Open the batch file for appending@>
  DUMMY = Writeln( BATCHFILE, MESSAGE )
  @<Close the batch file@>
  Say "MakeBatch: New entry added for" FONTNAME DPI "dpi"
End
@}

@d Open the batch file for appending
@{If ~Open( BATCHFILE, BATCHNAME, "Append" ) Then Do
  Say "MakeBatch: Can't open" BATCHNAME "to add new entry"
  Exit 10
End
@}

@d Close the batch file
@{If ~Close( BATCHFILE ) Then Do
  Say "MakeBatch: Error while adding new entry!"
  Exit 10
End
@}

\subsection{\texttt{MakeTeXFont.rexx}}

\subsubsection{User definable part}

Although considerable effort has been expended to make CallMF~2 fully
compliant to the new \TDS\ in the latest version I could find, there are
still some system dependent parts for the individual user to change.
\label{UserStuff}
@d User definable stuff in \texttt{MakeTeXFont.rexx}
@{@<Special introduction@>
@<Files and directories@>
@<The programs used@>
@<The default bases@>
@<Final decision@>
@}

Here we set up the script for a good start.  User breaks will be
handled in a special subroutine.  Several commands are addressed
to the operating system.  We try to keep system load as low as
possible.
@d Special introduction
@{Signal On BREAK_C
Signal On BREAK_D
Pragma( "Priority", -5 )
Address COMMAND
UnSetEnv "LAST_FONT_CREATED"
@| BREAK_C BREAK_D @}

As soon as your \TeX\ system is fully compliant to the \TDS\ developed by
\TUG, you should not have to change anything in this section.  The script
ensures that the environment variable `\texttt{SELFAUTOPARENT}' is set
prior to the first vital actions.  As soon as one of the AmiWeb2c programs
has run, this and some other variables are set, but in case you invoke
ShowDVI or DVIPrint after booting the system, a trick has to be applied
by calling `kpsewhich' once.

The names of the subdirectories are fairly standardized (except for the
CallMF specific `\texttt{/log}', not described in the \TDS\ draft).  CallMF
only has to handle bitmapped fonts, so there is no need to add entries for
`\texttt{/vf}' or~the~like.
@d Files and directories
@{PARENTDIR = MyGetEnv( "SELFAUTOPARENT" )
If "" = PARENTDIR Then Do
  Address COMMAND "kpsewhich --help > NIL:"
    /* Dummy command that sets \texttt{SELFAUTO} */
  PARENTDIR = MyGetEnv( "SELFAUTOPARENT" )
End

FONTSDIR = PARENTDIR || "/texmf/fonts"

SOURCEDIR = FONTSDIR || "/source"
GFDIR     = FONTSDIR || "/gf"
PKDIR     = FONTSDIR || "/pk"
TFMDIR    = FONTSDIR || "/tfm"
LOGDIR    = FONTSDIR || "/log"
AFMDIR    = FONTSDIR || "/afm"
TYPE1DIR  = FONTSDIR || "/type1"

DVIPSDIR  = PARENTDIR || "/texmf/dvips"

/* PSMAPFILENAME = DVIPSDIR || "/ps2pk.map" */
PSMAPFILENAME = "gsftopk.map" /* À faire : variable d'environnement */

FONTFILENAME = PARENTDIR || "/texmf/web2c/fontvols"

MASTERLOG = LOGDIR || "/MakeTeXFont.log"
@| FONTFILENAME fontvols PSMAPFILENAME ps2pk.map DVIPSDIR
FONTSDIR AFMDIR GFDIR LOGDIR PKDIR SOURCEDIR TFMDIR TYPE1DIR
MakeTeXFont.log PARENTDIR SELFAUTOPARENT @}

\MF\ and companion.  \texttt{PATH} should be set appropriately.
The definition of \texttt{KPSEWHICH} should also be here, but we
need to know \texttt{HBASE} first. We also check the variable
\texttt{T1CONVPRG} to choose \texttt{GSFTOPK} or \texttt{PS2PK}.

@d The programs used
@{VIRMF = GetClip( "VIRMF" )
If "" = VIRMF Then
  VIRMF = "MF"
GFTOPK = GetClip( "GFTOPK" )
If "" = GFTOPK Then
  GFTOPK = "GFtoPK"
PS2PK = GetClip( "PS2PK" )
If "" = PS2PK Then
  PS2PK = "PS2PK"
GSFTOPK = GetClip( "GSFTOPK" )
If "" = GSFTOPK Then
  GSFTOPK = "GSFTOPK"
T1CONVPRG = MyGetEnv( "T1CONVPRG" )
If "" = T1CONVPRG Then
  T1CONVPRG = "PS2PK"
@| VIRMF GFTOPK PS2PK GSFTOPK T1CONVPRG @}

We define the names of several bases, \texttt{CMBASE} for computer modern
fonts, \texttt{EXBASE} for ec fonts, and \texttt{NORMALBASE} for everything
else.
@d The default bases
@{NORMALBASE = MyGetEnv( "MFBASE" )
If "" = NORMALBASE Then
  NORMALBASE = "mf"

CMBASE = "cmbase"
EXBASE = "exbase"
@| NORMALBASE EXBASE CMBASE plain.mf cmbase exbase @}

Should gf files be stored for later reference?  Set this to `\texttt{1}'
if you don't want the gf files to be deleted after they are converted to
pk files.  (You can always recreate the gf file to a given pk file with
\texttt{PKtoGF} later.)
@d Final decision
@{KEEPGFFILES = 0
@| KEEPGFFILES @}

\subsubsection{Fixed part}

There is no user definable stuff below this point.  Really.  We do some
timing on the fly.  This covers almost the complete run including but not
limited to the conversion steps and the actual file installation.
@d The main body of \texttt{MakeTeXFont.rexx}
@{DUMMY = Time( "Reset" )
@<Do the actual work@>
ELAPSED = Time( "Elapsed" )
LOGSTRING = "created in" ELAPSED % 3600
LOGSTRING = LOGSTRING || ":" || Right( ELAPSED % 60 // 60, 2, "0" )
LOGSTRING = LOGSTRING || ":" || Right( ELAPSED % 1 // 60, 2, "0" )
Call Log( LOGSTRING )
If "nullmode" = MODE Then
  Call MySetEnv( "LAST_FONT_CREATED", TFMFILENAME )
Else
  Call MySetEnv( "LAST_FONT_CREATED", PKFILENAME )
Exit 0 /* This is the end */
@| ELAPSED LOGSTRING @}

@d Do the actual work
@{@<Get the arguments this script is called with@>
@<Create some internal defaults we need@>
@<Generate or find the font@>
@<Install the files at the appropriate places@>
@}

The arguments of the CallMF~2 scripts are exactly those of version~1 for
compatibility with the Pas\TeX\ drivers, but the parameters are used
differently, i.e, more intensely.  Do \emph{not} mingle the two versions.

The definition of \texttt{KPSEWHICH} may look a little bit odd, but we have
to do it like this since \texttt{kpsewhich} erases \verb+MAKETEX_MODE+ and
\verb+MAKETEX_DPI+ if there is no explicit mode and resolution in the
commandline.
@d Get the arguments this script is called with
@{Parse Arg FONTNAME DPI HBASE VBASE DRIVER PKFILEARG PKDIRARG .

KPSEWHICH = "kpsewhich -dpi=" || HBASE
KPSEWHICH = KPSEWHICH "-mode=" || MyGetEnv( "MAKETEX_MODE" )

@<Choose the base according to the fontname@>

LOGSTRING = "Making font" FONTNAME "at" DPI "dpi and base"
LOGSTRING = LOGSTRING "(" || HBASE || "," VBASE || ")"
Say LOGSTRING
@| FONTNAME DPI HBASE VBASE DRIVER PKFILEARG PKDIRARG KPSEWHICH @}

We choose the base to be used by looking at the first two characters of
the font name.  \texttt{ec} means \texttt{EXBASE}, \texttt{cm} means
\texttt{CMBASE}, and everything else will be \texttt{NORMALBASE}.

Note: AmiWeb2c does not assume or provide more than \texttt{mf.base},
so this code is reduced to the default.
Uncomment the other stuff if you like.
@d Choose the base according to the fontname
@{/* Select
  When SubStr( FONTNAME, 1, 2 ) = "ec" Then BASE = EXBASE
  When SubStr( FONTNAME, 1, 2 ) = "cm" Then BASE = CMBASE
Otherwise */
  BASE = NORMALBASE
/* End */
@| FONTNAME BASE NORMALBASE EXBASE CMBASE @}
  
These files will show up in the current directory later and
will be copied to the appropriate places further below.
Only the gf filename has the `extended' form used by~\MF, the
others will be stored in subdirectories that declare the resolution,
the filenames have `short' extensions.  \texttt{OLDPKFILENAME} is used
to locate the pk fonts on CDs using the `long' names.
@d Create some internal defaults we need
@{CURGFFILENAME  = FONTNAME || "." || DPI || "gf"
CURPKFILENAME  = FONTNAME || ".pk"
OLDPKFILENAME  = FONTNAME || "." || DPI || "pk"
CURLOGFILENAME = FONTNAME || ".log"
CURTFMFILENAME = FONTNAME || ".tfm"

LOGFILENAME = FONTNAME || ".log"
@| CURGFFILENAME CURPKFILENAME OLDPKFILENAME CURLOGFILENAME
CURTFMFILENAME LOGFILENAME @}

Check the top level directories for the respective files.
@d Create some internal defaults we need
@{Call SafeMakeDir( LOGDIR )
Call SafeMakeFile( MASTERLOG )
Call SafeMakeDir( PKDIR )
Call SafeMakeDir( TFMDIR )

If 0 ~= KEEPGFFILES Then
  Call SafeMakeDir( GFDIR )
@}

We first try to look in the pk volumes described in \texttt{FONTFILENAME}
to see if we can find an appropriate font, then we try to see if we may
generate a pk file from a type~1 font located in \texttt{PSMAPFILENAME} and
if none of these work we fallback on \MF.
@d Generate or find the font
@{@<Determine the mode we're in@>
@<Initialize multi-mode switches@>
FONTPKOK = 0
@<Get the font from PKVols@>
If 0 = FONTPKOK Then Do
  @<Generate font from type 1 definition@>
  If 0 = FONTPKOK Then Do
    @<Run {\MF} to generate the font@>
    @<Run \texttt{GFtoPK} to convert the pixel format@>
    @<Determine the source path@>
    @<Determine the supplier and the typeface@>
  End
End
@| FONTPKOK @}

Since the three methods to get a bitmap font do not produce the same file
we must add auxiliary variables to remember later what we should do.
@d Initialize multi-mode switches
@{CARETFM = 1
CAREGF = 1
DELETECURPK = 1
@| CARETFM CAREGF DELETECURPK @}

With the new directory structure, \texttt{ShowDVI} and \texttt{DVIprint}
already provide the \texttt{<mode>} we want to call \MF~with.  It comes
as the rightmost subdirectory name in the \texttt{PKDIRARG} argument.
The font configuration files can be set up so that only the \texttt{<mode>}
part padded with single slashes is supplied.
@d Determine the mode we're in
@{MODE = Left( PKDIRARG, LastPos( "/", PKDIRARG ) - 1 )
MODE = SubStr( MODE, LastPos( "/", MODE ) + 1 )
@| MODE @}

\subsubsection{Copying the font from \texttt{fontvols}}

We first look in the \texttt{FONTFILENAME} file to get the list of the
directories where we can find precalculated pk files.
@d Get the font from PKVols
@{If Open( "fontfile", fontfilename, "read" ) Then Do
  Do Until EOF( "fontfile" )
    @<Analyse each line for the matching entry@>
  End
  If ~Close( "fontfile" ) Then
    Say "Can't close file" FONTFILENAME || "!"
End
@}

@d Analyse each line for the matching entry
@{LINE = ReadLn( "fontfile" )
If 0 > Pos( ";", line ) Then
  LINE = Left( LINE, Pos( ";", LINE ) - 1 )
Parse Var LINE DISK || "=" || DDD || "d." || LINE
If DDD = HBASE Then
  Do Until LINE = ""
    Parse Var LINE DIR || "." || LINE
    If DIR = DPI Then Do
      If Exists( DISK || ":" || DPI || "/" || OLDPKFILENAME ) Then Do
        @<Adjust parameters for copied pk@>
        @<Create a dummy logfile@>
        @<Determine the supplier and the typeface for copied pk@>
        FONTPKOK = 1
        Say "PK file copied from" CURPKFILENAME
      End
    End
  End
@}

We adjust \texttt{CURPKFILENAME} to be the source pk file and nullify
\texttt{DELETECURPK}, \texttt{CARETFM}, and \texttt{CAREGF}.
@d Adjust parameters for copied pk
@{CURPKFILENAME = DISK || ":" || DPI || "/" || OLDPKFILENAME
DELETECURPK = 0
CARETFM = 0
CAREGF = 0
@}

We create a log file to keep track of the copy.  We also set the
\texttt{KPSERESULT} environment variable to find out the \texttt{SUPPLIER}
and the \texttt{TYPEFACE} later.
@d Create a dummy logfile
@{"Echo >" CURLOGFILENAME "PK file copied from" CURPKFILENAME
"Date >>" CURLOGFILENAME
"setenv KPSERESULT `" || KPSEWHICH || " " || FONTNAME || ".mf`"
@}

@d Determine the supplier and the typeface for copied pk
@{SUPPLIER = SubStr( MyGetEnv( "KPSERESULT" ), Length( SOURCEDIR ) + 1 )
SUPPLIER = Left( SUPPLIER, LastPos( "/", SUPPLIER ) - 1 )

TYPEFACE = SubStr( SUPPLIER, LastPos( "/", SUPPLIER ) )
SUPPLIER = Left( SUPPLIER, LastPos( "/", SUPPLIER ) - 1 )
@| SUPPLIER TYPEFACE @}

\subsubsection{Creating a font using \texttt{ps2pk} or \texttt{gsftok}}

We try to create a bitmap from a type~1 font. We can use either
\texttt{gsftopk} or \texttt{ps2pk}. The selection is made by positionning
a environment variable: \texttt{T1CONVPRG}. The default is to use
\texttt{ps2pk}. So if there is no \texttt{T1CONVPRG} variable or if the
variable's content is not \texttt{GSFTOPK}\footnote{case sensitive} then
\texttt{ps2pk} will be selected.

\texttt{gsftopk} is the more powerful of the two and is able, for instance,
to work with multiple master fonts. Howerever it is \emph{really} more
complicated to install since it requires \texttt{ghostscript} to be
installed first and is also \emph{more} memory consuming than
\texttt{ps2pk}.

@d Generate font from type 1 definition
@{If "GSFTOPK" = T1CONVPRG Then Do
    @<Generate font from type 1 definition with gsftopk@>
End; Else Do
    @<Generate font from type 1 definition with ps2pk@>
End
@}

Since \texttt{gsftopk} erase \texttt{MAKETEX_BASE_DPI} and
\texttt{MAKETEX_MODE} so we save them before the call and restore them
after. Starting with \texttt{gsftopk}~1.15, an environment variable is set
to keep track of where the \texttt{tfm} file is. This is really useful
since a call to \texttt{kpsewhich} is really time consuming\footnote{at
least on my machine}. It may change in a near future since this method is
not applicable on Unix systems. Since we call \texttt{gsftopk} for every
font we assume that a \texttt{RC} not equal to \texttt{0} is most likely
not a type 1 font.

@d Generate font from type 1 definition with gsftopk
@{Say "Trying to create pk with:"
Say GSFTOPK ">gsftopk.log --dosnames --mapfile" PSMAPFILENAME FONTNAME DPI
SAVEMTBD = MyGetEnv( "MAKETEX_BASE_DPI" )
SAVEMTM = MyGetEnv( "MAKETEX_MODE" )
GSFTOPK ">gsftopk.log --dosnames --mapfile" PSMAPFILENAME FONTNAME DPI
Call MySetEnv( "MAKETEX_BASE_DPI", SAVEMTBD )
Call MySetEnv( "MAKETEX_MODE", SAVEMTM )
If 0 = RC Then Do
  G2PTFM   = MyGetEnv( "GSFTOPKTFM" )
  If "" ~= G2PTFM Then Do
    SUPPLIER = Substr( G2PTFM, Length( TFMDIR ) + 1 )
    SUPPLIER = Left( SUPPLIER, LastPos( "/", SUPPLIER ) - 1 )
    TYPEFACE = Substr( SUPPLIER, LastPos( "/", SUPPLIER ) )
    SUPPLIER = Left( SUPPLIER, LastPos( "/", SUPPLIER ) - 1 )
    DELETECURPK = 1
    CARETFM = 0
    CAREGF = 0
    FONTPKOK = 1
    MODE = "modeless"
    "rename gsftopk.log" FONTNAME || ".log"
  End; Else
    Say "No valid pk generated by gsftopk"
End; Else
  Say "Hmm gsftopk did not generate anything, may be not a type1 font..."
@}

@d Generate font from type 1 definition with ps2pk
@{If Open( "mapfile", DVIPSDIR || "/" || PSMAPFILENAME ) Then Do
  @<Find the parameters for ps2pk from mapfile@>
  If "" ~= MFNAME Then Do
    @<Check the \PostScript\ files@>
    If "" ~= PSNAME Then Do
      @<Get supplier and typeface for \PostScript\ font@>
      @<Call \texttt{ps2pk}@>
      @<Check type1 errors@>
      "Unsetenv T1INPUTS"
    End
  End
  Call Close( "mapfile" );
End
@}

Get some parameters from \texttt{PSMAPFILENAME}.  We set \texttt{MFNAME} to
a empty string if we could not find the correct line in the map file.
@d Find the parameters for ps2pk from mapfile
@{@<Find the correct line in mapfile@>
If FONTNAME = MFNAME Then Do
  @<Decode the line@>
  If "" = PSNAME Then
    MFNAME = ""
End; Else
  MFNAME = ""
@| MFNAME @}

We scan every line from the map file until we find one matching
\texttt{FONTNAME}.
@d Find the correct line in mapfile
@{Do Until Eof( "mapfile" )
  LINE = Trim( Readln( "mapfile" ) )
  C = Left( LINE, 1 )
  If ~ ( " " = C | "*" = C | ";" = C | "#" = C ) Then Do
    Parse Var LINE MFNAME " " LINE
    If FONTNAME = MFNAME Then Leave
  End
End
@}

We decode \texttt{LINE} to find the font file name, the font encoding, the
slant and the extension factors.
@d Decode the line
@{If 0 ~= Pos( '"', LINE) Then
  Parse Var LINE '"' QUOTED '"' LINE

Parse Var LINE "<" PSFONTENC " " LINE
Parse Var LINE "<" PSNAME " " LINE

If "" = PSNAME Then Do
  PSNAME = PSFONTENC
  PSFONTENC = ""
End

SLANT = ""
EXTEND = ""
ENCODING = ""

If "" ~= QUOTED Then Do
  If 0 ~= Pos( "SlantFont", QUOTED ) Then Do
    Parse Var QUOTED TMPSTR " SlantFont"
    SLANT = "-S" || Word( TMPSTR, Words( TMPSTR ) )
  End
  If 0 ~= Pos( "ExtendFont", quoted ) Then Do
    Parse Var QUOTED TMPSTR " ExtendFont"
    EXTEND = "-E" || Word( TMPSTR, Words( TMPSTR ) )
  End
End

PSNAME = Strip( PSNAME )
PSFONTENC = Strip( PSFONTENC )
@| PSNAME PSFONTENC SLANT EXTEND @}

We check if we can find both metrics and font files.  We set \texttt{PSFOK}
to 0 if both files can be found.  We set \texttt{PSFNAME} to an empty string
if a file is missing.  This part also sets the \texttt{TYPE1SRCFILE}
environment variable to be used later.  We use \texttt{KPSEWHICH}
to be sure of the existence of the needed files.
@d Check the \PostScript\ files
@{"unsetenv T1INPUTS"
"setenv TYPE1SRCFILE `" || KPSEWHICH PSNAME || "`"
If 0 = RC Then Do
  AFMNAME = Substr( PSNAME, 1, Pos( ".", PSNAME ) - 1 ) || ".afm"

  "Echo >" CURLOGFILENAME "PK file created from" PSNAME
  "Date >>" CURLOGFILENAME
  KPSEWHICH ">NIL:" PSNAME
  If 0 ~= RC Then Do
    PSNAME = ""
  End
End; Else Do
  Say "Can't find" PSNAME
  PSNAME = ""
End
@| PSFOK AFMDIR @}

We find the supplier and the typeface from the \texttt{TYPE1SRCFILE}
environment variable.
@d Get supplier and typeface for \PostScript\ font
@{TYPE1SRCFILE = MyGetEnv( TYPE1SRCFILE )
SUPPLIER = Substr( TYPE1SRCFILE, Length( TYPE1DIR ) + 1 )
SUPPLIER = Left( SUPPLIER, LastPos( "/", SUPPLIER ) - 1 )

TYPEFACE = Substr( SUPPLIER, LastPos( "/", SUPPLIER ) )
SUPPLIER = Left( SUPPLIER, LastPos( "/", SUPPLIER ) - 1 )
@}

@d Call \texttt{ps2pk}
@{T1INPUTSSTRING = TYPE1DIR || SUPPLIER || TYPEFACE
T1INPUTSSTRING = T1INPUTSSTRING || ","
T1INPUTSSTRING = T1INPUTSSTRING || AFMDIR || SUPPLIER || TYPEFACE
T1INPUTSSTRING = T1INPUTSSTRING || ","
T1INPUTSSTRING = T1INPUTSSTRING || DVIPSDIR

"Setenv T1INPUTS" T1INPUTSSTRING

If "" ~= PSFONTENC Then
  ENCODING = "-e" PSFONTENC

PSSIZE = 10.0 * DPI / HBASE

OPTIONS = ">>" CURLOGFILENAME "-v" ENCODING
OPTIONS = OPTIONS "-P" || PSSIZE EXTEND SLANT
OPTIONS = OPTIONS "-X" || HBASE "-Y" || VBASE
OPTIONS = OPTIONS PSNAME CURPKFILENAME

Say "Generating PK file from PostScript font with options"
Say "  " OPTIONS

PS2PK OPTIONS
@}

@d Check type1 errors
@{If 0 = RC Then Do
  DELETECURPK = 1
  CARETFM = 0
  CAREGF = 0
  FONTPKOK = 1
  MODE = "modeless"
End
@}

\subsubsection{Creating a font with \MF}

@d Run {\MF} to generate the font
@{@<Set up the command line options@>
@<Call {\MF}@>
@<Check for possible errors@>
@}

The \texttt{<mag>} parameter for \MF\ is almost trivial.  With the above
setting we can omit the tedious calculations done in version~1.  And there
is no need for the dubious `\texttt{config/modes}' file any longer.

The missing information will come directly from \MF\ itself, because it
should best know where the font files are located.  \TDS\ helps greatly
reduce the effort to determine the other locations.  Here we take for
granted that the ``missing font'' actually was never created before and
so we call \MF~first.  (The font will never be found anyway, if the \TDS\
is not correctly set~up.)
@d Set up the command line options
@{MFOPTIONS = "\mode=" || MODE || ";"
MFOPTIONS = MFOPTIONS "mag=" || DPI || "/" || HBASE || ";"
MFOPTIONS = MFOPTIONS "scrollmode;"
MFOPTIONS = MFOPTIONS "input" FONTNAME
@| MFOPTIONS @}

First, create the gf file and the tfm file and the log file by calling
the \MF\ program.  If anything below fails, you can proceed by hand; all
necessary files will be present in the current directory.  To allow
`restart', \MF~is not called when the expected output file is already
present.  So you should delete the gf file if parts are missing.
@d Call {\MF}
@{Say "Calling MetaFont with base: &" || BASE "and startup commands:"
Say "`" || MFOPTIONS || "'"

If ~Exists( CURGFFILENAME ) Then
  VIRMF "&" || BASE '"' || MFOPTIONS || '"'
Else RC = 0 /* Simulate a perfect result */
@| RC @}

\MF\ returns `0' only in case of a perfect run, any anomalies will be
marked as `20' and lead to the abortion of this script.  For compliance
with former distributions of the \MF\ system error analysis extends to
the intermediate values `5' and `10' as well, which could lead to a
slightly different behaviour.
@d Check for possible errors
@{ERRORCODE = RC

If 5 >= ERRORCODE Then Do
  If 0 < ERRORCODE Then
    Call Error /* and fall through! */
  Else
    Say FONTNAME "translated without errors."
End; Else Do
  Call Error
  Exit 10
End
@| ERRORCODE EDITSCRIPT MFREXXEDIT SOURCEFILE @}

Second, create the pk file by calling the \texttt{GFtoPK} program.  This is
done in the local directory, not yet in the final path.  We omit this step
if the special \texttt{nullmode} is applied and only tfm files are created.
\texttt{GFToPK} seems to reset the \verb|MAKETEX_BASE_DPI| and
\verb|MAKETEX_MODE| environment variables so we better save them
before running \texttt{GFtoPK}.
@d Run \texttt{GFtoPK} to convert the pixel format
@{If "nullmode" ~= MODE Then Do
  SAVEMTBD = MyGetEnv( "MAKETEX_BASE_DPI" )
  SAVEMTM = MyGetEnv( "MAKETEX_MODE" )
  GFTOPK CURGFFILENAME CURPKFILENAME
  Call MySetEnv( "MAKETEX_BASE_DPI", SAVEMTBD )
  Call MySetEnv( "MAKETEX_MODE", SAVEMTM )
  @<Check the output@>
End
@| GFTOPK @}

Don't delete the gf file on failure.  The extra information
attached to the pk file is a convenience, this and even more
information is actually contained in the pk file itself (if
the \MF\ base has `\texttt{modes.mf}' loaded).
@d Check the output
@{If Exists( CURPKFILENAME ) Then Do
  If 0 = KEEPGFFILES Then
    Delete CURGFFILENAME
  FILENOTESTRING = '"mode=' || MODE || ","
  FILENOTESTRING = FILENOTESTRING "mag=" || DPI || "/" || HBASE || '"'
  FileNote CURPKFILENAME FILENOTESTRING
End; Else Do
  Call Log( "Where is my" CURPKFILENAME || "?" )
  Exit 5
End
@}

@d Determine the source path
@{If ~Open( LOGFILE, CURLOGFILENAME, "Read" ) Then Do
  Call Log( "Can't open" CURLOGFILENAME || "!" )
  Exit 10
End

LINE = ReadLn( LOGFILE ) /* Dummy read the first intro line */
LINE = ReadLn( LOGFILE ) /* Dummy read the second calling line */
LINE = ReadLn( LOGFILE ) /* Read the third line for real */

SOURCEFILE = Word( LINE, 1 ) /* The `driver' file is what we want */

If ~Close( LOGFILE ) Then Do
  Call Log( "Can't close" CURLOGFILENAME || "!" )
  Exit 10
End
@| LOGFILE LINE SOURCEFILE @}

Get the \texttt{<supplier>} and \texttt{<typeface>} parts of the
directory names.  Both keep the slash on the left side, but not on the
right side.  This code is a bit tricky, so don't fool around with~it.
@d Determine the supplier and the typeface
@{SUPPLIER = SubStr( SOURCEFILE, Length( SOURCEDIR ) + 2 )
/* `+1' for the open brace and `+1' for the leftmost slash */
SUPPLIER = Left( SUPPLIER, LastPos( "/", SUPPLIER ) - 1 )

TYPEFACE = SubStr( SUPPLIER, LastPos( "/", SUPPLIER ) )
SUPPLIER = Left( SUPPLIER, LastPos( "/", SUPPLIER ) - 1 )
@| SUPPLIER TYPEFACE @}

\subsubsection{Common end}

Third, check all directories needed for installation and try to move the
created files appropriately.  For this we consult the log file directly.
Bitmapped fonts are not created and installed when the special
\texttt{nullmode} is used.
@d Install the files at the appropriate places
@{@<Install the log file@>
If 1 = CARETFM Then
  @<Install the tfm file@>
If "nullmode" ~= MODE Then Do
  @<Install the pk file@>
  If 1 = CAREGF Then
    @<Install the gf file@>
End
@}

@d Install the log file
@{@<Check and create the log directory@>
@<Copy the log file@>
@}

Check the directory structure for the renamed log file.  The following
steps directly document the \TDS\ as proposed by \TUG\ and thus should
be fairly easy to adopt for a (slightly) different scheme.  (This has
already been very useful between AmiWeb2c~1 and AmiWeb2c~2, i.~e., between
version~0.76 and version~0.98 of the \TDS\ specification.)
@d Check and create the log directory
@{LOGDIR = LOGDIR || "/" || MODE
Call SafeMakeDir( LOGDIR )

LOGDIR = LOGDIR || SUPPLIER
Call SafeMakeDir( LOGDIR )

LOGDIR = LOGDIR || TYPEFACE
Call SafeMakeDir( LOGDIR )

LOGDIR = LOGDIR || "/dpi" || DPI
Call SafeMakeDir( LOGDIR )

LOGFILENAME = LOGDIR || "/" || LOGFILENAME
@}

We use `\texttt{Copy}/\texttt{Delete}' instead of `\texttt{Rename}'
to overwrite the existing log file (e.g., from a failed call of
\texttt{MakeTeXFont}).  This works between devices,~too.
@d Copy the log file
@{Copy CURLOGFILENAME LOGFILENAME clone
Delete CURLOGFILENAME
@}

@d Install the tfm file
@{Do
  @<Check and create the tfm directory@>
  @<Copy the tfm file@>
End
@}

Check the directory structure for the renamed tfm file.
@d Check and create the tfm directory
@{TFMDIR = TFMDIR || SUPPLIER
Call SafeMakeDir( TFMDIR )

TFMDIR = TFMDIR || TYPEFACE
Call SafeMakeDir( TFMDIR )

TFMFILENAME = TFMDIR || "/" || CURTFMFILENAME
@}

Check the tfm file; if it doesn't exist, move it there and delete it here.
This will be done only once, since as soon as a tfm file is correctly
installed, it is valid for all pk files together (even if there were milder
forms of warnings in the \MF~run).
@d Copy the tfm file
@{If ~Exists( TFMFILENAME ) Then Do
  Copy CURTFMFILENAME TFMFILENAME clone
  Protect TFMFILENAME r
End

Delete CURTFMFILENAME
@}

@d Install the pk file
@{@<Check and create the pk directory@>
@<Copy the pk file@>
@}

Check the directory structure for the renamed pk file.
@d Check and create the pk directory
@{PKDIR = PKDIR || "/" || MODE
Call SafeMakeDir( PKDIR )

PKDIR = PKDIR || SUPPLIER
Call SafeMakeDir( PKDIR )

PKDIR = PKDIR || TYPEFACE
Call SafeMakeDir( PKDIR )

PKDIR = PKDIR || "/dpi" || DPI
Call SafeMakedir( PKDIR )

PKFILENAME = PKDIR || "/" || FONTNAME || ".pk"
@}

Look if the font already is installed.  (Shouldn't happen!)
@d Copy the pk file
@{If Exists( PKFILENAME ) Then Do
  LOGSTRING = PKFILENAME
  LOGSTRING = LOGSTRING "already exists;" '0A'X
  LOGSTRING = LOGSTRING "check your driver's configuration!"
  Say LOGSTRING
  Call Log( LOGSTRING )
  If 1 = DELETECURPK Then
    Delete CURPKFILENAME
  Exit 5
End

Copy CURPKFILENAME PKFILENAME clone
If 1 = DELETECURPK Then
  Delete CURPKFILENAME
Protect PKFILENAME r
@}

The ``generic font'' files are only kept, when you modify this script in
the section about ``user-definable stuff''.
@d Install the gf file
@{If 0 ~= KEEPGFFILES Then Do
  @<Check and create the gf directory@>
  @<Copy the gf file@>
End
@}

Check the directory structure for the renamed gf file.
@d Check and create the gf directory
@{GFDIR = GFDIR || "/" || MODE
Call SafeMakeDir( GFDIR )

GFDIR = GFDIR || SUPPLIER
Call SafeMakeDir( GFDIR )

GFDIR = GFDIR || TYPEFACE
Call SafeMakeDir( GFDIR )

GFDIR = GFDIR || "/dpi" || DPI
Call SafeMakedir( GFDIR )

GFFILENAME = GFDIR || "/" || CURGFFILENAME
@}

Look if the font already is installed.  (Shouldn't happen!)
@d Copy the gf file
@{If Exists( GFFILENAME ) Then Do
  LOGSTRING = GFFILENAME
  LOGSTRING = LOGSTRING "already exists;" '0A'X
  LOGSTRING = LOGSTRING "check your driver's configuration!"
  Say LOGSTRING
  Call Log( LOGSTRING )
  Delete CURGFFILENAME
  Exit 5
End

Copy CURGFFILENAME GFFILENAME clone
Delete CURGFFILENAME
Protect GFFILENAME r
@}

\subsubsection{Local subroutines}

And finally we define the local routines used in the main body.
@d Local procedures for \texttt{MakeTeXFont.rexx}
@{BREAK_C:
BREAK_D:
  Call Log( "Execution aborted!" )

  If Exists( CURGFFILENAME ) Then
    Delete CURGFFILENAME
  If Exists( CURLOGFILENAME ) Then
    Delete CURLOGFILENAME

  Exit 10
@| BREAK_C BREAK_D @}

@d Local procedures for \texttt{MakeTeXFont.rexx}
@{Log: Procedure Expose MASTERLOG FONTNAME MODE HBASE VBASE DPI
Parse Arg MSG

MESSAGE = Date() Time() || ":"
MESSAGE = MESSAGE FONTNAME "for" MODE
MESSAGE = MESSAGE "(" || HBASE || "," || VBASE || ") with" DPI "dpi"
MESSAGE = MESSAGE "(mag=" || DPI || "/" || HBASE || ")" '0A'X
MESSAGE = MESSAGE || MSG
Say MESSAGE

If ~Open( LOGFILE, MASTERLOG, "Append" ) Then Do
  Say "Can't open logfile!"
  Return
End

DUMMY = WriteLn( LOGFILE, MESSAGE )
If ~Close( LOGFILE ) Then
  Say "Can't close logfile!"

Return
@| Log @}

@d Local procedures for \texttt{MakeTeXFont.rexx}
@{Error:
  Say "Translation problem, MetaFont returned" ERRORCODE || "."
  Call Log( "Translation problem, MetaFont returned" ERRORCODE || "." )
Return
@| Error @}

@d Local procedures for \texttt{MakeTeXFont.rexx}
@{MyGetEnv: Procedure
Parse Arg NAME

OLDADDR = ADDRESS()
ADDRESS "REXX"

If Open( TEMPFILE, "ENV:" || NAME, "Read" ) Then Do
  GIVES = Readln( TEMPFILE )
  Close( TEMPFILE )
End; Else
  GIVES = ""

ADDRESS OLDADDR

Return GIVES
@| MyGetEnv GIVES TEMPFILE @}

@d Local procedures for \texttt{MakeTeXFont.rexx}
@{MySetEnv: Procedure
Parse Arg NAME,VALUE

Address COMMAND "SetEnv" NAME '"' || VALUE || '"'

Return
@| MySetEnv TEMPFILE @}

@d Local procedures for \texttt{MakeTeXFont.rexx}
@{SafeMakeDir: Procedure
Parse Arg DIRNAME

If ~Exists( DIRNAME ) Then Do
  MakeDir DIRNAME
  If ~Exists( DIRNAME ) Then Do
    Call Log( "Could not create directory" DIRNAME )
    Exit 10
  End
  Say "Directory (" || DIRNAME || ") did not exist.  It was created."
End

Return
@| SafeMakeDir DIRNAME @}

@d Local procedures for \texttt{MakeTeXFont.rexx}
@{SafeMakeFile: Procedure
Parse Arg FILENAME

If ~Exists( FILENAME ) Then Do
  "echo >" FILENAME
  If ~Exists( FILENAME ) Then Do
    Call Log( "Could not create file=" || FILENAME )
    Exit 10
  End
  Say "File (" || FILENAME || ") did not exist.  It was created."
End

Return
@| SafeMakeFile FILENAME @}

\subsection{\texttt{MakeTeXPK.rexx}}

The first three arguments of \texttt{MakeTeXPK.rexx} are mandatory.
The \texttt{MODE} name can be omitted and will be guessed from the
\texttt{HBASE} value (in rare cases).
@d Parse the calling parameters
@{Parse Arg FONTNAME DPI HBASE MODE .

If "?" = FONTNAME Then
  @<Quit \texttt{MakeTeXPK.rexx}@>

If "" = MODE | "/" = MODE Then
  @<Try to guess the \texttt{MODE} part@>
@| FONTNAME DPI HBASE MODE @}

In some special cases \texttt{MakeTeXPK.rexx} will try to insert the
\texttt{MODE} part.  This ``guessing mode'' is by far not general, so
either you should call the script with four parameters, providing the
\texttt{<mode>} explicitly, or you will have to change things here.
I suggest that you stick to the standard collection in \texttt{modes.mf}.

@d Try to guess the \texttt{MODE} part
@{Select
  When 100 = HBASE Then MODE = "amiga"
  When 101 = HBASE Then MODE = "nullmode"
  When 120 = HBASE Then MODE = "epsdraft"
  When 180 = HBASE Then MODE = "nec"
  When 240 = HBASE Then MODE = "epson"
  When 300 = HBASE Then MODE = "deskjet"
  When 360 = HBASE Then MODE = "nechi"
  When 600 = HBASE Then MODE = "ljfour"
  Otherwise @<Quit \texttt{MakeTeXPK.rexx}@>
End
@}

@d Quit \texttt{MakeTeXPK.rexx}
@{Do
  Say "rx MakeTeXPK FONTNAME DPI HBASE [MODE]"
  Exit 5
End
@}

AmiWeb2c, respectively KPathSea, sometimes produces \texttt{missfont.log}
files when \texttt{tfm} files are missing.  These files can automatically
be executed to create the missing font information files.  For this purpose
\texttt{MakeTeXPK.rexx} strips off the \texttt{.tfm} extension before
calling \texttt{MakeTXFont.rexx}.

@d Strip a...
@{If "TFM" = Upper( Right( FONTNAME, 3 ) ) Then
  FONTNAME = DelStr( FONTNAME, LastPos( ".", FONTNAME ) )
@}

\texttt{MakeTeXFont.rexx} requires several more parameters, but these can
be provided automatically, so using \texttt{MakeTeXPK.rexx} saves fooling
around with the correct entries in \texttt{MakeTeXFont.sh}.  The following
values are more or less ignored by \texttt{MakeTeXFont.rexx} anyway.
@d Set up the additional arguments
@{VBASE = HBASE
DRIVER = MODE
DUMMY = "dummy"
@| VBASE DRIVER DUMMY @}

Finally, we call \texttt{MakeTeXFont.rexx} with the full list of
parameters.  Notice that the \texttt{MODE} part is padded with~`\texttt{/}'
on both sides in order that the mode can be parsed correctly.
@d Call the main script \texttt{MakeTeXFont.rexx}
@{"rx" MAKETEXFONT FONTNAME DPI HBASE VBASE DRIVER DUMMY "/" || MODE || "/"
@}

\section{Files}

@f

\section{Macros}

@m

\section{Identifiers}

@u

\end{document}
