Optimization, bugfixes, refactoring