final code with comments