Some refactorings. Add cleanup code