Did some refactoring and added some comments