Refactoring, simplification, bugfixes