second commit
third commit
Broadly working version. Need to sort out logging.