Modularize and clean up the code