Added comments and some minor refactoring.