simple refactoring, optimizations and bugfixes