Seems to work, needs a bit of tidying.