Refactored and commented a bit.