Complete code with comments