refactored code using some concepts i learned in poodir