Added comments and some refactoring.