Fix warnings and a few bugs uncovered by them