Lots of bug fixes/improvements

See commit messages.