Adding comments, refactoring some variables and function names for better understanding.