Refactor as per your codereview request on r/codereview

First pass. Will probably refactor more later.