Fixes #278
Fixes #279 and some small refactorings