Further refactored the code and added some comments