Refactor for code style and make some logic fixes