Document code

There are also minor bug fixes mixed into this commit.