A lot of refactoring. Fixed some bugs.