Fixed bugs and refactoring code