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