Some refactoring and bug solving