Optimization, refactoring, bugfixes