Added comments, some refactoring