Fixed some bugs and refactoring