final edited code with comments