Merge branch 'master' into pygromacs
[alexxy/gromacs.git] / src / gromacs / gmxana / gmx_bar.cpp
similarity index 94%
rename from src/gromacs/gmxana/gmx_bar.c
rename to src/gromacs/gmxana/gmx_bar.cpp
index 84cc7caf32a80e64fe2c8c8481547e35096f3761..776c6882ad741ccc9e6713c47c6c0e72988ff506 100644 (file)
  */
 #include "gmxpre.h"
 
-#include <ctype.h>
-#include <float.h>
-#include <math.h>
-#include <stdlib.h>
-#include <string.h>
+#include <cctype>
+#include <cmath>
+#include <cstdlib>
+#include <cstring>
+
+#include <algorithm>
+#include <limits>
 
 #include "gromacs/commandline/pargs.h"
 #include "gromacs/fileio/enxio.h"
@@ -54,6 +56,7 @@
 #include "gromacs/utility/cstringutil.h"
 #include "gromacs/utility/dir_separator.h"
 #include "gromacs/utility/fatalerror.h"
+#include "gromacs/utility/gmxassert.h"
 #include "gromacs/utility/smalloc.h"
 #include "gromacs/utility/snprintf.h"
 
@@ -236,7 +239,7 @@ static void lambda_components_add(lambda_components_t *lc,
         srenew(lc->names, lc->Nalloc);
     }
     snew(lc->names[lc->N], name_length+1);
-    strncpy(lc->names[lc->N], name, name_length);
+    std::strncpy(lc->names[lc->N], name, name_length);
     lc->N++;
 }
 
@@ -261,12 +264,12 @@ static gmx_bool lambda_components_check(const lambda_components_t *lc,
     {
         return FALSE;
     }
-    len = strlen(lc->names[index]);
+    len = std::strlen(lc->names[index]);
     if (len != name_length)
     {
         return FALSE;
     }
-    if (strncmp(lc->names[index], name, name_length) == 0)
+    if (std::strncmp(lc->names[index], name, name_length) == 0)
     {
         return TRUE;
     }
@@ -282,7 +285,7 @@ static int lambda_components_find(const lambda_components_t *lc,
 
     for (i = 0; i < lc->N; i++)
     {
-        if (strncmp(lc->names[i], name, name_length) == 0)
+        if (std::strncmp(lc->names[i], name, name_length) == 0)
         {
             return i;
         }
@@ -323,7 +326,6 @@ static void lambda_vec_copy(lambda_vec_t *lv, const lambda_vec_t *orig)
 static void lambda_vec_print(const lambda_vec_t *lv, char *str, gmx_bool named)
 {
     int    i;
-    size_t np;
 
     str[0] = 0; /* reset the string */
     if (lv->dhdl < 0)
@@ -346,14 +348,14 @@ static void lambda_vec_print(const lambda_vec_t *lv, char *str, gmx_bool named)
         }
         if (lv->lc->N > 1)
         {
-            str += sprintf(str, ")");
+            sprintf(str, ")");
         }
     }
     else
     {
         /* this lambda vector describes a derivative */
         str += sprintf(str, "dH/dl");
-        if (strlen(lv->lc->names[lv->dhdl]) > 0)
+        if (std::strlen(lv->lc->names[lv->dhdl]) > 0)
         {
             sprintf(str, " (%s)", lv->lc->names[lv->dhdl]);
         }
@@ -363,9 +365,6 @@ static void lambda_vec_print(const lambda_vec_t *lv, char *str, gmx_bool named)
 /* write a shortened version of the lambda vec to a preallocated string */
 static void lambda_vec_print_short(const lambda_vec_t *lv, char *str)
 {
-    int    i;
-    size_t np;
-
     if (lv->index >= 0)
     {
         sprintf(str, "%6d", lv->index);
@@ -387,19 +386,16 @@ static void lambda_vec_print_short(const lambda_vec_t *lv, char *str)
 static void lambda_vec_print_intermediate(const lambda_vec_t *a,
                                           const lambda_vec_t *b, char *str)
 {
-    int    i;
-    size_t np;
-
     str[0] = 0;
     if ( (a->index >= 0) && (b->index >= 0) )
     {
-        sprintf(str, "%6.3f", ((double)a->index+(double)b->index)/2.);
+        sprintf(str, "%6.3f", (a->index+b->index)/2.0);
     }
     else
     {
         if ( (a->dhdl < 0) && (b->dhdl < 0) )
         {
-            sprintf(str, "%6.3f", (a->val[0]+b->val[0])/2.);
+            sprintf(str, "%6.3f", (a->val[0]+b->val[0])/2.0);
         }
     }
 }
@@ -452,7 +448,7 @@ static double lambda_vec_abs_diff(const lambda_vec_t *a, const lambda_vec_t *b)
         double df = a->val[i] - b->val[i];
         ret += df*df;
     }
-    return sqrt(ret);
+    return std::sqrt(ret);
 }
 
 
@@ -545,8 +541,6 @@ static gmx_bool lambda_vec_cmp_foreign(const lambda_vec_t *a,
 static gmx_bool lambda_vec_cmp_native(const lambda_vec_t *a,
                                       const lambda_vec_t *b)
 {
-    int i;
-
     if (a->lc != b->lc)
     {
         gmx_fatal(FARGS, "Can't compare lambdas with differing basis sets");
@@ -809,7 +803,7 @@ static void sample_coll_insert_sample(sample_coll_t *sc, samples_t *s,
     /* check if there's room */
     if ( (sc->nsamples + 1) > sc->nsamples_alloc)
     {
-        sc->nsamples_alloc = max(2*sc->nsamples_alloc, 2);
+        sc->nsamples_alloc = std::max(2*sc->nsamples_alloc, 2);
         srenew(sc->s, sc->nsamples_alloc);
         srenew(sc->r, sc->nsamples_alloc);
     }
@@ -968,7 +962,7 @@ static void sample_coll_make_hist(sample_coll_t *sc, int **bin,
     }
     else
     {
-        *nbin = (xmax-(*xmin))/(*dx);
+        *nbin = static_cast<int>((xmax-(*xmin))/(*dx));
     }
 
     if (*nbin > *nbin_alloc)
@@ -998,7 +992,7 @@ static void sample_coll_make_hist(sample_coll_t *sc, int **bin,
                     /* calculate the bin corresponding to the middle of the
                        original bin */
                     double x     = hdx*(j+0.5) + xmin_hist;
-                    int    binnr = (int)((x-(*xmin))/(*dx));
+                    int    binnr = static_cast<int>((x-(*xmin))/(*dx));
 
                     if (binnr >= *nbin || binnr < 0)
                     {
@@ -1015,7 +1009,7 @@ static void sample_coll_make_hist(sample_coll_t *sc, int **bin,
             int endi   = sc->r[i].end;
             for (j = starti; j < endi; j++)
             {
-                int binnr = (int)((sc->s[i]->du[j]-(*xmin))/(*dx));
+                int binnr = static_cast<int>((sc->s[i]->du[j]-(*xmin))/(*dx));
                 if (binnr >= *nbin || binnr < 0)
                 {
                     binnr = (*nbin)-1;
@@ -1045,7 +1039,7 @@ void sim_data_histogram(sim_data_t *sd, const char *filename,
     int            nbin       = 0;
     int            nbin_alloc = 0;
     double         dx         = 0;
-    double         min        = 0;
+    double         minval     = 0;
     int            i;
     lambda_data_t *bl_head = sd->lb;
 
@@ -1105,13 +1099,13 @@ void sim_data_histogram(sim_data_t *sd, const char *filename,
                 xvgr_new_dataset(fp, 0, 0, NULL, oenv);
             }
 
-            sample_coll_make_hist(sc, &hist, &nbin_alloc, &nbin, &dx, &min,
+            sample_coll_make_hist(sc, &hist, &nbin_alloc, &nbin, &dx, &minval,
                                   nbin_default);
 
             for (i = 0; i < nbin; i++)
             {
-                double xmin = i*dx + min;
-                double xmax = (i+1)*dx + min;
+                double xmin = i*dx + minval;
+                double xmax = (i+1)*dx + minval;
 
                 fprintf(fp, "%g %d\n%g %d\n", xmin, hist[i], xmax, hist[i]);
             }
@@ -1164,7 +1158,6 @@ static barres_t *barres_list_create(sim_data_t *sd, int *nres,
     lambda_data_t *bl;
     int            nlambda = 0;
     barres_t      *res;
-    int            i;
     gmx_bool       dhdl    = FALSE;
     gmx_bool       first   = TRUE;
     lambda_data_t *bl_head = sd->lb;
@@ -1267,7 +1260,7 @@ static double barres_list_max_disc_err(barres_t *res, int nres)
                     Wfac =  delta_lambda;
                 }
 
-                disc_err = max(disc_err, Wfac*br->a->s[j]->hist->dx[0]);
+                disc_err = std::max(disc_err, Wfac*br->a->s[j]->hist->dx[0]);
             }
         }
         for (j = 0; j < br->b->nsamples; j++)
@@ -1279,7 +1272,7 @@ static double barres_list_max_disc_err(barres_t *res, int nres)
                 {
                     Wfac =  delta_lambda;
                 }
-                disc_err = max(disc_err, Wfac*br->b->s[j]->hist->dx[0]);
+                disc_err = std::max(disc_err, Wfac*br->b->s[j]->hist->dx[0]);
             }
         }
     }
@@ -1312,12 +1305,12 @@ static void sample_coll_impose_times(sample_coll_t *sc, double begin_t,
                 double end_time;
                 if (s->start_time < begin_t)
                 {
-                    r->start = (int)((begin_t - s->start_time)/s->delta_time);
+                    r->start = static_cast<int>((begin_t - s->start_time)/s->delta_time);
                 }
                 end_time = s->delta_time*s->ndu + s->start_time;
                 if (end_time > end_t)
                 {
-                    r->end = (int)((end_t - s->start_time)/s->delta_time);
+                    r->end = static_cast<int>((end_t - s->start_time)/s->delta_time);
                 }
             }
             else
@@ -1451,7 +1444,6 @@ static gmx_bool sample_coll_create_subsample(sample_coll_t  *sc,
                                              int i, int ni)
 {
     int             j;
-    int             hist_start, hist_end;
 
     gmx_int64_t     ntot_start;
     gmx_int64_t     ntot_end;
@@ -1472,8 +1464,8 @@ static gmx_bool sample_coll_create_subsample(sample_coll_t  *sc,
 
     /* now fix start and end fields */
     /* the casts avoid possible overflows */
-    ntot_start  = (gmx_int64_t)(sc_orig->ntot*(double)i/(double)ni);
-    ntot_end    = (gmx_int64_t)(sc_orig->ntot*(double)(i+1)/(double)ni);
+    ntot_start  = static_cast<gmx_int64_t>(sc_orig->ntot*static_cast<double>(i)/static_cast<double>(ni));
+    ntot_end    = static_cast<gmx_int64_t>(sc_orig->ntot*static_cast<double>(i+1)/static_cast<double>(ni));
     ntot_so_far = 0;
     for (j = 0; j < sc->nsamples; j++)
     {
@@ -1521,8 +1513,10 @@ static gmx_bool sample_coll_create_subsample(sample_coll_t  *sc,
                 new_end   = 0;
             }
             /* and write the new range */
-            sc->r[j].start = (int)new_start;
-            sc->r[j].end   = (int)new_end;
+            GMX_RELEASE_ASSERT(new_start <= std::numeric_limits<int>::max(), "Value of 'new_start' too large for int converstion");
+            GMX_RELEASE_ASSERT(new_end <= std::numeric_limits<int>::max(), "Value of 'new_end' too large for int converstion");
+            sc->r[j].start = static_cast<int>(new_start);
+            sc->r[j].end   = static_cast<int>(new_end);
         }
         else
         {
@@ -1536,12 +1530,12 @@ static gmx_bool sample_coll_create_subsample(sample_coll_t  *sc,
 
                 /* first calculate normalized bounds
                    (where 0 is the start of the hist range, and 1 the end) */
-                ntot_start_norm = (ntot_start-ntot_so_far)/(double)ntot_add;
-                ntot_end_norm   = (ntot_end-ntot_so_far)/(double)ntot_add;
+                ntot_start_norm = (ntot_start-ntot_so_far)/static_cast<double>(ntot_add);
+                ntot_end_norm   = (ntot_end-ntot_so_far)/static_cast<double>(ntot_add);
 
                 /* now fix the boundaries */
-                ntot_start_norm = min(1, max(0., ntot_start_norm));
-                ntot_end_norm   = max(0, min(1., ntot_end_norm));
+                ntot_start_norm = std::min(1.0, std::max(0.0, ntot_start_norm));
+                ntot_end_norm   = std::max(0.0, std::min(1.0, ntot_end_norm));
 
                 /* and calculate the overlap */
                 overlap = ntot_end_norm - ntot_start_norm;
@@ -1573,8 +1567,8 @@ static void sample_coll_min_max(sample_coll_t *sc, double Wfac,
 {
     int i, j;
 
-    *Wmin = FLT_MAX;
-    *Wmax = -FLT_MAX;
+    *Wmin =  std::numeric_limits<float>::max();
+    *Wmax = -std::numeric_limits<float>::max();
 
     for (i = 0; i < sc->nsamples; i++)
     {
@@ -1586,8 +1580,8 @@ static void sample_coll_min_max(sample_coll_t *sc, double Wfac,
             {
                 for (j = r->start; j < r->end; j++)
                 {
-                    *Wmin = min(*Wmin, s->du[j]*Wfac);
-                    *Wmax = max(*Wmax, s->du[j]*Wfac);
+                    *Wmin = std::min(*Wmin, s->du[j]*Wfac);
+                    *Wmax = std::max(*Wmax, s->du[j]*Wfac);
                 }
             }
             else
@@ -1602,13 +1596,13 @@ static void sample_coll_min_max(sample_coll_t *sc, double Wfac,
 
                 for (j = s->hist->nbin[hd]-1; j >= 0; j--)
                 {
-                    *Wmin = min(*Wmin, Wfac*(s->hist->x0[hd])*dx);
-                    *Wmax = max(*Wmax, Wfac*(s->hist->x0[hd])*dx);
+                    *Wmin = std::min(*Wmin, Wfac*(s->hist->x0[hd])*dx);
+                    *Wmax = std::max(*Wmax, Wfac*(s->hist->x0[hd])*dx);
                     /* look for the highest value bin with values */
                     if (s->hist->bin[hd][j] > 0)
                     {
-                        *Wmin = min(*Wmin, Wfac*(j+s->hist->x0[hd]+1)*dx);
-                        *Wmax = max(*Wmax, Wfac*(j+s->hist->x0[hd]+1)*dx);
+                        *Wmin = std::min(*Wmin, Wfac*(j+s->hist->x0[hd]+1)*dx);
+                        *Wmax = std::max(*Wmax, Wfac*(j+s->hist->x0[hd]+1)*dx);
                         break;
                     }
                 }
@@ -1638,7 +1632,7 @@ static double calc_bar_sum(int n, const double *W, double Wfac, double sbMmDG)
 
     for (i = 0; i < n; i++)
     {
-        sum += 1./(1. + exp(Wfac*W[i] + sbMmDG));
+        sum += 1./(1. + std::exp(Wfac*W[i] + sbMmDG));
     }
 
     return sum;
@@ -1654,7 +1648,7 @@ static double calc_bar_sum_hist(const hist_t *hist, double Wfac, double sbMmDG,
 {
     double sum = 0.;
     int    i;
-    int    max;
+    int    maxbin;
     /* normalization factor multiplied with bin width and
        number of samples (we normalize through M): */
     double normdx = 1.;
@@ -1665,19 +1659,19 @@ static double calc_bar_sum_hist(const hist_t *hist, double Wfac, double sbMmDG,
     {
         hd = 1;
     }
-    dx  = hist->dx[hd];
-    max = hist->nbin[hd]-1;
+    dx     = hist->dx[hd];
+    maxbin = hist->nbin[hd]-1;
     if (type == 1)
     {
-        max = hist->nbin[hd]; /* we also add whatever was out of range */
+        maxbin = hist->nbin[hd]; /* we also add whatever was out of range */
     }
 
-    for (i = 0; i < max; i++)
+    for (i = 0; i < maxbin; i++)
     {
         double x    = Wfac*((i+hist->x0[hd])+0.5)*dx; /* bin middle */
         double pxdx = hist->bin[0][i]*normdx;         /* p(x)dx */
 
-        sum += pxdx/(1. + exp(x + sbMmDG));
+        sum += pxdx/(1. + std::exp(x + sbMmDG));
     }
 
     return sum;
@@ -1687,11 +1681,9 @@ static double calc_bar_lowlevel(sample_coll_t *ca, sample_coll_t *cb,
                                 double temp, double tol, int type)
 {
     double kT, beta, M;
-    double DG;
-    int    i, j;
+    int    i;
     double Wfac1, Wfac2, Wmin, Wmax;
     double DG0, DG1, DG2, dDG1;
-    double sum1, sum2;
     double n1, n2; /* numbers of samples as doubles */
 
     kT   = BOLTZ*temp;
@@ -1701,7 +1693,7 @@ static double calc_bar_lowlevel(sample_coll_t *ca, sample_coll_t *cb,
     n1 = ca->ntot;
     n2 = cb->ntot;
 
-    M = log(n1/n2);
+    M = std::log(n1/n2);
 
     /*if (!lambda_vec_same(ca->native_lambda, ca->foreign_lambda))*/
     if (ca->foreign_lambda->dhdl < 0)
@@ -1745,8 +1737,8 @@ static double calc_bar_lowlevel(sample_coll_t *ca, sample_coll_t *cb,
         sample_coll_min_max(ca, Wfac1, &Wmin1, &Wmax1);
         sample_coll_min_max(cb, Wfac2, &Wmin2, &Wmax2);
 
-        Wmin = min(Wmin1, Wmin2);
-        Wmax = max(Wmax1, Wmax2);
+        Wmin = std::min(Wmin1, Wmin2);
+        Wmax = std::max(Wmax1, Wmax2);
     }
 
     DG0 = Wmin;
@@ -1972,7 +1964,7 @@ static void calc_dg_stddev(sample_coll_t *ca, sample_coll_t *cb,
         Wfac2 = -beta*delta_lambda;
     }
 
-    M = log(n1/n2);
+    M = std::log(n1/n2);
 
 
     /* calculate average in both directions */
@@ -1986,7 +1978,7 @@ static void calc_dg_stddev(sample_coll_t *ca, sample_coll_t *cb,
             {
                 for (j = r->start; j < r->end; j++)
                 {
-                    sigmafact += 1./(2. + 2.*cosh((M + Wfac1*s->du[j] - dg)));
+                    sigmafact += 1./(2. + 2.*std::cosh((M + Wfac1*s->du[j] - dg)));
                 }
             }
             else
@@ -2007,7 +1999,7 @@ static void calc_dg_stddev(sample_coll_t *ca, sample_coll_t *cb,
                     double x    = Wfac1*((j+s->hist->x0[0])+0.5)*dx; /*bin ctr*/
                     double pxdx = s->hist->bin[0][j]*normdx;         /* p(x)dx */
 
-                    sigmafact += pxdx/(2. + 2.*cosh((M + x - dg)));
+                    sigmafact += pxdx/(2. + 2.*std::cosh((M + x - dg)));
                 }
             }
         }
@@ -2022,7 +2014,7 @@ static void calc_dg_stddev(sample_coll_t *ca, sample_coll_t *cb,
             {
                 for (j = r->start; j < r->end; j++)
                 {
-                    sigmafact += 1./(2. + 2.*cosh((M - Wfac2*s->du[j] - dg)));
+                    sigmafact += 1./(2. + 2.*std::cosh((M - Wfac2*s->du[j] - dg)));
                 }
             }
             else
@@ -2043,7 +2035,7 @@ static void calc_dg_stddev(sample_coll_t *ca, sample_coll_t *cb,
                     double x    = Wfac2*((j+s->hist->x0[0])+0.5)*dx; /*bin ctr*/
                     double pxdx = s->hist->bin[0][j]*normdx;         /* p(x)dx */
 
-                    sigmafact += pxdx/(2. + 2.*cosh((M - x - dg)));
+                    sigmafact += pxdx/(2. + 2.*std::cosh((M - x - dg)));
                 }
             }
         }
@@ -2054,7 +2046,7 @@ static void calc_dg_stddev(sample_coll_t *ca, sample_coll_t *cb,
 
     /* Eq. 10 from
        Shirts, Bair, Hooker & Pande, Phys. Rev. Lett 91, 140601 (2003): */
-    *stddev = sqrt(((1./sigmafact) - ( (n1+n2)/n1 + (n1+n2)/n2 )));
+    *stddev = std::sqrt(((1.0/sigmafact) - ( (n1+n2)/n1 + (n1+n2)/n2 )));
 }
 
 
@@ -2066,9 +2058,8 @@ static void calc_bar(barres_t *br, double tol,
     int      npee, p;
     double   dg_sig2, sa_sig2, sb_sig2, stddev_sig2; /* intermediate variance values
                                                         for calculated quantities */
-    int      nsample1, nsample2;
     double   temp = br->a->temp;
-    int      i, j;
+    int      i;
     double   dg_min, dg_max;
     gmx_bool have_hist = FALSE;
 
@@ -2104,25 +2095,25 @@ static void calc_bar(barres_t *br, double tol,
         dg_min = calc_bar_lowlevel(br->a, br->b, temp, tol, -1);
         dg_max = calc_bar_lowlevel(br->a, br->b, temp, tol, 1);
 
-        if (fabs(dg_max - dg_min) > GMX_REAL_EPS*10)
+        if (std::abs(dg_max - dg_min) > GMX_REAL_EPS*10)
         {
             /* the histogram range  error is the biggest of the differences
                between the best estimate and the extremes */
-            br->dg_histrange_err = fabs(dg_max - dg_min);
+            br->dg_histrange_err = std::abs(dg_max - dg_min);
         }
         br->dg_disc_err = 0.;
         for (i = 0; i < br->a->nsamples; i++)
         {
             if (br->a->s[i]->hist)
             {
-                br->dg_disc_err = max(br->dg_disc_err, br->a->s[i]->hist->dx[0]);
+                br->dg_disc_err = std::max(br->dg_disc_err, br->a->s[i]->hist->dx[0]);
             }
         }
         for (i = 0; i < br->b->nsamples; i++)
         {
             if (br->b->s[i]->hist)
             {
-                br->dg_disc_err = max(br->dg_disc_err, br->b->s[i]->hist->dx[0]);
+                br->dg_disc_err = std::max(br->dg_disc_err, br->b->s[i]->hist->dx[0]);
             }
         }
     }
@@ -2216,10 +2207,10 @@ static void calc_bar(barres_t *br, double tol,
             dstddev2    /= npee;
             stddev_sig2 += (dstddev2-dstddev*dstddev)/(npee-1);
         }
-        br->dg_err        = sqrt(dg_sig2/(npee_max - npee_min + 1));
-        br->sa_err        = sqrt(sa_sig2/(npee_max - npee_min + 1));
-        br->sb_err        = sqrt(sb_sig2/(npee_max - npee_min + 1));
-        br->dg_stddev_err = sqrt(stddev_sig2/(npee_max - npee_min + 1));
+        br->dg_err        = std::sqrt(dg_sig2/(npee_max - npee_min + 1));
+        br->sa_err        = std::sqrt(sa_sig2/(npee_max - npee_min + 1));
+        br->sb_err        = std::sqrt(sb_sig2/(npee_max - npee_min + 1));
+        br->dg_stddev_err = std::sqrt(stddev_sig2/(npee_max - npee_min + 1));
     }
 }
 
@@ -2245,7 +2236,7 @@ static double bar_err(int nbmin, int nbmax, const double *partsum)
         svar += (s2 - s*s)/(nb - 1);
     }
 
-    return sqrt(svar/(nbmax + 1 - nbmin));
+    return std::sqrt(svar/(nbmax + 1 - nbmin));
 }
 
 
@@ -2268,14 +2259,14 @@ static const char *find_value(const char *str)
         /* first find the end of the name */
         if (!name_end_found)
         {
-            if (isspace(*str) || (*str == '=') )
+            if (std::isspace(*str) || (*str == '=') )
             {
                 name_end_found = TRUE;
             }
         }
         else
         {
-            if (!( isspace(*str) || (*str == '=') ))
+            if (!( std::isspace(*str) || (*str == '=') ))
             {
                 return str;
             }
@@ -2286,7 +2277,6 @@ static const char *find_value(const char *str)
 }
 
 
-
 /* read a vector-notation description of a lambda vector */
 static gmx_bool read_lambda_compvec(const char                *str,
                                     lambda_vec_t              *lv,
@@ -2326,7 +2316,7 @@ static gmx_bool read_lambda_compvec(const char                *str,
     {
         if (!start_reached)
         {
-            if (isalnum(*str))
+            if (std::isalnum(*str))
             {
                 vector        = FALSE;
                 start_reached = TRUE;
@@ -2337,7 +2327,7 @@ static gmx_bool read_lambda_compvec(const char                *str,
                 vector        = TRUE;
                 start_reached = TRUE;
             }
-            else if (!isspace(*str))
+            else if (!std::isspace(*str))
             {
                 gmx_fatal(FARGS, "Error in lambda components in %s", fn);
             }
@@ -2346,7 +2336,7 @@ static gmx_bool read_lambda_compvec(const char                *str,
         {
             if (val_start)
             {
-                if (isspace(*str) || *str == ')' || *str == ',' || *str == '\0')
+                if (std::isspace(*str) || *str == ')' || *str == ',' || *str == '\0')
                 {
                     /* end of value */
                     if (lv == NULL)
@@ -2384,7 +2374,7 @@ static gmx_bool read_lambda_compvec(const char                *str,
                     }
                 }
             }
-            else if (isalnum(*str))
+            else if (std::isalnum(*str))
             {
                 val_start = str;
             }
@@ -2401,6 +2391,7 @@ static gmx_bool read_lambda_compvec(const char                *str,
                 }
                 else
                 {
+                    GMX_RELEASE_ASSERT(lc_in != NULL, "Internal inconsistency? lc_in==NULL");
                     if (n == lc_in->N)
                     {
                         return OK;
@@ -2468,7 +2459,6 @@ static gmx_bool legend2lambda(const char   *fn,
                               const char   *legend,
                               lambda_vec_t *lam)
 {
-    double        lambda = 0;
     const char   *ptr    = NULL, *ptr2 = NULL;
     gmx_bool      ok     = FALSE;
     gmx_bool      bdhdl  = FALSE;
@@ -2483,7 +2473,7 @@ static gmx_bool legend2lambda(const char   *fn,
     ptr2 = legend;
     do
     {
-        ptr2 = strstr(ptr2, tostr);
+        ptr2 = std::strstr(ptr2, tostr);
         if (ptr2 != NULL)
         {
             ptr = ptr2;
@@ -2494,30 +2484,30 @@ static gmx_bool legend2lambda(const char   *fn,
 
     if (ptr)
     {
-        ptr += strlen(tostr)-1; /* and advance past that 'to' */
+        ptr += std::strlen(tostr)-1; /* and advance past that 'to' */
     }
     else
     {
         /* look for the = sign */
-        ptr = strrchr(legend, '=');
+        ptr = std::strrchr(legend, '=');
         if (!ptr)
         {
             /* otherwise look for the last space */
-            ptr = strrchr(legend, ' ');
+            ptr = std::strrchr(legend, ' ');
         }
     }
 
-    if (strstr(legend, "dH"))
+    if (std::strstr(legend, "dH"))
     {
         ok    = TRUE;
         bdhdl = TRUE;
     }
-    else if (strchr(legend, 'D') != NULL && strchr(legend, 'H') != NULL)
+    else if (std::strchr(legend, 'D') != NULL && std::strchr(legend, 'H') != NULL)
     {
         ok    = TRUE;
         bdhdl = FALSE;
     }
-    else /*if (strstr(legend, "pV"))*/
+    else /*if (std::strstr(legend, "pV"))*/
     {
         return FALSE;
     }
@@ -2542,9 +2532,8 @@ static gmx_bool legend2lambda(const char   *fn,
     {
         int         dhdl_index;
         const char *end;
-        char        buf[STRLEN];
 
-        ptr = strrchr(legend, '=');
+        ptr = std::strrchr(legend, '=');
         end = ptr;
         if (ptr)
         {
@@ -2564,7 +2553,7 @@ static gmx_bool legend2lambda(const char   *fn,
                     gmx_fatal(FARGS, "dhdl legend '%s' %s faulty", legend, fn);
                 }
             }
-            while (!isspace(*ptr))
+            while (!std::isspace(*ptr))
             {
                 ptr--;
                 if (ptr < legend)
@@ -2573,13 +2562,11 @@ static gmx_bool legend2lambda(const char   *fn,
                 }
             }
             ptr++;
-            strncpy(buf, ptr, (end-ptr));
-            buf[(end-ptr)] = '\0';
             dhdl_index     = lambda_components_find(lam->lc, ptr, (end-ptr));
             if (dhdl_index < 0)
             {
                 char buf[STRLEN];
-                strncpy(buf, ptr, (end-ptr));
+                std::strncpy(buf, ptr, (end-ptr));
                 buf[(end-ptr)] = '\0';
                 gmx_fatal(FARGS,
                           "Did not find lambda component for '%s' in %s",
@@ -2612,7 +2599,7 @@ static gmx_bool subtitle2lambda(const char *subtitle, xvg_t *ba, const char *fn,
     bFound = FALSE;
 
     /* first check for a state string */
-    ptr = strstr(subtitle, "state");
+    ptr = std::strstr(subtitle, "state");
     if (ptr)
     {
         int         index = -1;
@@ -2622,7 +2609,7 @@ static gmx_bool subtitle2lambda(const char *subtitle, xvg_t *ba, const char *fn,
         ptr = find_value(ptr);
         if (ptr)
         {
-            index = strtol(ptr, &end, 10);
+            index = std::strtol(ptr, &end, 10);
             if (ptr == end)
             {
                 gmx_fatal(FARGS, "Incomplete state data in %s", fn);
@@ -2636,7 +2623,7 @@ static gmx_bool subtitle2lambda(const char *subtitle, xvg_t *ba, const char *fn,
             return FALSE;
         }
         /* now find the lambda vector component names */
-        while (*ptr != '(' && !isalnum(*ptr))
+        while (*ptr != '(' && !std::isalnum(*ptr))
         {
             ptr++;
             if (*ptr == '\0')
@@ -2671,20 +2658,20 @@ static gmx_bool subtitle2lambda(const char *subtitle, xvg_t *ba, const char *fn,
     {
         /* compatibility mode: check for lambda in other ways. */
         /* plain text lambda string */
-        ptr = strstr(subtitle, "lambda");
+        ptr = std::strstr(subtitle, "lambda");
         if (ptr == NULL)
         {
             /* xmgrace formatted lambda string */
-            ptr = strstr(subtitle, "\\xl\\f{}");
+            ptr = std::strstr(subtitle, "\\xl\\f{}");
         }
         if (ptr == NULL)
         {
             /* xmgr formatted lambda string */
-            ptr = strstr(subtitle, "\\8l\\4");
+            ptr = std::strstr(subtitle, "\\8l\\4");
         }
         if (ptr != NULL)
         {
-            ptr = strstr(ptr, "=");
+            ptr = std::strstr(ptr, "=");
         }
         if (ptr != NULL)
         {
@@ -2711,7 +2698,7 @@ static gmx_bool subtitle2lambda(const char *subtitle, xvg_t *ba, const char *fn,
     return bFound;
 }
 
-static void filename2lambda(const char *fn)
+static double filename2lambda(const char *fn)
 {
     double        lambda;
     const char   *ptr, *digitptr;
@@ -2740,7 +2727,7 @@ static void filename2lambda(const char *fn)
         }
         /* save the last position of a digit between the last two
            separators = in the last dirname */
-        if (dirsep > 0 && isdigit(*ptr))
+        if (dirsep > 0 && std::isdigit(*ptr))
         {
             digitptr = ptr;
         }
@@ -2760,6 +2747,7 @@ static void filename2lambda(const char *fn)
     {
         gmx_fatal(FARGS, "Malformed number in file path '%s'", fn);
     }
+    return lambda;
 }
 
 static void read_bar_xvg_lowlevel(const char *fn, real *temp, xvg_t *ba,
@@ -2770,7 +2758,6 @@ static void read_bar_xvg_lowlevel(const char *fn, real *temp, xvg_t *ba,
     int          np;
     gmx_bool     native_lambda_read = FALSE;
     char         buf[STRLEN];
-    lambda_vec_t lv;
 
     xvg_init(ba);
 
@@ -2799,7 +2786,7 @@ static void read_bar_xvg_lowlevel(const char *fn, real *temp, xvg_t *ba,
     if (subtitle != NULL)
     {
         /* try to extract temperature */
-        ptr = strstr(subtitle, "T =");
+        ptr = std::strstr(subtitle, "T =");
         if (ptr != NULL)
         {
             ptr += 3;
@@ -2838,7 +2825,10 @@ static void read_bar_xvg_lowlevel(const char *fn, real *temp, xvg_t *ba,
         {
             if (!native_lambda_read)
             {
-                /* Deduce lambda from the file name */
+                // Deduce lambda from the file name.
+                // Updated the routine filename2lambda to actually return lambda
+                // to avoid C++ warnings, but this usage does not seem to need it?
+                // EL 2015-07-10
                 filename2lambda(fn);
                 native_lambda_read = TRUE;
             }
@@ -2897,7 +2887,6 @@ static void read_bar_xvg(char *fn, real *temp, sim_data_t *sd)
     xvg_t     *barsim;
     samples_t *s;
     int        i;
-    double    *lambda;
 
     snew(barsim, 1);
 
@@ -2949,8 +2938,6 @@ static void read_edr_rawdh_block(samples_t **smp, int *ndu, t_enxblock *blk,
                                  double *last_t, const char *filename)
 {
     int           i, j;
-    gmx_bool      allocated;
-    double        old_foreign_lambda;
     lambda_vec_t *foreign_lambda;
     int           type;
     samples_t    *s; /* convenience pointer */
@@ -3058,7 +3045,6 @@ static samples_t *read_edr_hist_block(int *nsamples, t_enxblock *blk,
     int           i, j;
     samples_t    *s;
     int           nhist;
-    double        old_foreign_lambda;
     lambda_vec_t *foreign_lambda;
     int           type;
     int           nbins[2];
@@ -3093,7 +3079,7 @@ static samples_t *read_edr_hist_block(int *nsamples, t_enxblock *blk,
     snew(foreign_lambda, 1);
     lambda_vec_init(foreign_lambda, native_lambda->lc);
     lambda_vec_copy(foreign_lambda, native_lambda);
-    type = (int)(blk->sub[1].lval[1]);
+    type = static_cast<int>(blk->sub[1].lval[1]);
     if (type == dhbtDH)
     {
         double old_foreign_lambda;
@@ -3163,12 +3149,11 @@ static samples_t *read_edr_hist_block(int *nsamples, t_enxblock *blk,
 
     for (i = 0; i < nhist; i++)
     {
-        int             nbin;
         gmx_int64_t     sum = 0;
 
         for (j = 0; j < s->hist->nbin[i]; j++)
         {
-            int binv = (int)(blk->sub[i+2].ival[j]);
+            int binv = static_cast<int>(blk->sub[i+2].ival[j]);
 
             s->hist->bin[i][j] = binv;
             sum               += binv;
@@ -3211,7 +3196,6 @@ static void read_barsim_edr(char *fn, real *temp, sim_data_t *sd)
     int           *npts          = NULL; /* array to keep count & print at end */
     lambda_vec_t **lambdas       = NULL; /* array to keep count & print at end */
     lambda_vec_t  *native_lambda;
-    double         end_time;             /* the end time of the last batch of samples */
     int            nsamples = 0;
     lambda_vec_t   start_lambda;
 
@@ -3255,9 +3239,9 @@ static void read_barsim_edr(char *fn, real *temp, sim_data_t *sd)
                 }
 
                 /* read the data from the DHCOLL block */
-                rtemp            =        fr->block[i].sub[0].dval[0];
-                start_time       =   fr->block[i].sub[0].dval[1];
-                delta_time       =   fr->block[i].sub[0].dval[2];
+                rtemp            = fr->block[i].sub[0].dval[0];
+                start_time       = fr->block[i].sub[0].dval[1];
+                delta_time       = fr->block[i].sub[0].dval[2];
                 old_start_lambda = fr->block[i].sub[0].dval[3];
                 delta_lambda     = fr->block[i].sub[0].dval[4];
 
@@ -3312,12 +3296,12 @@ static void read_barsim_edr(char *fn, real *temp, sim_data_t *sd)
                         {
                             /* check the components */
                             lambda_components_check(&(sd->lc), j, name,
-                                                    strlen(name));
+                                                    std::strlen(name));
                         }
                         else
                         {
                             lambda_components_add(&(sd->lc), name,
-                                                  strlen(name));
+                                                  std::strlen(name));
                         }
                     }
                     lambda_vec_init(&start_lambda, &(sd->lc));
@@ -3343,8 +3327,31 @@ static void read_barsim_edr(char *fn, real *temp, sim_data_t *sd)
             gmx_fatal(FARGS, "Can't handle both raw delta U data and histograms in the same file %s", fn);
         }
 
-        if (nsamples > 0)
+        if (nsamples == 0)
         {
+            /* this is the first round; allocate the associated data
+               structures */
+            /*native_lambda=start_lambda;*/
+            lambda_vec_init(native_lambda, &(sd->lc));
+            lambda_vec_copy(native_lambda, &start_lambda);
+            nsamples = nblocks_raw+nblocks_hist;
+            snew(nhists, nsamples);
+            snew(npts, nsamples);
+            snew(lambdas, nsamples);
+            snew(samples_rawdh, nsamples);
+            for (i = 0; i < nsamples; i++)
+            {
+                nhists[i]        = 0;
+                npts[i]          = 0;
+                lambdas[i]       = NULL;
+                samples_rawdh[i] = NULL; /* init to NULL so we know which
+                                            ones contain values */
+            }
+        }
+        else
+        {
+            // nsamples > 0 means this is NOT the first iteration
+
             /* check the native lambda */
             if (!lambda_vec_same(&start_lambda, native_lambda) )
             {
@@ -3359,11 +3366,16 @@ static void read_barsim_edr(char *fn, real *temp, sim_data_t *sd)
             }
             /* check whether last iterations's end time matches with
                the currrent start time */
-            if ( (fabs(last_t - start_time) > 2*delta_time)  && last_t >= 0)
+            if ( (std::abs(last_t - start_time) > 2*delta_time)  && last_t >= 0)
             {
                 /* it didn't. We need to store our samples and reallocate */
+
                 for (i = 0; i < nsamples; i++)
                 {
+                    // nsamples is always >0 here, so samples_rawdh must be a valid pointer. Unfortunately
+                    // cppcheck does not understand the logic unless the assert is inside the loop, but
+                    // this is not performance-sensitive code.
+                    GMX_RELEASE_ASSERT(samples_rawdh != NULL, "samples_rawdh==NULL with nsamples>0");
                     if (samples_rawdh[i])
                     {
                         /* insert it into the existing list */
@@ -3376,27 +3388,6 @@ static void read_barsim_edr(char *fn, real *temp, sim_data_t *sd)
                 }
             }
         }
-        else
-        {
-            /* this is the first round; allocate the associated data
-               structures */
-            /*native_lambda=start_lambda;*/
-            lambda_vec_init(native_lambda, &(sd->lc));
-            lambda_vec_copy(native_lambda, &start_lambda);
-            nsamples = nblocks_raw+nblocks_hist;
-            snew(nhists, nsamples);
-            snew(npts, nsamples);
-            snew(lambdas, nsamples);
-            snew(samples_rawdh, nsamples);
-            for (i = 0; i < nsamples; i++)
-            {
-                nhists[i]        = 0;
-                npts[i]          = 0;
-                lambdas[i]       = NULL;
-                samples_rawdh[i] = NULL; /* init to NULL so we know which
-                                            ones contain values */
-            }
-        }
 
         /* and read them */
         k = 0; /* counter for the lambdas, etc. arrays */
@@ -3424,7 +3415,7 @@ static void read_barsim_edr(char *fn, real *temp, sim_data_t *sd)
             }
             else if (fr->block[i].id == enxDHHIST)
             {
-                int type = (int)(fr->block[i].sub[1].lval[1]);
+                int type = static_cast<int>(fr->block[i].sub[1].lval[1]);
                 if (type == dhbtDH || type == dhbtDHDL)
                 {
                     int        j;
@@ -3599,8 +3590,7 @@ int gmx_bar(int argc, char *argv[])
     int                nd       = 2, nbmin = 5, nbmax = 5;
     int                nbin     = 100;
     gmx_bool           use_dhdl = FALSE;
-    gmx_bool           calc_s, calc_v;
-    t_pargs            pa[] = {
+    t_pargs            pa[]     = {
         { "-b",    FALSE, etREAL, {&begin},  "Begin time for BAR" },
         { "-e",    FALSE, etREAL, {&end},    "End time for BAR" },
         { "-temp", FALSE, etREAL, {&temp},   "Temperature (K)" },
@@ -3620,9 +3610,8 @@ int gmx_bar(int argc, char *argv[])
     };
 #define NFILE asize(fnm)
 
-    int          f, i, j;
+    int          f;
     int          nf = 0;    /* file counter */
-    int          nbs;
     int          nfile_tot; /* total number of input files */
     int          nxvgfile = 0;
     int          nedrfile = 0;
@@ -3633,14 +3622,14 @@ int gmx_bar(int argc, char *argv[])
     int          nresults; /* number of results in results array */
 
     double      *partsum;
-    double       prec, dg_tot, dg, sig, dg_tot_max, dg_tot_min;
+    double       prec, dg_tot;
     FILE        *fpb, *fpi;
     char         dgformat[20], xvg2format[STRLEN], xvg3format[STRLEN];
     char         buf[STRLEN], buf2[STRLEN];
     char         ktformat[STRLEN], sktformat[STRLEN];
     char         kteformat[STRLEN], skteformat[STRLEN];
     output_env_t oenv;
-    double       kT, beta;
+    double       kT;
     gmx_bool     result_OK = TRUE, bEE = TRUE;
 
     gmx_bool     disc_err          = FALSE;
@@ -3686,7 +3675,7 @@ int gmx_bar(int argc, char *argv[])
     {
         gmx_fatal(FARGS, "Can not have negative number of digits");
     }
-    prec = pow(10, -nd);
+    prec = std::pow(10.0, static_cast<double>(-nd));
 
     snew(partsum, (nbmax+1)*(nbmax+1));
     nf = 0;
@@ -3726,7 +3715,7 @@ int gmx_bar(int argc, char *argv[])
     if (sum_disc_err > prec)
     {
         prec = sum_disc_err;
-        nd   = ceil(-log10(prec));
+        nd   = static_cast<int>(std::ceil(-std::log10(prec)));
         printf("WARNING: setting the precision to %g because that is the minimum\n         reasonable number, given the expected discretization error.\n", prec);
     }
 
@@ -3790,7 +3779,6 @@ int gmx_bar(int argc, char *argv[])
 
     /* print results in kT */
     kT   = BOLTZ*temp;
-    beta = 1/kT;
 
     printf("\nTemperature: %g K\n", temp);
 
@@ -3946,7 +3934,7 @@ int gmx_bar(int argc, char *argv[])
     {
         stat_err = bar_err(nbmin, nbmax, partsum)*kT;
         printf(" +/- ");
-        printf(dgformat, max(max(stat_err, sum_disc_err), sum_histrange_err));
+        printf(dgformat, std::max(std::max(stat_err, sum_disc_err), sum_histrange_err));
     }
     printf("\n");
     if (disc_err)