refactoring to make the code clear and simple and fix some bugs