Fixed up compiler warnings and potential bugs. Now builds with gcc/clang.