Added upgrade machinery and some refactorings