Bit of refactoring and few bug fixes