Refactored and wrote some comments