140814 Complete rewrite, not quite tested though