Refactor run_transform function

There was a lot of code in this function so I tried to break it up into
more meaningful blocks of functionality.