A bit of refactoring, and few bugfixes