Refactor the pipeline/hsc interaction

It would probably still benefit from some tidying up, but it's now
much more opaque, with the control flow easier to understand.