Some fixes and some refactoring