Refactored/refunctorised code

Still lots more to do, but this seems like a reasonable checkpoint.