Some bugfixes from pervious commit, additional performance improvements.