A lot of refactorings and cleanups...