Refactoring code to make it work more smoothly