code optimizations and bugfixes