Big bugfix & refactoring