Comprehensive refactorisation to fix issue #1 and allow monad transformers.