Fixing up a bunch of warnings found by cppcheck: Mostly avoiding using old style C-casts. A few bugs where found in the process of using static_cast explicitly. Also using local scopes for loop counters, which again identified a few bugs.