Fix several subtle bugs found during emscripten port