Pull out the useful bits into a more general purpose module

Work in progress.