complete code with comments-final