Refactoring.

Fixed some bugs