some long necessary code clean up (removing dublicated code and using subroutines instead)