Refactoring major part of the code