Fix cppcheck 1.64 warnings
[alexxy/gromacs.git] / src / gromacs / gmxlib / checkpoint.c
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2008,2009,2010,2011,2012,2013,2014, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35
36 /* The source code in this file should be thread-safe.
37    Please keep it that way. */
38
39
40 #ifdef HAVE_CONFIG_H
41 #include <config.h>
42 #endif
43
44 #include <errno.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <time.h>
48
49 #include <fcntl.h>
50 #ifdef HAVE_SYS_TIME_H
51 #include <sys/time.h>
52 #endif
53
54 #ifdef HAVE_UNISTD_H
55 #include <unistd.h>
56 #endif
57
58 #ifdef GMX_NATIVE_WINDOWS
59 /* _chsize_s */
60 #include <io.h>
61 #include <sys/locking.h>
62 #endif
63
64 #include "copyrite.h"
65 #include "names.h"
66 #include "typedefs.h"
67 #include "types/commrec.h"
68 #include "gromacs/utility/smalloc.h"
69 #include "txtdump.h"
70 #include "gromacs/math/vec.h"
71 #include "network.h"
72 #include "checkpoint.h"
73 #include "gromacs/utility/cstringutil.h"
74
75 #include "gromacs/fileio/filenm.h"
76 #include "gromacs/utility/futil.h"
77 #include "gromacs/fileio/gmxfio.h"
78 #include "gromacs/fileio/xdrf.h"
79 #include "gromacs/fileio/xdr_datatype.h"
80 #include "gromacs/utility/basenetwork.h"
81 #include "gromacs/utility/baseversion.h"
82 #include "gromacs/utility/fatalerror.h"
83
84 #include "buildinfo.h"
85
86 #ifdef GMX_FAHCORE
87 #include "corewrap.h"
88 #endif
89
90 #define CPT_MAGIC1 171817
91 #define CPT_MAGIC2 171819
92 #define CPTSTRLEN 1024
93
94 #ifdef GMX_DOUBLE
95 #define GMX_CPT_BUILD_DP 1
96 #else
97 #define GMX_CPT_BUILD_DP 0
98 #endif
99
100 /* cpt_version should normally only be changed
101  * when the header of footer format changes.
102  * The state data format itself is backward and forward compatible.
103  * But old code can not read a new entry that is present in the file
104  * (but can read a new format when new entries are not present).
105  */
106 static const int cpt_version = 16;
107
108
109 const char *est_names[estNR] =
110 {
111     "FE-lambda",
112     "box", "box-rel", "box-v", "pres_prev",
113     "nosehoover-xi", "thermostat-integral",
114     "x", "v", "SDx", "CGp", "LD-rng", "LD-rng-i",
115     "disre_initf", "disre_rm3tav",
116     "orire_initf", "orire_Dtav",
117     "svir_prev", "nosehoover-vxi", "v_eta", "vol0", "nhpres_xi", "nhpres_vxi", "fvir_prev", "fep_state", "MC-rng", "MC-rng-i"
118 };
119
120 enum {
121     eeksEKIN_N, eeksEKINH, eeksDEKINDL, eeksMVCOS, eeksEKINF, eeksEKINO, eeksEKINSCALEF, eeksEKINSCALEH, eeksVSCALE, eeksEKINTOTAL, eeksNR
122 };
123
124 const char *eeks_names[eeksNR] =
125 {
126     "Ekin_n", "Ekinh", "dEkindlambda", "mv_cos",
127     "Ekinf", "Ekinh_old", "EkinScaleF_NHC", "EkinScaleH_NHC", "Vscale_NHC", "Ekin_Total"
128 };
129
130 enum {
131     eenhENERGY_N, eenhENERGY_AVER, eenhENERGY_SUM, eenhENERGY_NSUM,
132     eenhENERGY_SUM_SIM, eenhENERGY_NSUM_SIM,
133     eenhENERGY_NSTEPS, eenhENERGY_NSTEPS_SIM,
134     eenhENERGY_DELTA_H_NN,
135     eenhENERGY_DELTA_H_LIST,
136     eenhENERGY_DELTA_H_STARTTIME,
137     eenhENERGY_DELTA_H_STARTLAMBDA,
138     eenhNR
139 };
140
141 const char *eenh_names[eenhNR] =
142 {
143     "energy_n", "energy_aver", "energy_sum", "energy_nsum",
144     "energy_sum_sim", "energy_nsum_sim",
145     "energy_nsteps", "energy_nsteps_sim",
146     "energy_delta_h_nn",
147     "energy_delta_h_list",
148     "energy_delta_h_start_time",
149     "energy_delta_h_start_lambda"
150 };
151
152 /* free energy history variables -- need to be preserved over checkpoint */
153 enum {
154     edfhBEQUIL, edfhNATLAMBDA, edfhWLHISTO, edfhWLDELTA, edfhSUMWEIGHTS, edfhSUMDG, edfhSUMMINVAR, edfhSUMVAR,
155     edfhACCUMP, edfhACCUMM, edfhACCUMP2, edfhACCUMM2, edfhTIJ, edfhTIJEMP, edfhNR
156 };
157 /* free energy history variable names  */
158 const char *edfh_names[edfhNR] =
159 {
160     "bEquilibrated", "N_at_state", "Wang-Landau Histogram", "Wang-Landau Delta", "Weights", "Free Energies", "minvar", "variance",
161     "accumulated_plus", "accumulated_minus", "accumulated_plus_2",  "accumulated_minus_2", "Tij", "Tij_empirical"
162 };
163
164 #ifdef GMX_NATIVE_WINDOWS
165 static int
166 gmx_wintruncate(const char *filename, __int64 size)
167 {
168 #ifdef GMX_FAHCORE
169     /*we do this elsewhere*/
170     return 0;
171 #else
172     FILE *fp;
173     int   rc;
174
175     fp = fopen(filename, "rb+");
176
177     if (fp == NULL)
178     {
179         return -1;
180     }
181
182     return _chsize_s( fileno(fp), size);
183 #endif
184 }
185 #endif
186
187
188 enum {
189     ecprREAL, ecprRVEC, ecprMATRIX
190 };
191
192 enum {
193     cptpEST, cptpEEKS, cptpEENH, cptpEDFH
194 };
195 /* enums for the different components of checkpoint variables, replacing the hard coded ones.
196    cptpEST - state variables.
197    cptpEEKS - Kinetic energy state variables.
198    cptpEENH - Energy history state variables.
199    cptpEDFH - free energy history variables.
200  */
201
202
203 static const char *st_names(int cptp, int ecpt)
204 {
205     switch (cptp)
206     {
207         case cptpEST: return est_names [ecpt]; break;
208         case cptpEEKS: return eeks_names[ecpt]; break;
209         case cptpEENH: return eenh_names[ecpt]; break;
210         case cptpEDFH: return edfh_names[ecpt]; break;
211     }
212
213     return NULL;
214 }
215
216 static void cp_warning(FILE *fp)
217 {
218     fprintf(fp, "\nWARNING: Checkpoint file is corrupted or truncated\n\n");
219 }
220
221 static void cp_error()
222 {
223     gmx_fatal(FARGS, "Checkpoint file corrupted/truncated, or maybe you are out of disk space?");
224 }
225
226 static void do_cpt_string_err(XDR *xd, gmx_bool bRead, const char *desc, char **s, FILE *list)
227 {
228     bool_t res = 0;
229
230     if (bRead)
231     {
232         snew(*s, CPTSTRLEN);
233     }
234     res = xdr_string(xd, s, CPTSTRLEN);
235     if (res == 0)
236     {
237         cp_error();
238     }
239     if (list)
240     {
241         fprintf(list, "%s = %s\n", desc, *s);
242         sfree(*s);
243     }
244 }
245
246 static int do_cpt_int(XDR *xd, const char *desc, int *i, FILE *list)
247 {
248     bool_t res = 0;
249
250     res = xdr_int(xd, i);
251     if (res == 0)
252     {
253         return -1;
254     }
255     if (list)
256     {
257         fprintf(list, "%s = %d\n", desc, *i);
258     }
259     return 0;
260 }
261
262 static int do_cpt_u_chars(XDR *xd, const char *desc, int n, unsigned char *i, FILE *list)
263 {
264     bool_t res = 1;
265     int    j;
266     if (list)
267     {
268         fprintf(list, "%s = ", desc);
269     }
270     for (j = 0; j < n && res; j++)
271     {
272         res &= xdr_u_char(xd, &i[j]);
273         if (list)
274         {
275             fprintf(list, "%02x", i[j]);
276         }
277     }
278     if (list)
279     {
280         fprintf(list, "\n");
281     }
282     if (res == 0)
283     {
284         return -1;
285     }
286
287     return 0;
288 }
289
290 static void do_cpt_int_err(XDR *xd, const char *desc, int *i, FILE *list)
291 {
292     if (do_cpt_int(xd, desc, i, list) < 0)
293     {
294         cp_error();
295     }
296 }
297
298 static void do_cpt_step_err(XDR *xd, const char *desc, gmx_int64_t *i, FILE *list)
299 {
300     bool_t res = 0;
301     char   buf[STEPSTRSIZE];
302
303     res = xdr_int64(xd, i);
304     if (res == 0)
305     {
306         cp_error();
307     }
308     if (list)
309     {
310         fprintf(list, "%s = %s\n", desc, gmx_step_str(*i, buf));
311     }
312 }
313
314 static void do_cpt_double_err(XDR *xd, const char *desc, double *f, FILE *list)
315 {
316     bool_t res = 0;
317
318     res = xdr_double(xd, f);
319     if (res == 0)
320     {
321         cp_error();
322     }
323     if (list)
324     {
325         fprintf(list, "%s = %f\n", desc, *f);
326     }
327 }
328
329 static void do_cpt_real_err(XDR *xd, real *f)
330 {
331     bool_t res = 0;
332
333 #ifdef GMX_DOUBLE
334     res = xdr_double(xd, f);
335 #else
336     res = xdr_float(xd, f);
337 #endif
338     if (res == 0)
339     {
340         cp_error();
341     }
342 }
343
344 static void do_cpt_n_rvecs_err(XDR *xd, const char *desc, int n, rvec f[], FILE *list)
345 {
346     int i, j;
347
348     for (i = 0; i < n; i++)
349     {
350         for (j = 0; j < DIM; j++)
351         {
352             do_cpt_real_err(xd, &f[i][j]);
353         }
354     }
355
356     if (list)
357     {
358         pr_rvecs(list, 0, desc, f, n);
359     }
360 }
361
362 /* If nval >= 0, nval is used; on read this should match the passed value.
363  * If nval n<0, *nptr is used; on read the value is stored in nptr
364  */
365 static int do_cpte_reals_low(XDR *xd, int cptp, int ecpt, int sflags,
366                              int nval, int *nptr, real **v,
367                              FILE *list, int erealtype)
368 {
369     bool_t  res = 0;
370 #ifndef GMX_DOUBLE
371     int     dtc = xdr_datatype_float;
372 #else
373     int     dtc = xdr_datatype_double;
374 #endif
375     real   *vp, *va = NULL;
376     float  *vf;
377     double *vd;
378     int     nf, dt, i;
379
380     if (list == NULL)
381     {
382         if (nval >= 0)
383         {
384             nf = nval;
385         }
386         else
387         {
388             if (nptr == NULL)
389             {
390                 gmx_incons("*ntpr=NULL in do_cpte_reals_low");
391             }
392             nf = *nptr;
393         }
394     }
395     res = xdr_int(xd, &nf);
396     if (res == 0)
397     {
398         return -1;
399     }
400     if (list == NULL)
401     {
402         if (nval >= 0)
403         {
404             if (nf != nval)
405             {
406                 gmx_fatal(FARGS, "Count mismatch for state entry %s, code count is %d, file count is %d\n", st_names(cptp, ecpt), nval, nf);
407             }
408         }
409         else
410         {
411             *nptr = nf;
412         }
413     }
414     dt  = dtc;
415     res = xdr_int(xd, &dt);
416     if (res == 0)
417     {
418         return -1;
419     }
420     if (dt != dtc)
421     {
422         fprintf(stderr, "Precision mismatch for state entry %s, code precision is %s, file precision is %s\n",
423                 st_names(cptp, ecpt), xdr_datatype_names[dtc],
424                 xdr_datatype_names[dt]);
425     }
426     if (list || !(sflags & (1<<ecpt)))
427     {
428         snew(va, nf);
429         vp = va;
430     }
431     else
432     {
433         if (*v == NULL)
434         {
435             snew(*v, nf);
436         }
437         vp = *v;
438     }
439     if (dt == xdr_datatype_float)
440     {
441         if (dtc == xdr_datatype_float)
442         {
443             vf = (float *)vp;
444         }
445         else
446         {
447             snew(vf, nf);
448         }
449         res = xdr_vector(xd, (char *)vf, nf,
450                          (unsigned int)sizeof(float), (xdrproc_t)xdr_float);
451         if (res == 0)
452         {
453             return -1;
454         }
455         if (dtc != xdr_datatype_float)
456         {
457             for (i = 0; i < nf; i++)
458             {
459                 vp[i] = vf[i];
460             }
461             sfree(vf);
462         }
463     }
464     else
465     {
466         if (dtc == xdr_datatype_double)
467         {
468             /* cppcheck-suppress invalidPointerCast
469              * Only executed if real is anyhow double */
470             vd = (double *)vp;
471         }
472         else
473         {
474             snew(vd, nf);
475         }
476         res = xdr_vector(xd, (char *)vd, nf,
477                          (unsigned int)sizeof(double), (xdrproc_t)xdr_double);
478         if (res == 0)
479         {
480             return -1;
481         }
482         if (dtc != xdr_datatype_double)
483         {
484             for (i = 0; i < nf; i++)
485             {
486                 vp[i] = vd[i];
487             }
488             sfree(vd);
489         }
490     }
491
492     if (list)
493     {
494         switch (erealtype)
495         {
496             case ecprREAL:
497                 pr_reals(list, 0, st_names(cptp, ecpt), vp, nf);
498                 break;
499             case ecprRVEC:
500                 pr_rvecs(list, 0, st_names(cptp, ecpt), (rvec *)vp, nf/3);
501                 break;
502             default:
503                 gmx_incons("Unknown checkpoint real type");
504         }
505     }
506     if (va)
507     {
508         sfree(va);
509     }
510
511     return 0;
512 }
513
514
515 /* This function stores n along with the reals for reading,
516  * but on reading it assumes that n matches the value in the checkpoint file,
517  * a fatal error is generated when this is not the case.
518  */
519 static int do_cpte_reals(XDR *xd, int cptp, int ecpt, int sflags,
520                          int n, real **v, FILE *list)
521 {
522     return do_cpte_reals_low(xd, cptp, ecpt, sflags, n, NULL, v, list, ecprREAL);
523 }
524
525 /* This function does the same as do_cpte_reals,
526  * except that on reading it ignores the passed value of *n
527  * and stored the value read from the checkpoint file in *n.
528  */
529 static int do_cpte_n_reals(XDR *xd, int cptp, int ecpt, int sflags,
530                            int *n, real **v, FILE *list)
531 {
532     return do_cpte_reals_low(xd, cptp, ecpt, sflags, -1, n, v, list, ecprREAL);
533 }
534
535 static int do_cpte_real(XDR *xd, int cptp, int ecpt, int sflags,
536                         real *r, FILE *list)
537 {
538     int n;
539
540     return do_cpte_reals_low(xd, cptp, ecpt, sflags, 1, NULL, &r, list, ecprREAL);
541 }
542
543 static int do_cpte_ints(XDR *xd, int cptp, int ecpt, int sflags,
544                         int n, int **v, FILE *list)
545 {
546     bool_t res = 0;
547     int    dtc = xdr_datatype_int;
548     int   *vp, *va = NULL;
549     int    nf, dt, i;
550
551     nf  = n;
552     res = xdr_int(xd, &nf);
553     if (res == 0)
554     {
555         return -1;
556     }
557     if (list == NULL && v != NULL && nf != n)
558     {
559         gmx_fatal(FARGS, "Count mismatch for state entry %s, code count is %d, file count is %d\n", st_names(cptp, ecpt), n, nf);
560     }
561     dt  = dtc;
562     res = xdr_int(xd, &dt);
563     if (res == 0)
564     {
565         return -1;
566     }
567     if (dt != dtc)
568     {
569         gmx_fatal(FARGS, "Type mismatch for state entry %s, code type is %s, file type is %s\n",
570                   st_names(cptp, ecpt), xdr_datatype_names[dtc],
571                   xdr_datatype_names[dt]);
572     }
573     if (list || !(sflags & (1<<ecpt)) || v == NULL)
574     {
575         snew(va, nf);
576         vp = va;
577     }
578     else
579     {
580         if (*v == NULL)
581         {
582             snew(*v, nf);
583         }
584         vp = *v;
585     }
586     res = xdr_vector(xd, (char *)vp, nf,
587                      (unsigned int)sizeof(int), (xdrproc_t)xdr_int);
588     if (res == 0)
589     {
590         return -1;
591     }
592     if (list)
593     {
594         pr_ivec(list, 0, st_names(cptp, ecpt), vp, nf, TRUE);
595     }
596     if (va)
597     {
598         sfree(va);
599     }
600
601     return 0;
602 }
603
604 static int do_cpte_int(XDR *xd, int cptp, int ecpt, int sflags,
605                        int *i, FILE *list)
606 {
607     return do_cpte_ints(xd, cptp, ecpt, sflags, 1, &i, list);
608 }
609
610 static int do_cpte_doubles(XDR *xd, int cptp, int ecpt, int sflags,
611                            int n, double **v, FILE *list)
612 {
613     bool_t  res = 0;
614     int     dtc = xdr_datatype_double;
615     double *vp, *va = NULL;
616     int     nf, dt, i;
617
618     nf  = n;
619     res = xdr_int(xd, &nf);
620     if (res == 0)
621     {
622         return -1;
623     }
624     if (list == NULL && nf != n)
625     {
626         gmx_fatal(FARGS, "Count mismatch for state entry %s, code count is %d, file count is %d\n", st_names(cptp, ecpt), n, nf);
627     }
628     dt  = dtc;
629     res = xdr_int(xd, &dt);
630     if (res == 0)
631     {
632         return -1;
633     }
634     if (dt != dtc)
635     {
636         gmx_fatal(FARGS, "Precision mismatch for state entry %s, code precision is %s, file precision is %s\n",
637                   st_names(cptp, ecpt), xdr_datatype_names[dtc],
638                   xdr_datatype_names[dt]);
639     }
640     if (list || !(sflags & (1<<ecpt)))
641     {
642         snew(va, nf);
643         vp = va;
644     }
645     else
646     {
647         if (*v == NULL)
648         {
649             snew(*v, nf);
650         }
651         vp = *v;
652     }
653     res = xdr_vector(xd, (char *)vp, nf,
654                      (unsigned int)sizeof(double), (xdrproc_t)xdr_double);
655     if (res == 0)
656     {
657         return -1;
658     }
659     if (list)
660     {
661         pr_doubles(list, 0, st_names(cptp, ecpt), vp, nf);
662     }
663     if (va)
664     {
665         sfree(va);
666     }
667
668     return 0;
669 }
670
671 static int do_cpte_double(XDR *xd, int cptp, int ecpt, int sflags,
672                           double *r, FILE *list)
673 {
674     return do_cpte_doubles(xd, cptp, ecpt, sflags, 1, &r, list);
675 }
676
677
678 static int do_cpte_rvecs(XDR *xd, int cptp, int ecpt, int sflags,
679                          int n, rvec **v, FILE *list)
680 {
681     int n3;
682
683     return do_cpte_reals_low(xd, cptp, ecpt, sflags,
684                              n*DIM, NULL, (real **)v, list, ecprRVEC);
685 }
686
687 static int do_cpte_matrix(XDR *xd, int cptp, int ecpt, int sflags,
688                           matrix v, FILE *list)
689 {
690     real *vr;
691     real  ret;
692
693     vr  = (real *)&(v[0][0]);
694     ret = do_cpte_reals_low(xd, cptp, ecpt, sflags,
695                             DIM*DIM, NULL, &vr, NULL, ecprMATRIX);
696
697     if (list && ret == 0)
698     {
699         pr_rvecs(list, 0, st_names(cptp, ecpt), v, DIM);
700     }
701
702     return ret;
703 }
704
705
706 static int do_cpte_nmatrix(XDR *xd, int cptp, int ecpt, int sflags,
707                            int n, real **v, FILE *list)
708 {
709     int   i;
710     real *vr;
711     real  ret, reti;
712     char  name[CPTSTRLEN];
713
714     ret = 0;
715     if (v == NULL)
716     {
717         snew(v, n);
718     }
719     for (i = 0; i < n; i++)
720     {
721         vr   = v[i];
722         reti = do_cpte_reals_low(xd, cptp, ecpt, sflags, n, NULL, &(v[i]), NULL, ecprREAL);
723         if (list && reti == 0)
724         {
725             sprintf(name, "%s[%d]", st_names(cptp, ecpt), i);
726             pr_reals(list, 0, name, v[i], n);
727         }
728         if (reti == 0)
729         {
730             ret = 0;
731         }
732     }
733     return ret;
734 }
735
736 static int do_cpte_matrices(XDR *xd, int cptp, int ecpt, int sflags,
737                             int n, matrix **v, FILE *list)
738 {
739     bool_t  res = 0;
740     matrix *vp, *va = NULL;
741     real   *vr;
742     int     nf, i, j, k;
743     int     ret;
744
745     nf  = n;
746     res = xdr_int(xd, &nf);
747     if (res == 0)
748     {
749         return -1;
750     }
751     if (list == NULL && nf != n)
752     {
753         gmx_fatal(FARGS, "Count mismatch for state entry %s, code count is %d, file count is %d\n", st_names(cptp, ecpt), n, nf);
754     }
755     if (list || !(sflags & (1<<ecpt)))
756     {
757         snew(va, nf);
758         vp = va;
759     }
760     else
761     {
762         if (*v == NULL)
763         {
764             snew(*v, nf);
765         }
766         vp = *v;
767     }
768     snew(vr, nf*DIM*DIM);
769     for (i = 0; i < nf; i++)
770     {
771         for (j = 0; j < DIM; j++)
772         {
773             for (k = 0; k < DIM; k++)
774             {
775                 vr[(i*DIM+j)*DIM+k] = vp[i][j][k];
776             }
777         }
778     }
779     ret = do_cpte_reals_low(xd, cptp, ecpt, sflags,
780                             nf*DIM*DIM, NULL, &vr, NULL, ecprMATRIX);
781     for (i = 0; i < nf; i++)
782     {
783         for (j = 0; j < DIM; j++)
784         {
785             for (k = 0; k < DIM; k++)
786             {
787                 vp[i][j][k] = vr[(i*DIM+j)*DIM+k];
788             }
789         }
790     }
791     sfree(vr);
792
793     if (list && ret == 0)
794     {
795         for (i = 0; i < nf; i++)
796         {
797             pr_rvecs(list, 0, st_names(cptp, ecpt), vp[i], DIM);
798         }
799     }
800     if (va)
801     {
802         sfree(va);
803     }
804
805     return ret;
806 }
807
808 static void do_cpt_header(XDR *xd, gmx_bool bRead, int *file_version,
809                           char **version, char **btime, char **buser, char **bhost,
810                           int *double_prec,
811                           char **fprog, char **ftime,
812                           int *eIntegrator, int *simulation_part,
813                           gmx_int64_t *step, double *t,
814                           int *nnodes, int *dd_nc, int *npme,
815                           int *natoms, int *ngtc, int *nnhpres, int *nhchainlength,
816                           int *nlambda, int *flags_state,
817                           int *flags_eks, int *flags_enh, int *flags_dfh,
818                           int *nED, int *eSwapCoords,
819                           FILE *list)
820 {
821     bool_t res = 0;
822     int    magic;
823     int    idum = 0;
824     int    i;
825     char  *fhost;
826
827     if (bRead)
828     {
829         magic = -1;
830     }
831     else
832     {
833         magic = CPT_MAGIC1;
834     }
835     res = xdr_int(xd, &magic);
836     if (res == 0)
837     {
838         gmx_fatal(FARGS, "The checkpoint file is empty/corrupted, or maybe you are out of disk space?");
839     }
840     if (magic != CPT_MAGIC1)
841     {
842         gmx_fatal(FARGS, "Start of file magic number mismatch, checkpoint file has %d, should be %d\n"
843                   "The checkpoint file is corrupted or not a checkpoint file",
844                   magic, CPT_MAGIC1);
845     }
846     if (!bRead)
847     {
848         snew(fhost, 255);
849         gmx_gethostname(fhost, 255);
850     }
851     do_cpt_string_err(xd, bRead, "GROMACS version", version, list);
852     do_cpt_string_err(xd, bRead, "GROMACS build time", btime, list);
853     do_cpt_string_err(xd, bRead, "GROMACS build user", buser, list);
854     do_cpt_string_err(xd, bRead, "GROMACS build host", bhost, list);
855     do_cpt_string_err(xd, bRead, "generating program", fprog, list);
856     do_cpt_string_err(xd, bRead, "generation time", ftime, list);
857     *file_version = cpt_version;
858     do_cpt_int_err(xd, "checkpoint file version", file_version, list);
859     if (*file_version > cpt_version)
860     {
861         gmx_fatal(FARGS, "Attempting to read a checkpoint file of version %d with code of version %d\n", *file_version, cpt_version);
862     }
863     if (*file_version >= 13)
864     {
865         do_cpt_int_err(xd, "GROMACS double precision", double_prec, list);
866     }
867     else
868     {
869         *double_prec = -1;
870     }
871     if (*file_version >= 12)
872     {
873         do_cpt_string_err(xd, bRead, "generating host", &fhost, list);
874         if (list == NULL)
875         {
876             sfree(fhost);
877         }
878     }
879     do_cpt_int_err(xd, "#atoms", natoms, list);
880     do_cpt_int_err(xd, "#T-coupling groups", ngtc, list);
881     if (*file_version >= 10)
882     {
883         do_cpt_int_err(xd, "#Nose-Hoover T-chains", nhchainlength, list);
884     }
885     else
886     {
887         *nhchainlength = 1;
888     }
889     if (*file_version >= 11)
890     {
891         do_cpt_int_err(xd, "#Nose-Hoover T-chains for barostat ", nnhpres, list);
892     }
893     else
894     {
895         *nnhpres = 0;
896     }
897     if (*file_version >= 14)
898     {
899         do_cpt_int_err(xd, "# of total lambda states ", nlambda, list);
900     }
901     else
902     {
903         *nlambda = 0;
904     }
905     do_cpt_int_err(xd, "integrator", eIntegrator, list);
906     if (*file_version >= 3)
907     {
908         do_cpt_int_err(xd, "simulation part #", simulation_part, list);
909     }
910     else
911     {
912         *simulation_part = 1;
913     }
914     if (*file_version >= 5)
915     {
916         do_cpt_step_err(xd, "step", step, list);
917     }
918     else
919     {
920         do_cpt_int_err(xd, "step", &idum, list);
921         *step = idum;
922     }
923     do_cpt_double_err(xd, "t", t, list);
924     do_cpt_int_err(xd, "#PP-nodes", nnodes, list);
925     idum = 1;
926     do_cpt_int_err(xd, "dd_nc[x]", dd_nc ? &(dd_nc[0]) : &idum, list);
927     do_cpt_int_err(xd, "dd_nc[y]", dd_nc ? &(dd_nc[1]) : &idum, list);
928     do_cpt_int_err(xd, "dd_nc[z]", dd_nc ? &(dd_nc[2]) : &idum, list);
929     do_cpt_int_err(xd, "#PME-only nodes", npme, list);
930     do_cpt_int_err(xd, "state flags", flags_state, list);
931     if (*file_version >= 4)
932     {
933         do_cpt_int_err(xd, "ekin data flags", flags_eks, list);
934         do_cpt_int_err(xd, "energy history flags", flags_enh, list);
935     }
936     else
937     {
938         *flags_eks   = 0;
939         *flags_enh   = (*flags_state >> (estORIRE_DTAV+1));
940         *flags_state = (*flags_state & ~((1<<(estORIRE_DTAV+1)) |
941                                          (1<<(estORIRE_DTAV+2)) |
942                                          (1<<(estORIRE_DTAV+3))));
943     }
944     if (*file_version >= 14)
945     {
946         do_cpt_int_err(xd, "df history flags", flags_dfh, list);
947     }
948     else
949     {
950         *flags_dfh = 0;
951     }
952
953     if (*file_version >= 15)
954     {
955         do_cpt_int_err(xd, "ED data sets", nED, list);
956     }
957     else
958     {
959         *nED = 0;
960     }
961     if (*file_version >= 16)
962     {
963         do_cpt_int_err(xd, "swap", eSwapCoords, list);
964     }
965 }
966
967 static int do_cpt_footer(XDR *xd, int file_version)
968 {
969     bool_t res = 0;
970     int    magic;
971
972     if (file_version >= 2)
973     {
974         magic = CPT_MAGIC2;
975         res   = xdr_int(xd, &magic);
976         if (res == 0)
977         {
978             cp_error();
979         }
980         if (magic != CPT_MAGIC2)
981         {
982             return -1;
983         }
984     }
985
986     return 0;
987 }
988
989 static int do_cpt_state(XDR *xd, gmx_bool bRead,
990                         int fflags, t_state *state,
991                         FILE *list)
992 {
993     int    sflags;
994     int    i;
995     int    ret;
996     int    nnht, nnhtp;
997
998     ret = 0;
999
1000     nnht  = state->nhchainlength*state->ngtc;
1001     nnhtp = state->nhchainlength*state->nnhpres;
1002
1003     if (bRead) /* we need to allocate space for dfhist if we are reading */
1004     {
1005         init_df_history(&state->dfhist, state->dfhist.nlambda);
1006     }
1007
1008     sflags = state->flags;
1009     for (i = 0; (i < estNR && ret == 0); i++)
1010     {
1011         if (fflags & (1<<i))
1012         {
1013             switch (i)
1014             {
1015                 case estLAMBDA:  ret      = do_cpte_reals(xd, cptpEST, i, sflags, efptNR, &(state->lambda), list); break;
1016                 case estFEPSTATE: ret     = do_cpte_int (xd, cptpEST, i, sflags, &state->fep_state, list); break;
1017                 case estBOX:     ret      = do_cpte_matrix(xd, cptpEST, i, sflags, state->box, list); break;
1018                 case estBOX_REL: ret      = do_cpte_matrix(xd, cptpEST, i, sflags, state->box_rel, list); break;
1019                 case estBOXV:    ret      = do_cpte_matrix(xd, cptpEST, i, sflags, state->boxv, list); break;
1020                 case estPRES_PREV: ret    = do_cpte_matrix(xd, cptpEST, i, sflags, state->pres_prev, list); break;
1021                 case estSVIR_PREV:  ret   = do_cpte_matrix(xd, cptpEST, i, sflags, state->svir_prev, list); break;
1022                 case estFVIR_PREV:  ret   = do_cpte_matrix(xd, cptpEST, i, sflags, state->fvir_prev, list); break;
1023                 case estNH_XI:   ret      = do_cpte_doubles(xd, cptpEST, i, sflags, nnht, &state->nosehoover_xi, list); break;
1024                 case estNH_VXI:  ret      = do_cpte_doubles(xd, cptpEST, i, sflags, nnht, &state->nosehoover_vxi, list); break;
1025                 case estNHPRES_XI:   ret  = do_cpte_doubles(xd, cptpEST, i, sflags, nnhtp, &state->nhpres_xi, list); break;
1026                 case estNHPRES_VXI:  ret  = do_cpte_doubles(xd, cptpEST, i, sflags, nnhtp, &state->nhpres_vxi, list); break;
1027                 case estTC_INT:  ret      = do_cpte_doubles(xd, cptpEST, i, sflags, state->ngtc, &state->therm_integral, list); break;
1028                 case estVETA:    ret      = do_cpte_real(xd, cptpEST, i, sflags, &state->veta, list); break;
1029                 case estVOL0:    ret      = do_cpte_real(xd, cptpEST, i, sflags, &state->vol0, list); break;
1030                 case estX:       ret      = do_cpte_rvecs(xd, cptpEST, i, sflags, state->natoms, &state->x, list); break;
1031                 case estV:       ret      = do_cpte_rvecs(xd, cptpEST, i, sflags, state->natoms, &state->v, list); break;
1032                 case estSDX:     ret      = do_cpte_rvecs(xd, cptpEST, i, sflags, state->natoms, &state->sd_X, list); break;
1033                 /* The RNG entries are no longer written,
1034                  * the next 4 lines are only for reading old files.
1035                  */
1036                 case estLD_RNG:  ret      = do_cpte_ints(xd, cptpEST, i, sflags, 0, NULL, list); break;
1037                 case estLD_RNGI: ret      = do_cpte_ints(xd, cptpEST, i, sflags, 0, NULL, list); break;
1038                 case estMC_RNG:  ret      = do_cpte_ints(xd, cptpEST, i, sflags, 0, NULL, list); break;
1039                 case estMC_RNGI: ret      = do_cpte_ints(xd, cptpEST, i, sflags, 0, NULL, list); break;
1040                 case estDISRE_INITF:  ret = do_cpte_real (xd, cptpEST, i, sflags, &state->hist.disre_initf, list); break;
1041                 case estDISRE_RM3TAV: ret = do_cpte_n_reals(xd, cptpEST, i, sflags, &state->hist.ndisrepairs, &state->hist.disre_rm3tav, list); break;
1042                 case estORIRE_INITF:  ret = do_cpte_real (xd, cptpEST, i, sflags, &state->hist.orire_initf, list); break;
1043                 case estORIRE_DTAV:   ret = do_cpte_n_reals(xd, cptpEST, i, sflags, &state->hist.norire_Dtav, &state->hist.orire_Dtav, list); break;
1044                 default:
1045                     gmx_fatal(FARGS, "Unknown state entry %d\n"
1046                               "You are probably reading a new checkpoint file with old code", i);
1047             }
1048         }
1049     }
1050
1051     return ret;
1052 }
1053
1054 static int do_cpt_ekinstate(XDR *xd, int fflags, ekinstate_t *ekins,
1055                             FILE *list)
1056 {
1057     int  i;
1058     int  ret;
1059
1060     ret = 0;
1061
1062     for (i = 0; (i < eeksNR && ret == 0); i++)
1063     {
1064         if (fflags & (1<<i))
1065         {
1066             switch (i)
1067             {
1068
1069                 case eeksEKIN_N:     ret = do_cpte_int(xd, cptpEEKS, i, fflags, &ekins->ekin_n, list); break;
1070                 case eeksEKINH:     ret  = do_cpte_matrices(xd, cptpEEKS, i, fflags, ekins->ekin_n, &ekins->ekinh, list); break;
1071                 case eeksEKINF:      ret = do_cpte_matrices(xd, cptpEEKS, i, fflags, ekins->ekin_n, &ekins->ekinf, list); break;
1072                 case eeksEKINO:      ret = do_cpte_matrices(xd, cptpEEKS, i, fflags, ekins->ekin_n, &ekins->ekinh_old, list); break;
1073                 case eeksEKINTOTAL:  ret = do_cpte_matrix(xd, cptpEEKS, i, fflags, ekins->ekin_total, list); break;
1074                 case eeksEKINSCALEF: ret = do_cpte_doubles(xd, cptpEEKS, i, fflags, ekins->ekin_n, &ekins->ekinscalef_nhc, list); break;
1075                 case eeksVSCALE:     ret = do_cpte_doubles(xd, 1, cptpEEKS, fflags, ekins->ekin_n, &ekins->vscale_nhc, list); break;
1076                 case eeksEKINSCALEH: ret = do_cpte_doubles(xd, 1, cptpEEKS, fflags, ekins->ekin_n, &ekins->ekinscaleh_nhc, list); break;
1077                 case eeksDEKINDL:   ret  = do_cpte_real(xd, 1, cptpEEKS, fflags, &ekins->dekindl, list); break;
1078                 case eeksMVCOS:      ret = do_cpte_real(xd, 1, cptpEEKS, fflags, &ekins->mvcos, list); break;
1079                 default:
1080                     gmx_fatal(FARGS, "Unknown ekin data state entry %d\n"
1081                               "You are probably reading a new checkpoint file with old code", i);
1082             }
1083         }
1084     }
1085
1086     return ret;
1087 }
1088
1089
1090 static int do_cpt_swapstate(XDR *xd, gmx_bool bRead, swapstate_t *swapstate, FILE *list)
1091 {
1092     int ii, ic, j;
1093     int ret              = 0;
1094     int swap_cpt_version = 1;
1095
1096
1097     if (eswapNO == swapstate->eSwapCoords)
1098     {
1099         return ret;
1100     }
1101
1102     swapstate->bFromCpt = bRead;
1103
1104     do_cpt_int_err(xd, "swap checkpoint version", &swap_cpt_version, list);
1105     do_cpt_int_err(xd, "swap coupling steps", &swapstate->nAverage, list);
1106
1107     /* When reading, init_swapcoords has not been called yet,
1108      * so we have to allocate memory first. */
1109
1110     for (ic = 0; ic < eCompNR; ic++)
1111     {
1112         for (ii = 0; ii < eIonNR; ii++)
1113         {
1114             if (bRead)
1115             {
1116                 do_cpt_int_err(xd, "swap requested atoms", &swapstate->nat_req[ic][ii], list);
1117             }
1118             else
1119             {
1120                 do_cpt_int_err(xd, "swap requested atoms p", swapstate->nat_req_p[ic][ii], list);
1121             }
1122
1123             if (bRead)
1124             {
1125                 do_cpt_int_err(xd, "swap influx netto", &swapstate->inflow_netto[ic][ii], list);
1126             }
1127             else
1128             {
1129                 do_cpt_int_err(xd, "swap influx netto p", swapstate->inflow_netto_p[ic][ii], list);
1130             }
1131
1132             if (bRead && (NULL == swapstate->nat_past[ic][ii]) )
1133             {
1134                 snew(swapstate->nat_past[ic][ii], swapstate->nAverage);
1135             }
1136
1137             for (j = 0; j < swapstate->nAverage; j++)
1138             {
1139                 if (bRead)
1140                 {
1141                     do_cpt_int_err(xd, "swap past atom counts", &swapstate->nat_past[ic][ii][j], list);
1142                 }
1143                 else
1144                 {
1145                     do_cpt_int_err(xd, "swap past atom counts p", &swapstate->nat_past_p[ic][ii][j], list);
1146                 }
1147             }
1148         }
1149     }
1150
1151     /* Ion flux per channel */
1152     for (ic = 0; ic < eChanNR; ic++)
1153     {
1154         for (ii = 0; ii < eIonNR; ii++)
1155         {
1156             if (bRead)
1157             {
1158                 do_cpt_int_err(xd, "channel flux", &swapstate->fluxfromAtoB[ic][ii], list);
1159             }
1160             else
1161             {
1162                 do_cpt_int_err(xd, "channel flux p", swapstate->fluxfromAtoB_p[ic][ii], list);
1163             }
1164         }
1165     }
1166
1167     /* Ion flux leakage */
1168     if (bRead)
1169     {
1170         snew(swapstate->fluxleak, 1);
1171     }
1172     do_cpt_int_err(xd, "flux leakage", swapstate->fluxleak, list);
1173
1174     /* Ion history */
1175     do_cpt_int_err(xd, "number of ions", &swapstate->nions, list);
1176
1177     if (bRead)
1178     {
1179         snew(swapstate->channel_label, swapstate->nions);
1180         snew(swapstate->comp_from, swapstate->nions);
1181     }
1182
1183     do_cpt_u_chars(xd, "channel history", swapstate->nions, swapstate->channel_label, list);
1184     do_cpt_u_chars(xd, "domain history", swapstate->nions, swapstate->comp_from, list);
1185
1186     /* Save the last known whole positions to checkpoint
1187      * file to be able to also make multimeric channels whole in PBC */
1188     do_cpt_int_err(xd, "Ch0 atoms", &swapstate->nat[eChan0], list);
1189     do_cpt_int_err(xd, "Ch1 atoms", &swapstate->nat[eChan1], list);
1190     if (bRead)
1191     {
1192         snew(swapstate->xc_old_whole[eChan0], swapstate->nat[eChan0]);
1193         snew(swapstate->xc_old_whole[eChan1], swapstate->nat[eChan1]);
1194         do_cpt_n_rvecs_err(xd, "Ch0 whole x", swapstate->nat[eChan0], swapstate->xc_old_whole[eChan0], list);
1195         do_cpt_n_rvecs_err(xd, "Ch1 whole x", swapstate->nat[eChan1], swapstate->xc_old_whole[eChan1], list);
1196     }
1197     else
1198     {
1199         do_cpt_n_rvecs_err(xd, "Ch0 whole x", swapstate->nat[eChan0], *swapstate->xc_old_whole_p[eChan0], list);
1200         do_cpt_n_rvecs_err(xd, "Ch1 whole x", swapstate->nat[eChan1], *swapstate->xc_old_whole_p[eChan1], list);
1201     }
1202
1203     return ret;
1204 }
1205
1206
1207 static int do_cpt_enerhist(XDR *xd, gmx_bool bRead,
1208                            int fflags, energyhistory_t *enerhist,
1209                            FILE *list)
1210 {
1211     int  i;
1212     int  j;
1213     int  ret;
1214
1215     ret = 0;
1216
1217     if (bRead)
1218     {
1219         enerhist->nsteps     = 0;
1220         enerhist->nsum       = 0;
1221         enerhist->nsteps_sim = 0;
1222         enerhist->nsum_sim   = 0;
1223         enerhist->dht        = NULL;
1224
1225         if (fflags & (1<< eenhENERGY_DELTA_H_NN) )
1226         {
1227             snew(enerhist->dht, 1);
1228             enerhist->dht->ndh              = NULL;
1229             enerhist->dht->dh               = NULL;
1230             enerhist->dht->start_lambda_set = FALSE;
1231         }
1232     }
1233
1234     for (i = 0; (i < eenhNR && ret == 0); i++)
1235     {
1236         if (fflags & (1<<i))
1237         {
1238             switch (i)
1239             {
1240                 case eenhENERGY_N:     ret = do_cpte_int(xd, cptpEENH, i, fflags, &enerhist->nener, list); break;
1241                 case eenhENERGY_AVER:  ret = do_cpte_doubles(xd, cptpEENH, i, fflags, enerhist->nener, &enerhist->ener_ave, list); break;
1242                 case eenhENERGY_SUM:   ret = do_cpte_doubles(xd, cptpEENH, i, fflags, enerhist->nener, &enerhist->ener_sum, list); break;
1243                 case eenhENERGY_NSUM:  do_cpt_step_err(xd, eenh_names[i], &enerhist->nsum, list); break;
1244                 case eenhENERGY_SUM_SIM: ret = do_cpte_doubles(xd, cptpEENH, i, fflags, enerhist->nener, &enerhist->ener_sum_sim, list); break;
1245                 case eenhENERGY_NSUM_SIM:   do_cpt_step_err(xd, eenh_names[i], &enerhist->nsum_sim, list); break;
1246                 case eenhENERGY_NSTEPS:     do_cpt_step_err(xd, eenh_names[i], &enerhist->nsteps, list); break;
1247                 case eenhENERGY_NSTEPS_SIM: do_cpt_step_err(xd, eenh_names[i], &enerhist->nsteps_sim, list); break;
1248                 case eenhENERGY_DELTA_H_NN: do_cpt_int_err(xd, eenh_names[i], &(enerhist->dht->nndh), list);
1249                     if (bRead) /* now allocate memory for it */
1250                     {
1251                         snew(enerhist->dht->dh, enerhist->dht->nndh);
1252                         snew(enerhist->dht->ndh, enerhist->dht->nndh);
1253                         for (j = 0; j < enerhist->dht->nndh; j++)
1254                         {
1255                             enerhist->dht->ndh[j] = 0;
1256                             enerhist->dht->dh[j]  = NULL;
1257                         }
1258                     }
1259                     break;
1260                 case eenhENERGY_DELTA_H_LIST:
1261                     for (j = 0; j < enerhist->dht->nndh; j++)
1262                     {
1263                         ret = do_cpte_n_reals(xd, cptpEENH, i, fflags, &enerhist->dht->ndh[j], &(enerhist->dht->dh[j]), list);
1264                     }
1265                     break;
1266                 case eenhENERGY_DELTA_H_STARTTIME:
1267                     ret = do_cpte_double(xd, cptpEENH, i, fflags, &(enerhist->dht->start_time), list); break;
1268                 case eenhENERGY_DELTA_H_STARTLAMBDA:
1269                     ret = do_cpte_double(xd, cptpEENH, i, fflags, &(enerhist->dht->start_lambda), list); break;
1270                 default:
1271                     gmx_fatal(FARGS, "Unknown energy history entry %d\n"
1272                               "You are probably reading a new checkpoint file with old code", i);
1273             }
1274         }
1275     }
1276
1277     if ((fflags & (1<<eenhENERGY_SUM)) && !(fflags & (1<<eenhENERGY_SUM_SIM)))
1278     {
1279         /* Assume we have an old file format and copy sum to sum_sim */
1280         srenew(enerhist->ener_sum_sim, enerhist->nener);
1281         for (i = 0; i < enerhist->nener; i++)
1282         {
1283             enerhist->ener_sum_sim[i] = enerhist->ener_sum[i];
1284         }
1285     }
1286
1287     if ( (fflags & (1<<eenhENERGY_NSUM)) &&
1288          !(fflags & (1<<eenhENERGY_NSTEPS)))
1289     {
1290         /* Assume we have an old file format and copy nsum to nsteps */
1291         enerhist->nsteps = enerhist->nsum;
1292     }
1293     if ( (fflags & (1<<eenhENERGY_NSUM_SIM)) &&
1294          !(fflags & (1<<eenhENERGY_NSTEPS_SIM)))
1295     {
1296         /* Assume we have an old file format and copy nsum to nsteps */
1297         enerhist->nsteps_sim = enerhist->nsum_sim;
1298     }
1299
1300     return ret;
1301 }
1302
1303 static int do_cpt_df_hist(XDR *xd, int fflags, df_history_t *dfhist, FILE *list)
1304 {
1305     int  i, nlambda;
1306     int  ret;
1307
1308     nlambda = dfhist->nlambda;
1309     ret     = 0;
1310
1311     for (i = 0; (i < edfhNR && ret == 0); i++)
1312     {
1313         if (fflags & (1<<i))
1314         {
1315             switch (i)
1316             {
1317                 case edfhBEQUIL:       ret = do_cpte_int(xd, cptpEDFH, i, fflags, &dfhist->bEquil, list); break;
1318                 case edfhNATLAMBDA:    ret = do_cpte_ints(xd, cptpEDFH, i, fflags, nlambda, &dfhist->n_at_lam, list); break;
1319                 case edfhWLHISTO:      ret = do_cpte_reals(xd, cptpEDFH, i, fflags, nlambda, &dfhist->wl_histo, list); break;
1320                 case edfhWLDELTA:      ret = do_cpte_real(xd, cptpEDFH, i, fflags, &dfhist->wl_delta, list); break;
1321                 case edfhSUMWEIGHTS:   ret = do_cpte_reals(xd, cptpEDFH, i, fflags, nlambda, &dfhist->sum_weights, list); break;
1322                 case edfhSUMDG:        ret = do_cpte_reals(xd, cptpEDFH, i, fflags, nlambda, &dfhist->sum_dg, list); break;
1323                 case edfhSUMMINVAR:    ret = do_cpte_reals(xd, cptpEDFH, i, fflags, nlambda, &dfhist->sum_minvar, list); break;
1324                 case edfhSUMVAR:       ret = do_cpte_reals(xd, cptpEDFH, i, fflags, nlambda, &dfhist->sum_variance, list); break;
1325                 case edfhACCUMP:       ret = do_cpte_nmatrix(xd, cptpEDFH, i, fflags, nlambda, dfhist->accum_p, list); break;
1326                 case edfhACCUMM:       ret = do_cpte_nmatrix(xd, cptpEDFH, i, fflags, nlambda, dfhist->accum_m, list); break;
1327                 case edfhACCUMP2:      ret = do_cpte_nmatrix(xd, cptpEDFH, i, fflags, nlambda, dfhist->accum_p2, list); break;
1328                 case edfhACCUMM2:      ret = do_cpte_nmatrix(xd, cptpEDFH, i, fflags, nlambda, dfhist->accum_m2, list); break;
1329                 case edfhTIJ:          ret = do_cpte_nmatrix(xd, cptpEDFH, i, fflags, nlambda, dfhist->Tij, list); break;
1330                 case edfhTIJEMP:       ret = do_cpte_nmatrix(xd, cptpEDFH, i, fflags, nlambda, dfhist->Tij_empirical, list); break;
1331
1332                 default:
1333                     gmx_fatal(FARGS, "Unknown df history entry %d\n"
1334                               "You are probably reading a new checkpoint file with old code", i);
1335             }
1336         }
1337     }
1338
1339     return ret;
1340 }
1341
1342
1343 /* This function stores the last whole configuration of the reference and
1344  * average structure in the .cpt file
1345  */
1346 static int do_cpt_EDstate(XDR *xd, gmx_bool bRead,
1347                           edsamstate_t *EDstate, FILE *list)
1348 {
1349     int  i, j;
1350     int  ret = 0;
1351     char buf[STRLEN];
1352
1353
1354     EDstate->bFromCpt = bRead;
1355
1356     if (EDstate->nED <= 0)
1357     {
1358         return ret;
1359     }
1360
1361     /* When reading, init_edsam has not been called yet,
1362      * so we have to allocate memory first. */
1363     if (bRead)
1364     {
1365         snew(EDstate->nref, EDstate->nED);
1366         snew(EDstate->old_sref, EDstate->nED);
1367         snew(EDstate->nav, EDstate->nED);
1368         snew(EDstate->old_sav, EDstate->nED);
1369     }
1370
1371     /* Read/write the last whole conformation of SREF and SAV for each ED dataset (usually only one) */
1372     for (i = 0; i < EDstate->nED; i++)
1373     {
1374         /* Reference structure SREF */
1375         sprintf(buf, "ED%d # of atoms in reference structure", i+1);
1376         do_cpt_int_err(xd, buf, &EDstate->nref[i], list);
1377         sprintf(buf, "ED%d x_ref", i+1);
1378         if (bRead)
1379         {
1380             snew(EDstate->old_sref[i], EDstate->nref[i]);
1381             do_cpt_n_rvecs_err(xd, buf, EDstate->nref[i], EDstate->old_sref[i], list);
1382         }
1383         else
1384         {
1385             do_cpt_n_rvecs_err(xd, buf, EDstate->nref[i], EDstate->old_sref_p[i], list);
1386         }
1387
1388         /* Average structure SAV */
1389         sprintf(buf, "ED%d # of atoms in average structure", i+1);
1390         do_cpt_int_err(xd, buf, &EDstate->nav[i], list);
1391         sprintf(buf, "ED%d x_av", i+1);
1392         if (bRead)
1393         {
1394             snew(EDstate->old_sav[i], EDstate->nav[i]);
1395             do_cpt_n_rvecs_err(xd, buf, EDstate->nav[i], EDstate->old_sav[i], list);
1396         }
1397         else
1398         {
1399             do_cpt_n_rvecs_err(xd, buf, EDstate->nav[i], EDstate->old_sav_p[i], list);
1400         }
1401     }
1402
1403     return ret;
1404 }
1405
1406
1407 static int do_cpt_files(XDR *xd, gmx_bool bRead,
1408                         gmx_file_position_t **p_outputfiles, int *nfiles,
1409                         FILE *list, int file_version)
1410 {
1411     int                  i, j;
1412     gmx_off_t            offset;
1413     gmx_off_t            mask = 0xFFFFFFFFL;
1414     int                  offset_high, offset_low;
1415     char                *buf;
1416     gmx_file_position_t *outputfiles;
1417
1418     if (do_cpt_int(xd, "number of output files", nfiles, list) != 0)
1419     {
1420         return -1;
1421     }
1422
1423     if (bRead)
1424     {
1425         snew(*p_outputfiles, *nfiles);
1426     }
1427
1428     outputfiles = *p_outputfiles;
1429
1430     for (i = 0; i < *nfiles; i++)
1431     {
1432         /* 64-bit XDR numbers are not portable, so it is stored as separate high/low fractions */
1433         if (bRead)
1434         {
1435             do_cpt_string_err(xd, bRead, "output filename", &buf, list);
1436             strncpy(outputfiles[i].filename, buf, CPTSTRLEN-1);
1437             if (list == NULL)
1438             {
1439                 sfree(buf);
1440             }
1441
1442             if (do_cpt_int(xd, "file_offset_high", &offset_high, list) != 0)
1443             {
1444                 return -1;
1445             }
1446             if (do_cpt_int(xd, "file_offset_low", &offset_low, list) != 0)
1447             {
1448                 return -1;
1449             }
1450             outputfiles[i].offset = ( ((gmx_off_t) offset_high) << 32 ) | ( (gmx_off_t) offset_low & mask );
1451         }
1452         else
1453         {
1454             buf = outputfiles[i].filename;
1455             do_cpt_string_err(xd, bRead, "output filename", &buf, list);
1456             /* writing */
1457             offset      = outputfiles[i].offset;
1458             if (offset == -1)
1459             {
1460                 offset_low  = -1;
1461                 offset_high = -1;
1462             }
1463             else
1464             {
1465                 offset_low  = (int) (offset & mask);
1466                 offset_high = (int) ((offset >> 32) & mask);
1467             }
1468             if (do_cpt_int(xd, "file_offset_high", &offset_high, list) != 0)
1469             {
1470                 return -1;
1471             }
1472             if (do_cpt_int(xd, "file_offset_low", &offset_low, list) != 0)
1473             {
1474                 return -1;
1475             }
1476         }
1477         if (file_version >= 8)
1478         {
1479             if (do_cpt_int(xd, "file_checksum_size", &(outputfiles[i].chksum_size),
1480                            list) != 0)
1481             {
1482                 return -1;
1483             }
1484             if (do_cpt_u_chars(xd, "file_checksum", 16, outputfiles[i].chksum, list) != 0)
1485             {
1486                 return -1;
1487             }
1488         }
1489         else
1490         {
1491             outputfiles[i].chksum_size = -1;
1492         }
1493     }
1494     return 0;
1495 }
1496
1497
1498 void write_checkpoint(const char *fn, gmx_bool bNumberAndKeep,
1499                       FILE *fplog, t_commrec *cr,
1500                       int eIntegrator, int simulation_part,
1501                       gmx_bool bExpanded, int elamstats,
1502                       gmx_int64_t step, double t, t_state *state)
1503 {
1504     t_fileio            *fp;
1505     int                  file_version;
1506     char                *version;
1507     char                *btime;
1508     char                *buser;
1509     char                *bhost;
1510     int                  double_prec;
1511     char                *fprog;
1512     char                *fntemp; /* the temporary checkpoint file name */
1513     time_t               now;
1514     char                 timebuf[STRLEN];
1515     int                  nppnodes, npmenodes, flag_64bit;
1516     char                 buf[1024], suffix[5+STEPSTRSIZE], sbuf[STEPSTRSIZE];
1517     gmx_file_position_t *outputfiles;
1518     int                  noutputfiles;
1519     char                *ftime;
1520     int                  flags_eks, flags_enh, flags_dfh, i;
1521     t_fileio            *ret;
1522
1523     if (DOMAINDECOMP(cr))
1524     {
1525         nppnodes  = cr->dd->nnodes;
1526         npmenodes = cr->npmenodes;
1527     }
1528     else
1529     {
1530         nppnodes  = 1;
1531         npmenodes = 0;
1532     }
1533
1534 #ifndef GMX_NO_RENAME
1535     /* make the new temporary filename */
1536     snew(fntemp, strlen(fn)+5+STEPSTRSIZE);
1537     strcpy(fntemp, fn);
1538     fntemp[strlen(fn) - strlen(ftp2ext(fn2ftp(fn))) - 1] = '\0';
1539     sprintf(suffix, "_%s%s", "step", gmx_step_str(step, sbuf));
1540     strcat(fntemp, suffix);
1541     strcat(fntemp, fn+strlen(fn) - strlen(ftp2ext(fn2ftp(fn))) - 1);
1542 #else
1543     /* if we can't rename, we just overwrite the cpt file.
1544      * dangerous if interrupted.
1545      */
1546     snew(fntemp, strlen(fn));
1547     strcpy(fntemp, fn);
1548 #endif
1549     time(&now);
1550     gmx_ctime_r(&now, timebuf, STRLEN);
1551
1552     if (fplog)
1553     {
1554         fprintf(fplog, "Writing checkpoint, step %s at %s\n\n",
1555                 gmx_step_str(step, buf), timebuf);
1556     }
1557
1558     /* Get offsets for open files */
1559     gmx_fio_get_output_file_positions(&outputfiles, &noutputfiles);
1560
1561     fp = gmx_fio_open(fntemp, "w");
1562
1563     if (state->ekinstate.bUpToDate)
1564     {
1565         flags_eks =
1566             ((1<<eeksEKIN_N) | (1<<eeksEKINH) | (1<<eeksEKINF) |
1567              (1<<eeksEKINO) | (1<<eeksEKINSCALEF) | (1<<eeksEKINSCALEH) |
1568              (1<<eeksVSCALE) | (1<<eeksDEKINDL) | (1<<eeksMVCOS));
1569     }
1570     else
1571     {
1572         flags_eks = 0;
1573     }
1574
1575     flags_enh = 0;
1576     if (state->enerhist.nsum > 0 || state->enerhist.nsum_sim > 0)
1577     {
1578         flags_enh |= (1<<eenhENERGY_N);
1579         if (state->enerhist.nsum > 0)
1580         {
1581             flags_enh |= ((1<<eenhENERGY_AVER) | (1<<eenhENERGY_SUM) |
1582                           (1<<eenhENERGY_NSTEPS) | (1<<eenhENERGY_NSUM));
1583         }
1584         if (state->enerhist.nsum_sim > 0)
1585         {
1586             flags_enh |= ((1<<eenhENERGY_SUM_SIM) | (1<<eenhENERGY_NSTEPS_SIM) |
1587                           (1<<eenhENERGY_NSUM_SIM));
1588         }
1589         if (state->enerhist.dht)
1590         {
1591             flags_enh |= ( (1<< eenhENERGY_DELTA_H_NN) |
1592                            (1<< eenhENERGY_DELTA_H_LIST) |
1593                            (1<< eenhENERGY_DELTA_H_STARTTIME) |
1594                            (1<< eenhENERGY_DELTA_H_STARTLAMBDA) );
1595         }
1596     }
1597
1598     if (bExpanded)
1599     {
1600         flags_dfh = ((1<<edfhBEQUIL) | (1<<edfhNATLAMBDA) | (1<<edfhSUMWEIGHTS) |  (1<<edfhSUMDG)  |
1601                      (1<<edfhTIJ) | (1<<edfhTIJEMP));
1602         if (EWL(elamstats))
1603         {
1604             flags_dfh |= ((1<<edfhWLDELTA) | (1<<edfhWLHISTO));
1605         }
1606         if ((elamstats == elamstatsMINVAR) || (elamstats == elamstatsBARKER) || (elamstats == elamstatsMETROPOLIS))
1607         {
1608             flags_dfh |= ((1<<edfhACCUMP) | (1<<edfhACCUMM) | (1<<edfhACCUMP2) | (1<<edfhACCUMM2)
1609                           | (1<<edfhSUMMINVAR) | (1<<edfhSUMVAR));
1610         }
1611     }
1612     else
1613     {
1614         flags_dfh = 0;
1615     }
1616
1617     /* We can check many more things now (CPU, acceleration, etc), but
1618      * it is highly unlikely to have two separate builds with exactly
1619      * the same version, user, time, and build host!
1620      */
1621
1622     version = gmx_strdup(gmx_version());
1623     btime   = gmx_strdup(BUILD_TIME);
1624     buser   = gmx_strdup(BUILD_USER);
1625     bhost   = gmx_strdup(BUILD_HOST);
1626
1627     double_prec = GMX_CPT_BUILD_DP;
1628     fprog       = gmx_strdup(Program());
1629
1630     ftime   = &(timebuf[0]);
1631
1632     do_cpt_header(gmx_fio_getxdr(fp), FALSE, &file_version,
1633                   &version, &btime, &buser, &bhost, &double_prec, &fprog, &ftime,
1634                   &eIntegrator, &simulation_part, &step, &t, &nppnodes,
1635                   DOMAINDECOMP(cr) ? cr->dd->nc : NULL, &npmenodes,
1636                   &state->natoms, &state->ngtc, &state->nnhpres,
1637                   &state->nhchainlength, &(state->dfhist.nlambda), &state->flags, &flags_eks, &flags_enh, &flags_dfh,
1638                   &state->edsamstate.nED, &state->swapstate.eSwapCoords,
1639                   NULL);
1640
1641     sfree(version);
1642     sfree(btime);
1643     sfree(buser);
1644     sfree(bhost);
1645     sfree(fprog);
1646
1647     if ((do_cpt_state(gmx_fio_getxdr(fp), FALSE, state->flags, state, NULL) < 0)        ||
1648         (do_cpt_ekinstate(gmx_fio_getxdr(fp), flags_eks, &state->ekinstate, NULL) < 0) ||
1649         (do_cpt_enerhist(gmx_fio_getxdr(fp), FALSE, flags_enh, &state->enerhist, NULL) < 0)  ||
1650         (do_cpt_df_hist(gmx_fio_getxdr(fp), flags_dfh, &state->dfhist, NULL) < 0)  ||
1651         (do_cpt_EDstate(gmx_fio_getxdr(fp), FALSE, &state->edsamstate, NULL) < 0)      ||
1652         (do_cpt_swapstate(gmx_fio_getxdr(fp), FALSE, &state->swapstate, NULL) < 0) ||
1653         (do_cpt_files(gmx_fio_getxdr(fp), FALSE, &outputfiles, &noutputfiles, NULL,
1654                       file_version) < 0))
1655     {
1656         gmx_file("Cannot read/write checkpoint; corrupt file, or maybe you are out of disk space?");
1657     }
1658
1659     do_cpt_footer(gmx_fio_getxdr(fp), file_version);
1660
1661     /* we really, REALLY, want to make sure to physically write the checkpoint,
1662        and all the files it depends on, out to disk. Because we've
1663        opened the checkpoint with gmx_fio_open(), it's in our list
1664        of open files.  */
1665     ret = gmx_fio_all_output_fsync();
1666
1667     if (ret)
1668     {
1669         char buf[STRLEN];
1670         sprintf(buf,
1671                 "Cannot fsync '%s'; maybe you are out of disk space?",
1672                 gmx_fio_getname(ret));
1673
1674         if (getenv(GMX_IGNORE_FSYNC_FAILURE_ENV) == NULL)
1675         {
1676             gmx_file(buf);
1677         }
1678         else
1679         {
1680             gmx_warning(buf);
1681         }
1682     }
1683
1684     if (gmx_fio_close(fp) != 0)
1685     {
1686         gmx_file("Cannot read/write checkpoint; corrupt file, or maybe you are out of disk space?");
1687     }
1688
1689     /* we don't move the checkpoint if the user specified they didn't want it,
1690        or if the fsyncs failed */
1691 #ifndef GMX_NO_RENAME
1692     if (!bNumberAndKeep && !ret)
1693     {
1694         if (gmx_fexist(fn))
1695         {
1696             /* Rename the previous checkpoint file */
1697             strcpy(buf, fn);
1698             buf[strlen(fn) - strlen(ftp2ext(fn2ftp(fn))) - 1] = '\0';
1699             strcat(buf, "_prev");
1700             strcat(buf, fn+strlen(fn) - strlen(ftp2ext(fn2ftp(fn))) - 1);
1701 #ifndef GMX_FAHCORE
1702             /* we copy here so that if something goes wrong between now and
1703              * the rename below, there's always a state.cpt.
1704              * If renames are atomic (such as in POSIX systems),
1705              * this copying should be unneccesary.
1706              */
1707             gmx_file_copy(fn, buf, FALSE);
1708             /* We don't really care if this fails:
1709              * there's already a new checkpoint.
1710              */
1711 #else
1712             gmx_file_rename(fn, buf);
1713 #endif
1714         }
1715         if (gmx_file_rename(fntemp, fn) != 0)
1716         {
1717             gmx_file("Cannot rename checkpoint file; maybe you are out of disk space?");
1718         }
1719     }
1720 #endif  /* GMX_NO_RENAME */
1721
1722     sfree(outputfiles);
1723     sfree(fntemp);
1724
1725 #ifdef GMX_FAHCORE
1726     /*code for alternate checkpointing scheme.  moved from top of loop over
1727        steps */
1728     fcRequestCheckPoint();
1729     if (fcCheckPointParallel( cr->nodeid, NULL, 0) == 0)
1730     {
1731         gmx_fatal( 3, __FILE__, __LINE__, "Checkpoint error on step %d\n", step );
1732     }
1733 #endif /* end GMX_FAHCORE block */
1734 }
1735
1736 static void print_flag_mismatch(FILE *fplog, int sflags, int fflags)
1737 {
1738     int i;
1739
1740     fprintf(fplog, "\nState entry mismatch between the simulation and the checkpoint file\n");
1741     fprintf(fplog, "Entries which are not present in the checkpoint file will not be updated\n");
1742     fprintf(fplog, "  %24s    %11s    %11s\n", "", "simulation", "checkpoint");
1743     for (i = 0; i < estNR; i++)
1744     {
1745         if ((sflags & (1<<i)) || (fflags & (1<<i)))
1746         {
1747             fprintf(fplog, "  %24s    %11s    %11s\n",
1748                     est_names[i],
1749                     (sflags & (1<<i)) ? "  present  " : "not present",
1750                     (fflags & (1<<i)) ? "  present  " : "not present");
1751         }
1752     }
1753 }
1754
1755 static void check_int(FILE *fplog, const char *type, int p, int f, gmx_bool *mm)
1756 {
1757     FILE *fp = fplog ? fplog : stderr;
1758
1759     if (p != f)
1760     {
1761         fprintf(fp, "  %s mismatch,\n", type);
1762         fprintf(fp, "    current program: %d\n", p);
1763         fprintf(fp, "    checkpoint file: %d\n", f);
1764         fprintf(fp, "\n");
1765         *mm = TRUE;
1766     }
1767 }
1768
1769 static void check_string(FILE *fplog, const char *type, const char *p,
1770                          const char *f, gmx_bool *mm)
1771 {
1772     FILE *fp = fplog ? fplog : stderr;
1773
1774     if (strcmp(p, f) != 0)
1775     {
1776         fprintf(fp, "  %s mismatch,\n", type);
1777         fprintf(fp, "    current program: %s\n", p);
1778         fprintf(fp, "    checkpoint file: %s\n", f);
1779         fprintf(fp, "\n");
1780         *mm = TRUE;
1781     }
1782 }
1783
1784 static void check_match(FILE *fplog,
1785                         char *version,
1786                         char *btime, char *buser, char *bhost, int double_prec,
1787                         char *fprog,
1788                         t_commrec *cr, int npp_f, int npme_f,
1789                         ivec dd_nc, ivec dd_nc_f)
1790 {
1791     int      npp;
1792     gmx_bool mm;
1793
1794     mm = FALSE;
1795
1796     check_string(fplog, "Version", gmx_version(), version, &mm);
1797     check_string(fplog, "Build time", BUILD_TIME, btime, &mm);
1798     check_string(fplog, "Build user", BUILD_USER, buser, &mm);
1799     check_string(fplog, "Build host", BUILD_HOST, bhost, &mm);
1800     check_int   (fplog, "Double prec.", GMX_CPT_BUILD_DP, double_prec, &mm);
1801     check_string(fplog, "Program name", Program(), fprog, &mm);
1802
1803     check_int   (fplog, "#nodes", cr->nnodes, npp_f+npme_f, &mm);
1804     if (cr->nnodes > 1)
1805     {
1806         check_int (fplog, "#PME-nodes", cr->npmenodes, npme_f, &mm);
1807
1808         npp = cr->nnodes;
1809         if (cr->npmenodes >= 0)
1810         {
1811             npp -= cr->npmenodes;
1812         }
1813         if (npp == npp_f)
1814         {
1815             check_int (fplog, "#DD-cells[x]", dd_nc[XX], dd_nc_f[XX], &mm);
1816             check_int (fplog, "#DD-cells[y]", dd_nc[YY], dd_nc_f[YY], &mm);
1817             check_int (fplog, "#DD-cells[z]", dd_nc[ZZ], dd_nc_f[ZZ], &mm);
1818         }
1819     }
1820
1821     if (mm)
1822     {
1823         fprintf(stderr,
1824                 "Gromacs binary or parallel settings not identical to previous run.\n"
1825                 "Continuation is exact, but is not guaranteed to be binary identical%s.\n\n",
1826                 fplog ? ",\n see the log file for details" : "");
1827
1828         if (fplog)
1829         {
1830             fprintf(fplog,
1831                     "Gromacs binary or parallel settings not identical to previous run.\n"
1832                     "Continuation is exact, but is not guaranteed to be binary identical.\n\n");
1833         }
1834     }
1835 }
1836
1837 static void read_checkpoint(const char *fn, FILE **pfplog,
1838                             t_commrec *cr, ivec dd_nc,
1839                             int eIntegrator, int *init_fep_state, gmx_int64_t *step, double *t,
1840                             t_state *state, gmx_bool *bReadEkin,
1841                             int *simulation_part,
1842                             gmx_bool bAppendOutputFiles, gmx_bool bForceAppend)
1843 {
1844     t_fileio            *fp;
1845     int                  i, j, rc;
1846     int                  file_version;
1847     char                *version, *btime, *buser, *bhost, *fprog, *ftime;
1848     int                  double_prec;
1849     char                 filename[STRLEN], buf[STEPSTRSIZE];
1850     int                  nppnodes, eIntegrator_f, nppnodes_f, npmenodes_f;
1851     ivec                 dd_nc_f;
1852     int                  natoms, ngtc, nnhpres, nhchainlength, nlambda, fflags, flags_eks, flags_enh, flags_dfh;
1853     int                  d;
1854     int                  ret;
1855     gmx_file_position_t *outputfiles;
1856     int                  nfiles;
1857     t_fileio            *chksum_file;
1858     FILE               * fplog = *pfplog;
1859     unsigned char        digest[16];
1860 #if !defined __native_client__ && !defined GMX_NATIVE_WINDOWS
1861     struct flock         fl; /* don't initialize here: the struct order is OS
1862                                 dependent! */
1863 #endif
1864
1865     const char *int_warn =
1866         "WARNING: The checkpoint file was generated with integrator %s,\n"
1867         "         while the simulation uses integrator %s\n\n";
1868
1869 #if !defined __native_client__ && !defined GMX_NATIVE_WINDOWS
1870     fl.l_type   = F_WRLCK;
1871     fl.l_whence = SEEK_SET;
1872     fl.l_start  = 0;
1873     fl.l_len    = 0;
1874     fl.l_pid    = 0;
1875 #endif
1876
1877     fp = gmx_fio_open(fn, "r");
1878     do_cpt_header(gmx_fio_getxdr(fp), TRUE, &file_version,
1879                   &version, &btime, &buser, &bhost, &double_prec, &fprog, &ftime,
1880                   &eIntegrator_f, simulation_part, step, t,
1881                   &nppnodes_f, dd_nc_f, &npmenodes_f,
1882                   &natoms, &ngtc, &nnhpres, &nhchainlength, &nlambda,
1883                   &fflags, &flags_eks, &flags_enh, &flags_dfh,
1884                   &state->edsamstate.nED, &state->swapstate.eSwapCoords, NULL);
1885
1886     if (bAppendOutputFiles &&
1887         file_version >= 13 && double_prec != GMX_CPT_BUILD_DP)
1888     {
1889         gmx_fatal(FARGS, "Output file appending requested, but the code and checkpoint file precision (single/double) don't match");
1890     }
1891
1892     if (cr == NULL || MASTER(cr))
1893     {
1894         fprintf(stderr, "\nReading checkpoint file %s generated: %s\n\n",
1895                 fn, ftime);
1896     }
1897
1898     /* This will not be written if we do appending, since fplog is still NULL then */
1899     if (fplog)
1900     {
1901         fprintf(fplog, "\n");
1902         fprintf(fplog, "Reading checkpoint file %s\n", fn);
1903         fprintf(fplog, "  file generated by:     %s\n", fprog);
1904         fprintf(fplog, "  file generated at:     %s\n", ftime);
1905         fprintf(fplog, "  GROMACS build time:    %s\n", btime);
1906         fprintf(fplog, "  GROMACS build user:    %s\n", buser);
1907         fprintf(fplog, "  GROMACS build host:    %s\n", bhost);
1908         fprintf(fplog, "  GROMACS double prec.:  %d\n", double_prec);
1909         fprintf(fplog, "  simulation part #:     %d\n", *simulation_part);
1910         fprintf(fplog, "  step:                  %s\n", gmx_step_str(*step, buf));
1911         fprintf(fplog, "  time:                  %f\n", *t);
1912         fprintf(fplog, "\n");
1913     }
1914
1915     if (natoms != state->natoms)
1916     {
1917         gmx_fatal(FARGS, "Checkpoint file is for a system of %d atoms, while the current system consists of %d atoms", natoms, state->natoms);
1918     }
1919     if (ngtc != state->ngtc)
1920     {
1921         gmx_fatal(FARGS, "Checkpoint file is for a system of %d T-coupling groups, while the current system consists of %d T-coupling groups", ngtc, state->ngtc);
1922     }
1923     if (nnhpres != state->nnhpres)
1924     {
1925         gmx_fatal(FARGS, "Checkpoint file is for a system of %d NH-pressure-coupling variables, while the current system consists of %d NH-pressure-coupling variables", nnhpres, state->nnhpres);
1926     }
1927
1928     if (nlambda != state->dfhist.nlambda)
1929     {
1930         gmx_fatal(FARGS, "Checkpoint file is for a system with %d lambda states, while the current system consists of %d lambda states", nlambda, state->dfhist.nlambda);
1931     }
1932
1933     init_gtc_state(state, state->ngtc, state->nnhpres, nhchainlength); /* need to keep this here to keep the tpr format working */
1934     /* write over whatever was read; we use the number of Nose-Hoover chains from the checkpoint */
1935
1936     if (eIntegrator_f != eIntegrator)
1937     {
1938         if (MASTER(cr))
1939         {
1940             fprintf(stderr, int_warn, EI(eIntegrator_f), EI(eIntegrator));
1941         }
1942         if (bAppendOutputFiles)
1943         {
1944             gmx_fatal(FARGS,
1945                       "Output file appending requested, but input/checkpoint integrators do not match.\n"
1946                       "Stopping the run to prevent you from ruining all your data...\n"
1947                       "If you _really_ know what you are doing, try with the -noappend option.\n");
1948         }
1949         if (fplog)
1950         {
1951             fprintf(fplog, int_warn, EI(eIntegrator_f), EI(eIntegrator));
1952         }
1953     }
1954
1955     if (!PAR(cr))
1956     {
1957         nppnodes      = 1;
1958         cr->npmenodes = 0;
1959     }
1960     else if (cr->nnodes == nppnodes_f + npmenodes_f)
1961     {
1962         if (cr->npmenodes < 0)
1963         {
1964             cr->npmenodes = npmenodes_f;
1965         }
1966         nppnodes = cr->nnodes - cr->npmenodes;
1967         if (nppnodes == nppnodes_f)
1968         {
1969             for (d = 0; d < DIM; d++)
1970             {
1971                 if (dd_nc[d] == 0)
1972                 {
1973                     dd_nc[d] = dd_nc_f[d];
1974                 }
1975             }
1976         }
1977     }
1978     else
1979     {
1980         /* The number of PP nodes has not been set yet */
1981         nppnodes = -1;
1982     }
1983
1984     if (fflags != state->flags)
1985     {
1986
1987         if (MASTER(cr))
1988         {
1989             if (bAppendOutputFiles)
1990             {
1991                 gmx_fatal(FARGS,
1992                           "Output file appending requested, but input and checkpoint states are not identical.\n"
1993                           "Stopping the run to prevent you from ruining all your data...\n"
1994                           "You can try with the -noappend option, and get more info in the log file.\n");
1995             }
1996
1997             if (getenv("GMX_ALLOW_CPT_MISMATCH") == NULL)
1998             {
1999                 gmx_fatal(FARGS, "You seem to have switched ensemble, integrator, T and/or P-coupling algorithm between the cpt and tpr file. The recommended way of doing this is passing the cpt file to grompp (with option -t) instead of to mdrun. If you know what you are doing, you can override this error by setting the env.var. GMX_ALLOW_CPT_MISMATCH");
2000             }
2001             else
2002             {
2003                 fprintf(stderr,
2004                         "WARNING: The checkpoint state entries do not match the simulation,\n"
2005                         "         see the log file for details\n\n");
2006             }
2007         }
2008
2009         if (fplog)
2010         {
2011             print_flag_mismatch(fplog, state->flags, fflags);
2012         }
2013     }
2014     else
2015     {
2016         if (MASTER(cr))
2017         {
2018             check_match(fplog, version, btime, buser, bhost, double_prec, fprog,
2019                         cr, nppnodes_f, npmenodes_f, dd_nc, dd_nc_f);
2020         }
2021     }
2022     ret             = do_cpt_state(gmx_fio_getxdr(fp), TRUE, fflags, state, NULL);
2023     *init_fep_state = state->fep_state;  /* there should be a better way to do this than setting it here.
2024                                             Investigate for 5.0. */
2025     if (ret)
2026     {
2027         cp_error();
2028     }
2029     ret = do_cpt_ekinstate(gmx_fio_getxdr(fp), flags_eks, &state->ekinstate, NULL);
2030     if (ret)
2031     {
2032         cp_error();
2033     }
2034     *bReadEkin = ((flags_eks & (1<<eeksEKINH)) || (flags_eks & (1<<eeksEKINF)) || (flags_eks & (1<<eeksEKINO)) ||
2035                   ((flags_eks & (1<<eeksEKINSCALEF)) | (flags_eks & (1<<eeksEKINSCALEH)) | (flags_eks & (1<<eeksVSCALE))));
2036
2037     ret = do_cpt_enerhist(gmx_fio_getxdr(fp), TRUE,
2038                           flags_enh, &state->enerhist, NULL);
2039     if (ret)
2040     {
2041         cp_error();
2042     }
2043
2044     if (file_version < 6)
2045     {
2046         const char *warn = "Reading checkpoint file in old format, assuming that the run that generated this file started at step 0, if this is not the case the averages stored in the energy file will be incorrect.";
2047
2048         fprintf(stderr, "\nWARNING: %s\n\n", warn);
2049         if (fplog)
2050         {
2051             fprintf(fplog, "\nWARNING: %s\n\n", warn);
2052         }
2053         state->enerhist.nsum     = *step;
2054         state->enerhist.nsum_sim = *step;
2055     }
2056
2057     ret = do_cpt_df_hist(gmx_fio_getxdr(fp), flags_dfh, &state->dfhist, NULL);
2058     if (ret)
2059     {
2060         cp_error();
2061     }
2062
2063     ret = do_cpt_swapstate(gmx_fio_getxdr(fp), TRUE, &state->swapstate, NULL);
2064     if (ret)
2065     {
2066         cp_error();
2067     }
2068
2069     ret = do_cpt_EDstate(gmx_fio_getxdr(fp), TRUE, &state->edsamstate, NULL);
2070     if (ret)
2071     {
2072         cp_error();
2073     }
2074
2075     ret = do_cpt_files(gmx_fio_getxdr(fp), TRUE, &outputfiles, &nfiles, NULL, file_version);
2076     if (ret)
2077     {
2078         cp_error();
2079     }
2080
2081     ret = do_cpt_footer(gmx_fio_getxdr(fp), file_version);
2082     if (ret)
2083     {
2084         cp_error();
2085     }
2086     if (gmx_fio_close(fp) != 0)
2087     {
2088         gmx_file("Cannot read/write checkpoint; corrupt file, or maybe you are out of disk space?");
2089     }
2090
2091     sfree(fprog);
2092     sfree(ftime);
2093     sfree(btime);
2094     sfree(buser);
2095     sfree(bhost);
2096
2097     /* If the user wants to append to output files,
2098      * we use the file pointer positions of the output files stored
2099      * in the checkpoint file and truncate the files such that any frames
2100      * written after the checkpoint time are removed.
2101      * All files are md5sum checked such that we can be sure that
2102      * we do not truncate other (maybe imprortant) files.
2103      */
2104     if (bAppendOutputFiles)
2105     {
2106         if (fn2ftp(outputfiles[0].filename) != efLOG)
2107         {
2108             /* make sure first file is log file so that it is OK to use it for
2109              * locking
2110              */
2111             gmx_fatal(FARGS, "The first output file should always be the log "
2112                       "file but instead is: %s. Cannot do appending because of this condition.", outputfiles[0].filename);
2113         }
2114         for (i = 0; i < nfiles; i++)
2115         {
2116             if (outputfiles[i].offset < 0)
2117             {
2118                 gmx_fatal(FARGS, "The original run wrote a file called '%s' which "
2119                           "is larger than 2 GB, but mdrun did not support large file"
2120                           " offsets. Can not append. Run mdrun with -noappend",
2121                           outputfiles[i].filename);
2122             }
2123 #ifdef GMX_FAHCORE
2124             chksum_file = gmx_fio_open(outputfiles[i].filename, "a");
2125
2126 #else
2127             chksum_file = gmx_fio_open(outputfiles[i].filename, "r+");
2128
2129             /* lock log file */
2130             if (i == 0)
2131             {
2132                 /* Note that there are systems where the lock operation
2133                  * will succeed, but a second process can also lock the file.
2134                  * We should probably try to detect this.
2135                  */
2136 #if defined __native_client__
2137                 errno = ENOSYS;
2138                 if (1)
2139
2140 #elif defined GMX_NATIVE_WINDOWS
2141                 if (_locking(fileno(gmx_fio_getfp(chksum_file)), _LK_NBLCK, LONG_MAX) == -1)
2142 #else
2143                 if (fcntl(fileno(gmx_fio_getfp(chksum_file)), F_SETLK, &fl) == -1)
2144 #endif
2145                 {
2146                     if (errno == ENOSYS)
2147                     {
2148                         if (!bForceAppend)
2149                         {
2150                             gmx_fatal(FARGS, "File locking is not supported on this system. Use -noappend or specify -append explicitly to append anyhow.");
2151                         }
2152                         else
2153                         {
2154                             fprintf(stderr, "\nNOTE: File locking is not supported on this system, will not lock %s\n\n", outputfiles[i].filename);
2155                             if (fplog)
2156                             {
2157                                 fprintf(fplog, "\nNOTE: File locking not supported on this system, will not lock %s\n\n", outputfiles[i].filename);
2158                             }
2159                         }
2160                     }
2161                     else if (errno == EACCES || errno == EAGAIN)
2162                     {
2163                         gmx_fatal(FARGS, "Failed to lock: %s. Already running "
2164                                   "simulation?", outputfiles[i].filename);
2165                     }
2166                     else
2167                     {
2168                         gmx_fatal(FARGS, "Failed to lock: %s. %s.",
2169                                   outputfiles[i].filename, strerror(errno));
2170                     }
2171                 }
2172             }
2173
2174             /* compute md5 chksum */
2175             if (outputfiles[i].chksum_size != -1)
2176             {
2177                 if (gmx_fio_get_file_md5(chksum_file, outputfiles[i].offset,
2178                                          digest) != outputfiles[i].chksum_size) /*at the end of the call the file position is at the end of the file*/
2179                 {
2180                     gmx_fatal(FARGS, "Can't read %d bytes of '%s' to compute checksum. The file has been replaced or its contents have been modified. Cannot do appending because of this condition.",
2181                               outputfiles[i].chksum_size,
2182                               outputfiles[i].filename);
2183                 }
2184             }
2185             if (i == 0)  /*log file needs to be seeked in case we need to truncate (other files are truncated below)*/
2186             {
2187                 if (gmx_fio_seek(chksum_file, outputfiles[i].offset))
2188                 {
2189                     gmx_fatal(FARGS, "Seek error! Failed to truncate log-file: %s.", strerror(errno));
2190                 }
2191             }
2192 #endif
2193
2194             if (i == 0) /*open log file here - so that lock is never lifted
2195                            after chksum is calculated */
2196             {
2197                 *pfplog = gmx_fio_getfp(chksum_file);
2198             }
2199             else
2200             {
2201                 gmx_fio_close(chksum_file);
2202             }
2203 #ifndef GMX_FAHCORE
2204             /* compare md5 chksum */
2205             if (outputfiles[i].chksum_size != -1 &&
2206                 memcmp(digest, outputfiles[i].chksum, 16) != 0)
2207             {
2208                 if (debug)
2209                 {
2210                     fprintf(debug, "chksum for %s: ", outputfiles[i].filename);
2211                     for (j = 0; j < 16; j++)
2212                     {
2213                         fprintf(debug, "%02x", digest[j]);
2214                     }
2215                     fprintf(debug, "\n");
2216                 }
2217                 gmx_fatal(FARGS, "Checksum wrong for '%s'. The file has been replaced or its contents have been modified. Cannot do appending because of this condition.",
2218                           outputfiles[i].filename);
2219             }
2220 #endif
2221
2222
2223             if (i != 0) /*log file is already seeked to correct position */
2224             {
2225 #ifdef GMX_NATIVE_WINDOWS
2226                 rc = gmx_wintruncate(outputfiles[i].filename, outputfiles[i].offset);
2227 #else
2228                 rc = truncate(outputfiles[i].filename, outputfiles[i].offset);
2229 #endif
2230                 if (rc != 0)
2231                 {
2232                     gmx_fatal(FARGS, "Truncation of file %s failed. Cannot do appending because of this failure.", outputfiles[i].filename);
2233                 }
2234             }
2235         }
2236     }
2237
2238     sfree(outputfiles);
2239 }
2240
2241
2242 void load_checkpoint(const char *fn, FILE **fplog,
2243                      t_commrec *cr, ivec dd_nc,
2244                      t_inputrec *ir, t_state *state,
2245                      gmx_bool *bReadEkin,
2246                      gmx_bool bAppend, gmx_bool bForceAppend)
2247 {
2248     gmx_int64_t     step;
2249     double          t;
2250
2251     if (SIMMASTER(cr))
2252     {
2253         /* Read the state from the checkpoint file */
2254         read_checkpoint(fn, fplog,
2255                         cr, dd_nc,
2256                         ir->eI, &(ir->fepvals->init_fep_state), &step, &t, state, bReadEkin,
2257                         &ir->simulation_part, bAppend, bForceAppend);
2258     }
2259     if (PAR(cr))
2260     {
2261         gmx_bcast(sizeof(cr->npmenodes), &cr->npmenodes, cr);
2262         gmx_bcast(DIM*sizeof(dd_nc[0]), dd_nc, cr);
2263         gmx_bcast(sizeof(step), &step, cr);
2264         gmx_bcast(sizeof(*bReadEkin), bReadEkin, cr);
2265     }
2266     ir->bContinuation    = TRUE;
2267     if (ir->nsteps >= 0)
2268     {
2269         ir->nsteps          += ir->init_step - step;
2270     }
2271     ir->init_step        = step;
2272     ir->simulation_part += 1;
2273 }
2274
2275 static void read_checkpoint_data(t_fileio *fp, int *simulation_part,
2276                                  gmx_int64_t *step, double *t, t_state *state,
2277                                  int *nfiles, gmx_file_position_t **outputfiles)
2278 {
2279     int                  file_version;
2280     char                *version, *btime, *buser, *bhost, *fprog, *ftime;
2281     int                  double_prec;
2282     int                  eIntegrator;
2283     int                  nppnodes, npme;
2284     ivec                 dd_nc;
2285     int                  flags_eks, flags_enh, flags_dfh;
2286     int                  nfiles_loc;
2287     gmx_file_position_t *files_loc = NULL;
2288     int                  ret;
2289
2290     do_cpt_header(gmx_fio_getxdr(fp), TRUE, &file_version,
2291                   &version, &btime, &buser, &bhost, &double_prec, &fprog, &ftime,
2292                   &eIntegrator, simulation_part, step, t, &nppnodes, dd_nc, &npme,
2293                   &state->natoms, &state->ngtc, &state->nnhpres, &state->nhchainlength,
2294                   &(state->dfhist.nlambda), &state->flags, &flags_eks, &flags_enh, &flags_dfh,
2295                   &state->edsamstate.nED, &state->swapstate.eSwapCoords, NULL);
2296     ret =
2297         do_cpt_state(gmx_fio_getxdr(fp), TRUE, state->flags, state, NULL);
2298     if (ret)
2299     {
2300         cp_error();
2301     }
2302     ret = do_cpt_ekinstate(gmx_fio_getxdr(fp), flags_eks, &state->ekinstate, NULL);
2303     if (ret)
2304     {
2305         cp_error();
2306     }
2307     ret = do_cpt_enerhist(gmx_fio_getxdr(fp), TRUE,
2308                           flags_enh, &state->enerhist, NULL);
2309     if (ret)
2310     {
2311         cp_error();
2312     }
2313     ret = do_cpt_df_hist(gmx_fio_getxdr(fp), flags_dfh, &state->dfhist, NULL);
2314     if (ret)
2315     {
2316         cp_error();
2317     }
2318
2319     ret = do_cpt_EDstate(gmx_fio_getxdr(fp), TRUE, &state->edsamstate, NULL);
2320     if (ret)
2321     {
2322         cp_error();
2323     }
2324
2325     ret = do_cpt_swapstate(gmx_fio_getxdr(fp), TRUE, &state->swapstate, NULL);
2326     if (ret)
2327     {
2328         cp_error();
2329     }
2330
2331     ret = do_cpt_files(gmx_fio_getxdr(fp), TRUE,
2332                        outputfiles != NULL ? outputfiles : &files_loc,
2333                        outputfiles != NULL ? nfiles : &nfiles_loc,
2334                        NULL, file_version);
2335     if (files_loc != NULL)
2336     {
2337         sfree(files_loc);
2338     }
2339
2340     if (ret)
2341     {
2342         cp_error();
2343     }
2344
2345     ret = do_cpt_footer(gmx_fio_getxdr(fp), file_version);
2346     if (ret)
2347     {
2348         cp_error();
2349     }
2350
2351     sfree(fprog);
2352     sfree(ftime);
2353     sfree(btime);
2354     sfree(buser);
2355     sfree(bhost);
2356 }
2357
2358 void
2359 read_checkpoint_state(const char *fn, int *simulation_part,
2360                       gmx_int64_t *step, double *t, t_state *state)
2361 {
2362     t_fileio *fp;
2363
2364     fp = gmx_fio_open(fn, "r");
2365     read_checkpoint_data(fp, simulation_part, step, t, state, NULL, NULL);
2366     if (gmx_fio_close(fp) != 0)
2367     {
2368         gmx_file("Cannot read/write checkpoint; corrupt file, or maybe you are out of disk space?");
2369     }
2370 }
2371
2372 void read_checkpoint_trxframe(t_fileio *fp, t_trxframe *fr)
2373 {
2374     /* This next line is nasty because the sub-structures of t_state
2375      * cannot be assumed to be zeroed (or even initialized in ways the
2376      * rest of the code might assume). Using snew would be better, but
2377      * this will all go away for 5.0. */
2378     t_state         state;
2379     int             simulation_part;
2380     gmx_int64_t     step;
2381     double          t;
2382
2383     init_state(&state, 0, 0, 0, 0, 0);
2384
2385     read_checkpoint_data(fp, &simulation_part, &step, &t, &state, NULL, NULL);
2386
2387     fr->natoms  = state.natoms;
2388     fr->bTitle  = FALSE;
2389     fr->bStep   = TRUE;
2390     fr->step    = gmx_int64_to_int(step,
2391                                    "conversion of checkpoint to trajectory");
2392     fr->bTime      = TRUE;
2393     fr->time       = t;
2394     fr->bLambda    = TRUE;
2395     fr->lambda     = state.lambda[efptFEP];
2396     fr->fep_state  = state.fep_state;
2397     fr->bAtoms     = FALSE;
2398     fr->bX         = (state.flags & (1<<estX));
2399     if (fr->bX)
2400     {
2401         fr->x     = state.x;
2402         state.x   = NULL;
2403     }
2404     fr->bV      = (state.flags & (1<<estV));
2405     if (fr->bV)
2406     {
2407         fr->v     = state.v;
2408         state.v   = NULL;
2409     }
2410     fr->bF      = FALSE;
2411     fr->bBox    = (state.flags & (1<<estBOX));
2412     if (fr->bBox)
2413     {
2414         copy_mat(state.box, fr->box);
2415     }
2416     done_state(&state);
2417 }
2418
2419 void list_checkpoint(const char *fn, FILE *out)
2420 {
2421     t_fileio            *fp;
2422     int                  file_version;
2423     char                *version, *btime, *buser, *bhost, *fprog, *ftime;
2424     int                  double_prec;
2425     int                  eIntegrator, simulation_part, nppnodes, npme;
2426     gmx_int64_t          step;
2427     double               t;
2428     ivec                 dd_nc;
2429     t_state              state;
2430     int                  flags_eks, flags_enh, flags_dfh;
2431     int                  indent;
2432     int                  i, j;
2433     int                  ret;
2434     gmx_file_position_t *outputfiles;
2435     int                  nfiles;
2436
2437     init_state(&state, -1, -1, -1, -1, 0);
2438
2439     fp = gmx_fio_open(fn, "r");
2440     do_cpt_header(gmx_fio_getxdr(fp), TRUE, &file_version,
2441                   &version, &btime, &buser, &bhost, &double_prec, &fprog, &ftime,
2442                   &eIntegrator, &simulation_part, &step, &t, &nppnodes, dd_nc, &npme,
2443                   &state.natoms, &state.ngtc, &state.nnhpres, &state.nhchainlength,
2444                   &(state.dfhist.nlambda), &state.flags,
2445                   &flags_eks, &flags_enh, &flags_dfh, &state.edsamstate.nED,
2446                   &state.swapstate.eSwapCoords, out);
2447     ret = do_cpt_state(gmx_fio_getxdr(fp), TRUE, state.flags, &state, out);
2448     if (ret)
2449     {
2450         cp_error();
2451     }
2452     ret = do_cpt_ekinstate(gmx_fio_getxdr(fp), flags_eks, &state.ekinstate, out);
2453     if (ret)
2454     {
2455         cp_error();
2456     }
2457     ret = do_cpt_enerhist(gmx_fio_getxdr(fp), TRUE,
2458                           flags_enh, &state.enerhist, out);
2459
2460     if (ret == 0)
2461     {
2462         ret = do_cpt_df_hist(gmx_fio_getxdr(fp),
2463                              flags_dfh, &state.dfhist, out);
2464     }
2465
2466     if (ret == 0)
2467     {
2468         ret = do_cpt_EDstate(gmx_fio_getxdr(fp), TRUE, &state.edsamstate, out);
2469     }
2470
2471     if (ret == 0)
2472     {
2473         ret = do_cpt_swapstate(gmx_fio_getxdr(fp), TRUE, &state.swapstate, out);
2474     }
2475
2476     if (ret == 0)
2477     {
2478         do_cpt_files(gmx_fio_getxdr(fp), TRUE, &outputfiles, &nfiles, out, file_version);
2479     }
2480
2481     if (ret == 0)
2482     {
2483         ret = do_cpt_footer(gmx_fio_getxdr(fp), file_version);
2484     }
2485
2486     if (ret)
2487     {
2488         cp_warning(out);
2489     }
2490     if (gmx_fio_close(fp) != 0)
2491     {
2492         gmx_file("Cannot read/write checkpoint; corrupt file, or maybe you are out of disk space?");
2493     }
2494
2495     done_state(&state);
2496 }
2497
2498
2499 static gmx_bool exist_output_file(const char *fnm_cp, int nfile, const t_filenm fnm[])
2500 {
2501     int i;
2502
2503     /* Check if the output file name stored in the checkpoint file
2504      * is one of the output file names of mdrun.
2505      */
2506     i = 0;
2507     while (i < nfile &&
2508            !(is_output(&fnm[i]) && strcmp(fnm_cp, fnm[i].fns[0]) == 0))
2509     {
2510         i++;
2511     }
2512
2513     return (i < nfile && gmx_fexist(fnm_cp));
2514 }
2515
2516 /* This routine cannot print tons of data, since it is called before the log file is opened. */
2517 gmx_bool read_checkpoint_simulation_part(const char *filename, int *simulation_part,
2518                                          gmx_int64_t *cpt_step, t_commrec *cr,
2519                                          gmx_bool bAppendReq,
2520                                          int nfile, const t_filenm fnm[],
2521                                          const char *part_suffix, gmx_bool *bAddPart)
2522 {
2523     t_fileio            *fp;
2524     gmx_int64_t          step = 0;
2525     double               t;
2526     /* This next line is nasty because the sub-structures of t_state
2527      * cannot be assumed to be zeroed (or even initialized in ways the
2528      * rest of the code might assume). Using snew would be better, but
2529      * this will all go away for 5.0. */
2530     t_state              state;
2531     int                  nfiles;
2532     gmx_file_position_t *outputfiles;
2533     int                  nexist, f;
2534     gmx_bool             bAppend;
2535     char                *fn, suf_up[STRLEN];
2536
2537     bAppend = FALSE;
2538
2539     if (SIMMASTER(cr))
2540     {
2541         if (!gmx_fexist(filename) || (!(fp = gmx_fio_open(filename, "r")) ))
2542         {
2543             *simulation_part = 0;
2544         }
2545         else
2546         {
2547             init_state(&state, 0, 0, 0, 0, 0);
2548
2549             read_checkpoint_data(fp, simulation_part, &step, &t, &state,
2550                                  &nfiles, &outputfiles);
2551             if (gmx_fio_close(fp) != 0)
2552             {
2553                 gmx_file("Cannot read/write checkpoint; corrupt file, or maybe you are out of disk space?");
2554             }
2555             done_state(&state);
2556
2557             if (bAppendReq)
2558             {
2559                 nexist = 0;
2560                 for (f = 0; f < nfiles; f++)
2561                 {
2562                     if (exist_output_file(outputfiles[f].filename, nfile, fnm))
2563                     {
2564                         nexist++;
2565                     }
2566                 }
2567                 if (nexist == nfiles)
2568                 {
2569                     bAppend = bAppendReq;
2570                 }
2571                 else if (nexist > 0)
2572                 {
2573                     fprintf(stderr,
2574                             "Output file appending has been requested,\n"
2575                             "but some output files listed in the checkpoint file %s\n"
2576                             "are not present or are named differently by the current program:\n",
2577                             filename);
2578                     fprintf(stderr, "output files present:");
2579                     for (f = 0; f < nfiles; f++)
2580                     {
2581                         if (exist_output_file(outputfiles[f].filename,
2582                                               nfile, fnm))
2583                         {
2584                             fprintf(stderr, " %s", outputfiles[f].filename);
2585                         }
2586                     }
2587                     fprintf(stderr, "\n");
2588                     fprintf(stderr, "output files not present or named differently:");
2589                     for (f = 0; f < nfiles; f++)
2590                     {
2591                         if (!exist_output_file(outputfiles[f].filename,
2592                                                nfile, fnm))
2593                         {
2594                             fprintf(stderr, " %s", outputfiles[f].filename);
2595                         }
2596                     }
2597                     fprintf(stderr, "\n");
2598
2599                     gmx_fatal(FARGS, "File appending requested, but only %d of the %d output files are present", nexist, nfiles);
2600                 }
2601             }
2602
2603             if (bAppend)
2604             {
2605                 if (nfiles == 0)
2606                 {
2607                     gmx_fatal(FARGS, "File appending requested, but no output file information is stored in the checkpoint file");
2608                 }
2609                 fn = outputfiles[0].filename;
2610                 if (strlen(fn) < 4 ||
2611                     gmx_strcasecmp(fn+strlen(fn)-4, ftp2ext(efLOG)) == 0)
2612                 {
2613                     gmx_fatal(FARGS, "File appending requested, but the log file is not the first file listed in the checkpoint file");
2614                 }
2615                 /* Set bAddPart to whether the suffix string '.part' is present
2616                  * in the log file name.
2617                  */
2618                 strcpy(suf_up, part_suffix);
2619                 upstring(suf_up);
2620                 *bAddPart = (strstr(fn, part_suffix) != NULL ||
2621                              strstr(fn, suf_up) != NULL);
2622             }
2623
2624             sfree(outputfiles);
2625         }
2626     }
2627     if (PAR(cr))
2628     {
2629         gmx_bcast(sizeof(*simulation_part), simulation_part, cr);
2630
2631         if (*simulation_part > 0 && bAppendReq)
2632         {
2633             gmx_bcast(sizeof(bAppend), &bAppend, cr);
2634             gmx_bcast(sizeof(*bAddPart), bAddPart, cr);
2635         }
2636     }
2637     if (NULL != cpt_step)
2638     {
2639         *cpt_step = step;
2640     }
2641
2642     return bAppend;
2643 }