Some bug fixes and refactoring