Refactor

Attempted refactor, but the code is now broken - abandoning branch