modularize and beautify the code