Fixing errors and warning produced by the static code analysis of PVS-Studio. Couple of actual bugs and rest is dead code cleanup etc.