Minor fixes and some refactoring