Major refactoring and bugfixing