refactored the code a bit