Refactoring and some bugs fixed.