Refactored and commented.