Final code with comments