Some Bug fixes and refactoring