Fixes & optimizations

Here are some fixes for type-safety and exception safety, as well as some small optimizations. See the commit messages for details.