Merge upstream changes, refactor and cleanup.