bugfixes, optimizations, and added tests