Refactored and documented a bit.