reformatted and refactored to be more concise (sub-100 lines\!)