Refactored and commented the code