Refactored some code, fixed small errors