Refactored code and fixed some bugs.