Refactoring code structure to remove duplication

@zankich  could you please take a look?

also  @hunterboerner  :)
I forgot this is missing @zankich ...