Refactor, primarily adding comments to explain flow