Various bug fixes, optimizations, test tweaks