Fixed bugs and refactored code