Remove unused thole polarization rfac parameter
[alexxy/gromacs.git] / src / gromacs / fileio / tpxio.cpp
index 61214f2aceef7e153345d7ba0334c95ac2438686..f8b0ced58defbeb726d921d29b5b9480923a4e01 100644 (file)
@@ -3,7 +3,8 @@
  *
  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
  * Copyright (c) 2001-2004, The GROMACS development team.
- * Copyright (c) 2013,2014,2015,2016,2017,2018,2019, by the GROMACS development team, led by
+ * Copyright (c) 2013,2014,2015,2016,2017 by the GROMACS development team.
+ * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by
  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
  * and including many others, as listed in the AUTHORS file in the
  * top-level source directory and at http://www.gromacs.org.
@@ -38,7 +39,7 @@
 
 /* This file is completely threadsafe - keep it that way! */
 
-#include "tpxio.h"
+#include "gromacs/fileio/tpxio.h"
 
 #include <cstdio>
 #include <cstdlib>
@@ -48,6 +49,7 @@
 #include <memory>
 #include <vector>
 
+#include "gromacs/applied_forces/awh/read_params.h"
 #include "gromacs/fileio/filetypes.h"
 #include "gromacs/fileio/gmxfio.h"
 #include "gromacs/fileio/gmxfio_xdr.h"
@@ -57,6 +59,7 @@
 #include "gromacs/mdtypes/awh_params.h"
 #include "gromacs/mdtypes/inputrec.h"
 #include "gromacs/mdtypes/md_enums.h"
+#include "gromacs/mdtypes/multipletimestepping.h"
 #include "gromacs/mdtypes/pull_params.h"
 #include "gromacs/mdtypes/state.h"
 #include "gromacs/pbcutil/boxutilities.h"
 #include "gromacs/utility/futil.h"
 #include "gromacs/utility/gmxassert.h"
 #include "gromacs/utility/inmemoryserializer.h"
+#include "gromacs/utility/iserializer.h"
 #include "gromacs/utility/keyvaluetreebuilder.h"
 #include "gromacs/utility/keyvaluetreeserializer.h"
 #include "gromacs/utility/smalloc.h"
 #include "gromacs/utility/snprintf.h"
 #include "gromacs/utility/txtdump.h"
 
-#define TPX_TAG_RELEASE  "release"
+#define TPX_TAG_RELEASE "release"
 
 /*! \brief Tag string for the file format written to run input files
  * written by this version of the code.
@@ -91,7 +95,7 @@
  * merging with mainstream GROMACS, set this tag string back to
  * TPX_TAG_RELEASE, and instead add an element to tpxv.
  */
-static const char *tpx_tag = TPX_TAG_RELEASE;
+static const std::string tpx_tag = TPX_TAG_RELEASE;
 
 /*! \brief Enum of values that describe the contents of a tpr file
  * whose format matches a version number
@@ -104,31 +108,40 @@ static const char *tpx_tag = TPX_TAG_RELEASE;
  */
 enum tpxv
 {
-    tpxv_ComputationalElectrophysiology = 96,                /**< support for ion/water position swaps (computational electrophysiology) */
-    tpxv_Use64BitRandomSeed,                                 /**< change ld_seed from int to int64_t */
+    tpxv_ComputationalElectrophysiology =
+            96, /**< support for ion/water position swaps (computational electrophysiology) */
+    tpxv_Use64BitRandomSeed, /**< change ld_seed from int to int64_t */
     tpxv_RestrictedBendingAndCombinedAngleTorsionPotentials, /**< potentials for supporting coarse-grained force fields */
-    tpxv_InteractiveMolecularDynamics,                       /**< interactive molecular dynamics (IMD) */
-    tpxv_RemoveObsoleteParameters1,                          /**< remove optimize_fft, dihre_fc, nstcheckpoint */
-    tpxv_PullCoordTypeGeom,                                  /**< add pull type and geometry per group and flat-bottom */
-    tpxv_PullGeomDirRel,                                     /**< add pull geometry direction-relative */
-    tpxv_IntermolecularBondeds,                              /**< permit inter-molecular bonded interactions in the topology */
-    tpxv_CompElWithSwapLayerOffset,                          /**< added parameters for improved CompEl setups */
-    tpxv_CompElPolyatomicIonsAndMultipleIonTypes,            /**< CompEl now can handle polyatomic ions and more than two types of ions */
-    tpxv_RemoveAdress,                                       /**< removed support for AdResS */
-    tpxv_PullCoordNGroup,                                    /**< add ngroup to pull coord */
-    tpxv_RemoveTwinRange,                                    /**< removed support for twin-range interactions */
-    tpxv_ReplacePullPrintCOM12,                              /**< Replaced print-com-1, 2 with pull-print-com */
-    tpxv_PullExternalPotential,                              /**< Added pull type external potential */
-    tpxv_GenericParamsForElectricField,                      /**< Introduced KeyValueTree and moved electric field parameters */
-    tpxv_AcceleratedWeightHistogram,                         /**< sampling with accelerated weight histogram method (AWH) */
-    tpxv_RemoveImplicitSolvation,                            /**< removed support for implicit solvation */
-    tpxv_PullPrevStepCOMAsReference,                         /**< Enabled using the COM of the pull group of the last frame as reference for PBC */
-    tpxv_MimicQMMM,                                          /**< Introduced support for MiMiC QM/MM interface */
-    tpxv_PullAverage,                                        /**< Added possibility to output average pull force and position */
-    tpxv_GenericInternalParameters,                          /**< Added internal parameters for mdrun modules*/
-    tpxv_VSite2FD,                                           /**< Added 2FD type virtual site */
-    tpxv_AddSizeField,                                       /**< Added field with information about the size of the serialized tpr file in bytes, excluding the header */
-    tpxv_Count                                               /**< the total number of tpxv versions */
+    tpxv_InteractiveMolecularDynamics, /**< interactive molecular dynamics (IMD) */
+    tpxv_RemoveObsoleteParameters1,    /**< remove optimize_fft, dihre_fc, nstcheckpoint */
+    tpxv_PullCoordTypeGeom,            /**< add pull type and geometry per group and flat-bottom */
+    tpxv_PullGeomDirRel,               /**< add pull geometry direction-relative */
+    tpxv_IntermolecularBondeds, /**< permit inter-molecular bonded interactions in the topology */
+    tpxv_CompElWithSwapLayerOffset, /**< added parameters for improved CompEl setups */
+    tpxv_CompElPolyatomicIonsAndMultipleIonTypes, /**< CompEl now can handle polyatomic ions and more than two types of ions */
+    tpxv_RemoveAdress,                            /**< removed support for AdResS */
+    tpxv_PullCoordNGroup,               /**< add ngroup to pull coord */
+    tpxv_RemoveTwinRange,               /**< removed support for twin-range interactions */
+    tpxv_ReplacePullPrintCOM12,         /**< Replaced print-com-1, 2 with pull-print-com */
+    tpxv_PullExternalPotential,         /**< Added pull type external potential */
+    tpxv_GenericParamsForElectricField, /**< Introduced KeyValueTree and moved electric field parameters */
+    tpxv_AcceleratedWeightHistogram, /**< sampling with accelerated weight histogram method (AWH) */
+    tpxv_RemoveImplicitSolvation,    /**< removed support for implicit solvation */
+    tpxv_PullPrevStepCOMAsReference, /**< Enabled using the COM of the pull group of the last frame as reference for PBC */
+    tpxv_MimicQMMM,   /**< Introduced support for MiMiC QM/MM interface */
+    tpxv_PullAverage, /**< Added possibility to output average pull force and position */
+    tpxv_GenericInternalParameters, /**< Added internal parameters for mdrun modules*/
+    tpxv_VSite2FD,                  /**< Added 2FD type virtual site */
+    tpxv_AddSizeField, /**< Added field with information about the size of the serialized tpr file in bytes, excluding the header */
+    tpxv_StoreNonBondedInteractionExclusionGroup, /**< Store the non bonded interaction exclusion group in the topology */
+    tpxv_VSite1,                                  /**< Added 1 type virtual site */
+    tpxv_MTS,                                     /**< Added multiple time stepping */
+    tpxv_RemovedConstantAcceleration, /**< Removed support for constant acceleration NEMD. */
+    tpxv_TransformationPullCoord,     /**< Support for transformation pull coordinates */
+    tpxv_SoftcoreGapsys,              /**< Added gapsys softcore function */
+    tpxv_ReaddedConstantAcceleration, /**< Re-added support for constant acceleration NEMD. */
+    tpxv_RemoveTholeRfac,             /**< Remove unused rfac parameter from thole listed force */
+    tpxv_Count                        /**< the total number of tpxv versions */
 };
 
 /*! \brief Version number of the file format written to run input
@@ -145,8 +158,13 @@ enum tpxv
 static const int tpx_version = tpxv_Count - 1;
 
 
-/* This number should only be increased when you edit the TOPOLOGY section
- * or the HEADER of the tpx format.
+/*! \brief
+ * Enum keeping track of incompatible changes for older TPR versions.
+ *
+ * The enum should be updated with a new field when editing the TOPOLOGY
+ * or HEADER of the tpx format. In particular, updating ftupd or
+ * changing the fields of TprHeaderVersion often trigger such needs.
+ *
  * This way we can maintain forward compatibility too for all analysis tools
  * and/or external programs that only need to know the atom/residue names,
  * charges, and bond connectivity.
@@ -157,10 +175,17 @@ static const int tpx_version = tpxv_Count - 1;
  *
  * In particular, it must be increased when adding new elements to
  * ftupd, so that old code can read new .tpr files.
- *
- * Updated for added field that contains the number of bytes of the tpr body, excluding the header.
  */
-static const int tpx_generation = 27;
+enum class TpxGeneration : int
+{
+    Initial = 26, //! First version is 26
+    AddSizeField, //! TPR header modified for writing as a block.
+    AddVSite1,    //! ftupd changed to include VSite1 type.
+    Count         //! Number of entries.
+};
+
+//! Value of Current TPR generation.
+static const int tpx_generation = static_cast<int>(TpxGeneration::Count) - 1;
 
 /* This number should be the most recent backwards incompatible version
  * I.e., if this number is 9, we cannot read tpx version 9 with this code.
@@ -168,9 +193,9 @@ static const int tpx_generation = 27;
 static const int tpx_incompatible_version = 57; // GMX4.0 has version 58
 
 
-
 /* Struct used to maintain tpx compatibility when function types are added */
-typedef struct {
+typedef struct
+{
     int fvnr;  /* file version number in which the function type first appeared */
     int ftype; /* function type */
 } t_ftupd;
@@ -188,62 +213,63 @@ typedef struct {
  * obsolete t_interaction_function types. Any data read from such
  * fields is discarded. Their names have _NOLONGERUSED appended to
  * them to make things clear.
+ *
+ * When adding to or making breaking changes to reading this struct,
+ * update TpxGeneration.
  */
 static const t_ftupd ftupd[] = {
-    { 70, F_RESTRBONDS        },
+    { 70, F_RESTRBONDS },
     { tpxv_RestrictedBendingAndCombinedAngleTorsionPotentials, F_RESTRANGLES },
-    { 76, F_LINEAR_ANGLES     },
+    { 76, F_LINEAR_ANGLES },
     { tpxv_RestrictedBendingAndCombinedAngleTorsionPotentials, F_RESTRDIHS },
     { tpxv_RestrictedBendingAndCombinedAngleTorsionPotentials, F_CBTDIHS },
-    { 65, F_CMAP              },
+    { 65, F_CMAP },
     { 60, F_GB12_NOLONGERUSED },
     { 61, F_GB13_NOLONGERUSED },
     { 61, F_GB14_NOLONGERUSED },
     { 72, F_GBPOL_NOLONGERUSED },
     { 72, F_NPSOLVATION_NOLONGERUSED },
-    { 93, F_LJ_RECIP          },
-    { 90, F_FBPOSRES          },
-    { 69, F_VTEMP_NOLONGERUSED},
-    { 66, F_PDISPCORR         },
-    { 76, F_ANHARM_POL        },
-    { 79, F_DVDL_COUL         },
-    { 79, F_DVDL_VDW,         },
-    { 79, F_DVDL_BONDED,      },
-    { 79, F_DVDL_RESTRAINT    },
-    { 79, F_DVDL_TEMPERATURE  },
-    { tpxv_GenericInternalParameters, F_DENSITYFITTING },
+    { 93, F_LJ_RECIP },
+    { 76, F_ANHARM_POL },
+    { 90, F_FBPOSRES },
+    { tpxv_VSite1, F_VSITE1 },
     { tpxv_VSite2FD, F_VSITE2FD },
+    { tpxv_GenericInternalParameters, F_DENSITYFITTING },
+    { 69, F_VTEMP_NOLONGERUSED },
+    { 66, F_PDISPCORR },
+    { 79, F_DVDL_COUL },
+    {
+            79,
+            F_DVDL_VDW,
+    },
+    {
+            79,
+            F_DVDL_BONDED,
+    },
+    { 79, F_DVDL_RESTRAINT },
+    { 79, F_DVDL_TEMPERATURE },
 };
 #define NFTUPD asize(ftupd)
 
-/* Needed for backward compatibility */
-#define MAXNODES 256
-
 /**************************************************************
  *
  * Now the higer level routines that do io of the structures and arrays
  *
  **************************************************************/
-static void do_pullgrp_tpx_pre95(gmx::ISerializer         *serializer,
-                                 t_pull_group             *pgrp,
-                                 t_pull_coord             *pcrd)
+static void do_pullgrp_tpx_pre95(gmx::ISerializer* serializer, t_pull_group* pgrp, t_pull_coord* pcrd)
 {
     rvec tmp;
 
-    serializer->doInt(&pgrp->nat);
-    if (serializer->reading())
-    {
-        snew(pgrp->ind, pgrp->nat);
-    }
-    serializer->doIntArray(pgrp->ind, pgrp->nat);
-    serializer->doInt(&pgrp->nweight);
-    if (serializer->reading())
-    {
-        snew(pgrp->weight, pgrp->nweight);
-    }
-    serializer->doRealArray(pgrp->weight, pgrp->nweight);
+    int numAtoms = pgrp->ind.size();
+    serializer->doInt(&numAtoms);
+    pgrp->ind.resize(numAtoms);
+    serializer->doIntArray(pgrp->ind.data(), numAtoms);
+    int numWeights = pgrp->weight.size();
+    serializer->doInt(&numWeights);
+    pgrp->weight.resize(numWeights);
+    serializer->doRealArray(pgrp->weight.data(), numWeights);
     serializer->doInt(&pgrp->pbcatom);
-    serializer->doRvec(&pcrd->vec);
+    serializer->doRvec(&pcrd->vec.as_vec());
     clear_rvec(pcrd->origin);
     serializer->doRvec(&tmp);
     pcrd->init = tmp[0];
@@ -252,68 +278,56 @@ static void do_pullgrp_tpx_pre95(gmx::ISerializer         *serializer,
     serializer->doReal(&pcrd->kB);
 }
 
-static void do_pull_group(gmx::ISerializer *serializer, t_pull_group *pgrp)
+static void do_pull_group(gmx::ISerializer* serializer, t_pull_group* pgrp)
 {
-    serializer->doInt(&pgrp->nat);
-    if (serializer->reading())
-    {
-        snew(pgrp->ind, pgrp->nat);
-    }
-    serializer->doIntArray(pgrp->ind, pgrp->nat);
-    serializer->doInt(&pgrp->nweight);
-    if (serializer->reading())
-    {
-        snew(pgrp->weight, pgrp->nweight);
-    }
-    serializer->doRealArray(pgrp->weight, pgrp->nweight);
+    int numAtoms = pgrp->ind.size();
+    serializer->doInt(&numAtoms);
+    pgrp->ind.resize(numAtoms);
+    serializer->doIntArray(pgrp->ind.data(), numAtoms);
+    int numWeights = pgrp->weight.size();
+    serializer->doInt(&numWeights);
+    pgrp->weight.resize(numWeights);
+    serializer->doRealArray(pgrp->weight.data(), numWeights);
     serializer->doInt(&pgrp->pbcatom);
 }
 
-static void do_pull_coord(gmx::ISerializer *serializer,
-                          t_pull_coord *pcrd,
-                          int file_version,
-                          int ePullOld, int eGeomOld, ivec dimOld)
+static void do_pull_coord(gmx::ISerializer* serializer,
+                          t_pull_coord*     pcrd,
+                          int               file_version,
+                          PullingAlgorithm  ePullOld,
+                          PullGroupGeometry eGeomOld,
+                          ivec              dimOld)
 {
     if (file_version >= tpxv_PullCoordNGroup)
     {
-        serializer->doInt(&pcrd->eType);
+        serializer->doEnumAsInt(&pcrd->eType);
         if (file_version >= tpxv_PullExternalPotential)
         {
-            if (pcrd->eType == epullEXTERNAL)
+            if (pcrd->eType == PullingAlgorithm::External)
             {
-                std::string buf;
-                if (serializer->reading())
-                {
-                    serializer->doString(&buf);
-                    pcrd->externalPotentialProvider = gmx_strdup(buf.c_str());
-                }
-                else
-                {
-                    buf = pcrd->externalPotentialProvider;
-                    serializer->doString(&buf);
-                }
+                serializer->doString(&pcrd->externalPotentialProvider);
             }
             else
             {
-                pcrd->externalPotentialProvider = nullptr;
+                pcrd->externalPotentialProvider.clear();
             }
         }
         else
         {
             if (serializer->reading())
             {
-                pcrd->externalPotentialProvider = nullptr;
+                pcrd->externalPotentialProvider.clear();
             }
         }
         /* Note that we try to support adding new geometries without
          * changing the tpx version. This requires checks when printing the
          * geometry string and a check and fatal_error in init_pull.
          */
-        serializer->doInt(&pcrd->eGeom);
+        serializer->doEnumAsInt(&pcrd->eGeom);
         serializer->doInt(&pcrd->ngroup);
         if (pcrd->ngroup <= c_pullCoordNgroupMax)
         {
-            serializer->doIntArray(pcrd->group, pcrd->ngroup);
+            serializer->doIntArray(pcrd->group.data(), pcrd->ngroup);
         }
         else
         {
@@ -322,14 +336,25 @@ static void do_pull_coord(gmx::ISerializer *serializer,
              * use the groups for this coord (checks in the pull and WHAM code
              * ensure this), we can ignore the groups and set ngroup=0.
              */
-            int *dum;
+            intdum;
             snew(dum, pcrd->ngroup);
             serializer->doIntArray(dum, pcrd->ngroup);
             sfree(dum);
 
             pcrd->ngroup = 0;
         }
-        serializer->doIvec(&pcrd->dim);
+        serializer->doIvec(&pcrd->dim.as_vec());
+        if (file_version >= tpxv_TransformationPullCoord)
+        {
+            serializer->doString(&pcrd->expression);
+        }
+        else
+        {
+            if (serializer->reading())
+            {
+                pcrd->expression.clear();
+            }
+        }
     }
     else
     {
@@ -338,15 +363,15 @@ static void do_pull_coord(gmx::ISerializer *serializer,
         serializer->doInt(&pcrd->group[1]);
         if (file_version >= tpxv_PullCoordTypeGeom)
         {
-            pcrd->ngroup = (pcrd->eGeom == epullgDIRRELATIVE ? 4 : 2);
-            serializer->doInt(&pcrd->eType);
-            serializer->doInt(&pcrd->eGeom);
+            pcrd->ngroup = (pcrd->eGeom == PullGroupGeometry::DirectionRelative ? 4 : 2);
+            serializer->doEnumAsInt(&pcrd->eType);
+            serializer->doEnumAsInt(&pcrd->eGeom);
             if (pcrd->ngroup == 4)
             {
                 serializer->doInt(&pcrd->group[2]);
                 serializer->doInt(&pcrd->group[3]);
             }
-            serializer->doIvec(&pcrd->dim);
+            serializer->doIvec(&pcrd->dim.as_vec());
         }
         else
         {
@@ -355,8 +380,8 @@ static void do_pull_coord(gmx::ISerializer *serializer,
             copy_ivec(dimOld, pcrd->dim);
         }
     }
-    serializer->doRvec(&pcrd->origin);
-    serializer->doRvec(&pcrd->vec);
+    serializer->doRvec(&pcrd->origin.as_vec());
+    serializer->doRvec(&pcrd->vec.as_vec());
     if (file_version >= tpxv_PullCoordTypeGeom)
     {
         serializer->doBool(&pcrd->bStart);
@@ -372,12 +397,9 @@ static void do_pull_coord(gmx::ISerializer *serializer,
     serializer->doReal(&pcrd->kB);
 }
 
-static void do_expandedvals(gmx::ISerializer         *serializer,
-                            t_expanded               *expand,
-                            t_lambda                 *fepvals,
-                            int                       file_version)
+static void do_expandedvals(gmx::ISerializer* serializer, t_expanded* expand, t_lambda* fepvals, int file_version)
 {
-    int      n_lambda = fepvals->n_lambda;
+    int n_lambda = fepvals->n_lambda;
 
     /* reset the lambda calculation window */
     fepvals->lambda_start_n = 0;
@@ -386,17 +408,14 @@ static void do_expandedvals(gmx::ISerializer         *serializer,
     {
         if (n_lambda > 0)
         {
-            if (serializer->reading())
-            {
-                snew(expand->init_lambda_weights, n_lambda);
-            }
-            serializer->doRealArray(expand->init_lambda_weights, n_lambda);
+            expand->init_lambda_weights.resize(n_lambda);
+            serializer->doRealArray(expand->init_lambda_weights.data(), n_lambda);
             serializer->doBool(&expand->bInit_weights);
         }
 
         serializer->doInt(&expand->nstexpanded);
-        serializer->doInt(&expand->elmcmove);
-        serializer->doInt(&expand->elamstats);
+        serializer->doEnumAsInt(&expand->elmcmove);
+        serializer->doEnumAsInt(&expand->elamstats);
         serializer->doInt(&expand->lmc_repeats);
         serializer->doInt(&expand->gibbsdeltalam);
         serializer->doInt(&expand->lmc_forced_nstart);
@@ -410,7 +429,7 @@ static void do_expandedvals(gmx::ISerializer         *serializer,
         serializer->doReal(&expand->wl_ratio);
         serializer->doReal(&expand->init_wl_delta);
         serializer->doBool(&expand->bWLoneovert);
-        serializer->doInt(&expand->elmceq);
+        serializer->doEnumAsInt(&expand->elmceq);
         serializer->doInt(&expand->equil_steps);
         serializer->doInt(&expand->equil_samples);
         serializer->doInt(&expand->equil_n_at_lam);
@@ -419,28 +438,25 @@ static void do_expandedvals(gmx::ISerializer         *serializer,
     }
 }
 
-static void do_simtempvals(gmx::ISerializer         *serializer,
-                           t_simtemp                *simtemp,
-                           int                       n_lambda,
-                           int                       file_version)
+static void do_simtempvals(gmx::ISerializer* serializer, t_simtemp* simtemp, int n_lambda, int file_version)
 {
     if (file_version >= 79)
     {
-        serializer->doInt(&simtemp->eSimTempScale);
+        serializer->doEnumAsInt(&simtemp->eSimTempScale);
         serializer->doReal(&simtemp->simtemp_high);
         serializer->doReal(&simtemp->simtemp_low);
         if (n_lambda > 0)
         {
             if (serializer->reading())
             {
-                snew(simtemp->temperatures, n_lambda);
+                simtemp->temperatures.resize(n_lambda);
             }
-            serializer->doRealArray(simtemp->temperatures, n_lambda);
+            serializer->doRealArray(simtemp->temperatures.data(), n_lambda);
         }
     }
 }
 
-static void do_imd(gmx::ISerializer *serializer, t_IMD *imd)
+static void do_imd(gmx::ISerializer* serializer, t_IMD* imd)
 {
     serializer->doInt(&imd->nat);
     if (serializer->reading())
@@ -450,13 +466,10 @@ static void do_imd(gmx::ISerializer *serializer, t_IMD *imd)
     serializer->doIntArray(imd->ind, imd->nat);
 }
 
-static void do_fepvals(gmx::ISerializer         *serializer,
-                       t_lambda                 *fepvals,
-                       int                       file_version)
+static void do_fepvals(gmx::ISerializer* serializer, t_lambda* fepvals, int file_version)
 {
     /* i is defined in the ndo_double macro; use g to iterate. */
-    int      g;
-    real     rdum;
+    real rdum;
 
     /* free energy values */
 
@@ -481,24 +494,17 @@ static void do_fepvals(gmx::ISerializer         *serializer,
     if (file_version >= 79)
     {
         serializer->doInt(&fepvals->n_lambda);
-        if (serializer->reading())
-        {
-            snew(fepvals->all_lambda, efptNR);
-        }
-        for (g = 0; g < efptNR; g++)
+        for (auto g : keysOf(fepvals->all_lambda))
         {
             if (fepvals->n_lambda > 0)
             {
-                if (serializer->reading())
-                {
-                    snew(fepvals->all_lambda[g], fepvals->n_lambda);
-                }
-                serializer->doDoubleArray(fepvals->all_lambda[g], fepvals->n_lambda);
-                serializer->doBoolArray(fepvals->separate_dvdl, efptNR);
+                fepvals->all_lambda[g].resize(fepvals->n_lambda);
+                serializer->doDoubleArray(fepvals->all_lambda[g].data(), fepvals->n_lambda);
+                serializer->doBoolArray(fepvals->separate_dvdl.begin(), fepvals->separate_dvdl.size());
             }
             else if (fepvals->init_lambda >= 0)
             {
-                fepvals->separate_dvdl[efptFEP] = TRUE;
+                fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Fep] = TRUE;
             }
         }
     }
@@ -507,37 +513,33 @@ static void do_fepvals(gmx::ISerializer         *serializer,
         serializer->doInt(&fepvals->n_lambda);
         if (serializer->reading())
         {
-            int g;
-
-            snew(fepvals->all_lambda, efptNR);
             /* still allocate the all_lambda array's contents. */
-            for (g = 0; g < efptNR; g++)
+            for (auto g : keysOf(fepvals->all_lambda))
             {
                 if (fepvals->n_lambda > 0)
                 {
-                    snew(fepvals->all_lambda[g], fepvals->n_lambda);
+                    fepvals->all_lambda[g].resize(fepvals->n_lambda);
                 }
             }
         }
-        serializer->doDoubleArray(fepvals->all_lambda[efptFEP], fepvals->n_lambda);
+        serializer->doDoubleArray(fepvals->all_lambda[FreeEnergyPerturbationCouplingType::Fep].data(),
+                                  fepvals->n_lambda);
         if (fepvals->init_lambda >= 0)
         {
-            int g, h;
-
-            fepvals->separate_dvdl[efptFEP] = TRUE;
+            fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Fep] = TRUE;
 
             if (serializer->reading())
             {
                 /* copy the contents of the efptFEP lambda component to all
                    the other components */
-                for (g = 0; g < efptNR; g++)
+                for (auto g : keysOf(fepvals->all_lambda))
                 {
-                    for (h = 0; h < fepvals->n_lambda; h++)
+                    for (int h = 0; h < fepvals->n_lambda; h++)
                     {
-                        if (g != efptFEP)
+                        if (g != FreeEnergyPerturbationCouplingType::Fep)
                         {
                             fepvals->all_lambda[g][h] =
-                                fepvals->all_lambda[efptFEP][h];
+                                    fepvals->all_lambda[FreeEnergyPerturbationCouplingType::Fep][h];
                         }
                     }
                 }
@@ -546,11 +548,10 @@ static void do_fepvals(gmx::ISerializer         *serializer,
     }
     else
     {
-        fepvals->n_lambda     = 0;
-        fepvals->all_lambda   = nullptr;
+        fepvals->n_lambda = 0;
         if (fepvals->init_lambda >= 0)
         {
-            fepvals->separate_dvdl[efptFEP] = TRUE;
+            fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Fep] = TRUE;
         }
     }
     serializer->doReal(&fepvals->sc_alpha);
@@ -563,6 +564,10 @@ static void do_fepvals(gmx::ISerializer         *serializer,
     {
         fepvals->sc_r_power = 6.0;
     }
+    if (fepvals->sc_r_power != 6.0)
+    {
+        gmx_fatal(FARGS, "sc-r-power=48 is no longer supported");
+    }
     serializer->doReal(&fepvals->sc_sigma);
     if (serializer->reading())
     {
@@ -594,13 +599,13 @@ static void do_fepvals(gmx::ISerializer         *serializer,
 
     if (file_version >= 73)
     {
-        serializer->doInt(&fepvals->separate_dhdl_file);
-        serializer->doInt(&fepvals->dhdl_derivatives);
+        serializer->doEnumAsInt(&fepvals->separate_dhdl_file);
+        serializer->doEnumAsInt(&fepvals->dhdl_derivatives);
     }
     else
     {
-        fepvals->separate_dhdl_file = esepdhdlfileYES;
-        fepvals->dhdl_derivatives   = edhdlderivativesYES;
+        fepvals->separate_dhdl_file = SeparateDhdlFile::Yes;
+        fepvals->dhdl_derivatives   = DhDlDerivativeCalculation::Yes;
     }
     if (file_version >= 71)
     {
@@ -614,24 +619,36 @@ static void do_fepvals(gmx::ISerializer         *serializer,
     }
     if (file_version >= 79)
     {
-        serializer->doInt(&fepvals->edHdLPrintEnergy);
+        serializer->doEnumAsInt(&fepvals->edHdLPrintEnergy);
     }
     else
     {
-        fepvals->edHdLPrintEnergy = edHdLPrintEnergyNO;
+        fepvals->edHdLPrintEnergy = FreeEnergyPrintEnergy::No;
+    }
+    if (file_version >= tpxv_SoftcoreGapsys)
+    {
+        serializer->doInt(reinterpret_cast<int*>(&fepvals->softcoreFunction));
+        serializer->doReal(&fepvals->scGapsysScaleLinpointLJ);
+        serializer->doReal(&fepvals->scGapsysScaleLinpointQ);
+        serializer->doReal(&fepvals->scGapsysSigmaLJ);
+    }
+    else
+    {
+        fepvals->softcoreFunction        = SoftcoreType::Beutler;
+        fepvals->scGapsysScaleLinpointLJ = 0.85;
+        fepvals->scGapsysScaleLinpointQ  = 0.3;
+        fepvals->scGapsysSigmaLJ         = 0.3;
     }
 
     /* handle lambda_neighbors */
     if ((file_version >= 83 && file_version < 90) || file_version >= 92)
     {
         serializer->doInt(&fepvals->lambda_neighbors);
-        if ( (fepvals->lambda_neighbors >= 0) && (fepvals->init_fep_state >= 0) &&
-             (fepvals->init_lambda < 0) )
+        if ((fepvals->lambda_neighbors >= 0) && (fepvals->init_fep_state >= 0)
+            && (fepvals->init_lambda < 0))
         {
-            fepvals->lambda_start_n = (fepvals->init_fep_state -
-                                       fepvals->lambda_neighbors);
-            fepvals->lambda_stop_n = (fepvals->init_fep_state +
-                                      fepvals->lambda_neighbors + 1);
+            fepvals->lambda_start_n = (fepvals->init_fep_state - fepvals->lambda_neighbors);
+            fepvals->lambda_stop_n  = (fepvals->init_fep_state + fepvals->lambda_neighbors + 1);
             if (fepvals->lambda_start_n < 0)
             {
                 fepvals->lambda_start_n = 0;
@@ -654,74 +671,11 @@ static void do_fepvals(gmx::ISerializer         *serializer,
     }
 }
 
-static void do_awhBias(gmx::ISerializer *serializer, gmx::AwhBiasParams *awhBiasParams,
-                       int gmx_unused file_version)
-{
-    serializer->doInt(&awhBiasParams->eTarget);
-    serializer->doDouble(&awhBiasParams->targetBetaScaling);
-    serializer->doDouble(&awhBiasParams->targetCutoff);
-    serializer->doInt(&awhBiasParams->eGrowth);
-    serializer->doInt(&awhBiasParams->bUserData);
-    serializer->doDouble(&awhBiasParams->errorInitial);
-    serializer->doInt(&awhBiasParams->ndim);
-    serializer->doInt(&awhBiasParams->shareGroup);
-    serializer->doBool(&awhBiasParams->equilibrateHistogram);
-
-    if (serializer->reading())
-    {
-        snew(awhBiasParams->dimParams, awhBiasParams->ndim);
-    }
-
-    for (int d = 0; d < awhBiasParams->ndim; d++)
-    {
-        gmx::AwhDimParams *dimParams = &awhBiasParams->dimParams[d];
-
-        serializer->doInt(&dimParams->eCoordProvider);
-        serializer->doInt(&dimParams->coordIndex);
-        serializer->doDouble(&dimParams->origin);
-        serializer->doDouble(&dimParams->end);
-        serializer->doDouble(&dimParams->period);
-        serializer->doDouble(&dimParams->forceConstant);
-        serializer->doDouble(&dimParams->diffusion);
-        serializer->doDouble(&dimParams->coordValueInit);
-        serializer->doDouble(&dimParams->coverDiameter);
-    }
-}
-
-static void do_awh(gmx::ISerializer         *serializer,
-                   gmx::AwhParams           *awhParams,
-                   int gmx_unused            file_version)
-{
-    serializer->doInt(&awhParams->numBias);
-    serializer->doInt(&awhParams->nstOut);
-    serializer->doInt64(&awhParams->seed);
-    serializer->doInt(&awhParams->nstSampleCoord);
-    serializer->doInt(&awhParams->numSamplesUpdateFreeEnergy);
-    serializer->doInt(&awhParams->ePotential);
-    serializer->doBool(&awhParams->shareBiasMultisim);
-
-    if (awhParams->numBias > 0)
-    {
-        if (serializer->reading())
-        {
-            snew(awhParams->awhBiasParams, awhParams->numBias);
-        }
-
-        for (int k = 0; k < awhParams->numBias; k++)
-        {
-            do_awhBias(serializer, &awhParams->awhBiasParams[k], file_version);
-        }
-    }
-}
-
-static void do_pull(gmx::ISerializer         *serializer,
-                    pull_params_t            *pull,
-                    int                       file_version,
-                    int                       ePullOld)
+static void do_pull(gmx::ISerializer* serializer, pull_params_t* pull, int file_version, PullingAlgorithm ePullOld)
 {
-    int  eGeomOld = -1;
-    ivec dimOld;
-    int  g;
+    PullGroupGeometry eGeomOld = PullGroupGeometry::Count;
+    ivec              dimOld;
+    int               g;
 
     if (file_version >= 95)
     {
@@ -736,7 +690,7 @@ static void do_pull(gmx::ISerializer         *serializer,
     {
         real dum;
 
-        serializer->doInt(&eGeomOld);
+        serializer->doEnumAsInt(&eGeomOld);
         serializer->doIvec(&dimOld);
         /* The inner cylinder radius, now removed */
         serializer->doReal(&dum);
@@ -775,35 +729,44 @@ static void do_pull(gmx::ISerializer         *serializer,
     {
         pull->bSetPbcRefToPrevStepCOM = FALSE;
     }
-    if (serializer->reading())
-    {
-        snew(pull->group, pull->ngroup);
-        snew(pull->coord, pull->ncoord);
-    }
+    pull->group.resize(pull->ngroup);
+    pull->coord.resize(pull->ncoord);
     if (file_version < 95)
     {
         /* epullgPOS for position pulling, before epullgDIRPBC was removed */
-        if (eGeomOld == epullgDIRPBC)
+        if (eGeomOld == PullGroupGeometry::DirectionPBC)
         {
             gmx_fatal(FARGS, "pull-geometry=position is no longer supported");
         }
-        if (eGeomOld > epullgDIRPBC)
+        if (eGeomOld > PullGroupGeometry::DirectionPBC)
         {
-            eGeomOld -= 1;
+            switch (eGeomOld)
+            {
+                case (PullGroupGeometry::DirectionRelative):
+                    eGeomOld = PullGroupGeometry::DirectionPBC;
+                    break;
+                case (PullGroupGeometry::Angle):
+                    eGeomOld = PullGroupGeometry::DirectionRelative;
+                    break;
+                case (PullGroupGeometry::Dihedral): eGeomOld = PullGroupGeometry::Angle; break;
+                case (PullGroupGeometry::AngleAxis): eGeomOld = PullGroupGeometry::Dihedral; break;
+                case (PullGroupGeometry::Count): eGeomOld = PullGroupGeometry::AngleAxis; break;
+                default: GMX_RELEASE_ASSERT(false, "Unhandled old pull type");
+            }
         }
 
         for (g = 0; g < pull->ngroup; g++)
         {
             /* We read and ignore a pull coordinate for group 0 */
-            do_pullgrp_tpx_pre95(serializer, &pull->group[g], &pull->coord[std::max(g-1, 0)]);
+            do_pullgrp_tpx_pre95(serializer, &pull->group[g], &pull->coord[std::max(g - 1, 0)]);
             if (g > 0)
             {
-                pull->coord[g-1].group[0] = 0;
-                pull->coord[g-1].group[1] = g;
+                pull->coord[g - 1].group[0] = 0;
+                pull->coord[g - 1].group[1] = g;
             }
         }
 
-        pull->bPrintCOM = (pull->group[0].nat > 0);
+        pull->bPrintCOM = (!pull->group[0].ind.empty());
     }
     else
     {
@@ -813,15 +776,18 @@ static void do_pull(gmx::ISerializer         *serializer,
         }
         for (g = 0; g < pull->ncoord; g++)
         {
-            do_pull_coord(serializer, &pull->coord[g],
-                          file_version, ePullOld, eGeomOld, dimOld);
+            do_pull_coord(serializer, &pull->coord[g], file_version, ePullOld, eGeomOld, dimOld);
+            if (serializer->reading())
+            {
+                pull->coord[g].coordIndex = g;
+            }
         }
     }
     if (file_version >= tpxv_PullAverage)
     {
         gmx_bool v;
 
-        v                  = pull->bXOutAverage;
+        v = pull->bXOutAverage;
         serializer->doBool(&v);
         pull->bXOutAverage = v;
         v                  = pull->bFOutAverage;
@@ -831,11 +797,20 @@ static void do_pull(gmx::ISerializer         *serializer,
 }
 
 
-static void do_rotgrp(gmx::ISerializer         *serializer,
-                      t_rotgrp                 *rotg)
+static void do_rotgrp(gmx::ISerializer* serializer, t_rotgrp* rotg)
 {
-    serializer->doInt(&rotg->eType);
-    serializer->doInt(&rotg->bMassW);
+    serializer->doEnumAsInt(&rotg->eType);
+    if (serializer->reading())
+    {
+        int temp = 0;
+        serializer->doInt(&temp);
+        rotg->bMassW = static_cast<bool>(temp);
+    }
+    else
+    {
+        int temp = static_cast<int>(rotg->bMassW);
+        serializer->doInt(&temp);
+    }
     serializer->doInt(&rotg->nat);
     if (serializer->reading())
     {
@@ -854,13 +829,12 @@ static void do_rotgrp(gmx::ISerializer         *serializer,
     serializer->doReal(&rotg->slab_dist);
     serializer->doReal(&rotg->min_gaussian);
     serializer->doReal(&rotg->eps);
-    serializer->doInt(&rotg->eFittype);
+    serializer->doEnumAsInt(&rotg->eFittype);
     serializer->doInt(&rotg->PotAngle_nstep);
     serializer->doReal(&rotg->PotAngle_step);
 }
 
-static void do_rot(gmx::ISerializer         *serializer,
-                   t_rot                    *rot)
+static void do_rot(gmx::ISerializer* serializer, t_rot* rot)
 {
     int g;
 
@@ -878,8 +852,7 @@ static void do_rot(gmx::ISerializer         *serializer,
 }
 
 
-static void do_swapgroup(gmx::ISerializer         *serializer,
-                         t_swapGroup              *g)
+static void do_swapgroup(gmx::ISerializer* serializer, t_swapGroup* g)
 {
 
     /* Name of the group or molecule */
@@ -906,19 +879,21 @@ static void do_swapgroup(gmx::ISerializer         *serializer,
     serializer->doIntArray(g->ind, g->nat);
 
     /* Requested counts for compartments A and B */
-    serializer->doIntArray(g->nmolReq, eCompNR);
+    serializer->doIntArray(g->nmolReq.data(), static_cast<int>(Compartment::Count));
 }
 
-static void do_swapcoords_tpx(gmx::ISerializer         *serializer,
-                              t_swapcoords             *swap,
-                              int                       file_version)
+static void do_swapcoords_tpx(gmx::ISerializer* serializer, t_swapcoords* swap, int file_version)
 {
     /* Enums for better readability of the code */
-    enum {
-        eCompA = 0, eCompB
+    enum
+    {
+        eCompA = 0,
+        eCompB
     };
-    enum {
-        eChannel0 = 0, eChannel1
+    enum
+    {
+        eChannel0 = 0,
+        eChannel1
     };
 
 
@@ -956,17 +931,18 @@ static void do_swapcoords_tpx(gmx::ISerializer         *serializer,
         swap->ngrp = 5;
         snew(swap->grp, swap->ngrp);
 
-        swap->grp[eGrpSplit0 ].molname = gmx_strdup("split0" );  // group 0: split0
-        swap->grp[eGrpSplit1 ].molname = gmx_strdup("split1" );  // group 1: split1
-        swap->grp[eGrpSolvent].molname = gmx_strdup("solvent");  // group 2: solvent
-        swap->grp[3          ].molname = gmx_strdup("anions" );  // group 3: anions
-        swap->grp[4          ].molname = gmx_strdup("cations");  // group 4: cations
+        swap->grp[static_cast<int>(SwapGroupSplittingType::Split0)].molname = gmx_strdup("split0"); // group 0: split0
+        swap->grp[static_cast<int>(SwapGroupSplittingType::Split1)].molname = gmx_strdup("split1"); // group 1: split1
+        swap->grp[static_cast<int>(SwapGroupSplittingType::Solvent)].molname =
+                gmx_strdup("solvent");                // group 2: solvent
+        swap->grp[3].molname = gmx_strdup("anions");  // group 3: anions
+        swap->grp[4].molname = gmx_strdup("cations"); // group 4: cations
 
         serializer->doInt(&swap->grp[3].nat);
-        serializer->doInt(&swap->grp[eGrpSolvent].nat);
-        serializer->doInt(&swap->grp[eGrpSplit0].nat);
+        serializer->doInt(&swap->grp[static_cast<int>(SwapGroupSplittingType::Solvent)].nat);
+        serializer->doInt(&swap->grp[static_cast<int>(SwapGroupSplittingType::Split0)].nat);
         serializer->doBool(&swap->massw_split[eChannel0]);
-        serializer->doInt(&swap->grp[eGrpSplit1].nat);
+        serializer->doInt(&swap->grp[static_cast<int>(SwapGroupSplittingType::Split1)].nat);
         serializer->doBool(&swap->massw_split[eChannel1]);
         serializer->doInt(&swap->nstswap);
         serializer->doInt(&swap->nAverage);
@@ -981,7 +957,10 @@ static void do_swapcoords_tpx(gmx::ISerializer         *serializer,
         // The order[] array keeps compatibility with older .tpr files
         // by reading in the groups in the classic order
         {
-            const int order[4] = {3, eGrpSolvent, eGrpSplit0, eGrpSplit1 };
+            const int order[4] = { 3,
+                                   static_cast<int>(SwapGroupSplittingType::Solvent),
+                                   static_cast<int>(SwapGroupSplittingType::Split0),
+                                   static_cast<int>(SwapGroupSplittingType::Split1) };
 
             for (int ig = 0; ig < 4; ig++)
             {
@@ -996,22 +975,21 @@ static void do_swapcoords_tpx(gmx::ISerializer         *serializer,
             serializer->doInt(&swap->grp[3].nmolReq[j]); // group 3 = anions
             serializer->doInt(&swap->grp[4].nmolReq[j]); // group 4 = cations
         }
-    }                                                    /* End support reading older CompEl .tpr files */
+    } /* End support reading older CompEl .tpr files */
 
     if (file_version >= tpxv_CompElWithSwapLayerOffset)
     {
         serializer->doReal(&swap->bulkOffset[eCompA]);
         serializer->doReal(&swap->bulkOffset[eCompB]);
     }
-
 }
 
-static void do_legacy_efield(gmx::ISerializer *serializer, gmx::KeyValueTreeObjectBuilder *root)
+static void do_legacy_efield(gmx::ISerializer* serializer, gmx::KeyValueTreeObjectBuilder* root)
 {
-    const char *const dimName[] = { "x", "y", "z" };
+    const charconst dimName[] = { "x", "y", "z" };
 
-    auto              appliedForcesObj = root->addObject("applied-forces");
-    auto              efieldObj        = appliedForcesObj.addObject("electric-field");
+    auto appliedForcesObj = root->addObject("applied-forces");
+    auto efieldObj        = appliedForcesObj.addObject("electric-field");
     // The content of the tpr file for this feature has
     // been the same since gromacs 4.0 that was used for
     // developing.
@@ -1020,16 +998,18 @@ static void do_legacy_efield(gmx::ISerializer *serializer, gmx::KeyValueTreeObje
         int n, nt;
         serializer->doInt(&n);
         serializer->doInt(&nt);
-        std::vector<real> aa(n+1), phi(nt+1), at(nt+1), phit(nt+1);
-        serializer->doRealArray(aa.data(),  n);
+        std::vector<real> aa(n + 1), phi(nt + 1), at(nt + 1), phit(nt + 1);
+        serializer->doRealArray(aa.data(), n);
         serializer->doRealArray(phi.data(), n);
-        serializer->doRealArray(at.data(),  nt);
+        serializer->doRealArray(at.data(), nt);
         serializer->doRealArray(phit.data(), nt);
         if (n > 0)
         {
             if (n > 1 || nt > 1)
             {
-                gmx_fatal(FARGS, "Can not handle tpr files with more than one electric field term per direction.");
+                gmx_fatal(FARGS,
+                          "Can not handle tpr files with more than one electric field term per "
+                          "direction.");
             }
             auto dimObj = efieldObj.addObject(dimName[j]);
             dimObj.addValue<real>("E0", aa[0]);
@@ -1041,9 +1021,7 @@ static void do_legacy_efield(gmx::ISerializer *serializer, gmx::KeyValueTreeObje
 }
 
 
-static void do_inputrec(gmx::ISerializer         *serializer,
-                        t_inputrec               *ir,
-                        int                       file_version)
+static void do_inputrec(gmx::ISerializer* serializer, t_inputrec* ir, int file_version)
 {
     int      i, j, k, idum = 0;
     real     rdum;
@@ -1052,8 +1030,7 @@ static void do_inputrec(gmx::ISerializer         *serializer,
     if (file_version != tpx_version)
     {
         /* Give a warning about features that are not accessible */
-        fprintf(stderr, "Note: file tpx version %d, software tpx version %d\n",
-                file_version, tpx_version);
+        fprintf(stderr, "Note: file tpx version %d, software tpx version %d\n", file_version, tpx_version);
     }
 
     if (file_version == 0)
@@ -1065,7 +1042,7 @@ static void do_inputrec(gmx::ISerializer         *serializer,
     gmx::KeyValueTreeObjectBuilder paramsObj = paramsBuilder.rootObject();
 
     /* Basic inputrec stuff */
-    serializer->doInt(&ir->eI);
+    serializer->doEnumAsInt(&ir->eI);
     if (file_version >= 62)
     {
         serializer->doInt64(&ir->nsteps);
@@ -1088,6 +1065,29 @@ static void do_inputrec(gmx::ISerializer         *serializer,
 
     serializer->doInt(&ir->simulation_part);
 
+    if (file_version >= tpxv_MTS)
+    {
+        serializer->doBool(&ir->useMts);
+        int numLevels = ir->mtsLevels.size();
+        if (ir->useMts)
+        {
+            serializer->doInt(&numLevels);
+        }
+        ir->mtsLevels.resize(numLevels);
+        for (auto& mtsLevel : ir->mtsLevels)
+        {
+            int forceGroups = mtsLevel.forceGroups.to_ulong();
+            serializer->doInt(&forceGroups);
+            mtsLevel.forceGroups = std::bitset<static_cast<int>(gmx::MtsForceGroups::Count)>(forceGroups);
+            serializer->doInt(&mtsLevel.stepFactor);
+        }
+    }
+    else
+    {
+        ir->useMts = false;
+        ir->mtsLevels.clear();
+    }
+
     if (file_version >= 67)
     {
         serializer->doInt(&ir->nstcalcenergy);
@@ -1098,15 +1098,21 @@ static void do_inputrec(gmx::ISerializer         *serializer,
     }
     if (file_version >= 81)
     {
-        serializer->doInt(&ir->cutoff_scheme);
+        serializer->doEnumAsInt(&ir->cutoff_scheme);
         if (file_version < 94)
         {
-            ir->cutoff_scheme = 1 - ir->cutoff_scheme;
+            // Need to invert the scheme order
+            switch (ir->cutoff_scheme)
+            {
+                case (CutoffScheme::Group): ir->cutoff_scheme = CutoffScheme::Verlet; break;
+                case (CutoffScheme::Verlet): ir->cutoff_scheme = CutoffScheme::Group; break;
+                default: GMX_RELEASE_ASSERT(false, "Unhandled cutoff scheme type");
+            }
         }
     }
     else
     {
-        ir->cutoff_scheme = ecutsGROUP;
+        ir->cutoff_scheme = CutoffScheme::Group;
     }
     serializer->doInt(&idum); /* used to be ns_type; not used anymore */
     serializer->doInt(&ir->nstlist);
@@ -1115,7 +1121,7 @@ static void do_inputrec(gmx::ISerializer         *serializer,
     serializer->doReal(&ir->rtpi);
 
     serializer->doInt(&ir->nstcomm);
-    serializer->doInt(&ir->comm_mode);
+    serializer->doEnumAsInt(&ir->comm_mode);
 
     /* ignore nstcheckpoint */
     if (file_version < tpxv_RemoveObsoleteParameters1)
@@ -1164,20 +1170,14 @@ static void do_inputrec(gmx::ISerializer         *serializer,
             real dummy_rlistlong = -1;
             serializer->doReal(&dummy_rlistlong);
 
-            if (ir->rlist > 0 && (dummy_rlistlong == 0 || dummy_rlistlong > ir->rlist))
-            {
-                // Get mdrun to issue an error (regardless of
-                // ir->cutoff_scheme).
-                ir->useTwinRange = true;
-            }
-            else
-            {
-                // grompp used to set rlistlong actively. Users were
-                // probably also confused and set rlistlong == rlist.
-                // However, in all remaining cases, it is safe to let
-                // mdrun proceed normally.
-                ir->useTwinRange = false;
-            }
+            ir->useTwinRange = (ir->rlist > 0 && (dummy_rlistlong == 0 || dummy_rlistlong > ir->rlist));
+            // When true, this forces mdrun to issue an error (regardless of
+            // ir->cutoff_scheme).
+            //
+            // Otherwise, grompp used to set rlistlong actively. Users
+            // were probably also confused and set rlistlong == rlist.
+            // However, in all remaining cases, it is safe to let
+            // mdrun proceed normally.
         }
     }
     else
@@ -1193,29 +1193,31 @@ static void do_inputrec(gmx::ISerializer         *serializer,
         int dummy_nstcalclr = -1;
         serializer->doInt(&dummy_nstcalclr);
     }
-    serializer->doInt(&ir->coulombtype);
+    serializer->doEnumAsInt(&ir->coulombtype);
     if (file_version >= 81)
     {
-        serializer->doInt(&ir->coulomb_modifier);
+        serializer->doEnumAsInt(&ir->coulomb_modifier);
     }
     else
     {
-        ir->coulomb_modifier = (ir->cutoff_scheme == ecutsVERLET ? eintmodPOTSHIFT : eintmodNONE);
+        ir->coulomb_modifier = (ir->cutoff_scheme == CutoffScheme::Verlet ? InteractionModifiers::PotShift
+                                                                          : InteractionModifiers::None);
     }
     serializer->doReal(&ir->rcoulomb_switch);
     serializer->doReal(&ir->rcoulomb);
-    serializer->doInt(&ir->vdwtype);
+    serializer->doEnumAsInt(&ir->vdwtype);
     if (file_version >= 81)
     {
-        serializer->doInt(&ir->vdw_modifier);
+        serializer->doEnumAsInt(&ir->vdw_modifier);
     }
     else
     {
-        ir->vdw_modifier = (ir->cutoff_scheme == ecutsVERLET ? eintmodPOTSHIFT : eintmodNONE);
+        ir->vdw_modifier = (ir->cutoff_scheme == CutoffScheme::Verlet ? InteractionModifiers::PotShift
+                                                                      : InteractionModifiers::None);
     }
     serializer->doReal(&ir->rvdw_switch);
     serializer->doReal(&ir->rvdw);
-    serializer->doInt(&ir->eDispCorr);
+    serializer->doEnumAsInt(&ir->eDispCorr);
     serializer->doReal(&ir->epsilon_r);
     serializer->doReal(&ir->epsilon_rf);
     serializer->doReal(&ir->tabext);
@@ -1274,7 +1276,7 @@ static void do_inputrec(gmx::ISerializer         *serializer,
     {
         ir->ewald_rtol_lj = ir->ewald_rtol;
     }
-    serializer->doInt(&ir->ewald_geometry);
+    serializer->doEnumAsInt(&ir->ewald_geometry);
     serializer->doReal(&ir->epsilon_surface);
 
     /* ignore bOptFFT */
@@ -1285,10 +1287,10 @@ static void do_inputrec(gmx::ISerializer         *serializer,
 
     if (file_version >= 93)
     {
-        serializer->doInt(&ir->ljpme_combination_rule);
+        serializer->doEnumAsInt(&ir->ljpme_combination_rule);
     }
     serializer->doBool(&ir->bContinuation);
-    serializer->doInt(&ir->etc);
+    serializer->doEnumAsInt(&ir->etc);
     /* before version 18, ir->etc was a gmx_bool (ir->btc),
      * but the values 0 and 1 still mean no and
      * berendsen temperature coupling, respectively.
@@ -1305,8 +1307,8 @@ static void do_inputrec(gmx::ISerializer         *serializer,
     {
         ir->nsttcouple = ir->nstcalcenergy;
     }
-    serializer->doInt(&ir->epc);
-    serializer->doInt(&ir->epct);
+    serializer->doEnumAsInt(&ir->epc);
+    serializer->doEnumAsInt(&ir->epct);
     if (file_version >= 71)
     {
         serializer->doInt(&ir->nstpcouple);
@@ -1322,7 +1324,7 @@ static void do_inputrec(gmx::ISerializer         *serializer,
     serializer->doRvec(&ir->compress[XX]);
     serializer->doRvec(&ir->compress[YY]);
     serializer->doRvec(&ir->compress[ZZ]);
-    serializer->doInt(&ir->refcoord_scaling);
+    serializer->doEnumAsInt(&ir->refcoord_scaling);
     serializer->doRvec(&ir->posres_com);
     serializer->doRvec(&ir->posres_comB);
 
@@ -1337,8 +1339,12 @@ static void do_inputrec(gmx::ISerializer         *serializer,
 
     serializer->doReal(&ir->shake_tol);
 
-    serializer->doInt(&ir->efep);
-    do_fepvals(serializer, ir->fepvals, file_version);
+    serializer->doEnumAsInt(&ir->efep);
+    if (serializer->reading())
+    {
+        ir->fepvals = std::make_unique<t_lambda>();
+    }
+    do_fepvals(serializer, ir->fepvals.get(), file_version);
 
     if (file_version >= 79)
     {
@@ -1354,28 +1360,28 @@ static void do_inputrec(gmx::ISerializer         *serializer,
     }
     if (ir->bSimTemp)
     {
-        do_simtempvals(serializer, ir->simtempvals, ir->fepvals->n_lambda, file_version);
+        if (serializer->reading())
+        {
+            ir->simtempvals = std::make_unique<t_simtemp>();
+        }
+        do_simtempvals(serializer, ir->simtempvals.get(), ir->fepvals->n_lambda, file_version);
     }
 
     if (file_version >= 79)
     {
         serializer->doBool(&ir->bExpanded);
-        if (ir->bExpanded)
-        {
-            ir->bExpanded = TRUE;
-        }
-        else
-        {
-            ir->bExpanded = FALSE;
-        }
     }
     if (ir->bExpanded)
     {
-        do_expandedvals(serializer, ir->expandedvals, ir->fepvals, file_version);
+        if (serializer->reading())
+        {
+            ir->expandedvals = std::make_unique<t_expanded>();
+        }
+        do_expandedvals(serializer, ir->expandedvals.get(), ir->fepvals.get(), file_version);
     }
 
-    serializer->doInt(&ir->eDisre);
-    serializer->doInt(&ir->eDisreWeighting);
+    serializer->doEnumAsInt(&ir->eDisre);
+    serializer->doEnumAsInt(&ir->eDisreWeighting);
     serializer->doBool(&ir->bDisreMixed);
     serializer->doReal(&ir->dr_fc);
     serializer->doReal(&ir->dr_tau);
@@ -1395,7 +1401,7 @@ static void do_inputrec(gmx::ISerializer         *serializer,
     serializer->doBool(&ir->bShakeSOR);
     serializer->doInt(&ir->niter);
     serializer->doReal(&ir->fc_stepsize);
-    serializer->doInt(&ir->eConstrAlg);
+    serializer->doEnumAsInt(&ir->eConstrAlg);
     serializer->doInt(&ir->nProjOrder);
     serializer->doReal(&ir->LincsWarnAngle);
     serializer->doInt(&ir->nLincsIter);
@@ -1466,7 +1472,7 @@ static void do_inputrec(gmx::ISerializer         *serializer,
 
     /* pull stuff */
     {
-        int ePullOld = 0;
+        PullingAlgorithm ePullOld = PullingAlgorithm::Umbrella;
 
         if (file_version >= tpxv_PullCoordTypeGeom)
         {
@@ -1474,18 +1480,36 @@ static void do_inputrec(gmx::ISerializer         *serializer,
         }
         else
         {
-            serializer->doInt(&ePullOld);
-            ir->bPull = (ePullOld > 0);
+            serializer->doEnumAsInt(&ePullOld);
+            ir->bPull = (ePullOld != PullingAlgorithm::Umbrella);
             /* We removed the first ePull=ePullNo for the enum */
-            ePullOld -= 1;
+            switch (ePullOld)
+            {
+                case (PullingAlgorithm::Umbrella): break; // this is equal to not using pulling
+                case (PullingAlgorithm::Constraint): ePullOld = PullingAlgorithm::Umbrella; break;
+                case (PullingAlgorithm::ConstantForce):
+                    ePullOld = PullingAlgorithm::Constraint;
+                    break;
+                case (PullingAlgorithm::FlatBottom):
+                    ePullOld = PullingAlgorithm::ConstantForce;
+                    break;
+                case (PullingAlgorithm::FlatBottomHigh):
+                    ePullOld = PullingAlgorithm::FlatBottom;
+                    break;
+                case (PullingAlgorithm::External):
+                    ePullOld = PullingAlgorithm::FlatBottomHigh;
+                    break;
+                case (PullingAlgorithm::Count): ePullOld = PullingAlgorithm::External; break;
+                default: GMX_RELEASE_ASSERT(false, "Unhandled old pull algorithm");
+            }
         }
         if (ir->bPull)
         {
             if (serializer->reading())
             {
-                snew(ir->pull, 1);
+                ir->pull = std::make_unique<pull_params_t>();
             }
-            do_pull(serializer, ir->pull, file_version, ePullOld);
+            do_pull(serializer, ir->pull.get(), file_version, ePullOld);
         }
     }
 
@@ -1497,9 +1521,12 @@ static void do_inputrec(gmx::ISerializer         *serializer,
         {
             if (serializer->reading())
             {
-                snew(ir->awhParams, 1);
+                ir->awhParams = std::make_unique<gmx::AwhParams>(serializer);
+            }
+            else
+            {
+                ir->awhParams->serialize(serializer);
             }
-            do_awh(serializer, ir->awhParams, file_version);
         }
     }
     else
@@ -1554,22 +1581,30 @@ static void do_inputrec(gmx::ISerializer         *serializer,
     {
         ir->opts.nhchainlength = 1;
     }
-    serializer->doInt(&ir->opts.ngacc);
+    if (serializer->reading() && file_version >= tpxv_RemovedConstantAcceleration
+        && file_version < tpxv_ReaddedConstantAcceleration)
+    {
+        ir->opts.ngacc = 0;
+    }
+    else
+    {
+        serializer->doInt(&ir->opts.ngacc);
+    }
     serializer->doInt(&ir->opts.ngfrz);
     serializer->doInt(&ir->opts.ngener);
 
     if (serializer->reading())
     {
-        snew(ir->opts.nrdf,   ir->opts.ngtc);
-        snew(ir->opts.ref_t,  ir->opts.ngtc);
+        snew(ir->opts.nrdf, ir->opts.ngtc);
+        snew(ir->opts.ref_t, ir->opts.ngtc);
         snew(ir->opts.annealing, ir->opts.ngtc);
         snew(ir->opts.anneal_npoints, ir->opts.ngtc);
         snew(ir->opts.anneal_time, ir->opts.ngtc);
         snew(ir->opts.anneal_temp, ir->opts.ngtc);
-        snew(ir->opts.tau_t,  ir->opts.ngtc);
+        snew(ir->opts.tau_t, ir->opts.ngtc);
         snew(ir->opts.nFreeze, ir->opts.ngfrz);
-        snew(ir->opts.acc,    ir->opts.ngacc);
-        snew(ir->opts.egp_flags, ir->opts.ngener*ir->opts.ngener);
+        snew(ir->opts.acceleration, ir->opts.ngacc);
+        snew(ir->opts.egp_flags, ir->opts.ngener * ir->opts.ngener);
     }
     if (ir->opts.ngtc > 0)
     {
@@ -1583,13 +1618,23 @@ static void do_inputrec(gmx::ISerializer         *serializer,
     }
     if (ir->opts.ngacc > 0)
     {
-        serializer->doRvecArray(ir->opts.acc, ir->opts.ngacc);
+        serializer->doRvecArray(ir->opts.acceleration, ir->opts.ngacc);
     }
-    serializer->doIntArray(ir->opts.egp_flags,
-                           ir->opts.ngener*ir->opts.ngener);
+    if (serializer->reading())
+    {
+        ir->useConstantAcceleration = false;
+        for (int g = 0; g < ir->opts.ngacc; g++)
+        {
+            if (norm2(ir->opts.acceleration[g]) != 0)
+            {
+                ir->useConstantAcceleration = true;
+            }
+        }
+    }
+    serializer->doIntArray(ir->opts.egp_flags, ir->opts.ngener * ir->opts.ngener);
 
     /* First read the lists with annealing and npoints for each group */
-    serializer->doIntArray(ir->opts.annealing, ir->opts.ngtc);
+    serializer->doEnumArrayAsInt(ir->opts.annealing, ir->opts.ngtc);
     serializer->doIntArray(ir->opts.anneal_npoints, ir->opts.ngtc);
     for (j = 0; j < (ir->opts.ngtc); j++)
     {
@@ -1605,7 +1650,7 @@ static void do_inputrec(gmx::ISerializer         *serializer,
     /* Walls */
     {
         serializer->doInt(&ir->nwall);
-        serializer->doInt(&ir->wall_type);
+        serializer->doEnumAsInt(&ir->wall_type);
         serializer->doReal(&ir->wall_r_linpot);
         serializer->doInt(&ir->wall_atomtype[0]);
         serializer->doInt(&ir->wall_atomtype[1]);
@@ -1623,8 +1668,8 @@ static void do_inputrec(gmx::ISerializer         *serializer,
     /* Swap ions */
     if (file_version >= tpxv_ComputationalElectrophysiology)
     {
-        serializer->doInt(&ir->eSwapCoords);
-        if (ir->eSwapCoords != eswapNO)
+        serializer->doEnumAsInt(&ir->eSwapCoords);
+        if (ir->eSwapCoords != SwapType::No)
         {
             if (serializer->reading())
             {
@@ -1634,43 +1679,43 @@ static void do_inputrec(gmx::ISerializer         *serializer,
         }
     }
 
-    /* QMMM stuff */
+    /* QMMM reading - despite defunct we require reading for backwards
+     * compability and correct serialization
+     */
     {
         serializer->doBool(&ir->bQMMM);
-        serializer->doInt(&ir->QMMMscheme);
-        serializer->doReal(&ir->scalefactor);
+        int qmmmScheme;
+        serializer->doInt(&qmmmScheme);
+        real unusedScalefactor;
+        serializer->doReal(&unusedScalefactor);
+
+        // this is still used in Mimic
         serializer->doInt(&ir->opts.ngQM);
-        if (serializer->reading())
-        {
-            snew(ir->opts.QMmethod,    ir->opts.ngQM);
-            snew(ir->opts.QMbasis,     ir->opts.ngQM);
-            snew(ir->opts.QMcharge,    ir->opts.ngQM);
-            snew(ir->opts.QMmult,      ir->opts.ngQM);
-            snew(ir->opts.bSH,         ir->opts.ngQM);
-            snew(ir->opts.CASorbitals, ir->opts.ngQM);
-            snew(ir->opts.CASelectrons, ir->opts.ngQM);
-            snew(ir->opts.SAon,        ir->opts.ngQM);
-            snew(ir->opts.SAoff,       ir->opts.ngQM);
-            snew(ir->opts.SAsteps,     ir->opts.ngQM);
-        }
         if (ir->opts.ngQM > 0 && ir->bQMMM)
         {
-            serializer->doIntArray(ir->opts.QMmethod, ir->opts.ngQM);
-            serializer->doIntArray(ir->opts.QMbasis, ir->opts.ngQM);
-            serializer->doIntArray(ir->opts.QMcharge, ir->opts.ngQM);
-            serializer->doIntArray(ir->opts.QMmult, ir->opts.ngQM);
-            serializer->doBoolArray(ir->opts.bSH, ir->opts.ngQM);
-            serializer->doIntArray(ir->opts.CASorbitals, ir->opts.ngQM);
-            serializer->doIntArray(ir->opts.CASelectrons, ir->opts.ngQM);
-            serializer->doRealArray(ir->opts.SAon, ir->opts.ngQM);
-            serializer->doRealArray(ir->opts.SAoff, ir->opts.ngQM);
-            serializer->doIntArray(ir->opts.SAsteps, ir->opts.ngQM);
             /* We leave in dummy i/o for removed parameters to avoid
-             * changing the tpr format for every QMMM change.
+             * changing the tpr format.
              */
-            std::vector<int> dummy(ir->opts.ngQM, 0);
-            serializer->doIntArray(dummy.data(), ir->opts.ngQM);
-            serializer->doIntArray(dummy.data(), ir->opts.ngQM);
+            std::vector<int> dummyIntVec(4 * ir->opts.ngQM, 0);
+            serializer->doIntArray(dummyIntVec.data(), dummyIntVec.size());
+            dummyIntVec.clear();
+
+            // std::vector<bool> has no data()
+            std::vector<char> dummyBoolVec(ir->opts.ngQM * sizeof(bool) / sizeof(char));
+            serializer->doBoolArray(reinterpret_cast<bool*>(dummyBoolVec.data()), dummyBoolVec.size());
+            dummyBoolVec.clear();
+
+            dummyIntVec.resize(2 * ir->opts.ngQM, 0);
+            serializer->doIntArray(dummyIntVec.data(), dummyIntVec.size());
+            dummyIntVec.clear();
+
+            std::vector<real> dummyRealVec(2 * ir->opts.ngQM, 0);
+            serializer->doRealArray(dummyRealVec.data(), dummyRealVec.size());
+            dummyRealVec.clear();
+
+            dummyIntVec.resize(3 * ir->opts.ngQM, 0);
+            serializer->doIntArray(dummyIntVec.data(), dummyIntVec.size());
+            dummyIntVec.clear();
         }
         /* end of QMMM stuff */
     }
@@ -1679,8 +1724,7 @@ static void do_inputrec(gmx::ISerializer         *serializer,
     {
         if (serializer->reading())
         {
-            paramsObj.mergeObject(
-                    gmx::deserializeKeyValueTree(serializer));
+            paramsObj.mergeObject(gmx::deserializeKeyValueTree(serializer));
         }
         else
         {
@@ -1700,7 +1744,8 @@ static void do_inputrec(gmx::ISerializer         *serializer,
     {
         if (serializer->reading())
         {
-            ir->internalParameters = std::make_unique<gmx::KeyValueTreeObject>(gmx::deserializeKeyValueTree(serializer));
+            ir->internalParameters =
+                    std::make_unique<gmx::KeyValueTreeObject>(gmx::deserializeKeyValueTree(serializer));
         }
         else
         {
@@ -1712,7 +1757,7 @@ static void do_inputrec(gmx::ISerializer         *serializer,
 }
 
 
-static void do_harm(gmx::ISerializer *serializer, t_iparams *iparams)
+static void do_harm(gmx::ISerializer* serializer, t_iparams* iparams)
 {
     serializer->doReal(&iparams->harmonic.rA);
     serializer->doReal(&iparams->harmonic.krA);
@@ -1720,13 +1765,10 @@ static void do_harm(gmx::ISerializer *serializer, t_iparams *iparams)
     serializer->doReal(&iparams->harmonic.krB);
 }
 
-static void do_iparams(gmx::ISerializer         *serializer,
-                       t_functype                ftype,
-                       t_iparams                *iparams,
-                       int                       file_version)
+static void do_iparams(gmx::ISerializer* serializer, t_functype ftype, t_iparams* iparams, int file_version)
 {
-    int      idum;
-    real     rdum;
+    int  idum;
+    real rdum;
 
     switch (ftype)
     {
@@ -1839,11 +1881,8 @@ static void do_iparams(gmx::ISerializer         *serializer,
             serializer->doReal(&iparams->cubic.kb);
             serializer->doReal(&iparams->cubic.kcub);
             break;
-        case F_CONNBONDS:
-            break;
-        case F_POLARIZATION:
-            serializer->doReal(&iparams->polarize.alpha);
-            break;
+        case F_CONNBONDS: break;
+        case F_POLARIZATION: serializer->doReal(&iparams->polarize.alpha); break;
         case F_ANHARM_POL:
             serializer->doReal(&iparams->anharm_polarize.alpha);
             serializer->doReal(&iparams->anharm_polarize.drcut);
@@ -1861,7 +1900,12 @@ static void do_iparams(gmx::ISerializer         *serializer,
             serializer->doReal(&iparams->thole.a);
             serializer->doReal(&iparams->thole.alpha1);
             serializer->doReal(&iparams->thole.alpha2);
-            serializer->doReal(&iparams->thole.rfac);
+            if (file_version < tpxv_RemoveTholeRfac)
+            {
+                real noRfac = 0;
+                serializer->doReal(&noRfac);
+            }
+
             break;
         case F_LJ:
             serializer->doReal(&iparams->lj.c6);
@@ -1950,13 +1994,9 @@ static void do_iparams(gmx::ISerializer         *serializer,
             serializer->doReal(&iparams->fbposres.r);
             serializer->doReal(&iparams->fbposres.k);
             break;
-        case F_CBTDIHS:
-            serializer->doRealArray(iparams->cbtdihs.cbtcA, NR_CBTDIHS);
-            break;
+        case F_CBTDIHS: serializer->doRealArray(iparams->cbtdihs.cbtcA, NR_CBTDIHS); break;
         case F_RBDIHS:
-            serializer->doRealArray(iparams->rbdihs.rbcA, NR_RBDIHS);
-            serializer->doRealArray(iparams->rbdihs.rbcB, NR_RBDIHS);
-            break;
+            // Fall-through intended
         case F_FOURDIHS:
             /* Fourier dihedrals are internally represented
              * as Ryckaert-Bellemans since those are faster to compute.
@@ -1973,10 +2013,9 @@ static void do_iparams(gmx::ISerializer         *serializer,
             serializer->doReal(&iparams->settle.doh);
             serializer->doReal(&iparams->settle.dhh);
             break;
+        case F_VSITE1: break; // VSite1 has 0 parameters
         case F_VSITE2:
-        case F_VSITE2FD:
-            serializer->doReal(&iparams->vsite.a);
-            break;
+        case F_VSITE2FD: serializer->doReal(&iparams->vsite.a); break;
         case F_VSITE3:
         case F_VSITE3FD:
         case F_VSITE3FAD:
@@ -2022,12 +2061,16 @@ static void do_iparams(gmx::ISerializer         *serializer,
             serializer->doInt(&iparams->cmap.cmapB);
             break;
         default:
-            gmx_fatal(FARGS, "unknown function type %d (%s) in %s line %d",
-                      ftype, interaction_function[ftype].name, __FILE__, __LINE__);
+            gmx_fatal(FARGS,
+                      "unknown function type %d (%s) in %s line %d",
+                      ftype,
+                      interaction_function[ftype].name,
+                      __FILE__,
+                      __LINE__);
     }
 }
 
-static void do_ilist(gmx::ISerializer *serializer, InteractionList *ilist)
+static void do_ilist(gmx::ISerializer* serializer, InteractionList* ilist)
 {
     int nr = ilist->size();
     serializer->doInt(&nr);
@@ -2038,9 +2081,7 @@ static void do_ilist(gmx::ISerializer *serializer, InteractionList *ilist)
     serializer->doIntArray(ilist->iatoms.data(), ilist->size());
 }
 
-static void do_ffparams(gmx::ISerializer         *serializer,
-                        gmx_ffparams_t           *ffparams,
-                        int                       file_version)
+static void do_ffparams(gmx::ISerializer* serializer, gmx_ffparams_t* ffparams, int file_version)
 {
     serializer->doInt(&ffparams->atnr);
     int numTypes = ffparams->numTypes();
@@ -2076,44 +2117,41 @@ static void do_ffparams(gmx::ISerializer         *serializer,
             for (int k = 0; k < NFTUPD; k++)
             {
                 /* Compare the read file_version to the update table */
-                if ((file_version < ftupd[k].fvnr) &&
-                    (ffparams->functype[i] >= ftupd[k].ftype))
+                if ((file_version < ftupd[k].fvnr) && (ffparams->functype[i] >= ftupd[k].ftype))
                 {
                     ffparams->functype[i] += 1;
                 }
             }
         }
 
-        do_iparams(serializer, ffparams->functype[i], &ffparams->iparams[i],
-                   file_version);
+        do_iparams(serializer, ffparams->functype[i], &ffparams->iparams[i], file_version);
     }
 }
 
-static void add_settle_atoms(InteractionList *ilist)
+static void add_settle_atoms(InteractionListilist)
 {
     int i;
 
     /* Settle used to only store the first atom: add the other two */
-    ilist->iatoms.resize(2*ilist->size());
-    for (i = ilist->size()/4 - 1; i >= 0; i--)
+    ilist->iatoms.resize(2 * ilist->size());
+    for (i = ilist->size() / 4 - 1; i >= 0; i--)
     {
-        ilist->iatoms[4*i+0] = ilist->iatoms[2*i+0];
-        ilist->iatoms[4*i+1] = ilist->iatoms[2*i+1];
-        ilist->iatoms[4*i+2] = ilist->iatoms[2*i+1] + 1;
-        ilist->iatoms[4*i+3] = ilist->iatoms[2*i+1] + 2;
+        ilist->iatoms[4 * i + 0] = ilist->iatoms[2 * i + 0];
+        ilist->iatoms[4 * i + 1] = ilist->iatoms[2 * i + 1];
+        ilist->iatoms[4 * i + 2] = ilist->iatoms[2 * i + 1] + 1;
+        ilist->iatoms[4 * i + 3] = ilist->iatoms[2 * i + 1] + 2;
     }
 }
 
-static void do_ilists(gmx::ISerializer         *serializer,
-                      InteractionLists         *ilists,
-                      int                       file_version)
+static void do_ilists(gmx::ISerializer* serializer, InteractionLists* ilists, int file_version)
 {
     GMX_RELEASE_ASSERT(ilists, "Need a valid ilists object");
-    GMX_RELEASE_ASSERT(ilists->size() == F_NRE, "The code needs to be in sync with InteractionLists");
+    GMX_RELEASE_ASSERT(ilists->size() == F_NRE,
+                       "The code needs to be in sync with InteractionLists");
 
     for (int j = 0; j < F_NRE; j++)
     {
-        InteractionList &ilist  = (*ilists)[j];
+        InteractionListilist  = (*ilists)[j];
         gmx_bool         bClear = FALSE;
         if (serializer->reading())
         {
@@ -2132,7 +2170,7 @@ static void do_ilists(gmx::ISerializer         *serializer,
         else
         {
             do_ilist(serializer, &ilist);
-            if (file_version < 78 && j == F_SETTLE && ilist.size() > 0)
+            if (file_version < 78 && j == F_SETTLE && !ilist.empty())
             {
                 add_settle_atoms(&ilist);
             }
@@ -2140,7 +2178,7 @@ static void do_ilists(gmx::ISerializer         *serializer,
     }
 }
 
-static void do_block(gmx::ISerializer *serializer, t_block *block)
+static void do_block(gmx::ISerializer* serializer, t_block* block)
 {
     serializer->doInt(&block->nr);
     if (serializer->reading())
@@ -2149,54 +2187,59 @@ static void do_block(gmx::ISerializer *serializer, t_block *block)
         {
             sfree(block->index);
         }
-        block->nalloc_index = block->nr+1;
+        block->nalloc_index = block->nr + 1;
         snew(block->index, block->nalloc_index);
     }
-    serializer->doIntArray(block->index, block->nr+1);
+    serializer->doIntArray(block->index, block->nr + 1);
 }
 
-static void do_blocka(gmx::ISerializer *serializer, t_blocka *block)
+static void doListOfLists(gmx::ISerializer* serializer, gmx::ListOfLists<int>* listOfLists)
 {
-    serializer->doInt(&block->nr);
-    serializer->doInt(&block->nra);
+    int numLists = listOfLists->ssize();
+    serializer->doInt(&numLists);
+    int numElements = listOfLists->elementsView().ssize();
+    serializer->doInt(&numElements);
     if (serializer->reading())
     {
-        block->nalloc_index = block->nr+1;
-        snew(block->index, block->nalloc_index);
-        block->nalloc_a = block->nra;
-        snew(block->a, block->nalloc_a);
+        std::vector<int> listRanges(numLists + 1);
+        serializer->doIntArray(listRanges.data(), numLists + 1);
+        std::vector<int> elements(numElements);
+        serializer->doIntArray(elements.data(), numElements);
+        *listOfLists = gmx::ListOfLists<int>(std::move(listRanges), std::move(elements));
+    }
+    else
+    {
+        serializer->doIntArray(const_cast<int*>(listOfLists->listRangesView().data()), numLists + 1);
+        serializer->doIntArray(const_cast<int*>(listOfLists->elementsView().data()), numElements);
     }
-    serializer->doIntArray(block->index, block->nr+1);
-    serializer->doIntArray(block->a, block->nra);
 }
 
 /* This is a primitive routine to make it possible to translate atomic numbers
  * to element names when reading TPR files, without making the Gromacs library
  * directory a dependency on mdrun (which is the case if we need elements.dat).
  */
-static const char *
-atomicnumber_to_element(int atomicnumber)
+static const char* atomicnumber_to_element(int atomicnumber)
 {
-    const char * p;
+    const char* p;
 
     /* This does not have to be complete, so we only include elements likely
      * to occur in PDB files.
      */
     switch (atomicnumber)
     {
-        case 1:  p = "H";  break;
-        case 5:  p = "B";  break;
-        case 6:  p = "C";  break;
-        case 7:  p = "N";  break;
-        case 8:  p = "O";  break;
-        case 9:  p = "F";  break;
+        case 1: p = "H"; break;
+        case 5: p = "B"; break;
+        case 6: p = "C"; break;
+        case 7: p = "N"; break;
+        case 8: p = "O"; break;
+        case 9: p = "F"; break;
         case 11: p = "Na"; break;
         case 12: p = "Mg"; break;
-        case 15: p = "P";  break;
-        case 16: p = "S";  break;
+        case 15: p = "P"; break;
+        case 16: p = "S"; break;
         case 17: p = "Cl"; break;
         case 18: p = "Ar"; break;
-        case 19: p = "K";  break;
+        case 19: p = "K"; break;
         case 20: p = "Ca"; break;
         case 25: p = "Mn"; break;
         case 26: p = "Fe"; break;
@@ -2205,13 +2248,13 @@ atomicnumber_to_element(int atomicnumber)
         case 30: p = "Zn"; break;
         case 35: p = "Br"; break;
         case 47: p = "Ag"; break;
-        default: p = "";   break;
+        default: p = ""; break;
     }
     return p;
 }
 
 
-static void do_atom(gmx::ISerializer *serializer, t_atom *atom)
+static void do_atom(gmx::ISerializer* serializer, t_atom* atom)
 {
     serializer->doReal(&atom->m);
     serializer->doReal(&atom->q);
@@ -2219,7 +2262,7 @@ static void do_atom(gmx::ISerializer *serializer, t_atom *atom)
     serializer->doReal(&atom->qB);
     serializer->doUShort(&atom->type);
     serializer->doUShort(&atom->typeB);
-    serializer->doInt(&atom->ptype);
+    serializer->doEnumAsInt(&atom->ptype);
     serializer->doInt(&atom->resind);
     serializer->doInt(&atom->atomnumber);
     if (serializer->reading())
@@ -2233,10 +2276,9 @@ static void do_atom(gmx::ISerializer *serializer, t_atom *atom)
     }
 }
 
-static void do_grps(gmx::ISerializer               *serializer,
-                    gmx::ArrayRef<AtomGroupIndices> grps)
+static void do_grps(gmx::ISerializer* serializer, gmx::ArrayRef<AtomGroupIndices> grps)
 {
-    for (auto &group : grps)
+    for (autogroup : grps)
     {
         int size = group.size();
         serializer->doInt(&size);
@@ -2248,7 +2290,7 @@ static void do_grps(gmx::ISerializer               *serializer,
     }
 }
 
-static void do_symstr(gmx::ISerializer *serializer, char ***nm, t_symtab *symtab)
+static void do_symstr(gmx::ISerializer* serializer, char*** nm, t_symtab* symtab)
 {
     int ls;
 
@@ -2264,12 +2306,9 @@ static void do_symstr(gmx::ISerializer *serializer, char ***nm, t_symtab *symtab
     }
 }
 
-static void do_strstr(gmx::ISerializer         *serializer,
-                      int                       nstr,
-                      char                   ***nm,
-                      t_symtab                 *symtab)
+static void do_strstr(gmx::ISerializer* serializer, int nstr, char*** nm, t_symtab* symtab)
 {
-    int  j;
+    int j;
 
     for (j = 0; (j < nstr); j++)
     {
@@ -2277,13 +2316,9 @@ static void do_strstr(gmx::ISerializer         *serializer,
     }
 }
 
-static void do_resinfo(gmx::ISerializer         *serializer,
-                       int                       n,
-                       t_resinfo                *ri,
-                       t_symtab                 *symtab,
-                       int                       file_version)
+static void do_resinfo(gmx::ISerializer* serializer, int n, t_resinfo* ri, t_symtab* symtab, int file_version)
 {
-    int  j;
+    int j;
 
     for (j = 0; (j < n); j++)
     {
@@ -2301,10 +2336,7 @@ static void do_resinfo(gmx::ISerializer         *serializer,
     }
 }
 
-static void do_atoms(gmx::ISerializer         *serializer,
-                     t_atoms                  *atoms,
-                     t_symtab                 *symtab,
-                     int                       file_version)
+static void do_atoms(gmx::ISerializer* serializer, t_atoms* atoms, t_symtab* symtab, int file_version)
 {
     int i;
 
@@ -2331,7 +2363,9 @@ static void do_atoms(gmx::ISerializer         *serializer,
     }
     else
     {
-        GMX_RELEASE_ASSERT(atoms->haveMass && atoms->haveCharge && atoms->haveType && atoms->haveBState, "Mass, charge, atomtype and B-state parameters should be present in t_atoms when writing a tpr file");
+        GMX_RELEASE_ASSERT(atoms->haveMass && atoms->haveCharge && atoms->haveType && atoms->haveBState,
+                           "Mass, charge, atomtype and B-state parameters should be present in "
+                           "t_atoms when writing a tpr file");
     }
     for (i = 0; (i < atoms->nr); i++)
     {
@@ -2344,9 +2378,7 @@ static void do_atoms(gmx::ISerializer         *serializer,
     do_resinfo(serializer, atoms->nres, atoms->resinfo, symtab, file_version);
 }
 
-static void do_groups(gmx::ISerializer         *serializer,
-                      SimulationGroups         *groups,
-                      t_symtab                 *symtab)
+static void do_groups(gmx::ISerializer* serializer, SimulationGroups* groups, t_symtab* symtab)
 {
     do_grps(serializer, groups->groups);
     int numberOfGroupNames = groups->groupNames.size();
@@ -2371,10 +2403,9 @@ static void do_groups(gmx::ISerializer         *serializer,
     }
 }
 
-static void do_atomtypes(gmx::ISerializer *serializer, t_atomtypes *atomtypes,
-                         int file_version)
+static void do_atomtypes(gmx::ISerializer* serializer, t_atomtypes* atomtypes, int file_version)
 {
-    int      j;
+    int j;
 
     serializer->doInt(&atomtypes->nr);
     j = atomtypes->nr;
@@ -2399,13 +2430,13 @@ static void do_atomtypes(gmx::ISerializer *serializer, t_atomtypes *atomtypes,
     }
 }
 
-static void do_symtab(gmx::ISerializer *serializer, t_symtab *symtab)
+static void do_symtab(gmx::ISerializer* serializer, t_symtab* symtab)
 {
     int       i, nr;
-    t_symbuf *symbuf;
+    t_symbufsymbuf;
 
     serializer->doInt(&symtab->nr);
-    nr     = symtab->nr;
+    nr = symtab->nr;
     if (serializer->reading())
     {
         snew(symtab->symbuf, 1);
@@ -2429,7 +2460,7 @@ static void do_symtab(gmx::ISerializer *serializer, t_symtab *symtab)
                 std::string buf = symbuf->buf[i];
                 serializer->doString(&buf);
             }
-            nr    -= i;
+            nr -= i;
             symbuf = symbuf->next;
         }
         if (nr != 0)
@@ -2439,7 +2470,7 @@ static void do_symtab(gmx::ISerializer *serializer, t_symtab *symtab)
     }
 }
 
-static void do_cmap(gmx::ISerializer *serializer, gmx_cmap_t *cmap_grid)
+static void do_cmap(gmx::ISerializer* serializer, gmx_cmap_t* cmap_grid)
 {
 
     int ngrid = cmap_grid->cmapdata.size();
@@ -2455,7 +2486,7 @@ static void do_cmap(gmx::ISerializer *serializer, gmx_cmap_t *cmap_grid)
 
         for (int i = 0; i < ngrid; i++)
         {
-            cmap_grid->cmapdata[i].cmap.resize(4*nelem);
+            cmap_grid->cmapdata[i].cmap.resize(4 * nelem);
         }
     }
 
@@ -2463,19 +2494,16 @@ static void do_cmap(gmx::ISerializer *serializer, gmx_cmap_t *cmap_grid)
     {
         for (int j = 0; j < nelem; j++)
         {
-            serializer->doReal(&cmap_grid->cmapdata[i].cmap[j*4]);
-            serializer->doReal(&cmap_grid->cmapdata[i].cmap[j*4+1]);
-            serializer->doReal(&cmap_grid->cmapdata[i].cmap[j*4+2]);
-            serializer->doReal(&cmap_grid->cmapdata[i].cmap[j*4+3]);
+            serializer->doReal(&cmap_grid->cmapdata[i].cmap[j * 4]);
+            serializer->doReal(&cmap_grid->cmapdata[i].cmap[j * 4 + 1]);
+            serializer->doReal(&cmap_grid->cmapdata[i].cmap[j * 4 + 2]);
+            serializer->doReal(&cmap_grid->cmapdata[i].cmap[j * 4 + 3]);
         }
     }
 }
 
 
-static void do_moltype(gmx::ISerializer         *serializer,
-                       gmx_moltype_t            *molt,
-                       t_symtab                 *symtab,
-                       int                       file_version)
+static void do_moltype(gmx::ISerializer* serializer, gmx_moltype_t* molt, t_symtab* symtab, int file_version)
 {
     do_symstr(serializer, &(molt->name), symtab);
 
@@ -2483,15 +2511,23 @@ static void do_moltype(gmx::ISerializer         *serializer,
 
     do_ilists(serializer, &molt->ilist, file_version);
 
-    do_block(serializer, &molt->cgs);
+    /* TODO: Remove the obsolete charge group index from the file */
+    t_block cgs;
+    cgs.nr           = molt->atoms.nr;
+    cgs.nalloc_index = cgs.nr + 1;
+    snew(cgs.index, cgs.nalloc_index);
+    for (int i = 0; i < cgs.nr + 1; i++)
+    {
+        cgs.index[i] = i;
+    }
+    do_block(serializer, &cgs);
+    sfree(cgs.index);
 
     /* This used to be in the atoms struct */
-    do_blocka(serializer, &molt->excls);
+    doListOfLists(serializer, &molt->excls);
 }
 
-static void do_molblock(gmx::ISerializer         *serializer,
-                        gmx_molblock_t           *molb,
-                        int                       numAtomsPerMolecule)
+static void do_molblock(gmx::ISerializer* serializer, gmx_molblock_t* molb, int numAtomsPerMolecule)
 {
     serializer->doInt(&molb->type);
     serializer->doInt(&molb->nmol);
@@ -2521,29 +2557,24 @@ static void do_molblock(gmx::ISerializer         *serializer,
         }
         serializer->doRvecArray(as_rvec_array(molb->posres_xB.data()), numPosres_xB);
     }
-
 }
 
-static void set_disres_npair(gmx_mtop_t *mtop)
+static void set_disres_npair(gmx_mtop_tmtop)
 {
-    gmx_mtop_ilistloop_t     iloop;
-    int                      nmol;
-
     gmx::ArrayRef<t_iparams> ip = mtop->ffparams.iparams;
 
-    iloop     = gmx_mtop_ilistloop_init(mtop);
-    while (const InteractionLists *ilist = gmx_mtop_ilistloop_next(iloop, &nmol))
+    for (const auto ilist : IListRange(*mtop))
     {
-        const InteractionList &il = (*ilist)[F_DISRES];
+        const InteractionList& il = ilist.list()[F_DISRES];
 
-        if (il.size() > 0)
+        if (!il.empty())
         {
             gmx::ArrayRef<const int> a     = il.iatoms;
             int                      npair = 0;
             for (int i = 0; i < il.size(); i += 3)
             {
                 npair++;
-                if (i+3 == il.size() || ip[a[i]].disres.label != ip[a[i+3]].disres.label)
+                if (i + 3 == il.size() || ip[a[i]].disres.label != ip[a[i + 3]].disres.label)
                 {
                     ip[a[i]].disres.npair = npair;
                     npair                 = 0;
@@ -2553,9 +2584,7 @@ static void set_disres_npair(gmx_mtop_t *mtop)
     }
 }
 
-static void do_mtop(gmx::ISerializer         *serializer,
-                    gmx_mtop_t               *mtop,
-                    int                       file_version)
+static void do_mtop(gmx::ISerializer* serializer, gmx_mtop_t* mtop, int file_version)
 {
     do_symtab(serializer, &(mtop->symtab));
 
@@ -2569,7 +2598,7 @@ static void do_mtop(gmx::ISerializer         *serializer,
     {
         mtop->moltype.resize(nmoltype);
     }
-    for (gmx_moltype_t &moltype : mtop->moltype)
+    for (gmx_moltype_tmoltype : mtop->moltype)
     {
         do_moltype(serializer, &moltype, &mtop->symtab, file_version);
     }
@@ -2580,7 +2609,7 @@ static void do_mtop(gmx::ISerializer         *serializer,
     {
         mtop->molblock.resize(nmolblock);
     }
-    for (gmx_molblock_t &molblock : mtop->molblock)
+    for (gmx_molblock_tmolblock : mtop->molblock)
     {
         int numAtomsPerMolecule = (serializer->reading() ? 0 : mtop->moltype[molblock.type].atoms.nr);
         do_molblock(serializer, &molblock, numAtomsPerMolecule);
@@ -2604,7 +2633,7 @@ static void do_mtop(gmx::ISerializer         *serializer,
         mtop->bIntermolecularInteractions = FALSE;
     }
 
-    do_atomtypes (serializer, &(mtop->atomtypes), file_version);
+    do_atomtypes(serializer, &(mtop->atomtypes), file_version);
 
     if (file_version >= 65)
     {
@@ -2620,6 +2649,18 @@ static void do_mtop(gmx::ISerializer         *serializer,
 
     mtop->haveMoleculeIndices = true;
 
+    if (file_version >= tpxv_StoreNonBondedInteractionExclusionGroup)
+    {
+        std::int64_t intermolecularExclusionGroupSize = gmx::ssize(mtop->intermolecularExclusionGroup);
+        serializer->doInt64(&intermolecularExclusionGroupSize);
+        GMX_RELEASE_ASSERT(intermolecularExclusionGroupSize >= 0,
+                           "Number of atoms with excluded intermolecular non-bonded interactions "
+                           "is negative.");
+        mtop->intermolecularExclusionGroup.resize(intermolecularExclusionGroupSize); // no effect when writing
+        serializer->doIntArray(mtop->intermolecularExclusionGroup.data(),
+                               mtop->intermolecularExclusionGroup.size());
+    }
+
     if (serializer->reading())
     {
         close_symtab(&(mtop->symtab));
@@ -2645,16 +2686,15 @@ static void do_mtop(gmx::ISerializer         *serializer,
  * \param[in,out] fio File handle.
  * \param[in] TopOnlyOK If not reading \p ir is fine or not.
  */
-static void do_tpxheader(gmx::FileIOXdrSerializer *serializer,
-                         TpxFileHeader            *tpx,
-                         const char               *filename,
-                         t_fileio                 *fio,
+static void do_tpxheader(gmx::FileIOXdrSerializerserializer,
+                         TpxFileHeader*            tpx,
+                         const char*               filename,
+                         t_fileio*                 fio,
                          bool                      TopOnlyOK)
 {
-    gmx_bool  bDouble;
-    int       precision;
-    int       idum = 0;
-    real      rdum = 0;
+    int  precision;
+    int  idum = 0;
+    real rdum = 0;
 
     /* XDR binary topology file */
     precision = sizeof(real);
@@ -2665,31 +2705,44 @@ static void do_tpxheader(gmx::FileIOXdrSerializer *serializer,
         serializer->doString(&buf);
         if (std::strncmp(buf.c_str(), "VERSION", 7) != 0)
         {
-            gmx_fatal(FARGS, "Can not read file %s,\n"
-                      "             this file is from a GROMACS version which is older than 2.0\n"
-                      "             Make a new one with grompp or use a gro or pdb file, if possible",
-                      filename);
-        }
+            gmx_fatal(
+                    FARGS,
+                    "Can not read file %s,\n"
+                    "             this file is from a GROMACS version which is older than 2.0\n"
+                    "             Make a new one with grompp or use a gro or pdb file, if possible",
+                    filename);
+        }
+        // We need to know the precision used to write the TPR file, to match it
+        // to the precision of the currently running binary. If the precisions match
+        // there is no problem, but mismatching precision needs to be accounted for
+        // by reading into temporary variables of the correct precision instead
+        // of the desired target datastructures.
         serializer->doInt(&precision);
-        bDouble = (precision == sizeof(double));
-        if ((precision != sizeof(float)) && !bDouble)
+        tpx->isDouble = (precision == sizeof(double));
+        if ((precision != sizeof(float)) && !tpx->isDouble)
         {
-            gmx_fatal(FARGS, "Unknown precision in file %s: real is %d bytes "
+            gmx_fatal(FARGS,
+                      "Unknown precision in file %s: real is %d bytes "
                       "instead of %zu or %zu",
-                      filename, precision, sizeof(float), sizeof(double));
-        }
-        gmx_fio_setprecision(fio, bDouble);
-        fprintf(stderr, "Reading file %s, %s (%s precision)\n",
-                filename, buf.c_str(), bDouble ? "double" : "single");
+                      filename,
+                      precision,
+                      sizeof(float),
+                      sizeof(double));
+        }
+        gmx_fio_setprecision(fio, tpx->isDouble);
+        fprintf(stderr,
+                "Reading file %s, %s (%s precision)\n",
+                filename,
+                buf.c_str(),
+                tpx->isDouble ? "double" : "single");
     }
     else
     {
         buf = gmx::formatString("VERSION %s", gmx_version());
         serializer->doString(&buf);
-        bDouble = (precision == sizeof(double));
-        gmx_fio_setprecision(fio, bDouble);
+        gmx_fio_setprecision(fio, tpx->isDouble);
         serializer->doInt(&precision);
-        fileTag        = gmx::formatString("%s", tpx_tag);
+        fileTag = tpx_tag;
     }
 
     /* Check versions! */
@@ -2721,28 +2774,34 @@ static void do_tpxheader(gmx::FileIOXdrSerializer *serializer,
 
         if (fileTag != tpx_tag)
         {
-            fprintf(stderr, "Note: file tpx tag '%s', software tpx tag '%s'\n",
-                    fileTag.c_str(), tpx_tag);
+            fprintf(stderr, "Note: file tpx tag '%s', software tpx tag '%s'\n", fileTag.c_str(), tpx_tag.c_str());
 
             /* We only support reading tpx files with the same tag as the code
              * or tpx files with the release tag and with lower version number.
              */
             if (fileTag != TPX_TAG_RELEASE && tpx->fileVersion < tpx_version)
             {
-                gmx_fatal(FARGS, "tpx tag/version mismatch: reading tpx file (%s) version %d, tag '%s' with program for tpx version %d, tag '%s'",
-                          filename, tpx->fileVersion, fileTag.c_str(),
-                          tpx_version, tpx_tag);
+                gmx_fatal(FARGS,
+                          "tpx tag/version mismatch: reading tpx file (%s) version %d, tag '%s' "
+                          "with program for tpx version %d, tag '%s'",
+                          filename,
+                          tpx->fileVersion,
+                          fileTag.c_str(),
+                          tpx_version,
+                          tpx_tag.c_str());
             }
         }
     }
 
-    if ((tpx->fileVersion <= tpx_incompatible_version) ||
-        ((tpx->fileVersion > tpx_version) && !TopOnlyOK) ||
-        (tpx->fileGeneration > tpx_generation) ||
-        tpx_version == 80) /*80 was used by both 5.0-dev and 4.6-dev*/
+    if ((tpx->fileVersion <= tpx_incompatible_version)
+        || ((tpx->fileVersion > tpx_version) && !TopOnlyOK) || (tpx->fileGeneration > tpx_generation)
+        || tpx_version == 80) /*80 was used by both 5.0-dev and 4.6-dev*/
     {
-        gmx_fatal(FARGS, "reading tpx file (%s) version %d with version %d program",
-                  filename, tpx->fileVersion, tpx_version);
+        gmx_fatal(FARGS,
+                  "reading tpx file (%s) version %d with version %d program",
+                  filename,
+                  tpx->fileVersion,
+                  tpx_version);
     }
 
     serializer->doInt(&tpx->natoms);
@@ -2769,7 +2828,8 @@ static void do_tpxheader(gmx::FileIOXdrSerializer *serializer,
     {
         if (!serializer->reading())
         {
-            GMX_RELEASE_ASSERT(tpx->sizeOfTprBody != 0, "Not possible to write new file with zero TPR body size");
+            GMX_RELEASE_ASSERT(tpx->sizeOfTprBody != 0,
+                               "Not possible to write new file with zero TPR body size");
         }
         serializer->doInt64(&tpx->sizeOfTprBody);
     }
@@ -2781,55 +2841,32 @@ static void do_tpxheader(gmx::FileIOXdrSerializer *serializer,
     }
 }
 
-static int do_tpx_body(gmx::ISerializer *serializer,
-                       TpxFileHeader    *tpx,
-                       t_inputrec       *ir,
-                       t_state          *state,
-                       rvec             *x,
-                       rvec             *v,
-                       gmx_mtop_t       *mtop)
-{
-    int             ePBC;
-    gmx_bool        bPeriodicMols;
-
-    if (!serializer->reading())
-    {
-        GMX_RELEASE_ASSERT(x == nullptr && v == nullptr, "Passing separate x and v pointers to do_tpx() is not supported when writing");
-    }
-    else
-    {
-        GMX_RELEASE_ASSERT(!(x == nullptr && v != nullptr), "Passing x==NULL and v!=NULL is not supported");
-    }
+#define do_test(serializer, b, p)                            \
+    if ((serializer)->reading() && ((p) != nullptr) && !(b)) \
+    gmx_fatal(FARGS, "No %s in input file", #p)
 
+/*! \brief
+ * Process the first part of the TPR into the state datastructure.
+ *
+ * Due to the structure of the legacy code, it is necessary
+ * to split up the state reading into two parts, with the
+ * box and legacy temperature coupling processed before the
+ * topology datastructures.
+ *
+ * See the documentation for do_tpx_body for the correct order of
+ * the operations for reading a tpr file.
+ *
+ * \param[in] serializer Abstract serializer used to read/write data.
+ * \param[in] tpx The file header data.
+ * \param[in, out] state Global state data.
+ */
+static void do_tpx_state_first(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_state* state)
+{
     if (serializer->reading())
     {
         state->flags = 0;
         init_gtc_state(state, tpx->ngtc, 0, 0);
-        if (x == nullptr)
-        {
-            // v is also nullptr by the above assertion, so we may
-            // need to make memory in state for storing the contents
-            // of the tpx file.
-            if (tpx->bX)
-            {
-                state->flags |= (1 << estX);
-            }
-            if (tpx->bV)
-            {
-                state->flags |= (1 << estV);
-            }
-            state_change_natoms(state, tpx->natoms);
-        }
     }
-
-    if (x == nullptr)
-    {
-        x = state->x.rvec_array();
-        v = state->v.rvec_array();
-    }
-
-#define do_test(serializer, b, p) if ((serializer)->reading() && ((p) != nullptr) && !(b)) gmx_fatal(FARGS, "No %s in input file",#p)
-
     do_test(serializer, tpx->bBox, state->box);
     if (tpx->bBox)
     {
@@ -2853,7 +2890,7 @@ static int do_tpx_body(gmx::ISerializer *serializer,
 
     if (state->ngtc > 0)
     {
-        real *dumv;
+        realdumv;
         snew(dumv, state->ngtc);
         if (tpx->fileVersion < 69)
         {
@@ -2863,13 +2900,28 @@ static int do_tpx_body(gmx::ISerializer *serializer,
         serializer->doRealArray(dumv, state->ngtc);
         sfree(dumv);
     }
+}
 
+/*! \brief
+ * Process global topology data.
+ *
+ * See the documentation for do_tpx_body for the correct order of
+ * the operations for reading a tpr file.
+ *
+ * \param[in] serializer Abstract serializer  used to read/write data.
+ * \param[in] tpx The file header data.
+ * \param[in,out] mtop Global topology.
+ */
+static void do_tpx_mtop(gmx::ISerializer* serializer, TpxFileHeader* tpx, gmx_mtop_t* mtop)
+{
     do_test(serializer, tpx->bTop, mtop);
     if (tpx->bTop)
     {
         if (mtop)
         {
             do_mtop(serializer, mtop, tpx->fileVersion);
+            set_disres_npair(mtop);
+            mtop->finalize();
         }
         else
         {
@@ -2877,12 +2929,65 @@ static int do_tpx_body(gmx::ISerializer *serializer,
             do_mtop(serializer, &dum_top, tpx->fileVersion);
         }
     }
+}
+/*! \brief
+ * Process coordinate vectors for state data.
+ *
+ * Main part of state gets processed here.
+ *
+ * See the documentation for do_tpx_body for the correct order of
+ * the operations for reading a tpr file.
+ *
+ * \param[in] serializer Abstract serializer used to read/write data.
+ * \param[in] tpx The file header data.
+ * \param[in,out] state Global state data.
+ * \param[in,out] x Individual coordinates for processing, deprecated.
+ * \param[in,out] v Individual velocities for processing, deprecated.
+ */
+static void do_tpx_state_second(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_state* state, rvec* x, rvec* v)
+{
+    if (!serializer->reading())
+    {
+        GMX_RELEASE_ASSERT(
+                x == nullptr && v == nullptr,
+                "Passing separate x and v pointers to do_tpx() is not supported when writing");
+    }
+    else
+    {
+        GMX_RELEASE_ASSERT(!(x == nullptr && v != nullptr),
+                           "Passing x==NULL and v!=NULL is not supported");
+    }
+
+    if (serializer->reading())
+    {
+        if (x == nullptr)
+        {
+            // v is also nullptr by the above assertion, so we may
+            // need to make memory in state for storing the contents
+            // of the tpx file.
+            if (tpx->bX)
+            {
+                state->flags |= enumValueToBitMask(StateEntry::X);
+            }
+            if (tpx->bV)
+            {
+                state->flags |= enumValueToBitMask(StateEntry::V);
+            }
+            state_change_natoms(state, tpx->natoms);
+        }
+    }
+
+    if (x == nullptr)
+    {
+        x = state->x.rvec_array();
+        v = state->v.rvec_array();
+    }
     do_test(serializer, tpx->bX, x);
     if (tpx->bX)
     {
         if (serializer->reading())
         {
-            state->flags |= (1<<estX);
+            state->flags |= enumValueToBitMask(StateEntry::X);
         }
         serializer->doRvecArray(x, tpx->natoms);
     }
@@ -2892,7 +2997,7 @@ static int do_tpx_body(gmx::ISerializer *serializer,
     {
         if (serializer->reading())
         {
-            state->flags |= (1<<estV);
+            state->flags |= enumValueToBitMask(StateEntry::V);
         }
         if (!v)
         {
@@ -2911,6 +3016,21 @@ static int do_tpx_body(gmx::ISerializer *serializer,
         std::vector<gmx::RVec> dummyForces(state->natoms);
         serializer->doRvecArray(as_rvec_array(dummyForces.data()), tpx->natoms);
     }
+}
+/*! \brief
+ * Process simulation parameters.
+ *
+ * See the documentation for do_tpx_body for the correct order of
+ * the operations for reading a tpr file.
+ *
+ * \param[in] serializer Abstract serializer used to read/write data.
+ * \param[in] tpx The file header data.
+ * \param[in,out] ir Datastructure with simulation parameters.
+ */
+static PbcType do_tpx_ir(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_inputrec* ir)
+{
+    PbcType  pbcType;
+    gmx_bool bPeriodicMols;
 
     /* Starting with tpx version 26, we have the inputrec
      * at the end of the file, so we can ignore it
@@ -2919,7 +3039,7 @@ static int do_tpx_body(gmx::ISerializer *serializer,
      *
      *
      */
-    ePBC          = -1;
+    pbcType       = PbcType::Unset;
     bPeriodicMols = FALSE;
 
     do_test(serializer, tpx->bIr, ir);
@@ -2930,74 +3050,133 @@ static int do_tpx_body(gmx::ISerializer *serializer,
             /* Removed the pbc info from do_inputrec, since we always want it */
             if (!serializer->reading())
             {
-                ePBC          = ir->ePBC;
+                pbcType       = ir->pbcType;
                 bPeriodicMols = ir->bPeriodicMols;
             }
-            serializer->doInt(&ePBC);
+            serializer->doInt(reinterpret_cast<int*>(&pbcType));
             serializer->doBool(&bPeriodicMols);
         }
         if (tpx->fileGeneration <= tpx_generation && ir)
         {
             do_inputrec(serializer, ir, tpx->fileVersion);
-            if (tpx->fileVersion < 51)
-            {
-                set_box_rel(ir, state);
-            }
             if (tpx->fileVersion < 53)
             {
-                ePBC          = ir->ePBC;
+                pbcType       = ir->pbcType;
                 bPeriodicMols = ir->bPeriodicMols;
             }
         }
         if (serializer->reading() && ir && tpx->fileVersion >= 53)
         {
             /* We need to do this after do_inputrec, since that initializes ir */
-            ir->ePBC          = ePBC;
+            ir->pbcType       = pbcType;
             ir->bPeriodicMols = bPeriodicMols;
         }
     }
+    return pbcType;
+}
 
-    if (serializer->reading())
+/*! \brief
+ * Correct and finalize read information.
+ *
+ * If \p state is nullptr, skip the parts dependent on it.
+ *
+ * See the documentation for do_tpx_body for the correct order of
+ * the operations for reading a tpr file.
+ *
+ * \param[in] tpx The file header used to check version numbers.
+ * \param[out] ir Input rec that needs correction.
+ * \param[out] state State needing correction.
+ * \param[out] mtop Topology to finalize.
+ */
+static void do_tpx_finalize(TpxFileHeader* tpx, t_inputrec* ir, t_state* state, gmx_mtop_t* mtop)
+{
+    if (tpx->fileVersion < 51 && state)
+    {
+        set_box_rel(ir, state);
+    }
+    if (tpx->bIr && ir)
     {
-        if (tpx->bIr && ir)
+        if (state && state->ngtc == 0)
         {
-            if (state->ngtc == 0)
-            {
-                /* Reading old version without tcoupl state data: set it */
-                init_gtc_state(state, ir->opts.ngtc, 0, ir->opts.nhchainlength);
-            }
-            if (tpx->bTop && mtop)
-            {
-                if (tpx->fileVersion < 57)
-                {
-                    if (mtop->moltype[0].ilist[F_DISRES].size() > 0)
-                    {
-                        ir->eDisre = edrSimple;
-                    }
-                    else
-                    {
-                        ir->eDisre = edrNone;
-                    }
-                }
-                set_disres_npair(mtop);
-            }
+            /* Reading old version without tcoupl state data: set it */
+            init_gtc_state(state, ir->opts.ngtc, 0, ir->opts.nhchainlength);
         }
-
         if (tpx->bTop && mtop)
         {
-            gmx_mtop_finalize(mtop);
+            if (tpx->fileVersion < 57)
+            {
+                ir->eDisre = !mtop->moltype[0].ilist[F_DISRES].empty()
+                                     ? DistanceRestraintRefinement::Simple
+                                     : DistanceRestraintRefinement::None;
+            }
         }
     }
+}
 
-    return ePBC;
+/*! \brief
+ * Process TPR data for file reading/writing.
+ *
+ * The TPR file gets processed in in four stages due to the organization
+ * of the data within it.
+ *
+ * First, state data for the box is processed in do_tpx_state_first.
+ * This is followed by processing the topology in do_tpx_mtop.
+ * Coordinate and velocity vectors are handled next in do_tpx_state_second.
+ * The last file information processed is the collection of simulation parameters in do_tpx_ir.
+ * When reading, a final processing step is undertaken at the end.
+ *
+ * \param[in] serializer Abstract serializer used to read/write data.
+ * \param[in] tpx The file header data.
+ * \param[in,out] ir Datastructures with simulation parameters.
+ * \param[in,out] state Global state data.
+ * \param[in,out] x Individual coordinates for processing, deprecated.
+ * \param[in,out] v Individual velocities for processing, deprecated.
+ * \param[in,out] mtop Global topology.
+ */
+static PbcType do_tpx_body(gmx::ISerializer* serializer,
+                           TpxFileHeader*    tpx,
+                           t_inputrec*       ir,
+                           t_state*          state,
+                           rvec*             x,
+                           rvec*             v,
+                           gmx_mtop_t*       mtop)
+{
+    if (state)
+    {
+        do_tpx_state_first(serializer, tpx, state);
+    }
+    do_tpx_mtop(serializer, tpx, mtop);
+    if (state)
+    {
+        do_tpx_state_second(serializer, tpx, state, x, v);
+    }
+    PbcType pbcType = do_tpx_ir(serializer, tpx, ir);
+    if (serializer->reading())
+    {
+        do_tpx_finalize(tpx, ir, state, mtop);
+    }
+    return pbcType;
+}
+
+/*! \brief
+ * Overload for do_tpx_body that defaults to state vectors being nullptr.
+ *
+ * \param[in] serializer Abstract serializer used to read/write data.
+ * \param[in] tpx The file header data.
+ * \param[in,out] ir Datastructures with simulation parameters.
+ * \param[in,out] mtop Global topology.
+ */
+static PbcType do_tpx_body(gmx::ISerializer* serializer, TpxFileHeader* tpx, t_inputrec* ir, gmx_mtop_t* mtop)
+{
+    return do_tpx_body(serializer, tpx, ir, nullptr, nullptr, nullptr, mtop);
 }
 
-static t_fileio *open_tpx(const char *fn, const char *mode)
+static t_fileio* open_tpx(const char* fn, const char* mode)
 {
     return gmx_fio_open(fn, mode);
 }
 
-static void close_tpx(t_fileio *fio)
+static void close_tpx(t_fileiofio)
 {
     gmx_fio_close(fio);
 }
@@ -3013,30 +3192,107 @@ static void close_tpx(t_fileio *fio)
  * \param[in] mtop Global topology.
  * \returns Fully populated header.
  */
-static TpxFileHeader populateTpxHeader(const t_state    &state,
-                                       const t_inputrec *ir,
-                                       const gmx_mtop_t *mtop)
+static TpxFileHeader populateTpxHeader(const t_state& state, const t_inputrec* ir, const gmx_mtop_t* mtop)
 {
     TpxFileHeader header;
     header.natoms         = state.natoms;
     header.ngtc           = state.ngtc;
     header.fep_state      = state.fep_state;
-    header.lambda         = state.lambda[efptFEP];
-    header.bIr            = ir       != nullptr;
-    header.bTop           = mtop     != nullptr;
-    header.bX             = (state.flags & (1 << estX)) != 0;
-    header.bV             = (state.flags & (1 << estV)) != 0;
+    header.lambda         = state.lambda[FreeEnergyPerturbationCouplingType::Fep];
+    header.bIr            = ir != nullptr;
+    header.bTop           = mtop != nullptr;
+    header.bX             = (state.flags & enumValueToBitMask(StateEntry::X)) != 0;
+    header.bV             = (state.flags & enumValueToBitMask(StateEntry::V)) != 0;
     header.bF             = false;
     header.bBox           = true;
     header.fileVersion    = tpx_version;
     header.fileGeneration = tpx_generation;
+    header.isDouble       = (sizeof(real) == sizeof(double));
 
     return header;
 }
 
-static void doTpxBodyBuffer(gmx::ISerializer *topologySerializer, gmx::ArrayRef<char> buffer)
+/*! \brief
+ * Process the body of a TPR file as an opaque data buffer.
+ *
+ * Reads/writes the information in \p buffer from/to the \p serializer
+ * provided to the function. Does not interact with the actual
+ * TPR datastructures but with an in memory representation of the
+ * data, so that this data can be efficiently read or written from/to
+ * an original source.
+ *
+ * \param[in] serializer The abstract serializer used for reading or writing
+ *                       the information in \p buffer.
+ * \param[in,out] buffer Information from TPR file as char buffer.
+ */
+static void doTpxBodyBuffer(gmx::ISerializer* serializer, gmx::ArrayRef<char> buffer)
 {
-    topologySerializer->doCharArray(buffer.data(), buffer.size());
+    serializer->doOpaque(buffer.data(), buffer.size());
+}
+
+/*! \brief
+ * Populates simulation datastructures.
+ *
+ * Here the information from the serialization interface \p serializer
+ * is used to first populate the datastructures containing the simulation
+ * information. Depending on the version found in the header \p tpx,
+ * this is done using the new reading of the data as one block from disk,
+ * followed by complete deserialization of the information read from there.
+ * Otherwise, the datastructures are populated as before one by one from disk.
+ * The second version is the default for the legacy tools that read the
+ * coordinates and velocities separate from the state.
+ *
+ * After reading in the data, a separate buffer is populated from them
+ * containing only \p ir and \p mtop that can be communicated directly
+ * to nodes needing the information to set up a simulation.
+ *
+ * \param[in] tpx The file header.
+ * \param[in] serializer The Serialization interface used to read the TPR.
+ * \param[out] ir Input rec to populate.
+ * \param[out] state State vectors to populate.
+ * \param[out] x Coordinates to populate if needed.
+ * \param[out] v Velocities to populate if needed.
+ * \param[out] mtop Global topology to populate.
+ *
+ * \returns Partial de-serialized TPR used for communication to nodes.
+ */
+static PartialDeserializedTprFile readTpxBody(TpxFileHeader*    tpx,
+                                              gmx::ISerializer* serializer,
+                                              t_inputrec*       ir,
+                                              t_state*          state,
+                                              rvec*             x,
+                                              rvec*             v,
+                                              gmx_mtop_t*       mtop)
+{
+    PartialDeserializedTprFile partialDeserializedTpr;
+    if (tpx->fileVersion >= tpxv_AddSizeField && tpx->fileGeneration >= 27)
+    {
+        partialDeserializedTpr.body.resize(tpx->sizeOfTprBody);
+        partialDeserializedTpr.header = *tpx;
+        doTpxBodyBuffer(serializer, partialDeserializedTpr.body);
+
+        partialDeserializedTpr.pbcType =
+                completeTprDeserialization(&partialDeserializedTpr, ir, state, x, v, mtop);
+    }
+    else
+    {
+        partialDeserializedTpr.pbcType = do_tpx_body(serializer, tpx, ir, state, x, v, mtop);
+    }
+    // Update header to system info for communication to nodes.
+    // As we only need to communicate the inputrec and mtop to other nodes,
+    // we prepare a new char buffer with the information we have already read
+    // in on master.
+    partialDeserializedTpr.header = populateTpxHeader(*state, ir, mtop);
+    // Long-term we should move to use little endian in files to avoid extra byte swapping,
+    // but since we just used the default XDR format (which is big endian) for the TPR
+    // header it would cause third-party libraries reading our raw data to tear their hair
+    // if we swap the endian in the middle of the file, so we stick to big endian in the
+    // TPR file for now - and thus we ask the serializer to swap if this host is little endian.
+    gmx::InMemorySerializer tprBodySerializer(gmx::EndianSwapBehavior::SwapIfHostIsLittleEndian);
+    do_tpx_body(&tprBodySerializer, &partialDeserializedTpr.header, ir, mtop);
+    partialDeserializedTpr.body = tprBodySerializer.finishAndGetBuffer();
+
+    return partialDeserializedTpr;
 }
 
 /************************************************************
@@ -3045,21 +3301,20 @@ static void doTpxBodyBuffer(gmx::ISerializer *topologySerializer, gmx::ArrayRef<
  *
  ************************************************************/
 
-TpxFileHeader readTpxHeader(const char *fileName, bool canReadTopologyOnly)
+TpxFileHeader readTpxHeader(const charfileName, bool canReadTopologyOnly)
 {
-    t_fileio *fio;
+    t_fileiofio;
 
     fio = open_tpx(fileName, "r");
     gmx::FileIOXdrSerializer serializer(fio);
 
-    TpxFileHeader            tpx;
+    TpxFileHeader tpx;
     do_tpxheader(&serializer, &tpx, fileName, fio, canReadTopologyOnly);
     close_tpx(fio);
     return tpx;
 }
 
-void write_tpx_state(const char *fn,
-                     const t_inputrec *ir, const t_state *state, const gmx_mtop_t *mtop)
+void write_tpx_state(const char* fn, const t_inputrec* ir, const t_state* state, const gmx_mtop_t& mtop)
 {
     /* To write a state, we first need to write the state information to a buffer before
      * we append the raw bytes to the file. For this, the header information needs to be
@@ -3067,122 +3322,84 @@ void write_tpx_state(const char *fn,
      * otherwise not available.
      */
 
-    t_fileio     *fio;
+    t_fileiofio;
 
-    TpxFileHeader tpx = populateTpxHeader(*state,
-                                          ir,
-                                          mtop);
-
-    gmx::InMemorySerializer tprBodySerializer;
+    TpxFileHeader tpx = populateTpxHeader(*state, ir, &mtop);
+    // Long-term we should move to use little endian in files to avoid extra byte swapping,
+    // but since we just used the default XDR format (which is big endian) for the TPR
+    // header it would cause third-party libraries reading our raw data to tear their hair
+    // if we swap the endian in the middle of the file, so we stick to big endian in the
+    // TPR file for now - and thus we ask the serializer to swap if this host is little endian.
+    gmx::InMemorySerializer tprBodySerializer(gmx::EndianSwapBehavior::SwapIfHostIsLittleEndian);
 
     do_tpx_body(&tprBodySerializer,
                 &tpx,
-                const_cast<t_inputrec *>(ir),
-                const_cast<t_state *>(state), nullptr, nullptr,
-                const_cast<gmx_mtop_t *>(mtop));
+                const_cast<t_inputrec*>(ir),
+                const_cast<t_state*>(state),
+                nullptr,
+                nullptr,
+                const_cast<gmx_mtop_t*>(&mtop));
 
     std::vector<char> tprBody = tprBodySerializer.finishAndGetBuffer();
-    tpx.sizeOfTprBody = tprBody.size();
+    tpx.sizeOfTprBody         = tprBody.size();
 
     fio = open_tpx(fn, "w");
     gmx::FileIOXdrSerializer serializer(fio);
-    do_tpxheader(&serializer,
-                 &tpx,
-                 fn,
-                 fio,
-                 ir == nullptr);
+    do_tpxheader(&serializer, &tpx, fn, fio, ir == nullptr);
     doTpxBodyBuffer(&serializer, tprBody);
 
     close_tpx(fio);
 }
 
-/*! \brief
- * Wraps reading of header before and after introduction of size field.
- *
- * \param[in] tpx The file header.
- * \param[in] serializer The Serialization interface used to read the TPR.
- * \param[in] isDouble Whether the file is double or single precision.
- * \param[out] ir Input rec to populate.
- * \param[out] state State vectors to populate.
- * \param[out] x Coordinates to populate if needed.
- * \param[out] v Velocities to populate if needed.
- * \param[out] mtop Global topology to populate.
- *
- * \returns Flag for pbc.
- */
-static int do_tpx_body_dispatcher(TpxFileHeader *tpx,
-                                  gmx::ISerializer *serializer,
-                                  bool isDouble,
-                                  t_inputrec *ir,
-                                  t_state *state,
-                                  rvec *x, rvec *v,
-                                  gmx_mtop_t *mtop)
+PbcType completeTprDeserialization(PartialDeserializedTprFile* partialDeserializedTpr,
+                                   t_inputrec*                 ir,
+                                   t_state*                    state,
+                                   rvec*                       x,
+                                   rvec*                       v,
+                                   gmx_mtop_t*                 mtop)
 {
-    int ePBC;
-    if (tpx->fileVersion >= tpxv_AddSizeField && tpx->fileGeneration >= 27)
-    {
-        std::vector<char>         tprBody(tpx->sizeOfTprBody);
-        doTpxBodyBuffer(serializer, tprBody);
-        gmx::InMemoryDeserializer tprBodyDeserializer(tprBody, isDouble);
-
-        ePBC = do_tpx_body(&tprBodyDeserializer,
-                           tpx,
-                           ir,
-                           state,
-                           x,
-                           v,
-                           mtop);
-    }
-    else
-    {
-        ePBC = do_tpx_body(serializer,
-                           tpx,
-                           ir,
-                           state,
-                           x,
-                           v,
-                           mtop);
-    }
-    return ePBC;
+    // Long-term we should move to use little endian in files to avoid extra byte swapping,
+    // but since we just used the default XDR format (which is big endian) for the TPR
+    // header it would cause third-party libraries reading our raw data to tear their hair
+    // if we swap the endian in the middle of the file, so we stick to big endian in the
+    // TPR file for now - and thus we ask the serializer to swap if this host is little endian.
+    gmx::InMemoryDeserializer tprBodyDeserializer(partialDeserializedTpr->body,
+                                                  partialDeserializedTpr->header.isDouble,
+                                                  gmx::EndianSwapBehavior::SwapIfHostIsLittleEndian);
+    return do_tpx_body(&tprBodyDeserializer, &partialDeserializedTpr->header, ir, state, x, v, mtop);
 }
 
-
-void read_tpx_state(const char *fn,
-                    t_inputrec *ir, t_state *state, gmx_mtop_t *mtop)
+PbcType completeTprDeserialization(PartialDeserializedTprFile* partialDeserializedTpr,
+                                   t_inputrec*                 ir,
+                                   gmx_mtop_t*                 mtop)
 {
-    t_fileio                *fio;
+    return completeTprDeserialization(partialDeserializedTpr, ir, nullptr, nullptr, nullptr, mtop);
+}
 
-    TpxFileHeader            tpx;
+PartialDeserializedTprFile read_tpx_state(const char* fn, t_inputrec* ir, t_state* state, gmx_mtop_t* mtop)
+{
+    t_fileio* fio;
     fio = open_tpx(fn, "r");
-    gmx::FileIOXdrSerializer serializer(fio);
-    do_tpxheader(&serializer,
-                 &tpx,
-                 fn,
-                 fio,
-                 ir == nullptr);
-    do_tpx_body_dispatcher(&tpx, &serializer, gmx_fio_is_double(fio),
-                           ir, state, nullptr, nullptr, mtop);
+    gmx::FileIOXdrSerializer   serializer(fio);
+    PartialDeserializedTprFile partialDeserializedTpr;
+    do_tpxheader(&serializer, &partialDeserializedTpr.header, fn, fio, ir == nullptr);
+    partialDeserializedTpr =
+            readTpxBody(&partialDeserializedTpr.header, &serializer, ir, state, nullptr, nullptr, mtop);
     close_tpx(fio);
+    return partialDeserializedTpr;
 }
 
-int read_tpx(const char *fn,
-             t_inputrec *ir, matrix box, int *natoms,
-             rvec *x, rvec *v, gmx_mtop_t *mtop)
+PbcType read_tpx(const char* fn, t_inputrec* ir, matrix box, int* natoms, rvec* x, rvec* v, gmx_mtop_t* mtop)
 {
-    t_fileio                *fio;
-    t_state                  state;
-    int                      ePBC;
+    t_fileio* fio;
+    t_state   state;
 
-    TpxFileHeader            tpx;
-    fio     = open_tpx(fn, "r");
+    TpxFileHeader tpx;
+    fio = open_tpx(fn, "r");
     gmx::FileIOXdrSerializer serializer(fio);
-    do_tpxheader(&serializer,
-                 &tpx,
-                 fn,
-                 fio,
-                 ir == nullptr);
-    ePBC = do_tpx_body_dispatcher(&tpx, &serializer, gmx_fio_is_double(fio),
-                                  ir, &state, x, v, mtop);
+    do_tpxheader(&serializer, &tpx, fn, fio, ir == nullptr);
+    PartialDeserializedTprFile partialDeserializedTpr =
+            readTpxBody(&tpx, &serializer, ir, &state, x, v, mtop);
     close_tpx(fio);
     if (mtop != nullptr && natoms != nullptr)
     {
@@ -3192,29 +3409,27 @@ int read_tpx(const char *fn,
     {
         copy_mat(state.box, box);
     }
-    return ePBC;
+    return partialDeserializedTpr.pbcType;
 }
 
-int read_tpx_top(const char *fn,
-                 t_inputrec *ir, matrix box, int *natoms,
-                 rvec *x, rvec *v, t_topology *top)
+PbcType read_tpx_top(const char* fn, t_inputrec* ir, matrix box, int* natoms, rvec* x, rvec* v, t_topology* top)
 {
-    gmx_mtop_t  mtop;
-    int         ePBC;
+    gmx_mtop_t mtop;
+    PbcType    pbcType;
 
-    ePBC = read_tpx(fn, ir, box, natoms, x, v, &mtop);
+    pbcType = read_tpx(fn, ir, box, natoms, x, v, &mtop);
 
     *top = gmx_mtop_t_to_t_topology(&mtop, true);
 
-    return ePBC;
+    return pbcType;
 }
 
-gmx_bool fn2bTPX(const char *file)
+gmx_bool fn2bTPX(const charfile)
 {
     return (efTPR == fn2ftp(file));
 }
 
-void pr_tpxheader(FILE *fp, int indent, const char *title, const TpxFileHeader *sh)
+void pr_tpxheader(FILE* fp, int indent, const char* title, const TpxFileHeader* sh)
 {
     if (available(fp, sh, indent, title))
     {