#!/usr/pkg/bin/perl

=begin COPYRIGHT

----------------------------------------------------------------------------

    Copyright (C) 2005-2026 Marc Penninga.

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation, either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to
        Free Software Foundation, Inc.,
        59 Temple Place,
        Suite 330,
        Boston, MA 02111-1307,
        USA

----------------------------------------------------------------------------

=end COPYRIGHT

=cut

use strict;
use warnings;

use Cwd ();
use File::Basename ();
use File::Path ();
use File::Spec ();
use Getopt::Long ();
use Pod::Usage ();
use POSIX ();

my $VERSION = '20260210';

my ($d, $m, $y) = (localtime time)[3 .. 5];
my $TODAY = sprintf "%04d/%02d/%02d", $y + 1900, $m + 1, $d;

my $RUNNING_AS_MAIN = (__PACKAGE__ eq 'main');


=begin Comment

----------------------------------------------------------------------------

    Autoinst consists of a number of parts:

        main        Contains just the main() routine.

        Options     Parses the command-line options.
                    Note that the *processing* of the user's choices
                    is mostly taken care of by the `Tables` package,
                    since this processing involves adapting those tables.

        Log         Logs the font parsing and creation process.

        Attr        Contains tables and routines that represent
                    font attributes (weight, width, shape).

        Font        Parses an OpenType font's metadata.

        Tables      Contains tables that drive the font creation process
                    (especially the decisions which fonts to create).

        Work        Generates all font files, driven by data from `Tables`.

        LaTeX       Creates LaTeX support (.sty and .fd files).

        Otftotfm    Drives `otftotfm` to actually generate the fonts.

        Util        Some miscellaneous utility functions.

----------------------------------------------------------------------------

=end Comment

=cut


sub main {
    print "autoinst, version $VERSION\n";

    Options::parse_options();
    Tables::process_options();

    my %fontfamily;
    for my $fontfile (@ARGV) {
        my $font = Font::parse($fontfile);
        my $family = $font->{family};
        push @{$fontfamily{$family}}, $font;
    }

    while (my ($family, $fontlist) = each %fontfamily) {

        local %ARGV = %ARGV;
        Tables::process_family_dependent_options($fontlist);

        my $log = Log->new($ARGV{logfile});
        $log->log_options();
        $log->log_parsing($fontlist);

        # We defer asserting that all fonts were parsed in a unique way
        # until after the results of the parsing have been logged.
        Font::assert_unique($log, $fontlist);

        my $mappings = Attr::map_nfss_codes($fontlist);
        my ($from_nfss, $to_nfss) = @{$mappings};
        $log->log_nfss_mapping($from_nfss);

        my @workitems = Work::generate_worklist($fontlist);
        $log->log_worklist(\@workitems);

        my $targetdirs = Otftotfm::get_targetdirs($family, $fontlist);
        my @commands = map { Otftotfm::create_command($_, $targetdirs) }
                           @workitems;
        $log->log_commands(\@commands) if $ARGV{verbose} >= 1;

        if (!$ARGV{dryrun}) {
            LaTeX::create_support_files(\@workitems, $family, $to_nfss);
            Otftotfm::run_commands(\@commands, $family, $log);

            if (!$ARGV{manual}) {
                if ($ARGV{t1suffix}) {
                    Work::modify_fontnames($family, $fontlist);
                }

                print <<"END_MESSAGE_UPDMAP";
[INFO]      Done generating fonts!
            Please update TeX's databases (by calling 'texhash' and 'updmap'
            or their equivalents on your system) before using these fonts.
END_MESSAGE_UPDMAP
            }
        }

        $log->close();
    }

    return;
}


############################################################################


package Attr;

=begin Comment

    Some fontnames contain abbreviated words for width, weight and/or shape;
    we unabbreviate these using the following table.

=end Comment

=cut

my %FULL_FORM = (
    cmp     =>  'compressed',
    comp    =>  'compressed',
    cond    =>  'condensed',
    demi    =>  'demibold',
    extcond =>  'extracondensed',
    hair    =>  'hairline',
    incline =>  'inclined',
    it      =>  'italic',
    ita     =>  'italic',
    md      =>  'medium',
    slant   =>  'slanted',
    smbold  =>  'semibold',
    smcond  =>  'semicondensed',
    smexp   =>  'semiexpanded',
    ultra   =>  'ultrablack',
);

# Auxiliary table that reverses FULL_FORM; maps full forms to abbrevs.
my %abbrev;
while (my ($k, $v) = each %FULL_FORM) {
    push @{$abbrev{$v}}, $k;
}

# Add full forms as known abbreviations of themselves.
for my $full (keys %abbrev) {
    push @{$abbrev{$full}}, $full;
}

# Internal helper: returns a list of known abbreviations of its argument.
sub _get_abbreviated_forms {
    my $key = shift;

    return @{ $abbrev{$key} // [$key] };
}


=begin Comment

    LaTeX's NFSS contains a number of standard codes for weight and width:
    - weight: ul, el, l, sl, m, sb, b, eb, ub
    - width:  uc, ec, c, sc, m, sx, x, ex, ux

    These codes are not always a perfect match with the weights and widths
    present in a font family; some families (especially many sans serif ones)
    contain more or different weights and widths, and the naming of those
    weights and widths isn't always consistent between font families.
    To handle this situation, we use a two-tiered approach:
    1.  We install all fonts using a "series" name that is the concatenation
        of whatever the font designer has chosen to call the weight and width
        (but in all *lower*case).
    2.  We add "alias" rules to the .fd files that map the standard NFSS codes
        to actual fonts.

    In step 1, we follow NFSS in leaving out any occurrence of
    the word "regular" unless *both* weight and width are Regular;
    in that case, the 'series' attribute becomes "regular".

    The two tables WEIGHT and WIDTH are used to control step 2.
    It contains several entries of the form

        sc  =>  [ qw( semicondensed narrow ) ],

    This should be read as follows: the NFSS code "sc" is mapped to
    the *first* width on the right hand side present in the current family.

    Please note that the tables contain empty keys instead of "m" for the
    regular weight and width. NFSS actually combines weight and width into
    a single "series" attribute; a weight or width of "m" is left out of
    this combination (unless *both* weight and width are equal to "m"; then
    the series becomes "m", but that's a special case we deal with later on).

    In addition to the mapping of NFSS codes, the two mentioned tables are
    also used in parsing the font's metadata to determine its weight and
    width: any string that occurs on the right hand side is considered a
    possible name to be searched for.

    These tables can be extended to teach autoinst about new weights or
    widths.  Suppose your font family contains a "Hemibold" weight, that
    you want mapped to the "sb" code. Then add the name "hemibold" to
    the right hand side of the "sb" entry in the WEIGHT table:

        sb  =>  [ qw( semibold demibold medium hemibold ) ],

    In this case, since it's in last position, it's only mapped to "sb"
    if none of the other fonts are present. Put it earlier in the list
    to give it higher priority.

    Note that autoinst converts all metadata to lowercase to avoid
    inconsistent capitalization; so all entries in these tables should
    be *lowercase* as well.

    Technical notes:
    -   We define WEIGHT and WIDTH first as arrays
        and then as hashtables; this allows us to use the array-variants
        as an *ordered* (by weight/width) list of values (in the routines
        get_all_nfss_weights and get_all_nfss_widths).

=end Comment

=cut

my @WEIGHT = (
    ul  =>  [ qw( ultralight thin 100 hairline ) ],
    el  =>  [ qw( extralight 200 ) ],
    l   =>  [ qw( light 300 ) ],
    sl  =>  [ qw( semilight blond ) ],
    ''  =>  [ qw( regular normal text book 400 normallight normaldark plain ) ],
    sb  =>  [ qw( semibold demibold 600 medium 500 ) ],
    b   =>  [ qw( bold 700 ) ],
    eb  =>  [ qw( extrabold 800 ) ],
    ub  =>  [ qw( ultrabold black heavy extrablack ultrablack 900 fatface
                  ultraheavy poster super 1000 ) ],
);

my @WIDTH = (
    uc  =>  [ qw( ultracondensed extracompressed ultracompressed ) ],
    ec  =>  [ qw( extracondensed compressed compact ) ],
    c   =>  [ qw( condensed ) ],
    sc  =>  [ qw( semicondensed narrow ) ],
    ''  =>  [ qw( regular ) ],
    sx  =>  [ qw( semiextended semiexpanded wide ) ],
    x   =>  [ qw( extended expanded ) ],
    ex  =>  [],
    ux  =>  [],
);

my %WEIGHT = @WEIGHT;
@WEIGHT = grep { !ref } @WEIGHT;
# Add abbreviated forms of weight names.
for my $code (@WEIGHT) {
    $WEIGHT{$code}
        = [ map { _get_abbreviated_forms($_) } @{$WEIGHT{$code}} ];
}

my @allweights = grep { $_ !~ m/ medium | regular | text /xms }
                      map { @{$_} } values %WEIGHT;
@allweights = (
    Util::sort_desc_length(@allweights),
    qw(medium regular text)
);


my %WIDTH = @WIDTH;
@WIDTH = grep { !ref } @WIDTH;
# Add abbreviated forms.
for my $code (@WIDTH) {
    $WIDTH{$code}
        = [ map { _get_abbreviated_forms($_) } @{$WIDTH{$code}} ];
}

my @allwidths = grep { $_ ne 'regular' } map { @{$_} } values %WIDTH;
@allwidths = Util::sort_desc_length(@allwidths);


=begin Comment

    The next two tables, DEFAULT_WEIGHT and DEFAULT_WIDTH, map
    weight_class and width_class indicators (from a font's OS/2 table)
    to default weight and width names. We use these names as a last resort
    if font metadata parsing fails.

    The mapping from weight_class and width_class to weight or width names
    is taken from the OpenType specification (see 5.2.8.3 and 5.2.8.4).

=end Comment

=cut

my %DEFAULT_WEIGHT = (
    100 =>  'thin',
    200 =>  'extralight',
    300 =>  'light',
    400 =>  'regular',
    500 =>  'medium',
    600 =>  'semibold',
    700 =>  'bold',
    800 =>  'extrabold',
    900 =>  'black',
);

sub get_default_weight {
    my $weight_class = shift;

    return $DEFAULT_WEIGHT{$weight_class};
}

my %DEFAULT_WIDTH = (
    1   =>  'ultracondensed',
    2   =>  'extracondensed',
    3   =>  'condensed',
    4   =>  'semicondensed',
    5   =>  'regular',
    6   =>  'semiexpanded',
    7   =>  'expanded',
    8   =>  'extraexpanded',
    9   =>  'ultraexpanded',
);

sub get_default_width {
    my $width_class = shift;

    return $DEFAULT_WIDTH{$width_class};
}


=begin Comment

    The SHAPE table maps various shape names to NFSS codes.

    Like in the other * tables, entries may be added to teach autoinst
    about new shapes. Note that this table is "the other way around"
    compared to WEIGHT and WIDTH; those map NFSS codes to names,
    this one maps names to NFSS codes. That's because the data from
    this table is used in a slightly different way; notably, it isn't
    used in the map_nfss_codes routine.

=end Comment

=cut

my %SHAPE = (
    roman       =>  'n',
    upright     =>  'n',
    italic      =>  'it',
    inclined    =>  'sl',
    oblique     =>  'sl',
    slanted     =>  'sl',
    romani      =>  'n',    # Silentium has two roman shapes, but no italic;
    romanii     =>  'it',   # so we cheat by mapping the second roman to 'it'
);

# Add abbreviated forms.
for my $full (keys %abbrev) {
    if (defined $SHAPE{$full}) {
        for my $abbrev (_get_abbreviated_forms($full)) {
            $SHAPE{$abbrev} = $SHAPE{$full};
        }
    }
}

my @allshapes = Util::sort_desc_length(keys %SHAPE);


# --------------------------------------------------------------------------
#   Returns the unabbreviated form of its argument,
#   or its argument itself if no unabbreviated form is known.
# --------------------------------------------------------------------------
sub unabbreviate {
    my $key = shift;

    return $FULL_FORM{$key} // $key;
}


# --------------------------------------------------------------------------
#   Prepends weight names to the WEIGHT table for a given NFSS code.
# --------------------------------------------------------------------------
sub set_weight {
    my ($key, @values) = @_;

    $WEIGHT{$key} = [ @values ];
    return;
}


# --------------------------------------------------------------------------
#   Returns a list of NFSS weight names, sorted by weight.
# --------------------------------------------------------------------------
sub get_all_nfss_weights {
    return @WEIGHT;
}


# --------------------------------------------------------------------------
#   Returns a list of all known weights, in an order suitable for searching.
# --------------------------------------------------------------------------
sub get_all_weights {
    return @allweights;
}


# --------------------------------------------------------------------------
#   Prepends weight names to the WIDTH table for a given NFSS code.
# --------------------------------------------------------------------------
sub set_width {
    my ($key, @values) = @_;

    $WIDTH{$key} = [ @values ];
    return;
}


# --------------------------------------------------------------------------
#   Returns a list of NFSS width names, sorted by width.
# --------------------------------------------------------------------------
sub get_all_nfss_widths {
    return @WIDTH;
}


# --------------------------------------------------------------------------
#   Returns a list of all known widths, in an order suitable for searching.
# --------------------------------------------------------------------------
sub get_all_widths {
    return @allwidths;
}


# --------------------------------------------------------------------------
#   Returns the NFSS code for the given shape.
# --------------------------------------------------------------------------
sub to_nfss {
    my $key = shift;

    return $SHAPE{$key};
}


# --------------------------------------------------------------------------
#   Returns a list of all known shapes, in an order suitable for searching.
# --------------------------------------------------------------------------
sub get_all_shapes {
    return @allshapes;
}


# --------------------------------------------------------------------------
#   Returns mappings of NFSS codes to weight and width, and vice versa.
# --------------------------------------------------------------------------
sub map_nfss_codes {
    my $fontlist = shift;

    my (%weight, %width);
    for my $font (@{$fontlist}) {
        $weight{ $font->{weight} } //= $font->{weight_class};
        $width{  $font->{width} }  //= $font->{width_class};
    }

    my $from_nfss = {
        weight => {},
        width => {},
    };

    for my $nfssweight (get_all_nfss_weights()) {
        $from_nfss->{weight}{$nfssweight}
            = [ grep { $weight{$_} } @{$WEIGHT{$nfssweight}} ];
    }

    # Some trickery to handle the case where the ul/ub codes are mapped
    # but the el/eb codes are still empty. We try two things:
    # 1.  if there is a Thin (Heavy) weight and this is less extreme
    #     than the weight mapped to ul (ub), we map Thin (Heavy) to ul (ub)
    # 2.  otherwise we move the ul/ub weight to the el/eb position,
    #     unless that weight is the Ultralight/Ultrabold weight
    if (!$ARGV{el} and !$ARGV{ul}) {
        if (@{$from_nfss->{weight}{ul}}
                and !@{$from_nfss->{weight}{el}}) {
            if ($weight{thin}
                    and $weight{thin}
                        > $weight{$from_nfss->{weight}{ul}[0]}) {
                $from_nfss->{weight}{el} = ['thin',];
            }
            elsif ($from_nfss->{weight}{ul}[0] ne 'ultralight') {
                $from_nfss->{weight}{el}
                    = [ shift @{$from_nfss->{weight}{ul}} ];
            }
        }
    }
    if (!$ARGV{eb} and !$ARGV{ub}) {
        if (@{$from_nfss->{weight}{ub}}
                and !@{$from_nfss->{weight}{eb}}) {
            if ($weight{heavy}
                    and $weight{heavy}
                        < $weight{$from_nfss->{weight}{ub}[0]}) {
                $from_nfss->{weight}{eb} = ['heavy',]
                    unless @{$from_nfss->{weight}{b}}
                       and $weight{$from_nfss->{weight}{b}[0]}
                           > $weight{heavy};
            }
            elsif ($from_nfss->{weight}{ub}[0] ne 'ultrabold') {
                $from_nfss->{weight}{eb}
                    = [ shift @{$from_nfss->{weight}{ub}} ];
            }
        }
    }

    # Special case: if we don't have Regular but we *do* have Medium,
    # move Medium from the "sb" list to the "m" (i.e., Regular) one.
    if (!@{$from_nfss->{weight}{''}}) {
        my $alternate = ( grep { $weight{$_} } qw(medium 500) )[0];
        if ($alternate) {
            $from_nfss->{weight}{''} = [$alternate];
            $from_nfss->{weight}{sb}
                = [ grep { $_ ne $alternate } @{$from_nfss->{weight}{sb}} ];
        }
    }

    # Some more trickery to map the sl code to Book or Text (but of course
    # only if sl is empty and Book/Text is lighter than Regular)
    if (!@{$from_nfss->{weight}{sl}}) {
        $from_nfss->{weight}{sl}
            = [ grep { $weight{$_} < $weight{$from_nfss->{weight}{''}[0]} }
                     @{$from_nfss->{weight}{''}} ];
    }

    NFSSWIDTH:
    for my $nfsswidth (get_all_nfss_widths()) {
        for my $width ( @{$WIDTH{$nfsswidth}} ) {
            if ($width{$width}) {
                $from_nfss->{width}{$nfsswidth} = [$width];
                next NFSSWIDTH;
            }
        }
        $from_nfss->{width}{$nfsswidth} = [];
    }

    # Warn if we (still) don't have a regular weight or width
    if (!@{$from_nfss->{weight}{''}}) {
        warn <<"END_NO_REGULAR_WEIGHT";
[WARNING]   I could not find a 'Regular' weight;
            consider using the '-nfssweight=m=...' option
            (see the documentation).
END_NO_REGULAR_WEIGHT
    }
    if (!@{$from_nfss->{width}{''}}) {
        warn <<"END_NO_REGULAR_WIDTH";
[WARNING]   I could not find a 'Regular' width;
            consider using the '-nfsswidth=m=...' option
            (see the documentation).
END_NO_REGULAR_WIDTH
    }

    # Reverse the %from_nfss mapping to get %to_nfss
    my %to_nfss;
    NFSSWEIGHT:
    for my $nfssweight (get_all_nfss_weights()) {
        next unless @{$from_nfss->{weight}{$nfssweight}};
        my $weight = $from_nfss->{weight}{$nfssweight}[0];
        $weight = "" if $weight eq 'regular';

        NFSSWIDTH:
        for my $nfsswidth (get_all_nfss_widths()) {
            my $nfssseries = ($nfssweight . $nfsswidth) || 'm';

            next unless @{$from_nfss->{width}{$nfsswidth}};
            my $width = $from_nfss->{width}{$nfsswidth}[0];
            $width = "" if $width eq 'regular';
            my $series = ($weight . $width) || 'regular';
            $to_nfss{$series} = $nfssseries;
        }
    }

    return [ $from_nfss, \%to_nfss ];
}


############################################################################


package Font;

# --------------------------------------------------------------------------
#   Constructor: returns a new Font object.
# --------------------------------------------------------------------------
sub _new {
    my ($class, $filename) = @_;

    my $self = {
        filename     => $filename,
        width        => 'regular',
        weight       => undef,
        shape        => 'roman',
        minsize      => 0,
        maxsize      => 0,
        is_smallcaps => 0,
        weight_class => 0,
        width_class  => 0,
        nfss         => 'rm',
    };

    return bless $self, $class;
}


# --------------------------------------------------------------------------
#   Factory function: parses a font's metadata and creates a Font object.
# --------------------------------------------------------------------------
sub parse {
    my $filename = shift;

    my $self = __PACKAGE__->_new($filename);

    my $metadata = _get_metadata($filename);

    $self->_get_missing_metadata($filename);

    $self->_parse_metadata($metadata)
         ->_parse_featuredata()
         ->_parse_sizedata()
         ->_parse_nfss_classification()
         ->_parse_fonttype()
         ;

    return $self;
}


# --------------------------------------------------------------------------
#   Returns the output of otfinfo -i as a list of key-value pairs.
# --------------------------------------------------------------------------
sub _get_metadata {
    my $filename = shift;

    my $cmd = qq(otfinfo --info "$filename");
    open my $otfinfo, '-|', $cmd
        or die "[ERROR]     Could not run '$cmd': $!";
    my %data = map { my ($k,$v) = m/\A\s* ([^:]+?) \s*:\s* ([^\r\n]+)/xms;
                     $k =~ s/\s+//xmsg;
                     (lc $k => $v);
                   }
                   grep { m/\A\s* [^:]+? \s*:\s* [^\r\n]+/xms } <$otfinfo>;
    close $otfinfo
        or die "[ERROR]     '$cmd' failed";

    return \%data;
}


# --------------------------------------------------------------------------
#   Get some missing metadata from the font file.
#
#   otfinfo doesn't extract all the metadata we need, so we parse some of
#   the raw tables from the font file ourselves to get the missing metadata.
# --------------------------------------------------------------------------
sub _get_missing_metadata {
    my ($self, $filename) = @_;

    my $tables;
    eval {
        my $cmd = qq(otfinfo --tables "$filename");
        open my $otfinfo, '-|:raw', $cmd
            or die "could not fork(): $!";
        $tables = do { local $/; <$otfinfo> };
        close $otfinfo
            or die "'$cmd' failed";
    } or warn "[WARNING]   $@";

    # We need the cff_name because cfftot1 uses that instead of
    # the font's PostScript name.
    $self->{cff_name} = '';
    if (index($tables, 'CFF') > -1) {
        my $cff_table;
        eval {
            my $cmd = qq(otfinfo --dump-table "CFF" "$filename");
            open my $otfinfo, '-|:raw', $cmd
                or die "could not fork(): $!";
            $cff_table = do { local $/; <$otfinfo> };
            close $otfinfo
                or die "'$cmd' failed";
        } or warn "[WARNING]   $@";

        my ($name_index) = unpack '@8C/Z', $cff_table;

        $self->{cff_name} = $name_index;
    }

    # WeightClass and WidthClass contain (numerical) indications
    # of the font's weight and width
    $self->{weight_class} = 400;
    $self->{width_class}  = 5;
    if (index($tables, 'OS/2') > -1) {
        my $os2_table;
        eval {
            my $cmd = qq(otfinfo --dump-table "OS/2" "$filename");
            open my $otfinfo, '-|:raw', $cmd
                or die "could not fork(): $!";
            $os2_table = do { local $/; <$otfinfo> };
            close $otfinfo
                or die "'$cmd' failed";
        } or warn "[WARNING]   $@";

        my ($weight_class, $width_class) = unpack '@4n @6n', $os2_table;

        $self->{weight_class} = $weight_class;
        $self->{width_class}  = $width_class;
    }

    # isFixedPitch does (or at least should) indicate whether
    # the font is fixed-pitch (i.e., monospaced).
    if (index($tables, 'post') > -1) {
        my $post_table;
        eval {
            my $cmd = qq(otfinfo --dump-table "post" "$self->{filename}");
            open my $otfinfo, '-|:raw', $cmd
                or die "could not fork(): $!";
            $post_table = do { local $/; <$otfinfo> };
            close $otfinfo
                or die "'$cmd' failed";
        } or warn "[WARNING]   $@";

        my $is_fixed_pitch = unpack '@12N', $post_table;

        $self->{is_fixed_pitch} = $is_fixed_pitch;
    }

    return $self;
}


# --------------------------------------------------------------------------
#   Processes the basic metadata for this font.
# --------------------------------------------------------------------------
sub _parse_metadata {
    my ($self, $data) = @_;

    $self->{originalfamily} = $data->{family};

    for my $key (keys %{$data}) {
        $data->{$key} =~ s/\s+//xmsg;
    }

    for my $item (qw(family subfamily fullname)) {
        if (!$data->{$item}) {
            die <<"END_ERR_METADATA_MISSING"
[ERROR]     Parsing font metadata failed for $self->{filename}:
            could not find '$item' metadata item
END_ERR_METADATA_MISSING
        }
    }

    $data->{family}    =  $data->{preferredfamily} || $data->{family};
    $data->{subfamily} =  $data->{preferredsubfamily} || $data->{subfamily};
    $data->{fullname}  =~ s/\A$data->{family}//xms;
    $data->{fullname}  =  lc $data->{fullname};

    # clean up family name (it's used in LaTeX command names)
    my @DIGITS = qw(Zero One Two Three Four Five Six Seven Eight Nine);
    $data->{family}    =~ s/(?: LT | MT)(?: Std | Pro )//xms;
    $data->{family}    =~ s/(\d)/$DIGITS[$1]/xmsge;
    $data->{family}    =~ s/[^A-Za-z]+//xmsg;

    if ($data->{family} =~ s/\A DTL//xms) {
        $data->{subfamily} =~ s/\A (?: ST | T | SD | D)//xms;
    }

    # Some extended font families, especially from Adobe,
    # include the optical master in the family name.
    # We don't want this, as all these fonts should be part of the same family,
    # with different values for the optical size range.
    # We therefore move the optical master name from the family to the subfamily.
    # We don't discard this information entirely, since we need it later on
    # in _parse_sizedata().
    # This hack causes problems with Libertinus Serif Display,
    # so we skip it for that font.
    if ($data->{family} !~ m/Libertinus/xmsi) {
        for my $optical (qw(Caption SmText SmallText Subhead Display)) {
            if ($data->{family} =~ s/$optical\z//xms) {
                $data->{subfamily} .= $optical;
                last;
            }
        }
    }

    # Sometimes the relevant info is in Fullname, sometimes in Subfamily;
    # so we need to test against both
    my $fullinfo = lc "$data->{subfamily} | $data->{fullname}";

    # remove Adobe's SmallText size, to avoid mistaking it for Text weight
    $fullinfo =~ s/(?: SmallText | SmText )//gxmsi;

    # remove the word 'TypeWriter' from the info, to avoid it matching
    # against the "It" shape
    $fullinfo =~ s/typewriter//gxmsi;

    # We need to be careful when parsing the font info; in particular
    # we must parse strings like 'UltraCondensed' as 'Regular' weight
    # and 'UltraCondensed' width, not as 'Ultra' weight and 'Condensed' width.
    # The following rules should prevent accidents:
    # 1.  Search for matching widths before matching weights
    #     (as none of the widths is a proper substring of some weight)
    # 2.  Remove any recognised search string from the 'fullinfo'
    # 3.  Test the weights 'medium' and 'regular' *last*, since these strings
    #     may also occur in Subfamily without indicating the weight;
    #     so we only take them to mean weight if we find no other hit.
    my @widths = Attr::get_all_widths();
    for my $width (@widths) {
        if ($fullinfo =~ m/$width/xms) {
            $self->{width} = $width;
            my $widths = join '|', @widths;
            $fullinfo =~ s/$widths//gxmsi;
            last;
        }
    }

    my @weights = Attr::get_all_weights();
    for my $weight (@weights) {
        if ($fullinfo =~ m/$weight/xms) {
            $self->{weight} = $weight;
            my $weights = join '|', @weights;
            $fullinfo =~ s/$weights//gxmsi;
            last;
        }
    }

    unless ($self->{weight}) {
        $self->{weight} = $DEFAULT_WEIGHT{$self->{weight_class}};
    }
    $self->{weight} //= 'regular';

    my @shapes = Attr::get_all_shapes();
    for my $shape (@shapes) {
        if ($fullinfo =~ m/$shape/xms) {
            $self->{shape} = $shape;
            my $shapes = join '|', @shapes;
            $fullinfo =~ s/$shapes//gxmsi;
            last;
        }
    }

    # In many font families, each font is in a subfamily of its own;
    # so we remove width, weight and shape from the 'subfamily' value.
    $data->{subfamily} =~ s/$self->{width}//xmsi;
    $data->{subfamily} =~ s/$self->{weight}//xmsi;
    $data->{subfamily} =~ s/$self->{shape}//xmsi;

    $self->{name}      = $data->{postscriptname};
    $self->{family}    = $data->{family};
    $self->{subfamily} = $data->{subfamily};

    # Take care to unabbreviate weight and width; CondensedUltra fonts
    # might end up as 'ultracondensed' instead of 'ultrablackcondensed'!
    $self->{width}  = Attr::unabbreviate($self->{width});
    $self->{weight} = Attr::unabbreviate($self->{weight});
    $self->{shape}  = Attr::unabbreviate($self->{shape});

    # Handle the (semi)condensed widths of the Thesis family.
    # Doing this in the WIDTH table is tricky (i.e., TheSansCd might be
    # parsed as the SCd width of the TheSan family), so we treat it as
    # a special case instead.
    if ($self->{family} =~ m/\A (The (?: Sans | Serif | Mix)) (S? Cd) \z/xms
            and $self->{width} eq 'regular') {
        $self->{family} = $1;
        $self->{width}
            = $2 eq 'Cd'  ? 'condensed'
            : $2 eq 'SCd' ? 'semicondensed'
            :               die '[ERROR]     Internal error, please report!'
            ;
    }

    # Some font families put small caps into separate families;
    # we merge these into the 'main' family.
    # We have to test both 'family', 'subfamily' and 'name' for hints
    # that this is a small caps font, as some fonts (e.g., Dolly)
    # only mention this in their name.
    my $shapes = join '|', Util::sort_desc_length(qw(smallcaps sc smcp caps));
    if ($self->{family} =~ m/(.+?) (?: $shapes) \z/xmsi) {
        $self->{family}       = $1;
        $self->{is_smallcaps} = 1;
    }
    if ($self->{subfamily} =~ m/(.+?) (?: $shapes) \z/xmsi) {
        $self->{subfamily}    = $1;
        $self->{is_smallcaps} = 1;
    }
    if ($self->{name} =~ m/\A DTL/xms && $self->{subfamily} =~ s/Caps//xms) {
        $self->{is_smallcaps} = 1;
    }
    if ($self->{name} =~ m/(.+?) (?: $shapes) \z/xmsi) {
        $self->{is_smallcaps} = 1;
    }
    # Some font families put italic shapes into separate families;
    # we merge these into the 'main' family.
    $shapes = join '|', Util::sort_desc_length(qw(it italic));
    if ($self->{family} =~ m/(.+?) ($shapes) \z/xmsi
            and ($self->{shape} eq 'regular'
                    or $self->{shape} eq Attr::unabbreviate(lc($2)))) {
        $self->{family} = $1;
        $self->{shape}  = Attr::unabbreviate(lc($2));
    }

    # Some font families put different widths into separate families;
    # we merge these into the 'main' font family.
    my $widths = join '|', Attr::get_all_widths();
    if ($self->{family} =~ m/(.+?) ($widths) \z/xmsi
            and ($self->{width} eq 'regular'
                    or $self->{width} eq Attr::unabbreviate(lc($2)))) {
        $self->{family} = $1;
        $self->{width}  = Attr::unabbreviate(lc($2));
    }

    # Some font families put unusual weights into separate families;
    # we merge these into the 'main' font family. But we have to be
    # careful with the word 'Text': this might be part of the family name
    # (i.e., Libre Caslon Text) and should not be mistaken for a weight.
    my $weights = join '|', Attr::get_all_weights();
    if ($self->{family} =~ m/text \z/xmsi) {
        $weights =~ s/[|]? text//xms;
    }
    if ($self->{family} =~ m/(.+?) ($weights) \z/xmsi
            and ($self->{weight} eq 'regular'
                    or $self->{weight} eq Attr::unabbreviate(lc($2)))) {
        $self->{family} = $1;
        $self->{weight} = Attr::unabbreviate(lc($2));
    }

    $self->{basicshape} = Attr::to_nfss($self->{shape});

    # Work around a bug(?) in League Mono: the Regular width has
    # a WidthClass of 6 instead of 5; that would cause our test below
    # to (mis)classify it as SemiCondensed.
    if ($self->{family} eq 'LeagueMono'
            and $self->{width} eq 'regular'
            and $self->{width_class} == 6) {
        $self->{width_class} = 5;
    }

    # A last-resort approach: if we couldn't parse weight or width,
    # we use the WeightClass and WidthClass indicators to derive
    # a default value for weight or width.
    # The reason we only use this as a last resort is that some fonts
    # contain non-standard or otherwise non-meaningful values
    # for these indicators.
    if ($self->{weight} eq 'regular'
            and $self->{weight_class} != 400) {
        $self->{weight} = Attr::get_default_weight($self->{weight_class}) // 'regular';
    }

    if ($self->{width} eq 'regular'
            and $self->{width_class} != 5) {
        $self->{width} = Attr::get_default_width($self->{width_class}) // 'regular';
    }

    # We define 'series' as 'weight + width'. This matches NFSS,
    # but contradicts how most fonts are named (which is 'width + weight').
    $self->{series}
        = ($self->{width}  eq 'regular') ? $self->{weight}
        : ($self->{weight} eq 'regular') ? $self->{width}
        :                                  $self->{weight} . $self->{width}
        ;

    $self->{cff_name} ||= $self->{name};

    return $self;
}


# --------------------------------------------------------------------------
#   Returns a list of features that this font supports.
#   We include 'kern' in this list even if there is only a 'kern' table
#   (but no feature), since otftotfm can also use the (legacy) table.
# --------------------------------------------------------------------------
sub _parse_featuredata {
    my $self = shift;

    my $cmd = qq(otfinfo --features "$self->{filename}");
    open my $otfinfo, '-|', $cmd
        or die "[ERROR]     Could not run '$cmd': $!";
    my @data = map { substr $_, 0, 4 } <$otfinfo>;
    close $otfinfo
        or die "[ERROR]     '$cmd' failed";

    $cmd = qq(otfinfo --tables "$self->{filename}");
    open $otfinfo, '-|', $cmd
        or die "[ERROR]     Could not run '$cmd': $!";
    my $data = do { local $/; <$otfinfo> };
    close $otfinfo
        or die "[ERROR]     '$cmd' failed";

    if ($data =~ m/\d+ \s+ kern/xms) {
        push @data, 'kern';
    }

    %{$self->{feature}} = map { $_ => 1 } @data;

    return $self;
}


# --------------------------------------------------------------------------
#   Extracts 'minsize' and 'maxsize' from the optical design size info.
# --------------------------------------------------------------------------
sub _parse_sizedata {
    my $self = shift;

    my $cmd = qq(otfinfo --optical-size "$self->{filename}");
    open my $otfinfo, '-|', $cmd
        or die "[ERROR]     Could not run '$cmd': $!";
    my $data = do { local $/; <$otfinfo> };
    close $otfinfo
        or die "[ERROR]     '$cmd' failed";

    my ($minsize, $maxsize)
        = $data =~ m/[([] ([\d.]+) (?:\s* pt)?, \s*
                          ([\d.]+) (?:\s* pt)?  \s* [])]/xms;

    $minsize //= 0;
    $maxsize //= 0;

    # fix some known bugs
    if ($self->{name} eq 'GaramondPremrPro-It'
        && $minsize == 6 && $maxsize == 8.9) {
        ($minsize, $maxsize) = (8.9, 14.9);
    }
    elsif ($self->{family} eq 'KeplerStd'
        && $self->{subfamily} =~ m/Caption/xms
        && $minsize == 8.9 && $maxsize == 13.9) {
        ($minsize, $maxsize) = (6, 8.9);
    }
    elsif ($self->{family} eq 'KeplerStd'
        && $self->{subfamily} =~ m/Subhead/xms
        && $minsize == 8.9 && $maxsize == 13.9) {
        ($minsize, $maxsize) = (13.9, 23);
    }
    elsif ($self->{family} eq 'KeplerStd'
        && $self->{subfamily} =~ m/Display/xms
        && $minsize == 8.9 && $maxsize == 13.9) {
        ($minsize, $maxsize) = (23, 72);
    }
    # Adobe's Source Serif 4 follows a recent version of the OpenType
    # spec and keeps its optical size info as a `size` feature rather
    #  than in the OS/2 table. This isn't (yet?) supported by otfinfo,
    #  so we add the missing size info here.
    elsif ($self->{family} eq 'SourceSerifFour'
        && $minsize == 0 && $maxsize == 0) {
        if ($self->{subfamily} eq 'Caption') {
            ($minsize, $maxsize) = (0, 6);
        }
        elsif ($self->{subfamily} eq 'SmText') {
            ($minsize, $maxsize) = (6, 9);
        }
        elsif ($self->{subfamily} eq '') {
            ($minsize, $maxsize) = (9, 13);
        }
        elsif ($self->{subfamily} eq 'Subhead') {
            ($minsize, $maxsize) = (13, 24);
        }
        elsif ($self->{subfamily} eq 'Display') {
            ($minsize, $maxsize) = (24, 72);
        }
        else {
            die "[ERROR]     Unknown subfamily '$self->{subfamily}' in $self->{filename}";
        }
    }

    @{$self}{qw(minsize maxsize)} = ($minsize, $maxsize);

    return $self;
}


# --------------------------------------------------------------------------
#   Adds the NFSS classification (rm, sf, tt) to self.
# --------------------------------------------------------------------------
sub _parse_nfss_classification {
    my $self = shift;

    $self->{nfss} = $self->{is_fixed_pitch}                     ? 'tt'
                    : $self->{filename} =~ m/mono(?!type)/xmsi  ? 'tt'
                    : $self->{filename} =~ m/sans/xmsi          ? 'sf'
                    :                                             'rm'
                    ;

    return $self;
}


# --------------------------------------------------------------------------
#   Determines the OpenType flavor of this font.
# --------------------------------------------------------------------------
sub _parse_fonttype() {
    my $self = shift;

    my ($ext) = $self->{filename} =~ m/[.] ([^.]+) \z/xmsi;
    $ext = lc $ext;

    $self->{fonttype}
        = $ext eq 'otf' ? 'opentype'
        : $ext eq 'ttf' ? 'truetype'
        :                 ''
        ;

    if (!$self->{fonttype}) {
        open my $fontfile, '<:raw', $self->{filename}
            or die "[ERROR]     Could not open '$self->{filename}': $!";
        my $fontsignature;
        read $fontfile, $fontsignature, 4;
        $self->{fonttype}
            = $fontsignature eq 'OTTO'             ? 'opentype'
            : $fontsignature eq "\x00\x01\x00\x00" ? 'truetype'
            :                                        ''
            ;
        close $fontfile;
    }

    if (!$self->{fonttype}) {
        die "[ERROR]     Unknown font type ($self->{filename})"
    }

    return $self;
}


# Error messages, used in assert_unique().
my $ERR_DETAIL =<<'END_ERR_DETAIL';
[ERROR]     I've parsed both %s
                         and %s as

            Family:     %s
            Weight:     %s
            Width:      %s
            Shape:      %s
            Size:       %s-%s
            Smallcaps:  %s

END_ERR_DETAIL

my $ERR_PARSE =<<'END_ERR_PARSE';
[ERROR]     I failed to parse all fonts in a unique way;
            presumably some fonts have unusual widths, weights or shapes.

            Try one of the following:
            -   Run 'autoinst' on a smaller set of fonts,
                omitting the ones that weren't parsed correctly;
            -   Add the missing widths, weights or shapes to the tables
                'WIDTH', 'WEIGHT' or 'SHAPE' in the source code;

            Please also send a bug report to the author.
END_ERR_PARSE

# --------------------------------------------------------------------------
#   Asserts all parsed fonts are unique.
# --------------------------------------------------------------------------
sub assert_unique {
    my ($log, $fontlist) = @_;

    # These attributes should uniquely identify each font.
    my @attributes
        = qw(family weight width shape minsize maxsize is_smallcaps);

    my (%seen, $err_details);
    for my $font (@{$fontlist}) {
        my $key = join "\x00", @{$font}{@attributes};

        if ($seen{$key}) {
            $err_details .= sprintf $ERR_DETAIL,
                                    $seen{$key}{filename},
                                    $font->{filename},
                                    @{$font}{@attributes};
        }
        else {
             $seen{$key} = $font;
        }
    }

    # Die with detailed error message if the font infos aren't unique.
    if ($err_details) {
        $log->log($err_details, $ERR_PARSE);
        die $err_details, $ERR_PARSE;
    }

    return 1;
}


############################################################################


package LaTeX;

# --------------------------------------------------------------------------
#   Creates .sty and .fd files for LaTeX.
# --------------------------------------------------------------------------
sub create_support_files {
    my ($worklist, $family, $nfss_mapping) = @_;

    # Organize the worklist by family, encoding, style, series and shape.
    my %fddata;
    for my $workitem (@{$worklist}) {
        my $encoding    = $workitem->{encoding};
        my $figurestyle = $workitem->{figurestyle};
        my $series      = $workitem->{font}{series};
        my $shape       = $workitem->{fdshape};
        my $minsize     = $workitem->{font}{minsize};
        my $maxsize     = $workitem->{font}{maxsize};

        push @{$fddata{$encoding}{$figurestyle}{$series}{$shape}},
             [ $minsize, $maxsize, $workitem->{fontname} ];
    }

    create_stylefile($nfss_mapping, $family, \%fddata);
    while (my ($enc, $encdata) = each %fddata) {
        while (my ($sty, $stydata) = each %$encdata) {
            create_fdfile($nfss_mapping, $family, $enc, $sty, $stydata);
        }
    }

    return;
}


# This table is used to generate extra ssub rules in .fd files
# to map missing Slanted shapes to Italic and vice versa.
my %SSUB_SHAPE = (
    sl      =>  'it',
    scsl    =>  'scit',
    it      =>  'sl',
    scit    =>  'scsl',
);

# --------------------------------------------------------------------------
#   Creates a LaTeX style file.
# --------------------------------------------------------------------------
sub create_stylefile {
    my ($nfss_mapping, $fam, $data) = @_;

    my %seen = %{Util::get_keys($data)};

    my $fn = sprintf "%s.sty", $fam;
    my $dir = File::Spec->catdir(
        $ARGV{target}, 'tex', 'latex', $ARGV{typeface} || $fam);
    File::Path::make_path($dir);
    $fn = File::Spec->catfile($dir, $fn);
    open my $STY, '>', $fn or die "[ERROR]     Can't create '$fn': $!";
    # We use binmode since TeX expects these files to have
    # Unix-style line ends even on Windows.
    binmode $STY;

    print {$STY} <<"END_STY_HEADER";
\\NeedsTeXFormat{LaTeX2e}[2020/02/02]
\\ProvidesPackage{$fam}
    [$TODAY (autoinst)  Style file for $fam fonts.]

END_STY_HEADER

    print {$STY} <<"END_STY_XKEYVAL";
\\RequirePackage{xkeyval}
\\newcommand*{\\$fam\@scale}{1}
\\DeclareOptionX{scale}{\\renewcommand*{\\$fam\@scale}{#1}}
\\DeclareOptionX{scaled}{\\renewcommand*{\\$fam\@scale}{#1}}

END_STY_XKEYVAL

    my ($figurestyle_default, $figurealign_default);
    if ($seen{LF} or $seen{TLF}) {
        print {$STY}
            "\\DeclareOptionX{lining}{\\edef\\$fam\@figurestyle{LF}}\n";
        $figurestyle_default = 'LF';
    }
    if ($seen{OsF} or $seen{TOsF}) {
        print {$STY}
            "\\DeclareOptionX{oldstyle}{\\edef\\$fam\@figurestyle{OsF}}\n";
        $figurestyle_default = 'OsF';
    }
    if ($seen{TLF} or $seen{TOsF}) {
        print {$STY}
            "\\DeclareOptionX{tabular}{\\edef\\$fam\@figurealign{T}}\n";
        $figurealign_default = 'T';
    }
    if ($seen{LF} or $seen{OsF}) {
        print {$STY}
            "\\DeclareOptionX{proportional}{\\edef\\$fam\@figurealign{}}\n";
        $figurealign_default = '';
    }

    print {$STY} <<"END_STY_MAINFONT";
\\edef\\$fam\@figurestyle{$figurestyle_default}
\\edef\\$fam\@figurealign{$figurealign_default}

\\DeclareOptionX{mainfont}{
    \\renewcommand{\\familydefault}{\\$ARGV{nfss}default}
}
END_STY_MAINFONT

    for my $series (qw(heavy black extrabold demibold semibold bold)) {
        if ( $seen{$series} ) {
            print {$STY}
                "\\DeclareOptionX{$series}{\\edef\\bfseries\@$ARGV{nfss}",
                "{$series}}\n";
        }
    }

    for my $series (qw(medium book text normal regular)) {
        if ( $seen{$series} ) {
            print {$STY}
                "\\DeclareOptionX{$series}{\\edef\\mdseries\@$ARGV{nfss}",
                "{$series}}\n";
        }
    }
    print {$STY} "\n";

    if ($ARGV{math}) {
        print {$STY} <<"END_STY_MATHOPTION";
\\newif\\if$fam\@math\\$fam\@mathfalse
\\DeclareOptionX{math}{\\$fam\@mathtrue}
\\DeclareOptionX{nomath}{\\$fam\@mathfalse}

\\newif\\if$fam\@mathgreek\\$fam\@mathgreektrue
\\DeclareOptionX{mathgreek}{\\$fam\@mathgreektrue}
\\DeclareOptionX{nomathgreek}{\\$fam\@mathgreekfalse}

\\newcommand*{\\$fam\@mathstyle}{TeX}
\\DeclareOptionX{math-style}{\\renewcommand*{\\$fam\@mathstyle}{#1}}

\\newcommand*{\\$fam\@Sscale}{1.1}
\\newcommand*{\\$fam\@SSscale}{\\fpeval{\\$fam\@Sscale * \\$fam\@Sscale}}
\\DeclareOptionX{scriptscale}{%
    \\renewcommand{\\$fam\@Sscale}{#1}%
    \\renewcommand{\\$fam\@SSscale}{\\fpeval{#1 * #1}}}

END_STY_MATHOPTION

        my ($mathfigurestyle_default, $mathfigurealign_default);
        if ($seen{OsF} or $seen{TOsF}) {
            print {$STY}
                "\\DeclareOptionX{matholdstyle}{\\edef\\$fam\@mathfigurestyle{OsF}}\n";
            $mathfigurestyle_default = 'OsF';
        }
        if ($seen{LF} or $seen{TLF}) {
            print {$STY}
                "\\DeclareOptionX{mathlining}{\\edef\\$fam\@mathfigurestyle{LF}}\n";
            $mathfigurestyle_default = 'LF';
        }
        if ($seen{LF} or $seen{OsF}) {
            print {$STY}
                "\\DeclareOptionX{mathproportional}{\\edef\\$fam\@mathfigurealign{}}\n";
            $mathfigurealign_default = '';
        }
        if ($seen{TLF} or $seen{TOsF}) {
            print {$STY}
                "\\DeclareOptionX{mathtabular}{\\edef\\$fam\@mathfigurealign{T}}\n";
            $mathfigurealign_default = 'T';
        }
        print {$STY} <<"END_STY_MATHDEFAULTS";
\\edef\\$fam\@mathfigurestyle{$mathfigurestyle_default}
\\edef\\$fam\@mathfigurealign{$mathfigurealign_default}

END_STY_MATHDEFAULTS

        if ($seen{sw}) {
            print {$STY} <<"END_STY_MATHCALOPTION";
\\newif\\if$fam\@mathcal\\$fam\@mathcalfalse
\\DeclareOptionX{mathcal}{\\$fam\@mathcaltrue}

END_STY_MATHCALOPTION
        }
    }

    print {$STY} <<"END_STY_PROCESSOPTIONS";
\\ProcessOptionsX\\relax

END_STY_PROCESSOPTIONS

    my @known_encodings = grep { $_ !~ m/\A U_/xmsi } @{$ARGV{encoding}};
    my $fontenc = join ',', grep { $_ ne 'OT1' } @known_encodings;
    if ($fontenc) {
        print {$STY} "\\RequirePackage[$fontenc]{fontenc}\n";
    }
    print {$STY} "\\RequirePackage{textcomp}\n" if $seen{TS1};
    print {$STY} "\\RequirePackage{ifthen}\n";
    print {$STY} "\\RequirePackage{xspace}\n";
    print {$STY} "\n";

    print {$STY} <<'END_STY_FIGUREVERSIONS_START';
\ExplSyntaxOn
\IfFileExists{figureversions.sty}{
    \RequirePackage{figureversions}

END_STY_FIGUREVERSIONS_START

    if ($seen{Sup}) {
        print {$STY} <<'END_STY_FIGUREVERSIONS_SUP';
    \figureversions_new_figurestyle:nnn {superior} {Sup} {Sup}
    \def\supfigures{\@nomath\supfigures
        \fontfigurestyle{superior}\selectfont}
    \let\sufigures\supfigures
    \DeclareTextFontCommand{\textsup}{\supfigures}
    \let\textsu\textsup
    \let\textsuperior\textsup
    \let\@oldtextsuperscript\textsuperscript
    \def\textsuperscript{\@ifstar\@oldtextsuperscript\textsup}
    \def\@makefnmark{%
        \mbox{\footnotemarkfont\textsuperscript{\@thefnmark}}}
    \@ifundefined{ftntm@font}%
        {\let\footnotemarkfont\normalfont}%
        {\let\footnotemarkfont\ftntm@font}

END_STY_FIGUREVERSIONS_SUP
    }

    if ($seen{Inf}) {
        print {$STY} <<'END_STY_FIGUREVERSIONS_INF';
    \figureversions_new_figurestyle:nnn {inferior} {Inf} {Inf}
    \def\inffigures{\@nomath\inffigures
        \fontfigurestyle{inferior}\selectfont}
    \let\infigures\inffigures
    \DeclareTextFontCommand{\textinf}{\inffigures}
    \let\textin\textinf
    \let\textinferior\textinf
    \let\@oldtextsubscript\textsubscript
    \def\textsubscript{\@ifstar\@oldtextsubscript\textinf}

END_STY_FIGUREVERSIONS_INF
    }

    if ($seen{Titl}) {
        print {$STY} <<'END_STY_FIGUREVERSIONS_TITL';
    \figureversions_new_figurestyle:nnn {titlingshape} {Titl} {Titl}
    \def\tlshape{\@nomath\tlshape
        \fontfigurestyle{titlingshape}\selectfont}
    \DeclareTextFontCommand{\texttl}{\tlshape}
    \let\texttitling\texttl

END_STY_FIGUREVERSIONS_TITL
    }

    if ($seen{Orn}) {
        print {$STY} <<'END_STY_FIGUREVERSIONS_ORN';
    \figureversions_new_figurestyle:nnn {ornament} {Orn} {Orn}
    \def\ornament{\@nomath\ornament
        \fontencoding{U}\fontfigurestyle{ornament}\selectfont}
    \newcommand*{\textornament}[1]{{\ornament\char##1}\xspace}
    % Backward-compatible alternates
    \let\ornaments\ornament
    \let\textornaments\textornament

END_STY_FIGUREVERSIONS_ORN
    }

    if ($seen{Numr}) {
        print {$STY} <<'END_STY_FIGUREVERSIONS_NUMR';
    \figureversions_new_figurestyle:nnn {numerators} {Numr} {Numr}
    \figureversions_new_figurestyle:nnn {numerator}  {Numr} {Numr}

END_STY_FIGUREVERSIONS_NUMR
    }

    if ($seen{Dnom}) {
        print {$STY} <<'END_STY_FIGUREVERSIONS_DNOM';
    \figureversions_new_figurestyle:nnn {denominators} {Dnom} {Dnom}
    \figureversions_new_figurestyle:nnn {denominator}  {Dnom} {Dnom}

END_STY_FIGUREVERSIONS_DNOM
    }

    print {$STY} "}{}\n\\ExplSyntaxOff\n\n";

    #   For the scale=MatchLowercase option, we need the name for
    #   one of the fonts from the family, to pass to plain TeX's
    #   \font macro (as explained below, we cannot use NFSS's
    #   font loading mechanism before we have calculated the correct
    #   scaling parameter).
    my $testfont = eval {
        my $testenc = $known_encodings[-1];
        my $testfig = ( grep { exists $data->{$testenc}{$_} }
                             qw(OsF LF TOsF TLF) )[0] or die;
        my $testweight = ( grep { $nfss_mapping->{$_} eq "m" }
                                keys %{$nfss_mapping} )[0] or die;
        my $testshape
            = ( grep { exists $data->{$testenc}{$testfig}{$testweight}{$_} }
                     qw(n sc it sl)
              )[0] or die;
        return $data->{$testenc}{$testfig}{$testweight}{$testshape}[0][2]
            || die;
    };

    if (defined $testfont) {
        print {$STY} <<"END_STY_MATCHLOWERCASE";
%   Here we implement the scale=MatchLowercase option.
%   If this is given, we must compute the correct value of
%   the "\\$fam\@scale" parameter before loading the .fd files;
%   but to determine that value we of course need the font's x-height.
%   To avoid triggering the loading of .fd files,
%   we use plain TeX's \\font primitive to load the testfont.
%   We then compute the ratio of the current x-height to our font's x-height;
%   this is the "\\$fam\@scale" we will pass to the .fd files.
\\ifthenelse{\\equal{\\$fam\@scale}{MatchLowercase}}
    {   \\newlength{\\$fam\@currentx}
        \\settoheight{\\$fam\@currentx}{x}
        \\newlength{\\$fam\@xheight}
        \\settoheight{\\$fam\@xheight}
            {{\\font\\testfont=$testfont at \\f\@size pt\\testfont x}}
        \\renewcommand*{\\$fam\@scale}
            {\\fpeval{\\$fam\@currentx / \\$fam\@xheight}}}
    {}

END_STY_MATCHLOWERCASE
    }

    print {$STY} <<"END_STYLE_REST";
\\renewcommand*
    {\\$ARGV{nfss}default}
    {$fam-\\$fam\@figurealign\\$fam\@figurestyle}

END_STYLE_REST

    if ($ARGV{math}) {
        print {$STY} <<"END_STY_MATH";
% Logically these definitions belong inside the \\if$fam\@math,
% but somehow Latex doesn't like that.
\\newif\\if$fam\@mathLATINup\\$fam\@mathLATINupfalse
\\newif\\if$fam\@mathlatinup\\$fam\@mathlatinupfalse
\\newif\\if$fam\@mathGREEKup\\$fam\@mathGREEKupfalse
\\newif\\if$fam\@mathgreekup\\$fam\@mathgreekupfalse

\\if$fam\@math
    \\ifthenelse{\\equal{\\$fam\@mathstyle}{TeX}}
        {\\$fam\@mathGREEKuptrue}
        {}
    \\ifthenelse{\\equal{\\$fam\@mathstyle}{french}}
        {\\$fam\@mathLATINuptrue
         \\$fam\@mathGREEKuptrue
         \\$fam\@mathgreekuptrue}
        {}
    \\ifthenelse{\\equal{\\$fam\@mathstyle}{upright}}
        {\\$fam\@mathLATINuptrue
         \\$fam\@mathlatinuptrue
         \\$fam\@mathGREEKuptrue
         \\$fam\@mathgreekuptrue}
        {}

    \\DeclareMathSizes{8}{8}{\\fpeval{\\$fam\@Sscale * 6}}{\\fpeval{\\$fam\@SSscale * 5}}
    \\DeclareMathSizes{9}{9}{\\fpeval{\\$fam\@Sscale * 6}}{\\fpeval{\\$fam\@SSscale * 5}}
    \\DeclareMathSizes{\\\@xpt}{\\\@xpt}{\\fpeval{\\$fam\@Sscale * 7}}{\\fpeval{\\$fam\@SSscale * 5}}
    \\DeclareMathSizes{\\\@xipt}{\\\@xipt}{\\fpeval{\\$fam\@Sscale * 8}}{\\fpeval{\\$fam\@SSscale * 6}}
    \\DeclareMathSizes{\\\@xiipt}{\\\@xiipt}{\\fpeval{\\$fam\@Sscale * 8}}{\\fpeval{\\$fam\@SSscale * 6}}
    \\DeclareMathSizes{\\\@xivpt}{\\\@xivpt}{\\fpeval{\\$fam\@Sscale * \\\@xpt}}{\\fpeval{\\$fam\@SSscale * 7}}
    \\DeclareMathSizes{\\\@xviipt}{\\\@xviipt}{\\fpeval{\\$fam\@Sscale * \\\@xiipt}}{\\fpeval{\\$fam\@SSscale * \\\@xpt}}
    \\DeclareMathSizes{\\\@xxpt}{\\\@xxpt}{\\fpeval{\\$fam\@Sscale * \\\@xivpt}}{\\fpeval{\\$fam\@SSscale * \\\@xiipt}}
    \\DeclareMathSizes{\\\@xxvpt}{\\\@xxvpt}{\\fpeval{\\$fam\@Sscale * \\\@xxpt}}{\\fpeval{\\$fam\@SSscale * \\\@xviipt}}

    \\def\\defaultscriptratio{\\fpeval{\\$fam\@Sscale * 0.7}}
    \\def\\defaultscriptscriptratio{\\fpeval{\\$fam\@SSscale * 0.5}}

    \\DeclareSymbolFont{newoperators}  {OT1}{$fam-\\$fam\@mathfigurealign\\$fam\@mathfigurestyle}{\\mdseries\@$ARGV{nfss}}{n}
    \\SetSymbolFont{newoperators}{bold}{OT1}{$fam-\\$fam\@mathfigurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{n}

    \\DeclareSymbolFont{newletters}  {OML}{$fam-\\$fam\@mathfigurealign\\$fam\@mathfigurestyle}{\\mdseries\@$ARGV{nfss}}{it}
    \\SetSymbolFont{newletters}{bold}{OML}{$fam-\\$fam\@mathfigurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{it}

    \\DeclareSymbolFontAlphabet{\\mathrm}{newoperators}
    \\DeclareSymbolFontAlphabet{\\mathnormal}{newletters}

    \\def\\operator\@font{\\mathgroup\\symnewoperators}
    \\SetMathAlphabet{\\mathit}{normal}{OT1}{$fam-\\$fam\@mathfigurealign\\$fam\@mathfigurestyle}{\\mdseries\@$ARGV{nfss}}{it}
    \\SetMathAlphabet{\\mathit}{bold}  {OT1}{$fam-\\$fam\@mathfigurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{it}

    \\SetMathAlphabet{\\mathbf}{normal}{OT1}{$fam-\\$fam\@mathfigurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{n}
    \\SetMathAlphabet{\\mathbf}{bold}  {OT1}{$fam-\\$fam\@mathfigurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{n}

    \\def\\re\@DeclareMathSymbol#1#2#3#4{%
        \\if\\relax\\noexpand#1\\let#1=\\undefined\\fi
        \\DeclareMathSymbol{#1}{#2}{#3}{#4}}

    \\def\\re\@DeclareMathDelimiter#1#2#3#4#5#6{%
        \\let#1=\\undefined
        \\DeclareMathDelimiter{#1}{#2}{#3}{#4}{#5}{#6}}

    \\def\\re\@DeclareMathAccent#1#2#3#4{%
        \\let#1=\\undefined
        \\DeclareMathAccent{#1}{#2}{#3}{#4}}

    \\re\@DeclareMathSymbol{0}{\\mathalpha}{newoperators}{`0}
    \\re\@DeclareMathSymbol{1}{\\mathalpha}{newoperators}{`1}
    \\re\@DeclareMathSymbol{2}{\\mathalpha}{newoperators}{`2}
    \\re\@DeclareMathSymbol{3}{\\mathalpha}{newoperators}{`3}
    \\re\@DeclareMathSymbol{4}{\\mathalpha}{newoperators}{`4}
    \\re\@DeclareMathSymbol{5}{\\mathalpha}{newoperators}{`5}
    \\re\@DeclareMathSymbol{6}{\\mathalpha}{newoperators}{`6}
    \\re\@DeclareMathSymbol{7}{\\mathalpha}{newoperators}{`7}
    \\re\@DeclareMathSymbol{8}{\\mathalpha}{newoperators}{`8}
    \\re\@DeclareMathSymbol{9}{\\mathalpha}{newoperators}{`9}

    \\re\@DeclareMathSymbol{a}{\\mathalpha}{newletters}{`a}
    \\re\@DeclareMathSymbol{b}{\\mathalpha}{newletters}{`b}
    \\re\@DeclareMathSymbol{c}{\\mathalpha}{newletters}{`c}
    \\re\@DeclareMathSymbol{d}{\\mathalpha}{newletters}{`d}
    \\re\@DeclareMathSymbol{e}{\\mathalpha}{newletters}{`e}
    \\re\@DeclareMathSymbol{f}{\\mathalpha}{newletters}{`f}
    \\re\@DeclareMathSymbol{g}{\\mathalpha}{newletters}{`g}
    \\re\@DeclareMathSymbol{h}{\\mathalpha}{newletters}{`h}
    \\re\@DeclareMathSymbol{i}{\\mathalpha}{newletters}{`i}
    \\re\@DeclareMathSymbol{j}{\\mathalpha}{newletters}{`j}
    \\re\@DeclareMathSymbol{k}{\\mathalpha}{newletters}{`k}
    \\re\@DeclareMathSymbol{l}{\\mathalpha}{newletters}{`l}
    \\re\@DeclareMathSymbol{m}{\\mathalpha}{newletters}{`m}
    \\re\@DeclareMathSymbol{n}{\\mathalpha}{newletters}{`n}
    \\re\@DeclareMathSymbol{o}{\\mathalpha}{newletters}{`o}
    \\re\@DeclareMathSymbol{p}{\\mathalpha}{newletters}{`p}
    \\re\@DeclareMathSymbol{q}{\\mathalpha}{newletters}{`q}
    \\re\@DeclareMathSymbol{r}{\\mathalpha}{newletters}{`r}
    \\re\@DeclareMathSymbol{s}{\\mathalpha}{newletters}{`s}
    \\re\@DeclareMathSymbol{t}{\\mathalpha}{newletters}{`t}
    \\re\@DeclareMathSymbol{u}{\\mathalpha}{newletters}{`u}
    \\re\@DeclareMathSymbol{v}{\\mathalpha}{newletters}{`v}
    \\re\@DeclareMathSymbol{w}{\\mathalpha}{newletters}{`w}
    \\re\@DeclareMathSymbol{x}{\\mathalpha}{newletters}{`x}
    \\re\@DeclareMathSymbol{y}{\\mathalpha}{newletters}{`y}
    \\re\@DeclareMathSymbol{z}{\\mathalpha}{newletters}{`z}

    \\re\@DeclareMathSymbol{A}{\\mathalpha}{newletters}{`A}
    \\re\@DeclareMathSymbol{B}{\\mathalpha}{newletters}{`B}
    \\re\@DeclareMathSymbol{C}{\\mathalpha}{newletters}{`C}
    \\re\@DeclareMathSymbol{D}{\\mathalpha}{newletters}{`D}
    \\re\@DeclareMathSymbol{E}{\\mathalpha}{newletters}{`E}
    \\re\@DeclareMathSymbol{F}{\\mathalpha}{newletters}{`F}
    \\re\@DeclareMathSymbol{G}{\\mathalpha}{newletters}{`G}
    \\re\@DeclareMathSymbol{H}{\\mathalpha}{newletters}{`H}
    \\re\@DeclareMathSymbol{I}{\\mathalpha}{newletters}{`I}
    \\re\@DeclareMathSymbol{J}{\\mathalpha}{newletters}{`J}
    \\re\@DeclareMathSymbol{K}{\\mathalpha}{newletters}{`K}
    \\re\@DeclareMathSymbol{L}{\\mathalpha}{newletters}{`L}
    \\re\@DeclareMathSymbol{M}{\\mathalpha}{newletters}{`M}
    \\re\@DeclareMathSymbol{N}{\\mathalpha}{newletters}{`N}
    \\re\@DeclareMathSymbol{O}{\\mathalpha}{newletters}{`O}
    \\re\@DeclareMathSymbol{P}{\\mathalpha}{newletters}{`P}
    \\re\@DeclareMathSymbol{Q}{\\mathalpha}{newletters}{`Q}
    \\re\@DeclareMathSymbol{R}{\\mathalpha}{newletters}{`R}
    \\re\@DeclareMathSymbol{S}{\\mathalpha}{newletters}{`S}
    \\re\@DeclareMathSymbol{T}{\\mathalpha}{newletters}{`T}
    \\re\@DeclareMathSymbol{U}{\\mathalpha}{newletters}{`U}
    \\re\@DeclareMathSymbol{V}{\\mathalpha}{newletters}{`V}
    \\re\@DeclareMathSymbol{W}{\\mathalpha}{newletters}{`W}
    \\re\@DeclareMathSymbol{X}{\\mathalpha}{newletters}{`X}
    \\re\@DeclareMathSymbol{Y}{\\mathalpha}{newletters}{`Y}
    \\re\@DeclareMathSymbol{Z}{\\mathalpha}{newletters}{`Z}

    \\re\@DeclareMathSymbol{\\partial}{\\mathord}{newletters}{"40}
    \\re\@DeclareMathSymbol{\\ell}    {\\mathord}{newletters}{"60}
    \\re\@DeclareMathSymbol{\\imath}  {\\mathord}{newletters}{"7B}
    \\re\@DeclareMathSymbol{\\jmath}  {\\mathord}{newletters}{"7C}

    %
    %   A number of math symbol declarations have been commented out,
    %   since these characters generally do not work very well when
    %   typesetting maths (either because of spacing issues or because
    %   they don't mix with others symbols).
    %   The commented-out declarations have been left in this style file
    %   in case the user does want to re-activate those characters.
    %

    \\re\@DeclareMathSymbol{!}{\\mathclose}{newoperators}{"21}
  % \\re\@DeclareMathSymbol{+}{\\mathbin}  {newoperators}{"2B}
  % \\re\@DeclareMathSymbol{:}{\\mathrel}  {newoperators}{"3A}
    \\re\@DeclareMathSymbol{;}{\\mathpunct}{newoperators}{"3B}
  % \\re\@DeclareMathSymbol{=}{\\mathrel}  {newoperators}{"3D}
    \\re\@DeclareMathSymbol{?}{\\mathclose}{newoperators}{"3F}

  % \\re\@DeclareMathSymbol{.}{\\mathord}  {newletters}{"3A}
    \\re\@DeclareMathSymbol{,}{\\mathpunct}{newletters}{"3B}
  % \\re\@DeclareMathSymbol{<}{\\mathrel}  {newletters}{"3C}
  % \\re\@DeclareMathSymbol{/}{\\mathord}  {newletters}{"3D}
  % \\re\@DeclareMathSymbol{>}{\\mathrel}  {newletters}{"3E}

    \\re\@DeclareMathSymbol{\\mathdollar}{\\mathord}  {newoperators}{"24}
    \\re\@DeclareMathSymbol{\\colon}     {\\mathpunct}{newoperators}{"3A}

  % \\DeclareMathDelimiter{(}{\\mathopen} {newoperators}{"28}{largesymbols}{"00}
  % \\DeclareMathDelimiter{)}{\\mathclose}{newoperators}{"29}{largesymbols}{"01}
  % \\DeclareMathDelimiter{[}{\\mathopen} {newoperators}{"5B}{largesymbols}{"02}
  % \\DeclareMathDelimiter{]}{\\mathclose}{newoperators}{"5D}{largesymbols}{"03}
  % \\DeclareMathDelimiter{/}{\\mathord}  {newoperators}{"2F}{largesymbols}{"0E}

    \\re\@DeclareMathAccent{\\grave}   {\\mathalpha}{newoperators}{"12}
    \\re\@DeclareMathAccent{\\acute}   {\\mathalpha}{newoperators}{"13}
    \\re\@DeclareMathAccent{\\check}   {\\mathalpha}{newoperators}{"14}
    \\re\@DeclareMathAccent{\\breve}   {\\mathalpha}{newoperators}{"15}
    \\re\@DeclareMathAccent{\\bar}     {\\mathalpha}{newoperators}{"16}
    \\re\@DeclareMathAccent{\\mathring}{\\mathalpha}{newoperators}{"17}
    \\re\@DeclareMathAccent{\\hat}     {\\mathalpha}{newoperators}{"5E}
    \\re\@DeclareMathAccent{\\dot}     {\\mathalpha}{newoperators}{"5F}
    \\re\@DeclareMathAccent{\\tilde}   {\\mathalpha}{newoperators}{"7E}
    \\re\@DeclareMathAccent{\\ddot}    {\\mathalpha}{newoperators}{"7F}

    \\if$fam\@mathgreek
        \\re\@DeclareMathSymbol{\\Gamma}    {\\mathalpha}{newoperators}{"00}
        \\re\@DeclareMathSymbol{\\Delta}    {\\mathalpha}{newoperators}{"01}
        \\re\@DeclareMathSymbol{\\Theta}    {\\mathalpha}{newoperators}{"02}
        \\re\@DeclareMathSymbol{\\Lambda}   {\\mathalpha}{newoperators}{"03}
        \\re\@DeclareMathSymbol{\\Xi}       {\\mathalpha}{newoperators}{"04}
        \\re\@DeclareMathSymbol{\\Pi}       {\\mathalpha}{newoperators}{"05}
        \\re\@DeclareMathSymbol{\\Sigma}    {\\mathalpha}{newoperators}{"06}
        \\re\@DeclareMathSymbol{\\Upsilon}  {\\mathalpha}{newoperators}{"07}
        \\re\@DeclareMathSymbol{\\Phi}      {\\mathalpha}{newoperators}{"08}
        \\re\@DeclareMathSymbol{\\Psi}      {\\mathalpha}{newoperators}{"09}
        \\re\@DeclareMathSymbol{\\Omega}    {\\mathalpha}{newoperators}{"0A}

        \\re\@DeclareMathSymbol{\\upGamma}  {\\mathalpha}{newoperators}{"00}
        \\re\@DeclareMathSymbol{\\upDelta}  {\\mathalpha}{newoperators}{"01}
        \\re\@DeclareMathSymbol{\\upTheta}  {\\mathalpha}{newoperators}{"02}
        \\re\@DeclareMathSymbol{\\upLambda} {\\mathalpha}{newoperators}{"03}
        \\re\@DeclareMathSymbol{\\upXi}     {\\mathalpha}{newoperators}{"04}
        \\re\@DeclareMathSymbol{\\upPi}     {\\mathalpha}{newoperators}{"05}
        \\re\@DeclareMathSymbol{\\upSigma}  {\\mathalpha}{newoperators}{"06}
        \\re\@DeclareMathSymbol{\\upUpsilon}{\\mathalpha}{newoperators}{"07}
        \\re\@DeclareMathSymbol{\\upPhi}    {\\mathalpha}{newoperators}{"08}
        \\re\@DeclareMathSymbol{\\upPsi}    {\\mathalpha}{newoperators}{"09}
        \\re\@DeclareMathSymbol{\\upOmega}  {\\mathalpha}{newoperators}{"0A}

        \\re\@DeclareMathSymbol{\\alpha}       {\\mathord}{newletters}{"0B}
        \\re\@DeclareMathSymbol{\\beta}        {\\mathord}{newletters}{"0C}
        \\re\@DeclareMathSymbol{\\gamma}       {\\mathord}{newletters}{"0D}
        \\re\@DeclareMathSymbol{\\delta}       {\\mathord}{newletters}{"0E}
        \\re\@DeclareMathSymbol{\\epsilon}     {\\mathord}{newletters}{"0F}
        \\re\@DeclareMathSymbol{\\zeta}        {\\mathord}{newletters}{"10}
        \\re\@DeclareMathSymbol{\\eta}         {\\mathord}{newletters}{"11}
        \\re\@DeclareMathSymbol{\\theta}       {\\mathord}{newletters}{"12}
        \\re\@DeclareMathSymbol{\\iota}        {\\mathord}{newletters}{"13}
        \\re\@DeclareMathSymbol{\\kappa}       {\\mathord}{newletters}{"14}
        \\re\@DeclareMathSymbol{\\lambda}      {\\mathord}{newletters}{"15}
        \\re\@DeclareMathSymbol{\\mu}          {\\mathord}{newletters}{"16}
        \\re\@DeclareMathSymbol{\\nu}          {\\mathord}{newletters}{"17}
        \\re\@DeclareMathSymbol{\\xi}          {\\mathord}{newletters}{"18}
        \\re\@DeclareMathSymbol{\\pi}          {\\mathord}{newletters}{"19}
        \\re\@DeclareMathSymbol{\\rho}         {\\mathord}{newletters}{"1A}
        \\re\@DeclareMathSymbol{\\sigma}       {\\mathord}{newletters}{"1B}
        \\re\@DeclareMathSymbol{\\tau}         {\\mathord}{newletters}{"1C}
        \\re\@DeclareMathSymbol{\\upsilon}     {\\mathord}{newletters}{"1D}
        \\re\@DeclareMathSymbol{\\phi}         {\\mathord}{newletters}{"1E}
        \\re\@DeclareMathSymbol{\\chi}         {\\mathord}{newletters}{"1F}
        \\re\@DeclareMathSymbol{\\psi}         {\\mathord}{newletters}{"20}
        \\re\@DeclareMathSymbol{\\omega}       {\\mathord}{newletters}{"21}
        \\re\@DeclareMathSymbol{\\varepsilon}  {\\mathord}{newletters}{"22}
        \\re\@DeclareMathSymbol{\\vartheta}    {\\mathord}{newletters}{"23}
        \\re\@DeclareMathSymbol{\\varpi}       {\\mathord}{newletters}{"24}
        \\re\@DeclareMathSymbol{\\varrho}      {\\mathord}{newletters}{"25}
        \\re\@DeclareMathSymbol{\\varsigma}    {\\mathord}{newletters}{"26}
        \\re\@DeclareMathSymbol{\\varphi}      {\\mathord}{newletters}{"27}

        \\re\@DeclareMathSymbol{\\italpha}     {\\mathord}{newletters}{"0B}
        \\re\@DeclareMathSymbol{\\itbeta}      {\\mathord}{newletters}{"0C}
        \\re\@DeclareMathSymbol{\\itgamma}     {\\mathord}{newletters}{"0D}
        \\re\@DeclareMathSymbol{\\itdelta}     {\\mathord}{newletters}{"0E}
        \\re\@DeclareMathSymbol{\\itepsilon}   {\\mathord}{newletters}{"0F}
        \\re\@DeclareMathSymbol{\\itzeta}      {\\mathord}{newletters}{"10}
        \\re\@DeclareMathSymbol{\\iteta}       {\\mathord}{newletters}{"11}
        \\re\@DeclareMathSymbol{\\ittheta}     {\\mathord}{newletters}{"12}
        \\re\@DeclareMathSymbol{\\itiota}      {\\mathord}{newletters}{"13}
        \\re\@DeclareMathSymbol{\\itkappa}     {\\mathord}{newletters}{"14}
        \\re\@DeclareMathSymbol{\\itlambda}    {\\mathord}{newletters}{"15}
        \\re\@DeclareMathSymbol{\\itmu}        {\\mathord}{newletters}{"16}
        \\re\@DeclareMathSymbol{\\itnu}        {\\mathord}{newletters}{"17}
        \\re\@DeclareMathSymbol{\\itxi}        {\\mathord}{newletters}{"18}
        \\re\@DeclareMathSymbol{\\itpi}        {\\mathord}{newletters}{"19}
        \\re\@DeclareMathSymbol{\\itrho}       {\\mathord}{newletters}{"1A}
        \\re\@DeclareMathSymbol{\\itsigma}     {\\mathord}{newletters}{"1B}
        \\re\@DeclareMathSymbol{\\ittau}       {\\mathord}{newletters}{"1C}
        \\re\@DeclareMathSymbol{\\itupsilon}   {\\mathord}{newletters}{"1D}
        \\re\@DeclareMathSymbol{\\itphi}       {\\mathord}{newletters}{"1E}
        \\re\@DeclareMathSymbol{\\itchi}       {\\mathord}{newletters}{"1F}
        \\re\@DeclareMathSymbol{\\itpsi}       {\\mathord}{newletters}{"20}
        \\re\@DeclareMathSymbol{\\itomega}     {\\mathord}{newletters}{"21}
        \\re\@DeclareMathSymbol{\\itvarepsilon}{\\mathord}{newletters}{"22}
        \\re\@DeclareMathSymbol{\\itvartheta}  {\\mathord}{newletters}{"23}
        \\re\@DeclareMathSymbol{\\itvarpi}     {\\mathord}{newletters}{"24}
        \\re\@DeclareMathSymbol{\\itvarrho}    {\\mathord}{newletters}{"25}
        \\re\@DeclareMathSymbol{\\itvarsigma}  {\\mathord}{newletters}{"26}
        \\re\@DeclareMathSymbol{\\itvarphi}    {\\mathord}{newletters}{"27}
    \\fi

    \\if$fam\@mathLATINup
        \\re\@DeclareMathSymbol{A}{\\mathalpha}{newoperators}{`A}
        \\re\@DeclareMathSymbol{B}{\\mathalpha}{newoperators}{`B}
        \\re\@DeclareMathSymbol{C}{\\mathalpha}{newoperators}{`C}
        \\re\@DeclareMathSymbol{D}{\\mathalpha}{newoperators}{`D}
        \\re\@DeclareMathSymbol{E}{\\mathalpha}{newoperators}{`E}
        \\re\@DeclareMathSymbol{F}{\\mathalpha}{newoperators}{`F}
        \\re\@DeclareMathSymbol{G}{\\mathalpha}{newoperators}{`G}
        \\re\@DeclareMathSymbol{H}{\\mathalpha}{newoperators}{`H}
        \\re\@DeclareMathSymbol{I}{\\mathalpha}{newoperators}{`I}
        \\re\@DeclareMathSymbol{J}{\\mathalpha}{newoperators}{`J}
        \\re\@DeclareMathSymbol{K}{\\mathalpha}{newoperators}{`K}
        \\re\@DeclareMathSymbol{L}{\\mathalpha}{newoperators}{`L}
        \\re\@DeclareMathSymbol{M}{\\mathalpha}{newoperators}{`M}
        \\re\@DeclareMathSymbol{N}{\\mathalpha}{newoperators}{`N}
        \\re\@DeclareMathSymbol{O}{\\mathalpha}{newoperators}{`O}
        \\re\@DeclareMathSymbol{P}{\\mathalpha}{newoperators}{`P}
        \\re\@DeclareMathSymbol{Q}{\\mathalpha}{newoperators}{`Q}
        \\re\@DeclareMathSymbol{R}{\\mathalpha}{newoperators}{`R}
        \\re\@DeclareMathSymbol{S}{\\mathalpha}{newoperators}{`S}
        \\re\@DeclareMathSymbol{T}{\\mathalpha}{newoperators}{`T}
        \\re\@DeclareMathSymbol{U}{\\mathalpha}{newoperators}{`U}
        \\re\@DeclareMathSymbol{V}{\\mathalpha}{newoperators}{`V}
        \\re\@DeclareMathSymbol{W}{\\mathalpha}{newoperators}{`W}
        \\re\@DeclareMathSymbol{X}{\\mathalpha}{newoperators}{`X}
        \\re\@DeclareMathSymbol{Y}{\\mathalpha}{newoperators}{`Y}
        \\re\@DeclareMathSymbol{Z}{\\mathalpha}{newoperators}{`Z}
    \\fi

    \\if$fam\@mathlatinup
        \\DeclareSymbolFont{upletters}  {OML}{$fam-\\$fam\@mathfigurealign\\$fam\@mathfigurestyle}{\\mdseries\@$ARGV{nfss}}{n}
        \\SetSymbolFont{upletters}{bold}{OML}{$fam-\\$fam\@mathfigurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{n}

        \\re\@DeclareMathSymbol{a}{\\mathord}{upletters}{`a}
        \\re\@DeclareMathSymbol{b}{\\mathord}{upletters}{`b}
        \\re\@DeclareMathSymbol{c}{\\mathord}{upletters}{`c}
        \\re\@DeclareMathSymbol{d}{\\mathord}{upletters}{`d}
        \\re\@DeclareMathSymbol{e}{\\mathord}{upletters}{`e}
        \\re\@DeclareMathSymbol{f}{\\mathord}{upletters}{`f}
        \\re\@DeclareMathSymbol{g}{\\mathord}{upletters}{`g}
        \\re\@DeclareMathSymbol{h}{\\mathord}{upletters}{`h}
        \\re\@DeclareMathSymbol{i}{\\mathord}{upletters}{`i}
        \\re\@DeclareMathSymbol{j}{\\mathord}{upletters}{`j}
        \\re\@DeclareMathSymbol{k}{\\mathord}{upletters}{`k}
        \\re\@DeclareMathSymbol{l}{\\mathord}{upletters}{`l}
        \\re\@DeclareMathSymbol{m}{\\mathord}{upletters}{`m}
        \\re\@DeclareMathSymbol{n}{\\mathord}{upletters}{`n}
        \\re\@DeclareMathSymbol{o}{\\mathord}{upletters}{`o}
        \\re\@DeclareMathSymbol{p}{\\mathord}{upletters}{`p}
        \\re\@DeclareMathSymbol{q}{\\mathord}{upletters}{`q}
        \\re\@DeclareMathSymbol{r}{\\mathord}{upletters}{`r}
        \\re\@DeclareMathSymbol{s}{\\mathord}{upletters}{`s}
        \\re\@DeclareMathSymbol{t}{\\mathord}{upletters}{`t}
        \\re\@DeclareMathSymbol{u}{\\mathord}{upletters}{`u}
        \\re\@DeclareMathSymbol{v}{\\mathord}{upletters}{`v}
        \\re\@DeclareMathSymbol{w}{\\mathord}{upletters}{`w}
        \\re\@DeclareMathSymbol{x}{\\mathord}{upletters}{`x}
        \\re\@DeclareMathSymbol{y}{\\mathord}{upletters}{`y}
        \\re\@DeclareMathSymbol{z}{\\mathord}{upletters}{`z}

        \\re\@DeclareMathSymbol{\\imath}{\\mathord}{upletters}{"7B}
        \\re\@DeclareMathSymbol{\\jmath}{\\mathord}{upletters}{"7C}
    \\fi

    \\if$fam\@mathgreek
        \\if$fam\@mathGREEKup
        \\else
            \\re\@DeclareMathSymbol{\\Gamma}  {\\mathalpha}{newletters}{"00}
            \\re\@DeclareMathSymbol{\\Delta}  {\\mathalpha}{newletters}{"01}
            \\re\@DeclareMathSymbol{\\Theta}  {\\mathalpha}{newletters}{"02}
            \\re\@DeclareMathSymbol{\\Lambda} {\\mathalpha}{newletters}{"03}
            \\re\@DeclareMathSymbol{\\Xi}     {\\mathalpha}{newletters}{"04}
            \\re\@DeclareMathSymbol{\\Pi}     {\\mathalpha}{newletters}{"05}
            \\re\@DeclareMathSymbol{\\Sigma}  {\\mathalpha}{newletters}{"06}
            \\re\@DeclareMathSymbol{\\Upsilon}{\\mathalpha}{newletters}{"07}
            \\re\@DeclareMathSymbol{\\Phi}    {\\mathalpha}{newletters}{"08}
            \\re\@DeclareMathSymbol{\\Psi}    {\\mathalpha}{newletters}{"09}
            \\re\@DeclareMathSymbol{\\Omega}  {\\mathalpha}{newletters}{"0A}
        \\fi
        \\re\@DeclareMathSymbol{\\itGamma}  {\\mathalpha}{newletters}{"00}
        \\re\@DeclareMathSymbol{\\itDelta}  {\\mathalpha}{newletters}{"01}
        \\re\@DeclareMathSymbol{\\itTheta}  {\\mathalpha}{newletters}{"02}
        \\re\@DeclareMathSymbol{\\itLambda} {\\mathalpha}{newletters}{"03}
        \\re\@DeclareMathSymbol{\\itXi}     {\\mathalpha}{newletters}{"04}
        \\re\@DeclareMathSymbol{\\itPi}     {\\mathalpha}{newletters}{"05}
        \\re\@DeclareMathSymbol{\\itSigma}  {\\mathalpha}{newletters}{"06}
        \\re\@DeclareMathSymbol{\\itUpsilon}{\\mathalpha}{newletters}{"07}
        \\re\@DeclareMathSymbol{\\itPhi}    {\\mathalpha}{newletters}{"08}
        \\re\@DeclareMathSymbol{\\itPsi}    {\\mathalpha}{newletters}{"09}
        \\re\@DeclareMathSymbol{\\itOmega}  {\\mathalpha}{newletters}{"0A}

        \\DeclareSymbolFont{upletters}  {OML}{$fam-\\$fam\@mathfigurealign\\$fam\@mathfigurestyle}{\\mdseries\@$ARGV{nfss}}{n}
        \\SetSymbolFont{upletters}{bold}{OML}{$fam-\\$fam\@mathfigurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{n}
        \\if$fam\@mathgreekup
            \\re\@DeclareMathSymbol{\\alpha}     {\\mathord}{upletters}{"0B}
            \\re\@DeclareMathSymbol{\\beta}      {\\mathord}{upletters}{"0C}
            \\re\@DeclareMathSymbol{\\gamma}     {\\mathord}{upletters}{"0D}
            \\re\@DeclareMathSymbol{\\delta}     {\\mathord}{upletters}{"0E}
            \\re\@DeclareMathSymbol{\\epsilon}   {\\mathord}{upletters}{"0F}
            \\re\@DeclareMathSymbol{\\zeta}      {\\mathord}{upletters}{"10}
            \\re\@DeclareMathSymbol{\\eta}       {\\mathord}{upletters}{"11}
            \\re\@DeclareMathSymbol{\\theta}     {\\mathord}{upletters}{"12}
            \\re\@DeclareMathSymbol{\\iota}      {\\mathord}{upletters}{"13}
            \\re\@DeclareMathSymbol{\\kappa}     {\\mathord}{upletters}{"14}
            \\re\@DeclareMathSymbol{\\lambda}    {\\mathord}{upletters}{"15}
            \\re\@DeclareMathSymbol{\\mu}        {\\mathord}{upletters}{"16}
            \\re\@DeclareMathSymbol{\\nu}        {\\mathord}{upletters}{"17}
            \\re\@DeclareMathSymbol{\\xi}        {\\mathord}{upletters}{"18}
            \\re\@DeclareMathSymbol{\\pi}        {\\mathord}{upletters}{"19}
            \\re\@DeclareMathSymbol{\\rho}       {\\mathord}{upletters}{"1A}
            \\re\@DeclareMathSymbol{\\sigma}     {\\mathord}{upletters}{"1B}
            \\re\@DeclareMathSymbol{\\tau}       {\\mathord}{upletters}{"1C}
            \\re\@DeclareMathSymbol{\\upsilon}   {\\mathord}{upletters}{"1D}
            \\re\@DeclareMathSymbol{\\phi}       {\\mathord}{upletters}{"1E}
            \\re\@DeclareMathSymbol{\\chi}       {\\mathord}{upletters}{"1F}
            \\re\@DeclareMathSymbol{\\psi}       {\\mathord}{upletters}{"20}
            \\re\@DeclareMathSymbol{\\omega}     {\\mathord}{upletters}{"21}
            \\re\@DeclareMathSymbol{\\varepsilon}{\\mathord}{upletters}{"22}
            \\re\@DeclareMathSymbol{\\vartheta}  {\\mathord}{upletters}{"23}
            \\re\@DeclareMathSymbol{\\varpi}     {\\mathord}{upletters}{"24}
            \\re\@DeclareMathSymbol{\\varrho}    {\\mathord}{upletters}{"25}
            \\re\@DeclareMathSymbol{\\varsigma}  {\\mathord}{upletters}{"26}
            \\re\@DeclareMathSymbol{\\varphi}    {\\mathord}{upletters}{"27}
        \\fi
        \\re\@DeclareMathSymbol{\\upalpha}     {\\mathord}{upletters}{"0B}
        \\re\@DeclareMathSymbol{\\upbeta}      {\\mathord}{upletters}{"0C}
        \\re\@DeclareMathSymbol{\\upgamma}     {\\mathord}{upletters}{"0D}
        \\re\@DeclareMathSymbol{\\updelta}     {\\mathord}{upletters}{"0E}
        \\re\@DeclareMathSymbol{\\upepsilon}   {\\mathord}{upletters}{"0F}
        \\re\@DeclareMathSymbol{\\upzeta}      {\\mathord}{upletters}{"10}
        \\re\@DeclareMathSymbol{\\upeta}       {\\mathord}{upletters}{"11}
        \\re\@DeclareMathSymbol{\\uptheta}     {\\mathord}{upletters}{"12}
        \\re\@DeclareMathSymbol{\\upiota}      {\\mathord}{upletters}{"13}
        \\re\@DeclareMathSymbol{\\upkappa}     {\\mathord}{upletters}{"14}
        \\re\@DeclareMathSymbol{\\uplambda}    {\\mathord}{upletters}{"15}
        \\re\@DeclareMathSymbol{\\upmu}        {\\mathord}{upletters}{"16}
        \\re\@DeclareMathSymbol{\\upnu}        {\\mathord}{upletters}{"17}
        \\re\@DeclareMathSymbol{\\upxi}        {\\mathord}{upletters}{"18}
        \\re\@DeclareMathSymbol{\\uppi}        {\\mathord}{upletters}{"19}
        \\re\@DeclareMathSymbol{\\uprho}       {\\mathord}{upletters}{"1A}
        \\re\@DeclareMathSymbol{\\upsigma}     {\\mathord}{upletters}{"1B}
        \\re\@DeclareMathSymbol{\\uptau}       {\\mathord}{upletters}{"1C}
        \\re\@DeclareMathSymbol{\\upupsilon}   {\\mathord}{upletters}{"1D}
        \\re\@DeclareMathSymbol{\\upphi}       {\\mathord}{upletters}{"1E}
        \\re\@DeclareMathSymbol{\\upchi}       {\\mathord}{upletters}{"1F}
        \\re\@DeclareMathSymbol{\\uppsi}       {\\mathord}{upletters}{"20}
        \\re\@DeclareMathSymbol{\\upomega}     {\\mathord}{upletters}{"21}
        \\re\@DeclareMathSymbol{\\upvarepsilon}{\\mathord}{upletters}{"22}
        \\re\@DeclareMathSymbol{\\upvartheta}  {\\mathord}{upletters}{"23}
        \\re\@DeclareMathSymbol{\\upvarpi}     {\\mathord}{upletters}{"24}
        \\re\@DeclareMathSymbol{\\upvarrho}    {\\mathord}{upletters}{"25}
        \\re\@DeclareMathSymbol{\\upvarsigma}  {\\mathord}{upletters}{"26}
        \\re\@DeclareMathSymbol{\\upvarphi}    {\\mathord}{upletters}{"27}
    \\fi
\\fi

END_STY_MATH

        if ($seen{sw}) {
            print {$STY} <<"END_STY_MATHCAL";
\\if$fam\@mathcal
    \\SetMathAlphabet{\\mathcal}{normal}{OT1}{$fam-\\$fam\@mathfigurealign\\$fam\@mathfigurestyle}{\\mdseries\@$ARGV{nfss}}{sw}
    \\SetMathAlphabet{\\mathcal}{bold}  {OT1}{$fam-\\$fam\@mathfigurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{sw}
\\fi

END_STY_MATHCAL
        }
    }

    print {$STY} "\\endinput\n";
    close $STY;

    return;
}


# --------------------------------------------------------------------------
#   Creates a .fd file for LaTeX.
# --------------------------------------------------------------------------
sub create_fdfile {
    my ($nfss_mapping, $fam, $enc, $sty, $data) = @_;

    my $fn = sprintf "%s%s-%s.fd", $enc, $fam, $sty;
    my $dir = File::Spec->catdir(
        $ARGV{target}, 'tex', 'latex', $ARGV{typeface} || $fam);
    File::Path::make_path($dir);
    $fn = File::Spec->catfile($dir, $fn);
    open my $FD, '>', $fn
        or die "[ERROR]     Can't create '$fn': $!";
    binmode $FD;

    print {$FD} <<"END_FD_HEADER";
%% Generated by autoinst on $TODAY
%%
\\ProvidesFile{$enc$fam-$sty.fd}
    [$TODAY (autoinst)  Font definitions for $enc/$fam-$sty.]

\\ifcsname s\@fct\@alias\\endcsname\\else
\\gdef\\s\@fct\@alias{\\sub\@sfcnt\\\@font\@aliasinfo}
\\gdef\\\@font\@aliasinfo#1{%
    \\\@font\@info{Font\\space shape\\space `\\curr\@fontshape'\\space will
        \\space be\\space aliased\\MessageBreak to\\space `\\mandatory\@arg'}%
}
\\fi

\\expandafter\\ifx\\csname $fam\@scale\\endcsname\\relax
    \\let\\$fam\@\@scale\\\@empty
\\else
    \\edef\\$fam\@\@scale{s*[\\csname $fam\@scale\\endcsname]}%
\\fi

\\DeclareFontFamily{$enc}{$fam-$sty}{@{[
    $ARGV{nfss} eq 'tt' ? '\hyphenchar\font=-1'
    : $enc eq 'OML'     ? '\skewchar\font=127'
    :                     q{}
]}}

END_FD_HEADER

    while (my ($series, $fdseries) = each %$data) {
        my $nfssseries = $nfss_mapping->{$series};

        my $alias = $series;
        if (defined $nfssseries) {
            print {$FD} "\n%   ----  $nfssseries = $series  ----\n\n";
            $series = $nfssseries;
        }
        else {
            print {$FD} "\n%   ----  $series  ----\n\n";
        }
        while (my ($shape, $fdshape) = each %$fdseries) {
            print {$FD}
                "\\DeclareFontShape{$enc}{$fam-$sty}{$series}{$shape}{\n";
            my @sizes = sort { $a->[0] <=> $b->[0] }
                                @{$fdshape};
            $sizes[0][0] = $sizes[-1][1] = '';
            $sizes[$_][0] = $sizes[$_ - 1][1] for (1 .. $#sizes);
            for my $size (@sizes) {
                print {$FD} "      <$size->[0]-$size->[1]> ",
                            "\\$fam\@\@scale $size->[2]\n";
            }
            print {$FD} "}{}\n\n";

            if (defined $nfssseries) {
                print {$FD} <<"END_ALIAS_SERIES";
\\DeclareFontShape{$enc}{$fam-$sty}{$alias}{$shape}{
      <-> alias * $fam-$sty/$nfssseries/$shape
}{}

END_ALIAS_SERIES
            }
        }

        # ssub italic for missing slanted, or vice versa
        while (my ($shape, $replace) = each %SSUB_SHAPE) {
            if (!exists $fdseries->{$shape} && exists $fdseries->{$replace}) {
                print {$FD} <<"END_SSUB_SHAPE";
\\DeclareFontShape{$enc}{$fam-$sty}{$series}{$shape}{
    <-> ssub * $fam-$sty/$series/$replace
}{}

END_SSUB_SHAPE
                if (defined $nfssseries) {
                    print {$FD} <<"END_SSUB_ALIAS";
\\DeclareFontShape{$enc}{$fam-$sty}{$alias}{$shape}{
    <-> ssub * $fam-$sty/$alias/$replace
}{}

END_SSUB_ALIAS
                }
                $fdseries->{$shape} = 1;
            }
        }
    }

    my %seen;
    while (my ($series, $nfssseries) = each %{$nfss_mapping}) {
        if (exists $data->{$series}) {
            for my $shape (keys %{$data->{$series}}) {
                $seen{$nfssseries}{$shape} = 1;
            }
        }
    }

    print {$FD} "\n%   ----  Extra 'ssub' rules to map 'bx' to 'b'  ----\n\n";
    for my $shape (keys %{$seen{b}}) {
        if (!exists $seen{bx}{$shape}) {
            print {$FD} <<"END_SSUB_BX";
\\DeclareFontShape{$enc}{$fam-$sty}{bx}{$shape}{
      <-> ssub * $fam-$sty/b/$shape
}{}

END_SSUB_BX
        }
    }

    print {$FD} "\\endinput\n";
    close $FD;

    return;
}


############################################################################


package Log;

# --------------------------------------------------------------------------
#   Constructor: creates new Log object, writing to $logfile.
# --------------------------------------------------------------------------
sub new {
    my ($class, $filename) = @_;

    if (-e $filename) {
        print "[WARNING]   File '$filename' already exists;\n" .
        "            appending new log data to end.\n";
    }
    open my $log, '>>', $filename
        or die "$0: cannot create '$filename': $!";

    return bless $log, $class;
}


# --------------------------------------------------------------------------
#   Writes a message to the log file.
# --------------------------------------------------------------------------
sub log {
    my ($self, $msg) = @_;

    print {$self} $msg;

    return;
}


# --------------------------------------------------------------------------
#   Closes the logfile associated with this Log object.
# --------------------------------------------------------------------------
sub close {
    my $self = shift;

    close $self;

    return;
}


# --------------------------------------------------------------------------
#   Logs the command line options.
# --------------------------------------------------------------------------
sub log_options {
    my $self = shift;

    print {$self} <<"END_ARGUMENTS";


############################################################################


@{[ POSIX::strftime("[%F %T]", localtime time) ]}  $0, version $VERSION

Command was:

    "$ARGV{cmdline}"

----------------------------------------------------------------------------

I'm using the following options:

    encoding(s):        @{[ join ', ', @{$ARGV{encoding}} ]}
    NFSS:               $ARGV{nfss} @{[ $ARGV{nfss} eq 'rm' ? '(serif)'
                                      : $ARGV{nfss} eq 'sf' ? '(sanserif)'
                                      : $ARGV{nfss} eq 'tt' ? '(typewriter)'
                                      :                       '(unknown)'
                                    ]}

    lining:             @{[ $ARGV{lining}       ? 'yes'     : 'no'     ]}
    oldstyle:           @{[ $ARGV{oldstyle}     ? 'yes'     : 'no'     ]}
    proportional:       @{[ $ARGV{proportional} ? 'yes'     : 'no'     ]}
    tabular:            @{[ $ARGV{tabular}      ? 'yes'     : 'no'     ]}
    ts1:                @{[ $ARGV{textcomp}     ? 'yes'     : 'no'     ]}
    smallcaps:          @{[ $ARGV{smallcaps}    ? 'yes'     : 'no'     ]}
    swash:              @{[ $ARGV{swash}        ? 'yes'     : 'no'     ]}
    titling:            @{[ $ARGV{titling}      ? 'yes'     : 'no'     ]}
    superiors:          @{[ $ARGV{superiors}    ? 'yes'     : 'no'     ]}
    inferiors:          $ARGV{inferiors}
    ornaments:          @{[ $ARGV{ornaments}    ? 'yes'     : 'no'     ]}
    fractions:          @{[ $ARGV{fractions}    ? 'yes'     : 'no'     ]}
    ligatures:          @{[ $ARGV{ligatures}    ? 'yes'     : 'no'     ]}

    target:             $ARGV{target}
    extra:              $ARGV{extra}

    figurekern:         @{[ $ARGV{figurekern} ? 'keep' : 'remove' ]}

    nfssweight:         @{[ join q{, }, @{$ARGV{nfssweight}} ]}
    nfsswidth:          @{[ join q{, }, @{$ARGV{nfsswidth}}  ]}

    math:               @{[ $ARGV{math} ? 'yes' : 'no' ]}
    mathspacing:        $ARGV{mathspacing}

    auto/manual:        @{[ $ARGV{manual} ? 'manual' : 'auto' ]}
    fontname suffix:    @{[ $ARGV{t1suffix} || '(none)' ]}

END_ARGUMENTS

    if ($ARGV{fig_height} or $ARGV{fig_width}) {
        print {$self} <<"END_FIGURE_DEFAULTS";
    default figures:    @{[
                            $ARGV{fig_width}  eq 'pnum' ? 'proportional'
                                :                         'tabular'
                        ]} @{[
                            $ARGV{fig_height} eq 'onum' ? 'oldstyle'
                                :                         'lining'
                        ]}

END_FIGURE_DEFAULTS
    }

    if ($ARGV{dryrun}) {
        print {$self} "    DRY RUN\n\n";
    }

    return;
}


# --------------------------------------------------------------------------
#   Logs command line options and the results of font info parsing.
# --------------------------------------------------------------------------
sub log_parsing {
    my ($self, $fontlist) = @_;

    print {$self} '-' x 76 . "\n\n" . "Results of font info parsing:\n";

    for my $font (@{$fontlist}) {
        print {$self} <<"END_PARSE_FONT";

    $font->{filename}
        Name:       $font->{name}
        Family:     $font->{family}
        Subfamily:  $font->{subfamily}
        Weight:     $font->{weight} ($font->{weight_class})
        Width:      $font->{width} ($font->{width_class})
        Shape:      $font->{shape} @{[ $font->{is_smallcaps}
                                            ? 'smallcaps' : '' ]}
        Size:       $font->{minsize}-$font->{maxsize}
        Features:   @{[ join q(, ), sort keys %{$font->{feature}} ]}
END_PARSE_FONT
    }

    return;
}


# --------------------------------------------------------------------------
#   Logs the mapping of NFSS codes to weights and widths.
# --------------------------------------------------------------------------
sub log_nfss_mapping {
    my ($self, $nfss_mapping) = @_;

    print {$self} "\n" . '-' x 76 . "\n\nNFSS mappings:\n\n";
    for my $weight (Attr::get_all_nfss_weights()) {
        printf {$self} "    %-3s =>  %s\n",
                       $weight || 'm',
                       $nfss_mapping->{weight}{$weight}[0] || '';
    }
    printf {$self} "\n";
    for my $width (Attr::get_all_nfss_widths()) {
        printf {$self} "    %-3s =>  %s\n",
                       $width || 'm',
                       $nfss_mapping->{width}{$width}[0] || '';
    }

    return;
}


# --------------------------------------------------------------------------
#   Logs all fonts we're going to create.
# --------------------------------------------------------------------------
sub log_worklist {
    my ($self, $worklist) = @_;

    my @workitems
        = sort { $a->{font}{filename}    cmp $b->{font}{filename}
                    || $a->{encoding}    cmp $b->{encoding}
                    || $a->{figurestyle} cmp $b->{figurestyle}
               }
               @{$worklist};

    my $prevfn = q{};
    for my $workitem (@workitems) {
        if ($prevfn ne $workitem->{font}{filename}) {
            print {$self} <<"END_FONTINFO";

    ------------------------------------------------------------------------

    $workitem->{font}{filename}

        Generating these encodings, figure styles and shapes:

            ENC     STYLE   SHAPE   FEATURES USED

END_FONTINFO
        }
        printf {$self} "            %-3s     %-4s    %-4s    %s\n",
                       $workitem->{encoding},
                       $workitem->{figurestyle},
                       $workitem->{fdshape},
                       join(q{, }, @{$workitem->{features}});
        $prevfn  = $workitem->{font}{filename};
    }

    return;
}


# --------------------------------------------------------------------------
#   Logs all generated otftotfm commands.
# --------------------------------------------------------------------------
sub log_commands {
    my ($self, $commandlist) = @_;

    print {$self} "\n\n";
    print {$self} join "\n\n", @{$commandlist};
    print {$self} "\n";

    return;
}


############################################################################


package Options;

my $USAGE =<<'END_USAGE';

'autoinst' is a wrapper around Eddie Kohler's TypeTools
(http://www.lcdf.org/type/), for installing OpenType fonts in LaTeX.

Usage: autoinst [options] font[s]

Possible options:
    -encoding=ENC[,ENC]*    Specify text encoding(s) (default: OT1,LY1,T1)

    -(no)lining             Toggle creation of lining digits
    -(no)oldstyle           Toggle creation of oldstyle digits
    -(no)proportional       Toggle creation of proportional digits
    -(no)tabular            Toggle creation of tabular digits
    -(no)ts1                Toggle creation of TS1 fonts
    -(no)smallcaps          Toggle creation of smallcaps
    -(no)swash              Toggle creation of swash
    -(no)titling            Toggle creation of titling
    -(no)superiors          Toggle creation of fonts with superior characters
    -noinferiors
    -inferiors=[none|auto|subs|sinf|dnom]
                            Use this style for subscripts (see docs)
    -(no)ornaments          Toggle creation of ornament fonts
    -(no)fractions          Toggle creation of fonts with digits for fractions
    -(no)ligatures          Toggle manual addition of f-ligatures to font

    -serif                  Install font as serif font
    -sanserif               Install font as sanserif font
    -typewriter             Install font as typewriter font

    -defaultlining
    -defaultoldstyle        Specify which figure style should be
    -defaulttabular             considered 'default' for this font; see docs
    -defaultproportional

    -extra="EXTRA"          Add EXTRA to the otftotfm command for all fonts
    -target="DIRECTORY"     Install files into specified TEXMF tree
    -vendor="VENDOR"        Only used for naming directories
    -typeface="TYPEFACE"    Only used for naming directories

    -(no)figurekern         Keep or remove kerns between tabular figures

    -nfssweight=XX=YYYY     Map the "XX" NFSS code to the "YYYY" weight
    -nfsswidth=XX=YYYY      Map the "XX" NFSS code to the "YYYY" width

    -help                   Print this text and exit
    -doc                    Print the complete documentation and exit
    -dryrun                 Don't generate fonts, only log what would be done
    -logfile="FILE"         Write log to "FILE" (default: <fontfamily>.log)
    -verbose                Print more data to log file
    -version                Print version number and exit

    -math                   Generate basic math fonts
    -mathspacing=AMOUNT     Letterspace the math fonts by AMOUNT/1000 em

    -manual                 Manual mode (see documentation)
    -t1suffix=SUFFIX        Add SUFFIX to name of generated pfb fonts

    font[s]                 The fonts (.otf or .ttf format) to install.

Please report any bugs or suggestions to <marcpenninga@gmail.com>.
END_USAGE

# Default values for the command-line arguments.
%ARGV = (
    encoding        => 'OT1,LY1,T1',
    textcomp        => '2',     # 0 = no, 1 = yes, 2 = ('T1' ? yes : no)
    lining          => '1',     # 0 = no, 1 = yes
    oldstyle        => '1',     # 0 = no, 1 = yes
    proportional    => '1',     # 0 = no, 1 = yes
    tabular         => '1',     # 0 = no, 1 = yes
    smallcaps       => '1',     # 0 = no, 1 = yes
    swash           => '1',     # 0 = no, 1 = yes
    titling         => '1',     # 0 = no, 1 = yes
    superiors       => '1',     # 0 = no, 1 = yes
    inferiors       => 'none',  # values: none, auto, subs, sinf, dnom
    ornaments       => '1',     # 0 = no, 1 = yes
    fractions       => '0',     # 0 = no, 1 = yes
    ligatures       => '2',     # 0 = no, 1 = yes, 2 = ('tt' ? no : yes)
    nfss            => '',
    fig_height      => '',
    fig_width       => '',
    extra           => '',
    target          => '',
    vendor          => 'lcdftools',
    typeface        => '',
    manual          => '0',     # 0 = no, 1 = yes
    dryrun          => '0',     # 0 = no, 1 = yes
    logfile         => '',
    figurekern      => '1',     # 0 = no, 1 = yes
    verbose         => 0,
    nfsswidth       => [],
    nfssweight      => [],
    math            => 0,
    mathspacing     => 0,
    t1suffix        => 'none',
);


# --------------------------------------------------------------------------
#   Parses the command-line options and removes these from @ARGV.
# --------------------------------------------------------------------------
sub parse_options {
    $ARGV{cmdline} = join ' ', ($0, @ARGV);

    Getopt::Long::GetOptions(
        'help|?'              =>  sub { print $USAGE; exit },
        'version'             =>  sub { exit },
        'doc'                 =>  sub { Pod::Usage::pod2usage(-verbose => 2) },
        'encoding=s'          => \$ARGV{encoding},
        'ts1!'                => \$ARGV{textcomp},
        'lining!'             => \$ARGV{lining},
        'oldstyle!'           => \$ARGV{oldstyle},
        'proportional!'       => \$ARGV{proportional},
        'tabular!'            => \$ARGV{tabular},
        'smallcaps!'          => \$ARGV{smallcaps},
        'swash!'              => \$ARGV{swash},
        'titling!'            => \$ARGV{titling},
        'superiors!'          => \$ARGV{superiors},
        'noinferiors'         =>  sub { $ARGV{inferiors} = 'none' },
        'inferiors:s'         => \$ARGV{inferiors},
        'ornaments!'          => \$ARGV{ornaments},
        'fractions!'          => \$ARGV{fractions},
        'ligatures!'          => \$ARGV{ligatures},
        'serif'               =>  sub { $ARGV{nfss} = 'rm' },
        'sanserif'            =>  sub { $ARGV{nfss} = 'sf' },
        'typewriter'          =>  sub { $ARGV{nfss} = 'tt' },
        'defaultlining'       =>  sub { $ARGV{fig_height} = 'lnum' },
        'defaultoldstyle'     =>  sub { $ARGV{fig_height} = 'onum' },
        'defaulttabular'      =>  sub { $ARGV{fig_width}  = 'tnum' },
        'defaultproportional' =>  sub { $ARGV{fig_width}  = 'pnum' },
        'extra=s'             => \$ARGV{extra},
        'target=s'            => \$ARGV{target},
        'vendor=s'            => \$ARGV{vendor},
        'typeface=s'          => \$ARGV{typeface},
        'manual'              => \$ARGV{manual},
        'dryrun'              => \$ARGV{dryrun},
        'figurekern!'         => \$ARGV{figurekern},
        'logfile=s'           => \$ARGV{logfile},
        'verbose+'            => \$ARGV{verbose},
        'nfssweight=s%'       => sub {
                                     my ($ignored, $key, $values) = @_;
                                     $key = lc $key;
                                     push @{$ARGV{nfssweight}},
                                          "$key=$values";
                                     my @values = split m/,/, lc $values;
                                     $key = q{} if $key eq 'm';
                                     Attr::set_weight($key, @values);
                                     $ARGV{$key} = 'user-defined';
                                 },
        'nfsswidth=s%'        => sub {
                                     my ($ignored, $key, $values) = @_;
                                     $key = lc $key;
                                     my @values = split m/,/, lc $values;
                                     push @{$ARGV{nfsswidth}},
                                          "$key=$values";
                                     $key = q{} if $key eq 'm';
                                     Attr::set_width($key, @values);
                                     $ARGV{$key} = 'user-defined';
                                 },
        'math!'               => \$ARGV{math},
        'mathspacing=i'       => \$ARGV{mathspacing},
        't1suffix:s'          => \$ARGV{t1suffix},
    )
    or die "$USAGE";

    if (!@ARGV) {
        Pod::Usage::pod2usage(
            -msg => '[ERROR]     No font files given, nothing to do!',
            -verbose => 1);
    }

    return;
}


############################################################################


package Otftotfm;

# --------------------------------------------------------------------------
#   Returns a string with all "directory" options for otftotfm set.
#   Also creates directories that don't exist yet.
# --------------------------------------------------------------------------
sub get_targetdirs {
    my ($family, $fontlist) = @_;

    my %has_fonttype = map { ($_->{fonttype} => 1) } @{$fontlist};

    my @filetypes = qw(tfm vf);
    if ($has_fonttype{opentype}) { push @filetypes, qw(type1) }
    if ($has_fonttype{truetype}) { push @filetypes, qw(truetype) }

    my %dir = map { ( $_ => File::Spec->catdir(
                                $ARGV{target},
                                'fonts',
                                $_,
                                $ARGV{vendor},
                                $ARGV{typeface} || $family) )
                  }
                  @filetypes;

    $dir{$_}
        = File::Spec->catdir(
            $ARGV{target}, 'fonts', $_, 'dvips', $ARGV{typeface} || $family)
        for qw(enc map);

    File::Path::make_path(values %dir) unless $ARGV{dryrun};

    my $result
        = join q{ },
               map { qq(--${_}-directory="$dir{$_}") }
                   @filetypes;
    $result .= qq( --encoding-directory="$dir{enc}" --map-file=")
               . File::Spec->catfile($dir{map}, "$family.map")
               . '"';

    return $result;
}


# The official names for various coding schemes.
my %SCHEME = (
    OT1 => 'TEX TEXT',
    OML => 'TEX MATH ITALIC',
    T1  => 'EXTENDED TEX FONT ENCODING - LATIN',
    TS1 => 'TEX TEXT COMPANION SYMBOLS 1---TS1',
    LY1 => 'TEX TYPEWRITER AND WINDOWS ANSI',
    LGR => 'GREEK FONT ENCODING - LGR',
    T2A => 'TEX CYRILLIC FONT ENCODING - T2A',
    T2B => 'TEX CYRILLIC FONT ENCODING - T2B',
    T2C => 'TEX CYRILLIC FONT ENCODING - T2C',
    T3  => 'TEX IPA ENCODING',
    TS3 => 'TEX IPA SYMBOL ENCODING',
);

# --------------------------------------------------------------------------
#   Generates a command for otftotfm from a work item.
# --------------------------------------------------------------------------
sub create_command {
    my ($workitem, $targetdirs) = @_;

    my $want_ligkerns
        = ( $ARGV{ligatures} == 1 )
            || Util::any( map { $_ eq 'liga' } @{$workitem->{features}} );

    return join q( ), 'otftotfm',
                      ($ARGV{manual} ? '--pl' : '--automatic'),
                      "--encoding=$workitem->{enc_file}",
                      $targetdirs,
                      '--no-updmap',
                      '--force',
                      ($SCHEME{$workitem->{encoding}}
                         ? qq(--coding-scheme="$SCHEME{$workitem->{encoding}}")
                         : q()),
                      (map { "--feature=$_" } @{$workitem->{features}}),
                      ($want_ligkerns
                         ? ( '--ligkern="f i =: fi"',
                             '--ligkern="f l =: fl"',
                             '--ligkern="f f =: ff"',
                             '--ligkern="ff i =: ffi"',
                             '--ligkern="ff l =: ffl"' )
                         : q()),
                      Tables::get_extra($workitem->{figurestyle}),
                      Tables::get_extra($workitem->{style}),
                      $ARGV{extra},
                      qq("$workitem->{font}{filename}"),
                      $workitem->{fontname},
                      ;
}


# --------------------------------------------------------------------------
#   Executes (or saves to file, when $ARGV{manual} is true) all commands.
# --------------------------------------------------------------------------
sub run_commands {
    my ($commandlist, $family, $log) = @_;

    if ($ARGV{manual}) {
        open my $BAT, '>', 'autoinst.bat'
            or die "[ERROR]     Can't create 'autoinst.bat': $!";
        print {$BAT} "$_\n" for @{$commandlist};
        close $BAT;
    }
    else {
        my $n_cmds = scalar @{$commandlist};
        my ($log_ncmds, $ceil) = (1, 10);
        while ($n_cmds >= $ceil) {
            $log_ncmds++;
            $ceil *= 10;
        }
        my $template = sprintf "%%%dd of %%%dd", $log_ncmds, $log_ncmds;
        my $l_template = 4 + 2 * $log_ncmds;
        $| = 1; # autoflush
        print "[INFO]      Generating fonts for $family: ", " " x $l_template;

        my $i_cmd  = 1;
        my $oops = 0;
        for my $command (@{$commandlist}) {
            print "\b" x $l_template;
            printf $template, $i_cmd++, $n_cmds;
            open my $otftotfm, '-|', "$command 2>&1"
                or die "could not fork(): $!";
            my $msgs = do { local $/; <$otftotfm> };
            close $otftotfm
                or do {
                warn "\n$command\n\n$msgs\n";
                $log->log("\n$command\n\n$msgs\n");
                $oops = 1;
            };
        }
        print "\n";
        $| = 0;
        if ($oops) {
            warn <<"END_OTFTOTFM_WARNING";
[ERROR]     One or more calls to 'otftotfm' returned a non-zero status code;
            please check the messages above and in the log file.
END_OTFTOTFM_WARNING
        }
    }

    return;
}


############################################################################


package Tables;

=begin Comment

    The %STYLE table is used in deciding which font styles
    (normal, small caps, swash or textcomp) to generate.

    Each key in this table names a style; the corresponding value
    is an anonymous hash with several key/value pairs:
        code    An anonymous hash with three possible keys:
                'n'  -> the NFSS code to use for this variant shape
                        if the 'basic shape' is upright;
                'it' -> the NFSS code to use for this variant shape
                        if the 'basic shape' is italic
                'sl' -> the NFSS code to use for this variant shape
                        if the 'basic shape' is slanted (aka oblique);
                If any entry is missing, the corresponding version
                of this variant style will not be built.
        reqd    A list of required OpenType features;
                this style is built if the font supports at least *one*
                of these features.
        nice    A list of optional OpenType features;
                these are used if the font supports them, but don't
                prevent this style from being built when missing.
        extra   Extra options passed to otftotfm when creating this style.
        name    A string added to the name of the generated font,
                to make it unique.

    Textcomp is treated as a 'style' even though it is technically
    an encoding; that is just the easiest way to do things.

=end Comment

=cut

my %STYLE = (
    normal => {
        code  => { n => 'n', it => 'it', sl => 'sl' },
        reqd  => [],
        nice  => [],
        extra => '',
        name  => '',
    },
    smallcaps => {
        code  => { n => 'sc', it => 'scit', sl => 'scsl' },
        reqd  => [ 'smcp' ],
        nice  => [],
        extra => '--unicoding="germandbls =: SSsmall" --unicoding="ff =: FFsmall" --unicoding="fi =: FIsmall" --unicoding="ffi =: FFIsmall" --unicoding="fl =: FLsmall" --unicoding="ffl =: FFLsmall"',
        name  => 'sc',
    },
    swash => {
        code  => { n => 'nw', it => 'sw' },
        reqd  => [ 'swsh' ],
        nice  => [ 'cswh', 'dlig' ],
        extra => '--include-alternates="*.swash"',
        name  => 'swash',
    },
    textcomp => {
        code  => { n => 'n', it => 'it', sl => 'sl' },
        reqd  => [],
        nice  => [ 'onum' ],
        extra => '',
        name  => '',
    },
    math => {
        code  => { n => 'n', it => 'it', sl => 'sl' },
        reqd  => [],
        nice  => [ 'onum', 'mgrk' ],
        extra => '--math-spacing=127',
        name  => '',
    },
);

=begin Comment

    The %FIGURESTYLE table is used in deciding which figure styles to generate.
    Each figure style (lining, oldstyle, tabular, proportional, superior,
    inferior etc.) becomes a separate font family. We also treat Ornaments
    as a figure style here; that's just the easiest way to handle them.

    Each key in this table names a figure style; the corresponding
    value is an anonymous hash with four key/value pairs:
        reqd    A list of required OpenType features; this style is built
                if the font supports *all* these features.
        nice    A list of optional OpenType features;
                these are used if the font supports them, but don't
                prevent this style from being built when missing.
        extra   Extra options passed to otftotfm when creating this style.
        style   An anonymous array of 'variant' styles to build with
                this figure style.

    The 'reqd' and 'nice' subtables for the TLF, LF, TOsF and OsF styles
    are empty; these are filled in at run time, depending on
    which figure style is default for the current font.

    The 'reqd' subtable for the Inf style is also empty; this may be filled
    with 'subs', 'sinf' or 'dnom' depending on the -inferiors options.

=end Comment

=cut

my %FIGURESTYLE = (
    TLF => {
        reqd   => [],
        nice   => [ 'kern', 'liga' ],
        extra  => '',
        styles => [ qw(normal smallcaps swash textcomp math) ],
    },
    LF => {
        reqd   => [],
        nice   => [ 'kern', 'liga' ],
        extra  => '',
        styles => [ qw(normal smallcaps swash textcomp math) ],
    },
    TOsF => {
        reqd   => [],
        nice   => [ 'kern', 'liga' ],
        extra  => '',
        styles => [ qw(normal smallcaps swash textcomp math) ],
    },
    OsF => {
        reqd   => [],
        nice   => [ 'kern', 'liga' ],
        extra  => '',
        styles => [ qw(normal smallcaps swash textcomp math) ],
    },
    Sup => {
        reqd   => [ 'sups' ],
        nice   => [],
        extra  => '--ligkern="* {KL} *"',
        styles => [ 'normal' ],
    },
    Inf => {
        reqd   => [],
        nice   => [],
        extra  => '--ligkern="* {KL} *"',
        styles => [ 'normal' ],
    },
    Numr => {
        reqd   => [ 'numr'],
        nice   => [],
        extra  => '--ligkern="* {KL} *"',
        styles => [ 'normal' ],
    },
    Dnom => {
        reqd   => [ 'dnom' ],
        nice   => [],
        extra  => '--ligkern="* {KL} *"',
        styles => [ 'normal' ],
    },
    Titl => {
        reqd   => [ 'titl' ],
        nice   => [ 'kern', 'liga' ],
        extra  => '',
        styles => [ 'normal' ],
    },
    Orn => {
        reqd   => [ 'ornm' ],
        nice   => [],
        extra  => '--ligkern="* {KL} *"',
        styles => [ 'normal' ],
    },
);


# --------------------------------------------------------------------------
#   Getter; returns a list of all known figure styles.
# --------------------------------------------------------------------------
sub get_all_figurestyles {
    return keys %FIGURESTYLE;
}


# --------------------------------------------------------------------------
#   Getter; returns all styles to generate for the given figure style.
# --------------------------------------------------------------------------
sub get_styles {
    my $figurestyle = shift;

    return grep { defined $STYLE{$_} }
                @{$FIGURESTYLE{$figurestyle}{styles}};
}


# --------------------------------------------------------------------------
#   Getter; returns a list of req'd features for the given (figure) style.
# --------------------------------------------------------------------------
sub get_reqd_features {
    my $what = shift;

    my $result = $FIGURESTYLE{$what}{reqd} // $STYLE{$what}{reqd} // [];

    return @{$result};
}


# --------------------------------------------------------------------------
#   Getter; returns a list of add'l features for the given (figure) style.
# --------------------------------------------------------------------------
sub get_nice_features {
    my $what = shift;

    my $result = $FIGURESTYLE{$what}{nice} // $STYLE{$what}{nice} // [];

    return @{$result};
}


# --------------------------------------------------------------------------
#   Getter; returns a list of all features for the given (figure) style.
# --------------------------------------------------------------------------
sub get_features {
    my $what = shift;

    return ( get_reqd_features($what), get_nice_features($what) );
}


# --------------------------------------------------------------------------
#   Getter; returns the name of the given style.
# --------------------------------------------------------------------------
sub get_name {
    my $what = shift;

    return $STYLE{$what}{name} // '';
}


# --------------------------------------------------------------------------
#   Getter; returns the 'extra' arguments for the given (figure) style.
# --------------------------------------------------------------------------
sub get_extra {
    my $what = shift;

    return $FIGURESTYLE{$what}{extra} // $STYLE{$what}{extra} // '';
}


# --------------------------------------------------------------------------
#   Getter; returns the NFSS code for the given style and 'basic' shape.
# --------------------------------------------------------------------------
sub get_fdshape {
    my ($style, $basicshape) = @_;

    return $STYLE{$style}{code}{$basicshape};
}


# --------------------------------------------------------------------------
#   Processes the command-line options. This is split into a number
#   of smaller steps, that each process a group of related options.
# --------------------------------------------------------------------------
sub process_options {
    process_styles_options();
    process_encoding_options();
    process_target_options();
    process_output_options();

    return;
}


# --------------------------------------------------------------------------
#   Processes all options that select or deselect styles.
# --------------------------------------------------------------------------
sub process_styles_options {
    delete $STYLE{smallcaps}           unless $ARGV{smallcaps};
    delete $STYLE{swash}               unless $ARGV{swash};

    delete $FIGURESTYLE{Titl}          unless $ARGV{titling};
    delete $FIGURESTYLE{Sup}           unless $ARGV{superiors};
    delete $FIGURESTYLE{Orn}           unless $ARGV{ornaments};
    delete @FIGURESTYLE{qw(Numr Dnom)} unless $ARGV{fractions};
    $ARGV{inferiors} ||= 'auto';
    if    ($ARGV{inferiors} eq 'none') { delete $FIGURESTYLE{Inf} }
    elsif ($ARGV{inferiors} eq 'auto') { $FIGURESTYLE{Inf}{reqd} = ['auto'] }
    elsif ($ARGV{inferiors} eq 'subs') { $FIGURESTYLE{Inf}{reqd} = ['subs'] }
    elsif ($ARGV{inferiors} eq 'sinf') { $FIGURESTYLE{Inf}{reqd} = ['sinf'] }
    elsif ($ARGV{inferiors} eq 'dnom') { $FIGURESTYLE{Inf}{reqd} = ['dnom'] }
    else  {
        # Apparently we mistook the first argument (font name) for
        # an optional argument to -inferiors; let's undo that.
        unshift @ARGV, $ARGV{inferiors};
        $ARGV{inferiors} = 'auto';
        $FIGURESTYLE{Inf}{reqd} = ['auto'];
    }

    # Fix the %FIGURESTYLE table to take 'default' figure styles into account.
    if ($ARGV{fig_height} eq 'onum') {
        push @{$FIGURESTYLE{TLF}{reqd}},  'lnum';
        push @{$FIGURESTYLE{LF}{reqd}},   'lnum';
        push @{$FIGURESTYLE{TOsF}{nice}}, 'onum';
        push @{$FIGURESTYLE{OsF}{nice}},  'onum';
    }
    else {
        push @{$FIGURESTYLE{TLF}{nice}},  'lnum';
        push @{$FIGURESTYLE{LF}{nice}},   'lnum';
        push @{$FIGURESTYLE{TOsF}{reqd}}, 'onum';
        push @{$FIGURESTYLE{OsF}{reqd}},  'onum';
    }

    if ($ARGV{fig_width} eq 'pnum') {
        push @{$FIGURESTYLE{TLF}{reqd}},  'tnum';
        push @{$FIGURESTYLE{TOsF}{reqd}}, 'tnum';
        push @{$FIGURESTYLE{LF}{nice}},   'pnum';
        push @{$FIGURESTYLE{OsF}{nice}},  'pnum';
    }
    else {
        push @{$FIGURESTYLE{TLF}{nice}},  'tnum';
        push @{$FIGURESTYLE{TOsF}{nice}}, 'tnum';
        push @{$FIGURESTYLE{LF}{reqd}},   'pnum';
        push @{$FIGURESTYLE{OsF}{reqd}},  'pnum';
    }

    delete @FIGURESTYLE{qw(LF TLF)}    unless $ARGV{lining};
    delete @FIGURESTYLE{qw(OsF TOsF)}  unless $ARGV{oldstyle};
    delete @FIGURESTYLE{qw(LF OsF)}    unless $ARGV{proportional};
    delete @FIGURESTYLE{qw(TLF TOsF)}  unless $ARGV{tabular};

    if (!$ARGV{figurekern}) {
        my @digits = qw(zero one two three four five six seven eight nine);
        my $tkern
            = join ' ', map { my $left = $_;
                              map { qq(--ligkern="$left {} $_") } @digits
                            }
                            @digits;

        $FIGURESTYLE{TLF}{extra}  = $tkern;
        $FIGURESTYLE{TOsF}{extra} = $tkern;
    }

    return;
}


# --------------------------------------------------------------------------
#   Processes the options for selecting encodings.
# --------------------------------------------------------------------------
sub process_encoding_options {

    # All specified encodings should either be built-in,
    # or have an accompanying .enc file in the current directory.
    my @encodings = split /,/, $ARGV{encoding};
    for my $enc (@encodings) {
        if ($enc !~ m/\A(OT1|T[1345]|T2[ABC]|TS[13]|LY1|LGR|CS|L7X|QX)\z/xmsi) {
            my $try = $enc;
            $try .= '.enc' if $try !~ m/[.]enc\z/xmsi;
            if (!-e $try) {
                die "[ERROR]     No .enc file found for '$enc'";
            }
        }
    }
    my @textencodings = grep { $_ !~ m/TS1/xmsi } @encodings;
    $ARGV{encoding} = \@textencodings;

    # TS1-encoded fonts are generated if:
    # - the user explicitly asked for TS1, or
    # - the text encodings contain T1 and the user didn't turn off TS1
    if ($ARGV{textcomp} == 1
            or ($ARGV{textcomp} >= 1
                and grep { uc $_ eq 'T1' } @{$ARGV{encoding}})) {
        $ARGV{textcomp} = 1;
    }
    else {
        delete $STYLE{textcomp};
    }

    if ($ARGV{math}) {
        if (!( grep { $_ eq 'OT1' } @{$ARGV{encoding}} )) {
            $ARGV{encoding} = [ 'OT1', @{$ARGV{encoding}} ];
        }
    }
    else {
        delete $STYLE{math}
    }

    if ($ARGV{mathspacing}) {
        if (defined $STYLE{math}{extra}) {
            $STYLE{math}{extra} .= " --letterspacing=$ARGV{mathspacing}";
        }
    }

    return;
}


# --------------------------------------------------------------------------
#   Processes the options related to the target TEXMF directory.
# --------------------------------------------------------------------------
sub process_target_options{

    my $localtarget = File::Spec->catdir( Cwd::getcwd(), 'autoinst_output' );
    if ($ARGV{manual}) {
        warn "[WARNING]   Option '-target' overridden by '-manual'!\n"
            if $ARGV{target};
        $ARGV{target} = $localtarget;
    }
    elsif (!$ARGV{target}) {
        my $is_windows_os = ( $^O =~ /^MSWin/i );
        my $kpsepath = $is_windows_os
            ? eval { qx( kpsewhich -expand-var=\$TEXMFLOCAL;\$TEXMFHOME ) }
            : eval { qx( kpsewhich -expand-var='\$TEXMFLOCAL:\$TEXMFHOME' ) }
            ;
        if (!$kpsepath) {
            warn <<"END_WARNING_KPSEWHICH";
[WARNING]   Call to "kpsewhich" failed.
            Maybe your TeX system doesn't use the kpathsea library?

            Consider using the "-target" command line option
            to specify a TEXMF tree where autoinst should install all files.
END_WARNING_KPSEWHICH
        }
        else {
            my $pathsep = $is_windows_os ? ';' : ':';
            for my $dir ( split m/$pathsep/xms, substr $kpsepath, 0, -1 ) {
                if (-w $dir) { $ARGV{target} = $dir; last }
                if (-e $dir) { next }
                my $par = File::Spec->catdir( $dir, File::Spec->updir() );
                if (-w $par) { $ARGV{target} = $dir; last }
            }
        }
    }

    if (!$ARGV{target}) {
        $ARGV{target} = $localtarget;
        warn <<"END_WARNING_DUMPING_FILES";
[WARNING]   No user-writable TEXMF-tree found!

            I'm putting all generated files in "$ARGV{target}".

            Please install these files into a suitable TEXMF directory,
            update the filename database and run 'updmap' (or similar);
            see your TeX installation's documentation.
END_WARNING_DUMPING_FILES
    }

    if ($ARGV{target} =~ m/\s/xms) {
        warn <<"END_WARNING_SPACES_IN_PATHS";
[WARNING]   The pathname of your target directory contains spaces:
                "$ARGV{target}"
            If you experience any problems, try re-running autoinst
            on a target directory without spaces in its name.
END_WARNING_SPACES_IN_PATHS
    }

    return;
}


# --------------------------------------------------------------------------
#   Processes the output related options.
# --------------------------------------------------------------------------
sub process_output_options{
    # If the user gave -t1suffix *without* value as the last option,
    # Getopt::Long may mistake the next argument (a font filename)
    # for the value of -t1suffix; we take care of this case
    # by testing whether the value refers to an existing file
    # and repairing things if necessary.
    if (-e $ARGV{t1suffix}) {
        unshift @ARGV, $ARGV{t1suffix};
        $ARGV{t1suffix} = '';
    }

    $ARGV{t1suffix} ||= 'PS';

    if ($ARGV{t1suffix} eq 'none') {
        $ARGV{t1suffix} = '';
    }

    return;
}


# --------------------------------------------------------------------------
#   Processes command line options with font family-specific defaults.
# --------------------------------------------------------------------------
sub process_family_dependent_options {
    my $fontlist = shift;

    if (!$ARGV{nfss}) {
        $ARGV{nfss} = $fontlist->[0]{nfss};
    }
    # If the user didn't explicitly say anything about ligatures,
    # activate them unless the font is a typewriter font.
    if ($ARGV{ligatures} == 2 and $ARGV{nfss} eq 'tt') {
        $ARGV{ligatures} = 0;
    }

    # We can only handle the '-inferiors=auto' option now;
    # since we need to know which inferior figures this font supports,
    # we have to do the font info parsing first.
    if ($ARGV{inferiors} eq 'auto') {
        choose_inferiors($fontlist);
    }

    $ARGV{logfile} ||= sprintf "%s.log", lc $fontlist->[0]{family};

    return;
}


# --------------------------------------------------------------------------
#   Processes the -inferiors=auto option, given a list of fonts.
#   We look through these fonts and simply pick the very first
#   type of inferiors we see (we assume that this type is supported
#   by all fonts in this family).
# --------------------------------------------------------------------------
sub choose_inferiors {
    my $fontlist = shift;

    FONT:
    for my $font (@{$fontlist}) {
        for my $inf (qw(sinf subs dnom)) {
            if (exists $font->{feature}{$inf}) {
                $ARGV{inferiors} = "auto (-> $inf)";
                $FIGURESTYLE{Inf}{reqd} = [$inf];
                last FONT;
            }
        }
    }

    # If we didn't find any inferior figures,
    # delete the 'Inf' entry from the %FIGURESTYLE table
    # to indicate we don't want to generate this style.
    if ($ARGV{inferiors} eq 'auto') {
        delete $FIGURESTYLE{Inf};
        $ARGV{inferiors} = "auto (-> none)";
    }

    return;
}


############################################################################


package Util;

# --------------------------------------------------------------------------
#   Tests if all given predicates are true.
# --------------------------------------------------------------------------
sub all {
    return !( grep { !$_ } @_ );
}


# --------------------------------------------------------------------------
#   Tests if any of the given predicates are true.
# --------------------------------------------------------------------------
sub any {
    return grep { $_ } @_;
}


# --------------------------------------------------------------------------
#   Walks a (nested) dictionary and returns a lookup table with all keys.
# --------------------------------------------------------------------------
sub get_keys {
    my $dict = shift;
    my $seen = shift // {};

    while (my ($k, $v) = each %$dict) {
        $seen->{$k} = 1;
        get_keys($v, $seen) if ref $v eq 'HASH';
    }

    return $seen;
}


# --------------------------------------------------------------------------
#   Sorts its arguments so that longer strings come before shorter ones.
# --------------------------------------------------------------------------
sub sort_desc_length {
    return reverse sort { length($a) <=> length($b) } @_;
}


############################################################################


package Work;


# --------------------------------------------------------------------------
#   Decides which styles, figure styles and encodings to generate
#   for the given fonts.
# --------------------------------------------------------------------------
sub generate_worklist {
    my $fontlist = shift;

    my @worklist = map { { font => $_ } } @{$fontlist};

    #   1.  For each font, decide which figure styles should be created.
    @worklist = map { expand_figurestyles($_) } @worklist;

    #   2.  For each (font, figure style) combination,
    #       decide which styles should be created.
    @worklist = map { expand_styles($_) } @worklist;

    #   3.  For each (font, figure style, style) combination,
    #       decide which encodings should be created.
    @worklist = map { expand_encodings($_) } @worklist;

    #   4.  Some miscellaneous finishing touches.
    @worklist = grep { $_ } map { cleanup($_) } @worklist;

    return @worklist;
}


# --------------------------------------------------------------------------
#   Determines which figure styles to create for the given work item.
#   A figure style is created if the current font contains all of
#   the 'reqd' features for this figure style.
#   Returns a list of new work items, one for each figure style.
# --------------------------------------------------------------------------
sub expand_figurestyles {
    my $workitem = shift;

    my $font = $workitem->{font};

    my @results;
    for my $figurestyle (Tables::get_all_figurestyles()) {
        my @reqd = Tables::get_reqd_features($figurestyle);
        my $has_all_reqd = Util::all(map { $font->{feature}{$_} } @reqd);
        if ($has_all_reqd) {
            my %new_workitem = %{$workitem};
            $new_workitem{figurestyle} = $figurestyle;
            push @results, \%new_workitem;
        }
    }

    return @results;
}


# --------------------------------------------------------------------------
#   Determines which styles to create for the given work item.
#   A style is created if the current font has at least one of the
#   'reqd' features for this style, or if there are no 'reqd' features.
#   Returns a list of new work items, one for each style.
# --------------------------------------------------------------------------
sub expand_styles {
    my $workitem = shift;

    my ($font, $figurestyle) = @{$workitem}{qw(font figurestyle)};

    my @results;
    for my $style (Tables::get_styles($figurestyle)) {
        my @reqd = Tables::get_reqd_features($style);
        my $has_any_reqd
                = (scalar @reqd == 0)
                  || Util::any(map { $font->{feature}{$_} } @reqd);
        if ($has_any_reqd) {
            my %new_workitem = %{$workitem};
            $new_workitem{style} = $style;
            push @results, \%new_workitem;
        }
    }

    return @results;
}


# --------------------------------------------------------------------------
#   Determines which encodings to use for the given work item;
#   returns a list of new work items, one for each encoding.
# --------------------------------------------------------------------------
sub expand_encodings {
    my $workitem = shift;

    my ($font, $figurestyle, $style)
        = @{$workitem}{qw(font figurestyle style)};
    my @encodings = $style eq 'textcomp'  ? qw(ts1)
                  : $figurestyle eq 'Orn' ? qw(ot1)
                  : $style eq 'math'      ? qw(oml)
                  :                         @{$ARGV{encoding}}
                  ;

    my @results;
    for my $encoding (@encodings) {
        my %new_workitem = %{$workitem};
        $new_workitem{encoding} = $encoding;
        push @results, \%new_workitem;
    }

    return @results;
}


# --------------------------------------------------------------------------
#   Adds some miscellaneous finishing touches to the given work item.
# --------------------------------------------------------------------------
sub cleanup {
    my $workitem = shift;

    my ($font, $figurestyle, $style)
        = @{$workitem}{qw(font figurestyle style)};

    # Don't generate smallcaps version of TS1-encoded fonts,
    # as these contain the same glyphs as the regular version.
    if ($font->{is_smallcaps}) {
        if ($style eq 'textcomp') {
            return;
        }
        else {
            $style = 'smallcaps';
        }
    }

    # Look up the NFSS code for this font's shape...
    $workitem->{fdshape} = Tables::get_fdshape($style, $font->{basicshape});
    # ... but drop this workitem if we shouldn't generate this shape.
    if (!defined $workitem->{fdshape}) {
        return;
    }

    # Figure out whether the encoding option refers to a custom encoding file
    # in the current directory, or to the name of one of our standard
    # encodings. In the former case, we quote the filename, to account
    # for possible spaces or other metacharacters; in the latter case,
    # we add the 'fontools_' prefix.
    if (-e $workitem->{encoding}) {
        $workitem->{enc_file} = qq{"$workitem->{encoding}"};
        $workitem->{encoding}
            = File::Basename::basename($workitem->{encoding}, '.enc', '.ENC');
    }
    else {
        ($workitem->{enc_file} = $workitem->{encoding})
            =~ s{ \A (OT1|OML|T[1345]|T2[ABC]|TS[13]|LY1|LGR|CS|L7X|QX) \z }
                {fontools_\L$1\E}xmsi;
    }

    # Ornaments have no text encoding, and don't need kerning and ligatures.
    if ($figurestyle eq 'Orn') {
        $workitem->{encoding} = 'u';
    }

    # Compile list of OpenType features to use with this font.
    my %feature = map { ($_ => 1) }
                      grep { $font->{feature}{$_} }
                           ( Tables::get_features($figurestyle),
                             Tables::get_features($style) );
    if ($feature{lnum} && $feature{onum}) {
        delete $feature{lnum};
    }

    # Don't create ligatures if the user doesn't want them.
    delete $feature{liga} if !$ARGV{ligatures};

    # Don't create kerns and ligatures for symbol or otherwise "unencoded" fonts.
    delete @feature{qw(kern liga)}
        if $workitem->{encoding} =~ m/\A ( TS\d | OM[LS] ) \z | \A U_ /xmsi;

    $workitem->{features} = [ sort keys %feature ];

    # Generate a unique name for this font.
    (my $encoding = lc $workitem->{encoding}) =~ s/\A u_ //xms;
    $workitem->{fontname}
            = join '-', grep { $_ } $font->{name},
                                    lc $figurestyle,
                                    lc Tables::get_name($style),
                                    $encoding;

    $workitem->{encoding} = uc $workitem->{encoding};
    if ($workitem->{encoding} =~ m/\A U_/xms) {
        $workitem->{encoding} = 'U';
    }

    return $workitem;
}


# --------------------------------------------------------------------------
#   Modify the font and file names of all generated .pfb files.
# --------------------------------------------------------------------------
sub modify_fontnames {
    my ($family, $fontlist) = @_;

    my %has_fonttype = map { ($_->{fonttype} => 1) } @{$fontlist};
    return unless $has_fonttype{opentype};

    my $pfb_dir = File::Spec->catdir(
        $ARGV{target},
        'fonts',
        'type1',
        $ARGV{vendor},
        $ARGV{typeface} || $family);

    # The otftotfm-generated map file refers to the original otf files;
    # we need to change this to use our name-modified Type1 fonts instead.
    # Note that cfftot1 uses the Name INDEX from the CFF table,
    # not the PostScript name from the name table. These two names are
    # usually equal,  but not necessarily (sec 5.4.2 in OpenType spec).
    my $mapfile = File::Spec->catfile(
        $ARGV{target},
        'fonts',
        'map',
        'dvips',
        $ARGV{typeface} || $family,
        $family . '.map');
    open my $map, '<', $mapfile
        or die "[ERROR]     Cannot open '$mapfile' for reading";
    my $mapdata = do { local $/; <$map> };
    close $map;

    my $NOTICE = 'Converted to Type1 by autoinst/cfftot1; '
               . 'for use with pdfTeX only! ';

    my $newfam = $family . $ARGV{t1suffix};

    for my $font (@{$fontlist}) {
        next unless $font->{fonttype} eq 'opentype';

        my $full_family = $font->{originalfamily};
        if (index($full_family, $family) > -1) {
            $full_family = $family;
        }
        else {
            while ($full_family =~ m/[ ]/xms) {
                (my $no_space = $full_family) =~ s/[ ]+//xmsg;
                last if $no_space eq $family;
                $full_family =~ s/[ ]\S*\z//xms;
            }
            $full_family ||= $family;
        }
        my $newfullfam = $full_family . q( ) . $ARGV{t1suffix};

        my $newname;
        if ($font->{cff_name} =~ m/$family/xms) {
            ($newname = $font->{cff_name}) =~ s/$family/$newfam/xms;
        }
        else {
            (my $dashfam = $font->{originalfamily}) =~ s/[ ]/-/xmsg;
            if ($font->{cff_name} =~ m/$dashfam(.+)/xms) {
                $newname = $dashfam . '-' . $ARGV{t1suffix} . $1;
            }
            else {
                $newname = $font->{cff_name} . $ARGV{t1suffix};
            }
        }

        for my $suffix (q(), q(LCDFJ)) {
            my $oldfn = File::Spec->catfile(
                $pfb_dir, $font->{cff_name} . $suffix . '.pfb');
            my $newfn = File::Spec->catfile(
                $pfb_dir, $newname . $suffix . '.pfb');

            next unless -e $oldfn;
            if ($suffix eq 'LCDFJ' and -z $oldfn) {
                unlink $oldfn;
                next;
            }

            my $cmd = qq(t1disasm "$oldfn");
            open my $t1disasm, '-|:raw', $cmd
                or die "[ERROR]     Could not run '$cmd': $!";
            my @pfbdata = readline $t1disasm;
            close $t1disasm
                or die "[ERROR]     '$cmd' failed";

            for (@pfbdata) {
                if (m/%!PS-AdobeFont-1.0:[ ] | \/FontName[ ]/xms) {
                    s/$font->{cff_name}/$newname/;
                }
                if (m/\/Notice[ ]/xms) {
                    s/[(]/($NOTICE/xms;
                }
                if (m/\/FullName[ ] | \/FamilyName[ ]/xms) {
                    s/$full_family/$newfullfam/
                        or s/(.+?)(-|\z)/$1$ARGV{t1suffix}$2/;
                }
            }

            $cmd = qq(t1asm --pfb >"$newfn");
            open my $t1asm, '|-:raw', $cmd
                or die "[ERROR]     Could not run '$cmd': $!";
            print {$t1asm} @pfbdata;
            close $t1asm
                or die "[ERROR]     '$cmd' failed";

            unlink $oldfn unless $oldfn eq $newfn;

            $mapdata =~ s/$font->{cff_name}$suffix(?!-)/$newname$suffix/g;
        }
    }

    open $map, '>', $mapfile
        or die "[ERROR]     Cannot open '$mapfile' for writing";
    print {$map} $mapdata;
    close $map;

    return;
}


############################################################################


package main;

if ($RUNNING_AS_MAIN) {
    main();
}


__END__


############################################################################


    To create the documentation:

    pod2man --center='Marc Penninga' --release='fontools' --section=1 \
        autoinst - | groff -Tps -man - | ps2pdf - autoinst.pdf


=pod

=head1 NAME

autoinst - wrapper around the F<LCDF TypeTools>,
for installing and using OpenType fonts in LaTeX.


=head1 SYNOPSIS

B<autoinst> I<-help>

B<autoinst> [I<options>] B<font(s)>


=head1 DESCRIPTION

Eddie Kohler's I<LCDF TypeTools> are superb tools for installing
OpenType fonts in LaTeX, but they can be hard to use:
they need many, often long, command lines
and don't generate the F<fd> and F<sty> files LaTeX needs.
B<autoinst> simplifies the use of the I<TypeTools> for font installation
by generating and executing all commands for I<otftotfm>,
and by creating and installing all necessary F<fd> and F<sty> files.

Given a family of font files (in F<otf> or F<ttf> format),
B<autoinst> will create several LaTeX font families:

=over 2

=over 3

=item -

Four text families (with lining and oldstyle digits,
each in both tabular and proportional variants),
all with the following shapes:

=over 2

=over 8

=item I<n>

Roman (i.e., upright) text

=item I<it>, I<sl>

Italic and slanted (sometimes called oblique) text

=item I<sc>

Small caps

=item I<scit>, I<scsl>

Italic and slanted small caps

=item I<sw>

Swash

=item I<nw>

"Upright swash"

=back

=back

=item -

For each T1-encoded text family:
a family of TS1-encoded symbol fonts, in roman, italic and slanted shapes.

=item -

Families with superiors, inferiors, numerators and denominators,
in roman, italic and slanted shapes.

=item -

Families with "Titling" characters;
these I<"... replace the default glyphs
with corresponding forms designed specifically for titling.
These may be all-capital and/or larger on the body,
and adjusted for viewing at larger sizes">
(according to the OpenType Specification).

=item -

An ornament family; also in roman, italic and slanted shapes.

=back

=back

Of course, if your fonts don't contain italics, oldstyle digits, small caps
etc., the corresponding shapes and families are not created.
In addition, the creation of most families and shapes can be controlled
by the user (see L</COMMAND-LINE OPTIONS> below).

These families use the I<FontPro> project's naming scheme:
I<< <FontFamily>-<Suffix> >>, where I<< <Suffix> >> is:

=over 8

=item I<LF>

proportional (i.e., figures have varying widths) lining figures

=item I<TLF>

tabular (i.e., all figures have the same width) lining figures

=item I<OsF>

proportional oldstyle figures

=item I<TOsF>

tabular oldstyle figures

=item I<Sup>

superior characters (note that most fonts have only an incomplete set of
superior characters: digits, some punctuation and the letters I<abdeilmnorst>;
normal forms are used for other characters)

=item I<Inf>

inferior characters; usually only digits and some punctuation,
normal forms for other characters

=item I<Titl>

Titling characters; see above

=item I<Orn>

ornaments

=item I<Numr>, I<Dnom>

numerators and denominators

=back

The individual fonts are named I<< <FontName>-<suffix>-<shape>-<enc> >>,
where I<< <suffix> >> is the same as above (but in lowercase),
I<< <shape> >> is either empty, "sc" or "swash",
and I<< <enc> >> is the encoding (also in lowercase).
A typical name in this scheme would be I<FiraSans-Light-osf-sc-ly1>.


=head2 Using the fonts in your LaTeX documents

B<autoinst> generates a style file for using the fonts in LaTeX documents,
named F<< <FontFamily>.sty >>. This style file also loads the F<fontenc>
and F<textcomp> packages, if necessary.
To use the fonts, add the command C<<< \usepackage{I<< <FontFamily> >>} >>>
to the preamble of your document.

This style file has a few options:

=over 4

=item C<mainfont>

Redefine C<\familydefault> to make this font the main font
for the document.
This is a no-op if the font is installed as a serif font;
but if the font is installed as a sanserif or typewriter font,
this option saves you from having to redefine C<\familydefault>
yourself.

=item C<lining>, C<oldstyle>, C<tabular>, C<proportional>

Choose which figure style to use.
The defaults are "oldstyle" and "proportional" (if available).

=item C<<< scale=I<< <factor> >> >>>, C<scale=MatchLowercase>

Scale the font by I<< <factor> >>;
as an example, C<<< \usepackage[scale=1.05]{I<< <FontFamily> >>} >>>
will increase the font's size by 5%.
The special value C<MatchLowercase> may be used to scale the font
so that its x-height matches that of the current main font
(which is usually Computer Modern Roman, unless you have loaded
another font package before this one).
The word "scale" may also be spelled as "scaled".

=item C<medium>, C<book>, C<text>, C<normal>, C<regular>

Select the weight that LaTeX will use as the "regular" weight.

=item C<heavy>, C<black>, C<extrabold>, C<demibold>, C<semibold>, C<bold>

Select the weight that LaTeX will use as the "bold" weight.

=back

The default here is not to change LaTeX's default,
i.e. use the "m" and "b" weights.

The style file will also try to load the F<figureversions> package
(on CTAN), which gives easy access to various font shapes and styles.
Using the machinery set up by F<figureversions>, the generated style file
defines a number of commands (which take the text to be typeset as argument)
and declarations (which don't take arguments, but affect all text up to
the end of the current group) to access titling, superior and inferior
characters:


    DECLARATION     COMMAND         SHORT FORM OF COMMAND

    \tlshape        \texttitling    \texttl
    \supfigures     \textsuperior   \textsup, \textsu
    \inffigures     \textinferior   \textinf, \textin


Finally, the style file redefines Latex's C<\textsuperscript> and
C<\textsubscript> commands to use the fonts' superior and inferior figures,
and modifies Latex's footnote mechanism to use C<\textsuperscript>
instead of reduced-size numerals from the regular text font.
The old versions of these commands are still available as
C<\textsuperscript*> and C<\textsubscript*>.

There are no commands for accessing the numerator and denominator
fonts; these can be selected using F<figureversions>' standard commands,
e.g., C<\fontfigurestyle{numerator}\selectfont>.

Once again: all these commands are only generated for existing shapes and number styles;
no commands are generated for shapes and styles that are missing from your fonts.
Note that all these commands are built on top of F<figureversions>; if that package
cannot be found, you're limited to using lower-level commands from
standard NFSS (C<\fontfamily>, C<\fontseries>, C<\fontshape> etc.).

By default, B<autoinst> generates text fonts with OT1, LY1 and T1
encodings, and the generated style files use T1 as the default text encoding.
Other encodings can be chosen using the I<-encoding> option
(see L</COMMAND-LINE OPTIONS> below).


=head2 Maths

This is an experimental feature; B<USE AT YOUR OWN RISK!>
Test the results thoroughly before using them in real documents,
and be warned that future versions of B<autoinst> may introduce
incompatible changes.

The I<-math> option tells B<autoinst> to generate basic math fonts.
When enabled, the generated style file defines a few extra options
to access these math fonts:

=over 4

=item C<math>

Use these fonts for the maths in your document.

=item C<mathlining>, C<matholdstyle>, C<mathtabular>, C<mathproportional>

Choose which figure style and alignment to use in maths.
The defaults are "mathlining" and "mathtabular".

=item C<mathcal>

Use the swash characters from these fonts as the C<\mathcal> alphabet.
(This option will only exist if your fonts actually contain
both swash characters and a C<swsh> feature to access them).

=item C<nomathgreek>

Don't redeclare greek letters in math.

=item C<<< math-style=I<< <style> >> >>>

Choose the "math style" to use.
With C<math-style=ISO>, all latin and greek letters in math are italic;
with C<math-style=TeX> (the default), uppercase greek is upright;
with C<math-style=french>, all greek as well as uppercase latin is upright;
and with C<math-style=upright> all letters are upright.

=item C<<< scriptscale=I<< <scale> >> >>>

By default, Latex loads fonts for the "script" and "scriptscript" styles
at 70% and 50% of the text font size. For many text fonts, this is too small
and hurts readability.
This option scales the "script" style by a factor of I<scale> and
the "scriptscript" style by the square of that.
The default value is 1.1, which loads the "script" and "scriptscript" styles
at a more readable 77% and 60.5%, respectively.
To use Latex's defaults, use C<scriptscale=1.0>.

=back

The style file also defines commands C<\up...> and C<\it...> to access upright
and italic greek characters regardless of the chosen math style:
C<\upGamma>, C<\upalpha>, C<\itDelta>, C<\itbeta> etc.

Note that this C<math> option only affects digits, latin and greek letters,
plus a few basic punctuation characters; all other mathematical symbols,
operators, delimiters etc. are left as they were before.
If you don't want to use TeX's default versions of those symbols,
load another math package (such as F<mathdesign> or F<newtxmath>)
before loading the B<autoinst>-generated style file.

Finally, note that B<autoinst> doesn't check if your fonts actually contains
all of the required characters;
it just assumes that they do and sets up the style file accordingly.
Even if your fonts do contain greek, characters such as C<\varepsilon>
may be missing.
You may also find that some glyphs I<are> present in your fonts,
but don't work well in equations or don't match other symbols;
edit the generated style file to remove the declarations of
these offending characters.
Once again: test the results before using them!
If the characters themselves are fine but spaced too tightly,
you may try increasing the side bearings in math fonts with
the I<-mathspacing> option (see below), e.g. C<-mathspacing=50>.


=head2 NFSS codes

LaTeX's New Font Selection System (NFSS)
identifies fonts by a combination of family,
series (the concatenation of weight and width), shape and size.
B<autoinst> parses the font's metadata to determine these parameters.
When this fails (usually because the font family contains uncommon weights,
widths or shapes),
B<autoinst> ends up with multiple fonts having the same values
for these font parameters; such fonts cannot be used in NFSS,
since there's no way distinguish them.
When B<autoinst> detects such a situation, it will print an error message
and abort.
If that happens, either rerun B<autoinst> on a smaller set of fonts,
or add the missing widths, weights and shapes to the tables C<@WIDTH>,
C<@WEIGHT> and C<%SHAPE> in the source code.
Please also send a bug report (see L<AUTHOR> below).

The mapping of shapes to NFSS codes is done using the following table:

    SHAPE                               CODE
    --------------------------------    ----
    Roman, Upright                      n
    Italic                              it
    Oblique, Slant(ed), Incline(d)      sl

(I<Exception:> Adobe Silentium Pro contains two Roman shapes;
we map the first of these to C<n>, for the second one we (ab)use the C<it> code
as this family doesn't contain an Italic shape.)

For weights and widths, B<autoinst> tries to the standard NFSS codes
(ul, el, l, sl, m, sb, b, eb and ub for weights;
uc, ec, c, sc, m, sx, x, ex and ux for widths)
as much as possible.
Of course, not all 81 combinations of these NFSS weights and widths will map
to existing fonts;
and conversely it may not be possible to assign every existing font
a unique code in a sane way (especially for the weights,
some font families offer more variants than NFSS's codes can handle;
e.g., Fira Sans contains fifteen different weights!).
Therefore every font is also assigned a "series" name that is
the concatenation of its weight and width,
after expanding any abbreviations and converting to lowercase.
A font of "Cond" width and "Ultra" weight will then be known
as "ultrablackcondensed".

The exact mapping between fonts and NFSS codes can be found
in the generated F<fd> files and in the log file
(you may want to run B<autoinst> with the I<-dryrun> option
to check the chosen mapping beforehand).
The I<-nfssweight> and I<-nfsswidth> command-line options can be used
to finetune the mapping between NFSS codes and fonts.

To access specific weights or widths,
one can always use the C<\fontseries> command with the full series name
(i.e., C<\fontseries{demibold}\selectfont>).


=head2 Ornaments

B<autoinst> provides a best-effort interface to access ornament characters.
The OpenType specification offers two ways for fonts to implement ornaments:
one way is to map them to the lowercase ASCII letters, the other is
to define them as alternates for the "bullet" character.
Ornaments of the first type can be used from Latex without problem,
but ornaments implemented in the second way cannot easily be used from Latex
(at least not generically; it may be done by creating font-specific encoding files).

Unfortunately, there is no way to tell which of these alternatives a font uses;
B<autoinst> just assumes that the font maps ornaments to lowercase ASCII
and creates an OT1-encoded font that hopefully contains the ornaments,
plus a C<\textornament> command to access them.
That command takes one argument: the slot number of the ornament.
E.g., to access the ornament at the position of "a" (hexadecimal 0x61),
use C<\textornament{"61}>.

To see which ornaments a font contains (and at which positions),
run LaTeX on the file F<nfssfont.tex> (which is included in any
standard LaTeX installation), supply the name of the ornament font
(i.e., C<Garamontio-Regular-orn-u>) and give the command C<\table\bye>;
this will create a table of all glyphs in that font.
If this table shows no ornaments, your font unfortunately handles ornaments
in a non-Latex-compatible (or at least non-B<autoinst>-compatible) way.

As a final caveat, note that even when your font does handle ornaments in
a Latex-compatible way, it may very well map them to other characters
(such as digits or punctuation) instead of lowercase ASCII.


=head1 WARNINGS AND CAVEATS

=head2 OpenType fonts and licensing issues

Since F<pdfTeX> cannot subset otf-flavoured OpenType fonts,
I<otftotfm> will convert such fonts to Type1 (pfb) format.
However, many fonts (at least those licensed under the SIL Open Font License)
do not allow redistributing such converted versions under their original name.

In order to try to meet such licensing requirements, B<autoinst> provides
a I<-t1suffix> command-line option that appends a suffix to the names
(both the filename and the internal font name)
of all generated Type1 fonts; see L</COMMAND-LINE OPTIONS> below.

Please note that I am not a lawyer and do not guarantee that
this suffix is sufficient to meet the license's requirements.
When in doubt, consult a real lawyer!


=head2 Sorry, LIGTABLE too long for me to handle

The LIGTABLE in TeX's F<tfm> files, which contains a font's ligatures
and kerning pairs, is limited to about 32,500 entries (2^15 - 256).
If the number of ligatures plus kerns in a font is higher than that limit,
I<pltotf> and I<vptovf> will complain loudly and ignore the excess entries.
This happens at least with Adobe's Source Serif 4 and Minion 3 font families.
Even when I<pltotf> and I<vptovf> don't warn about the LIGTABLE's size,
you may still find that I<pdftex> crashes with a
C<Bad metric (TFM) file> error.
The best way to handle this situation is to use B<autoinst>'s C<-extra> option
to raise F<otftotfm>'s value for the C<--min-kern> parameter, which causes it
to ignore small kerning pairs: C<-extra='--min-kern=6.0'>.
Finding a working value for the C<--min-kern> parameter may require some
trial and error.


=head2 A note for MiKTeX users

Automatically installing the fonts into a suitable TEXMF tree
(as B<autoinst> tries to do by default) only works for TeX-installations
that use the F<kpathsea> library; with TeX distributions that implement
their own directory searching, such as MiKTeX, B<autoinst> will complain
that it cannot find the F<kpsewhich> program and move all generated files
into a subdirectory C<autoinst_output/> of the current directory.
If you use such a TeX distribution, you should either move these files
to their correct destinations by hand, or use the I<-target> option
(see L</COMMAND-LINE OPTIONS> below) to manually specify a TEXMF tree.

Also, some OpenType fonts contain so many kerning pairs that the resulting
F<pl> and F<vpl> files are too big for MiKTeX's F<pltotf> and F<vptovf>;
the versions that come with W32TeX (F<http://www.w32tex.org>)
and TeXLive (F<http://tug.org/texlive>) don't seem to have this problem.


=head2 A note for MacTeX users

By default, B<autoinst> will try to install all generated files into
the $TEXMFLOCAL tree; when this directory isn't user-writable,
it will use the $TEXMFHOME tree instead.  Unfortunately, MacTeX's version
of C<updmap-sys> doesn't search in $TEXMFHOME,
and hence MacTeX will not find the new fonts.

To remedy this, either run B<autoinst> as root (so that it can install
everything into $TEXMFLOCAL) or manually run C<updmap -user> to tell
TeX about the files in $TEXMFHOME.
This latter option does, however, come with some caveats;
see F<https://tug.org/texlive/scripts-sys-user.html>.



=head1 COMMAND-LINE OPTIONS

B<autoinst> tries hard to do The Right Thing (TM) by default,
so you usually won't need these options;
but most aspects of its operation can be fine-tuned if you want to.

You may use either one or two dashes before options,
and option names may be shortened to a unique prefix
(e.g., B<-encoding> may be abbreviated to B<-enc> or even B<-en>,
but B<-e> is ambiguous (it may mean either B<-encoding> or B<-extra>)).


=head2 General options

=over 4

=item B<-help>

Print a (relatively) short help text and exit.

=item B<-dryrun>

Don't generate output; just parse input fonts and write
the results to the log file.

=item B<-verbose>

Add more details to the log file.

=item B<-version>

Print B<autoinst>'s version number and exit.

=back


=head2 Font creation options

=over 4

=item B<-encoding>=I<encoding[,encoding]>

Generate the specified encoding(s) for the text fonts.
Multiple encodings may be specified as a comma-separated list
(without spaces!); the default choice of encodings is C<OT1,LY1,T1>.

For each encoding argument, B<autoinst> will first check if it is
the filename of an encoding file, and if found it will use that;
otherwise the argument is assumed to be the name of one of
the built-in encodings.
If the argument is a filename,
B<autoinst> will define the font with an NFSS encoding
equal to the filename (minus a ".enc" extension),
except when the filename starts with "U_";
in that case the NFSS encoding will be "U"
and the part after "U_" will be used as the "enc" part
of the name of the generated font.

Currently B<autoinst> comes with built-in support for the OT1, T1/TS1, LY1,
T2A/B/C, T3/TS3, T4, T5, LGR, CS, L7X and QX encodings.
(The corresponding files are called F<fontools_ot1.enc> etc.,
to avoid name clashes with other packages;
the F<fontools_> prefix may be omitted.)

=item B<-ts1>/B<-nots1>

Control the creation of TS1-encoded fonts. The default is B<-ts1>
if the text encodings (see I<-encoding> above) include T1,
B<-nots1> otherwise.

=item B<-lining>/B<-nolining>

Control the creation of fonts with lining figures. The default is
B<-lining>.

=item B<-oldstyle>/B<-nooldstyle>

Control the creation of fonts with oldstyle figures. The default is
B<-oldstyle>.

=item B<-proportional>/B<-noproportional>

Control the creation of fonts with proportional figures. The default is
B<-proportional>.

=item B<-tabular>/B<-notabular>

Control the creation of fonts with tabular figures. The default is
B<-tabular>.

=item B<-smallcaps>/B<-nosmallcaps>

Control the creation of small caps fonts. The default is
B<-smallcaps>.

=item B<-swash>/B<-noswash>

Control the creation of swash fonts. The default is B<-swash>.

=item B<-titling>/B<-notitling>

Control the creation of titling families. The default is B<-titling>.

=item B<-superiors>/B<-nosuperiors>

Control the creation of fonts with superior characters.
The default is B<-superiors>.

=item B<-inferiors> [ = B<none> | B<auto> | B<subs> | B<sinf> | B<dnom> ]

=item B<-noinferiors>

The OpenType standard defines several kinds of digits that might be used
as inferiors or subscripts: "Subscripts" (OpenType feature C<subs>),
"Scientific Inferiors" (C<sinf>), and "Denominators" (C<dnom>).
This option allows the user to determine which of these styles B<autoinst>
should use for the inferior characters.
Alternatively, the value "auto" tells B<autoinst> to use the first value
in C<sinf>, C<subs> or C<dnom> that is supported by the font.
Saying just B<-inferiors> is equivalent to B<-inferiors=auto>;
otherwise the default is B<-noinferiors>.

I<< If you specify a style of inferiors that isn't present in the font,
B<autoinst> will fall back to its default behaviour of not creating fonts
with inferiors at all; it won't try to substitute one of the other styles. >>

=item B<-fractions>/B<-nofractions>

Control the creation of fonts with numerators and denominators.
The default is B<-nofractions>.

=item B<-ligatures>/B<-noligatures>

Some fonts contain glyphs for the standard f-ligatures (ff, fi, fl, ffi, ffl),
but don't provide a C<liga> feature to access these.
This option tells B<autoinst> to add extra C<LIGKERN> rules to
the generated fonts to enable the use of these ligatures.
The default is B<-ligatures>, except for typewriter fonts.

Specify B<-noligatures> to disable generation of ligatures even for fonts
that do contain a C<liga> feature.

=item B<-ornaments>/B<-noornaments>

Control the creation of ornament fonts. The default is B<-ornaments>.

=item B<-serif>/B<-sanserif>/B<-typewriter>

Install the font as a serif, sanserif or typewriter font, respectively.
This changes how you access the font in LaTeX:
with C<\rmfamily>/C<\textrm>, C<\sffamily>/C<\textsf>
or C<\ttfamily>/C<\texttt>.

Installing the font as a typewriter font will cause two further changes:
it will - by default - turn off the use of f-ligatures
(though this can be overridden with the I<-ligatures> option),
and it will disable hyphenation for this font.
This latter effect cannot be re-enabled in B<autoinst>;
if you want typewriter text to be hyphenated, use the F<hyphenat> package.

If none of these options is specified, B<autoinst> tries to guess:
if the font's filename contains the string "mono"
or if the field C<isFixedPitch> in the font's C<post> table is True,
it will select B<-typewriter>;
else if the filename contains "sans" it will select B<-sanserif>;
otherwise it will opt for B<-serif>.

=item B<-math>

Tells B<autoinst> to create basic math fonts (see above).

=item B<-mathspacing>=I<amount>

Letterspace each character in the math fonts by I<amount> units,
where 1000 units equal one em.
In my opinion, many text fonts benefit from letterspacing by 50 to 100 units
when used in maths; some fonts need even more. Use your own judgement!

=back


=head2 Output options

=over 4

=item B<-t1suffix> [ = I<SUFFIX> ]

Tell B<autoinst> to modify the font names of all generated Type1-fonts,
by adding I<SUFFIX> to the family name.
If you use this option without specifying a I<SUFFIX> value,
B<autoinst> will use the value "PS".
The default behaviour when this option is not given
is to not modify font names at all.

See also L</OpenType fonts and licensing issues> in L<WARNINGS AND CAVEATS> above.

=item B<-target>=I<DIRECTORY>

Install all generated files into the TEXMF tree at I<DIRECTORY>.

By default, B<autoinst> searches the $TEXMFLOCAL and $TEXMFHOME trees
and installs all files into the first user-writable TEXMF tree it finds.
If B<autoinst> cannot find such a user-writable directory
(which shouldn't happen, since $TEXMFHOME is supposed to be user-writable)
it will print a warning message and put all files into the subdirectory
C<autoinst_output/> of the current directory.
It's then up to the user to move the generated files to a better location
and update all relevant databases
(usually by calling F<texhash> and F<updmap>).

=item B<-vendor>=I<VENDOR>

=item B<-typeface>=I<TYPEFACE>

These options are equivalent to F<otftotfm>'s I< --vendor> and I< --typeface>
options: they change the "vendor" and "typeface" parts of the names of the
subdirectories in the TEXMF tree where generated files will be stored.
The default values are "lcdftools" and the font's FontFamily name.
These options change I<only> directory names,
not the names of any generated files.

=item B<-logfile>=I<filename>

Write log data to F<filename> instead of the default F<< <fontfamily>.log >>.
If the file already exists, B<autoinst> appends to it;
it doesn't overwrite an existing file.

=back


=head2 Specialist options

=over 4

=item B<-defaultlining>/B<-defaultoldstyle>

=item B<-defaulttabular>/B<-defaultproportional>

Tell B<autoinst> which figure style is the current font family's default
(i.e., which figures you get when you don't specify any OpenType features).

I<Don't use these options unless you are certain you need them!>
They are only needed for fonts that don't provide OpenType features
for their default figure style; and even in that case,
B<autoinst>'s default values (B<-defaultlining> and B<-defaulttabular>)
are usually correct.

=item B<-nfssweight>=I<code>=I<weight>

=item B<-nfsswidth>=I<code>=I<width>

Map the NFSS code I<code> to the given weight or width,
overriding the built-in tables.
Each of these options may be given multiple times,
to override more than one NFSS code.
Example: to map the C<ul> code to the "Thin" weight,
use C<-nfssweight=ul=thin>.
To inhibit the use of the C<ul> code completely,
use C<-nfssweight=ul=>.

=item B<-extra>=I<extra options>

Pass I<extra options> to the commands for I<otftotfm>.
To prevent I<extra options> from accidentily being interpreted as
options to B<autoinst>, they should be properly quoted.

=item B<-manual>

Manual mode; for users who want to post-process the generated files
and commands. By default, B<autoinst> immediately executes all
F<otftotfm> commands it generates;
in manual mode, these are instead written to a file F<autoinst.bat>.
Furthermore it tells F<otftotfm> to generate human readable (and editable)
F<pl/vpl> files instead of the default F<tfm/vf> ones,
and to place all generated files in a subdirectory C<./autoinst_output/>
of the current directory, rather than install them into your TeX installation.

When using this option, you need to execute the following manual steps after
B<autoinst> has finished:

=over 2

=item - run F<pltotf> and F<vptovf> on the generated F<pl> and F<vf> files,
to convert them to F<tfm/vf> format;

=item - move all generated files to a proper TEXMF tree,
and, if necessary, update the filename database;

=item - tell TeX about the new F<map> file
(usually by running C<updmap> or similar).

=back

Note that some options (I<-target>, I<-vendor> and I<-typeface>)
are meaningless, and hence ignored, in manual mode.

Also note that font name modification doesn't happen in manual mode.

=item B<-nofigurekern>

Some fonts provide kerning pairs for tabular figures.
This is very probably not what you want
(e.g., numbers in tables won't line up exactly).
This option adds extra I< --ligkern> options
to the commands for I<otftotfm> to suppress such kerns.
Note that this option leads to very long commands (it adds
one hundred I< --ligkern> options), which may cause problems on some systems;
hence it is not active by default.

=back


=head1 SEE ALSO

Eddie Kohler's B<TypeTools> and B<T1Utils> (F<http://www.lcdf.org/type>).

B<Perl> can be obtained from F<http://www.perl.org>;
it is included in most Linux distributions.
For Windows, try ActivePerl (F<http://www.activestate.com>)
or Strawberry Perl (F<http://strawberryperl.com>).

B<LuaTeX> (F<http://www.luatex.org>) and
B<XeTeX> (F<http://www.tug.org/xetex>)
are Unicode-aware TeX engines that can use OpenType fonts directly,
without any (La)TeX-specific support files.

The B<FontPro> project (F<https://github.com/sebschub/FontPro>)
offers very complete LaTeX support (even for typesetting maths) for
Adobe's Minion Pro, Myriad Pro and Cronos Pro font families.


=head1 AUTHOR

Marc Penninga (F<marcpenninga@gmail.com>)

When sending a bug report, please give as much relevant information as
possible; this usually includes (but may not be limited to) the log file
(please add the I<-verbose> command-line option, for extra info).
If you see any error messages, please include these I<verbatim>;
don't paraphase.


=head1 COPYRIGHT

Copyright (C) 2005-2026 Marc Penninga.


=head1 LICENSE

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 2 of the License,
or (at your option) any later version.
A copy of the text of the GNU General Public License is included in
the I<fontools> distribution; see the file F<GPLv2.txt>.


=head1 DISCLAIMER

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.


=head1 VERSION

This document describes B<autoinst> version 20260210.


=head1 RECENT CHANGES

(See the source for the full story, all the way back to 2005.)

=over 12

=item I<2026-02-10>

Generated style files now use the I<figureversions> package
to access superior and inferior figures and fractions,
instead of the (deprecated) I<fontaxes> package.
Added the I<scriptscale> option to the generated style file.
When creating math fonts, we use the font's "mgrk" feature,
if present.
Fixed a few obscure bugs.

=item I<2025-09-09>

Use the font's WeightClass if its weight cannot be determined
from other metadata (suggested by Christoph L. Spiel).

=item I<2025-08-25>

Fixed a bug in the processing of the C<-nfssweight> and
C<-nfsswidth> options.

=item I<2025-08-19>

Fixed a bug where any fonts with the word "Typewriter"
in their name would be parsed as "Italic".

=item I<2025-07-02>

The hack in font metadata parsing for Source Serif 4
(See 2025-01-07) is also needed for other fonts;
at least for Arno Pro, maybe some other Adobe fonts as well.
So we changed the test again: we apply this hack by default,
except for Libertinus.

=item I<2025-06-23>

Introduced the "U_" rule for encoding file names.

=item I<2025-04-16>

Don't load the I<mweights> package, as its functionality
is now part of the LaTeX kernel
(and, in fact, has been for a while ...).

=item I<2025-01-07>

The 'fix' in font metadata parsing that we introduced
for Source Serif 4 was biting Libertinus Serif Display
(and maybe other fonts as well),
so we now test if the family is actually Source Serif 4
before applying that fix.

=back


=begin Really_old_history

=over 12

=item I<2024-01-04>

We take a more generic approach to font metadata parsing;
this should work better for fonts with unusually named weights
or widths.
We now also warn in font metadata parsing could not find
a 'Regular' weight or width.

=item I<2023-12-30>

Bugfix: font info parsing now works for Junicode 2.

=item I<2023-09-14>

Added the C<\up...> and C<\it...> commands to the style file.

=item I<2023-06-28>

Adapted font metadata parsing for Adobe Source Serif 4.

=item I<2023-02-01>

Added support for the T4, T5, CS, L7X and QX encodings.

=item I<2023-01-31>

If the fonts contain superior and/or inferior figures,
the generated style file now redefines the C<\textsuperscript>
and C<\textsubscript> commands, and patches Latex's footnote
mechanism to use these figures
(inspired by the F<realscripts> package).
Fixed a few bugs in metadata parsing, style file generation
and the C<-t1suffix> option, so that the latter also works
for dvips and dvipdfmx.

=item I<2021-11-15>

Bugfix: font info parsing now works for Adobe Source Serif 4.

=item I<2021-07-21>

Bugfixes:

=over 3

=item -

Yet another problem with argument quoting on Windows.

=item -

Selecting numerator/denominator fonts didn't work as documented.

=item -

Font info parsing failed for Microsoft Sitka and LucasFonts Thesis.

=back

=item I<2021-04-01>

The I<-encoding> option now also accepts filenames of encoding files
in directories other than the current directory.
Directory names containing spaces do (or at least should) also work.

=item I<2020-12-18>

Fixed a problem with files not being found on Windows.
Added extra C<--unicoding> options to prevent getting
lowercase f-ligatures in smallcaps for some buggy fonts.
Optimized font info parsing for DTL and TypeBy font families.
Cleaned up the code for better maintainability.

=item I<2020-07-29>

Some changes in the generated F<sty> and F<fd> files,
to improve compatibility with the F<microtype> package.
Made sure that F<pfb> fonts are always generated whenever
the input fonts are in F<otf> format.
Added the I<-t1suffix> command-line option,
to modify the font and file names of those generated Type1 fonts.

=item I<2020-06-19>

Added the C<nomathgreek> option to generated style files.
Reorganized the generated style files to make them more
standards-conforming.

=item I<2020-05-27>

Added basic (and still somewhat experimental) math support.
Implemented the C<scale=MatchLowercase> option value
in the generated style files.
"Wide" fonts are mapped to the C<sx> NFSS code instead of C<x>,
to cater for League Mono Variable's Wide and Extended widths.
The generated style files now use C<\textsup> and C<\textinf>
instead of the more cryptic C<\textsu> and C<\textin> to access
superior and inferior characters
(though the old forms are retained for backwards compatibility).

=item I<2020-05-11>

When present, use encoding files in the current working directory
in preference of the ones that come with B<autoinst>.
Changed the way ornament fonts are created; ornament glyphs are now
always included in the position chosen by the font's designer.

=item I<2020-04-28>

Fix a bug where the first font argument would be mistaken for
an argument to I<-inferiors>.

=item I<2020-01-29>

Don't create empty subdirectories in the target TEXMF tree.

=item I<2019-11-18>

Fine-tuned calling of F<kpsewhich> on Windows (patch by Akira Kakuto).
The font info parsing now also recognises numerical weights, e.g. in Museo.

=item I<2019-10-29>

The generated style files now use T1 as the default text encoding.

=item I<2019-10-27>

The mapping in F<fd> files between font series and standard NFSS attributes
now uses the new I<alias> function instead of I<ssub> (based on code by
Frank Mittelbach).
The way F<otftotfm> is called was changed to work around a Perl/Windows bug;
the old way might cause the process to hang.
Using the I<-target> option now implies I<-noupdmap>, since choosing
a non-standard target directory interferes with kpathsea/texhash and updmap.

=item I<2019-10-01>

Handle I<-target> directories with spaces in their path names.
Tweaked messages and logs to make them more useful to the user.

=item I<2019-07-12>

Replaced single quotes in calls to F<otfinfo> with double quotes,
as they caused problems on Windows 10.

=item I<2019-06-25>

=over 3

=item -

Added the I<-mergeweights> and I<-mergeshapes> options,
and improved I<-mergewidths>.

=item -

Improved the parsing of fonts' widths and weights.

=item -

Improved the mapping of widths and weights to NFSS codes.

=item -

Changed logging code so that that results of font info parsing
are always logged, even (especially!) when parsing fails.

=item -

Added a warning when installing fonts from multiple families.

=item -

Added simple recognition for sanserif and typewriter fonts.

=item -

Fixed error checking after calls to F<otfinfo>
(B<autoinst> previously only checked whether C<fork()> was successful,
not whether the actual call to F<otfinfo> worked).

=item -

Fixed a bug in the I<-inferiors> option;
when used without a (supposedly optional) value,
it would silently gobble the next option instead.

=back

=item I<2019-05-22>

Added the I<mainfont> option to the generated F<sty> files.
Prevented hyphenation for typewriter fonts
(added C<\hyphenchar\font=-1> to the C<\DeclareFontFamily> declarations).
Added the I<-version> option.

=item I<2019-05-17>

Changed the way the F<-ligatures> option works:
F<-ligatures> enables f-ligatures (even without a C<liga> feature),
F<-noligatures> now disables f-ligatures (overriding a C<liga> feature).

=item I<2019-05-11>

Separate small caps families are now also recognised when the family name
ends with "SC" (previously B<autoinst> only looked for "SmallCaps").

=item I<2019-04-22>

Fixed a bug in the generation of swash shapes.

=item I<2019-04-19>

Fixed a bug that affected -mergesmallcaps with multiple encodings.

=item I<2019-04-16>

Added the <-mergesmallcaps> option, to handle cases where
the small caps fonts are in separate font families.
Titling shape is now treated as a separate family instead of a distinct shape;
it is generated only for fonts with the C<titl> feature.
Only add f-ligatures to fonts when explicitly asked to (I<-ligatures>).

=item I<2019-04-11>

Tried to make the log file more relevant.
Added the I<-nfssweight> and I<-nfsswidth> options,
and finetuned the automatic mapping between fonts and NFSS codes.
Changed the name of the generated log file to F<< <fontfamily>.log >>,
and revived the I<-logfile> option to allow overriding this choice.
Made I<-mergewidths> the default (instead of I<-nomergewidths>).

=item I<2019-04-01>

Fine-tuned the decision where to put generated files;
in particular, create $TEXMFHOME if it doesn't already exist
and $TEXMFLOCAL isn't user-writable.

In manual mode, or when we can't find a user-writable TEXMF tree,
put all generated files into a subdirectory C<./autoinst_output/>
instead of all over the current working directory.

Added "auto" value to the I<inferiors> option,
to tell B<autoinst> to use whatever inferior characters are available.

=item I<2019-03-14>

Overhauled the mapping of fonts (more specifically of weights and widths;
the mapping of shapes didn't change) to NFSS codes.
Instead of inventing our own codes to deal with every possible weight
and width out there, we now create "long" codes based on the names
in the font metadata.
Then we add C<ssub> rules to the F<fd> files to map the standard NFSS codes
to our fancy names (see the section B<NFSS codes>;
based on discussions with Frank Mittelbach and Bob Tennent).

=item I<2018-08-10>

Added encoding files for LGR and T2A/B/C to I<fontools>.

=item I<2018-03-26>

Added the I<-(no)mergewidths> option; tried to improve the documentation.

=item I<2018-03-26>

Added the "Text" weight and the I<-(no)mergewidths> option.
Changed the NFSS codes for "Thin" and "Book" to C<i> and C<o>, respectively.
Tried to improve the documentation.

=item I<2018-01-09>

Added the C<sl> weight for font families (such as Fira Sans) that contain both
"Book" and "Regular" weights (reported by Bob Tennent).
Added the "Two", "Four", "Eight" and "Hair" weights (for Fira Sans).

=item I<2017-06-16>

Changed the I<-inferiors> option from a binary yes-or-no choice to allow
the user to choose one of the C<subs>, C<sinf> and C<dnom> features.
B<autoinst> now always creates a log file.

=item I<2017-03-21>

Updated the F<fontools_ot1.enc> encoding file to include the "Lslash"
and "lslash" glyphs (thanks to Bob Tennent).

=item I<2015-11-22>

Bugfix: LaTeX doesn't like command names with dashes in it.

=item I<2015-05-13>

Fixed an error message that mixed up width and weight.

=item I<2014-04-04>

Fixed a bug in the font info parsing code.

=item I<2014-01-21>

"Oblique" or "slanted" fonts are now mapped to NFSS code C<sl> instead
of C<it>; added C<ssub> rules to the F<fd> files to substitute slanted fonts
for italic ones if the latter are missing. Fixed a few bugs.

=item I<2014-01-03>

Added the I<-dryrun> and I<-logfile> options; changed which info is logged.
Added the I<-lining>, I<-oldstyle>, I<-tabular> and I<-proportional>
options; the old options with those names have been renamed to
I<-defaultlining>, I<-defaultoldstyle> etc.

=item I<2013-10-31>

The previous change required Perl v5.14 or newer;
now it also works with older versions.

=item I<2013-10-01>

Added the I<-lining>, I<-oldstyle>, I<-tabular> and I<-proportional>
command line options.

=item I<2013-07-25>

The generated F<sty> files now use the I<mweights> package instead of
redefining C<\mddefault> and C<\bfdefault>.
Added C<scale> as an alias for the package option C<scaled>.

=item I<2013-02-06>

Bugfix: the directory names for map and encoding files contained
the "vendor" instead of the "typeface".

=item I<2013-01-03>

Added extra C<ssub> rules to the F<fd> files that substitute C<b> for C<bx>.
Verbose mode now also prints all generated commands before they're executed.

=item I<2012-10-25>

Added extra C<ssub> rules to the F<fd> files that substitute italic
shapes for slanted ones.

=item I<2012-09-25>

Added the I<-vendor>, I<-typeface> and I<-(no)updmap> command line options.

=item I<2012-07-06>

Documentation update.

=item I<2012-03-06>

Implemented the "splitting the font family into multiple subfamilies"
emergency strategy when font info parsing fails.
Added recognition for a number of unusual widths, weights and shapes.

=item I<2012-02-29>

Fixed a bug in the font parsing code,
where possible widths, weights and shapes where tested in the wrong order;
this led to "ExtraLight" fonts being recognised as "Light".
Added recognition for "Narrow" and "Wide" widths.
Also added the I<-(no)figurekern> command-line option.

=item I<2012-02-01>

Reorganised the code, and fixed some bugs in the process.
Added the I<-target> command-line option.
Made B<autoinst> install the F<fd> and F<sty> files in
the same TEXMF tree as the other generated files.
Generate OT1, T1 and LY1 encoded text fonts by default.
Made I<-titling> a default option (instead of I<-notitling>).
Updated the documentation.

=item I<2011-06-15>

Fixed the font info parsing code for some fonts that are
too lazy to spell out "Italic" in full.

=item I<2010-04-29>

The I< --feature=kern> option is only used for fonts that
contain either a I<kern> feature or a I<kern> table.
Font feature selection commands in the F<sty> file are only
generated for shapes and figure styles that are supported
by the current font, and whose generation has not been
turned off using the command-line options.
Fixed the font info parsing to work with the Condensed fonts
in the Minion Pro family.

=item I<2010-04-23>

Always provide the I< --feature=kern> option to F<otftotfm>,
even if the font doesn't have a I<kern> feature;
this will make F<otftotfm> use the I<kern> table if present.
For fonts without a I<liga> feature, add I< --ligkern>
options for the common f-ligatures to the F<otftotfm> command line,
so that any ligatures present in the font will still be used.
Bug fix: the generated F<sty> files now work for font families
with names containing digits.

=item I<2009-04-09>

Prefixed the filenames of  the included encoding files with
I<fontools_>, to prevent name clashes with other packages.

=item I<2009-04-06>

A small patch to the C<get_orn> subroutine:
it now also recognises the I<bullet.xxx> ornament glyphs
in Adobe Kepler Pro.

=item I<2007-08-07>

Fixed a small bug with filename quoting on Windows.

=item I<2007-07-31>

Changed the tables that map weights and widths to NFSS codes:
in some extended families, different combinations of
weight and width were mapped to the same series.
Added a work-around for incorrect size info in some Kepler fonts.
Fixed a small bug in the generated commands for otftotfm
(sometimes, the C<onum> feature was included twice).
Added encoding file for OT1 to the I<fontools> collection.

=item I<2007-07-27>

Two bugfixes: a closing brace was missing in the generated style file,
and the NFSS series was formed as "width plus weight" instead of the reverse.

=item I<2007-06-10>

Bugfix: silently replacing \DeclareOption, \ProcessOptions and
\ExecuteOptions with their counterparts from the xkeyval package
caused problems for some other packages.

=item I<2007-06-04>

Added the I< --no-updmap> option to all generated commands for F<otftotfm>
(except the last); this should yield a significant speed-up for large
families (suggested by Steven E. Harris).
Tweaked the font info parsing to work around a bug in the naming of
some FontFont fonts, where every font is in a family of its own.
Added the C<scaled> option (including the loading of F<xkeyval>)
to the generated style file.
Extended the output of the I<-verbose> option.

=item I<2007-02-08>

Yet Another Complete Rewrite.
The code is now much more readable and more flexible;
the program can now handle fonts from different families,
as well as multiple text encodings.
Rewrote the font info parsing code to work for Arno Pro.

=item I<2006-10-11>

The program determines the fonts' weights, widths and shapes by parsing
the output from C<otfinfo --info> instead of the font filename.
This should make B<autoinst> work for non-Adobe fonts.
Filenames with spaces now work as well.

=item I<2006-08-31>

Made the generated style files try to include F<fontaxes.sty>;
changed the names of the generated fonts and families
(to make the previous change possible);
added command-line options for most font styles and shapes;
tweaked the filename parsing code for Cronos Pro and Gill Sans Pro;
added runtime generation of encoding vectors for ornament fonts
(because GaramondPremier's ornament names differ from other fonts);
changed the NFSS-code for italic small caps and titling to C<scit> and C<tlit>
(to work with F<fontaxes>);
and edited (and hopefully improved) the documentation.

=item I<2005-10-03>

When creating LY1, T1, OT1 or TS1 encoded fonts, the I<-coding-scheme>
option is added to the commands for F<otftotfm>; this should make the
generated F<pl> and F<vpl> files acceptable to I<fontinst>.
Also elaborated the documentation somewhat and fixed a small bug.

=item I<2005-09-22>

Added check to see if filename parsing succeeded;
updated the filename parsing code to cater for GaramondPremier Pro,
Silentium Pro and some non-Adobe fonts;
added the I<-sanserif> and I<-typewriter> options and hacked the
style files to support using several different font families in one document.

=item I<2005-09-12>

Cleaned up the code (it now runs under the F<strict> and F<warnings> pragmas);
fixed a (rather obscure) bug that occurred when creating TS1-encoded
fonts for families with multiple optical masters and oldstyle digits;
added the I<medium, semibold> etc. options to the style file;
and improved the layout of the generated files.

=item I<2005-08-11>

The generated commands weren't actually executed, only printed...
Also added a small hack to cater for fonts
(such as some recent versions of MinionPro)
that contain swash characters but don't provide a C<swsh> feature.

=item I<2005-08-10>

Dropped the "fontname" scheme in favor of a more verbose naming scheme,
since many filenames were still more than eight characters long anyway.
Added F<nfssext.sty>-like commands to the generated style file.
Changed the default encoding to LY1 and added the "inferior" shape.

=item I<2005-08-01>

Rewrote (and hopefully improved) the user interface;
changed the program to by default execute the generated F<otftotfm> command
lines rather than writing them to a file;
added automatic determination of the "fontname" code for the font family;
changed the NFSS code for italic small caps to C<si>; added titling shapes;
changed the generated style
file to include an interface for the ornaments and to load Lehman's NFSS
extensions F<nfssext.sty> if this is installed; corrected the "fontname" codes
for OT1, T1, LY1 and user-specific encodings; extended the output generated by
the I<-verbose> option; and rewrote and extended the documentation.

=item I<2005-06-16>

Did some more finetuning to the filename-parsing code.

=item I<2005-05-31>

Generate correct fontname for OT1-encoded fonts.

=item I<2005-05-18>

Tried to make the filename-parsing code a bit more robust by adding several
weights and widths; changed the error that's displayed when filename parsing
fails; commented the code.

=item I<2005-04-29>

Rewrote large parts of the code (yes it I<was> even worse).

=item I<2005-04-18>

Changed default text-encoding to T1, added TS1.

=item I<2005-03-29>

Added support for font families with multiple widths.

=item I<2005-03-15>

First version.

=back

=end Really_old_history
