full refactoring and solving the problem