re-organized and modularized the code