Move running logic into its own module

Also merge some of the functions to make the code easier to
read.