Unittest and misc fixes

Please see individual commit messages for more detail :D