Clean up futil.*
[alexxy/gromacs.git] / src / gromacs / gmxpreprocess / fflibutil.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2010,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 #ifdef HAVE_CONFIG_H
36 #include <config.h>
37 #endif
38
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <fcntl.h>
45
46 #include "sysstuff.h"
47 #include "network.h"
48
49 #include "gromacs/utility/cstringutil.h"
50 #include "gromacs/utility/fatalerror.h"
51 #include "gromacs/utility/smalloc.h"
52
53 #ifdef HAVE_UNISTD_H
54 #include <unistd.h>
55 #endif
56
57 #include "fflibutil.h"
58
59 #include "gromacs/fileio/futil.h"
60 #include "gromacs/fileio/path.h"
61 #include "gromacs/utility/exceptions.h"
62 #include "gromacs/utility/programcontext.h"
63
64 const char *fflib_forcefield_dir_ext()
65 {
66     return ".ff";
67 }
68
69 const char *fflib_forcefield_itp()
70 {
71     return "forcefield.itp";
72 }
73
74 const char *fflib_forcefield_doc()
75 {
76     return "forcefield.doc";
77 }
78
79 void fflib_filename_base(const char *filename, char *filebase, int maxlen)
80 {
81     const char *cptr;
82     char       *ptr;
83
84     cptr = strrchr(filename, DIR_SEPARATOR);
85     if (cptr != NULL)
86     {
87         /* Skip the separator */
88         cptr += 1;
89     }
90     else
91     {
92         cptr = filename;
93     }
94     if (strlen(filename) >= (size_t)maxlen)
95     {
96         gmx_fatal(FARGS, "filename is longer (%d) than maxlen (%d)",
97                   strlen(filename), maxlen);
98     }
99     strcpy(filebase, cptr);
100     /* Remove the extension */
101     ptr = strrchr(filebase, '.');
102     if (ptr != NULL)
103     {
104         ptr[0] = '\0';
105     }
106 }
107
108 static void sort_filenames(int n, char **name, char **name2)
109 {
110     /* Slow sort, but we usually have tens of names */
111     int   i, j, f;
112     char *tmp;
113
114     for (i = 0; i < n-1; i++)
115     {
116         f = i;
117         for (j = i+1; j < n; j++)
118         {
119             if (strcmp(name[j], name[f]) < 0)
120             {
121                 f = j;
122             }
123         }
124         if (f > i)
125         {
126             tmp     = name[i];
127             name[i] = name[f];
128             name[f] = tmp;
129             if (name2 != NULL)
130             {
131                 tmp      = name2[i];
132                 name2[i] = name2[f];
133                 name2[f] = tmp;
134             }
135         }
136     }
137 }
138
139 static int low_fflib_search_file_end(const char *ffdir,
140                                      gmx_bool    bAddCWD,
141                                      const char *file_end,
142                                      gmx_bool    bFatalError,
143                                      char     ***filenames,
144                                      char     ***filenames_short)
145 {
146     char **fns = NULL, **fns_short = NULL;
147     int    n   = 0;
148     try
149     {
150         std::vector<std::string> libPaths;
151         bool                     bEnvIsSet = false;
152
153         if (ffdir != NULL)
154         {
155             /* Search ffdir in current dir and library dirs */
156             libPaths.push_back(gmxlibfn(ffdir));
157         }
158         else
159         {
160             /* GMXLIB can be a path now */
161             if (bAddCWD)
162             {
163                 libPaths.push_back(".");
164             }
165             const char *lib = getenv("GMXLIB");
166             if (lib != NULL)
167             {
168                 bEnvIsSet = true;
169                 gmx::Path::splitPathEnvironment(lib, &libPaths);
170             }
171             else
172             {
173                 libPaths.push_back(gmx::getProgramContext().defaultLibraryDataPath());
174             }
175         }
176
177         const int len_fe = strlen(file_end);
178
179         std::vector<std::string>::const_iterator i;
180         for (i = libPaths.begin(); i != libPaths.end(); ++i)
181         {
182             const char      *dir = i->c_str();
183             gmx_directory_t  dirhandle;
184             const int        rc  = gmx_directory_open(&dirhandle, dir);
185             if (rc == 0)
186             {
187                 char nextname[STRLEN];
188                 int  n_thisdir = 0;
189                 while (gmx_directory_nextfile(dirhandle, nextname, STRLEN-1) == 0)
190                 {
191                     nextname[STRLEN-1] = 0;
192                     if (debug)
193                     {
194                         fprintf(debug, "dir '%s' %d file '%s'\n",
195                                 dir, n_thisdir, nextname);
196                     }
197                     const int len_name = strlen(nextname);
198                     /* What about case sensitivity? */
199                     if (len_name >= len_fe &&
200                         strcmp(nextname+len_name-len_fe, file_end) == 0)
201                     {
202                         char fn_dir[GMX_PATH_MAX];
203                         /* We have a match */
204                         srenew(fns, n+1);
205                         sprintf(fn_dir, "%s%c%s", dir, DIR_SEPARATOR, nextname);
206
207                         /* Copy the file name, possibly including the path. */
208                         fns[n] = strdup(fn_dir);
209
210                         if (ffdir == NULL)
211                         {
212                             /* We are searching in a path.
213                              * Use the relative path when we use share/top
214                              * from the installation.
215                              * Add the full path when we use the current
216                              * working directory of GMXLIB.
217                              */
218                             srenew(fns_short, n+1);
219                             if (strcmp(dir, ".") == 0 || bEnvIsSet)
220                             {
221                                 fns_short[n] = strdup(fn_dir);
222                             }
223                             else
224                             {
225                                 fns_short[n] = strdup(nextname);
226                             }
227                         }
228                         n++;
229                         n_thisdir++;
230                     }
231                 }
232                 gmx_directory_close(dirhandle);
233
234                 sort_filenames(n_thisdir,
235                                fns+n-n_thisdir,
236                                fns_short == NULL ? NULL : fns_short+n-n_thisdir);
237             }
238         }
239     }
240     GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
241
242     if (n == 0 && bFatalError)
243     {
244         if (ffdir != NULL)
245         {
246             gmx_fatal(FARGS, "Could not find any files ending on '%s' in the force field directory '%s'", file_end, ffdir);
247         }
248         else
249         {
250             gmx_fatal(FARGS, "Could not find any files ending on '%s' in the current directory or the GROMACS library search path", file_end);
251         }
252     }
253
254     *filenames = fns;
255     if (ffdir == NULL)
256     {
257         *filenames_short = fns_short;
258     }
259
260     return n;
261 }
262
263 int fflib_search_file_end(const char *ffdir,
264                           const char *file_end,
265                           gmx_bool    bFatalError,
266                           char     ***filenames)
267 {
268     return low_fflib_search_file_end(ffdir, FALSE, file_end, bFatalError,
269                                      filenames, NULL);
270 }
271
272 int fflib_search_file_in_dirend(const char *filename, const char *dirend,
273                                 char ***dirnames)
274 {
275     int             nf, i;
276     char          **f, **f_short;
277     int             n;
278     char          **dns;
279     gmx_directory_t dirhandle;
280     char            nextname[STRLEN];
281     int             rc;
282
283     /* Find all files (not only dir's) ending on dirend */
284     nf = low_fflib_search_file_end(NULL, TRUE, dirend, FALSE, &f, &f_short);
285
286     n   = 0;
287     dns = NULL;
288     for (i = 0; i < nf; i++)
289     {
290         rc = gmx_directory_open(&dirhandle, f[i]);
291
292         if (rc == 0)
293         {
294             while (gmx_directory_nextfile(dirhandle, nextname, STRLEN-1) == 0)
295             {
296                 nextname[STRLEN-1] = 0;
297                 if (strcmp(nextname, filename) == 0)
298                 {
299                     /* We have a match */
300                     srenew(dns, n+1);
301                     dns[n] = strdup(f_short[i]);
302                     n++;
303                 }
304             }
305             gmx_directory_close(dirhandle);
306         }
307         sfree(f[i]);
308         sfree(f_short[i]);
309     }
310     sfree(f);
311     sfree(f_short);
312
313     *dirnames = dns;
314
315     return n;
316 }
317
318 gmx_bool fflib_fexist(const char *file)
319 {
320     char *file_fullpath;
321
322     file_fullpath = low_gmxlibfn(file, TRUE, FALSE);
323
324     if (file_fullpath == NULL)
325     {
326         return FALSE;
327     }
328     else
329     {
330         sfree(file_fullpath);
331
332         return TRUE;
333     }
334 }
335
336
337 FILE *fflib_open(const char *file)
338 {
339     char *file_fullpath;
340     FILE *fp;
341
342     file_fullpath = gmxlibfn(file);
343     fprintf(stderr, "Opening force field file %s\n", file_fullpath);
344     fp = gmx_ffopen(file_fullpath, "r");
345     sfree(file_fullpath);
346
347     return fp;
348 }