Refactored and added some comments