Some cleanup and refactorization