Added comments and did some refactoring