Refactored code and fixed several bugs