Refactoring and removing some bugs.