Some refactoring and a fix