Refactoring and working version