Fixed bugs and refactored some code