Code refactoring done. Initial working version