Added comments and a few refactorings