First round of metadata tests and some bug fixes

TODO: Add tests here (in the next pull request).