Added comments and refactored a bit.