Some refactoring to fix error