Various refactorings and code cleanup