Refactored the code a bit, and added some comments