Refactoring and Bug fixes