OK time to clean up - this first attempt has some interesting quirks...