Some fixes, some refactoring