Fixed bugs and refactored