Rewriting the code to be more modular and readable