Fix bugs found through compiler warnings

I started a separate seperate pull to work on fixing compiler warnings. These are the bugs I found during that work which I am pushing up separately so they get better scrutiny. Especially note the ones which have FIXME comments where some questions still remain. If you could comment on those and then I will update and/or remove the FIXME comments.