Modularize and simplify the code