Major refactoring to simplify the code