refactored and added some comments