Refactoring, bugs fixing