Code optimizations and unit test fixes (thanks to Jano Svitok)