Final working code with comments