Refactorization. Credit to @ryhan.