modularized functions and cleaned a little code