Added comments and removed a bug in the code.