Turn loops into range-based form

and some things suggested by cppcheck and compiler warnings.