Huge crapload of refactoring and some bugfixes