More refactorization and improvements