Fixed some bugs, minor refactoring.