diff --git a/gromologist/Section.py b/gromologist/Section.py
index 0e78105..2a6618c 100644
--- a/gromologist/Section.py
+++ b/gromologist/Section.py
@@ -3285,7 +3285,12 @@ class SectionParam(Section):
         except KeyError:
             self.init_subsection(subsection_dict[(len(types), interaction_type)])
             subs = self.subsections[-1]
-        matching = [ent for ent in subs.entries_param if ent.types == types or ent.types == types[::-1]]
+        # an entry matches only when it has the same interaction type: an amber
+        # parameter set may define the same atom types as a proper and as an
+        # improper dihedral, and those must not replace each other
+        matching = [ent for ent in subs.entries_param
+                    if (ent.types == types or ent.types == types[::-1])
+                    and str(ent.interaction_type) == str(interaction_type)]
         if matching:
             action = action_default
             while action not in 'rta':
diff --git a/gromologist/Topology.py b/gromologist/Topology.py
index 95b89b9..1a55b31 100644
--- a/gromologist/Topology.py
+++ b/gromologist/Topology.py
@@ -33,6 +33,17 @@ from typing import Optional, Iterable, TextIO, Union
 import gromologist as gml
 from collections import OrderedDict
 
+# Column header comments written after the section header of the force field parameter
+# sections to document the meaning of the columns
+FF_SECTION_COLUMN_HEADERS = {
+    'atomtypes': '; name  at.num          mass    charge ptype          sigma   epsilon',
+    'bondtypes': ';      i        j   func            b0            kb',
+    'angletypes': ';      i        j        k   func           th0           cth',
+    'dihedraltypes': ';      i        j        k        l   func         phase            kd     pn',
+    # the cmaptypes grid values are not fixed-width, only document the layout
+    'cmaptypes': '; i  j  k  l  func  nx  ny   atomtype-residuetype tokens, nx*ny grid values follow',
+}
+
 
 class Top:
     def __init__(self, filename='', gmx_dir=None, gmx_exe=None, pdb=None, ignore_ifdef=False, define=None, ifdef=None,
@@ -1311,6 +1322,8 @@ class Top:
             # close any open frames before starting a new subsection
             frames = emit_transition(frames, [])
             outfile.write('\n[ {} ]\n'.format(subsection.header))
+            if isinstance(section, gml.SectionParam) and subsection.header in FF_SECTION_COLUMN_HEADERS:
+                outfile.write(FF_SECTION_COLUMN_HEADERS[subsection.header] + '\n')
             for entry in subsection:
                 frames = emit_transition(frames, entry.condition_frames)
                 if not entry.comment and not entry.content:
diff --git a/gromologist/Utils.py b/gromologist/Utils.py
index be771ff..398b466 100644
--- a/gromologist/Utils.py
+++ b/gromologist/Utils.py
@@ -20,11 +20,13 @@ Contents:
         fix_rtp
         find_leap_files
         amber2gmxFF
+        amber2ffa
         reorder_amber_impropers
         dih_match
         read_addAtomTypes
         guess_element_properties
         read_prep_impropers
+        assign_impropers
         prep_to_rtp
         calc_Coulomb_force
         calc_LJ_force
@@ -47,6 +49,7 @@ Notes:
 """
 
 
+import argparse
 import math
 import os, re, sys
 import tempfile
@@ -54,7 +57,7 @@ from contextlib import nullcontext
 from glob import glob
 from subprocess import run, PIPE
 from shutil import copy2, rmtree
-from itertools import permutations, groupby
+from itertools import combinations, permutations, groupby
 
 import gromologist as gml
 from typing import Optional, Iterable, Union, Dict, List, Tuple
@@ -195,12 +198,43 @@ def generate_orca_input(pdb: Union["gml.Pdb", str], directive_file: str, outfile
 
 # TODO move REST2 preparation here
 
-def parse_frcmod(filename: str) -> (dict, dict, dict, dict, dict, dict, dict):
+def _split_frcmod_types(line: str, ntypes: int):
+    """Split leading dash-separated atom type columns of an frcmod/parm file
+    line, tolerating spaces around the dashes (e.g. 'CQ - N*' and
+    'N - C - N*' found in older frcmod files). Returns (types, rest_of_line)
+    or None if the line does not start with the expected type columns."""
+    t = r"[^\s-]+"
+    sep = r"\s*-\s*"
+    pattern = r"^\s*" + sep.join("(" + t + ")" for _ in range(ntypes)) + r"\s+(.*)$"
+    m = re.match(pattern, line)
+    if m is None:
+        return None
+    groups = m.groups()
+    return tuple(groups[:-1]), groups[-1]
+
+
+def parse_scaling_tag(line: str) -> (float, float):
+    """
+    Extracts the optional SCEE=/SCNB= per-torsion 1-4 scaling tags from an
+    Amber parameter line (leap .dat format), defaulting to standard AMBER values
+    :param line: str, line with a dihedral/improper parameter definition
+    :return: tuple of float, (scee, scnb)
+    """
+    scee = re.search(r'(?i)\bSCEE\s*=\s*([-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?)', line)
+    scnb = re.search(r'(?i)\bSCNB\s*=\s*([-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?)', line)
+    return (float(scee.group(1)) if scee else 1.2, float(scnb.group(1)) if scnb else 2.0)
+
+
+def parse_frcmod(filename: str, return_scaling: bool = False):
     """
     Parses either an frcmod file with extra parameters, or a parm file with
     core FF parameters (both have slightly different formats for opening/closing sections)
     :param filename: str, name of the file to be read
+    :param return_scaling: bool, if True, an additional dictionary with per-torsion 1-4
+        scaling factors (SCEE/SCNB tags, defaulting to 1.2/2.0) is returned as
+        {atom types tuple: [(scee, scnb), ...]} with one item per parameter term
     :return: tuple of dict, FF parameres in their respective formats
+        (plus the scaling dict if return_scaling is set)
     """
     dat = True if filename.endswith('dat') else False
     content = open(filename).readlines()
@@ -208,6 +242,7 @@ def parse_frcmod(filename: str) -> (dict, dict, dict, dict, dict, dict, dict):
         raise RuntimeError("LJ type A/C not supported, terminating")
     content = content[1:] if dat else content
     atomtypes, bondtypes, angletypes, dihedraltypes, impropertypes, nonbonded, cmaptypes = {}, {}, {}, {}, {}, {}, {}
+    scaling, last_dihedral_types = {}, None
     cmapresol, cmapres, cmapvals, cmapread = None, [], [], False
     headers = ['MASS', 'BOND', 'ANGL', 'DIHE', 'IMPR', 'HBON', 'NONB', 'LJED', 'CMAP']
     identical_nonbonded = {}
@@ -230,12 +265,18 @@ def parse_frcmod(filename: str) -> (dict, dict, dict, dict, dict, dict, dict):
         if current == 'BOND':
             if dat and '-' not in line[:5]:
                 continue
-            types = tuple(x.strip() for x in line[:5].split('-'))
-            vals = tuple(float(x) for x in line[5:].split()[:2])
+            parsed = _split_frcmod_types(line, 2)
+            if parsed is None:
+                continue
+            types, rest = parsed
+            vals = tuple(float(x) for x in rest.split()[:2])
             bondtypes[types] = [vals[1] / 10, vals[0] * 200 * 4.184]
         elif current == 'ANGL':
-            types = tuple(x.strip() for x in line[:8].split('-'))
-            vals = tuple(float(x) for x in line[8:].split()[:2])
+            parsed = _split_frcmod_types(line, 3)
+            if parsed is None:
+                continue
+            types, rest = parsed
+            vals = tuple(float(x) for x in rest.split()[:2])
             angletypes[types] = [vals[1], vals[0] * 2 * 4.184]
         elif current == 'MASS':
             types = line.split()[0]
@@ -274,16 +315,30 @@ def parse_frcmod(filename: str) -> (dict, dict, dict, dict, dict, dict, dict):
             assert vals[0] == vals[2] and vals[1] == vals[3]
             nonbonded[types] = [float(vals[0]) * 0.2 * 2 ** (-1 / 6), float(vals[1]) * 4.184]
         elif current == 'DIHE':
-            types = tuple(x.strip() for x in line[:12].split('-'))
-            vals = tuple(float(x) for x in line[12:].split()[:4])
+            parsed = _split_frcmod_types(line, 4)
+            if parsed is not None:
+                types, rest = parsed
+                last_dihedral_types = types
+            elif last_dihedral_types is not None:
+                # continuation line with an additional term for the preceding set of types
+                types = last_dihedral_types
+                rest = line
+            else:
+                print(f"Skipping dihedral line {nl + 2} without atom types: {line.strip()}")
+                continue
+            vals = tuple(float(x) for x in rest.split()[:4])
             entry = [vals[2], 4.184 * vals[1] / vals[0], int((vals[3] ** 2) ** 0.5)]
             if types in dihedraltypes.keys():
                 dihedraltypes[types].extend(entry)
             else:
                 dihedraltypes[types] = entry
+            scaling.setdefault(types, []).append(parse_scaling_tag(line))
         elif current == 'IMPR':
-            types = tuple(x.strip() for x in line[:12].split('-'))
-            vals = tuple(float(x) for x in line[12:].split()[:3])
+            parsed = _split_frcmod_types(line, 4)
+            if parsed is None:
+                continue
+            types, rest = parsed
+            vals = tuple(float(x) for x in rest.split()[:3])
             entry = [vals[1], 4.184 * vals[0], int((vals[2] ** 2) ** 0.5)]
             impropertypes[types] = entry
         elif current == 'CMAP':
@@ -311,27 +366,38 @@ def parse_frcmod(filename: str) -> (dict, dict, dict, dict, dict, dict, dict):
     non_atomtypes = [key for key, val in atomtypes.items() if len(val) != 3]
     if non_atomtypes:
         print(f"skipping atomtypes {non_atomtypes}, missing LJ parameters")
+    if return_scaling:
+        return atomtypes, bondtypes, angletypes, dihedraltypes, impropertypes, nonbonded, cmaptypes, scaling
     return atomtypes, bondtypes, angletypes, dihedraltypes, impropertypes, nonbonded, cmaptypes
 
 
-def load_frcmod(top: Union[str, "gml.Top"], filename: str, return_cmap: bool = False, pro_atoms: Optional[dict] = None) \
-        -> Optional[dict]:
+def load_frcmod(top: Union[str, "gml.Top"], filename: str, return_cmap: bool = False, pro_atoms: Optional[dict] = None,
+                warn_scaling: bool = True) -> Optional[dict]:
     """
     Loads an .frcmod file into an existing topology. Can be also launched as
     gml.Top().load_frcmod(...)
     :param top: str or gml.Top, existing gmx topology
     :param filename: str, name of the frcmod file to load
     :param return_cmap: bool, if set to True will return cmaptypes
+    :param warn_scaling: bool, print a warning when per-torsion 1-4 scaling factors
+        that cannot be represented in a regular Gromacs topology are encountered
     :return: None or dict, depending on return_cmap
     """
     top = gml.obj_or_str(top)
-    atomtypes, bondtypes, angletypes, dihedraltypes, impropertypes, nonbonded, cmaptypes = parse_frcmod(filename)
+    atomtypes, bondtypes, angletypes, dihedraltypes, impropertypes, nonbonded, cmaptypes, scaling = \
+        parse_frcmod(filename, return_scaling=True)
+    if warn_scaling:
+        non_standard = sorted({factors for values in scaling.values() for factors in values if factors != (1.2, 2.0)})
+        if non_standard:
+            print(f"WARNING: {filename} uses per-torsion 1-4 scaling {non_standard} that is lost when loading "
+                  "into a regular Gromacs topology; consider gml.amber2ffa() to generate a force field addon "
+                  "with [ addon_scaling ]/[ pair_scaling ] sections instead")
     for k in cmaptypes.keys():
         try:
             cc = [adata[1] for adata in pro_atoms[k[1]] if adata[0] == "C"][0]
             na = [adata[1] for adata in pro_atoms[k[1]] if adata[0] == "N"][0]
             ca = [adata[1] for adata in pro_atoms[k[1]] if adata[0] == "CA"][0]
-        except KeyError:
+        except (KeyError, IndexError, TypeError):
             cc, na, ca = "C", "N", "CA"
         cmaptypes[k].append(f'{cc}-* {na}-{k[-1]} {ca}-{k[-1]} {cc}-{k[-1]} {na}-*'.split())
     params = top.parameters
@@ -344,8 +410,16 @@ def load_frcmod(top: Union[str, "gml.Top"], filename: str, return_cmap: bool = F
     for d in dihedraltypes.keys():
         # TODO add wildcards at the end?
         params.add_bonded_param(d, dihedraltypes[d], 9, action_default='r')
-    for i in impropertypes.keys():
-        params.add_bonded_param(i, impropertypes[i], 4, action_default='r')
+    for key, value in impropertypes.items():
+        # LEaP canonicalizes the outer types of an improper record when loading
+        # it (zParmSetOrderImproperAtoms): the central atom stays at position 3
+        # and the outer types are sorted alphabetically with the wildcards first;
+        # the [ impropers ] entries generated by assign_impropers follow the same
+        # convention, so that pdb2gmx matches them positionally
+        if len(key) == 4:
+            outer = sorted(key[:2] + key[3:], key=lambda x: ' ' if x == 'X' else x)
+            key = (outer[0], outer[1], key[2], outer[2])
+        params.add_bonded_param(key, value, 4, action_default='r')
     for n in nonbonded.keys():
         try:
             params.add_nbfix(*n, new_sigma=nonbonded[n][0], new_epsilon=nonbonded[n][1])
@@ -401,8 +475,85 @@ def read_lib(lib: str) -> (dict, dict, dict):
     return atoms, bonds, connector
 
 
+def assign_impropers(residue_atoms: dict, residue_bonds: dict,
+                     impr_records: Iterable[tuple]) -> dict:
+    """
+    Generate per-residue improper dihedral instances the way LEaP does, so that
+    residues taken from .lib files, which carry no explicit improper lists, obtain
+    [ impropers ] blocks. For every atom with at least three neighbors in the
+    residue's bond graph, all triples of neighbors are tried as outer atoms of an
+    improper centered on it (LEaP keeps the central atom at position 3 of the
+    improper while the first, second and fourth atoms are permutable, loop.c).
+    A triple matches an improper record when the central atom type matches exactly
+    and the non-wildcard outer types of the record occur, in order, in the triple
+    sorted alphabetically by atom type (zbParmSetMatchImproper); the most specific
+    record wins, ties go to the earlier-read one. The atom names are emitted in the
+    canonical order expected by pdb2gmx in the _FF_AMBER_LEAP_ATOM_REORDERING mode:
+    the positions of wildcard record types first (in residue atom order), then the
+    specific record types in their order, so that the [ dihedraltypes ] entries
+    written from the same records match the pushed interactions positionally.
+    :param residue_atoms: dict of tuple, {res: [(name, type, charge, n), ...]} as read by read_lib
+    :param residue_bonds: dict of tuple, {res: [(i, j), ...]} 1-based atom index pairs as read by read_lib
+    :param impr_records: iterable of tuples, improper parameter records of 4 atom
+        types (X wildcards allowed, central atom at position 3) in the order they
+        were read from the parameter files
+    :return: dict of list, {res: [(name1, name2, central, name4), ...]}
+    """
+    records = []
+    for types in impr_records:
+        if len(types) != 4 or types[2] == 'X':
+            # LEaP never matches a record with a wildcard central atom type
+            continue
+        outer = sorted(types[:2] + types[3:], key=lambda t: ' ' if t == 'X' else t)
+        records.append((types[2], tuple(outer), outer.count('X')))
+    impropers = {}
+    for res, atoms in residue_atoms.items():
+        neighbors = [[] for _ in atoms]
+        for i, j in residue_bonds.get(res, []):
+            neighbors[i - 1].append(j - 1)
+            neighbors[j - 1].append(i - 1)
+        res_impropers = []
+        for center in range(len(atoms)):
+            if len(neighbors[center]) < 3:
+                continue
+            for triple in combinations(neighbors[center], 3):
+                # LEaP sorts the outer atoms by atom type before the parameter search
+                query = sorted(triple, key=lambda n: atoms[n][1])
+                best, assignment = None, None
+                for rec_center, rec_outer, rec_wild in records:
+                    if rec_center != atoms[center][1] or (best is not None
+                                                          and rec_wild >= best[2]):
+                        continue
+                    # the specific record types must occur in the sorted query in order
+                    rest, specific = list(query), {}
+                    for pos, t in enumerate(rec_outer):
+                        if t == 'X':
+                            continue
+                        for k, n in enumerate(rest):
+                            if atoms[n][1] == t:
+                                specific[pos] = rest.pop(k)
+                                break
+                        else:
+                            break
+                    else:
+                        best, assignment = (rec_center, rec_outer, rec_wild), (specific, rest)
+                if best is None:
+                    continue
+                specific, wild_atoms = assignment
+                # canonical order: wildcard positions (residue atom order), then the
+                # specific record positions in their order
+                outer_names = [atoms[n][0] for n in sorted(wild_atoms)] + \
+                              [atoms[specific[p]][0] for p in sorted(specific)]
+                res_impropers.append((outer_names[0], outer_names[1],
+                                      atoms[center][0], outer_names[2]))
+        if res_impropers:
+            impropers[res] = res_impropers
+    return impropers
+
+
 def write_rtp(atoms: dict, bonds: dict, connector: dict, outfile: str = "new.rtp", ff='amber',
-              impropers: Optional[dict] = None, cmap: Optional[dict] = None):
+              impropers: Optional[dict] = None, cmap: Optional[dict] = None,
+              backbone_impropers: bool = False):
     """
     Writes an .rtp file given all per-residue dictionary with topology, extra dihedrals/impropers, CMAP etc.
     :param atoms: dict of tuple, atom names/types and their ID/charge
@@ -416,7 +567,10 @@ def write_rtp(atoms: dict, bonds: dict, connector: dict, outfile: str = "new.rtp
     """
     if ff.lower() not in ['amber', 'charmm']:
         raise RuntimeError("Only Amber and CHARMM are currently supported")
-    btypes = '11941310' if ff == 'amber' else '15921310'
+    # column 9 (replace residue names with residue types) is required for Amber force
+    # fields, otherwise pdb2gmx keeps the PDB residue names and the atomtype-residuetype
+    # patterns of the [ cmaptypes ] entries cannot be matched
+    btypes = '119413101' if ff == 'amber' else '15921310'
     print(f"Setting [ bondedtypes ] in {outfile} file for the {ff}-type force field, please make sure this is right")
     with open(outfile, 'w') as out:
         out.write(f"[ bondedtypes ]\n{' '.join(btypes)}\n\n")
@@ -435,11 +589,20 @@ def write_rtp(atoms: dict, bonds: dict, connector: dict, outfile: str = "new.rtp
                     out.write(f"  -C  {atoms[res][connector[res][0] - 1][0]}\n")
                 elif is_na:
                     out.write(f"  -O3'  {atoms[res][connector[res][0] - 1][0]}\n")
-            if impropers is not None:
-                if res in impropers.keys():
-                    out.write(f" [ impropers ]\n")
-                    for imp in impropers[res]:
-                        out.write(f" {imp[0]:5s} {imp[1]:5s} {imp[2]:5s} {imp[3]:5s}\n")
+            extra_impr = []
+            if backbone_impropers:
+                # the peptide backbone impropers of the shipped Amber fields are
+                # written for every polymerized residue with the link atoms, so
+                # that residues linked through the rtp backbone markers obtain
+                # the same terms as the standard amino acids
+                names = {at[0] for at in atoms[res]}
+                if {'N', 'CA', 'C', 'O', 'H'} <= names:
+                    extra_impr = [('-C', 'CA', 'N', 'H'), ('CA', '+N', 'C', 'O')]
+            nimp = (impropers.get(res) if impropers is not None else None) or []
+            if nimp or extra_impr:
+                out.write(f" [ impropers ]\n")
+                for imp in list(nimp) + extra_impr:
+                    out.write(f" {imp[0]:5s} {imp[1]:5s} {imp[2]:5s} {imp[3]:5s}\n")
             if cmap is not None:
                 if res in cmap.keys():
                     out.write(f" [ cmap ]\n")
@@ -448,6 +611,459 @@ def write_rtp(atoms: dict, bonds: dict, connector: dict, outfile: str = "new.rtp
             out.write("\n\n")
 
 
+def _hdb_common_prefix(names: list) -> Optional[str]:
+    """
+    Derives the hdb name prefix from the actual hydrogen names in the .rtp entry.
+    For more than one hydrogen the hydrogen database requires the common stem of
+    names of the form <stem><digits> (e.g. HB for HB1/HB2), since pdb2gmx's
+    genhydro looks up <stem><number> atoms in the rtp entry.
+    :param names: list of str, hydrogen atom names bonded to the same heavy atom
+    :return: str or None, the prefix, or None when the names do not follow the convention
+    """
+    if len(names) == 1:
+        return names[0]
+    prefix = os.path.commonprefix(names)
+    if not prefix:
+        return None
+    if any(not name[len(prefix):].isdigit() for name in names):
+        return None
+    return prefix
+
+
+def _hdb_control_atom(node: str, candidates: list, forward: dict, reverse: dict) -> Optional[str]:
+    """
+    Selects a control atom for a hydrogen database entry from the given candidates.
+    A candidate starting with the same letter as the node and carrying a number is
+    preferred (so C5 is chosen as a reference for C6), otherwise the candidate with
+    the largest number of links is used.
+    :param node: str, atom name the hydrogen atoms are attached to
+    :param candidates: list of str, possible control atoms
+    :param forward: dict, atom name to names of heavy atoms bonded in forward direction
+    :param reverse: dict, atom name to names of heavy atoms bonded in reverse direction
+    :return: str or None, the selected control atom
+    """
+    if re.search(r".\d", node):
+        for candidate in candidates:
+            if re.search(r".\d", candidate) and candidate[0] == node[0]:
+                return candidate
+    best, count = None, 0
+    for candidate in candidates:
+        links = len(forward.get(candidate, [])) + len(reverse.get(candidate, []))
+        if links > count:
+            best, count = candidate, links
+    return best
+
+
+def _hdb_descent(j: str, node: str, forward: dict, reverse: dict) -> list:
+    """
+    Candidates for a second control atom from the neighbours of the first control
+    atom j, excluding j itself and the atom the hydrogens are attached to (the
+    latter would otherwise make the control atoms coincide).
+    :param j: str, the first control atom
+    :param node: str, atom the hydrogen atoms are attached to
+    :param forward: dict, atom name to names of heavy atoms bonded in forward direction
+    :param reverse: dict, atom name to names of heavy atoms bonded in reverse direction
+    :return: list of str, candidate control atom names
+    """
+    return [x for x in forward.get(j, []) + reverse.get(j, []) if x not in (j, node)]
+
+
+def _hdb_controls(node: str, forward: dict, reverse: dict) -> (Optional[str], Optional[str]):
+    """
+    Determines the two primary control atoms (j and k) for a hydrogen database entry,
+    following the bond graph around the atom the hydrogens are attached to; when the
+    atom has a single heavy neighbour, the neighbour's own neighbours are used (e.g.
+    for a hydroxyl group).
+    :param node: str, atom name the hydrogen atoms are attached to
+    :param forward: dict, atom name to names of heavy atoms bonded in forward direction
+    :param reverse: dict, atom name to names of heavy atoms bonded in reverse direction
+    :return: tuple, the two control atom names (either may be None)
+    """
+    fh = forward.get(node, [])
+    rb = reverse.get(node, [])
+    if fh and rb:
+        return _hdb_control_atom(node, fh, forward, reverse), _hdb_control_atom(node, rb, forward, reverse)
+    if fh:
+        j = _hdb_control_atom(node, fh, forward, reverse)
+        rest = [x for x in fh if x != j]
+        if rest:
+            return j, _hdb_control_atom(node, rest, forward, reverse)
+        return j, _hdb_control_atom(j, _hdb_descent(j, node, forward, reverse), forward, reverse)
+    if rb:
+        j = _hdb_control_atom(node, rb, forward, reverse)
+        rest = [x for x in rb if x != j]
+        if rest:
+            return j, _hdb_control_atom(node, rest, forward, reverse)
+        return j, _hdb_control_atom(j, _hdb_descent(j, node, forward, reverse), forward, reverse)
+    return None, None
+
+
+def _hdb_ring_planar(node: str, heavy_neighbours: dict, hydrogen_counts: dict) -> bool:
+    """
+    Recognises an sp2 carbon from conjugation: it is used when a carbon carrying a
+    single hydrogen has two heavy neighbours and no improper term to tell sp2 (ring)
+    CH groups, as in force fields whose residue topologies carry no impropers (they
+    keep planarity through dihedrals instead). A node is considered sp2 when it lies
+    in a 5- or 6-membered ring in which most atoms have fewer connections than their
+    normal valence (aromatic rings; a saturated pyranose-type ring does not qualify).
+    :param node: str, atom to test
+    :param heavy_neighbours: dict, atom name to names of bonded heavy atoms
+    :param hydrogen_counts: dict, atom name to number of bonded hydrogens
+    :return: bool, whether the node is part of a conjugated ring
+    """
+    valences = {'C': 4, 'N': 3, 'O': 2, 'S': 2}
+    ring_neighbours = {a: [x for x in xs if x[0] not in ('-', '+')]
+                       for a, xs in heavy_neighbours.items()}
+
+    def unsaturated(atom: str) -> bool:
+        return hydrogen_counts.get(atom, 0) + len(ring_neighbours.get(atom, [])) \
+            < valences.get(atom[0], 4)
+
+    for size in (5, 6):
+        stack = [(start, (node, start)) for start in ring_neighbours.get(node, [])]
+        while stack:
+            current, path = stack.pop()
+            if len(path) == size:
+                if node in ring_neighbours.get(current, []) \
+                        and 2 * sum(unsaturated(a) for a in path) > size:
+                    return True
+                continue
+            for nxt in ring_neighbours.get(current, []):
+                if nxt != node and nxt not in path:
+                    stack.append((nxt, path + (nxt,)))
+    return False
+
+
+def _hdb_hydrogen_type(element: str, n_hydrogens: int, n_links: int,
+                       planar: bool = False) -> Optional[int]:
+    """
+    Maps the local environment of a hydrogen-carrying atom onto one of the hydrogen
+    addition methods of the Gromacs hydrogen database (types 1-6 as documented in
+    the pdb2gmx manual). Combinations that cannot be constructed with the available
+    methods return None.
+    :param element: str, element symbol of the atom carrying the hydrogens
+    :param n_hydrogens: int, number of hydrogen atoms attached to it
+    :param n_links: int, number of heavy atoms bonded to it
+    :param planar: bool, whether the atom carries an improper term (sp2 centre)
+    :return: int or None, the hdb addition type
+    """
+    if element in ('O', 'S'):
+        # a sulfhydryl hydrogen is constructed like a hydroxyl one, as in the shipped
+        # amino acid hydrogen databases (CYS: "1 2 HG SG CB CA")
+        return 2 if n_hydrogens == 1 else None
+    if element == 'N':
+        if n_hydrogens == 1:
+            return 1
+        if n_links == 1:
+            if n_hydrogens == 2:
+                return 3
+            if n_hydrogens == 3:
+                return 4
+        return None
+    if element == 'C':
+        if n_hydrogens == 1:
+            # three heavy neighbours give the tetrahedral construction; with two, an
+            # sp2 centre (marked by an improper term, e.g. aromatic and olefinic CH)
+            # uses the planar construction as the shipped databases do, whereas a
+            # carbon with an open valence is constructed like a hydroxyl hydrogen; a
+            # single neighbour uses that single-hydrogen approximation as well, which
+            # the Gromacs documentation recommends for other uncovered cases
+            if n_links == 2:
+                return 1 if planar else 2
+            return {3: 5, 1: 2}.get(n_links)
+        if n_hydrogens == 2:
+            return 3 if n_links == 1 else 6 if n_links == 2 else None
+        if n_hydrogens == 3 and n_links == 1:
+            return 4
+        return None
+    return None
+
+
+def rtp_to_hdb(atoms: dict, bonds: dict, impropers: Optional[dict] = None) -> dict:
+    """
+    Generates hydrogen database (hdb) data from the .rtp residue data. The hydrogen
+    atoms present in the [ atoms ] blocks determine how they have to be re-created in
+    structures that lack them: for every heavy atom carrying hydrogens an entry lists
+    their number, the construction method, the name prefix taken from the actual rtp
+    names, the atom itself and the control atoms that anchor the construction. Groups
+    that cannot be represented (unsupported environment, hydrogen on a connection
+    atom, hydrogen names not following the <prefix><number> convention) are skipped
+    with a warning.
+    :param atoms: dict of tuple, atom names/types and charges, same format as for write_rtp
+    :param bonds: dict of tuples, 1-based indices of pairs defining bonds, same format as for write_rtp
+    :param impropers: dict of tuples with atom names involved in impropers, used to
+        recognise sp2 centres, for which single hydrogens are built planar (optional)
+    :return: dict, residue names to lists of tuples (number of H, type, prefix, atom, j, k[, l])
+    """
+    hdb = {}
+    for res in atoms:
+        names = [at[0] for at in atoms[res]]
+        planar_atoms = set()
+        if impropers is not None and res in impropers:
+            for imp in impropers[res]:
+                planar_atoms.update(imp)
+        hydrogen_counts = {}
+        forward, reverse, hydrogens = {}, {}, {}
+        for pair in bonds.get(res, []):
+            first, second = names[pair[0] - 1], names[pair[1] - 1]
+            if first.startswith('H') and not second.startswith('H'):
+                hydrogens.setdefault(second, []).append(first)
+            elif second.startswith('H') and not first.startswith('H'):
+                hydrogens.setdefault(first, []).append(second)
+            elif not (first.startswith('H') or second.startswith('H')):
+                forward.setdefault(first, []).append(second)
+                reverse.setdefault(second, []).append(first)
+        for heavy in set(list(forward) + list(reverse)):
+            hydrogen_counts[heavy] = 0
+        for heavy, h_names in hydrogens.items():
+            hydrogen_counts[heavy] = len(h_names)
+        forward_keys = set(list(forward) + list(reverse))
+        entries = []
+        for node, h_names in hydrogens.items():
+            if '-' in node or '+' in node:
+                print(f"WARNING: no hydrogen database entries generated for residue {res}, hydrogen "
+                      f"attached to the connection atom {node}")
+                break
+            prefix = _hdb_common_prefix(h_names)
+            if prefix is None:
+                print(f"WARNING: skipping the hydrogen group on {node} in residue {res}, the names "
+                      f"{h_names} do not follow the <prefix><number> convention of the hydrogen database")
+                continue
+            neighbors = list(dict.fromkeys(forward.get(node, []) + reverse.get(node, [])))
+            planar = node in planar_atoms
+            if not planar and node[0] == 'C' and len(h_names) == 1 and len(neighbors) == 2:
+                heavy_neighbours = {a: list(dict.fromkeys(forward.get(a, []) + reverse.get(a, [])))
+                                    for a in forward_keys}
+                planar = _hdb_ring_planar(node, heavy_neighbours, hydrogen_counts)
+            h_type = _hdb_hydrogen_type(node[0], len(h_names), len(neighbors), planar)
+            if h_type is None:
+                print(f"WARNING: cannot construct a hydrogen database entry for {len(h_names)} hydrogen(s) "
+                      f"on {node} with {len(neighbors)} heavy neighbour(s) in residue {res}; the combination "
+                      "is not supported by the hydrogen database")
+                continue
+            j, k = _hdb_controls(node, forward, reverse)
+            l = None
+            if h_type == 5:
+                remaining = [n for n in neighbors if n not in (j, k)]
+                if remaining:
+                    l = remaining[0]
+            control_atoms = [node, j, k] + ([l] if l is not None else [])
+            if any(c is None for c in control_atoms) or len(set(control_atoms)) != len(control_atoms):
+                print(f"WARNING: not enough distinct control atoms for the hydrogen group on {node} "
+                      f"in residue {res}; skipping")
+                continue
+            entries.append((len(h_names), h_type, prefix, node, j, k) + ((l,) if l is not None else ()))
+        if entries:
+            hdb[res] = entries
+    return hdb
+
+
+
+def rename_hydrogens(atoms: dict, bonds: dict, impropers: Optional[dict] = None):
+    """
+    Renames hydrogen atoms whose names cannot be produced by the Gromacs hydrogen
+    database. For groups of more than one hydrogen on the same heavy atom, pdb2gmx
+    constructs names as <prefix><number>, so names carrying letter suffixes (such as
+    the GLYCAM H5E/H5A or H1M/H2M/H3M) make such groups impossible to rebuild. The
+    affected groups are renamed to H<heavy><number>, where <heavy> is the name of the
+    attached heavy atom without its leading C (C5 -> H51/H52, CME -> HME1/HME2/HME3);
+    the .rtp atom names and the improper definitions are adjusted in place accordingly,
+    and the mapping of the original names is returned so that it can be written as .arn
+    renaming data for structures that still use them. Groups that already follow the
+    convention and single hydrogens are left untouched; groups whose new names clash
+    with other atoms of the residue are skipped with a warning.
+    :param atoms: dict of tuple, atom names/types and charges, same format as for write_rtp;
+        the entries of the residues that need it are replaced in place
+    :param bonds: dict of tuples, 1-based indices of pairs defining bonds, same format as for write_rtp
+    :param impropers: dict of tuples with atom names involved in impropers, adjusted in place (optional)
+    :return: tuple (atoms, impropers, renames), renames maps residue names to dicts
+        {original_name: new_name}
+    """
+    renames = {}
+    for res in atoms:
+        entries = atoms[res]
+        names = [at[0] for at in entries]
+        hydrogens = {}
+        for pair in bonds.get(res, []):
+            first, second = names[pair[0] - 1], names[pair[1] - 1]
+            if first.startswith('H') and not second.startswith('H'):
+                hydrogens.setdefault(second, []).append(first)
+            elif second.startswith('H') and not first.startswith('H'):
+                hydrogens.setdefault(first, []).append(second)
+        rename_map = {}
+        for node, h_names in hydrogens.items():
+            if len(h_names) < 2 or _hdb_common_prefix(h_names) is not None:
+                continue
+            base = 'H' + (node[1:] if node[0] == 'C' else node)
+            new_names = [f"{base}{k + 1}" for k in range(len(h_names))]
+            if any(new_name in names and new_name not in h_names for new_name in new_names):
+                print(f"WARNING: cannot rename the hydrogens {h_names} on {node} in residue {res} "
+                      f"to {new_names}: name conflict within the residue; these hydrogens cannot be "
+                      "reconstructed from the hydrogen database")
+                continue
+            for old_name, new_name in zip(h_names, new_names):
+                rename_map[old_name] = new_name
+        if not rename_map:
+            continue
+        atoms[res] = [(rename_map.get(at[0], at[0]), *at[1:]) for at in entries]
+        if impropers is not None and res in impropers:
+            impropers[res] = [tuple(rename_map.get(name, name) for name in imp) for imp in impropers[res]]
+        renames[res] = rename_map
+    return atoms, impropers, renames
+
+
+# Legacy Gromacs/PDB input atom names that pdb2gmx has to map onto the Amber names kept
+# in the converted .rtp entries, mirroring the .arn files of the shipped Amber force fields
+legacy_input_renames = {
+    'ILE': {'CD': 'CD1', 'HD1': 'HD11', 'HD2': 'HD12', 'HD3': 'HD13'},
+    'CILE': {'CD': 'CD1', 'HD1': 'HD11', 'HD2': 'HD12', 'HD3': 'HD13'},
+    'NILE': {'CD': 'CD1', 'HD1': 'HD11', 'HD2': 'HD12', 'HD3': 'HD13'},
+    'LYN': {'HZ1': 'HZ3'},
+    'NPRO': {'H1': 'H3'},
+}
+
+# legacy PDB input atom names that pdb2gmx maps onto the Gromacs names used in the
+# generated nucleic acid .rtp entries; like the shipped Amber force fields, these are
+# keyed by the residue type so that they apply to every nucleotide of the polymer
+legacy_nucleic_input_renames = {
+    'RNA': {'OP1': 'O1P', 'OP2': 'O2P', "H2'": "H2'1", "H2''": "H2'2",
+            "H5'": "H5'1", "H5''": "H5'2", "HO5'": 'H5T', "HO3'": 'H3T'},
+    'DNA': {'OP1': 'O1P', 'OP2': 'O2P', "H2'": "H2'1", "H2''": "H2'2",
+            "H5'": "H5'1", "H5''": "H5'2", "HO5'": 'H5T', "HO3'": 'H3T'},
+}
+
+
+def write_arn(renames: dict, outfile: str, append: bool = False) -> bool:
+    """
+    Writes atom renaming (.arn) data so that input structures that still use the
+    original hydrogen names are translated by pdb2gmx to their new names in the
+    generated .rtp entries (pdb2gmx expects residue, original, new columns).
+    Pairs that are already present in an appended file are skipped.
+    :param renames: dict, residue names to {original_name: new_name} as returned by rename_hydrogens
+    :param outfile: str, file to write to
+    :param append: bool, append to an existing file without repeating its header
+    :return: bool, whether anything was written (False for empty renames, file not created)
+    """
+    known = set()
+    if append and os.path.exists(outfile):
+        with open(outfile) as infile:
+            for line in infile:
+                fields = line.split()
+                if len(fields) == 3 and not fields[0].startswith(';'):
+                    known.add((fields[0], fields[1]))
+    renames = {res: {o: n for o, n in pairs.items() if (res, o) not in known}
+               for res, pairs in renames.items()}
+    renames = {res: pairs for res, pairs in renames.items() if pairs}
+    if not renames:
+        return False
+    add_header = not (append and os.path.exists(outfile))
+    with open(outfile, 'a' if not add_header else 'w') as out:
+        if add_header:
+            out.write("; renaming of hydrogen atoms adjusted by gromologist for the hydrogen database\n")
+            out.write("; residue   original   gromacs\n")
+        for res in sorted(renames):
+            for old_name, new_name in sorted(renames[res].items()):
+                out.write(f"{res:8s} {old_name:9s} {new_name}\n")
+    return True
+
+
+def write_r2b(residue_names, block_type: str, outfile: str) -> bool:
+    """
+    Generates a residue to building block (.r2b) table from the converted residue names.
+    Amber force fields express termini as explicit building blocks whose names match the
+    Gromacs convention (NALA/CALA, DA5/DA3/DAN, R5A/R3A), so the table can be derived from
+    the set of residues present in the converted force field; pdb2gmx uses it to map
+    standard residue names (and the one-letter PDB nucleobase names) onto these blocks,
+    including the terminal forms.
+    :param residue_names: iterable of str, residue names of the converted force field
+    :param block_type: str, one of 'protein', 'DNA' or 'RNA'
+    :param outfile: str, file to write to
+    :return: bool, whether anything was written (False when no mapping row applies)
+    """
+    names = set(residue_names)
+    rows = []
+    if block_type == 'protein':
+        for res in sorted(names.intersection(gml.Pdb.prot_map.keys())):
+            n_ter = 'N' + res if 'N' + res in names else '-'
+            c_ter = 'C' + res if 'C' + res in names else '-'
+            if n_ter == '-' and c_ter == '-':
+                continue
+            rows.append((res, res, n_ter, c_ter, '-'))
+        # pdb2gmx emits the legacy Gromacs names for the automated histidine
+        # protonation (HISD/HISE/HISH), the disulfide-cystine pair (CYS2) and
+        # the deprotonated lysine (LYSN); map them onto the Amber names
+        for alias, target in (('HISD', 'HID'), ('HISE', 'HIE'), ('HISH', 'HIP'),
+                              ('CYS2', 'CYX'), ('LYSN', 'LYN')):
+            if target in names:
+                rows.append((alias, target,
+                             'N' + target if 'N' + target in names else '-',
+                             'C' + target if 'C' + target in names else '-',
+                             '-'))
+    elif block_type == 'DNA':
+        for base in 'ACGU':
+            main = 'D' + base
+            if main in names:
+                rows.append((main, main) +
+                            tuple(f'{main}{s}' if f'{main}{s}' in names else '-' for s in '53N'))
+    elif block_type == 'RNA':
+        for base in 'ACGU':
+            main = 'R' + base
+            if main in names:
+                # pdb2gmx matches nucleic acids by the one-letter PDB residue names,
+                # like the shipped rna.r2b tables do
+                rows.append((base, main) +
+                            tuple(c if c in names else '-'
+                                  for c in (f'R{base}5', f'R{base}3', f'R{base}N')))
+    else:
+        raise ValueError(f"unsupported building block type {block_type}")
+    if not rows:
+        return False
+    with open(outfile, 'w') as out:
+        out.write("; residue to building block table generated by gromologist from the\n"
+                  "; converted residue topologies\n"
+                  ";       main  N-ter C-ter 2-ter\n")
+        for row in rows:
+            out.write('\t'.join(row) + '\n')
+    return True
+
+
+def _hdb_residue_names(path: str) -> set:
+    """
+    Collects the residue names present in a hydrogen database file.
+    :param path: str, path of the .hdb file
+    :return: set of str, residue names
+    """
+    names = set()
+    with open(path) as infile:
+        for line in infile:
+            fields = line.split(';')[0].split()
+            if len(fields) == 2 and fields[1].isdigit():
+                names.add(fields[0])
+    return names
+
+
+def write_hdb(entries: dict, outfile: str, append: bool = False) -> bool:
+    """
+    Writes the data returned by rtp_to_hdb in the Gromacs hydrogen database format.
+    :param entries: dict, residue names to lists of entry tuples as returned by rtp_to_hdb
+    :param outfile: str, file to write to
+    :param append: bool, append to an existing file
+    :return: bool, whether anything was written (False for empty entries, file not created)
+
+    The Gromacs hdb reader does not support comments: every non-blank line is
+    parsed as a residue entry, so no header comment may be written.
+    """
+    if not entries:
+        return False
+    with open(outfile, 'a' if append and os.path.exists(outfile) else 'w') as out:
+        for res in entries:
+            out.write(f"{res}\t{len(entries[res])}\n")
+            for entry in entries[res]:
+                out.write("\t".join(str(field) for field in entry) + "\n")
+    return True
+
+
+
 def dict_filter(indict: dict, restype: str) -> dict:
     """
     Filters dictionaries based on whether they belong to DNA, RNA or protein
@@ -464,43 +1080,34 @@ def dict_filter(indict: dict, restype: str) -> dict:
         return {k: v for k, v in indict.items() if k not in nucres}
 
 
-def fix_rtp(rtp_dict: dict, impr: bool = False, rna: bool = False) -> dict:
+def fix_rtp(rtp_dict: dict, impr: bool = False, rna: bool = False,
+            renames_out: Optional[dict] = None) -> dict:
     """
     Makes Gromacs-specific changes in .rtp data, e.g. adjusts atom names, terminal atom naming,
     hydrogen numbering, RNA residue names, improper type order etc.
     :param rtp_dict: dict, dictionary with .rtp data (atoms or impropers)
     :param impr: bool, whether the entry contains improper dihedral data
     :param rna: bool, whether the entry represents RNA residues
+    :param renames_out: dict, optional output collecting residue names to {old_name: new_name}
+        maps of the applied atom renames, suitable for writing an .arn file
     :return: dict, the dictionary with necessary modifications
     """
+
+    def record_rename(res: str, old_name: str, new_name: str):
+        if renames_out is not None and old_name != new_name:
+            renames_out.setdefault(res, {})[old_name] = new_name
+
+    rna_atom_names = {"OP1": 'O1P', "OP2": 'O2P', "H5''": "H5'2", "H5'": "H5'1",
+                      "H2'": "H2'1", "HO2'": "HO'2", "HO3'": 'H3T', "HO5'": 'H5T'}
     to_copy = {}
     for res in rtp_dict.keys():
         if not rna:
-            if "ILE" in res:
-                for n, ent in enumerate(rtp_dict[res]):
-                    if ent[0] == "CD1":
-                        rtp_dict[res][n] = ('CD', *ent[1:])
-                    elif ent[0].startswith("HD1"):
-                        rtp_dict[res][n] = (ent[0].replace("HD1", "HD"), *ent[1:])
-            if res.startswith("C") and res[1:] in gml.Pdb.prot_map.keys():
-                if not impr:
-                    for n, ent in enumerate(rtp_dict[res]):
-                        if ent[0] == "O":
-                            rtp_dict[res][n] = ('OC1', *ent[1:])
-                        elif ent[0] == "OXT":
-                            rtp_dict[res][n] = ('OC2', *ent[1:])
-                else:
-                    for n, ent in enumerate(rtp_dict[res]):
-                        for m, atname in enumerate(ent):
-                            if atname == "O":
-                                rtp_dict[res][n][m] = 'OC2'
-                            elif atname == "OXT":
-                                rtp_dict[res][n][m] = 'OC1'
             for mid in ["A", "B", "G", "D", "E", "G1"]:
                 if f"H{mid}3" in [e[0] for e in rtp_dict[res]] and f"H{mid}1" not in [e[0] for e in rtp_dict[res]]:
                     for n, ent in enumerate(rtp_dict[res]):
                         if ent[0] == f"H{mid}3":
                             rtp_dict[res][n] = (f'H{mid}1', *ent[1:])
+                            record_rename(res, f"H{mid}3", f'H{mid}1')
             if impr:
                 for n, ent in enumerate(rtp_dict[res]):
                     for m, atname in enumerate(ent):
@@ -510,31 +1117,28 @@ def fix_rtp(rtp_dict: dict, impr: bool = False, rna: bool = False) -> dict:
                             rtp_dict[res][n][m] = '+N'
         if rna:
             for res in rtp_dict.keys():
-                if res[0] in 'CAGU':
+                # only the standard bases map onto the R-prefixed building blocks
+                # known to pdb2gmx (RA/RC/RG/RU and their terminal variants);
+                # modified residues keep their own names
+                if re.fullmatch(r"[ACGU][35N]?", res):
                     to_copy[res] = 'R' + res
                 if impr:
+                    # improper entries are tuples of atom names; the renames
+                    # apply to every position
+                    for n, imp in enumerate(rtp_dict[res]):
+                        new_imp = tuple(rna_atom_names.get(name, name) for name in imp)
+                        if new_imp != imp:
+                            rtp_dict[res][n] = new_imp
                     continue
                 for n, ent in enumerate(rtp_dict[res]):
                     try:
                         _ = ent[0]
                     except TypeError:
                         continue
-                    if ent[0] == "OP1":
-                        rtp_dict[res][n] = ('O1P', *ent[1:])
-                    elif ent[0] == "OP2":
-                        rtp_dict[res][n] = ('O2P', *ent[1:])
-                    elif ent[0] == "H5''":
-                        rtp_dict[res][n] = ("H5'2", *ent[1:])
-                    elif ent[0] == "H5'":
-                        rtp_dict[res][n] = ("H5'1", *ent[1:])
-                    elif ent[0] == "H2'":
-                        rtp_dict[res][n] = ("H2'1", *ent[1:])
-                    elif ent[0] == "HO2'":
-                        rtp_dict[res][n] = ("HO'2", *ent[1:])
-                    elif ent[0] == "HO3'":
-                        rtp_dict[res][n] = ("H3T", *ent[1:])
-                    elif ent[0] == "HO5'":
-                        rtp_dict[res][n] = ("H5T", *ent[1:])
+                    if ent[0] in rna_atom_names:
+                        rtp_dict[res][n] = (rna_atom_names[ent[0]], *ent[1:])
+                    if rtp_dict[res][n][0] != ent[0]:
+                        record_rename(res, ent[0], rtp_dict[res][n][0])
     for cop in to_copy.keys():
         rtp_dict[to_copy[cop]] = rtp_dict[cop]
     for clean in to_copy.keys():
@@ -542,8 +1146,27 @@ def fix_rtp(rtp_dict: dict, impr: bool = False, rna: bool = False) -> dict:
     return rtp_dict
 
 
+def replicate_building_blocks(rtp_dict: dict) -> dict:
+    """
+    Duplicates the standard nucleic entries of the dictionary under the
+    R-prefixed building block names known to pdb2gmx and drops the
+    originals, mirroring the residue-name handling of fix_rtp for entries
+    whose contents it must not rewrite (bond and connector data are 1-based
+    atom index pairs, not atom names).
+    :param rtp_dict: dict, dictionary keyed by residue name
+    :return: dict, the same dictionary with the copies applied
+    """
+
+    to_copy = {res: 'R' + res for res in rtp_dict if re.fullmatch(r"[ACGU][35N]?", res)}
+    for src, dst in to_copy.items():
+        rtp_dict[dst] = rtp_dict[src]
+    for src in to_copy.keys():
+        del rtp_dict[src]
+    return rtp_dict
+
+
 def find_leap_files(ambdir: str, filetype: str, leaprc: str, extras: Optional[list] = None):
-    content = [line.strip() for line in open(leaprc)]
+    content = [line.strip() for line in open(leaprc) if not line.strip().startswith('#')]
     extras = extras if extras is not None else []
     pref = os.path.sep if leaprc.startswith(os.path.sep) else ''
     reldir = pref + os.path.sep.join(leaprc.split(os.path.sep)[:-1]) + pref
@@ -553,8 +1176,11 @@ def find_leap_files(ambdir: str, filetype: str, leaprc: str, extras: Optional[li
     elif filetype == 'parm':
         files = [line.split()[-1] for line in content if
                  len(line.split()) >= 2 and "loadamberparams" in [w.lower() for w in line.split()]] + extras
+    elif filetype == 'prep':
+        files = [line.split()[-1] for line in content if
+                 len(line.split()) >= 2 and "loadamberprep" in [w.lower() for w in line.split()]] + extras
     else:
-        raise RuntimeError('select "parm" or "lib"')
+        raise RuntimeError('select "parm", "lib" or "prep"')
     files_in_ambdir = [ambdir + f'/{filetype}/' + f for f in files]
     files_in_reldir = [reldir + '/' + f for f in files]
     print(files_in_reldir)
@@ -562,15 +1188,66 @@ def find_leap_files(ambdir: str, filetype: str, leaprc: str, extras: Optional[li
     return found_files
 
 
+def find_leap_res_files(ambdir: str, leaprc: str, extras: Optional[list] = None):
+    """
+    Finds the residue definition files (.lib and .prep) referenced by a .leaprc file
+    in the order in which the leaprc loads them. LEaP lets the file loaded last
+    replace the units of the earlier ones, so the relative order of loadOff and
+    loadamberprep commands matters; extras are appended at the end according to
+    their extension.
+    :param leaprc: str, name of the .leaprc file
+    :param ambdir: str, Amber data directory
+    :param extras: list, optional additional .lib/.prep files
+    :return: list of tuples, (kind, path) with kind in {'lib', 'prep'}
+    """
+    content = [line.strip() for line in open(leaprc) if not line.strip().startswith('#')]
+    extras = extras if extras is not None else []
+    pref = os.path.sep if leaprc.startswith(os.path.sep) else ''
+    reldir = pref + os.path.sep.join(leaprc.split(os.path.sep)[:-1]) + pref
+
+    def resolve(filetype, fname):
+        for cand in (ambdir + f'/{filetype}/' + fname, reldir + '/' + fname):
+            if os.path.exists(cand):
+                return cand
+        return None
+
+    entries = []
+    for line in content:
+        words = [w.lower() for w in line.split()]
+        if len(line.split()) < 2:
+            continue
+        kind = 'lib' if 'loadoff' in words else ('prep' if 'loadamberprep' in words else None)
+        if kind is None:
+            continue
+        path = resolve(kind, line.split()[-1])
+        if path is not None:
+            entries.append((kind, path))
+    for extra in extras:
+        if extra.endswith('lib'):
+            entries.append(('lib', extra))
+        elif extra.endswith('in') or extra.endswith('prep'):
+            entries.append(('prep', extra))
+    return entries
+
+
 def amber2gmxFF(leaprc: str, outdir: str, amber_dir: Optional[str] = None, base_ff: Optional[str] = None,
                 extra_files: Optional[list] = None):
     """
     Reads a .leaprc file and all parameter dependencies from Amber to convert into a Gromacs .ff dir
-    Files that should be copied manually: watermodels.dat and tip*itp, .hdb, .tdb and .arn
+    The [ impropers ] blocks of the residue topologies are taken from the .prep files when
+    present and generated from the IMPROPER parameter records for the residues that come from
+    .lib files, reproducing the LEaP enumeration and atom ordering.
+    With base_ff given, accessory files of an already converted force field are copied into the
+    new directory and the hydrogen database is completed from the converted residue topologies the
+    way amber2ffa does. Without base_ff, the hydrogen databases and the .r2b building block tables
+    are generated from the converted data and only the termini databases (.tdb), the solvent models
+    (.itp, watermodels.dat) and specbond.dat still need to be added manually.
     :param leaprc: str, a file that sources dependencies from which the .ff will be created
     :param outdir: str, a new .ff directory that will contain the Gromacs-compatible files
     :param amber_dir: str, Abs path to the dir containing Amber prep, parm, lib directories if `leaprc` is a local file
-    :param base_ff: str, name of the source .ff directory that will be used for auxilliary files
+    :param base_ff: str, an already converted .ff directory (a name in the installed Gromacs data
+        directory or an absolute path) whose accessory files are copied; when None, nothing is
+        copied and the auxiliary data generated from the converted residues is used instead
     :param extra_files: list of str, additional files that should be included (e.g. frcmod.tip3p)
     :return: None
     """
@@ -588,6 +1265,7 @@ def amber2gmxFF(leaprc: str, outdir: str, amber_dir: Optional[str] = None, base_
     pro_atoms, pro_bonds, pro_connectors = {}, {}, {}
     dna_atoms, dna_bonds, dna_connectors = {}, {}, {}
     rna_atoms, rna_bonds, rna_connectors = {}, {}, {}
+    pro_renames, rna_renames = {}, {}
     impropers = {}
     prepsel = "/prep/all*.in"
     for prep in glob(amb + prepsel) + glob(amb + "/prep/nuc*.in") + extra_prep:
@@ -596,13 +1274,13 @@ def amber2gmxFF(leaprc: str, outdir: str, amber_dir: Optional[str] = None, base_
     for lib in libs:
         print(f"***** Adding residues from {lib} *****")
         a, b, c = gml.read_lib(lib)
-        pro_atoms.update(fix_rtp(dict_filter(a, 'protein')))
+        pro_atoms.update(fix_rtp(dict_filter(a, 'protein'), renames_out=pro_renames))
         pro_bonds.update(dict_filter(b, 'protein'))
         pro_connectors.update(dict_filter(c, 'protein'))
         dna_atoms.update(dict_filter(a, 'DNA'))
         dna_bonds.update(dict_filter(b, 'DNA'))
         dna_connectors.update(dict_filter(c, 'DNA'))
-        rna_atoms.update(fix_rtp(dict_filter(a, 'RNA'), rna=True))
+        rna_atoms.update(fix_rtp(dict_filter(a, 'RNA'), rna=True, renames_out=rna_renames))
         rna_bonds.update(fix_rtp(dict_filter(b, 'RNA'), rna=True))
         rna_connectors.update(fix_rtp(dict_filter(c, 'RNA'), rna=True))
     print('\n')
@@ -626,11 +1304,43 @@ def amber2gmxFF(leaprc: str, outdir: str, amber_dir: Optional[str] = None, base_
                     imp_types_all.add(imp_types)
     new_top = gml.Top(amber=True)
     cmaptypes, rtp_cmap = {}, {}
+    impr_records = {}
     print('\n')
     for dat in dats:
         print(f"***** Adding parameters from {dat} *****")
         cmaptypes.update(load_frcmod(new_top, dat, return_cmap=True, pro_atoms=pro_atoms))
+        for types in parse_frcmod(dat)[4]:
+            # the last file that defines a record wins, as when LEaP loads several frcmods
+            impr_records.pop(types, None)
+            impr_records[types] = None
+    # LEaP generates the improper torsions of a built unit from the IMPROPER
+    # records; residues taken from .lib files carry no explicit list, so it has
+    # to be recomputed here (the explicit lists from .prep files win)
+    for atoms_g, bonds_g, impr_g in ((pro_atoms, pro_bonds, pro_impropers),
+                                     (dna_atoms, dna_bonds, dna_impropers),
+                                     (rna_atoms, rna_bonds, rna_impropers)):
+        for res, quads in assign_impropers(atoms_g, bonds_g, list(impr_records)).items():
+            impr_g.setdefault(res, quads)
     print('\n')
+    # atom types referenced by bonded parameters but without Lennard-Jones parameters
+    # defined by any of the loaded files (e.g. CJ in parm19.dat) receive a zero
+    # Lennard-Jones placeholder, mirroring the Leap behaviour for types declared only
+    # in the addAtomTypes block; without it grompp rejects the field as referencing
+    # unknown atom types. The mass and the atomic number are filled in below from the
+    # element mapping of the addAtomTypes block
+    defined_types = {entry.types[0] for entry in new_top.parameters.atomtypes.entries_param}
+    referenced_types = set()
+    for subs in new_top.parameters.subsections:
+        if subs.header in ('bondtypes', 'angletypes', 'dihedraltypes'):
+            for entry in subs.entries_param:
+                referenced_types.update(entry.types)
+    for atype_name in sorted(referenced_types - defined_types):
+        if atype_name == 'X' or '*' in atype_name:
+            continue  # wildcards are resolved by grompp itself
+        print(f"WARNING: atom type {atype_name} is referenced by the bonded parameters but has no "
+              "Lennard-Jones parameters defined by the source files; a zero Lennard-Jones entry "
+              "is written for it, supply the defining frcmod file if the type is used by any residue")
+        new_top.parameters.add_atomtype(atype_name, 0, 0.0, 0.0, action_default='t')
     for k in cmaptypes.keys():
         rtp_cmap[k[1]] = [f'-C N CA C +N'.split()]
     new_top = reorder_amber_impropers(new_top, imp_types_all)
@@ -659,28 +1369,709 @@ def amber2gmxFF(leaprc: str, outdir: str, amber_dir: Optional[str] = None, base_
     if rna_atoms:
         gml.write_rtp(rna_atoms, rna_bonds, rna_connectors, 'rna.rtp', impropers=rna_impropers)
     gmx_dir = new_top.gromacs_dir
-    if not gmx_dir:
-        print("Gromacs directory not found. Please move the additional files (.hdb, solvent .itp etc.) manually")
-    else:
-        if base_ff is None:
-            base_ff = gmx_dir + '/amber99.ff'
-        else:
-            if not base_ff.startswith('/'):
+    copied_base = None
+    if base_ff is not None:
+        if not base_ff.startswith('/'):
+            if not gmx_dir:
+                print(f"WARNING: Gromacs data directory not found, cannot resolve the base force "
+                      f"field '{base_ff}'; no accessory files will be copied")
+            else:
                 base_ff = gmx_dir + f'/{base_ff}'
-        wildcards_to_copy = ['tip*', 'spc*', '*r2b', '*tdb', '*arn', '*hdb']
-        files_to_copy = []
-        for wildcard in wildcards_to_copy:
-            files_to_copy.extend(glob(f'{base_ff}/{wildcard}'))
-        print(f"Copying accessory files (.hdb, .atp, solvent .itp etc.) from {base_ff}\n")
-        for file_to_copy in files_to_copy:
-            copy2(file_to_copy, '.')
+        if os.path.isdir(base_ff):
+            copied_base = base_ff
+            wildcards_to_copy = ['tip*', 'spc*', '*r2b', '*tdb', '*arn', '*hdb']
+            files_to_copy = []
+            for wildcard in wildcards_to_copy:
+                files_to_copy.extend(glob(f'{base_ff}/{wildcard}'))
+            print(f"Copying accessory files (.hdb, .atp, solvent .itp etc.) from {base_ff}\n")
+            for file_to_copy in files_to_copy:
+                copy2(file_to_copy, '.')
+    if copied_base is None:
+        print("No base force field used: the hydrogen databases and .r2b building block tables are "
+              "generated from the converted residues; termini databases (.tdb), solvent models "
+              "(.itp, watermodels.dat) and specbond.dat must be added manually")
+    for hdb_atoms, hdb_bonds, hdb_impropers, hdb_name in ((pro_atoms, pro_bonds, pro_impropers, 'aminoacids'),
+                                                           (dna_atoms, dna_bonds, dna_impropers, 'dna'),
+                                                           (rna_atoms, rna_bonds, rna_impropers, 'rna')):
+        if not hdb_atoms:
+            continue
+        hdb_entries = rtp_to_hdb(hdb_atoms, hdb_bonds, hdb_impropers if hdb_impropers else None)
+        if os.path.exists(hdb_name + '.hdb'):
+            known = _hdb_residue_names(hdb_name + '.hdb')
+            hdb_entries = {r: e for r, e in hdb_entries.items() if r not in known}
+        if write_hdb(hdb_entries, hdb_name + '.hdb', append=True):
+            print(f"Generated hydrogen database entries for {len(hdb_entries)} residue(s) in {hdb_name}.hdb")
+    for res, pairs in legacy_input_renames.items():
+        if res in pro_atoms:
+            pro_renames.setdefault(res, {}).update(pairs)
+    for renames, arn_name in ((pro_renames, 'aminoacids'), (rna_renames, 'rna')):
+        if write_arn(renames, arn_name + '.arn', append=True):
+            print(f"Generated atom renaming data in {arn_name}.arn")
+    for residue_set, block_type, r2b_name in ((pro_atoms.keys(), 'protein', 'aminoacids'),
+                                              (dna_atoms.keys(), 'DNA', 'dna'),
+                                              (rna_atoms.keys(), 'RNA', 'rna')):
+        if residue_set and not os.path.exists(r2b_name + '.r2b'):
+            if write_r2b(residue_set, block_type, r2b_name + '.r2b'):
+                print(f"Generated building block table in {r2b_name}.r2b")
     with open('atomtypes.atp', 'w') as outfile:
+        outfile.write("; name               mass\n")
         for atype in new_top.parameters.atomtypes.entries_param:
             outfile.write(f"{atype.types[0]:12s} {float(atype.modifiers[1]):12.5f}\n")
     new_top.find_undefined_types()
     # TODO set up watermodels.dat
 
 
+def base_residue_names(ffdir: Optional[str]) -> set:
+    """
+    Collects the residue names already known to a base force field, i.e. defined by its
+    own .rtp files or listed in the residuetypes.dat of the force field directory. The
+    global (library-level) residuetypes.dat is deliberately not consulted: it lists all
+    recognized residue names, including ones without any topology, and must not prevent
+    an addon from defining them
+    :param ffdir: str, path of the force field directory
+    :return: set of str, residue names
+    """
+    names = set()
+    if ffdir is None:
+        return names
+    sections = {'bondedtypes', 'atoms', 'bonds', 'impropers', 'cmap', 'external'}
+    for rtp_file in glob(os.path.join(ffdir, '*.rtp')):
+        residue, n_atoms = None, 0
+        entries = {}
+        with open(rtp_file) as infile:
+            for line in infile:
+                stripped = line.strip()
+                if stripped.startswith('[') and stripped.endswith(']'):
+                    tag = stripped[1:-1].strip()
+                    if tag in sections:
+                        continue
+                    if residue is not None:
+                        entries[residue] = entries.get(residue, 0) + n_atoms
+                    residue, n_atoms = tag, 0
+                elif residue is not None and stripped and not stripped.startswith((';', '#')):
+                    n_atoms += 1
+        if residue is not None:
+            entries[residue] = entries.get(residue, 0) + n_atoms
+        # monatomic entries are ions handled through the nonbonded parameters; they
+        # must not block an addon from defining a polyatomic residue of the same
+        # name (e.g. the U4+ ion vs the RNA residue U renamed to RU)
+        names.update(res for res, count in entries.items() if count > 1)
+    for types_file in (os.path.join(ffdir, 'residuetypes.dat'),):
+        if os.path.exists(types_file):
+            with open(types_file) as infile:
+                for line in infile:
+                    if line.strip() and not line.strip().startswith((';', '#')):
+                        names.add(line.split()[0])
+    return names
+
+
+def amber2ffa(leaprc: str, outdir: str, name: Optional[str] = None, compatibility: Optional[list] = None,
+              priority: int = 10, base_ff: Optional[Union[str, list]] = None,
+              amber_dir: Optional[str] = None,
+              extra_files: Optional[list] = None,
+              extra_atomtypes: Optional[Union[str, list]] = None,
+              residues: bool = True, skip_residues: Optional[list] = None,
+              deduplicate: bool = True) -> str:
+    """
+    Reads a .leaprc file with Amber parameter dependencies and generates a Gromacs
+    force field addon (a <name>.ffa directory) that can be used together with a base
+    .ff force field through pdb2gmx -ffa. In contrast to amber2gmxFF, per-torsion 1-4
+    scaling factors (SCEE=/SCNB= tags, e.g. in GLYCAM or lipid21) are preserved: the
+    dominant values are written as an [ addon_scaling ] section, and the torsion types
+    that deviate from them are listed in a [ pair_scaling ] section in the dihedral
+    form "type1 type2 type3 type4 fudgeLJ fudgeQQ", which applies only to 1-4 pairs
+    that are terminal atoms of a torsion matching the pattern in either direction, so
+    the same atom type pair can carry different scaling in different torsion contexts.
+
+    If the leaprc sources residue topologies (.prep files via loadamberprep and/or
+    .lib files via loadOff), the addon additionally receives residue database files
+    in the layout of a regular force field directory (aminoacids.rtp, dna.rtp,
+    rna.rtp, other.rtp and residuetypes.dat) so that pdb2gmx can build the new
+    residues; residues already defined by the base force field, monatomic ion
+    residues and skip_residues entries are excluded. Note that old-style .prep files
+    carry no inter-residue connection information, so polymerization of such residues
+    into chains is not possible. A .hdb hydrogen database file is generated for each
+    residue file from the hydrogen atoms present in the .rtp entries, so that pdb2gmx
+    can add hydrogens to input structures that lack them. Hydrogen groups whose names
+    pdb2gmx cannot reconstruct (letter suffixes such as GLYCAM H5E/H5A) are renamed to
+    the <prefix><number> convention in the generated .rtp entries, with a matching .arn
+    renaming file written so that input structures using the original names still
+    translate. The .r2b building block tables of the converted nucleic acid
+    residues are generated from their names; the .tdb databases cannot be generated
+    from Amber data and must be placed into the addon directory manually when they
+    are needed (pdb2gmx merges same-kind data files from addons).
+
+    CMAP corrections are written to the addon as a [ cmaptypes ] section; for the
+    residues included in the addon residue topologies a backbone [ cmap ] block is
+    generated. For CMAP residues taken from the base force field only the parameters
+    are written: pdb2gmx applies the correction to such residues once addon .rtp
+    entries can override the base ones. The [ impropers ] blocks of the generated
+    residue topologies are taken from the .prep files when present and generated
+    from the IMPROPER parameter records otherwise (the records of the base force
+    field plus those of the converted files, in that order, as LEaP sees them),
+    reproducing the LEaP enumeration and atom ordering (the central atom at
+    position 3, the outer atoms in the order canonical for pdb2gmx). Amber improper torsions contribute no scaling (Gromacs
+    impropers generate no 1-4 interactions anyway).
+
+    :param leaprc: str, a file that sources dependencies from which the addon will be created
+    :param outdir: str, directory in which the <name>.ffa directory will be created
+    :param name: str, name of the addon, defaults to the base name of leaprc
+    :param compatibility: list of str, base force fields the addon is compatible with
+        (written to compatibility.dat, defaults to ['*'], i.e. any force field)
+    :param priority: int, priority of the addon, written to its [ addon_priority ]
+        section; higher wins in conflicts with definitions or scaling from other files
+    :param base_ff: str or list of str, base force field name, directory or
+        ffnonbonded.itp path; when a list is
+        given, its entries are the base force field followed by already generated
+        sibling addons. Atom types and bonded parameter blocks that are already defined
+        by one of them are dropped from the addon in favor of the first definition,
+        warning when the parameters differ
+    :param amber_dir: str, abs path to the dir containing Amber prep, parm, lib directories
+        if leaprc is a local file
+    :param extra_files: list of str, additional .dat/.frcmod files to include
+    :param extra_atomtypes: str or list of str, additional .dat/.frcmod files (e.g. parm19.dat and
+        frcmod.ff19SB for an amber19sb base) that only contribute Lennard-Jones parameters of atom types
+        not defined by the leaprc-sourced parameter files. This is needed e.g. for GLYCAM, whose parameters
+        for protein and nucleic acid residues reference types (CT, N, 2C, ...) that the main GLYCAM file
+        does not define. Bonded entries that keep referencing atom types undefined everywhere (e.g. the
+        legacy NH type of GLYCAM) are dropped with a warning, because grompp rejects addons referencing
+        unknown atom types
+    :param residues: bool, generate residue topology files (.rtp and residuetypes.dat)
+        from the .prep/.lib files referenced by the leaprc (default True)
+    :param skip_residues: list of str, residue names to exclude from the generated
+        residue topologies on top of those already defined by the base force field
+    :param deduplicate: bool, drop the atom types and bonded parameter blocks that
+        are already defined by base_ff or by an earlier sibling addon (default True).
+        Set it to False to keep the overlapping entries in the addon: grompp and
+        pdb2gmx then resolve the overlaps by the priority declared in the
+        [ addon_priority ] section, so addons with overlapping definitions must be
+        generated with different priorities
+    :return: str, path of the generated .ffa directory
+    """
+    orig_dir = os.path.sep.join(leaprc.split(os.path.sep)[:-1]) + os.path.sep if os.path.sep in leaprc else ''
+    amb = amber_dir if amber_dir is not None else orig_dir + '../'
+    extra_files = extra_files if extra_files is not None else []
+    extra_dats = [pth for pth in extra_files if pth.endswith('dat') or 'frcmod' in pth.split(os.path.sep)[-1]]
+    extra_libs = [pth for pth in extra_files if pth.endswith('lib')]
+    extra_preps = [pth for pth in extra_files if pth.endswith('in') or pth.endswith('prep')]
+    dats = find_leap_files(amb, 'parm', leaprc, extra_dats)
+    res_files = find_leap_res_files(amb, leaprc, extra_libs + extra_preps) if residues else []
+    if not dats:
+        raise RuntimeError(f"No parameter files (.dat/.frcmod) found for {leaprc}")
+    if name is None:
+        name = os.path.splitext(os.path.split(leaprc)[-1])[0]
+    new_top = gml.Top(amber=True)
+    # the residue libraries are read before the parameter files: the atom types of the
+    # C/N/CA atoms of the CMAP residues define the atomtype-residuetype patterns of the
+    # [ cmaptypes ] entries
+    residue_atoms, residue_bonds, residue_connectors, residue_impropers = {}, {}, {}, {}
+    if residues and res_files:
+        for kind, res_file in res_files:
+            print(f"***** Adding residues from {res_file} *****")
+            if kind == 'lib':
+                part_atoms, part_bonds, part_connectors = read_lib(res_file)
+                part_impropers = {}
+            else:
+                part_atoms, part_bonds, part_connectors, part_impropers = read_prep(res_file)
+            # a unit redefined by a later file replaces the earlier definition
+            # entirely, including its impropers, which may name atoms of the
+            # replaced unit and would otherwise linger in the generated topology
+            for res in part_atoms:
+                if res in residue_atoms:
+                    residue_impropers.pop(res, None)
+            residue_atoms.update(part_atoms)
+            residue_bonds.update(part_bonds)
+            residue_connectors.update(part_connectors)
+            # an empty improper list (e.g. from .prep files without explicit
+            # improper records) must not shadow the ones computed later by
+            # assign_impropers, which reproduces the LEaP matching
+            residue_impropers.update({k: v for k, v in part_impropers.items() if v})
+    scaling = {}
+    addon_cmap = {}
+    impr_records = {}
+    for dat in dats:
+        print(f"***** Adding parameters from {dat} *****")
+        _at, _bo, _an, _di, impropertypes, _nb, _cm, scaling_part = parse_frcmod(dat, return_scaling=True)
+        for types in impropertypes:
+            # the last file that defines a record wins, as when LEaP loads several frcmods
+            impr_records.pop(types, None)
+            impr_records[types] = None
+        addon_cmap.update(load_frcmod(new_top, dat, return_cmap=True, pro_atoms=residue_atoms,
+                                      warn_scaling=False))
+        for key, values in scaling_part.items():
+            scaling.setdefault(key, [])
+            scaling[key].extend(values)
+    if extra_atomtypes is not None:
+        extra_type_files = [extra_atomtypes] if isinstance(extra_atomtypes, str) else extra_atomtypes
+        for extra_file in extra_type_files:
+            for atype_name, atype_params in parse_frcmod(extra_file)[0].items():
+                new_top.parameters.add_atomtype(atype_name, *atype_params, action_default='t')
+    new_top.parameters.sort_dihedrals()
+    counts = {}
+    for values in scaling.values():
+        for factors in values:
+            counts[factors] = counts.get(factors, 0) + 1
+    scee, scnb = max(counts, key=counts.get) if counts else (1.2, 2.0)
+    overrides = {}
+    for types, values in scaling.items():
+        for factors in values:
+            if factors == (scee, scnb):
+                continue
+            canon = min(types, tuple(reversed(types)))
+            if canon in overrides and overrides[canon] != factors:
+                print(f"WARNING: conflicting 1-4 scaling for torsion types {canon}: keeping {overrides[canon]}, "
+                      f"ignoring {factors}")
+            else:
+                overrides[canon] = factors
+    ffadir = os.path.join(outdir, f'{name}.ffa')
+    os.makedirs(ffadir, exist_ok=True)
+    with open(os.path.join(ffadir, 'compatibility.dat'), 'w') as outfile:
+        for base in compatibility if compatibility else ['*']:
+            outfile.write(f"{base}\n")
+    atom_entries = new_top.parameters.atomtypes.entries_param
+    base_defined = set()
+    base_types = {}
+    base_type_entries = {}
+    base_ffdirs = []
+    if base_ff is not None:
+        base_ff_list = base_ff if isinstance(base_ff, list) else [base_ff]
+        for base_item in base_ff_list:
+            if os.path.isabs(base_item) and os.path.isdir(base_item):
+                # a force field or addon directory given by an absolute path
+                base_path = os.path.join(base_item, 'ffnonbonded.itp')
+            else:
+                base_path = base_item if os.path.isabs(base_item) else \
+                    os.path.join(new_top.gromacs_dir, base_item, 'ffnonbonded.itp')
+                if not os.path.exists(base_path):
+                    base_path = base_path.replace(os.path.sep + base_item + os.path.sep,
+                                                  os.path.sep + base_item + '.ff' + os.path.sep)
+                if not os.path.exists(base_path) and os.path.isdir(base_item):
+                    base_path = os.path.join(base_item, 'ffnonbonded.itp')
+            if not os.path.exists(base_path):
+                raise RuntimeError(f"Cannot read {base_path} to check atom type compatibility "
+                                   f"with the base force field")
+            base_ffdirs.append(os.path.dirname(os.path.abspath(base_path)))
+        # entries already defined by an earlier source (the base force field and, when a
+        # list is given, the previously generated sibling addons) are dropped; the first
+        # definition wins, which matches the order in which pdb2gmx merges the topologies
+        for base_path_dir in base_ffdirs:
+            with open(os.path.join(base_path_dir, 'ffnonbonded.itp')) as infile:
+                base_top = gml.Top._from_text('[ defaults ]\n1 2 yes 0.5 0.8333\n' + infile.read())
+            for entry in base_top.parameters.atomtypes.entries_param:
+                name = entry.types[0]
+                if name not in base_types:
+                    base_types[name] = entry.params
+                    base_type_entries[name] = entry
+        base_defined = set(base_types)
+        if deduplicate:
+            kept = []
+            for entry in atom_entries:
+                if entry.types[0] in base_types:
+                    if any(abs(float(new) - float(old)) > 1e-4 for new, old in
+                           zip(entry.params[:2], base_types[entry.types[0]][:2])):
+                        print(f"WARNING: atom type {entry.types[0]} has different Lennard-Jones parameters in the addon "
+                              f"({entry.params[0]:.4f}/{entry.params[1]:.4f}) and in the base force field "
+                              f"({base_types[entry.types[0]][0]:.4f}/{base_types[entry.types[0]][1]:.4f}); the addon "
+                              "entry is dropped and the base force field parameters will be used")
+                    continue
+                kept.append(entry)
+            atom_entries = kept
+        else:
+            for entry in atom_entries:
+                if entry.types[0] in base_types:
+                    # an frcmod may omit the mass of a type it only uses; inherit it
+                    # (and the atomic number) from the base force field so that the
+                    # overriding entry does not zero out a real mass
+                    base_entry = base_type_entries[entry.types[0]]
+                    try:
+                        bmass = float(base_entry.modifiers[1])
+                    except (ValueError, TypeError, IndexError):
+                        bmass = 0.0
+                    try:
+                        amass = float(entry.modifiers[1])
+                    except (ValueError, TypeError, IndexError):
+                        amass = 0.0
+                    if amass == 0 and bmass != 0:
+                        entry.modifiers[1] = base_entry.modifiers[1]
+                        try:
+                            if float(entry.modifiers[0]) == 0:
+                                entry.modifiers[0] = base_entry.modifiers[0]
+                        except (ValueError, TypeError, IndexError):
+                            pass
+                    if any(abs(float(new) - float(old)) > 1e-4 for new, old in
+                           zip(entry.params[:2], base_types[entry.types[0]][:2])):
+                        print(f"WARNING: atom type {entry.types[0]} has different Lennard-Jones parameters in the addon "
+                              f"({entry.params[0]:.4f}/{entry.params[1]:.4f}) and in the base force field "
+                              f"({base_types[entry.types[0]][0]:.4f}/{base_types[entry.types[0]][1]:.4f}); the addon "
+                              "entry is kept and overrides the base parameters according to the addon priority")
+    if residues and res_files:
+        # LEaP generates the improper torsions of a built unit from the IMPROPER
+        # records of the whole parameter set: the records the base force field
+        # was converted from apply to the addon residues as well; the addon's
+        # own records are appended after them (leap's order of loading).
+        # Residues taken from .lib files carry no explicit improper list, so it
+        # has to be recomputed here (the explicit lists from .prep files win)
+        impr_pool = {}
+        for base_path_dir in base_ffdirs:
+            base_bonded_impr = os.path.join(base_path_dir, 'ffbonded.itp')
+            if not os.path.exists(base_bonded_impr):
+                continue
+            with open(base_bonded_impr) as infile:
+                btop_impr = gml.Top._from_text('[ defaults ]\n1 2 yes 0.5 0.8333\n' + infile.read())
+            for subs in btop_impr.parameters.subsections:
+                if subs.header == 'dihedraltypes':
+                    for entry in subs.entries_param:
+                        if str(entry.interaction_type) == '4' and len(entry.types) == 4:
+                            # records with a zero force constant exist in the amber
+                            # parameter sets only for the 1-4 exclusions they generate;
+                            # they carry no energy and the shipped base records are not
+                            # canonically ordered, so they must not drive the generated
+                            # [ impropers ] blocks
+                            try:
+                                if abs(float(entry.params[1])) < 1e-9:
+                                    continue
+                            except (ValueError, TypeError, IndexError):
+                                pass
+                            impr_pool.setdefault(tuple(entry.types), None)
+        for types in impr_records:
+            impr_pool.setdefault(types, None)
+        for res, quads in assign_impropers(residue_atoms, residue_bonds,
+                                           list(impr_pool)).items():
+            residue_impropers.setdefault(res, quads)
+    base_ffdir = base_ffdirs[0] if base_ffdirs else None
+    referenced = set()
+    for section in ('bondtypes', 'angletypes', 'dihedraltypes'):
+        for subs in [s for s in new_top.parameters.subsections if s.header == section]:
+            for entry in subs.entries_param:
+                referenced.update(entry.types)
+    missing = sorted(t for t in referenced if t not in ({e.types[0] for e in atom_entries} | base_defined)
+                     and t != 'X')
+    if missing:
+        missing_set = set(missing)
+        print(f"WARNING: bonded parameters reference atom type(s) {missing} that are defined neither by the source "
+              "parameter files and extra_atomtypes nor by the base force field; since grompp rejects addons "
+              "referencing unknown atom types, all entries referencing them are dropped; supply their "
+              "Lennard-Jones parameters via extra_atomtypes (e.g. parm19.dat and frcmod.ff19SB for an amber19sb "
+              "base) to keep those entries")
+        dropped = 0
+        for subs in [s for s in new_top.parameters.subsections
+                     if s.header in ('bondtypes', 'angletypes', 'dihedraltypes')]:
+            keep = [ent for ent in subs.entries
+                    if not isinstance(ent, gml.EntryParam) or not missing_set.intersection(ent.types)]
+            dropped += len(subs.entries) - len(keep)
+            subs.entries = keep
+        overrides = {pair: factors for pair, factors in overrides.items() if not missing_set.intersection(pair)}
+        print(f"WARNING: dropped {dropped} bonded parameter entries referencing undefined atom type(s)")
+
+    # duplicate bonded parameter blocks are removed from the addon: grompp rejects
+    # duplicate dihedral blocks even when they carry the same values, and warns about
+    # duplicate bond and angle types. Blocks whose atom types are already defined by
+    # the base force field (or by an earlier sibling addon, when base_ff is a list)
+    # are dropped in favor of the first definition; this keeps stale general
+    # parameters from an addon frcmod from overriding a newer base force field.
+    # When deduplicate is False the base comparison is skipped and grompp/pdb2gmx
+    # resolve the overlaps by the priority declared in [ addon_priority ] instead;
+    # duplicates within the addon itself are always removed, since definitions from
+    # the same file share one priority
+    sections = ('bondtypes', 'angletypes', 'dihedraltypes', 'impropertypes')
+
+    def block_key(header, entry):
+        types = tuple(entry.types)
+        if header in ('bondtypes', 'angletypes') \
+                or (header == 'dihedraltypes' and str(entry.interaction_type) == '9'):
+            # bond and angle types are order-insensitive, proper dihedrals are
+            # symmetric under reversal
+            return header, min(types, tuple(reversed(types)))
+        return header, types
+
+    def collect_blocks(subsections):
+        # group consecutive parameter lines into blocks, keyed by the canonical
+        # atom type tuple; multi-term blocks keep all their terms
+        blocks = {}
+        for subs in subsections:
+            if subs.header not in sections:
+                continue
+            cur_key, cur_block = None, []
+            for entry in subs.entries_param:
+                vals = tuple(round(float(v), 4) for v in entry.params)
+                key = block_key(subs.header, entry)
+                if key != cur_key:
+                    if cur_key is not None:
+                        blocks[cur_key] = cur_block
+                    cur_key, cur_block = key, [vals]
+                else:
+                    cur_block.append(vals)
+            if cur_key is not None:
+                blocks[cur_key] = cur_block
+        return blocks
+
+    base_blocks = {}
+    if deduplicate and base_ffdirs:
+        for base_path_dir in base_ffdirs:
+            base_bonded = os.path.join(base_path_dir, 'ffbonded.itp')
+            if not os.path.exists(base_bonded):
+                continue
+            with open(base_bonded) as infile:
+                base_btop = gml.Top._from_text('[ defaults ]\n1 2 yes 0.5 0.8333\n' + infile.read())
+            for key, vals in collect_blocks(base_btop.parameters.subsections).items():
+                if key not in base_blocks:
+                    base_blocks[key] = vals
+    n_identical = 0
+    n_internal = 0
+    n_term_dups = 0
+    conflicting = []
+    for subs in [s for s in new_top.parameters.subsections if s.header in sections]:
+        addon_blocks = collect_blocks([subs])
+        drop_keys = set()
+        if deduplicate:
+            for key, vals in addon_blocks.items():
+                bvals = base_blocks.get(key) if base_blocks else None
+                if bvals is None:
+                    continue
+                drop_keys.add(key)
+                if len(bvals) == len(vals) and all(a == b for a, b in zip(sorted(bvals), sorted(vals))):
+                    n_identical += 1
+                else:
+                    conflicting.append(key)
+        if drop_keys:
+            subs.entries = [e for e in subs.entries
+                            if not isinstance(e, gml.EntryParam)
+                            or block_key(subs.header, e) not in drop_keys]
+        # drop repeated blocks of the same types within the addon itself (a second,
+        # non-contiguous run of the same canonical types): grompp either rejects them
+        # (multi-term dihedral blocks) or would count the interactions twice
+        # collapse identical consecutive term lines within a block: frcmod files
+        # sometimes repeat a torsion line verbatim, and grompp would otherwise
+        # generate the same dihedral potential multiple times
+        collapsed, prev_sig = [], None
+        for e in subs.entries:
+            if isinstance(e, gml.EntryParam):
+                sig = (block_key(subs.header, e), tuple(round(float(v), 4) for v in e.params))
+                if sig == prev_sig:
+                    n_term_dups += 1
+                    continue
+                prev_sig = sig
+            else:
+                prev_sig = None
+            collapsed.append(e)
+        subs.entries = collapsed
+        addon_blocks = collect_blocks([subs])
+        if len(addon_blocks) < sum(1 for e in subs.entries if isinstance(e, gml.EntryParam)):
+            seen_keys = set()
+            current_key, dropping = None, False
+            kept = []
+            for e in subs.entries:
+                if isinstance(e, gml.EntryParam):
+                    key = block_key(subs.header, e)
+                    if key != current_key:
+                        current_key = key
+                        dropping = key in seen_keys
+                        if dropping:
+                            n_internal += 1
+                            first = addon_blocks[key][0]
+                            vals = tuple(round(float(v), 4) for v in e.params)
+                            if vals != first:
+                                print(f"WARNING: repeated bonded parameter block {'-'.join(key[1])} "
+                                      f"({key[0]}) with different parameters within the addon; "
+                                      "keeping the first occurrence")
+                        else:
+                            seen_keys.add(key)
+                    if dropping:
+                        continue
+                kept.append(e)
+            subs.entries = kept
+    if n_identical:
+        print(f"Dropped {n_identical} bonded parameter block(s) identical to the base force field")
+    if n_term_dups:
+        print(f"Collapsed {n_term_dups} repeated identical parameter line(s) within blocks")
+    if n_internal:
+        print(f"Dropped {n_internal} repeated bonded parameter block(s) within the addon")
+    if conflicting:
+        print(f"WARNING: dropping {len(conflicting)} bonded parameter block(s) whose atom types are already")
+        print("WARNING: defined by the base force field with different parameters; the base parameters win.")
+        for header, types in sorted(conflicting):
+            print(f"WARNING:   {header} {'-'.join(types)}")
+
+    source_atomtypes = read_addAtomTypes(leaprc)
+    for atype in atom_entries:
+        if atype.types[0] in source_atomtypes:
+            if atype.modifiers[0] == '0':
+                atype.modifiers[0] = str(source_atomtypes[atype.types[0]][0])
+            if atype.modifiers[1] == '0':
+                atype.modifiers[1] = str(source_atomtypes[atype.types[0]][1])
+    # pdb2gmx reads *.atp addon files in the "<name> <mass>" format, the Lennard-Jones
+    # parameters are taken from the [ atomtypes ] section of the addon itp instead
+    with open(os.path.join(ffadir, 'atomtypes.atp'), 'w') as outfile:
+        outfile.write("; name and mass of the atom types added by the addon\n")
+        outfile.write("; name               mass\n")
+        for atype in atom_entries:
+            outfile.write(f"{atype.types[0]:12s} {float(atype.modifiers[1]):12.5f}\n")
+    with open(os.path.join(ffadir, 'ffnonbonded.itp'), 'w') as outfile:
+        outfile.write("; Lennard-Jones parameters of the atom types added by the addon\n")
+        outfile.write("[ atomtypes ]\n"
+                      f"{gml.Topology.FF_SECTION_COLUMN_HEADERS['atomtypes']}\n")
+        for atype in atom_entries:
+            outfile.write(f"{str(atype).rstrip()}\n")
+    with open(os.path.join(ffadir, 'ffbonded.itp'), 'w') as outfile:
+        for section in ('bondtypes', 'angletypes', 'dihedraltypes', 'cmaptypes'):
+            for subs in [s for s in new_top.parameters.subsections if s.header == section]:
+                outfile.write(f"[ {section} ]\n"
+                              f"{gml.Topology.FF_SECTION_COLUMN_HEADERS[section]}\n")
+                for entry in subs.entries_param:
+                    outfile.write(f"{str(entry).rstrip()}\n")
+                outfile.write("\n")
+    # the addon itp plays the role of forcefield.itp: scaling declarations plus includes,
+    # the parameters themselves live in the regular ffnonbonded/ffbonded files
+    with open(os.path.join(ffadir, 'forcefield-addon.itp'), 'w') as outfile:
+        outfile.write(f"; Force field addon generated by gromologist from {os.path.split(leaprc)[-1]}\n")
+        # the scaling and priority must be declared before the includes, so that
+        # the included parameter files inherit them (grompp propagates the
+        # [ addon_scaling ] declaration and the [ addon_priority ] value of a
+        # file into the files that it includes)
+        outfile.write(f"; the scaling below corresponds to the dominant per-torsion SCEE/SCNB values "
+                      f"of the source parameters (SCEE={scee}, SCNB={scnb})\n")
+        outfile.write("[ addon_priority ]\n"
+                      f"{priority}\n\n")
+        outfile.write("[ addon_scaling ]\n; nbfunc comb-rule gen-pairs fudgeLJ fudgeQQ\n")
+        outfile.write(f"1        2         yes        {1 / scnb:.4f}     {1 / scee:.4f}\n\n")
+        outfile.write('#include "ffnonbonded.itp"\n#include "ffbonded.itp"\n')
+        if overrides:
+            # grompp requires the atom types of a [ pair_scaling ] entry to be
+            # defined before the directive, so it goes after the includes
+            outfile.write("; torsion type patterns whose 1-4 scaling differs from the addon default;\n")
+            outfile.write("; the dihedral form applies only to 1-4 pairs that are terminal atoms of a\n")
+            outfile.write("; torsion matching the pattern in either direction\n")
+            outfile.write("[ pair_scaling ]\n; type1  type2  type3  type4  fudgeLJ  fudgeQQ\n")
+            for types, factors in sorted(overrides.items()):
+                outfile.write(f"{types[0]:8s} {types[1]:8s} {types[2]:8s} {types[3]:8s} "
+                              f"{1 / factors[1]:<8.4f} {1 / factors[0]:<8.4f}\n")
+            outfile.write("\n")
+    residue_files = []
+    if residues and res_files:
+        base_resnames = set()
+        for base_path_dir in base_ffdirs:
+            base_resnames.update(base_residue_names(base_path_dir))
+        monatomic = sorted(r for r, ats in residue_atoms.items() if len(ats) <= 1)
+        if monatomic:
+            print(f"NOTE: excluding monatomic residue(s) {monatomic}, monatomic ions are defined by the "
+                  "nonbonded parameters of the force field")
+        in_base = sorted(set(residue_atoms) & base_resnames)
+        if in_base:
+            print(f"WARNING: excluding residue(s) {in_base} already defined by the base force field or its "
+                  "residuetypes.dat, pdb2gmx rejects overlapping residue entries")
+        for name in set(monatomic) | set(in_base) | set(skip_residues or []):
+            for dct in (residue_atoms, residue_bonds, residue_connectors, residue_impropers):
+                dct.pop(name, None)
+        rtp_cmap = {}
+        cmap_residues = {k[-1] for k in addon_cmap}
+        for res in sorted(cmap_residues & set(residue_atoms)):
+            if {'C', 'N', 'CA'} <= {at[0] for at in residue_atoms[res]}:
+                rtp_cmap[res] = [['-C', 'N', 'CA', 'C', '+N']]
+            else:
+                print(f"WARNING: residue {res} carries a CMAP correction but lacks the C/N/CA backbone "
+                      "atoms; no [ cmap ] block is generated for it")
+        base_cmap = sorted(cmap_residues - set(residue_atoms))
+        if base_cmap:
+            print(f"NOTE: CMAP corrections for residue(s) {base_cmap} are written to the addon parameters, "
+                  "but the residues themselves come from the base force field; pdb2gmx will apply them "
+                  "once addon .rtp entries can override the base ones")
+        all_types_rtp = {at[1] for atoms_list in residue_atoms.values() for at in atoms_list}
+        undefined = sorted(all_types_rtp - new_top.defined_atomtypes - set(base_types))
+        if undefined:
+            print(f"WARNING: atom type(s) {undefined} used in the generated residue topologies are defined "
+                  "neither by the addon nor by the base force field; supply them via extra_atomtypes")
+
+        def residue_type(name: str) -> str:
+            if name in gml.Pdb.nucl_knw.keys():
+                return 'DNA' if name.startswith('D') else 'RNA'
+            if name in gml.Pdb.prot_knw.keys():
+                return 'Protein'
+            # modified nucleotides (e.g. from tRNA or modrna libraries) are recognized by
+            # their ribose/deoxyribose; pdb2gmx only polymerizes residues of matching type
+            atom_names = {at[0] for at in residue_atoms.get(name, [])}
+            if "C1'" in atom_names and "O4'" in atom_names:
+                return 'RNA'
+            # amino-acid-like units carrying the peptide backbone N-CA-C atoms
+            # (e.g. the glycosylated NLN/OLS/OLT residues of the GLYCAM libraries)
+            # are polymerized by pdb2gmx like proteins
+            if {'N', 'CA', 'C'} <= atom_names:
+                return 'Protein'
+            return 'Other'
+
+        groups = {'aminoacids': [], 'dna': [], 'rna': [], 'other': []}
+        for res_name in sorted(residue_atoms):
+            groups[{'Protein': 'aminoacids', 'DNA': 'dna', 'RNA': 'rna', 'Other': 'other'}[residue_type(res_name)]] \
+                .append(res_name)
+
+        def subset(dct: dict, names: list) -> dict:
+            return {k: v for k, v in dct.items() if k in names}
+
+        for filename, names in groups.items():
+            if not names:
+                continue
+            fix_renames: dict = {}
+            if filename == 'aminoacids':
+                group_atoms = fix_rtp(subset(residue_atoms, names), renames_out=fix_renames)
+                # the bond data is 1-based atom index pairs, not atom names, so
+                # the name-dependent fix_rtp transformations do not apply to it
+                group_bonds = subset(residue_bonds, names)
+                group_connectors = subset(residue_connectors, names)
+                group_impropers = fix_rtp(subset(residue_impropers, names), impr=True)
+            elif filename in ('rna', 'dna'):
+                # the standard Amber nucleic atom names (OP1/OP2, HO5'/HO3', the
+                # double-prime hydrogens) are converted to the names of the shipped
+                # fields; the input names stay usable through the .arn renames
+                group_atoms = fix_rtp(subset(residue_atoms, names), rna=True, renames_out=fix_renames)
+                # the bond data is 1-based atom index pairs, not atom names, so
+                # the name-dependent fix_rtp transformations do not apply to it;
+                # only the building block replication is required
+                group_bonds = replicate_building_blocks(subset(residue_bonds, names))
+                group_connectors = replicate_building_blocks(subset(residue_connectors, names))
+                group_impropers = fix_rtp(subset(residue_impropers, names), impr=True, rna=True)
+            else:
+                group_atoms = subset(residue_atoms, names)
+                group_bonds = subset(residue_bonds, names)
+                group_connectors = subset(residue_connectors, names)
+                group_impropers = subset(residue_impropers, names)
+            group_atoms, group_impropers, group_renames = rename_hydrogens(
+                group_atoms, group_bonds, group_impropers if group_impropers else None)
+            # the renames collected by fix_rtp are keyed by the pre-rename residue
+            # names, remap them to the R-prefixed building block names where applied
+            for res, pairs in fix_renames.items():
+                target = res if res in group_atoms else \
+                    ('R' + res if 'R' + res in group_atoms else None)
+                if target is not None:
+                    group_renames.setdefault(target, {}).update(pairs)
+            if filename in ('rna', 'dna'):
+                for old_name, new_name in legacy_nucleic_input_renames[filename.upper()].items():
+                    group_renames.setdefault(filename.upper(), {})[old_name] = new_name
+            write_rtp(group_atoms, group_bonds, group_connectors, os.path.join(ffadir, f'{filename}.rtp'),
+                      impropers=group_impropers if group_impropers else None,
+                      cmap=rtp_cmap if rtp_cmap else None,
+                      backbone_impropers=(filename == 'aminoacids'))
+            residue_files.append(f'{filename}.rtp')
+            hdb_entries = rtp_to_hdb(group_atoms, group_bonds,
+                                     group_impropers if group_impropers else None)
+            if write_hdb(hdb_entries, os.path.join(ffadir, f'{filename}.hdb')):
+                residue_files.append(f'{filename}.hdb')
+            if write_arn(group_renames, os.path.join(ffadir, f'{filename}.arn')):
+                residue_files.append(f'{filename}.arn')
+            if filename in ('rna', 'dna'):
+                if write_r2b(list(group_atoms.keys()), 'RNA' if filename == 'rna' else 'DNA',
+                             os.path.join(ffadir, f'{filename}.r2b')):
+                    residue_files.append(f'{filename}.r2b')
+        if residue_files:
+            with open(os.path.join(ffadir, 'residuetypes.dat'), 'w') as outfile:
+                outfile.write("; residue types introduced by the addon\n")
+                for res_name in sorted(residue_atoms):
+                    outfile.write(f"{res_name}\t{residue_type(res_name)}\n")
+            residue_files.append('residuetypes.dat')
+    print(f"Wrote force field addon to {ffadir} "
+          f"({len(atom_entries)} atom types, {len(overrides)} scaled type-pair overrides"
+          + (", residue files: " + ', '.join(sorted(residue_files)) if residue_files else '') + ")")
+    return ffadir
+
+
 def reorder_amber_impropers(new_top: "gml.Top", rtp_dihedrals: set) -> "gml.Top":
     """
     Modifying improper dihedral order, empirically checked against GMX FFs
@@ -797,7 +2188,13 @@ def read_prep_impropers(prepfile: str) -> dict:
     return impropers
 
 
-def prep_to_rtp(prepfile, outfile="new.rtp", ff='amber'):
+def read_prep(prepfile: str) -> (dict, dict, dict, dict):
+    """
+    Reads the residues from a file in the old-style Amber .prep format
+    :param prepfile: str, input file for reading
+    :return: tuple of dict, atoms, bonds, connectors and impropers in the per-residue
+        format used by write_rtp
+    """
     content = [l.strip() for l in open(prepfile)]
     atoms = {}
     bonds = {}
@@ -834,7 +2231,13 @@ def prep_to_rtp(prepfile, outfile="new.rtp", ff='amber'):
             bonds[current_res].append((int(n1), int(n2)))
         elif reading_impropers and len(ln.split()) > 3:
             impropers[current_res].append(ln.split())
-    bonds[current_res] = sorted(bonds[current_res], key=lambda x: x[0])
+    if current_res:
+        bonds[current_res] = sorted(bonds[current_res], key=lambda x: x[0])
+    return atoms, bonds, connectors, impropers
+
+
+def prep_to_rtp(prepfile, outfile="new.rtp", ff='amber'):
+    atoms, bonds, connectors, impropers = read_prep(prepfile)
     write_rtp(atoms, bonds, connector=connectors, outfile=outfile, impropers=impropers, ff=ff)
 
 
@@ -1970,3 +3373,76 @@ def make_grid_movies(argv=sys.argv[1:]):
         out.write('do_nothing t=1\n')
     result = run(['molywood', 'gml_molywood_input.txt'], stderr=PIPE, stdout=PIPE, check=False)
     return result.stdout.decode() + result.stderr.decode()
+
+
+def amber2gmxFF_cli(argv=sys.argv[1:]):
+    """Command-line wrapper for amber2gmxFF (see its docstring for the details)."""
+    parser = argparse.ArgumentParser(
+        prog='gml-amber2gmx',
+        description="Convert an Amber leaprc and the parameter files and residue libraries it "
+                    "sources into a Gromacs .ff force field directory.")
+    parser.add_argument("leaprc", help="leaprc file to convert, or a leaprc.* name from the Amber "
+                                       "installation (resolved through --amber-dir)")
+    parser.add_argument("outdir", help="the .ff directory to create")
+    parser.add_argument("--amber-dir", default=None,
+                        help="path to the Amber data directory (the one containing prep/, parm/ and "
+                             "lib/, e.g. <ambertools>/dat/leap) used to resolve the sourced files")
+    parser.add_argument("--base-ff", default=None,
+                        help="already converted .ff directory (a name in the Gromacs data directory "
+                             "or a path) whose accessory files are copied into the new force field")
+    parser.add_argument("--extra-file", action="append", default=None,
+                        help="additional library or parameter file to include (repeatable)")
+    args = parser.parse_args(argv)
+    amber2gmxFF(args.leaprc, args.outdir, amber_dir=args.amber_dir,
+                base_ff=args.base_ff, extra_files=args.extra_file)
+
+
+def amber2ffa_cli(argv=sys.argv[1:]):
+    """Command-line wrapper for amber2ffa (see its docstring for the details)."""
+    parser = argparse.ArgumentParser(
+        prog='gml-amber2ffa',
+        description="Convert an Amber leaprc and the parameter files and residue libraries it "
+                    "sources into a Gromacs force field addon (<name>.ffa directory) for "
+                    "gmx pdb2gmx -ffa.")
+    parser.add_argument("leaprc", help="leaprc file to convert, or a leaprc.* name from the Amber "
+                                       "installation (resolved through --amber-dir)")
+    parser.add_argument("outdir", nargs="?", default=".",
+                        help="directory to create <name>.ffa in (default: current directory)")
+    parser.add_argument("--name", default=None,
+                        help="addon name (default: base name of the leaprc)")
+    parser.add_argument("--compatibility", default=None,
+                        help="comma-separated base force fields the addon is compatible with "
+                             "(default: *, any)")
+    parser.add_argument("--priority", type=int, default=10,
+                        help="addon priority, written to [ addon_priority ]; higher wins in "
+                             "atom type conflicts (default: 10)")
+    parser.add_argument("--base-ff", default=None,
+                        help="base force field name, directory or ffnonbonded.itp path; comma-separated "
+                             "entries are the base force field followed by sibling addons")
+    parser.add_argument("--amber-dir", default=None,
+                        help="path to the Amber data directory (the one containing prep/, parm/ and "
+                             "lib/, e.g. <ambertools>/dat/leap) used to resolve the sourced files")
+    parser.add_argument("--extra-file", action="append", default=None,
+                        help="additional library or parameter file to include (repeatable)")
+    parser.add_argument("--extra-atomtypes", action="append", default=None,
+                        help="additional atom types file (atp) to read (repeatable)")
+    parser.add_argument("--no-residues", action="store_true",
+                        help="do not generate the residue database files (rtp, residuetypes.dat)")
+    parser.add_argument("--skip-residue", action="append", default=None,
+                        help="residue to exclude from the addon residue databases (repeatable)")
+    parser.add_argument("--no-deduplicate", action="store_true",
+                        help="keep entries already defined by the base force field or an earlier addon; "
+                             "the overlaps are then resolved by [ addon_priority ], so addons with "
+                             "overlapping definitions must use different priorities")
+    args = parser.parse_args(argv)
+    out = amber2ffa(args.leaprc, args.outdir, name=args.name,
+                    compatibility=None if args.compatibility is None else args.compatibility.split(","),
+                    priority=args.priority,
+                    base_ff=args.base_ff.split(",") if args.base_ff and "," in args.base_ff else args.base_ff,
+                    amber_dir=args.amber_dir,
+                    extra_files=args.extra_file,
+                    extra_atomtypes=args.extra_atomtypes,
+                    residues=not args.no_residues,
+                    skip_residues=args.skip_residue,
+                    deduplicate=not args.no_deduplicate)
+    print(out)
diff --git a/setup.py b/setup.py
index a082331..5c4066c 100644
--- a/setup.py
+++ b/setup.py
@@ -19,7 +19,9 @@ setup(name='gromologist',
             'gml-keep-waters = gromologist.Utils:keep_waters_cli',
             'gml-make-index = gromologist.Gmx:make_index',
             'gml-interpolate-structures = gromologist.Pdb:ext_interpolate_structures',
-            'gml-pbc-from-template = gromologist.Utils:nojump_per_chain'
+            'gml-pbc-from-template = gromologist.Utils:nojump_per_chain',
+            'gml-amber2gmx = gromologist.Utils:amber2gmxFF_cli',
+            'gml-amber2ffa = gromologist.Utils:amber2ffa_cli'
           ]
       },
       zip_safe=False)
diff --git a/tests/test_amber2gmx.py b/tests/test_amber2gmx.py
new file mode 100644
index 0000000..7ae9e9b
--- /dev/null
+++ b/tests/test_amber2gmx.py
@@ -0,0 +1,311 @@
+"""
+Tests for the Amber->Gromacs force field conversion (amber2gmxFF).
+"""
+import contextlib
+import glob
+import io
+import os
+import shutil
+import tempfile
+import unittest
+
+import gromologist as gml
+
+from test_ffa import DAT, LIB_H, LEAPRC_RES_H
+
+
+class TestAmber2gmFFResidueData(unittest.TestCase):
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+        self.old_dir = os.getcwd()
+        self.dat = os.path.join(self.tmpdir, 'testff.dat')
+        with open(self.dat, 'w') as out:
+            out.write(DAT)
+        self.lib = os.path.join(self.tmpdir, 'testffh.lib')
+        with open(self.lib, 'w') as out:
+            out.write(LIB_H)
+        self.leaprc = os.path.join(self.tmpdir, 'testffh.leaprc')
+        with open(self.leaprc, 'w') as out:
+            out.write(LEAPRC_RES_H)
+
+    def tearDown(self):
+        os.chdir(self.old_dir)
+        shutil.rmtree(self.tmpdir)
+
+    def test_atp_and_hdb_generated(self):
+        outdir = os.path.join(self.tmpdir, 'out')
+        try:
+            gml.amber2gmxFF(self.leaprc, outdir)
+        finally:
+            os.chdir(self.old_dir)
+        ffd = os.path.join(outdir + '.ff')
+        with open(os.path.join(ffd, 'atomtypes.atp')) as infile:
+            atp = infile.read()
+        self.assertIn('CT', atp)
+        self.assertIn('H1', atp)
+        self.assertIn('; name               mass', atp)
+        # the parameter file documents the meaning of the columns of its sections
+        with open(os.path.join(ffd, 'ffparams.itp')) as infile:
+            ffparams = infile.read()
+        self.assertIn('[ atomtypes ]\n; name  at.num          mass    charge ptype          sigma   epsilon', ffparams)
+        self.assertIn('[ bondtypes ]\n;      i        j   func            b0            kb', ffparams)
+        self.assertIn('[ angletypes ]\n;      i        j        k   func           th0           cth', ffparams)
+        self.assertIn('[ dihedraltypes ]\n;      i        j        k        l   func         phase            kd     pn', ffparams)
+        with open(os.path.join(ffd, 'aminoacids.rtp')) as infile:
+            self.assertIn('ZZA', infile.read())
+        with open(os.path.join(ffd, 'aminoacids.hdb')) as infile:
+            hdb = infile.read()
+        # the groups whose names follow the <prefix><number> convention get entries
+        self.assertIn('2\t6\tH2\tC2\tO3\tC1', hdb)
+        self.assertIn('1\t2\tHO3\tO3\tC2\tC1', hdb)
+        # the letter-suffixed hydrogens cannot be rebuilt and are skipped
+        self.assertNotIn('H1A', hdb)
+
+
+
+class TestAmber2gmFFUndefinedBondedType(unittest.TestCase):
+    # a type referenced by the bonded parameters without any Lennard-Jones definition
+    # (e.g. CJ in parm19.dat) must not make the converted field unreadable by grompp
+    FRCMOD = """Test frcmod with a type missing Lennard-Jones parameters
+MASS
+ CT 12.011
+ N 14.007
+NONB
+ CT 1.9000000 0.1094000
+ N 1.8240000 0.1700000
+DIHE
+ CT-N-CT-Zz   9.000     1.000     0.0     1.000
+"""
+
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+        self.old_dir = os.getcwd()
+        frcmod = os.path.join(self.tmpdir, 'testff.frcmod')
+        with open(frcmod, 'w') as out:
+            out.write(self.FRCMOD)
+        self.leaprc = os.path.join(self.tmpdir, 'testff.leaprc')
+        with open(self.leaprc, 'w') as out:
+            out.write('loadamberparams testff.frcmod\n')
+
+    def tearDown(self):
+        os.chdir(self.old_dir)
+        shutil.rmtree(self.tmpdir)
+
+    def test_placeholder_atomtype_written(self):
+        outdir = os.path.join(self.tmpdir, 'out')
+        stdout = io.StringIO()
+        try:
+            with contextlib.redirect_stdout(stdout):
+                gml.amber2gmxFF(self.leaprc, outdir)
+        finally:
+            os.chdir(self.old_dir)
+        self.assertIn('referenced by the bonded parameters but has no Lennard-Jones',
+                      stdout.getvalue())
+        with open(os.path.join(outdir + '.ff', 'ffparams.itp')) as infile:
+            entries = [line.split() for line in infile
+                       if line.split() and line.split()[0] == 'Zz'
+                       and len(line.split()) == 7]
+        self.assertEqual(len(entries), 1)
+        self.assertEqual(entries[0][3:5], ['0.0000', 'A'])
+        self.assertAlmostEqual(float(entries[0][5]), 0.0)
+        self.assertAlmostEqual(float(entries[0][6]), 0.0)
+
+
+class TestFixRtp(unittest.TestCase):
+    """Unit tests for the .rtp adjustments applied by the full force field conversion."""
+
+    def test_amber_atom_names_are_kept(self):
+        # the shipped Gromacs Amber force fields use the original Amber atom names, so
+        # the former renames CD1->CD, HD1*->HD* and O/OXT->OC1/OC2 must not be applied
+        rtp = {'ILE': [('CD1', 'CT', -0.1, 9), ('HD11', 'H1', 0.1, 10),
+                       ('HD12', 'H1', 0.1, 11), ('HD13', 'H1', 0.1, 12)],
+               'CALA': [('C', 'C', 0.5, 1), ('O', 'O', -0.5, 2), ('OXT', 'O2', -0.5, 3)]}
+        renames = {}
+        fixed = gml.fix_rtp(rtp, renames_out=renames)
+        self.assertEqual([e[0] for e in fixed['ILE']], ['CD1', 'HD11', 'HD12', 'HD13'])
+        self.assertEqual([e[0] for e in fixed['CALA']], ['C', 'O', 'OXT'])
+        self.assertEqual(renames, {})
+
+    def test_hydrogen3_rename_is_recorded(self):
+        rtp = {'LYS': [('HG3', 'H1', 0.1, 1), ('HG2', 'H1', 0.1, 2)]}
+        renames = {}
+        fixed = gml.fix_rtp(rtp, renames_out=renames)
+        self.assertEqual(fixed['LYS'][0][0], 'HG1')
+        self.assertEqual(renames, {'LYS': {'HG3': 'HG1'}})
+
+    def test_rna_renames_are_recorded(self):
+        rtp = {'A': [('OP1', 'O', -0.5, 1), ("H5\'", 'H1', 0.1, 2), ("C5\'", 'C', 0.1, 3)]}
+        renames = {}
+        fixed = gml.fix_rtp(rtp, rna=True, renames_out=renames)
+        self.assertIn('RA', fixed)
+        self.assertNotIn('A', fixed)
+        self.assertEqual([e[0] for e in fixed['RA']], ['O1P', "H5\'1", "C5\'"])
+        self.assertEqual(renames, {'A': {'OP1': 'O1P', "H5\'": "H5\'1"}})
+
+
+class TestWriteR2b(unittest.TestCase):
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+
+    def tearDown(self):
+        shutil.rmtree(self.tmpdir)
+
+    def _rows(self, names, block_type):
+        outfile = os.path.join(self.tmpdir, f'{block_type}.r2b')
+        if not gml.write_r2b(names, block_type, outfile):
+            self.assertFalse(os.path.exists(outfile))
+            return None
+        with open(outfile) as infile:
+            return [line for line in infile.read().splitlines() if not line.startswith(';')]
+
+    def test_protein_rows(self):
+        self.assertEqual(self._rows({'ALA', 'NALA', 'CALA', 'ARG'}, 'protein'),
+                         ['ALA\tALA\tNALA\tCALA\t-'])
+
+    def test_protein_without_terminal_blocks(self):
+        self.assertIsNone(self._rows({'ALA', 'ARG'}, 'protein'))
+
+    def test_dna_rows(self):
+        self.assertEqual(self._rows({'DA', 'DA5', 'DA3', 'DAN', 'DG'}, 'DNA'),
+                         ['DA\tDA\tDA5\tDA3\tDAN', 'DG\tDG\t-\t-\t-'])
+
+    def test_rna_rows(self):
+        self.assertEqual(self._rows({'RA', 'RA5', 'RA3', 'RAN', 'RU'}, 'RNA'),
+                         ['A\tRA\tRA5\tRA3\tRAN', 'U\tRU\t-\t-\t-'])
+
+    def test_unsupported_block_type(self):
+        with self.assertRaises(ValueError):
+            gml.write_r2b({'ALA'}, 'sugar', os.path.join(self.tmpdir, 'x.r2b'))
+
+    def test_protein_legacy_name_aliases(self):
+        # pdb2gmx emits the legacy Gromacs names for the histidine tautomers,
+        # the disulfide-cystine pair and the deprotonated lysine; the table
+        # must map them onto the Amber residue names
+        rows = self._rows({'ALA', 'NALA', 'CALA', 'HID', 'NHID', 'CHID', 'HIE', 'NHIE',
+                           'CHIE', 'HIP', 'NHIP', 'CHIP', 'CYX', 'NCYX', 'CCYX', 'LYN'},
+                          'protein')
+        for expected in ('HISD\tHID\tNHID\tCHID\t-',
+                         'HISE\tHIE\tNHIE\tCHIE\t-',
+                         'HISH\tHIP\tNHIP\tCHIP\t-',
+                         'CYS2\tCYX\tNCYX\tCCYX\t-',
+                         'LYSN\tLYN\t-\t-\t-'):
+            self.assertIn(expected, rows)
+
+    def test_protein_legacy_name_aliases_target_absent(self):
+        # no alias row is emitted when the target residue is missing
+        rows = self._rows({'ALA', 'NALA', 'CALA'}, 'protein')
+        self.assertNotIn('HISD\tHID\tNHID\tCHID\t-', rows)
+        self.assertFalse([row for row in rows if row.split('\t')[0] in
+                          ('HISD', 'HISE', 'HISH', 'CYS2', 'LYSN')])
+
+
+class TestWriteRtpBondedTypes(unittest.TestCase):
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+
+    def tearDown(self):
+        shutil.rmtree(self.tmpdir)
+
+    def _header(self, ff):
+        atoms = {'ALA': [('N', 'N', -0.4, 1), ('H', 'H', 0.3, 2)]}
+        bonds = {'ALA': []}
+        connector = {'ALA': []}
+        outfile = os.path.join(self.tmpdir, f'{ff}.rtp')
+        with contextlib.redirect_stdout(io.StringIO()):
+            gml.write_rtp(atoms, bonds, connector, outfile, ff=ff)
+        with open(outfile) as infile:
+            return infile.read().splitlines()[1]
+
+    def test_amber_residue_name_replacement(self):
+        # column 9 tells pdb2gmx to replace the residue names with the residue
+        # types, which the atomtype-residuetype cmap patterns depend on
+        self.assertEqual(self._header('amber'), '1 1 9 4 1 3 1 0 1')
+
+    def test_charmm_header_unchanged(self):
+        self.assertEqual(self._header('charmm'), '1 5 9 2 1 3 1 0')
+
+
+class TestAmber2gmFFBaseForceField(unittest.TestCase):
+    """How amber2gmFF behaves with and without an already converted base force field."""
+
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+        self.old_dir = os.getcwd()
+        self.dat = os.path.join(self.tmpdir, 'testff.dat')
+        with open(self.dat, 'w') as out:
+            out.write(DAT)
+        self.lib = os.path.join(self.tmpdir, 'testffh.lib')
+        with open(self.lib, 'w') as out:
+            out.write(LIB_H)
+        self.leaprc = os.path.join(self.tmpdir, 'testffh.leaprc')
+        with open(self.leaprc, 'w') as out:
+            out.write(LEAPRC_RES_H)
+
+    def tearDown(self):
+        os.chdir(self.old_dir)
+        shutil.rmtree(self.tmpdir)
+
+    def test_without_base_ff(self):
+        outdir = os.path.join(self.tmpdir, 'out')
+        stdout = io.StringIO()
+        try:
+            with contextlib.redirect_stdout(stdout):
+                gml.amber2gmxFF(self.leaprc, outdir, base_ff=None)
+        finally:
+            os.chdir(self.old_dir)
+        self.assertIn('No base force field used', stdout.getvalue())
+        ffd = outdir + '.ff'
+        # solvent models are not copied, but everything derivable is generated
+        self.assertFalse(os.path.exists(os.path.join(ffd, 'spc.itp')))
+        self.assertEqual(glob.glob(os.path.join(ffd, 'tip*')), [])
+        with open(os.path.join(ffd, 'aminoacids.hdb')) as infile:
+            self.assertIn('ZZA', infile.read())
+        # the fixture residue is not a standard building block, so no table is written
+        self.assertFalse(os.path.exists(os.path.join(ffd, 'aminoacids.r2b')))
+
+    def test_base_ff_files_are_copied_and_hdb_merged(self):
+        base = os.path.join(self.tmpdir, 'baseff.ff')
+        os.mkdir(base)
+        with open(os.path.join(base, 'spc.itp'), 'w') as out:
+            out.write('[ moleculetype ]\nSOL  1\n')
+        with open(os.path.join(base, 'aminoacids.hdb'), 'w') as out:
+            out.write('; base hydrogen database\nXXX\n2\t4\tH1\tC1\tC2\tC3\n')
+        outdir = os.path.join(self.tmpdir, 'out')
+        try:
+            with contextlib.redirect_stdout(io.StringIO()):
+                gml.amber2gmxFF(self.leaprc, outdir, base_ff=base)
+        finally:
+            os.chdir(self.old_dir)
+        ffd = outdir + '.ff'
+        self.assertTrue(os.path.exists(os.path.join(ffd, 'spc.itp')))
+        with open(os.path.join(ffd, 'aminoacids.hdb')) as infile:
+            hdb = infile.read()
+        # the base entries are kept and the generated ones appended
+        self.assertIn('XXX', hdb)
+        self.assertIn('ZZA', hdb)
+
+
+class TestWriteArn(unittest.TestCase):
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+
+    def tearDown(self):
+        shutil.rmtree(self.tmpdir)
+
+    def test_append_skips_known_pairs(self):
+        outfile = os.path.join(self.tmpdir, 'test.arn')
+        self.assertTrue(gml.write_arn({'ILE': {'HG13': 'HG11'}}, outfile))
+        self.assertTrue(gml.write_arn({**gml.legacy_input_renames,
+                                       'ILE': {**gml.legacy_input_renames['ILE'],
+                                               'HG13': 'HG13'}},
+                                      outfile, append=True))
+        with open(outfile) as infile:
+            lines = [line.split() for line in infile if not line.startswith(';')]
+        # the legacy table is added, the already known (ILE, HG13) pair is not repeated
+        self.assertEqual(lines.count(['ILE', 'CD', 'CD1']), 1)
+        self.assertEqual(lines.count(['ILE', 'HG13', 'HG11']), 1)
+        self.assertEqual(sum(1 for l in lines if l[0] == 'ILE'), 5)
+        # a second pass with the same data adds nothing
+        self.assertFalse(gml.write_arn(gml.legacy_input_renames, outfile, append=True))
+        with open(outfile) as infile:
+            self.assertEqual(len([line for line in infile if not line.startswith(';')]), len(lines))
diff --git a/tests/test_ffa.py b/tests/test_ffa.py
new file mode 100644
index 0000000..040fa9e
--- /dev/null
+++ b/tests/test_ffa.py
@@ -0,0 +1,1102 @@
+"""
+Tests for the Amber->Gromacs force field addon generation (amber2ffa).
+"""
+import contextlib
+import io
+import os
+import shutil
+import tempfile
+import unittest
+
+import gromologist as gml
+
+
+DAT = """TEST FF PARAMETERS
+Cg 12.01
+Oy 16.00
+CT 12.01
+H1 1.008
+C 12.01
+
+Cg-Oy    400.00     1.410
+Cg-CT    300.00     1.500
+
+Cg-Oy-Cg    100.00    112.00
+
+Cg-Oy-Cg-H1   1    0.30          0.0            -1.         SCEE=1.0 SCNB=1.0 comment
+              1    1.27          0.0            -2.         SCEE=1.0 SCNB=1.0
+              1    0.37          0.0             3.         SCEE=1.0 SCNB=1.0
+CT-H1-Cg-Oy   1    0.16          0.0             3.
+Cg-Oy-CT-H1   1    0.27          0.0             3.    SCEE=1.2 SCNB=2.0
+
+Cg-Oy-C-O   1   1.100       180.
+
+H1-Cg   0.0   2.2
+
+Cg 1.9000000 0.1094000
+Oy 1.6612000 0.2000000
+CT 1.9000000 0.1094000
+H1 1.3870000 0.0157000
+C 1.9000000 0.1200000
+"""
+
+LEAPRC = """# fake leaprc for tests
+loadamberparams testff.dat
+addAtomTypes {
+  { "Cg" "C" "sp2" }
+  { "Oy" "O" "sp2" }
+  { "CT" "C" "sp3" }
+  { "H1" "H" "1" }
+  { "C" "C" "sp2" }
+}
+"""
+
+LIB = """KOLMONORAMBER
+!entry.ZZZ.unit.atoms table  str name  str type  int typex  int resx  int flags  int seq  int elmnt  dbl chg
+ "C1" "Cg" 0 1 1 1 6 -0.050000
+ "C2" "Cg" 0 1 1 2 6 -0.050000
+!entry.ZZZ.unit.connect array int
+ 2
+!entry.ZZZ.unit.connectivity table  int atom1x  int atom2x  int flags
+ 1 2 1
+!entry.ZZ1.unit.atoms table  str name  str type  int typex  int resx  int flags  int seq  int elmnt  dbl chg
+ "ZZ" "Cg" 0 1 1 1 6 1.000000
+"""
+
+LEAPRC_RES = """# fake leaprc with a residue library
+loadamberparams testff.dat
+loadOff testff.lib
+"""
+
+
+class TestBondedParamInteractionType(unittest.TestCase):
+    def test_same_types_proper_and_improper_coexist(self):
+        # an amber parameter set may define the same atom types as a proper and
+        # as an improper dihedral; adding one must not replace the other
+        top = gml.Top(amber=True)
+        params = top.parameters
+        params.add_bonded_param(('Cg', 'Oy', 'Cg', 'H1'), [0.0, 10.0, 2], 9, action_default='r')
+        params.add_bonded_param(('Cg', 'Oy', 'Cg', 'H1'), [180.0, 4.6, 2], 4, action_default='r')
+        entries = [e for subs in params.subsections if subs.header == 'dihedraltypes'
+                   for e in subs.entries_param]
+        self.assertEqual(sorted(str(e.interaction_type) for e in entries), ['4', '9'])
+
+    def test_same_types_same_interaction_type_replaces(self):
+        # the reverse-order match and the replacement must still work within
+        # one interaction type
+        top = gml.Top(amber=True)
+        params = top.parameters
+        params.add_bonded_param(('Cg', 'Oy', 'Cg', 'H1'), [0.0, 10.0, 2], 9, action_default='r')
+        params.add_bonded_param(('H1', 'Cg', 'Oy', 'Cg'), [0.0, 20.0, 2], 9, action_default='r')
+        entries = [e for subs in params.subsections if subs.header == 'dihedraltypes'
+                   for e in subs.entries_param]
+        self.assertEqual(len(entries), 1)
+        self.assertEqual(entries[0].types, ('H1', 'Cg', 'Oy', 'Cg'))
+
+
+class TestAmber2ffa(unittest.TestCase):
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+        self.dat = os.path.join(self.tmpdir, 'testff.dat')
+        with open(self.dat, 'w') as out:
+            out.write(DAT)
+        self.leaprc = os.path.join(self.tmpdir, 'testff.leaprc')
+        with open(self.leaprc, 'w') as out:
+            out.write(LEAPRC)
+
+    def tearDown(self):
+        shutil.rmtree(self.tmpdir)
+
+    def test_extra_atomtypes(self):
+        # files contributing LJ of types not present in the main parameter file
+        extra = os.path.join(self.tmpdir, 'extra.dat')
+        with open(extra, 'w') as out:
+            # the .dat format separates blocks by a single blank line; ANGL, DIHE, IMPR, HBON are empty here
+            out.write('EXTRA PARAMETERS\nZz 30.00\n\nCg-Zz   100.0     1.500\n\n\n\n\n\n'
+                      'Zz 2.0000000 0.0500000\n')
+        outdir = os.path.join(self.tmpdir, 'out')
+        ffadir = gml.amber2ffa(self.leaprc, outdir, extra_atomtypes=extra)
+        with open(os.path.join(ffadir, 'atomtypes.atp')) as infile:
+            atp_names = [line.split()[0] for line in infile if line.strip() and not line.strip().startswith((';', '['))]
+        self.assertIn('Zz', atp_names)
+        with open(os.path.join(ffadir, 'ffnonbonded.itp')) as infile:
+            self.assertIn('Zz', infile.read())
+        extra2 = os.path.join(self.tmpdir, 'extra2.dat')
+        with open(extra2, 'w') as out:
+            out.write('EXTRA2 PARAMETERS\nYy 20.00\n\n\n\n\n\n\nYy 1.8000000 0.0300000\n')
+        ffadir2 = gml.amber2ffa(self.leaprc, os.path.join(self.tmpdir, 'out2'), extra_atomtypes=[extra, extra2])
+        with open(os.path.join(ffadir2, 'atomtypes.atp')) as infile:
+            atp2 = [line.split()[0] for line in infile
+                    if line.strip() and not line.strip().startswith((';', '['))]
+        self.assertIn('Zz', atp2)
+        self.assertIn('Yy', atp2)
+
+    def test_missing_atomtype_warning(self):
+        # a dihedral on a type without LJ anywhere must be reported and dropped,
+        # since grompp rejects parameter entries that reference undefined atom types
+        dat2 = DAT.replace('CT-H1-Cg-Oy   1', 'CT-H1-Cg-Nz   1')
+        with open(self.dat, 'w') as out:
+            out.write(dat2)
+        outdir = os.path.join(self.tmpdir, 'out')
+        stdout = io.StringIO()
+        with contextlib.redirect_stdout(stdout):
+            ffadir = gml.amber2ffa(self.leaprc, outdir)
+        self.assertRegex(stdout.getvalue(), r'WARNING.*Nz')
+        self.assertRegex(stdout.getvalue(), r'dropped \d+ bonded parameter entries')
+        for filename in os.listdir(ffadir):
+            with open(os.path.join(ffadir, filename)) as infile:
+                self.assertNotIn('Nz', infile.read())  # the referencing entries have been dropped
+
+    def test_amber2ffa(self):
+        outdir = os.path.join(self.tmpdir, 'out')
+        ffadir = gml.amber2ffa(self.leaprc, outdir, compatibility=['testff-99'])
+        self.assertTrue(ffadir.endswith('testff.ffa'))
+        with open(os.path.join(ffadir, 'compatibility.dat')) as infile:
+            self.assertEqual(infile.read().strip(), 'testff-99')
+        # the .atp file only carries the names and masses, as expected by pdb2gmx
+        with open(os.path.join(ffadir, 'atomtypes.atp')) as infile:
+            atp_lines = [line for line in infile if line.strip() and not line.strip().startswith((';', '['))]
+        self.assertEqual(len(atp_lines), 5)
+        self.assertIn('; name               mass', ''.join(
+            line for line in open(os.path.join(ffadir, 'atomtypes.atp')) if line.startswith(';')))
+        self.assertEqual(atp_lines[0].split(), ['Cg', '12.01000'])
+        # like a regular force field, the parameters live in ffnonbonded.itp/ffbonded.itp
+        with open(os.path.join(ffadir, 'ffnonbonded.itp')) as infile:
+            nonbonded = infile.read()
+        self.assertIn('[ atomtypes ]', nonbonded)
+        self.assertIn('[ atomtypes ]\n; name  at.num          mass    charge ptype          sigma   epsilon', nonbonded)
+        with open(os.path.join(ffadir, 'ffbonded.itp')) as infile:
+            bonded = infile.read()
+        for section in ('[ bondtypes ]', '[ angletypes ]', '[ dihedraltypes ]'):
+            self.assertIn(section, bonded)
+        self.assertIn('[ bondtypes ]\n;      i        j   func            b0            kb', bonded)
+        self.assertIn('[ angletypes ]\n;      i        j        k   func           th0           cth', bonded)
+        self.assertIn('[ dihedraltypes ]\n;      i        j        k        l   func         phase            kd     pn', bonded)
+        # the addon itp only declares the scaling and includes the parameter files
+        with open(os.path.join(ffadir, 'forcefield-addon.itp')) as infile:
+            text = infile.read()
+        self.assertNotIn('[ atomtypes ]', text)
+        self.assertIn('#include "ffnonbonded.itp"', text)
+        self.assertIn('#include "ffbonded.itp"', text)
+        self.assertIn('[ addon_scaling ]', text)
+        # grompp propagates [ addon_scaling ] and [ addon_priority ] into the files
+        # that a file includes, so they must be declared before the includes
+        self.assertLess(text.index('[ addon_priority ]'), text.index('#include "ffnonbonded.itp"'))
+        self.assertLess(text.index('[ addon_scaling ]'), text.index('#include "ffnonbonded.itp"'))
+        lines = text.splitlines()
+        self.assertEqual(lines[lines.index('[ addon_priority ]') + 1].strip(), '10')
+        addon_line = [line for line in lines if line.startswith('1 ')][0]
+        self.assertEqual(addon_line.split()[:5], ['1', '2', 'yes', '1.0000', '1.0000'])
+        self.assertIn('[ pair_scaling ]', text)
+        # grompp requires the atom types of a [ pair_scaling ] entry to be
+        # defined before the directive, so the section must follow the includes
+        self.assertLess(text.index('#include "ffbonded.itp"'), text.index('[ pair_scaling ]'))
+        pairs = {}
+        inside = False
+        for line in text.splitlines():
+            inside = line.strip() == '[ pair_scaling ]' or (inside and not line.strip().startswith('['))
+            if inside and line.strip() and not line.strip().startswith((';', '[', '#')):
+                cols = line.split()
+                self.assertEqual(len(cols), 6)
+                pairs[tuple(cols[:4])] = tuple(cols[4:])
+        self.assertEqual(pairs, {('CT', 'H1', 'Cg', 'Oy'): ('0.5000', '0.8333'),
+                                 ('Cg', 'Oy', 'CT', 'H1'): ('0.5000', '0.8333')})
+        # the generated parameter files should be parseable by gromologist itself; parameter sections are
+        # only recognized in a file starting with [ defaults ]
+        probe = gml.Top._from_text('[ defaults ]\n1 2 yes 0.5 0.8333\n' + nonbonded + bonded)
+        subsections = [sub.header for sub in probe.parameters.subsections]
+        for section in ('atomtypes', 'bondtypes', 'angletypes', 'dihedraltypes'):
+            self.assertIn(section, subsections)
+
+
+class TestAmber2ffaResidues(unittest.TestCase):
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+        with open(os.path.join(self.tmpdir, 'testff.dat'), 'w') as out:
+            out.write(DAT)
+        with open(os.path.join(self.tmpdir, 'testff.lib'), 'w') as out:
+            out.write(LIB)
+        self.leaprc = os.path.join(self.tmpdir, 'testff.leaprc')
+        with open(self.leaprc, 'w') as out:
+            out.write(LEAPRC_RES)
+
+    def tearDown(self):
+        shutil.rmtree(self.tmpdir)
+
+    def test_residue_files(self):
+        outdir = os.path.join(self.tmpdir, 'out')
+        stdout = io.StringIO()
+        with contextlib.redirect_stdout(stdout):
+            ffadir = gml.amber2ffa(self.leaprc, outdir)
+        # monatomic residues are ions of the nonbonded parameters, not .rtp entries
+        self.assertRegex(stdout.getvalue(), r'NOTE.*ZZ1')
+        with open(os.path.join(ffadir, 'other.rtp')) as infile:
+            rtp = infile.read()
+        self.assertIn('[ ZZZ ]', rtp)
+        self.assertIn('C1', rtp)
+        self.assertIn('Cg', rtp)
+        self.assertNotIn('ZZ1', rtp)
+        with open(os.path.join(ffadir, 'residuetypes.dat')) as infile:
+            types = [line.split() for line in infile if line.strip() and not line.startswith(';')]
+        self.assertIn(['ZZZ', 'Other'], types)
+        self.assertNotIn('ZZ1', [t[0] for t in types])
+        self.assertIn('residue files', stdout.getvalue())
+
+    def test_residues_disabled(self):
+        outdir = os.path.join(self.tmpdir, 'out')
+        ffadir = gml.amber2ffa(self.leaprc, outdir, residues=False)
+        self.assertFalse(os.path.exists(os.path.join(ffadir, 'other.rtp')))
+        self.assertFalse(os.path.exists(os.path.join(ffadir, 'residuetypes.dat')))
+        self.assertTrue(os.path.exists(os.path.join(ffadir, 'ffnonbonded.itp')))
+
+    def test_skip_residues(self):
+        outdir = os.path.join(self.tmpdir, 'out')
+        ffadir = gml.amber2ffa(self.leaprc, outdir, skip_residues=['ZZZ'])
+        self.assertFalse(os.path.exists(os.path.join(ffadir, 'other.rtp')))
+
+
+LIB_H = """TEST FF LIBRARY WITH HYDROGENS
+!entry.ZZA.unit.atoms table  str name  str type  int typex  int resx  int flags  int seq  int elmnt  dbl chg
+ "C1" "CT" 0 1 1 1 6 -0.100000
+ "C2" "CT" 0 1 1 2 6 -0.100000
+ "H1A" "H1" 0 1 1 3 1 0.050000
+ "H1B" "H1" 0 1 1 4 1 0.050000
+ "H21" "H1" 0 1 1 5 1 0.050000
+ "H22" "H1" 0 1 1 6 1 0.050000
+ "O3" "Oy" 0 1 1 7 8 -0.500000
+ "HO3" "H1" 0 1 1 8 1 0.400000
+!entry.ZZA.unit.connectivity table  int atom1x  int atom2x  int flags
+ 1 2 1
+ 1 3 1
+ 1 4 1
+ 2 5 1
+ 2 6 1
+ 2 7 1
+ 7 8 1
+"""
+
+LEAPRC_RES_H = """# fake leaprc with hydrogens
+loadamberparams testff.dat
+loadOff testffh.lib
+"""
+
+
+class TestRtpToHdb(unittest.TestCase):
+    def setUp(self):
+        # one residue exercising every supported hydrogen environment
+        self.atoms = {'SUG': [('C1', 'C', 0.1, 1), ('H1', 'H', 0.1, 2),
+                              ('C2', 'C', 0.1, 3), ('H21', 'H', 0.1, 4), ('H22', 'H', 0.1, 5),
+                              ('C3', 'C', 0.1, 6), ('H31', 'H', 0.1, 7), ('H32', 'H', 0.1, 8),
+                              ('H33', 'H', 0.1, 9),
+                              ('O4', 'O', 0.1, 10), ('HO4', 'H', 0.1, 11),
+                              ('N5', 'N', 0.1, 12), ('H51', 'H', 0.1, 13), ('H52', 'H', 0.1, 14),
+                              ('O7', 'O', 0.1, 15), ('H7', 'H', 0.1, 16), ('H8', 'H', 0.1, 17)]}
+        # C1: 1H + 3 heavy neighbours -> type 5; C2: 2H + 2 -> type 6; C3: methyl -> type 4;
+        # O4: hydroxyl -> type 2; N5: amide -> type 3; O7: two hydrogens on oxygen -> unsupported
+        self.bonds = {'SUG': [(1, 2), (1, 3), (1, 10), (1, 12),
+                              (3, 4), (3, 5), (3, 6),
+                              (6, 7), (6, 8), (6, 9),
+                              (10, 11), (12, 13), (12, 14), (15, 16), (15, 17)]}
+
+    def test_entries(self):
+        with contextlib.redirect_stdout(io.StringIO()):
+            hdb = gml.rtp_to_hdb(self.atoms, self.bonds)
+        self.assertEqual(list(hdb), ['SUG'])
+        self.assertEqual(hdb['SUG'],
+                         [(1, 5, 'H1', 'C1', 'C2', 'O4', 'N5'),
+                          (2, 6, 'H2', 'C2', 'C3', 'C1'),
+                          (3, 4, 'H3', 'C3', 'C2', 'C1'),
+                          (1, 2, 'HO4', 'O4', 'C1', 'C2'),
+                          (2, 3, 'H5', 'N5', 'C1', 'C2')])
+
+    def test_planar_methine_thiol_and_single_link_types(self):
+        # a carbon with one hydrogen and two heavy neighbours that carries an improper
+        # term is sp2 and uses the planar construction (type 1, as the shipped
+        # databases do for aromatic CH); the same environment without an improper term
+        # (an open valence) uses the single-hydrogen construction (type 2), as does a
+        # sulfhydryl hydrogen or a carbon hydrogen with a single heavy neighbour; the
+        # second control atom must not degenerate to the hydrogen-carrying atom itself
+        atoms = {'PLN': [('C1', 'C', 0.1, 1), ('H11', 'H', 0.1, 2),
+                         ('C2', 'C', 0.1, 3), ('C3', 'C', 0.1, 4),
+                         ('S4', 'S', 0.1, 5), ('HS4', 'H', 0.1, 6),
+                         ('C5', 'C', 0.1, 7), ('H51', 'H', 0.1, 8),
+                         ('C6', 'C', 0.1, 9),
+                         ('C7', 'C', 0.1, 10), ('H71', 'H', 0.1, 11),
+                         ('C8', 'C', 0.1, 12), ('C9', 'C', 0.1, 13)]}
+        bonds = {'PLN': [(1, 2), (1, 3), (1, 4), (4, 5), (5, 6), (3, 7), (7, 8), (4, 9),
+                         (10, 11), (10, 12), (10, 13)]}
+        impropers = {'PLN': [('C1', 'C2', 'C3', 'H11')]}
+        out = io.StringIO()
+        with contextlib.redirect_stdout(out):
+            hdb = gml.rtp_to_hdb(atoms, bonds, impropers)
+        self.assertEqual(out.getvalue(), '')
+        self.assertEqual(hdb['PLN'],
+                         [(1, 1, 'H11', 'C1', 'C2', 'C3'),
+                          (1, 2, 'HS4', 'S4', 'C3', 'C6'),
+                          (1, 2, 'H51', 'C5', 'C2', 'C1'),
+                          (1, 2, 'H71', 'C7', 'C8', 'C9')])
+
+    def test_unsupported_combination_warns_and_skips(self):
+        out = io.StringIO()
+        with contextlib.redirect_stdout(out):
+            hdb = gml.rtp_to_hdb(self.atoms, self.bonds)
+        self.assertNotIn('O7', [e[3] for e in hdb['SUG']])
+        self.assertIn('O7', out.getvalue())
+        self.assertIn('not supported', out.getvalue())
+
+    def test_write_hdb_format(self):
+        with contextlib.redirect_stdout(io.StringIO()):
+            hdb = gml.rtp_to_hdb(self.atoms, self.bonds)
+        tmpdir = tempfile.mkdtemp()
+        try:
+            path = os.path.join(tmpdir, 'test.hdb')
+            self.assertTrue(gml.write_hdb(hdb, path))
+            with open(path) as infile:
+                lines = infile.read().strip().split('\n')
+            self.assertEqual(lines[0], 'SUG\t5')
+            self.assertEqual(lines[1], '1\t5\tH1\tC1\tC2\tO4\tN5')
+            self.assertFalse(gml.write_hdb({}, os.path.join(tmpdir, 'none.hdb')))
+            self.assertFalse(os.path.exists(os.path.join(tmpdir, 'none.hdb')))
+        finally:
+            shutil.rmtree(tmpdir)
+
+
+class TestRenameHydrogens(unittest.TestCase):
+    def test_letter_suffixes_renamed(self):
+        atoms = {'SUG': [('C4', 'C', 0.1, 1), ('C5', 'C', 0.1, 2), ('H5E', 'H', 0.1, 3),
+                         ('H5A', 'H', 0.1, 4), ('O6', 'O', 0.1, 5), ('HO6', 'H', 0.1, 6)]}
+        bonds = {'SUG': [(1, 2), (2, 3), (2, 4), (1, 5), (5, 6)]}
+        impropers = {'SUG': [('C5', 'H5E', 'C4', 'O6')]}
+        out = io.StringIO()
+        with contextlib.redirect_stdout(out):
+            atoms, impropers, renames = gml.rename_hydrogens(atoms, bonds, impropers)
+        self.assertEqual(renames, {'SUG': {'H5E': 'H51', 'H5A': 'H52'}})
+        self.assertEqual([at[0] for at in atoms['SUG']], ['C4', 'C5', 'H51', 'H52', 'O6', 'HO6'])
+        self.assertEqual(impropers['SUG'], [('C5', 'H51', 'C4', 'O6')])
+        self.assertEqual(out.getvalue(), '')
+
+    def test_conflicting_names_skipped(self):
+        atoms = {'SUG': [('C5', 'C', 0.1, 1), ('H5E', 'H', 0.1, 2), ('H5A', 'H', 0.1, 3),
+                         ('H51', 'C', 0.1, 4)]}
+        bonds = {'SUG': [(1, 2), (1, 3)]}
+        out = io.StringIO()
+        with contextlib.redirect_stdout(out):
+            _, _, renames = gml.rename_hydrogens(atoms, bonds)
+        self.assertEqual(renames, {})
+        self.assertIn('name conflict', out.getvalue())
+
+    def test_conforming_names_untouched(self):
+        atoms = {'SUG': [('C6', 'C', 0.1, 1), ('H61', 'H', 0.1, 2), ('H62', 'H', 0.1, 3)]}
+        bonds = {'SUG': [(1, 2), (1, 3)]}
+        _, _, renames = gml.rename_hydrogens(atoms, bonds)
+        self.assertEqual(renames, {})
+        self.assertEqual([at[0] for at in atoms['SUG']], ['C6', 'H61', 'H62'])
+
+
+class TestAmber2ffaHydrogenData(unittest.TestCase):
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+        self.dat = os.path.join(self.tmpdir, 'testff.dat')
+        with open(self.dat, 'w') as out:
+            out.write(DAT)
+        self.lib = os.path.join(self.tmpdir, 'testffh.lib')
+        with open(self.lib, 'w') as out:
+            out.write(LIB_H)
+        self.leaprc = os.path.join(self.tmpdir, 'testffh.leaprc')
+        with open(self.leaprc, 'w') as out:
+            out.write(LEAPRC_RES_H)
+
+    def tearDown(self):
+        shutil.rmtree(self.tmpdir)
+
+    def test_hdb_and_arn_generated(self):
+        outdir = os.path.join(self.tmpdir, 'out')
+        ffadir = gml.amber2ffa(self.leaprc, outdir)
+        self.assertTrue(os.path.exists(os.path.join(ffadir, 'other.hdb')))
+        self.assertTrue(os.path.exists(os.path.join(ffadir, 'other.arn')))
+        with open(os.path.join(ffadir, 'other.rtp')) as infile:
+            rtp = infile.read()
+        # the letter-suffixed hydrogens were renamed in the rtp
+        self.assertNotIn('H1A', rtp)
+        self.assertIn('H11', rtp)
+        self.assertIn('H12', rtp)
+        # while the numeric-suffixed names are kept
+        self.assertIn('H21', rtp)
+        with open(os.path.join(ffadir, 'other.hdb')) as infile:
+            hdb = infile.read()
+        self.assertIn('ZZA\t3\n', hdb)
+        self.assertIn('2\t3\tH1\tC1\tC2\tO3', hdb)
+        self.assertIn('2\t6\tH2\tC2\tO3\tC1', hdb)
+        self.assertIn('1\t2\tHO3\tO3\tC2\tC1', hdb)
+        with open(os.path.join(ffadir, 'other.arn')) as infile:
+            arn = infile.read()
+        self.assertIn('ZZA      H1A       H11', arn)
+        self.assertIn('ZZA      H1B       H12', arn)
+
+
+
+RTP_BASE_FF = """; base ff residues
+[ bondedtypes ]
+1	1	1	0	0	0	0	0
+
+[ ALA ]
+N	0.320900	14.00670
+CA	0.049940	12.01070
+
+[ U ]
+P	1.000000	30.97376
+O1P	-0.500000	15.99940
+
+[ U4+ ]
+U	2.000000	238.02890
+"""
+
+
+class TestBaseResidueNames(unittest.TestCase):
+    """Only the residue topologies of the force field itself may block an addon
+    residue: the library-level residuetypes.dat lists all recognized names and the
+    monatomic .rtp entries are ions defined through the nonbonded parameters"""
+
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+        self.ffdir = os.path.join(self.tmpdir, 'base.ff')
+        os.makedirs(self.ffdir)
+        with open(os.path.join(self.ffdir, 'residues.rtp'), 'w') as out:
+            out.write(RTP_BASE_FF)
+        with open(os.path.join(self.ffdir, 'residuetypes.dat'), 'w') as out:
+            out.write('MG\tMetal\n')
+        # a library-level file must not leak into the names of the force field itself
+        with open(os.path.join(self.tmpdir, 'residuetypes.dat'), 'w') as out:
+            out.write('ZZ9\tOther\n')
+
+    def tearDown(self):
+        shutil.rmtree(self.tmpdir)
+
+    def test_names(self):
+        names = gml.Utils.base_residue_names(self.ffdir)
+        self.assertIn('ALA', names)
+        self.assertIn('U', names)
+        self.assertIn('MG', names)
+        self.assertNotIn('U4+', names)
+        self.assertNotIn('ZZ9', names)
+
+
+LIB_RNA = """TEST RNA LIBRARY
+!entry.U.unit.atoms table  str name  str type  int typex  int resx  int flags  int seq  int elmnt  dbl chg
+ "P"   "CT" 0 1 1 1 6  1.000000
+ "OP1" "Oy" 0 1 2 1 8 -0.500000
+ "OP2" "Oy" 0 1 3 1 8 -0.500000
+ "O5'" "Oy" 0 1 4 1 8 -0.500000
+ "C5'" "CT" 0 1 5 1 6  0.100000
+ "H5'" "H1" 0 1 6 1 1  0.050000
+ "H5''" "H1" 0 1 7 1 1  0.050000
+ "C4'" "CT" 0 1 8 1 6  0.100000
+ "O4'" "Oy" 0 1 9 1 8 -0.400000
+ "C1'" "CT" 0 1 10 1 6  0.300000
+ "H1'" "H1" 0 1 11 1 1  0.200000
+ "N1"  "C"  0 1 12 1 7 -0.400000
+ "C2"  "Cg" 0 1 13 1 6  0.700000
+ "O2"  "Oy" 0 1 14 1 8 -0.600000
+ "N3"  "C"  0 1 15 1 7 -0.400000
+ "H3"  "H1" 0 1 16 1 1  0.300000
+ "C4"  "Cg" 0 1 17 1 6  0.300000
+ "O4"  "Oy" 0 1 18 1 8 -0.600000
+ "C5"  "Cg" 0 1 19 1 6 -0.700000
+ "C6"  "Cg" 0 1 20 1 6  0.500000
+ "H6"  "H1" 0 1 21 1 1  0.200000
+!entry.U.unit.connectivity table  int atom1x  int atom2x  int flags
+ 1 2 1
+ 1 3 1
+ 1 4 1
+ 4 5 1
+ 5 6 1
+ 5 7 1
+ 5 8 1
+ 8 9 1
+ 8 10 1
+ 10 11 1
+ 10 12 1
+ 12 13 1
+ 13 14 1
+ 13 15 1
+ 15 16 1
+ 15 17 1
+ 17 18 1
+ 17 19 1
+ 19 20 1
+ 20 21 1
+!entry.PSU.unit.atoms table  str name  str type  int typex  int resx  int flags  int seq  int elmnt  dbl chg
+ "P"   "CT" 0 1 1 1 6  1.000000
+ "OP1" "Oy" 0 1 2 1 8 -0.500000
+ "O5'" "Oy" 0 1 3 1 8 -0.500000
+ "C5'" "CT" 0 1 4 1 6  0.100000
+ "C4'" "CT" 0 1 5 1 6  0.100000
+ "O4'" "Oy" 0 1 6 1 8 -0.400000
+ "C1'" "CT" 0 1 7 1 6  0.300000
+ "H1'" "H1" 0 1 8 1 1  0.200000
+!entry.PSU.unit.connectivity table  int atom1x  int atom2x  int flags
+ 1 2 1
+ 1 3 1
+ 3 4 1
+ 4 5 1
+ 5 6 1
+ 5 7 1
+ 7 8 1
+"""
+
+LEAPRC_RNA = """# fake leaprc with RNA residues
+loadamberparams testff.dat
+loadOff testffrna.lib
+"""
+
+
+class TestAmber2ffaNucleicResidues(unittest.TestCase):
+    """Standard bases map onto the R-prefixed building blocks known to pdb2gmx,
+    modified nucleotides are recognized by their ribose and keep their own names;
+    the legacy input atom names are provided through an .arn table"""
+
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+        with open(os.path.join(self.tmpdir, 'testff.dat'), 'w') as out:
+            out.write(DAT)
+        with open(os.path.join(self.tmpdir, 'testffrna.lib'), 'w') as out:
+            out.write(LIB_RNA)
+        self.leaprc = os.path.join(self.tmpdir, 'testff.leaprc')
+        with open(self.leaprc, 'w') as out:
+            out.write(LEAPRC_RNA)
+
+    def tearDown(self):
+        shutil.rmtree(self.tmpdir)
+
+    def test_rtp_building_blocks(self):
+        outdir = os.path.join(self.tmpdir, 'out')
+        with contextlib.redirect_stdout(io.StringIO()):
+            ffadir = gml.amber2ffa(self.leaprc, outdir)
+        with open(os.path.join(ffadir, 'rna.rtp')) as infile:
+            rtp = infile.read()
+        # the standard base becomes the R-prefixed building block, the modified one
+        # is recognized by its ribose and keeps its name
+        self.assertIn('[ RU ]', rtp)
+        self.assertIn('[ PSU ]', rtp)
+        self.assertNotIn('[ U ]', rtp)
+        # Amber phosphate and ribose names are translated to the Gromacs ones
+        self.assertIn('O1P', rtp)
+        self.assertIn("H5'2", rtp)
+
+    def test_r2b_and_arn(self):
+        outdir = os.path.join(self.tmpdir, 'out')
+        with contextlib.redirect_stdout(io.StringIO()):
+            ffadir = gml.amber2ffa(self.leaprc, outdir)
+        with open(os.path.join(ffadir, 'rna.r2b')) as infile:
+            rows = [line.split() for line in infile
+                    if line.strip() and not line.startswith(';')]
+        self.assertIn(['U', 'RU', '-', '-', '-'], rows)
+        self.assertNotIn('PSU', [row[0] for row in rows])
+        with open(os.path.join(ffadir, 'rna.arn')) as infile:
+            arn = infile.read()
+        # the type-keyed legacy renames apply to every nucleotide of the polymer
+        self.assertRegex(arn, r'(?m)^RNA\s+OP1\s+O1P$')
+        self.assertRegex(arn, r"(?m)^RNA\s+HO5'\s+H5T$")
+        self.assertRegex(arn, r"(?m)^RNA\s+H2''\s+H2'2$")
+        # the renames applied by fix_rtp are recorded per building block
+        self.assertRegex(arn, r'(?m)^RU\s+OP1\s+O1P$')
+        self.assertRegex(arn, r'(?m)^PSU\s+OP1\s+O1P$')
+        with open(os.path.join(ffadir, 'residuetypes.dat')) as infile:
+            types = [line.split() for line in infile
+                     if line.strip() and not line.startswith(';')]
+        self.assertIn(['PSU', 'RNA'], types)
+
+    def test_fix_rtp_standard_bases_only(self):
+        atoms = {'A': [('N1', 'C', 0.0, 1)],
+                 'U3': [("C1'", 'CT', 0.0, 1)],
+                 '1MA': [("C1'", 'CT', 0.0, 1)],
+                 'PSU': [('OP1', 'Oy', 0.0, 1)]}
+        result = gml.Utils.fix_rtp(atoms, rna=True)
+        self.assertIn('RA', result)
+        self.assertIn('RU3', result)
+        self.assertNotIn('A', result)
+        self.assertNotIn('U3', result)
+        # modified residues keep their own names
+        self.assertIn('1MA', result)
+        self.assertIn('PSU', result)
+        # the legacy Amber atom names of the modified residues are still translated
+        self.assertEqual([at[0] for at in result['PSU']], ['O1P'])
+
+
+LIB_DNA = """TEST DNA LIBRARY
+!entry.DA.unit.atoms table  str name  str type  int typex  int resx  int flags  int seq  int elmnt  dbl chg
+ "P"   "CT" 0 1 1 1 6  1.000000
+ "OP1" "Oy" 0 1 2 1 8 -0.500000
+ "OP2" "Oy" 0 1 3 1 8 -0.500000
+ "O5'" "Oy" 0 1 4 1 8 -0.400000
+ "C5'" "CT" 0 1 5 1 6  0.100000
+ "H5'" "H1" 0 1 6 1 1  0.050000
+ "H5''" "H1" 0 1 7 1 1  0.050000
+ "C4'" "CT" 0 1 8 1 6  0.100000
+ "O4'" "Oy" 0 1 9 1 8 -0.400000
+ "C3'" "CT" 0 1 10 1 6  0.100000
+ "O3'" "Oy" 0 1 11 1 8 -0.500000
+ "C2'" "CT" 0 1 12 1 6  0.100000
+ "H2'" "H1" 0 1 13 1 1  0.050000
+ "H2''" "H1" 0 1 14 1 1  0.050000
+ "C1'" "CT" 0 1 15 1 6  0.300000
+ "H1'" "H1" 0 1 16 1 1  0.200000
+ "N9"  "C"  0 1 17 1 7 -0.400000
+!entry.DA.unit.connectivity table  int atom1x  int atom2x  int flags
+ 1 2 1
+ 1 3 1
+ 1 4 1
+ 4 5 1
+ 5 6 1
+ 5 7 1
+ 5 8 1
+ 8 9 1
+ 8 10 1
+ 10 11 1
+ 10 12 1
+ 12 13 1
+ 12 14 1
+ 12 15 1
+ 15 9 1
+ 15 16 1
+ 15 17 1
+"""
+
+LEAPRC_DNA = """# fake leaprc with DNA residues
+loadamberparams testff.dat
+loadOff testffdna.lib
+"""
+
+
+class TestAmber2ffaDnaResidues(unittest.TestCase):
+    """DNA residues keep the Amber residue names known to pdb2gmx, but their legacy
+    atom names are translated to the names of the shipped fields just like for RNA"""
+
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+        with open(os.path.join(self.tmpdir, 'testff.dat'), 'w') as out:
+            out.write(DAT)
+        with open(os.path.join(self.tmpdir, 'testffdna.lib'), 'w') as out:
+            out.write(LIB_DNA)
+        self.leaprc = os.path.join(self.tmpdir, 'testff.leaprc')
+        with open(self.leaprc, 'w') as out:
+            out.write(LEAPRC_DNA)
+
+    def tearDown(self):
+        shutil.rmtree(self.tmpdir)
+
+    def test_dna_rtp_names(self):
+        outdir = os.path.join(self.tmpdir, 'out')
+        with contextlib.redirect_stdout(io.StringIO()):
+            ffadir = gml.amber2ffa(self.leaprc, outdir)
+        with open(os.path.join(ffadir, 'dna.rtp')) as infile:
+            rtp = infile.read()
+        # the DNA building blocks keep the names pdb2gmx knows
+        self.assertIn('[ DA ]', rtp)
+        self.assertNotIn('[ RDA ]', rtp)
+        # the legacy Amber atom names are translated as in the shipped fields
+        self.assertIn('O1P', rtp)
+        self.assertNotIn('OP1', rtp)
+        self.assertIn("H5'2", rtp)
+        self.assertIn("H2'2", rtp)
+        self.assertNotIn("H5''", rtp)
+
+    def test_dna_arn(self):
+        outdir = os.path.join(self.tmpdir, 'out')
+        with contextlib.redirect_stdout(io.StringIO()):
+            ffadir = gml.amber2ffa(self.leaprc, outdir)
+        with open(os.path.join(ffadir, 'dna.arn')) as infile:
+            arn = infile.read()
+        # the type-keyed legacy renames apply to every nucleotide of the polymer
+        self.assertRegex(arn, r"(?m)^DNA\s+OP1\s+O1P$")
+        self.assertRegex(arn, r"(?m)^DA\s+OP1\s+O1P$")
+        self.assertRegex(arn, r"(?m)^DNA\s+H2''\s+H2'2$")
+        with open(os.path.join(ffadir, 'residuetypes.dat')) as infile:
+            types = [line.split() for line in infile
+                     if line.strip() and not line.startswith(';')]
+        self.assertIn(['DA', 'DNA'], types)
+
+
+class TestAmber2ffaBondedDeduplication(unittest.TestCase):
+    """Bonded parameter blocks already defined by the base force field (or by an
+    earlier sibling addon, when base_ff is a list) must not be repeated by the
+    addon: grompp rejects duplicate dihedral blocks and the first definition
+    wins anyway"""
+
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+        with open(os.path.join(self.tmpdir, 'testff.dat'), 'w') as out:
+            out.write(DAT)
+        self.leaprc = os.path.join(self.tmpdir, 'testff.leaprc')
+        with open(self.leaprc, 'w') as out:
+            out.write(LEAPRC)
+        # a generated addon serving as the base force field
+        with contextlib.redirect_stdout(io.StringIO()):
+            self.base_ffa = gml.amber2ffa(self.leaprc, os.path.join(self.tmpdir, 'first'))
+
+    def tearDown(self):
+        shutil.rmtree(self.tmpdir)
+
+    @staticmethod
+    def _entries(path, section):
+        entries, inside = [], False
+        with open(path) as infile:
+            for line in infile:
+                stripped = line.strip()
+                if stripped.startswith('['):
+                    inside = stripped == f'[ {section} ]'
+                    continue
+                if inside and stripped and not stripped.startswith((';', '#')):
+                    entries.append(tuple(stripped.split()[:2]))
+        return entries
+
+    def test_identical_and_conflicting_blocks(self):
+        basedir = os.path.join(self.tmpdir, 'base.ff')
+        os.makedirs(basedir)
+        shutil.copy(os.path.join(self.base_ffa, 'ffnonbonded.itp'), basedir)
+        # the base defines every block identically except the Cg-Oy bond, whose
+        # parameters differ: all of them must be dropped in favor of the base
+        bonded = open(os.path.join(self.base_ffa, 'ffbonded.itp')).read()
+        bonded = bonded.replace('334720.00', '400000.00')
+        with open(os.path.join(basedir, 'ffbonded.itp'), 'w') as out:
+            out.write(bonded)
+        stdout = io.StringIO()
+        with contextlib.redirect_stdout(stdout):
+            ffadir = gml.amber2ffa(self.leaprc, os.path.join(self.tmpdir, 'out'),
+                                   base_ff=os.path.join(basedir, 'ffnonbonded.itp'))
+        text = stdout.getvalue()
+        self.assertIn('identical to the base force field', text)
+        self.assertIn('the base parameters win', text)
+        self.assertIn('bondtypes Cg-Oy', text)
+        nonbonded_lines = open(os.path.join(ffadir, 'ffnonbonded.itp')).read().splitlines()
+        self.assertFalse([ln for ln in nonbonded_lines if ln.split()[:1] == ['Cg']])
+        new_bonded = open(os.path.join(ffadir, 'ffbonded.itp')).read()
+        self.assertNotIn('Cg', new_bonded)
+
+    def test_base_ff_list(self):
+        # base_ff accepts a list of sources; the atom types and bonded blocks of all
+        # of them count, with the first definition winning
+        basedir1 = os.path.join(self.tmpdir, 'base1.ff')
+        basedir2 = os.path.join(self.tmpdir, 'sibling.ffa')
+        os.makedirs(basedir1)
+        os.makedirs(basedir2)
+        nonbonded = open(os.path.join(self.base_ffa, 'ffnonbonded.itp')).read().splitlines()
+        header = [line for line in nonbonded
+                  if not line.split() or line.strip().startswith((';', '['))]
+        types = {line.split()[0]: line for line in nonbonded
+                 if line.split() and not line.strip().startswith((';', '['))}
+        with open(os.path.join(basedir1, 'ffnonbonded.itp'), 'w') as out:
+            out.write('\n'.join(header + [types['Cg'], types['Oy']]) + '\n')
+        with open(os.path.join(basedir2, 'ffnonbonded.itp'), 'w') as out:
+            out.write('\n'.join(header + [types['CT'], types['H1'], types['C']]) + '\n')
+        # the first source also defines the Cg-Oy bond with the same parameters
+        bond_line = [line for line in open(os.path.join(self.base_ffa, 'ffbonded.itp'))
+                     if line.split()[:2] == ['Cg', 'Oy']][0]
+        with open(os.path.join(basedir1, 'ffbonded.itp'), 'w') as out:
+            out.write('[ bondtypes ]\n' + bond_line)
+        stdout = io.StringIO()
+        with contextlib.redirect_stdout(stdout):
+            ffadir = gml.amber2ffa(self.leaprc, os.path.join(self.tmpdir, 'out'),
+                                   base_ff=[os.path.join(basedir1, 'ffnonbonded.itp'),
+                                            os.path.join(basedir2, 'ffnonbonded.itp')])
+        text = stdout.getvalue()
+        self.assertIn('Dropped 1 bonded parameter block(s) identical to the base force field',
+                      text)
+        self.assertNotIn('the base parameters win', text)
+        self.assertEqual(self._entries(os.path.join(ffadir, 'ffnonbonded.itp'), 'atomtypes'), [])
+        bonds = self._entries(os.path.join(ffadir, 'ffbonded.itp'), 'bondtypes')
+        self.assertNotIn(('Cg', 'Oy'), bonds)
+        self.assertIn(('Cg', 'CT'), bonds)
+
+    def _conflicting_base(self, dirname):
+        # a base force field identical to the generated addon except for the Cg
+        # Lennard-Jones epsilon, so that the Cg type definition conflicts
+        basedir = os.path.join(self.tmpdir, dirname)
+        os.makedirs(basedir)
+        nonbonded = open(os.path.join(self.base_ffa, 'ffnonbonded.itp')).read().splitlines()
+        inside = False
+        for i, line in enumerate(nonbonded):
+            stripped = line.strip()
+            if stripped.startswith('['):
+                inside = stripped == '[ atomtypes ]'
+                continue
+            if inside and line.split()[:1] == ['Cg']:
+                fields = line.split()
+                fields[-1] = '0.2000000e+00'
+                nonbonded[i] = ' '.join(fields)
+                break
+        else:
+            self.fail('Cg atom type not found in the generated addon')
+        with open(os.path.join(basedir, 'ffnonbonded.itp'), 'w') as out:
+            out.write('\n'.join(nonbonded) + '\n')
+        shutil.copy(os.path.join(self.base_ffa, 'ffbonded.itp'), basedir)
+        return basedir
+
+    def test_deduplicate_false_keeps_overlapping_entries(self):
+        # with deduplicate=False the entries that overlap with the base force
+        # field stay in the addon; grompp and pdb2gmx resolve them by priority
+        basedir = self._conflicting_base('base.ff')
+        stdout = io.StringIO()
+        with contextlib.redirect_stdout(stdout):
+            ffadir = gml.amber2ffa(self.leaprc, os.path.join(self.tmpdir, 'out'),
+                                   base_ff=os.path.join(basedir, 'ffnonbonded.itp'),
+                                   deduplicate=False)
+        text = stdout.getvalue()
+        self.assertIn('overrides the base parameters according to the addon priority', text)
+        self.assertNotIn('identical to the base force field', text)
+        self.assertNotIn('the base parameters win', text)
+        types = self._entries(os.path.join(ffadir, 'ffnonbonded.itp'), 'atomtypes')
+        self.assertIn('Cg', {entry[0] for entry in types})
+        bonds = self._entries(os.path.join(ffadir, 'ffbonded.itp'), 'bondtypes')
+        self.assertIn(('Cg', 'Oy'), bonds)
+        self.assertIn(('Cg', 'CT'), bonds)
+
+    def test_deduplicate_false_inherits_mass_from_base(self):
+        # an frcmod that uses a type without defining its mass must not zero out
+        # the base mass when the addon entry overrides the base definition
+        d2 = os.path.join(self.tmpdir, 'nomass')
+        os.makedirs(d2)
+        dat2 = '\n'.join(line for line in DAT.splitlines()
+                         if not (line.split()[:1] == ['H1'] and len(line.split()) == 2))
+        with open(os.path.join(d2, 'testff.dat'), 'w') as out:
+            out.write(dat2 + '\n')
+        with open(os.path.join(d2, 'testff.leaprc'), 'w') as out:
+            out.write(LEAPRC)
+        basedir = self._conflicting_base('basemass.ff')
+        stdout = io.StringIO()
+        with contextlib.redirect_stdout(stdout):
+            ffadir = gml.amber2ffa(os.path.join(d2, 'testff.leaprc'),
+                                   os.path.join(self.tmpdir, 'out'),
+                                   base_ff=os.path.join(basedir, 'ffnonbonded.itp'),
+                                   deduplicate=False)
+        lines = open(os.path.join(ffadir, 'ffnonbonded.itp')).read().splitlines()
+        h1 = [line for line in lines if line.split()[:1] == ['H1']]
+        self.assertEqual(len(h1), 1)
+        fields = h1[0].split()
+        self.assertAlmostEqual(float(fields[1]), 1.0)  # atomic number inherited
+        self.assertAlmostEqual(float(fields[2]), 1.008, places=3)  # mass inherited
+
+    def test_deduplicate_default_drops_conflicting_atom_type(self):
+        # by default a conflicting atom type is still dropped in favor of the base
+        basedir = self._conflicting_base('base.ff')
+        stdout = io.StringIO()
+        with contextlib.redirect_stdout(stdout):
+            ffadir = gml.amber2ffa(self.leaprc, os.path.join(self.tmpdir, 'out'),
+                                   base_ff=os.path.join(basedir, 'ffnonbonded.itp'))
+        text = stdout.getvalue()
+        self.assertIn('is dropped and the base force field parameters will be used', text)
+        # every type of the addon (including the non-conflicting CT) is dropped
+        # in favor of the base definition
+        types = self._entries(os.path.join(ffadir, 'ffnonbonded.itp'), 'atomtypes')
+        self.assertNotIn('Cg', {entry[0] for entry in types})
+        self.assertEqual({entry[0] for entry in types}, set())
+
+    def test_base_ff_directory(self):
+        # an absolute path of a force field or addon directory is accepted as
+        # base_ff and its ffnonbonded.itp is read
+        basedir = os.path.join(self.tmpdir, 'base.ff')
+        os.makedirs(basedir)
+        shutil.copy(os.path.join(self.base_ffa, 'ffnonbonded.itp'), basedir)
+        shutil.copy(os.path.join(self.base_ffa, 'ffbonded.itp'), basedir)
+        stdout = io.StringIO()
+        with contextlib.redirect_stdout(stdout):
+            ffadir = gml.amber2ffa(self.leaprc, os.path.join(self.tmpdir, 'out'),
+                                   base_ff=basedir)
+        self.assertIn('identical to the base force field', stdout.getvalue())
+        self.assertEqual(self._entries(os.path.join(ffadir, 'ffnonbonded.itp'), 'atomtypes'), [])
+        self.assertNotIn('Cg', open(os.path.join(ffadir, 'ffbonded.itp')).read())
+class TestAmber2ffaCmap(unittest.TestCase):
+    # CMAP corrections of the source parameters must be written to the addon as
+    # [ cmaptypes ] entries, and the residues provided by the addon must receive
+    # a backbone [ cmap ] block in their generated .rtp entries
+    FRCMOD = """Test frcmod with a CMAP correction
+MASS
+ CT 12.011
+ N 14.007
+ C 12.011
+ H1 1.008
+ O 16.00
+NONB
+ CT 1.9000000 0.1094000
+ N 1.8240000 0.1700000
+ C 1.9000000 0.1200000
+ H1 1.3870000 0.0157000
+ O 1.6612000 0.2000000
+CMAP
+%FLAG CMAP_COUNT   1
+%FLAG CMAP_TITLE
+XYZ CMAP
+%FLAG CMAP_RESLIST  1
+XYZ
+%FLAG CMAP_RESOLUTION 2
+%FLAG CMAP_PARAMETER
+  1.0   2.0
+  3.0   4.0
+"""
+
+    LIB = """KOLMONORAMBER
+!entry.XYZ.unit.atoms table  str name  str type  int typex  int resx  int flags  int seq  int elmnt  dbl chg
+ "N" "N" 0 1 83 1 7 -0.415700
+ "H" "H1" 0 1 8 2 1 0.271900
+ "CA" "CT" 0 1 83 3 6 -0.025200
+ "C" "C" 0 1 83 4 6 0.597300
+ "O" "O" 0 1 8 5 8 -0.567900
+!entry.XYZ.unit.connect array int
+ 4
+!entry.XYZ.unit.connectivity table  int atom1x  int atom2x  int flags
+ 1 2 1
+ 1 3 1
+ 3 4 1
+ 4 5 1
+"""
+
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+        self.frcmod = os.path.join(self.tmpdir, 'testff.frcmod')
+        with open(self.frcmod, 'w') as out:
+            out.write(self.FRCMOD)
+        lib = os.path.join(self.tmpdir, 'testff.lib')
+        with open(lib, 'w') as out:
+            out.write(self.LIB)
+        self.leaprc = os.path.join(self.tmpdir, 'testff.leaprc')
+        with open(self.leaprc, 'w') as out:
+            out.write('loadamberparams testff.frcmod\nloadOff testff.lib\n')
+
+    def tearDown(self):
+        shutil.rmtree(self.tmpdir)
+
+    def test_cmap_written_to_addon(self):
+        stdout = io.StringIO()
+        with contextlib.redirect_stdout(stdout):
+            ffadir = gml.amber2ffa(self.leaprc, os.path.join(self.tmpdir, 'out'))
+        self.assertNotIn('cannot be represented', stdout.getvalue())
+        bonded = open(os.path.join(ffadir, 'ffbonded.itp')).read()
+        self.assertIn('[ cmaptypes ]', bonded)
+        self.assertIn('C-* N-XYZ CT-XYZ C-XYZ N-* 1 2 2', bonded)
+        # the grid values are scaled from kcal/mol to kJ/mol
+        for value in ('4.184', '8.368', '12.552', '16.736'):
+            self.assertIn(value, bonded)
+
+    def test_cmap_block_in_rtp(self):
+        stdout = io.StringIO()
+        with contextlib.redirect_stdout(stdout):
+            ffadir = gml.amber2ffa(self.leaprc, os.path.join(self.tmpdir, 'out'))
+        # the CMAP residue carries the peptide N-CA-C backbone, so it is
+        # classified as a protein residue and lands in aminoacids.rtp
+        rtp = open(os.path.join(ffadir, 'aminoacids.rtp')).read()
+        self.assertIn('[ cmap ]', rtp)
+        self.assertTrue([line for line in rtp.splitlines()
+                         if line.split() == ['-C', 'N', 'CA', 'C', '+N']])
+
+    def test_cmap_excluded_residue_note(self):
+        # a CMAP residue already defined by the base force field is reported, but
+        # its correction grid is still written to the addon parameters
+        basedir = os.path.join(self.tmpdir, 'base.ff')
+        os.makedirs(basedir)
+        with open(os.path.join(basedir, 'ffnonbonded.itp'), 'w') as out:
+            out.write('[ atomtypes ]\nCT 12.01 0.0 A 0.19 0.1\n')
+        with open(os.path.join(basedir, 'residuetypes.dat'), 'w') as out:
+            out.write('XYZ  Protein\n')
+        stdout = io.StringIO()
+        with contextlib.redirect_stdout(stdout):
+            ffadir = gml.amber2ffa(self.leaprc, os.path.join(self.tmpdir, 'out'),
+                                   base_ff=basedir)
+        self.assertIn("CMAP corrections for residue(s) ['XYZ']", stdout.getvalue())
+        self.assertIn('C-* N-XYZ CT-XYZ C-XYZ N-* 1 2 2',
+                      open(os.path.join(ffadir, 'ffbonded.itp')).read())
+
+    def test_load_frcmod_without_pro_atoms(self):
+        # CMAP entries must not crash load_frcmod when no residue data is available
+        top = gml.Top(amber=True)
+        cmaps = gml.load_frcmod(top, self.frcmod, return_cmap=True)
+        self.assertEqual(len(cmaps), 1)
+        self.assertEqual(list(cmaps)[0][-1], 'XYZ')
+
+
+class TestAssignImpropers(unittest.TestCase):
+    """LEaP-style periodic improper generation for residues taken from .lib files."""
+
+    ATOMS = {'R': [('C2', 'C2', 0.0, 6), ('N1', 'N1', 0.0, 7),
+                   ('N3', 'N3', 0.0, 7), ('H2', 'H2', 0.0, 1)]}
+    BONDS = {'R': [(1, 2), (1, 3), (1, 4)]}
+
+    def test_specific_record(self):
+        result = gml.assign_impropers(self.ATOMS, self.BONDS, [('N1', 'N3', 'C2', 'H2')])
+        # the outer atoms are emitted in the canonical order of the matched record
+        self.assertEqual(result, {'R': [('H2', 'N1', 'C2', 'N3')]})
+
+    def test_wildcards_come_first(self):
+        self.assertEqual(gml.assign_impropers(self.ATOMS, self.BONDS, [('X', 'X', 'C2', 'H2')]),
+                         {'R': [('N1', 'N3', 'C2', 'H2')]})
+        self.assertEqual(gml.assign_impropers(self.ATOMS, self.BONDS, [('X', 'N3', 'C2', 'H2')]),
+                         {'R': [('N1', 'H2', 'C2', 'N3')]})
+
+    def test_most_specific_record_wins(self):
+        atoms = {'R': [('CA', 'CA', 0.0, 6), ('N', 'N', 0.0, 7),
+                       ('C', 'C', 0.0, 6), ('H', 'H1', 0.0, 1)]}
+        bonds = {'R': [(1, 2), (1, 3), (1, 4)]}
+        expected = {'R': [('H', 'C', 'CA', 'N')]}
+        for records in ([('X', 'X', 'CA', 'N'), ('X', 'C', 'CA', 'N')],
+                        [('X', 'C', 'CA', 'N'), ('X', 'X', 'CA', 'N')]):
+            self.assertEqual(gml.assign_impropers(atoms, bonds, records), expected)
+
+    def test_wildcard_central_type_never_matches(self):
+        self.assertEqual(gml.assign_impropers(self.ATOMS, self.BONDS,
+                                              [('N1', 'N3', 'X', 'H2')]), {})
+
+    def test_unmatched_triples_are_dropped(self):
+        self.assertEqual(gml.assign_impropers(self.ATOMS, self.BONDS,
+                                              [('C2', 'N3', 'H2', 'N1')]), {})
+
+
+class TestAmber2ffaImpropers(unittest.TestCase):
+    """[ impropers ] blocks generated from the improper records of the base force field."""
+
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+        with open(os.path.join(self.tmpdir, 'testff.dat'), 'w') as out:
+            out.write(DAT)
+        with open(os.path.join(self.tmpdir, 'testffh.lib'), 'w') as out:
+            out.write(LIB_H)
+        self.leaprc = os.path.join(self.tmpdir, 'testff.leaprc')
+        with open(self.leaprc, 'w') as out:
+            out.write(LEAPRC_RES_H)
+        self.basedir = os.path.join(self.tmpdir, 'base.ff')
+        os.makedirs(self.basedir)
+        with open(os.path.join(self.basedir, 'ffnonbonded.itp'), 'w') as out:
+            out.write('[ atomtypes ]\nCT 12.01 0.0 A 0.19 0.1\n'
+                      'H1 1.008 0.0 A 0.13 0.06\nOy 16.0 0.0 A 0.16 0.2\n')
+        with open(os.path.join(self.basedir, 'residuetypes.dat'), 'w') as out:
+            out.write('')
+
+    def tearDown(self):
+        shutil.rmtree(self.tmpdir)
+
+    def _generate(self, record):
+        with open(os.path.join(self.basedir, 'ffbonded.itp'), 'w') as out:
+            out.write(f'[ dihedraltypes ]\n{record}\n')
+        stdout = io.StringIO()
+        with contextlib.redirect_stdout(stdout):
+            ffadir = gml.amber2ffa(self.leaprc, os.path.join(self.tmpdir, 'out'),
+                                   base_ff=self.basedir)
+        with open(os.path.join(ffadir, 'other.rtp')) as infile:
+            return infile.read()
+
+    def test_base_ff_records_drive_generated_impropers(self):
+        # the improper records of the base force field apply to the addon residues
+        # as well, as in leap; the generated line matches the record positionally
+        rtp = self._generate('H1 H1 CT Oy    4    180.00000     0.50000     2')
+        self.assertIn(' [ impropers ]', rtp)
+        self.assertTrue([line for line in rtp.splitlines()
+                         if line.split() == ['H21', 'H22', 'C2', 'O3']])
+
+    def test_zero_k_base_record_skipped(self):
+        # zero force constant records exist in amber parameter sets only for the
+        # 1-4 exclusions they generate and are not canonically ordered; they must
+        # not drive the generation of the [ impropers ] blocks
+        rtp = self._generate('H1 H1 CT Oy    4    180.00000     0.00000     2')
+        self.assertNotIn('[ impropers ]', rtp)
+
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/tests/test_scaling.py b/tests/test_scaling.py
new file mode 100644
index 0000000..054c3f7
--- /dev/null
+++ b/tests/test_scaling.py
@@ -0,0 +1,138 @@
+"""
+Tests for per-torsion 1-4 scaling parsing in Amber parameter files (parse_scaling_tag,
+parse_frcmod).
+"""
+import os
+import shutil
+import tempfile
+import unittest
+
+import gromologist as gml
+
+
+DAT = """TEST FF PARAMETERS
+Cg 12.01
+Oy 16.00
+CT 12.01
+H1 1.008
+C 12.01
+
+Cg-Oy    400.00     1.410
+Cg-CT    300.00     1.500
+
+Cg-Oy-Cg    100.00    112.00
+
+Cg-Oy-Cg-H1   1    0.30          0.0            -1.         SCEE=1.0 SCNB=1.0 comment
+              1    1.27          0.0            -2.         SCEE=1.0 SCNB=1.0
+              1    0.37          0.0             3.         SCEE=1.0 SCNB=1.0
+CT-H1-Cg-Oy   1    0.16          0.0             3.
+Cg-Oy-CT-H1   1    0.27          0.0             3.    SCEE=1.2 SCNB=2.0
+
+Cg-Oy-C-O   1   1.100       180.
+
+H1-Cg   0.0   2.2
+
+Cg 1.9000000 0.1094000
+Oy 1.6612000 0.2000000
+CT 1.9000000 0.1094000
+H1 1.3870000 0.0157000
+C 1.9000000 0.1200000
+"""
+
+
+class TestScalingParsing(unittest.TestCase):
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+        self.dat = os.path.join(self.tmpdir, 'testff.dat')
+        with open(self.dat, 'w') as out:
+            out.write(DAT)
+
+    def tearDown(self):
+        shutil.rmtree(self.tmpdir)
+
+    def test_continuation_and_scaling(self):
+        *_, scaling = gml.Utils.parse_frcmod(self.dat, return_scaling=True)
+        self.assertNotIn(('',), scaling)
+        self.assertEqual(scaling[('Cg', 'Oy', 'Cg', 'H1')], [(1.0, 1.0)] * 3)
+        self.assertEqual(scaling[('CT', 'H1', 'Cg', 'Oy')], [(1.2, 2.0)])
+        self.assertEqual(scaling[('Cg', 'Oy', 'CT', 'H1')], [(1.2, 2.0)])
+
+    def test_continuation_types(self):
+        atomtypes, bondtypes, angtypes, dihtypes, imptypes, nonbonded, cmap = \
+            gml.Utils.parse_frcmod(self.dat)
+        self.assertNotIn(('',), dihtypes)
+        self.assertEqual(len(dihtypes[('Cg', 'Oy', 'Cg', 'H1')]), 9)  # three terms of three params
+        self.assertEqual(len(dihtypes[('CT', 'H1', 'Cg', 'Oy')]), 3)
+
+    def test_backwards_compatible(self):
+        result = gml.Utils.parse_frcmod(self.dat)
+        self.assertEqual(len(result), 7)
+
+
+if __name__ == '__main__':
+    unittest.main()
+
+SPACED_FRCMOD = """TEST FF PARAMETERS WITH SPACES AROUND THE DASHES
+
+MASS
+Cg 12.01
+Oy 16.00
+CQ 12.01
+N* 14.01
+H1 1.008
+
+BOND
+Cg - Oy    400.00     1.410
+CQ - N*    300.00     1.500
+
+ANGL
+Cg - Oy - Cg    100.00    112.00
+
+DIHE
+Cg - Oy - Cg - H1   1    0.30          0.0            -1.
+                    1    1.27          0.0            -2.
+N* - Cg - Oy - Cg   1    0.20          0.0             2.
+
+IMPR
+Cg - Oy - Cg - N*   75.000      180.000       2.
+
+NONB
+Cg 1.9000000 0.1094000
+Oy 1.6612000 0.2000000
+CQ 1.9000000 0.1094000
+N* 1.7000000 0.2000000
+H1 1.3870000 0.0157000
+"""
+
+
+class TestSpacedDashTypes(unittest.TestCase):
+    """Older frcmod files separate the atom type columns with spaced dashes
+    (e.g. 'CQ - N*'); the parser must not split the type names on those dashes"""
+
+    def setUp(self):
+        self.tmpdir = tempfile.mkdtemp()
+        self.frcmod = os.path.join(self.tmpdir, 'spaced.frcmod')
+        with open(self.frcmod, 'w') as out:
+            out.write(SPACED_FRCMOD)
+
+    def tearDown(self):
+        shutil.rmtree(self.tmpdir)
+
+    def test_spaced_dash_types(self):
+        atomtypes, bondtypes, angtypes, dihtypes, imptypes, nonbonded, cmap = \
+            gml.Utils.parse_frcmod(self.frcmod)
+        self.assertIn(('Cg', 'Oy'), bondtypes)
+        self.assertIn(('CQ', 'N*'), bondtypes)
+        self.assertEqual(bondtypes[('Cg', 'Oy')], [1.410 / 10, 400.00 * 200 * 4.184])
+        self.assertIn(('Cg', 'Oy', 'Cg'), angtypes)
+        self.assertEqual(angtypes[('Cg', 'Oy', 'Cg')], [112.00, 100.00 * 2 * 4.184])
+        # a continuation line with an extra term must attach to the spaced-dash types
+        self.assertIn(('Cg', 'Oy', 'Cg', 'H1'), dihtypes)
+        self.assertEqual(len(dihtypes[('Cg', 'Oy', 'Cg', 'H1')]), 6)
+        self.assertIn(('N*', 'Cg', 'Oy', 'Cg'), dihtypes)
+        self.assertIn(('Cg', 'Oy', 'Cg', 'N*'), imptypes)
+        for table in (bondtypes, angtypes, dihtypes, imptypes):
+            for types in table:
+                self.assertNotIn('', types)
+                for name in types:
+                    self.assertNotIn(' ', name)
