refactored the code to make it simpler