Fixed bugs, code refactoring