Fix minor bugs

Fix minor bugs and refactoring