Refactoring and optimization. Bugfixes.