final updated code with comments