Did some refactoring, fixed some bugs.