Refactored the code a little bit