Simplify code structure for C++ analysis tools
[alexxy/gromacs.git] / src / gromacs / gmxlib / confio.c
1 /*
2  *
3  *                This source code is part of
4  *
5  *                 G   R   O   M   A   C   S
6  *
7  *          GROningen MAchine for Chemical Simulations
8  *
9  *                        VERSION 3.2.0
10  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
11  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
12  * Copyright (c) 2001-2004, The GROMACS development team,
13  * check out http://www.gromacs.org for more information.
14
15  * This program is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU General Public License
17  * as published by the Free Software Foundation; either version 2
18  * of the License, or (at your option) any later version.
19  *
20  * If you want to redistribute modifications, please consider that
21  * scientific software is very special. Version control is crucial -
22  * bugs must be traceable. We will be happy to consider code for
23  * inclusion in the official distribution, but derived work must not
24  * be called official GROMACS. Details are found in the README & COPYING
25  * files - if they are missing, get the official version at www.gromacs.org.
26  *
27  * To help us fund GROMACS development, we humbly ask that you cite
28  * the papers on the package - you can find them in the top README file.
29  *
30  * For more info, check our website at http://www.gromacs.org
31  *
32  * And Hey:
33  * GROningen Mixture of Alchemy and Childrens' Stories
34  */
35 #ifdef HAVE_CONFIG_H
36 #include <config.h>
37 #endif
38
39 #include <math.h>
40 #include "sysstuff.h"
41 #include "typedefs.h"
42 #include "smalloc.h"
43 #include "sysstuff.h"
44 #include <errno.h>
45 #include "macros.h"
46 #include "string2.h"
47 #include "confio.h"
48 #include "vec.h"
49 #include "symtab.h"
50 #include "futil.h"
51 #include "xdrf.h"
52 #include "filenm.h"
53 #include "pdbio.h"
54 #include "tpxio.h"
55 #include "gmx_fatal.h"
56 #include "copyrite.h"
57 #include "filenm.h"
58 #include "statutil.h"
59 #include "pbc.h"
60 #include "mtop_util.h"
61 #include "gmxfio.h"
62
63 #define CHAR_SHIFT 24
64
65 static int read_g96_pos(char line[], t_symtab *symtab,
66                         FILE *fp, const char *infile,
67                         t_trxframe *fr)
68 {
69     t_atoms   *atoms;
70     gmx_bool   bEnd;
71     int        nwanted, natoms, atnr, resnr = 0, oldres, newres, shift;
72     char       anm[STRLEN], resnm[STRLEN];
73     char       c1, c2;
74     double     db1, db2, db3;
75
76     nwanted = fr->natoms;
77
78     atoms = fr->atoms;
79
80     natoms = 0;
81
82     if (fr->bX)
83     {
84         if (fr->bAtoms)
85         {
86             shift = CHAR_SHIFT;
87         }
88         else
89         {
90             shift = 0;
91         }
92         newres  = -1;
93         oldres  = -666; /* Unlikely number for the first residue! */
94         bEnd    = FALSE;
95         while (!bEnd && fgets2(line, STRLEN, fp))
96         {
97             bEnd = (strncmp(line, "END", 3) == 0);
98             if (!bEnd  && (line[0] != '#'))
99             {
100                 if (sscanf(line+shift, "%15lf%15lf%15lf", &db1, &db2, &db3) != 3)
101                 {
102                     gmx_fatal(FARGS, "Did not find 3 coordinates for atom %d in %s\n",
103                               natoms+1, infile);
104                 }
105                 if ((nwanted != -1) && (natoms >= nwanted))
106                 {
107                     gmx_fatal(FARGS,
108                               "Found more coordinates (%d) in %s than expected %d\n",
109                               natoms, infile, nwanted);
110                 }
111                 if (atoms)
112                 {
113                     if (fr->bAtoms &&
114                         (sscanf(line, "%5d%c%5s%c%5s%7d", &resnr, &c1, resnm, &c2, anm, &atnr)
115                          != 6))
116                     {
117                         if (oldres >= 0)
118                         {
119                             resnr = oldres;
120                         }
121                         else
122                         {
123                             resnr    = 1;
124                             strncpy(resnm, "???", sizeof(resnm)-1);
125                         }
126                         strncpy(anm, "???", sizeof(anm)-1);
127                     }
128                     atoms->atomname[natoms] = put_symtab(symtab, anm);
129                     if (resnr != oldres)
130                     {
131                         oldres = resnr;
132                         newres++;
133                         if (newres >= atoms->nr)
134                         {
135                             gmx_fatal(FARGS, "More residues than atoms in %s (natoms = %d)",
136                                       infile, atoms->nr);
137                         }
138                         atoms->atom[natoms].resind = newres;
139                         if (newres+1 > atoms->nres)
140                         {
141                             atoms->nres = newres+1;
142                         }
143                         t_atoms_set_resinfo(atoms, natoms, symtab, resnm, resnr, ' ', 0, ' ');
144                     }
145                     else
146                     {
147                         atoms->atom[natoms].resind = newres;
148                     }
149                 }
150                 if (fr->x)
151                 {
152                     fr->x[natoms][0] = db1;
153                     fr->x[natoms][1] = db2;
154                     fr->x[natoms][2] = db3;
155                 }
156                 natoms++;
157             }
158         }
159         if ((nwanted != -1) && natoms != nwanted)
160         {
161             fprintf(stderr,
162                     "Warning: found less coordinates (%d) in %s than expected %d\n",
163                     natoms, infile, nwanted);
164         }
165     }
166
167     fr->natoms = natoms;
168
169     return natoms;
170 }
171
172 static int read_g96_vel(char line[], FILE *fp, const char *infile,
173                         t_trxframe *fr)
174 {
175     gmx_bool   bEnd;
176     int        nwanted, natoms = -1, shift;
177     double     db1, db2, db3;
178
179     nwanted = fr->natoms;
180
181     if (fr->v && fr->bV)
182     {
183         if (strcmp(line, "VELOCITYRED") == 0)
184         {
185             shift = 0;
186         }
187         else
188         {
189             shift = CHAR_SHIFT;
190         }
191         natoms = 0;
192         bEnd   = FALSE;
193         while (!bEnd && fgets2(line, STRLEN, fp))
194         {
195             bEnd = (strncmp(line, "END", 3) == 0);
196             if (!bEnd && (line[0] != '#'))
197             {
198                 if (sscanf(line+shift, "%15lf%15lf%15lf", &db1, &db2, &db3) != 3)
199                 {
200                     gmx_fatal(FARGS, "Did not find 3 velocities for atom %d in %s",
201                               natoms+1, infile);
202                 }
203                 if ((nwanted != -1) && (natoms >= nwanted))
204                 {
205                     gmx_fatal(FARGS, "Found more velocities (%d) in %s than expected %d\n",
206                               natoms, infile, nwanted);
207                 }
208                 if (fr->v)
209                 {
210                     fr->v[natoms][0] = db1;
211                     fr->v[natoms][1] = db2;
212                     fr->v[natoms][2] = db3;
213                 }
214                 natoms++;
215             }
216         }
217         if ((nwanted != -1) && (natoms != nwanted))
218         {
219             fprintf(stderr,
220                     "Warning: found less velocities (%d) in %s than expected %d\n",
221                     natoms, infile, nwanted);
222         }
223     }
224
225     return natoms;
226 }
227
228 int read_g96_conf(FILE *fp, const char *infile, t_trxframe *fr, char *line)
229 {
230     t_symtab  *symtab = NULL;
231     gmx_bool   bAtStart, bTime, bAtoms, bPos, bVel, bBox, bEnd, bFinished;
232     int        natoms, nbp;
233     double     db1, db2, db3, db4, db5, db6, db7, db8, db9;
234
235     bAtStart = (ftell(fp) == 0);
236
237     clear_trxframe(fr, FALSE);
238
239     if (!symtab)
240     {
241         snew(symtab, 1);
242         open_symtab(symtab);
243     }
244
245     natoms = 0;
246
247     if (bAtStart)
248     {
249         while (!fr->bTitle && fgets2(line, STRLEN, fp))
250         {
251             fr->bTitle = (strcmp(line, "TITLE") == 0);
252         }
253         if (fr->title == NULL)
254         {
255             fgets2(line, STRLEN, fp);
256             fr->title = strdup(line);
257         }
258         bEnd = FALSE;
259         while (!bEnd && fgets2(line, STRLEN, fp))
260         {
261             bEnd = (strcmp(line, "END") == 0);
262         }
263         fgets2(line, STRLEN, fp);
264     }
265
266     /* Do not get a line if we are not at the start of the file, *
267      * because without a parameter file we don't know what is in *
268      * the trajectory and we have already read the line in the   *
269      * previous call (VERY DIRTY).                               */
270     bFinished = FALSE;
271     do
272     {
273         bTime  = (strcmp(line, "TIMESTEP") == 0);
274         bAtoms = (strcmp(line, "POSITION") == 0);
275         bPos   = (bAtoms || (strcmp(line, "POSITIONRED") == 0));
276         bVel   = (strncmp(line, "VELOCITY", 8) == 0);
277         bBox   = (strcmp(line, "BOX") == 0);
278         if (bTime)
279         {
280             if (!fr->bTime && !fr->bX)
281             {
282                 fr->bStep = bTime;
283                 fr->bTime = bTime;
284                 do
285                 {
286                     bFinished = (fgets2(line, STRLEN, fp) == NULL);
287                 }
288                 while (!bFinished && (line[0] == '#'));
289                 sscanf(line, "%15d%15lf", &(fr->step), &db1);
290                 fr->time = db1;
291             }
292             else
293             {
294                 bFinished = TRUE;
295             }
296         }
297         if (bPos)
298         {
299             if (!fr->bX)
300             {
301                 fr->bAtoms = bAtoms;
302                 fr->bX     = bPos;
303                 natoms     = read_g96_pos(line, symtab, fp, infile, fr);
304             }
305             else
306             {
307                 bFinished = TRUE;
308             }
309         }
310         if (fr->v && bVel)
311         {
312             fr->bV = bVel;
313             natoms = read_g96_vel(line, fp, infile, fr);
314         }
315         if (bBox)
316         {
317             fr->bBox = bBox;
318             clear_mat(fr->box);
319             bEnd = FALSE;
320             while (!bEnd && fgets2(line, STRLEN, fp))
321             {
322                 bEnd = (strncmp(line, "END", 3) == 0);
323                 if (!bEnd && (line[0] != '#'))
324                 {
325                     nbp = sscanf(line, "%15lf%15lf%15lf%15lf%15lf%15lf%15lf%15lf%15lf",
326                                  &db1, &db2, &db3, &db4, &db5, &db6, &db7, &db8, &db9);
327                     if (nbp < 3)
328                     {
329                         gmx_fatal(FARGS, "Found a BOX line, but no box in %s", infile);
330                     }
331                     fr->box[XX][XX] = db1;
332                     fr->box[YY][YY] = db2;
333                     fr->box[ZZ][ZZ] = db3;
334                     if (nbp == 9)
335                     {
336                         fr->box[XX][YY] = db4;
337                         fr->box[XX][ZZ] = db5;
338                         fr->box[YY][XX] = db6;
339                         fr->box[YY][ZZ] = db7;
340                         fr->box[ZZ][XX] = db8;
341                         fr->box[ZZ][YY] = db9;
342                     }
343                 }
344             }
345             bFinished = TRUE;
346         }
347     }
348     while (!bFinished && fgets2(line, STRLEN, fp));
349
350     free_symtab(symtab);
351
352     fr->natoms = natoms;
353
354     return natoms;
355 }
356
357 void write_g96_conf(FILE *out, t_trxframe *fr,
358                     int nindex, const atom_id *index)
359 {
360     t_atoms *atoms;
361     int      nout, i, a;
362
363     atoms = fr->atoms;
364
365     if (index)
366     {
367         nout = nindex;
368     }
369     else
370     {
371         nout = fr->natoms;
372     }
373
374     if (fr->bTitle)
375     {
376         fprintf(out, "TITLE\n%s\nEND\n", fr->title);
377     }
378     if (fr->bStep || fr->bTime)
379     {
380         /* Officially the time format is %15.9, which is not enough for 10 ns */
381         fprintf(out, "TIMESTEP\n%15d%15.6f\nEND\n", fr->step, fr->time);
382     }
383     if (fr->bX)
384     {
385         if (fr->bAtoms)
386         {
387             fprintf(out, "POSITION\n");
388             for (i = 0; i < nout; i++)
389             {
390                 if (index)
391                 {
392                     a = index[i];
393                 }
394                 else
395                 {
396                     a = i;
397                 }
398                 fprintf(out, "%5d %-5s %-5s%7d%15.9f%15.9f%15.9f\n",
399                         (atoms->resinfo[atoms->atom[a].resind].nr) % 100000,
400                         *atoms->resinfo[atoms->atom[a].resind].name,
401                         *atoms->atomname[a], (i+1) % 10000000,
402                         fr->x[a][XX], fr->x[a][YY], fr->x[a][ZZ]);
403             }
404         }
405         else
406         {
407             fprintf(out, "POSITIONRED\n");
408             for (i = 0; i < nout; i++)
409             {
410                 if (index)
411                 {
412                     a = index[i];
413                 }
414                 else
415                 {
416                     a = i;
417                 }
418                 fprintf(out, "%15.9f%15.9f%15.9f\n",
419                         fr->x[a][XX], fr->x[a][YY], fr->x[a][ZZ]);
420             }
421         }
422         fprintf(out, "END\n");
423     }
424     if (fr->bV)
425     {
426         if (fr->bAtoms)
427         {
428             fprintf(out, "VELOCITY\n");
429             for (i = 0; i < nout; i++)
430             {
431                 if (index)
432                 {
433                     a = index[i];
434                 }
435                 else
436                 {
437                     a = i;
438                 }
439                 fprintf(out, "%5d %-5s %-5s%7d%15.9f%15.9f%15.9f\n",
440                         (atoms->resinfo[atoms->atom[a].resind].nr) % 100000,
441                         *atoms->resinfo[atoms->atom[a].resind].name,
442                         *atoms->atomname[a], (i+1) % 10000000,
443                         fr->v[a][XX], fr->v[a][YY], fr->v[a][ZZ]);
444             }
445         }
446         else
447         {
448             fprintf(out, "VELOCITYRED\n");
449             for (i = 0; i < nout; i++)
450             {
451                 if (index)
452                 {
453                     a = index[i];
454                 }
455                 else
456                 {
457                     a = i;
458                 }
459                 fprintf(out, "%15.9f%15.9f%15.9f\n",
460                         fr->v[a][XX], fr->v[a][YY], fr->v[a][ZZ]);
461             }
462         }
463         fprintf(out, "END\n");
464     }
465     if (fr->bBox)
466     {
467         fprintf(out, "BOX\n");
468         fprintf(out, "%15.9f%15.9f%15.9f",
469                 fr->box[XX][XX], fr->box[YY][YY], fr->box[ZZ][ZZ]);
470         if (fr->box[XX][YY] || fr->box[XX][ZZ] || fr->box[YY][XX] ||
471             fr->box[YY][ZZ] || fr->box[ZZ][XX] || fr->box[ZZ][YY])
472         {
473             fprintf(out, "%15.9f%15.9f%15.9f%15.9f%15.9f%15.9f",
474                     fr->box[XX][YY], fr->box[XX][ZZ], fr->box[YY][XX],
475                     fr->box[YY][ZZ], fr->box[ZZ][XX], fr->box[ZZ][YY]);
476         }
477         fprintf(out, "\n");
478         fprintf(out, "END\n");
479     }
480 }
481
482 static int get_espresso_word(FILE *fp, char word[])
483 {
484     int  ret, nc, i;
485
486     ret = 0;
487     nc  = 0;
488
489     do
490     {
491         i = fgetc(fp);
492         if (i != EOF)
493         {
494             if (i == ' ' || i == '\n' || i == '\t')
495             {
496                 if (nc > 0)
497                 {
498                     ret = 1;
499                 }
500             }
501             else if (i == '{')
502             {
503                 if (nc == 0)
504                 {
505                     word[nc++] = '{';
506                 }
507                 ret = 2;
508             }
509             else if (i == '}')
510             {
511                 if (nc == 0)
512                 {
513                     word[nc++] = '}';
514                 }
515                 ret = 3;
516             }
517             else
518             {
519                 word[nc++] = (char)i;
520             }
521         }
522     }
523     while (i != EOF && ret == 0);
524
525     word[nc] = '\0';
526
527     /*  printf("'%s'\n",word); */
528
529     return ret;
530 }
531
532 static int check_open_parenthesis(FILE *fp, int r,
533                                   const char *infile, const char *keyword)
534 {
535     int  level_inc;
536     char word[STRLEN];
537
538     level_inc = 0;
539     if (r == 2)
540     {
541         level_inc++;
542     }
543     else
544     {
545         r = get_espresso_word(fp, word);
546         if (r == 2)
547         {
548             level_inc++;
549         }
550         else
551         {
552             gmx_fatal(FARGS, "Expected '{' after '%s' in file '%s'",
553                       keyword, infile);
554         }
555     }
556
557     return level_inc;
558 }
559
560 static int check_close_parenthesis(FILE *fp, int r,
561                                    const char *infile, const char *keyword)
562 {
563     int  level_inc;
564     char word[STRLEN];
565
566     level_inc = 0;
567     if (r == 3)
568     {
569         level_inc--;
570     }
571     else
572     {
573         r = get_espresso_word(fp, word);
574         if (r == 3)
575         {
576             level_inc--;
577         }
578         else
579         {
580             gmx_fatal(FARGS, "Expected '}' after section '%s' in file '%s'",
581                       keyword, infile);
582         }
583     }
584
585     return level_inc;
586 }
587
588 enum {
589     espID, espPOS, espTYPE, espQ, espV, espF, espMOLECULE, espNR
590 };
591 const char *esp_prop[espNR] = {
592     "id", "pos", "type", "q", "v", "f",
593     "molecule"
594 };
595
596 static void read_espresso_conf(const char *infile,
597                                t_atoms *atoms, rvec x[], rvec *v, matrix box)
598 {
599     t_symtab *symtab = NULL;
600     FILE     *fp;
601     char      word[STRLEN], buf[STRLEN];
602     int       natoms, level, npar, r, nprop, p, i, m, molnr;
603     int       prop[32];
604     double    d;
605     gmx_bool  bFoundParticles, bFoundProp, bFoundVariable, bMol;
606
607     if (!symtab)
608     {
609         snew(symtab, 1);
610         open_symtab(symtab);
611     }
612
613     clear_mat(box);
614
615     fp = gmx_fio_fopen(infile, "r");
616
617     bFoundParticles = FALSE;
618     bFoundVariable  = FALSE;
619     bMol            = FALSE;
620     level           = 0;
621     while ((r = get_espresso_word(fp, word)))
622     {
623         if (level == 1 && strcmp(word, "particles") == 0 && !bFoundParticles)
624         {
625             bFoundParticles = TRUE;
626             level          += check_open_parenthesis(fp, r, infile, "particles");
627             nprop           = 0;
628             while (level == 2 && (r = get_espresso_word(fp, word)))
629             {
630                 bFoundProp = FALSE;
631                 for (p = 0; p < espNR; p++)
632                 {
633                     if (strcmp(word, esp_prop[p]) == 0)
634                     {
635                         bFoundProp    = TRUE;
636                         prop[nprop++] = p;
637                         /* printf("  prop[%d] = %s\n",nprop-1,esp_prop[prop[nprop-1]]); */
638                     }
639                 }
640                 if (!bFoundProp && word[0] != '}')
641                 {
642                     gmx_fatal(FARGS, "Can not read Espresso files with particle property '%s'", word);
643                 }
644                 if (bFoundProp && p == espMOLECULE)
645                 {
646                     bMol = TRUE;
647                 }
648                 if (r == 3)
649                 {
650                     level--;
651                 }
652             }
653
654             i = 0;
655             while (level > 0 && (r = get_espresso_word(fp, word)))
656             {
657                 if (r == 2)
658                 {
659                     level++;
660                 }
661                 else if (r == 3)
662                 {
663                     level--;
664                 }
665                 if (level == 2)
666                 {
667                     for (p = 0; p < nprop; p++)
668                     {
669                         switch (prop[p])
670                         {
671                             case espID:
672                                 r = get_espresso_word(fp, word);
673                                 /* Not used */
674                                 break;
675                             case espPOS:
676                                 for (m = 0; m < 3; m++)
677                                 {
678                                     r = get_espresso_word(fp, word);
679                                     sscanf(word, "%lf", &d);
680                                     x[i][m] = d;
681                                 }
682                                 break;
683                             case espTYPE:
684                                 r                   = get_espresso_word(fp, word);
685                                 atoms->atom[i].type = strtol(word, NULL, 10);
686                                 break;
687                             case espQ:
688                                 r = get_espresso_word(fp, word);
689                                 sscanf(word, "%lf", &d);
690                                 atoms->atom[i].q = d;
691                                 break;
692                             case espV:
693                                 for (m = 0; m < 3; m++)
694                                 {
695                                     r = get_espresso_word(fp, word);
696                                     sscanf(word, "%lf", &d);
697                                     v[i][m] = d;
698                                 }
699                                 break;
700                             case espF:
701                                 for (m = 0; m < 3; m++)
702                                 {
703                                     r = get_espresso_word(fp, word);
704                                     /* not used */
705                                 }
706                                 break;
707                             case espMOLECULE:
708                                 r     = get_espresso_word(fp, word);
709                                 molnr = strtol(word, NULL, 10);
710                                 if (i == 0 ||
711                                     atoms->resinfo[atoms->atom[i-1].resind].nr != molnr)
712                                 {
713                                     atoms->atom[i].resind =
714                                         (i == 0 ? 0 : atoms->atom[i-1].resind+1);
715                                     atoms->resinfo[atoms->atom[i].resind].nr       = molnr;
716                                     atoms->resinfo[atoms->atom[i].resind].ic       = ' ';
717                                     atoms->resinfo[atoms->atom[i].resind].chainid  = ' ';
718                                     atoms->resinfo[atoms->atom[i].resind].chainnum = molnr; /* Not sure if this is right? */
719                                 }
720                                 else
721                                 {
722                                     atoms->atom[i].resind = atoms->atom[i-1].resind;
723                                 }
724                                 break;
725                         }
726                     }
727                     /* Generate an atom name from the particle type */
728                     sprintf(buf, "T%d", atoms->atom[i].type);
729                     atoms->atomname[i] = put_symtab(symtab, buf);
730                     if (bMol)
731                     {
732                         if (i == 0 || atoms->atom[i].resind != atoms->atom[i-1].resind)
733                         {
734                             atoms->resinfo[atoms->atom[i].resind].name =
735                                 put_symtab(symtab, "MOL");
736                         }
737                     }
738                     else
739                     {
740                         /* Residue number is the atom number */
741                         atoms->atom[i].resind = i;
742                         /* Generate an residue name from the particle type */
743                         if (atoms->atom[i].type < 26)
744                         {
745                             sprintf(buf, "T%c", 'A'+atoms->atom[i].type);
746                         }
747                         else
748                         {
749                             sprintf(buf, "T%c%c",
750                                     'A'+atoms->atom[i].type/26, 'A'+atoms->atom[i].type%26);
751                         }
752                         t_atoms_set_resinfo(atoms, i, symtab, buf, i, ' ', 0, ' ');
753                     }
754
755                     if (r == 3)
756                     {
757                         level--;
758                     }
759                     i++;
760                 }
761             }
762             atoms->nres = atoms->nr;
763
764             if (i != atoms->nr)
765             {
766                 gmx_fatal(FARGS, "Internal inconsistency in Espresso routines, read %d atoms, expected %d atoms", i, atoms->nr);
767             }
768         }
769         else if (level == 1 && strcmp(word, "variable") == 0 && !bFoundVariable)
770         {
771             bFoundVariable = TRUE;
772             level         += check_open_parenthesis(fp, r, infile, "variable");
773             while (level == 2 && (r = get_espresso_word(fp, word)))
774             {
775                 if (level == 2 && strcmp(word, "box_l") == 0)
776                 {
777                     for (m = 0; m < 3; m++)
778                     {
779                         r = get_espresso_word(fp, word);
780                         sscanf(word, "%lf", &d);
781                         box[m][m] = d;
782                     }
783                     level += check_close_parenthesis(fp, r, infile, "box_l");
784                 }
785             }
786         }
787         else if (r == 2)
788         {
789             level++;
790         }
791         else if (r == 3)
792         {
793             level--;
794         }
795     }
796
797     if (!bFoundParticles)
798     {
799         fprintf(stderr, "Did not find a particles section in Espresso file '%s'\n",
800                 infile);
801     }
802
803     gmx_fio_fclose(fp);
804 }
805
806 static int get_espresso_coordnum(const char *infile)
807 {
808     FILE    *fp;
809     char     word[STRLEN];
810     int      natoms, level, r;
811     gmx_bool bFoundParticles;
812
813     natoms = 0;
814
815     fp = gmx_fio_fopen(infile, "r");
816
817     bFoundParticles = FALSE;
818     level           = 0;
819     while ((r = get_espresso_word(fp, word)) && !bFoundParticles)
820     {
821         if (level == 1 && strcmp(word, "particles") == 0 && !bFoundParticles)
822         {
823             bFoundParticles = TRUE;
824             level          += check_open_parenthesis(fp, r, infile, "particles");
825             while (level > 0 && (r = get_espresso_word(fp, word)))
826             {
827                 if (r == 2)
828                 {
829                     level++;
830                     if (level == 2)
831                     {
832                         natoms++;
833                     }
834                 }
835                 else if (r == 3)
836                 {
837                     level--;
838                 }
839             }
840         }
841         else if (r == 2)
842         {
843             level++;
844         }
845         else if (r == 3)
846         {
847             level--;
848         }
849     }
850     if (!bFoundParticles)
851     {
852         fprintf(stderr, "Did not find a particles section in Espresso file '%s'\n",
853                 infile);
854     }
855
856     gmx_fio_fclose(fp);
857
858     return natoms;
859 }
860
861 static void write_espresso_conf_indexed(FILE *out, const char *title,
862                                         t_atoms *atoms, int nx, atom_id *index,
863                                         rvec *x, rvec *v, matrix box)
864 {
865     int i, j;
866
867     fprintf(out, "# %s\n", title);
868     if (TRICLINIC(box))
869     {
870         gmx_warning("The Espresso format does not support triclinic unit-cells");
871     }
872     fprintf(out, "{variable {box_l %f %f %f}}\n", box[0][0], box[1][1], box[2][2]);
873
874     fprintf(out, "{particles {id pos type q%s}\n", v ? " v" : "");
875     for (i = 0; i < nx; i++)
876     {
877         if (index)
878         {
879             j = index[i];
880         }
881         else
882         {
883             j = i;
884         }
885         fprintf(out, "\t{%d %f %f %f %d %g",
886                 j, x[j][XX], x[j][YY], x[j][ZZ],
887                 atoms->atom[j].type, atoms->atom[j].q);
888         if (v)
889         {
890             fprintf(out, " %f %f %f", v[j][XX], v[j][YY], v[j][ZZ]);
891         }
892         fprintf(out, "}\n");
893     }
894     fprintf(out, "}\n");
895 }
896
897 static void get_coordnum_fp (FILE *in, char *title, int *natoms)
898 {
899     char line[STRLEN+1];
900
901     fgets2 (title, STRLEN, in);
902     fgets2 (line, STRLEN, in);
903     if (sscanf (line, "%d", natoms) != 1)
904     {
905         gmx_fatal(FARGS, "gro file does not have the number of atoms on the second line");
906     }
907 }
908
909 static void get_coordnum (const char *infile, int *natoms)
910 {
911     FILE *in;
912     char  title[STRLEN];
913
914     in = gmx_fio_fopen(infile, "r");
915     get_coordnum_fp(in, title, natoms);
916     gmx_fio_fclose (in);
917 }
918
919 static gmx_bool get_w_conf(FILE *in, const char *infile, char *title,
920                            t_symtab *symtab, t_atoms *atoms, int *ndec,
921                            rvec x[], rvec *v, matrix box)
922 {
923     char       name[6];
924     char       line[STRLEN+1], *ptr;
925     char       buf[256];
926     double     x1, y1, z1, x2, y2, z2;
927     rvec       xmin, xmax;
928     int        natoms, i, m, resnr, newres, oldres, ddist, c;
929     gmx_bool   bFirst, bVel;
930     char      *p1, *p2, *p3;
931
932     newres  = -1;
933     oldres  = NOTSET; /* Unlikely number for the first residue! */
934     ddist   = 0;
935
936     /* Read the title and number of atoms */
937     get_coordnum_fp(in, title, &natoms);
938
939     if (natoms > atoms->nr)
940     {
941         gmx_fatal(FARGS, "gro file contains more atoms (%d) than expected (%d)",
942                   natoms, atoms->nr);
943     }
944     else if (natoms <  atoms->nr)
945     {
946         fprintf(stderr, "Warning: gro file contains less atoms (%d) than expected"
947                 " (%d)\n", natoms, atoms->nr);
948     }
949
950     bFirst = TRUE;
951
952     bVel = FALSE;
953
954     /* just pray the arrays are big enough */
955     for (i = 0; (i < natoms); i++)
956     {
957         if ((fgets2 (line, STRLEN, in)) == NULL)
958         {
959             unexpected_eof(infile, i+2);
960         }
961         if (strlen(line) < 39)
962         {
963             gmx_fatal(FARGS, "Invalid line in %s for atom %d:\n%s", infile, i+1, line);
964         }
965
966         /* determine read precision from distance between periods
967            (decimal points) */
968         if (bFirst)
969         {
970             bFirst = FALSE;
971             p1     = strchr(line, '.');
972             if (p1 == NULL)
973             {
974                 gmx_fatal(FARGS, "A coordinate in file %s does not contain a '.'", infile);
975             }
976             p2 = strchr(&p1[1], '.');
977             if (p2 == NULL)
978             {
979                 gmx_fatal(FARGS, "A coordinate in file %s does not contain a '.'", infile);
980             }
981             ddist = p2 - p1;
982             *ndec = ddist - 5;
983
984             p3 = strchr(&p2[1], '.');
985             if (p3 == NULL)
986             {
987                 gmx_fatal(FARGS, "A coordinate in file %s does not contain a '.'", infile);
988             }
989
990             if (p3 - p2 != ddist)
991             {
992                 gmx_fatal(FARGS, "The spacing of the decimal points in file %s is not consistent for x, y and z", infile);
993             }
994         }
995
996         /* residue number*/
997         memcpy(name, line, 5);
998         name[5] = '\0';
999         sscanf(name, "%d", &resnr);
1000         memcpy(name, line+5, 5);
1001         name[5] = '\0';
1002         if (resnr != oldres)
1003         {
1004             oldres = resnr;
1005             newres++;
1006             if (newres >= natoms)
1007             {
1008                 gmx_fatal(FARGS, "More residues than atoms in %s (natoms = %d)",
1009                           infile, natoms);
1010             }
1011             atoms->atom[i].resind = newres;
1012             t_atoms_set_resinfo(atoms, i, symtab, name, resnr, ' ', 0, ' ');
1013         }
1014         else
1015         {
1016             atoms->atom[i].resind = newres;
1017         }
1018
1019         /* atomname */
1020         memcpy(name, line+10, 5);
1021         atoms->atomname[i] = put_symtab(symtab, name);
1022
1023         /* eventueel controle atomnumber met i+1 */
1024
1025         /* coordinates (start after residue shit) */
1026         ptr = line + 20;
1027         /* Read fixed format */
1028         for (m = 0; m < DIM; m++)
1029         {
1030             for (c = 0; (c < ddist && ptr[0]); c++)
1031             {
1032                 buf[c] = ptr[0];
1033                 ptr++;
1034             }
1035             buf[c] = '\0';
1036             if (sscanf (buf, "%lf %lf", &x1, &x2) != 1)
1037             {
1038                 gmx_fatal(FARGS, "Something is wrong in the coordinate formatting of file %s. Note that gro is fixed format (see the manual)", infile);
1039             }
1040             else
1041             {
1042                 x[i][m] = x1;
1043             }
1044         }
1045
1046         /* velocities (start after residues and coordinates) */
1047         if (v)
1048         {
1049             /* Read fixed format */
1050             for (m = 0; m < DIM; m++)
1051             {
1052                 for (c = 0; (c < ddist && ptr[0]); c++)
1053                 {
1054                     buf[c] = ptr[0];
1055                     ptr++;
1056                 }
1057                 buf[c] = '\0';
1058                 if (sscanf (buf, "%lf", &x1) != 1)
1059                 {
1060                     v[i][m] = 0;
1061                 }
1062                 else
1063                 {
1064                     v[i][m] = x1;
1065                     bVel    = TRUE;
1066                 }
1067             }
1068         }
1069     }
1070     atoms->nres = newres + 1;
1071
1072     /* box */
1073     fgets2 (line, STRLEN, in);
1074     if (sscanf (line, "%lf%lf%lf", &x1, &y1, &z1) != 3)
1075     {
1076         gmx_warning("Bad box in file %s", infile);
1077
1078         /* Generate a cubic box */
1079         for (m = 0; (m < DIM); m++)
1080         {
1081             xmin[m] = xmax[m] = x[0][m];
1082         }
1083         for (i = 1; (i < atoms->nr); i++)
1084         {
1085             for (m = 0; (m < DIM); m++)
1086             {
1087                 xmin[m] = min(xmin[m], x[i][m]);
1088                 xmax[m] = max(xmax[m], x[i][m]);
1089             }
1090         }
1091         for (i = 0; i < DIM; i++)
1092         {
1093             for (m = 0; m < DIM; m++)
1094             {
1095                 box[i][m] = 0.0;
1096             }
1097         }
1098         for (m = 0; (m < DIM); m++)
1099         {
1100             box[m][m] = (xmax[m]-xmin[m]);
1101         }
1102         fprintf(stderr, "Generated a cubic box %8.3f x %8.3f x %8.3f\n",
1103                 box[XX][XX], box[YY][YY], box[ZZ][ZZ]);
1104     }
1105     else
1106     {
1107         /* We found the first three values, the diagonal elements */
1108         box[XX][XX] = x1;
1109         box[YY][YY] = y1;
1110         box[ZZ][ZZ] = z1;
1111         if (sscanf (line, "%*f%*f%*f%lf%lf%lf%lf%lf%lf",
1112                     &x1, &y1, &z1, &x2, &y2, &z2) != 6)
1113         {
1114             x1 = y1 = z1 = x2 = y2 = z2 = 0.0;
1115         }
1116         box[XX][YY] = x1;
1117         box[XX][ZZ] = y1;
1118         box[YY][XX] = z1;
1119         box[YY][ZZ] = x2;
1120         box[ZZ][XX] = y2;
1121         box[ZZ][YY] = z2;
1122     }
1123
1124     return bVel;
1125 }
1126
1127 static void read_whole_conf(const char *infile, char *title,
1128                             t_atoms *atoms, rvec x[], rvec *v, matrix box)
1129 {
1130     FILE    *in;
1131     int      ndec;
1132     t_symtab symtab;
1133
1134     /* open file */
1135     in = gmx_fio_fopen(infile, "r");
1136
1137     open_symtab(&symtab);
1138     get_w_conf(in, infile, title, &symtab, atoms, &ndec, x, v, box);
1139     /* We can't free the symbols, as they are still used in atoms, so
1140      * the only choice is to leak them. */
1141     free_symtab(&symtab);
1142
1143     gmx_fio_fclose(in);
1144 }
1145
1146 gmx_bool gro_next_x_or_v(FILE *status, t_trxframe *fr)
1147 {
1148     t_atoms  atoms;
1149     t_symtab symtab;
1150     char     title[STRLEN], *p;
1151     double   tt;
1152     int      ndec = 0, i;
1153
1154     if (gmx_eof(status))
1155     {
1156         return FALSE;
1157     }
1158
1159     open_symtab(&symtab);
1160     atoms.nr = fr->natoms;
1161     snew(atoms.atom, fr->natoms);
1162     atoms.nres = fr->natoms;
1163     snew(atoms.resinfo, fr->natoms);
1164     snew(atoms.atomname, fr->natoms);
1165
1166     fr->bV    = get_w_conf(status, title, title, &symtab, &atoms, &ndec, fr->x, fr->v, fr->box);
1167     fr->bPrec = TRUE;
1168     fr->prec  = 1;
1169     /* prec = 10^ndec: */
1170     for (i = 0; i < ndec; i++)
1171     {
1172         fr->prec *= 10;
1173     }
1174     fr->title  = title;
1175     fr->bTitle = TRUE;
1176     fr->bX     = TRUE;
1177     fr->bBox   = TRUE;
1178
1179     sfree(atoms.atom);
1180     sfree(atoms.resinfo);
1181     sfree(atoms.atomname);
1182     done_symtab(&symtab);
1183
1184     if ((p = strstr(title, "t=")) != NULL)
1185     {
1186         p += 2;
1187         if (sscanf(p, "%lf", &tt) == 1)
1188         {
1189             fr->time  = tt;
1190             fr->bTime = TRUE;
1191         }
1192         else
1193         {
1194             fr->time  = 0;
1195             fr->bTime = FALSE;
1196         }
1197     }
1198
1199     if (atoms.nr != fr->natoms)
1200     {
1201         gmx_fatal(FARGS, "Number of atoms in gro frame (%d) doesn't match the number in the previous frame (%d)", atoms.nr, fr->natoms);
1202     }
1203
1204     return TRUE;
1205 }
1206
1207 int gro_first_x_or_v(FILE *status, t_trxframe *fr)
1208 {
1209     char title[STRLEN];
1210
1211     frewind(status);
1212     fprintf(stderr, "Reading frames from gro file");
1213     get_coordnum_fp(status, title, &fr->natoms);
1214     frewind(status);
1215     fprintf(stderr, " '%s', %d atoms.\n", title, fr->natoms);
1216     fr->bTitle = TRUE;
1217     fr->title  = title;
1218     if (fr->natoms == 0)
1219     {
1220         gmx_file("No coordinates in gro file");
1221     }
1222
1223     snew(fr->x, fr->natoms);
1224     snew(fr->v, fr->natoms);
1225     gro_next_x_or_v(status, fr);
1226
1227     return fr->natoms;
1228 }
1229
1230 static void make_hconf_format(int pr, gmx_bool bVel, char format[])
1231 {
1232     int l, vpr;
1233
1234     /* build format string for printing,
1235        something like "%8.3f" for x and "%8.4f" for v */
1236     if (pr < 0)
1237     {
1238         pr = 0;
1239     }
1240     if (pr > 30)
1241     {
1242         pr = 30;
1243     }
1244     l   = pr+5;
1245     vpr = pr+1;
1246     if (bVel)
1247     {
1248         sprintf(format, "%%%d.%df%%%d.%df%%%d.%df%%%d.%df%%%d.%df%%%d.%df\n",
1249                 l, pr, l, pr, l, pr, l, vpr, l, vpr, l, vpr);
1250     }
1251     else
1252     {
1253         sprintf(format, "%%%d.%df%%%d.%df%%%d.%df\n", l, pr, l, pr, l, pr);
1254     }
1255
1256 }
1257
1258 static void write_hconf_box(FILE *out, int pr, matrix box)
1259 {
1260     char format[100];
1261     int  l;
1262
1263     if (pr < 5)
1264     {
1265         pr = 5;
1266     }
1267     l = pr+5;
1268
1269     if (box[XX][YY] || box[XX][ZZ] || box[YY][XX] || box[YY][ZZ] ||
1270         box[ZZ][XX] || box[ZZ][YY])
1271     {
1272         sprintf(format, "%%%d.%df%%%d.%df%%%d.%df"
1273                 "%%%d.%df%%%d.%df%%%d.%df%%%d.%df%%%d.%df%%%d.%df\n",
1274                 l, pr, l, pr, l, pr, l, pr, l, pr, l, pr, l, pr, l, pr, l, pr);
1275         fprintf(out, format,
1276                 box[XX][XX], box[YY][YY], box[ZZ][ZZ],
1277                 box[XX][YY], box[XX][ZZ], box[YY][XX],
1278                 box[YY][ZZ], box[ZZ][XX], box[ZZ][YY]);
1279     }
1280     else
1281     {
1282         sprintf(format, "%%%d.%df%%%d.%df%%%d.%df\n", l, pr, l, pr, l, pr);
1283         fprintf(out, format,
1284                 box[XX][XX], box[YY][YY], box[ZZ][ZZ]);
1285     }
1286 }
1287
1288 void write_hconf_indexed_p(FILE *out, const char *title, t_atoms *atoms,
1289                            int nx, const atom_id index[], int pr,
1290                            rvec *x, rvec *v, matrix box)
1291 {
1292     char resnm[6], nm[6], format[100];
1293     int  ai, i, resind, resnr;
1294
1295     bromacs(format, 99);
1296     fprintf (out, "%s\n", (title && title[0]) ? title : format);
1297     fprintf (out, "%5d\n", nx);
1298
1299     make_hconf_format(pr, v != NULL, format);
1300
1301     for (i = 0; (i < nx); i++)
1302     {
1303         ai = index[i];
1304
1305         resind = atoms->atom[ai].resind;
1306         strncpy(resnm, " ??? ", sizeof(resnm)-1);
1307         if (resind < atoms->nres)
1308         {
1309             strncpy(resnm, *atoms->resinfo[resind].name, sizeof(resnm)-1);
1310             resnr = atoms->resinfo[resind].nr;
1311         }
1312         else
1313         {
1314             strncpy(resnm, " ??? ", sizeof(resnm)-1);
1315             resnr = resind + 1;
1316         }
1317
1318         if (atoms->atom)
1319         {
1320             strncpy(nm, *atoms->atomname[ai], sizeof(nm)-1);
1321         }
1322         else
1323         {
1324             strncpy(nm, " ??? ", sizeof(nm)-1);
1325         }
1326
1327         fprintf(out, "%5d%-5.5s%5.5s%5d", resnr%100000, resnm, nm, (ai+1)%100000);
1328         /* next fprintf uses built format string */
1329         if (v)
1330         {
1331             fprintf(out, format,
1332                     x[ai][XX], x[ai][YY], x[ai][ZZ], v[ai][XX], v[ai][YY], v[ai][ZZ]);
1333         }
1334         else
1335         {
1336             fprintf(out, format,
1337                     x[ai][XX], x[ai][YY], x[ai][ZZ]);
1338         }
1339     }
1340
1341     write_hconf_box(out, pr, box);
1342
1343     fflush(out);
1344 }
1345
1346 static void write_hconf_mtop(FILE *out, const char *title, gmx_mtop_t *mtop,
1347                              int pr,
1348                              rvec *x, rvec *v, matrix box)
1349 {
1350     char                    format[100];
1351     int                     i, resnr;
1352     gmx_mtop_atomloop_all_t aloop;
1353     t_atom                 *atom;
1354     char                   *atomname, *resname;
1355
1356     bromacs(format, 99);
1357     fprintf (out, "%s\n", (title && title[0]) ? title : format);
1358     fprintf (out, "%5d\n", mtop->natoms);
1359
1360     make_hconf_format(pr, v != NULL, format);
1361
1362     aloop = gmx_mtop_atomloop_all_init(mtop);
1363     while (gmx_mtop_atomloop_all_next(aloop, &i, &atom))
1364     {
1365         gmx_mtop_atomloop_all_names(aloop, &atomname, &resnr, &resname);
1366
1367         fprintf(out, "%5d%-5.5s%5.5s%5d",
1368                 resnr%100000, resname, atomname, (i+1)%100000);
1369         /* next fprintf uses built format string */
1370         if (v)
1371         {
1372             fprintf(out, format,
1373                     x[i][XX], x[i][YY], x[i][ZZ], v[i][XX], v[i][YY], v[i][ZZ]);
1374         }
1375         else
1376         {
1377             fprintf(out, format,
1378                     x[i][XX], x[i][YY], x[i][ZZ]);
1379         }
1380     }
1381
1382     write_hconf_box(out, pr, box);
1383
1384     fflush(out);
1385 }
1386
1387 void write_hconf_p(FILE *out, const char *title, t_atoms *atoms, int pr,
1388                    rvec *x, rvec *v, matrix box)
1389 {
1390     atom_id *aa;
1391     int      i;
1392
1393     snew(aa, atoms->nr);
1394     for (i = 0; (i < atoms->nr); i++)
1395     {
1396         aa[i] = i;
1397     }
1398     write_hconf_indexed_p(out, title, atoms, atoms->nr, aa, pr, x, v, box);
1399     sfree(aa);
1400 }
1401
1402 void write_conf_p(const char *outfile, const char *title,
1403                   t_atoms *atoms, int pr,
1404                   rvec *x, rvec *v, matrix box)
1405 {
1406     FILE *out;
1407
1408     out = gmx_fio_fopen(outfile, "w");
1409     write_hconf_p(out, title, atoms, pr, x, v, box);
1410
1411     gmx_fio_fclose (out);
1412 }
1413
1414 static void write_conf(const char *outfile, const char *title, t_atoms *atoms,
1415                        rvec *x, rvec *v, matrix box)
1416 {
1417     write_conf_p(outfile, title, atoms, 3, x, v, box);
1418 }
1419
1420 void write_sto_conf_indexed(const char *outfile, const char *title,
1421                             t_atoms *atoms,
1422                             rvec x[], rvec *v, int ePBC, matrix box,
1423                             atom_id nindex, atom_id index[])
1424 {
1425     FILE       *out;
1426     int         ftp;
1427     t_trxframe  fr;
1428
1429     ftp = fn2ftp(outfile);
1430     switch (ftp)
1431     {
1432         case efGRO:
1433             out = gmx_fio_fopen(outfile, "w");
1434             write_hconf_indexed_p(out, title, atoms, nindex, index, 3, x, v, box);
1435             gmx_fio_fclose(out);
1436             break;
1437         case efG96:
1438             clear_trxframe(&fr, TRUE);
1439             fr.bTitle = TRUE;
1440             fr.title  = title;
1441             fr.natoms = atoms->nr;
1442             fr.bAtoms = TRUE;
1443             fr.atoms  = atoms;
1444             fr.bX     = TRUE;
1445             fr.x      = x;
1446             if (v)
1447             {
1448                 fr.bV = TRUE;
1449                 fr.v  = v;
1450             }
1451             fr.bBox = TRUE;
1452             copy_mat(box, fr.box);
1453             out = gmx_fio_fopen(outfile, "w");
1454             write_g96_conf(out, &fr, nindex, index);
1455             gmx_fio_fclose(out);
1456             break;
1457         case efPDB:
1458         case efBRK:
1459         case efENT:
1460         case efPQR:
1461             out = gmx_fio_fopen(outfile, "w");
1462             write_pdbfile_indexed(out, title, atoms, x, ePBC, box, ' ', -1, nindex, index, NULL, TRUE);
1463             gmx_fio_fclose(out);
1464             break;
1465         case efESP:
1466             out = gmx_fio_fopen(outfile, "w");
1467             write_espresso_conf_indexed(out, title, atoms, nindex, index, x, v, box);
1468             gmx_fio_fclose(out);
1469             break;
1470         case efTPR:
1471         case efTPB:
1472         case efTPA:
1473             gmx_fatal(FARGS, "Sorry, can not write a topology to %s", outfile);
1474             break;
1475         default:
1476             gmx_incons("Not supported in write_sto_conf_indexed");
1477     }
1478 }
1479
1480 static void write_xyz_conf(const char *outfile, const char *title,
1481                            t_atoms *atoms, rvec *x)
1482 {
1483     FILE          *fp;
1484     int            i, anr;
1485     real           value;
1486     char          *ptr, *name;
1487     gmx_atomprop_t aps = gmx_atomprop_init();
1488
1489     fp = gmx_fio_fopen(outfile, "w");
1490     fprintf(fp, "%3d\n", atoms->nr);
1491     fprintf(fp, "%s\n", title);
1492     for (i = 0; (i < atoms->nr); i++)
1493     {
1494         anr  = atoms->atom[i].atomnumber;
1495         name = *atoms->atomname[i];
1496         if (anr == NOTSET)
1497         {
1498             if (gmx_atomprop_query(aps, epropElement, "???", name, &value))
1499             {
1500                 anr = gmx_nint(value);
1501             }
1502         }
1503         if ((ptr = gmx_atomprop_element(aps, anr)) == NULL)
1504         {
1505             ptr = name;
1506         }
1507         fprintf(fp, "%3s%10.5f%10.5f%10.5f\n", ptr,
1508                 10*x[i][XX], 10*x[i][YY], 10*x[i][ZZ]);
1509     }
1510     gmx_fio_fclose(fp);
1511     gmx_atomprop_destroy(aps);
1512 }
1513
1514 void write_sto_conf(const char *outfile, const char *title, t_atoms *atoms,
1515                     rvec x[], rvec *v, int ePBC, matrix box)
1516 {
1517     FILE       *out;
1518     int         ftp;
1519     t_trxframe  fr;
1520
1521     ftp = fn2ftp(outfile);
1522     switch (ftp)
1523     {
1524         case efGRO:
1525             write_conf(outfile, title, atoms, x, v, box);
1526             break;
1527         case efG96:
1528             clear_trxframe(&fr, TRUE);
1529             fr.bTitle = TRUE;
1530             fr.title  = title;
1531             fr.natoms = atoms->nr;
1532             fr.bAtoms = TRUE;
1533             fr.atoms  = atoms;
1534             fr.bX     = TRUE;
1535             fr.x      = x;
1536             if (v)
1537             {
1538                 fr.bV = TRUE;
1539                 fr.v  = v;
1540             }
1541             fr.bBox = TRUE;
1542             copy_mat(box, fr.box);
1543             out = gmx_fio_fopen(outfile, "w");
1544             write_g96_conf(out, &fr, -1, NULL);
1545             gmx_fio_fclose(out);
1546             break;
1547         case efXYZ:
1548             write_xyz_conf(outfile, (strlen(title) > 0) ? title : outfile, atoms, x);
1549             break;
1550         case efPDB:
1551         case efBRK:
1552         case efENT:
1553             out = gmx_fio_fopen(outfile, "w");
1554             write_pdbfile(out, title, atoms, x, ePBC, box, ' ', -1, NULL, TRUE);
1555             gmx_fio_fclose(out);
1556             break;
1557         case efESP:
1558             out = gmx_fio_fopen(outfile, "w");
1559             write_espresso_conf_indexed(out, title, atoms, atoms->nr, NULL, x, v, box);
1560             gmx_fio_fclose(out);
1561             break;
1562         case efTPR:
1563         case efTPB:
1564         case efTPA:
1565             gmx_fatal(FARGS, "Sorry, can not write a topology to %s", outfile);
1566             break;
1567         default:
1568             gmx_incons("Not supported in write_sto_conf");
1569     }
1570 }
1571
1572 void write_sto_conf_mtop(const char *outfile, const char *title,
1573                          gmx_mtop_t *mtop,
1574                          rvec x[], rvec *v, int ePBC, matrix box)
1575 {
1576     int     ftp;
1577     FILE   *out;
1578     t_atoms atoms;
1579
1580     ftp = fn2ftp(outfile);
1581     switch (ftp)
1582     {
1583         case efGRO:
1584             out = gmx_fio_fopen(outfile, "w");
1585             write_hconf_mtop(out, title, mtop, 3, x, v, box);
1586             gmx_fio_fclose(out);
1587             break;
1588         default:
1589             /* This is a brute force approach which requires a lot of memory.
1590              * We should implement mtop versions of all writing routines.
1591              */
1592             atoms = gmx_mtop_global_atoms(mtop);
1593
1594             write_sto_conf(outfile, title, &atoms, x, v, ePBC, box);
1595
1596             done_atom(&atoms);
1597             break;
1598     }
1599 }
1600
1601 static int get_xyz_coordnum(const char *infile)
1602 {
1603     FILE *fp;
1604     int   n;
1605
1606     fp = gmx_fio_fopen(infile, "r");
1607     if (fscanf(fp, "%d", &n) != 1)
1608     {
1609         gmx_fatal(FARGS, "Can not read number of atoms from %s", infile);
1610     }
1611     gmx_fio_fclose(fp);
1612
1613     return n;
1614 }
1615
1616 static void read_xyz_conf(const char *infile, char *title,
1617                           t_atoms *atoms, rvec *x)
1618 {
1619     FILE     *fp;
1620     int       i, n;
1621     double    xx, yy, zz;
1622     t_symtab *tab;
1623     char      atomnm[32], buf[STRLEN];
1624
1625     snew(tab, 1);
1626     fp = gmx_fio_fopen(infile, "r");
1627     fgets2(buf, STRLEN-1, fp);
1628     if (sscanf(buf, "%d", &n) != 1)
1629     {
1630         gmx_fatal(FARGS, "Can not read number of atoms from %s", infile);
1631     }
1632     fgets2(buf, STRLEN-1, fp);
1633     strcpy(title, buf);
1634     for (i = 0; (i < n); i++)
1635     {
1636         fgets2(buf, STRLEN-1, fp);
1637         if (sscanf(buf, "%s%lf%lf%lf", atomnm, &xx, &yy, &zz) != 4)
1638         {
1639             gmx_fatal(FARGS, "Can not read coordinates from %s", infile);
1640         }
1641         atoms->atomname[i] = put_symtab(tab, atomnm);
1642         x[i][XX]           = xx*0.1;
1643         x[i][YY]           = yy*0.1;
1644         x[i][ZZ]           = zz*0.1;
1645     }
1646     gmx_fio_fclose(fp);
1647 }
1648
1649 void get_stx_coordnum(const char *infile, int *natoms)
1650 {
1651     FILE      *in;
1652     int        ftp, tpxver, tpxgen;
1653     t_trxframe fr;
1654     char       g96_line[STRLEN+1];
1655
1656     ftp = fn2ftp(infile);
1657     range_check(ftp, 0, efNR);
1658     switch (ftp)
1659     {
1660         case efGRO:
1661             get_coordnum(infile, natoms);
1662             break;
1663         case efG96:
1664             in        = gmx_fio_fopen(infile, "r");
1665             fr.title  = NULL;
1666             fr.natoms = -1;
1667             fr.atoms  = NULL;
1668             fr.x      = NULL;
1669             fr.v      = NULL;
1670             fr.f      = NULL;
1671             *natoms   = read_g96_conf(in, infile, &fr, g96_line);
1672             gmx_fio_fclose(in);
1673             break;
1674         case efXYZ:
1675             *natoms = get_xyz_coordnum(infile);
1676             break;
1677         case efPDB:
1678         case efBRK:
1679         case efENT:
1680             in = gmx_fio_fopen(infile, "r");
1681             get_pdb_coordnum(in, natoms);
1682             gmx_fio_fclose(in);
1683             break;
1684         case efESP:
1685             *natoms = get_espresso_coordnum(infile);
1686             break;
1687         case efTPA:
1688         case efTPB:
1689         case efTPR:
1690         {
1691             t_tpxheader tpx;
1692
1693             read_tpxheader(infile, &tpx, TRUE, &tpxver, &tpxgen);
1694             *natoms = tpx.natoms;
1695             break;
1696         }
1697         default:
1698             gmx_fatal(FARGS, "File type %s not supported in get_stx_coordnum",
1699                       ftp2ext(ftp));
1700     }
1701 }
1702
1703 void read_stx_conf(const char *infile, char *title, t_atoms *atoms,
1704                    rvec x[], rvec *v, int *ePBC, matrix box)
1705 {
1706     FILE       *in;
1707     char        buf[256];
1708     gmx_mtop_t *mtop;
1709     t_topology  top;
1710     t_trxframe  fr;
1711     int         i, ftp, natoms;
1712     real        d;
1713     char        g96_line[STRLEN+1];
1714
1715     if (atoms->nr == 0)
1716     {
1717         fprintf(stderr, "Warning: Number of atoms in %s is 0\n", infile);
1718     }
1719     else if (atoms->atom == NULL)
1720     {
1721         gmx_mem("Uninitialized array atom");
1722     }
1723
1724     if (ePBC)
1725     {
1726         *ePBC = -1;
1727     }
1728
1729     ftp = fn2ftp(infile);
1730     switch (ftp)
1731     {
1732         case efGRO:
1733             read_whole_conf(infile, title, atoms, x, v, box);
1734             break;
1735         case efXYZ:
1736             read_xyz_conf(infile, title, atoms, x);
1737             break;
1738         case efG96:
1739             fr.title  = NULL;
1740             fr.natoms = atoms->nr;
1741             fr.atoms  = atoms;
1742             fr.x      = x;
1743             fr.v      = v;
1744             fr.f      = NULL;
1745             in        = gmx_fio_fopen(infile, "r");
1746             read_g96_conf(in, infile, &fr, g96_line);
1747             gmx_fio_fclose(in);
1748             copy_mat(fr.box, box);
1749             strncpy(title, fr.title, STRLEN);
1750             break;
1751         case efPDB:
1752         case efBRK:
1753         case efENT:
1754             read_pdb_conf(infile, title, atoms, x, ePBC, box, TRUE, NULL);
1755             break;
1756         case efESP:
1757             read_espresso_conf(infile, atoms, x, v, box);
1758             break;
1759         case efTPR:
1760         case efTPB:
1761         case efTPA:
1762             snew(mtop, 1);
1763             i = read_tpx(infile, NULL, box, &natoms, x, v, NULL, mtop);
1764             if (ePBC)
1765             {
1766                 *ePBC = i;
1767             }
1768
1769             strcpy(title, *(mtop->name));
1770
1771             /* Free possibly allocated memory */
1772             done_atom(atoms);
1773
1774             *atoms = gmx_mtop_global_atoms(mtop);
1775             top    = gmx_mtop_t_to_t_topology(mtop);
1776             tpx_make_chain_identifiers(atoms, &top.mols);
1777
1778             sfree(mtop);
1779             /* The strings in the symtab are still in use in the returned t_atoms
1780              * structure, so we should not free them. But there is no place to put the
1781              * symbols; the only choice is to leak the memory...
1782              * So we clear the symbol table before freeing the topology structure. */
1783             free_symtab(&top.symtab);
1784             done_top(&top);
1785
1786             break;
1787         default:
1788             gmx_incons("Not supported in read_stx_conf");
1789     }
1790 }