Fixed some bugs discovered by Sonar.