modularized the code a bit