FIx some bugs after refactoring. Now all tests passes