Factorize the code and some comments