Refactoring, simplification and cleanup