Refactorization to fix potential bugs.